Use DISABLE_COPY_AND_ASSIGN
[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 <fcntl.h>
79 #include <sys/types.h>
80 #include <algorithm>
81 #include <unordered_set>
82 #include <unordered_map>
83
84 typedef struct symbol *symbolp;
85 DEF_VEC_P (symbolp);
86
87 /* When == 1, print basic high level tracing messages.
88    When > 1, be more verbose.
89    This is in contrast to the low level DIE reading of dwarf_die_debug.  */
90 static unsigned int dwarf_read_debug = 0;
91
92 /* When non-zero, dump DIEs after they are read in.  */
93 static unsigned int dwarf_die_debug = 0;
94
95 /* When non-zero, dump line number entries as they are read in.  */
96 static unsigned int dwarf_line_debug = 0;
97
98 /* When non-zero, cross-check physname against demangler.  */
99 static int check_physname = 0;
100
101 /* When non-zero, do not reject deprecated .gdb_index sections.  */
102 static int use_deprecated_index_sections = 0;
103
104 static const struct objfile_data *dwarf2_objfile_data_key;
105
106 /* The "aclass" indices for various kinds of computed DWARF symbols.  */
107
108 static int dwarf2_locexpr_index;
109 static int dwarf2_loclist_index;
110 static int dwarf2_locexpr_block_index;
111 static int dwarf2_loclist_block_index;
112
113 /* A descriptor for dwarf sections.
114
115    S.ASECTION, SIZE are typically initialized when the objfile is first
116    scanned.  BUFFER, READIN are filled in later when the section is read.
117    If the section contained compressed data then SIZE is updated to record
118    the uncompressed size of the section.
119
120    DWP file format V2 introduces a wrinkle that is easiest to handle by
121    creating the concept of virtual sections contained within a real section.
122    In DWP V2 the sections of the input DWO files are concatenated together
123    into one section, but section offsets are kept relative to the original
124    input section.
125    If this is a virtual dwp-v2 section, S.CONTAINING_SECTION is a backlink to
126    the real section this "virtual" section is contained in, and BUFFER,SIZE
127    describe the virtual section.  */
128
129 struct dwarf2_section_info
130 {
131   union
132   {
133     /* If this is a real section, the bfd section.  */
134     asection *section;
135     /* If this is a virtual section, pointer to the containing ("real")
136        section.  */
137     struct dwarf2_section_info *containing_section;
138   } s;
139   /* Pointer to section data, only valid if readin.  */
140   const gdb_byte *buffer;
141   /* The size of the section, real or virtual.  */
142   bfd_size_type size;
143   /* If this is a virtual section, the offset in the real section.
144      Only valid if is_virtual.  */
145   bfd_size_type virtual_offset;
146   /* True if we have tried to read this section.  */
147   char readin;
148   /* True if this is a virtual section, False otherwise.
149      This specifies which of s.section and s.containing_section to use.  */
150   char is_virtual;
151 };
152
153 typedef struct dwarf2_section_info dwarf2_section_info_def;
154 DEF_VEC_O (dwarf2_section_info_def);
155
156 /* All offsets in the index are of this type.  It must be
157    architecture-independent.  */
158 typedef uint32_t offset_type;
159
160 DEF_VEC_I (offset_type);
161
162 /* Ensure only legit values are used.  */
163 #define DW2_GDB_INDEX_SYMBOL_STATIC_SET_VALUE(cu_index, value) \
164   do { \
165     gdb_assert ((unsigned int) (value) <= 1); \
166     GDB_INDEX_SYMBOL_STATIC_SET_VALUE((cu_index), (value)); \
167   } while (0)
168
169 /* Ensure only legit values are used.  */
170 #define DW2_GDB_INDEX_SYMBOL_KIND_SET_VALUE(cu_index, value) \
171   do { \
172     gdb_assert ((value) >= GDB_INDEX_SYMBOL_KIND_TYPE \
173                 && (value) <= GDB_INDEX_SYMBOL_KIND_OTHER); \
174     GDB_INDEX_SYMBOL_KIND_SET_VALUE((cu_index), (value)); \
175   } while (0)
176
177 /* Ensure we don't use more than the alloted nuber of bits for the CU.  */
178 #define DW2_GDB_INDEX_CU_SET_VALUE(cu_index, value) \
179   do { \
180     gdb_assert (((value) & ~GDB_INDEX_CU_MASK) == 0); \
181     GDB_INDEX_CU_SET_VALUE((cu_index), (value)); \
182   } while (0)
183
184 /* A description of the mapped index.  The file format is described in
185    a comment by the code that writes the index.  */
186 struct mapped_index
187 {
188   /* Index data format version.  */
189   int version;
190
191   /* The total length of the buffer.  */
192   off_t total_size;
193
194   /* A pointer to the address table data.  */
195   const gdb_byte *address_table;
196
197   /* Size of the address table data in bytes.  */
198   offset_type address_table_size;
199
200   /* The symbol table, implemented as a hash table.  */
201   const offset_type *symbol_table;
202
203   /* Size in slots, each slot is 2 offset_types.  */
204   offset_type symbol_table_slots;
205
206   /* A pointer to the constant pool.  */
207   const char *constant_pool;
208 };
209
210 typedef struct dwarf2_per_cu_data *dwarf2_per_cu_ptr;
211 DEF_VEC_P (dwarf2_per_cu_ptr);
212
213 struct tu_stats
214 {
215   int nr_uniq_abbrev_tables;
216   int nr_symtabs;
217   int nr_symtab_sharers;
218   int nr_stmt_less_type_units;
219   int nr_all_type_units_reallocs;
220 };
221
222 /* Collection of data recorded per objfile.
223    This hangs off of dwarf2_objfile_data_key.  */
224
225 struct dwarf2_per_objfile
226 {
227   /* Construct a dwarf2_per_objfile for OBJFILE.  NAMES points to the
228      dwarf2 section names, or is NULL if the standard ELF names are
229      used.  */
230   dwarf2_per_objfile (struct objfile *objfile,
231                       const dwarf2_debug_sections *names);
232
233   ~dwarf2_per_objfile ();
234
235   DISABLE_COPY_AND_ASSIGN (dwarf2_per_objfile);
236
237   /* Free all cached compilation units.  */
238   void free_cached_comp_units ();
239 private:
240   /* This function is mapped across the sections and remembers the
241      offset and size of each of the debugging sections we are
242      interested in.  */
243   void locate_sections (bfd *abfd, asection *sectp,
244                         const dwarf2_debug_sections &names);
245
246 public:
247   dwarf2_section_info info {};
248   dwarf2_section_info abbrev {};
249   dwarf2_section_info line {};
250   dwarf2_section_info loc {};
251   dwarf2_section_info loclists {};
252   dwarf2_section_info macinfo {};
253   dwarf2_section_info macro {};
254   dwarf2_section_info str {};
255   dwarf2_section_info line_str {};
256   dwarf2_section_info ranges {};
257   dwarf2_section_info rnglists {};
258   dwarf2_section_info addr {};
259   dwarf2_section_info frame {};
260   dwarf2_section_info eh_frame {};
261   dwarf2_section_info gdb_index {};
262
263   VEC (dwarf2_section_info_def) *types = NULL;
264
265   /* Back link.  */
266   struct objfile *objfile = NULL;
267
268   /* Table of all the compilation units.  This is used to locate
269      the target compilation unit of a particular reference.  */
270   struct dwarf2_per_cu_data **all_comp_units = NULL;
271
272   /* The number of compilation units in ALL_COMP_UNITS.  */
273   int n_comp_units = 0;
274
275   /* The number of .debug_types-related CUs.  */
276   int n_type_units = 0;
277
278   /* The number of elements allocated in all_type_units.
279      If there are skeleton-less TUs, we add them to all_type_units lazily.  */
280   int n_allocated_type_units = 0;
281
282   /* The .debug_types-related CUs (TUs).
283      This is stored in malloc space because we may realloc it.  */
284   struct signatured_type **all_type_units = NULL;
285
286   /* Table of struct type_unit_group objects.
287      The hash key is the DW_AT_stmt_list value.  */
288   htab_t type_unit_groups {};
289
290   /* A table mapping .debug_types signatures to its signatured_type entry.
291      This is NULL if the .debug_types section hasn't been read in yet.  */
292   htab_t signatured_types {};
293
294   /* Type unit statistics, to see how well the scaling improvements
295      are doing.  */
296   struct tu_stats tu_stats {};
297
298   /* A chain of compilation units that are currently read in, so that
299      they can be freed later.  */
300   dwarf2_per_cu_data *read_in_chain = NULL;
301
302   /* A table mapping DW_AT_dwo_name values to struct dwo_file objects.
303      This is NULL if the table hasn't been allocated yet.  */
304   htab_t dwo_files {};
305
306   /* True if we've checked for whether there is a DWP file.  */
307   bool dwp_checked = false;
308
309   /* The DWP file if there is one, or NULL.  */
310   struct dwp_file *dwp_file = NULL;
311
312   /* The shared '.dwz' file, if one exists.  This is used when the
313      original data was compressed using 'dwz -m'.  */
314   struct dwz_file *dwz_file = NULL;
315
316   /* A flag indicating whether this objfile has a section loaded at a
317      VMA of 0.  */
318   bool has_section_at_zero = false;
319
320   /* True if we are using the mapped index,
321      or we are faking it for OBJF_READNOW's sake.  */
322   bool using_index = false;
323
324   /* The mapped index, or NULL if .gdb_index is missing or not being used.  */
325   mapped_index *index_table = NULL;
326
327   /* When using index_table, this keeps track of all quick_file_names entries.
328      TUs typically share line table entries with a CU, so we maintain a
329      separate table of all line table entries to support the sharing.
330      Note that while there can be way more TUs than CUs, we've already
331      sorted all the TUs into "type unit groups", grouped by their
332      DW_AT_stmt_list value.  Therefore the only sharing done here is with a
333      CU and its associated TU group if there is one.  */
334   htab_t quick_file_names_table {};
335
336   /* Set during partial symbol reading, to prevent queueing of full
337      symbols.  */
338   bool reading_partial_symbols = false;
339
340   /* Table mapping type DIEs to their struct type *.
341      This is NULL if not allocated yet.
342      The mapping is done via (CU/TU + DIE offset) -> type.  */
343   htab_t die_type_hash {};
344
345   /* The CUs we recently read.  */
346   VEC (dwarf2_per_cu_ptr) *just_read_cus = NULL;
347
348   /* Table containing line_header indexed by offset and offset_in_dwz.  */
349   htab_t line_header_hash {};
350
351   /* Table containing all filenames.  This is an optional because the
352      table is lazily constructed on first access.  */
353   gdb::optional<filename_seen_cache> filenames_cache;
354 };
355
356 static struct dwarf2_per_objfile *dwarf2_per_objfile;
357
358 /* Default names of the debugging sections.  */
359
360 /* Note that if the debugging section has been compressed, it might
361    have a name like .zdebug_info.  */
362
363 static const struct dwarf2_debug_sections dwarf2_elf_names =
364 {
365   { ".debug_info", ".zdebug_info" },
366   { ".debug_abbrev", ".zdebug_abbrev" },
367   { ".debug_line", ".zdebug_line" },
368   { ".debug_loc", ".zdebug_loc" },
369   { ".debug_loclists", ".zdebug_loclists" },
370   { ".debug_macinfo", ".zdebug_macinfo" },
371   { ".debug_macro", ".zdebug_macro" },
372   { ".debug_str", ".zdebug_str" },
373   { ".debug_line_str", ".zdebug_line_str" },
374   { ".debug_ranges", ".zdebug_ranges" },
375   { ".debug_rnglists", ".zdebug_rnglists" },
376   { ".debug_types", ".zdebug_types" },
377   { ".debug_addr", ".zdebug_addr" },
378   { ".debug_frame", ".zdebug_frame" },
379   { ".eh_frame", NULL },
380   { ".gdb_index", ".zgdb_index" },
381   23
382 };
383
384 /* List of DWO/DWP sections.  */
385
386 static const struct dwop_section_names
387 {
388   struct dwarf2_section_names abbrev_dwo;
389   struct dwarf2_section_names info_dwo;
390   struct dwarf2_section_names line_dwo;
391   struct dwarf2_section_names loc_dwo;
392   struct dwarf2_section_names loclists_dwo;
393   struct dwarf2_section_names macinfo_dwo;
394   struct dwarf2_section_names macro_dwo;
395   struct dwarf2_section_names str_dwo;
396   struct dwarf2_section_names str_offsets_dwo;
397   struct dwarf2_section_names types_dwo;
398   struct dwarf2_section_names cu_index;
399   struct dwarf2_section_names tu_index;
400 }
401 dwop_section_names =
402 {
403   { ".debug_abbrev.dwo", ".zdebug_abbrev.dwo" },
404   { ".debug_info.dwo", ".zdebug_info.dwo" },
405   { ".debug_line.dwo", ".zdebug_line.dwo" },
406   { ".debug_loc.dwo", ".zdebug_loc.dwo" },
407   { ".debug_loclists.dwo", ".zdebug_loclists.dwo" },
408   { ".debug_macinfo.dwo", ".zdebug_macinfo.dwo" },
409   { ".debug_macro.dwo", ".zdebug_macro.dwo" },
410   { ".debug_str.dwo", ".zdebug_str.dwo" },
411   { ".debug_str_offsets.dwo", ".zdebug_str_offsets.dwo" },
412   { ".debug_types.dwo", ".zdebug_types.dwo" },
413   { ".debug_cu_index", ".zdebug_cu_index" },
414   { ".debug_tu_index", ".zdebug_tu_index" },
415 };
416
417 /* local data types */
418
419 /* The data in a compilation unit header, after target2host
420    translation, looks like this.  */
421 struct comp_unit_head
422 {
423   unsigned int length;
424   short version;
425   unsigned char addr_size;
426   unsigned char signed_addr_p;
427   sect_offset abbrev_sect_off;
428
429   /* Size of file offsets; either 4 or 8.  */
430   unsigned int offset_size;
431
432   /* Size of the length field; either 4 or 12.  */
433   unsigned int initial_length_size;
434
435   enum dwarf_unit_type unit_type;
436
437   /* Offset to the first byte of this compilation unit header in the
438      .debug_info section, for resolving relative reference dies.  */
439   sect_offset sect_off;
440
441   /* Offset to first die in this cu from the start of the cu.
442      This will be the first byte following the compilation unit header.  */
443   cu_offset first_die_cu_offset;
444
445   /* 64-bit signature of this type unit - it is valid only for
446      UNIT_TYPE DW_UT_type.  */
447   ULONGEST signature;
448
449   /* For types, offset in the type's DIE of the type defined by this TU.  */
450   cu_offset type_cu_offset_in_tu;
451 };
452
453 /* Type used for delaying computation of method physnames.
454    See comments for compute_delayed_physnames.  */
455 struct delayed_method_info
456 {
457   /* The type to which the method is attached, i.e., its parent class.  */
458   struct type *type;
459
460   /* The index of the method in the type's function fieldlists.  */
461   int fnfield_index;
462
463   /* The index of the method in the fieldlist.  */
464   int index;
465
466   /* The name of the DIE.  */
467   const char *name;
468
469   /*  The DIE associated with this method.  */
470   struct die_info *die;
471 };
472
473 typedef struct delayed_method_info delayed_method_info;
474 DEF_VEC_O (delayed_method_info);
475
476 /* Internal state when decoding a particular compilation unit.  */
477 struct dwarf2_cu
478 {
479   /* The objfile containing this compilation unit.  */
480   struct objfile *objfile;
481
482   /* The header of the compilation unit.  */
483   struct comp_unit_head header;
484
485   /* Base address of this compilation unit.  */
486   CORE_ADDR base_address;
487
488   /* Non-zero if base_address has been set.  */
489   int base_known;
490
491   /* The language we are debugging.  */
492   enum language language;
493   const struct language_defn *language_defn;
494
495   const char *producer;
496
497   /* The generic symbol table building routines have separate lists for
498      file scope symbols and all all other scopes (local scopes).  So
499      we need to select the right one to pass to add_symbol_to_list().
500      We do it by keeping a pointer to the correct list in list_in_scope.
501
502      FIXME: The original dwarf code just treated the file scope as the
503      first local scope, and all other local scopes as nested local
504      scopes, and worked fine.  Check to see if we really need to
505      distinguish these in buildsym.c.  */
506   struct pending **list_in_scope;
507
508   /* The abbrev table for this CU.
509      Normally this points to the abbrev table in the objfile.
510      But if DWO_UNIT is non-NULL this is the abbrev table in the DWO file.  */
511   struct abbrev_table *abbrev_table;
512
513   /* Hash table holding all the loaded partial DIEs
514      with partial_die->offset.SECT_OFF as hash.  */
515   htab_t partial_dies;
516
517   /* Storage for things with the same lifetime as this read-in compilation
518      unit, including partial DIEs.  */
519   struct obstack comp_unit_obstack;
520
521   /* When multiple dwarf2_cu structures are living in memory, this field
522      chains them all together, so that they can be released efficiently.
523      We will probably also want a generation counter so that most-recently-used
524      compilation units are cached...  */
525   struct dwarf2_per_cu_data *read_in_chain;
526
527   /* Backlink to our per_cu entry.  */
528   struct dwarf2_per_cu_data *per_cu;
529
530   /* How many compilation units ago was this CU last referenced?  */
531   int last_used;
532
533   /* A hash table of DIE cu_offset for following references with
534      die_info->offset.sect_off as hash.  */
535   htab_t die_hash;
536
537   /* Full DIEs if read in.  */
538   struct die_info *dies;
539
540   /* A set of pointers to dwarf2_per_cu_data objects for compilation
541      units referenced by this one.  Only set during full symbol processing;
542      partial symbol tables do not have dependencies.  */
543   htab_t dependencies;
544
545   /* Header data from the line table, during full symbol processing.  */
546   struct line_header *line_header;
547   /* Non-NULL if LINE_HEADER is owned by this DWARF_CU.  Otherwise,
548      it's owned by dwarf2_per_objfile::line_header_hash.  If non-NULL,
549      this is the DW_TAG_compile_unit die for this CU.  We'll hold on
550      to the line header as long as this DIE is being processed.  See
551      process_die_scope.  */
552   die_info *line_header_die_owner;
553
554   /* A list of methods which need to have physnames computed
555      after all type information has been read.  */
556   VEC (delayed_method_info) *method_list;
557
558   /* To be copied to symtab->call_site_htab.  */
559   htab_t call_site_htab;
560
561   /* Non-NULL if this CU came from a DWO file.
562      There is an invariant here that is important to remember:
563      Except for attributes copied from the top level DIE in the "main"
564      (or "stub") file in preparation for reading the DWO file
565      (e.g., DW_AT_GNU_addr_base), we KISS: there is only *one* CU.
566      Either there isn't a DWO file (in which case this is NULL and the point
567      is moot), or there is and either we're not going to read it (in which
568      case this is NULL) or there is and we are reading it (in which case this
569      is non-NULL).  */
570   struct dwo_unit *dwo_unit;
571
572   /* The DW_AT_addr_base attribute if present, zero otherwise
573      (zero is a valid value though).
574      Note this value comes from the Fission stub CU/TU's DIE.  */
575   ULONGEST addr_base;
576
577   /* The DW_AT_ranges_base attribute if present, zero otherwise
578      (zero is a valid value though).
579      Note this value comes from the Fission stub CU/TU's DIE.
580      Also note that the value is zero in the non-DWO case so this value can
581      be used without needing to know whether DWO files are in use or not.
582      N.B. This does not apply to DW_AT_ranges appearing in
583      DW_TAG_compile_unit dies.  This is a bit of a wart, consider if ever
584      DW_AT_ranges appeared in the DW_TAG_compile_unit of DWO DIEs: then
585      DW_AT_ranges_base *would* have to be applied, and we'd have to care
586      whether the DW_AT_ranges attribute came from the skeleton or DWO.  */
587   ULONGEST ranges_base;
588
589   /* Mark used when releasing cached dies.  */
590   unsigned int mark : 1;
591
592   /* This CU references .debug_loc.  See the symtab->locations_valid field.
593      This test is imperfect as there may exist optimized debug code not using
594      any location list and still facing inlining issues if handled as
595      unoptimized code.  For a future better test see GCC PR other/32998.  */
596   unsigned int has_loclist : 1;
597
598   /* These cache the results for producer_is_* fields.  CHECKED_PRODUCER is set
599      if all the producer_is_* fields are valid.  This information is cached
600      because profiling CU expansion showed excessive time spent in
601      producer_is_gxx_lt_4_6.  */
602   unsigned int checked_producer : 1;
603   unsigned int producer_is_gxx_lt_4_6 : 1;
604   unsigned int producer_is_gcc_lt_4_3 : 1;
605   unsigned int producer_is_icc : 1;
606
607   /* When set, the file that we're processing is known to have
608      debugging info for C++ namespaces.  GCC 3.3.x did not produce
609      this information, but later versions do.  */
610
611   unsigned int processing_has_namespace_info : 1;
612 };
613
614 /* Persistent data held for a compilation unit, even when not
615    processing it.  We put a pointer to this structure in the
616    read_symtab_private field of the psymtab.  */
617
618 struct dwarf2_per_cu_data
619 {
620   /* The start offset and length of this compilation unit.
621      NOTE: Unlike comp_unit_head.length, this length includes
622      initial_length_size.
623      If the DIE refers to a DWO file, this is always of the original die,
624      not the DWO file.  */
625   sect_offset sect_off;
626   unsigned int length;
627
628   /* DWARF standard version this data has been read from (such as 4 or 5).  */
629   short dwarf_version;
630
631   /* Flag indicating this compilation unit will be read in before
632      any of the current compilation units are processed.  */
633   unsigned int queued : 1;
634
635   /* This flag will be set when reading partial DIEs if we need to load
636      absolutely all DIEs for this compilation unit, instead of just the ones
637      we think are interesting.  It gets set if we look for a DIE in the
638      hash table and don't find it.  */
639   unsigned int load_all_dies : 1;
640
641   /* Non-zero if this CU is from .debug_types.
642      Struct dwarf2_per_cu_data is contained in struct signatured_type iff
643      this is non-zero.  */
644   unsigned int is_debug_types : 1;
645
646   /* Non-zero if this CU is from the .dwz file.  */
647   unsigned int is_dwz : 1;
648
649   /* Non-zero if reading a TU directly from a DWO file, bypassing the stub.
650      This flag is only valid if is_debug_types is true.
651      We can't read a CU directly from a DWO file: There are required
652      attributes in the stub.  */
653   unsigned int reading_dwo_directly : 1;
654
655   /* Non-zero if the TU has been read.
656      This is used to assist the "Stay in DWO Optimization" for Fission:
657      When reading a DWO, it's faster to read TUs from the DWO instead of
658      fetching them from random other DWOs (due to comdat folding).
659      If the TU has already been read, the optimization is unnecessary
660      (and unwise - we don't want to change where gdb thinks the TU lives
661      "midflight").
662      This flag is only valid if is_debug_types is true.  */
663   unsigned int tu_read : 1;
664
665   /* The section this CU/TU lives in.
666      If the DIE refers to a DWO file, this is always the original die,
667      not the DWO file.  */
668   struct dwarf2_section_info *section;
669
670   /* Set to non-NULL iff this CU is currently loaded.  When it gets freed out
671      of the CU cache it gets reset to NULL again.  This is left as NULL for
672      dummy CUs (a CU header, but nothing else).  */
673   struct dwarf2_cu *cu;
674
675   /* The corresponding objfile.
676      Normally we can get the objfile from dwarf2_per_objfile.
677      However we can enter this file with just a "per_cu" handle.  */
678   struct objfile *objfile;
679
680   /* When dwarf2_per_objfile->using_index is true, the 'quick' field
681      is active.  Otherwise, the 'psymtab' field is active.  */
682   union
683   {
684     /* The partial symbol table associated with this compilation unit,
685        or NULL for unread partial units.  */
686     struct partial_symtab *psymtab;
687
688     /* Data needed by the "quick" functions.  */
689     struct dwarf2_per_cu_quick_data *quick;
690   } v;
691
692   /* The CUs we import using DW_TAG_imported_unit.  This is filled in
693      while reading psymtabs, used to compute the psymtab dependencies,
694      and then cleared.  Then it is filled in again while reading full
695      symbols, and only deleted when the objfile is destroyed.
696
697      This is also used to work around a difference between the way gold
698      generates .gdb_index version <=7 and the way gdb does.  Arguably this
699      is a gold bug.  For symbols coming from TUs, gold records in the index
700      the CU that includes the TU instead of the TU itself.  This breaks
701      dw2_lookup_symbol: It assumes that if the index says symbol X lives
702      in CU/TU Y, then one need only expand Y and a subsequent lookup in Y
703      will find X.  Alas TUs live in their own symtab, so after expanding CU Y
704      we need to look in TU Z to find X.  Fortunately, this is akin to
705      DW_TAG_imported_unit, so we just use the same mechanism: For
706      .gdb_index version <=7 this also records the TUs that the CU referred
707      to.  Concurrently with this change gdb was modified to emit version 8
708      indices so we only pay a price for gold generated indices.
709      http://sourceware.org/bugzilla/show_bug.cgi?id=15021.  */
710   VEC (dwarf2_per_cu_ptr) *imported_symtabs;
711 };
712
713 /* Entry in the signatured_types hash table.  */
714
715 struct signatured_type
716 {
717   /* The "per_cu" object of this type.
718      This struct is used iff per_cu.is_debug_types.
719      N.B.: This is the first member so that it's easy to convert pointers
720      between them.  */
721   struct dwarf2_per_cu_data per_cu;
722
723   /* The type's signature.  */
724   ULONGEST signature;
725
726   /* Offset in the TU of the type's DIE, as read from the TU header.
727      If this TU is a DWO stub and the definition lives in a DWO file
728      (specified by DW_AT_GNU_dwo_name), this value is unusable.  */
729   cu_offset type_offset_in_tu;
730
731   /* Offset in the section of the type's DIE.
732      If the definition lives in a DWO file, this is the offset in the
733      .debug_types.dwo section.
734      The value is zero until the actual value is known.
735      Zero is otherwise not a valid section offset.  */
736   sect_offset type_offset_in_section;
737
738   /* Type units are grouped by their DW_AT_stmt_list entry so that they
739      can share them.  This points to the containing symtab.  */
740   struct type_unit_group *type_unit_group;
741
742   /* The type.
743      The first time we encounter this type we fully read it in and install it
744      in the symbol tables.  Subsequent times we only need the type.  */
745   struct type *type;
746
747   /* Containing DWO unit.
748      This field is valid iff per_cu.reading_dwo_directly.  */
749   struct dwo_unit *dwo_unit;
750 };
751
752 typedef struct signatured_type *sig_type_ptr;
753 DEF_VEC_P (sig_type_ptr);
754
755 /* A struct that can be used as a hash key for tables based on DW_AT_stmt_list.
756    This includes type_unit_group and quick_file_names.  */
757
758 struct stmt_list_hash
759 {
760   /* The DWO unit this table is from or NULL if there is none.  */
761   struct dwo_unit *dwo_unit;
762
763   /* Offset in .debug_line or .debug_line.dwo.  */
764   sect_offset line_sect_off;
765 };
766
767 /* Each element of dwarf2_per_objfile->type_unit_groups is a pointer to
768    an object of this type.  */
769
770 struct type_unit_group
771 {
772   /* dwarf2read.c's main "handle" on a TU symtab.
773      To simplify things we create an artificial CU that "includes" all the
774      type units using this stmt_list so that the rest of the code still has
775      a "per_cu" handle on the symtab.
776      This PER_CU is recognized by having no section.  */
777 #define IS_TYPE_UNIT_GROUP(per_cu) ((per_cu)->section == NULL)
778   struct dwarf2_per_cu_data per_cu;
779
780   /* The TUs that share this DW_AT_stmt_list entry.
781      This is added to while parsing type units to build partial symtabs,
782      and is deleted afterwards and not used again.  */
783   VEC (sig_type_ptr) *tus;
784
785   /* The compunit symtab.
786      Type units in a group needn't all be defined in the same source file,
787      so we create an essentially anonymous symtab as the compunit symtab.  */
788   struct compunit_symtab *compunit_symtab;
789
790   /* The data used to construct the hash key.  */
791   struct stmt_list_hash hash;
792
793   /* The number of symtabs from the line header.
794      The value here must match line_header.num_file_names.  */
795   unsigned int num_symtabs;
796
797   /* The symbol tables for this TU (obtained from the files listed in
798      DW_AT_stmt_list).
799      WARNING: The order of entries here must match the order of entries
800      in the line header.  After the first TU using this type_unit_group, the
801      line header for the subsequent TUs is recreated from this.  This is done
802      because we need to use the same symtabs for each TU using the same
803      DW_AT_stmt_list value.  Also note that symtabs may be repeated here,
804      there's no guarantee the line header doesn't have duplicate entries.  */
805   struct symtab **symtabs;
806 };
807
808 /* These sections are what may appear in a (real or virtual) DWO file.  */
809
810 struct dwo_sections
811 {
812   struct dwarf2_section_info abbrev;
813   struct dwarf2_section_info line;
814   struct dwarf2_section_info loc;
815   struct dwarf2_section_info loclists;
816   struct dwarf2_section_info macinfo;
817   struct dwarf2_section_info macro;
818   struct dwarf2_section_info str;
819   struct dwarf2_section_info str_offsets;
820   /* In the case of a virtual DWO file, these two are unused.  */
821   struct dwarf2_section_info info;
822   VEC (dwarf2_section_info_def) *types;
823 };
824
825 /* CUs/TUs in DWP/DWO files.  */
826
827 struct dwo_unit
828 {
829   /* Backlink to the containing struct dwo_file.  */
830   struct dwo_file *dwo_file;
831
832   /* The "id" that distinguishes this CU/TU.
833      .debug_info calls this "dwo_id", .debug_types calls this "signature".
834      Since signatures came first, we stick with it for consistency.  */
835   ULONGEST signature;
836
837   /* The section this CU/TU lives in, in the DWO file.  */
838   struct dwarf2_section_info *section;
839
840   /* Same as dwarf2_per_cu_data:{sect_off,length} but in the DWO section.  */
841   sect_offset sect_off;
842   unsigned int length;
843
844   /* For types, offset in the type's DIE of the type defined by this TU.  */
845   cu_offset type_offset_in_tu;
846 };
847
848 /* include/dwarf2.h defines the DWP section codes.
849    It defines a max value but it doesn't define a min value, which we
850    use for error checking, so provide one.  */
851
852 enum dwp_v2_section_ids
853 {
854   DW_SECT_MIN = 1
855 };
856
857 /* Data for one DWO file.
858
859    This includes virtual DWO files (a virtual DWO file is a DWO file as it
860    appears in a DWP file).  DWP files don't really have DWO files per se -
861    comdat folding of types "loses" the DWO file they came from, and from
862    a high level view DWP files appear to contain a mass of random types.
863    However, to maintain consistency with the non-DWP case we pretend DWP
864    files contain virtual DWO files, and we assign each TU with one virtual
865    DWO file (generally based on the line and abbrev section offsets -
866    a heuristic that seems to work in practice).  */
867
868 struct dwo_file
869 {
870   /* The DW_AT_GNU_dwo_name attribute.
871      For virtual DWO files the name is constructed from the section offsets
872      of abbrev,line,loc,str_offsets so that we combine virtual DWO files
873      from related CU+TUs.  */
874   const char *dwo_name;
875
876   /* The DW_AT_comp_dir attribute.  */
877   const char *comp_dir;
878
879   /* The bfd, when the file is open.  Otherwise this is NULL.
880      This is unused(NULL) for virtual DWO files where we use dwp_file.dbfd.  */
881   bfd *dbfd;
882
883   /* The sections that make up this DWO file.
884      Remember that for virtual DWO files in DWP V2, these are virtual
885      sections (for lack of a better name).  */
886   struct dwo_sections sections;
887
888   /* The CUs in the file.
889      Each element is a struct dwo_unit. Multiple CUs per DWO are supported as
890      an extension to handle LLVM's Link Time Optimization output (where
891      multiple source files may be compiled into a single object/dwo pair). */
892   htab_t cus;
893
894   /* Table of TUs in the file.
895      Each element is a struct dwo_unit.  */
896   htab_t tus;
897 };
898
899 /* These sections are what may appear in a DWP file.  */
900
901 struct dwp_sections
902 {
903   /* These are used by both DWP version 1 and 2.  */
904   struct dwarf2_section_info str;
905   struct dwarf2_section_info cu_index;
906   struct dwarf2_section_info tu_index;
907
908   /* These are only used by DWP version 2 files.
909      In DWP version 1 the .debug_info.dwo, .debug_types.dwo, and other
910      sections are referenced by section number, and are not recorded here.
911      In DWP version 2 there is at most one copy of all these sections, each
912      section being (effectively) comprised of the concatenation of all of the
913      individual sections that exist in the version 1 format.
914      To keep the code simple we treat each of these concatenated pieces as a
915      section itself (a virtual section?).  */
916   struct dwarf2_section_info abbrev;
917   struct dwarf2_section_info info;
918   struct dwarf2_section_info line;
919   struct dwarf2_section_info loc;
920   struct dwarf2_section_info macinfo;
921   struct dwarf2_section_info macro;
922   struct dwarf2_section_info str_offsets;
923   struct dwarf2_section_info types;
924 };
925
926 /* These sections are what may appear in a virtual DWO file in DWP version 1.
927    A virtual DWO file is a DWO file as it appears in a DWP file.  */
928
929 struct virtual_v1_dwo_sections
930 {
931   struct dwarf2_section_info abbrev;
932   struct dwarf2_section_info line;
933   struct dwarf2_section_info loc;
934   struct dwarf2_section_info macinfo;
935   struct dwarf2_section_info macro;
936   struct dwarf2_section_info str_offsets;
937   /* Each DWP hash table entry records one CU or one TU.
938      That is recorded here, and copied to dwo_unit.section.  */
939   struct dwarf2_section_info info_or_types;
940 };
941
942 /* Similar to virtual_v1_dwo_sections, but for DWP version 2.
943    In version 2, the sections of the DWO files are concatenated together
944    and stored in one section of that name.  Thus each ELF section contains
945    several "virtual" sections.  */
946
947 struct virtual_v2_dwo_sections
948 {
949   bfd_size_type abbrev_offset;
950   bfd_size_type abbrev_size;
951
952   bfd_size_type line_offset;
953   bfd_size_type line_size;
954
955   bfd_size_type loc_offset;
956   bfd_size_type loc_size;
957
958   bfd_size_type macinfo_offset;
959   bfd_size_type macinfo_size;
960
961   bfd_size_type macro_offset;
962   bfd_size_type macro_size;
963
964   bfd_size_type str_offsets_offset;
965   bfd_size_type str_offsets_size;
966
967   /* Each DWP hash table entry records one CU or one TU.
968      That is recorded here, and copied to dwo_unit.section.  */
969   bfd_size_type info_or_types_offset;
970   bfd_size_type info_or_types_size;
971 };
972
973 /* Contents of DWP hash tables.  */
974
975 struct dwp_hash_table
976 {
977   uint32_t version, nr_columns;
978   uint32_t nr_units, nr_slots;
979   const gdb_byte *hash_table, *unit_table;
980   union
981   {
982     struct
983     {
984       const gdb_byte *indices;
985     } v1;
986     struct
987     {
988       /* This is indexed by column number and gives the id of the section
989          in that column.  */
990 #define MAX_NR_V2_DWO_SECTIONS \
991   (1 /* .debug_info or .debug_types */ \
992    + 1 /* .debug_abbrev */ \
993    + 1 /* .debug_line */ \
994    + 1 /* .debug_loc */ \
995    + 1 /* .debug_str_offsets */ \
996    + 1 /* .debug_macro or .debug_macinfo */)
997       int section_ids[MAX_NR_V2_DWO_SECTIONS];
998       const gdb_byte *offsets;
999       const gdb_byte *sizes;
1000     } v2;
1001   } section_pool;
1002 };
1003
1004 /* Data for one DWP file.  */
1005
1006 struct dwp_file
1007 {
1008   /* Name of the file.  */
1009   const char *name;
1010
1011   /* File format version.  */
1012   int version;
1013
1014   /* The bfd.  */
1015   bfd *dbfd;
1016
1017   /* Section info for this file.  */
1018   struct dwp_sections sections;
1019
1020   /* Table of CUs in the file.  */
1021   const struct dwp_hash_table *cus;
1022
1023   /* Table of TUs in the file.  */
1024   const struct dwp_hash_table *tus;
1025
1026   /* Tables of loaded CUs/TUs.  Each entry is a struct dwo_unit *.  */
1027   htab_t loaded_cus;
1028   htab_t loaded_tus;
1029
1030   /* Table to map ELF section numbers to their sections.
1031      This is only needed for the DWP V1 file format.  */
1032   unsigned int num_sections;
1033   asection **elf_sections;
1034 };
1035
1036 /* This represents a '.dwz' file.  */
1037
1038 struct dwz_file
1039 {
1040   /* A dwz file can only contain a few sections.  */
1041   struct dwarf2_section_info abbrev;
1042   struct dwarf2_section_info info;
1043   struct dwarf2_section_info str;
1044   struct dwarf2_section_info line;
1045   struct dwarf2_section_info macro;
1046   struct dwarf2_section_info gdb_index;
1047
1048   /* The dwz's BFD.  */
1049   bfd *dwz_bfd;
1050 };
1051
1052 /* Struct used to pass misc. parameters to read_die_and_children, et
1053    al.  which are used for both .debug_info and .debug_types dies.
1054    All parameters here are unchanging for the life of the call.  This
1055    struct exists to abstract away the constant parameters of die reading.  */
1056
1057 struct die_reader_specs
1058 {
1059   /* The bfd of die_section.  */
1060   bfd* abfd;
1061
1062   /* The CU of the DIE we are parsing.  */
1063   struct dwarf2_cu *cu;
1064
1065   /* Non-NULL if reading a DWO file (including one packaged into a DWP).  */
1066   struct dwo_file *dwo_file;
1067
1068   /* The section the die comes from.
1069      This is either .debug_info or .debug_types, or the .dwo variants.  */
1070   struct dwarf2_section_info *die_section;
1071
1072   /* die_section->buffer.  */
1073   const gdb_byte *buffer;
1074
1075   /* The end of the buffer.  */
1076   const gdb_byte *buffer_end;
1077
1078   /* The value of the DW_AT_comp_dir attribute.  */
1079   const char *comp_dir;
1080 };
1081
1082 /* Type of function passed to init_cutu_and_read_dies, et.al.  */
1083 typedef void (die_reader_func_ftype) (const struct die_reader_specs *reader,
1084                                       const gdb_byte *info_ptr,
1085                                       struct die_info *comp_unit_die,
1086                                       int has_children,
1087                                       void *data);
1088
1089 /* A 1-based directory index.  This is a strong typedef to prevent
1090    accidentally using a directory index as a 0-based index into an
1091    array/vector.  */
1092 enum class dir_index : unsigned int {};
1093
1094 /* Likewise, a 1-based file name index.  */
1095 enum class file_name_index : unsigned int {};
1096
1097 struct file_entry
1098 {
1099   file_entry () = default;
1100
1101   file_entry (const char *name_, dir_index d_index_,
1102               unsigned int mod_time_, unsigned int length_)
1103     : name (name_),
1104       d_index (d_index_),
1105       mod_time (mod_time_),
1106       length (length_)
1107   {}
1108
1109   /* Return the include directory at D_INDEX stored in LH.  Returns
1110      NULL if D_INDEX is out of bounds.  */
1111   const char *include_dir (const line_header *lh) const;
1112
1113   /* The file name.  Note this is an observing pointer.  The memory is
1114      owned by debug_line_buffer.  */
1115   const char *name {};
1116
1117   /* The directory index (1-based).  */
1118   dir_index d_index {};
1119
1120   unsigned int mod_time {};
1121
1122   unsigned int length {};
1123
1124   /* True if referenced by the Line Number Program.  */
1125   bool included_p {};
1126
1127   /* The associated symbol table, if any.  */
1128   struct symtab *symtab {};
1129 };
1130
1131 /* The line number information for a compilation unit (found in the
1132    .debug_line section) begins with a "statement program header",
1133    which contains the following information.  */
1134 struct line_header
1135 {
1136   line_header ()
1137     : offset_in_dwz {}
1138   {}
1139
1140   /* Add an entry to the include directory table.  */
1141   void add_include_dir (const char *include_dir);
1142
1143   /* Add an entry to the file name table.  */
1144   void add_file_name (const char *name, dir_index d_index,
1145                       unsigned int mod_time, unsigned int length);
1146
1147   /* Return the include dir at INDEX (1-based).  Returns NULL if INDEX
1148      is out of bounds.  */
1149   const char *include_dir_at (dir_index index) const
1150   {
1151     /* Convert directory index number (1-based) to vector index
1152        (0-based).  */
1153     size_t vec_index = to_underlying (index) - 1;
1154
1155     if (vec_index >= include_dirs.size ())
1156       return NULL;
1157     return include_dirs[vec_index];
1158   }
1159
1160   /* Return the file name at INDEX (1-based).  Returns NULL if INDEX
1161      is out of bounds.  */
1162   file_entry *file_name_at (file_name_index index)
1163   {
1164     /* Convert file name index number (1-based) to vector index
1165        (0-based).  */
1166     size_t vec_index = to_underlying (index) - 1;
1167
1168     if (vec_index >= file_names.size ())
1169       return NULL;
1170     return &file_names[vec_index];
1171   }
1172
1173   /* Const version of the above.  */
1174   const file_entry *file_name_at (unsigned int index) const
1175   {
1176     if (index >= file_names.size ())
1177       return NULL;
1178     return &file_names[index];
1179   }
1180
1181   /* Offset of line number information in .debug_line section.  */
1182   sect_offset sect_off {};
1183
1184   /* OFFSET is for struct dwz_file associated with dwarf2_per_objfile.  */
1185   unsigned offset_in_dwz : 1; /* Can't initialize bitfields in-class.  */
1186
1187   unsigned int total_length {};
1188   unsigned short version {};
1189   unsigned int header_length {};
1190   unsigned char minimum_instruction_length {};
1191   unsigned char maximum_ops_per_instruction {};
1192   unsigned char default_is_stmt {};
1193   int line_base {};
1194   unsigned char line_range {};
1195   unsigned char opcode_base {};
1196
1197   /* standard_opcode_lengths[i] is the number of operands for the
1198      standard opcode whose value is i.  This means that
1199      standard_opcode_lengths[0] is unused, and the last meaningful
1200      element is standard_opcode_lengths[opcode_base - 1].  */
1201   std::unique_ptr<unsigned char[]> standard_opcode_lengths;
1202
1203   /* The include_directories table.  Note these are observing
1204      pointers.  The memory is owned by debug_line_buffer.  */
1205   std::vector<const char *> include_dirs;
1206
1207   /* The file_names table.  */
1208   std::vector<file_entry> file_names;
1209
1210   /* The start and end of the statement program following this
1211      header.  These point into dwarf2_per_objfile->line_buffer.  */
1212   const gdb_byte *statement_program_start {}, *statement_program_end {};
1213 };
1214
1215 typedef std::unique_ptr<line_header> line_header_up;
1216
1217 const char *
1218 file_entry::include_dir (const line_header *lh) const
1219 {
1220   return lh->include_dir_at (d_index);
1221 }
1222
1223 /* When we construct a partial symbol table entry we only
1224    need this much information.  */
1225 struct partial_die_info
1226   {
1227     /* Offset of this DIE.  */
1228     sect_offset sect_off;
1229
1230     /* DWARF-2 tag for this DIE.  */
1231     ENUM_BITFIELD(dwarf_tag) tag : 16;
1232
1233     /* Assorted flags describing the data found in this DIE.  */
1234     unsigned int has_children : 1;
1235     unsigned int is_external : 1;
1236     unsigned int is_declaration : 1;
1237     unsigned int has_type : 1;
1238     unsigned int has_specification : 1;
1239     unsigned int has_pc_info : 1;
1240     unsigned int may_be_inlined : 1;
1241
1242     /* This DIE has been marked DW_AT_main_subprogram.  */
1243     unsigned int main_subprogram : 1;
1244
1245     /* Flag set if the SCOPE field of this structure has been
1246        computed.  */
1247     unsigned int scope_set : 1;
1248
1249     /* Flag set if the DIE has a byte_size attribute.  */
1250     unsigned int has_byte_size : 1;
1251
1252     /* Flag set if the DIE has a DW_AT_const_value attribute.  */
1253     unsigned int has_const_value : 1;
1254
1255     /* Flag set if any of the DIE's children are template arguments.  */
1256     unsigned int has_template_arguments : 1;
1257
1258     /* Flag set if fixup_partial_die has been called on this die.  */
1259     unsigned int fixup_called : 1;
1260
1261     /* Flag set if DW_TAG_imported_unit uses DW_FORM_GNU_ref_alt.  */
1262     unsigned int is_dwz : 1;
1263
1264     /* Flag set if spec_offset uses DW_FORM_GNU_ref_alt.  */
1265     unsigned int spec_is_dwz : 1;
1266
1267     /* The name of this DIE.  Normally the value of DW_AT_name, but
1268        sometimes a default name for unnamed DIEs.  */
1269     const char *name;
1270
1271     /* The linkage name, if present.  */
1272     const char *linkage_name;
1273
1274     /* The scope to prepend to our children.  This is generally
1275        allocated on the comp_unit_obstack, so will disappear
1276        when this compilation unit leaves the cache.  */
1277     const char *scope;
1278
1279     /* Some data associated with the partial DIE.  The tag determines
1280        which field is live.  */
1281     union
1282     {
1283       /* The location description associated with this DIE, if any.  */
1284       struct dwarf_block *locdesc;
1285       /* The offset of an import, for DW_TAG_imported_unit.  */
1286       sect_offset sect_off;
1287     } d;
1288
1289     /* If HAS_PC_INFO, the PC range associated with this DIE.  */
1290     CORE_ADDR lowpc;
1291     CORE_ADDR highpc;
1292
1293     /* Pointer into the info_buffer (or types_buffer) pointing at the target of
1294        DW_AT_sibling, if any.  */
1295     /* NOTE: This member isn't strictly necessary, read_partial_die could
1296        return DW_AT_sibling values to its caller load_partial_dies.  */
1297     const gdb_byte *sibling;
1298
1299     /* If HAS_SPECIFICATION, the offset of the DIE referred to by
1300        DW_AT_specification (or DW_AT_abstract_origin or
1301        DW_AT_extension).  */
1302     sect_offset spec_offset;
1303
1304     /* Pointers to this DIE's parent, first child, and next sibling,
1305        if any.  */
1306     struct partial_die_info *die_parent, *die_child, *die_sibling;
1307   };
1308
1309 /* This data structure holds the information of an abbrev.  */
1310 struct abbrev_info
1311   {
1312     unsigned int number;        /* number identifying abbrev */
1313     enum dwarf_tag tag;         /* dwarf tag */
1314     unsigned short has_children;                /* boolean */
1315     unsigned short num_attrs;   /* number of attributes */
1316     struct attr_abbrev *attrs;  /* an array of attribute descriptions */
1317     struct abbrev_info *next;   /* next in chain */
1318   };
1319
1320 struct attr_abbrev
1321   {
1322     ENUM_BITFIELD(dwarf_attribute) name : 16;
1323     ENUM_BITFIELD(dwarf_form) form : 16;
1324
1325     /* It is valid only if FORM is DW_FORM_implicit_const.  */
1326     LONGEST implicit_const;
1327   };
1328
1329 /* Size of abbrev_table.abbrev_hash_table.  */
1330 #define ABBREV_HASH_SIZE 121
1331
1332 /* Top level data structure to contain an abbreviation table.  */
1333
1334 struct abbrev_table
1335 {
1336   /* Where the abbrev table came from.
1337      This is used as a sanity check when the table is used.  */
1338   sect_offset sect_off;
1339
1340   /* Storage for the abbrev table.  */
1341   struct obstack abbrev_obstack;
1342
1343   /* Hash table of abbrevs.
1344      This is an array of size ABBREV_HASH_SIZE allocated in abbrev_obstack.
1345      It could be statically allocated, but the previous code didn't so we
1346      don't either.  */
1347   struct abbrev_info **abbrevs;
1348 };
1349
1350 /* Attributes have a name and a value.  */
1351 struct attribute
1352   {
1353     ENUM_BITFIELD(dwarf_attribute) name : 16;
1354     ENUM_BITFIELD(dwarf_form) form : 15;
1355
1356     /* Has DW_STRING already been updated by dwarf2_canonicalize_name?  This
1357        field should be in u.str (existing only for DW_STRING) but it is kept
1358        here for better struct attribute alignment.  */
1359     unsigned int string_is_canonical : 1;
1360
1361     union
1362       {
1363         const char *str;
1364         struct dwarf_block *blk;
1365         ULONGEST unsnd;
1366         LONGEST snd;
1367         CORE_ADDR addr;
1368         ULONGEST signature;
1369       }
1370     u;
1371   };
1372
1373 /* This data structure holds a complete die structure.  */
1374 struct die_info
1375   {
1376     /* DWARF-2 tag for this DIE.  */
1377     ENUM_BITFIELD(dwarf_tag) tag : 16;
1378
1379     /* Number of attributes */
1380     unsigned char num_attrs;
1381
1382     /* True if we're presently building the full type name for the
1383        type derived from this DIE.  */
1384     unsigned char building_fullname : 1;
1385
1386     /* True if this die is in process.  PR 16581.  */
1387     unsigned char in_process : 1;
1388
1389     /* Abbrev number */
1390     unsigned int abbrev;
1391
1392     /* Offset in .debug_info or .debug_types section.  */
1393     sect_offset sect_off;
1394
1395     /* The dies in a compilation unit form an n-ary tree.  PARENT
1396        points to this die's parent; CHILD points to the first child of
1397        this node; and all the children of a given node are chained
1398        together via their SIBLING fields.  */
1399     struct die_info *child;     /* Its first child, if any.  */
1400     struct die_info *sibling;   /* Its next sibling, if any.  */
1401     struct die_info *parent;    /* Its parent, if any.  */
1402
1403     /* An array of attributes, with NUM_ATTRS elements.  There may be
1404        zero, but it's not common and zero-sized arrays are not
1405        sufficiently portable C.  */
1406     struct attribute attrs[1];
1407   };
1408
1409 /* Get at parts of an attribute structure.  */
1410
1411 #define DW_STRING(attr)    ((attr)->u.str)
1412 #define DW_STRING_IS_CANONICAL(attr) ((attr)->string_is_canonical)
1413 #define DW_UNSND(attr)     ((attr)->u.unsnd)
1414 #define DW_BLOCK(attr)     ((attr)->u.blk)
1415 #define DW_SND(attr)       ((attr)->u.snd)
1416 #define DW_ADDR(attr)      ((attr)->u.addr)
1417 #define DW_SIGNATURE(attr) ((attr)->u.signature)
1418
1419 /* Blocks are a bunch of untyped bytes.  */
1420 struct dwarf_block
1421   {
1422     size_t size;
1423
1424     /* Valid only if SIZE is not zero.  */
1425     const gdb_byte *data;
1426   };
1427
1428 #ifndef ATTR_ALLOC_CHUNK
1429 #define ATTR_ALLOC_CHUNK 4
1430 #endif
1431
1432 /* Allocate fields for structs, unions and enums in this size.  */
1433 #ifndef DW_FIELD_ALLOC_CHUNK
1434 #define DW_FIELD_ALLOC_CHUNK 4
1435 #endif
1436
1437 /* FIXME: We might want to set this from BFD via bfd_arch_bits_per_byte,
1438    but this would require a corresponding change in unpack_field_as_long
1439    and friends.  */
1440 static int bits_per_byte = 8;
1441
1442 struct nextfield
1443 {
1444   struct nextfield *next;
1445   int accessibility;
1446   int virtuality;
1447   struct field field;
1448 };
1449
1450 struct nextfnfield
1451 {
1452   struct nextfnfield *next;
1453   struct fn_field fnfield;
1454 };
1455
1456 struct fnfieldlist
1457 {
1458   const char *name;
1459   int length;
1460   struct nextfnfield *head;
1461 };
1462
1463 struct typedef_field_list
1464 {
1465   struct typedef_field field;
1466   struct typedef_field_list *next;
1467 };
1468
1469 /* The routines that read and process dies for a C struct or C++ class
1470    pass lists of data member fields and lists of member function fields
1471    in an instance of a field_info structure, as defined below.  */
1472 struct field_info
1473   {
1474     /* List of data member and baseclasses fields.  */
1475     struct nextfield *fields, *baseclasses;
1476
1477     /* Number of fields (including baseclasses).  */
1478     int nfields;
1479
1480     /* Number of baseclasses.  */
1481     int nbaseclasses;
1482
1483     /* Set if the accesibility of one of the fields is not public.  */
1484     int non_public_fields;
1485
1486     /* Member function fieldlist array, contains name of possibly overloaded
1487        member function, number of overloaded member functions and a pointer
1488        to the head of the member function field chain.  */
1489     struct fnfieldlist *fnfieldlists;
1490
1491     /* Number of entries in the fnfieldlists array.  */
1492     int nfnfields;
1493
1494     /* typedefs defined inside this class.  TYPEDEF_FIELD_LIST contains head of
1495        a NULL terminated list of TYPEDEF_FIELD_LIST_COUNT elements.  */
1496     struct typedef_field_list *typedef_field_list;
1497     unsigned typedef_field_list_count;
1498   };
1499
1500 /* One item on the queue of compilation units to read in full symbols
1501    for.  */
1502 struct dwarf2_queue_item
1503 {
1504   struct dwarf2_per_cu_data *per_cu;
1505   enum language pretend_language;
1506   struct dwarf2_queue_item *next;
1507 };
1508
1509 /* The current queue.  */
1510 static struct dwarf2_queue_item *dwarf2_queue, *dwarf2_queue_tail;
1511
1512 /* Loaded secondary compilation units are kept in memory until they
1513    have not been referenced for the processing of this many
1514    compilation units.  Set this to zero to disable caching.  Cache
1515    sizes of up to at least twenty will improve startup time for
1516    typical inter-CU-reference binaries, at an obvious memory cost.  */
1517 static int dwarf_max_cache_age = 5;
1518 static void
1519 show_dwarf_max_cache_age (struct ui_file *file, int from_tty,
1520                           struct cmd_list_element *c, const char *value)
1521 {
1522   fprintf_filtered (file, _("The upper bound on the age of cached "
1523                             "DWARF compilation units is %s.\n"),
1524                     value);
1525 }
1526 \f
1527 /* local function prototypes */
1528
1529 static const char *get_section_name (const struct dwarf2_section_info *);
1530
1531 static const char *get_section_file_name (const struct dwarf2_section_info *);
1532
1533 static void dwarf2_find_base_address (struct die_info *die,
1534                                       struct dwarf2_cu *cu);
1535
1536 static struct partial_symtab *create_partial_symtab
1537   (struct dwarf2_per_cu_data *per_cu, const char *name);
1538
1539 static void build_type_psymtabs_reader (const struct die_reader_specs *reader,
1540                                         const gdb_byte *info_ptr,
1541                                         struct die_info *type_unit_die,
1542                                         int has_children, void *data);
1543
1544 static void dwarf2_build_psymtabs_hard (struct objfile *);
1545
1546 static void scan_partial_symbols (struct partial_die_info *,
1547                                   CORE_ADDR *, CORE_ADDR *,
1548                                   int, struct dwarf2_cu *);
1549
1550 static void add_partial_symbol (struct partial_die_info *,
1551                                 struct dwarf2_cu *);
1552
1553 static void add_partial_namespace (struct partial_die_info *pdi,
1554                                    CORE_ADDR *lowpc, CORE_ADDR *highpc,
1555                                    int set_addrmap, struct dwarf2_cu *cu);
1556
1557 static void add_partial_module (struct partial_die_info *pdi, CORE_ADDR *lowpc,
1558                                 CORE_ADDR *highpc, int set_addrmap,
1559                                 struct dwarf2_cu *cu);
1560
1561 static void add_partial_enumeration (struct partial_die_info *enum_pdi,
1562                                      struct dwarf2_cu *cu);
1563
1564 static void add_partial_subprogram (struct partial_die_info *pdi,
1565                                     CORE_ADDR *lowpc, CORE_ADDR *highpc,
1566                                     int need_pc, struct dwarf2_cu *cu);
1567
1568 static void dwarf2_read_symtab (struct partial_symtab *,
1569                                 struct objfile *);
1570
1571 static void psymtab_to_symtab_1 (struct partial_symtab *);
1572
1573 static struct abbrev_info *abbrev_table_lookup_abbrev
1574   (const struct abbrev_table *, unsigned int);
1575
1576 static struct abbrev_table *abbrev_table_read_table
1577   (struct dwarf2_section_info *, sect_offset);
1578
1579 static void abbrev_table_free (struct abbrev_table *);
1580
1581 static void abbrev_table_free_cleanup (void *);
1582
1583 static void dwarf2_read_abbrevs (struct dwarf2_cu *,
1584                                  struct dwarf2_section_info *);
1585
1586 static void dwarf2_free_abbrev_table (void *);
1587
1588 static unsigned int peek_abbrev_code (bfd *, const gdb_byte *);
1589
1590 static struct partial_die_info *load_partial_dies
1591   (const struct die_reader_specs *, const gdb_byte *, int);
1592
1593 static const gdb_byte *read_partial_die (const struct die_reader_specs *,
1594                                          struct partial_die_info *,
1595                                          struct abbrev_info *,
1596                                          unsigned int,
1597                                          const gdb_byte *);
1598
1599 static struct partial_die_info *find_partial_die (sect_offset, int,
1600                                                   struct dwarf2_cu *);
1601
1602 static void fixup_partial_die (struct partial_die_info *,
1603                                struct dwarf2_cu *);
1604
1605 static const gdb_byte *read_attribute (const struct die_reader_specs *,
1606                                        struct attribute *, struct attr_abbrev *,
1607                                        const gdb_byte *);
1608
1609 static unsigned int read_1_byte (bfd *, const gdb_byte *);
1610
1611 static int read_1_signed_byte (bfd *, const gdb_byte *);
1612
1613 static unsigned int read_2_bytes (bfd *, const gdb_byte *);
1614
1615 static unsigned int read_4_bytes (bfd *, const gdb_byte *);
1616
1617 static ULONGEST read_8_bytes (bfd *, const gdb_byte *);
1618
1619 static CORE_ADDR read_address (bfd *, const gdb_byte *ptr, struct dwarf2_cu *,
1620                                unsigned int *);
1621
1622 static LONGEST read_initial_length (bfd *, const gdb_byte *, unsigned int *);
1623
1624 static LONGEST read_checked_initial_length_and_offset
1625   (bfd *, const gdb_byte *, const struct comp_unit_head *,
1626    unsigned int *, unsigned int *);
1627
1628 static LONGEST read_offset (bfd *, const gdb_byte *,
1629                             const struct comp_unit_head *,
1630                             unsigned int *);
1631
1632 static LONGEST read_offset_1 (bfd *, const gdb_byte *, unsigned int);
1633
1634 static sect_offset read_abbrev_offset (struct dwarf2_section_info *,
1635                                        sect_offset);
1636
1637 static const gdb_byte *read_n_bytes (bfd *, const gdb_byte *, unsigned int);
1638
1639 static const char *read_direct_string (bfd *, const gdb_byte *, unsigned int *);
1640
1641 static const char *read_indirect_string (bfd *, const gdb_byte *,
1642                                          const struct comp_unit_head *,
1643                                          unsigned int *);
1644
1645 static const char *read_indirect_line_string (bfd *, const gdb_byte *,
1646                                               const struct comp_unit_head *,
1647                                               unsigned int *);
1648
1649 static const char *read_indirect_string_from_dwz (struct dwz_file *, LONGEST);
1650
1651 static LONGEST read_signed_leb128 (bfd *, const gdb_byte *, unsigned int *);
1652
1653 static CORE_ADDR read_addr_index_from_leb128 (struct dwarf2_cu *,
1654                                               const gdb_byte *,
1655                                               unsigned int *);
1656
1657 static const char *read_str_index (const struct die_reader_specs *reader,
1658                                    ULONGEST str_index);
1659
1660 static void set_cu_language (unsigned int, struct dwarf2_cu *);
1661
1662 static struct attribute *dwarf2_attr (struct die_info *, unsigned int,
1663                                       struct dwarf2_cu *);
1664
1665 static struct attribute *dwarf2_attr_no_follow (struct die_info *,
1666                                                 unsigned int);
1667
1668 static const char *dwarf2_string_attr (struct die_info *die, unsigned int name,
1669                                        struct dwarf2_cu *cu);
1670
1671 static int dwarf2_flag_true_p (struct die_info *die, unsigned name,
1672                                struct dwarf2_cu *cu);
1673
1674 static int die_is_declaration (struct die_info *, struct dwarf2_cu *cu);
1675
1676 static struct die_info *die_specification (struct die_info *die,
1677                                            struct dwarf2_cu **);
1678
1679 static line_header_up dwarf_decode_line_header (sect_offset sect_off,
1680                                                 struct dwarf2_cu *cu);
1681
1682 static void dwarf_decode_lines (struct line_header *, const char *,
1683                                 struct dwarf2_cu *, struct partial_symtab *,
1684                                 CORE_ADDR, int decode_mapping);
1685
1686 static void dwarf2_start_subfile (const char *, const char *);
1687
1688 static struct compunit_symtab *dwarf2_start_symtab (struct dwarf2_cu *,
1689                                                     const char *, const char *,
1690                                                     CORE_ADDR);
1691
1692 static struct symbol *new_symbol (struct die_info *, struct type *,
1693                                   struct dwarf2_cu *);
1694
1695 static struct symbol *new_symbol_full (struct die_info *, struct type *,
1696                                        struct dwarf2_cu *, struct symbol *);
1697
1698 static void dwarf2_const_value (const struct attribute *, struct symbol *,
1699                                 struct dwarf2_cu *);
1700
1701 static void dwarf2_const_value_attr (const struct attribute *attr,
1702                                      struct type *type,
1703                                      const char *name,
1704                                      struct obstack *obstack,
1705                                      struct dwarf2_cu *cu, LONGEST *value,
1706                                      const gdb_byte **bytes,
1707                                      struct dwarf2_locexpr_baton **baton);
1708
1709 static struct type *die_type (struct die_info *, struct dwarf2_cu *);
1710
1711 static int need_gnat_info (struct dwarf2_cu *);
1712
1713 static struct type *die_descriptive_type (struct die_info *,
1714                                           struct dwarf2_cu *);
1715
1716 static void set_descriptive_type (struct type *, struct die_info *,
1717                                   struct dwarf2_cu *);
1718
1719 static struct type *die_containing_type (struct die_info *,
1720                                          struct dwarf2_cu *);
1721
1722 static struct type *lookup_die_type (struct die_info *, const struct attribute *,
1723                                      struct dwarf2_cu *);
1724
1725 static struct type *read_type_die (struct die_info *, struct dwarf2_cu *);
1726
1727 static struct type *read_type_die_1 (struct die_info *, struct dwarf2_cu *);
1728
1729 static const char *determine_prefix (struct die_info *die, struct dwarf2_cu *);
1730
1731 static char *typename_concat (struct obstack *obs, const char *prefix,
1732                               const char *suffix, int physname,
1733                               struct dwarf2_cu *cu);
1734
1735 static void read_file_scope (struct die_info *, struct dwarf2_cu *);
1736
1737 static void read_type_unit_scope (struct die_info *, struct dwarf2_cu *);
1738
1739 static void read_func_scope (struct die_info *, struct dwarf2_cu *);
1740
1741 static void read_lexical_block_scope (struct die_info *, struct dwarf2_cu *);
1742
1743 static void read_call_site_scope (struct die_info *die, struct dwarf2_cu *cu);
1744
1745 static int dwarf2_ranges_read (unsigned, CORE_ADDR *, CORE_ADDR *,
1746                                struct dwarf2_cu *, struct partial_symtab *);
1747
1748 /* How dwarf2_get_pc_bounds constructed its *LOWPC and *HIGHPC return
1749    values.  Keep the items ordered with increasing constraints compliance.  */
1750 enum pc_bounds_kind
1751 {
1752   /* No attribute DW_AT_low_pc, DW_AT_high_pc or DW_AT_ranges was found.  */
1753   PC_BOUNDS_NOT_PRESENT,
1754
1755   /* Some of the attributes DW_AT_low_pc, DW_AT_high_pc or DW_AT_ranges
1756      were present but they do not form a valid range of PC addresses.  */
1757   PC_BOUNDS_INVALID,
1758
1759   /* Discontiguous range was found - that is DW_AT_ranges was found.  */
1760   PC_BOUNDS_RANGES,
1761
1762   /* Contiguous range was found - DW_AT_low_pc and DW_AT_high_pc were found.  */
1763   PC_BOUNDS_HIGH_LOW,
1764 };
1765
1766 static enum pc_bounds_kind dwarf2_get_pc_bounds (struct die_info *,
1767                                                  CORE_ADDR *, CORE_ADDR *,
1768                                                  struct dwarf2_cu *,
1769                                                  struct partial_symtab *);
1770
1771 static void get_scope_pc_bounds (struct die_info *,
1772                                  CORE_ADDR *, CORE_ADDR *,
1773                                  struct dwarf2_cu *);
1774
1775 static void dwarf2_record_block_ranges (struct die_info *, struct block *,
1776                                         CORE_ADDR, struct dwarf2_cu *);
1777
1778 static void dwarf2_add_field (struct field_info *, struct die_info *,
1779                               struct dwarf2_cu *);
1780
1781 static void dwarf2_attach_fields_to_type (struct field_info *,
1782                                           struct type *, struct dwarf2_cu *);
1783
1784 static void dwarf2_add_member_fn (struct field_info *,
1785                                   struct die_info *, struct type *,
1786                                   struct dwarf2_cu *);
1787
1788 static void dwarf2_attach_fn_fields_to_type (struct field_info *,
1789                                              struct type *,
1790                                              struct dwarf2_cu *);
1791
1792 static void process_structure_scope (struct die_info *, struct dwarf2_cu *);
1793
1794 static void read_common_block (struct die_info *, struct dwarf2_cu *);
1795
1796 static void read_namespace (struct die_info *die, struct dwarf2_cu *);
1797
1798 static void read_module (struct die_info *die, struct dwarf2_cu *cu);
1799
1800 static struct using_direct **using_directives (enum language);
1801
1802 static void read_import_statement (struct die_info *die, struct dwarf2_cu *);
1803
1804 static int read_namespace_alias (struct die_info *die, struct dwarf2_cu *cu);
1805
1806 static struct type *read_module_type (struct die_info *die,
1807                                       struct dwarf2_cu *cu);
1808
1809 static const char *namespace_name (struct die_info *die,
1810                                    int *is_anonymous, struct dwarf2_cu *);
1811
1812 static void process_enumeration_scope (struct die_info *, struct dwarf2_cu *);
1813
1814 static CORE_ADDR decode_locdesc (struct dwarf_block *, struct dwarf2_cu *);
1815
1816 static enum dwarf_array_dim_ordering read_array_order (struct die_info *,
1817                                                        struct dwarf2_cu *);
1818
1819 static struct die_info *read_die_and_siblings_1
1820   (const struct die_reader_specs *, const gdb_byte *, const gdb_byte **,
1821    struct die_info *);
1822
1823 static struct die_info *read_die_and_siblings (const struct die_reader_specs *,
1824                                                const gdb_byte *info_ptr,
1825                                                const gdb_byte **new_info_ptr,
1826                                                struct die_info *parent);
1827
1828 static const gdb_byte *read_full_die_1 (const struct die_reader_specs *,
1829                                         struct die_info **, const gdb_byte *,
1830                                         int *, int);
1831
1832 static const gdb_byte *read_full_die (const struct die_reader_specs *,
1833                                       struct die_info **, const gdb_byte *,
1834                                       int *);
1835
1836 static void process_die (struct die_info *, struct dwarf2_cu *);
1837
1838 static const char *dwarf2_canonicalize_name (const char *, struct dwarf2_cu *,
1839                                              struct obstack *);
1840
1841 static const char *dwarf2_name (struct die_info *die, struct dwarf2_cu *);
1842
1843 static const char *dwarf2_full_name (const char *name,
1844                                      struct die_info *die,
1845                                      struct dwarf2_cu *cu);
1846
1847 static const char *dwarf2_physname (const char *name, struct die_info *die,
1848                                     struct dwarf2_cu *cu);
1849
1850 static struct die_info *dwarf2_extension (struct die_info *die,
1851                                           struct dwarf2_cu **);
1852
1853 static const char *dwarf_tag_name (unsigned int);
1854
1855 static const char *dwarf_attr_name (unsigned int);
1856
1857 static const char *dwarf_form_name (unsigned int);
1858
1859 static const char *dwarf_bool_name (unsigned int);
1860
1861 static const char *dwarf_type_encoding_name (unsigned int);
1862
1863 static struct die_info *sibling_die (struct die_info *);
1864
1865 static void dump_die_shallow (struct ui_file *, int indent, struct die_info *);
1866
1867 static void dump_die_for_error (struct die_info *);
1868
1869 static void dump_die_1 (struct ui_file *, int level, int max_level,
1870                         struct die_info *);
1871
1872 /*static*/ void dump_die (struct die_info *, int max_level);
1873
1874 static void store_in_ref_table (struct die_info *,
1875                                 struct dwarf2_cu *);
1876
1877 static sect_offset dwarf2_get_ref_die_offset (const struct attribute *);
1878
1879 static LONGEST dwarf2_get_attr_constant_value (const struct attribute *, int);
1880
1881 static struct die_info *follow_die_ref_or_sig (struct die_info *,
1882                                                const struct attribute *,
1883                                                struct dwarf2_cu **);
1884
1885 static struct die_info *follow_die_ref (struct die_info *,
1886                                         const struct attribute *,
1887                                         struct dwarf2_cu **);
1888
1889 static struct die_info *follow_die_sig (struct die_info *,
1890                                         const struct attribute *,
1891                                         struct dwarf2_cu **);
1892
1893 static struct type *get_signatured_type (struct die_info *, ULONGEST,
1894                                          struct dwarf2_cu *);
1895
1896 static struct type *get_DW_AT_signature_type (struct die_info *,
1897                                               const struct attribute *,
1898                                               struct dwarf2_cu *);
1899
1900 static void load_full_type_unit (struct dwarf2_per_cu_data *per_cu);
1901
1902 static void read_signatured_type (struct signatured_type *);
1903
1904 static int attr_to_dynamic_prop (const struct attribute *attr,
1905                                  struct die_info *die, struct dwarf2_cu *cu,
1906                                  struct dynamic_prop *prop);
1907
1908 /* memory allocation interface */
1909
1910 static struct dwarf_block *dwarf_alloc_block (struct dwarf2_cu *);
1911
1912 static struct die_info *dwarf_alloc_die (struct dwarf2_cu *, int);
1913
1914 static void dwarf_decode_macros (struct dwarf2_cu *, unsigned int, int);
1915
1916 static int attr_form_is_block (const struct attribute *);
1917
1918 static int attr_form_is_section_offset (const struct attribute *);
1919
1920 static int attr_form_is_constant (const struct attribute *);
1921
1922 static int attr_form_is_ref (const struct attribute *);
1923
1924 static void fill_in_loclist_baton (struct dwarf2_cu *cu,
1925                                    struct dwarf2_loclist_baton *baton,
1926                                    const struct attribute *attr);
1927
1928 static void dwarf2_symbol_mark_computed (const struct attribute *attr,
1929                                          struct symbol *sym,
1930                                          struct dwarf2_cu *cu,
1931                                          int is_block);
1932
1933 static const gdb_byte *skip_one_die (const struct die_reader_specs *reader,
1934                                      const gdb_byte *info_ptr,
1935                                      struct abbrev_info *abbrev);
1936
1937 static void free_stack_comp_unit (void *);
1938
1939 static hashval_t partial_die_hash (const void *item);
1940
1941 static int partial_die_eq (const void *item_lhs, const void *item_rhs);
1942
1943 static struct dwarf2_per_cu_data *dwarf2_find_containing_comp_unit
1944   (sect_offset sect_off, unsigned int offset_in_dwz, struct objfile *objfile);
1945
1946 static void init_one_comp_unit (struct dwarf2_cu *cu,
1947                                 struct dwarf2_per_cu_data *per_cu);
1948
1949 static void prepare_one_comp_unit (struct dwarf2_cu *cu,
1950                                    struct die_info *comp_unit_die,
1951                                    enum language pretend_language);
1952
1953 static void free_heap_comp_unit (void *);
1954
1955 static void free_cached_comp_units (void *);
1956
1957 static void age_cached_comp_units (void);
1958
1959 static void free_one_cached_comp_unit (struct dwarf2_per_cu_data *);
1960
1961 static struct type *set_die_type (struct die_info *, struct type *,
1962                                   struct dwarf2_cu *);
1963
1964 static void create_all_comp_units (struct objfile *);
1965
1966 static int create_all_type_units (struct objfile *);
1967
1968 static void load_full_comp_unit (struct dwarf2_per_cu_data *,
1969                                  enum language);
1970
1971 static void process_full_comp_unit (struct dwarf2_per_cu_data *,
1972                                     enum language);
1973
1974 static void process_full_type_unit (struct dwarf2_per_cu_data *,
1975                                     enum language);
1976
1977 static void dwarf2_add_dependence (struct dwarf2_cu *,
1978                                    struct dwarf2_per_cu_data *);
1979
1980 static void dwarf2_mark (struct dwarf2_cu *);
1981
1982 static void dwarf2_clear_marks (struct dwarf2_per_cu_data *);
1983
1984 static struct type *get_die_type_at_offset (sect_offset,
1985                                             struct dwarf2_per_cu_data *);
1986
1987 static struct type *get_die_type (struct die_info *die, struct dwarf2_cu *cu);
1988
1989 static void dwarf2_release_queue (void *dummy);
1990
1991 static void queue_comp_unit (struct dwarf2_per_cu_data *per_cu,
1992                              enum language pretend_language);
1993
1994 static void process_queue (void);
1995
1996 /* The return type of find_file_and_directory.  Note, the enclosed
1997    string pointers are only valid while this object is valid.  */
1998
1999 struct file_and_directory
2000 {
2001   /* The filename.  This is never NULL.  */
2002   const char *name;
2003
2004   /* The compilation directory.  NULL if not known.  If we needed to
2005      compute a new string, this points to COMP_DIR_STORAGE, otherwise,
2006      points directly to the DW_AT_comp_dir string attribute owned by
2007      the obstack that owns the DIE.  */
2008   const char *comp_dir;
2009
2010   /* If we needed to build a new string for comp_dir, this is what
2011      owns the storage.  */
2012   std::string comp_dir_storage;
2013 };
2014
2015 static file_and_directory find_file_and_directory (struct die_info *die,
2016                                                    struct dwarf2_cu *cu);
2017
2018 static char *file_full_name (int file, struct line_header *lh,
2019                              const char *comp_dir);
2020
2021 /* Expected enum dwarf_unit_type for read_comp_unit_head.  */
2022 enum class rcuh_kind { COMPILE, TYPE };
2023
2024 static const gdb_byte *read_and_check_comp_unit_head
2025   (struct comp_unit_head *header,
2026    struct dwarf2_section_info *section,
2027    struct dwarf2_section_info *abbrev_section, const gdb_byte *info_ptr,
2028    rcuh_kind section_kind);
2029
2030 static void init_cutu_and_read_dies
2031   (struct dwarf2_per_cu_data *this_cu, struct abbrev_table *abbrev_table,
2032    int use_existing_cu, int keep,
2033    die_reader_func_ftype *die_reader_func, void *data);
2034
2035 static void init_cutu_and_read_dies_simple
2036   (struct dwarf2_per_cu_data *this_cu,
2037    die_reader_func_ftype *die_reader_func, void *data);
2038
2039 static htab_t allocate_signatured_type_table (struct objfile *objfile);
2040
2041 static htab_t allocate_dwo_unit_table (struct objfile *objfile);
2042
2043 static struct dwo_unit *lookup_dwo_unit_in_dwp
2044   (struct dwp_file *dwp_file, const char *comp_dir,
2045    ULONGEST signature, int is_debug_types);
2046
2047 static struct dwp_file *get_dwp_file (void);
2048
2049 static struct dwo_unit *lookup_dwo_comp_unit
2050   (struct dwarf2_per_cu_data *, const char *, const char *, ULONGEST);
2051
2052 static struct dwo_unit *lookup_dwo_type_unit
2053   (struct signatured_type *, const char *, const char *);
2054
2055 static void queue_and_load_all_dwo_tus (struct dwarf2_per_cu_data *);
2056
2057 static void free_dwo_file_cleanup (void *);
2058
2059 static void process_cu_includes (void);
2060
2061 static void check_producer (struct dwarf2_cu *cu);
2062
2063 static void free_line_header_voidp (void *arg);
2064 \f
2065 /* Various complaints about symbol reading that don't abort the process.  */
2066
2067 static void
2068 dwarf2_statement_list_fits_in_line_number_section_complaint (void)
2069 {
2070   complaint (&symfile_complaints,
2071              _("statement list doesn't fit in .debug_line section"));
2072 }
2073
2074 static void
2075 dwarf2_debug_line_missing_file_complaint (void)
2076 {
2077   complaint (&symfile_complaints,
2078              _(".debug_line section has line data without a file"));
2079 }
2080
2081 static void
2082 dwarf2_debug_line_missing_end_sequence_complaint (void)
2083 {
2084   complaint (&symfile_complaints,
2085              _(".debug_line section has line "
2086                "program sequence without an end"));
2087 }
2088
2089 static void
2090 dwarf2_complex_location_expr_complaint (void)
2091 {
2092   complaint (&symfile_complaints, _("location expression too complex"));
2093 }
2094
2095 static void
2096 dwarf2_const_value_length_mismatch_complaint (const char *arg1, int arg2,
2097                                               int arg3)
2098 {
2099   complaint (&symfile_complaints,
2100              _("const value length mismatch for '%s', got %d, expected %d"),
2101              arg1, arg2, arg3);
2102 }
2103
2104 static void
2105 dwarf2_section_buffer_overflow_complaint (struct dwarf2_section_info *section)
2106 {
2107   complaint (&symfile_complaints,
2108              _("debug info runs off end of %s section"
2109                " [in module %s]"),
2110              get_section_name (section),
2111              get_section_file_name (section));
2112 }
2113
2114 static void
2115 dwarf2_macro_malformed_definition_complaint (const char *arg1)
2116 {
2117   complaint (&symfile_complaints,
2118              _("macro debug info contains a "
2119                "malformed macro definition:\n`%s'"),
2120              arg1);
2121 }
2122
2123 static void
2124 dwarf2_invalid_attrib_class_complaint (const char *arg1, const char *arg2)
2125 {
2126   complaint (&symfile_complaints,
2127              _("invalid attribute class or form for '%s' in '%s'"),
2128              arg1, arg2);
2129 }
2130
2131 /* Hash function for line_header_hash.  */
2132
2133 static hashval_t
2134 line_header_hash (const struct line_header *ofs)
2135 {
2136   return to_underlying (ofs->sect_off) ^ ofs->offset_in_dwz;
2137 }
2138
2139 /* Hash function for htab_create_alloc_ex for line_header_hash.  */
2140
2141 static hashval_t
2142 line_header_hash_voidp (const void *item)
2143 {
2144   const struct line_header *ofs = (const struct line_header *) item;
2145
2146   return line_header_hash (ofs);
2147 }
2148
2149 /* Equality function for line_header_hash.  */
2150
2151 static int
2152 line_header_eq_voidp (const void *item_lhs, const void *item_rhs)
2153 {
2154   const struct line_header *ofs_lhs = (const struct line_header *) item_lhs;
2155   const struct line_header *ofs_rhs = (const struct line_header *) item_rhs;
2156
2157   return (ofs_lhs->sect_off == ofs_rhs->sect_off
2158           && ofs_lhs->offset_in_dwz == ofs_rhs->offset_in_dwz);
2159 }
2160
2161 \f
2162 #if WORDS_BIGENDIAN
2163
2164 /* Convert VALUE between big- and little-endian.  */
2165 static offset_type
2166 byte_swap (offset_type value)
2167 {
2168   offset_type result;
2169
2170   result = (value & 0xff) << 24;
2171   result |= (value & 0xff00) << 8;
2172   result |= (value & 0xff0000) >> 8;
2173   result |= (value & 0xff000000) >> 24;
2174   return result;
2175 }
2176
2177 #define MAYBE_SWAP(V)  byte_swap (V)
2178
2179 #else
2180 #define MAYBE_SWAP(V) static_cast<offset_type> (V)
2181 #endif /* WORDS_BIGENDIAN */
2182
2183 /* Read the given attribute value as an address, taking the attribute's
2184    form into account.  */
2185
2186 static CORE_ADDR
2187 attr_value_as_address (struct attribute *attr)
2188 {
2189   CORE_ADDR addr;
2190
2191   if (attr->form != DW_FORM_addr && attr->form != DW_FORM_GNU_addr_index)
2192     {
2193       /* Aside from a few clearly defined exceptions, attributes that
2194          contain an address must always be in DW_FORM_addr form.
2195          Unfortunately, some compilers happen to be violating this
2196          requirement by encoding addresses using other forms, such
2197          as DW_FORM_data4 for example.  For those broken compilers,
2198          we try to do our best, without any guarantee of success,
2199          to interpret the address correctly.  It would also be nice
2200          to generate a complaint, but that would require us to maintain
2201          a list of legitimate cases where a non-address form is allowed,
2202          as well as update callers to pass in at least the CU's DWARF
2203          version.  This is more overhead than what we're willing to
2204          expand for a pretty rare case.  */
2205       addr = DW_UNSND (attr);
2206     }
2207   else
2208     addr = DW_ADDR (attr);
2209
2210   return addr;
2211 }
2212
2213 /* The suffix for an index file.  */
2214 #define INDEX_SUFFIX ".gdb-index"
2215
2216 /* See declaration.  */
2217
2218 dwarf2_per_objfile::dwarf2_per_objfile (struct objfile *objfile_,
2219                                         const dwarf2_debug_sections *names)
2220   : objfile (objfile_)
2221 {
2222   if (names == NULL)
2223     names = &dwarf2_elf_names;
2224
2225   bfd *obfd = objfile->obfd;
2226
2227   for (asection *sec = obfd->sections; sec != NULL; sec = sec->next)
2228     locate_sections (obfd, sec, *names);
2229 }
2230
2231 dwarf2_per_objfile::~dwarf2_per_objfile ()
2232 {
2233   /* Cached DIE trees use xmalloc and the comp_unit_obstack.  */
2234   free_cached_comp_units ();
2235
2236   if (quick_file_names_table)
2237     htab_delete (quick_file_names_table);
2238
2239   if (line_header_hash)
2240     htab_delete (line_header_hash);
2241
2242   /* Everything else should be on the objfile obstack.  */
2243 }
2244
2245 /* See declaration.  */
2246
2247 void
2248 dwarf2_per_objfile::free_cached_comp_units ()
2249 {
2250   dwarf2_per_cu_data *per_cu = read_in_chain;
2251   dwarf2_per_cu_data **last_chain = &read_in_chain;
2252   while (per_cu != NULL)
2253     {
2254       dwarf2_per_cu_data *next_cu = per_cu->cu->read_in_chain;
2255
2256       free_heap_comp_unit (per_cu->cu);
2257       *last_chain = next_cu;
2258       per_cu = next_cu;
2259     }
2260 }
2261
2262 /* Try to locate the sections we need for DWARF 2 debugging
2263    information and return true if we have enough to do something.
2264    NAMES points to the dwarf2 section names, or is NULL if the standard
2265    ELF names are used.  */
2266
2267 int
2268 dwarf2_has_info (struct objfile *objfile,
2269                  const struct dwarf2_debug_sections *names)
2270 {
2271   dwarf2_per_objfile = ((struct dwarf2_per_objfile *)
2272                         objfile_data (objfile, dwarf2_objfile_data_key));
2273   if (!dwarf2_per_objfile)
2274     {
2275       /* Initialize per-objfile state.  */
2276       struct dwarf2_per_objfile *data
2277         = XOBNEW (&objfile->objfile_obstack, struct dwarf2_per_objfile);
2278
2279       dwarf2_per_objfile = new (data) struct dwarf2_per_objfile (objfile, names);
2280       set_objfile_data (objfile, dwarf2_objfile_data_key, dwarf2_per_objfile);
2281     }
2282   return (!dwarf2_per_objfile->info.is_virtual
2283           && dwarf2_per_objfile->info.s.section != NULL
2284           && !dwarf2_per_objfile->abbrev.is_virtual
2285           && dwarf2_per_objfile->abbrev.s.section != NULL);
2286 }
2287
2288 /* Return the containing section of virtual section SECTION.  */
2289
2290 static struct dwarf2_section_info *
2291 get_containing_section (const struct dwarf2_section_info *section)
2292 {
2293   gdb_assert (section->is_virtual);
2294   return section->s.containing_section;
2295 }
2296
2297 /* Return the bfd owner of SECTION.  */
2298
2299 static struct bfd *
2300 get_section_bfd_owner (const struct dwarf2_section_info *section)
2301 {
2302   if (section->is_virtual)
2303     {
2304       section = get_containing_section (section);
2305       gdb_assert (!section->is_virtual);
2306     }
2307   return section->s.section->owner;
2308 }
2309
2310 /* Return the bfd section of SECTION.
2311    Returns NULL if the section is not present.  */
2312
2313 static asection *
2314 get_section_bfd_section (const struct dwarf2_section_info *section)
2315 {
2316   if (section->is_virtual)
2317     {
2318       section = get_containing_section (section);
2319       gdb_assert (!section->is_virtual);
2320     }
2321   return section->s.section;
2322 }
2323
2324 /* Return the name of SECTION.  */
2325
2326 static const char *
2327 get_section_name (const struct dwarf2_section_info *section)
2328 {
2329   asection *sectp = get_section_bfd_section (section);
2330
2331   gdb_assert (sectp != NULL);
2332   return bfd_section_name (get_section_bfd_owner (section), sectp);
2333 }
2334
2335 /* Return the name of the file SECTION is in.  */
2336
2337 static const char *
2338 get_section_file_name (const struct dwarf2_section_info *section)
2339 {
2340   bfd *abfd = get_section_bfd_owner (section);
2341
2342   return bfd_get_filename (abfd);
2343 }
2344
2345 /* Return the id of SECTION.
2346    Returns 0 if SECTION doesn't exist.  */
2347
2348 static int
2349 get_section_id (const struct dwarf2_section_info *section)
2350 {
2351   asection *sectp = get_section_bfd_section (section);
2352
2353   if (sectp == NULL)
2354     return 0;
2355   return sectp->id;
2356 }
2357
2358 /* Return the flags of SECTION.
2359    SECTION (or containing section if this is a virtual section) must exist.  */
2360
2361 static int
2362 get_section_flags (const struct dwarf2_section_info *section)
2363 {
2364   asection *sectp = get_section_bfd_section (section);
2365
2366   gdb_assert (sectp != NULL);
2367   return bfd_get_section_flags (sectp->owner, sectp);
2368 }
2369
2370 /* When loading sections, we look either for uncompressed section or for
2371    compressed section names.  */
2372
2373 static int
2374 section_is_p (const char *section_name,
2375               const struct dwarf2_section_names *names)
2376 {
2377   if (names->normal != NULL
2378       && strcmp (section_name, names->normal) == 0)
2379     return 1;
2380   if (names->compressed != NULL
2381       && strcmp (section_name, names->compressed) == 0)
2382     return 1;
2383   return 0;
2384 }
2385
2386 /* See declaration.  */
2387
2388 void
2389 dwarf2_per_objfile::locate_sections (bfd *abfd, asection *sectp,
2390                                      const dwarf2_debug_sections &names)
2391 {
2392   flagword aflag = bfd_get_section_flags (abfd, sectp);
2393
2394   if ((aflag & SEC_HAS_CONTENTS) == 0)
2395     {
2396     }
2397   else if (section_is_p (sectp->name, &names.info))
2398     {
2399       this->info.s.section = sectp;
2400       this->info.size = bfd_get_section_size (sectp);
2401     }
2402   else if (section_is_p (sectp->name, &names.abbrev))
2403     {
2404       this->abbrev.s.section = sectp;
2405       this->abbrev.size = bfd_get_section_size (sectp);
2406     }
2407   else if (section_is_p (sectp->name, &names.line))
2408     {
2409       this->line.s.section = sectp;
2410       this->line.size = bfd_get_section_size (sectp);
2411     }
2412   else if (section_is_p (sectp->name, &names.loc))
2413     {
2414       this->loc.s.section = sectp;
2415       this->loc.size = bfd_get_section_size (sectp);
2416     }
2417   else if (section_is_p (sectp->name, &names.loclists))
2418     {
2419       this->loclists.s.section = sectp;
2420       this->loclists.size = bfd_get_section_size (sectp);
2421     }
2422   else if (section_is_p (sectp->name, &names.macinfo))
2423     {
2424       this->macinfo.s.section = sectp;
2425       this->macinfo.size = bfd_get_section_size (sectp);
2426     }
2427   else if (section_is_p (sectp->name, &names.macro))
2428     {
2429       this->macro.s.section = sectp;
2430       this->macro.size = bfd_get_section_size (sectp);
2431     }
2432   else if (section_is_p (sectp->name, &names.str))
2433     {
2434       this->str.s.section = sectp;
2435       this->str.size = bfd_get_section_size (sectp);
2436     }
2437   else if (section_is_p (sectp->name, &names.line_str))
2438     {
2439       this->line_str.s.section = sectp;
2440       this->line_str.size = bfd_get_section_size (sectp);
2441     }
2442   else if (section_is_p (sectp->name, &names.addr))
2443     {
2444       this->addr.s.section = sectp;
2445       this->addr.size = bfd_get_section_size (sectp);
2446     }
2447   else if (section_is_p (sectp->name, &names.frame))
2448     {
2449       this->frame.s.section = sectp;
2450       this->frame.size = bfd_get_section_size (sectp);
2451     }
2452   else if (section_is_p (sectp->name, &names.eh_frame))
2453     {
2454       this->eh_frame.s.section = sectp;
2455       this->eh_frame.size = bfd_get_section_size (sectp);
2456     }
2457   else if (section_is_p (sectp->name, &names.ranges))
2458     {
2459       this->ranges.s.section = sectp;
2460       this->ranges.size = bfd_get_section_size (sectp);
2461     }
2462   else if (section_is_p (sectp->name, &names.rnglists))
2463     {
2464       this->rnglists.s.section = sectp;
2465       this->rnglists.size = bfd_get_section_size (sectp);
2466     }
2467   else if (section_is_p (sectp->name, &names.types))
2468     {
2469       struct dwarf2_section_info type_section;
2470
2471       memset (&type_section, 0, sizeof (type_section));
2472       type_section.s.section = sectp;
2473       type_section.size = bfd_get_section_size (sectp);
2474
2475       VEC_safe_push (dwarf2_section_info_def, this->types,
2476                      &type_section);
2477     }
2478   else if (section_is_p (sectp->name, &names.gdb_index))
2479     {
2480       this->gdb_index.s.section = sectp;
2481       this->gdb_index.size = bfd_get_section_size (sectp);
2482     }
2483
2484   if ((bfd_get_section_flags (abfd, sectp) & (SEC_LOAD | SEC_ALLOC))
2485       && bfd_section_vma (abfd, sectp) == 0)
2486     this->has_section_at_zero = true;
2487 }
2488
2489 /* A helper function that decides whether a section is empty,
2490    or not present.  */
2491
2492 static int
2493 dwarf2_section_empty_p (const struct dwarf2_section_info *section)
2494 {
2495   if (section->is_virtual)
2496     return section->size == 0;
2497   return section->s.section == NULL || section->size == 0;
2498 }
2499
2500 /* Read the contents of the section INFO.
2501    OBJFILE is the main object file, but not necessarily the file where
2502    the section comes from.  E.g., for DWO files the bfd of INFO is the bfd
2503    of the DWO file.
2504    If the section is compressed, uncompress it before returning.  */
2505
2506 static void
2507 dwarf2_read_section (struct objfile *objfile, struct dwarf2_section_info *info)
2508 {
2509   asection *sectp;
2510   bfd *abfd;
2511   gdb_byte *buf, *retbuf;
2512
2513   if (info->readin)
2514     return;
2515   info->buffer = NULL;
2516   info->readin = 1;
2517
2518   if (dwarf2_section_empty_p (info))
2519     return;
2520
2521   sectp = get_section_bfd_section (info);
2522
2523   /* If this is a virtual section we need to read in the real one first.  */
2524   if (info->is_virtual)
2525     {
2526       struct dwarf2_section_info *containing_section =
2527         get_containing_section (info);
2528
2529       gdb_assert (sectp != NULL);
2530       if ((sectp->flags & SEC_RELOC) != 0)
2531         {
2532           error (_("Dwarf Error: DWP format V2 with relocations is not"
2533                    " supported in section %s [in module %s]"),
2534                  get_section_name (info), get_section_file_name (info));
2535         }
2536       dwarf2_read_section (objfile, containing_section);
2537       /* Other code should have already caught virtual sections that don't
2538          fit.  */
2539       gdb_assert (info->virtual_offset + info->size
2540                   <= containing_section->size);
2541       /* If the real section is empty or there was a problem reading the
2542          section we shouldn't get here.  */
2543       gdb_assert (containing_section->buffer != NULL);
2544       info->buffer = containing_section->buffer + info->virtual_offset;
2545       return;
2546     }
2547
2548   /* If the section has relocations, we must read it ourselves.
2549      Otherwise we attach it to the BFD.  */
2550   if ((sectp->flags & SEC_RELOC) == 0)
2551     {
2552       info->buffer = gdb_bfd_map_section (sectp, &info->size);
2553       return;
2554     }
2555
2556   buf = (gdb_byte *) obstack_alloc (&objfile->objfile_obstack, info->size);
2557   info->buffer = buf;
2558
2559   /* When debugging .o files, we may need to apply relocations; see
2560      http://sourceware.org/ml/gdb-patches/2002-04/msg00136.html .
2561      We never compress sections in .o files, so we only need to
2562      try this when the section is not compressed.  */
2563   retbuf = symfile_relocate_debug_section (objfile, sectp, buf);
2564   if (retbuf != NULL)
2565     {
2566       info->buffer = retbuf;
2567       return;
2568     }
2569
2570   abfd = get_section_bfd_owner (info);
2571   gdb_assert (abfd != NULL);
2572
2573   if (bfd_seek (abfd, sectp->filepos, SEEK_SET) != 0
2574       || bfd_bread (buf, info->size, abfd) != info->size)
2575     {
2576       error (_("Dwarf Error: Can't read DWARF data"
2577                " in section %s [in module %s]"),
2578              bfd_section_name (abfd, sectp), bfd_get_filename (abfd));
2579     }
2580 }
2581
2582 /* A helper function that returns the size of a section in a safe way.
2583    If you are positive that the section has been read before using the
2584    size, then it is safe to refer to the dwarf2_section_info object's
2585    "size" field directly.  In other cases, you must call this
2586    function, because for compressed sections the size field is not set
2587    correctly until the section has been read.  */
2588
2589 static bfd_size_type
2590 dwarf2_section_size (struct objfile *objfile,
2591                      struct dwarf2_section_info *info)
2592 {
2593   if (!info->readin)
2594     dwarf2_read_section (objfile, info);
2595   return info->size;
2596 }
2597
2598 /* Fill in SECTP, BUFP and SIZEP with section info, given OBJFILE and
2599    SECTION_NAME.  */
2600
2601 void
2602 dwarf2_get_section_info (struct objfile *objfile,
2603                          enum dwarf2_section_enum sect,
2604                          asection **sectp, const gdb_byte **bufp,
2605                          bfd_size_type *sizep)
2606 {
2607   struct dwarf2_per_objfile *data
2608     = (struct dwarf2_per_objfile *) objfile_data (objfile,
2609                                                   dwarf2_objfile_data_key);
2610   struct dwarf2_section_info *info;
2611
2612   /* We may see an objfile without any DWARF, in which case we just
2613      return nothing.  */
2614   if (data == NULL)
2615     {
2616       *sectp = NULL;
2617       *bufp = NULL;
2618       *sizep = 0;
2619       return;
2620     }
2621   switch (sect)
2622     {
2623     case DWARF2_DEBUG_FRAME:
2624       info = &data->frame;
2625       break;
2626     case DWARF2_EH_FRAME:
2627       info = &data->eh_frame;
2628       break;
2629     default:
2630       gdb_assert_not_reached ("unexpected section");
2631     }
2632
2633   dwarf2_read_section (objfile, info);
2634
2635   *sectp = get_section_bfd_section (info);
2636   *bufp = info->buffer;
2637   *sizep = info->size;
2638 }
2639
2640 /* A helper function to find the sections for a .dwz file.  */
2641
2642 static void
2643 locate_dwz_sections (bfd *abfd, asection *sectp, void *arg)
2644 {
2645   struct dwz_file *dwz_file = (struct dwz_file *) arg;
2646
2647   /* Note that we only support the standard ELF names, because .dwz
2648      is ELF-only (at the time of writing).  */
2649   if (section_is_p (sectp->name, &dwarf2_elf_names.abbrev))
2650     {
2651       dwz_file->abbrev.s.section = sectp;
2652       dwz_file->abbrev.size = bfd_get_section_size (sectp);
2653     }
2654   else if (section_is_p (sectp->name, &dwarf2_elf_names.info))
2655     {
2656       dwz_file->info.s.section = sectp;
2657       dwz_file->info.size = bfd_get_section_size (sectp);
2658     }
2659   else if (section_is_p (sectp->name, &dwarf2_elf_names.str))
2660     {
2661       dwz_file->str.s.section = sectp;
2662       dwz_file->str.size = bfd_get_section_size (sectp);
2663     }
2664   else if (section_is_p (sectp->name, &dwarf2_elf_names.line))
2665     {
2666       dwz_file->line.s.section = sectp;
2667       dwz_file->line.size = bfd_get_section_size (sectp);
2668     }
2669   else if (section_is_p (sectp->name, &dwarf2_elf_names.macro))
2670     {
2671       dwz_file->macro.s.section = sectp;
2672       dwz_file->macro.size = bfd_get_section_size (sectp);
2673     }
2674   else if (section_is_p (sectp->name, &dwarf2_elf_names.gdb_index))
2675     {
2676       dwz_file->gdb_index.s.section = sectp;
2677       dwz_file->gdb_index.size = bfd_get_section_size (sectp);
2678     }
2679 }
2680
2681 /* Open the separate '.dwz' debug file, if needed.  Return NULL if
2682    there is no .gnu_debugaltlink section in the file.  Error if there
2683    is such a section but the file cannot be found.  */
2684
2685 static struct dwz_file *
2686 dwarf2_get_dwz_file (void)
2687 {
2688   char *data;
2689   struct cleanup *cleanup;
2690   const char *filename;
2691   struct dwz_file *result;
2692   bfd_size_type buildid_len_arg;
2693   size_t buildid_len;
2694   bfd_byte *buildid;
2695
2696   if (dwarf2_per_objfile->dwz_file != NULL)
2697     return dwarf2_per_objfile->dwz_file;
2698
2699   bfd_set_error (bfd_error_no_error);
2700   data = bfd_get_alt_debug_link_info (dwarf2_per_objfile->objfile->obfd,
2701                                       &buildid_len_arg, &buildid);
2702   if (data == NULL)
2703     {
2704       if (bfd_get_error () == bfd_error_no_error)
2705         return NULL;
2706       error (_("could not read '.gnu_debugaltlink' section: %s"),
2707              bfd_errmsg (bfd_get_error ()));
2708     }
2709   cleanup = make_cleanup (xfree, data);
2710   make_cleanup (xfree, buildid);
2711
2712   buildid_len = (size_t) buildid_len_arg;
2713
2714   filename = (const char *) data;
2715
2716   std::string abs_storage;
2717   if (!IS_ABSOLUTE_PATH (filename))
2718     {
2719       gdb::unique_xmalloc_ptr<char> abs
2720         = gdb_realpath (objfile_name (dwarf2_per_objfile->objfile));
2721
2722       abs_storage = ldirname (abs.get ()) + SLASH_STRING + filename;
2723       filename = abs_storage.c_str ();
2724     }
2725
2726   /* First try the file name given in the section.  If that doesn't
2727      work, try to use the build-id instead.  */
2728   gdb_bfd_ref_ptr dwz_bfd (gdb_bfd_open (filename, gnutarget, -1));
2729   if (dwz_bfd != NULL)
2730     {
2731       if (!build_id_verify (dwz_bfd.get (), buildid_len, buildid))
2732         dwz_bfd.release ();
2733     }
2734
2735   if (dwz_bfd == NULL)
2736     dwz_bfd = build_id_to_debug_bfd (buildid_len, buildid);
2737
2738   if (dwz_bfd == NULL)
2739     error (_("could not find '.gnu_debugaltlink' file for %s"),
2740            objfile_name (dwarf2_per_objfile->objfile));
2741
2742   result = OBSTACK_ZALLOC (&dwarf2_per_objfile->objfile->objfile_obstack,
2743                            struct dwz_file);
2744   result->dwz_bfd = dwz_bfd.release ();
2745
2746   bfd_map_over_sections (result->dwz_bfd, locate_dwz_sections, result);
2747
2748   do_cleanups (cleanup);
2749
2750   gdb_bfd_record_inclusion (dwarf2_per_objfile->objfile->obfd, result->dwz_bfd);
2751   dwarf2_per_objfile->dwz_file = result;
2752   return result;
2753 }
2754 \f
2755 /* DWARF quick_symbols_functions support.  */
2756
2757 /* TUs can share .debug_line entries, and there can be a lot more TUs than
2758    unique line tables, so we maintain a separate table of all .debug_line
2759    derived entries to support the sharing.
2760    All the quick functions need is the list of file names.  We discard the
2761    line_header when we're done and don't need to record it here.  */
2762 struct quick_file_names
2763 {
2764   /* The data used to construct the hash key.  */
2765   struct stmt_list_hash hash;
2766
2767   /* The number of entries in file_names, real_names.  */
2768   unsigned int num_file_names;
2769
2770   /* The file names from the line table, after being run through
2771      file_full_name.  */
2772   const char **file_names;
2773
2774   /* The file names from the line table after being run through
2775      gdb_realpath.  These are computed lazily.  */
2776   const char **real_names;
2777 };
2778
2779 /* When using the index (and thus not using psymtabs), each CU has an
2780    object of this type.  This is used to hold information needed by
2781    the various "quick" methods.  */
2782 struct dwarf2_per_cu_quick_data
2783 {
2784   /* The file table.  This can be NULL if there was no file table
2785      or it's currently not read in.
2786      NOTE: This points into dwarf2_per_objfile->quick_file_names_table.  */
2787   struct quick_file_names *file_names;
2788
2789   /* The corresponding symbol table.  This is NULL if symbols for this
2790      CU have not yet been read.  */
2791   struct compunit_symtab *compunit_symtab;
2792
2793   /* A temporary mark bit used when iterating over all CUs in
2794      expand_symtabs_matching.  */
2795   unsigned int mark : 1;
2796
2797   /* True if we've tried to read the file table and found there isn't one.
2798      There will be no point in trying to read it again next time.  */
2799   unsigned int no_file_data : 1;
2800 };
2801
2802 /* Utility hash function for a stmt_list_hash.  */
2803
2804 static hashval_t
2805 hash_stmt_list_entry (const struct stmt_list_hash *stmt_list_hash)
2806 {
2807   hashval_t v = 0;
2808
2809   if (stmt_list_hash->dwo_unit != NULL)
2810     v += (uintptr_t) stmt_list_hash->dwo_unit->dwo_file;
2811   v += to_underlying (stmt_list_hash->line_sect_off);
2812   return v;
2813 }
2814
2815 /* Utility equality function for a stmt_list_hash.  */
2816
2817 static int
2818 eq_stmt_list_entry (const struct stmt_list_hash *lhs,
2819                     const struct stmt_list_hash *rhs)
2820 {
2821   if ((lhs->dwo_unit != NULL) != (rhs->dwo_unit != NULL))
2822     return 0;
2823   if (lhs->dwo_unit != NULL
2824       && lhs->dwo_unit->dwo_file != rhs->dwo_unit->dwo_file)
2825     return 0;
2826
2827   return lhs->line_sect_off == rhs->line_sect_off;
2828 }
2829
2830 /* Hash function for a quick_file_names.  */
2831
2832 static hashval_t
2833 hash_file_name_entry (const void *e)
2834 {
2835   const struct quick_file_names *file_data
2836     = (const struct quick_file_names *) e;
2837
2838   return hash_stmt_list_entry (&file_data->hash);
2839 }
2840
2841 /* Equality function for a quick_file_names.  */
2842
2843 static int
2844 eq_file_name_entry (const void *a, const void *b)
2845 {
2846   const struct quick_file_names *ea = (const struct quick_file_names *) a;
2847   const struct quick_file_names *eb = (const struct quick_file_names *) b;
2848
2849   return eq_stmt_list_entry (&ea->hash, &eb->hash);
2850 }
2851
2852 /* Delete function for a quick_file_names.  */
2853
2854 static void
2855 delete_file_name_entry (void *e)
2856 {
2857   struct quick_file_names *file_data = (struct quick_file_names *) e;
2858   int i;
2859
2860   for (i = 0; i < file_data->num_file_names; ++i)
2861     {
2862       xfree ((void*) file_data->file_names[i]);
2863       if (file_data->real_names)
2864         xfree ((void*) file_data->real_names[i]);
2865     }
2866
2867   /* The space for the struct itself lives on objfile_obstack,
2868      so we don't free it here.  */
2869 }
2870
2871 /* Create a quick_file_names hash table.  */
2872
2873 static htab_t
2874 create_quick_file_names_table (unsigned int nr_initial_entries)
2875 {
2876   return htab_create_alloc (nr_initial_entries,
2877                             hash_file_name_entry, eq_file_name_entry,
2878                             delete_file_name_entry, xcalloc, xfree);
2879 }
2880
2881 /* Read in PER_CU->CU.  This function is unrelated to symtabs, symtab would
2882    have to be created afterwards.  You should call age_cached_comp_units after
2883    processing PER_CU->CU.  dw2_setup must have been already called.  */
2884
2885 static void
2886 load_cu (struct dwarf2_per_cu_data *per_cu)
2887 {
2888   if (per_cu->is_debug_types)
2889     load_full_type_unit (per_cu);
2890   else
2891     load_full_comp_unit (per_cu, language_minimal);
2892
2893   if (per_cu->cu == NULL)
2894     return;  /* Dummy CU.  */
2895
2896   dwarf2_find_base_address (per_cu->cu->dies, per_cu->cu);
2897 }
2898
2899 /* Read in the symbols for PER_CU.  */
2900
2901 static void
2902 dw2_do_instantiate_symtab (struct dwarf2_per_cu_data *per_cu)
2903 {
2904   struct cleanup *back_to;
2905
2906   /* Skip type_unit_groups, reading the type units they contain
2907      is handled elsewhere.  */
2908   if (IS_TYPE_UNIT_GROUP (per_cu))
2909     return;
2910
2911   back_to = make_cleanup (dwarf2_release_queue, NULL);
2912
2913   if (dwarf2_per_objfile->using_index
2914       ? per_cu->v.quick->compunit_symtab == NULL
2915       : (per_cu->v.psymtab == NULL || !per_cu->v.psymtab->readin))
2916     {
2917       queue_comp_unit (per_cu, language_minimal);
2918       load_cu (per_cu);
2919
2920       /* If we just loaded a CU from a DWO, and we're working with an index
2921          that may badly handle TUs, load all the TUs in that DWO as well.
2922          http://sourceware.org/bugzilla/show_bug.cgi?id=15021  */
2923       if (!per_cu->is_debug_types
2924           && per_cu->cu != NULL
2925           && per_cu->cu->dwo_unit != NULL
2926           && dwarf2_per_objfile->index_table != NULL
2927           && dwarf2_per_objfile->index_table->version <= 7
2928           /* DWP files aren't supported yet.  */
2929           && get_dwp_file () == NULL)
2930         queue_and_load_all_dwo_tus (per_cu);
2931     }
2932
2933   process_queue ();
2934
2935   /* Age the cache, releasing compilation units that have not
2936      been used recently.  */
2937   age_cached_comp_units ();
2938
2939   do_cleanups (back_to);
2940 }
2941
2942 /* Ensure that the symbols for PER_CU have been read in.  OBJFILE is
2943    the objfile from which this CU came.  Returns the resulting symbol
2944    table.  */
2945
2946 static struct compunit_symtab *
2947 dw2_instantiate_symtab (struct dwarf2_per_cu_data *per_cu)
2948 {
2949   gdb_assert (dwarf2_per_objfile->using_index);
2950   if (!per_cu->v.quick->compunit_symtab)
2951     {
2952       struct cleanup *back_to = make_cleanup (free_cached_comp_units, NULL);
2953       scoped_restore decrementer = increment_reading_symtab ();
2954       dw2_do_instantiate_symtab (per_cu);
2955       process_cu_includes ();
2956       do_cleanups (back_to);
2957     }
2958
2959   return per_cu->v.quick->compunit_symtab;
2960 }
2961
2962 /* Return the CU/TU given its index.
2963
2964    This is intended for loops like:
2965
2966    for (i = 0; i < (dwarf2_per_objfile->n_comp_units
2967                     + dwarf2_per_objfile->n_type_units); ++i)
2968      {
2969        struct dwarf2_per_cu_data *per_cu = dw2_get_cutu (i);
2970
2971        ...;
2972      }
2973 */
2974
2975 static struct dwarf2_per_cu_data *
2976 dw2_get_cutu (int index)
2977 {
2978   if (index >= dwarf2_per_objfile->n_comp_units)
2979     {
2980       index -= dwarf2_per_objfile->n_comp_units;
2981       gdb_assert (index < dwarf2_per_objfile->n_type_units);
2982       return &dwarf2_per_objfile->all_type_units[index]->per_cu;
2983     }
2984
2985   return dwarf2_per_objfile->all_comp_units[index];
2986 }
2987
2988 /* Return the CU given its index.
2989    This differs from dw2_get_cutu in that it's for when you know INDEX
2990    refers to a CU.  */
2991
2992 static struct dwarf2_per_cu_data *
2993 dw2_get_cu (int index)
2994 {
2995   gdb_assert (index >= 0 && index < dwarf2_per_objfile->n_comp_units);
2996
2997   return dwarf2_per_objfile->all_comp_units[index];
2998 }
2999
3000 /* A helper for create_cus_from_index that handles a given list of
3001    CUs.  */
3002
3003 static void
3004 create_cus_from_index_list (struct objfile *objfile,
3005                             const gdb_byte *cu_list, offset_type n_elements,
3006                             struct dwarf2_section_info *section,
3007                             int is_dwz,
3008                             int base_offset)
3009 {
3010   offset_type i;
3011
3012   for (i = 0; i < n_elements; i += 2)
3013     {
3014       gdb_static_assert (sizeof (ULONGEST) >= 8);
3015
3016       sect_offset sect_off
3017         = (sect_offset) extract_unsigned_integer (cu_list, 8, BFD_ENDIAN_LITTLE);
3018       ULONGEST length = extract_unsigned_integer (cu_list + 8, 8, BFD_ENDIAN_LITTLE);
3019       cu_list += 2 * 8;
3020
3021       dwarf2_per_cu_data *the_cu
3022         = OBSTACK_ZALLOC (&objfile->objfile_obstack,
3023                           struct dwarf2_per_cu_data);
3024       the_cu->sect_off = sect_off;
3025       the_cu->length = length;
3026       the_cu->objfile = objfile;
3027       the_cu->section = section;
3028       the_cu->v.quick = OBSTACK_ZALLOC (&objfile->objfile_obstack,
3029                                         struct dwarf2_per_cu_quick_data);
3030       the_cu->is_dwz = is_dwz;
3031       dwarf2_per_objfile->all_comp_units[base_offset + i / 2] = the_cu;
3032     }
3033 }
3034
3035 /* Read the CU list from the mapped index, and use it to create all
3036    the CU objects for this objfile.  */
3037
3038 static void
3039 create_cus_from_index (struct objfile *objfile,
3040                        const gdb_byte *cu_list, offset_type cu_list_elements,
3041                        const gdb_byte *dwz_list, offset_type dwz_elements)
3042 {
3043   struct dwz_file *dwz;
3044
3045   dwarf2_per_objfile->n_comp_units = (cu_list_elements + dwz_elements) / 2;
3046   dwarf2_per_objfile->all_comp_units =
3047     XOBNEWVEC (&objfile->objfile_obstack, struct dwarf2_per_cu_data *,
3048                dwarf2_per_objfile->n_comp_units);
3049
3050   create_cus_from_index_list (objfile, cu_list, cu_list_elements,
3051                               &dwarf2_per_objfile->info, 0, 0);
3052
3053   if (dwz_elements == 0)
3054     return;
3055
3056   dwz = dwarf2_get_dwz_file ();
3057   create_cus_from_index_list (objfile, dwz_list, dwz_elements, &dwz->info, 1,
3058                               cu_list_elements / 2);
3059 }
3060
3061 /* Create the signatured type hash table from the index.  */
3062
3063 static void
3064 create_signatured_type_table_from_index (struct objfile *objfile,
3065                                          struct dwarf2_section_info *section,
3066                                          const gdb_byte *bytes,
3067                                          offset_type elements)
3068 {
3069   offset_type i;
3070   htab_t sig_types_hash;
3071
3072   dwarf2_per_objfile->n_type_units
3073     = dwarf2_per_objfile->n_allocated_type_units
3074     = elements / 3;
3075   dwarf2_per_objfile->all_type_units =
3076     XNEWVEC (struct signatured_type *, dwarf2_per_objfile->n_type_units);
3077
3078   sig_types_hash = allocate_signatured_type_table (objfile);
3079
3080   for (i = 0; i < elements; i += 3)
3081     {
3082       struct signatured_type *sig_type;
3083       ULONGEST signature;
3084       void **slot;
3085       cu_offset type_offset_in_tu;
3086
3087       gdb_static_assert (sizeof (ULONGEST) >= 8);
3088       sect_offset sect_off
3089         = (sect_offset) extract_unsigned_integer (bytes, 8, BFD_ENDIAN_LITTLE);
3090       type_offset_in_tu
3091         = (cu_offset) extract_unsigned_integer (bytes + 8, 8,
3092                                                 BFD_ENDIAN_LITTLE);
3093       signature = extract_unsigned_integer (bytes + 16, 8, BFD_ENDIAN_LITTLE);
3094       bytes += 3 * 8;
3095
3096       sig_type = OBSTACK_ZALLOC (&objfile->objfile_obstack,
3097                                  struct signatured_type);
3098       sig_type->signature = signature;
3099       sig_type->type_offset_in_tu = type_offset_in_tu;
3100       sig_type->per_cu.is_debug_types = 1;
3101       sig_type->per_cu.section = section;
3102       sig_type->per_cu.sect_off = sect_off;
3103       sig_type->per_cu.objfile = objfile;
3104       sig_type->per_cu.v.quick
3105         = OBSTACK_ZALLOC (&objfile->objfile_obstack,
3106                           struct dwarf2_per_cu_quick_data);
3107
3108       slot = htab_find_slot (sig_types_hash, sig_type, INSERT);
3109       *slot = sig_type;
3110
3111       dwarf2_per_objfile->all_type_units[i / 3] = sig_type;
3112     }
3113
3114   dwarf2_per_objfile->signatured_types = sig_types_hash;
3115 }
3116
3117 /* Read the address map data from the mapped index, and use it to
3118    populate the objfile's psymtabs_addrmap.  */
3119
3120 static void
3121 create_addrmap_from_index (struct objfile *objfile, struct mapped_index *index)
3122 {
3123   struct gdbarch *gdbarch = get_objfile_arch (objfile);
3124   const gdb_byte *iter, *end;
3125   struct addrmap *mutable_map;
3126   CORE_ADDR baseaddr;
3127
3128   auto_obstack temp_obstack;
3129
3130   mutable_map = addrmap_create_mutable (&temp_obstack);
3131
3132   iter = index->address_table;
3133   end = iter + index->address_table_size;
3134
3135   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
3136
3137   while (iter < end)
3138     {
3139       ULONGEST hi, lo, cu_index;
3140       lo = extract_unsigned_integer (iter, 8, BFD_ENDIAN_LITTLE);
3141       iter += 8;
3142       hi = extract_unsigned_integer (iter, 8, BFD_ENDIAN_LITTLE);
3143       iter += 8;
3144       cu_index = extract_unsigned_integer (iter, 4, BFD_ENDIAN_LITTLE);
3145       iter += 4;
3146
3147       if (lo > hi)
3148         {
3149           complaint (&symfile_complaints,
3150                      _(".gdb_index address table has invalid range (%s - %s)"),
3151                      hex_string (lo), hex_string (hi));
3152           continue;
3153         }
3154
3155       if (cu_index >= dwarf2_per_objfile->n_comp_units)
3156         {
3157           complaint (&symfile_complaints,
3158                      _(".gdb_index address table has invalid CU number %u"),
3159                      (unsigned) cu_index);
3160           continue;
3161         }
3162
3163       lo = gdbarch_adjust_dwarf2_addr (gdbarch, lo + baseaddr);
3164       hi = gdbarch_adjust_dwarf2_addr (gdbarch, hi + baseaddr);
3165       addrmap_set_empty (mutable_map, lo, hi - 1, dw2_get_cutu (cu_index));
3166     }
3167
3168   objfile->psymtabs_addrmap = addrmap_create_fixed (mutable_map,
3169                                                     &objfile->objfile_obstack);
3170 }
3171
3172 /* The hash function for strings in the mapped index.  This is the same as
3173    SYMBOL_HASH_NEXT, but we keep a separate copy to maintain control over the
3174    implementation.  This is necessary because the hash function is tied to the
3175    format of the mapped index file.  The hash values do not have to match with
3176    SYMBOL_HASH_NEXT.
3177    
3178    Use INT_MAX for INDEX_VERSION if you generate the current index format.  */
3179
3180 static hashval_t
3181 mapped_index_string_hash (int index_version, const void *p)
3182 {
3183   const unsigned char *str = (const unsigned char *) p;
3184   hashval_t r = 0;
3185   unsigned char c;
3186
3187   while ((c = *str++) != 0)
3188     {
3189       if (index_version >= 5)
3190         c = tolower (c);
3191       r = r * 67 + c - 113;
3192     }
3193
3194   return r;
3195 }
3196
3197 /* Find a slot in the mapped index INDEX for the object named NAME.
3198    If NAME is found, set *VEC_OUT to point to the CU vector in the
3199    constant pool and return 1.  If NAME cannot be found, return 0.  */
3200
3201 static int
3202 find_slot_in_mapped_hash (struct mapped_index *index, const char *name,
3203                           offset_type **vec_out)
3204 {
3205   struct cleanup *back_to = make_cleanup (null_cleanup, 0);
3206   offset_type hash;
3207   offset_type slot, step;
3208   int (*cmp) (const char *, const char *);
3209
3210   if (current_language->la_language == language_cplus
3211       || current_language->la_language == language_fortran
3212       || current_language->la_language == language_d)
3213     {
3214       /* NAME is already canonical.  Drop any qualifiers as .gdb_index does
3215          not contain any.  */
3216
3217       if (strchr (name, '(') != NULL)
3218         {
3219           char *without_params = cp_remove_params (name);
3220
3221           if (without_params != NULL)
3222             {
3223               make_cleanup (xfree, without_params);
3224               name = without_params;
3225             }
3226         }
3227     }
3228
3229   /* Index version 4 did not support case insensitive searches.  But the
3230      indices for case insensitive languages are built in lowercase, therefore
3231      simulate our NAME being searched is also lowercased.  */
3232   hash = mapped_index_string_hash ((index->version == 4
3233                                     && case_sensitivity == case_sensitive_off
3234                                     ? 5 : index->version),
3235                                    name);
3236
3237   slot = hash & (index->symbol_table_slots - 1);
3238   step = ((hash * 17) & (index->symbol_table_slots - 1)) | 1;
3239   cmp = (case_sensitivity == case_sensitive_on ? strcmp : strcasecmp);
3240
3241   for (;;)
3242     {
3243       /* Convert a slot number to an offset into the table.  */
3244       offset_type i = 2 * slot;
3245       const char *str;
3246       if (index->symbol_table[i] == 0 && index->symbol_table[i + 1] == 0)
3247         {
3248           do_cleanups (back_to);
3249           return 0;
3250         }
3251
3252       str = index->constant_pool + MAYBE_SWAP (index->symbol_table[i]);
3253       if (!cmp (name, str))
3254         {
3255           *vec_out = (offset_type *) (index->constant_pool
3256                                       + MAYBE_SWAP (index->symbol_table[i + 1]));
3257           do_cleanups (back_to);
3258           return 1;
3259         }
3260
3261       slot = (slot + step) & (index->symbol_table_slots - 1);
3262     }
3263 }
3264
3265 /* A helper function that reads the .gdb_index from SECTION and fills
3266    in MAP.  FILENAME is the name of the file containing the section;
3267    it is used for error reporting.  DEPRECATED_OK is nonzero if it is
3268    ok to use deprecated sections.
3269
3270    CU_LIST, CU_LIST_ELEMENTS, TYPES_LIST, and TYPES_LIST_ELEMENTS are
3271    out parameters that are filled in with information about the CU and
3272    TU lists in the section.
3273
3274    Returns 1 if all went well, 0 otherwise.  */
3275
3276 static int
3277 read_index_from_section (struct objfile *objfile,
3278                          const char *filename,
3279                          int deprecated_ok,
3280                          struct dwarf2_section_info *section,
3281                          struct mapped_index *map,
3282                          const gdb_byte **cu_list,
3283                          offset_type *cu_list_elements,
3284                          const gdb_byte **types_list,
3285                          offset_type *types_list_elements)
3286 {
3287   const gdb_byte *addr;
3288   offset_type version;
3289   offset_type *metadata;
3290   int i;
3291
3292   if (dwarf2_section_empty_p (section))
3293     return 0;
3294
3295   /* Older elfutils strip versions could keep the section in the main
3296      executable while splitting it for the separate debug info file.  */
3297   if ((get_section_flags (section) & SEC_HAS_CONTENTS) == 0)
3298     return 0;
3299
3300   dwarf2_read_section (objfile, section);
3301
3302   addr = section->buffer;
3303   /* Version check.  */
3304   version = MAYBE_SWAP (*(offset_type *) addr);
3305   /* Versions earlier than 3 emitted every copy of a psymbol.  This
3306      causes the index to behave very poorly for certain requests.  Version 3
3307      contained incomplete addrmap.  So, it seems better to just ignore such
3308      indices.  */
3309   if (version < 4)
3310     {
3311       static int warning_printed = 0;
3312       if (!warning_printed)
3313         {
3314           warning (_("Skipping obsolete .gdb_index section in %s."),
3315                    filename);
3316           warning_printed = 1;
3317         }
3318       return 0;
3319     }
3320   /* Index version 4 uses a different hash function than index version
3321      5 and later.
3322
3323      Versions earlier than 6 did not emit psymbols for inlined
3324      functions.  Using these files will cause GDB not to be able to
3325      set breakpoints on inlined functions by name, so we ignore these
3326      indices unless the user has done
3327      "set use-deprecated-index-sections on".  */
3328   if (version < 6 && !deprecated_ok)
3329     {
3330       static int warning_printed = 0;
3331       if (!warning_printed)
3332         {
3333           warning (_("\
3334 Skipping deprecated .gdb_index section in %s.\n\
3335 Do \"set use-deprecated-index-sections on\" before the file is read\n\
3336 to use the section anyway."),
3337                    filename);
3338           warning_printed = 1;
3339         }
3340       return 0;
3341     }
3342   /* Version 7 indices generated by gold refer to the CU for a symbol instead
3343      of the TU (for symbols coming from TUs),
3344      http://sourceware.org/bugzilla/show_bug.cgi?id=15021.
3345      Plus gold-generated indices can have duplicate entries for global symbols,
3346      http://sourceware.org/bugzilla/show_bug.cgi?id=15646.
3347      These are just performance bugs, and we can't distinguish gdb-generated
3348      indices from gold-generated ones, so issue no warning here.  */
3349
3350   /* Indexes with higher version than the one supported by GDB may be no
3351      longer backward compatible.  */
3352   if (version > 8)
3353     return 0;
3354
3355   map->version = version;
3356   map->total_size = section->size;
3357
3358   metadata = (offset_type *) (addr + sizeof (offset_type));
3359
3360   i = 0;
3361   *cu_list = addr + MAYBE_SWAP (metadata[i]);
3362   *cu_list_elements = ((MAYBE_SWAP (metadata[i + 1]) - MAYBE_SWAP (metadata[i]))
3363                        / 8);
3364   ++i;
3365
3366   *types_list = addr + MAYBE_SWAP (metadata[i]);
3367   *types_list_elements = ((MAYBE_SWAP (metadata[i + 1])
3368                            - MAYBE_SWAP (metadata[i]))
3369                           / 8);
3370   ++i;
3371
3372   map->address_table = addr + MAYBE_SWAP (metadata[i]);
3373   map->address_table_size = (MAYBE_SWAP (metadata[i + 1])
3374                              - MAYBE_SWAP (metadata[i]));
3375   ++i;
3376
3377   map->symbol_table = (offset_type *) (addr + MAYBE_SWAP (metadata[i]));
3378   map->symbol_table_slots = ((MAYBE_SWAP (metadata[i + 1])
3379                               - MAYBE_SWAP (metadata[i]))
3380                              / (2 * sizeof (offset_type)));
3381   ++i;
3382
3383   map->constant_pool = (char *) (addr + MAYBE_SWAP (metadata[i]));
3384
3385   return 1;
3386 }
3387
3388
3389 /* Read the index file.  If everything went ok, initialize the "quick"
3390    elements of all the CUs and return 1.  Otherwise, return 0.  */
3391
3392 static int
3393 dwarf2_read_index (struct objfile *objfile)
3394 {
3395   struct mapped_index local_map, *map;
3396   const gdb_byte *cu_list, *types_list, *dwz_list = NULL;
3397   offset_type cu_list_elements, types_list_elements, dwz_list_elements = 0;
3398   struct dwz_file *dwz;
3399
3400   if (!read_index_from_section (objfile, objfile_name (objfile),
3401                                 use_deprecated_index_sections,
3402                                 &dwarf2_per_objfile->gdb_index, &local_map,
3403                                 &cu_list, &cu_list_elements,
3404                                 &types_list, &types_list_elements))
3405     return 0;
3406
3407   /* Don't use the index if it's empty.  */
3408   if (local_map.symbol_table_slots == 0)
3409     return 0;
3410
3411   /* If there is a .dwz file, read it so we can get its CU list as
3412      well.  */
3413   dwz = dwarf2_get_dwz_file ();
3414   if (dwz != NULL)
3415     {
3416       struct mapped_index dwz_map;
3417       const gdb_byte *dwz_types_ignore;
3418       offset_type dwz_types_elements_ignore;
3419
3420       if (!read_index_from_section (objfile, bfd_get_filename (dwz->dwz_bfd),
3421                                     1,
3422                                     &dwz->gdb_index, &dwz_map,
3423                                     &dwz_list, &dwz_list_elements,
3424                                     &dwz_types_ignore,
3425                                     &dwz_types_elements_ignore))
3426         {
3427           warning (_("could not read '.gdb_index' section from %s; skipping"),
3428                    bfd_get_filename (dwz->dwz_bfd));
3429           return 0;
3430         }
3431     }
3432
3433   create_cus_from_index (objfile, cu_list, cu_list_elements, dwz_list,
3434                          dwz_list_elements);
3435
3436   if (types_list_elements)
3437     {
3438       struct dwarf2_section_info *section;
3439
3440       /* We can only handle a single .debug_types when we have an
3441          index.  */
3442       if (VEC_length (dwarf2_section_info_def, dwarf2_per_objfile->types) != 1)
3443         return 0;
3444
3445       section = VEC_index (dwarf2_section_info_def,
3446                            dwarf2_per_objfile->types, 0);
3447
3448       create_signatured_type_table_from_index (objfile, section, types_list,
3449                                                types_list_elements);
3450     }
3451
3452   create_addrmap_from_index (objfile, &local_map);
3453
3454   map = XOBNEW (&objfile->objfile_obstack, struct mapped_index);
3455   *map = local_map;
3456
3457   dwarf2_per_objfile->index_table = map;
3458   dwarf2_per_objfile->using_index = 1;
3459   dwarf2_per_objfile->quick_file_names_table =
3460     create_quick_file_names_table (dwarf2_per_objfile->n_comp_units);
3461
3462   return 1;
3463 }
3464
3465 /* A helper for the "quick" functions which sets the global
3466    dwarf2_per_objfile according to OBJFILE.  */
3467
3468 static void
3469 dw2_setup (struct objfile *objfile)
3470 {
3471   dwarf2_per_objfile = ((struct dwarf2_per_objfile *)
3472                         objfile_data (objfile, dwarf2_objfile_data_key));
3473   gdb_assert (dwarf2_per_objfile);
3474 }
3475
3476 /* die_reader_func for dw2_get_file_names.  */
3477
3478 static void
3479 dw2_get_file_names_reader (const struct die_reader_specs *reader,
3480                            const gdb_byte *info_ptr,
3481                            struct die_info *comp_unit_die,
3482                            int has_children,
3483                            void *data)
3484 {
3485   struct dwarf2_cu *cu = reader->cu;
3486   struct dwarf2_per_cu_data *this_cu = cu->per_cu;  
3487   struct objfile *objfile = dwarf2_per_objfile->objfile;
3488   struct dwarf2_per_cu_data *lh_cu;
3489   struct attribute *attr;
3490   int i;
3491   void **slot;
3492   struct quick_file_names *qfn;
3493
3494   gdb_assert (! this_cu->is_debug_types);
3495
3496   /* Our callers never want to match partial units -- instead they
3497      will match the enclosing full CU.  */
3498   if (comp_unit_die->tag == DW_TAG_partial_unit)
3499     {
3500       this_cu->v.quick->no_file_data = 1;
3501       return;
3502     }
3503
3504   lh_cu = this_cu;
3505   slot = NULL;
3506
3507   line_header_up lh;
3508   sect_offset line_offset {};
3509
3510   attr = dwarf2_attr (comp_unit_die, DW_AT_stmt_list, cu);
3511   if (attr)
3512     {
3513       struct quick_file_names find_entry;
3514
3515       line_offset = (sect_offset) DW_UNSND (attr);
3516
3517       /* We may have already read in this line header (TU line header sharing).
3518          If we have we're done.  */
3519       find_entry.hash.dwo_unit = cu->dwo_unit;
3520       find_entry.hash.line_sect_off = line_offset;
3521       slot = htab_find_slot (dwarf2_per_objfile->quick_file_names_table,
3522                              &find_entry, INSERT);
3523       if (*slot != NULL)
3524         {
3525           lh_cu->v.quick->file_names = (struct quick_file_names *) *slot;
3526           return;
3527         }
3528
3529       lh = dwarf_decode_line_header (line_offset, cu);
3530     }
3531   if (lh == NULL)
3532     {
3533       lh_cu->v.quick->no_file_data = 1;
3534       return;
3535     }
3536
3537   qfn = XOBNEW (&objfile->objfile_obstack, struct quick_file_names);
3538   qfn->hash.dwo_unit = cu->dwo_unit;
3539   qfn->hash.line_sect_off = line_offset;
3540   gdb_assert (slot != NULL);
3541   *slot = qfn;
3542
3543   file_and_directory fnd = find_file_and_directory (comp_unit_die, cu);
3544
3545   qfn->num_file_names = lh->file_names.size ();
3546   qfn->file_names =
3547     XOBNEWVEC (&objfile->objfile_obstack, const char *, lh->file_names.size ());
3548   for (i = 0; i < lh->file_names.size (); ++i)
3549     qfn->file_names[i] = file_full_name (i + 1, lh.get (), fnd.comp_dir);
3550   qfn->real_names = NULL;
3551
3552   lh_cu->v.quick->file_names = qfn;
3553 }
3554
3555 /* A helper for the "quick" functions which attempts to read the line
3556    table for THIS_CU.  */
3557
3558 static struct quick_file_names *
3559 dw2_get_file_names (struct dwarf2_per_cu_data *this_cu)
3560 {
3561   /* This should never be called for TUs.  */
3562   gdb_assert (! this_cu->is_debug_types);
3563   /* Nor type unit groups.  */
3564   gdb_assert (! IS_TYPE_UNIT_GROUP (this_cu));
3565
3566   if (this_cu->v.quick->file_names != NULL)
3567     return this_cu->v.quick->file_names;
3568   /* If we know there is no line data, no point in looking again.  */
3569   if (this_cu->v.quick->no_file_data)
3570     return NULL;
3571
3572   init_cutu_and_read_dies_simple (this_cu, dw2_get_file_names_reader, NULL);
3573
3574   if (this_cu->v.quick->no_file_data)
3575     return NULL;
3576   return this_cu->v.quick->file_names;
3577 }
3578
3579 /* A helper for the "quick" functions which computes and caches the
3580    real path for a given file name from the line table.  */
3581
3582 static const char *
3583 dw2_get_real_path (struct objfile *objfile,
3584                    struct quick_file_names *qfn, int index)
3585 {
3586   if (qfn->real_names == NULL)
3587     qfn->real_names = OBSTACK_CALLOC (&objfile->objfile_obstack,
3588                                       qfn->num_file_names, const char *);
3589
3590   if (qfn->real_names[index] == NULL)
3591     qfn->real_names[index] = gdb_realpath (qfn->file_names[index]).release ();
3592
3593   return qfn->real_names[index];
3594 }
3595
3596 static struct symtab *
3597 dw2_find_last_source_symtab (struct objfile *objfile)
3598 {
3599   struct compunit_symtab *cust;
3600   int index;
3601
3602   dw2_setup (objfile);
3603   index = dwarf2_per_objfile->n_comp_units - 1;
3604   cust = dw2_instantiate_symtab (dw2_get_cutu (index));
3605   if (cust == NULL)
3606     return NULL;
3607   return compunit_primary_filetab (cust);
3608 }
3609
3610 /* Traversal function for dw2_forget_cached_source_info.  */
3611
3612 static int
3613 dw2_free_cached_file_names (void **slot, void *info)
3614 {
3615   struct quick_file_names *file_data = (struct quick_file_names *) *slot;
3616
3617   if (file_data->real_names)
3618     {
3619       int i;
3620
3621       for (i = 0; i < file_data->num_file_names; ++i)
3622         {
3623           xfree ((void*) file_data->real_names[i]);
3624           file_data->real_names[i] = NULL;
3625         }
3626     }
3627
3628   return 1;
3629 }
3630
3631 static void
3632 dw2_forget_cached_source_info (struct objfile *objfile)
3633 {
3634   dw2_setup (objfile);
3635
3636   htab_traverse_noresize (dwarf2_per_objfile->quick_file_names_table,
3637                           dw2_free_cached_file_names, NULL);
3638 }
3639
3640 /* Helper function for dw2_map_symtabs_matching_filename that expands
3641    the symtabs and calls the iterator.  */
3642
3643 static int
3644 dw2_map_expand_apply (struct objfile *objfile,
3645                       struct dwarf2_per_cu_data *per_cu,
3646                       const char *name, const char *real_path,
3647                       gdb::function_view<bool (symtab *)> callback)
3648 {
3649   struct compunit_symtab *last_made = objfile->compunit_symtabs;
3650
3651   /* Don't visit already-expanded CUs.  */
3652   if (per_cu->v.quick->compunit_symtab)
3653     return 0;
3654
3655   /* This may expand more than one symtab, and we want to iterate over
3656      all of them.  */
3657   dw2_instantiate_symtab (per_cu);
3658
3659   return iterate_over_some_symtabs (name, real_path, objfile->compunit_symtabs,
3660                                     last_made, callback);
3661 }
3662
3663 /* Implementation of the map_symtabs_matching_filename method.  */
3664
3665 static bool
3666 dw2_map_symtabs_matching_filename
3667   (struct objfile *objfile, const char *name, const char *real_path,
3668    gdb::function_view<bool (symtab *)> callback)
3669 {
3670   int i;
3671   const char *name_basename = lbasename (name);
3672
3673   dw2_setup (objfile);
3674
3675   /* The rule is CUs specify all the files, including those used by
3676      any TU, so there's no need to scan TUs here.  */
3677
3678   for (i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
3679     {
3680       int j;
3681       struct dwarf2_per_cu_data *per_cu = dw2_get_cu (i);
3682       struct quick_file_names *file_data;
3683
3684       /* We only need to look at symtabs not already expanded.  */
3685       if (per_cu->v.quick->compunit_symtab)
3686         continue;
3687
3688       file_data = dw2_get_file_names (per_cu);
3689       if (file_data == NULL)
3690         continue;
3691
3692       for (j = 0; j < file_data->num_file_names; ++j)
3693         {
3694           const char *this_name = file_data->file_names[j];
3695           const char *this_real_name;
3696
3697           if (compare_filenames_for_search (this_name, name))
3698             {
3699               if (dw2_map_expand_apply (objfile, per_cu, name, real_path,
3700                                         callback))
3701                 return true;
3702               continue;
3703             }
3704
3705           /* Before we invoke realpath, which can get expensive when many
3706              files are involved, do a quick comparison of the basenames.  */
3707           if (! basenames_may_differ
3708               && FILENAME_CMP (lbasename (this_name), name_basename) != 0)
3709             continue;
3710
3711           this_real_name = dw2_get_real_path (objfile, file_data, j);
3712           if (compare_filenames_for_search (this_real_name, name))
3713             {
3714               if (dw2_map_expand_apply (objfile, per_cu, name, real_path,
3715                                         callback))
3716                 return true;
3717               continue;
3718             }
3719
3720           if (real_path != NULL)
3721             {
3722               gdb_assert (IS_ABSOLUTE_PATH (real_path));
3723               gdb_assert (IS_ABSOLUTE_PATH (name));
3724               if (this_real_name != NULL
3725                   && FILENAME_CMP (real_path, this_real_name) == 0)
3726                 {
3727                   if (dw2_map_expand_apply (objfile, per_cu, name, real_path,
3728                                             callback))
3729                     return true;
3730                   continue;
3731                 }
3732             }
3733         }
3734     }
3735
3736   return false;
3737 }
3738
3739 /* Struct used to manage iterating over all CUs looking for a symbol.  */
3740
3741 struct dw2_symtab_iterator
3742 {
3743   /* The internalized form of .gdb_index.  */
3744   struct mapped_index *index;
3745   /* If non-zero, only look for symbols that match BLOCK_INDEX.  */
3746   int want_specific_block;
3747   /* One of GLOBAL_BLOCK or STATIC_BLOCK.
3748      Unused if !WANT_SPECIFIC_BLOCK.  */
3749   int block_index;
3750   /* The kind of symbol we're looking for.  */
3751   domain_enum domain;
3752   /* The list of CUs from the index entry of the symbol,
3753      or NULL if not found.  */
3754   offset_type *vec;
3755   /* The next element in VEC to look at.  */
3756   int next;
3757   /* The number of elements in VEC, or zero if there is no match.  */
3758   int length;
3759   /* Have we seen a global version of the symbol?
3760      If so we can ignore all further global instances.
3761      This is to work around gold/15646, inefficient gold-generated
3762      indices.  */
3763   int global_seen;
3764 };
3765
3766 /* Initialize the index symtab iterator ITER.
3767    If WANT_SPECIFIC_BLOCK is non-zero, only look for symbols
3768    in block BLOCK_INDEX.  Otherwise BLOCK_INDEX is ignored.  */
3769
3770 static void
3771 dw2_symtab_iter_init (struct dw2_symtab_iterator *iter,
3772                       struct mapped_index *index,
3773                       int want_specific_block,
3774                       int block_index,
3775                       domain_enum domain,
3776                       const char *name)
3777 {
3778   iter->index = index;
3779   iter->want_specific_block = want_specific_block;
3780   iter->block_index = block_index;
3781   iter->domain = domain;
3782   iter->next = 0;
3783   iter->global_seen = 0;
3784
3785   if (find_slot_in_mapped_hash (index, name, &iter->vec))
3786     iter->length = MAYBE_SWAP (*iter->vec);
3787   else
3788     {
3789       iter->vec = NULL;
3790       iter->length = 0;
3791     }
3792 }
3793
3794 /* Return the next matching CU or NULL if there are no more.  */
3795
3796 static struct dwarf2_per_cu_data *
3797 dw2_symtab_iter_next (struct dw2_symtab_iterator *iter)
3798 {
3799   for ( ; iter->next < iter->length; ++iter->next)
3800     {
3801       offset_type cu_index_and_attrs =
3802         MAYBE_SWAP (iter->vec[iter->next + 1]);
3803       offset_type cu_index = GDB_INDEX_CU_VALUE (cu_index_and_attrs);
3804       struct dwarf2_per_cu_data *per_cu;
3805       int want_static = iter->block_index != GLOBAL_BLOCK;
3806       /* This value is only valid for index versions >= 7.  */
3807       int is_static = GDB_INDEX_SYMBOL_STATIC_VALUE (cu_index_and_attrs);
3808       gdb_index_symbol_kind symbol_kind =
3809         GDB_INDEX_SYMBOL_KIND_VALUE (cu_index_and_attrs);
3810       /* Only check the symbol attributes if they're present.
3811          Indices prior to version 7 don't record them,
3812          and indices >= 7 may elide them for certain symbols
3813          (gold does this).  */
3814       int attrs_valid =
3815         (iter->index->version >= 7
3816          && symbol_kind != GDB_INDEX_SYMBOL_KIND_NONE);
3817
3818       /* Don't crash on bad data.  */
3819       if (cu_index >= (dwarf2_per_objfile->n_comp_units
3820                        + dwarf2_per_objfile->n_type_units))
3821         {
3822           complaint (&symfile_complaints,
3823                      _(".gdb_index entry has bad CU index"
3824                        " [in module %s]"),
3825                      objfile_name (dwarf2_per_objfile->objfile));
3826           continue;
3827         }
3828
3829       per_cu = dw2_get_cutu (cu_index);
3830
3831       /* Skip if already read in.  */
3832       if (per_cu->v.quick->compunit_symtab)
3833         continue;
3834
3835       /* Check static vs global.  */
3836       if (attrs_valid)
3837         {
3838           if (iter->want_specific_block
3839               && want_static != is_static)
3840             continue;
3841           /* Work around gold/15646.  */
3842           if (!is_static && iter->global_seen)
3843             continue;
3844           if (!is_static)
3845             iter->global_seen = 1;
3846         }
3847
3848       /* Only check the symbol's kind if it has one.  */
3849       if (attrs_valid)
3850         {
3851           switch (iter->domain)
3852             {
3853             case VAR_DOMAIN:
3854               if (symbol_kind != GDB_INDEX_SYMBOL_KIND_VARIABLE
3855                   && symbol_kind != GDB_INDEX_SYMBOL_KIND_FUNCTION
3856                   /* Some types are also in VAR_DOMAIN.  */
3857                   && symbol_kind != GDB_INDEX_SYMBOL_KIND_TYPE)
3858                 continue;
3859               break;
3860             case STRUCT_DOMAIN:
3861               if (symbol_kind != GDB_INDEX_SYMBOL_KIND_TYPE)
3862                 continue;
3863               break;
3864             case LABEL_DOMAIN:
3865               if (symbol_kind != GDB_INDEX_SYMBOL_KIND_OTHER)
3866                 continue;
3867               break;
3868             default:
3869               break;
3870             }
3871         }
3872
3873       ++iter->next;
3874       return per_cu;
3875     }
3876
3877   return NULL;
3878 }
3879
3880 static struct compunit_symtab *
3881 dw2_lookup_symbol (struct objfile *objfile, int block_index,
3882                    const char *name, domain_enum domain)
3883 {
3884   struct compunit_symtab *stab_best = NULL;
3885   struct mapped_index *index;
3886
3887   dw2_setup (objfile);
3888
3889   index = dwarf2_per_objfile->index_table;
3890
3891   /* index is NULL if OBJF_READNOW.  */
3892   if (index)
3893     {
3894       struct dw2_symtab_iterator iter;
3895       struct dwarf2_per_cu_data *per_cu;
3896
3897       dw2_symtab_iter_init (&iter, index, 1, block_index, domain, name);
3898
3899       while ((per_cu = dw2_symtab_iter_next (&iter)) != NULL)
3900         {
3901           struct symbol *sym, *with_opaque = NULL;
3902           struct compunit_symtab *stab = dw2_instantiate_symtab (per_cu);
3903           const struct blockvector *bv = COMPUNIT_BLOCKVECTOR (stab);
3904           struct block *block = BLOCKVECTOR_BLOCK (bv, block_index);
3905
3906           sym = block_find_symbol (block, name, domain,
3907                                    block_find_non_opaque_type_preferred,
3908                                    &with_opaque);
3909
3910           /* Some caution must be observed with overloaded functions
3911              and methods, since the index will not contain any overload
3912              information (but NAME might contain it).  */
3913
3914           if (sym != NULL
3915               && SYMBOL_MATCHES_SEARCH_NAME (sym, name))
3916             return stab;
3917           if (with_opaque != NULL
3918               && SYMBOL_MATCHES_SEARCH_NAME (with_opaque, name))
3919             stab_best = stab;
3920
3921           /* Keep looking through other CUs.  */
3922         }
3923     }
3924
3925   return stab_best;
3926 }
3927
3928 static void
3929 dw2_print_stats (struct objfile *objfile)
3930 {
3931   int i, total, count;
3932
3933   dw2_setup (objfile);
3934   total = dwarf2_per_objfile->n_comp_units + dwarf2_per_objfile->n_type_units;
3935   count = 0;
3936   for (i = 0; i < total; ++i)
3937     {
3938       struct dwarf2_per_cu_data *per_cu = dw2_get_cutu (i);
3939
3940       if (!per_cu->v.quick->compunit_symtab)
3941         ++count;
3942     }
3943   printf_filtered (_("  Number of read CUs: %d\n"), total - count);
3944   printf_filtered (_("  Number of unread CUs: %d\n"), count);
3945 }
3946
3947 /* This dumps minimal information about the index.
3948    It is called via "mt print objfiles".
3949    One use is to verify .gdb_index has been loaded by the
3950    gdb.dwarf2/gdb-index.exp testcase.  */
3951
3952 static void
3953 dw2_dump (struct objfile *objfile)
3954 {
3955   dw2_setup (objfile);
3956   gdb_assert (dwarf2_per_objfile->using_index);
3957   printf_filtered (".gdb_index:");
3958   if (dwarf2_per_objfile->index_table != NULL)
3959     {
3960       printf_filtered (" version %d\n",
3961                        dwarf2_per_objfile->index_table->version);
3962     }
3963   else
3964     printf_filtered (" faked for \"readnow\"\n");
3965   printf_filtered ("\n");
3966 }
3967
3968 static void
3969 dw2_relocate (struct objfile *objfile,
3970               const struct section_offsets *new_offsets,
3971               const struct section_offsets *delta)
3972 {
3973   /* There's nothing to relocate here.  */
3974 }
3975
3976 static void
3977 dw2_expand_symtabs_for_function (struct objfile *objfile,
3978                                  const char *func_name)
3979 {
3980   struct mapped_index *index;
3981
3982   dw2_setup (objfile);
3983
3984   index = dwarf2_per_objfile->index_table;
3985
3986   /* index is NULL if OBJF_READNOW.  */
3987   if (index)
3988     {
3989       struct dw2_symtab_iterator iter;
3990       struct dwarf2_per_cu_data *per_cu;
3991
3992       /* Note: It doesn't matter what we pass for block_index here.  */
3993       dw2_symtab_iter_init (&iter, index, 0, GLOBAL_BLOCK, VAR_DOMAIN,
3994                             func_name);
3995
3996       while ((per_cu = dw2_symtab_iter_next (&iter)) != NULL)
3997         dw2_instantiate_symtab (per_cu);
3998     }
3999 }
4000
4001 static void
4002 dw2_expand_all_symtabs (struct objfile *objfile)
4003 {
4004   int i;
4005
4006   dw2_setup (objfile);
4007
4008   for (i = 0; i < (dwarf2_per_objfile->n_comp_units
4009                    + dwarf2_per_objfile->n_type_units); ++i)
4010     {
4011       struct dwarf2_per_cu_data *per_cu = dw2_get_cutu (i);
4012
4013       dw2_instantiate_symtab (per_cu);
4014     }
4015 }
4016
4017 static void
4018 dw2_expand_symtabs_with_fullname (struct objfile *objfile,
4019                                   const char *fullname)
4020 {
4021   int i;
4022
4023   dw2_setup (objfile);
4024
4025   /* We don't need to consider type units here.
4026      This is only called for examining code, e.g. expand_line_sal.
4027      There can be an order of magnitude (or more) more type units
4028      than comp units, and we avoid them if we can.  */
4029
4030   for (i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
4031     {
4032       int j;
4033       struct dwarf2_per_cu_data *per_cu = dw2_get_cutu (i);
4034       struct quick_file_names *file_data;
4035
4036       /* We only need to look at symtabs not already expanded.  */
4037       if (per_cu->v.quick->compunit_symtab)
4038         continue;
4039
4040       file_data = dw2_get_file_names (per_cu);
4041       if (file_data == NULL)
4042         continue;
4043
4044       for (j = 0; j < file_data->num_file_names; ++j)
4045         {
4046           const char *this_fullname = file_data->file_names[j];
4047
4048           if (filename_cmp (this_fullname, fullname) == 0)
4049             {
4050               dw2_instantiate_symtab (per_cu);
4051               break;
4052             }
4053         }
4054     }
4055 }
4056
4057 static void
4058 dw2_map_matching_symbols (struct objfile *objfile,
4059                           const char * name, domain_enum domain,
4060                           int global,
4061                           int (*callback) (struct block *,
4062                                            struct symbol *, void *),
4063                           void *data, symbol_compare_ftype *match,
4064                           symbol_compare_ftype *ordered_compare)
4065 {
4066   /* Currently unimplemented; used for Ada.  The function can be called if the
4067      current language is Ada for a non-Ada objfile using GNU index.  As Ada
4068      does not look for non-Ada symbols this function should just return.  */
4069 }
4070
4071 static void
4072 dw2_expand_symtabs_matching
4073   (struct objfile *objfile,
4074    gdb::function_view<expand_symtabs_file_matcher_ftype> file_matcher,
4075    gdb::function_view<expand_symtabs_symbol_matcher_ftype> symbol_matcher,
4076    gdb::function_view<expand_symtabs_exp_notify_ftype> expansion_notify,
4077    enum search_domain kind)
4078 {
4079   int i;
4080   offset_type iter;
4081   struct mapped_index *index;
4082
4083   dw2_setup (objfile);
4084
4085   /* index_table is NULL if OBJF_READNOW.  */
4086   if (!dwarf2_per_objfile->index_table)
4087     return;
4088   index = dwarf2_per_objfile->index_table;
4089
4090   if (file_matcher != NULL)
4091     {
4092       htab_up visited_found (htab_create_alloc (10, htab_hash_pointer,
4093                                                 htab_eq_pointer,
4094                                                 NULL, xcalloc, xfree));
4095       htab_up visited_not_found (htab_create_alloc (10, htab_hash_pointer,
4096                                                     htab_eq_pointer,
4097                                                     NULL, xcalloc, xfree));
4098
4099       /* The rule is CUs specify all the files, including those used by
4100          any TU, so there's no need to scan TUs here.  */
4101
4102       for (i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
4103         {
4104           int j;
4105           struct dwarf2_per_cu_data *per_cu = dw2_get_cu (i);
4106           struct quick_file_names *file_data;
4107           void **slot;
4108
4109           QUIT;
4110
4111           per_cu->v.quick->mark = 0;
4112
4113           /* We only need to look at symtabs not already expanded.  */
4114           if (per_cu->v.quick->compunit_symtab)
4115             continue;
4116
4117           file_data = dw2_get_file_names (per_cu);
4118           if (file_data == NULL)
4119             continue;
4120
4121           if (htab_find (visited_not_found.get (), file_data) != NULL)
4122             continue;
4123           else if (htab_find (visited_found.get (), file_data) != NULL)
4124             {
4125               per_cu->v.quick->mark = 1;
4126               continue;
4127             }
4128
4129           for (j = 0; j < file_data->num_file_names; ++j)
4130             {
4131               const char *this_real_name;
4132
4133               if (file_matcher (file_data->file_names[j], false))
4134                 {
4135                   per_cu->v.quick->mark = 1;
4136                   break;
4137                 }
4138
4139               /* Before we invoke realpath, which can get expensive when many
4140                  files are involved, do a quick comparison of the basenames.  */
4141               if (!basenames_may_differ
4142                   && !file_matcher (lbasename (file_data->file_names[j]),
4143                                     true))
4144                 continue;
4145
4146               this_real_name = dw2_get_real_path (objfile, file_data, j);
4147               if (file_matcher (this_real_name, false))
4148                 {
4149                   per_cu->v.quick->mark = 1;
4150                   break;
4151                 }
4152             }
4153
4154           slot = htab_find_slot (per_cu->v.quick->mark
4155                                  ? visited_found.get ()
4156                                  : visited_not_found.get (),
4157                                  file_data, INSERT);
4158           *slot = file_data;
4159         }
4160     }
4161
4162   for (iter = 0; iter < index->symbol_table_slots; ++iter)
4163     {
4164       offset_type idx = 2 * iter;
4165       const char *name;
4166       offset_type *vec, vec_len, vec_idx;
4167       int global_seen = 0;
4168
4169       QUIT;
4170
4171       if (index->symbol_table[idx] == 0 && index->symbol_table[idx + 1] == 0)
4172         continue;
4173
4174       name = index->constant_pool + MAYBE_SWAP (index->symbol_table[idx]);
4175
4176       if (!symbol_matcher (name))
4177         continue;
4178
4179       /* The name was matched, now expand corresponding CUs that were
4180          marked.  */
4181       vec = (offset_type *) (index->constant_pool
4182                              + MAYBE_SWAP (index->symbol_table[idx + 1]));
4183       vec_len = MAYBE_SWAP (vec[0]);
4184       for (vec_idx = 0; vec_idx < vec_len; ++vec_idx)
4185         {
4186           struct dwarf2_per_cu_data *per_cu;
4187           offset_type cu_index_and_attrs = MAYBE_SWAP (vec[vec_idx + 1]);
4188           /* This value is only valid for index versions >= 7.  */
4189           int is_static = GDB_INDEX_SYMBOL_STATIC_VALUE (cu_index_and_attrs);
4190           gdb_index_symbol_kind symbol_kind =
4191             GDB_INDEX_SYMBOL_KIND_VALUE (cu_index_and_attrs);
4192           int cu_index = GDB_INDEX_CU_VALUE (cu_index_and_attrs);
4193           /* Only check the symbol attributes if they're present.
4194              Indices prior to version 7 don't record them,
4195              and indices >= 7 may elide them for certain symbols
4196              (gold does this).  */
4197           int attrs_valid =
4198             (index->version >= 7
4199              && symbol_kind != GDB_INDEX_SYMBOL_KIND_NONE);
4200
4201           /* Work around gold/15646.  */
4202           if (attrs_valid)
4203             {
4204               if (!is_static && global_seen)
4205                 continue;
4206               if (!is_static)
4207                 global_seen = 1;
4208             }
4209
4210           /* Only check the symbol's kind if it has one.  */
4211           if (attrs_valid)
4212             {
4213               switch (kind)
4214                 {
4215                 case VARIABLES_DOMAIN:
4216                   if (symbol_kind != GDB_INDEX_SYMBOL_KIND_VARIABLE)
4217                     continue;
4218                   break;
4219                 case FUNCTIONS_DOMAIN:
4220                   if (symbol_kind != GDB_INDEX_SYMBOL_KIND_FUNCTION)
4221                     continue;
4222                   break;
4223                 case TYPES_DOMAIN:
4224                   if (symbol_kind != GDB_INDEX_SYMBOL_KIND_TYPE)
4225                     continue;
4226                   break;
4227                 default:
4228                   break;
4229                 }
4230             }
4231
4232           /* Don't crash on bad data.  */
4233           if (cu_index >= (dwarf2_per_objfile->n_comp_units
4234                            + dwarf2_per_objfile->n_type_units))
4235             {
4236               complaint (&symfile_complaints,
4237                          _(".gdb_index entry has bad CU index"
4238                            " [in module %s]"), objfile_name (objfile));
4239               continue;
4240             }
4241
4242           per_cu = dw2_get_cutu (cu_index);
4243           if (file_matcher == NULL || per_cu->v.quick->mark)
4244             {
4245               int symtab_was_null =
4246                 (per_cu->v.quick->compunit_symtab == NULL);
4247
4248               dw2_instantiate_symtab (per_cu);
4249
4250               if (expansion_notify != NULL
4251                   && symtab_was_null
4252                   && per_cu->v.quick->compunit_symtab != NULL)
4253                 {
4254                   expansion_notify (per_cu->v.quick->compunit_symtab);
4255                 }
4256             }
4257         }
4258     }
4259 }
4260
4261 /* A helper for dw2_find_pc_sect_compunit_symtab which finds the most specific
4262    symtab.  */
4263
4264 static struct compunit_symtab *
4265 recursively_find_pc_sect_compunit_symtab (struct compunit_symtab *cust,
4266                                           CORE_ADDR pc)
4267 {
4268   int i;
4269
4270   if (COMPUNIT_BLOCKVECTOR (cust) != NULL
4271       && blockvector_contains_pc (COMPUNIT_BLOCKVECTOR (cust), pc))
4272     return cust;
4273
4274   if (cust->includes == NULL)
4275     return NULL;
4276
4277   for (i = 0; cust->includes[i]; ++i)
4278     {
4279       struct compunit_symtab *s = cust->includes[i];
4280
4281       s = recursively_find_pc_sect_compunit_symtab (s, pc);
4282       if (s != NULL)
4283         return s;
4284     }
4285
4286   return NULL;
4287 }
4288
4289 static struct compunit_symtab *
4290 dw2_find_pc_sect_compunit_symtab (struct objfile *objfile,
4291                                   struct bound_minimal_symbol msymbol,
4292                                   CORE_ADDR pc,
4293                                   struct obj_section *section,
4294                                   int warn_if_readin)
4295 {
4296   struct dwarf2_per_cu_data *data;
4297   struct compunit_symtab *result;
4298
4299   dw2_setup (objfile);
4300
4301   if (!objfile->psymtabs_addrmap)
4302     return NULL;
4303
4304   data = (struct dwarf2_per_cu_data *) addrmap_find (objfile->psymtabs_addrmap,
4305                                                      pc);
4306   if (!data)
4307     return NULL;
4308
4309   if (warn_if_readin && data->v.quick->compunit_symtab)
4310     warning (_("(Internal error: pc %s in read in CU, but not in symtab.)"),
4311              paddress (get_objfile_arch (objfile), pc));
4312
4313   result
4314     = recursively_find_pc_sect_compunit_symtab (dw2_instantiate_symtab (data),
4315                                                 pc);
4316   gdb_assert (result != NULL);
4317   return result;
4318 }
4319
4320 static void
4321 dw2_map_symbol_filenames (struct objfile *objfile, symbol_filename_ftype *fun,
4322                           void *data, int need_fullname)
4323 {
4324   dw2_setup (objfile);
4325
4326   if (!dwarf2_per_objfile->filenames_cache)
4327     {
4328       dwarf2_per_objfile->filenames_cache.emplace ();
4329
4330       htab_up visited (htab_create_alloc (10,
4331                                           htab_hash_pointer, htab_eq_pointer,
4332                                           NULL, xcalloc, xfree));
4333
4334       /* The rule is CUs specify all the files, including those used
4335          by any TU, so there's no need to scan TUs here.  We can
4336          ignore file names coming from already-expanded CUs.  */
4337
4338       for (int i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
4339         {
4340           struct dwarf2_per_cu_data *per_cu = dw2_get_cutu (i);
4341
4342           if (per_cu->v.quick->compunit_symtab)
4343             {
4344               void **slot = htab_find_slot (visited.get (),
4345                                             per_cu->v.quick->file_names,
4346                                             INSERT);
4347
4348               *slot = per_cu->v.quick->file_names;
4349             }
4350         }
4351
4352       for (int i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
4353         {
4354           int j;
4355           struct dwarf2_per_cu_data *per_cu = dw2_get_cu (i);
4356           struct quick_file_names *file_data;
4357           void **slot;
4358
4359           /* We only need to look at symtabs not already expanded.  */
4360           if (per_cu->v.quick->compunit_symtab)
4361             continue;
4362
4363           file_data = dw2_get_file_names (per_cu);
4364           if (file_data == NULL)
4365             continue;
4366
4367           slot = htab_find_slot (visited.get (), file_data, INSERT);
4368           if (*slot)
4369             {
4370               /* Already visited.  */
4371               continue;
4372             }
4373           *slot = file_data;
4374
4375           for (int j = 0; j < file_data->num_file_names; ++j)
4376             {
4377               const char *filename = file_data->file_names[j];
4378               dwarf2_per_objfile->filenames_cache->seen (filename);
4379             }
4380         }
4381     }
4382
4383   dwarf2_per_objfile->filenames_cache->traverse ([&] (const char *filename)
4384     {
4385       gdb::unique_xmalloc_ptr<char> this_real_name;
4386
4387       if (need_fullname)
4388         this_real_name = gdb_realpath (filename);
4389       (*fun) (filename, this_real_name.get (), data);
4390     });
4391 }
4392
4393 static int
4394 dw2_has_symbols (struct objfile *objfile)
4395 {
4396   return 1;
4397 }
4398
4399 const struct quick_symbol_functions dwarf2_gdb_index_functions =
4400 {
4401   dw2_has_symbols,
4402   dw2_find_last_source_symtab,
4403   dw2_forget_cached_source_info,
4404   dw2_map_symtabs_matching_filename,
4405   dw2_lookup_symbol,
4406   dw2_print_stats,
4407   dw2_dump,
4408   dw2_relocate,
4409   dw2_expand_symtabs_for_function,
4410   dw2_expand_all_symtabs,
4411   dw2_expand_symtabs_with_fullname,
4412   dw2_map_matching_symbols,
4413   dw2_expand_symtabs_matching,
4414   dw2_find_pc_sect_compunit_symtab,
4415   dw2_map_symbol_filenames
4416 };
4417
4418 /* Initialize for reading DWARF for this objfile.  Return 0 if this
4419    file will use psymtabs, or 1 if using the GNU index.  */
4420
4421 int
4422 dwarf2_initialize_objfile (struct objfile *objfile)
4423 {
4424   /* If we're about to read full symbols, don't bother with the
4425      indices.  In this case we also don't care if some other debug
4426      format is making psymtabs, because they are all about to be
4427      expanded anyway.  */
4428   if ((objfile->flags & OBJF_READNOW))
4429     {
4430       int i;
4431
4432       dwarf2_per_objfile->using_index = 1;
4433       create_all_comp_units (objfile);
4434       create_all_type_units (objfile);
4435       dwarf2_per_objfile->quick_file_names_table =
4436         create_quick_file_names_table (dwarf2_per_objfile->n_comp_units);
4437
4438       for (i = 0; i < (dwarf2_per_objfile->n_comp_units
4439                        + dwarf2_per_objfile->n_type_units); ++i)
4440         {
4441           struct dwarf2_per_cu_data *per_cu = dw2_get_cutu (i);
4442
4443           per_cu->v.quick = OBSTACK_ZALLOC (&objfile->objfile_obstack,
4444                                             struct dwarf2_per_cu_quick_data);
4445         }
4446
4447       /* Return 1 so that gdb sees the "quick" functions.  However,
4448          these functions will be no-ops because we will have expanded
4449          all symtabs.  */
4450       return 1;
4451     }
4452
4453   if (dwarf2_read_index (objfile))
4454     return 1;
4455
4456   return 0;
4457 }
4458
4459 \f
4460
4461 /* Build a partial symbol table.  */
4462
4463 void
4464 dwarf2_build_psymtabs (struct objfile *objfile)
4465 {
4466
4467   if (objfile->global_psymbols.size == 0 && objfile->static_psymbols.size == 0)
4468     {
4469       init_psymbol_list (objfile, 1024);
4470     }
4471
4472   TRY
4473     {
4474       /* This isn't really ideal: all the data we allocate on the
4475          objfile's obstack is still uselessly kept around.  However,
4476          freeing it seems unsafe.  */
4477       psymtab_discarder psymtabs (objfile);
4478       dwarf2_build_psymtabs_hard (objfile);
4479       psymtabs.keep ();
4480     }
4481   CATCH (except, RETURN_MASK_ERROR)
4482     {
4483       exception_print (gdb_stderr, except);
4484     }
4485   END_CATCH
4486 }
4487
4488 /* Return the total length of the CU described by HEADER.  */
4489
4490 static unsigned int
4491 get_cu_length (const struct comp_unit_head *header)
4492 {
4493   return header->initial_length_size + header->length;
4494 }
4495
4496 /* Return TRUE if SECT_OFF is within CU_HEADER.  */
4497
4498 static inline bool
4499 offset_in_cu_p (const comp_unit_head *cu_header, sect_offset sect_off)
4500 {
4501   sect_offset bottom = cu_header->sect_off;
4502   sect_offset top = cu_header->sect_off + get_cu_length (cu_header);
4503
4504   return sect_off >= bottom && sect_off < top;
4505 }
4506
4507 /* Find the base address of the compilation unit for range lists and
4508    location lists.  It will normally be specified by DW_AT_low_pc.
4509    In DWARF-3 draft 4, the base address could be overridden by
4510    DW_AT_entry_pc.  It's been removed, but GCC still uses this for
4511    compilation units with discontinuous ranges.  */
4512
4513 static void
4514 dwarf2_find_base_address (struct die_info *die, struct dwarf2_cu *cu)
4515 {
4516   struct attribute *attr;
4517
4518   cu->base_known = 0;
4519   cu->base_address = 0;
4520
4521   attr = dwarf2_attr (die, DW_AT_entry_pc, cu);
4522   if (attr)
4523     {
4524       cu->base_address = attr_value_as_address (attr);
4525       cu->base_known = 1;
4526     }
4527   else
4528     {
4529       attr = dwarf2_attr (die, DW_AT_low_pc, cu);
4530       if (attr)
4531         {
4532           cu->base_address = attr_value_as_address (attr);
4533           cu->base_known = 1;
4534         }
4535     }
4536 }
4537
4538 /* Read in the comp unit header information from the debug_info at info_ptr.
4539    Use rcuh_kind::COMPILE as the default type if not known by the caller.
4540    NOTE: This leaves members offset, first_die_offset to be filled in
4541    by the caller.  */
4542
4543 static const gdb_byte *
4544 read_comp_unit_head (struct comp_unit_head *cu_header,
4545                      const gdb_byte *info_ptr,
4546                      struct dwarf2_section_info *section,
4547                      rcuh_kind section_kind)
4548 {
4549   int signed_addr;
4550   unsigned int bytes_read;
4551   const char *filename = get_section_file_name (section);
4552   bfd *abfd = get_section_bfd_owner (section);
4553
4554   cu_header->length = read_initial_length (abfd, info_ptr, &bytes_read);
4555   cu_header->initial_length_size = bytes_read;
4556   cu_header->offset_size = (bytes_read == 4) ? 4 : 8;
4557   info_ptr += bytes_read;
4558   cu_header->version = read_2_bytes (abfd, info_ptr);
4559   info_ptr += 2;
4560   if (cu_header->version < 5)
4561     switch (section_kind)
4562       {
4563       case rcuh_kind::COMPILE:
4564         cu_header->unit_type = DW_UT_compile;
4565         break;
4566       case rcuh_kind::TYPE:
4567         cu_header->unit_type = DW_UT_type;
4568         break;
4569       default:
4570         internal_error (__FILE__, __LINE__,
4571                         _("read_comp_unit_head: invalid section_kind"));
4572       }
4573   else
4574     {
4575       cu_header->unit_type = static_cast<enum dwarf_unit_type>
4576                                                  (read_1_byte (abfd, info_ptr));
4577       info_ptr += 1;
4578       switch (cu_header->unit_type)
4579         {
4580         case DW_UT_compile:
4581           if (section_kind != rcuh_kind::COMPILE)
4582             error (_("Dwarf Error: wrong unit_type in compilation unit header "
4583                    "(is DW_UT_compile, should be DW_UT_type) [in module %s]"),
4584                    filename);
4585           break;
4586         case DW_UT_type:
4587           section_kind = rcuh_kind::TYPE;
4588           break;
4589         default:
4590           error (_("Dwarf Error: wrong unit_type in compilation unit header "
4591                  "(is %d, should be %d or %d) [in module %s]"),
4592                  cu_header->unit_type, DW_UT_compile, DW_UT_type, filename);
4593         }
4594
4595       cu_header->addr_size = read_1_byte (abfd, info_ptr);
4596       info_ptr += 1;
4597     }
4598   cu_header->abbrev_sect_off = (sect_offset) read_offset (abfd, info_ptr,
4599                                                           cu_header,
4600                                                           &bytes_read);
4601   info_ptr += bytes_read;
4602   if (cu_header->version < 5)
4603     {
4604       cu_header->addr_size = read_1_byte (abfd, info_ptr);
4605       info_ptr += 1;
4606     }
4607   signed_addr = bfd_get_sign_extend_vma (abfd);
4608   if (signed_addr < 0)
4609     internal_error (__FILE__, __LINE__,
4610                     _("read_comp_unit_head: dwarf from non elf file"));
4611   cu_header->signed_addr_p = signed_addr;
4612
4613   if (section_kind == rcuh_kind::TYPE)
4614     {
4615       LONGEST type_offset;
4616
4617       cu_header->signature = read_8_bytes (abfd, info_ptr);
4618       info_ptr += 8;
4619
4620       type_offset = read_offset (abfd, info_ptr, cu_header, &bytes_read);
4621       info_ptr += bytes_read;
4622       cu_header->type_cu_offset_in_tu = (cu_offset) type_offset;
4623       if (to_underlying (cu_header->type_cu_offset_in_tu) != type_offset)
4624         error (_("Dwarf Error: Too big type_offset in compilation unit "
4625                "header (is %s) [in module %s]"), plongest (type_offset),
4626                filename);
4627     }
4628
4629   return info_ptr;
4630 }
4631
4632 /* Helper function that returns the proper abbrev section for
4633    THIS_CU.  */
4634
4635 static struct dwarf2_section_info *
4636 get_abbrev_section_for_cu (struct dwarf2_per_cu_data *this_cu)
4637 {
4638   struct dwarf2_section_info *abbrev;
4639
4640   if (this_cu->is_dwz)
4641     abbrev = &dwarf2_get_dwz_file ()->abbrev;
4642   else
4643     abbrev = &dwarf2_per_objfile->abbrev;
4644
4645   return abbrev;
4646 }
4647
4648 /* Subroutine of read_and_check_comp_unit_head and
4649    read_and_check_type_unit_head to simplify them.
4650    Perform various error checking on the header.  */
4651
4652 static void
4653 error_check_comp_unit_head (struct comp_unit_head *header,
4654                             struct dwarf2_section_info *section,
4655                             struct dwarf2_section_info *abbrev_section)
4656 {
4657   const char *filename = get_section_file_name (section);
4658
4659   if (header->version < 2 || header->version > 5)
4660     error (_("Dwarf Error: wrong version in compilation unit header "
4661            "(is %d, should be 2, 3, 4 or 5) [in module %s]"), header->version,
4662            filename);
4663
4664   if (to_underlying (header->abbrev_sect_off)
4665       >= dwarf2_section_size (dwarf2_per_objfile->objfile, abbrev_section))
4666     error (_("Dwarf Error: bad offset (0x%x) in compilation unit header "
4667            "(offset 0x%x + 6) [in module %s]"),
4668            to_underlying (header->abbrev_sect_off),
4669            to_underlying (header->sect_off),
4670            filename);
4671
4672   /* Cast to ULONGEST to use 64-bit arithmetic when possible to
4673      avoid potential 32-bit overflow.  */
4674   if (((ULONGEST) header->sect_off + get_cu_length (header))
4675       > section->size)
4676     error (_("Dwarf Error: bad length (0x%x) in compilation unit header "
4677            "(offset 0x%x + 0) [in module %s]"),
4678            header->length, to_underlying (header->sect_off),
4679            filename);
4680 }
4681
4682 /* Read in a CU/TU header and perform some basic error checking.
4683    The contents of the header are stored in HEADER.
4684    The result is a pointer to the start of the first DIE.  */
4685
4686 static const gdb_byte *
4687 read_and_check_comp_unit_head (struct comp_unit_head *header,
4688                                struct dwarf2_section_info *section,
4689                                struct dwarf2_section_info *abbrev_section,
4690                                const gdb_byte *info_ptr,
4691                                rcuh_kind section_kind)
4692 {
4693   const gdb_byte *beg_of_comp_unit = info_ptr;
4694   bfd *abfd = get_section_bfd_owner (section);
4695
4696   header->sect_off = (sect_offset) (beg_of_comp_unit - section->buffer);
4697
4698   info_ptr = read_comp_unit_head (header, info_ptr, section, section_kind);
4699
4700   header->first_die_cu_offset = (cu_offset) (info_ptr - beg_of_comp_unit);
4701
4702   error_check_comp_unit_head (header, section, abbrev_section);
4703
4704   return info_ptr;
4705 }
4706
4707 /* Fetch the abbreviation table offset from a comp or type unit header.  */
4708
4709 static sect_offset
4710 read_abbrev_offset (struct dwarf2_section_info *section,
4711                     sect_offset sect_off)
4712 {
4713   bfd *abfd = get_section_bfd_owner (section);
4714   const gdb_byte *info_ptr;
4715   unsigned int initial_length_size, offset_size;
4716   uint16_t version;
4717
4718   dwarf2_read_section (dwarf2_per_objfile->objfile, section);
4719   info_ptr = section->buffer + to_underlying (sect_off);
4720   read_initial_length (abfd, info_ptr, &initial_length_size);
4721   offset_size = initial_length_size == 4 ? 4 : 8;
4722   info_ptr += initial_length_size;
4723
4724   version = read_2_bytes (abfd, info_ptr);
4725   info_ptr += 2;
4726   if (version >= 5)
4727     {
4728       /* Skip unit type and address size.  */
4729       info_ptr += 2;
4730     }
4731
4732   return (sect_offset) read_offset_1 (abfd, info_ptr, offset_size);
4733 }
4734
4735 /* Allocate a new partial symtab for file named NAME and mark this new
4736    partial symtab as being an include of PST.  */
4737
4738 static void
4739 dwarf2_create_include_psymtab (const char *name, struct partial_symtab *pst,
4740                                struct objfile *objfile)
4741 {
4742   struct partial_symtab *subpst = allocate_psymtab (name, objfile);
4743
4744   if (!IS_ABSOLUTE_PATH (subpst->filename))
4745     {
4746       /* It shares objfile->objfile_obstack.  */
4747       subpst->dirname = pst->dirname;
4748     }
4749
4750   subpst->textlow = 0;
4751   subpst->texthigh = 0;
4752
4753   subpst->dependencies
4754     = XOBNEW (&objfile->objfile_obstack, struct partial_symtab *);
4755   subpst->dependencies[0] = pst;
4756   subpst->number_of_dependencies = 1;
4757
4758   subpst->globals_offset = 0;
4759   subpst->n_global_syms = 0;
4760   subpst->statics_offset = 0;
4761   subpst->n_static_syms = 0;
4762   subpst->compunit_symtab = NULL;
4763   subpst->read_symtab = pst->read_symtab;
4764   subpst->readin = 0;
4765
4766   /* No private part is necessary for include psymtabs.  This property
4767      can be used to differentiate between such include psymtabs and
4768      the regular ones.  */
4769   subpst->read_symtab_private = NULL;
4770 }
4771
4772 /* Read the Line Number Program data and extract the list of files
4773    included by the source file represented by PST.  Build an include
4774    partial symtab for each of these included files.  */
4775
4776 static void
4777 dwarf2_build_include_psymtabs (struct dwarf2_cu *cu,
4778                                struct die_info *die,
4779                                struct partial_symtab *pst)
4780 {
4781   line_header_up lh;
4782   struct attribute *attr;
4783
4784   attr = dwarf2_attr (die, DW_AT_stmt_list, cu);
4785   if (attr)
4786     lh = dwarf_decode_line_header ((sect_offset) DW_UNSND (attr), cu);
4787   if (lh == NULL)
4788     return;  /* No linetable, so no includes.  */
4789
4790   /* NOTE: pst->dirname is DW_AT_comp_dir (if present).  */
4791   dwarf_decode_lines (lh.get (), pst->dirname, cu, pst, pst->textlow, 1);
4792 }
4793
4794 static hashval_t
4795 hash_signatured_type (const void *item)
4796 {
4797   const struct signatured_type *sig_type
4798     = (const struct signatured_type *) item;
4799
4800   /* This drops the top 32 bits of the signature, but is ok for a hash.  */
4801   return sig_type->signature;
4802 }
4803
4804 static int
4805 eq_signatured_type (const void *item_lhs, const void *item_rhs)
4806 {
4807   const struct signatured_type *lhs = (const struct signatured_type *) item_lhs;
4808   const struct signatured_type *rhs = (const struct signatured_type *) item_rhs;
4809
4810   return lhs->signature == rhs->signature;
4811 }
4812
4813 /* Allocate a hash table for signatured types.  */
4814
4815 static htab_t
4816 allocate_signatured_type_table (struct objfile *objfile)
4817 {
4818   return htab_create_alloc_ex (41,
4819                                hash_signatured_type,
4820                                eq_signatured_type,
4821                                NULL,
4822                                &objfile->objfile_obstack,
4823                                hashtab_obstack_allocate,
4824                                dummy_obstack_deallocate);
4825 }
4826
4827 /* A helper function to add a signatured type CU to a table.  */
4828
4829 static int
4830 add_signatured_type_cu_to_table (void **slot, void *datum)
4831 {
4832   struct signatured_type *sigt = (struct signatured_type *) *slot;
4833   struct signatured_type ***datap = (struct signatured_type ***) datum;
4834
4835   **datap = sigt;
4836   ++*datap;
4837
4838   return 1;
4839 }
4840
4841 /* A helper for create_debug_types_hash_table.  Read types from SECTION
4842    and fill them into TYPES_HTAB.  It will process only type units,
4843    therefore DW_UT_type.  */
4844
4845 static void
4846 create_debug_type_hash_table (struct dwo_file *dwo_file,
4847                               dwarf2_section_info *section, htab_t &types_htab,
4848                               rcuh_kind section_kind)
4849 {
4850   struct objfile *objfile = dwarf2_per_objfile->objfile;
4851   struct dwarf2_section_info *abbrev_section;
4852   bfd *abfd;
4853   const gdb_byte *info_ptr, *end_ptr;
4854
4855   abbrev_section = (dwo_file != NULL
4856                     ? &dwo_file->sections.abbrev
4857                     : &dwarf2_per_objfile->abbrev);
4858
4859   if (dwarf_read_debug)
4860     fprintf_unfiltered (gdb_stdlog, "Reading %s for %s:\n",
4861                         get_section_name (section),
4862                         get_section_file_name (abbrev_section));
4863
4864   dwarf2_read_section (objfile, section);
4865   info_ptr = section->buffer;
4866
4867   if (info_ptr == NULL)
4868     return;
4869
4870   /* We can't set abfd until now because the section may be empty or
4871      not present, in which case the bfd is unknown.  */
4872   abfd = get_section_bfd_owner (section);
4873
4874   /* We don't use init_cutu_and_read_dies_simple, or some such, here
4875      because we don't need to read any dies: the signature is in the
4876      header.  */
4877
4878   end_ptr = info_ptr + section->size;
4879   while (info_ptr < end_ptr)
4880     {
4881       struct signatured_type *sig_type;
4882       struct dwo_unit *dwo_tu;
4883       void **slot;
4884       const gdb_byte *ptr = info_ptr;
4885       struct comp_unit_head header;
4886       unsigned int length;
4887
4888       sect_offset sect_off = (sect_offset) (ptr - section->buffer);
4889
4890       /* Initialize it due to a false compiler warning.  */
4891       header.signature = -1;
4892       header.type_cu_offset_in_tu = (cu_offset) -1;
4893
4894       /* We need to read the type's signature in order to build the hash
4895          table, but we don't need anything else just yet.  */
4896
4897       ptr = read_and_check_comp_unit_head (&header, section,
4898                                            abbrev_section, ptr, section_kind);
4899
4900       length = get_cu_length (&header);
4901
4902       /* Skip dummy type units.  */
4903       if (ptr >= info_ptr + length
4904           || peek_abbrev_code (abfd, ptr) == 0
4905           || header.unit_type != DW_UT_type)
4906         {
4907           info_ptr += length;
4908           continue;
4909         }
4910
4911       if (types_htab == NULL)
4912         {
4913           if (dwo_file)
4914             types_htab = allocate_dwo_unit_table (objfile);
4915           else
4916             types_htab = allocate_signatured_type_table (objfile);
4917         }
4918
4919       if (dwo_file)
4920         {
4921           sig_type = NULL;
4922           dwo_tu = OBSTACK_ZALLOC (&objfile->objfile_obstack,
4923                                    struct dwo_unit);
4924           dwo_tu->dwo_file = dwo_file;
4925           dwo_tu->signature = header.signature;
4926           dwo_tu->type_offset_in_tu = header.type_cu_offset_in_tu;
4927           dwo_tu->section = section;
4928           dwo_tu->sect_off = sect_off;
4929           dwo_tu->length = length;
4930         }
4931       else
4932         {
4933           /* N.B.: type_offset is not usable if this type uses a DWO file.
4934              The real type_offset is in the DWO file.  */
4935           dwo_tu = NULL;
4936           sig_type = OBSTACK_ZALLOC (&objfile->objfile_obstack,
4937                                      struct signatured_type);
4938           sig_type->signature = header.signature;
4939           sig_type->type_offset_in_tu = header.type_cu_offset_in_tu;
4940           sig_type->per_cu.objfile = objfile;
4941           sig_type->per_cu.is_debug_types = 1;
4942           sig_type->per_cu.section = section;
4943           sig_type->per_cu.sect_off = sect_off;
4944           sig_type->per_cu.length = length;
4945         }
4946
4947       slot = htab_find_slot (types_htab,
4948                              dwo_file ? (void*) dwo_tu : (void *) sig_type,
4949                              INSERT);
4950       gdb_assert (slot != NULL);
4951       if (*slot != NULL)
4952         {
4953           sect_offset dup_sect_off;
4954
4955           if (dwo_file)
4956             {
4957               const struct dwo_unit *dup_tu
4958                 = (const struct dwo_unit *) *slot;
4959
4960               dup_sect_off = dup_tu->sect_off;
4961             }
4962           else
4963             {
4964               const struct signatured_type *dup_tu
4965                 = (const struct signatured_type *) *slot;
4966
4967               dup_sect_off = dup_tu->per_cu.sect_off;
4968             }
4969
4970           complaint (&symfile_complaints,
4971                      _("debug type entry at offset 0x%x is duplicate to"
4972                        " the entry at offset 0x%x, signature %s"),
4973                      to_underlying (sect_off), to_underlying (dup_sect_off),
4974                      hex_string (header.signature));
4975         }
4976       *slot = dwo_file ? (void *) dwo_tu : (void *) sig_type;
4977
4978       if (dwarf_read_debug > 1)
4979         fprintf_unfiltered (gdb_stdlog, "  offset 0x%x, signature %s\n",
4980                             to_underlying (sect_off),
4981                             hex_string (header.signature));
4982
4983       info_ptr += length;
4984     }
4985 }
4986
4987 /* Create the hash table of all entries in the .debug_types
4988    (or .debug_types.dwo) section(s).
4989    If reading a DWO file, then DWO_FILE is a pointer to the DWO file object,
4990    otherwise it is NULL.
4991
4992    The result is a pointer to the hash table or NULL if there are no types.
4993
4994    Note: This function processes DWO files only, not DWP files.  */
4995
4996 static void
4997 create_debug_types_hash_table (struct dwo_file *dwo_file,
4998                                VEC (dwarf2_section_info_def) *types,
4999                                htab_t &types_htab)
5000 {
5001   int ix;
5002   struct dwarf2_section_info *section;
5003
5004   if (VEC_empty (dwarf2_section_info_def, types))
5005     return;
5006
5007   for (ix = 0;
5008        VEC_iterate (dwarf2_section_info_def, types, ix, section);
5009        ++ix)
5010     create_debug_type_hash_table (dwo_file, section, types_htab,
5011                                   rcuh_kind::TYPE);
5012 }
5013
5014 /* Create the hash table of all entries in the .debug_types section,
5015    and initialize all_type_units.
5016    The result is zero if there is an error (e.g. missing .debug_types section),
5017    otherwise non-zero.  */
5018
5019 static int
5020 create_all_type_units (struct objfile *objfile)
5021 {
5022   htab_t types_htab = NULL;
5023   struct signatured_type **iter;
5024
5025   create_debug_type_hash_table (NULL, &dwarf2_per_objfile->info, types_htab,
5026                                 rcuh_kind::COMPILE);
5027   create_debug_types_hash_table (NULL, dwarf2_per_objfile->types, types_htab);
5028   if (types_htab == NULL)
5029     {
5030       dwarf2_per_objfile->signatured_types = NULL;
5031       return 0;
5032     }
5033
5034   dwarf2_per_objfile->signatured_types = types_htab;
5035
5036   dwarf2_per_objfile->n_type_units
5037     = dwarf2_per_objfile->n_allocated_type_units
5038     = htab_elements (types_htab);
5039   dwarf2_per_objfile->all_type_units =
5040     XNEWVEC (struct signatured_type *, dwarf2_per_objfile->n_type_units);
5041   iter = &dwarf2_per_objfile->all_type_units[0];
5042   htab_traverse_noresize (types_htab, add_signatured_type_cu_to_table, &iter);
5043   gdb_assert (iter - &dwarf2_per_objfile->all_type_units[0]
5044               == dwarf2_per_objfile->n_type_units);
5045
5046   return 1;
5047 }
5048
5049 /* Add an entry for signature SIG to dwarf2_per_objfile->signatured_types.
5050    If SLOT is non-NULL, it is the entry to use in the hash table.
5051    Otherwise we find one.  */
5052
5053 static struct signatured_type *
5054 add_type_unit (ULONGEST sig, void **slot)
5055 {
5056   struct objfile *objfile = dwarf2_per_objfile->objfile;
5057   int n_type_units = dwarf2_per_objfile->n_type_units;
5058   struct signatured_type *sig_type;
5059
5060   gdb_assert (n_type_units <= dwarf2_per_objfile->n_allocated_type_units);
5061   ++n_type_units;
5062   if (n_type_units > dwarf2_per_objfile->n_allocated_type_units)
5063     {
5064       if (dwarf2_per_objfile->n_allocated_type_units == 0)
5065         dwarf2_per_objfile->n_allocated_type_units = 1;
5066       dwarf2_per_objfile->n_allocated_type_units *= 2;
5067       dwarf2_per_objfile->all_type_units
5068         = XRESIZEVEC (struct signatured_type *,
5069                       dwarf2_per_objfile->all_type_units,
5070                       dwarf2_per_objfile->n_allocated_type_units);
5071       ++dwarf2_per_objfile->tu_stats.nr_all_type_units_reallocs;
5072     }
5073   dwarf2_per_objfile->n_type_units = n_type_units;
5074
5075   sig_type = OBSTACK_ZALLOC (&objfile->objfile_obstack,
5076                              struct signatured_type);
5077   dwarf2_per_objfile->all_type_units[n_type_units - 1] = sig_type;
5078   sig_type->signature = sig;
5079   sig_type->per_cu.is_debug_types = 1;
5080   if (dwarf2_per_objfile->using_index)
5081     {
5082       sig_type->per_cu.v.quick =
5083         OBSTACK_ZALLOC (&objfile->objfile_obstack,
5084                         struct dwarf2_per_cu_quick_data);
5085     }
5086
5087   if (slot == NULL)
5088     {
5089       slot = htab_find_slot (dwarf2_per_objfile->signatured_types,
5090                              sig_type, INSERT);
5091     }
5092   gdb_assert (*slot == NULL);
5093   *slot = sig_type;
5094   /* The rest of sig_type must be filled in by the caller.  */
5095   return sig_type;
5096 }
5097
5098 /* Subroutine of lookup_dwo_signatured_type and lookup_dwp_signatured_type.
5099    Fill in SIG_ENTRY with DWO_ENTRY.  */
5100
5101 static void
5102 fill_in_sig_entry_from_dwo_entry (struct objfile *objfile,
5103                                   struct signatured_type *sig_entry,
5104                                   struct dwo_unit *dwo_entry)
5105 {
5106   /* Make sure we're not clobbering something we don't expect to.  */
5107   gdb_assert (! sig_entry->per_cu.queued);
5108   gdb_assert (sig_entry->per_cu.cu == NULL);
5109   if (dwarf2_per_objfile->using_index)
5110     {
5111       gdb_assert (sig_entry->per_cu.v.quick != NULL);
5112       gdb_assert (sig_entry->per_cu.v.quick->compunit_symtab == NULL);
5113     }
5114   else
5115       gdb_assert (sig_entry->per_cu.v.psymtab == NULL);
5116   gdb_assert (sig_entry->signature == dwo_entry->signature);
5117   gdb_assert (to_underlying (sig_entry->type_offset_in_section) == 0);
5118   gdb_assert (sig_entry->type_unit_group == NULL);
5119   gdb_assert (sig_entry->dwo_unit == NULL);
5120
5121   sig_entry->per_cu.section = dwo_entry->section;
5122   sig_entry->per_cu.sect_off = dwo_entry->sect_off;
5123   sig_entry->per_cu.length = dwo_entry->length;
5124   sig_entry->per_cu.reading_dwo_directly = 1;
5125   sig_entry->per_cu.objfile = objfile;
5126   sig_entry->type_offset_in_tu = dwo_entry->type_offset_in_tu;
5127   sig_entry->dwo_unit = dwo_entry;
5128 }
5129
5130 /* Subroutine of lookup_signatured_type.
5131    If we haven't read the TU yet, create the signatured_type data structure
5132    for a TU to be read in directly from a DWO file, bypassing the stub.
5133    This is the "Stay in DWO Optimization": When there is no DWP file and we're
5134    using .gdb_index, then when reading a CU we want to stay in the DWO file
5135    containing that CU.  Otherwise we could end up reading several other DWO
5136    files (due to comdat folding) to process the transitive closure of all the
5137    mentioned TUs, and that can be slow.  The current DWO file will have every
5138    type signature that it needs.
5139    We only do this for .gdb_index because in the psymtab case we already have
5140    to read all the DWOs to build the type unit groups.  */
5141
5142 static struct signatured_type *
5143 lookup_dwo_signatured_type (struct dwarf2_cu *cu, ULONGEST sig)
5144 {
5145   struct objfile *objfile = dwarf2_per_objfile->objfile;
5146   struct dwo_file *dwo_file;
5147   struct dwo_unit find_dwo_entry, *dwo_entry;
5148   struct signatured_type find_sig_entry, *sig_entry;
5149   void **slot;
5150
5151   gdb_assert (cu->dwo_unit && dwarf2_per_objfile->using_index);
5152
5153   /* If TU skeletons have been removed then we may not have read in any
5154      TUs yet.  */
5155   if (dwarf2_per_objfile->signatured_types == NULL)
5156     {
5157       dwarf2_per_objfile->signatured_types
5158         = allocate_signatured_type_table (objfile);
5159     }
5160
5161   /* We only ever need to read in one copy of a signatured type.
5162      Use the global signatured_types array to do our own comdat-folding
5163      of types.  If this is the first time we're reading this TU, and
5164      the TU has an entry in .gdb_index, replace the recorded data from
5165      .gdb_index with this TU.  */
5166
5167   find_sig_entry.signature = sig;
5168   slot = htab_find_slot (dwarf2_per_objfile->signatured_types,
5169                          &find_sig_entry, INSERT);
5170   sig_entry = (struct signatured_type *) *slot;
5171
5172   /* We can get here with the TU already read, *or* in the process of being
5173      read.  Don't reassign the global entry to point to this DWO if that's
5174      the case.  Also note that if the TU is already being read, it may not
5175      have come from a DWO, the program may be a mix of Fission-compiled
5176      code and non-Fission-compiled code.  */
5177
5178   /* Have we already tried to read this TU?
5179      Note: sig_entry can be NULL if the skeleton TU was removed (thus it
5180      needn't exist in the global table yet).  */
5181   if (sig_entry != NULL && sig_entry->per_cu.tu_read)
5182     return sig_entry;
5183
5184   /* Note: cu->dwo_unit is the dwo_unit that references this TU, not the
5185      dwo_unit of the TU itself.  */
5186   dwo_file = cu->dwo_unit->dwo_file;
5187
5188   /* Ok, this is the first time we're reading this TU.  */
5189   if (dwo_file->tus == NULL)
5190     return NULL;
5191   find_dwo_entry.signature = sig;
5192   dwo_entry = (struct dwo_unit *) htab_find (dwo_file->tus, &find_dwo_entry);
5193   if (dwo_entry == NULL)
5194     return NULL;
5195
5196   /* If the global table doesn't have an entry for this TU, add one.  */
5197   if (sig_entry == NULL)
5198     sig_entry = add_type_unit (sig, slot);
5199
5200   fill_in_sig_entry_from_dwo_entry (objfile, sig_entry, dwo_entry);
5201   sig_entry->per_cu.tu_read = 1;
5202   return sig_entry;
5203 }
5204
5205 /* Subroutine of lookup_signatured_type.
5206    Look up the type for signature SIG, and if we can't find SIG in .gdb_index
5207    then try the DWP file.  If the TU stub (skeleton) has been removed then
5208    it won't be in .gdb_index.  */
5209
5210 static struct signatured_type *
5211 lookup_dwp_signatured_type (struct dwarf2_cu *cu, ULONGEST sig)
5212 {
5213   struct objfile *objfile = dwarf2_per_objfile->objfile;
5214   struct dwp_file *dwp_file = get_dwp_file ();
5215   struct dwo_unit *dwo_entry;
5216   struct signatured_type find_sig_entry, *sig_entry;
5217   void **slot;
5218
5219   gdb_assert (cu->dwo_unit && dwarf2_per_objfile->using_index);
5220   gdb_assert (dwp_file != NULL);
5221
5222   /* If TU skeletons have been removed then we may not have read in any
5223      TUs yet.  */
5224   if (dwarf2_per_objfile->signatured_types == NULL)
5225     {
5226       dwarf2_per_objfile->signatured_types
5227         = allocate_signatured_type_table (objfile);
5228     }
5229
5230   find_sig_entry.signature = sig;
5231   slot = htab_find_slot (dwarf2_per_objfile->signatured_types,
5232                          &find_sig_entry, INSERT);
5233   sig_entry = (struct signatured_type *) *slot;
5234
5235   /* Have we already tried to read this TU?
5236      Note: sig_entry can be NULL if the skeleton TU was removed (thus it
5237      needn't exist in the global table yet).  */
5238   if (sig_entry != NULL)
5239     return sig_entry;
5240
5241   if (dwp_file->tus == NULL)
5242     return NULL;
5243   dwo_entry = lookup_dwo_unit_in_dwp (dwp_file, NULL,
5244                                       sig, 1 /* is_debug_types */);
5245   if (dwo_entry == NULL)
5246     return NULL;
5247
5248   sig_entry = add_type_unit (sig, slot);
5249   fill_in_sig_entry_from_dwo_entry (objfile, sig_entry, dwo_entry);
5250
5251   return sig_entry;
5252 }
5253
5254 /* Lookup a signature based type for DW_FORM_ref_sig8.
5255    Returns NULL if signature SIG is not present in the table.
5256    It is up to the caller to complain about this.  */
5257
5258 static struct signatured_type *
5259 lookup_signatured_type (struct dwarf2_cu *cu, ULONGEST sig)
5260 {
5261   if (cu->dwo_unit
5262       && dwarf2_per_objfile->using_index)
5263     {
5264       /* We're in a DWO/DWP file, and we're using .gdb_index.
5265          These cases require special processing.  */
5266       if (get_dwp_file () == NULL)
5267         return lookup_dwo_signatured_type (cu, sig);
5268       else
5269         return lookup_dwp_signatured_type (cu, sig);
5270     }
5271   else
5272     {
5273       struct signatured_type find_entry, *entry;
5274
5275       if (dwarf2_per_objfile->signatured_types == NULL)
5276         return NULL;
5277       find_entry.signature = sig;
5278       entry = ((struct signatured_type *)
5279                htab_find (dwarf2_per_objfile->signatured_types, &find_entry));
5280       return entry;
5281     }
5282 }
5283 \f
5284 /* Low level DIE reading support.  */
5285
5286 /* Initialize a die_reader_specs struct from a dwarf2_cu struct.  */
5287
5288 static void
5289 init_cu_die_reader (struct die_reader_specs *reader,
5290                     struct dwarf2_cu *cu,
5291                     struct dwarf2_section_info *section,
5292                     struct dwo_file *dwo_file)
5293 {
5294   gdb_assert (section->readin && section->buffer != NULL);
5295   reader->abfd = get_section_bfd_owner (section);
5296   reader->cu = cu;
5297   reader->dwo_file = dwo_file;
5298   reader->die_section = section;
5299   reader->buffer = section->buffer;
5300   reader->buffer_end = section->buffer + section->size;
5301   reader->comp_dir = NULL;
5302 }
5303
5304 /* Subroutine of init_cutu_and_read_dies to simplify it.
5305    Read in the rest of a CU/TU top level DIE from DWO_UNIT.
5306    There's just a lot of work to do, and init_cutu_and_read_dies is big enough
5307    already.
5308
5309    STUB_COMP_UNIT_DIE is for the stub DIE, we copy over certain attributes
5310    from it to the DIE in the DWO.  If NULL we are skipping the stub.
5311    STUB_COMP_DIR is similar to STUB_COMP_UNIT_DIE: When reading a TU directly
5312    from the DWO file, bypassing the stub, it contains the DW_AT_comp_dir
5313    attribute of the referencing CU.  At most one of STUB_COMP_UNIT_DIE and
5314    STUB_COMP_DIR may be non-NULL.
5315    *RESULT_READER,*RESULT_INFO_PTR,*RESULT_COMP_UNIT_DIE,*RESULT_HAS_CHILDREN
5316    are filled in with the info of the DIE from the DWO file.
5317    ABBREV_TABLE_PROVIDED is non-zero if the caller of init_cutu_and_read_dies
5318    provided an abbrev table to use.
5319    The result is non-zero if a valid (non-dummy) DIE was found.  */
5320
5321 static int
5322 read_cutu_die_from_dwo (struct dwarf2_per_cu_data *this_cu,
5323                         struct dwo_unit *dwo_unit,
5324                         int abbrev_table_provided,
5325                         struct die_info *stub_comp_unit_die,
5326                         const char *stub_comp_dir,
5327                         struct die_reader_specs *result_reader,
5328                         const gdb_byte **result_info_ptr,
5329                         struct die_info **result_comp_unit_die,
5330                         int *result_has_children)
5331 {
5332   struct objfile *objfile = dwarf2_per_objfile->objfile;
5333   struct dwarf2_cu *cu = this_cu->cu;
5334   struct dwarf2_section_info *section;
5335   bfd *abfd;
5336   const gdb_byte *begin_info_ptr, *info_ptr;
5337   ULONGEST signature; /* Or dwo_id.  */
5338   struct attribute *comp_dir, *stmt_list, *low_pc, *high_pc, *ranges;
5339   int i,num_extra_attrs;
5340   struct dwarf2_section_info *dwo_abbrev_section;
5341   struct attribute *attr;
5342   struct die_info *comp_unit_die;
5343
5344   /* At most one of these may be provided.  */
5345   gdb_assert ((stub_comp_unit_die != NULL) + (stub_comp_dir != NULL) <= 1);
5346
5347   /* These attributes aren't processed until later:
5348      DW_AT_stmt_list, DW_AT_low_pc, DW_AT_high_pc, DW_AT_ranges.
5349      DW_AT_comp_dir is used now, to find the DWO file, but it is also
5350      referenced later.  However, these attributes are found in the stub
5351      which we won't have later.  In order to not impose this complication
5352      on the rest of the code, we read them here and copy them to the
5353      DWO CU/TU die.  */
5354
5355   stmt_list = NULL;
5356   low_pc = NULL;
5357   high_pc = NULL;
5358   ranges = NULL;
5359   comp_dir = NULL;
5360
5361   if (stub_comp_unit_die != NULL)
5362     {
5363       /* For TUs in DWO files, the DW_AT_stmt_list attribute lives in the
5364          DWO file.  */
5365       if (! this_cu->is_debug_types)
5366         stmt_list = dwarf2_attr (stub_comp_unit_die, DW_AT_stmt_list, cu);
5367       low_pc = dwarf2_attr (stub_comp_unit_die, DW_AT_low_pc, cu);
5368       high_pc = dwarf2_attr (stub_comp_unit_die, DW_AT_high_pc, cu);
5369       ranges = dwarf2_attr (stub_comp_unit_die, DW_AT_ranges, cu);
5370       comp_dir = dwarf2_attr (stub_comp_unit_die, DW_AT_comp_dir, cu);
5371
5372       /* There should be a DW_AT_addr_base attribute here (if needed).
5373          We need the value before we can process DW_FORM_GNU_addr_index.  */
5374       cu->addr_base = 0;
5375       attr = dwarf2_attr (stub_comp_unit_die, DW_AT_GNU_addr_base, cu);
5376       if (attr)
5377         cu->addr_base = DW_UNSND (attr);
5378
5379       /* There should be a DW_AT_ranges_base attribute here (if needed).
5380          We need the value before we can process DW_AT_ranges.  */
5381       cu->ranges_base = 0;
5382       attr = dwarf2_attr (stub_comp_unit_die, DW_AT_GNU_ranges_base, cu);
5383       if (attr)
5384         cu->ranges_base = DW_UNSND (attr);
5385     }
5386   else if (stub_comp_dir != NULL)
5387     {
5388       /* Reconstruct the comp_dir attribute to simplify the code below.  */
5389       comp_dir = XOBNEW (&cu->comp_unit_obstack, struct attribute);
5390       comp_dir->name = DW_AT_comp_dir;
5391       comp_dir->form = DW_FORM_string;
5392       DW_STRING_IS_CANONICAL (comp_dir) = 0;
5393       DW_STRING (comp_dir) = stub_comp_dir;
5394     }
5395
5396   /* Set up for reading the DWO CU/TU.  */
5397   cu->dwo_unit = dwo_unit;
5398   section = dwo_unit->section;
5399   dwarf2_read_section (objfile, section);
5400   abfd = get_section_bfd_owner (section);
5401   begin_info_ptr = info_ptr = (section->buffer
5402                                + to_underlying (dwo_unit->sect_off));
5403   dwo_abbrev_section = &dwo_unit->dwo_file->sections.abbrev;
5404   init_cu_die_reader (result_reader, cu, section, dwo_unit->dwo_file);
5405
5406   if (this_cu->is_debug_types)
5407     {
5408       struct signatured_type *sig_type = (struct signatured_type *) this_cu;
5409
5410       info_ptr = read_and_check_comp_unit_head (&cu->header, section,
5411                                                 dwo_abbrev_section,
5412                                                 info_ptr, rcuh_kind::TYPE);
5413       /* This is not an assert because it can be caused by bad debug info.  */
5414       if (sig_type->signature != cu->header.signature)
5415         {
5416           error (_("Dwarf Error: signature mismatch %s vs %s while reading"
5417                    " TU at offset 0x%x [in module %s]"),
5418                  hex_string (sig_type->signature),
5419                  hex_string (cu->header.signature),
5420                  to_underlying (dwo_unit->sect_off),
5421                  bfd_get_filename (abfd));
5422         }
5423       gdb_assert (dwo_unit->sect_off == cu->header.sect_off);
5424       /* For DWOs coming from DWP files, we don't know the CU length
5425          nor the type's offset in the TU until now.  */
5426       dwo_unit->length = get_cu_length (&cu->header);
5427       dwo_unit->type_offset_in_tu = cu->header.type_cu_offset_in_tu;
5428
5429       /* Establish the type offset that can be used to lookup the type.
5430          For DWO files, we don't know it until now.  */
5431       sig_type->type_offset_in_section
5432         = dwo_unit->sect_off + to_underlying (dwo_unit->type_offset_in_tu);
5433     }
5434   else
5435     {
5436       info_ptr = read_and_check_comp_unit_head (&cu->header, section,
5437                                                 dwo_abbrev_section,
5438                                                 info_ptr, rcuh_kind::COMPILE);
5439       gdb_assert (dwo_unit->sect_off == cu->header.sect_off);
5440       /* For DWOs coming from DWP files, we don't know the CU length
5441          until now.  */
5442       dwo_unit->length = get_cu_length (&cu->header);
5443     }
5444
5445   /* Replace the CU's original abbrev table with the DWO's.
5446      Reminder: We can't read the abbrev table until we've read the header.  */
5447   if (abbrev_table_provided)
5448     {
5449       /* Don't free the provided abbrev table, the caller of
5450          init_cutu_and_read_dies owns it.  */
5451       dwarf2_read_abbrevs (cu, dwo_abbrev_section);
5452       /* Ensure the DWO abbrev table gets freed.  */
5453       make_cleanup (dwarf2_free_abbrev_table, cu);
5454     }
5455   else
5456     {
5457       dwarf2_free_abbrev_table (cu);
5458       dwarf2_read_abbrevs (cu, dwo_abbrev_section);
5459       /* Leave any existing abbrev table cleanup as is.  */
5460     }
5461
5462   /* Read in the die, but leave space to copy over the attributes
5463      from the stub.  This has the benefit of simplifying the rest of
5464      the code - all the work to maintain the illusion of a single
5465      DW_TAG_{compile,type}_unit DIE is done here.  */
5466   num_extra_attrs = ((stmt_list != NULL)
5467                      + (low_pc != NULL)
5468                      + (high_pc != NULL)
5469                      + (ranges != NULL)
5470                      + (comp_dir != NULL));
5471   info_ptr = read_full_die_1 (result_reader, result_comp_unit_die, info_ptr,
5472                               result_has_children, num_extra_attrs);
5473
5474   /* Copy over the attributes from the stub to the DIE we just read in.  */
5475   comp_unit_die = *result_comp_unit_die;
5476   i = comp_unit_die->num_attrs;
5477   if (stmt_list != NULL)
5478     comp_unit_die->attrs[i++] = *stmt_list;
5479   if (low_pc != NULL)
5480     comp_unit_die->attrs[i++] = *low_pc;
5481   if (high_pc != NULL)
5482     comp_unit_die->attrs[i++] = *high_pc;
5483   if (ranges != NULL)
5484     comp_unit_die->attrs[i++] = *ranges;
5485   if (comp_dir != NULL)
5486     comp_unit_die->attrs[i++] = *comp_dir;
5487   comp_unit_die->num_attrs += num_extra_attrs;
5488
5489   if (dwarf_die_debug)
5490     {
5491       fprintf_unfiltered (gdb_stdlog,
5492                           "Read die from %s@0x%x of %s:\n",
5493                           get_section_name (section),
5494                           (unsigned) (begin_info_ptr - section->buffer),
5495                           bfd_get_filename (abfd));
5496       dump_die (comp_unit_die, dwarf_die_debug);
5497     }
5498
5499   /* Save the comp_dir attribute.  If there is no DWP file then we'll read
5500      TUs by skipping the stub and going directly to the entry in the DWO file.
5501      However, skipping the stub means we won't get DW_AT_comp_dir, so we have
5502      to get it via circuitous means.  Blech.  */
5503   if (comp_dir != NULL)
5504     result_reader->comp_dir = DW_STRING (comp_dir);
5505
5506   /* Skip dummy compilation units.  */
5507   if (info_ptr >= begin_info_ptr + dwo_unit->length
5508       || peek_abbrev_code (abfd, info_ptr) == 0)
5509     return 0;
5510
5511   *result_info_ptr = info_ptr;
5512   return 1;
5513 }
5514
5515 /* Subroutine of init_cutu_and_read_dies to simplify it.
5516    Look up the DWO unit specified by COMP_UNIT_DIE of THIS_CU.
5517    Returns NULL if the specified DWO unit cannot be found.  */
5518
5519 static struct dwo_unit *
5520 lookup_dwo_unit (struct dwarf2_per_cu_data *this_cu,
5521                  struct die_info *comp_unit_die)
5522 {
5523   struct dwarf2_cu *cu = this_cu->cu;
5524   struct attribute *attr;
5525   ULONGEST signature;
5526   struct dwo_unit *dwo_unit;
5527   const char *comp_dir, *dwo_name;
5528
5529   gdb_assert (cu != NULL);
5530
5531   /* Yeah, we look dwo_name up again, but it simplifies the code.  */
5532   dwo_name = dwarf2_string_attr (comp_unit_die, DW_AT_GNU_dwo_name, cu);
5533   comp_dir = dwarf2_string_attr (comp_unit_die, DW_AT_comp_dir, cu);
5534
5535   if (this_cu->is_debug_types)
5536     {
5537       struct signatured_type *sig_type;
5538
5539       /* Since this_cu is the first member of struct signatured_type,
5540          we can go from a pointer to one to a pointer to the other.  */
5541       sig_type = (struct signatured_type *) this_cu;
5542       signature = sig_type->signature;
5543       dwo_unit = lookup_dwo_type_unit (sig_type, dwo_name, comp_dir);
5544     }
5545   else
5546     {
5547       struct attribute *attr;
5548
5549       attr = dwarf2_attr (comp_unit_die, DW_AT_GNU_dwo_id, cu);
5550       if (! attr)
5551         error (_("Dwarf Error: missing dwo_id for dwo_name %s"
5552                  " [in module %s]"),
5553                dwo_name, objfile_name (this_cu->objfile));
5554       signature = DW_UNSND (attr);
5555       dwo_unit = lookup_dwo_comp_unit (this_cu, dwo_name, comp_dir,
5556                                        signature);
5557     }
5558
5559   return dwo_unit;
5560 }
5561
5562 /* Subroutine of init_cutu_and_read_dies to simplify it.
5563    See it for a description of the parameters.
5564    Read a TU directly from a DWO file, bypassing the stub.
5565
5566    Note: This function could be a little bit simpler if we shared cleanups
5567    with our caller, init_cutu_and_read_dies.  That's generally a fragile thing
5568    to do, so we keep this function self-contained.  Or we could move this
5569    into our caller, but it's complex enough already.  */
5570
5571 static void
5572 init_tu_and_read_dwo_dies (struct dwarf2_per_cu_data *this_cu,
5573                            int use_existing_cu, int keep,
5574                            die_reader_func_ftype *die_reader_func,
5575                            void *data)
5576 {
5577   struct dwarf2_cu *cu;
5578   struct signatured_type *sig_type;
5579   struct cleanup *cleanups, *free_cu_cleanup = NULL;
5580   struct die_reader_specs reader;
5581   const gdb_byte *info_ptr;
5582   struct die_info *comp_unit_die;
5583   int has_children;
5584
5585   /* Verify we can do the following downcast, and that we have the
5586      data we need.  */
5587   gdb_assert (this_cu->is_debug_types && this_cu->reading_dwo_directly);
5588   sig_type = (struct signatured_type *) this_cu;
5589   gdb_assert (sig_type->dwo_unit != NULL);
5590
5591   cleanups = make_cleanup (null_cleanup, NULL);
5592
5593   if (use_existing_cu && this_cu->cu != NULL)
5594     {
5595       gdb_assert (this_cu->cu->dwo_unit == sig_type->dwo_unit);
5596       cu = this_cu->cu;
5597       /* There's no need to do the rereading_dwo_cu handling that
5598          init_cutu_and_read_dies does since we don't read the stub.  */
5599     }
5600   else
5601     {
5602       /* If !use_existing_cu, this_cu->cu must be NULL.  */
5603       gdb_assert (this_cu->cu == NULL);
5604       cu = XNEW (struct dwarf2_cu);
5605       init_one_comp_unit (cu, this_cu);
5606       /* If an error occurs while loading, release our storage.  */
5607       free_cu_cleanup = make_cleanup (free_heap_comp_unit, cu);
5608     }
5609
5610   /* A future optimization, if needed, would be to use an existing
5611      abbrev table.  When reading DWOs with skeletonless TUs, all the TUs
5612      could share abbrev tables.  */
5613
5614   if (read_cutu_die_from_dwo (this_cu, sig_type->dwo_unit,
5615                               0 /* abbrev_table_provided */,
5616                               NULL /* stub_comp_unit_die */,
5617                               sig_type->dwo_unit->dwo_file->comp_dir,
5618                               &reader, &info_ptr,
5619                               &comp_unit_die, &has_children) == 0)
5620     {
5621       /* Dummy die.  */
5622       do_cleanups (cleanups);
5623       return;
5624     }
5625
5626   /* All the "real" work is done here.  */
5627   die_reader_func (&reader, info_ptr, comp_unit_die, has_children, data);
5628
5629   /* This duplicates the code in init_cutu_and_read_dies,
5630      but the alternative is making the latter more complex.
5631      This function is only for the special case of using DWO files directly:
5632      no point in overly complicating the general case just to handle this.  */
5633   if (free_cu_cleanup != NULL)
5634     {
5635       if (keep)
5636         {
5637           /* We've successfully allocated this compilation unit.  Let our
5638              caller clean it up when finished with it.  */
5639           discard_cleanups (free_cu_cleanup);
5640
5641           /* We can only discard free_cu_cleanup and all subsequent cleanups.
5642              So we have to manually free the abbrev table.  */
5643           dwarf2_free_abbrev_table (cu);
5644
5645           /* Link this CU into read_in_chain.  */
5646           this_cu->cu->read_in_chain = dwarf2_per_objfile->read_in_chain;
5647           dwarf2_per_objfile->read_in_chain = this_cu;
5648         }
5649       else
5650         do_cleanups (free_cu_cleanup);
5651     }
5652
5653   do_cleanups (cleanups);
5654 }
5655
5656 /* Initialize a CU (or TU) and read its DIEs.
5657    If the CU defers to a DWO file, read the DWO file as well.
5658
5659    ABBREV_TABLE, if non-NULL, is the abbreviation table to use.
5660    Otherwise the table specified in the comp unit header is read in and used.
5661    This is an optimization for when we already have the abbrev table.
5662
5663    If USE_EXISTING_CU is non-zero, and THIS_CU->cu is non-NULL, then use it.
5664    Otherwise, a new CU is allocated with xmalloc.
5665
5666    If KEEP is non-zero, then if we allocated a dwarf2_cu we add it to
5667    read_in_chain.  Otherwise the dwarf2_cu data is freed at the end.
5668
5669    WARNING: If THIS_CU is a "dummy CU" (used as filler by the incremental
5670    linker) then DIE_READER_FUNC will not get called.  */
5671
5672 static void
5673 init_cutu_and_read_dies (struct dwarf2_per_cu_data *this_cu,
5674                          struct abbrev_table *abbrev_table,
5675                          int use_existing_cu, int keep,
5676                          die_reader_func_ftype *die_reader_func,
5677                          void *data)
5678 {
5679   struct objfile *objfile = dwarf2_per_objfile->objfile;
5680   struct dwarf2_section_info *section = this_cu->section;
5681   bfd *abfd = get_section_bfd_owner (section);
5682   struct dwarf2_cu *cu;
5683   const gdb_byte *begin_info_ptr, *info_ptr;
5684   struct die_reader_specs reader;
5685   struct die_info *comp_unit_die;
5686   int has_children;
5687   struct attribute *attr;
5688   struct cleanup *cleanups, *free_cu_cleanup = NULL;
5689   struct signatured_type *sig_type = NULL;
5690   struct dwarf2_section_info *abbrev_section;
5691   /* Non-zero if CU currently points to a DWO file and we need to
5692      reread it.  When this happens we need to reread the skeleton die
5693      before we can reread the DWO file (this only applies to CUs, not TUs).  */
5694   int rereading_dwo_cu = 0;
5695
5696   if (dwarf_die_debug)
5697     fprintf_unfiltered (gdb_stdlog, "Reading %s unit at offset 0x%x\n",
5698                         this_cu->is_debug_types ? "type" : "comp",
5699                         to_underlying (this_cu->sect_off));
5700
5701   if (use_existing_cu)
5702     gdb_assert (keep);
5703
5704   /* If we're reading a TU directly from a DWO file, including a virtual DWO
5705      file (instead of going through the stub), short-circuit all of this.  */
5706   if (this_cu->reading_dwo_directly)
5707     {
5708       /* Narrow down the scope of possibilities to have to understand.  */
5709       gdb_assert (this_cu->is_debug_types);
5710       gdb_assert (abbrev_table == NULL);
5711       init_tu_and_read_dwo_dies (this_cu, use_existing_cu, keep,
5712                                  die_reader_func, data);
5713       return;
5714     }
5715
5716   cleanups = make_cleanup (null_cleanup, NULL);
5717
5718   /* This is cheap if the section is already read in.  */
5719   dwarf2_read_section (objfile, section);
5720
5721   begin_info_ptr = info_ptr = section->buffer + to_underlying (this_cu->sect_off);
5722
5723   abbrev_section = get_abbrev_section_for_cu (this_cu);
5724
5725   if (use_existing_cu && this_cu->cu != NULL)
5726     {
5727       cu = this_cu->cu;
5728       /* If this CU is from a DWO file we need to start over, we need to
5729          refetch the attributes from the skeleton CU.
5730          This could be optimized by retrieving those attributes from when we
5731          were here the first time: the previous comp_unit_die was stored in
5732          comp_unit_obstack.  But there's no data yet that we need this
5733          optimization.  */
5734       if (cu->dwo_unit != NULL)
5735         rereading_dwo_cu = 1;
5736     }
5737   else
5738     {
5739       /* If !use_existing_cu, this_cu->cu must be NULL.  */
5740       gdb_assert (this_cu->cu == NULL);
5741       cu = XNEW (struct dwarf2_cu);
5742       init_one_comp_unit (cu, this_cu);
5743       /* If an error occurs while loading, release our storage.  */
5744       free_cu_cleanup = make_cleanup (free_heap_comp_unit, cu);
5745     }
5746
5747   /* Get the header.  */
5748   if (to_underlying (cu->header.first_die_cu_offset) != 0 && !rereading_dwo_cu)
5749     {
5750       /* We already have the header, there's no need to read it in again.  */
5751       info_ptr += to_underlying (cu->header.first_die_cu_offset);
5752     }
5753   else
5754     {
5755       if (this_cu->is_debug_types)
5756         {
5757           info_ptr = read_and_check_comp_unit_head (&cu->header, section,
5758                                                     abbrev_section, info_ptr,
5759                                                     rcuh_kind::TYPE);
5760
5761           /* Since per_cu is the first member of struct signatured_type,
5762              we can go from a pointer to one to a pointer to the other.  */
5763           sig_type = (struct signatured_type *) this_cu;
5764           gdb_assert (sig_type->signature == cu->header.signature);
5765           gdb_assert (sig_type->type_offset_in_tu
5766                       == cu->header.type_cu_offset_in_tu);
5767           gdb_assert (this_cu->sect_off == cu->header.sect_off);
5768
5769           /* LENGTH has not been set yet for type units if we're
5770              using .gdb_index.  */
5771           this_cu->length = get_cu_length (&cu->header);
5772
5773           /* Establish the type offset that can be used to lookup the type.  */
5774           sig_type->type_offset_in_section =
5775             this_cu->sect_off + to_underlying (sig_type->type_offset_in_tu);
5776
5777           this_cu->dwarf_version = cu->header.version;
5778         }
5779       else
5780         {
5781           info_ptr = read_and_check_comp_unit_head (&cu->header, section,
5782                                                     abbrev_section,
5783                                                     info_ptr,
5784                                                     rcuh_kind::COMPILE);
5785
5786           gdb_assert (this_cu->sect_off == cu->header.sect_off);
5787           gdb_assert (this_cu->length == get_cu_length (&cu->header));
5788           this_cu->dwarf_version = cu->header.version;
5789         }
5790     }
5791
5792   /* Skip dummy compilation units.  */
5793   if (info_ptr >= begin_info_ptr + this_cu->length
5794       || peek_abbrev_code (abfd, info_ptr) == 0)
5795     {
5796       do_cleanups (cleanups);
5797       return;
5798     }
5799
5800   /* If we don't have them yet, read the abbrevs for this compilation unit.
5801      And if we need to read them now, make sure they're freed when we're
5802      done.  Note that it's important that if the CU had an abbrev table
5803      on entry we don't free it when we're done: Somewhere up the call stack
5804      it may be in use.  */
5805   if (abbrev_table != NULL)
5806     {
5807       gdb_assert (cu->abbrev_table == NULL);
5808       gdb_assert (cu->header.abbrev_sect_off == abbrev_table->sect_off);
5809       cu->abbrev_table = abbrev_table;
5810     }
5811   else if (cu->abbrev_table == NULL)
5812     {
5813       dwarf2_read_abbrevs (cu, abbrev_section);
5814       make_cleanup (dwarf2_free_abbrev_table, cu);
5815     }
5816   else if (rereading_dwo_cu)
5817     {
5818       dwarf2_free_abbrev_table (cu);
5819       dwarf2_read_abbrevs (cu, abbrev_section);
5820     }
5821
5822   /* Read the top level CU/TU die.  */
5823   init_cu_die_reader (&reader, cu, section, NULL);
5824   info_ptr = read_full_die (&reader, &comp_unit_die, info_ptr, &has_children);
5825
5826   /* If we are in a DWO stub, process it and then read in the "real" CU/TU
5827      from the DWO file.
5828      Note that if USE_EXISTING_OK != 0, and THIS_CU->cu already contains a
5829      DWO CU, that this test will fail (the attribute will not be present).  */
5830   attr = dwarf2_attr (comp_unit_die, DW_AT_GNU_dwo_name, cu);
5831   if (attr)
5832     {
5833       struct dwo_unit *dwo_unit;
5834       struct die_info *dwo_comp_unit_die;
5835
5836       if (has_children)
5837         {
5838           complaint (&symfile_complaints,
5839                      _("compilation unit with DW_AT_GNU_dwo_name"
5840                        " has children (offset 0x%x) [in module %s]"),
5841                      to_underlying (this_cu->sect_off), bfd_get_filename (abfd));
5842         }
5843       dwo_unit = lookup_dwo_unit (this_cu, comp_unit_die);
5844       if (dwo_unit != NULL)
5845         {
5846           if (read_cutu_die_from_dwo (this_cu, dwo_unit,
5847                                       abbrev_table != NULL,
5848                                       comp_unit_die, NULL,
5849                                       &reader, &info_ptr,
5850                                       &dwo_comp_unit_die, &has_children) == 0)
5851             {
5852               /* Dummy die.  */
5853               do_cleanups (cleanups);
5854               return;
5855             }
5856           comp_unit_die = dwo_comp_unit_die;
5857         }
5858       else
5859         {
5860           /* Yikes, we couldn't find the rest of the DIE, we only have
5861              the stub.  A complaint has already been logged.  There's
5862              not much more we can do except pass on the stub DIE to
5863              die_reader_func.  We don't want to throw an error on bad
5864              debug info.  */
5865         }
5866     }
5867
5868   /* All of the above is setup for this call.  Yikes.  */
5869   die_reader_func (&reader, info_ptr, comp_unit_die, has_children, data);
5870
5871   /* Done, clean up.  */
5872   if (free_cu_cleanup != NULL)
5873     {
5874       if (keep)
5875         {
5876           /* We've successfully allocated this compilation unit.  Let our
5877              caller clean it up when finished with it.  */
5878           discard_cleanups (free_cu_cleanup);
5879
5880           /* We can only discard free_cu_cleanup and all subsequent cleanups.
5881              So we have to manually free the abbrev table.  */
5882           dwarf2_free_abbrev_table (cu);
5883
5884           /* Link this CU into read_in_chain.  */
5885           this_cu->cu->read_in_chain = dwarf2_per_objfile->read_in_chain;
5886           dwarf2_per_objfile->read_in_chain = this_cu;
5887         }
5888       else
5889         do_cleanups (free_cu_cleanup);
5890     }
5891
5892   do_cleanups (cleanups);
5893 }
5894
5895 /* Read CU/TU THIS_CU but do not follow DW_AT_GNU_dwo_name if present.
5896    DWO_FILE, if non-NULL, is the DWO file to read (the caller is assumed
5897    to have already done the lookup to find the DWO file).
5898
5899    The caller is required to fill in THIS_CU->section, THIS_CU->offset, and
5900    THIS_CU->is_debug_types, but nothing else.
5901
5902    We fill in THIS_CU->length.
5903
5904    WARNING: If THIS_CU is a "dummy CU" (used as filler by the incremental
5905    linker) then DIE_READER_FUNC will not get called.
5906
5907    THIS_CU->cu is always freed when done.
5908    This is done in order to not leave THIS_CU->cu in a state where we have
5909    to care whether it refers to the "main" CU or the DWO CU.  */
5910
5911 static void
5912 init_cutu_and_read_dies_no_follow (struct dwarf2_per_cu_data *this_cu,
5913                                    struct dwo_file *dwo_file,
5914                                    die_reader_func_ftype *die_reader_func,
5915                                    void *data)
5916 {
5917   struct objfile *objfile = dwarf2_per_objfile->objfile;
5918   struct dwarf2_section_info *section = this_cu->section;
5919   bfd *abfd = get_section_bfd_owner (section);
5920   struct dwarf2_section_info *abbrev_section;
5921   struct dwarf2_cu cu;
5922   const gdb_byte *begin_info_ptr, *info_ptr;
5923   struct die_reader_specs reader;
5924   struct cleanup *cleanups;
5925   struct die_info *comp_unit_die;
5926   int has_children;
5927
5928   if (dwarf_die_debug)
5929     fprintf_unfiltered (gdb_stdlog, "Reading %s unit at offset 0x%x\n",
5930                         this_cu->is_debug_types ? "type" : "comp",
5931                         to_underlying (this_cu->sect_off));
5932
5933   gdb_assert (this_cu->cu == NULL);
5934
5935   abbrev_section = (dwo_file != NULL
5936                     ? &dwo_file->sections.abbrev
5937                     : get_abbrev_section_for_cu (this_cu));
5938
5939   /* This is cheap if the section is already read in.  */
5940   dwarf2_read_section (objfile, section);
5941
5942   init_one_comp_unit (&cu, this_cu);
5943
5944   cleanups = make_cleanup (free_stack_comp_unit, &cu);
5945
5946   begin_info_ptr = info_ptr = section->buffer + to_underlying (this_cu->sect_off);
5947   info_ptr = read_and_check_comp_unit_head (&cu.header, section,
5948                                             abbrev_section, info_ptr,
5949                                             (this_cu->is_debug_types
5950                                              ? rcuh_kind::TYPE
5951                                              : rcuh_kind::COMPILE));
5952
5953   this_cu->length = get_cu_length (&cu.header);
5954
5955   /* Skip dummy compilation units.  */
5956   if (info_ptr >= begin_info_ptr + this_cu->length
5957       || peek_abbrev_code (abfd, info_ptr) == 0)
5958     {
5959       do_cleanups (cleanups);
5960       return;
5961     }
5962
5963   dwarf2_read_abbrevs (&cu, abbrev_section);
5964   make_cleanup (dwarf2_free_abbrev_table, &cu);
5965
5966   init_cu_die_reader (&reader, &cu, section, dwo_file);
5967   info_ptr = read_full_die (&reader, &comp_unit_die, info_ptr, &has_children);
5968
5969   die_reader_func (&reader, info_ptr, comp_unit_die, has_children, data);
5970
5971   do_cleanups (cleanups);
5972 }
5973
5974 /* Read a CU/TU, except that this does not look for DW_AT_GNU_dwo_name and
5975    does not lookup the specified DWO file.
5976    This cannot be used to read DWO files.
5977
5978    THIS_CU->cu is always freed when done.
5979    This is done in order to not leave THIS_CU->cu in a state where we have
5980    to care whether it refers to the "main" CU or the DWO CU.
5981    We can revisit this if the data shows there's a performance issue.  */
5982
5983 static void
5984 init_cutu_and_read_dies_simple (struct dwarf2_per_cu_data *this_cu,
5985                                 die_reader_func_ftype *die_reader_func,
5986                                 void *data)
5987 {
5988   init_cutu_and_read_dies_no_follow (this_cu, NULL, die_reader_func, data);
5989 }
5990 \f
5991 /* Type Unit Groups.
5992
5993    Type Unit Groups are a way to collapse the set of all TUs (type units) into
5994    a more manageable set.  The grouping is done by DW_AT_stmt_list entry
5995    so that all types coming from the same compilation (.o file) are grouped
5996    together.  A future step could be to put the types in the same symtab as
5997    the CU the types ultimately came from.  */
5998
5999 static hashval_t
6000 hash_type_unit_group (const void *item)
6001 {
6002   const struct type_unit_group *tu_group
6003     = (const struct type_unit_group *) item;
6004
6005   return hash_stmt_list_entry (&tu_group->hash);
6006 }
6007
6008 static int
6009 eq_type_unit_group (const void *item_lhs, const void *item_rhs)
6010 {
6011   const struct type_unit_group *lhs = (const struct type_unit_group *) item_lhs;
6012   const struct type_unit_group *rhs = (const struct type_unit_group *) item_rhs;
6013
6014   return eq_stmt_list_entry (&lhs->hash, &rhs->hash);
6015 }
6016
6017 /* Allocate a hash table for type unit groups.  */
6018
6019 static htab_t
6020 allocate_type_unit_groups_table (void)
6021 {
6022   return htab_create_alloc_ex (3,
6023                                hash_type_unit_group,
6024                                eq_type_unit_group,
6025                                NULL,
6026                                &dwarf2_per_objfile->objfile->objfile_obstack,
6027                                hashtab_obstack_allocate,
6028                                dummy_obstack_deallocate);
6029 }
6030
6031 /* Type units that don't have DW_AT_stmt_list are grouped into their own
6032    partial symtabs.  We combine several TUs per psymtab to not let the size
6033    of any one psymtab grow too big.  */
6034 #define NO_STMT_LIST_TYPE_UNIT_PSYMTAB (1 << 31)
6035 #define NO_STMT_LIST_TYPE_UNIT_PSYMTAB_SIZE 10
6036
6037 /* Helper routine for get_type_unit_group.
6038    Create the type_unit_group object used to hold one or more TUs.  */
6039
6040 static struct type_unit_group *
6041 create_type_unit_group (struct dwarf2_cu *cu, sect_offset line_offset_struct)
6042 {
6043   struct objfile *objfile = dwarf2_per_objfile->objfile;
6044   struct dwarf2_per_cu_data *per_cu;
6045   struct type_unit_group *tu_group;
6046
6047   tu_group = OBSTACK_ZALLOC (&objfile->objfile_obstack,
6048                              struct type_unit_group);
6049   per_cu = &tu_group->per_cu;
6050   per_cu->objfile = objfile;
6051
6052   if (dwarf2_per_objfile->using_index)
6053     {
6054       per_cu->v.quick = OBSTACK_ZALLOC (&objfile->objfile_obstack,
6055                                         struct dwarf2_per_cu_quick_data);
6056     }
6057   else
6058     {
6059       unsigned int line_offset = to_underlying (line_offset_struct);
6060       struct partial_symtab *pst;
6061       char *name;
6062
6063       /* Give the symtab a useful name for debug purposes.  */
6064       if ((line_offset & NO_STMT_LIST_TYPE_UNIT_PSYMTAB) != 0)
6065         name = xstrprintf ("<type_units_%d>",
6066                            (line_offset & ~NO_STMT_LIST_TYPE_UNIT_PSYMTAB));
6067       else
6068         name = xstrprintf ("<type_units_at_0x%x>", line_offset);
6069
6070       pst = create_partial_symtab (per_cu, name);
6071       pst->anonymous = 1;
6072
6073       xfree (name);
6074     }
6075
6076   tu_group->hash.dwo_unit = cu->dwo_unit;
6077   tu_group->hash.line_sect_off = line_offset_struct;
6078
6079   return tu_group;
6080 }
6081
6082 /* Look up the type_unit_group for type unit CU, and create it if necessary.
6083    STMT_LIST is a DW_AT_stmt_list attribute.  */
6084
6085 static struct type_unit_group *
6086 get_type_unit_group (struct dwarf2_cu *cu, const struct attribute *stmt_list)
6087 {
6088   struct tu_stats *tu_stats = &dwarf2_per_objfile->tu_stats;
6089   struct type_unit_group *tu_group;
6090   void **slot;
6091   unsigned int line_offset;
6092   struct type_unit_group type_unit_group_for_lookup;
6093
6094   if (dwarf2_per_objfile->type_unit_groups == NULL)
6095     {
6096       dwarf2_per_objfile->type_unit_groups =
6097         allocate_type_unit_groups_table ();
6098     }
6099
6100   /* Do we need to create a new group, or can we use an existing one?  */
6101
6102   if (stmt_list)
6103     {
6104       line_offset = DW_UNSND (stmt_list);
6105       ++tu_stats->nr_symtab_sharers;
6106     }
6107   else
6108     {
6109       /* Ugh, no stmt_list.  Rare, but we have to handle it.
6110          We can do various things here like create one group per TU or
6111          spread them over multiple groups to split up the expansion work.
6112          To avoid worst case scenarios (too many groups or too large groups)
6113          we, umm, group them in bunches.  */
6114       line_offset = (NO_STMT_LIST_TYPE_UNIT_PSYMTAB
6115                      | (tu_stats->nr_stmt_less_type_units
6116                         / NO_STMT_LIST_TYPE_UNIT_PSYMTAB_SIZE));
6117       ++tu_stats->nr_stmt_less_type_units;
6118     }
6119
6120   type_unit_group_for_lookup.hash.dwo_unit = cu->dwo_unit;
6121   type_unit_group_for_lookup.hash.line_sect_off = (sect_offset) line_offset;
6122   slot = htab_find_slot (dwarf2_per_objfile->type_unit_groups,
6123                          &type_unit_group_for_lookup, INSERT);
6124   if (*slot != NULL)
6125     {
6126       tu_group = (struct type_unit_group *) *slot;
6127       gdb_assert (tu_group != NULL);
6128     }
6129   else
6130     {
6131       sect_offset line_offset_struct = (sect_offset) line_offset;
6132       tu_group = create_type_unit_group (cu, line_offset_struct);
6133       *slot = tu_group;
6134       ++tu_stats->nr_symtabs;
6135     }
6136
6137   return tu_group;
6138 }
6139 \f
6140 /* Partial symbol tables.  */
6141
6142 /* Create a psymtab named NAME and assign it to PER_CU.
6143
6144    The caller must fill in the following details:
6145    dirname, textlow, texthigh.  */
6146
6147 static struct partial_symtab *
6148 create_partial_symtab (struct dwarf2_per_cu_data *per_cu, const char *name)
6149 {
6150   struct objfile *objfile = per_cu->objfile;
6151   struct partial_symtab *pst;
6152
6153   pst = start_psymtab_common (objfile, name, 0,
6154                               objfile->global_psymbols.next,
6155                               objfile->static_psymbols.next);
6156
6157   pst->psymtabs_addrmap_supported = 1;
6158
6159   /* This is the glue that links PST into GDB's symbol API.  */
6160   pst->read_symtab_private = per_cu;
6161   pst->read_symtab = dwarf2_read_symtab;
6162   per_cu->v.psymtab = pst;
6163
6164   return pst;
6165 }
6166
6167 /* The DATA object passed to process_psymtab_comp_unit_reader has this
6168    type.  */
6169
6170 struct process_psymtab_comp_unit_data
6171 {
6172   /* True if we are reading a DW_TAG_partial_unit.  */
6173
6174   int want_partial_unit;
6175
6176   /* The "pretend" language that is used if the CU doesn't declare a
6177      language.  */
6178
6179   enum language pretend_language;
6180 };
6181
6182 /* die_reader_func for process_psymtab_comp_unit.  */
6183
6184 static void
6185 process_psymtab_comp_unit_reader (const struct die_reader_specs *reader,
6186                                   const gdb_byte *info_ptr,
6187                                   struct die_info *comp_unit_die,
6188                                   int has_children,
6189                                   void *data)
6190 {
6191   struct dwarf2_cu *cu = reader->cu;
6192   struct objfile *objfile = cu->objfile;
6193   struct gdbarch *gdbarch = get_objfile_arch (objfile);
6194   struct dwarf2_per_cu_data *per_cu = cu->per_cu;
6195   CORE_ADDR baseaddr;
6196   CORE_ADDR best_lowpc = 0, best_highpc = 0;
6197   struct partial_symtab *pst;
6198   enum pc_bounds_kind cu_bounds_kind;
6199   const char *filename;
6200   struct process_psymtab_comp_unit_data *info
6201     = (struct process_psymtab_comp_unit_data *) data;
6202
6203   if (comp_unit_die->tag == DW_TAG_partial_unit && !info->want_partial_unit)
6204     return;
6205
6206   gdb_assert (! per_cu->is_debug_types);
6207
6208   prepare_one_comp_unit (cu, comp_unit_die, info->pretend_language);
6209
6210   cu->list_in_scope = &file_symbols;
6211
6212   /* Allocate a new partial symbol table structure.  */
6213   filename = dwarf2_string_attr (comp_unit_die, DW_AT_name, cu);
6214   if (filename == NULL)
6215     filename = "";
6216
6217   pst = create_partial_symtab (per_cu, filename);
6218
6219   /* This must be done before calling dwarf2_build_include_psymtabs.  */
6220   pst->dirname = dwarf2_string_attr (comp_unit_die, DW_AT_comp_dir, cu);
6221
6222   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
6223
6224   dwarf2_find_base_address (comp_unit_die, cu);
6225
6226   /* Possibly set the default values of LOWPC and HIGHPC from
6227      `DW_AT_ranges'.  */
6228   cu_bounds_kind = dwarf2_get_pc_bounds (comp_unit_die, &best_lowpc,
6229                                          &best_highpc, cu, pst);
6230   if (cu_bounds_kind == PC_BOUNDS_HIGH_LOW && best_lowpc < best_highpc)
6231     /* Store the contiguous range if it is not empty; it can be empty for
6232        CUs with no code.  */
6233     addrmap_set_empty (objfile->psymtabs_addrmap,
6234                        gdbarch_adjust_dwarf2_addr (gdbarch,
6235                                                    best_lowpc + baseaddr),
6236                        gdbarch_adjust_dwarf2_addr (gdbarch,
6237                                                    best_highpc + baseaddr) - 1,
6238                        pst);
6239
6240   /* Check if comp unit has_children.
6241      If so, read the rest of the partial symbols from this comp unit.
6242      If not, there's no more debug_info for this comp unit.  */
6243   if (has_children)
6244     {
6245       struct partial_die_info *first_die;
6246       CORE_ADDR lowpc, highpc;
6247
6248       lowpc = ((CORE_ADDR) -1);
6249       highpc = ((CORE_ADDR) 0);
6250
6251       first_die = load_partial_dies (reader, info_ptr, 1);
6252
6253       scan_partial_symbols (first_die, &lowpc, &highpc,
6254                             cu_bounds_kind <= PC_BOUNDS_INVALID, cu);
6255
6256       /* If we didn't find a lowpc, set it to highpc to avoid
6257          complaints from `maint check'.  */
6258       if (lowpc == ((CORE_ADDR) -1))
6259         lowpc = highpc;
6260
6261       /* If the compilation unit didn't have an explicit address range,
6262          then use the information extracted from its child dies.  */
6263       if (cu_bounds_kind <= PC_BOUNDS_INVALID)
6264         {
6265           best_lowpc = lowpc;
6266           best_highpc = highpc;
6267         }
6268     }
6269   pst->textlow = gdbarch_adjust_dwarf2_addr (gdbarch, best_lowpc + baseaddr);
6270   pst->texthigh = gdbarch_adjust_dwarf2_addr (gdbarch, best_highpc + baseaddr);
6271
6272   end_psymtab_common (objfile, pst);
6273
6274   if (!VEC_empty (dwarf2_per_cu_ptr, cu->per_cu->imported_symtabs))
6275     {
6276       int i;
6277       int len = VEC_length (dwarf2_per_cu_ptr, cu->per_cu->imported_symtabs);
6278       struct dwarf2_per_cu_data *iter;
6279
6280       /* Fill in 'dependencies' here; we fill in 'users' in a
6281          post-pass.  */
6282       pst->number_of_dependencies = len;
6283       pst->dependencies =
6284         XOBNEWVEC (&objfile->objfile_obstack, struct partial_symtab *, len);
6285       for (i = 0;
6286            VEC_iterate (dwarf2_per_cu_ptr, cu->per_cu->imported_symtabs,
6287                         i, iter);
6288            ++i)
6289         pst->dependencies[i] = iter->v.psymtab;
6290
6291       VEC_free (dwarf2_per_cu_ptr, cu->per_cu->imported_symtabs);
6292     }
6293
6294   /* Get the list of files included in the current compilation unit,
6295      and build a psymtab for each of them.  */
6296   dwarf2_build_include_psymtabs (cu, comp_unit_die, pst);
6297
6298   if (dwarf_read_debug)
6299     {
6300       struct gdbarch *gdbarch = get_objfile_arch (objfile);
6301
6302       fprintf_unfiltered (gdb_stdlog,
6303                           "Psymtab for %s unit @0x%x: %s - %s"
6304                           ", %d global, %d static syms\n",
6305                           per_cu->is_debug_types ? "type" : "comp",
6306                           to_underlying (per_cu->sect_off),
6307                           paddress (gdbarch, pst->textlow),
6308                           paddress (gdbarch, pst->texthigh),
6309                           pst->n_global_syms, pst->n_static_syms);
6310     }
6311 }
6312
6313 /* Subroutine of dwarf2_build_psymtabs_hard to simplify it.
6314    Process compilation unit THIS_CU for a psymtab.  */
6315
6316 static void
6317 process_psymtab_comp_unit (struct dwarf2_per_cu_data *this_cu,
6318                            int want_partial_unit,
6319                            enum language pretend_language)
6320 {
6321   /* If this compilation unit was already read in, free the
6322      cached copy in order to read it in again.  This is
6323      necessary because we skipped some symbols when we first
6324      read in the compilation unit (see load_partial_dies).
6325      This problem could be avoided, but the benefit is unclear.  */
6326   if (this_cu->cu != NULL)
6327     free_one_cached_comp_unit (this_cu);
6328
6329   if (this_cu->is_debug_types)
6330     init_cutu_and_read_dies (this_cu, NULL, 0, 0, build_type_psymtabs_reader,
6331                              NULL);
6332   else
6333     {
6334       process_psymtab_comp_unit_data info;
6335       info.want_partial_unit = want_partial_unit;
6336       info.pretend_language = pretend_language;
6337       init_cutu_and_read_dies (this_cu, NULL, 0, 0,
6338                                process_psymtab_comp_unit_reader, &info);
6339     }
6340
6341   /* Age out any secondary CUs.  */
6342   age_cached_comp_units ();
6343 }
6344
6345 /* Reader function for build_type_psymtabs.  */
6346
6347 static void
6348 build_type_psymtabs_reader (const struct die_reader_specs *reader,
6349                             const gdb_byte *info_ptr,
6350                             struct die_info *type_unit_die,
6351                             int has_children,
6352                             void *data)
6353 {
6354   struct objfile *objfile = dwarf2_per_objfile->objfile;
6355   struct dwarf2_cu *cu = reader->cu;
6356   struct dwarf2_per_cu_data *per_cu = cu->per_cu;
6357   struct signatured_type *sig_type;
6358   struct type_unit_group *tu_group;
6359   struct attribute *attr;
6360   struct partial_die_info *first_die;
6361   CORE_ADDR lowpc, highpc;
6362   struct partial_symtab *pst;
6363
6364   gdb_assert (data == NULL);
6365   gdb_assert (per_cu->is_debug_types);
6366   sig_type = (struct signatured_type *) per_cu;
6367
6368   if (! has_children)
6369     return;
6370
6371   attr = dwarf2_attr_no_follow (type_unit_die, DW_AT_stmt_list);
6372   tu_group = get_type_unit_group (cu, attr);
6373
6374   VEC_safe_push (sig_type_ptr, tu_group->tus, sig_type);
6375
6376   prepare_one_comp_unit (cu, type_unit_die, language_minimal);
6377   cu->list_in_scope = &file_symbols;
6378   pst = create_partial_symtab (per_cu, "");
6379   pst->anonymous = 1;
6380
6381   first_die = load_partial_dies (reader, info_ptr, 1);
6382
6383   lowpc = (CORE_ADDR) -1;
6384   highpc = (CORE_ADDR) 0;
6385   scan_partial_symbols (first_die, &lowpc, &highpc, 0, cu);
6386
6387   end_psymtab_common (objfile, pst);
6388 }
6389
6390 /* Struct used to sort TUs by their abbreviation table offset.  */
6391
6392 struct tu_abbrev_offset
6393 {
6394   struct signatured_type *sig_type;
6395   sect_offset abbrev_offset;
6396 };
6397
6398 /* Helper routine for build_type_psymtabs_1, passed to qsort.  */
6399
6400 static int
6401 sort_tu_by_abbrev_offset (const void *ap, const void *bp)
6402 {
6403   const struct tu_abbrev_offset * const *a
6404     = (const struct tu_abbrev_offset * const*) ap;
6405   const struct tu_abbrev_offset * const *b
6406     = (const struct tu_abbrev_offset * const*) bp;
6407   sect_offset aoff = (*a)->abbrev_offset;
6408   sect_offset boff = (*b)->abbrev_offset;
6409
6410   return (aoff > boff) - (aoff < boff);
6411 }
6412
6413 /* Efficiently read all the type units.
6414    This does the bulk of the work for build_type_psymtabs.
6415
6416    The efficiency is because we sort TUs by the abbrev table they use and
6417    only read each abbrev table once.  In one program there are 200K TUs
6418    sharing 8K abbrev tables.
6419
6420    The main purpose of this function is to support building the
6421    dwarf2_per_objfile->type_unit_groups table.
6422    TUs typically share the DW_AT_stmt_list of the CU they came from, so we
6423    can collapse the search space by grouping them by stmt_list.
6424    The savings can be significant, in the same program from above the 200K TUs
6425    share 8K stmt_list tables.
6426
6427    FUNC is expected to call get_type_unit_group, which will create the
6428    struct type_unit_group if necessary and add it to
6429    dwarf2_per_objfile->type_unit_groups.  */
6430
6431 static void
6432 build_type_psymtabs_1 (void)
6433 {
6434   struct tu_stats *tu_stats = &dwarf2_per_objfile->tu_stats;
6435   struct cleanup *cleanups;
6436   struct abbrev_table *abbrev_table;
6437   sect_offset abbrev_offset;
6438   struct tu_abbrev_offset *sorted_by_abbrev;
6439   int i;
6440
6441   /* It's up to the caller to not call us multiple times.  */
6442   gdb_assert (dwarf2_per_objfile->type_unit_groups == NULL);
6443
6444   if (dwarf2_per_objfile->n_type_units == 0)
6445     return;
6446
6447   /* TUs typically share abbrev tables, and there can be way more TUs than
6448      abbrev tables.  Sort by abbrev table to reduce the number of times we
6449      read each abbrev table in.
6450      Alternatives are to punt or to maintain a cache of abbrev tables.
6451      This is simpler and efficient enough for now.
6452
6453      Later we group TUs by their DW_AT_stmt_list value (as this defines the
6454      symtab to use).  Typically TUs with the same abbrev offset have the same
6455      stmt_list value too so in practice this should work well.
6456
6457      The basic algorithm here is:
6458
6459       sort TUs by abbrev table
6460       for each TU with same abbrev table:
6461         read abbrev table if first user
6462         read TU top level DIE
6463           [IWBN if DWO skeletons had DW_AT_stmt_list]
6464         call FUNC  */
6465
6466   if (dwarf_read_debug)
6467     fprintf_unfiltered (gdb_stdlog, "Building type unit groups ...\n");
6468
6469   /* Sort in a separate table to maintain the order of all_type_units
6470      for .gdb_index: TU indices directly index all_type_units.  */
6471   sorted_by_abbrev = XNEWVEC (struct tu_abbrev_offset,
6472                               dwarf2_per_objfile->n_type_units);
6473   for (i = 0; i < dwarf2_per_objfile->n_type_units; ++i)
6474     {
6475       struct signatured_type *sig_type = dwarf2_per_objfile->all_type_units[i];
6476
6477       sorted_by_abbrev[i].sig_type = sig_type;
6478       sorted_by_abbrev[i].abbrev_offset =
6479         read_abbrev_offset (sig_type->per_cu.section,
6480                             sig_type->per_cu.sect_off);
6481     }
6482   cleanups = make_cleanup (xfree, sorted_by_abbrev);
6483   qsort (sorted_by_abbrev, dwarf2_per_objfile->n_type_units,
6484          sizeof (struct tu_abbrev_offset), sort_tu_by_abbrev_offset);
6485
6486   abbrev_offset = (sect_offset) ~(unsigned) 0;
6487   abbrev_table = NULL;
6488   make_cleanup (abbrev_table_free_cleanup, &abbrev_table);
6489
6490   for (i = 0; i < dwarf2_per_objfile->n_type_units; ++i)
6491     {
6492       const struct tu_abbrev_offset *tu = &sorted_by_abbrev[i];
6493
6494       /* Switch to the next abbrev table if necessary.  */
6495       if (abbrev_table == NULL
6496           || tu->abbrev_offset != abbrev_offset)
6497         {
6498           if (abbrev_table != NULL)
6499             {
6500               abbrev_table_free (abbrev_table);
6501               /* Reset to NULL in case abbrev_table_read_table throws
6502                  an error: abbrev_table_free_cleanup will get called.  */
6503               abbrev_table = NULL;
6504             }
6505           abbrev_offset = tu->abbrev_offset;
6506           abbrev_table =
6507             abbrev_table_read_table (&dwarf2_per_objfile->abbrev,
6508                                      abbrev_offset);
6509           ++tu_stats->nr_uniq_abbrev_tables;
6510         }
6511
6512       init_cutu_and_read_dies (&tu->sig_type->per_cu, abbrev_table, 0, 0,
6513                                build_type_psymtabs_reader, NULL);
6514     }
6515
6516   do_cleanups (cleanups);
6517 }
6518
6519 /* Print collected type unit statistics.  */
6520
6521 static void
6522 print_tu_stats (void)
6523 {
6524   struct tu_stats *tu_stats = &dwarf2_per_objfile->tu_stats;
6525
6526   fprintf_unfiltered (gdb_stdlog, "Type unit statistics:\n");
6527   fprintf_unfiltered (gdb_stdlog, "  %d TUs\n",
6528                       dwarf2_per_objfile->n_type_units);
6529   fprintf_unfiltered (gdb_stdlog, "  %d uniq abbrev tables\n",
6530                       tu_stats->nr_uniq_abbrev_tables);
6531   fprintf_unfiltered (gdb_stdlog, "  %d symtabs from stmt_list entries\n",
6532                       tu_stats->nr_symtabs);
6533   fprintf_unfiltered (gdb_stdlog, "  %d symtab sharers\n",
6534                       tu_stats->nr_symtab_sharers);
6535   fprintf_unfiltered (gdb_stdlog, "  %d type units without a stmt_list\n",
6536                       tu_stats->nr_stmt_less_type_units);
6537   fprintf_unfiltered (gdb_stdlog, "  %d all_type_units reallocs\n",
6538                       tu_stats->nr_all_type_units_reallocs);
6539 }
6540
6541 /* Traversal function for build_type_psymtabs.  */
6542
6543 static int
6544 build_type_psymtab_dependencies (void **slot, void *info)
6545 {
6546   struct objfile *objfile = dwarf2_per_objfile->objfile;
6547   struct type_unit_group *tu_group = (struct type_unit_group *) *slot;
6548   struct dwarf2_per_cu_data *per_cu = &tu_group->per_cu;
6549   struct partial_symtab *pst = per_cu->v.psymtab;
6550   int len = VEC_length (sig_type_ptr, tu_group->tus);
6551   struct signatured_type *iter;
6552   int i;
6553
6554   gdb_assert (len > 0);
6555   gdb_assert (IS_TYPE_UNIT_GROUP (per_cu));
6556
6557   pst->number_of_dependencies = len;
6558   pst->dependencies =
6559     XOBNEWVEC (&objfile->objfile_obstack, struct partial_symtab *, len);
6560   for (i = 0;
6561        VEC_iterate (sig_type_ptr, tu_group->tus, i, iter);
6562        ++i)
6563     {
6564       gdb_assert (iter->per_cu.is_debug_types);
6565       pst->dependencies[i] = iter->per_cu.v.psymtab;
6566       iter->type_unit_group = tu_group;
6567     }
6568
6569   VEC_free (sig_type_ptr, tu_group->tus);
6570
6571   return 1;
6572 }
6573
6574 /* Subroutine of dwarf2_build_psymtabs_hard to simplify it.
6575    Build partial symbol tables for the .debug_types comp-units.  */
6576
6577 static void
6578 build_type_psymtabs (struct objfile *objfile)
6579 {
6580   if (! create_all_type_units (objfile))
6581     return;
6582
6583   build_type_psymtabs_1 ();
6584 }
6585
6586 /* Traversal function for process_skeletonless_type_unit.
6587    Read a TU in a DWO file and build partial symbols for it.  */
6588
6589 static int
6590 process_skeletonless_type_unit (void **slot, void *info)
6591 {
6592   struct dwo_unit *dwo_unit = (struct dwo_unit *) *slot;
6593   struct objfile *objfile = (struct objfile *) info;
6594   struct signatured_type find_entry, *entry;
6595
6596   /* If this TU doesn't exist in the global table, add it and read it in.  */
6597
6598   if (dwarf2_per_objfile->signatured_types == NULL)
6599     {
6600       dwarf2_per_objfile->signatured_types
6601         = allocate_signatured_type_table (objfile);
6602     }
6603
6604   find_entry.signature = dwo_unit->signature;
6605   slot = htab_find_slot (dwarf2_per_objfile->signatured_types, &find_entry,
6606                          INSERT);
6607   /* If we've already seen this type there's nothing to do.  What's happening
6608      is we're doing our own version of comdat-folding here.  */
6609   if (*slot != NULL)
6610     return 1;
6611
6612   /* This does the job that create_all_type_units would have done for
6613      this TU.  */
6614   entry = add_type_unit (dwo_unit->signature, slot);
6615   fill_in_sig_entry_from_dwo_entry (objfile, entry, dwo_unit);
6616   *slot = entry;
6617
6618   /* This does the job that build_type_psymtabs_1 would have done.  */
6619   init_cutu_and_read_dies (&entry->per_cu, NULL, 0, 0,
6620                            build_type_psymtabs_reader, NULL);
6621
6622   return 1;
6623 }
6624
6625 /* Traversal function for process_skeletonless_type_units.  */
6626
6627 static int
6628 process_dwo_file_for_skeletonless_type_units (void **slot, void *info)
6629 {
6630   struct dwo_file *dwo_file = (struct dwo_file *) *slot;
6631
6632   if (dwo_file->tus != NULL)
6633     {
6634       htab_traverse_noresize (dwo_file->tus,
6635                               process_skeletonless_type_unit, info);
6636     }
6637
6638   return 1;
6639 }
6640
6641 /* Scan all TUs of DWO files, verifying we've processed them.
6642    This is needed in case a TU was emitted without its skeleton.
6643    Note: This can't be done until we know what all the DWO files are.  */
6644
6645 static void
6646 process_skeletonless_type_units (struct objfile *objfile)
6647 {
6648   /* Skeletonless TUs in DWP files without .gdb_index is not supported yet.  */
6649   if (get_dwp_file () == NULL
6650       && dwarf2_per_objfile->dwo_files != NULL)
6651     {
6652       htab_traverse_noresize (dwarf2_per_objfile->dwo_files,
6653                               process_dwo_file_for_skeletonless_type_units,
6654                               objfile);
6655     }
6656 }
6657
6658 /* A cleanup function that clears objfile's psymtabs_addrmap field.  */
6659
6660 static void
6661 psymtabs_addrmap_cleanup (void *o)
6662 {
6663   struct objfile *objfile = (struct objfile *) o;
6664
6665   objfile->psymtabs_addrmap = NULL;
6666 }
6667
6668 /* Compute the 'user' field for each psymtab in OBJFILE.  */
6669
6670 static void
6671 set_partial_user (struct objfile *objfile)
6672 {
6673   int i;
6674
6675   for (i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
6676     {
6677       struct dwarf2_per_cu_data *per_cu = dw2_get_cutu (i);
6678       struct partial_symtab *pst = per_cu->v.psymtab;
6679       int j;
6680
6681       if (pst == NULL)
6682         continue;
6683
6684       for (j = 0; j < pst->number_of_dependencies; ++j)
6685         {
6686           /* Set the 'user' field only if it is not already set.  */
6687           if (pst->dependencies[j]->user == NULL)
6688             pst->dependencies[j]->user = pst;
6689         }
6690     }
6691 }
6692
6693 /* Build the partial symbol table by doing a quick pass through the
6694    .debug_info and .debug_abbrev sections.  */
6695
6696 static void
6697 dwarf2_build_psymtabs_hard (struct objfile *objfile)
6698 {
6699   struct cleanup *back_to, *addrmap_cleanup;
6700   int i;
6701
6702   if (dwarf_read_debug)
6703     {
6704       fprintf_unfiltered (gdb_stdlog, "Building psymtabs of objfile %s ...\n",
6705                           objfile_name (objfile));
6706     }
6707
6708   dwarf2_per_objfile->reading_partial_symbols = 1;
6709
6710   dwarf2_read_section (objfile, &dwarf2_per_objfile->info);
6711
6712   /* Any cached compilation units will be linked by the per-objfile
6713      read_in_chain.  Make sure to free them when we're done.  */
6714   back_to = make_cleanup (free_cached_comp_units, NULL);
6715
6716   build_type_psymtabs (objfile);
6717
6718   create_all_comp_units (objfile);
6719
6720   /* Create a temporary address map on a temporary obstack.  We later
6721      copy this to the final obstack.  */
6722   auto_obstack temp_obstack;
6723   objfile->psymtabs_addrmap = addrmap_create_mutable (&temp_obstack);
6724   addrmap_cleanup = make_cleanup (psymtabs_addrmap_cleanup, objfile);
6725
6726   for (i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
6727     {
6728       struct dwarf2_per_cu_data *per_cu = dw2_get_cutu (i);
6729
6730       process_psymtab_comp_unit (per_cu, 0, language_minimal);
6731     }
6732
6733   /* This has to wait until we read the CUs, we need the list of DWOs.  */
6734   process_skeletonless_type_units (objfile);
6735
6736   /* Now that all TUs have been processed we can fill in the dependencies.  */
6737   if (dwarf2_per_objfile->type_unit_groups != NULL)
6738     {
6739       htab_traverse_noresize (dwarf2_per_objfile->type_unit_groups,
6740                               build_type_psymtab_dependencies, NULL);
6741     }
6742
6743   if (dwarf_read_debug)
6744     print_tu_stats ();
6745
6746   set_partial_user (objfile);
6747
6748   objfile->psymtabs_addrmap = addrmap_create_fixed (objfile->psymtabs_addrmap,
6749                                                     &objfile->objfile_obstack);
6750   discard_cleanups (addrmap_cleanup);
6751
6752   do_cleanups (back_to);
6753
6754   if (dwarf_read_debug)
6755     fprintf_unfiltered (gdb_stdlog, "Done building psymtabs of %s\n",
6756                         objfile_name (objfile));
6757 }
6758
6759 /* die_reader_func for load_partial_comp_unit.  */
6760
6761 static void
6762 load_partial_comp_unit_reader (const struct die_reader_specs *reader,
6763                                const gdb_byte *info_ptr,
6764                                struct die_info *comp_unit_die,
6765                                int has_children,
6766                                void *data)
6767 {
6768   struct dwarf2_cu *cu = reader->cu;
6769
6770   prepare_one_comp_unit (cu, comp_unit_die, language_minimal);
6771
6772   /* Check if comp unit has_children.
6773      If so, read the rest of the partial symbols from this comp unit.
6774      If not, there's no more debug_info for this comp unit.  */
6775   if (has_children)
6776     load_partial_dies (reader, info_ptr, 0);
6777 }
6778
6779 /* Load the partial DIEs for a secondary CU into memory.
6780    This is also used when rereading a primary CU with load_all_dies.  */
6781
6782 static void
6783 load_partial_comp_unit (struct dwarf2_per_cu_data *this_cu)
6784 {
6785   init_cutu_and_read_dies (this_cu, NULL, 1, 1,
6786                            load_partial_comp_unit_reader, NULL);
6787 }
6788
6789 static void
6790 read_comp_units_from_section (struct objfile *objfile,
6791                               struct dwarf2_section_info *section,
6792                               struct dwarf2_section_info *abbrev_section,
6793                               unsigned int is_dwz,
6794                               int *n_allocated,
6795                               int *n_comp_units,
6796                               struct dwarf2_per_cu_data ***all_comp_units)
6797 {
6798   const gdb_byte *info_ptr;
6799   bfd *abfd = get_section_bfd_owner (section);
6800
6801   if (dwarf_read_debug)
6802     fprintf_unfiltered (gdb_stdlog, "Reading %s for %s\n",
6803                         get_section_name (section),
6804                         get_section_file_name (section));
6805
6806   dwarf2_read_section (objfile, section);
6807
6808   info_ptr = section->buffer;
6809
6810   while (info_ptr < section->buffer + section->size)
6811     {
6812       struct dwarf2_per_cu_data *this_cu;
6813
6814       sect_offset sect_off = (sect_offset) (info_ptr - section->buffer);
6815
6816       comp_unit_head cu_header;
6817       read_and_check_comp_unit_head (&cu_header, section, abbrev_section,
6818                                      info_ptr, rcuh_kind::COMPILE);
6819
6820       /* Save the compilation unit for later lookup.  */
6821       if (cu_header.unit_type != DW_UT_type)
6822         {
6823           this_cu = XOBNEW (&objfile->objfile_obstack,
6824                             struct dwarf2_per_cu_data);
6825           memset (this_cu, 0, sizeof (*this_cu));
6826         }
6827       else
6828         {
6829           auto sig_type = XOBNEW (&objfile->objfile_obstack,
6830                                   struct signatured_type);
6831           memset (sig_type, 0, sizeof (*sig_type));
6832           sig_type->signature = cu_header.signature;
6833           sig_type->type_offset_in_tu = cu_header.type_cu_offset_in_tu;
6834           this_cu = &sig_type->per_cu;
6835         }
6836       this_cu->is_debug_types = (cu_header.unit_type == DW_UT_type);
6837       this_cu->sect_off = sect_off;
6838       this_cu->length = cu_header.length + cu_header.initial_length_size;
6839       this_cu->is_dwz = is_dwz;
6840       this_cu->objfile = objfile;
6841       this_cu->section = section;
6842
6843       if (*n_comp_units == *n_allocated)
6844         {
6845           *n_allocated *= 2;
6846           *all_comp_units = XRESIZEVEC (struct dwarf2_per_cu_data *,
6847                                         *all_comp_units, *n_allocated);
6848         }
6849       (*all_comp_units)[*n_comp_units] = this_cu;
6850       ++*n_comp_units;
6851
6852       info_ptr = info_ptr + this_cu->length;
6853     }
6854 }
6855
6856 /* Create a list of all compilation units in OBJFILE.
6857    This is only done for -readnow and building partial symtabs.  */
6858
6859 static void
6860 create_all_comp_units (struct objfile *objfile)
6861 {
6862   int n_allocated;
6863   int n_comp_units;
6864   struct dwarf2_per_cu_data **all_comp_units;
6865   struct dwz_file *dwz;
6866
6867   n_comp_units = 0;
6868   n_allocated = 10;
6869   all_comp_units = XNEWVEC (struct dwarf2_per_cu_data *, n_allocated);
6870
6871   read_comp_units_from_section (objfile, &dwarf2_per_objfile->info,
6872                                 &dwarf2_per_objfile->abbrev, 0,
6873                                 &n_allocated, &n_comp_units, &all_comp_units);
6874
6875   dwz = dwarf2_get_dwz_file ();
6876   if (dwz != NULL)
6877     read_comp_units_from_section (objfile, &dwz->info, &dwz->abbrev, 1,
6878                                   &n_allocated, &n_comp_units,
6879                                   &all_comp_units);
6880
6881   dwarf2_per_objfile->all_comp_units = XOBNEWVEC (&objfile->objfile_obstack,
6882                                                   struct dwarf2_per_cu_data *,
6883                                                   n_comp_units);
6884   memcpy (dwarf2_per_objfile->all_comp_units, all_comp_units,
6885           n_comp_units * sizeof (struct dwarf2_per_cu_data *));
6886   xfree (all_comp_units);
6887   dwarf2_per_objfile->n_comp_units = n_comp_units;
6888 }
6889
6890 /* Process all loaded DIEs for compilation unit CU, starting at
6891    FIRST_DIE.  The caller should pass SET_ADDRMAP == 1 if the compilation
6892    unit DIE did not have PC info (DW_AT_low_pc and DW_AT_high_pc, or
6893    DW_AT_ranges).  See the comments of add_partial_subprogram on how
6894    SET_ADDRMAP is used and how *LOWPC and *HIGHPC are updated.  */
6895
6896 static void
6897 scan_partial_symbols (struct partial_die_info *first_die, CORE_ADDR *lowpc,
6898                       CORE_ADDR *highpc, int set_addrmap,
6899                       struct dwarf2_cu *cu)
6900 {
6901   struct partial_die_info *pdi;
6902
6903   /* Now, march along the PDI's, descending into ones which have
6904      interesting children but skipping the children of the other ones,
6905      until we reach the end of the compilation unit.  */
6906
6907   pdi = first_die;
6908
6909   while (pdi != NULL)
6910     {
6911       fixup_partial_die (pdi, cu);
6912
6913       /* Anonymous namespaces or modules have no name but have interesting
6914          children, so we need to look at them.  Ditto for anonymous
6915          enums.  */
6916
6917       if (pdi->name != NULL || pdi->tag == DW_TAG_namespace
6918           || pdi->tag == DW_TAG_module || pdi->tag == DW_TAG_enumeration_type
6919           || pdi->tag == DW_TAG_imported_unit)
6920         {
6921           switch (pdi->tag)
6922             {
6923             case DW_TAG_subprogram:
6924               add_partial_subprogram (pdi, lowpc, highpc, set_addrmap, cu);
6925               break;
6926             case DW_TAG_constant:
6927             case DW_TAG_variable:
6928             case DW_TAG_typedef:
6929             case DW_TAG_union_type:
6930               if (!pdi->is_declaration)
6931                 {
6932                   add_partial_symbol (pdi, cu);
6933                 }
6934               break;
6935             case DW_TAG_class_type:
6936             case DW_TAG_interface_type:
6937             case DW_TAG_structure_type:
6938               if (!pdi->is_declaration)
6939                 {
6940                   add_partial_symbol (pdi, cu);
6941                 }
6942               if (cu->language == language_rust && pdi->has_children)
6943                 scan_partial_symbols (pdi->die_child, lowpc, highpc,
6944                                       set_addrmap, cu);
6945               break;
6946             case DW_TAG_enumeration_type:
6947               if (!pdi->is_declaration)
6948                 add_partial_enumeration (pdi, cu);
6949               break;
6950             case DW_TAG_base_type:
6951             case DW_TAG_subrange_type:
6952               /* File scope base type definitions are added to the partial
6953                  symbol table.  */
6954               add_partial_symbol (pdi, cu);
6955               break;
6956             case DW_TAG_namespace:
6957               add_partial_namespace (pdi, lowpc, highpc, set_addrmap, cu);
6958               break;
6959             case DW_TAG_module:
6960               add_partial_module (pdi, lowpc, highpc, set_addrmap, cu);
6961               break;
6962             case DW_TAG_imported_unit:
6963               {
6964                 struct dwarf2_per_cu_data *per_cu;
6965
6966                 /* For now we don't handle imported units in type units.  */
6967                 if (cu->per_cu->is_debug_types)
6968                   {
6969                     error (_("Dwarf Error: DW_TAG_imported_unit is not"
6970                              " supported in type units [in module %s]"),
6971                            objfile_name (cu->objfile));
6972                   }
6973
6974                 per_cu = dwarf2_find_containing_comp_unit (pdi->d.sect_off,
6975                                                            pdi->is_dwz,
6976                                                            cu->objfile);
6977
6978                 /* Go read the partial unit, if needed.  */
6979                 if (per_cu->v.psymtab == NULL)
6980                   process_psymtab_comp_unit (per_cu, 1, cu->language);
6981
6982                 VEC_safe_push (dwarf2_per_cu_ptr,
6983                                cu->per_cu->imported_symtabs, per_cu);
6984               }
6985               break;
6986             case DW_TAG_imported_declaration:
6987               add_partial_symbol (pdi, cu);
6988               break;
6989             default:
6990               break;
6991             }
6992         }
6993
6994       /* If the die has a sibling, skip to the sibling.  */
6995
6996       pdi = pdi->die_sibling;
6997     }
6998 }
6999
7000 /* Functions used to compute the fully scoped name of a partial DIE.
7001
7002    Normally, this is simple.  For C++, the parent DIE's fully scoped
7003    name is concatenated with "::" and the partial DIE's name.
7004    Enumerators are an exception; they use the scope of their parent
7005    enumeration type, i.e. the name of the enumeration type is not
7006    prepended to the enumerator.
7007
7008    There are two complexities.  One is DW_AT_specification; in this
7009    case "parent" means the parent of the target of the specification,
7010    instead of the direct parent of the DIE.  The other is compilers
7011    which do not emit DW_TAG_namespace; in this case we try to guess
7012    the fully qualified name of structure types from their members'
7013    linkage names.  This must be done using the DIE's children rather
7014    than the children of any DW_AT_specification target.  We only need
7015    to do this for structures at the top level, i.e. if the target of
7016    any DW_AT_specification (if any; otherwise the DIE itself) does not
7017    have a parent.  */
7018
7019 /* Compute the scope prefix associated with PDI's parent, in
7020    compilation unit CU.  The result will be allocated on CU's
7021    comp_unit_obstack, or a copy of the already allocated PDI->NAME
7022    field.  NULL is returned if no prefix is necessary.  */
7023 static const char *
7024 partial_die_parent_scope (struct partial_die_info *pdi,
7025                           struct dwarf2_cu *cu)
7026 {
7027   const char *grandparent_scope;
7028   struct partial_die_info *parent, *real_pdi;
7029
7030   /* We need to look at our parent DIE; if we have a DW_AT_specification,
7031      then this means the parent of the specification DIE.  */
7032
7033   real_pdi = pdi;
7034   while (real_pdi->has_specification)
7035     real_pdi = find_partial_die (real_pdi->spec_offset,
7036                                  real_pdi->spec_is_dwz, cu);
7037
7038   parent = real_pdi->die_parent;
7039   if (parent == NULL)
7040     return NULL;
7041
7042   if (parent->scope_set)
7043     return parent->scope;
7044
7045   fixup_partial_die (parent, cu);
7046
7047   grandparent_scope = partial_die_parent_scope (parent, cu);
7048
7049   /* GCC 4.0 and 4.1 had a bug (PR c++/28460) where they generated bogus
7050      DW_TAG_namespace DIEs with a name of "::" for the global namespace.
7051      Work around this problem here.  */
7052   if (cu->language == language_cplus
7053       && parent->tag == DW_TAG_namespace
7054       && strcmp (parent->name, "::") == 0
7055       && grandparent_scope == NULL)
7056     {
7057       parent->scope = NULL;
7058       parent->scope_set = 1;
7059       return NULL;
7060     }
7061
7062   if (pdi->tag == DW_TAG_enumerator)
7063     /* Enumerators should not get the name of the enumeration as a prefix.  */
7064     parent->scope = grandparent_scope;
7065   else if (parent->tag == DW_TAG_namespace
7066       || parent->tag == DW_TAG_module
7067       || parent->tag == DW_TAG_structure_type
7068       || parent->tag == DW_TAG_class_type
7069       || parent->tag == DW_TAG_interface_type
7070       || parent->tag == DW_TAG_union_type
7071       || parent->tag == DW_TAG_enumeration_type)
7072     {
7073       if (grandparent_scope == NULL)
7074         parent->scope = parent->name;
7075       else
7076         parent->scope = typename_concat (&cu->comp_unit_obstack,
7077                                          grandparent_scope,
7078                                          parent->name, 0, cu);
7079     }
7080   else
7081     {
7082       /* FIXME drow/2004-04-01: What should we be doing with
7083          function-local names?  For partial symbols, we should probably be
7084          ignoring them.  */
7085       complaint (&symfile_complaints,
7086                  _("unhandled containing DIE tag %d for DIE at %d"),
7087                  parent->tag, to_underlying (pdi->sect_off));
7088       parent->scope = grandparent_scope;
7089     }
7090
7091   parent->scope_set = 1;
7092   return parent->scope;
7093 }
7094
7095 /* Return the fully scoped name associated with PDI, from compilation unit
7096    CU.  The result will be allocated with malloc.  */
7097
7098 static char *
7099 partial_die_full_name (struct partial_die_info *pdi,
7100                        struct dwarf2_cu *cu)
7101 {
7102   const char *parent_scope;
7103
7104   /* If this is a template instantiation, we can not work out the
7105      template arguments from partial DIEs.  So, unfortunately, we have
7106      to go through the full DIEs.  At least any work we do building
7107      types here will be reused if full symbols are loaded later.  */
7108   if (pdi->has_template_arguments)
7109     {
7110       fixup_partial_die (pdi, cu);
7111
7112       if (pdi->name != NULL && strchr (pdi->name, '<') == NULL)
7113         {
7114           struct die_info *die;
7115           struct attribute attr;
7116           struct dwarf2_cu *ref_cu = cu;
7117
7118           /* DW_FORM_ref_addr is using section offset.  */
7119           attr.name = (enum dwarf_attribute) 0;
7120           attr.form = DW_FORM_ref_addr;
7121           attr.u.unsnd = to_underlying (pdi->sect_off);
7122           die = follow_die_ref (NULL, &attr, &ref_cu);
7123
7124           return xstrdup (dwarf2_full_name (NULL, die, ref_cu));
7125         }
7126     }
7127
7128   parent_scope = partial_die_parent_scope (pdi, cu);
7129   if (parent_scope == NULL)
7130     return NULL;
7131   else
7132     return typename_concat (NULL, parent_scope, pdi->name, 0, cu);
7133 }
7134
7135 static void
7136 add_partial_symbol (struct partial_die_info *pdi, struct dwarf2_cu *cu)
7137 {
7138   struct objfile *objfile = cu->objfile;
7139   struct gdbarch *gdbarch = get_objfile_arch (objfile);
7140   CORE_ADDR addr = 0;
7141   const char *actual_name = NULL;
7142   CORE_ADDR baseaddr;
7143   char *built_actual_name;
7144
7145   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
7146
7147   built_actual_name = partial_die_full_name (pdi, cu);
7148   if (built_actual_name != NULL)
7149     actual_name = built_actual_name;
7150
7151   if (actual_name == NULL)
7152     actual_name = pdi->name;
7153
7154   switch (pdi->tag)
7155     {
7156     case DW_TAG_subprogram:
7157       addr = gdbarch_adjust_dwarf2_addr (gdbarch, pdi->lowpc + baseaddr);
7158       if (pdi->is_external || cu->language == language_ada)
7159         {
7160           /* brobecker/2007-12-26: Normally, only "external" DIEs are part
7161              of the global scope.  But in Ada, we want to be able to access
7162              nested procedures globally.  So all Ada subprograms are stored
7163              in the global scope.  */
7164           add_psymbol_to_list (actual_name, strlen (actual_name),
7165                                built_actual_name != NULL,
7166                                VAR_DOMAIN, LOC_BLOCK,
7167                                &objfile->global_psymbols,
7168                                addr, cu->language, objfile);
7169         }
7170       else
7171         {
7172           add_psymbol_to_list (actual_name, strlen (actual_name),
7173                                built_actual_name != NULL,
7174                                VAR_DOMAIN, LOC_BLOCK,
7175                                &objfile->static_psymbols,
7176                                addr, cu->language, objfile);
7177         }
7178
7179       if (pdi->main_subprogram && actual_name != NULL)
7180         set_objfile_main_name (objfile, actual_name, cu->language);
7181       break;
7182     case DW_TAG_constant:
7183       {
7184         struct psymbol_allocation_list *list;
7185
7186         if (pdi->is_external)
7187           list = &objfile->global_psymbols;
7188         else
7189           list = &objfile->static_psymbols;
7190         add_psymbol_to_list (actual_name, strlen (actual_name),
7191                              built_actual_name != NULL, VAR_DOMAIN, LOC_STATIC,
7192                              list, 0, cu->language, objfile);
7193       }
7194       break;
7195     case DW_TAG_variable:
7196       if (pdi->d.locdesc)
7197         addr = decode_locdesc (pdi->d.locdesc, cu);
7198
7199       if (pdi->d.locdesc
7200           && addr == 0
7201           && !dwarf2_per_objfile->has_section_at_zero)
7202         {
7203           /* A global or static variable may also have been stripped
7204              out by the linker if unused, in which case its address
7205              will be nullified; do not add such variables into partial
7206              symbol table then.  */
7207         }
7208       else if (pdi->is_external)
7209         {
7210           /* Global Variable.
7211              Don't enter into the minimal symbol tables as there is
7212              a minimal symbol table entry from the ELF symbols already.
7213              Enter into partial symbol table if it has a location
7214              descriptor or a type.
7215              If the location descriptor is missing, new_symbol will create
7216              a LOC_UNRESOLVED symbol, the address of the variable will then
7217              be determined from the minimal symbol table whenever the variable
7218              is referenced.
7219              The address for the partial symbol table entry is not
7220              used by GDB, but it comes in handy for debugging partial symbol
7221              table building.  */
7222
7223           if (pdi->d.locdesc || pdi->has_type)
7224             add_psymbol_to_list (actual_name, strlen (actual_name),
7225                                  built_actual_name != NULL,
7226                                  VAR_DOMAIN, LOC_STATIC,
7227                                  &objfile->global_psymbols,
7228                                  addr + baseaddr,
7229                                  cu->language, objfile);
7230         }
7231       else
7232         {
7233           int has_loc = pdi->d.locdesc != NULL;
7234
7235           /* Static Variable.  Skip symbols whose value we cannot know (those
7236              without location descriptors or constant values).  */
7237           if (!has_loc && !pdi->has_const_value)
7238             {
7239               xfree (built_actual_name);
7240               return;
7241             }
7242
7243           add_psymbol_to_list (actual_name, strlen (actual_name),
7244                                built_actual_name != NULL,
7245                                VAR_DOMAIN, LOC_STATIC,
7246                                &objfile->static_psymbols,
7247                                has_loc ? addr + baseaddr : (CORE_ADDR) 0,
7248                                cu->language, objfile);
7249         }
7250       break;
7251     case DW_TAG_typedef:
7252     case DW_TAG_base_type:
7253     case DW_TAG_subrange_type:
7254       add_psymbol_to_list (actual_name, strlen (actual_name),
7255                            built_actual_name != NULL,
7256                            VAR_DOMAIN, LOC_TYPEDEF,
7257                            &objfile->static_psymbols,
7258                            0, cu->language, objfile);
7259       break;
7260     case DW_TAG_imported_declaration:
7261     case DW_TAG_namespace:
7262       add_psymbol_to_list (actual_name, strlen (actual_name),
7263                            built_actual_name != NULL,
7264                            VAR_DOMAIN, LOC_TYPEDEF,
7265                            &objfile->global_psymbols,
7266                            0, cu->language, objfile);
7267       break;
7268     case DW_TAG_module:
7269       add_psymbol_to_list (actual_name, strlen (actual_name),
7270                            built_actual_name != NULL,
7271                            MODULE_DOMAIN, LOC_TYPEDEF,
7272                            &objfile->global_psymbols,
7273                            0, cu->language, objfile);
7274       break;
7275     case DW_TAG_class_type:
7276     case DW_TAG_interface_type:
7277     case DW_TAG_structure_type:
7278     case DW_TAG_union_type:
7279     case DW_TAG_enumeration_type:
7280       /* Skip external references.  The DWARF standard says in the section
7281          about "Structure, Union, and Class Type Entries": "An incomplete
7282          structure, union or class type is represented by a structure,
7283          union or class entry that does not have a byte size attribute
7284          and that has a DW_AT_declaration attribute."  */
7285       if (!pdi->has_byte_size && pdi->is_declaration)
7286         {
7287           xfree (built_actual_name);
7288           return;
7289         }
7290
7291       /* NOTE: carlton/2003-10-07: See comment in new_symbol about
7292          static vs. global.  */
7293       add_psymbol_to_list (actual_name, strlen (actual_name),
7294                            built_actual_name != NULL,
7295                            STRUCT_DOMAIN, LOC_TYPEDEF,
7296                            cu->language == language_cplus
7297                            ? &objfile->global_psymbols
7298                            : &objfile->static_psymbols,
7299                            0, cu->language, objfile);
7300
7301       break;
7302     case DW_TAG_enumerator:
7303       add_psymbol_to_list (actual_name, strlen (actual_name),
7304                            built_actual_name != NULL,
7305                            VAR_DOMAIN, LOC_CONST,
7306                            cu->language == language_cplus
7307                            ? &objfile->global_psymbols
7308                            : &objfile->static_psymbols,
7309                            0, cu->language, objfile);
7310       break;
7311     default:
7312       break;
7313     }
7314
7315   xfree (built_actual_name);
7316 }
7317
7318 /* Read a partial die corresponding to a namespace; also, add a symbol
7319    corresponding to that namespace to the symbol table.  NAMESPACE is
7320    the name of the enclosing namespace.  */
7321
7322 static void
7323 add_partial_namespace (struct partial_die_info *pdi,
7324                        CORE_ADDR *lowpc, CORE_ADDR *highpc,
7325                        int set_addrmap, struct dwarf2_cu *cu)
7326 {
7327   /* Add a symbol for the namespace.  */
7328
7329   add_partial_symbol (pdi, cu);
7330
7331   /* Now scan partial symbols in that namespace.  */
7332
7333   if (pdi->has_children)
7334     scan_partial_symbols (pdi->die_child, lowpc, highpc, set_addrmap, cu);
7335 }
7336
7337 /* Read a partial die corresponding to a Fortran module.  */
7338
7339 static void
7340 add_partial_module (struct partial_die_info *pdi, CORE_ADDR *lowpc,
7341                     CORE_ADDR *highpc, int set_addrmap, struct dwarf2_cu *cu)
7342 {
7343   /* Add a symbol for the namespace.  */
7344
7345   add_partial_symbol (pdi, cu);
7346
7347   /* Now scan partial symbols in that module.  */
7348
7349   if (pdi->has_children)
7350     scan_partial_symbols (pdi->die_child, lowpc, highpc, set_addrmap, cu);
7351 }
7352
7353 /* Read a partial die corresponding to a subprogram and create a partial
7354    symbol for that subprogram.  When the CU language allows it, this
7355    routine also defines a partial symbol for each nested subprogram
7356    that this subprogram contains.  If SET_ADDRMAP is true, record the
7357    covered ranges in the addrmap.  Set *LOWPC and *HIGHPC to the lowest
7358    and highest PC values found in PDI.
7359
7360    PDI may also be a lexical block, in which case we simply search
7361    recursively for subprograms defined inside that lexical block.
7362    Again, this is only performed when the CU language allows this
7363    type of definitions.  */
7364
7365 static void
7366 add_partial_subprogram (struct partial_die_info *pdi,
7367                         CORE_ADDR *lowpc, CORE_ADDR *highpc,
7368                         int set_addrmap, struct dwarf2_cu *cu)
7369 {
7370   if (pdi->tag == DW_TAG_subprogram)
7371     {
7372       if (pdi->has_pc_info)
7373         {
7374           if (pdi->lowpc < *lowpc)
7375             *lowpc = pdi->lowpc;
7376           if (pdi->highpc > *highpc)
7377             *highpc = pdi->highpc;
7378           if (set_addrmap)
7379             {
7380               struct objfile *objfile = cu->objfile;
7381               struct gdbarch *gdbarch = get_objfile_arch (objfile);
7382               CORE_ADDR baseaddr;
7383               CORE_ADDR highpc;
7384               CORE_ADDR lowpc;
7385
7386               baseaddr = ANOFFSET (objfile->section_offsets,
7387                                    SECT_OFF_TEXT (objfile));
7388               lowpc = gdbarch_adjust_dwarf2_addr (gdbarch,
7389                                                   pdi->lowpc + baseaddr);
7390               highpc = gdbarch_adjust_dwarf2_addr (gdbarch,
7391                                                    pdi->highpc + baseaddr);
7392               addrmap_set_empty (objfile->psymtabs_addrmap, lowpc, highpc - 1,
7393                                  cu->per_cu->v.psymtab);
7394             }
7395         }
7396
7397       if (pdi->has_pc_info || (!pdi->is_external && pdi->may_be_inlined))
7398         {
7399           if (!pdi->is_declaration)
7400             /* Ignore subprogram DIEs that do not have a name, they are
7401                illegal.  Do not emit a complaint at this point, we will
7402                do so when we convert this psymtab into a symtab.  */
7403             if (pdi->name)
7404               add_partial_symbol (pdi, cu);
7405         }
7406     }
7407
7408   if (! pdi->has_children)
7409     return;
7410
7411   if (cu->language == language_ada)
7412     {
7413       pdi = pdi->die_child;
7414       while (pdi != NULL)
7415         {
7416           fixup_partial_die (pdi, cu);
7417           if (pdi->tag == DW_TAG_subprogram
7418               || pdi->tag == DW_TAG_lexical_block)
7419             add_partial_subprogram (pdi, lowpc, highpc, set_addrmap, cu);
7420           pdi = pdi->die_sibling;
7421         }
7422     }
7423 }
7424
7425 /* Read a partial die corresponding to an enumeration type.  */
7426
7427 static void
7428 add_partial_enumeration (struct partial_die_info *enum_pdi,
7429                          struct dwarf2_cu *cu)
7430 {
7431   struct partial_die_info *pdi;
7432
7433   if (enum_pdi->name != NULL)
7434     add_partial_symbol (enum_pdi, cu);
7435
7436   pdi = enum_pdi->die_child;
7437   while (pdi)
7438     {
7439       if (pdi->tag != DW_TAG_enumerator || pdi->name == NULL)
7440         complaint (&symfile_complaints, _("malformed enumerator DIE ignored"));
7441       else
7442         add_partial_symbol (pdi, cu);
7443       pdi = pdi->die_sibling;
7444     }
7445 }
7446
7447 /* Return the initial uleb128 in the die at INFO_PTR.  */
7448
7449 static unsigned int
7450 peek_abbrev_code (bfd *abfd, const gdb_byte *info_ptr)
7451 {
7452   unsigned int bytes_read;
7453
7454   return read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
7455 }
7456
7457 /* Read the initial uleb128 in the die at INFO_PTR in compilation unit CU.
7458    Return the corresponding abbrev, or NULL if the number is zero (indicating
7459    an empty DIE).  In either case *BYTES_READ will be set to the length of
7460    the initial number.  */
7461
7462 static struct abbrev_info *
7463 peek_die_abbrev (const gdb_byte *info_ptr, unsigned int *bytes_read,
7464                  struct dwarf2_cu *cu)
7465 {
7466   bfd *abfd = cu->objfile->obfd;
7467   unsigned int abbrev_number;
7468   struct abbrev_info *abbrev;
7469
7470   abbrev_number = read_unsigned_leb128 (abfd, info_ptr, bytes_read);
7471
7472   if (abbrev_number == 0)
7473     return NULL;
7474
7475   abbrev = abbrev_table_lookup_abbrev (cu->abbrev_table, abbrev_number);
7476   if (!abbrev)
7477     {
7478       error (_("Dwarf Error: Could not find abbrev number %d in %s"
7479                " at offset 0x%x [in module %s]"),
7480              abbrev_number, cu->per_cu->is_debug_types ? "TU" : "CU",
7481              to_underlying (cu->header.sect_off), bfd_get_filename (abfd));
7482     }
7483
7484   return abbrev;
7485 }
7486
7487 /* Scan the debug information for CU starting at INFO_PTR in buffer BUFFER.
7488    Returns a pointer to the end of a series of DIEs, terminated by an empty
7489    DIE.  Any children of the skipped DIEs will also be skipped.  */
7490
7491 static const gdb_byte *
7492 skip_children (const struct die_reader_specs *reader, const gdb_byte *info_ptr)
7493 {
7494   struct dwarf2_cu *cu = reader->cu;
7495   struct abbrev_info *abbrev;
7496   unsigned int bytes_read;
7497
7498   while (1)
7499     {
7500       abbrev = peek_die_abbrev (info_ptr, &bytes_read, cu);
7501       if (abbrev == NULL)
7502         return info_ptr + bytes_read;
7503       else
7504         info_ptr = skip_one_die (reader, info_ptr + bytes_read, abbrev);
7505     }
7506 }
7507
7508 /* Scan the debug information for CU starting at INFO_PTR in buffer BUFFER.
7509    INFO_PTR should point just after the initial uleb128 of a DIE, and the
7510    abbrev corresponding to that skipped uleb128 should be passed in
7511    ABBREV.  Returns a pointer to this DIE's sibling, skipping any
7512    children.  */
7513
7514 static const gdb_byte *
7515 skip_one_die (const struct die_reader_specs *reader, const gdb_byte *info_ptr,
7516               struct abbrev_info *abbrev)
7517 {
7518   unsigned int bytes_read;
7519   struct attribute attr;
7520   bfd *abfd = reader->abfd;
7521   struct dwarf2_cu *cu = reader->cu;
7522   const gdb_byte *buffer = reader->buffer;
7523   const gdb_byte *buffer_end = reader->buffer_end;
7524   unsigned int form, i;
7525
7526   for (i = 0; i < abbrev->num_attrs; i++)
7527     {
7528       /* The only abbrev we care about is DW_AT_sibling.  */
7529       if (abbrev->attrs[i].name == DW_AT_sibling)
7530         {
7531           read_attribute (reader, &attr, &abbrev->attrs[i], info_ptr);
7532           if (attr.form == DW_FORM_ref_addr)
7533             complaint (&symfile_complaints,
7534                        _("ignoring absolute DW_AT_sibling"));
7535           else
7536             {
7537               sect_offset off = dwarf2_get_ref_die_offset (&attr);
7538               const gdb_byte *sibling_ptr = buffer + to_underlying (off);
7539
7540               if (sibling_ptr < info_ptr)
7541                 complaint (&symfile_complaints,
7542                            _("DW_AT_sibling points backwards"));
7543               else if (sibling_ptr > reader->buffer_end)
7544                 dwarf2_section_buffer_overflow_complaint (reader->die_section);
7545               else
7546                 return sibling_ptr;
7547             }
7548         }
7549
7550       /* If it isn't DW_AT_sibling, skip this attribute.  */
7551       form = abbrev->attrs[i].form;
7552     skip_attribute:
7553       switch (form)
7554         {
7555         case DW_FORM_ref_addr:
7556           /* In DWARF 2, DW_FORM_ref_addr is address sized; in DWARF 3
7557              and later it is offset sized.  */
7558           if (cu->header.version == 2)
7559             info_ptr += cu->header.addr_size;
7560           else
7561             info_ptr += cu->header.offset_size;
7562           break;
7563         case DW_FORM_GNU_ref_alt:
7564           info_ptr += cu->header.offset_size;
7565           break;
7566         case DW_FORM_addr:
7567           info_ptr += cu->header.addr_size;
7568           break;
7569         case DW_FORM_data1:
7570         case DW_FORM_ref1:
7571         case DW_FORM_flag:
7572           info_ptr += 1;
7573           break;
7574         case DW_FORM_flag_present:
7575         case DW_FORM_implicit_const:
7576           break;
7577         case DW_FORM_data2:
7578         case DW_FORM_ref2:
7579           info_ptr += 2;
7580           break;
7581         case DW_FORM_data4:
7582         case DW_FORM_ref4:
7583           info_ptr += 4;
7584           break;
7585         case DW_FORM_data8:
7586         case DW_FORM_ref8:
7587         case DW_FORM_ref_sig8:
7588           info_ptr += 8;
7589           break;
7590         case DW_FORM_data16:
7591           info_ptr += 16;
7592           break;
7593         case DW_FORM_string:
7594           read_direct_string (abfd, info_ptr, &bytes_read);
7595           info_ptr += bytes_read;
7596           break;
7597         case DW_FORM_sec_offset:
7598         case DW_FORM_strp:
7599         case DW_FORM_GNU_strp_alt:
7600           info_ptr += cu->header.offset_size;
7601           break;
7602         case DW_FORM_exprloc:
7603         case DW_FORM_block:
7604           info_ptr += read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
7605           info_ptr += bytes_read;
7606           break;
7607         case DW_FORM_block1:
7608           info_ptr += 1 + read_1_byte (abfd, info_ptr);
7609           break;
7610         case DW_FORM_block2:
7611           info_ptr += 2 + read_2_bytes (abfd, info_ptr);
7612           break;
7613         case DW_FORM_block4:
7614           info_ptr += 4 + read_4_bytes (abfd, info_ptr);
7615           break;
7616         case DW_FORM_sdata:
7617         case DW_FORM_udata:
7618         case DW_FORM_ref_udata:
7619         case DW_FORM_GNU_addr_index:
7620         case DW_FORM_GNU_str_index:
7621           info_ptr = safe_skip_leb128 (info_ptr, buffer_end);
7622           break;
7623         case DW_FORM_indirect:
7624           form = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
7625           info_ptr += bytes_read;
7626           /* We need to continue parsing from here, so just go back to
7627              the top.  */
7628           goto skip_attribute;
7629
7630         default:
7631           error (_("Dwarf Error: Cannot handle %s "
7632                    "in DWARF reader [in module %s]"),
7633                  dwarf_form_name (form),
7634                  bfd_get_filename (abfd));
7635         }
7636     }
7637
7638   if (abbrev->has_children)
7639     return skip_children (reader, info_ptr);
7640   else
7641     return info_ptr;
7642 }
7643
7644 /* Locate ORIG_PDI's sibling.
7645    INFO_PTR should point to the start of the next DIE after ORIG_PDI.  */
7646
7647 static const gdb_byte *
7648 locate_pdi_sibling (const struct die_reader_specs *reader,
7649                     struct partial_die_info *orig_pdi,
7650                     const gdb_byte *info_ptr)
7651 {
7652   /* Do we know the sibling already?  */
7653
7654   if (orig_pdi->sibling)
7655     return orig_pdi->sibling;
7656
7657   /* Are there any children to deal with?  */
7658
7659   if (!orig_pdi->has_children)
7660     return info_ptr;
7661
7662   /* Skip the children the long way.  */
7663
7664   return skip_children (reader, info_ptr);
7665 }
7666
7667 /* Expand this partial symbol table into a full symbol table.  SELF is
7668    not NULL.  */
7669
7670 static void
7671 dwarf2_read_symtab (struct partial_symtab *self,
7672                     struct objfile *objfile)
7673 {
7674   if (self->readin)
7675     {
7676       warning (_("bug: psymtab for %s is already read in."),
7677                self->filename);
7678     }
7679   else
7680     {
7681       if (info_verbose)
7682         {
7683           printf_filtered (_("Reading in symbols for %s..."),
7684                            self->filename);
7685           gdb_flush (gdb_stdout);
7686         }
7687
7688       /* Restore our global data.  */
7689       dwarf2_per_objfile
7690         = (struct dwarf2_per_objfile *) objfile_data (objfile,
7691                                                       dwarf2_objfile_data_key);
7692
7693       /* If this psymtab is constructed from a debug-only objfile, the
7694          has_section_at_zero flag will not necessarily be correct.  We
7695          can get the correct value for this flag by looking at the data
7696          associated with the (presumably stripped) associated objfile.  */
7697       if (objfile->separate_debug_objfile_backlink)
7698         {
7699           struct dwarf2_per_objfile *dpo_backlink
7700             = ((struct dwarf2_per_objfile *)
7701                objfile_data (objfile->separate_debug_objfile_backlink,
7702                              dwarf2_objfile_data_key));
7703
7704           dwarf2_per_objfile->has_section_at_zero
7705             = dpo_backlink->has_section_at_zero;
7706         }
7707
7708       dwarf2_per_objfile->reading_partial_symbols = 0;
7709
7710       psymtab_to_symtab_1 (self);
7711
7712       /* Finish up the debug error message.  */
7713       if (info_verbose)
7714         printf_filtered (_("done.\n"));
7715     }
7716
7717   process_cu_includes ();
7718 }
7719 \f
7720 /* Reading in full CUs.  */
7721
7722 /* Add PER_CU to the queue.  */
7723
7724 static void
7725 queue_comp_unit (struct dwarf2_per_cu_data *per_cu,
7726                  enum language pretend_language)
7727 {
7728   struct dwarf2_queue_item *item;
7729
7730   per_cu->queued = 1;
7731   item = XNEW (struct dwarf2_queue_item);
7732   item->per_cu = per_cu;
7733   item->pretend_language = pretend_language;
7734   item->next = NULL;
7735
7736   if (dwarf2_queue == NULL)
7737     dwarf2_queue = item;
7738   else
7739     dwarf2_queue_tail->next = item;
7740
7741   dwarf2_queue_tail = item;
7742 }
7743
7744 /* If PER_CU is not yet queued, add it to the queue.
7745    If DEPENDENT_CU is non-NULL, it has a reference to PER_CU so add a
7746    dependency.
7747    The result is non-zero if PER_CU was queued, otherwise the result is zero
7748    meaning either PER_CU is already queued or it is already loaded.
7749
7750    N.B. There is an invariant here that if a CU is queued then it is loaded.
7751    The caller is required to load PER_CU if we return non-zero.  */
7752
7753 static int
7754 maybe_queue_comp_unit (struct dwarf2_cu *dependent_cu,
7755                        struct dwarf2_per_cu_data *per_cu,
7756                        enum language pretend_language)
7757 {
7758   /* We may arrive here during partial symbol reading, if we need full
7759      DIEs to process an unusual case (e.g. template arguments).  Do
7760      not queue PER_CU, just tell our caller to load its DIEs.  */
7761   if (dwarf2_per_objfile->reading_partial_symbols)
7762     {
7763       if (per_cu->cu == NULL || per_cu->cu->dies == NULL)
7764         return 1;
7765       return 0;
7766     }
7767
7768   /* Mark the dependence relation so that we don't flush PER_CU
7769      too early.  */
7770   if (dependent_cu != NULL)
7771     dwarf2_add_dependence (dependent_cu, per_cu);
7772
7773   /* If it's already on the queue, we have nothing to do.  */
7774   if (per_cu->queued)
7775     return 0;
7776
7777   /* If the compilation unit is already loaded, just mark it as
7778      used.  */
7779   if (per_cu->cu != NULL)
7780     {
7781       per_cu->cu->last_used = 0;
7782       return 0;
7783     }
7784
7785   /* Add it to the queue.  */
7786   queue_comp_unit (per_cu, pretend_language);
7787
7788   return 1;
7789 }
7790
7791 /* Process the queue.  */
7792
7793 static void
7794 process_queue (void)
7795 {
7796   struct dwarf2_queue_item *item, *next_item;
7797
7798   if (dwarf_read_debug)
7799     {
7800       fprintf_unfiltered (gdb_stdlog,
7801                           "Expanding one or more symtabs of objfile %s ...\n",
7802                           objfile_name (dwarf2_per_objfile->objfile));
7803     }
7804
7805   /* The queue starts out with one item, but following a DIE reference
7806      may load a new CU, adding it to the end of the queue.  */
7807   for (item = dwarf2_queue; item != NULL; dwarf2_queue = item = next_item)
7808     {
7809       if ((dwarf2_per_objfile->using_index
7810            ? !item->per_cu->v.quick->compunit_symtab
7811            : (item->per_cu->v.psymtab && !item->per_cu->v.psymtab->readin))
7812           /* Skip dummy CUs.  */
7813           && item->per_cu->cu != NULL)
7814         {
7815           struct dwarf2_per_cu_data *per_cu = item->per_cu;
7816           unsigned int debug_print_threshold;
7817           char buf[100];
7818
7819           if (per_cu->is_debug_types)
7820             {
7821               struct signatured_type *sig_type =
7822                 (struct signatured_type *) per_cu;
7823
7824               sprintf (buf, "TU %s at offset 0x%x",
7825                        hex_string (sig_type->signature),
7826                        to_underlying (per_cu->sect_off));
7827               /* There can be 100s of TUs.
7828                  Only print them in verbose mode.  */
7829               debug_print_threshold = 2;
7830             }
7831           else
7832             {
7833               sprintf (buf, "CU at offset 0x%x",
7834                        to_underlying (per_cu->sect_off));
7835               debug_print_threshold = 1;
7836             }
7837
7838           if (dwarf_read_debug >= debug_print_threshold)
7839             fprintf_unfiltered (gdb_stdlog, "Expanding symtab of %s\n", buf);
7840
7841           if (per_cu->is_debug_types)
7842             process_full_type_unit (per_cu, item->pretend_language);
7843           else
7844             process_full_comp_unit (per_cu, item->pretend_language);
7845
7846           if (dwarf_read_debug >= debug_print_threshold)
7847             fprintf_unfiltered (gdb_stdlog, "Done expanding %s\n", buf);
7848         }
7849
7850       item->per_cu->queued = 0;
7851       next_item = item->next;
7852       xfree (item);
7853     }
7854
7855   dwarf2_queue_tail = NULL;
7856
7857   if (dwarf_read_debug)
7858     {
7859       fprintf_unfiltered (gdb_stdlog, "Done expanding symtabs of %s.\n",
7860                           objfile_name (dwarf2_per_objfile->objfile));
7861     }
7862 }
7863
7864 /* Free all allocated queue entries.  This function only releases anything if
7865    an error was thrown; if the queue was processed then it would have been
7866    freed as we went along.  */
7867
7868 static void
7869 dwarf2_release_queue (void *dummy)
7870 {
7871   struct dwarf2_queue_item *item, *last;
7872
7873   item = dwarf2_queue;
7874   while (item)
7875     {
7876       /* Anything still marked queued is likely to be in an
7877          inconsistent state, so discard it.  */
7878       if (item->per_cu->queued)
7879         {
7880           if (item->per_cu->cu != NULL)
7881             free_one_cached_comp_unit (item->per_cu);
7882           item->per_cu->queued = 0;
7883         }
7884
7885       last = item;
7886       item = item->next;
7887       xfree (last);
7888     }
7889
7890   dwarf2_queue = dwarf2_queue_tail = NULL;
7891 }
7892
7893 /* Read in full symbols for PST, and anything it depends on.  */
7894
7895 static void
7896 psymtab_to_symtab_1 (struct partial_symtab *pst)
7897 {
7898   struct dwarf2_per_cu_data *per_cu;
7899   int i;
7900
7901   if (pst->readin)
7902     return;
7903
7904   for (i = 0; i < pst->number_of_dependencies; i++)
7905     if (!pst->dependencies[i]->readin
7906         && pst->dependencies[i]->user == NULL)
7907       {
7908         /* Inform about additional files that need to be read in.  */
7909         if (info_verbose)
7910           {
7911             /* FIXME: i18n: Need to make this a single string.  */
7912             fputs_filtered (" ", gdb_stdout);
7913             wrap_here ("");
7914             fputs_filtered ("and ", gdb_stdout);
7915             wrap_here ("");
7916             printf_filtered ("%s...", pst->dependencies[i]->filename);
7917             wrap_here ("");     /* Flush output.  */
7918             gdb_flush (gdb_stdout);
7919           }
7920         psymtab_to_symtab_1 (pst->dependencies[i]);
7921       }
7922
7923   per_cu = (struct dwarf2_per_cu_data *) pst->read_symtab_private;
7924
7925   if (per_cu == NULL)
7926     {
7927       /* It's an include file, no symbols to read for it.
7928          Everything is in the parent symtab.  */
7929       pst->readin = 1;
7930       return;
7931     }
7932
7933   dw2_do_instantiate_symtab (per_cu);
7934 }
7935
7936 /* Trivial hash function for die_info: the hash value of a DIE
7937    is its offset in .debug_info for this objfile.  */
7938
7939 static hashval_t
7940 die_hash (const void *item)
7941 {
7942   const struct die_info *die = (const struct die_info *) item;
7943
7944   return to_underlying (die->sect_off);
7945 }
7946
7947 /* Trivial comparison function for die_info structures: two DIEs
7948    are equal if they have the same offset.  */
7949
7950 static int
7951 die_eq (const void *item_lhs, const void *item_rhs)
7952 {
7953   const struct die_info *die_lhs = (const struct die_info *) item_lhs;
7954   const struct die_info *die_rhs = (const struct die_info *) item_rhs;
7955
7956   return die_lhs->sect_off == die_rhs->sect_off;
7957 }
7958
7959 /* die_reader_func for load_full_comp_unit.
7960    This is identical to read_signatured_type_reader,
7961    but is kept separate for now.  */
7962
7963 static void
7964 load_full_comp_unit_reader (const struct die_reader_specs *reader,
7965                             const gdb_byte *info_ptr,
7966                             struct die_info *comp_unit_die,
7967                             int has_children,
7968                             void *data)
7969 {
7970   struct dwarf2_cu *cu = reader->cu;
7971   enum language *language_ptr = (enum language *) data;
7972
7973   gdb_assert (cu->die_hash == NULL);
7974   cu->die_hash =
7975     htab_create_alloc_ex (cu->header.length / 12,
7976                           die_hash,
7977                           die_eq,
7978                           NULL,
7979                           &cu->comp_unit_obstack,
7980                           hashtab_obstack_allocate,
7981                           dummy_obstack_deallocate);
7982
7983   if (has_children)
7984     comp_unit_die->child = read_die_and_siblings (reader, info_ptr,
7985                                                   &info_ptr, comp_unit_die);
7986   cu->dies = comp_unit_die;
7987   /* comp_unit_die is not stored in die_hash, no need.  */
7988
7989   /* We try not to read any attributes in this function, because not
7990      all CUs needed for references have been loaded yet, and symbol
7991      table processing isn't initialized.  But we have to set the CU language,
7992      or we won't be able to build types correctly.
7993      Similarly, if we do not read the producer, we can not apply
7994      producer-specific interpretation.  */
7995   prepare_one_comp_unit (cu, cu->dies, *language_ptr);
7996 }
7997
7998 /* Load the DIEs associated with PER_CU into memory.  */
7999
8000 static void
8001 load_full_comp_unit (struct dwarf2_per_cu_data *this_cu,
8002                      enum language pretend_language)
8003 {
8004   gdb_assert (! this_cu->is_debug_types);
8005
8006   init_cutu_and_read_dies (this_cu, NULL, 1, 1,
8007                            load_full_comp_unit_reader, &pretend_language);
8008 }
8009
8010 /* Add a DIE to the delayed physname list.  */
8011
8012 static void
8013 add_to_method_list (struct type *type, int fnfield_index, int index,
8014                     const char *name, struct die_info *die,
8015                     struct dwarf2_cu *cu)
8016 {
8017   struct delayed_method_info mi;
8018   mi.type = type;
8019   mi.fnfield_index = fnfield_index;
8020   mi.index = index;
8021   mi.name = name;
8022   mi.die = die;
8023   VEC_safe_push (delayed_method_info, cu->method_list, &mi);
8024 }
8025
8026 /* A cleanup for freeing the delayed method list.  */
8027
8028 static void
8029 free_delayed_list (void *ptr)
8030 {
8031   struct dwarf2_cu *cu = (struct dwarf2_cu *) ptr;
8032   if (cu->method_list != NULL)
8033     {
8034       VEC_free (delayed_method_info, cu->method_list);
8035       cu->method_list = NULL;
8036     }
8037 }
8038
8039 /* Check whether [PHYSNAME, PHYSNAME+LEN) ends with a modifier like
8040    "const" / "volatile".  If so, decrements LEN by the length of the
8041    modifier and return true.  Otherwise return false.  */
8042
8043 template<size_t N>
8044 static bool
8045 check_modifier (const char *physname, size_t &len, const char (&mod)[N])
8046 {
8047   size_t mod_len = sizeof (mod) - 1;
8048   if (len > mod_len && startswith (physname + (len - mod_len), mod))
8049     {
8050       len -= mod_len;
8051       return true;
8052     }
8053   return false;
8054 }
8055
8056 /* Compute the physnames of any methods on the CU's method list.
8057
8058    The computation of method physnames is delayed in order to avoid the
8059    (bad) condition that one of the method's formal parameters is of an as yet
8060    incomplete type.  */
8061
8062 static void
8063 compute_delayed_physnames (struct dwarf2_cu *cu)
8064 {
8065   int i;
8066   struct delayed_method_info *mi;
8067
8068   /* Only C++ delays computing physnames.  */
8069   if (VEC_empty (delayed_method_info, cu->method_list))
8070     return;
8071   gdb_assert (cu->language == language_cplus);
8072
8073   for (i = 0; VEC_iterate (delayed_method_info, cu->method_list, i, mi) ; ++i)
8074     {
8075       const char *physname;
8076       struct fn_fieldlist *fn_flp
8077         = &TYPE_FN_FIELDLIST (mi->type, mi->fnfield_index);
8078       physname = dwarf2_physname (mi->name, mi->die, cu);
8079       TYPE_FN_FIELD_PHYSNAME (fn_flp->fn_fields, mi->index)
8080         = physname ? physname : "";
8081
8082       /* Since there's no tag to indicate whether a method is a
8083          const/volatile overload, extract that information out of the
8084          demangled name.  */
8085       if (physname != NULL)
8086         {
8087           size_t len = strlen (physname);
8088
8089           while (1)
8090             {
8091               if (physname[len] == ')') /* shortcut */
8092                 break;
8093               else if (check_modifier (physname, len, " const"))
8094                 TYPE_FN_FIELD_CONST (fn_flp->fn_fields, mi->index) = 1;
8095               else if (check_modifier (physname, len, " volatile"))
8096                 TYPE_FN_FIELD_VOLATILE (fn_flp->fn_fields, mi->index) = 1;
8097               else
8098                 break;
8099             }
8100         }
8101     }
8102 }
8103
8104 /* Go objects should be embedded in a DW_TAG_module DIE,
8105    and it's not clear if/how imported objects will appear.
8106    To keep Go support simple until that's worked out,
8107    go back through what we've read and create something usable.
8108    We could do this while processing each DIE, and feels kinda cleaner,
8109    but that way is more invasive.
8110    This is to, for example, allow the user to type "p var" or "b main"
8111    without having to specify the package name, and allow lookups
8112    of module.object to work in contexts that use the expression
8113    parser.  */
8114
8115 static void
8116 fixup_go_packaging (struct dwarf2_cu *cu)
8117 {
8118   char *package_name = NULL;
8119   struct pending *list;
8120   int i;
8121
8122   for (list = global_symbols; list != NULL; list = list->next)
8123     {
8124       for (i = 0; i < list->nsyms; ++i)
8125         {
8126           struct symbol *sym = list->symbol[i];
8127
8128           if (SYMBOL_LANGUAGE (sym) == language_go
8129               && SYMBOL_CLASS (sym) == LOC_BLOCK)
8130             {
8131               char *this_package_name = go_symbol_package_name (sym);
8132
8133               if (this_package_name == NULL)
8134                 continue;
8135               if (package_name == NULL)
8136                 package_name = this_package_name;
8137               else
8138                 {
8139                   if (strcmp (package_name, this_package_name) != 0)
8140                     complaint (&symfile_complaints,
8141                                _("Symtab %s has objects from two different Go packages: %s and %s"),
8142                                (symbol_symtab (sym) != NULL
8143                                 ? symtab_to_filename_for_display
8144                                     (symbol_symtab (sym))
8145                                 : objfile_name (cu->objfile)),
8146                                this_package_name, package_name);
8147                   xfree (this_package_name);
8148                 }
8149             }
8150         }
8151     }
8152
8153   if (package_name != NULL)
8154     {
8155       struct objfile *objfile = cu->objfile;
8156       const char *saved_package_name
8157         = (const char *) obstack_copy0 (&objfile->per_bfd->storage_obstack,
8158                                         package_name,
8159                                         strlen (package_name));
8160       struct type *type = init_type (objfile, TYPE_CODE_MODULE, 0,
8161                                      saved_package_name);
8162       struct symbol *sym;
8163
8164       TYPE_TAG_NAME (type) = TYPE_NAME (type);
8165
8166       sym = allocate_symbol (objfile);
8167       SYMBOL_SET_LANGUAGE (sym, language_go, &objfile->objfile_obstack);
8168       SYMBOL_SET_NAMES (sym, saved_package_name,
8169                         strlen (saved_package_name), 0, objfile);
8170       /* This is not VAR_DOMAIN because we want a way to ensure a lookup of,
8171          e.g., "main" finds the "main" module and not C's main().  */
8172       SYMBOL_DOMAIN (sym) = STRUCT_DOMAIN;
8173       SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
8174       SYMBOL_TYPE (sym) = type;
8175
8176       add_symbol_to_list (sym, &global_symbols);
8177
8178       xfree (package_name);
8179     }
8180 }
8181
8182 /* Return the symtab for PER_CU.  This works properly regardless of
8183    whether we're using the index or psymtabs.  */
8184
8185 static struct compunit_symtab *
8186 get_compunit_symtab (struct dwarf2_per_cu_data *per_cu)
8187 {
8188   return (dwarf2_per_objfile->using_index
8189           ? per_cu->v.quick->compunit_symtab
8190           : per_cu->v.psymtab->compunit_symtab);
8191 }
8192
8193 /* A helper function for computing the list of all symbol tables
8194    included by PER_CU.  */
8195
8196 static void
8197 recursively_compute_inclusions (VEC (compunit_symtab_ptr) **result,
8198                                 htab_t all_children, htab_t all_type_symtabs,
8199                                 struct dwarf2_per_cu_data *per_cu,
8200                                 struct compunit_symtab *immediate_parent)
8201 {
8202   void **slot;
8203   int ix;
8204   struct compunit_symtab *cust;
8205   struct dwarf2_per_cu_data *iter;
8206
8207   slot = htab_find_slot (all_children, per_cu, INSERT);
8208   if (*slot != NULL)
8209     {
8210       /* This inclusion and its children have been processed.  */
8211       return;
8212     }
8213
8214   *slot = per_cu;
8215   /* Only add a CU if it has a symbol table.  */
8216   cust = get_compunit_symtab (per_cu);
8217   if (cust != NULL)
8218     {
8219       /* If this is a type unit only add its symbol table if we haven't
8220          seen it yet (type unit per_cu's can share symtabs).  */
8221       if (per_cu->is_debug_types)
8222         {
8223           slot = htab_find_slot (all_type_symtabs, cust, INSERT);
8224           if (*slot == NULL)
8225             {
8226               *slot = cust;
8227               VEC_safe_push (compunit_symtab_ptr, *result, cust);
8228               if (cust->user == NULL)
8229                 cust->user = immediate_parent;
8230             }
8231         }
8232       else
8233         {
8234           VEC_safe_push (compunit_symtab_ptr, *result, cust);
8235           if (cust->user == NULL)
8236             cust->user = immediate_parent;
8237         }
8238     }
8239
8240   for (ix = 0;
8241        VEC_iterate (dwarf2_per_cu_ptr, per_cu->imported_symtabs, ix, iter);
8242        ++ix)
8243     {
8244       recursively_compute_inclusions (result, all_children,
8245                                       all_type_symtabs, iter, cust);
8246     }
8247 }
8248
8249 /* Compute the compunit_symtab 'includes' fields for the compunit_symtab of
8250    PER_CU.  */
8251
8252 static void
8253 compute_compunit_symtab_includes (struct dwarf2_per_cu_data *per_cu)
8254 {
8255   gdb_assert (! per_cu->is_debug_types);
8256
8257   if (!VEC_empty (dwarf2_per_cu_ptr, per_cu->imported_symtabs))
8258     {
8259       int ix, len;
8260       struct dwarf2_per_cu_data *per_cu_iter;
8261       struct compunit_symtab *compunit_symtab_iter;
8262       VEC (compunit_symtab_ptr) *result_symtabs = NULL;
8263       htab_t all_children, all_type_symtabs;
8264       struct compunit_symtab *cust = get_compunit_symtab (per_cu);
8265
8266       /* If we don't have a symtab, we can just skip this case.  */
8267       if (cust == NULL)
8268         return;
8269
8270       all_children = htab_create_alloc (1, htab_hash_pointer, htab_eq_pointer,
8271                                         NULL, xcalloc, xfree);
8272       all_type_symtabs = htab_create_alloc (1, htab_hash_pointer, htab_eq_pointer,
8273                                             NULL, xcalloc, xfree);
8274
8275       for (ix = 0;
8276            VEC_iterate (dwarf2_per_cu_ptr, per_cu->imported_symtabs,
8277                         ix, per_cu_iter);
8278            ++ix)
8279         {
8280           recursively_compute_inclusions (&result_symtabs, all_children,
8281                                           all_type_symtabs, per_cu_iter,
8282                                           cust);
8283         }
8284
8285       /* Now we have a transitive closure of all the included symtabs.  */
8286       len = VEC_length (compunit_symtab_ptr, result_symtabs);
8287       cust->includes
8288         = XOBNEWVEC (&dwarf2_per_objfile->objfile->objfile_obstack,
8289                      struct compunit_symtab *, len + 1);
8290       for (ix = 0;
8291            VEC_iterate (compunit_symtab_ptr, result_symtabs, ix,
8292                         compunit_symtab_iter);
8293            ++ix)
8294         cust->includes[ix] = compunit_symtab_iter;
8295       cust->includes[len] = NULL;
8296
8297       VEC_free (compunit_symtab_ptr, result_symtabs);
8298       htab_delete (all_children);
8299       htab_delete (all_type_symtabs);
8300     }
8301 }
8302
8303 /* Compute the 'includes' field for the symtabs of all the CUs we just
8304    read.  */
8305
8306 static void
8307 process_cu_includes (void)
8308 {
8309   int ix;
8310   struct dwarf2_per_cu_data *iter;
8311
8312   for (ix = 0;
8313        VEC_iterate (dwarf2_per_cu_ptr, dwarf2_per_objfile->just_read_cus,
8314                     ix, iter);
8315        ++ix)
8316     {
8317       if (! iter->is_debug_types)
8318         compute_compunit_symtab_includes (iter);
8319     }
8320
8321   VEC_free (dwarf2_per_cu_ptr, dwarf2_per_objfile->just_read_cus);
8322 }
8323
8324 /* Generate full symbol information for PER_CU, whose DIEs have
8325    already been loaded into memory.  */
8326
8327 static void
8328 process_full_comp_unit (struct dwarf2_per_cu_data *per_cu,
8329                         enum language pretend_language)
8330 {
8331   struct dwarf2_cu *cu = per_cu->cu;
8332   struct objfile *objfile = per_cu->objfile;
8333   struct gdbarch *gdbarch = get_objfile_arch (objfile);
8334   CORE_ADDR lowpc, highpc;
8335   struct compunit_symtab *cust;
8336   struct cleanup *back_to, *delayed_list_cleanup;
8337   CORE_ADDR baseaddr;
8338   struct block *static_block;
8339   CORE_ADDR addr;
8340
8341   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
8342
8343   buildsym_init ();
8344   back_to = make_cleanup (really_free_pendings, NULL);
8345   delayed_list_cleanup = make_cleanup (free_delayed_list, cu);
8346
8347   cu->list_in_scope = &file_symbols;
8348
8349   cu->language = pretend_language;
8350   cu->language_defn = language_def (cu->language);
8351
8352   /* Do line number decoding in read_file_scope () */
8353   process_die (cu->dies, cu);
8354
8355   /* For now fudge the Go package.  */
8356   if (cu->language == language_go)
8357     fixup_go_packaging (cu);
8358
8359   /* Now that we have processed all the DIEs in the CU, all the types 
8360      should be complete, and it should now be safe to compute all of the
8361      physnames.  */
8362   compute_delayed_physnames (cu);
8363   do_cleanups (delayed_list_cleanup);
8364
8365   /* Some compilers don't define a DW_AT_high_pc attribute for the
8366      compilation unit.  If the DW_AT_high_pc is missing, synthesize
8367      it, by scanning the DIE's below the compilation unit.  */
8368   get_scope_pc_bounds (cu->dies, &lowpc, &highpc, cu);
8369
8370   addr = gdbarch_adjust_dwarf2_addr (gdbarch, highpc + baseaddr);
8371   static_block = end_symtab_get_static_block (addr, 0, 1);
8372
8373   /* If the comp unit has DW_AT_ranges, it may have discontiguous ranges.
8374      Also, DW_AT_ranges may record ranges not belonging to any child DIEs
8375      (such as virtual method tables).  Record the ranges in STATIC_BLOCK's
8376      addrmap to help ensure it has an accurate map of pc values belonging to
8377      this comp unit.  */
8378   dwarf2_record_block_ranges (cu->dies, static_block, baseaddr, cu);
8379
8380   cust = end_symtab_from_static_block (static_block,
8381                                        SECT_OFF_TEXT (objfile), 0);
8382
8383   if (cust != NULL)
8384     {
8385       int gcc_4_minor = producer_is_gcc_ge_4 (cu->producer);
8386
8387       /* Set symtab language to language from DW_AT_language.  If the
8388          compilation is from a C file generated by language preprocessors, do
8389          not set the language if it was already deduced by start_subfile.  */
8390       if (!(cu->language == language_c
8391             && COMPUNIT_FILETABS (cust)->language != language_unknown))
8392         COMPUNIT_FILETABS (cust)->language = cu->language;
8393
8394       /* GCC-4.0 has started to support -fvar-tracking.  GCC-3.x still can
8395          produce DW_AT_location with location lists but it can be possibly
8396          invalid without -fvar-tracking.  Still up to GCC-4.4.x incl. 4.4.0
8397          there were bugs in prologue debug info, fixed later in GCC-4.5
8398          by "unwind info for epilogues" patch (which is not directly related).
8399
8400          For -gdwarf-4 type units LOCATIONS_VALID indication is fortunately not
8401          needed, it would be wrong due to missing DW_AT_producer there.
8402
8403          Still one can confuse GDB by using non-standard GCC compilation
8404          options - this waits on GCC PR other/32998 (-frecord-gcc-switches).
8405          */ 
8406       if (cu->has_loclist && gcc_4_minor >= 5)
8407         cust->locations_valid = 1;
8408
8409       if (gcc_4_minor >= 5)
8410         cust->epilogue_unwind_valid = 1;
8411
8412       cust->call_site_htab = cu->call_site_htab;
8413     }
8414
8415   if (dwarf2_per_objfile->using_index)
8416     per_cu->v.quick->compunit_symtab = cust;
8417   else
8418     {
8419       struct partial_symtab *pst = per_cu->v.psymtab;
8420       pst->compunit_symtab = cust;
8421       pst->readin = 1;
8422     }
8423
8424   /* Push it for inclusion processing later.  */
8425   VEC_safe_push (dwarf2_per_cu_ptr, dwarf2_per_objfile->just_read_cus, per_cu);
8426
8427   do_cleanups (back_to);
8428 }
8429
8430 /* Generate full symbol information for type unit PER_CU, whose DIEs have
8431    already been loaded into memory.  */
8432
8433 static void
8434 process_full_type_unit (struct dwarf2_per_cu_data *per_cu,
8435                         enum language pretend_language)
8436 {
8437   struct dwarf2_cu *cu = per_cu->cu;
8438   struct objfile *objfile = per_cu->objfile;
8439   struct compunit_symtab *cust;
8440   struct cleanup *back_to, *delayed_list_cleanup;
8441   struct signatured_type *sig_type;
8442
8443   gdb_assert (per_cu->is_debug_types);
8444   sig_type = (struct signatured_type *) per_cu;
8445
8446   buildsym_init ();
8447   back_to = make_cleanup (really_free_pendings, NULL);
8448   delayed_list_cleanup = make_cleanup (free_delayed_list, cu);
8449
8450   cu->list_in_scope = &file_symbols;
8451
8452   cu->language = pretend_language;
8453   cu->language_defn = language_def (cu->language);
8454
8455   /* The symbol tables are set up in read_type_unit_scope.  */
8456   process_die (cu->dies, cu);
8457
8458   /* For now fudge the Go package.  */
8459   if (cu->language == language_go)
8460     fixup_go_packaging (cu);
8461
8462   /* Now that we have processed all the DIEs in the CU, all the types 
8463      should be complete, and it should now be safe to compute all of the
8464      physnames.  */
8465   compute_delayed_physnames (cu);
8466   do_cleanups (delayed_list_cleanup);
8467
8468   /* TUs share symbol tables.
8469      If this is the first TU to use this symtab, complete the construction
8470      of it with end_expandable_symtab.  Otherwise, complete the addition of
8471      this TU's symbols to the existing symtab.  */
8472   if (sig_type->type_unit_group->compunit_symtab == NULL)
8473     {
8474       cust = end_expandable_symtab (0, SECT_OFF_TEXT (objfile));
8475       sig_type->type_unit_group->compunit_symtab = cust;
8476
8477       if (cust != NULL)
8478         {
8479           /* Set symtab language to language from DW_AT_language.  If the
8480              compilation is from a C file generated by language preprocessors,
8481              do not set the language if it was already deduced by
8482              start_subfile.  */
8483           if (!(cu->language == language_c
8484                 && COMPUNIT_FILETABS (cust)->language != language_c))
8485             COMPUNIT_FILETABS (cust)->language = cu->language;
8486         }
8487     }
8488   else
8489     {
8490       augment_type_symtab ();
8491       cust = sig_type->type_unit_group->compunit_symtab;
8492     }
8493
8494   if (dwarf2_per_objfile->using_index)
8495     per_cu->v.quick->compunit_symtab = cust;
8496   else
8497     {
8498       struct partial_symtab *pst = per_cu->v.psymtab;
8499       pst->compunit_symtab = cust;
8500       pst->readin = 1;
8501     }
8502
8503   do_cleanups (back_to);
8504 }
8505
8506 /* Process an imported unit DIE.  */
8507
8508 static void
8509 process_imported_unit_die (struct die_info *die, struct dwarf2_cu *cu)
8510 {
8511   struct attribute *attr;
8512
8513   /* For now we don't handle imported units in type units.  */
8514   if (cu->per_cu->is_debug_types)
8515     {
8516       error (_("Dwarf Error: DW_TAG_imported_unit is not"
8517                " supported in type units [in module %s]"),
8518              objfile_name (cu->objfile));
8519     }
8520
8521   attr = dwarf2_attr (die, DW_AT_import, cu);
8522   if (attr != NULL)
8523     {
8524       sect_offset sect_off = dwarf2_get_ref_die_offset (attr);
8525       bool is_dwz = (attr->form == DW_FORM_GNU_ref_alt || cu->per_cu->is_dwz);
8526       dwarf2_per_cu_data *per_cu
8527         = dwarf2_find_containing_comp_unit (sect_off, is_dwz, cu->objfile);
8528
8529       /* If necessary, add it to the queue and load its DIEs.  */
8530       if (maybe_queue_comp_unit (cu, per_cu, cu->language))
8531         load_full_comp_unit (per_cu, cu->language);
8532
8533       VEC_safe_push (dwarf2_per_cu_ptr, cu->per_cu->imported_symtabs,
8534                      per_cu);
8535     }
8536 }
8537
8538 /* RAII object that represents a process_die scope: i.e.,
8539    starts/finishes processing a DIE.  */
8540 class process_die_scope
8541 {
8542 public:
8543   process_die_scope (die_info *die, dwarf2_cu *cu)
8544     : m_die (die), m_cu (cu)
8545   {
8546     /* We should only be processing DIEs not already in process.  */
8547     gdb_assert (!m_die->in_process);
8548     m_die->in_process = true;
8549   }
8550
8551   ~process_die_scope ()
8552   {
8553     m_die->in_process = false;
8554
8555     /* If we're done processing the DIE for the CU that owns the line
8556        header, we don't need the line header anymore.  */
8557     if (m_cu->line_header_die_owner == m_die)
8558       {
8559         delete m_cu->line_header;
8560         m_cu->line_header = NULL;
8561         m_cu->line_header_die_owner = NULL;
8562       }
8563   }
8564
8565 private:
8566   die_info *m_die;
8567   dwarf2_cu *m_cu;
8568 };
8569
8570 /* Process a die and its children.  */
8571
8572 static void
8573 process_die (struct die_info *die, struct dwarf2_cu *cu)
8574 {
8575   process_die_scope scope (die, cu);
8576
8577   switch (die->tag)
8578     {
8579     case DW_TAG_padding:
8580       break;
8581     case DW_TAG_compile_unit:
8582     case DW_TAG_partial_unit:
8583       read_file_scope (die, cu);
8584       break;
8585     case DW_TAG_type_unit:
8586       read_type_unit_scope (die, cu);
8587       break;
8588     case DW_TAG_subprogram:
8589     case DW_TAG_inlined_subroutine:
8590       read_func_scope (die, cu);
8591       break;
8592     case DW_TAG_lexical_block:
8593     case DW_TAG_try_block:
8594     case DW_TAG_catch_block:
8595       read_lexical_block_scope (die, cu);
8596       break;
8597     case DW_TAG_call_site:
8598     case DW_TAG_GNU_call_site:
8599       read_call_site_scope (die, cu);
8600       break;
8601     case DW_TAG_class_type:
8602     case DW_TAG_interface_type:
8603     case DW_TAG_structure_type:
8604     case DW_TAG_union_type:
8605       process_structure_scope (die, cu);
8606       break;
8607     case DW_TAG_enumeration_type:
8608       process_enumeration_scope (die, cu);
8609       break;
8610
8611     /* These dies have a type, but processing them does not create
8612        a symbol or recurse to process the children.  Therefore we can
8613        read them on-demand through read_type_die.  */
8614     case DW_TAG_subroutine_type:
8615     case DW_TAG_set_type:
8616     case DW_TAG_array_type:
8617     case DW_TAG_pointer_type:
8618     case DW_TAG_ptr_to_member_type:
8619     case DW_TAG_reference_type:
8620     case DW_TAG_rvalue_reference_type:
8621     case DW_TAG_string_type:
8622       break;
8623
8624     case DW_TAG_base_type:
8625     case DW_TAG_subrange_type:
8626     case DW_TAG_typedef:
8627       /* Add a typedef symbol for the type definition, if it has a
8628          DW_AT_name.  */
8629       new_symbol (die, read_type_die (die, cu), cu);
8630       break;
8631     case DW_TAG_common_block:
8632       read_common_block (die, cu);
8633       break;
8634     case DW_TAG_common_inclusion:
8635       break;
8636     case DW_TAG_namespace:
8637       cu->processing_has_namespace_info = 1;
8638       read_namespace (die, cu);
8639       break;
8640     case DW_TAG_module:
8641       cu->processing_has_namespace_info = 1;
8642       read_module (die, cu);
8643       break;
8644     case DW_TAG_imported_declaration:
8645       cu->processing_has_namespace_info = 1;
8646       if (read_namespace_alias (die, cu))
8647         break;
8648       /* The declaration is not a global namespace alias: fall through.  */
8649     case DW_TAG_imported_module:
8650       cu->processing_has_namespace_info = 1;
8651       if (die->child != NULL && (die->tag == DW_TAG_imported_declaration
8652                                  || cu->language != language_fortran))
8653         complaint (&symfile_complaints, _("Tag '%s' has unexpected children"),
8654                    dwarf_tag_name (die->tag));
8655       read_import_statement (die, cu);
8656       break;
8657
8658     case DW_TAG_imported_unit:
8659       process_imported_unit_die (die, cu);
8660       break;
8661
8662     default:
8663       new_symbol (die, NULL, cu);
8664       break;
8665     }
8666 }
8667 \f
8668 /* DWARF name computation.  */
8669
8670 /* A helper function for dwarf2_compute_name which determines whether DIE
8671    needs to have the name of the scope prepended to the name listed in the
8672    die.  */
8673
8674 static int
8675 die_needs_namespace (struct die_info *die, struct dwarf2_cu *cu)
8676 {
8677   struct attribute *attr;
8678
8679   switch (die->tag)
8680     {
8681     case DW_TAG_namespace:
8682     case DW_TAG_typedef:
8683     case DW_TAG_class_type:
8684     case DW_TAG_interface_type:
8685     case DW_TAG_structure_type:
8686     case DW_TAG_union_type:
8687     case DW_TAG_enumeration_type:
8688     case DW_TAG_enumerator:
8689     case DW_TAG_subprogram:
8690     case DW_TAG_inlined_subroutine:
8691     case DW_TAG_member:
8692     case DW_TAG_imported_declaration:
8693       return 1;
8694
8695     case DW_TAG_variable:
8696     case DW_TAG_constant:
8697       /* We only need to prefix "globally" visible variables.  These include
8698          any variable marked with DW_AT_external or any variable that
8699          lives in a namespace.  [Variables in anonymous namespaces
8700          require prefixing, but they are not DW_AT_external.]  */
8701
8702       if (dwarf2_attr (die, DW_AT_specification, cu))
8703         {
8704           struct dwarf2_cu *spec_cu = cu;
8705
8706           return die_needs_namespace (die_specification (die, &spec_cu),
8707                                       spec_cu);
8708         }
8709
8710       attr = dwarf2_attr (die, DW_AT_external, cu);
8711       if (attr == NULL && die->parent->tag != DW_TAG_namespace
8712           && die->parent->tag != DW_TAG_module)
8713         return 0;
8714       /* A variable in a lexical block of some kind does not need a
8715          namespace, even though in C++ such variables may be external
8716          and have a mangled name.  */
8717       if (die->parent->tag ==  DW_TAG_lexical_block
8718           || die->parent->tag ==  DW_TAG_try_block
8719           || die->parent->tag ==  DW_TAG_catch_block
8720           || die->parent->tag == DW_TAG_subprogram)
8721         return 0;
8722       return 1;
8723
8724     default:
8725       return 0;
8726     }
8727 }
8728
8729 /* Return the DIE's linkage name attribute, either DW_AT_linkage_name
8730    or DW_AT_MIPS_linkage_name.  Returns NULL if the attribute is not
8731    defined for the given DIE.  */
8732
8733 static struct attribute *
8734 dw2_linkage_name_attr (struct die_info *die, struct dwarf2_cu *cu)
8735 {
8736   struct attribute *attr;
8737
8738   attr = dwarf2_attr (die, DW_AT_linkage_name, cu);
8739   if (attr == NULL)
8740     attr = dwarf2_attr (die, DW_AT_MIPS_linkage_name, cu);
8741
8742   return attr;
8743 }
8744
8745 /* Return the DIE's linkage name as a string, either DW_AT_linkage_name
8746    or DW_AT_MIPS_linkage_name.  Returns NULL if the attribute is not
8747    defined for the given DIE.  */
8748
8749 static const char *
8750 dw2_linkage_name (struct die_info *die, struct dwarf2_cu *cu)
8751 {
8752   const char *linkage_name;
8753
8754   linkage_name = dwarf2_string_attr (die, DW_AT_linkage_name, cu);
8755   if (linkage_name == NULL)
8756     linkage_name = dwarf2_string_attr (die, DW_AT_MIPS_linkage_name, cu);
8757
8758   return linkage_name;
8759 }
8760
8761 /* Compute the fully qualified name of DIE in CU.  If PHYSNAME is nonzero,
8762    compute the physname for the object, which include a method's:
8763    - formal parameters (C++),
8764    - receiver type (Go),
8765
8766    The term "physname" is a bit confusing.
8767    For C++, for example, it is the demangled name.
8768    For Go, for example, it's the mangled name.
8769
8770    For Ada, return the DIE's linkage name rather than the fully qualified
8771    name.  PHYSNAME is ignored..
8772
8773    The result is allocated on the objfile_obstack and canonicalized.  */
8774
8775 static const char *
8776 dwarf2_compute_name (const char *name,
8777                      struct die_info *die, struct dwarf2_cu *cu,
8778                      int physname)
8779 {
8780   struct objfile *objfile = cu->objfile;
8781
8782   if (name == NULL)
8783     name = dwarf2_name (die, cu);
8784
8785   /* For Fortran GDB prefers DW_AT_*linkage_name for the physname if present
8786      but otherwise compute it by typename_concat inside GDB.
8787      FIXME: Actually this is not really true, or at least not always true.
8788      It's all very confusing.  SYMBOL_SET_NAMES doesn't try to demangle
8789      Fortran names because there is no mangling standard.  So new_symbol_full
8790      will set the demangled name to the result of dwarf2_full_name, and it is
8791      the demangled name that GDB uses if it exists.  */
8792   if (cu->language == language_ada
8793       || (cu->language == language_fortran && physname))
8794     {
8795       /* For Ada unit, we prefer the linkage name over the name, as
8796          the former contains the exported name, which the user expects
8797          to be able to reference.  Ideally, we want the user to be able
8798          to reference this entity using either natural or linkage name,
8799          but we haven't started looking at this enhancement yet.  */
8800       const char *linkage_name = dw2_linkage_name (die, cu);
8801
8802       if (linkage_name != NULL)
8803         return linkage_name;
8804     }
8805
8806   /* These are the only languages we know how to qualify names in.  */
8807   if (name != NULL
8808       && (cu->language == language_cplus
8809           || cu->language == language_fortran || cu->language == language_d
8810           || cu->language == language_rust))
8811     {
8812       if (die_needs_namespace (die, cu))
8813         {
8814           long length;
8815           const char *prefix;
8816           const char *canonical_name = NULL;
8817
8818           string_file buf;
8819
8820           prefix = determine_prefix (die, cu);
8821           if (*prefix != '\0')
8822             {
8823               char *prefixed_name = typename_concat (NULL, prefix, name,
8824                                                      physname, cu);
8825
8826               buf.puts (prefixed_name);
8827               xfree (prefixed_name);
8828             }
8829           else
8830             buf.puts (name);
8831
8832           /* Template parameters may be specified in the DIE's DW_AT_name, or
8833              as children with DW_TAG_template_type_param or
8834              DW_TAG_value_type_param.  If the latter, add them to the name
8835              here.  If the name already has template parameters, then
8836              skip this step; some versions of GCC emit both, and
8837              it is more efficient to use the pre-computed name.
8838
8839              Something to keep in mind about this process: it is very
8840              unlikely, or in some cases downright impossible, to produce
8841              something that will match the mangled name of a function.
8842              If the definition of the function has the same debug info,
8843              we should be able to match up with it anyway.  But fallbacks
8844              using the minimal symbol, for instance to find a method
8845              implemented in a stripped copy of libstdc++, will not work.
8846              If we do not have debug info for the definition, we will have to
8847              match them up some other way.
8848
8849              When we do name matching there is a related problem with function
8850              templates; two instantiated function templates are allowed to
8851              differ only by their return types, which we do not add here.  */
8852
8853           if (cu->language == language_cplus && strchr (name, '<') == NULL)
8854             {
8855               struct attribute *attr;
8856               struct die_info *child;
8857               int first = 1;
8858
8859               die->building_fullname = 1;
8860
8861               for (child = die->child; child != NULL; child = child->sibling)
8862                 {
8863                   struct type *type;
8864                   LONGEST value;
8865                   const gdb_byte *bytes;
8866                   struct dwarf2_locexpr_baton *baton;
8867                   struct value *v;
8868
8869                   if (child->tag != DW_TAG_template_type_param
8870                       && child->tag != DW_TAG_template_value_param)
8871                     continue;
8872
8873                   if (first)
8874                     {
8875                       buf.puts ("<");
8876                       first = 0;
8877                     }
8878                   else
8879                     buf.puts (", ");
8880
8881                   attr = dwarf2_attr (child, DW_AT_type, cu);
8882                   if (attr == NULL)
8883                     {
8884                       complaint (&symfile_complaints,
8885                                  _("template parameter missing DW_AT_type"));
8886                       buf.puts ("UNKNOWN_TYPE");
8887                       continue;
8888                     }
8889                   type = die_type (child, cu);
8890
8891                   if (child->tag == DW_TAG_template_type_param)
8892                     {
8893                       c_print_type (type, "", &buf, -1, 0, &type_print_raw_options);
8894                       continue;
8895                     }
8896
8897                   attr = dwarf2_attr (child, DW_AT_const_value, cu);
8898                   if (attr == NULL)
8899                     {
8900                       complaint (&symfile_complaints,
8901                                  _("template parameter missing "
8902                                    "DW_AT_const_value"));
8903                       buf.puts ("UNKNOWN_VALUE");
8904                       continue;
8905                     }
8906
8907                   dwarf2_const_value_attr (attr, type, name,
8908                                            &cu->comp_unit_obstack, cu,
8909                                            &value, &bytes, &baton);
8910
8911                   if (TYPE_NOSIGN (type))
8912                     /* GDB prints characters as NUMBER 'CHAR'.  If that's
8913                        changed, this can use value_print instead.  */
8914                     c_printchar (value, type, &buf);
8915                   else
8916                     {
8917                       struct value_print_options opts;
8918
8919                       if (baton != NULL)
8920                         v = dwarf2_evaluate_loc_desc (type, NULL,
8921                                                       baton->data,
8922                                                       baton->size,
8923                                                       baton->per_cu);
8924                       else if (bytes != NULL)
8925                         {
8926                           v = allocate_value (type);
8927                           memcpy (value_contents_writeable (v), bytes,
8928                                   TYPE_LENGTH (type));
8929                         }
8930                       else
8931                         v = value_from_longest (type, value);
8932
8933                       /* Specify decimal so that we do not depend on
8934                          the radix.  */
8935                       get_formatted_print_options (&opts, 'd');
8936                       opts.raw = 1;
8937                       value_print (v, &buf, &opts);
8938                       release_value (v);
8939                       value_free (v);
8940                     }
8941                 }
8942
8943               die->building_fullname = 0;
8944
8945               if (!first)
8946                 {
8947                   /* Close the argument list, with a space if necessary
8948                      (nested templates).  */
8949                   if (!buf.empty () && buf.string ().back () == '>')
8950                     buf.puts (" >");
8951                   else
8952                     buf.puts (">");
8953                 }
8954             }
8955
8956           /* For C++ methods, append formal parameter type
8957              information, if PHYSNAME.  */
8958
8959           if (physname && die->tag == DW_TAG_subprogram
8960               && cu->language == language_cplus)
8961             {
8962               struct type *type = read_type_die (die, cu);
8963
8964               c_type_print_args (type, &buf, 1, cu->language,
8965                                  &type_print_raw_options);
8966
8967               if (cu->language == language_cplus)
8968                 {
8969                   /* Assume that an artificial first parameter is
8970                      "this", but do not crash if it is not.  RealView
8971                      marks unnamed (and thus unused) parameters as
8972                      artificial; there is no way to differentiate
8973                      the two cases.  */
8974                   if (TYPE_NFIELDS (type) > 0
8975                       && TYPE_FIELD_ARTIFICIAL (type, 0)
8976                       && TYPE_CODE (TYPE_FIELD_TYPE (type, 0)) == TYPE_CODE_PTR
8977                       && TYPE_CONST (TYPE_TARGET_TYPE (TYPE_FIELD_TYPE (type,
8978                                                                         0))))
8979                     buf.puts (" const");
8980                 }
8981             }
8982
8983           const std::string &intermediate_name = buf.string ();
8984
8985           if (cu->language == language_cplus)
8986             canonical_name
8987               = dwarf2_canonicalize_name (intermediate_name.c_str (), cu,
8988                                           &objfile->per_bfd->storage_obstack);
8989
8990           /* If we only computed INTERMEDIATE_NAME, or if
8991              INTERMEDIATE_NAME is already canonical, then we need to
8992              copy it to the appropriate obstack.  */
8993           if (canonical_name == NULL || canonical_name == intermediate_name.c_str ())
8994             name = ((const char *)
8995                     obstack_copy0 (&objfile->per_bfd->storage_obstack,
8996                                    intermediate_name.c_str (),
8997                                    intermediate_name.length ()));
8998           else
8999             name = canonical_name;
9000         }
9001     }
9002
9003   return name;
9004 }
9005
9006 /* Return the fully qualified name of DIE, based on its DW_AT_name.
9007    If scope qualifiers are appropriate they will be added.  The result
9008    will be allocated on the storage_obstack, or NULL if the DIE does
9009    not have a name.  NAME may either be from a previous call to
9010    dwarf2_name or NULL.
9011
9012    The output string will be canonicalized (if C++).  */
9013
9014 static const char *
9015 dwarf2_full_name (const char *name, struct die_info *die, struct dwarf2_cu *cu)
9016 {
9017   return dwarf2_compute_name (name, die, cu, 0);
9018 }
9019
9020 /* Construct a physname for the given DIE in CU.  NAME may either be
9021    from a previous call to dwarf2_name or NULL.  The result will be
9022    allocated on the objfile_objstack or NULL if the DIE does not have a
9023    name.
9024
9025    The output string will be canonicalized (if C++).  */
9026
9027 static const char *
9028 dwarf2_physname (const char *name, struct die_info *die, struct dwarf2_cu *cu)
9029 {
9030   struct objfile *objfile = cu->objfile;
9031   const char *retval, *mangled = NULL, *canon = NULL;
9032   struct cleanup *back_to;
9033   int need_copy = 1;
9034
9035   /* In this case dwarf2_compute_name is just a shortcut not building anything
9036      on its own.  */
9037   if (!die_needs_namespace (die, cu))
9038     return dwarf2_compute_name (name, die, cu, 1);
9039
9040   back_to = make_cleanup (null_cleanup, NULL);
9041
9042   mangled = dw2_linkage_name (die, cu);
9043
9044   /* rustc emits invalid values for DW_AT_linkage_name.  Ignore these.
9045      See https://github.com/rust-lang/rust/issues/32925.  */
9046   if (cu->language == language_rust && mangled != NULL
9047       && strchr (mangled, '{') != NULL)
9048     mangled = NULL;
9049
9050   /* DW_AT_linkage_name is missing in some cases - depend on what GDB
9051      has computed.  */
9052   if (mangled != NULL)
9053     {
9054       char *demangled;
9055
9056       /* Use DMGL_RET_DROP for C++ template functions to suppress their return
9057          type.  It is easier for GDB users to search for such functions as
9058          `name(params)' than `long name(params)'.  In such case the minimal
9059          symbol names do not match the full symbol names but for template
9060          functions there is never a need to look up their definition from their
9061          declaration so the only disadvantage remains the minimal symbol
9062          variant `long name(params)' does not have the proper inferior type.
9063          */
9064
9065       if (cu->language == language_go)
9066         {
9067           /* This is a lie, but we already lie to the caller new_symbol_full.
9068              new_symbol_full assumes we return the mangled name.
9069              This just undoes that lie until things are cleaned up.  */
9070           demangled = NULL;
9071         }
9072       else
9073         {
9074           demangled = gdb_demangle (mangled,
9075                                     (DMGL_PARAMS | DMGL_ANSI | DMGL_RET_DROP));
9076         }
9077       if (demangled)
9078         {
9079           make_cleanup (xfree, demangled);
9080           canon = demangled;
9081         }
9082       else
9083         {
9084           canon = mangled;
9085           need_copy = 0;
9086         }
9087     }
9088
9089   if (canon == NULL || check_physname)
9090     {
9091       const char *physname = dwarf2_compute_name (name, die, cu, 1);
9092
9093       if (canon != NULL && strcmp (physname, canon) != 0)
9094         {
9095           /* It may not mean a bug in GDB.  The compiler could also
9096              compute DW_AT_linkage_name incorrectly.  But in such case
9097              GDB would need to be bug-to-bug compatible.  */
9098
9099           complaint (&symfile_complaints,
9100                      _("Computed physname <%s> does not match demangled <%s> "
9101                        "(from linkage <%s>) - DIE at 0x%x [in module %s]"),
9102                      physname, canon, mangled, to_underlying (die->sect_off),
9103                      objfile_name (objfile));
9104
9105           /* Prefer DW_AT_linkage_name (in the CANON form) - when it
9106              is available here - over computed PHYSNAME.  It is safer
9107              against both buggy GDB and buggy compilers.  */
9108
9109           retval = canon;
9110         }
9111       else
9112         {
9113           retval = physname;
9114           need_copy = 0;
9115         }
9116     }
9117   else
9118     retval = canon;
9119
9120   if (need_copy)
9121     retval = ((const char *)
9122               obstack_copy0 (&objfile->per_bfd->storage_obstack,
9123                              retval, strlen (retval)));
9124
9125   do_cleanups (back_to);
9126   return retval;
9127 }
9128
9129 /* Inspect DIE in CU for a namespace alias.  If one exists, record
9130    a new symbol for it.
9131
9132    Returns 1 if a namespace alias was recorded, 0 otherwise.  */
9133
9134 static int
9135 read_namespace_alias (struct die_info *die, struct dwarf2_cu *cu)
9136 {
9137   struct attribute *attr;
9138
9139   /* If the die does not have a name, this is not a namespace
9140      alias.  */
9141   attr = dwarf2_attr (die, DW_AT_name, cu);
9142   if (attr != NULL)
9143     {
9144       int num;
9145       struct die_info *d = die;
9146       struct dwarf2_cu *imported_cu = cu;
9147
9148       /* If the compiler has nested DW_AT_imported_declaration DIEs,
9149          keep inspecting DIEs until we hit the underlying import.  */
9150 #define MAX_NESTED_IMPORTED_DECLARATIONS 100
9151       for (num = 0; num  < MAX_NESTED_IMPORTED_DECLARATIONS; ++num)
9152         {
9153           attr = dwarf2_attr (d, DW_AT_import, cu);
9154           if (attr == NULL)
9155             break;
9156
9157           d = follow_die_ref (d, attr, &imported_cu);
9158           if (d->tag != DW_TAG_imported_declaration)
9159             break;
9160         }
9161
9162       if (num == MAX_NESTED_IMPORTED_DECLARATIONS)
9163         {
9164           complaint (&symfile_complaints,
9165                      _("DIE at 0x%x has too many recursively imported "
9166                        "declarations"), to_underlying (d->sect_off));
9167           return 0;
9168         }
9169
9170       if (attr != NULL)
9171         {
9172           struct type *type;
9173           sect_offset sect_off = dwarf2_get_ref_die_offset (attr);
9174
9175           type = get_die_type_at_offset (sect_off, cu->per_cu);
9176           if (type != NULL && TYPE_CODE (type) == TYPE_CODE_NAMESPACE)
9177             {
9178               /* This declaration is a global namespace alias.  Add
9179                  a symbol for it whose type is the aliased namespace.  */
9180               new_symbol (die, type, cu);
9181               return 1;
9182             }
9183         }
9184     }
9185
9186   return 0;
9187 }
9188
9189 /* Return the using directives repository (global or local?) to use in the
9190    current context for LANGUAGE.
9191
9192    For Ada, imported declarations can materialize renamings, which *may* be
9193    global.  However it is impossible (for now?) in DWARF to distinguish
9194    "external" imported declarations and "static" ones.  As all imported
9195    declarations seem to be static in all other languages, make them all CU-wide
9196    global only in Ada.  */
9197
9198 static struct using_direct **
9199 using_directives (enum language language)
9200 {
9201   if (language == language_ada && context_stack_depth == 0)
9202     return &global_using_directives;
9203   else
9204     return &local_using_directives;
9205 }
9206
9207 /* Read the import statement specified by the given die and record it.  */
9208
9209 static void
9210 read_import_statement (struct die_info *die, struct dwarf2_cu *cu)
9211 {
9212   struct objfile *objfile = cu->objfile;
9213   struct attribute *import_attr;
9214   struct die_info *imported_die, *child_die;
9215   struct dwarf2_cu *imported_cu;
9216   const char *imported_name;
9217   const char *imported_name_prefix;
9218   const char *canonical_name;
9219   const char *import_alias;
9220   const char *imported_declaration = NULL;
9221   const char *import_prefix;
9222   std::vector<const char *> excludes;
9223
9224   import_attr = dwarf2_attr (die, DW_AT_import, cu);
9225   if (import_attr == NULL)
9226     {
9227       complaint (&symfile_complaints, _("Tag '%s' has no DW_AT_import"),
9228                  dwarf_tag_name (die->tag));
9229       return;
9230     }
9231
9232   imported_cu = cu;
9233   imported_die = follow_die_ref_or_sig (die, import_attr, &imported_cu);
9234   imported_name = dwarf2_name (imported_die, imported_cu);
9235   if (imported_name == NULL)
9236     {
9237       /* GCC bug: https://bugzilla.redhat.com/show_bug.cgi?id=506524
9238
9239         The import in the following code:
9240         namespace A
9241           {
9242             typedef int B;
9243           }
9244
9245         int main ()
9246           {
9247             using A::B;
9248             B b;
9249             return b;
9250           }
9251
9252         ...
9253          <2><51>: Abbrev Number: 3 (DW_TAG_imported_declaration)
9254             <52>   DW_AT_decl_file   : 1
9255             <53>   DW_AT_decl_line   : 6
9256             <54>   DW_AT_import      : <0x75>
9257          <2><58>: Abbrev Number: 4 (DW_TAG_typedef)
9258             <59>   DW_AT_name        : B
9259             <5b>   DW_AT_decl_file   : 1
9260             <5c>   DW_AT_decl_line   : 2
9261             <5d>   DW_AT_type        : <0x6e>
9262         ...
9263          <1><75>: Abbrev Number: 7 (DW_TAG_base_type)
9264             <76>   DW_AT_byte_size   : 4
9265             <77>   DW_AT_encoding    : 5        (signed)
9266
9267         imports the wrong die ( 0x75 instead of 0x58 ).
9268         This case will be ignored until the gcc bug is fixed.  */
9269       return;
9270     }
9271
9272   /* Figure out the local name after import.  */
9273   import_alias = dwarf2_name (die, cu);
9274
9275   /* Figure out where the statement is being imported to.  */
9276   import_prefix = determine_prefix (die, cu);
9277
9278   /* Figure out what the scope of the imported die is and prepend it
9279      to the name of the imported die.  */
9280   imported_name_prefix = determine_prefix (imported_die, imported_cu);
9281
9282   if (imported_die->tag != DW_TAG_namespace
9283       && imported_die->tag != DW_TAG_module)
9284     {
9285       imported_declaration = imported_name;
9286       canonical_name = imported_name_prefix;
9287     }
9288   else if (strlen (imported_name_prefix) > 0)
9289     canonical_name = obconcat (&objfile->objfile_obstack,
9290                                imported_name_prefix,
9291                                (cu->language == language_d ? "." : "::"),
9292                                imported_name, (char *) NULL);
9293   else
9294     canonical_name = imported_name;
9295
9296   if (die->tag == DW_TAG_imported_module && cu->language == language_fortran)
9297     for (child_die = die->child; child_die && child_die->tag;
9298          child_die = sibling_die (child_die))
9299       {
9300         /* DWARF-4: A Fortran use statement with a “rename list” may be
9301            represented by an imported module entry with an import attribute
9302            referring to the module and owned entries corresponding to those
9303            entities that are renamed as part of being imported.  */
9304
9305         if (child_die->tag != DW_TAG_imported_declaration)
9306           {
9307             complaint (&symfile_complaints,
9308                        _("child DW_TAG_imported_declaration expected "
9309                          "- DIE at 0x%x [in module %s]"),
9310                        to_underlying (child_die->sect_off), objfile_name (objfile));
9311             continue;
9312           }
9313
9314         import_attr = dwarf2_attr (child_die, DW_AT_import, cu);
9315         if (import_attr == NULL)
9316           {
9317             complaint (&symfile_complaints, _("Tag '%s' has no DW_AT_import"),
9318                        dwarf_tag_name (child_die->tag));
9319             continue;
9320           }
9321
9322         imported_cu = cu;
9323         imported_die = follow_die_ref_or_sig (child_die, import_attr,
9324                                               &imported_cu);
9325         imported_name = dwarf2_name (imported_die, imported_cu);
9326         if (imported_name == NULL)
9327           {
9328             complaint (&symfile_complaints,
9329                        _("child DW_TAG_imported_declaration has unknown "
9330                          "imported name - DIE at 0x%x [in module %s]"),
9331                        to_underlying (child_die->sect_off), objfile_name (objfile));
9332             continue;
9333           }
9334
9335         excludes.push_back (imported_name);
9336
9337         process_die (child_die, cu);
9338       }
9339
9340   add_using_directive (using_directives (cu->language),
9341                        import_prefix,
9342                        canonical_name,
9343                        import_alias,
9344                        imported_declaration,
9345                        excludes,
9346                        0,
9347                        &objfile->objfile_obstack);
9348 }
9349
9350 /* Check for possibly missing DW_AT_comp_dir with relative .debug_line
9351    directory paths.  GCC SVN r127613 (new option -fdebug-prefix-map) fixed
9352    this, it was first present in GCC release 4.3.0.  */
9353
9354 static int
9355 producer_is_gcc_lt_4_3 (struct dwarf2_cu *cu)
9356 {
9357   if (!cu->checked_producer)
9358     check_producer (cu);
9359
9360   return cu->producer_is_gcc_lt_4_3;
9361 }
9362
9363 static file_and_directory
9364 find_file_and_directory (struct die_info *die, struct dwarf2_cu *cu)
9365 {
9366   file_and_directory res;
9367
9368   /* Find the filename.  Do not use dwarf2_name here, since the filename
9369      is not a source language identifier.  */
9370   res.name = dwarf2_string_attr (die, DW_AT_name, cu);
9371   res.comp_dir = dwarf2_string_attr (die, DW_AT_comp_dir, cu);
9372
9373   if (res.comp_dir == NULL
9374       && producer_is_gcc_lt_4_3 (cu) && res.name != NULL
9375       && IS_ABSOLUTE_PATH (res.name))
9376     {
9377       res.comp_dir_storage = ldirname (res.name);
9378       if (!res.comp_dir_storage.empty ())
9379         res.comp_dir = res.comp_dir_storage.c_str ();
9380     }
9381   if (res.comp_dir != NULL)
9382     {
9383       /* Irix 6.2 native cc prepends <machine>.: to the compilation
9384          directory, get rid of it.  */
9385       const char *cp = strchr (res.comp_dir, ':');
9386
9387       if (cp && cp != res.comp_dir && cp[-1] == '.' && cp[1] == '/')
9388         res.comp_dir = cp + 1;
9389     }
9390
9391   if (res.name == NULL)
9392     res.name = "<unknown>";
9393
9394   return res;
9395 }
9396
9397 /* Handle DW_AT_stmt_list for a compilation unit.
9398    DIE is the DW_TAG_compile_unit die for CU.
9399    COMP_DIR is the compilation directory.  LOWPC is passed to
9400    dwarf_decode_lines.  See dwarf_decode_lines comments about it.  */
9401
9402 static void
9403 handle_DW_AT_stmt_list (struct die_info *die, struct dwarf2_cu *cu,
9404                         const char *comp_dir, CORE_ADDR lowpc) /* ARI: editCase function */
9405 {
9406   struct objfile *objfile = dwarf2_per_objfile->objfile;
9407   struct attribute *attr;
9408   struct line_header line_header_local;
9409   hashval_t line_header_local_hash;
9410   unsigned u;
9411   void **slot;
9412   int decode_mapping;
9413
9414   gdb_assert (! cu->per_cu->is_debug_types);
9415
9416   attr = dwarf2_attr (die, DW_AT_stmt_list, cu);
9417   if (attr == NULL)
9418     return;
9419
9420   sect_offset line_offset = (sect_offset) DW_UNSND (attr);
9421
9422   /* The line header hash table is only created if needed (it exists to
9423      prevent redundant reading of the line table for partial_units).
9424      If we're given a partial_unit, we'll need it.  If we're given a
9425      compile_unit, then use the line header hash table if it's already
9426      created, but don't create one just yet.  */
9427
9428   if (dwarf2_per_objfile->line_header_hash == NULL
9429       && die->tag == DW_TAG_partial_unit)
9430     {
9431       dwarf2_per_objfile->line_header_hash
9432         = htab_create_alloc_ex (127, line_header_hash_voidp,
9433                                 line_header_eq_voidp,
9434                                 free_line_header_voidp,
9435                                 &objfile->objfile_obstack,
9436                                 hashtab_obstack_allocate,
9437                                 dummy_obstack_deallocate);
9438     }
9439
9440   line_header_local.sect_off = line_offset;
9441   line_header_local.offset_in_dwz = cu->per_cu->is_dwz;
9442   line_header_local_hash = line_header_hash (&line_header_local);
9443   if (dwarf2_per_objfile->line_header_hash != NULL)
9444     {
9445       slot = htab_find_slot_with_hash (dwarf2_per_objfile->line_header_hash,
9446                                        &line_header_local,
9447                                        line_header_local_hash, NO_INSERT);
9448
9449       /* For DW_TAG_compile_unit we need info like symtab::linetable which
9450          is not present in *SLOT (since if there is something in *SLOT then
9451          it will be for a partial_unit).  */
9452       if (die->tag == DW_TAG_partial_unit && slot != NULL)
9453         {
9454           gdb_assert (*slot != NULL);
9455           cu->line_header = (struct line_header *) *slot;
9456           return;
9457         }
9458     }
9459
9460   /* dwarf_decode_line_header does not yet provide sufficient information.
9461      We always have to call also dwarf_decode_lines for it.  */
9462   line_header_up lh = dwarf_decode_line_header (line_offset, cu);
9463   if (lh == NULL)
9464     return;
9465
9466   cu->line_header = lh.release ();
9467   cu->line_header_die_owner = die;
9468
9469   if (dwarf2_per_objfile->line_header_hash == NULL)
9470     slot = NULL;
9471   else
9472     {
9473       slot = htab_find_slot_with_hash (dwarf2_per_objfile->line_header_hash,
9474                                        &line_header_local,
9475                                        line_header_local_hash, INSERT);
9476       gdb_assert (slot != NULL);
9477     }
9478   if (slot != NULL && *slot == NULL)
9479     {
9480       /* This newly decoded line number information unit will be owned
9481          by line_header_hash hash table.  */
9482       *slot = cu->line_header;
9483       cu->line_header_die_owner = NULL;
9484     }
9485   else
9486     {
9487       /* We cannot free any current entry in (*slot) as that struct line_header
9488          may be already used by multiple CUs.  Create only temporary decoded
9489          line_header for this CU - it may happen at most once for each line
9490          number information unit.  And if we're not using line_header_hash
9491          then this is what we want as well.  */
9492       gdb_assert (die->tag != DW_TAG_partial_unit);
9493     }
9494   decode_mapping = (die->tag != DW_TAG_partial_unit);
9495   dwarf_decode_lines (cu->line_header, comp_dir, cu, NULL, lowpc,
9496                       decode_mapping);
9497
9498 }
9499
9500 /* Process DW_TAG_compile_unit or DW_TAG_partial_unit.  */
9501
9502 static void
9503 read_file_scope (struct die_info *die, struct dwarf2_cu *cu)
9504 {
9505   struct objfile *objfile = dwarf2_per_objfile->objfile;
9506   struct gdbarch *gdbarch = get_objfile_arch (objfile);
9507   CORE_ADDR lowpc = ((CORE_ADDR) -1);
9508   CORE_ADDR highpc = ((CORE_ADDR) 0);
9509   struct attribute *attr;
9510   struct die_info *child_die;
9511   CORE_ADDR baseaddr;
9512
9513   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
9514
9515   get_scope_pc_bounds (die, &lowpc, &highpc, cu);
9516
9517   /* If we didn't find a lowpc, set it to highpc to avoid complaints
9518      from finish_block.  */
9519   if (lowpc == ((CORE_ADDR) -1))
9520     lowpc = highpc;
9521   lowpc = gdbarch_adjust_dwarf2_addr (gdbarch, lowpc + baseaddr);
9522
9523   file_and_directory fnd = find_file_and_directory (die, cu);
9524
9525   prepare_one_comp_unit (cu, die, cu->language);
9526
9527   /* The XLCL doesn't generate DW_LANG_OpenCL because this attribute is not
9528      standardised yet.  As a workaround for the language detection we fall
9529      back to the DW_AT_producer string.  */
9530   if (cu->producer && strstr (cu->producer, "IBM XL C for OpenCL") != NULL)
9531     cu->language = language_opencl;
9532
9533   /* Similar hack for Go.  */
9534   if (cu->producer && strstr (cu->producer, "GNU Go ") != NULL)
9535     set_cu_language (DW_LANG_Go, cu);
9536
9537   dwarf2_start_symtab (cu, fnd.name, fnd.comp_dir, lowpc);
9538
9539   /* Decode line number information if present.  We do this before
9540      processing child DIEs, so that the line header table is available
9541      for DW_AT_decl_file.  */
9542   handle_DW_AT_stmt_list (die, cu, fnd.comp_dir, lowpc);
9543
9544   /* Process all dies in compilation unit.  */
9545   if (die->child != NULL)
9546     {
9547       child_die = die->child;
9548       while (child_die && child_die->tag)
9549         {
9550           process_die (child_die, cu);
9551           child_die = sibling_die (child_die);
9552         }
9553     }
9554
9555   /* Decode macro information, if present.  Dwarf 2 macro information
9556      refers to information in the line number info statement program
9557      header, so we can only read it if we've read the header
9558      successfully.  */
9559   attr = dwarf2_attr (die, DW_AT_macros, cu);
9560   if (attr == NULL)
9561     attr = dwarf2_attr (die, DW_AT_GNU_macros, cu);
9562   if (attr && cu->line_header)
9563     {
9564       if (dwarf2_attr (die, DW_AT_macro_info, cu))
9565         complaint (&symfile_complaints,
9566                    _("CU refers to both DW_AT_macros and DW_AT_macro_info"));
9567
9568       dwarf_decode_macros (cu, DW_UNSND (attr), 1);
9569     }
9570   else
9571     {
9572       attr = dwarf2_attr (die, DW_AT_macro_info, cu);
9573       if (attr && cu->line_header)
9574         {
9575           unsigned int macro_offset = DW_UNSND (attr);
9576
9577           dwarf_decode_macros (cu, macro_offset, 0);
9578         }
9579     }
9580 }
9581
9582 /* TU version of handle_DW_AT_stmt_list for read_type_unit_scope.
9583    Create the set of symtabs used by this TU, or if this TU is sharing
9584    symtabs with another TU and the symtabs have already been created
9585    then restore those symtabs in the line header.
9586    We don't need the pc/line-number mapping for type units.  */
9587
9588 static void
9589 setup_type_unit_groups (struct die_info *die, struct dwarf2_cu *cu)
9590 {
9591   struct dwarf2_per_cu_data *per_cu = cu->per_cu;
9592   struct type_unit_group *tu_group;
9593   int first_time;
9594   struct attribute *attr;
9595   unsigned int i;
9596   struct signatured_type *sig_type;
9597
9598   gdb_assert (per_cu->is_debug_types);
9599   sig_type = (struct signatured_type *) per_cu;
9600
9601   attr = dwarf2_attr (die, DW_AT_stmt_list, cu);
9602
9603   /* If we're using .gdb_index (includes -readnow) then
9604      per_cu->type_unit_group may not have been set up yet.  */
9605   if (sig_type->type_unit_group == NULL)
9606     sig_type->type_unit_group = get_type_unit_group (cu, attr);
9607   tu_group = sig_type->type_unit_group;
9608
9609   /* If we've already processed this stmt_list there's no real need to
9610      do it again, we could fake it and just recreate the part we need
9611      (file name,index -> symtab mapping).  If data shows this optimization
9612      is useful we can do it then.  */
9613   first_time = tu_group->compunit_symtab == NULL;
9614
9615   /* We have to handle the case of both a missing DW_AT_stmt_list or bad
9616      debug info.  */
9617   line_header_up lh;
9618   if (attr != NULL)
9619     {
9620       sect_offset line_offset = (sect_offset) DW_UNSND (attr);
9621       lh = dwarf_decode_line_header (line_offset, cu);
9622     }
9623   if (lh == NULL)
9624     {
9625       if (first_time)
9626         dwarf2_start_symtab (cu, "", NULL, 0);
9627       else
9628         {
9629           gdb_assert (tu_group->symtabs == NULL);
9630           restart_symtab (tu_group->compunit_symtab, "", 0);
9631         }
9632       return;
9633     }
9634
9635   cu->line_header = lh.release ();
9636   cu->line_header_die_owner = die;
9637
9638   if (first_time)
9639     {
9640       struct compunit_symtab *cust = dwarf2_start_symtab (cu, "", NULL, 0);
9641
9642       /* Note: We don't assign tu_group->compunit_symtab yet because we're
9643          still initializing it, and our caller (a few levels up)
9644          process_full_type_unit still needs to know if this is the first
9645          time.  */
9646
9647       tu_group->num_symtabs = cu->line_header->file_names.size ();
9648       tu_group->symtabs = XNEWVEC (struct symtab *,
9649                                    cu->line_header->file_names.size ());
9650
9651       for (i = 0; i < cu->line_header->file_names.size (); ++i)
9652         {
9653           file_entry &fe = cu->line_header->file_names[i];
9654
9655           dwarf2_start_subfile (fe.name, fe.include_dir (cu->line_header));
9656
9657           if (current_subfile->symtab == NULL)
9658             {
9659               /* NOTE: start_subfile will recognize when it's been
9660                  passed a file it has already seen.  So we can't
9661                  assume there's a simple mapping from
9662                  cu->line_header->file_names to subfiles, plus
9663                  cu->line_header->file_names may contain dups.  */
9664               current_subfile->symtab
9665                 = allocate_symtab (cust, current_subfile->name);
9666             }
9667
9668           fe.symtab = current_subfile->symtab;
9669           tu_group->symtabs[i] = fe.symtab;
9670         }
9671     }
9672   else
9673     {
9674       restart_symtab (tu_group->compunit_symtab, "", 0);
9675
9676       for (i = 0; i < cu->line_header->file_names.size (); ++i)
9677         {
9678           file_entry &fe = cu->line_header->file_names[i];
9679
9680           fe.symtab = tu_group->symtabs[i];
9681         }
9682     }
9683
9684   /* The main symtab is allocated last.  Type units don't have DW_AT_name
9685      so they don't have a "real" (so to speak) symtab anyway.
9686      There is later code that will assign the main symtab to all symbols
9687      that don't have one.  We need to handle the case of a symbol with a
9688      missing symtab (DW_AT_decl_file) anyway.  */
9689 }
9690
9691 /* Process DW_TAG_type_unit.
9692    For TUs we want to skip the first top level sibling if it's not the
9693    actual type being defined by this TU.  In this case the first top
9694    level sibling is there to provide context only.  */
9695
9696 static void
9697 read_type_unit_scope (struct die_info *die, struct dwarf2_cu *cu)
9698 {
9699   struct die_info *child_die;
9700
9701   prepare_one_comp_unit (cu, die, language_minimal);
9702
9703   /* Initialize (or reinitialize) the machinery for building symtabs.
9704      We do this before processing child DIEs, so that the line header table
9705      is available for DW_AT_decl_file.  */
9706   setup_type_unit_groups (die, cu);
9707
9708   if (die->child != NULL)
9709     {
9710       child_die = die->child;
9711       while (child_die && child_die->tag)
9712         {
9713           process_die (child_die, cu);
9714           child_die = sibling_die (child_die);
9715         }
9716     }
9717 }
9718 \f
9719 /* DWO/DWP files.
9720
9721    http://gcc.gnu.org/wiki/DebugFission
9722    http://gcc.gnu.org/wiki/DebugFissionDWP
9723
9724    To simplify handling of both DWO files ("object" files with the DWARF info)
9725    and DWP files (a file with the DWOs packaged up into one file), we treat
9726    DWP files as having a collection of virtual DWO files.  */
9727
9728 static hashval_t
9729 hash_dwo_file (const void *item)
9730 {
9731   const struct dwo_file *dwo_file = (const struct dwo_file *) item;
9732   hashval_t hash;
9733
9734   hash = htab_hash_string (dwo_file->dwo_name);
9735   if (dwo_file->comp_dir != NULL)
9736     hash += htab_hash_string (dwo_file->comp_dir);
9737   return hash;
9738 }
9739
9740 static int
9741 eq_dwo_file (const void *item_lhs, const void *item_rhs)
9742 {
9743   const struct dwo_file *lhs = (const struct dwo_file *) item_lhs;
9744   const struct dwo_file *rhs = (const struct dwo_file *) item_rhs;
9745
9746   if (strcmp (lhs->dwo_name, rhs->dwo_name) != 0)
9747     return 0;
9748   if (lhs->comp_dir == NULL || rhs->comp_dir == NULL)
9749     return lhs->comp_dir == rhs->comp_dir;
9750   return strcmp (lhs->comp_dir, rhs->comp_dir) == 0;
9751 }
9752
9753 /* Allocate a hash table for DWO files.  */
9754
9755 static htab_t
9756 allocate_dwo_file_hash_table (void)
9757 {
9758   struct objfile *objfile = dwarf2_per_objfile->objfile;
9759
9760   return htab_create_alloc_ex (41,
9761                                hash_dwo_file,
9762                                eq_dwo_file,
9763                                NULL,
9764                                &objfile->objfile_obstack,
9765                                hashtab_obstack_allocate,
9766                                dummy_obstack_deallocate);
9767 }
9768
9769 /* Lookup DWO file DWO_NAME.  */
9770
9771 static void **
9772 lookup_dwo_file_slot (const char *dwo_name, const char *comp_dir)
9773 {
9774   struct dwo_file find_entry;
9775   void **slot;
9776
9777   if (dwarf2_per_objfile->dwo_files == NULL)
9778     dwarf2_per_objfile->dwo_files = allocate_dwo_file_hash_table ();
9779
9780   memset (&find_entry, 0, sizeof (find_entry));
9781   find_entry.dwo_name = dwo_name;
9782   find_entry.comp_dir = comp_dir;
9783   slot = htab_find_slot (dwarf2_per_objfile->dwo_files, &find_entry, INSERT);
9784
9785   return slot;
9786 }
9787
9788 static hashval_t
9789 hash_dwo_unit (const void *item)
9790 {
9791   const struct dwo_unit *dwo_unit = (const struct dwo_unit *) item;
9792
9793   /* This drops the top 32 bits of the id, but is ok for a hash.  */
9794   return dwo_unit->signature;
9795 }
9796
9797 static int
9798 eq_dwo_unit (const void *item_lhs, const void *item_rhs)
9799 {
9800   const struct dwo_unit *lhs = (const struct dwo_unit *) item_lhs;
9801   const struct dwo_unit *rhs = (const struct dwo_unit *) item_rhs;
9802
9803   /* The signature is assumed to be unique within the DWO file.
9804      So while object file CU dwo_id's always have the value zero,
9805      that's OK, assuming each object file DWO file has only one CU,
9806      and that's the rule for now.  */
9807   return lhs->signature == rhs->signature;
9808 }
9809
9810 /* Allocate a hash table for DWO CUs,TUs.
9811    There is one of these tables for each of CUs,TUs for each DWO file.  */
9812
9813 static htab_t
9814 allocate_dwo_unit_table (struct objfile *objfile)
9815 {
9816   /* Start out with a pretty small number.
9817      Generally DWO files contain only one CU and maybe some TUs.  */
9818   return htab_create_alloc_ex (3,
9819                                hash_dwo_unit,
9820                                eq_dwo_unit,
9821                                NULL,
9822                                &objfile->objfile_obstack,
9823                                hashtab_obstack_allocate,
9824                                dummy_obstack_deallocate);
9825 }
9826
9827 /* Structure used to pass data to create_dwo_debug_info_hash_table_reader.  */
9828
9829 struct create_dwo_cu_data
9830 {
9831   struct dwo_file *dwo_file;
9832   struct dwo_unit dwo_unit;
9833 };
9834
9835 /* die_reader_func for create_dwo_cu.  */
9836
9837 static void
9838 create_dwo_cu_reader (const struct die_reader_specs *reader,
9839                       const gdb_byte *info_ptr,
9840                       struct die_info *comp_unit_die,
9841                       int has_children,
9842                       void *datap)
9843 {
9844   struct dwarf2_cu *cu = reader->cu;
9845   sect_offset sect_off = cu->per_cu->sect_off;
9846   struct dwarf2_section_info *section = cu->per_cu->section;
9847   struct create_dwo_cu_data *data = (struct create_dwo_cu_data *) datap;
9848   struct dwo_file *dwo_file = data->dwo_file;
9849   struct dwo_unit *dwo_unit = &data->dwo_unit;
9850   struct attribute *attr;
9851
9852   attr = dwarf2_attr (comp_unit_die, DW_AT_GNU_dwo_id, cu);
9853   if (attr == NULL)
9854     {
9855       complaint (&symfile_complaints,
9856                  _("Dwarf Error: debug entry at offset 0x%x is missing"
9857                    " its dwo_id [in module %s]"),
9858                  to_underlying (sect_off), dwo_file->dwo_name);
9859       return;
9860     }
9861
9862   dwo_unit->dwo_file = dwo_file;
9863   dwo_unit->signature = DW_UNSND (attr);
9864   dwo_unit->section = section;
9865   dwo_unit->sect_off = sect_off;
9866   dwo_unit->length = cu->per_cu->length;
9867
9868   if (dwarf_read_debug)
9869     fprintf_unfiltered (gdb_stdlog, "  offset 0x%x, dwo_id %s\n",
9870                         to_underlying (sect_off),
9871                         hex_string (dwo_unit->signature));
9872 }
9873
9874 /* Create the dwo_units for the CUs in a DWO_FILE.
9875    Note: This function processes DWO files only, not DWP files.  */
9876
9877 static void
9878 create_cus_hash_table (struct dwo_file &dwo_file, dwarf2_section_info &section,
9879                        htab_t &cus_htab)
9880 {
9881   struct objfile *objfile = dwarf2_per_objfile->objfile;
9882   const struct dwarf2_section_info *abbrev_section = &dwo_file.sections.abbrev;
9883   const gdb_byte *info_ptr, *end_ptr;
9884
9885   dwarf2_read_section (objfile, &section);
9886   info_ptr = section.buffer;
9887
9888   if (info_ptr == NULL)
9889     return;
9890
9891   if (dwarf_read_debug)
9892     {
9893       fprintf_unfiltered (gdb_stdlog, "Reading %s for %s:\n",
9894                           get_section_name (&section),
9895                           get_section_file_name (&section));
9896     }
9897
9898   end_ptr = info_ptr + section.size;
9899   while (info_ptr < end_ptr)
9900     {
9901       struct dwarf2_per_cu_data per_cu;
9902       struct create_dwo_cu_data create_dwo_cu_data;
9903       struct dwo_unit *dwo_unit;
9904       void **slot;
9905       sect_offset sect_off = (sect_offset) (info_ptr - section.buffer);
9906
9907       memset (&create_dwo_cu_data.dwo_unit, 0,
9908               sizeof (create_dwo_cu_data.dwo_unit));
9909       memset (&per_cu, 0, sizeof (per_cu));
9910       per_cu.objfile = objfile;
9911       per_cu.is_debug_types = 0;
9912       per_cu.sect_off = sect_offset (info_ptr - section.buffer);
9913       per_cu.section = &section;
9914       create_dwo_cu_data.dwo_file = &dwo_file;
9915
9916       init_cutu_and_read_dies_no_follow (
9917           &per_cu, &dwo_file, create_dwo_cu_reader, &create_dwo_cu_data);
9918       info_ptr += per_cu.length;
9919
9920       // If the unit could not be parsed, skip it.
9921       if (create_dwo_cu_data.dwo_unit.dwo_file == NULL)
9922         continue;
9923
9924       if (cus_htab == NULL)
9925         cus_htab = allocate_dwo_unit_table (objfile);
9926
9927       dwo_unit = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_unit);
9928       *dwo_unit = create_dwo_cu_data.dwo_unit;
9929       slot = htab_find_slot (cus_htab, dwo_unit, INSERT);
9930       gdb_assert (slot != NULL);
9931       if (*slot != NULL)
9932         {
9933           const struct dwo_unit *dup_cu = (const struct dwo_unit *)*slot;
9934           sect_offset dup_sect_off = dup_cu->sect_off;
9935
9936           complaint (&symfile_complaints,
9937                      _("debug cu entry at offset 0x%x is duplicate to"
9938                        " the entry at offset 0x%x, signature %s"),
9939                      to_underlying (sect_off), to_underlying (dup_sect_off),
9940                      hex_string (dwo_unit->signature));
9941         }
9942       *slot = (void *)dwo_unit;
9943     }
9944 }
9945
9946 /* DWP file .debug_{cu,tu}_index section format:
9947    [ref: http://gcc.gnu.org/wiki/DebugFissionDWP]
9948
9949    DWP Version 1:
9950
9951    Both index sections have the same format, and serve to map a 64-bit
9952    signature to a set of section numbers.  Each section begins with a header,
9953    followed by a hash table of 64-bit signatures, a parallel table of 32-bit
9954    indexes, and a pool of 32-bit section numbers.  The index sections will be
9955    aligned at 8-byte boundaries in the file.
9956
9957    The index section header consists of:
9958
9959     V, 32 bit version number
9960     -, 32 bits unused
9961     N, 32 bit number of compilation units or type units in the index
9962     M, 32 bit number of slots in the hash table
9963
9964    Numbers are recorded using the byte order of the application binary.
9965
9966    The hash table begins at offset 16 in the section, and consists of an array
9967    of M 64-bit slots.  Each slot contains a 64-bit signature (using the byte
9968    order of the application binary).  Unused slots in the hash table are 0.
9969    (We rely on the extreme unlikeliness of a signature being exactly 0.)
9970
9971    The parallel table begins immediately after the hash table
9972    (at offset 16 + 8 * M from the beginning of the section), and consists of an
9973    array of 32-bit indexes (using the byte order of the application binary),
9974    corresponding 1-1 with slots in the hash table.  Each entry in the parallel
9975    table contains a 32-bit index into the pool of section numbers.  For unused
9976    hash table slots, the corresponding entry in the parallel table will be 0.
9977
9978    The pool of section numbers begins immediately following the hash table
9979    (at offset 16 + 12 * M from the beginning of the section).  The pool of
9980    section numbers consists of an array of 32-bit words (using the byte order
9981    of the application binary).  Each item in the array is indexed starting
9982    from 0.  The hash table entry provides the index of the first section
9983    number in the set.  Additional section numbers in the set follow, and the
9984    set is terminated by a 0 entry (section number 0 is not used in ELF).
9985
9986    In each set of section numbers, the .debug_info.dwo or .debug_types.dwo
9987    section must be the first entry in the set, and the .debug_abbrev.dwo must
9988    be the second entry. Other members of the set may follow in any order.
9989
9990    ---
9991
9992    DWP Version 2:
9993
9994    DWP Version 2 combines all the .debug_info, etc. sections into one,
9995    and the entries in the index tables are now offsets into these sections.
9996    CU offsets begin at 0.  TU offsets begin at the size of the .debug_info
9997    section.
9998
9999    Index Section Contents:
10000     Header
10001     Hash Table of Signatures   dwp_hash_table.hash_table
10002     Parallel Table of Indices  dwp_hash_table.unit_table
10003     Table of Section Offsets   dwp_hash_table.v2.{section_ids,offsets}
10004     Table of Section Sizes     dwp_hash_table.v2.sizes
10005
10006    The index section header consists of:
10007
10008     V, 32 bit version number
10009     L, 32 bit number of columns in the table of section offsets
10010     N, 32 bit number of compilation units or type units in the index
10011     M, 32 bit number of slots in the hash table
10012
10013    Numbers are recorded using the byte order of the application binary.
10014
10015    The hash table has the same format as version 1.
10016    The parallel table of indices has the same format as version 1,
10017    except that the entries are origin-1 indices into the table of sections
10018    offsets and the table of section sizes.
10019
10020    The table of offsets begins immediately following the parallel table
10021    (at offset 16 + 12 * M from the beginning of the section).  The table is
10022    a two-dimensional array of 32-bit words (using the byte order of the
10023    application binary), with L columns and N+1 rows, in row-major order.
10024    Each row in the array is indexed starting from 0.  The first row provides
10025    a key to the remaining rows: each column in this row provides an identifier
10026    for a debug section, and the offsets in the same column of subsequent rows
10027    refer to that section.  The section identifiers are:
10028
10029     DW_SECT_INFO         1  .debug_info.dwo
10030     DW_SECT_TYPES        2  .debug_types.dwo
10031     DW_SECT_ABBREV       3  .debug_abbrev.dwo
10032     DW_SECT_LINE         4  .debug_line.dwo
10033     DW_SECT_LOC          5  .debug_loc.dwo
10034     DW_SECT_STR_OFFSETS  6  .debug_str_offsets.dwo
10035     DW_SECT_MACINFO      7  .debug_macinfo.dwo
10036     DW_SECT_MACRO        8  .debug_macro.dwo
10037
10038    The offsets provided by the CU and TU index sections are the base offsets
10039    for the contributions made by each CU or TU to the corresponding section
10040    in the package file.  Each CU and TU header contains an abbrev_offset
10041    field, used to find the abbreviations table for that CU or TU within the
10042    contribution to the .debug_abbrev.dwo section for that CU or TU, and should
10043    be interpreted as relative to the base offset given in the index section.
10044    Likewise, offsets into .debug_line.dwo from DW_AT_stmt_list attributes
10045    should be interpreted as relative to the base offset for .debug_line.dwo,
10046    and offsets into other debug sections obtained from DWARF attributes should
10047    also be interpreted as relative to the corresponding base offset.
10048
10049    The table of sizes begins immediately following the table of offsets.
10050    Like the table of offsets, it is a two-dimensional array of 32-bit words,
10051    with L columns and N rows, in row-major order.  Each row in the array is
10052    indexed starting from 1 (row 0 is shared by the two tables).
10053
10054    ---
10055
10056    Hash table lookup is handled the same in version 1 and 2:
10057
10058    We assume that N and M will not exceed 2^32 - 1.
10059    The size of the hash table, M, must be 2^k such that 2^k > 3*N/2.
10060
10061    Given a 64-bit compilation unit signature or a type signature S, an entry
10062    in the hash table is located as follows:
10063
10064    1) Calculate a primary hash H = S & MASK(k), where MASK(k) is a mask with
10065       the low-order k bits all set to 1.
10066
10067    2) Calculate a secondary hash H' = (((S >> 32) & MASK(k)) | 1).
10068
10069    3) If the hash table entry at index H matches the signature, use that
10070       entry.  If the hash table entry at index H is unused (all zeroes),
10071       terminate the search: the signature is not present in the table.
10072
10073    4) Let H = (H + H') modulo M. Repeat at Step 3.
10074
10075    Because M > N and H' and M are relatively prime, the search is guaranteed
10076    to stop at an unused slot or find the match.  */
10077
10078 /* Create a hash table to map DWO IDs to their CU/TU entry in
10079    .debug_{info,types}.dwo in DWP_FILE.
10080    Returns NULL if there isn't one.
10081    Note: This function processes DWP files only, not DWO files.  */
10082
10083 static struct dwp_hash_table *
10084 create_dwp_hash_table (struct dwp_file *dwp_file, int is_debug_types)
10085 {
10086   struct objfile *objfile = dwarf2_per_objfile->objfile;
10087   bfd *dbfd = dwp_file->dbfd;
10088   const gdb_byte *index_ptr, *index_end;
10089   struct dwarf2_section_info *index;
10090   uint32_t version, nr_columns, nr_units, nr_slots;
10091   struct dwp_hash_table *htab;
10092
10093   if (is_debug_types)
10094     index = &dwp_file->sections.tu_index;
10095   else
10096     index = &dwp_file->sections.cu_index;
10097
10098   if (dwarf2_section_empty_p (index))
10099     return NULL;
10100   dwarf2_read_section (objfile, index);
10101
10102   index_ptr = index->buffer;
10103   index_end = index_ptr + index->size;
10104
10105   version = read_4_bytes (dbfd, index_ptr);
10106   index_ptr += 4;
10107   if (version == 2)
10108     nr_columns = read_4_bytes (dbfd, index_ptr);
10109   else
10110     nr_columns = 0;
10111   index_ptr += 4;
10112   nr_units = read_4_bytes (dbfd, index_ptr);
10113   index_ptr += 4;
10114   nr_slots = read_4_bytes (dbfd, index_ptr);
10115   index_ptr += 4;
10116
10117   if (version != 1 && version != 2)
10118     {
10119       error (_("Dwarf Error: unsupported DWP file version (%s)"
10120                " [in module %s]"),
10121              pulongest (version), dwp_file->name);
10122     }
10123   if (nr_slots != (nr_slots & -nr_slots))
10124     {
10125       error (_("Dwarf Error: number of slots in DWP hash table (%s)"
10126                " is not power of 2 [in module %s]"),
10127              pulongest (nr_slots), dwp_file->name);
10128     }
10129
10130   htab = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwp_hash_table);
10131   htab->version = version;
10132   htab->nr_columns = nr_columns;
10133   htab->nr_units = nr_units;
10134   htab->nr_slots = nr_slots;
10135   htab->hash_table = index_ptr;
10136   htab->unit_table = htab->hash_table + sizeof (uint64_t) * nr_slots;
10137
10138   /* Exit early if the table is empty.  */
10139   if (nr_slots == 0 || nr_units == 0
10140       || (version == 2 && nr_columns == 0))
10141     {
10142       /* All must be zero.  */
10143       if (nr_slots != 0 || nr_units != 0
10144           || (version == 2 && nr_columns != 0))
10145         {
10146           complaint (&symfile_complaints,
10147                      _("Empty DWP but nr_slots,nr_units,nr_columns not"
10148                        " all zero [in modules %s]"),
10149                      dwp_file->name);
10150         }
10151       return htab;
10152     }
10153
10154   if (version == 1)
10155     {
10156       htab->section_pool.v1.indices =
10157         htab->unit_table + sizeof (uint32_t) * nr_slots;
10158       /* It's harder to decide whether the section is too small in v1.
10159          V1 is deprecated anyway so we punt.  */
10160     }
10161   else
10162     {
10163       const gdb_byte *ids_ptr = htab->unit_table + sizeof (uint32_t) * nr_slots;
10164       int *ids = htab->section_pool.v2.section_ids;
10165       /* Reverse map for error checking.  */
10166       int ids_seen[DW_SECT_MAX + 1];
10167       int i;
10168
10169       if (nr_columns < 2)
10170         {
10171           error (_("Dwarf Error: bad DWP hash table, too few columns"
10172                    " in section table [in module %s]"),
10173                  dwp_file->name);
10174         }
10175       if (nr_columns > MAX_NR_V2_DWO_SECTIONS)
10176         {
10177           error (_("Dwarf Error: bad DWP hash table, too many columns"
10178                    " in section table [in module %s]"),
10179                  dwp_file->name);
10180         }
10181       memset (ids, 255, (DW_SECT_MAX + 1) * sizeof (int32_t));
10182       memset (ids_seen, 255, (DW_SECT_MAX + 1) * sizeof (int32_t));
10183       for (i = 0; i < nr_columns; ++i)
10184         {
10185           int id = read_4_bytes (dbfd, ids_ptr + i * sizeof (uint32_t));
10186
10187           if (id < DW_SECT_MIN || id > DW_SECT_MAX)
10188             {
10189               error (_("Dwarf Error: bad DWP hash table, bad section id %d"
10190                        " in section table [in module %s]"),
10191                      id, dwp_file->name);
10192             }
10193           if (ids_seen[id] != -1)
10194             {
10195               error (_("Dwarf Error: bad DWP hash table, duplicate section"
10196                        " id %d in section table [in module %s]"),
10197                      id, dwp_file->name);
10198             }
10199           ids_seen[id] = i;
10200           ids[i] = id;
10201         }
10202       /* Must have exactly one info or types section.  */
10203       if (((ids_seen[DW_SECT_INFO] != -1)
10204            + (ids_seen[DW_SECT_TYPES] != -1))
10205           != 1)
10206         {
10207           error (_("Dwarf Error: bad DWP hash table, missing/duplicate"
10208                    " DWO info/types section [in module %s]"),
10209                  dwp_file->name);
10210         }
10211       /* Must have an abbrev section.  */
10212       if (ids_seen[DW_SECT_ABBREV] == -1)
10213         {
10214           error (_("Dwarf Error: bad DWP hash table, missing DWO abbrev"
10215                    " section [in module %s]"),
10216                  dwp_file->name);
10217         }
10218       htab->section_pool.v2.offsets = ids_ptr + sizeof (uint32_t) * nr_columns;
10219       htab->section_pool.v2.sizes =
10220         htab->section_pool.v2.offsets + (sizeof (uint32_t)
10221                                          * nr_units * nr_columns);
10222       if ((htab->section_pool.v2.sizes + (sizeof (uint32_t)
10223                                           * nr_units * nr_columns))
10224           > index_end)
10225         {
10226           error (_("Dwarf Error: DWP index section is corrupt (too small)"
10227                    " [in module %s]"),
10228                  dwp_file->name);
10229         }
10230     }
10231
10232   return htab;
10233 }
10234
10235 /* Update SECTIONS with the data from SECTP.
10236
10237    This function is like the other "locate" section routines that are
10238    passed to bfd_map_over_sections, but in this context the sections to
10239    read comes from the DWP V1 hash table, not the full ELF section table.
10240
10241    The result is non-zero for success, or zero if an error was found.  */
10242
10243 static int
10244 locate_v1_virtual_dwo_sections (asection *sectp,
10245                                 struct virtual_v1_dwo_sections *sections)
10246 {
10247   const struct dwop_section_names *names = &dwop_section_names;
10248
10249   if (section_is_p (sectp->name, &names->abbrev_dwo))
10250     {
10251       /* There can be only one.  */
10252       if (sections->abbrev.s.section != NULL)
10253         return 0;
10254       sections->abbrev.s.section = sectp;
10255       sections->abbrev.size = bfd_get_section_size (sectp);
10256     }
10257   else if (section_is_p (sectp->name, &names->info_dwo)
10258            || section_is_p (sectp->name, &names->types_dwo))
10259     {
10260       /* There can be only one.  */
10261       if (sections->info_or_types.s.section != NULL)
10262         return 0;
10263       sections->info_or_types.s.section = sectp;
10264       sections->info_or_types.size = bfd_get_section_size (sectp);
10265     }
10266   else if (section_is_p (sectp->name, &names->line_dwo))
10267     {
10268       /* There can be only one.  */
10269       if (sections->line.s.section != NULL)
10270         return 0;
10271       sections->line.s.section = sectp;
10272       sections->line.size = bfd_get_section_size (sectp);
10273     }
10274   else if (section_is_p (sectp->name, &names->loc_dwo))
10275     {
10276       /* There can be only one.  */
10277       if (sections->loc.s.section != NULL)
10278         return 0;
10279       sections->loc.s.section = sectp;
10280       sections->loc.size = bfd_get_section_size (sectp);
10281     }
10282   else if (section_is_p (sectp->name, &names->macinfo_dwo))
10283     {
10284       /* There can be only one.  */
10285       if (sections->macinfo.s.section != NULL)
10286         return 0;
10287       sections->macinfo.s.section = sectp;
10288       sections->macinfo.size = bfd_get_section_size (sectp);
10289     }
10290   else if (section_is_p (sectp->name, &names->macro_dwo))
10291     {
10292       /* There can be only one.  */
10293       if (sections->macro.s.section != NULL)
10294         return 0;
10295       sections->macro.s.section = sectp;
10296       sections->macro.size = bfd_get_section_size (sectp);
10297     }
10298   else if (section_is_p (sectp->name, &names->str_offsets_dwo))
10299     {
10300       /* There can be only one.  */
10301       if (sections->str_offsets.s.section != NULL)
10302         return 0;
10303       sections->str_offsets.s.section = sectp;
10304       sections->str_offsets.size = bfd_get_section_size (sectp);
10305     }
10306   else
10307     {
10308       /* No other kind of section is valid.  */
10309       return 0;
10310     }
10311
10312   return 1;
10313 }
10314
10315 /* Create a dwo_unit object for the DWO unit with signature SIGNATURE.
10316    UNIT_INDEX is the index of the DWO unit in the DWP hash table.
10317    COMP_DIR is the DW_AT_comp_dir attribute of the referencing CU.
10318    This is for DWP version 1 files.  */
10319
10320 static struct dwo_unit *
10321 create_dwo_unit_in_dwp_v1 (struct dwp_file *dwp_file,
10322                            uint32_t unit_index,
10323                            const char *comp_dir,
10324                            ULONGEST signature, int is_debug_types)
10325 {
10326   struct objfile *objfile = dwarf2_per_objfile->objfile;
10327   const struct dwp_hash_table *dwp_htab =
10328     is_debug_types ? dwp_file->tus : dwp_file->cus;
10329   bfd *dbfd = dwp_file->dbfd;
10330   const char *kind = is_debug_types ? "TU" : "CU";
10331   struct dwo_file *dwo_file;
10332   struct dwo_unit *dwo_unit;
10333   struct virtual_v1_dwo_sections sections;
10334   void **dwo_file_slot;
10335   char *virtual_dwo_name;
10336   struct cleanup *cleanups;
10337   int i;
10338
10339   gdb_assert (dwp_file->version == 1);
10340
10341   if (dwarf_read_debug)
10342     {
10343       fprintf_unfiltered (gdb_stdlog, "Reading %s %s/%s in DWP V1 file: %s\n",
10344                           kind,
10345                           pulongest (unit_index), hex_string (signature),
10346                           dwp_file->name);
10347     }
10348
10349   /* Fetch the sections of this DWO unit.
10350      Put a limit on the number of sections we look for so that bad data
10351      doesn't cause us to loop forever.  */
10352
10353 #define MAX_NR_V1_DWO_SECTIONS \
10354   (1 /* .debug_info or .debug_types */ \
10355    + 1 /* .debug_abbrev */ \
10356    + 1 /* .debug_line */ \
10357    + 1 /* .debug_loc */ \
10358    + 1 /* .debug_str_offsets */ \
10359    + 1 /* .debug_macro or .debug_macinfo */ \
10360    + 1 /* trailing zero */)
10361
10362   memset (&sections, 0, sizeof (sections));
10363   cleanups = make_cleanup (null_cleanup, 0);
10364
10365   for (i = 0; i < MAX_NR_V1_DWO_SECTIONS; ++i)
10366     {
10367       asection *sectp;
10368       uint32_t section_nr =
10369         read_4_bytes (dbfd,
10370                       dwp_htab->section_pool.v1.indices
10371                       + (unit_index + i) * sizeof (uint32_t));
10372
10373       if (section_nr == 0)
10374         break;
10375       if (section_nr >= dwp_file->num_sections)
10376         {
10377           error (_("Dwarf Error: bad DWP hash table, section number too large"
10378                    " [in module %s]"),
10379                  dwp_file->name);
10380         }
10381
10382       sectp = dwp_file->elf_sections[section_nr];
10383       if (! locate_v1_virtual_dwo_sections (sectp, &sections))
10384         {
10385           error (_("Dwarf Error: bad DWP hash table, invalid section found"
10386                    " [in module %s]"),
10387                  dwp_file->name);
10388         }
10389     }
10390
10391   if (i < 2
10392       || dwarf2_section_empty_p (&sections.info_or_types)
10393       || dwarf2_section_empty_p (&sections.abbrev))
10394     {
10395       error (_("Dwarf Error: bad DWP hash table, missing DWO sections"
10396                " [in module %s]"),
10397              dwp_file->name);
10398     }
10399   if (i == MAX_NR_V1_DWO_SECTIONS)
10400     {
10401       error (_("Dwarf Error: bad DWP hash table, too many DWO sections"
10402                " [in module %s]"),
10403              dwp_file->name);
10404     }
10405
10406   /* It's easier for the rest of the code if we fake a struct dwo_file and
10407      have dwo_unit "live" in that.  At least for now.
10408
10409      The DWP file can be made up of a random collection of CUs and TUs.
10410      However, for each CU + set of TUs that came from the same original DWO
10411      file, we can combine them back into a virtual DWO file to save space
10412      (fewer struct dwo_file objects to allocate).  Remember that for really
10413      large apps there can be on the order of 8K CUs and 200K TUs, or more.  */
10414
10415   virtual_dwo_name =
10416     xstrprintf ("virtual-dwo/%d-%d-%d-%d",
10417                 get_section_id (&sections.abbrev),
10418                 get_section_id (&sections.line),
10419                 get_section_id (&sections.loc),
10420                 get_section_id (&sections.str_offsets));
10421   make_cleanup (xfree, virtual_dwo_name);
10422   /* Can we use an existing virtual DWO file?  */
10423   dwo_file_slot = lookup_dwo_file_slot (virtual_dwo_name, comp_dir);
10424   /* Create one if necessary.  */
10425   if (*dwo_file_slot == NULL)
10426     {
10427       if (dwarf_read_debug)
10428         {
10429           fprintf_unfiltered (gdb_stdlog, "Creating virtual DWO: %s\n",
10430                               virtual_dwo_name);
10431         }
10432       dwo_file = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_file);
10433       dwo_file->dwo_name
10434         = (const char *) obstack_copy0 (&objfile->objfile_obstack,
10435                                         virtual_dwo_name,
10436                                         strlen (virtual_dwo_name));
10437       dwo_file->comp_dir = comp_dir;
10438       dwo_file->sections.abbrev = sections.abbrev;
10439       dwo_file->sections.line = sections.line;
10440       dwo_file->sections.loc = sections.loc;
10441       dwo_file->sections.macinfo = sections.macinfo;
10442       dwo_file->sections.macro = sections.macro;
10443       dwo_file->sections.str_offsets = sections.str_offsets;
10444       /* The "str" section is global to the entire DWP file.  */
10445       dwo_file->sections.str = dwp_file->sections.str;
10446       /* The info or types section is assigned below to dwo_unit,
10447          there's no need to record it in dwo_file.
10448          Also, we can't simply record type sections in dwo_file because
10449          we record a pointer into the vector in dwo_unit.  As we collect more
10450          types we'll grow the vector and eventually have to reallocate space
10451          for it, invalidating all copies of pointers into the previous
10452          contents.  */
10453       *dwo_file_slot = dwo_file;
10454     }
10455   else
10456     {
10457       if (dwarf_read_debug)
10458         {
10459           fprintf_unfiltered (gdb_stdlog, "Using existing virtual DWO: %s\n",
10460                               virtual_dwo_name);
10461         }
10462       dwo_file = (struct dwo_file *) *dwo_file_slot;
10463     }
10464   do_cleanups (cleanups);
10465
10466   dwo_unit = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_unit);
10467   dwo_unit->dwo_file = dwo_file;
10468   dwo_unit->signature = signature;
10469   dwo_unit->section =
10470     XOBNEW (&objfile->objfile_obstack, struct dwarf2_section_info);
10471   *dwo_unit->section = sections.info_or_types;
10472   /* dwo_unit->{offset,length,type_offset_in_tu} are set later.  */
10473
10474   return dwo_unit;
10475 }
10476
10477 /* Subroutine of create_dwo_unit_in_dwp_v2 to simplify it.
10478    Given a pointer to the containing section SECTION, and OFFSET,SIZE of the
10479    piece within that section used by a TU/CU, return a virtual section
10480    of just that piece.  */
10481
10482 static struct dwarf2_section_info
10483 create_dwp_v2_section (struct dwarf2_section_info *section,
10484                        bfd_size_type offset, bfd_size_type size)
10485 {
10486   struct dwarf2_section_info result;
10487   asection *sectp;
10488
10489   gdb_assert (section != NULL);
10490   gdb_assert (!section->is_virtual);
10491
10492   memset (&result, 0, sizeof (result));
10493   result.s.containing_section = section;
10494   result.is_virtual = 1;
10495
10496   if (size == 0)
10497     return result;
10498
10499   sectp = get_section_bfd_section (section);
10500
10501   /* Flag an error if the piece denoted by OFFSET,SIZE is outside the
10502      bounds of the real section.  This is a pretty-rare event, so just
10503      flag an error (easier) instead of a warning and trying to cope.  */
10504   if (sectp == NULL
10505       || offset + size > bfd_get_section_size (sectp))
10506     {
10507       bfd *abfd = sectp->owner;
10508
10509       error (_("Dwarf Error: Bad DWP V2 section info, doesn't fit"
10510                " in section %s [in module %s]"),
10511              sectp ? bfd_section_name (abfd, sectp) : "<unknown>",
10512              objfile_name (dwarf2_per_objfile->objfile));
10513     }
10514
10515   result.virtual_offset = offset;
10516   result.size = size;
10517   return result;
10518 }
10519
10520 /* Create a dwo_unit object for the DWO unit with signature SIGNATURE.
10521    UNIT_INDEX is the index of the DWO unit in the DWP hash table.
10522    COMP_DIR is the DW_AT_comp_dir attribute of the referencing CU.
10523    This is for DWP version 2 files.  */
10524
10525 static struct dwo_unit *
10526 create_dwo_unit_in_dwp_v2 (struct dwp_file *dwp_file,
10527                            uint32_t unit_index,
10528                            const char *comp_dir,
10529                            ULONGEST signature, int is_debug_types)
10530 {
10531   struct objfile *objfile = dwarf2_per_objfile->objfile;
10532   const struct dwp_hash_table *dwp_htab =
10533     is_debug_types ? dwp_file->tus : dwp_file->cus;
10534   bfd *dbfd = dwp_file->dbfd;
10535   const char *kind = is_debug_types ? "TU" : "CU";
10536   struct dwo_file *dwo_file;
10537   struct dwo_unit *dwo_unit;
10538   struct virtual_v2_dwo_sections sections;
10539   void **dwo_file_slot;
10540   char *virtual_dwo_name;
10541   struct cleanup *cleanups;
10542   int i;
10543
10544   gdb_assert (dwp_file->version == 2);
10545
10546   if (dwarf_read_debug)
10547     {
10548       fprintf_unfiltered (gdb_stdlog, "Reading %s %s/%s in DWP V2 file: %s\n",
10549                           kind,
10550                           pulongest (unit_index), hex_string (signature),
10551                           dwp_file->name);
10552     }
10553
10554   /* Fetch the section offsets of this DWO unit.  */
10555
10556   memset (&sections, 0, sizeof (sections));
10557   cleanups = make_cleanup (null_cleanup, 0);
10558
10559   for (i = 0; i < dwp_htab->nr_columns; ++i)
10560     {
10561       uint32_t offset = read_4_bytes (dbfd,
10562                                       dwp_htab->section_pool.v2.offsets
10563                                       + (((unit_index - 1) * dwp_htab->nr_columns
10564                                           + i)
10565                                          * sizeof (uint32_t)));
10566       uint32_t size = read_4_bytes (dbfd,
10567                                     dwp_htab->section_pool.v2.sizes
10568                                     + (((unit_index - 1) * dwp_htab->nr_columns
10569                                         + i)
10570                                        * sizeof (uint32_t)));
10571
10572       switch (dwp_htab->section_pool.v2.section_ids[i])
10573         {
10574         case DW_SECT_INFO:
10575         case DW_SECT_TYPES:
10576           sections.info_or_types_offset = offset;
10577           sections.info_or_types_size = size;
10578           break;
10579         case DW_SECT_ABBREV:
10580           sections.abbrev_offset = offset;
10581           sections.abbrev_size = size;
10582           break;
10583         case DW_SECT_LINE:
10584           sections.line_offset = offset;
10585           sections.line_size = size;
10586           break;
10587         case DW_SECT_LOC:
10588           sections.loc_offset = offset;
10589           sections.loc_size = size;
10590           break;
10591         case DW_SECT_STR_OFFSETS:
10592           sections.str_offsets_offset = offset;
10593           sections.str_offsets_size = size;
10594           break;
10595         case DW_SECT_MACINFO:
10596           sections.macinfo_offset = offset;
10597           sections.macinfo_size = size;
10598           break;
10599         case DW_SECT_MACRO:
10600           sections.macro_offset = offset;
10601           sections.macro_size = size;
10602           break;
10603         }
10604     }
10605
10606   /* It's easier for the rest of the code if we fake a struct dwo_file and
10607      have dwo_unit "live" in that.  At least for now.
10608
10609      The DWP file can be made up of a random collection of CUs and TUs.
10610      However, for each CU + set of TUs that came from the same original DWO
10611      file, we can combine them back into a virtual DWO file to save space
10612      (fewer struct dwo_file objects to allocate).  Remember that for really
10613      large apps there can be on the order of 8K CUs and 200K TUs, or more.  */
10614
10615   virtual_dwo_name =
10616     xstrprintf ("virtual-dwo/%ld-%ld-%ld-%ld",
10617                 (long) (sections.abbrev_size ? sections.abbrev_offset : 0),
10618                 (long) (sections.line_size ? sections.line_offset : 0),
10619                 (long) (sections.loc_size ? sections.loc_offset : 0),
10620                 (long) (sections.str_offsets_size
10621                         ? sections.str_offsets_offset : 0));
10622   make_cleanup (xfree, virtual_dwo_name);
10623   /* Can we use an existing virtual DWO file?  */
10624   dwo_file_slot = lookup_dwo_file_slot (virtual_dwo_name, comp_dir);
10625   /* Create one if necessary.  */
10626   if (*dwo_file_slot == NULL)
10627     {
10628       if (dwarf_read_debug)
10629         {
10630           fprintf_unfiltered (gdb_stdlog, "Creating virtual DWO: %s\n",
10631                               virtual_dwo_name);
10632         }
10633       dwo_file = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_file);
10634       dwo_file->dwo_name
10635         = (const char *) obstack_copy0 (&objfile->objfile_obstack,
10636                                         virtual_dwo_name,
10637                                         strlen (virtual_dwo_name));
10638       dwo_file->comp_dir = comp_dir;
10639       dwo_file->sections.abbrev =
10640         create_dwp_v2_section (&dwp_file->sections.abbrev,
10641                                sections.abbrev_offset, sections.abbrev_size);
10642       dwo_file->sections.line =
10643         create_dwp_v2_section (&dwp_file->sections.line,
10644                                sections.line_offset, sections.line_size);
10645       dwo_file->sections.loc =
10646         create_dwp_v2_section (&dwp_file->sections.loc,
10647                                sections.loc_offset, sections.loc_size);
10648       dwo_file->sections.macinfo =
10649         create_dwp_v2_section (&dwp_file->sections.macinfo,
10650                                sections.macinfo_offset, sections.macinfo_size);
10651       dwo_file->sections.macro =
10652         create_dwp_v2_section (&dwp_file->sections.macro,
10653                                sections.macro_offset, sections.macro_size);
10654       dwo_file->sections.str_offsets =
10655         create_dwp_v2_section (&dwp_file->sections.str_offsets,
10656                                sections.str_offsets_offset,
10657                                sections.str_offsets_size);
10658       /* The "str" section is global to the entire DWP file.  */
10659       dwo_file->sections.str = dwp_file->sections.str;
10660       /* The info or types section is assigned below to dwo_unit,
10661          there's no need to record it in dwo_file.
10662          Also, we can't simply record type sections in dwo_file because
10663          we record a pointer into the vector in dwo_unit.  As we collect more
10664          types we'll grow the vector and eventually have to reallocate space
10665          for it, invalidating all copies of pointers into the previous
10666          contents.  */
10667       *dwo_file_slot = dwo_file;
10668     }
10669   else
10670     {
10671       if (dwarf_read_debug)
10672         {
10673           fprintf_unfiltered (gdb_stdlog, "Using existing virtual DWO: %s\n",
10674                               virtual_dwo_name);
10675         }
10676       dwo_file = (struct dwo_file *) *dwo_file_slot;
10677     }
10678   do_cleanups (cleanups);
10679
10680   dwo_unit = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_unit);
10681   dwo_unit->dwo_file = dwo_file;
10682   dwo_unit->signature = signature;
10683   dwo_unit->section =
10684     XOBNEW (&objfile->objfile_obstack, struct dwarf2_section_info);
10685   *dwo_unit->section = create_dwp_v2_section (is_debug_types
10686                                               ? &dwp_file->sections.types
10687                                               : &dwp_file->sections.info,
10688                                               sections.info_or_types_offset,
10689                                               sections.info_or_types_size);
10690   /* dwo_unit->{offset,length,type_offset_in_tu} are set later.  */
10691
10692   return dwo_unit;
10693 }
10694
10695 /* Lookup the DWO unit with SIGNATURE in DWP_FILE.
10696    Returns NULL if the signature isn't found.  */
10697
10698 static struct dwo_unit *
10699 lookup_dwo_unit_in_dwp (struct dwp_file *dwp_file, const char *comp_dir,
10700                         ULONGEST signature, int is_debug_types)
10701 {
10702   const struct dwp_hash_table *dwp_htab =
10703     is_debug_types ? dwp_file->tus : dwp_file->cus;
10704   bfd *dbfd = dwp_file->dbfd;
10705   uint32_t mask = dwp_htab->nr_slots - 1;
10706   uint32_t hash = signature & mask;
10707   uint32_t hash2 = ((signature >> 32) & mask) | 1;
10708   unsigned int i;
10709   void **slot;
10710   struct dwo_unit find_dwo_cu;
10711
10712   memset (&find_dwo_cu, 0, sizeof (find_dwo_cu));
10713   find_dwo_cu.signature = signature;
10714   slot = htab_find_slot (is_debug_types
10715                          ? dwp_file->loaded_tus
10716                          : dwp_file->loaded_cus,
10717                          &find_dwo_cu, INSERT);
10718
10719   if (*slot != NULL)
10720     return (struct dwo_unit *) *slot;
10721
10722   /* Use a for loop so that we don't loop forever on bad debug info.  */
10723   for (i = 0; i < dwp_htab->nr_slots; ++i)
10724     {
10725       ULONGEST signature_in_table;
10726
10727       signature_in_table =
10728         read_8_bytes (dbfd, dwp_htab->hash_table + hash * sizeof (uint64_t));
10729       if (signature_in_table == signature)
10730         {
10731           uint32_t unit_index =
10732             read_4_bytes (dbfd,
10733                           dwp_htab->unit_table + hash * sizeof (uint32_t));
10734
10735           if (dwp_file->version == 1)
10736             {
10737               *slot = create_dwo_unit_in_dwp_v1 (dwp_file, unit_index,
10738                                                  comp_dir, signature,
10739                                                  is_debug_types);
10740             }
10741           else
10742             {
10743               *slot = create_dwo_unit_in_dwp_v2 (dwp_file, unit_index,
10744                                                  comp_dir, signature,
10745                                                  is_debug_types);
10746             }
10747           return (struct dwo_unit *) *slot;
10748         }
10749       if (signature_in_table == 0)
10750         return NULL;
10751       hash = (hash + hash2) & mask;
10752     }
10753
10754   error (_("Dwarf Error: bad DWP hash table, lookup didn't terminate"
10755            " [in module %s]"),
10756          dwp_file->name);
10757 }
10758
10759 /* Subroutine of open_dwo_file,open_dwp_file to simplify them.
10760    Open the file specified by FILE_NAME and hand it off to BFD for
10761    preliminary analysis.  Return a newly initialized bfd *, which
10762    includes a canonicalized copy of FILE_NAME.
10763    If IS_DWP is TRUE, we're opening a DWP file, otherwise a DWO file.
10764    SEARCH_CWD is true if the current directory is to be searched.
10765    It will be searched before debug-file-directory.
10766    If successful, the file is added to the bfd include table of the
10767    objfile's bfd (see gdb_bfd_record_inclusion).
10768    If unable to find/open the file, return NULL.
10769    NOTE: This function is derived from symfile_bfd_open.  */
10770
10771 static gdb_bfd_ref_ptr
10772 try_open_dwop_file (const char *file_name, int is_dwp, int search_cwd)
10773 {
10774   int desc, flags;
10775   char *absolute_name;
10776   /* Blech.  OPF_TRY_CWD_FIRST also disables searching the path list if
10777      FILE_NAME contains a '/'.  So we can't use it.  Instead prepend "."
10778      to debug_file_directory.  */
10779   char *search_path;
10780   static const char dirname_separator_string[] = { DIRNAME_SEPARATOR, '\0' };
10781
10782   if (search_cwd)
10783     {
10784       if (*debug_file_directory != '\0')
10785         search_path = concat (".", dirname_separator_string,
10786                               debug_file_directory, (char *) NULL);
10787       else
10788         search_path = xstrdup (".");
10789     }
10790   else
10791     search_path = xstrdup (debug_file_directory);
10792
10793   flags = OPF_RETURN_REALPATH;
10794   if (is_dwp)
10795     flags |= OPF_SEARCH_IN_PATH;
10796   desc = openp (search_path, flags, file_name,
10797                 O_RDONLY | O_BINARY, &absolute_name);
10798   xfree (search_path);
10799   if (desc < 0)
10800     return NULL;
10801
10802   gdb_bfd_ref_ptr sym_bfd (gdb_bfd_open (absolute_name, gnutarget, desc));
10803   xfree (absolute_name);
10804   if (sym_bfd == NULL)
10805     return NULL;
10806   bfd_set_cacheable (sym_bfd.get (), 1);
10807
10808   if (!bfd_check_format (sym_bfd.get (), bfd_object))
10809     return NULL;
10810
10811   /* Success.  Record the bfd as having been included by the objfile's bfd.
10812      This is important because things like demangled_names_hash lives in the
10813      objfile's per_bfd space and may have references to things like symbol
10814      names that live in the DWO/DWP file's per_bfd space.  PR 16426.  */
10815   gdb_bfd_record_inclusion (dwarf2_per_objfile->objfile->obfd, sym_bfd.get ());
10816
10817   return sym_bfd;
10818 }
10819
10820 /* Try to open DWO file FILE_NAME.
10821    COMP_DIR is the DW_AT_comp_dir attribute.
10822    The result is the bfd handle of the file.
10823    If there is a problem finding or opening the file, return NULL.
10824    Upon success, the canonicalized path of the file is stored in the bfd,
10825    same as symfile_bfd_open.  */
10826
10827 static gdb_bfd_ref_ptr
10828 open_dwo_file (const char *file_name, const char *comp_dir)
10829 {
10830   if (IS_ABSOLUTE_PATH (file_name))
10831     return try_open_dwop_file (file_name, 0 /*is_dwp*/, 0 /*search_cwd*/);
10832
10833   /* Before trying the search path, try DWO_NAME in COMP_DIR.  */
10834
10835   if (comp_dir != NULL)
10836     {
10837       char *path_to_try = concat (comp_dir, SLASH_STRING,
10838                                   file_name, (char *) NULL);
10839
10840       /* NOTE: If comp_dir is a relative path, this will also try the
10841          search path, which seems useful.  */
10842       gdb_bfd_ref_ptr abfd (try_open_dwop_file (path_to_try, 0 /*is_dwp*/,
10843                                                 1 /*search_cwd*/));
10844       xfree (path_to_try);
10845       if (abfd != NULL)
10846         return abfd;
10847     }
10848
10849   /* That didn't work, try debug-file-directory, which, despite its name,
10850      is a list of paths.  */
10851
10852   if (*debug_file_directory == '\0')
10853     return NULL;
10854
10855   return try_open_dwop_file (file_name, 0 /*is_dwp*/, 1 /*search_cwd*/);
10856 }
10857
10858 /* This function is mapped across the sections and remembers the offset and
10859    size of each of the DWO debugging sections we are interested in.  */
10860
10861 static void
10862 dwarf2_locate_dwo_sections (bfd *abfd, asection *sectp, void *dwo_sections_ptr)
10863 {
10864   struct dwo_sections *dwo_sections = (struct dwo_sections *) dwo_sections_ptr;
10865   const struct dwop_section_names *names = &dwop_section_names;
10866
10867   if (section_is_p (sectp->name, &names->abbrev_dwo))
10868     {
10869       dwo_sections->abbrev.s.section = sectp;
10870       dwo_sections->abbrev.size = bfd_get_section_size (sectp);
10871     }
10872   else if (section_is_p (sectp->name, &names->info_dwo))
10873     {
10874       dwo_sections->info.s.section = sectp;
10875       dwo_sections->info.size = bfd_get_section_size (sectp);
10876     }
10877   else if (section_is_p (sectp->name, &names->line_dwo))
10878     {
10879       dwo_sections->line.s.section = sectp;
10880       dwo_sections->line.size = bfd_get_section_size (sectp);
10881     }
10882   else if (section_is_p (sectp->name, &names->loc_dwo))
10883     {
10884       dwo_sections->loc.s.section = sectp;
10885       dwo_sections->loc.size = bfd_get_section_size (sectp);
10886     }
10887   else if (section_is_p (sectp->name, &names->macinfo_dwo))
10888     {
10889       dwo_sections->macinfo.s.section = sectp;
10890       dwo_sections->macinfo.size = bfd_get_section_size (sectp);
10891     }
10892   else if (section_is_p (sectp->name, &names->macro_dwo))
10893     {
10894       dwo_sections->macro.s.section = sectp;
10895       dwo_sections->macro.size = bfd_get_section_size (sectp);
10896     }
10897   else if (section_is_p (sectp->name, &names->str_dwo))
10898     {
10899       dwo_sections->str.s.section = sectp;
10900       dwo_sections->str.size = bfd_get_section_size (sectp);
10901     }
10902   else if (section_is_p (sectp->name, &names->str_offsets_dwo))
10903     {
10904       dwo_sections->str_offsets.s.section = sectp;
10905       dwo_sections->str_offsets.size = bfd_get_section_size (sectp);
10906     }
10907   else if (section_is_p (sectp->name, &names->types_dwo))
10908     {
10909       struct dwarf2_section_info type_section;
10910
10911       memset (&type_section, 0, sizeof (type_section));
10912       type_section.s.section = sectp;
10913       type_section.size = bfd_get_section_size (sectp);
10914       VEC_safe_push (dwarf2_section_info_def, dwo_sections->types,
10915                      &type_section);
10916     }
10917 }
10918
10919 /* Initialize the use of the DWO file specified by DWO_NAME and referenced
10920    by PER_CU.  This is for the non-DWP case.
10921    The result is NULL if DWO_NAME can't be found.  */
10922
10923 static struct dwo_file *
10924 open_and_init_dwo_file (struct dwarf2_per_cu_data *per_cu,
10925                         const char *dwo_name, const char *comp_dir)
10926 {
10927   struct objfile *objfile = dwarf2_per_objfile->objfile;
10928   struct dwo_file *dwo_file;
10929   struct cleanup *cleanups;
10930
10931   gdb_bfd_ref_ptr dbfd (open_dwo_file (dwo_name, comp_dir));
10932   if (dbfd == NULL)
10933     {
10934       if (dwarf_read_debug)
10935         fprintf_unfiltered (gdb_stdlog, "DWO file not found: %s\n", dwo_name);
10936       return NULL;
10937     }
10938   dwo_file = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_file);
10939   dwo_file->dwo_name = dwo_name;
10940   dwo_file->comp_dir = comp_dir;
10941   dwo_file->dbfd = dbfd.release ();
10942
10943   cleanups = make_cleanup (free_dwo_file_cleanup, dwo_file);
10944
10945   bfd_map_over_sections (dwo_file->dbfd, dwarf2_locate_dwo_sections,
10946                          &dwo_file->sections);
10947
10948   create_cus_hash_table (*dwo_file, dwo_file->sections.info, dwo_file->cus);
10949
10950   create_debug_types_hash_table (dwo_file, dwo_file->sections.types,
10951                                  dwo_file->tus);
10952
10953   discard_cleanups (cleanups);
10954
10955   if (dwarf_read_debug)
10956     fprintf_unfiltered (gdb_stdlog, "DWO file found: %s\n", dwo_name);
10957
10958   return dwo_file;
10959 }
10960
10961 /* This function is mapped across the sections and remembers the offset and
10962    size of each of the DWP debugging sections common to version 1 and 2 that
10963    we are interested in.  */
10964
10965 static void
10966 dwarf2_locate_common_dwp_sections (bfd *abfd, asection *sectp,
10967                                    void *dwp_file_ptr)
10968 {
10969   struct dwp_file *dwp_file = (struct dwp_file *) dwp_file_ptr;
10970   const struct dwop_section_names *names = &dwop_section_names;
10971   unsigned int elf_section_nr = elf_section_data (sectp)->this_idx;
10972
10973   /* Record the ELF section number for later lookup: this is what the
10974      .debug_cu_index,.debug_tu_index tables use in DWP V1.  */
10975   gdb_assert (elf_section_nr < dwp_file->num_sections);
10976   dwp_file->elf_sections[elf_section_nr] = sectp;
10977
10978   /* Look for specific sections that we need.  */
10979   if (section_is_p (sectp->name, &names->str_dwo))
10980     {
10981       dwp_file->sections.str.s.section = sectp;
10982       dwp_file->sections.str.size = bfd_get_section_size (sectp);
10983     }
10984   else if (section_is_p (sectp->name, &names->cu_index))
10985     {
10986       dwp_file->sections.cu_index.s.section = sectp;
10987       dwp_file->sections.cu_index.size = bfd_get_section_size (sectp);
10988     }
10989   else if (section_is_p (sectp->name, &names->tu_index))
10990     {
10991       dwp_file->sections.tu_index.s.section = sectp;
10992       dwp_file->sections.tu_index.size = bfd_get_section_size (sectp);
10993     }
10994 }
10995
10996 /* This function is mapped across the sections and remembers the offset and
10997    size of each of the DWP version 2 debugging sections that we are interested
10998    in.  This is split into a separate function because we don't know if we
10999    have version 1 or 2 until we parse the cu_index/tu_index sections.  */
11000
11001 static void
11002 dwarf2_locate_v2_dwp_sections (bfd *abfd, asection *sectp, void *dwp_file_ptr)
11003 {
11004   struct dwp_file *dwp_file = (struct dwp_file *) dwp_file_ptr;
11005   const struct dwop_section_names *names = &dwop_section_names;
11006   unsigned int elf_section_nr = elf_section_data (sectp)->this_idx;
11007
11008   /* Record the ELF section number for later lookup: this is what the
11009      .debug_cu_index,.debug_tu_index tables use in DWP V1.  */
11010   gdb_assert (elf_section_nr < dwp_file->num_sections);
11011   dwp_file->elf_sections[elf_section_nr] = sectp;
11012
11013   /* Look for specific sections that we need.  */
11014   if (section_is_p (sectp->name, &names->abbrev_dwo))
11015     {
11016       dwp_file->sections.abbrev.s.section = sectp;
11017       dwp_file->sections.abbrev.size = bfd_get_section_size (sectp);
11018     }
11019   else if (section_is_p (sectp->name, &names->info_dwo))
11020     {
11021       dwp_file->sections.info.s.section = sectp;
11022       dwp_file->sections.info.size = bfd_get_section_size (sectp);
11023     }
11024   else if (section_is_p (sectp->name, &names->line_dwo))
11025     {
11026       dwp_file->sections.line.s.section = sectp;
11027       dwp_file->sections.line.size = bfd_get_section_size (sectp);
11028     }
11029   else if (section_is_p (sectp->name, &names->loc_dwo))
11030     {
11031       dwp_file->sections.loc.s.section = sectp;
11032       dwp_file->sections.loc.size = bfd_get_section_size (sectp);
11033     }
11034   else if (section_is_p (sectp->name, &names->macinfo_dwo))
11035     {
11036       dwp_file->sections.macinfo.s.section = sectp;
11037       dwp_file->sections.macinfo.size = bfd_get_section_size (sectp);
11038     }
11039   else if (section_is_p (sectp->name, &names->macro_dwo))
11040     {
11041       dwp_file->sections.macro.s.section = sectp;
11042       dwp_file->sections.macro.size = bfd_get_section_size (sectp);
11043     }
11044   else if (section_is_p (sectp->name, &names->str_offsets_dwo))
11045     {
11046       dwp_file->sections.str_offsets.s.section = sectp;
11047       dwp_file->sections.str_offsets.size = bfd_get_section_size (sectp);
11048     }
11049   else if (section_is_p (sectp->name, &names->types_dwo))
11050     {
11051       dwp_file->sections.types.s.section = sectp;
11052       dwp_file->sections.types.size = bfd_get_section_size (sectp);
11053     }
11054 }
11055
11056 /* Hash function for dwp_file loaded CUs/TUs.  */
11057
11058 static hashval_t
11059 hash_dwp_loaded_cutus (const void *item)
11060 {
11061   const struct dwo_unit *dwo_unit = (const struct dwo_unit *) item;
11062
11063   /* This drops the top 32 bits of the signature, but is ok for a hash.  */
11064   return dwo_unit->signature;
11065 }
11066
11067 /* Equality function for dwp_file loaded CUs/TUs.  */
11068
11069 static int
11070 eq_dwp_loaded_cutus (const void *a, const void *b)
11071 {
11072   const struct dwo_unit *dua = (const struct dwo_unit *) a;
11073   const struct dwo_unit *dub = (const struct dwo_unit *) b;
11074
11075   return dua->signature == dub->signature;
11076 }
11077
11078 /* Allocate a hash table for dwp_file loaded CUs/TUs.  */
11079
11080 static htab_t
11081 allocate_dwp_loaded_cutus_table (struct objfile *objfile)
11082 {
11083   return htab_create_alloc_ex (3,
11084                                hash_dwp_loaded_cutus,
11085                                eq_dwp_loaded_cutus,
11086                                NULL,
11087                                &objfile->objfile_obstack,
11088                                hashtab_obstack_allocate,
11089                                dummy_obstack_deallocate);
11090 }
11091
11092 /* Try to open DWP file FILE_NAME.
11093    The result is the bfd handle of the file.
11094    If there is a problem finding or opening the file, return NULL.
11095    Upon success, the canonicalized path of the file is stored in the bfd,
11096    same as symfile_bfd_open.  */
11097
11098 static gdb_bfd_ref_ptr
11099 open_dwp_file (const char *file_name)
11100 {
11101   gdb_bfd_ref_ptr abfd (try_open_dwop_file (file_name, 1 /*is_dwp*/,
11102                                             1 /*search_cwd*/));
11103   if (abfd != NULL)
11104     return abfd;
11105
11106   /* Work around upstream bug 15652.
11107      http://sourceware.org/bugzilla/show_bug.cgi?id=15652
11108      [Whether that's a "bug" is debatable, but it is getting in our way.]
11109      We have no real idea where the dwp file is, because gdb's realpath-ing
11110      of the executable's path may have discarded the needed info.
11111      [IWBN if the dwp file name was recorded in the executable, akin to
11112      .gnu_debuglink, but that doesn't exist yet.]
11113      Strip the directory from FILE_NAME and search again.  */
11114   if (*debug_file_directory != '\0')
11115     {
11116       /* Don't implicitly search the current directory here.
11117          If the user wants to search "." to handle this case,
11118          it must be added to debug-file-directory.  */
11119       return try_open_dwop_file (lbasename (file_name), 1 /*is_dwp*/,
11120                                  0 /*search_cwd*/);
11121     }
11122
11123   return NULL;
11124 }
11125
11126 /* Initialize the use of the DWP file for the current objfile.
11127    By convention the name of the DWP file is ${objfile}.dwp.
11128    The result is NULL if it can't be found.  */
11129
11130 static struct dwp_file *
11131 open_and_init_dwp_file (void)
11132 {
11133   struct objfile *objfile = dwarf2_per_objfile->objfile;
11134   struct dwp_file *dwp_file;
11135
11136   /* Try to find first .dwp for the binary file before any symbolic links
11137      resolving.  */
11138
11139   /* If the objfile is a debug file, find the name of the real binary
11140      file and get the name of dwp file from there.  */
11141   std::string dwp_name;
11142   if (objfile->separate_debug_objfile_backlink != NULL)
11143     {
11144       struct objfile *backlink = objfile->separate_debug_objfile_backlink;
11145       const char *backlink_basename = lbasename (backlink->original_name);
11146
11147       dwp_name = ldirname (objfile->original_name) + SLASH_STRING + backlink_basename;
11148     }
11149   else
11150     dwp_name = objfile->original_name;
11151
11152   dwp_name += ".dwp";
11153
11154   gdb_bfd_ref_ptr dbfd (open_dwp_file (dwp_name.c_str ()));
11155   if (dbfd == NULL
11156       && strcmp (objfile->original_name, objfile_name (objfile)) != 0)
11157     {
11158       /* Try to find .dwp for the binary file after gdb_realpath resolving.  */
11159       dwp_name = objfile_name (objfile);
11160       dwp_name += ".dwp";
11161       dbfd = open_dwp_file (dwp_name.c_str ());
11162     }
11163
11164   if (dbfd == NULL)
11165     {
11166       if (dwarf_read_debug)
11167         fprintf_unfiltered (gdb_stdlog, "DWP file not found: %s\n", dwp_name.c_str ());
11168       return NULL;
11169     }
11170   dwp_file = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwp_file);
11171   dwp_file->name = bfd_get_filename (dbfd.get ());
11172   dwp_file->dbfd = dbfd.release ();
11173
11174   /* +1: section 0 is unused */
11175   dwp_file->num_sections = bfd_count_sections (dwp_file->dbfd) + 1;
11176   dwp_file->elf_sections =
11177     OBSTACK_CALLOC (&objfile->objfile_obstack,
11178                     dwp_file->num_sections, asection *);
11179
11180   bfd_map_over_sections (dwp_file->dbfd, dwarf2_locate_common_dwp_sections,
11181                          dwp_file);
11182
11183   dwp_file->cus = create_dwp_hash_table (dwp_file, 0);
11184
11185   dwp_file->tus = create_dwp_hash_table (dwp_file, 1);
11186
11187   /* The DWP file version is stored in the hash table.  Oh well.  */
11188   if (dwp_file->cus->version != dwp_file->tus->version)
11189     {
11190       /* Technically speaking, we should try to limp along, but this is
11191          pretty bizarre.  We use pulongest here because that's the established
11192          portability solution (e.g, we cannot use %u for uint32_t).  */
11193       error (_("Dwarf Error: DWP file CU version %s doesn't match"
11194                " TU version %s [in DWP file %s]"),
11195              pulongest (dwp_file->cus->version),
11196              pulongest (dwp_file->tus->version), dwp_name.c_str ());
11197     }
11198   dwp_file->version = dwp_file->cus->version;
11199
11200   if (dwp_file->version == 2)
11201     bfd_map_over_sections (dwp_file->dbfd, dwarf2_locate_v2_dwp_sections,
11202                            dwp_file);
11203
11204   dwp_file->loaded_cus = allocate_dwp_loaded_cutus_table (objfile);
11205   dwp_file->loaded_tus = allocate_dwp_loaded_cutus_table (objfile);
11206
11207   if (dwarf_read_debug)
11208     {
11209       fprintf_unfiltered (gdb_stdlog, "DWP file found: %s\n", dwp_file->name);
11210       fprintf_unfiltered (gdb_stdlog,
11211                           "    %s CUs, %s TUs\n",
11212                           pulongest (dwp_file->cus ? dwp_file->cus->nr_units : 0),
11213                           pulongest (dwp_file->tus ? dwp_file->tus->nr_units : 0));
11214     }
11215
11216   return dwp_file;
11217 }
11218
11219 /* Wrapper around open_and_init_dwp_file, only open it once.  */
11220
11221 static struct dwp_file *
11222 get_dwp_file (void)
11223 {
11224   if (! dwarf2_per_objfile->dwp_checked)
11225     {
11226       dwarf2_per_objfile->dwp_file = open_and_init_dwp_file ();
11227       dwarf2_per_objfile->dwp_checked = 1;
11228     }
11229   return dwarf2_per_objfile->dwp_file;
11230 }
11231
11232 /* Subroutine of lookup_dwo_comp_unit, lookup_dwo_type_unit.
11233    Look up the CU/TU with signature SIGNATURE, either in DWO file DWO_NAME
11234    or in the DWP file for the objfile, referenced by THIS_UNIT.
11235    If non-NULL, comp_dir is the DW_AT_comp_dir attribute.
11236    IS_DEBUG_TYPES is non-zero if reading a TU, otherwise read a CU.
11237
11238    This is called, for example, when wanting to read a variable with a
11239    complex location.  Therefore we don't want to do file i/o for every call.
11240    Therefore we don't want to look for a DWO file on every call.
11241    Therefore we first see if we've already seen SIGNATURE in a DWP file,
11242    then we check if we've already seen DWO_NAME, and only THEN do we check
11243    for a DWO file.
11244
11245    The result is a pointer to the dwo_unit object or NULL if we didn't find it
11246    (dwo_id mismatch or couldn't find the DWO/DWP file).  */
11247
11248 static struct dwo_unit *
11249 lookup_dwo_cutu (struct dwarf2_per_cu_data *this_unit,
11250                  const char *dwo_name, const char *comp_dir,
11251                  ULONGEST signature, int is_debug_types)
11252 {
11253   struct objfile *objfile = dwarf2_per_objfile->objfile;
11254   const char *kind = is_debug_types ? "TU" : "CU";
11255   void **dwo_file_slot;
11256   struct dwo_file *dwo_file;
11257   struct dwp_file *dwp_file;
11258
11259   /* First see if there's a DWP file.
11260      If we have a DWP file but didn't find the DWO inside it, don't
11261      look for the original DWO file.  It makes gdb behave differently
11262      depending on whether one is debugging in the build tree.  */
11263
11264   dwp_file = get_dwp_file ();
11265   if (dwp_file != NULL)
11266     {
11267       const struct dwp_hash_table *dwp_htab =
11268         is_debug_types ? dwp_file->tus : dwp_file->cus;
11269
11270       if (dwp_htab != NULL)
11271         {
11272           struct dwo_unit *dwo_cutu =
11273             lookup_dwo_unit_in_dwp (dwp_file, comp_dir,
11274                                     signature, is_debug_types);
11275
11276           if (dwo_cutu != NULL)
11277             {
11278               if (dwarf_read_debug)
11279                 {
11280                   fprintf_unfiltered (gdb_stdlog,
11281                                       "Virtual DWO %s %s found: @%s\n",
11282                                       kind, hex_string (signature),
11283                                       host_address_to_string (dwo_cutu));
11284                 }
11285               return dwo_cutu;
11286             }
11287         }
11288     }
11289   else
11290     {
11291       /* No DWP file, look for the DWO file.  */
11292
11293       dwo_file_slot = lookup_dwo_file_slot (dwo_name, comp_dir);
11294       if (*dwo_file_slot == NULL)
11295         {
11296           /* Read in the file and build a table of the CUs/TUs it contains.  */
11297           *dwo_file_slot = open_and_init_dwo_file (this_unit, dwo_name, comp_dir);
11298         }
11299       /* NOTE: This will be NULL if unable to open the file.  */
11300       dwo_file = (struct dwo_file *) *dwo_file_slot;
11301
11302       if (dwo_file != NULL)
11303         {
11304           struct dwo_unit *dwo_cutu = NULL;
11305
11306           if (is_debug_types && dwo_file->tus)
11307             {
11308               struct dwo_unit find_dwo_cutu;
11309
11310               memset (&find_dwo_cutu, 0, sizeof (find_dwo_cutu));
11311               find_dwo_cutu.signature = signature;
11312               dwo_cutu
11313                 = (struct dwo_unit *) htab_find (dwo_file->tus, &find_dwo_cutu);
11314             }
11315           else if (!is_debug_types && dwo_file->cus)
11316             {
11317               struct dwo_unit find_dwo_cutu;
11318
11319               memset (&find_dwo_cutu, 0, sizeof (find_dwo_cutu));
11320               find_dwo_cutu.signature = signature;
11321               dwo_cutu = (struct dwo_unit *)htab_find (dwo_file->cus,
11322                                                        &find_dwo_cutu);
11323             }
11324
11325           if (dwo_cutu != NULL)
11326             {
11327               if (dwarf_read_debug)
11328                 {
11329                   fprintf_unfiltered (gdb_stdlog, "DWO %s %s(%s) found: @%s\n",
11330                                       kind, dwo_name, hex_string (signature),
11331                                       host_address_to_string (dwo_cutu));
11332                 }
11333               return dwo_cutu;
11334             }
11335         }
11336     }
11337
11338   /* We didn't find it.  This could mean a dwo_id mismatch, or
11339      someone deleted the DWO/DWP file, or the search path isn't set up
11340      correctly to find the file.  */
11341
11342   if (dwarf_read_debug)
11343     {
11344       fprintf_unfiltered (gdb_stdlog, "DWO %s %s(%s) not found\n",
11345                           kind, dwo_name, hex_string (signature));
11346     }
11347
11348   /* This is a warning and not a complaint because it can be caused by
11349      pilot error (e.g., user accidentally deleting the DWO).  */
11350   {
11351     /* Print the name of the DWP file if we looked there, helps the user
11352        better diagnose the problem.  */
11353     char *dwp_text = NULL;
11354     struct cleanup *cleanups;
11355
11356     if (dwp_file != NULL)
11357       dwp_text = xstrprintf (" [in DWP file %s]", lbasename (dwp_file->name));
11358     cleanups = make_cleanup (xfree, dwp_text);
11359
11360     warning (_("Could not find DWO %s %s(%s)%s referenced by %s at offset 0x%x"
11361                " [in module %s]"),
11362              kind, dwo_name, hex_string (signature),
11363              dwp_text != NULL ? dwp_text : "",
11364              this_unit->is_debug_types ? "TU" : "CU",
11365              to_underlying (this_unit->sect_off), objfile_name (objfile));
11366
11367     do_cleanups (cleanups);
11368   }
11369   return NULL;
11370 }
11371
11372 /* Lookup the DWO CU DWO_NAME/SIGNATURE referenced from THIS_CU.
11373    See lookup_dwo_cutu_unit for details.  */
11374
11375 static struct dwo_unit *
11376 lookup_dwo_comp_unit (struct dwarf2_per_cu_data *this_cu,
11377                       const char *dwo_name, const char *comp_dir,
11378                       ULONGEST signature)
11379 {
11380   return lookup_dwo_cutu (this_cu, dwo_name, comp_dir, signature, 0);
11381 }
11382
11383 /* Lookup the DWO TU DWO_NAME/SIGNATURE referenced from THIS_TU.
11384    See lookup_dwo_cutu_unit for details.  */
11385
11386 static struct dwo_unit *
11387 lookup_dwo_type_unit (struct signatured_type *this_tu,
11388                       const char *dwo_name, const char *comp_dir)
11389 {
11390   return lookup_dwo_cutu (&this_tu->per_cu, dwo_name, comp_dir, this_tu->signature, 1);
11391 }
11392
11393 /* Traversal function for queue_and_load_all_dwo_tus.  */
11394
11395 static int
11396 queue_and_load_dwo_tu (void **slot, void *info)
11397 {
11398   struct dwo_unit *dwo_unit = (struct dwo_unit *) *slot;
11399   struct dwarf2_per_cu_data *per_cu = (struct dwarf2_per_cu_data *) info;
11400   ULONGEST signature = dwo_unit->signature;
11401   struct signatured_type *sig_type =
11402     lookup_dwo_signatured_type (per_cu->cu, signature);
11403
11404   if (sig_type != NULL)
11405     {
11406       struct dwarf2_per_cu_data *sig_cu = &sig_type->per_cu;
11407
11408       /* We pass NULL for DEPENDENT_CU because we don't yet know if there's
11409          a real dependency of PER_CU on SIG_TYPE.  That is detected later
11410          while processing PER_CU.  */
11411       if (maybe_queue_comp_unit (NULL, sig_cu, per_cu->cu->language))
11412         load_full_type_unit (sig_cu);
11413       VEC_safe_push (dwarf2_per_cu_ptr, per_cu->imported_symtabs, sig_cu);
11414     }
11415
11416   return 1;
11417 }
11418
11419 /* Queue all TUs contained in the DWO of PER_CU to be read in.
11420    The DWO may have the only definition of the type, though it may not be
11421    referenced anywhere in PER_CU.  Thus we have to load *all* its TUs.
11422    http://sourceware.org/bugzilla/show_bug.cgi?id=15021  */
11423
11424 static void
11425 queue_and_load_all_dwo_tus (struct dwarf2_per_cu_data *per_cu)
11426 {
11427   struct dwo_unit *dwo_unit;
11428   struct dwo_file *dwo_file;
11429
11430   gdb_assert (!per_cu->is_debug_types);
11431   gdb_assert (get_dwp_file () == NULL);
11432   gdb_assert (per_cu->cu != NULL);
11433
11434   dwo_unit = per_cu->cu->dwo_unit;
11435   gdb_assert (dwo_unit != NULL);
11436
11437   dwo_file = dwo_unit->dwo_file;
11438   if (dwo_file->tus != NULL)
11439     htab_traverse_noresize (dwo_file->tus, queue_and_load_dwo_tu, per_cu);
11440 }
11441
11442 /* Free all resources associated with DWO_FILE.
11443    Close the DWO file and munmap the sections.
11444    All memory should be on the objfile obstack.  */
11445
11446 static void
11447 free_dwo_file (struct dwo_file *dwo_file, struct objfile *objfile)
11448 {
11449
11450   /* Note: dbfd is NULL for virtual DWO files.  */
11451   gdb_bfd_unref (dwo_file->dbfd);
11452
11453   VEC_free (dwarf2_section_info_def, dwo_file->sections.types);
11454 }
11455
11456 /* Wrapper for free_dwo_file for use in cleanups.  */
11457
11458 static void
11459 free_dwo_file_cleanup (void *arg)
11460 {
11461   struct dwo_file *dwo_file = (struct dwo_file *) arg;
11462   struct objfile *objfile = dwarf2_per_objfile->objfile;
11463
11464   free_dwo_file (dwo_file, objfile);
11465 }
11466
11467 /* Traversal function for free_dwo_files.  */
11468
11469 static int
11470 free_dwo_file_from_slot (void **slot, void *info)
11471 {
11472   struct dwo_file *dwo_file = (struct dwo_file *) *slot;
11473   struct objfile *objfile = (struct objfile *) info;
11474
11475   free_dwo_file (dwo_file, objfile);
11476
11477   return 1;
11478 }
11479
11480 /* Free all resources associated with DWO_FILES.  */
11481
11482 static void
11483 free_dwo_files (htab_t dwo_files, struct objfile *objfile)
11484 {
11485   htab_traverse_noresize (dwo_files, free_dwo_file_from_slot, objfile);
11486 }
11487 \f
11488 /* Read in various DIEs.  */
11489
11490 /* qsort helper for inherit_abstract_dies.  */
11491
11492 static int
11493 unsigned_int_compar (const void *ap, const void *bp)
11494 {
11495   unsigned int a = *(unsigned int *) ap;
11496   unsigned int b = *(unsigned int *) bp;
11497
11498   return (a > b) - (b > a);
11499 }
11500
11501 /* DW_AT_abstract_origin inherits whole DIEs (not just their attributes).
11502    Inherit only the children of the DW_AT_abstract_origin DIE not being
11503    already referenced by DW_AT_abstract_origin from the children of the
11504    current DIE.  */
11505
11506 static void
11507 inherit_abstract_dies (struct die_info *die, struct dwarf2_cu *cu)
11508 {
11509   struct die_info *child_die;
11510   unsigned die_children_count;
11511   /* CU offsets which were referenced by children of the current DIE.  */
11512   sect_offset *offsets;
11513   sect_offset *offsets_end, *offsetp;
11514   /* Parent of DIE - referenced by DW_AT_abstract_origin.  */
11515   struct die_info *origin_die;
11516   /* Iterator of the ORIGIN_DIE children.  */
11517   struct die_info *origin_child_die;
11518   struct cleanup *cleanups;
11519   struct attribute *attr;
11520   struct dwarf2_cu *origin_cu;
11521   struct pending **origin_previous_list_in_scope;
11522
11523   attr = dwarf2_attr (die, DW_AT_abstract_origin, cu);
11524   if (!attr)
11525     return;
11526
11527   /* Note that following die references may follow to a die in a
11528      different cu.  */
11529
11530   origin_cu = cu;
11531   origin_die = follow_die_ref (die, attr, &origin_cu);
11532
11533   /* We're inheriting ORIGIN's children into the scope we'd put DIE's
11534      symbols in.  */
11535   origin_previous_list_in_scope = origin_cu->list_in_scope;
11536   origin_cu->list_in_scope = cu->list_in_scope;
11537
11538   if (die->tag != origin_die->tag
11539       && !(die->tag == DW_TAG_inlined_subroutine
11540            && origin_die->tag == DW_TAG_subprogram))
11541     complaint (&symfile_complaints,
11542                _("DIE 0x%x and its abstract origin 0x%x have different tags"),
11543                to_underlying (die->sect_off),
11544                to_underlying (origin_die->sect_off));
11545
11546   child_die = die->child;
11547   die_children_count = 0;
11548   while (child_die && child_die->tag)
11549     {
11550       child_die = sibling_die (child_die);
11551       die_children_count++;
11552     }
11553   offsets = XNEWVEC (sect_offset, die_children_count);
11554   cleanups = make_cleanup (xfree, offsets);
11555
11556   offsets_end = offsets;
11557   for (child_die = die->child;
11558        child_die && child_die->tag;
11559        child_die = sibling_die (child_die))
11560     {
11561       struct die_info *child_origin_die;
11562       struct dwarf2_cu *child_origin_cu;
11563
11564       /* We are trying to process concrete instance entries:
11565          DW_TAG_call_site DIEs indeed have a DW_AT_abstract_origin tag, but
11566          it's not relevant to our analysis here. i.e. detecting DIEs that are
11567          present in the abstract instance but not referenced in the concrete
11568          one.  */
11569       if (child_die->tag == DW_TAG_call_site
11570           || child_die->tag == DW_TAG_GNU_call_site)
11571         continue;
11572
11573       /* For each CHILD_DIE, find the corresponding child of
11574          ORIGIN_DIE.  If there is more than one layer of
11575          DW_AT_abstract_origin, follow them all; there shouldn't be,
11576          but GCC versions at least through 4.4 generate this (GCC PR
11577          40573).  */
11578       child_origin_die = child_die;
11579       child_origin_cu = cu;
11580       while (1)
11581         {
11582           attr = dwarf2_attr (child_origin_die, DW_AT_abstract_origin,
11583                               child_origin_cu);
11584           if (attr == NULL)
11585             break;
11586           child_origin_die = follow_die_ref (child_origin_die, attr,
11587                                              &child_origin_cu);
11588         }
11589
11590       /* According to DWARF3 3.3.8.2 #3 new entries without their abstract
11591          counterpart may exist.  */
11592       if (child_origin_die != child_die)
11593         {
11594           if (child_die->tag != child_origin_die->tag
11595               && !(child_die->tag == DW_TAG_inlined_subroutine
11596                    && child_origin_die->tag == DW_TAG_subprogram))
11597             complaint (&symfile_complaints,
11598                        _("Child DIE 0x%x and its abstract origin 0x%x have "
11599                          "different tags"),
11600                        to_underlying (child_die->sect_off),
11601                        to_underlying (child_origin_die->sect_off));
11602           if (child_origin_die->parent != origin_die)
11603             complaint (&symfile_complaints,
11604                        _("Child DIE 0x%x and its abstract origin 0x%x have "
11605                          "different parents"),
11606                        to_underlying (child_die->sect_off),
11607                        to_underlying (child_origin_die->sect_off));
11608           else
11609             *offsets_end++ = child_origin_die->sect_off;
11610         }
11611     }
11612   qsort (offsets, offsets_end - offsets, sizeof (*offsets),
11613          unsigned_int_compar);
11614   for (offsetp = offsets + 1; offsetp < offsets_end; offsetp++)
11615     if (offsetp[-1] == *offsetp)
11616       complaint (&symfile_complaints,
11617                  _("Multiple children of DIE 0x%x refer "
11618                    "to DIE 0x%x as their abstract origin"),
11619                  to_underlying (die->sect_off), to_underlying (*offsetp));
11620
11621   offsetp = offsets;
11622   origin_child_die = origin_die->child;
11623   while (origin_child_die && origin_child_die->tag)
11624     {
11625       /* Is ORIGIN_CHILD_DIE referenced by any of the DIE children?  */
11626       while (offsetp < offsets_end
11627              && *offsetp < origin_child_die->sect_off)
11628         offsetp++;
11629       if (offsetp >= offsets_end
11630           || *offsetp > origin_child_die->sect_off)
11631         {
11632           /* Found that ORIGIN_CHILD_DIE is really not referenced.
11633              Check whether we're already processing ORIGIN_CHILD_DIE.
11634              This can happen with mutually referenced abstract_origins.
11635              PR 16581.  */
11636           if (!origin_child_die->in_process)
11637             process_die (origin_child_die, origin_cu);
11638         }
11639       origin_child_die = sibling_die (origin_child_die);
11640     }
11641   origin_cu->list_in_scope = origin_previous_list_in_scope;
11642
11643   do_cleanups (cleanups);
11644 }
11645
11646 static void
11647 read_func_scope (struct die_info *die, struct dwarf2_cu *cu)
11648 {
11649   struct objfile *objfile = cu->objfile;
11650   struct gdbarch *gdbarch = get_objfile_arch (objfile);
11651   struct context_stack *newobj;
11652   CORE_ADDR lowpc;
11653   CORE_ADDR highpc;
11654   struct die_info *child_die;
11655   struct attribute *attr, *call_line, *call_file;
11656   const char *name;
11657   CORE_ADDR baseaddr;
11658   struct block *block;
11659   int inlined_func = (die->tag == DW_TAG_inlined_subroutine);
11660   VEC (symbolp) *template_args = NULL;
11661   struct template_symbol *templ_func = NULL;
11662
11663   if (inlined_func)
11664     {
11665       /* If we do not have call site information, we can't show the
11666          caller of this inlined function.  That's too confusing, so
11667          only use the scope for local variables.  */
11668       call_line = dwarf2_attr (die, DW_AT_call_line, cu);
11669       call_file = dwarf2_attr (die, DW_AT_call_file, cu);
11670       if (call_line == NULL || call_file == NULL)
11671         {
11672           read_lexical_block_scope (die, cu);
11673           return;
11674         }
11675     }
11676
11677   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
11678
11679   name = dwarf2_name (die, cu);
11680
11681   /* Ignore functions with missing or empty names.  These are actually
11682      illegal according to the DWARF standard.  */
11683   if (name == NULL)
11684     {
11685       complaint (&symfile_complaints,
11686                  _("missing name for subprogram DIE at %d"),
11687                  to_underlying (die->sect_off));
11688       return;
11689     }
11690
11691   /* Ignore functions with missing or invalid low and high pc attributes.  */
11692   if (dwarf2_get_pc_bounds (die, &lowpc, &highpc, cu, NULL)
11693       <= PC_BOUNDS_INVALID)
11694     {
11695       attr = dwarf2_attr (die, DW_AT_external, cu);
11696       if (!attr || !DW_UNSND (attr))
11697         complaint (&symfile_complaints,
11698                    _("cannot get low and high bounds "
11699                      "for subprogram DIE at %d"),
11700                    to_underlying (die->sect_off));
11701       return;
11702     }
11703
11704   lowpc = gdbarch_adjust_dwarf2_addr (gdbarch, lowpc + baseaddr);
11705   highpc = gdbarch_adjust_dwarf2_addr (gdbarch, highpc + baseaddr);
11706
11707   /* If we have any template arguments, then we must allocate a
11708      different sort of symbol.  */
11709   for (child_die = die->child; child_die; child_die = sibling_die (child_die))
11710     {
11711       if (child_die->tag == DW_TAG_template_type_param
11712           || child_die->tag == DW_TAG_template_value_param)
11713         {
11714           templ_func = allocate_template_symbol (objfile);
11715           templ_func->base.is_cplus_template_function = 1;
11716           break;
11717         }
11718     }
11719
11720   newobj = push_context (0, lowpc);
11721   newobj->name = new_symbol_full (die, read_type_die (die, cu), cu,
11722                                (struct symbol *) templ_func);
11723
11724   /* If there is a location expression for DW_AT_frame_base, record
11725      it.  */
11726   attr = dwarf2_attr (die, DW_AT_frame_base, cu);
11727   if (attr)
11728     dwarf2_symbol_mark_computed (attr, newobj->name, cu, 1);
11729
11730   /* If there is a location for the static link, record it.  */
11731   newobj->static_link = NULL;
11732   attr = dwarf2_attr (die, DW_AT_static_link, cu);
11733   if (attr)
11734     {
11735       newobj->static_link
11736         = XOBNEW (&objfile->objfile_obstack, struct dynamic_prop);
11737       attr_to_dynamic_prop (attr, die, cu, newobj->static_link);
11738     }
11739
11740   cu->list_in_scope = &local_symbols;
11741
11742   if (die->child != NULL)
11743     {
11744       child_die = die->child;
11745       while (child_die && child_die->tag)
11746         {
11747           if (child_die->tag == DW_TAG_template_type_param
11748               || child_die->tag == DW_TAG_template_value_param)
11749             {
11750               struct symbol *arg = new_symbol (child_die, NULL, cu);
11751
11752               if (arg != NULL)
11753                 VEC_safe_push (symbolp, template_args, arg);
11754             }
11755           else
11756             process_die (child_die, cu);
11757           child_die = sibling_die (child_die);
11758         }
11759     }
11760
11761   inherit_abstract_dies (die, cu);
11762
11763   /* If we have a DW_AT_specification, we might need to import using
11764      directives from the context of the specification DIE.  See the
11765      comment in determine_prefix.  */
11766   if (cu->language == language_cplus
11767       && dwarf2_attr (die, DW_AT_specification, cu))
11768     {
11769       struct dwarf2_cu *spec_cu = cu;
11770       struct die_info *spec_die = die_specification (die, &spec_cu);
11771
11772       while (spec_die)
11773         {
11774           child_die = spec_die->child;
11775           while (child_die && child_die->tag)
11776             {
11777               if (child_die->tag == DW_TAG_imported_module)
11778                 process_die (child_die, spec_cu);
11779               child_die = sibling_die (child_die);
11780             }
11781
11782           /* In some cases, GCC generates specification DIEs that
11783              themselves contain DW_AT_specification attributes.  */
11784           spec_die = die_specification (spec_die, &spec_cu);
11785         }
11786     }
11787
11788   newobj = pop_context ();
11789   /* Make a block for the local symbols within.  */
11790   block = finish_block (newobj->name, &local_symbols, newobj->old_blocks,
11791                         newobj->static_link, lowpc, highpc);
11792
11793   /* For C++, set the block's scope.  */
11794   if ((cu->language == language_cplus
11795        || cu->language == language_fortran
11796        || cu->language == language_d
11797        || cu->language == language_rust)
11798       && cu->processing_has_namespace_info)
11799     block_set_scope (block, determine_prefix (die, cu),
11800                      &objfile->objfile_obstack);
11801
11802   /* If we have address ranges, record them.  */
11803   dwarf2_record_block_ranges (die, block, baseaddr, cu);
11804
11805   gdbarch_make_symbol_special (gdbarch, newobj->name, objfile);
11806
11807   /* Attach template arguments to function.  */
11808   if (! VEC_empty (symbolp, template_args))
11809     {
11810       gdb_assert (templ_func != NULL);
11811
11812       templ_func->n_template_arguments = VEC_length (symbolp, template_args);
11813       templ_func->template_arguments
11814         = XOBNEWVEC (&objfile->objfile_obstack, struct symbol *,
11815                      templ_func->n_template_arguments);
11816       memcpy (templ_func->template_arguments,
11817               VEC_address (symbolp, template_args),
11818               (templ_func->n_template_arguments * sizeof (struct symbol *)));
11819       VEC_free (symbolp, template_args);
11820     }
11821
11822   /* In C++, we can have functions nested inside functions (e.g., when
11823      a function declares a class that has methods).  This means that
11824      when we finish processing a function scope, we may need to go
11825      back to building a containing block's symbol lists.  */
11826   local_symbols = newobj->locals;
11827   local_using_directives = newobj->local_using_directives;
11828
11829   /* If we've finished processing a top-level function, subsequent
11830      symbols go in the file symbol list.  */
11831   if (outermost_context_p ())
11832     cu->list_in_scope = &file_symbols;
11833 }
11834
11835 /* Process all the DIES contained within a lexical block scope.  Start
11836    a new scope, process the dies, and then close the scope.  */
11837
11838 static void
11839 read_lexical_block_scope (struct die_info *die, struct dwarf2_cu *cu)
11840 {
11841   struct objfile *objfile = cu->objfile;
11842   struct gdbarch *gdbarch = get_objfile_arch (objfile);
11843   struct context_stack *newobj;
11844   CORE_ADDR lowpc, highpc;
11845   struct die_info *child_die;
11846   CORE_ADDR baseaddr;
11847
11848   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
11849
11850   /* Ignore blocks with missing or invalid low and high pc attributes.  */
11851   /* ??? Perhaps consider discontiguous blocks defined by DW_AT_ranges
11852      as multiple lexical blocks?  Handling children in a sane way would
11853      be nasty.  Might be easier to properly extend generic blocks to
11854      describe ranges.  */
11855   switch (dwarf2_get_pc_bounds (die, &lowpc, &highpc, cu, NULL))
11856     {
11857     case PC_BOUNDS_NOT_PRESENT:
11858       /* DW_TAG_lexical_block has no attributes, process its children as if
11859          there was no wrapping by that DW_TAG_lexical_block.
11860          GCC does no longer produces such DWARF since GCC r224161.  */
11861       for (child_die = die->child;
11862            child_die != NULL && child_die->tag;
11863            child_die = sibling_die (child_die))
11864         process_die (child_die, cu);
11865       return;
11866     case PC_BOUNDS_INVALID:
11867       return;
11868     }
11869   lowpc = gdbarch_adjust_dwarf2_addr (gdbarch, lowpc + baseaddr);
11870   highpc = gdbarch_adjust_dwarf2_addr (gdbarch, highpc + baseaddr);
11871
11872   push_context (0, lowpc);
11873   if (die->child != NULL)
11874     {
11875       child_die = die->child;
11876       while (child_die && child_die->tag)
11877         {
11878           process_die (child_die, cu);
11879           child_die = sibling_die (child_die);
11880         }
11881     }
11882   inherit_abstract_dies (die, cu);
11883   newobj = pop_context ();
11884
11885   if (local_symbols != NULL || local_using_directives != NULL)
11886     {
11887       struct block *block
11888         = finish_block (0, &local_symbols, newobj->old_blocks, NULL,
11889                         newobj->start_addr, highpc);
11890
11891       /* Note that recording ranges after traversing children, as we
11892          do here, means that recording a parent's ranges entails
11893          walking across all its children's ranges as they appear in
11894          the address map, which is quadratic behavior.
11895
11896          It would be nicer to record the parent's ranges before
11897          traversing its children, simply overriding whatever you find
11898          there.  But since we don't even decide whether to create a
11899          block until after we've traversed its children, that's hard
11900          to do.  */
11901       dwarf2_record_block_ranges (die, block, baseaddr, cu);
11902     }
11903   local_symbols = newobj->locals;
11904   local_using_directives = newobj->local_using_directives;
11905 }
11906
11907 /* Read in DW_TAG_call_site and insert it to CU->call_site_htab.  */
11908
11909 static void
11910 read_call_site_scope (struct die_info *die, struct dwarf2_cu *cu)
11911 {
11912   struct objfile *objfile = cu->objfile;
11913   struct gdbarch *gdbarch = get_objfile_arch (objfile);
11914   CORE_ADDR pc, baseaddr;
11915   struct attribute *attr;
11916   struct call_site *call_site, call_site_local;
11917   void **slot;
11918   int nparams;
11919   struct die_info *child_die;
11920
11921   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
11922
11923   attr = dwarf2_attr (die, DW_AT_call_return_pc, cu);
11924   if (attr == NULL)
11925     {
11926       /* This was a pre-DWARF-5 GNU extension alias
11927          for DW_AT_call_return_pc.  */
11928       attr = dwarf2_attr (die, DW_AT_low_pc, cu);
11929     }
11930   if (!attr)
11931     {
11932       complaint (&symfile_complaints,
11933                  _("missing DW_AT_call_return_pc for DW_TAG_call_site "
11934                    "DIE 0x%x [in module %s]"),
11935                  to_underlying (die->sect_off), objfile_name (objfile));
11936       return;
11937     }
11938   pc = attr_value_as_address (attr) + baseaddr;
11939   pc = gdbarch_adjust_dwarf2_addr (gdbarch, pc);
11940
11941   if (cu->call_site_htab == NULL)
11942     cu->call_site_htab = htab_create_alloc_ex (16, core_addr_hash, core_addr_eq,
11943                                                NULL, &objfile->objfile_obstack,
11944                                                hashtab_obstack_allocate, NULL);
11945   call_site_local.pc = pc;
11946   slot = htab_find_slot (cu->call_site_htab, &call_site_local, INSERT);
11947   if (*slot != NULL)
11948     {
11949       complaint (&symfile_complaints,
11950                  _("Duplicate PC %s for DW_TAG_call_site "
11951                    "DIE 0x%x [in module %s]"),
11952                  paddress (gdbarch, pc), to_underlying (die->sect_off),
11953                  objfile_name (objfile));
11954       return;
11955     }
11956
11957   /* Count parameters at the caller.  */
11958
11959   nparams = 0;
11960   for (child_die = die->child; child_die && child_die->tag;
11961        child_die = sibling_die (child_die))
11962     {
11963       if (child_die->tag != DW_TAG_call_site_parameter
11964           && child_die->tag != DW_TAG_GNU_call_site_parameter)
11965         {
11966           complaint (&symfile_complaints,
11967                      _("Tag %d is not DW_TAG_call_site_parameter in "
11968                        "DW_TAG_call_site child DIE 0x%x [in module %s]"),
11969                      child_die->tag, to_underlying (child_die->sect_off),
11970                      objfile_name (objfile));
11971           continue;
11972         }
11973
11974       nparams++;
11975     }
11976
11977   call_site
11978     = ((struct call_site *)
11979        obstack_alloc (&objfile->objfile_obstack,
11980                       sizeof (*call_site)
11981                       + (sizeof (*call_site->parameter) * (nparams - 1))));
11982   *slot = call_site;
11983   memset (call_site, 0, sizeof (*call_site) - sizeof (*call_site->parameter));
11984   call_site->pc = pc;
11985
11986   if (dwarf2_flag_true_p (die, DW_AT_call_tail_call, cu)
11987       || dwarf2_flag_true_p (die, DW_AT_GNU_tail_call, cu))
11988     {
11989       struct die_info *func_die;
11990
11991       /* Skip also over DW_TAG_inlined_subroutine.  */
11992       for (func_die = die->parent;
11993            func_die && func_die->tag != DW_TAG_subprogram
11994            && func_die->tag != DW_TAG_subroutine_type;
11995            func_die = func_die->parent);
11996
11997       /* DW_AT_call_all_calls is a superset
11998          of DW_AT_call_all_tail_calls.  */
11999       if (func_die
12000           && !dwarf2_flag_true_p (func_die, DW_AT_call_all_calls, cu)
12001           && !dwarf2_flag_true_p (func_die, DW_AT_GNU_all_call_sites, cu)
12002           && !dwarf2_flag_true_p (func_die, DW_AT_call_all_tail_calls, cu)
12003           && !dwarf2_flag_true_p (func_die, DW_AT_GNU_all_tail_call_sites, cu))
12004         {
12005           /* TYPE_TAIL_CALL_LIST is not interesting in functions where it is
12006              not complete.  But keep CALL_SITE for look ups via call_site_htab,
12007              both the initial caller containing the real return address PC and
12008              the final callee containing the current PC of a chain of tail
12009              calls do not need to have the tail call list complete.  But any
12010              function candidate for a virtual tail call frame searched via
12011              TYPE_TAIL_CALL_LIST must have the tail call list complete to be
12012              determined unambiguously.  */
12013         }
12014       else
12015         {
12016           struct type *func_type = NULL;
12017
12018           if (func_die)
12019             func_type = get_die_type (func_die, cu);
12020           if (func_type != NULL)
12021             {
12022               gdb_assert (TYPE_CODE (func_type) == TYPE_CODE_FUNC);
12023
12024               /* Enlist this call site to the function.  */
12025               call_site->tail_call_next = TYPE_TAIL_CALL_LIST (func_type);
12026               TYPE_TAIL_CALL_LIST (func_type) = call_site;
12027             }
12028           else
12029             complaint (&symfile_complaints,
12030                        _("Cannot find function owning DW_TAG_call_site "
12031                          "DIE 0x%x [in module %s]"),
12032                        to_underlying (die->sect_off), objfile_name (objfile));
12033         }
12034     }
12035
12036   attr = dwarf2_attr (die, DW_AT_call_target, cu);
12037   if (attr == NULL)
12038     attr = dwarf2_attr (die, DW_AT_GNU_call_site_target, cu);
12039   if (attr == NULL)
12040     attr = dwarf2_attr (die, DW_AT_call_origin, cu);
12041   if (attr == NULL)
12042     {
12043       /* This was a pre-DWARF-5 GNU extension alias for DW_AT_call_origin.  */
12044       attr = dwarf2_attr (die, DW_AT_abstract_origin, cu);
12045     }
12046   SET_FIELD_DWARF_BLOCK (call_site->target, NULL);
12047   if (!attr || (attr_form_is_block (attr) && DW_BLOCK (attr)->size == 0))
12048     /* Keep NULL DWARF_BLOCK.  */;
12049   else if (attr_form_is_block (attr))
12050     {
12051       struct dwarf2_locexpr_baton *dlbaton;
12052
12053       dlbaton = XOBNEW (&objfile->objfile_obstack, struct dwarf2_locexpr_baton);
12054       dlbaton->data = DW_BLOCK (attr)->data;
12055       dlbaton->size = DW_BLOCK (attr)->size;
12056       dlbaton->per_cu = cu->per_cu;
12057
12058       SET_FIELD_DWARF_BLOCK (call_site->target, dlbaton);
12059     }
12060   else if (attr_form_is_ref (attr))
12061     {
12062       struct dwarf2_cu *target_cu = cu;
12063       struct die_info *target_die;
12064
12065       target_die = follow_die_ref (die, attr, &target_cu);
12066       gdb_assert (target_cu->objfile == objfile);
12067       if (die_is_declaration (target_die, target_cu))
12068         {
12069           const char *target_physname;
12070
12071           /* Prefer the mangled name; otherwise compute the demangled one.  */
12072           target_physname = dw2_linkage_name (target_die, target_cu);
12073           if (target_physname == NULL)
12074             target_physname = dwarf2_physname (NULL, target_die, target_cu);
12075           if (target_physname == NULL)
12076             complaint (&symfile_complaints,
12077                        _("DW_AT_call_target target DIE has invalid "
12078                          "physname, for referencing DIE 0x%x [in module %s]"),
12079                        to_underlying (die->sect_off), objfile_name (objfile));
12080           else
12081             SET_FIELD_PHYSNAME (call_site->target, target_physname);
12082         }
12083       else
12084         {
12085           CORE_ADDR lowpc;
12086
12087           /* DW_AT_entry_pc should be preferred.  */
12088           if (dwarf2_get_pc_bounds (target_die, &lowpc, NULL, target_cu, NULL)
12089               <= PC_BOUNDS_INVALID)
12090             complaint (&symfile_complaints,
12091                        _("DW_AT_call_target target DIE has invalid "
12092                          "low pc, for referencing DIE 0x%x [in module %s]"),
12093                        to_underlying (die->sect_off), objfile_name (objfile));
12094           else
12095             {
12096               lowpc = gdbarch_adjust_dwarf2_addr (gdbarch, lowpc + baseaddr);
12097               SET_FIELD_PHYSADDR (call_site->target, lowpc);
12098             }
12099         }
12100     }
12101   else
12102     complaint (&symfile_complaints,
12103                _("DW_TAG_call_site DW_AT_call_target is neither "
12104                  "block nor reference, for DIE 0x%x [in module %s]"),
12105                to_underlying (die->sect_off), objfile_name (objfile));
12106
12107   call_site->per_cu = cu->per_cu;
12108
12109   for (child_die = die->child;
12110        child_die && child_die->tag;
12111        child_die = sibling_die (child_die))
12112     {
12113       struct call_site_parameter *parameter;
12114       struct attribute *loc, *origin;
12115
12116       if (child_die->tag != DW_TAG_call_site_parameter
12117           && child_die->tag != DW_TAG_GNU_call_site_parameter)
12118         {
12119           /* Already printed the complaint above.  */
12120           continue;
12121         }
12122
12123       gdb_assert (call_site->parameter_count < nparams);
12124       parameter = &call_site->parameter[call_site->parameter_count];
12125
12126       /* DW_AT_location specifies the register number or DW_AT_abstract_origin
12127          specifies DW_TAG_formal_parameter.  Value of the data assumed for the
12128          register is contained in DW_AT_call_value.  */
12129
12130       loc = dwarf2_attr (child_die, DW_AT_location, cu);
12131       origin = dwarf2_attr (child_die, DW_AT_call_parameter, cu);
12132       if (origin == NULL)
12133         {
12134           /* This was a pre-DWARF-5 GNU extension alias
12135              for DW_AT_call_parameter.  */
12136           origin = dwarf2_attr (child_die, DW_AT_abstract_origin, cu);
12137         }
12138       if (loc == NULL && origin != NULL && attr_form_is_ref (origin))
12139         {
12140           parameter->kind = CALL_SITE_PARAMETER_PARAM_OFFSET;
12141
12142           sect_offset sect_off
12143             = (sect_offset) dwarf2_get_ref_die_offset (origin);
12144           if (!offset_in_cu_p (&cu->header, sect_off))
12145             {
12146               /* As DW_OP_GNU_parameter_ref uses CU-relative offset this
12147                  binding can be done only inside one CU.  Such referenced DIE
12148                  therefore cannot be even moved to DW_TAG_partial_unit.  */
12149               complaint (&symfile_complaints,
12150                          _("DW_AT_call_parameter offset is not in CU for "
12151                            "DW_TAG_call_site child DIE 0x%x [in module %s]"),
12152                          to_underlying (child_die->sect_off),
12153                          objfile_name (objfile));
12154               continue;
12155             }
12156           parameter->u.param_cu_off
12157             = (cu_offset) (sect_off - cu->header.sect_off);
12158         }
12159       else if (loc == NULL || origin != NULL || !attr_form_is_block (loc))
12160         {
12161           complaint (&symfile_complaints,
12162                      _("No DW_FORM_block* DW_AT_location for "
12163                        "DW_TAG_call_site child DIE 0x%x [in module %s]"),
12164                      to_underlying (child_die->sect_off), objfile_name (objfile));
12165           continue;
12166         }
12167       else
12168         {
12169           parameter->u.dwarf_reg = dwarf_block_to_dwarf_reg
12170             (DW_BLOCK (loc)->data, &DW_BLOCK (loc)->data[DW_BLOCK (loc)->size]);
12171           if (parameter->u.dwarf_reg != -1)
12172             parameter->kind = CALL_SITE_PARAMETER_DWARF_REG;
12173           else if (dwarf_block_to_sp_offset (gdbarch, DW_BLOCK (loc)->data,
12174                                     &DW_BLOCK (loc)->data[DW_BLOCK (loc)->size],
12175                                              &parameter->u.fb_offset))
12176             parameter->kind = CALL_SITE_PARAMETER_FB_OFFSET;
12177           else
12178             {
12179               complaint (&symfile_complaints,
12180                          _("Only single DW_OP_reg or DW_OP_fbreg is supported "
12181                            "for DW_FORM_block* DW_AT_location is supported for "
12182                            "DW_TAG_call_site child DIE 0x%x "
12183                            "[in module %s]"),
12184                          to_underlying (child_die->sect_off),
12185                          objfile_name (objfile));
12186               continue;
12187             }
12188         }
12189
12190       attr = dwarf2_attr (child_die, DW_AT_call_value, cu);
12191       if (attr == NULL)
12192         attr = dwarf2_attr (child_die, DW_AT_GNU_call_site_value, cu);
12193       if (!attr_form_is_block (attr))
12194         {
12195           complaint (&symfile_complaints,
12196                      _("No DW_FORM_block* DW_AT_call_value for "
12197                        "DW_TAG_call_site child DIE 0x%x [in module %s]"),
12198                      to_underlying (child_die->sect_off),
12199                      objfile_name (objfile));
12200           continue;
12201         }
12202       parameter->value = DW_BLOCK (attr)->data;
12203       parameter->value_size = DW_BLOCK (attr)->size;
12204
12205       /* Parameters are not pre-cleared by memset above.  */
12206       parameter->data_value = NULL;
12207       parameter->data_value_size = 0;
12208       call_site->parameter_count++;
12209
12210       attr = dwarf2_attr (child_die, DW_AT_call_data_value, cu);
12211       if (attr == NULL)
12212         attr = dwarf2_attr (child_die, DW_AT_GNU_call_site_data_value, cu);
12213       if (attr)
12214         {
12215           if (!attr_form_is_block (attr))
12216             complaint (&symfile_complaints,
12217                        _("No DW_FORM_block* DW_AT_call_data_value for "
12218                          "DW_TAG_call_site child DIE 0x%x [in module %s]"),
12219                        to_underlying (child_die->sect_off),
12220                        objfile_name (objfile));
12221           else
12222             {
12223               parameter->data_value = DW_BLOCK (attr)->data;
12224               parameter->data_value_size = DW_BLOCK (attr)->size;
12225             }
12226         }
12227     }
12228 }
12229
12230 /* Call CALLBACK from DW_AT_ranges attribute value OFFSET
12231    reading .debug_rnglists.
12232    Callback's type should be:
12233     void (CORE_ADDR range_beginning, CORE_ADDR range_end)
12234    Return true if the attributes are present and valid, otherwise,
12235    return false.  */
12236
12237 template <typename Callback>
12238 static bool
12239 dwarf2_rnglists_process (unsigned offset, struct dwarf2_cu *cu,
12240                          Callback &&callback)
12241 {
12242   struct objfile *objfile = cu->objfile;
12243   struct gdbarch *gdbarch = get_objfile_arch (objfile);
12244   struct comp_unit_head *cu_header = &cu->header;
12245   bfd *obfd = objfile->obfd;
12246   unsigned int addr_size = cu_header->addr_size;
12247   CORE_ADDR mask = ~(~(CORE_ADDR)1 << (addr_size * 8 - 1));
12248   /* Base address selection entry.  */
12249   CORE_ADDR base;
12250   int found_base;
12251   unsigned int dummy;
12252   const gdb_byte *buffer;
12253   CORE_ADDR low = 0;
12254   CORE_ADDR high = 0;
12255   CORE_ADDR baseaddr;
12256   bool overflow = false;
12257
12258   found_base = cu->base_known;
12259   base = cu->base_address;
12260
12261   dwarf2_read_section (objfile, &dwarf2_per_objfile->rnglists);
12262   if (offset >= dwarf2_per_objfile->rnglists.size)
12263     {
12264       complaint (&symfile_complaints,
12265                  _("Offset %d out of bounds for DW_AT_ranges attribute"),
12266                  offset);
12267       return false;
12268     }
12269   buffer = dwarf2_per_objfile->rnglists.buffer + offset;
12270
12271   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
12272
12273   while (1)
12274     {
12275       /* Initialize it due to a false compiler warning.  */
12276       CORE_ADDR range_beginning = 0, range_end = 0;
12277       const gdb_byte *buf_end = (dwarf2_per_objfile->rnglists.buffer
12278                                  + dwarf2_per_objfile->rnglists.size);
12279       unsigned int bytes_read;
12280
12281       if (buffer == buf_end)
12282         {
12283           overflow = true;
12284           break;
12285         }
12286       const auto rlet = static_cast<enum dwarf_range_list_entry>(*buffer++);
12287       switch (rlet)
12288         {
12289         case DW_RLE_end_of_list:
12290           break;
12291         case DW_RLE_base_address:
12292           if (buffer + cu->header.addr_size > buf_end)
12293             {
12294               overflow = true;
12295               break;
12296             }
12297           base = read_address (obfd, buffer, cu, &bytes_read);
12298           found_base = 1;
12299           buffer += bytes_read;
12300           break;
12301         case DW_RLE_start_length:
12302           if (buffer + cu->header.addr_size > buf_end)
12303             {
12304               overflow = true;
12305               break;
12306             }
12307           range_beginning = read_address (obfd, buffer, cu, &bytes_read);
12308           buffer += bytes_read;
12309           range_end = (range_beginning
12310                        + read_unsigned_leb128 (obfd, buffer, &bytes_read));
12311           buffer += bytes_read;
12312           if (buffer > buf_end)
12313             {
12314               overflow = true;
12315               break;
12316             }
12317           break;
12318         case DW_RLE_offset_pair:
12319           range_beginning = read_unsigned_leb128 (obfd, buffer, &bytes_read);
12320           buffer += bytes_read;
12321           if (buffer > buf_end)
12322             {
12323               overflow = true;
12324               break;
12325             }
12326           range_end = read_unsigned_leb128 (obfd, buffer, &bytes_read);
12327           buffer += bytes_read;
12328           if (buffer > buf_end)
12329             {
12330               overflow = true;
12331               break;
12332             }
12333           break;
12334         case DW_RLE_start_end:
12335           if (buffer + 2 * cu->header.addr_size > buf_end)
12336             {
12337               overflow = true;
12338               break;
12339             }
12340           range_beginning = read_address (obfd, buffer, cu, &bytes_read);
12341           buffer += bytes_read;
12342           range_end = read_address (obfd, buffer, cu, &bytes_read);
12343           buffer += bytes_read;
12344           break;
12345         default:
12346           complaint (&symfile_complaints,
12347                      _("Invalid .debug_rnglists data (no base address)"));
12348           return false;
12349         }
12350       if (rlet == DW_RLE_end_of_list || overflow)
12351         break;
12352       if (rlet == DW_RLE_base_address)
12353         continue;
12354
12355       if (!found_base)
12356         {
12357           /* We have no valid base address for the ranges
12358              data.  */
12359           complaint (&symfile_complaints,
12360                      _("Invalid .debug_rnglists data (no base address)"));
12361           return false;
12362         }
12363
12364       if (range_beginning > range_end)
12365         {
12366           /* Inverted range entries are invalid.  */
12367           complaint (&symfile_complaints,
12368                      _("Invalid .debug_rnglists data (inverted range)"));
12369           return false;
12370         }
12371
12372       /* Empty range entries have no effect.  */
12373       if (range_beginning == range_end)
12374         continue;
12375
12376       range_beginning += base;
12377       range_end += base;
12378
12379       /* A not-uncommon case of bad debug info.
12380          Don't pollute the addrmap with bad data.  */
12381       if (range_beginning + baseaddr == 0
12382           && !dwarf2_per_objfile->has_section_at_zero)
12383         {
12384           complaint (&symfile_complaints,
12385                      _(".debug_rnglists entry has start address of zero"
12386                        " [in module %s]"), objfile_name (objfile));
12387           continue;
12388         }
12389
12390       callback (range_beginning, range_end);
12391     }
12392
12393   if (overflow)
12394     {
12395       complaint (&symfile_complaints,
12396                  _("Offset %d is not terminated "
12397                    "for DW_AT_ranges attribute"),
12398                  offset);
12399       return false;
12400     }
12401
12402   return true;
12403 }
12404
12405 /* Call CALLBACK from DW_AT_ranges attribute value OFFSET reading .debug_ranges.
12406    Callback's type should be:
12407     void (CORE_ADDR range_beginning, CORE_ADDR range_end)
12408    Return 1 if the attributes are present and valid, otherwise, return 0.  */
12409
12410 template <typename Callback>
12411 static int
12412 dwarf2_ranges_process (unsigned offset, struct dwarf2_cu *cu,
12413                        Callback &&callback)
12414 {
12415   struct objfile *objfile = cu->objfile;
12416   struct gdbarch *gdbarch = get_objfile_arch (objfile);
12417   struct comp_unit_head *cu_header = &cu->header;
12418   bfd *obfd = objfile->obfd;
12419   unsigned int addr_size = cu_header->addr_size;
12420   CORE_ADDR mask = ~(~(CORE_ADDR)1 << (addr_size * 8 - 1));
12421   /* Base address selection entry.  */
12422   CORE_ADDR base;
12423   int found_base;
12424   unsigned int dummy;
12425   const gdb_byte *buffer;
12426   CORE_ADDR baseaddr;
12427
12428   if (cu_header->version >= 5)
12429     return dwarf2_rnglists_process (offset, cu, callback);
12430
12431   found_base = cu->base_known;
12432   base = cu->base_address;
12433
12434   dwarf2_read_section (objfile, &dwarf2_per_objfile->ranges);
12435   if (offset >= dwarf2_per_objfile->ranges.size)
12436     {
12437       complaint (&symfile_complaints,
12438                  _("Offset %d out of bounds for DW_AT_ranges attribute"),
12439                  offset);
12440       return 0;
12441     }
12442   buffer = dwarf2_per_objfile->ranges.buffer + offset;
12443
12444   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
12445
12446   while (1)
12447     {
12448       CORE_ADDR range_beginning, range_end;
12449
12450       range_beginning = read_address (obfd, buffer, cu, &dummy);
12451       buffer += addr_size;
12452       range_end = read_address (obfd, buffer, cu, &dummy);
12453       buffer += addr_size;
12454       offset += 2 * addr_size;
12455
12456       /* An end of list marker is a pair of zero addresses.  */
12457       if (range_beginning == 0 && range_end == 0)
12458         /* Found the end of list entry.  */
12459         break;
12460
12461       /* Each base address selection entry is a pair of 2 values.
12462          The first is the largest possible address, the second is
12463          the base address.  Check for a base address here.  */
12464       if ((range_beginning & mask) == mask)
12465         {
12466           /* If we found the largest possible address, then we already
12467              have the base address in range_end.  */
12468           base = range_end;
12469           found_base = 1;
12470           continue;
12471         }
12472
12473       if (!found_base)
12474         {
12475           /* We have no valid base address for the ranges
12476              data.  */
12477           complaint (&symfile_complaints,
12478                      _("Invalid .debug_ranges data (no base address)"));
12479           return 0;
12480         }
12481
12482       if (range_beginning > range_end)
12483         {
12484           /* Inverted range entries are invalid.  */
12485           complaint (&symfile_complaints,
12486                      _("Invalid .debug_ranges data (inverted range)"));
12487           return 0;
12488         }
12489
12490       /* Empty range entries have no effect.  */
12491       if (range_beginning == range_end)
12492         continue;
12493
12494       range_beginning += base;
12495       range_end += base;
12496
12497       /* A not-uncommon case of bad debug info.
12498          Don't pollute the addrmap with bad data.  */
12499       if (range_beginning + baseaddr == 0
12500           && !dwarf2_per_objfile->has_section_at_zero)
12501         {
12502           complaint (&symfile_complaints,
12503                      _(".debug_ranges entry has start address of zero"
12504                        " [in module %s]"), objfile_name (objfile));
12505           continue;
12506         }
12507
12508       callback (range_beginning, range_end);
12509     }
12510
12511   return 1;
12512 }
12513
12514 /* Get low and high pc attributes from DW_AT_ranges attribute value OFFSET.
12515    Return 1 if the attributes are present and valid, otherwise, return 0.
12516    If RANGES_PST is not NULL we should setup `objfile->psymtabs_addrmap'.  */
12517
12518 static int
12519 dwarf2_ranges_read (unsigned offset, CORE_ADDR *low_return,
12520                     CORE_ADDR *high_return, struct dwarf2_cu *cu,
12521                     struct partial_symtab *ranges_pst)
12522 {
12523   struct objfile *objfile = cu->objfile;
12524   struct gdbarch *gdbarch = get_objfile_arch (objfile);
12525   const CORE_ADDR baseaddr = ANOFFSET (objfile->section_offsets,
12526                                        SECT_OFF_TEXT (objfile));
12527   int low_set = 0;
12528   CORE_ADDR low = 0;
12529   CORE_ADDR high = 0;
12530   int retval;
12531
12532   retval = dwarf2_ranges_process (offset, cu,
12533     [&] (CORE_ADDR range_beginning, CORE_ADDR range_end)
12534     {
12535       if (ranges_pst != NULL)
12536         {
12537           CORE_ADDR lowpc;
12538           CORE_ADDR highpc;
12539
12540           lowpc = gdbarch_adjust_dwarf2_addr (gdbarch,
12541                                               range_beginning + baseaddr);
12542           highpc = gdbarch_adjust_dwarf2_addr (gdbarch,
12543                                                range_end + baseaddr);
12544           addrmap_set_empty (objfile->psymtabs_addrmap, lowpc, highpc - 1,
12545                              ranges_pst);
12546         }
12547
12548       /* FIXME: This is recording everything as a low-high
12549          segment of consecutive addresses.  We should have a
12550          data structure for discontiguous block ranges
12551          instead.  */
12552       if (! low_set)
12553         {
12554           low = range_beginning;
12555           high = range_end;
12556           low_set = 1;
12557         }
12558       else
12559         {
12560           if (range_beginning < low)
12561             low = range_beginning;
12562           if (range_end > high)
12563             high = range_end;
12564         }
12565     });
12566   if (!retval)
12567     return 0;
12568
12569   if (! low_set)
12570     /* If the first entry is an end-of-list marker, the range
12571        describes an empty scope, i.e. no instructions.  */
12572     return 0;
12573
12574   if (low_return)
12575     *low_return = low;
12576   if (high_return)
12577     *high_return = high;
12578   return 1;
12579 }
12580
12581 /* Get low and high pc attributes from a die.  See enum pc_bounds_kind
12582    definition for the return value.  *LOWPC and *HIGHPC are set iff
12583    neither PC_BOUNDS_NOT_PRESENT nor PC_BOUNDS_INVALID are returned.  */
12584
12585 static enum pc_bounds_kind
12586 dwarf2_get_pc_bounds (struct die_info *die, CORE_ADDR *lowpc,
12587                       CORE_ADDR *highpc, struct dwarf2_cu *cu,
12588                       struct partial_symtab *pst)
12589 {
12590   struct attribute *attr;
12591   struct attribute *attr_high;
12592   CORE_ADDR low = 0;
12593   CORE_ADDR high = 0;
12594   enum pc_bounds_kind ret;
12595
12596   attr_high = dwarf2_attr (die, DW_AT_high_pc, cu);
12597   if (attr_high)
12598     {
12599       attr = dwarf2_attr (die, DW_AT_low_pc, cu);
12600       if (attr)
12601         {
12602           low = attr_value_as_address (attr);
12603           high = attr_value_as_address (attr_high);
12604           if (cu->header.version >= 4 && attr_form_is_constant (attr_high))
12605             high += low;
12606         }
12607       else
12608         /* Found high w/o low attribute.  */
12609         return PC_BOUNDS_INVALID;
12610
12611       /* Found consecutive range of addresses.  */
12612       ret = PC_BOUNDS_HIGH_LOW;
12613     }
12614   else
12615     {
12616       attr = dwarf2_attr (die, DW_AT_ranges, cu);
12617       if (attr != NULL)
12618         {
12619           /* DW_AT_ranges_base does not apply to DIEs from the DWO skeleton.
12620              We take advantage of the fact that DW_AT_ranges does not appear
12621              in DW_TAG_compile_unit of DWO files.  */
12622           int need_ranges_base = die->tag != DW_TAG_compile_unit;
12623           unsigned int ranges_offset = (DW_UNSND (attr)
12624                                         + (need_ranges_base
12625                                            ? cu->ranges_base
12626                                            : 0));
12627
12628           /* Value of the DW_AT_ranges attribute is the offset in the
12629              .debug_ranges section.  */
12630           if (!dwarf2_ranges_read (ranges_offset, &low, &high, cu, pst))
12631             return PC_BOUNDS_INVALID;
12632           /* Found discontinuous range of addresses.  */
12633           ret = PC_BOUNDS_RANGES;
12634         }
12635       else
12636         return PC_BOUNDS_NOT_PRESENT;
12637     }
12638
12639   /* read_partial_die has also the strict LOW < HIGH requirement.  */
12640   if (high <= low)
12641     return PC_BOUNDS_INVALID;
12642
12643   /* When using the GNU linker, .gnu.linkonce. sections are used to
12644      eliminate duplicate copies of functions and vtables and such.
12645      The linker will arbitrarily choose one and discard the others.
12646      The AT_*_pc values for such functions refer to local labels in
12647      these sections.  If the section from that file was discarded, the
12648      labels are not in the output, so the relocs get a value of 0.
12649      If this is a discarded function, mark the pc bounds as invalid,
12650      so that GDB will ignore it.  */
12651   if (low == 0 && !dwarf2_per_objfile->has_section_at_zero)
12652     return PC_BOUNDS_INVALID;
12653
12654   *lowpc = low;
12655   if (highpc)
12656     *highpc = high;
12657   return ret;
12658 }
12659
12660 /* Assuming that DIE represents a subprogram DIE or a lexical block, get
12661    its low and high PC addresses.  Do nothing if these addresses could not
12662    be determined.  Otherwise, set LOWPC to the low address if it is smaller,
12663    and HIGHPC to the high address if greater than HIGHPC.  */
12664
12665 static void
12666 dwarf2_get_subprogram_pc_bounds (struct die_info *die,
12667                                  CORE_ADDR *lowpc, CORE_ADDR *highpc,
12668                                  struct dwarf2_cu *cu)
12669 {
12670   CORE_ADDR low, high;
12671   struct die_info *child = die->child;
12672
12673   if (dwarf2_get_pc_bounds (die, &low, &high, cu, NULL) >= PC_BOUNDS_RANGES)
12674     {
12675       *lowpc = std::min (*lowpc, low);
12676       *highpc = std::max (*highpc, high);
12677     }
12678
12679   /* If the language does not allow nested subprograms (either inside
12680      subprograms or lexical blocks), we're done.  */
12681   if (cu->language != language_ada)
12682     return;
12683
12684   /* Check all the children of the given DIE.  If it contains nested
12685      subprograms, then check their pc bounds.  Likewise, we need to
12686      check lexical blocks as well, as they may also contain subprogram
12687      definitions.  */
12688   while (child && child->tag)
12689     {
12690       if (child->tag == DW_TAG_subprogram
12691           || child->tag == DW_TAG_lexical_block)
12692         dwarf2_get_subprogram_pc_bounds (child, lowpc, highpc, cu);
12693       child = sibling_die (child);
12694     }
12695 }
12696
12697 /* Get the low and high pc's represented by the scope DIE, and store
12698    them in *LOWPC and *HIGHPC.  If the correct values can't be
12699    determined, set *LOWPC to -1 and *HIGHPC to 0.  */
12700
12701 static void
12702 get_scope_pc_bounds (struct die_info *die,
12703                      CORE_ADDR *lowpc, CORE_ADDR *highpc,
12704                      struct dwarf2_cu *cu)
12705 {
12706   CORE_ADDR best_low = (CORE_ADDR) -1;
12707   CORE_ADDR best_high = (CORE_ADDR) 0;
12708   CORE_ADDR current_low, current_high;
12709
12710   if (dwarf2_get_pc_bounds (die, &current_low, &current_high, cu, NULL)
12711       >= PC_BOUNDS_RANGES)
12712     {
12713       best_low = current_low;
12714       best_high = current_high;
12715     }
12716   else
12717     {
12718       struct die_info *child = die->child;
12719
12720       while (child && child->tag)
12721         {
12722           switch (child->tag) {
12723           case DW_TAG_subprogram:
12724             dwarf2_get_subprogram_pc_bounds (child, &best_low, &best_high, cu);
12725             break;
12726           case DW_TAG_namespace:
12727           case DW_TAG_module:
12728             /* FIXME: carlton/2004-01-16: Should we do this for
12729                DW_TAG_class_type/DW_TAG_structure_type, too?  I think
12730                that current GCC's always emit the DIEs corresponding
12731                to definitions of methods of classes as children of a
12732                DW_TAG_compile_unit or DW_TAG_namespace (as opposed to
12733                the DIEs giving the declarations, which could be
12734                anywhere).  But I don't see any reason why the
12735                standards says that they have to be there.  */
12736             get_scope_pc_bounds (child, &current_low, &current_high, cu);
12737
12738             if (current_low != ((CORE_ADDR) -1))
12739               {
12740                 best_low = std::min (best_low, current_low);
12741                 best_high = std::max (best_high, current_high);
12742               }
12743             break;
12744           default:
12745             /* Ignore.  */
12746             break;
12747           }
12748
12749           child = sibling_die (child);
12750         }
12751     }
12752
12753   *lowpc = best_low;
12754   *highpc = best_high;
12755 }
12756
12757 /* Record the address ranges for BLOCK, offset by BASEADDR, as given
12758    in DIE.  */
12759
12760 static void
12761 dwarf2_record_block_ranges (struct die_info *die, struct block *block,
12762                             CORE_ADDR baseaddr, struct dwarf2_cu *cu)
12763 {
12764   struct objfile *objfile = cu->objfile;
12765   struct gdbarch *gdbarch = get_objfile_arch (objfile);
12766   struct attribute *attr;
12767   struct attribute *attr_high;
12768
12769   attr_high = dwarf2_attr (die, DW_AT_high_pc, cu);
12770   if (attr_high)
12771     {
12772       attr = dwarf2_attr (die, DW_AT_low_pc, cu);
12773       if (attr)
12774         {
12775           CORE_ADDR low = attr_value_as_address (attr);
12776           CORE_ADDR high = attr_value_as_address (attr_high);
12777
12778           if (cu->header.version >= 4 && attr_form_is_constant (attr_high))
12779             high += low;
12780
12781           low = gdbarch_adjust_dwarf2_addr (gdbarch, low + baseaddr);
12782           high = gdbarch_adjust_dwarf2_addr (gdbarch, high + baseaddr);
12783           record_block_range (block, low, high - 1);
12784         }
12785     }
12786
12787   attr = dwarf2_attr (die, DW_AT_ranges, cu);
12788   if (attr)
12789     {
12790       bfd *obfd = objfile->obfd;
12791       /* DW_AT_ranges_base does not apply to DIEs from the DWO skeleton.
12792          We take advantage of the fact that DW_AT_ranges does not appear
12793          in DW_TAG_compile_unit of DWO files.  */
12794       int need_ranges_base = die->tag != DW_TAG_compile_unit;
12795
12796       /* The value of the DW_AT_ranges attribute is the offset of the
12797          address range list in the .debug_ranges section.  */
12798       unsigned long offset = (DW_UNSND (attr)
12799                               + (need_ranges_base ? cu->ranges_base : 0));
12800       const gdb_byte *buffer;
12801
12802       /* For some target architectures, but not others, the
12803          read_address function sign-extends the addresses it returns.
12804          To recognize base address selection entries, we need a
12805          mask.  */
12806       unsigned int addr_size = cu->header.addr_size;
12807       CORE_ADDR base_select_mask = ~(~(CORE_ADDR)1 << (addr_size * 8 - 1));
12808
12809       /* The base address, to which the next pair is relative.  Note
12810          that this 'base' is a DWARF concept: most entries in a range
12811          list are relative, to reduce the number of relocs against the
12812          debugging information.  This is separate from this function's
12813          'baseaddr' argument, which GDB uses to relocate debugging
12814          information from a shared library based on the address at
12815          which the library was loaded.  */
12816       CORE_ADDR base = cu->base_address;
12817       int base_known = cu->base_known;
12818
12819       dwarf2_ranges_process (offset, cu,
12820         [&] (CORE_ADDR start, CORE_ADDR end)
12821         {
12822           start += baseaddr;
12823           end += baseaddr;
12824           start = gdbarch_adjust_dwarf2_addr (gdbarch, start);
12825           end = gdbarch_adjust_dwarf2_addr (gdbarch, end);
12826           record_block_range (block, start, end - 1);
12827         });
12828     }
12829 }
12830
12831 /* Check whether the producer field indicates either of GCC < 4.6, or the
12832    Intel C/C++ compiler, and cache the result in CU.  */
12833
12834 static void
12835 check_producer (struct dwarf2_cu *cu)
12836 {
12837   int major, minor;
12838
12839   if (cu->producer == NULL)
12840     {
12841       /* For unknown compilers expect their behavior is DWARF version
12842          compliant.
12843
12844          GCC started to support .debug_types sections by -gdwarf-4 since
12845          gcc-4.5.x.  As the .debug_types sections are missing DW_AT_producer
12846          for their space efficiency GDB cannot workaround gcc-4.5.x -gdwarf-4
12847          combination.  gcc-4.5.x -gdwarf-4 binaries have DW_AT_accessibility
12848          interpreted incorrectly by GDB now - GCC PR debug/48229.  */
12849     }
12850   else if (producer_is_gcc (cu->producer, &major, &minor))
12851     {
12852       cu->producer_is_gxx_lt_4_6 = major < 4 || (major == 4 && minor < 6);
12853       cu->producer_is_gcc_lt_4_3 = major < 4 || (major == 4 && minor < 3);
12854     }
12855   else if (startswith (cu->producer, "Intel(R) C"))
12856     cu->producer_is_icc = 1;
12857   else
12858     {
12859       /* For other non-GCC compilers, expect their behavior is DWARF version
12860          compliant.  */
12861     }
12862
12863   cu->checked_producer = 1;
12864 }
12865
12866 /* Check for GCC PR debug/45124 fix which is not present in any G++ version up
12867    to 4.5.any while it is present already in G++ 4.6.0 - the PR has been fixed
12868    during 4.6.0 experimental.  */
12869
12870 static int
12871 producer_is_gxx_lt_4_6 (struct dwarf2_cu *cu)
12872 {
12873   if (!cu->checked_producer)
12874     check_producer (cu);
12875
12876   return cu->producer_is_gxx_lt_4_6;
12877 }
12878
12879 /* Return the default accessibility type if it is not overriden by
12880    DW_AT_accessibility.  */
12881
12882 static enum dwarf_access_attribute
12883 dwarf2_default_access_attribute (struct die_info *die, struct dwarf2_cu *cu)
12884 {
12885   if (cu->header.version < 3 || producer_is_gxx_lt_4_6 (cu))
12886     {
12887       /* The default DWARF 2 accessibility for members is public, the default
12888          accessibility for inheritance is private.  */
12889
12890       if (die->tag != DW_TAG_inheritance)
12891         return DW_ACCESS_public;
12892       else
12893         return DW_ACCESS_private;
12894     }
12895   else
12896     {
12897       /* DWARF 3+ defines the default accessibility a different way.  The same
12898          rules apply now for DW_TAG_inheritance as for the members and it only
12899          depends on the container kind.  */
12900
12901       if (die->parent->tag == DW_TAG_class_type)
12902         return DW_ACCESS_private;
12903       else
12904         return DW_ACCESS_public;
12905     }
12906 }
12907
12908 /* Look for DW_AT_data_member_location.  Set *OFFSET to the byte
12909    offset.  If the attribute was not found return 0, otherwise return
12910    1.  If it was found but could not properly be handled, set *OFFSET
12911    to 0.  */
12912
12913 static int
12914 handle_data_member_location (struct die_info *die, struct dwarf2_cu *cu,
12915                              LONGEST *offset)
12916 {
12917   struct attribute *attr;
12918
12919   attr = dwarf2_attr (die, DW_AT_data_member_location, cu);
12920   if (attr != NULL)
12921     {
12922       *offset = 0;
12923
12924       /* Note that we do not check for a section offset first here.
12925          This is because DW_AT_data_member_location is new in DWARF 4,
12926          so if we see it, we can assume that a constant form is really
12927          a constant and not a section offset.  */
12928       if (attr_form_is_constant (attr))
12929         *offset = dwarf2_get_attr_constant_value (attr, 0);
12930       else if (attr_form_is_section_offset (attr))
12931         dwarf2_complex_location_expr_complaint ();
12932       else if (attr_form_is_block (attr))
12933         *offset = decode_locdesc (DW_BLOCK (attr), cu);
12934       else
12935         dwarf2_complex_location_expr_complaint ();
12936
12937       return 1;
12938     }
12939
12940   return 0;
12941 }
12942
12943 /* Add an aggregate field to the field list.  */
12944
12945 static void
12946 dwarf2_add_field (struct field_info *fip, struct die_info *die,
12947                   struct dwarf2_cu *cu)
12948 {
12949   struct objfile *objfile = cu->objfile;
12950   struct gdbarch *gdbarch = get_objfile_arch (objfile);
12951   struct nextfield *new_field;
12952   struct attribute *attr;
12953   struct field *fp;
12954   const char *fieldname = "";
12955
12956   /* Allocate a new field list entry and link it in.  */
12957   new_field = XNEW (struct nextfield);
12958   make_cleanup (xfree, new_field);
12959   memset (new_field, 0, sizeof (struct nextfield));
12960
12961   if (die->tag == DW_TAG_inheritance)
12962     {
12963       new_field->next = fip->baseclasses;
12964       fip->baseclasses = new_field;
12965     }
12966   else
12967     {
12968       new_field->next = fip->fields;
12969       fip->fields = new_field;
12970     }
12971   fip->nfields++;
12972
12973   attr = dwarf2_attr (die, DW_AT_accessibility, cu);
12974   if (attr)
12975     new_field->accessibility = DW_UNSND (attr);
12976   else
12977     new_field->accessibility = dwarf2_default_access_attribute (die, cu);
12978   if (new_field->accessibility != DW_ACCESS_public)
12979     fip->non_public_fields = 1;
12980
12981   attr = dwarf2_attr (die, DW_AT_virtuality, cu);
12982   if (attr)
12983     new_field->virtuality = DW_UNSND (attr);
12984   else
12985     new_field->virtuality = DW_VIRTUALITY_none;
12986
12987   fp = &new_field->field;
12988
12989   if (die->tag == DW_TAG_member && ! die_is_declaration (die, cu))
12990     {
12991       LONGEST offset;
12992
12993       /* Data member other than a C++ static data member.  */
12994
12995       /* Get type of field.  */
12996       fp->type = die_type (die, cu);
12997
12998       SET_FIELD_BITPOS (*fp, 0);
12999
13000       /* Get bit size of field (zero if none).  */
13001       attr = dwarf2_attr (die, DW_AT_bit_size, cu);
13002       if (attr)
13003         {
13004           FIELD_BITSIZE (*fp) = DW_UNSND (attr);
13005         }
13006       else
13007         {
13008           FIELD_BITSIZE (*fp) = 0;
13009         }
13010
13011       /* Get bit offset of field.  */
13012       if (handle_data_member_location (die, cu, &offset))
13013         SET_FIELD_BITPOS (*fp, offset * bits_per_byte);
13014       attr = dwarf2_attr (die, DW_AT_bit_offset, cu);
13015       if (attr)
13016         {
13017           if (gdbarch_bits_big_endian (gdbarch))
13018             {
13019               /* For big endian bits, the DW_AT_bit_offset gives the
13020                  additional bit offset from the MSB of the containing
13021                  anonymous object to the MSB of the field.  We don't
13022                  have to do anything special since we don't need to
13023                  know the size of the anonymous object.  */
13024               SET_FIELD_BITPOS (*fp, FIELD_BITPOS (*fp) + DW_UNSND (attr));
13025             }
13026           else
13027             {
13028               /* For little endian bits, compute the bit offset to the
13029                  MSB of the anonymous object, subtract off the number of
13030                  bits from the MSB of the field to the MSB of the
13031                  object, and then subtract off the number of bits of
13032                  the field itself.  The result is the bit offset of
13033                  the LSB of the field.  */
13034               int anonymous_size;
13035               int bit_offset = DW_UNSND (attr);
13036
13037               attr = dwarf2_attr (die, DW_AT_byte_size, cu);
13038               if (attr)
13039                 {
13040                   /* The size of the anonymous object containing
13041                      the bit field is explicit, so use the
13042                      indicated size (in bytes).  */
13043                   anonymous_size = DW_UNSND (attr);
13044                 }
13045               else
13046                 {
13047                   /* The size of the anonymous object containing
13048                      the bit field must be inferred from the type
13049                      attribute of the data member containing the
13050                      bit field.  */
13051                   anonymous_size = TYPE_LENGTH (fp->type);
13052                 }
13053               SET_FIELD_BITPOS (*fp,
13054                                 (FIELD_BITPOS (*fp)
13055                                  + anonymous_size * bits_per_byte
13056                                  - bit_offset - FIELD_BITSIZE (*fp)));
13057             }
13058         }
13059       attr = dwarf2_attr (die, DW_AT_data_bit_offset, cu);
13060       if (attr != NULL)
13061         SET_FIELD_BITPOS (*fp, (FIELD_BITPOS (*fp)
13062                                 + dwarf2_get_attr_constant_value (attr, 0)));
13063
13064       /* Get name of field.  */
13065       fieldname = dwarf2_name (die, cu);
13066       if (fieldname == NULL)
13067         fieldname = "";
13068
13069       /* The name is already allocated along with this objfile, so we don't
13070          need to duplicate it for the type.  */
13071       fp->name = fieldname;
13072
13073       /* Change accessibility for artificial fields (e.g. virtual table
13074          pointer or virtual base class pointer) to private.  */
13075       if (dwarf2_attr (die, DW_AT_artificial, cu))
13076         {
13077           FIELD_ARTIFICIAL (*fp) = 1;
13078           new_field->accessibility = DW_ACCESS_private;
13079           fip->non_public_fields = 1;
13080         }
13081     }
13082   else if (die->tag == DW_TAG_member || die->tag == DW_TAG_variable)
13083     {
13084       /* C++ static member.  */
13085
13086       /* NOTE: carlton/2002-11-05: It should be a DW_TAG_member that
13087          is a declaration, but all versions of G++ as of this writing
13088          (so through at least 3.2.1) incorrectly generate
13089          DW_TAG_variable tags.  */
13090
13091       const char *physname;
13092
13093       /* Get name of field.  */
13094       fieldname = dwarf2_name (die, cu);
13095       if (fieldname == NULL)
13096         return;
13097
13098       attr = dwarf2_attr (die, DW_AT_const_value, cu);
13099       if (attr
13100           /* Only create a symbol if this is an external value.
13101              new_symbol checks this and puts the value in the global symbol
13102              table, which we want.  If it is not external, new_symbol
13103              will try to put the value in cu->list_in_scope which is wrong.  */
13104           && dwarf2_flag_true_p (die, DW_AT_external, cu))
13105         {
13106           /* A static const member, not much different than an enum as far as
13107              we're concerned, except that we can support more types.  */
13108           new_symbol (die, NULL, cu);
13109         }
13110
13111       /* Get physical name.  */
13112       physname = dwarf2_physname (fieldname, die, cu);
13113
13114       /* The name is already allocated along with this objfile, so we don't
13115          need to duplicate it for the type.  */
13116       SET_FIELD_PHYSNAME (*fp, physname ? physname : "");
13117       FIELD_TYPE (*fp) = die_type (die, cu);
13118       FIELD_NAME (*fp) = fieldname;
13119     }
13120   else if (die->tag == DW_TAG_inheritance)
13121     {
13122       LONGEST offset;
13123
13124       /* C++ base class field.  */
13125       if (handle_data_member_location (die, cu, &offset))
13126         SET_FIELD_BITPOS (*fp, offset * bits_per_byte);
13127       FIELD_BITSIZE (*fp) = 0;
13128       FIELD_TYPE (*fp) = die_type (die, cu);
13129       FIELD_NAME (*fp) = type_name_no_tag (fp->type);
13130       fip->nbaseclasses++;
13131     }
13132 }
13133
13134 /* Add a typedef defined in the scope of the FIP's class.  */
13135
13136 static void
13137 dwarf2_add_typedef (struct field_info *fip, struct die_info *die,
13138                     struct dwarf2_cu *cu)
13139 {
13140   struct typedef_field_list *new_field;
13141   struct typedef_field *fp;
13142
13143   /* Allocate a new field list entry and link it in.  */
13144   new_field = XCNEW (struct typedef_field_list);
13145   make_cleanup (xfree, new_field);
13146
13147   gdb_assert (die->tag == DW_TAG_typedef);
13148
13149   fp = &new_field->field;
13150
13151   /* Get name of field.  */
13152   fp->name = dwarf2_name (die, cu);
13153   if (fp->name == NULL)
13154     return;
13155
13156   fp->type = read_type_die (die, cu);
13157
13158   new_field->next = fip->typedef_field_list;
13159   fip->typedef_field_list = new_field;
13160   fip->typedef_field_list_count++;
13161 }
13162
13163 /* Create the vector of fields, and attach it to the type.  */
13164
13165 static void
13166 dwarf2_attach_fields_to_type (struct field_info *fip, struct type *type,
13167                               struct dwarf2_cu *cu)
13168 {
13169   int nfields = fip->nfields;
13170
13171   /* Record the field count, allocate space for the array of fields,
13172      and create blank accessibility bitfields if necessary.  */
13173   TYPE_NFIELDS (type) = nfields;
13174   TYPE_FIELDS (type) = (struct field *)
13175     TYPE_ALLOC (type, sizeof (struct field) * nfields);
13176   memset (TYPE_FIELDS (type), 0, sizeof (struct field) * nfields);
13177
13178   if (fip->non_public_fields && cu->language != language_ada)
13179     {
13180       ALLOCATE_CPLUS_STRUCT_TYPE (type);
13181
13182       TYPE_FIELD_PRIVATE_BITS (type) =
13183         (B_TYPE *) TYPE_ALLOC (type, B_BYTES (nfields));
13184       B_CLRALL (TYPE_FIELD_PRIVATE_BITS (type), nfields);
13185
13186       TYPE_FIELD_PROTECTED_BITS (type) =
13187         (B_TYPE *) TYPE_ALLOC (type, B_BYTES (nfields));
13188       B_CLRALL (TYPE_FIELD_PROTECTED_BITS (type), nfields);
13189
13190       TYPE_FIELD_IGNORE_BITS (type) =
13191         (B_TYPE *) TYPE_ALLOC (type, B_BYTES (nfields));
13192       B_CLRALL (TYPE_FIELD_IGNORE_BITS (type), nfields);
13193     }
13194
13195   /* If the type has baseclasses, allocate and clear a bit vector for
13196      TYPE_FIELD_VIRTUAL_BITS.  */
13197   if (fip->nbaseclasses && cu->language != language_ada)
13198     {
13199       int num_bytes = B_BYTES (fip->nbaseclasses);
13200       unsigned char *pointer;
13201
13202       ALLOCATE_CPLUS_STRUCT_TYPE (type);
13203       pointer = (unsigned char *) TYPE_ALLOC (type, num_bytes);
13204       TYPE_FIELD_VIRTUAL_BITS (type) = pointer;
13205       B_CLRALL (TYPE_FIELD_VIRTUAL_BITS (type), fip->nbaseclasses);
13206       TYPE_N_BASECLASSES (type) = fip->nbaseclasses;
13207     }
13208
13209   /* Copy the saved-up fields into the field vector.  Start from the head of
13210      the list, adding to the tail of the field array, so that they end up in
13211      the same order in the array in which they were added to the list.  */
13212   while (nfields-- > 0)
13213     {
13214       struct nextfield *fieldp;
13215
13216       if (fip->fields)
13217         {
13218           fieldp = fip->fields;
13219           fip->fields = fieldp->next;
13220         }
13221       else
13222         {
13223           fieldp = fip->baseclasses;
13224           fip->baseclasses = fieldp->next;
13225         }
13226
13227       TYPE_FIELD (type, nfields) = fieldp->field;
13228       switch (fieldp->accessibility)
13229         {
13230         case DW_ACCESS_private:
13231           if (cu->language != language_ada)
13232             SET_TYPE_FIELD_PRIVATE (type, nfields);
13233           break;
13234
13235         case DW_ACCESS_protected:
13236           if (cu->language != language_ada)
13237             SET_TYPE_FIELD_PROTECTED (type, nfields);
13238           break;
13239
13240         case DW_ACCESS_public:
13241           break;
13242
13243         default:
13244           /* Unknown accessibility.  Complain and treat it as public.  */
13245           {
13246             complaint (&symfile_complaints, _("unsupported accessibility %d"),
13247                        fieldp->accessibility);
13248           }
13249           break;
13250         }
13251       if (nfields < fip->nbaseclasses)
13252         {
13253           switch (fieldp->virtuality)
13254             {
13255             case DW_VIRTUALITY_virtual:
13256             case DW_VIRTUALITY_pure_virtual:
13257               if (cu->language == language_ada)
13258                 error (_("unexpected virtuality in component of Ada type"));
13259               SET_TYPE_FIELD_VIRTUAL (type, nfields);
13260               break;
13261             }
13262         }
13263     }
13264 }
13265
13266 /* Return true if this member function is a constructor, false
13267    otherwise.  */
13268
13269 static int
13270 dwarf2_is_constructor (struct die_info *die, struct dwarf2_cu *cu)
13271 {
13272   const char *fieldname;
13273   const char *type_name;
13274   int len;
13275
13276   if (die->parent == NULL)
13277     return 0;
13278
13279   if (die->parent->tag != DW_TAG_structure_type
13280       && die->parent->tag != DW_TAG_union_type
13281       && die->parent->tag != DW_TAG_class_type)
13282     return 0;
13283
13284   fieldname = dwarf2_name (die, cu);
13285   type_name = dwarf2_name (die->parent, cu);
13286   if (fieldname == NULL || type_name == NULL)
13287     return 0;
13288
13289   len = strlen (fieldname);
13290   return (strncmp (fieldname, type_name, len) == 0
13291           && (type_name[len] == '\0' || type_name[len] == '<'));
13292 }
13293
13294 /* Add a member function to the proper fieldlist.  */
13295
13296 static void
13297 dwarf2_add_member_fn (struct field_info *fip, struct die_info *die,
13298                       struct type *type, struct dwarf2_cu *cu)
13299 {
13300   struct objfile *objfile = cu->objfile;
13301   struct attribute *attr;
13302   struct fnfieldlist *flp;
13303   int i;
13304   struct fn_field *fnp;
13305   const char *fieldname;
13306   struct nextfnfield *new_fnfield;
13307   struct type *this_type;
13308   enum dwarf_access_attribute accessibility;
13309
13310   if (cu->language == language_ada)
13311     error (_("unexpected member function in Ada type"));
13312
13313   /* Get name of member function.  */
13314   fieldname = dwarf2_name (die, cu);
13315   if (fieldname == NULL)
13316     return;
13317
13318   /* Look up member function name in fieldlist.  */
13319   for (i = 0; i < fip->nfnfields; i++)
13320     {
13321       if (strcmp (fip->fnfieldlists[i].name, fieldname) == 0)
13322         break;
13323     }
13324
13325   /* Create new list element if necessary.  */
13326   if (i < fip->nfnfields)
13327     flp = &fip->fnfieldlists[i];
13328   else
13329     {
13330       if ((fip->nfnfields % DW_FIELD_ALLOC_CHUNK) == 0)
13331         {
13332           fip->fnfieldlists = (struct fnfieldlist *)
13333             xrealloc (fip->fnfieldlists,
13334                       (fip->nfnfields + DW_FIELD_ALLOC_CHUNK)
13335                       * sizeof (struct fnfieldlist));
13336           if (fip->nfnfields == 0)
13337             make_cleanup (free_current_contents, &fip->fnfieldlists);
13338         }
13339       flp = &fip->fnfieldlists[fip->nfnfields];
13340       flp->name = fieldname;
13341       flp->length = 0;
13342       flp->head = NULL;
13343       i = fip->nfnfields++;
13344     }
13345
13346   /* Create a new member function field and chain it to the field list
13347      entry.  */
13348   new_fnfield = XNEW (struct nextfnfield);
13349   make_cleanup (xfree, new_fnfield);
13350   memset (new_fnfield, 0, sizeof (struct nextfnfield));
13351   new_fnfield->next = flp->head;
13352   flp->head = new_fnfield;
13353   flp->length++;
13354
13355   /* Fill in the member function field info.  */
13356   fnp = &new_fnfield->fnfield;
13357
13358   /* Delay processing of the physname until later.  */
13359   if (cu->language == language_cplus)
13360     {
13361       add_to_method_list (type, i, flp->length - 1, fieldname,
13362                           die, cu);
13363     }
13364   else
13365     {
13366       const char *physname = dwarf2_physname (fieldname, die, cu);
13367       fnp->physname = physname ? physname : "";
13368     }
13369
13370   fnp->type = alloc_type (objfile);
13371   this_type = read_type_die (die, cu);
13372   if (this_type && TYPE_CODE (this_type) == TYPE_CODE_FUNC)
13373     {
13374       int nparams = TYPE_NFIELDS (this_type);
13375
13376       /* TYPE is the domain of this method, and THIS_TYPE is the type
13377            of the method itself (TYPE_CODE_METHOD).  */
13378       smash_to_method_type (fnp->type, type,
13379                             TYPE_TARGET_TYPE (this_type),
13380                             TYPE_FIELDS (this_type),
13381                             TYPE_NFIELDS (this_type),
13382                             TYPE_VARARGS (this_type));
13383
13384       /* Handle static member functions.
13385          Dwarf2 has no clean way to discern C++ static and non-static
13386          member functions.  G++ helps GDB by marking the first
13387          parameter for non-static member functions (which is the this
13388          pointer) as artificial.  We obtain this information from
13389          read_subroutine_type via TYPE_FIELD_ARTIFICIAL.  */
13390       if (nparams == 0 || TYPE_FIELD_ARTIFICIAL (this_type, 0) == 0)
13391         fnp->voffset = VOFFSET_STATIC;
13392     }
13393   else
13394     complaint (&symfile_complaints, _("member function type missing for '%s'"),
13395                dwarf2_full_name (fieldname, die, cu));
13396
13397   /* Get fcontext from DW_AT_containing_type if present.  */
13398   if (dwarf2_attr (die, DW_AT_containing_type, cu) != NULL)
13399     fnp->fcontext = die_containing_type (die, cu);
13400
13401   /* dwarf2 doesn't have stubbed physical names, so the setting of is_const and
13402      is_volatile is irrelevant, as it is needed by gdb_mangle_name only.  */
13403
13404   /* Get accessibility.  */
13405   attr = dwarf2_attr (die, DW_AT_accessibility, cu);
13406   if (attr)
13407     accessibility = (enum dwarf_access_attribute) DW_UNSND (attr);
13408   else
13409     accessibility = dwarf2_default_access_attribute (die, cu);
13410   switch (accessibility)
13411     {
13412     case DW_ACCESS_private:
13413       fnp->is_private = 1;
13414       break;
13415     case DW_ACCESS_protected:
13416       fnp->is_protected = 1;
13417       break;
13418     }
13419
13420   /* Check for artificial methods.  */
13421   attr = dwarf2_attr (die, DW_AT_artificial, cu);
13422   if (attr && DW_UNSND (attr) != 0)
13423     fnp->is_artificial = 1;
13424
13425   fnp->is_constructor = dwarf2_is_constructor (die, cu);
13426
13427   /* Get index in virtual function table if it is a virtual member
13428      function.  For older versions of GCC, this is an offset in the
13429      appropriate virtual table, as specified by DW_AT_containing_type.
13430      For everyone else, it is an expression to be evaluated relative
13431      to the object address.  */
13432
13433   attr = dwarf2_attr (die, DW_AT_vtable_elem_location, cu);
13434   if (attr)
13435     {
13436       if (attr_form_is_block (attr) && DW_BLOCK (attr)->size > 0)
13437         {
13438           if (DW_BLOCK (attr)->data[0] == DW_OP_constu)
13439             {
13440               /* Old-style GCC.  */
13441               fnp->voffset = decode_locdesc (DW_BLOCK (attr), cu) + 2;
13442             }
13443           else if (DW_BLOCK (attr)->data[0] == DW_OP_deref
13444                    || (DW_BLOCK (attr)->size > 1
13445                        && DW_BLOCK (attr)->data[0] == DW_OP_deref_size
13446                        && DW_BLOCK (attr)->data[1] == cu->header.addr_size))
13447             {
13448               fnp->voffset = decode_locdesc (DW_BLOCK (attr), cu);
13449               if ((fnp->voffset % cu->header.addr_size) != 0)
13450                 dwarf2_complex_location_expr_complaint ();
13451               else
13452                 fnp->voffset /= cu->header.addr_size;
13453               fnp->voffset += 2;
13454             }
13455           else
13456             dwarf2_complex_location_expr_complaint ();
13457
13458           if (!fnp->fcontext)
13459             {
13460               /* If there is no `this' field and no DW_AT_containing_type,
13461                  we cannot actually find a base class context for the
13462                  vtable!  */
13463               if (TYPE_NFIELDS (this_type) == 0
13464                   || !TYPE_FIELD_ARTIFICIAL (this_type, 0))
13465                 {
13466                   complaint (&symfile_complaints,
13467                              _("cannot determine context for virtual member "
13468                                "function \"%s\" (offset %d)"),
13469                              fieldname, to_underlying (die->sect_off));
13470                 }
13471               else
13472                 {
13473                   fnp->fcontext
13474                     = TYPE_TARGET_TYPE (TYPE_FIELD_TYPE (this_type, 0));
13475                 }
13476             }
13477         }
13478       else if (attr_form_is_section_offset (attr))
13479         {
13480           dwarf2_complex_location_expr_complaint ();
13481         }
13482       else
13483         {
13484           dwarf2_invalid_attrib_class_complaint ("DW_AT_vtable_elem_location",
13485                                                  fieldname);
13486         }
13487     }
13488   else
13489     {
13490       attr = dwarf2_attr (die, DW_AT_virtuality, cu);
13491       if (attr && DW_UNSND (attr))
13492         {
13493           /* GCC does this, as of 2008-08-25; PR debug/37237.  */
13494           complaint (&symfile_complaints,
13495                      _("Member function \"%s\" (offset %d) is virtual "
13496                        "but the vtable offset is not specified"),
13497                      fieldname, to_underlying (die->sect_off));
13498           ALLOCATE_CPLUS_STRUCT_TYPE (type);
13499           TYPE_CPLUS_DYNAMIC (type) = 1;
13500         }
13501     }
13502 }
13503
13504 /* Create the vector of member function fields, and attach it to the type.  */
13505
13506 static void
13507 dwarf2_attach_fn_fields_to_type (struct field_info *fip, struct type *type,
13508                                  struct dwarf2_cu *cu)
13509 {
13510   struct fnfieldlist *flp;
13511   int i;
13512
13513   if (cu->language == language_ada)
13514     error (_("unexpected member functions in Ada type"));
13515
13516   ALLOCATE_CPLUS_STRUCT_TYPE (type);
13517   TYPE_FN_FIELDLISTS (type) = (struct fn_fieldlist *)
13518     TYPE_ALLOC (type, sizeof (struct fn_fieldlist) * fip->nfnfields);
13519
13520   for (i = 0, flp = fip->fnfieldlists; i < fip->nfnfields; i++, flp++)
13521     {
13522       struct nextfnfield *nfp = flp->head;
13523       struct fn_fieldlist *fn_flp = &TYPE_FN_FIELDLIST (type, i);
13524       int k;
13525
13526       TYPE_FN_FIELDLIST_NAME (type, i) = flp->name;
13527       TYPE_FN_FIELDLIST_LENGTH (type, i) = flp->length;
13528       fn_flp->fn_fields = (struct fn_field *)
13529         TYPE_ALLOC (type, sizeof (struct fn_field) * flp->length);
13530       for (k = flp->length; (k--, nfp); nfp = nfp->next)
13531         fn_flp->fn_fields[k] = nfp->fnfield;
13532     }
13533
13534   TYPE_NFN_FIELDS (type) = fip->nfnfields;
13535 }
13536
13537 /* Returns non-zero if NAME is the name of a vtable member in CU's
13538    language, zero otherwise.  */
13539 static int
13540 is_vtable_name (const char *name, struct dwarf2_cu *cu)
13541 {
13542   static const char vptr[] = "_vptr";
13543   static const char vtable[] = "vtable";
13544
13545   /* Look for the C++ form of the vtable.  */
13546   if (startswith (name, vptr) && is_cplus_marker (name[sizeof (vptr) - 1]))
13547     return 1;
13548
13549   return 0;
13550 }
13551
13552 /* GCC outputs unnamed structures that are really pointers to member
13553    functions, with the ABI-specified layout.  If TYPE describes
13554    such a structure, smash it into a member function type.
13555
13556    GCC shouldn't do this; it should just output pointer to member DIEs.
13557    This is GCC PR debug/28767.  */
13558
13559 static void
13560 quirk_gcc_member_function_pointer (struct type *type, struct objfile *objfile)
13561 {
13562   struct type *pfn_type, *self_type, *new_type;
13563
13564   /* Check for a structure with no name and two children.  */
13565   if (TYPE_CODE (type) != TYPE_CODE_STRUCT || TYPE_NFIELDS (type) != 2)
13566     return;
13567
13568   /* Check for __pfn and __delta members.  */
13569   if (TYPE_FIELD_NAME (type, 0) == NULL
13570       || strcmp (TYPE_FIELD_NAME (type, 0), "__pfn") != 0
13571       || TYPE_FIELD_NAME (type, 1) == NULL
13572       || strcmp (TYPE_FIELD_NAME (type, 1), "__delta") != 0)
13573     return;
13574
13575   /* Find the type of the method.  */
13576   pfn_type = TYPE_FIELD_TYPE (type, 0);
13577   if (pfn_type == NULL
13578       || TYPE_CODE (pfn_type) != TYPE_CODE_PTR
13579       || TYPE_CODE (TYPE_TARGET_TYPE (pfn_type)) != TYPE_CODE_FUNC)
13580     return;
13581
13582   /* Look for the "this" argument.  */
13583   pfn_type = TYPE_TARGET_TYPE (pfn_type);
13584   if (TYPE_NFIELDS (pfn_type) == 0
13585       /* || TYPE_FIELD_TYPE (pfn_type, 0) == NULL */
13586       || TYPE_CODE (TYPE_FIELD_TYPE (pfn_type, 0)) != TYPE_CODE_PTR)
13587     return;
13588
13589   self_type = TYPE_TARGET_TYPE (TYPE_FIELD_TYPE (pfn_type, 0));
13590   new_type = alloc_type (objfile);
13591   smash_to_method_type (new_type, self_type, TYPE_TARGET_TYPE (pfn_type),
13592                         TYPE_FIELDS (pfn_type), TYPE_NFIELDS (pfn_type),
13593                         TYPE_VARARGS (pfn_type));
13594   smash_to_methodptr_type (type, new_type);
13595 }
13596
13597 /* Return non-zero if the CU's PRODUCER string matches the Intel C/C++ compiler
13598    (icc).  */
13599
13600 static int
13601 producer_is_icc (struct dwarf2_cu *cu)
13602 {
13603   if (!cu->checked_producer)
13604     check_producer (cu);
13605
13606   return cu->producer_is_icc;
13607 }
13608
13609 /* Called when we find the DIE that starts a structure or union scope
13610    (definition) to create a type for the structure or union.  Fill in
13611    the type's name and general properties; the members will not be
13612    processed until process_structure_scope.  A symbol table entry for
13613    the type will also not be done until process_structure_scope (assuming
13614    the type has a name).
13615
13616    NOTE: we need to call these functions regardless of whether or not the
13617    DIE has a DW_AT_name attribute, since it might be an anonymous
13618    structure or union.  This gets the type entered into our set of
13619    user defined types.  */
13620
13621 static struct type *
13622 read_structure_type (struct die_info *die, struct dwarf2_cu *cu)
13623 {
13624   struct objfile *objfile = cu->objfile;
13625   struct type *type;
13626   struct attribute *attr;
13627   const char *name;
13628
13629   /* If the definition of this type lives in .debug_types, read that type.
13630      Don't follow DW_AT_specification though, that will take us back up
13631      the chain and we want to go down.  */
13632   attr = dwarf2_attr_no_follow (die, DW_AT_signature);
13633   if (attr)
13634     {
13635       type = get_DW_AT_signature_type (die, attr, cu);
13636
13637       /* The type's CU may not be the same as CU.
13638          Ensure TYPE is recorded with CU in die_type_hash.  */
13639       return set_die_type (die, type, cu);
13640     }
13641
13642   type = alloc_type (objfile);
13643   INIT_CPLUS_SPECIFIC (type);
13644
13645   name = dwarf2_name (die, cu);
13646   if (name != NULL)
13647     {
13648       if (cu->language == language_cplus
13649           || cu->language == language_d
13650           || cu->language == language_rust)
13651         {
13652           const char *full_name = dwarf2_full_name (name, die, cu);
13653
13654           /* dwarf2_full_name might have already finished building the DIE's
13655              type.  If so, there is no need to continue.  */
13656           if (get_die_type (die, cu) != NULL)
13657             return get_die_type (die, cu);
13658
13659           TYPE_TAG_NAME (type) = full_name;
13660           if (die->tag == DW_TAG_structure_type
13661               || die->tag == DW_TAG_class_type)
13662             TYPE_NAME (type) = TYPE_TAG_NAME (type);
13663         }
13664       else
13665         {
13666           /* The name is already allocated along with this objfile, so
13667              we don't need to duplicate it for the type.  */
13668           TYPE_TAG_NAME (type) = name;
13669           if (die->tag == DW_TAG_class_type)
13670             TYPE_NAME (type) = TYPE_TAG_NAME (type);
13671         }
13672     }
13673
13674   if (die->tag == DW_TAG_structure_type)
13675     {
13676       TYPE_CODE (type) = TYPE_CODE_STRUCT;
13677     }
13678   else if (die->tag == DW_TAG_union_type)
13679     {
13680       TYPE_CODE (type) = TYPE_CODE_UNION;
13681     }
13682   else
13683     {
13684       TYPE_CODE (type) = TYPE_CODE_STRUCT;
13685     }
13686
13687   if (cu->language == language_cplus && die->tag == DW_TAG_class_type)
13688     TYPE_DECLARED_CLASS (type) = 1;
13689
13690   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
13691   if (attr)
13692     {
13693       if (attr_form_is_constant (attr))
13694         TYPE_LENGTH (type) = DW_UNSND (attr);
13695       else
13696         {
13697           /* For the moment, dynamic type sizes are not supported
13698              by GDB's struct type.  The actual size is determined
13699              on-demand when resolving the type of a given object,
13700              so set the type's length to zero for now.  Otherwise,
13701              we record an expression as the length, and that expression
13702              could lead to a very large value, which could eventually
13703              lead to us trying to allocate that much memory when creating
13704              a value of that type.  */
13705           TYPE_LENGTH (type) = 0;
13706         }
13707     }
13708   else
13709     {
13710       TYPE_LENGTH (type) = 0;
13711     }
13712
13713   if (producer_is_icc (cu) && (TYPE_LENGTH (type) == 0))
13714     {
13715       /* ICC does not output the required DW_AT_declaration
13716          on incomplete types, but gives them a size of zero.  */
13717       TYPE_STUB (type) = 1;
13718     }
13719   else
13720     TYPE_STUB_SUPPORTED (type) = 1;
13721
13722   if (die_is_declaration (die, cu))
13723     TYPE_STUB (type) = 1;
13724   else if (attr == NULL && die->child == NULL
13725            && producer_is_realview (cu->producer))
13726     /* RealView does not output the required DW_AT_declaration
13727        on incomplete types.  */
13728     TYPE_STUB (type) = 1;
13729
13730   /* We need to add the type field to the die immediately so we don't
13731      infinitely recurse when dealing with pointers to the structure
13732      type within the structure itself.  */
13733   set_die_type (die, type, cu);
13734
13735   /* set_die_type should be already done.  */
13736   set_descriptive_type (type, die, cu);
13737
13738   return type;
13739 }
13740
13741 /* Finish creating a structure or union type, including filling in
13742    its members and creating a symbol for it.  */
13743
13744 static void
13745 process_structure_scope (struct die_info *die, struct dwarf2_cu *cu)
13746 {
13747   struct objfile *objfile = cu->objfile;
13748   struct die_info *child_die;
13749   struct type *type;
13750
13751   type = get_die_type (die, cu);
13752   if (type == NULL)
13753     type = read_structure_type (die, cu);
13754
13755   if (die->child != NULL && ! die_is_declaration (die, cu))
13756     {
13757       struct field_info fi;
13758       VEC (symbolp) *template_args = NULL;
13759       struct cleanup *back_to = make_cleanup (null_cleanup, 0);
13760
13761       memset (&fi, 0, sizeof (struct field_info));
13762
13763       child_die = die->child;
13764
13765       while (child_die && child_die->tag)
13766         {
13767           if (child_die->tag == DW_TAG_member
13768               || child_die->tag == DW_TAG_variable)
13769             {
13770               /* NOTE: carlton/2002-11-05: A C++ static data member
13771                  should be a DW_TAG_member that is a declaration, but
13772                  all versions of G++ as of this writing (so through at
13773                  least 3.2.1) incorrectly generate DW_TAG_variable
13774                  tags for them instead.  */
13775               dwarf2_add_field (&fi, child_die, cu);
13776             }
13777           else if (child_die->tag == DW_TAG_subprogram)
13778             {
13779               /* Rust doesn't have member functions in the C++ sense.
13780                  However, it does emit ordinary functions as children
13781                  of a struct DIE.  */
13782               if (cu->language == language_rust)
13783                 read_func_scope (child_die, cu);
13784               else
13785                 {
13786                   /* C++ member function.  */
13787                   dwarf2_add_member_fn (&fi, child_die, type, cu);
13788                 }
13789             }
13790           else if (child_die->tag == DW_TAG_inheritance)
13791             {
13792               /* C++ base class field.  */
13793               dwarf2_add_field (&fi, child_die, cu);
13794             }
13795           else if (child_die->tag == DW_TAG_typedef)
13796             dwarf2_add_typedef (&fi, child_die, cu);
13797           else if (child_die->tag == DW_TAG_template_type_param
13798                    || child_die->tag == DW_TAG_template_value_param)
13799             {
13800               struct symbol *arg = new_symbol (child_die, NULL, cu);
13801
13802               if (arg != NULL)
13803                 VEC_safe_push (symbolp, template_args, arg);
13804             }
13805
13806           child_die = sibling_die (child_die);
13807         }
13808
13809       /* Attach template arguments to type.  */
13810       if (! VEC_empty (symbolp, template_args))
13811         {
13812           ALLOCATE_CPLUS_STRUCT_TYPE (type);
13813           TYPE_N_TEMPLATE_ARGUMENTS (type)
13814             = VEC_length (symbolp, template_args);
13815           TYPE_TEMPLATE_ARGUMENTS (type)
13816             = XOBNEWVEC (&objfile->objfile_obstack,
13817                          struct symbol *,
13818                          TYPE_N_TEMPLATE_ARGUMENTS (type));
13819           memcpy (TYPE_TEMPLATE_ARGUMENTS (type),
13820                   VEC_address (symbolp, template_args),
13821                   (TYPE_N_TEMPLATE_ARGUMENTS (type)
13822                    * sizeof (struct symbol *)));
13823           VEC_free (symbolp, template_args);
13824         }
13825
13826       /* Attach fields and member functions to the type.  */
13827       if (fi.nfields)
13828         dwarf2_attach_fields_to_type (&fi, type, cu);
13829       if (fi.nfnfields)
13830         {
13831           dwarf2_attach_fn_fields_to_type (&fi, type, cu);
13832
13833           /* Get the type which refers to the base class (possibly this
13834              class itself) which contains the vtable pointer for the current
13835              class from the DW_AT_containing_type attribute.  This use of
13836              DW_AT_containing_type is a GNU extension.  */
13837
13838           if (dwarf2_attr (die, DW_AT_containing_type, cu) != NULL)
13839             {
13840               struct type *t = die_containing_type (die, cu);
13841
13842               set_type_vptr_basetype (type, t);
13843               if (type == t)
13844                 {
13845                   int i;
13846
13847                   /* Our own class provides vtbl ptr.  */
13848                   for (i = TYPE_NFIELDS (t) - 1;
13849                        i >= TYPE_N_BASECLASSES (t);
13850                        --i)
13851                     {
13852                       const char *fieldname = TYPE_FIELD_NAME (t, i);
13853
13854                       if (is_vtable_name (fieldname, cu))
13855                         {
13856                           set_type_vptr_fieldno (type, i);
13857                           break;
13858                         }
13859                     }
13860
13861                   /* Complain if virtual function table field not found.  */
13862                   if (i < TYPE_N_BASECLASSES (t))
13863                     complaint (&symfile_complaints,
13864                                _("virtual function table pointer "
13865                                  "not found when defining class '%s'"),
13866                                TYPE_TAG_NAME (type) ? TYPE_TAG_NAME (type) :
13867                                "");
13868                 }
13869               else
13870                 {
13871                   set_type_vptr_fieldno (type, TYPE_VPTR_FIELDNO (t));
13872                 }
13873             }
13874           else if (cu->producer
13875                    && startswith (cu->producer, "IBM(R) XL C/C++ Advanced Edition"))
13876             {
13877               /* The IBM XLC compiler does not provide direct indication
13878                  of the containing type, but the vtable pointer is
13879                  always named __vfp.  */
13880
13881               int i;
13882
13883               for (i = TYPE_NFIELDS (type) - 1;
13884                    i >= TYPE_N_BASECLASSES (type);
13885                    --i)
13886                 {
13887                   if (strcmp (TYPE_FIELD_NAME (type, i), "__vfp") == 0)
13888                     {
13889                       set_type_vptr_fieldno (type, i);
13890                       set_type_vptr_basetype (type, type);
13891                       break;
13892                     }
13893                 }
13894             }
13895         }
13896
13897       /* Copy fi.typedef_field_list linked list elements content into the
13898          allocated array TYPE_TYPEDEF_FIELD_ARRAY (type).  */
13899       if (fi.typedef_field_list)
13900         {
13901           int i = fi.typedef_field_list_count;
13902
13903           ALLOCATE_CPLUS_STRUCT_TYPE (type);
13904           TYPE_TYPEDEF_FIELD_ARRAY (type)
13905             = ((struct typedef_field *)
13906                TYPE_ALLOC (type, sizeof (TYPE_TYPEDEF_FIELD (type, 0)) * i));
13907           TYPE_TYPEDEF_FIELD_COUNT (type) = i;
13908
13909           /* Reverse the list order to keep the debug info elements order.  */
13910           while (--i >= 0)
13911             {
13912               struct typedef_field *dest, *src;
13913
13914               dest = &TYPE_TYPEDEF_FIELD (type, i);
13915               src = &fi.typedef_field_list->field;
13916               fi.typedef_field_list = fi.typedef_field_list->next;
13917               *dest = *src;
13918             }
13919         }
13920
13921       do_cleanups (back_to);
13922     }
13923
13924   quirk_gcc_member_function_pointer (type, objfile);
13925
13926   /* NOTE: carlton/2004-03-16: GCC 3.4 (or at least one of its
13927      snapshots) has been known to create a die giving a declaration
13928      for a class that has, as a child, a die giving a definition for a
13929      nested class.  So we have to process our children even if the
13930      current die is a declaration.  Normally, of course, a declaration
13931      won't have any children at all.  */
13932
13933   child_die = die->child;
13934
13935   while (child_die != NULL && child_die->tag)
13936     {
13937       if (child_die->tag == DW_TAG_member
13938           || child_die->tag == DW_TAG_variable
13939           || child_die->tag == DW_TAG_inheritance
13940           || child_die->tag == DW_TAG_template_value_param
13941           || child_die->tag == DW_TAG_template_type_param)
13942         {
13943           /* Do nothing.  */
13944         }
13945       else
13946         process_die (child_die, cu);
13947
13948       child_die = sibling_die (child_die);
13949     }
13950
13951   /* Do not consider external references.  According to the DWARF standard,
13952      these DIEs are identified by the fact that they have no byte_size
13953      attribute, and a declaration attribute.  */
13954   if (dwarf2_attr (die, DW_AT_byte_size, cu) != NULL
13955       || !die_is_declaration (die, cu))
13956     new_symbol (die, type, cu);
13957 }
13958
13959 /* Assuming DIE is an enumeration type, and TYPE is its associated type,
13960    update TYPE using some information only available in DIE's children.  */
13961
13962 static void
13963 update_enumeration_type_from_children (struct die_info *die,
13964                                        struct type *type,
13965                                        struct dwarf2_cu *cu)
13966 {
13967   struct die_info *child_die;
13968   int unsigned_enum = 1;
13969   int flag_enum = 1;
13970   ULONGEST mask = 0;
13971
13972   auto_obstack obstack;
13973
13974   for (child_die = die->child;
13975        child_die != NULL && child_die->tag;
13976        child_die = sibling_die (child_die))
13977     {
13978       struct attribute *attr;
13979       LONGEST value;
13980       const gdb_byte *bytes;
13981       struct dwarf2_locexpr_baton *baton;
13982       const char *name;
13983
13984       if (child_die->tag != DW_TAG_enumerator)
13985         continue;
13986
13987       attr = dwarf2_attr (child_die, DW_AT_const_value, cu);
13988       if (attr == NULL)
13989         continue;
13990
13991       name = dwarf2_name (child_die, cu);
13992       if (name == NULL)
13993         name = "<anonymous enumerator>";
13994
13995       dwarf2_const_value_attr (attr, type, name, &obstack, cu,
13996                                &value, &bytes, &baton);
13997       if (value < 0)
13998         {
13999           unsigned_enum = 0;
14000           flag_enum = 0;
14001         }
14002       else if ((mask & value) != 0)
14003         flag_enum = 0;
14004       else
14005         mask |= value;
14006
14007       /* If we already know that the enum type is neither unsigned, nor
14008          a flag type, no need to look at the rest of the enumerates.  */
14009       if (!unsigned_enum && !flag_enum)
14010         break;
14011     }
14012
14013   if (unsigned_enum)
14014     TYPE_UNSIGNED (type) = 1;
14015   if (flag_enum)
14016     TYPE_FLAG_ENUM (type) = 1;
14017 }
14018
14019 /* Given a DW_AT_enumeration_type die, set its type.  We do not
14020    complete the type's fields yet, or create any symbols.  */
14021
14022 static struct type *
14023 read_enumeration_type (struct die_info *die, struct dwarf2_cu *cu)
14024 {
14025   struct objfile *objfile = cu->objfile;
14026   struct type *type;
14027   struct attribute *attr;
14028   const char *name;
14029
14030   /* If the definition of this type lives in .debug_types, read that type.
14031      Don't follow DW_AT_specification though, that will take us back up
14032      the chain and we want to go down.  */
14033   attr = dwarf2_attr_no_follow (die, DW_AT_signature);
14034   if (attr)
14035     {
14036       type = get_DW_AT_signature_type (die, attr, cu);
14037
14038       /* The type's CU may not be the same as CU.
14039          Ensure TYPE is recorded with CU in die_type_hash.  */
14040       return set_die_type (die, type, cu);
14041     }
14042
14043   type = alloc_type (objfile);
14044
14045   TYPE_CODE (type) = TYPE_CODE_ENUM;
14046   name = dwarf2_full_name (NULL, die, cu);
14047   if (name != NULL)
14048     TYPE_TAG_NAME (type) = name;
14049
14050   attr = dwarf2_attr (die, DW_AT_type, cu);
14051   if (attr != NULL)
14052     {
14053       struct type *underlying_type = die_type (die, cu);
14054
14055       TYPE_TARGET_TYPE (type) = underlying_type;
14056     }
14057
14058   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
14059   if (attr)
14060     {
14061       TYPE_LENGTH (type) = DW_UNSND (attr);
14062     }
14063   else
14064     {
14065       TYPE_LENGTH (type) = 0;
14066     }
14067
14068   /* The enumeration DIE can be incomplete.  In Ada, any type can be
14069      declared as private in the package spec, and then defined only
14070      inside the package body.  Such types are known as Taft Amendment
14071      Types.  When another package uses such a type, an incomplete DIE
14072      may be generated by the compiler.  */
14073   if (die_is_declaration (die, cu))
14074     TYPE_STUB (type) = 1;
14075
14076   /* Finish the creation of this type by using the enum's children.
14077      We must call this even when the underlying type has been provided
14078      so that we can determine if we're looking at a "flag" enum.  */
14079   update_enumeration_type_from_children (die, type, cu);
14080
14081   /* If this type has an underlying type that is not a stub, then we
14082      may use its attributes.  We always use the "unsigned" attribute
14083      in this situation, because ordinarily we guess whether the type
14084      is unsigned -- but the guess can be wrong and the underlying type
14085      can tell us the reality.  However, we defer to a local size
14086      attribute if one exists, because this lets the compiler override
14087      the underlying type if needed.  */
14088   if (TYPE_TARGET_TYPE (type) != NULL && !TYPE_STUB (TYPE_TARGET_TYPE (type)))
14089     {
14090       TYPE_UNSIGNED (type) = TYPE_UNSIGNED (TYPE_TARGET_TYPE (type));
14091       if (TYPE_LENGTH (type) == 0)
14092         TYPE_LENGTH (type) = TYPE_LENGTH (TYPE_TARGET_TYPE (type));
14093     }
14094
14095   TYPE_DECLARED_CLASS (type) = dwarf2_flag_true_p (die, DW_AT_enum_class, cu);
14096
14097   return set_die_type (die, type, cu);
14098 }
14099
14100 /* Given a pointer to a die which begins an enumeration, process all
14101    the dies that define the members of the enumeration, and create the
14102    symbol for the enumeration type.
14103
14104    NOTE: We reverse the order of the element list.  */
14105
14106 static void
14107 process_enumeration_scope (struct die_info *die, struct dwarf2_cu *cu)
14108 {
14109   struct type *this_type;
14110
14111   this_type = get_die_type (die, cu);
14112   if (this_type == NULL)
14113     this_type = read_enumeration_type (die, cu);
14114
14115   if (die->child != NULL)
14116     {
14117       struct die_info *child_die;
14118       struct symbol *sym;
14119       struct field *fields = NULL;
14120       int num_fields = 0;
14121       const char *name;
14122
14123       child_die = die->child;
14124       while (child_die && child_die->tag)
14125         {
14126           if (child_die->tag != DW_TAG_enumerator)
14127             {
14128               process_die (child_die, cu);
14129             }
14130           else
14131             {
14132               name = dwarf2_name (child_die, cu);
14133               if (name)
14134                 {
14135                   sym = new_symbol (child_die, this_type, cu);
14136
14137                   if ((num_fields % DW_FIELD_ALLOC_CHUNK) == 0)
14138                     {
14139                       fields = (struct field *)
14140                         xrealloc (fields,
14141                                   (num_fields + DW_FIELD_ALLOC_CHUNK)
14142                                   * sizeof (struct field));
14143                     }
14144
14145                   FIELD_NAME (fields[num_fields]) = SYMBOL_LINKAGE_NAME (sym);
14146                   FIELD_TYPE (fields[num_fields]) = NULL;
14147                   SET_FIELD_ENUMVAL (fields[num_fields], SYMBOL_VALUE (sym));
14148                   FIELD_BITSIZE (fields[num_fields]) = 0;
14149
14150                   num_fields++;
14151                 }
14152             }
14153
14154           child_die = sibling_die (child_die);
14155         }
14156
14157       if (num_fields)
14158         {
14159           TYPE_NFIELDS (this_type) = num_fields;
14160           TYPE_FIELDS (this_type) = (struct field *)
14161             TYPE_ALLOC (this_type, sizeof (struct field) * num_fields);
14162           memcpy (TYPE_FIELDS (this_type), fields,
14163                   sizeof (struct field) * num_fields);
14164           xfree (fields);
14165         }
14166     }
14167
14168   /* If we are reading an enum from a .debug_types unit, and the enum
14169      is a declaration, and the enum is not the signatured type in the
14170      unit, then we do not want to add a symbol for it.  Adding a
14171      symbol would in some cases obscure the true definition of the
14172      enum, giving users an incomplete type when the definition is
14173      actually available.  Note that we do not want to do this for all
14174      enums which are just declarations, because C++0x allows forward
14175      enum declarations.  */
14176   if (cu->per_cu->is_debug_types
14177       && die_is_declaration (die, cu))
14178     {
14179       struct signatured_type *sig_type;
14180
14181       sig_type = (struct signatured_type *) cu->per_cu;
14182       gdb_assert (to_underlying (sig_type->type_offset_in_section) != 0);
14183       if (sig_type->type_offset_in_section != die->sect_off)
14184         return;
14185     }
14186
14187   new_symbol (die, this_type, cu);
14188 }
14189
14190 /* Extract all information from a DW_TAG_array_type DIE and put it in
14191    the DIE's type field.  For now, this only handles one dimensional
14192    arrays.  */
14193
14194 static struct type *
14195 read_array_type (struct die_info *die, struct dwarf2_cu *cu)
14196 {
14197   struct objfile *objfile = cu->objfile;
14198   struct die_info *child_die;
14199   struct type *type;
14200   struct type *element_type, *range_type, *index_type;
14201   struct type **range_types = NULL;
14202   struct attribute *attr;
14203   int ndim = 0;
14204   struct cleanup *back_to;
14205   const char *name;
14206   unsigned int bit_stride = 0;
14207
14208   element_type = die_type (die, cu);
14209
14210   /* The die_type call above may have already set the type for this DIE.  */
14211   type = get_die_type (die, cu);
14212   if (type)
14213     return type;
14214
14215   attr = dwarf2_attr (die, DW_AT_byte_stride, cu);
14216   if (attr != NULL)
14217     bit_stride = DW_UNSND (attr) * 8;
14218
14219   attr = dwarf2_attr (die, DW_AT_bit_stride, cu);
14220   if (attr != NULL)
14221     bit_stride = DW_UNSND (attr);
14222
14223   /* Irix 6.2 native cc creates array types without children for
14224      arrays with unspecified length.  */
14225   if (die->child == NULL)
14226     {
14227       index_type = objfile_type (objfile)->builtin_int;
14228       range_type = create_static_range_type (NULL, index_type, 0, -1);
14229       type = create_array_type_with_stride (NULL, element_type, range_type,
14230                                             bit_stride);
14231       return set_die_type (die, type, cu);
14232     }
14233
14234   back_to = make_cleanup (null_cleanup, NULL);
14235   child_die = die->child;
14236   while (child_die && child_die->tag)
14237     {
14238       if (child_die->tag == DW_TAG_subrange_type)
14239         {
14240           struct type *child_type = read_type_die (child_die, cu);
14241
14242           if (child_type != NULL)
14243             {
14244               /* The range type was succesfully read.  Save it for the
14245                  array type creation.  */
14246               if ((ndim % DW_FIELD_ALLOC_CHUNK) == 0)
14247                 {
14248                   range_types = (struct type **)
14249                     xrealloc (range_types, (ndim + DW_FIELD_ALLOC_CHUNK)
14250                               * sizeof (struct type *));
14251                   if (ndim == 0)
14252                     make_cleanup (free_current_contents, &range_types);
14253                 }
14254               range_types[ndim++] = child_type;
14255             }
14256         }
14257       child_die = sibling_die (child_die);
14258     }
14259
14260   /* Dwarf2 dimensions are output from left to right, create the
14261      necessary array types in backwards order.  */
14262
14263   type = element_type;
14264
14265   if (read_array_order (die, cu) == DW_ORD_col_major)
14266     {
14267       int i = 0;
14268
14269       while (i < ndim)
14270         type = create_array_type_with_stride (NULL, type, range_types[i++],
14271                                               bit_stride);
14272     }
14273   else
14274     {
14275       while (ndim-- > 0)
14276         type = create_array_type_with_stride (NULL, type, range_types[ndim],
14277                                               bit_stride);
14278     }
14279
14280   /* Understand Dwarf2 support for vector types (like they occur on
14281      the PowerPC w/ AltiVec).  Gcc just adds another attribute to the
14282      array type.  This is not part of the Dwarf2/3 standard yet, but a
14283      custom vendor extension.  The main difference between a regular
14284      array and the vector variant is that vectors are passed by value
14285      to functions.  */
14286   attr = dwarf2_attr (die, DW_AT_GNU_vector, cu);
14287   if (attr)
14288     make_vector_type (type);
14289
14290   /* The DIE may have DW_AT_byte_size set.  For example an OpenCL
14291      implementation may choose to implement triple vectors using this
14292      attribute.  */
14293   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
14294   if (attr)
14295     {
14296       if (DW_UNSND (attr) >= TYPE_LENGTH (type))
14297         TYPE_LENGTH (type) = DW_UNSND (attr);
14298       else
14299         complaint (&symfile_complaints,
14300                    _("DW_AT_byte_size for array type smaller "
14301                      "than the total size of elements"));
14302     }
14303
14304   name = dwarf2_name (die, cu);
14305   if (name)
14306     TYPE_NAME (type) = name;
14307
14308   /* Install the type in the die.  */
14309   set_die_type (die, type, cu);
14310
14311   /* set_die_type should be already done.  */
14312   set_descriptive_type (type, die, cu);
14313
14314   do_cleanups (back_to);
14315
14316   return type;
14317 }
14318
14319 static enum dwarf_array_dim_ordering
14320 read_array_order (struct die_info *die, struct dwarf2_cu *cu)
14321 {
14322   struct attribute *attr;
14323
14324   attr = dwarf2_attr (die, DW_AT_ordering, cu);
14325
14326   if (attr)
14327     return (enum dwarf_array_dim_ordering) DW_SND (attr);
14328
14329   /* GNU F77 is a special case, as at 08/2004 array type info is the
14330      opposite order to the dwarf2 specification, but data is still
14331      laid out as per normal fortran.
14332
14333      FIXME: dsl/2004-8-20: If G77 is ever fixed, this will also need
14334      version checking.  */
14335
14336   if (cu->language == language_fortran
14337       && cu->producer && strstr (cu->producer, "GNU F77"))
14338     {
14339       return DW_ORD_row_major;
14340     }
14341
14342   switch (cu->language_defn->la_array_ordering)
14343     {
14344     case array_column_major:
14345       return DW_ORD_col_major;
14346     case array_row_major:
14347     default:
14348       return DW_ORD_row_major;
14349     };
14350 }
14351
14352 /* Extract all information from a DW_TAG_set_type DIE and put it in
14353    the DIE's type field.  */
14354
14355 static struct type *
14356 read_set_type (struct die_info *die, struct dwarf2_cu *cu)
14357 {
14358   struct type *domain_type, *set_type;
14359   struct attribute *attr;
14360
14361   domain_type = die_type (die, cu);
14362
14363   /* The die_type call above may have already set the type for this DIE.  */
14364   set_type = get_die_type (die, cu);
14365   if (set_type)
14366     return set_type;
14367
14368   set_type = create_set_type (NULL, domain_type);
14369
14370   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
14371   if (attr)
14372     TYPE_LENGTH (set_type) = DW_UNSND (attr);
14373
14374   return set_die_type (die, set_type, cu);
14375 }
14376
14377 /* A helper for read_common_block that creates a locexpr baton.
14378    SYM is the symbol which we are marking as computed.
14379    COMMON_DIE is the DIE for the common block.
14380    COMMON_LOC is the location expression attribute for the common
14381    block itself.
14382    MEMBER_LOC is the location expression attribute for the particular
14383    member of the common block that we are processing.
14384    CU is the CU from which the above come.  */
14385
14386 static void
14387 mark_common_block_symbol_computed (struct symbol *sym,
14388                                    struct die_info *common_die,
14389                                    struct attribute *common_loc,
14390                                    struct attribute *member_loc,
14391                                    struct dwarf2_cu *cu)
14392 {
14393   struct objfile *objfile = dwarf2_per_objfile->objfile;
14394   struct dwarf2_locexpr_baton *baton;
14395   gdb_byte *ptr;
14396   unsigned int cu_off;
14397   enum bfd_endian byte_order = gdbarch_byte_order (get_objfile_arch (objfile));
14398   LONGEST offset = 0;
14399
14400   gdb_assert (common_loc && member_loc);
14401   gdb_assert (attr_form_is_block (common_loc));
14402   gdb_assert (attr_form_is_block (member_loc)
14403               || attr_form_is_constant (member_loc));
14404
14405   baton = XOBNEW (&objfile->objfile_obstack, struct dwarf2_locexpr_baton);
14406   baton->per_cu = cu->per_cu;
14407   gdb_assert (baton->per_cu);
14408
14409   baton->size = 5 /* DW_OP_call4 */ + 1 /* DW_OP_plus */;
14410
14411   if (attr_form_is_constant (member_loc))
14412     {
14413       offset = dwarf2_get_attr_constant_value (member_loc, 0);
14414       baton->size += 1 /* DW_OP_addr */ + cu->header.addr_size;
14415     }
14416   else
14417     baton->size += DW_BLOCK (member_loc)->size;
14418
14419   ptr = (gdb_byte *) obstack_alloc (&objfile->objfile_obstack, baton->size);
14420   baton->data = ptr;
14421
14422   *ptr++ = DW_OP_call4;
14423   cu_off = common_die->sect_off - cu->per_cu->sect_off;
14424   store_unsigned_integer (ptr, 4, byte_order, cu_off);
14425   ptr += 4;
14426
14427   if (attr_form_is_constant (member_loc))
14428     {
14429       *ptr++ = DW_OP_addr;
14430       store_unsigned_integer (ptr, cu->header.addr_size, byte_order, offset);
14431       ptr += cu->header.addr_size;
14432     }
14433   else
14434     {
14435       /* We have to copy the data here, because DW_OP_call4 will only
14436          use a DW_AT_location attribute.  */
14437       memcpy (ptr, DW_BLOCK (member_loc)->data, DW_BLOCK (member_loc)->size);
14438       ptr += DW_BLOCK (member_loc)->size;
14439     }
14440
14441   *ptr++ = DW_OP_plus;
14442   gdb_assert (ptr - baton->data == baton->size);
14443
14444   SYMBOL_LOCATION_BATON (sym) = baton;
14445   SYMBOL_ACLASS_INDEX (sym) = dwarf2_locexpr_index;
14446 }
14447
14448 /* Create appropriate locally-scoped variables for all the
14449    DW_TAG_common_block entries.  Also create a struct common_block
14450    listing all such variables for `info common'.  COMMON_BLOCK_DOMAIN
14451    is used to sepate the common blocks name namespace from regular
14452    variable names.  */
14453
14454 static void
14455 read_common_block (struct die_info *die, struct dwarf2_cu *cu)
14456 {
14457   struct attribute *attr;
14458
14459   attr = dwarf2_attr (die, DW_AT_location, cu);
14460   if (attr)
14461     {
14462       /* Support the .debug_loc offsets.  */
14463       if (attr_form_is_block (attr))
14464         {
14465           /* Ok.  */
14466         }
14467       else if (attr_form_is_section_offset (attr))
14468         {
14469           dwarf2_complex_location_expr_complaint ();
14470           attr = NULL;
14471         }
14472       else
14473         {
14474           dwarf2_invalid_attrib_class_complaint ("DW_AT_location",
14475                                                  "common block member");
14476           attr = NULL;
14477         }
14478     }
14479
14480   if (die->child != NULL)
14481     {
14482       struct objfile *objfile = cu->objfile;
14483       struct die_info *child_die;
14484       size_t n_entries = 0, size;
14485       struct common_block *common_block;
14486       struct symbol *sym;
14487
14488       for (child_die = die->child;
14489            child_die && child_die->tag;
14490            child_die = sibling_die (child_die))
14491         ++n_entries;
14492
14493       size = (sizeof (struct common_block)
14494               + (n_entries - 1) * sizeof (struct symbol *));
14495       common_block
14496         = (struct common_block *) obstack_alloc (&objfile->objfile_obstack,
14497                                                  size);
14498       memset (common_block->contents, 0, n_entries * sizeof (struct symbol *));
14499       common_block->n_entries = 0;
14500
14501       for (child_die = die->child;
14502            child_die && child_die->tag;
14503            child_die = sibling_die (child_die))
14504         {
14505           /* Create the symbol in the DW_TAG_common_block block in the current
14506              symbol scope.  */
14507           sym = new_symbol (child_die, NULL, cu);
14508           if (sym != NULL)
14509             {
14510               struct attribute *member_loc;
14511
14512               common_block->contents[common_block->n_entries++] = sym;
14513
14514               member_loc = dwarf2_attr (child_die, DW_AT_data_member_location,
14515                                         cu);
14516               if (member_loc)
14517                 {
14518                   /* GDB has handled this for a long time, but it is
14519                      not specified by DWARF.  It seems to have been
14520                      emitted by gfortran at least as recently as:
14521                      http://gcc.gnu.org/bugzilla/show_bug.cgi?id=23057.  */
14522                   complaint (&symfile_complaints,
14523                              _("Variable in common block has "
14524                                "DW_AT_data_member_location "
14525                                "- DIE at 0x%x [in module %s]"),
14526                              to_underlying (child_die->sect_off),
14527                              objfile_name (cu->objfile));
14528
14529                   if (attr_form_is_section_offset (member_loc))
14530                     dwarf2_complex_location_expr_complaint ();
14531                   else if (attr_form_is_constant (member_loc)
14532                            || attr_form_is_block (member_loc))
14533                     {
14534                       if (attr)
14535                         mark_common_block_symbol_computed (sym, die, attr,
14536                                                            member_loc, cu);
14537                     }
14538                   else
14539                     dwarf2_complex_location_expr_complaint ();
14540                 }
14541             }
14542         }
14543
14544       sym = new_symbol (die, objfile_type (objfile)->builtin_void, cu);
14545       SYMBOL_VALUE_COMMON_BLOCK (sym) = common_block;
14546     }
14547 }
14548
14549 /* Create a type for a C++ namespace.  */
14550
14551 static struct type *
14552 read_namespace_type (struct die_info *die, struct dwarf2_cu *cu)
14553 {
14554   struct objfile *objfile = cu->objfile;
14555   const char *previous_prefix, *name;
14556   int is_anonymous;
14557   struct type *type;
14558
14559   /* For extensions, reuse the type of the original namespace.  */
14560   if (dwarf2_attr (die, DW_AT_extension, cu) != NULL)
14561     {
14562       struct die_info *ext_die;
14563       struct dwarf2_cu *ext_cu = cu;
14564
14565       ext_die = dwarf2_extension (die, &ext_cu);
14566       type = read_type_die (ext_die, ext_cu);
14567
14568       /* EXT_CU may not be the same as CU.
14569          Ensure TYPE is recorded with CU in die_type_hash.  */
14570       return set_die_type (die, type, cu);
14571     }
14572
14573   name = namespace_name (die, &is_anonymous, cu);
14574
14575   /* Now build the name of the current namespace.  */
14576
14577   previous_prefix = determine_prefix (die, cu);
14578   if (previous_prefix[0] != '\0')
14579     name = typename_concat (&objfile->objfile_obstack,
14580                             previous_prefix, name, 0, cu);
14581
14582   /* Create the type.  */
14583   type = init_type (objfile, TYPE_CODE_NAMESPACE, 0, name);
14584   TYPE_TAG_NAME (type) = TYPE_NAME (type);
14585
14586   return set_die_type (die, type, cu);
14587 }
14588
14589 /* Read a namespace scope.  */
14590
14591 static void
14592 read_namespace (struct die_info *die, struct dwarf2_cu *cu)
14593 {
14594   struct objfile *objfile = cu->objfile;
14595   int is_anonymous;
14596
14597   /* Add a symbol associated to this if we haven't seen the namespace
14598      before.  Also, add a using directive if it's an anonymous
14599      namespace.  */
14600
14601   if (dwarf2_attr (die, DW_AT_extension, cu) == NULL)
14602     {
14603       struct type *type;
14604
14605       type = read_type_die (die, cu);
14606       new_symbol (die, type, cu);
14607
14608       namespace_name (die, &is_anonymous, cu);
14609       if (is_anonymous)
14610         {
14611           const char *previous_prefix = determine_prefix (die, cu);
14612
14613           std::vector<const char *> excludes;
14614           add_using_directive (using_directives (cu->language),
14615                                previous_prefix, TYPE_NAME (type), NULL,
14616                                NULL, excludes, 0, &objfile->objfile_obstack);
14617         }
14618     }
14619
14620   if (die->child != NULL)
14621     {
14622       struct die_info *child_die = die->child;
14623
14624       while (child_die && child_die->tag)
14625         {
14626           process_die (child_die, cu);
14627           child_die = sibling_die (child_die);
14628         }
14629     }
14630 }
14631
14632 /* Read a Fortran module as type.  This DIE can be only a declaration used for
14633    imported module.  Still we need that type as local Fortran "use ... only"
14634    declaration imports depend on the created type in determine_prefix.  */
14635
14636 static struct type *
14637 read_module_type (struct die_info *die, struct dwarf2_cu *cu)
14638 {
14639   struct objfile *objfile = cu->objfile;
14640   const char *module_name;
14641   struct type *type;
14642
14643   module_name = dwarf2_name (die, cu);
14644   if (!module_name)
14645     complaint (&symfile_complaints,
14646                _("DW_TAG_module has no name, offset 0x%x"),
14647                to_underlying (die->sect_off));
14648   type = init_type (objfile, TYPE_CODE_MODULE, 0, module_name);
14649
14650   /* determine_prefix uses TYPE_TAG_NAME.  */
14651   TYPE_TAG_NAME (type) = TYPE_NAME (type);
14652
14653   return set_die_type (die, type, cu);
14654 }
14655
14656 /* Read a Fortran module.  */
14657
14658 static void
14659 read_module (struct die_info *die, struct dwarf2_cu *cu)
14660 {
14661   struct die_info *child_die = die->child;
14662   struct type *type;
14663
14664   type = read_type_die (die, cu);
14665   new_symbol (die, type, cu);
14666
14667   while (child_die && child_die->tag)
14668     {
14669       process_die (child_die, cu);
14670       child_die = sibling_die (child_die);
14671     }
14672 }
14673
14674 /* Return the name of the namespace represented by DIE.  Set
14675    *IS_ANONYMOUS to tell whether or not the namespace is an anonymous
14676    namespace.  */
14677
14678 static const char *
14679 namespace_name (struct die_info *die, int *is_anonymous, struct dwarf2_cu *cu)
14680 {
14681   struct die_info *current_die;
14682   const char *name = NULL;
14683
14684   /* Loop through the extensions until we find a name.  */
14685
14686   for (current_die = die;
14687        current_die != NULL;
14688        current_die = dwarf2_extension (die, &cu))
14689     {
14690       /* We don't use dwarf2_name here so that we can detect the absence
14691          of a name -> anonymous namespace.  */
14692       name = dwarf2_string_attr (die, DW_AT_name, cu);
14693
14694       if (name != NULL)
14695         break;
14696     }
14697
14698   /* Is it an anonymous namespace?  */
14699
14700   *is_anonymous = (name == NULL);
14701   if (*is_anonymous)
14702     name = CP_ANONYMOUS_NAMESPACE_STR;
14703
14704   return name;
14705 }
14706
14707 /* Extract all information from a DW_TAG_pointer_type DIE and add to
14708    the user defined type vector.  */
14709
14710 static struct type *
14711 read_tag_pointer_type (struct die_info *die, struct dwarf2_cu *cu)
14712 {
14713   struct gdbarch *gdbarch = get_objfile_arch (cu->objfile);
14714   struct comp_unit_head *cu_header = &cu->header;
14715   struct type *type;
14716   struct attribute *attr_byte_size;
14717   struct attribute *attr_address_class;
14718   int byte_size, addr_class;
14719   struct type *target_type;
14720
14721   target_type = die_type (die, cu);
14722
14723   /* The die_type call above may have already set the type for this DIE.  */
14724   type = get_die_type (die, cu);
14725   if (type)
14726     return type;
14727
14728   type = lookup_pointer_type (target_type);
14729
14730   attr_byte_size = dwarf2_attr (die, DW_AT_byte_size, cu);
14731   if (attr_byte_size)
14732     byte_size = DW_UNSND (attr_byte_size);
14733   else
14734     byte_size = cu_header->addr_size;
14735
14736   attr_address_class = dwarf2_attr (die, DW_AT_address_class, cu);
14737   if (attr_address_class)
14738     addr_class = DW_UNSND (attr_address_class);
14739   else
14740     addr_class = DW_ADDR_none;
14741
14742   /* If the pointer size or address class is different than the
14743      default, create a type variant marked as such and set the
14744      length accordingly.  */
14745   if (TYPE_LENGTH (type) != byte_size || addr_class != DW_ADDR_none)
14746     {
14747       if (gdbarch_address_class_type_flags_p (gdbarch))
14748         {
14749           int type_flags;
14750
14751           type_flags = gdbarch_address_class_type_flags
14752                          (gdbarch, byte_size, addr_class);
14753           gdb_assert ((type_flags & ~TYPE_INSTANCE_FLAG_ADDRESS_CLASS_ALL)
14754                       == 0);
14755           type = make_type_with_address_space (type, type_flags);
14756         }
14757       else if (TYPE_LENGTH (type) != byte_size)
14758         {
14759           complaint (&symfile_complaints,
14760                      _("invalid pointer size %d"), byte_size);
14761         }
14762       else
14763         {
14764           /* Should we also complain about unhandled address classes?  */
14765         }
14766     }
14767
14768   TYPE_LENGTH (type) = byte_size;
14769   return set_die_type (die, type, cu);
14770 }
14771
14772 /* Extract all information from a DW_TAG_ptr_to_member_type DIE and add to
14773    the user defined type vector.  */
14774
14775 static struct type *
14776 read_tag_ptr_to_member_type (struct die_info *die, struct dwarf2_cu *cu)
14777 {
14778   struct type *type;
14779   struct type *to_type;
14780   struct type *domain;
14781
14782   to_type = die_type (die, cu);
14783   domain = die_containing_type (die, cu);
14784
14785   /* The calls above may have already set the type for this DIE.  */
14786   type = get_die_type (die, cu);
14787   if (type)
14788     return type;
14789
14790   if (TYPE_CODE (check_typedef (to_type)) == TYPE_CODE_METHOD)
14791     type = lookup_methodptr_type (to_type);
14792   else if (TYPE_CODE (check_typedef (to_type)) == TYPE_CODE_FUNC)
14793     {
14794       struct type *new_type = alloc_type (cu->objfile);
14795
14796       smash_to_method_type (new_type, domain, TYPE_TARGET_TYPE (to_type),
14797                             TYPE_FIELDS (to_type), TYPE_NFIELDS (to_type),
14798                             TYPE_VARARGS (to_type));
14799       type = lookup_methodptr_type (new_type);
14800     }
14801   else
14802     type = lookup_memberptr_type (to_type, domain);
14803
14804   return set_die_type (die, type, cu);
14805 }
14806
14807 /* Extract all information from a DW_TAG_{rvalue_,}reference_type DIE and add to
14808    the user defined type vector.  */
14809
14810 static struct type *
14811 read_tag_reference_type (struct die_info *die, struct dwarf2_cu *cu,
14812                           enum type_code refcode)
14813 {
14814   struct comp_unit_head *cu_header = &cu->header;
14815   struct type *type, *target_type;
14816   struct attribute *attr;
14817
14818   gdb_assert (refcode == TYPE_CODE_REF || refcode == TYPE_CODE_RVALUE_REF);
14819
14820   target_type = die_type (die, cu);
14821
14822   /* The die_type call above may have already set the type for this DIE.  */
14823   type = get_die_type (die, cu);
14824   if (type)
14825     return type;
14826
14827   type = lookup_reference_type (target_type, refcode);
14828   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
14829   if (attr)
14830     {
14831       TYPE_LENGTH (type) = DW_UNSND (attr);
14832     }
14833   else
14834     {
14835       TYPE_LENGTH (type) = cu_header->addr_size;
14836     }
14837   return set_die_type (die, type, cu);
14838 }
14839
14840 /* Add the given cv-qualifiers to the element type of the array.  GCC
14841    outputs DWARF type qualifiers that apply to an array, not the
14842    element type.  But GDB relies on the array element type to carry
14843    the cv-qualifiers.  This mimics section 6.7.3 of the C99
14844    specification.  */
14845
14846 static struct type *
14847 add_array_cv_type (struct die_info *die, struct dwarf2_cu *cu,
14848                    struct type *base_type, int cnst, int voltl)
14849 {
14850   struct type *el_type, *inner_array;
14851
14852   base_type = copy_type (base_type);
14853   inner_array = base_type;
14854
14855   while (TYPE_CODE (TYPE_TARGET_TYPE (inner_array)) == TYPE_CODE_ARRAY)
14856     {
14857       TYPE_TARGET_TYPE (inner_array) =
14858         copy_type (TYPE_TARGET_TYPE (inner_array));
14859       inner_array = TYPE_TARGET_TYPE (inner_array);
14860     }
14861
14862   el_type = TYPE_TARGET_TYPE (inner_array);
14863   cnst |= TYPE_CONST (el_type);
14864   voltl |= TYPE_VOLATILE (el_type);
14865   TYPE_TARGET_TYPE (inner_array) = make_cv_type (cnst, voltl, el_type, NULL);
14866
14867   return set_die_type (die, base_type, cu);
14868 }
14869
14870 static struct type *
14871 read_tag_const_type (struct die_info *die, struct dwarf2_cu *cu)
14872 {
14873   struct type *base_type, *cv_type;
14874
14875   base_type = die_type (die, cu);
14876
14877   /* The die_type call above may have already set the type for this DIE.  */
14878   cv_type = get_die_type (die, cu);
14879   if (cv_type)
14880     return cv_type;
14881
14882   /* In case the const qualifier is applied to an array type, the element type
14883      is so qualified, not the array type (section 6.7.3 of C99).  */
14884   if (TYPE_CODE (base_type) == TYPE_CODE_ARRAY)
14885     return add_array_cv_type (die, cu, base_type, 1, 0);
14886
14887   cv_type = make_cv_type (1, TYPE_VOLATILE (base_type), base_type, 0);
14888   return set_die_type (die, cv_type, cu);
14889 }
14890
14891 static struct type *
14892 read_tag_volatile_type (struct die_info *die, struct dwarf2_cu *cu)
14893 {
14894   struct type *base_type, *cv_type;
14895
14896   base_type = die_type (die, cu);
14897
14898   /* The die_type call above may have already set the type for this DIE.  */
14899   cv_type = get_die_type (die, cu);
14900   if (cv_type)
14901     return cv_type;
14902
14903   /* In case the volatile qualifier is applied to an array type, the
14904      element type is so qualified, not the array type (section 6.7.3
14905      of C99).  */
14906   if (TYPE_CODE (base_type) == TYPE_CODE_ARRAY)
14907     return add_array_cv_type (die, cu, base_type, 0, 1);
14908
14909   cv_type = make_cv_type (TYPE_CONST (base_type), 1, base_type, 0);
14910   return set_die_type (die, cv_type, cu);
14911 }
14912
14913 /* Handle DW_TAG_restrict_type.  */
14914
14915 static struct type *
14916 read_tag_restrict_type (struct die_info *die, struct dwarf2_cu *cu)
14917 {
14918   struct type *base_type, *cv_type;
14919
14920   base_type = die_type (die, cu);
14921
14922   /* The die_type call above may have already set the type for this DIE.  */
14923   cv_type = get_die_type (die, cu);
14924   if (cv_type)
14925     return cv_type;
14926
14927   cv_type = make_restrict_type (base_type);
14928   return set_die_type (die, cv_type, cu);
14929 }
14930
14931 /* Handle DW_TAG_atomic_type.  */
14932
14933 static struct type *
14934 read_tag_atomic_type (struct die_info *die, struct dwarf2_cu *cu)
14935 {
14936   struct type *base_type, *cv_type;
14937
14938   base_type = die_type (die, cu);
14939
14940   /* The die_type call above may have already set the type for this DIE.  */
14941   cv_type = get_die_type (die, cu);
14942   if (cv_type)
14943     return cv_type;
14944
14945   cv_type = make_atomic_type (base_type);
14946   return set_die_type (die, cv_type, cu);
14947 }
14948
14949 /* Extract all information from a DW_TAG_string_type DIE and add to
14950    the user defined type vector.  It isn't really a user defined type,
14951    but it behaves like one, with other DIE's using an AT_user_def_type
14952    attribute to reference it.  */
14953
14954 static struct type *
14955 read_tag_string_type (struct die_info *die, struct dwarf2_cu *cu)
14956 {
14957   struct objfile *objfile = cu->objfile;
14958   struct gdbarch *gdbarch = get_objfile_arch (objfile);
14959   struct type *type, *range_type, *index_type, *char_type;
14960   struct attribute *attr;
14961   unsigned int length;
14962
14963   attr = dwarf2_attr (die, DW_AT_string_length, cu);
14964   if (attr)
14965     {
14966       length = DW_UNSND (attr);
14967     }
14968   else
14969     {
14970       /* Check for the DW_AT_byte_size attribute.  */
14971       attr = dwarf2_attr (die, DW_AT_byte_size, cu);
14972       if (attr)
14973         {
14974           length = DW_UNSND (attr);
14975         }
14976       else
14977         {
14978           length = 1;
14979         }
14980     }
14981
14982   index_type = objfile_type (objfile)->builtin_int;
14983   range_type = create_static_range_type (NULL, index_type, 1, length);
14984   char_type = language_string_char_type (cu->language_defn, gdbarch);
14985   type = create_string_type (NULL, char_type, range_type);
14986
14987   return set_die_type (die, type, cu);
14988 }
14989
14990 /* Assuming that DIE corresponds to a function, returns nonzero
14991    if the function is prototyped.  */
14992
14993 static int
14994 prototyped_function_p (struct die_info *die, struct dwarf2_cu *cu)
14995 {
14996   struct attribute *attr;
14997
14998   attr = dwarf2_attr (die, DW_AT_prototyped, cu);
14999   if (attr && (DW_UNSND (attr) != 0))
15000     return 1;
15001
15002   /* The DWARF standard implies that the DW_AT_prototyped attribute
15003      is only meaninful for C, but the concept also extends to other
15004      languages that allow unprototyped functions (Eg: Objective C).
15005      For all other languages, assume that functions are always
15006      prototyped.  */
15007   if (cu->language != language_c
15008       && cu->language != language_objc
15009       && cu->language != language_opencl)
15010     return 1;
15011
15012   /* RealView does not emit DW_AT_prototyped.  We can not distinguish
15013      prototyped and unprototyped functions; default to prototyped,
15014      since that is more common in modern code (and RealView warns
15015      about unprototyped functions).  */
15016   if (producer_is_realview (cu->producer))
15017     return 1;
15018
15019   return 0;
15020 }
15021
15022 /* Handle DIES due to C code like:
15023
15024    struct foo
15025    {
15026    int (*funcp)(int a, long l);
15027    int b;
15028    };
15029
15030    ('funcp' generates a DW_TAG_subroutine_type DIE).  */
15031
15032 static struct type *
15033 read_subroutine_type (struct die_info *die, struct dwarf2_cu *cu)
15034 {
15035   struct objfile *objfile = cu->objfile;
15036   struct type *type;            /* Type that this function returns.  */
15037   struct type *ftype;           /* Function that returns above type.  */
15038   struct attribute *attr;
15039
15040   type = die_type (die, cu);
15041
15042   /* The die_type call above may have already set the type for this DIE.  */
15043   ftype = get_die_type (die, cu);
15044   if (ftype)
15045     return ftype;
15046
15047   ftype = lookup_function_type (type);
15048
15049   if (prototyped_function_p (die, cu))
15050     TYPE_PROTOTYPED (ftype) = 1;
15051
15052   /* Store the calling convention in the type if it's available in
15053      the subroutine die.  Otherwise set the calling convention to
15054      the default value DW_CC_normal.  */
15055   attr = dwarf2_attr (die, DW_AT_calling_convention, cu);
15056   if (attr)
15057     TYPE_CALLING_CONVENTION (ftype) = DW_UNSND (attr);
15058   else if (cu->producer && strstr (cu->producer, "IBM XL C for OpenCL"))
15059     TYPE_CALLING_CONVENTION (ftype) = DW_CC_GDB_IBM_OpenCL;
15060   else
15061     TYPE_CALLING_CONVENTION (ftype) = DW_CC_normal;
15062
15063   /* Record whether the function returns normally to its caller or not
15064      if the DWARF producer set that information.  */
15065   attr = dwarf2_attr (die, DW_AT_noreturn, cu);
15066   if (attr && (DW_UNSND (attr) != 0))
15067     TYPE_NO_RETURN (ftype) = 1;
15068
15069   /* We need to add the subroutine type to the die immediately so
15070      we don't infinitely recurse when dealing with parameters
15071      declared as the same subroutine type.  */
15072   set_die_type (die, ftype, cu);
15073
15074   if (die->child != NULL)
15075     {
15076       struct type *void_type = objfile_type (objfile)->builtin_void;
15077       struct die_info *child_die;
15078       int nparams, iparams;
15079
15080       /* Count the number of parameters.
15081          FIXME: GDB currently ignores vararg functions, but knows about
15082          vararg member functions.  */
15083       nparams = 0;
15084       child_die = die->child;
15085       while (child_die && child_die->tag)
15086         {
15087           if (child_die->tag == DW_TAG_formal_parameter)
15088             nparams++;
15089           else if (child_die->tag == DW_TAG_unspecified_parameters)
15090             TYPE_VARARGS (ftype) = 1;
15091           child_die = sibling_die (child_die);
15092         }
15093
15094       /* Allocate storage for parameters and fill them in.  */
15095       TYPE_NFIELDS (ftype) = nparams;
15096       TYPE_FIELDS (ftype) = (struct field *)
15097         TYPE_ZALLOC (ftype, nparams * sizeof (struct field));
15098
15099       /* TYPE_FIELD_TYPE must never be NULL.  Pre-fill the array to ensure it
15100          even if we error out during the parameters reading below.  */
15101       for (iparams = 0; iparams < nparams; iparams++)
15102         TYPE_FIELD_TYPE (ftype, iparams) = void_type;
15103
15104       iparams = 0;
15105       child_die = die->child;
15106       while (child_die && child_die->tag)
15107         {
15108           if (child_die->tag == DW_TAG_formal_parameter)
15109             {
15110               struct type *arg_type;
15111
15112               /* DWARF version 2 has no clean way to discern C++
15113                  static and non-static member functions.  G++ helps
15114                  GDB by marking the first parameter for non-static
15115                  member functions (which is the this pointer) as
15116                  artificial.  We pass this information to
15117                  dwarf2_add_member_fn via TYPE_FIELD_ARTIFICIAL.
15118
15119                  DWARF version 3 added DW_AT_object_pointer, which GCC
15120                  4.5 does not yet generate.  */
15121               attr = dwarf2_attr (child_die, DW_AT_artificial, cu);
15122               if (attr)
15123                 TYPE_FIELD_ARTIFICIAL (ftype, iparams) = DW_UNSND (attr);
15124               else
15125                 TYPE_FIELD_ARTIFICIAL (ftype, iparams) = 0;
15126               arg_type = die_type (child_die, cu);
15127
15128               /* RealView does not mark THIS as const, which the testsuite
15129                  expects.  GCC marks THIS as const in method definitions,
15130                  but not in the class specifications (GCC PR 43053).  */
15131               if (cu->language == language_cplus && !TYPE_CONST (arg_type)
15132                   && TYPE_FIELD_ARTIFICIAL (ftype, iparams))
15133                 {
15134                   int is_this = 0;
15135                   struct dwarf2_cu *arg_cu = cu;
15136                   const char *name = dwarf2_name (child_die, cu);
15137
15138                   attr = dwarf2_attr (die, DW_AT_object_pointer, cu);
15139                   if (attr)
15140                     {
15141                       /* If the compiler emits this, use it.  */
15142                       if (follow_die_ref (die, attr, &arg_cu) == child_die)
15143                         is_this = 1;
15144                     }
15145                   else if (name && strcmp (name, "this") == 0)
15146                     /* Function definitions will have the argument names.  */
15147                     is_this = 1;
15148                   else if (name == NULL && iparams == 0)
15149                     /* Declarations may not have the names, so like
15150                        elsewhere in GDB, assume an artificial first
15151                        argument is "this".  */
15152                     is_this = 1;
15153
15154                   if (is_this)
15155                     arg_type = make_cv_type (1, TYPE_VOLATILE (arg_type),
15156                                              arg_type, 0);
15157                 }
15158
15159               TYPE_FIELD_TYPE (ftype, iparams) = arg_type;
15160               iparams++;
15161             }
15162           child_die = sibling_die (child_die);
15163         }
15164     }
15165
15166   return ftype;
15167 }
15168
15169 static struct type *
15170 read_typedef (struct die_info *die, struct dwarf2_cu *cu)
15171 {
15172   struct objfile *objfile = cu->objfile;
15173   const char *name = NULL;
15174   struct type *this_type, *target_type;
15175
15176   name = dwarf2_full_name (NULL, die, cu);
15177   this_type = init_type (objfile, TYPE_CODE_TYPEDEF, 0, name);
15178   TYPE_TARGET_STUB (this_type) = 1;
15179   set_die_type (die, this_type, cu);
15180   target_type = die_type (die, cu);
15181   if (target_type != this_type)
15182     TYPE_TARGET_TYPE (this_type) = target_type;
15183   else
15184     {
15185       /* Self-referential typedefs are, it seems, not allowed by the DWARF
15186          spec and cause infinite loops in GDB.  */
15187       complaint (&symfile_complaints,
15188                  _("Self-referential DW_TAG_typedef "
15189                    "- DIE at 0x%x [in module %s]"),
15190                  to_underlying (die->sect_off), objfile_name (objfile));
15191       TYPE_TARGET_TYPE (this_type) = NULL;
15192     }
15193   return this_type;
15194 }
15195
15196 /* Allocate a floating-point type of size BITS and name NAME.  Pass NAME_HINT
15197    (which may be different from NAME) to the architecture back-end to allow
15198    it to guess the correct format if necessary.  */
15199
15200 static struct type *
15201 dwarf2_init_float_type (struct objfile *objfile, int bits, const char *name,
15202                         const char *name_hint)
15203 {
15204   struct gdbarch *gdbarch = get_objfile_arch (objfile);
15205   const struct floatformat **format;
15206   struct type *type;
15207
15208   format = gdbarch_floatformat_for_type (gdbarch, name_hint, bits);
15209   if (format)
15210     type = init_float_type (objfile, bits, name, format);
15211   else
15212     type = init_type (objfile, TYPE_CODE_ERROR, bits / TARGET_CHAR_BIT, name);
15213
15214   return type;
15215 }
15216
15217 /* Find a representation of a given base type and install
15218    it in the TYPE field of the die.  */
15219
15220 static struct type *
15221 read_base_type (struct die_info *die, struct dwarf2_cu *cu)
15222 {
15223   struct objfile *objfile = cu->objfile;
15224   struct type *type;
15225   struct attribute *attr;
15226   int encoding = 0, bits = 0;
15227   const char *name;
15228
15229   attr = dwarf2_attr (die, DW_AT_encoding, cu);
15230   if (attr)
15231     {
15232       encoding = DW_UNSND (attr);
15233     }
15234   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
15235   if (attr)
15236     {
15237       bits = DW_UNSND (attr) * TARGET_CHAR_BIT;
15238     }
15239   name = dwarf2_name (die, cu);
15240   if (!name)
15241     {
15242       complaint (&symfile_complaints,
15243                  _("DW_AT_name missing from DW_TAG_base_type"));
15244     }
15245
15246   switch (encoding)
15247     {
15248       case DW_ATE_address:
15249         /* Turn DW_ATE_address into a void * pointer.  */
15250         type = init_type (objfile, TYPE_CODE_VOID, 1, NULL);
15251         type = init_pointer_type (objfile, bits, name, type);
15252         break;
15253       case DW_ATE_boolean:
15254         type = init_boolean_type (objfile, bits, 1, name);
15255         break;
15256       case DW_ATE_complex_float:
15257         type = dwarf2_init_float_type (objfile, bits / 2, NULL, name);
15258         type = init_complex_type (objfile, name, type);
15259         break;
15260       case DW_ATE_decimal_float:
15261         type = init_decfloat_type (objfile, bits, name);
15262         break;
15263       case DW_ATE_float:
15264         type = dwarf2_init_float_type (objfile, bits, name, name);
15265         break;
15266       case DW_ATE_signed:
15267         type = init_integer_type (objfile, bits, 0, name);
15268         break;
15269       case DW_ATE_unsigned:
15270         if (cu->language == language_fortran
15271             && name
15272             && startswith (name, "character("))
15273           type = init_character_type (objfile, bits, 1, name);
15274         else
15275           type = init_integer_type (objfile, bits, 1, name);
15276         break;
15277       case DW_ATE_signed_char:
15278         if (cu->language == language_ada || cu->language == language_m2
15279             || cu->language == language_pascal
15280             || cu->language == language_fortran)
15281           type = init_character_type (objfile, bits, 0, name);
15282         else
15283           type = init_integer_type (objfile, bits, 0, name);
15284         break;
15285       case DW_ATE_unsigned_char:
15286         if (cu->language == language_ada || cu->language == language_m2
15287             || cu->language == language_pascal
15288             || cu->language == language_fortran
15289             || cu->language == language_rust)
15290           type = init_character_type (objfile, bits, 1, name);
15291         else
15292           type = init_integer_type (objfile, bits, 1, name);
15293         break;
15294       case DW_ATE_UTF:
15295         {
15296           gdbarch *arch = get_objfile_arch (objfile);
15297
15298           if (bits == 16)
15299             type = builtin_type (arch)->builtin_char16;
15300           else if (bits == 32)
15301             type = builtin_type (arch)->builtin_char32;
15302           else
15303             {
15304               complaint (&symfile_complaints,
15305                          _("unsupported DW_ATE_UTF bit size: '%d'"),
15306                          bits);
15307               type = init_integer_type (objfile, bits, 1, name);
15308             }
15309           return set_die_type (die, type, cu);
15310         }
15311         break;
15312
15313       default:
15314         complaint (&symfile_complaints, _("unsupported DW_AT_encoding: '%s'"),
15315                    dwarf_type_encoding_name (encoding));
15316         type = init_type (objfile, TYPE_CODE_ERROR,
15317                           bits / TARGET_CHAR_BIT, name);
15318         break;
15319     }
15320
15321   if (name && strcmp (name, "char") == 0)
15322     TYPE_NOSIGN (type) = 1;
15323
15324   return set_die_type (die, type, cu);
15325 }
15326
15327 /* Parse dwarf attribute if it's a block, reference or constant and put the
15328    resulting value of the attribute into struct bound_prop.
15329    Returns 1 if ATTR could be resolved into PROP, 0 otherwise.  */
15330
15331 static int
15332 attr_to_dynamic_prop (const struct attribute *attr, struct die_info *die,
15333                       struct dwarf2_cu *cu, struct dynamic_prop *prop)
15334 {
15335   struct dwarf2_property_baton *baton;
15336   struct obstack *obstack = &cu->objfile->objfile_obstack;
15337
15338   if (attr == NULL || prop == NULL)
15339     return 0;
15340
15341   if (attr_form_is_block (attr))
15342     {
15343       baton = XOBNEW (obstack, struct dwarf2_property_baton);
15344       baton->referenced_type = NULL;
15345       baton->locexpr.per_cu = cu->per_cu;
15346       baton->locexpr.size = DW_BLOCK (attr)->size;
15347       baton->locexpr.data = DW_BLOCK (attr)->data;
15348       prop->data.baton = baton;
15349       prop->kind = PROP_LOCEXPR;
15350       gdb_assert (prop->data.baton != NULL);
15351     }
15352   else if (attr_form_is_ref (attr))
15353     {
15354       struct dwarf2_cu *target_cu = cu;
15355       struct die_info *target_die;
15356       struct attribute *target_attr;
15357
15358       target_die = follow_die_ref (die, attr, &target_cu);
15359       target_attr = dwarf2_attr (target_die, DW_AT_location, target_cu);
15360       if (target_attr == NULL)
15361         target_attr = dwarf2_attr (target_die, DW_AT_data_member_location,
15362                                    target_cu);
15363       if (target_attr == NULL)
15364         return 0;
15365
15366       switch (target_attr->name)
15367         {
15368           case DW_AT_location:
15369             if (attr_form_is_section_offset (target_attr))
15370               {
15371                 baton = XOBNEW (obstack, struct dwarf2_property_baton);
15372                 baton->referenced_type = die_type (target_die, target_cu);
15373                 fill_in_loclist_baton (cu, &baton->loclist, target_attr);
15374                 prop->data.baton = baton;
15375                 prop->kind = PROP_LOCLIST;
15376                 gdb_assert (prop->data.baton != NULL);
15377               }
15378             else if (attr_form_is_block (target_attr))
15379               {
15380                 baton = XOBNEW (obstack, struct dwarf2_property_baton);
15381                 baton->referenced_type = die_type (target_die, target_cu);
15382                 baton->locexpr.per_cu = cu->per_cu;
15383                 baton->locexpr.size = DW_BLOCK (target_attr)->size;
15384                 baton->locexpr.data = DW_BLOCK (target_attr)->data;
15385                 prop->data.baton = baton;
15386                 prop->kind = PROP_LOCEXPR;
15387                 gdb_assert (prop->data.baton != NULL);
15388               }
15389             else
15390               {
15391                 dwarf2_invalid_attrib_class_complaint ("DW_AT_location",
15392                                                        "dynamic property");
15393                 return 0;
15394               }
15395             break;
15396           case DW_AT_data_member_location:
15397             {
15398               LONGEST offset;
15399
15400               if (!handle_data_member_location (target_die, target_cu,
15401                                                 &offset))
15402                 return 0;
15403
15404               baton = XOBNEW (obstack, struct dwarf2_property_baton);
15405               baton->referenced_type = read_type_die (target_die->parent,
15406                                                       target_cu);
15407               baton->offset_info.offset = offset;
15408               baton->offset_info.type = die_type (target_die, target_cu);
15409               prop->data.baton = baton;
15410               prop->kind = PROP_ADDR_OFFSET;
15411               break;
15412             }
15413         }
15414     }
15415   else if (attr_form_is_constant (attr))
15416     {
15417       prop->data.const_val = dwarf2_get_attr_constant_value (attr, 0);
15418       prop->kind = PROP_CONST;
15419     }
15420   else
15421     {
15422       dwarf2_invalid_attrib_class_complaint (dwarf_form_name (attr->form),
15423                                              dwarf2_name (die, cu));
15424       return 0;
15425     }
15426
15427   return 1;
15428 }
15429
15430 /* Read the given DW_AT_subrange DIE.  */
15431
15432 static struct type *
15433 read_subrange_type (struct die_info *die, struct dwarf2_cu *cu)
15434 {
15435   struct type *base_type, *orig_base_type;
15436   struct type *range_type;
15437   struct attribute *attr;
15438   struct dynamic_prop low, high;
15439   int low_default_is_valid;
15440   int high_bound_is_count = 0;
15441   const char *name;
15442   LONGEST negative_mask;
15443
15444   orig_base_type = die_type (die, cu);
15445   /* If ORIG_BASE_TYPE is a typedef, it will not be TYPE_UNSIGNED,
15446      whereas the real type might be.  So, we use ORIG_BASE_TYPE when
15447      creating the range type, but we use the result of check_typedef
15448      when examining properties of the type.  */
15449   base_type = check_typedef (orig_base_type);
15450
15451   /* The die_type call above may have already set the type for this DIE.  */
15452   range_type = get_die_type (die, cu);
15453   if (range_type)
15454     return range_type;
15455
15456   low.kind = PROP_CONST;
15457   high.kind = PROP_CONST;
15458   high.data.const_val = 0;
15459
15460   /* Set LOW_DEFAULT_IS_VALID if current language and DWARF version allow
15461      omitting DW_AT_lower_bound.  */
15462   switch (cu->language)
15463     {
15464     case language_c:
15465     case language_cplus:
15466       low.data.const_val = 0;
15467       low_default_is_valid = 1;
15468       break;
15469     case language_fortran:
15470       low.data.const_val = 1;
15471       low_default_is_valid = 1;
15472       break;
15473     case language_d:
15474     case language_objc:
15475     case language_rust:
15476       low.data.const_val = 0;
15477       low_default_is_valid = (cu->header.version >= 4);
15478       break;
15479     case language_ada:
15480     case language_m2:
15481     case language_pascal:
15482       low.data.const_val = 1;
15483       low_default_is_valid = (cu->header.version >= 4);
15484       break;
15485     default:
15486       low.data.const_val = 0;
15487       low_default_is_valid = 0;
15488       break;
15489     }
15490
15491   attr = dwarf2_attr (die, DW_AT_lower_bound, cu);
15492   if (attr)
15493     attr_to_dynamic_prop (attr, die, cu, &low);
15494   else if (!low_default_is_valid)
15495     complaint (&symfile_complaints, _("Missing DW_AT_lower_bound "
15496                                       "- DIE at 0x%x [in module %s]"),
15497                to_underlying (die->sect_off), objfile_name (cu->objfile));
15498
15499   attr = dwarf2_attr (die, DW_AT_upper_bound, cu);
15500   if (!attr_to_dynamic_prop (attr, die, cu, &high))
15501     {
15502       attr = dwarf2_attr (die, DW_AT_count, cu);
15503       if (attr_to_dynamic_prop (attr, die, cu, &high))
15504         {
15505           /* If bounds are constant do the final calculation here.  */
15506           if (low.kind == PROP_CONST && high.kind == PROP_CONST)
15507             high.data.const_val = low.data.const_val + high.data.const_val - 1;
15508           else
15509             high_bound_is_count = 1;
15510         }
15511     }
15512
15513   /* Dwarf-2 specifications explicitly allows to create subrange types
15514      without specifying a base type.
15515      In that case, the base type must be set to the type of
15516      the lower bound, upper bound or count, in that order, if any of these
15517      three attributes references an object that has a type.
15518      If no base type is found, the Dwarf-2 specifications say that
15519      a signed integer type of size equal to the size of an address should
15520      be used.
15521      For the following C code: `extern char gdb_int [];'
15522      GCC produces an empty range DIE.
15523      FIXME: muller/2010-05-28: Possible references to object for low bound,
15524      high bound or count are not yet handled by this code.  */
15525   if (TYPE_CODE (base_type) == TYPE_CODE_VOID)
15526     {
15527       struct objfile *objfile = cu->objfile;
15528       struct gdbarch *gdbarch = get_objfile_arch (objfile);
15529       int addr_size = gdbarch_addr_bit (gdbarch) /8;
15530       struct type *int_type = objfile_type (objfile)->builtin_int;
15531
15532       /* Test "int", "long int", and "long long int" objfile types,
15533          and select the first one having a size above or equal to the
15534          architecture address size.  */
15535       if (int_type && TYPE_LENGTH (int_type) >= addr_size)
15536         base_type = int_type;
15537       else
15538         {
15539           int_type = objfile_type (objfile)->builtin_long;
15540           if (int_type && TYPE_LENGTH (int_type) >= addr_size)
15541             base_type = int_type;
15542           else
15543             {
15544               int_type = objfile_type (objfile)->builtin_long_long;
15545               if (int_type && TYPE_LENGTH (int_type) >= addr_size)
15546                 base_type = int_type;
15547             }
15548         }
15549     }
15550
15551   /* Normally, the DWARF producers are expected to use a signed
15552      constant form (Eg. DW_FORM_sdata) to express negative bounds.
15553      But this is unfortunately not always the case, as witnessed
15554      with GCC, for instance, where the ambiguous DW_FORM_dataN form
15555      is used instead.  To work around that ambiguity, we treat
15556      the bounds as signed, and thus sign-extend their values, when
15557      the base type is signed.  */
15558   negative_mask =
15559     -((LONGEST) 1 << (TYPE_LENGTH (base_type) * TARGET_CHAR_BIT - 1));
15560   if (low.kind == PROP_CONST
15561       && !TYPE_UNSIGNED (base_type) && (low.data.const_val & negative_mask))
15562     low.data.const_val |= negative_mask;
15563   if (high.kind == PROP_CONST
15564       && !TYPE_UNSIGNED (base_type) && (high.data.const_val & negative_mask))
15565     high.data.const_val |= negative_mask;
15566
15567   range_type = create_range_type (NULL, orig_base_type, &low, &high);
15568
15569   if (high_bound_is_count)
15570     TYPE_RANGE_DATA (range_type)->flag_upper_bound_is_count = 1;
15571
15572   /* Ada expects an empty array on no boundary attributes.  */
15573   if (attr == NULL && cu->language != language_ada)
15574     TYPE_HIGH_BOUND_KIND (range_type) = PROP_UNDEFINED;
15575
15576   name = dwarf2_name (die, cu);
15577   if (name)
15578     TYPE_NAME (range_type) = name;
15579
15580   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
15581   if (attr)
15582     TYPE_LENGTH (range_type) = DW_UNSND (attr);
15583
15584   set_die_type (die, range_type, cu);
15585
15586   /* set_die_type should be already done.  */
15587   set_descriptive_type (range_type, die, cu);
15588
15589   return range_type;
15590 }
15591
15592 static struct type *
15593 read_unspecified_type (struct die_info *die, struct dwarf2_cu *cu)
15594 {
15595   struct type *type;
15596
15597   /* For now, we only support the C meaning of an unspecified type: void.  */
15598
15599   type = init_type (cu->objfile, TYPE_CODE_VOID, 0, NULL);
15600   TYPE_NAME (type) = dwarf2_name (die, cu);
15601
15602   return set_die_type (die, type, cu);
15603 }
15604
15605 /* Read a single die and all its descendents.  Set the die's sibling
15606    field to NULL; set other fields in the die correctly, and set all
15607    of the descendents' fields correctly.  Set *NEW_INFO_PTR to the
15608    location of the info_ptr after reading all of those dies.  PARENT
15609    is the parent of the die in question.  */
15610
15611 static struct die_info *
15612 read_die_and_children (const struct die_reader_specs *reader,
15613                        const gdb_byte *info_ptr,
15614                        const gdb_byte **new_info_ptr,
15615                        struct die_info *parent)
15616 {
15617   struct die_info *die;
15618   const gdb_byte *cur_ptr;
15619   int has_children;
15620
15621   cur_ptr = read_full_die_1 (reader, &die, info_ptr, &has_children, 0);
15622   if (die == NULL)
15623     {
15624       *new_info_ptr = cur_ptr;
15625       return NULL;
15626     }
15627   store_in_ref_table (die, reader->cu);
15628
15629   if (has_children)
15630     die->child = read_die_and_siblings_1 (reader, cur_ptr, new_info_ptr, die);
15631   else
15632     {
15633       die->child = NULL;
15634       *new_info_ptr = cur_ptr;
15635     }
15636
15637   die->sibling = NULL;
15638   die->parent = parent;
15639   return die;
15640 }
15641
15642 /* Read a die, all of its descendents, and all of its siblings; set
15643    all of the fields of all of the dies correctly.  Arguments are as
15644    in read_die_and_children.  */
15645
15646 static struct die_info *
15647 read_die_and_siblings_1 (const struct die_reader_specs *reader,
15648                          const gdb_byte *info_ptr,
15649                          const gdb_byte **new_info_ptr,
15650                          struct die_info *parent)
15651 {
15652   struct die_info *first_die, *last_sibling;
15653   const gdb_byte *cur_ptr;
15654
15655   cur_ptr = info_ptr;
15656   first_die = last_sibling = NULL;
15657
15658   while (1)
15659     {
15660       struct die_info *die
15661         = read_die_and_children (reader, cur_ptr, &cur_ptr, parent);
15662
15663       if (die == NULL)
15664         {
15665           *new_info_ptr = cur_ptr;
15666           return first_die;
15667         }
15668
15669       if (!first_die)
15670         first_die = die;
15671       else
15672         last_sibling->sibling = die;
15673
15674       last_sibling = die;
15675     }
15676 }
15677
15678 /* Read a die, all of its descendents, and all of its siblings; set
15679    all of the fields of all of the dies correctly.  Arguments are as
15680    in read_die_and_children.
15681    This the main entry point for reading a DIE and all its children.  */
15682
15683 static struct die_info *
15684 read_die_and_siblings (const struct die_reader_specs *reader,
15685                        const gdb_byte *info_ptr,
15686                        const gdb_byte **new_info_ptr,
15687                        struct die_info *parent)
15688 {
15689   struct die_info *die = read_die_and_siblings_1 (reader, info_ptr,
15690                                                   new_info_ptr, parent);
15691
15692   if (dwarf_die_debug)
15693     {
15694       fprintf_unfiltered (gdb_stdlog,
15695                           "Read die from %s@0x%x of %s:\n",
15696                           get_section_name (reader->die_section),
15697                           (unsigned) (info_ptr - reader->die_section->buffer),
15698                           bfd_get_filename (reader->abfd));
15699       dump_die (die, dwarf_die_debug);
15700     }
15701
15702   return die;
15703 }
15704
15705 /* Read a die and all its attributes, leave space for NUM_EXTRA_ATTRS
15706    attributes.
15707    The caller is responsible for filling in the extra attributes
15708    and updating (*DIEP)->num_attrs.
15709    Set DIEP to point to a newly allocated die with its information,
15710    except for its child, sibling, and parent fields.
15711    Set HAS_CHILDREN to tell whether the die has children or not.  */
15712
15713 static const gdb_byte *
15714 read_full_die_1 (const struct die_reader_specs *reader,
15715                  struct die_info **diep, const gdb_byte *info_ptr,
15716                  int *has_children, int num_extra_attrs)
15717 {
15718   unsigned int abbrev_number, bytes_read, i;
15719   struct abbrev_info *abbrev;
15720   struct die_info *die;
15721   struct dwarf2_cu *cu = reader->cu;
15722   bfd *abfd = reader->abfd;
15723
15724   sect_offset sect_off = (sect_offset) (info_ptr - reader->buffer);
15725   abbrev_number = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
15726   info_ptr += bytes_read;
15727   if (!abbrev_number)
15728     {
15729       *diep = NULL;
15730       *has_children = 0;
15731       return info_ptr;
15732     }
15733
15734   abbrev = abbrev_table_lookup_abbrev (cu->abbrev_table, abbrev_number);
15735   if (!abbrev)
15736     error (_("Dwarf Error: could not find abbrev number %d [in module %s]"),
15737            abbrev_number,
15738            bfd_get_filename (abfd));
15739
15740   die = dwarf_alloc_die (cu, abbrev->num_attrs + num_extra_attrs);
15741   die->sect_off = sect_off;
15742   die->tag = abbrev->tag;
15743   die->abbrev = abbrev_number;
15744
15745   /* Make the result usable.
15746      The caller needs to update num_attrs after adding the extra
15747      attributes.  */
15748   die->num_attrs = abbrev->num_attrs;
15749
15750   for (i = 0; i < abbrev->num_attrs; ++i)
15751     info_ptr = read_attribute (reader, &die->attrs[i], &abbrev->attrs[i],
15752                                info_ptr);
15753
15754   *diep = die;
15755   *has_children = abbrev->has_children;
15756   return info_ptr;
15757 }
15758
15759 /* Read a die and all its attributes.
15760    Set DIEP to point to a newly allocated die with its information,
15761    except for its child, sibling, and parent fields.
15762    Set HAS_CHILDREN to tell whether the die has children or not.  */
15763
15764 static const gdb_byte *
15765 read_full_die (const struct die_reader_specs *reader,
15766                struct die_info **diep, const gdb_byte *info_ptr,
15767                int *has_children)
15768 {
15769   const gdb_byte *result;
15770
15771   result = read_full_die_1 (reader, diep, info_ptr, has_children, 0);
15772
15773   if (dwarf_die_debug)
15774     {
15775       fprintf_unfiltered (gdb_stdlog,
15776                           "Read die from %s@0x%x of %s:\n",
15777                           get_section_name (reader->die_section),
15778                           (unsigned) (info_ptr - reader->die_section->buffer),
15779                           bfd_get_filename (reader->abfd));
15780       dump_die (*diep, dwarf_die_debug);
15781     }
15782
15783   return result;
15784 }
15785 \f
15786 /* Abbreviation tables.
15787
15788    In DWARF version 2, the description of the debugging information is
15789    stored in a separate .debug_abbrev section.  Before we read any
15790    dies from a section we read in all abbreviations and install them
15791    in a hash table.  */
15792
15793 /* Allocate space for a struct abbrev_info object in ABBREV_TABLE.  */
15794
15795 static struct abbrev_info *
15796 abbrev_table_alloc_abbrev (struct abbrev_table *abbrev_table)
15797 {
15798   struct abbrev_info *abbrev;
15799
15800   abbrev = XOBNEW (&abbrev_table->abbrev_obstack, struct abbrev_info);
15801   memset (abbrev, 0, sizeof (struct abbrev_info));
15802
15803   return abbrev;
15804 }
15805
15806 /* Add an abbreviation to the table.  */
15807
15808 static void
15809 abbrev_table_add_abbrev (struct abbrev_table *abbrev_table,
15810                          unsigned int abbrev_number,
15811                          struct abbrev_info *abbrev)
15812 {
15813   unsigned int hash_number;
15814
15815   hash_number = abbrev_number % ABBREV_HASH_SIZE;
15816   abbrev->next = abbrev_table->abbrevs[hash_number];
15817   abbrev_table->abbrevs[hash_number] = abbrev;
15818 }
15819
15820 /* Look up an abbrev in the table.
15821    Returns NULL if the abbrev is not found.  */
15822
15823 static struct abbrev_info *
15824 abbrev_table_lookup_abbrev (const struct abbrev_table *abbrev_table,
15825                             unsigned int abbrev_number)
15826 {
15827   unsigned int hash_number;
15828   struct abbrev_info *abbrev;
15829
15830   hash_number = abbrev_number % ABBREV_HASH_SIZE;
15831   abbrev = abbrev_table->abbrevs[hash_number];
15832
15833   while (abbrev)
15834     {
15835       if (abbrev->number == abbrev_number)
15836         return abbrev;
15837       abbrev = abbrev->next;
15838     }
15839   return NULL;
15840 }
15841
15842 /* Read in an abbrev table.  */
15843
15844 static struct abbrev_table *
15845 abbrev_table_read_table (struct dwarf2_section_info *section,
15846                          sect_offset sect_off)
15847 {
15848   struct objfile *objfile = dwarf2_per_objfile->objfile;
15849   bfd *abfd = get_section_bfd_owner (section);
15850   struct abbrev_table *abbrev_table;
15851   const gdb_byte *abbrev_ptr;
15852   struct abbrev_info *cur_abbrev;
15853   unsigned int abbrev_number, bytes_read, abbrev_name;
15854   unsigned int abbrev_form;
15855   struct attr_abbrev *cur_attrs;
15856   unsigned int allocated_attrs;
15857
15858   abbrev_table = XNEW (struct abbrev_table);
15859   abbrev_table->sect_off = sect_off;
15860   obstack_init (&abbrev_table->abbrev_obstack);
15861   abbrev_table->abbrevs =
15862     XOBNEWVEC (&abbrev_table->abbrev_obstack, struct abbrev_info *,
15863                ABBREV_HASH_SIZE);
15864   memset (abbrev_table->abbrevs, 0,
15865           ABBREV_HASH_SIZE * sizeof (struct abbrev_info *));
15866
15867   dwarf2_read_section (objfile, section);
15868   abbrev_ptr = section->buffer + to_underlying (sect_off);
15869   abbrev_number = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
15870   abbrev_ptr += bytes_read;
15871
15872   allocated_attrs = ATTR_ALLOC_CHUNK;
15873   cur_attrs = XNEWVEC (struct attr_abbrev, allocated_attrs);
15874
15875   /* Loop until we reach an abbrev number of 0.  */
15876   while (abbrev_number)
15877     {
15878       cur_abbrev = abbrev_table_alloc_abbrev (abbrev_table);
15879
15880       /* read in abbrev header */
15881       cur_abbrev->number = abbrev_number;
15882       cur_abbrev->tag
15883         = (enum dwarf_tag) read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
15884       abbrev_ptr += bytes_read;
15885       cur_abbrev->has_children = read_1_byte (abfd, abbrev_ptr);
15886       abbrev_ptr += 1;
15887
15888       /* now read in declarations */
15889       for (;;)
15890         {
15891           LONGEST implicit_const;
15892
15893           abbrev_name = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
15894           abbrev_ptr += bytes_read;
15895           abbrev_form = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
15896           abbrev_ptr += bytes_read;
15897           if (abbrev_form == DW_FORM_implicit_const)
15898             {
15899               implicit_const = read_signed_leb128 (abfd, abbrev_ptr,
15900                                                    &bytes_read);
15901               abbrev_ptr += bytes_read;
15902             }
15903           else
15904             {
15905               /* Initialize it due to a false compiler warning.  */
15906               implicit_const = -1;
15907             }
15908
15909           if (abbrev_name == 0)
15910             break;
15911
15912           if (cur_abbrev->num_attrs == allocated_attrs)
15913             {
15914               allocated_attrs += ATTR_ALLOC_CHUNK;
15915               cur_attrs
15916                 = XRESIZEVEC (struct attr_abbrev, cur_attrs, allocated_attrs);
15917             }
15918
15919           cur_attrs[cur_abbrev->num_attrs].name
15920             = (enum dwarf_attribute) abbrev_name;
15921           cur_attrs[cur_abbrev->num_attrs].form
15922             = (enum dwarf_form) abbrev_form;
15923           cur_attrs[cur_abbrev->num_attrs].implicit_const = implicit_const;
15924           ++cur_abbrev->num_attrs;
15925         }
15926
15927       cur_abbrev->attrs =
15928         XOBNEWVEC (&abbrev_table->abbrev_obstack, struct attr_abbrev,
15929                    cur_abbrev->num_attrs);
15930       memcpy (cur_abbrev->attrs, cur_attrs,
15931               cur_abbrev->num_attrs * sizeof (struct attr_abbrev));
15932
15933       abbrev_table_add_abbrev (abbrev_table, abbrev_number, cur_abbrev);
15934
15935       /* Get next abbreviation.
15936          Under Irix6 the abbreviations for a compilation unit are not
15937          always properly terminated with an abbrev number of 0.
15938          Exit loop if we encounter an abbreviation which we have
15939          already read (which means we are about to read the abbreviations
15940          for the next compile unit) or if the end of the abbreviation
15941          table is reached.  */
15942       if ((unsigned int) (abbrev_ptr - section->buffer) >= section->size)
15943         break;
15944       abbrev_number = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
15945       abbrev_ptr += bytes_read;
15946       if (abbrev_table_lookup_abbrev (abbrev_table, abbrev_number) != NULL)
15947         break;
15948     }
15949
15950   xfree (cur_attrs);
15951   return abbrev_table;
15952 }
15953
15954 /* Free the resources held by ABBREV_TABLE.  */
15955
15956 static void
15957 abbrev_table_free (struct abbrev_table *abbrev_table)
15958 {
15959   obstack_free (&abbrev_table->abbrev_obstack, NULL);
15960   xfree (abbrev_table);
15961 }
15962
15963 /* Same as abbrev_table_free but as a cleanup.
15964    We pass in a pointer to the pointer to the table so that we can
15965    set the pointer to NULL when we're done.  It also simplifies
15966    build_type_psymtabs_1.  */
15967
15968 static void
15969 abbrev_table_free_cleanup (void *table_ptr)
15970 {
15971   struct abbrev_table **abbrev_table_ptr = (struct abbrev_table **) table_ptr;
15972
15973   if (*abbrev_table_ptr != NULL)
15974     abbrev_table_free (*abbrev_table_ptr);
15975   *abbrev_table_ptr = NULL;
15976 }
15977
15978 /* Read the abbrev table for CU from ABBREV_SECTION.  */
15979
15980 static void
15981 dwarf2_read_abbrevs (struct dwarf2_cu *cu,
15982                      struct dwarf2_section_info *abbrev_section)
15983 {
15984   cu->abbrev_table =
15985     abbrev_table_read_table (abbrev_section, cu->header.abbrev_sect_off);
15986 }
15987
15988 /* Release the memory used by the abbrev table for a compilation unit.  */
15989
15990 static void
15991 dwarf2_free_abbrev_table (void *ptr_to_cu)
15992 {
15993   struct dwarf2_cu *cu = (struct dwarf2_cu *) ptr_to_cu;
15994
15995   if (cu->abbrev_table != NULL)
15996     abbrev_table_free (cu->abbrev_table);
15997   /* Set this to NULL so that we SEGV if we try to read it later,
15998      and also because free_comp_unit verifies this is NULL.  */
15999   cu->abbrev_table = NULL;
16000 }
16001 \f
16002 /* Returns nonzero if TAG represents a type that we might generate a partial
16003    symbol for.  */
16004
16005 static int
16006 is_type_tag_for_partial (int tag)
16007 {
16008   switch (tag)
16009     {
16010 #if 0
16011     /* Some types that would be reasonable to generate partial symbols for,
16012        that we don't at present.  */
16013     case DW_TAG_array_type:
16014     case DW_TAG_file_type:
16015     case DW_TAG_ptr_to_member_type:
16016     case DW_TAG_set_type:
16017     case DW_TAG_string_type:
16018     case DW_TAG_subroutine_type:
16019 #endif
16020     case DW_TAG_base_type:
16021     case DW_TAG_class_type:
16022     case DW_TAG_interface_type:
16023     case DW_TAG_enumeration_type:
16024     case DW_TAG_structure_type:
16025     case DW_TAG_subrange_type:
16026     case DW_TAG_typedef:
16027     case DW_TAG_union_type:
16028       return 1;
16029     default:
16030       return 0;
16031     }
16032 }
16033
16034 /* Load all DIEs that are interesting for partial symbols into memory.  */
16035
16036 static struct partial_die_info *
16037 load_partial_dies (const struct die_reader_specs *reader,
16038                    const gdb_byte *info_ptr, int building_psymtab)
16039 {
16040   struct dwarf2_cu *cu = reader->cu;
16041   struct objfile *objfile = cu->objfile;
16042   struct partial_die_info *part_die;
16043   struct partial_die_info *parent_die, *last_die, *first_die = NULL;
16044   struct abbrev_info *abbrev;
16045   unsigned int bytes_read;
16046   unsigned int load_all = 0;
16047   int nesting_level = 1;
16048
16049   parent_die = NULL;
16050   last_die = NULL;
16051
16052   gdb_assert (cu->per_cu != NULL);
16053   if (cu->per_cu->load_all_dies)
16054     load_all = 1;
16055
16056   cu->partial_dies
16057     = htab_create_alloc_ex (cu->header.length / 12,
16058                             partial_die_hash,
16059                             partial_die_eq,
16060                             NULL,
16061                             &cu->comp_unit_obstack,
16062                             hashtab_obstack_allocate,
16063                             dummy_obstack_deallocate);
16064
16065   part_die = XOBNEW (&cu->comp_unit_obstack, struct partial_die_info);
16066
16067   while (1)
16068     {
16069       abbrev = peek_die_abbrev (info_ptr, &bytes_read, cu);
16070
16071       /* A NULL abbrev means the end of a series of children.  */
16072       if (abbrev == NULL)
16073         {
16074           if (--nesting_level == 0)
16075             {
16076               /* PART_DIE was probably the last thing allocated on the
16077                  comp_unit_obstack, so we could call obstack_free
16078                  here.  We don't do that because the waste is small,
16079                  and will be cleaned up when we're done with this
16080                  compilation unit.  This way, we're also more robust
16081                  against other users of the comp_unit_obstack.  */
16082               return first_die;
16083             }
16084           info_ptr += bytes_read;
16085           last_die = parent_die;
16086           parent_die = parent_die->die_parent;
16087           continue;
16088         }
16089
16090       /* Check for template arguments.  We never save these; if
16091          they're seen, we just mark the parent, and go on our way.  */
16092       if (parent_die != NULL
16093           && cu->language == language_cplus
16094           && (abbrev->tag == DW_TAG_template_type_param
16095               || abbrev->tag == DW_TAG_template_value_param))
16096         {
16097           parent_die->has_template_arguments = 1;
16098
16099           if (!load_all)
16100             {
16101               /* We don't need a partial DIE for the template argument.  */
16102               info_ptr = skip_one_die (reader, info_ptr + bytes_read, abbrev);
16103               continue;
16104             }
16105         }
16106
16107       /* We only recurse into c++ subprograms looking for template arguments.
16108          Skip their other children.  */
16109       if (!load_all
16110           && cu->language == language_cplus
16111           && parent_die != NULL
16112           && parent_die->tag == DW_TAG_subprogram)
16113         {
16114           info_ptr = skip_one_die (reader, info_ptr + bytes_read, abbrev);
16115           continue;
16116         }
16117
16118       /* Check whether this DIE is interesting enough to save.  Normally
16119          we would not be interested in members here, but there may be
16120          later variables referencing them via DW_AT_specification (for
16121          static members).  */
16122       if (!load_all
16123           && !is_type_tag_for_partial (abbrev->tag)
16124           && abbrev->tag != DW_TAG_constant
16125           && abbrev->tag != DW_TAG_enumerator
16126           && abbrev->tag != DW_TAG_subprogram
16127           && abbrev->tag != DW_TAG_lexical_block
16128           && abbrev->tag != DW_TAG_variable
16129           && abbrev->tag != DW_TAG_namespace
16130           && abbrev->tag != DW_TAG_module
16131           && abbrev->tag != DW_TAG_member
16132           && abbrev->tag != DW_TAG_imported_unit
16133           && abbrev->tag != DW_TAG_imported_declaration)
16134         {
16135           /* Otherwise we skip to the next sibling, if any.  */
16136           info_ptr = skip_one_die (reader, info_ptr + bytes_read, abbrev);
16137           continue;
16138         }
16139
16140       info_ptr = read_partial_die (reader, part_die, abbrev, bytes_read,
16141                                    info_ptr);
16142
16143       /* This two-pass algorithm for processing partial symbols has a
16144          high cost in cache pressure.  Thus, handle some simple cases
16145          here which cover the majority of C partial symbols.  DIEs
16146          which neither have specification tags in them, nor could have
16147          specification tags elsewhere pointing at them, can simply be
16148          processed and discarded.
16149
16150          This segment is also optional; scan_partial_symbols and
16151          add_partial_symbol will handle these DIEs if we chain
16152          them in normally.  When compilers which do not emit large
16153          quantities of duplicate debug information are more common,
16154          this code can probably be removed.  */
16155
16156       /* Any complete simple types at the top level (pretty much all
16157          of them, for a language without namespaces), can be processed
16158          directly.  */
16159       if (parent_die == NULL
16160           && part_die->has_specification == 0
16161           && part_die->is_declaration == 0
16162           && ((part_die->tag == DW_TAG_typedef && !part_die->has_children)
16163               || part_die->tag == DW_TAG_base_type
16164               || part_die->tag == DW_TAG_subrange_type))
16165         {
16166           if (building_psymtab && part_die->name != NULL)
16167             add_psymbol_to_list (part_die->name, strlen (part_die->name), 0,
16168                                  VAR_DOMAIN, LOC_TYPEDEF,
16169                                  &objfile->static_psymbols,
16170                                  0, cu->language, objfile);
16171           info_ptr = locate_pdi_sibling (reader, part_die, info_ptr);
16172           continue;
16173         }
16174
16175       /* The exception for DW_TAG_typedef with has_children above is
16176          a workaround of GCC PR debug/47510.  In the case of this complaint
16177          type_name_no_tag_or_error will error on such types later.
16178
16179          GDB skipped children of DW_TAG_typedef by the shortcut above and then
16180          it could not find the child DIEs referenced later, this is checked
16181          above.  In correct DWARF DW_TAG_typedef should have no children.  */
16182
16183       if (part_die->tag == DW_TAG_typedef && part_die->has_children)
16184         complaint (&symfile_complaints,
16185                    _("DW_TAG_typedef has childen - GCC PR debug/47510 bug "
16186                      "- DIE at 0x%x [in module %s]"),
16187                    to_underlying (part_die->sect_off), objfile_name (objfile));
16188
16189       /* If we're at the second level, and we're an enumerator, and
16190          our parent has no specification (meaning possibly lives in a
16191          namespace elsewhere), then we can add the partial symbol now
16192          instead of queueing it.  */
16193       if (part_die->tag == DW_TAG_enumerator
16194           && parent_die != NULL
16195           && parent_die->die_parent == NULL
16196           && parent_die->tag == DW_TAG_enumeration_type
16197           && parent_die->has_specification == 0)
16198         {
16199           if (part_die->name == NULL)
16200             complaint (&symfile_complaints,
16201                        _("malformed enumerator DIE ignored"));
16202           else if (building_psymtab)
16203             add_psymbol_to_list (part_die->name, strlen (part_die->name), 0,
16204                                  VAR_DOMAIN, LOC_CONST,
16205                                  cu->language == language_cplus
16206                                  ? &objfile->global_psymbols
16207                                  : &objfile->static_psymbols,
16208                                  0, cu->language, objfile);
16209
16210           info_ptr = locate_pdi_sibling (reader, part_die, info_ptr);
16211           continue;
16212         }
16213
16214       /* We'll save this DIE so link it in.  */
16215       part_die->die_parent = parent_die;
16216       part_die->die_sibling = NULL;
16217       part_die->die_child = NULL;
16218
16219       if (last_die && last_die == parent_die)
16220         last_die->die_child = part_die;
16221       else if (last_die)
16222         last_die->die_sibling = part_die;
16223
16224       last_die = part_die;
16225
16226       if (first_die == NULL)
16227         first_die = part_die;
16228
16229       /* Maybe add the DIE to the hash table.  Not all DIEs that we
16230          find interesting need to be in the hash table, because we
16231          also have the parent/sibling/child chains; only those that we
16232          might refer to by offset later during partial symbol reading.
16233
16234          For now this means things that might have be the target of a
16235          DW_AT_specification, DW_AT_abstract_origin, or
16236          DW_AT_extension.  DW_AT_extension will refer only to
16237          namespaces; DW_AT_abstract_origin refers to functions (and
16238          many things under the function DIE, but we do not recurse
16239          into function DIEs during partial symbol reading) and
16240          possibly variables as well; DW_AT_specification refers to
16241          declarations.  Declarations ought to have the DW_AT_declaration
16242          flag.  It happens that GCC forgets to put it in sometimes, but
16243          only for functions, not for types.
16244
16245          Adding more things than necessary to the hash table is harmless
16246          except for the performance cost.  Adding too few will result in
16247          wasted time in find_partial_die, when we reread the compilation
16248          unit with load_all_dies set.  */
16249
16250       if (load_all
16251           || abbrev->tag == DW_TAG_constant
16252           || abbrev->tag == DW_TAG_subprogram
16253           || abbrev->tag == DW_TAG_variable
16254           || abbrev->tag == DW_TAG_namespace
16255           || part_die->is_declaration)
16256         {
16257           void **slot;
16258
16259           slot = htab_find_slot_with_hash (cu->partial_dies, part_die,
16260                                            to_underlying (part_die->sect_off),
16261                                            INSERT);
16262           *slot = part_die;
16263         }
16264
16265       part_die = XOBNEW (&cu->comp_unit_obstack, struct partial_die_info);
16266
16267       /* For some DIEs we want to follow their children (if any).  For C
16268          we have no reason to follow the children of structures; for other
16269          languages we have to, so that we can get at method physnames
16270          to infer fully qualified class names, for DW_AT_specification,
16271          and for C++ template arguments.  For C++, we also look one level
16272          inside functions to find template arguments (if the name of the
16273          function does not already contain the template arguments).
16274
16275          For Ada, we need to scan the children of subprograms and lexical
16276          blocks as well because Ada allows the definition of nested
16277          entities that could be interesting for the debugger, such as
16278          nested subprograms for instance.  */
16279       if (last_die->has_children
16280           && (load_all
16281               || last_die->tag == DW_TAG_namespace
16282               || last_die->tag == DW_TAG_module
16283               || last_die->tag == DW_TAG_enumeration_type
16284               || (cu->language == language_cplus
16285                   && last_die->tag == DW_TAG_subprogram
16286                   && (last_die->name == NULL
16287                       || strchr (last_die->name, '<') == NULL))
16288               || (cu->language != language_c
16289                   && (last_die->tag == DW_TAG_class_type
16290                       || last_die->tag == DW_TAG_interface_type
16291                       || last_die->tag == DW_TAG_structure_type
16292                       || last_die->tag == DW_TAG_union_type))
16293               || (cu->language == language_ada
16294                   && (last_die->tag == DW_TAG_subprogram
16295                       || last_die->tag == DW_TAG_lexical_block))))
16296         {
16297           nesting_level++;
16298           parent_die = last_die;
16299           continue;
16300         }
16301
16302       /* Otherwise we skip to the next sibling, if any.  */
16303       info_ptr = locate_pdi_sibling (reader, last_die, info_ptr);
16304
16305       /* Back to the top, do it again.  */
16306     }
16307 }
16308
16309 /* Read a minimal amount of information into the minimal die structure.  */
16310
16311 static const gdb_byte *
16312 read_partial_die (const struct die_reader_specs *reader,
16313                   struct partial_die_info *part_die,
16314                   struct abbrev_info *abbrev, unsigned int abbrev_len,
16315                   const gdb_byte *info_ptr)
16316 {
16317   struct dwarf2_cu *cu = reader->cu;
16318   struct objfile *objfile = cu->objfile;
16319   const gdb_byte *buffer = reader->buffer;
16320   unsigned int i;
16321   struct attribute attr;
16322   int has_low_pc_attr = 0;
16323   int has_high_pc_attr = 0;
16324   int high_pc_relative = 0;
16325
16326   memset (part_die, 0, sizeof (struct partial_die_info));
16327
16328   part_die->sect_off = (sect_offset) (info_ptr - buffer);
16329
16330   info_ptr += abbrev_len;
16331
16332   if (abbrev == NULL)
16333     return info_ptr;
16334
16335   part_die->tag = abbrev->tag;
16336   part_die->has_children = abbrev->has_children;
16337
16338   for (i = 0; i < abbrev->num_attrs; ++i)
16339     {
16340       info_ptr = read_attribute (reader, &attr, &abbrev->attrs[i], info_ptr);
16341
16342       /* Store the data if it is of an attribute we want to keep in a
16343          partial symbol table.  */
16344       switch (attr.name)
16345         {
16346         case DW_AT_name:
16347           switch (part_die->tag)
16348             {
16349             case DW_TAG_compile_unit:
16350             case DW_TAG_partial_unit:
16351             case DW_TAG_type_unit:
16352               /* Compilation units have a DW_AT_name that is a filename, not
16353                  a source language identifier.  */
16354             case DW_TAG_enumeration_type:
16355             case DW_TAG_enumerator:
16356               /* These tags always have simple identifiers already; no need
16357                  to canonicalize them.  */
16358               part_die->name = DW_STRING (&attr);
16359               break;
16360             default:
16361               part_die->name
16362                 = dwarf2_canonicalize_name (DW_STRING (&attr), cu,
16363                                             &objfile->per_bfd->storage_obstack);
16364               break;
16365             }
16366           break;
16367         case DW_AT_linkage_name:
16368         case DW_AT_MIPS_linkage_name:
16369           /* Note that both forms of linkage name might appear.  We
16370              assume they will be the same, and we only store the last
16371              one we see.  */
16372           if (cu->language == language_ada)
16373             part_die->name = DW_STRING (&attr);
16374           part_die->linkage_name = DW_STRING (&attr);
16375           break;
16376         case DW_AT_low_pc:
16377           has_low_pc_attr = 1;
16378           part_die->lowpc = attr_value_as_address (&attr);
16379           break;
16380         case DW_AT_high_pc:
16381           has_high_pc_attr = 1;
16382           part_die->highpc = attr_value_as_address (&attr);
16383           if (cu->header.version >= 4 && attr_form_is_constant (&attr))
16384                 high_pc_relative = 1;
16385           break;
16386         case DW_AT_location:
16387           /* Support the .debug_loc offsets.  */
16388           if (attr_form_is_block (&attr))
16389             {
16390                part_die->d.locdesc = DW_BLOCK (&attr);
16391             }
16392           else if (attr_form_is_section_offset (&attr))
16393             {
16394               dwarf2_complex_location_expr_complaint ();
16395             }
16396           else
16397             {
16398               dwarf2_invalid_attrib_class_complaint ("DW_AT_location",
16399                                                      "partial symbol information");
16400             }
16401           break;
16402         case DW_AT_external:
16403           part_die->is_external = DW_UNSND (&attr);
16404           break;
16405         case DW_AT_declaration:
16406           part_die->is_declaration = DW_UNSND (&attr);
16407           break;
16408         case DW_AT_type:
16409           part_die->has_type = 1;
16410           break;
16411         case DW_AT_abstract_origin:
16412         case DW_AT_specification:
16413         case DW_AT_extension:
16414           part_die->has_specification = 1;
16415           part_die->spec_offset = dwarf2_get_ref_die_offset (&attr);
16416           part_die->spec_is_dwz = (attr.form == DW_FORM_GNU_ref_alt
16417                                    || cu->per_cu->is_dwz);
16418           break;
16419         case DW_AT_sibling:
16420           /* Ignore absolute siblings, they might point outside of
16421              the current compile unit.  */
16422           if (attr.form == DW_FORM_ref_addr)
16423             complaint (&symfile_complaints,
16424                        _("ignoring absolute DW_AT_sibling"));
16425           else
16426             {
16427               sect_offset off = dwarf2_get_ref_die_offset (&attr);
16428               const gdb_byte *sibling_ptr = buffer + to_underlying (off);
16429
16430               if (sibling_ptr < info_ptr)
16431                 complaint (&symfile_complaints,
16432                            _("DW_AT_sibling points backwards"));
16433               else if (sibling_ptr > reader->buffer_end)
16434                 dwarf2_section_buffer_overflow_complaint (reader->die_section);
16435               else
16436                 part_die->sibling = sibling_ptr;
16437             }
16438           break;
16439         case DW_AT_byte_size:
16440           part_die->has_byte_size = 1;
16441           break;
16442         case DW_AT_const_value:
16443           part_die->has_const_value = 1;
16444           break;
16445         case DW_AT_calling_convention:
16446           /* DWARF doesn't provide a way to identify a program's source-level
16447              entry point.  DW_AT_calling_convention attributes are only meant
16448              to describe functions' calling conventions.
16449
16450              However, because it's a necessary piece of information in
16451              Fortran, and before DWARF 4 DW_CC_program was the only
16452              piece of debugging information whose definition refers to
16453              a 'main program' at all, several compilers marked Fortran
16454              main programs with DW_CC_program --- even when those
16455              functions use the standard calling conventions.
16456
16457              Although DWARF now specifies a way to provide this
16458              information, we support this practice for backward
16459              compatibility.  */
16460           if (DW_UNSND (&attr) == DW_CC_program
16461               && cu->language == language_fortran)
16462             part_die->main_subprogram = 1;
16463           break;
16464         case DW_AT_inline:
16465           if (DW_UNSND (&attr) == DW_INL_inlined
16466               || DW_UNSND (&attr) == DW_INL_declared_inlined)
16467             part_die->may_be_inlined = 1;
16468           break;
16469
16470         case DW_AT_import:
16471           if (part_die->tag == DW_TAG_imported_unit)
16472             {
16473               part_die->d.sect_off = dwarf2_get_ref_die_offset (&attr);
16474               part_die->is_dwz = (attr.form == DW_FORM_GNU_ref_alt
16475                                   || cu->per_cu->is_dwz);
16476             }
16477           break;
16478
16479         case DW_AT_main_subprogram:
16480           part_die->main_subprogram = DW_UNSND (&attr);
16481           break;
16482
16483         default:
16484           break;
16485         }
16486     }
16487
16488   if (high_pc_relative)
16489     part_die->highpc += part_die->lowpc;
16490
16491   if (has_low_pc_attr && has_high_pc_attr)
16492     {
16493       /* When using the GNU linker, .gnu.linkonce. sections are used to
16494          eliminate duplicate copies of functions and vtables and such.
16495          The linker will arbitrarily choose one and discard the others.
16496          The AT_*_pc values for such functions refer to local labels in
16497          these sections.  If the section from that file was discarded, the
16498          labels are not in the output, so the relocs get a value of 0.
16499          If this is a discarded function, mark the pc bounds as invalid,
16500          so that GDB will ignore it.  */
16501       if (part_die->lowpc == 0 && !dwarf2_per_objfile->has_section_at_zero)
16502         {
16503           struct gdbarch *gdbarch = get_objfile_arch (objfile);
16504
16505           complaint (&symfile_complaints,
16506                      _("DW_AT_low_pc %s is zero "
16507                        "for DIE at 0x%x [in module %s]"),
16508                      paddress (gdbarch, part_die->lowpc),
16509                      to_underlying (part_die->sect_off), objfile_name (objfile));
16510         }
16511       /* dwarf2_get_pc_bounds has also the strict low < high requirement.  */
16512       else if (part_die->lowpc >= part_die->highpc)
16513         {
16514           struct gdbarch *gdbarch = get_objfile_arch (objfile);
16515
16516           complaint (&symfile_complaints,
16517                      _("DW_AT_low_pc %s is not < DW_AT_high_pc %s "
16518                        "for DIE at 0x%x [in module %s]"),
16519                      paddress (gdbarch, part_die->lowpc),
16520                      paddress (gdbarch, part_die->highpc),
16521                      to_underlying (part_die->sect_off),
16522                      objfile_name (objfile));
16523         }
16524       else
16525         part_die->has_pc_info = 1;
16526     }
16527
16528   return info_ptr;
16529 }
16530
16531 /* Find a cached partial DIE at OFFSET in CU.  */
16532
16533 static struct partial_die_info *
16534 find_partial_die_in_comp_unit (sect_offset sect_off, struct dwarf2_cu *cu)
16535 {
16536   struct partial_die_info *lookup_die = NULL;
16537   struct partial_die_info part_die;
16538
16539   part_die.sect_off = sect_off;
16540   lookup_die = ((struct partial_die_info *)
16541                 htab_find_with_hash (cu->partial_dies, &part_die,
16542                                      to_underlying (sect_off)));
16543
16544   return lookup_die;
16545 }
16546
16547 /* Find a partial DIE at OFFSET, which may or may not be in CU,
16548    except in the case of .debug_types DIEs which do not reference
16549    outside their CU (they do however referencing other types via
16550    DW_FORM_ref_sig8).  */
16551
16552 static struct partial_die_info *
16553 find_partial_die (sect_offset sect_off, int offset_in_dwz, struct dwarf2_cu *cu)
16554 {
16555   struct objfile *objfile = cu->objfile;
16556   struct dwarf2_per_cu_data *per_cu = NULL;
16557   struct partial_die_info *pd = NULL;
16558
16559   if (offset_in_dwz == cu->per_cu->is_dwz
16560       && offset_in_cu_p (&cu->header, sect_off))
16561     {
16562       pd = find_partial_die_in_comp_unit (sect_off, cu);
16563       if (pd != NULL)
16564         return pd;
16565       /* We missed recording what we needed.
16566          Load all dies and try again.  */
16567       per_cu = cu->per_cu;
16568     }
16569   else
16570     {
16571       /* TUs don't reference other CUs/TUs (except via type signatures).  */
16572       if (cu->per_cu->is_debug_types)
16573         {
16574           error (_("Dwarf Error: Type Unit at offset 0x%x contains"
16575                    " external reference to offset 0x%x [in module %s].\n"),
16576                  to_underlying (cu->header.sect_off), to_underlying (sect_off),
16577                  bfd_get_filename (objfile->obfd));
16578         }
16579       per_cu = dwarf2_find_containing_comp_unit (sect_off, offset_in_dwz,
16580                                                  objfile);
16581
16582       if (per_cu->cu == NULL || per_cu->cu->partial_dies == NULL)
16583         load_partial_comp_unit (per_cu);
16584
16585       per_cu->cu->last_used = 0;
16586       pd = find_partial_die_in_comp_unit (sect_off, per_cu->cu);
16587     }
16588
16589   /* If we didn't find it, and not all dies have been loaded,
16590      load them all and try again.  */
16591
16592   if (pd == NULL && per_cu->load_all_dies == 0)
16593     {
16594       per_cu->load_all_dies = 1;
16595
16596       /* This is nasty.  When we reread the DIEs, somewhere up the call chain
16597          THIS_CU->cu may already be in use.  So we can't just free it and
16598          replace its DIEs with the ones we read in.  Instead, we leave those
16599          DIEs alone (which can still be in use, e.g. in scan_partial_symbols),
16600          and clobber THIS_CU->cu->partial_dies with the hash table for the new
16601          set.  */
16602       load_partial_comp_unit (per_cu);
16603
16604       pd = find_partial_die_in_comp_unit (sect_off, per_cu->cu);
16605     }
16606
16607   if (pd == NULL)
16608     internal_error (__FILE__, __LINE__,
16609                     _("could not find partial DIE 0x%x "
16610                       "in cache [from module %s]\n"),
16611                     to_underlying (sect_off), bfd_get_filename (objfile->obfd));
16612   return pd;
16613 }
16614
16615 /* See if we can figure out if the class lives in a namespace.  We do
16616    this by looking for a member function; its demangled name will
16617    contain namespace info, if there is any.  */
16618
16619 static void
16620 guess_partial_die_structure_name (struct partial_die_info *struct_pdi,
16621                                   struct dwarf2_cu *cu)
16622 {
16623   /* NOTE: carlton/2003-10-07: Getting the info this way changes
16624      what template types look like, because the demangler
16625      frequently doesn't give the same name as the debug info.  We
16626      could fix this by only using the demangled name to get the
16627      prefix (but see comment in read_structure_type).  */
16628
16629   struct partial_die_info *real_pdi;
16630   struct partial_die_info *child_pdi;
16631
16632   /* If this DIE (this DIE's specification, if any) has a parent, then
16633      we should not do this.  We'll prepend the parent's fully qualified
16634      name when we create the partial symbol.  */
16635
16636   real_pdi = struct_pdi;
16637   while (real_pdi->has_specification)
16638     real_pdi = find_partial_die (real_pdi->spec_offset,
16639                                  real_pdi->spec_is_dwz, cu);
16640
16641   if (real_pdi->die_parent != NULL)
16642     return;
16643
16644   for (child_pdi = struct_pdi->die_child;
16645        child_pdi != NULL;
16646        child_pdi = child_pdi->die_sibling)
16647     {
16648       if (child_pdi->tag == DW_TAG_subprogram
16649           && child_pdi->linkage_name != NULL)
16650         {
16651           char *actual_class_name
16652             = language_class_name_from_physname (cu->language_defn,
16653                                                  child_pdi->linkage_name);
16654           if (actual_class_name != NULL)
16655             {
16656               struct_pdi->name
16657                 = ((const char *)
16658                    obstack_copy0 (&cu->objfile->per_bfd->storage_obstack,
16659                                   actual_class_name,
16660                                   strlen (actual_class_name)));
16661               xfree (actual_class_name);
16662             }
16663           break;
16664         }
16665     }
16666 }
16667
16668 /* Adjust PART_DIE before generating a symbol for it.  This function
16669    may set the is_external flag or change the DIE's name.  */
16670
16671 static void
16672 fixup_partial_die (struct partial_die_info *part_die,
16673                    struct dwarf2_cu *cu)
16674 {
16675   /* Once we've fixed up a die, there's no point in doing so again.
16676      This also avoids a memory leak if we were to call
16677      guess_partial_die_structure_name multiple times.  */
16678   if (part_die->fixup_called)
16679     return;
16680
16681   /* If we found a reference attribute and the DIE has no name, try
16682      to find a name in the referred to DIE.  */
16683
16684   if (part_die->name == NULL && part_die->has_specification)
16685     {
16686       struct partial_die_info *spec_die;
16687
16688       spec_die = find_partial_die (part_die->spec_offset,
16689                                    part_die->spec_is_dwz, cu);
16690
16691       fixup_partial_die (spec_die, cu);
16692
16693       if (spec_die->name)
16694         {
16695           part_die->name = spec_die->name;
16696
16697           /* Copy DW_AT_external attribute if it is set.  */
16698           if (spec_die->is_external)
16699             part_die->is_external = spec_die->is_external;
16700         }
16701     }
16702
16703   /* Set default names for some unnamed DIEs.  */
16704
16705   if (part_die->name == NULL && part_die->tag == DW_TAG_namespace)
16706     part_die->name = CP_ANONYMOUS_NAMESPACE_STR;
16707
16708   /* If there is no parent die to provide a namespace, and there are
16709      children, see if we can determine the namespace from their linkage
16710      name.  */
16711   if (cu->language == language_cplus
16712       && !VEC_empty (dwarf2_section_info_def, dwarf2_per_objfile->types)
16713       && part_die->die_parent == NULL
16714       && part_die->has_children
16715       && (part_die->tag == DW_TAG_class_type
16716           || part_die->tag == DW_TAG_structure_type
16717           || part_die->tag == DW_TAG_union_type))
16718     guess_partial_die_structure_name (part_die, cu);
16719
16720   /* GCC might emit a nameless struct or union that has a linkage
16721      name.  See http://gcc.gnu.org/bugzilla/show_bug.cgi?id=47510.  */
16722   if (part_die->name == NULL
16723       && (part_die->tag == DW_TAG_class_type
16724           || part_die->tag == DW_TAG_interface_type
16725           || part_die->tag == DW_TAG_structure_type
16726           || part_die->tag == DW_TAG_union_type)
16727       && part_die->linkage_name != NULL)
16728     {
16729       char *demangled;
16730
16731       demangled = gdb_demangle (part_die->linkage_name, DMGL_TYPES);
16732       if (demangled)
16733         {
16734           const char *base;
16735
16736           /* Strip any leading namespaces/classes, keep only the base name.
16737              DW_AT_name for named DIEs does not contain the prefixes.  */
16738           base = strrchr (demangled, ':');
16739           if (base && base > demangled && base[-1] == ':')
16740             base++;
16741           else
16742             base = demangled;
16743
16744           part_die->name
16745             = ((const char *)
16746                obstack_copy0 (&cu->objfile->per_bfd->storage_obstack,
16747                               base, strlen (base)));
16748           xfree (demangled);
16749         }
16750     }
16751
16752   part_die->fixup_called = 1;
16753 }
16754
16755 /* Read an attribute value described by an attribute form.  */
16756
16757 static const gdb_byte *
16758 read_attribute_value (const struct die_reader_specs *reader,
16759                       struct attribute *attr, unsigned form,
16760                       LONGEST implicit_const, const gdb_byte *info_ptr)
16761 {
16762   struct dwarf2_cu *cu = reader->cu;
16763   struct objfile *objfile = cu->objfile;
16764   struct gdbarch *gdbarch = get_objfile_arch (objfile);
16765   bfd *abfd = reader->abfd;
16766   struct comp_unit_head *cu_header = &cu->header;
16767   unsigned int bytes_read;
16768   struct dwarf_block *blk;
16769
16770   attr->form = (enum dwarf_form) form;
16771   switch (form)
16772     {
16773     case DW_FORM_ref_addr:
16774       if (cu->header.version == 2)
16775         DW_UNSND (attr) = read_address (abfd, info_ptr, cu, &bytes_read);
16776       else
16777         DW_UNSND (attr) = read_offset (abfd, info_ptr,
16778                                        &cu->header, &bytes_read);
16779       info_ptr += bytes_read;
16780       break;
16781     case DW_FORM_GNU_ref_alt:
16782       DW_UNSND (attr) = read_offset (abfd, info_ptr, &cu->header, &bytes_read);
16783       info_ptr += bytes_read;
16784       break;
16785     case DW_FORM_addr:
16786       DW_ADDR (attr) = read_address (abfd, info_ptr, cu, &bytes_read);
16787       DW_ADDR (attr) = gdbarch_adjust_dwarf2_addr (gdbarch, DW_ADDR (attr));
16788       info_ptr += bytes_read;
16789       break;
16790     case DW_FORM_block2:
16791       blk = dwarf_alloc_block (cu);
16792       blk->size = read_2_bytes (abfd, info_ptr);
16793       info_ptr += 2;
16794       blk->data = read_n_bytes (abfd, info_ptr, blk->size);
16795       info_ptr += blk->size;
16796       DW_BLOCK (attr) = blk;
16797       break;
16798     case DW_FORM_block4:
16799       blk = dwarf_alloc_block (cu);
16800       blk->size = read_4_bytes (abfd, info_ptr);
16801       info_ptr += 4;
16802       blk->data = read_n_bytes (abfd, info_ptr, blk->size);
16803       info_ptr += blk->size;
16804       DW_BLOCK (attr) = blk;
16805       break;
16806     case DW_FORM_data2:
16807       DW_UNSND (attr) = read_2_bytes (abfd, info_ptr);
16808       info_ptr += 2;
16809       break;
16810     case DW_FORM_data4:
16811       DW_UNSND (attr) = read_4_bytes (abfd, info_ptr);
16812       info_ptr += 4;
16813       break;
16814     case DW_FORM_data8:
16815       DW_UNSND (attr) = read_8_bytes (abfd, info_ptr);
16816       info_ptr += 8;
16817       break;
16818     case DW_FORM_data16:
16819       blk = dwarf_alloc_block (cu);
16820       blk->size = 16;
16821       blk->data = read_n_bytes (abfd, info_ptr, 16);
16822       info_ptr += 16;
16823       DW_BLOCK (attr) = blk;
16824       break;
16825     case DW_FORM_sec_offset:
16826       DW_UNSND (attr) = read_offset (abfd, info_ptr, &cu->header, &bytes_read);
16827       info_ptr += bytes_read;
16828       break;
16829     case DW_FORM_string:
16830       DW_STRING (attr) = read_direct_string (abfd, info_ptr, &bytes_read);
16831       DW_STRING_IS_CANONICAL (attr) = 0;
16832       info_ptr += bytes_read;
16833       break;
16834     case DW_FORM_strp:
16835       if (!cu->per_cu->is_dwz)
16836         {
16837           DW_STRING (attr) = read_indirect_string (abfd, info_ptr, cu_header,
16838                                                    &bytes_read);
16839           DW_STRING_IS_CANONICAL (attr) = 0;
16840           info_ptr += bytes_read;
16841           break;
16842         }
16843       /* FALLTHROUGH */
16844     case DW_FORM_line_strp:
16845       if (!cu->per_cu->is_dwz)
16846         {
16847           DW_STRING (attr) = read_indirect_line_string (abfd, info_ptr,
16848                                                         cu_header, &bytes_read);
16849           DW_STRING_IS_CANONICAL (attr) = 0;
16850           info_ptr += bytes_read;
16851           break;
16852         }
16853       /* FALLTHROUGH */
16854     case DW_FORM_GNU_strp_alt:
16855       {
16856         struct dwz_file *dwz = dwarf2_get_dwz_file ();
16857         LONGEST str_offset = read_offset (abfd, info_ptr, cu_header,
16858                                           &bytes_read);
16859
16860         DW_STRING (attr) = read_indirect_string_from_dwz (dwz, str_offset);
16861         DW_STRING_IS_CANONICAL (attr) = 0;
16862         info_ptr += bytes_read;
16863       }
16864       break;
16865     case DW_FORM_exprloc:
16866     case DW_FORM_block:
16867       blk = dwarf_alloc_block (cu);
16868       blk->size = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
16869       info_ptr += bytes_read;
16870       blk->data = read_n_bytes (abfd, info_ptr, blk->size);
16871       info_ptr += blk->size;
16872       DW_BLOCK (attr) = blk;
16873       break;
16874     case DW_FORM_block1:
16875       blk = dwarf_alloc_block (cu);
16876       blk->size = read_1_byte (abfd, info_ptr);
16877       info_ptr += 1;
16878       blk->data = read_n_bytes (abfd, info_ptr, blk->size);
16879       info_ptr += blk->size;
16880       DW_BLOCK (attr) = blk;
16881       break;
16882     case DW_FORM_data1:
16883       DW_UNSND (attr) = read_1_byte (abfd, info_ptr);
16884       info_ptr += 1;
16885       break;
16886     case DW_FORM_flag:
16887       DW_UNSND (attr) = read_1_byte (abfd, info_ptr);
16888       info_ptr += 1;
16889       break;
16890     case DW_FORM_flag_present:
16891       DW_UNSND (attr) = 1;
16892       break;
16893     case DW_FORM_sdata:
16894       DW_SND (attr) = read_signed_leb128 (abfd, info_ptr, &bytes_read);
16895       info_ptr += bytes_read;
16896       break;
16897     case DW_FORM_udata:
16898       DW_UNSND (attr) = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
16899       info_ptr += bytes_read;
16900       break;
16901     case DW_FORM_ref1:
16902       DW_UNSND (attr) = (to_underlying (cu->header.sect_off)
16903                          + read_1_byte (abfd, info_ptr));
16904       info_ptr += 1;
16905       break;
16906     case DW_FORM_ref2:
16907       DW_UNSND (attr) = (to_underlying (cu->header.sect_off)
16908                          + read_2_bytes (abfd, info_ptr));
16909       info_ptr += 2;
16910       break;
16911     case DW_FORM_ref4:
16912       DW_UNSND (attr) = (to_underlying (cu->header.sect_off)
16913                          + read_4_bytes (abfd, info_ptr));
16914       info_ptr += 4;
16915       break;
16916     case DW_FORM_ref8:
16917       DW_UNSND (attr) = (to_underlying (cu->header.sect_off)
16918                          + read_8_bytes (abfd, info_ptr));
16919       info_ptr += 8;
16920       break;
16921     case DW_FORM_ref_sig8:
16922       DW_SIGNATURE (attr) = read_8_bytes (abfd, info_ptr);
16923       info_ptr += 8;
16924       break;
16925     case DW_FORM_ref_udata:
16926       DW_UNSND (attr) = (to_underlying (cu->header.sect_off)
16927                          + read_unsigned_leb128 (abfd, info_ptr, &bytes_read));
16928       info_ptr += bytes_read;
16929       break;
16930     case DW_FORM_indirect:
16931       form = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
16932       info_ptr += bytes_read;
16933       if (form == DW_FORM_implicit_const)
16934         {
16935           implicit_const = read_signed_leb128 (abfd, info_ptr, &bytes_read);
16936           info_ptr += bytes_read;
16937         }
16938       info_ptr = read_attribute_value (reader, attr, form, implicit_const,
16939                                        info_ptr);
16940       break;
16941     case DW_FORM_implicit_const:
16942       DW_SND (attr) = implicit_const;
16943       break;
16944     case DW_FORM_GNU_addr_index:
16945       if (reader->dwo_file == NULL)
16946         {
16947           /* For now flag a hard error.
16948              Later we can turn this into a complaint.  */
16949           error (_("Dwarf Error: %s found in non-DWO CU [in module %s]"),
16950                  dwarf_form_name (form),
16951                  bfd_get_filename (abfd));
16952         }
16953       DW_ADDR (attr) = read_addr_index_from_leb128 (cu, info_ptr, &bytes_read);
16954       info_ptr += bytes_read;
16955       break;
16956     case DW_FORM_GNU_str_index:
16957       if (reader->dwo_file == NULL)
16958         {
16959           /* For now flag a hard error.
16960              Later we can turn this into a complaint if warranted.  */
16961           error (_("Dwarf Error: %s found in non-DWO CU [in module %s]"),
16962                  dwarf_form_name (form),
16963                  bfd_get_filename (abfd));
16964         }
16965       {
16966         ULONGEST str_index =
16967           read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
16968
16969         DW_STRING (attr) = read_str_index (reader, str_index);
16970         DW_STRING_IS_CANONICAL (attr) = 0;
16971         info_ptr += bytes_read;
16972       }
16973       break;
16974     default:
16975       error (_("Dwarf Error: Cannot handle %s in DWARF reader [in module %s]"),
16976              dwarf_form_name (form),
16977              bfd_get_filename (abfd));
16978     }
16979
16980   /* Super hack.  */
16981   if (cu->per_cu->is_dwz && attr_form_is_ref (attr))
16982     attr->form = DW_FORM_GNU_ref_alt;
16983
16984   /* We have seen instances where the compiler tried to emit a byte
16985      size attribute of -1 which ended up being encoded as an unsigned
16986      0xffffffff.  Although 0xffffffff is technically a valid size value,
16987      an object of this size seems pretty unlikely so we can relatively
16988      safely treat these cases as if the size attribute was invalid and
16989      treat them as zero by default.  */
16990   if (attr->name == DW_AT_byte_size
16991       && form == DW_FORM_data4
16992       && DW_UNSND (attr) >= 0xffffffff)
16993     {
16994       complaint
16995         (&symfile_complaints,
16996          _("Suspicious DW_AT_byte_size value treated as zero instead of %s"),
16997          hex_string (DW_UNSND (attr)));
16998       DW_UNSND (attr) = 0;
16999     }
17000
17001   return info_ptr;
17002 }
17003
17004 /* Read an attribute described by an abbreviated attribute.  */
17005
17006 static const gdb_byte *
17007 read_attribute (const struct die_reader_specs *reader,
17008                 struct attribute *attr, struct attr_abbrev *abbrev,
17009                 const gdb_byte *info_ptr)
17010 {
17011   attr->name = abbrev->name;
17012   return read_attribute_value (reader, attr, abbrev->form,
17013                                abbrev->implicit_const, info_ptr);
17014 }
17015
17016 /* Read dwarf information from a buffer.  */
17017
17018 static unsigned int
17019 read_1_byte (bfd *abfd, const gdb_byte *buf)
17020 {
17021   return bfd_get_8 (abfd, buf);
17022 }
17023
17024 static int
17025 read_1_signed_byte (bfd *abfd, const gdb_byte *buf)
17026 {
17027   return bfd_get_signed_8 (abfd, buf);
17028 }
17029
17030 static unsigned int
17031 read_2_bytes (bfd *abfd, const gdb_byte *buf)
17032 {
17033   return bfd_get_16 (abfd, buf);
17034 }
17035
17036 static int
17037 read_2_signed_bytes (bfd *abfd, const gdb_byte *buf)
17038 {
17039   return bfd_get_signed_16 (abfd, buf);
17040 }
17041
17042 static unsigned int
17043 read_4_bytes (bfd *abfd, const gdb_byte *buf)
17044 {
17045   return bfd_get_32 (abfd, buf);
17046 }
17047
17048 static int
17049 read_4_signed_bytes (bfd *abfd, const gdb_byte *buf)
17050 {
17051   return bfd_get_signed_32 (abfd, buf);
17052 }
17053
17054 static ULONGEST
17055 read_8_bytes (bfd *abfd, const gdb_byte *buf)
17056 {
17057   return bfd_get_64 (abfd, buf);
17058 }
17059
17060 static CORE_ADDR
17061 read_address (bfd *abfd, const gdb_byte *buf, struct dwarf2_cu *cu,
17062               unsigned int *bytes_read)
17063 {
17064   struct comp_unit_head *cu_header = &cu->header;
17065   CORE_ADDR retval = 0;
17066
17067   if (cu_header->signed_addr_p)
17068     {
17069       switch (cu_header->addr_size)
17070         {
17071         case 2:
17072           retval = bfd_get_signed_16 (abfd, buf);
17073           break;
17074         case 4:
17075           retval = bfd_get_signed_32 (abfd, buf);
17076           break;
17077         case 8:
17078           retval = bfd_get_signed_64 (abfd, buf);
17079           break;
17080         default:
17081           internal_error (__FILE__, __LINE__,
17082                           _("read_address: bad switch, signed [in module %s]"),
17083                           bfd_get_filename (abfd));
17084         }
17085     }
17086   else
17087     {
17088       switch (cu_header->addr_size)
17089         {
17090         case 2:
17091           retval = bfd_get_16 (abfd, buf);
17092           break;
17093         case 4:
17094           retval = bfd_get_32 (abfd, buf);
17095           break;
17096         case 8:
17097           retval = bfd_get_64 (abfd, buf);
17098           break;
17099         default:
17100           internal_error (__FILE__, __LINE__,
17101                           _("read_address: bad switch, "
17102                             "unsigned [in module %s]"),
17103                           bfd_get_filename (abfd));
17104         }
17105     }
17106
17107   *bytes_read = cu_header->addr_size;
17108   return retval;
17109 }
17110
17111 /* Read the initial length from a section.  The (draft) DWARF 3
17112    specification allows the initial length to take up either 4 bytes
17113    or 12 bytes.  If the first 4 bytes are 0xffffffff, then the next 8
17114    bytes describe the length and all offsets will be 8 bytes in length
17115    instead of 4.
17116
17117    An older, non-standard 64-bit format is also handled by this
17118    function.  The older format in question stores the initial length
17119    as an 8-byte quantity without an escape value.  Lengths greater
17120    than 2^32 aren't very common which means that the initial 4 bytes
17121    is almost always zero.  Since a length value of zero doesn't make
17122    sense for the 32-bit format, this initial zero can be considered to
17123    be an escape value which indicates the presence of the older 64-bit
17124    format.  As written, the code can't detect (old format) lengths
17125    greater than 4GB.  If it becomes necessary to handle lengths
17126    somewhat larger than 4GB, we could allow other small values (such
17127    as the non-sensical values of 1, 2, and 3) to also be used as
17128    escape values indicating the presence of the old format.
17129
17130    The value returned via bytes_read should be used to increment the
17131    relevant pointer after calling read_initial_length().
17132
17133    [ Note:  read_initial_length() and read_offset() are based on the
17134      document entitled "DWARF Debugging Information Format", revision
17135      3, draft 8, dated November 19, 2001.  This document was obtained
17136      from:
17137
17138         http://reality.sgiweb.org/davea/dwarf3-draft8-011125.pdf
17139
17140      This document is only a draft and is subject to change.  (So beware.)
17141
17142      Details regarding the older, non-standard 64-bit format were
17143      determined empirically by examining 64-bit ELF files produced by
17144      the SGI toolchain on an IRIX 6.5 machine.
17145
17146      - Kevin, July 16, 2002
17147    ] */
17148
17149 static LONGEST
17150 read_initial_length (bfd *abfd, const gdb_byte *buf, unsigned int *bytes_read)
17151 {
17152   LONGEST length = bfd_get_32 (abfd, buf);
17153
17154   if (length == 0xffffffff)
17155     {
17156       length = bfd_get_64 (abfd, buf + 4);
17157       *bytes_read = 12;
17158     }
17159   else if (length == 0)
17160     {
17161       /* Handle the (non-standard) 64-bit DWARF2 format used by IRIX.  */
17162       length = bfd_get_64 (abfd, buf);
17163       *bytes_read = 8;
17164     }
17165   else
17166     {
17167       *bytes_read = 4;
17168     }
17169
17170   return length;
17171 }
17172
17173 /* Cover function for read_initial_length.
17174    Returns the length of the object at BUF, and stores the size of the
17175    initial length in *BYTES_READ and stores the size that offsets will be in
17176    *OFFSET_SIZE.
17177    If the initial length size is not equivalent to that specified in
17178    CU_HEADER then issue a complaint.
17179    This is useful when reading non-comp-unit headers.  */
17180
17181 static LONGEST
17182 read_checked_initial_length_and_offset (bfd *abfd, const gdb_byte *buf,
17183                                         const struct comp_unit_head *cu_header,
17184                                         unsigned int *bytes_read,
17185                                         unsigned int *offset_size)
17186 {
17187   LONGEST length = read_initial_length (abfd, buf, bytes_read);
17188
17189   gdb_assert (cu_header->initial_length_size == 4
17190               || cu_header->initial_length_size == 8
17191               || cu_header->initial_length_size == 12);
17192
17193   if (cu_header->initial_length_size != *bytes_read)
17194     complaint (&symfile_complaints,
17195                _("intermixed 32-bit and 64-bit DWARF sections"));
17196
17197   *offset_size = (*bytes_read == 4) ? 4 : 8;
17198   return length;
17199 }
17200
17201 /* Read an offset from the data stream.  The size of the offset is
17202    given by cu_header->offset_size.  */
17203
17204 static LONGEST
17205 read_offset (bfd *abfd, const gdb_byte *buf,
17206              const struct comp_unit_head *cu_header,
17207              unsigned int *bytes_read)
17208 {
17209   LONGEST offset = read_offset_1 (abfd, buf, cu_header->offset_size);
17210
17211   *bytes_read = cu_header->offset_size;
17212   return offset;
17213 }
17214
17215 /* Read an offset from the data stream.  */
17216
17217 static LONGEST
17218 read_offset_1 (bfd *abfd, const gdb_byte *buf, unsigned int offset_size)
17219 {
17220   LONGEST retval = 0;
17221
17222   switch (offset_size)
17223     {
17224     case 4:
17225       retval = bfd_get_32 (abfd, buf);
17226       break;
17227     case 8:
17228       retval = bfd_get_64 (abfd, buf);
17229       break;
17230     default:
17231       internal_error (__FILE__, __LINE__,
17232                       _("read_offset_1: bad switch [in module %s]"),
17233                       bfd_get_filename (abfd));
17234     }
17235
17236   return retval;
17237 }
17238
17239 static const gdb_byte *
17240 read_n_bytes (bfd *abfd, const gdb_byte *buf, unsigned int size)
17241 {
17242   /* If the size of a host char is 8 bits, we can return a pointer
17243      to the buffer, otherwise we have to copy the data to a buffer
17244      allocated on the temporary obstack.  */
17245   gdb_assert (HOST_CHAR_BIT == 8);
17246   return buf;
17247 }
17248
17249 static const char *
17250 read_direct_string (bfd *abfd, const gdb_byte *buf,
17251                     unsigned int *bytes_read_ptr)
17252 {
17253   /* If the size of a host char is 8 bits, we can return a pointer
17254      to the string, otherwise we have to copy the string to a buffer
17255      allocated on the temporary obstack.  */
17256   gdb_assert (HOST_CHAR_BIT == 8);
17257   if (*buf == '\0')
17258     {
17259       *bytes_read_ptr = 1;
17260       return NULL;
17261     }
17262   *bytes_read_ptr = strlen ((const char *) buf) + 1;
17263   return (const char *) buf;
17264 }
17265
17266 /* Return pointer to string at section SECT offset STR_OFFSET with error
17267    reporting strings FORM_NAME and SECT_NAME.  */
17268
17269 static const char *
17270 read_indirect_string_at_offset_from (bfd *abfd, LONGEST str_offset,
17271                                      struct dwarf2_section_info *sect,
17272                                      const char *form_name,
17273                                      const char *sect_name)
17274 {
17275   dwarf2_read_section (dwarf2_per_objfile->objfile, sect);
17276   if (sect->buffer == NULL)
17277     error (_("%s used without %s section [in module %s]"),
17278            form_name, sect_name, bfd_get_filename (abfd));
17279   if (str_offset >= sect->size)
17280     error (_("%s pointing outside of %s section [in module %s]"),
17281            form_name, sect_name, bfd_get_filename (abfd));
17282   gdb_assert (HOST_CHAR_BIT == 8);
17283   if (sect->buffer[str_offset] == '\0')
17284     return NULL;
17285   return (const char *) (sect->buffer + str_offset);
17286 }
17287
17288 /* Return pointer to string at .debug_str offset STR_OFFSET.  */
17289
17290 static const char *
17291 read_indirect_string_at_offset (bfd *abfd, LONGEST str_offset)
17292 {
17293   return read_indirect_string_at_offset_from (abfd, str_offset,
17294                                               &dwarf2_per_objfile->str,
17295                                               "DW_FORM_strp", ".debug_str");
17296 }
17297
17298 /* Return pointer to string at .debug_line_str offset STR_OFFSET.  */
17299
17300 static const char *
17301 read_indirect_line_string_at_offset (bfd *abfd, LONGEST str_offset)
17302 {
17303   return read_indirect_string_at_offset_from (abfd, str_offset,
17304                                               &dwarf2_per_objfile->line_str,
17305                                               "DW_FORM_line_strp",
17306                                               ".debug_line_str");
17307 }
17308
17309 /* Read a string at offset STR_OFFSET in the .debug_str section from
17310    the .dwz file DWZ.  Throw an error if the offset is too large.  If
17311    the string consists of a single NUL byte, return NULL; otherwise
17312    return a pointer to the string.  */
17313
17314 static const char *
17315 read_indirect_string_from_dwz (struct dwz_file *dwz, LONGEST str_offset)
17316 {
17317   dwarf2_read_section (dwarf2_per_objfile->objfile, &dwz->str);
17318
17319   if (dwz->str.buffer == NULL)
17320     error (_("DW_FORM_GNU_strp_alt used without .debug_str "
17321              "section [in module %s]"),
17322            bfd_get_filename (dwz->dwz_bfd));
17323   if (str_offset >= dwz->str.size)
17324     error (_("DW_FORM_GNU_strp_alt pointing outside of "
17325              ".debug_str section [in module %s]"),
17326            bfd_get_filename (dwz->dwz_bfd));
17327   gdb_assert (HOST_CHAR_BIT == 8);
17328   if (dwz->str.buffer[str_offset] == '\0')
17329     return NULL;
17330   return (const char *) (dwz->str.buffer + str_offset);
17331 }
17332
17333 /* Return pointer to string at .debug_str offset as read from BUF.
17334    BUF is assumed to be in a compilation unit described by CU_HEADER.
17335    Return *BYTES_READ_PTR count of bytes read from BUF.  */
17336
17337 static const char *
17338 read_indirect_string (bfd *abfd, const gdb_byte *buf,
17339                       const struct comp_unit_head *cu_header,
17340                       unsigned int *bytes_read_ptr)
17341 {
17342   LONGEST str_offset = read_offset (abfd, buf, cu_header, bytes_read_ptr);
17343
17344   return read_indirect_string_at_offset (abfd, str_offset);
17345 }
17346
17347 /* Return pointer to string at .debug_line_str offset as read from BUF.
17348    BUF is assumed to be in a compilation unit described by CU_HEADER.
17349    Return *BYTES_READ_PTR count of bytes read from BUF.  */
17350
17351 static const char *
17352 read_indirect_line_string (bfd *abfd, const gdb_byte *buf,
17353                            const struct comp_unit_head *cu_header,
17354                            unsigned int *bytes_read_ptr)
17355 {
17356   LONGEST str_offset = read_offset (abfd, buf, cu_header, bytes_read_ptr);
17357
17358   return read_indirect_line_string_at_offset (abfd, str_offset);
17359 }
17360
17361 ULONGEST
17362 read_unsigned_leb128 (bfd *abfd, const gdb_byte *buf,
17363                           unsigned int *bytes_read_ptr)
17364 {
17365   ULONGEST result;
17366   unsigned int num_read;
17367   int shift;
17368   unsigned char byte;
17369
17370   result = 0;
17371   shift = 0;
17372   num_read = 0;
17373   while (1)
17374     {
17375       byte = bfd_get_8 (abfd, buf);
17376       buf++;
17377       num_read++;
17378       result |= ((ULONGEST) (byte & 127) << shift);
17379       if ((byte & 128) == 0)
17380         {
17381           break;
17382         }
17383       shift += 7;
17384     }
17385   *bytes_read_ptr = num_read;
17386   return result;
17387 }
17388
17389 static LONGEST
17390 read_signed_leb128 (bfd *abfd, const gdb_byte *buf,
17391                     unsigned int *bytes_read_ptr)
17392 {
17393   LONGEST result;
17394   int shift, num_read;
17395   unsigned char byte;
17396
17397   result = 0;
17398   shift = 0;
17399   num_read = 0;
17400   while (1)
17401     {
17402       byte = bfd_get_8 (abfd, buf);
17403       buf++;
17404       num_read++;
17405       result |= ((LONGEST) (byte & 127) << shift);
17406       shift += 7;
17407       if ((byte & 128) == 0)
17408         {
17409           break;
17410         }
17411     }
17412   if ((shift < 8 * sizeof (result)) && (byte & 0x40))
17413     result |= -(((LONGEST) 1) << shift);
17414   *bytes_read_ptr = num_read;
17415   return result;
17416 }
17417
17418 /* Given index ADDR_INDEX in .debug_addr, fetch the value.
17419    ADDR_BASE is the DW_AT_GNU_addr_base attribute or zero.
17420    ADDR_SIZE is the size of addresses from the CU header.  */
17421
17422 static CORE_ADDR
17423 read_addr_index_1 (unsigned int addr_index, ULONGEST addr_base, int addr_size)
17424 {
17425   struct objfile *objfile = dwarf2_per_objfile->objfile;
17426   bfd *abfd = objfile->obfd;
17427   const gdb_byte *info_ptr;
17428
17429   dwarf2_read_section (objfile, &dwarf2_per_objfile->addr);
17430   if (dwarf2_per_objfile->addr.buffer == NULL)
17431     error (_("DW_FORM_addr_index used without .debug_addr section [in module %s]"),
17432            objfile_name (objfile));
17433   if (addr_base + addr_index * addr_size >= dwarf2_per_objfile->addr.size)
17434     error (_("DW_FORM_addr_index pointing outside of "
17435              ".debug_addr section [in module %s]"),
17436            objfile_name (objfile));
17437   info_ptr = (dwarf2_per_objfile->addr.buffer
17438               + addr_base + addr_index * addr_size);
17439   if (addr_size == 4)
17440     return bfd_get_32 (abfd, info_ptr);
17441   else
17442     return bfd_get_64 (abfd, info_ptr);
17443 }
17444
17445 /* Given index ADDR_INDEX in .debug_addr, fetch the value.  */
17446
17447 static CORE_ADDR
17448 read_addr_index (struct dwarf2_cu *cu, unsigned int addr_index)
17449 {
17450   return read_addr_index_1 (addr_index, cu->addr_base, cu->header.addr_size);
17451 }
17452
17453 /* Given a pointer to an leb128 value, fetch the value from .debug_addr.  */
17454
17455 static CORE_ADDR
17456 read_addr_index_from_leb128 (struct dwarf2_cu *cu, const gdb_byte *info_ptr,
17457                              unsigned int *bytes_read)
17458 {
17459   bfd *abfd = cu->objfile->obfd;
17460   unsigned int addr_index = read_unsigned_leb128 (abfd, info_ptr, bytes_read);
17461
17462   return read_addr_index (cu, addr_index);
17463 }
17464
17465 /* Data structure to pass results from dwarf2_read_addr_index_reader
17466    back to dwarf2_read_addr_index.  */
17467
17468 struct dwarf2_read_addr_index_data
17469 {
17470   ULONGEST addr_base;
17471   int addr_size;
17472 };
17473
17474 /* die_reader_func for dwarf2_read_addr_index.  */
17475
17476 static void
17477 dwarf2_read_addr_index_reader (const struct die_reader_specs *reader,
17478                                const gdb_byte *info_ptr,
17479                                struct die_info *comp_unit_die,
17480                                int has_children,
17481                                void *data)
17482 {
17483   struct dwarf2_cu *cu = reader->cu;
17484   struct dwarf2_read_addr_index_data *aidata =
17485     (struct dwarf2_read_addr_index_data *) data;
17486
17487   aidata->addr_base = cu->addr_base;
17488   aidata->addr_size = cu->header.addr_size;
17489 }
17490
17491 /* Given an index in .debug_addr, fetch the value.
17492    NOTE: This can be called during dwarf expression evaluation,
17493    long after the debug information has been read, and thus per_cu->cu
17494    may no longer exist.  */
17495
17496 CORE_ADDR
17497 dwarf2_read_addr_index (struct dwarf2_per_cu_data *per_cu,
17498                         unsigned int addr_index)
17499 {
17500   struct objfile *objfile = per_cu->objfile;
17501   struct dwarf2_cu *cu = per_cu->cu;
17502   ULONGEST addr_base;
17503   int addr_size;
17504
17505   /* This is intended to be called from outside this file.  */
17506   dw2_setup (objfile);
17507
17508   /* We need addr_base and addr_size.
17509      If we don't have PER_CU->cu, we have to get it.
17510      Nasty, but the alternative is storing the needed info in PER_CU,
17511      which at this point doesn't seem justified: it's not clear how frequently
17512      it would get used and it would increase the size of every PER_CU.
17513      Entry points like dwarf2_per_cu_addr_size do a similar thing
17514      so we're not in uncharted territory here.
17515      Alas we need to be a bit more complicated as addr_base is contained
17516      in the DIE.
17517
17518      We don't need to read the entire CU(/TU).
17519      We just need the header and top level die.
17520
17521      IWBN to use the aging mechanism to let us lazily later discard the CU.
17522      For now we skip this optimization.  */
17523
17524   if (cu != NULL)
17525     {
17526       addr_base = cu->addr_base;
17527       addr_size = cu->header.addr_size;
17528     }
17529   else
17530     {
17531       struct dwarf2_read_addr_index_data aidata;
17532
17533       /* Note: We can't use init_cutu_and_read_dies_simple here,
17534          we need addr_base.  */
17535       init_cutu_and_read_dies (per_cu, NULL, 0, 0,
17536                                dwarf2_read_addr_index_reader, &aidata);
17537       addr_base = aidata.addr_base;
17538       addr_size = aidata.addr_size;
17539     }
17540
17541   return read_addr_index_1 (addr_index, addr_base, addr_size);
17542 }
17543
17544 /* Given a DW_FORM_GNU_str_index, fetch the string.
17545    This is only used by the Fission support.  */
17546
17547 static const char *
17548 read_str_index (const struct die_reader_specs *reader, ULONGEST str_index)
17549 {
17550   struct objfile *objfile = dwarf2_per_objfile->objfile;
17551   const char *objf_name = objfile_name (objfile);
17552   bfd *abfd = objfile->obfd;
17553   struct dwarf2_cu *cu = reader->cu;
17554   struct dwarf2_section_info *str_section = &reader->dwo_file->sections.str;
17555   struct dwarf2_section_info *str_offsets_section =
17556     &reader->dwo_file->sections.str_offsets;
17557   const gdb_byte *info_ptr;
17558   ULONGEST str_offset;
17559   static const char form_name[] = "DW_FORM_GNU_str_index";
17560
17561   dwarf2_read_section (objfile, str_section);
17562   dwarf2_read_section (objfile, str_offsets_section);
17563   if (str_section->buffer == NULL)
17564     error (_("%s used without .debug_str.dwo section"
17565              " in CU at offset 0x%x [in module %s]"),
17566            form_name, to_underlying (cu->header.sect_off), objf_name);
17567   if (str_offsets_section->buffer == NULL)
17568     error (_("%s used without .debug_str_offsets.dwo section"
17569              " in CU at offset 0x%x [in module %s]"),
17570            form_name, to_underlying (cu->header.sect_off), objf_name);
17571   if (str_index * cu->header.offset_size >= str_offsets_section->size)
17572     error (_("%s pointing outside of .debug_str_offsets.dwo"
17573              " section in CU at offset 0x%x [in module %s]"),
17574            form_name, to_underlying (cu->header.sect_off), objf_name);
17575   info_ptr = (str_offsets_section->buffer
17576               + str_index * cu->header.offset_size);
17577   if (cu->header.offset_size == 4)
17578     str_offset = bfd_get_32 (abfd, info_ptr);
17579   else
17580     str_offset = bfd_get_64 (abfd, info_ptr);
17581   if (str_offset >= str_section->size)
17582     error (_("Offset from %s pointing outside of"
17583              " .debug_str.dwo section in CU at offset 0x%x [in module %s]"),
17584            form_name, to_underlying (cu->header.sect_off), objf_name);
17585   return (const char *) (str_section->buffer + str_offset);
17586 }
17587
17588 /* Return the length of an LEB128 number in BUF.  */
17589
17590 static int
17591 leb128_size (const gdb_byte *buf)
17592 {
17593   const gdb_byte *begin = buf;
17594   gdb_byte byte;
17595
17596   while (1)
17597     {
17598       byte = *buf++;
17599       if ((byte & 128) == 0)
17600         return buf - begin;
17601     }
17602 }
17603
17604 static void
17605 set_cu_language (unsigned int lang, struct dwarf2_cu *cu)
17606 {
17607   switch (lang)
17608     {
17609     case DW_LANG_C89:
17610     case DW_LANG_C99:
17611     case DW_LANG_C11:
17612     case DW_LANG_C:
17613     case DW_LANG_UPC:
17614       cu->language = language_c;
17615       break;
17616     case DW_LANG_Java:
17617     case DW_LANG_C_plus_plus:
17618     case DW_LANG_C_plus_plus_11:
17619     case DW_LANG_C_plus_plus_14:
17620       cu->language = language_cplus;
17621       break;
17622     case DW_LANG_D:
17623       cu->language = language_d;
17624       break;
17625     case DW_LANG_Fortran77:
17626     case DW_LANG_Fortran90:
17627     case DW_LANG_Fortran95:
17628     case DW_LANG_Fortran03:
17629     case DW_LANG_Fortran08:
17630       cu->language = language_fortran;
17631       break;
17632     case DW_LANG_Go:
17633       cu->language = language_go;
17634       break;
17635     case DW_LANG_Mips_Assembler:
17636       cu->language = language_asm;
17637       break;
17638     case DW_LANG_Ada83:
17639     case DW_LANG_Ada95:
17640       cu->language = language_ada;
17641       break;
17642     case DW_LANG_Modula2:
17643       cu->language = language_m2;
17644       break;
17645     case DW_LANG_Pascal83:
17646       cu->language = language_pascal;
17647       break;
17648     case DW_LANG_ObjC:
17649       cu->language = language_objc;
17650       break;
17651     case DW_LANG_Rust:
17652     case DW_LANG_Rust_old:
17653       cu->language = language_rust;
17654       break;
17655     case DW_LANG_Cobol74:
17656     case DW_LANG_Cobol85:
17657     default:
17658       cu->language = language_minimal;
17659       break;
17660     }
17661   cu->language_defn = language_def (cu->language);
17662 }
17663
17664 /* Return the named attribute or NULL if not there.  */
17665
17666 static struct attribute *
17667 dwarf2_attr (struct die_info *die, unsigned int name, struct dwarf2_cu *cu)
17668 {
17669   for (;;)
17670     {
17671       unsigned int i;
17672       struct attribute *spec = NULL;
17673
17674       for (i = 0; i < die->num_attrs; ++i)
17675         {
17676           if (die->attrs[i].name == name)
17677             return &die->attrs[i];
17678           if (die->attrs[i].name == DW_AT_specification
17679               || die->attrs[i].name == DW_AT_abstract_origin)
17680             spec = &die->attrs[i];
17681         }
17682
17683       if (!spec)
17684         break;
17685
17686       die = follow_die_ref (die, spec, &cu);
17687     }
17688
17689   return NULL;
17690 }
17691
17692 /* Return the named attribute or NULL if not there,
17693    but do not follow DW_AT_specification, etc.
17694    This is for use in contexts where we're reading .debug_types dies.
17695    Following DW_AT_specification, DW_AT_abstract_origin will take us
17696    back up the chain, and we want to go down.  */
17697
17698 static struct attribute *
17699 dwarf2_attr_no_follow (struct die_info *die, unsigned int name)
17700 {
17701   unsigned int i;
17702
17703   for (i = 0; i < die->num_attrs; ++i)
17704     if (die->attrs[i].name == name)
17705       return &die->attrs[i];
17706
17707   return NULL;
17708 }
17709
17710 /* Return the string associated with a string-typed attribute, or NULL if it
17711    is either not found or is of an incorrect type.  */
17712
17713 static const char *
17714 dwarf2_string_attr (struct die_info *die, unsigned int name, struct dwarf2_cu *cu)
17715 {
17716   struct attribute *attr;
17717   const char *str = NULL;
17718
17719   attr = dwarf2_attr (die, name, cu);
17720
17721   if (attr != NULL)
17722     {
17723       if (attr->form == DW_FORM_strp || attr->form == DW_FORM_line_strp
17724           || attr->form == DW_FORM_string
17725           || attr->form == DW_FORM_GNU_str_index
17726           || attr->form == DW_FORM_GNU_strp_alt)
17727         str = DW_STRING (attr);
17728       else
17729         complaint (&symfile_complaints,
17730                    _("string type expected for attribute %s for "
17731                      "DIE at 0x%x in module %s"),
17732                    dwarf_attr_name (name), to_underlying (die->sect_off),
17733                    objfile_name (cu->objfile));
17734     }
17735
17736   return str;
17737 }
17738
17739 /* Return non-zero iff the attribute NAME is defined for the given DIE,
17740    and holds a non-zero value.  This function should only be used for
17741    DW_FORM_flag or DW_FORM_flag_present attributes.  */
17742
17743 static int
17744 dwarf2_flag_true_p (struct die_info *die, unsigned name, struct dwarf2_cu *cu)
17745 {
17746   struct attribute *attr = dwarf2_attr (die, name, cu);
17747
17748   return (attr && DW_UNSND (attr));
17749 }
17750
17751 static int
17752 die_is_declaration (struct die_info *die, struct dwarf2_cu *cu)
17753 {
17754   /* A DIE is a declaration if it has a DW_AT_declaration attribute
17755      which value is non-zero.  However, we have to be careful with
17756      DIEs having a DW_AT_specification attribute, because dwarf2_attr()
17757      (via dwarf2_flag_true_p) follows this attribute.  So we may
17758      end up accidently finding a declaration attribute that belongs
17759      to a different DIE referenced by the specification attribute,
17760      even though the given DIE does not have a declaration attribute.  */
17761   return (dwarf2_flag_true_p (die, DW_AT_declaration, cu)
17762           && dwarf2_attr (die, DW_AT_specification, cu) == NULL);
17763 }
17764
17765 /* Return the die giving the specification for DIE, if there is
17766    one.  *SPEC_CU is the CU containing DIE on input, and the CU
17767    containing the return value on output.  If there is no
17768    specification, but there is an abstract origin, that is
17769    returned.  */
17770
17771 static struct die_info *
17772 die_specification (struct die_info *die, struct dwarf2_cu **spec_cu)
17773 {
17774   struct attribute *spec_attr = dwarf2_attr (die, DW_AT_specification,
17775                                              *spec_cu);
17776
17777   if (spec_attr == NULL)
17778     spec_attr = dwarf2_attr (die, DW_AT_abstract_origin, *spec_cu);
17779
17780   if (spec_attr == NULL)
17781     return NULL;
17782   else
17783     return follow_die_ref (die, spec_attr, spec_cu);
17784 }
17785
17786 /* Stub for free_line_header to match void * callback types.  */
17787
17788 static void
17789 free_line_header_voidp (void *arg)
17790 {
17791   struct line_header *lh = (struct line_header *) arg;
17792
17793   delete lh;
17794 }
17795
17796 void
17797 line_header::add_include_dir (const char *include_dir)
17798 {
17799   if (dwarf_line_debug >= 2)
17800     fprintf_unfiltered (gdb_stdlog, "Adding dir %zu: %s\n",
17801                         include_dirs.size () + 1, include_dir);
17802
17803   include_dirs.push_back (include_dir);
17804 }
17805
17806 void
17807 line_header::add_file_name (const char *name,
17808                             dir_index d_index,
17809                             unsigned int mod_time,
17810                             unsigned int length)
17811 {
17812   if (dwarf_line_debug >= 2)
17813     fprintf_unfiltered (gdb_stdlog, "Adding file %u: %s\n",
17814                         (unsigned) file_names.size () + 1, name);
17815
17816   file_names.emplace_back (name, d_index, mod_time, length);
17817 }
17818
17819 /* A convenience function to find the proper .debug_line section for a CU.  */
17820
17821 static struct dwarf2_section_info *
17822 get_debug_line_section (struct dwarf2_cu *cu)
17823 {
17824   struct dwarf2_section_info *section;
17825
17826   /* For TUs in DWO files, the DW_AT_stmt_list attribute lives in the
17827      DWO file.  */
17828   if (cu->dwo_unit && cu->per_cu->is_debug_types)
17829     section = &cu->dwo_unit->dwo_file->sections.line;
17830   else if (cu->per_cu->is_dwz)
17831     {
17832       struct dwz_file *dwz = dwarf2_get_dwz_file ();
17833
17834       section = &dwz->line;
17835     }
17836   else
17837     section = &dwarf2_per_objfile->line;
17838
17839   return section;
17840 }
17841
17842 /* Read directory or file name entry format, starting with byte of
17843    format count entries, ULEB128 pairs of entry formats, ULEB128 of
17844    entries count and the entries themselves in the described entry
17845    format.  */
17846
17847 static void
17848 read_formatted_entries (bfd *abfd, const gdb_byte **bufp,
17849                         struct line_header *lh,
17850                         const struct comp_unit_head *cu_header,
17851                         void (*callback) (struct line_header *lh,
17852                                           const char *name,
17853                                           dir_index d_index,
17854                                           unsigned int mod_time,
17855                                           unsigned int length))
17856 {
17857   gdb_byte format_count, formati;
17858   ULONGEST data_count, datai;
17859   const gdb_byte *buf = *bufp;
17860   const gdb_byte *format_header_data;
17861   int i;
17862   unsigned int bytes_read;
17863
17864   format_count = read_1_byte (abfd, buf);
17865   buf += 1;
17866   format_header_data = buf;
17867   for (formati = 0; formati < format_count; formati++)
17868     {
17869       read_unsigned_leb128 (abfd, buf, &bytes_read);
17870       buf += bytes_read;
17871       read_unsigned_leb128 (abfd, buf, &bytes_read);
17872       buf += bytes_read;
17873     }
17874
17875   data_count = read_unsigned_leb128 (abfd, buf, &bytes_read);
17876   buf += bytes_read;
17877   for (datai = 0; datai < data_count; datai++)
17878     {
17879       const gdb_byte *format = format_header_data;
17880       struct file_entry fe;
17881
17882       for (formati = 0; formati < format_count; formati++)
17883         {
17884           ULONGEST content_type = read_unsigned_leb128 (abfd, format, &bytes_read);
17885           format += bytes_read;
17886
17887           ULONGEST form  = read_unsigned_leb128 (abfd, format, &bytes_read);
17888           format += bytes_read;
17889
17890           gdb::optional<const char *> string;
17891           gdb::optional<unsigned int> uint;
17892
17893           switch (form)
17894             {
17895             case DW_FORM_string:
17896               string.emplace (read_direct_string (abfd, buf, &bytes_read));
17897               buf += bytes_read;
17898               break;
17899
17900             case DW_FORM_line_strp:
17901               string.emplace (read_indirect_line_string (abfd, buf,
17902                                                          cu_header,
17903                                                          &bytes_read));
17904               buf += bytes_read;
17905               break;
17906
17907             case DW_FORM_data1:
17908               uint.emplace (read_1_byte (abfd, buf));
17909               buf += 1;
17910               break;
17911
17912             case DW_FORM_data2:
17913               uint.emplace (read_2_bytes (abfd, buf));
17914               buf += 2;
17915               break;
17916
17917             case DW_FORM_data4:
17918               uint.emplace (read_4_bytes (abfd, buf));
17919               buf += 4;
17920               break;
17921
17922             case DW_FORM_data8:
17923               uint.emplace (read_8_bytes (abfd, buf));
17924               buf += 8;
17925               break;
17926
17927             case DW_FORM_udata:
17928               uint.emplace (read_unsigned_leb128 (abfd, buf, &bytes_read));
17929               buf += bytes_read;
17930               break;
17931
17932             case DW_FORM_block:
17933               /* It is valid only for DW_LNCT_timestamp which is ignored by
17934                  current GDB.  */
17935               break;
17936             }
17937
17938           switch (content_type)
17939             {
17940             case DW_LNCT_path:
17941               if (string.has_value ())
17942                 fe.name = *string;
17943               break;
17944             case DW_LNCT_directory_index:
17945               if (uint.has_value ())
17946                 fe.d_index = (dir_index) *uint;
17947               break;
17948             case DW_LNCT_timestamp:
17949               if (uint.has_value ())
17950                 fe.mod_time = *uint;
17951               break;
17952             case DW_LNCT_size:
17953               if (uint.has_value ())
17954                 fe.length = *uint;
17955               break;
17956             case DW_LNCT_MD5:
17957               break;
17958             default:
17959               complaint (&symfile_complaints,
17960                          _("Unknown format content type %s"),
17961                          pulongest (content_type));
17962             }
17963         }
17964
17965       callback (lh, fe.name, fe.d_index, fe.mod_time, fe.length);
17966     }
17967
17968   *bufp = buf;
17969 }
17970
17971 /* Read the statement program header starting at OFFSET in
17972    .debug_line, or .debug_line.dwo.  Return a pointer
17973    to a struct line_header, allocated using xmalloc.
17974    Returns NULL if there is a problem reading the header, e.g., if it
17975    has a version we don't understand.
17976
17977    NOTE: the strings in the include directory and file name tables of
17978    the returned object point into the dwarf line section buffer,
17979    and must not be freed.  */
17980
17981 static line_header_up
17982 dwarf_decode_line_header (sect_offset sect_off, struct dwarf2_cu *cu)
17983 {
17984   const gdb_byte *line_ptr;
17985   unsigned int bytes_read, offset_size;
17986   int i;
17987   const char *cur_dir, *cur_file;
17988   struct dwarf2_section_info *section;
17989   bfd *abfd;
17990
17991   section = get_debug_line_section (cu);
17992   dwarf2_read_section (dwarf2_per_objfile->objfile, section);
17993   if (section->buffer == NULL)
17994     {
17995       if (cu->dwo_unit && cu->per_cu->is_debug_types)
17996         complaint (&symfile_complaints, _("missing .debug_line.dwo section"));
17997       else
17998         complaint (&symfile_complaints, _("missing .debug_line section"));
17999       return 0;
18000     }
18001
18002   /* We can't do this until we know the section is non-empty.
18003      Only then do we know we have such a section.  */
18004   abfd = get_section_bfd_owner (section);
18005
18006   /* Make sure that at least there's room for the total_length field.
18007      That could be 12 bytes long, but we're just going to fudge that.  */
18008   if (to_underlying (sect_off) + 4 >= section->size)
18009     {
18010       dwarf2_statement_list_fits_in_line_number_section_complaint ();
18011       return 0;
18012     }
18013
18014   line_header_up lh (new line_header ());
18015
18016   lh->sect_off = sect_off;
18017   lh->offset_in_dwz = cu->per_cu->is_dwz;
18018
18019   line_ptr = section->buffer + to_underlying (sect_off);
18020
18021   /* Read in the header.  */
18022   lh->total_length =
18023     read_checked_initial_length_and_offset (abfd, line_ptr, &cu->header,
18024                                             &bytes_read, &offset_size);
18025   line_ptr += bytes_read;
18026   if (line_ptr + lh->total_length > (section->buffer + section->size))
18027     {
18028       dwarf2_statement_list_fits_in_line_number_section_complaint ();
18029       return 0;
18030     }
18031   lh->statement_program_end = line_ptr + lh->total_length;
18032   lh->version = read_2_bytes (abfd, line_ptr);
18033   line_ptr += 2;
18034   if (lh->version > 5)
18035     {
18036       /* This is a version we don't understand.  The format could have
18037          changed in ways we don't handle properly so just punt.  */
18038       complaint (&symfile_complaints,
18039                  _("unsupported version in .debug_line section"));
18040       return NULL;
18041     }
18042   if (lh->version >= 5)
18043     {
18044       gdb_byte segment_selector_size;
18045
18046       /* Skip address size.  */
18047       read_1_byte (abfd, line_ptr);
18048       line_ptr += 1;
18049
18050       segment_selector_size = read_1_byte (abfd, line_ptr);
18051       line_ptr += 1;
18052       if (segment_selector_size != 0)
18053         {
18054           complaint (&symfile_complaints,
18055                      _("unsupported segment selector size %u "
18056                        "in .debug_line section"),
18057                      segment_selector_size);
18058           return NULL;
18059         }
18060     }
18061   lh->header_length = read_offset_1 (abfd, line_ptr, offset_size);
18062   line_ptr += offset_size;
18063   lh->minimum_instruction_length = read_1_byte (abfd, line_ptr);
18064   line_ptr += 1;
18065   if (lh->version >= 4)
18066     {
18067       lh->maximum_ops_per_instruction = read_1_byte (abfd, line_ptr);
18068       line_ptr += 1;
18069     }
18070   else
18071     lh->maximum_ops_per_instruction = 1;
18072
18073   if (lh->maximum_ops_per_instruction == 0)
18074     {
18075       lh->maximum_ops_per_instruction = 1;
18076       complaint (&symfile_complaints,
18077                  _("invalid maximum_ops_per_instruction "
18078                    "in `.debug_line' section"));
18079     }
18080
18081   lh->default_is_stmt = read_1_byte (abfd, line_ptr);
18082   line_ptr += 1;
18083   lh->line_base = read_1_signed_byte (abfd, line_ptr);
18084   line_ptr += 1;
18085   lh->line_range = read_1_byte (abfd, line_ptr);
18086   line_ptr += 1;
18087   lh->opcode_base = read_1_byte (abfd, line_ptr);
18088   line_ptr += 1;
18089   lh->standard_opcode_lengths.reset (new unsigned char[lh->opcode_base]);
18090
18091   lh->standard_opcode_lengths[0] = 1;  /* This should never be used anyway.  */
18092   for (i = 1; i < lh->opcode_base; ++i)
18093     {
18094       lh->standard_opcode_lengths[i] = read_1_byte (abfd, line_ptr);
18095       line_ptr += 1;
18096     }
18097
18098   if (lh->version >= 5)
18099     {
18100       /* Read directory table.  */
18101       read_formatted_entries (abfd, &line_ptr, lh.get (), &cu->header,
18102                               [] (struct line_header *lh, const char *name,
18103                                   dir_index d_index, unsigned int mod_time,
18104                                   unsigned int length)
18105         {
18106           lh->add_include_dir (name);
18107         });
18108
18109       /* Read file name table.  */
18110       read_formatted_entries (abfd, &line_ptr, lh.get (), &cu->header,
18111                               [] (struct line_header *lh, const char *name,
18112                                   dir_index d_index, unsigned int mod_time,
18113                                   unsigned int length)
18114         {
18115           lh->add_file_name (name, d_index, mod_time, length);
18116         });
18117     }
18118   else
18119     {
18120       /* Read directory table.  */
18121       while ((cur_dir = read_direct_string (abfd, line_ptr, &bytes_read)) != NULL)
18122         {
18123           line_ptr += bytes_read;
18124           lh->add_include_dir (cur_dir);
18125         }
18126       line_ptr += bytes_read;
18127
18128       /* Read file name table.  */
18129       while ((cur_file = read_direct_string (abfd, line_ptr, &bytes_read)) != NULL)
18130         {
18131           unsigned int mod_time, length;
18132           dir_index d_index;
18133
18134           line_ptr += bytes_read;
18135           d_index = (dir_index) read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
18136           line_ptr += bytes_read;
18137           mod_time = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
18138           line_ptr += bytes_read;
18139           length = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
18140           line_ptr += bytes_read;
18141
18142           lh->add_file_name (cur_file, d_index, mod_time, length);
18143         }
18144       line_ptr += bytes_read;
18145     }
18146   lh->statement_program_start = line_ptr;
18147
18148   if (line_ptr > (section->buffer + section->size))
18149     complaint (&symfile_complaints,
18150                _("line number info header doesn't "
18151                  "fit in `.debug_line' section"));
18152
18153   return lh;
18154 }
18155
18156 /* Subroutine of dwarf_decode_lines to simplify it.
18157    Return the file name of the psymtab for included file FILE_INDEX
18158    in line header LH of PST.
18159    COMP_DIR is the compilation directory (DW_AT_comp_dir) or NULL if unknown.
18160    If space for the result is malloc'd, it will be freed by a cleanup.
18161    Returns NULL if FILE_INDEX should be ignored, i.e., it is pst->filename.
18162
18163    The function creates dangling cleanup registration.  */
18164
18165 static const char *
18166 psymtab_include_file_name (const struct line_header *lh, int file_index,
18167                            const struct partial_symtab *pst,
18168                            const char *comp_dir)
18169 {
18170   const file_entry &fe = lh->file_names[file_index];
18171   const char *include_name = fe.name;
18172   const char *include_name_to_compare = include_name;
18173   const char *pst_filename;
18174   char *copied_name = NULL;
18175   int file_is_pst;
18176
18177   const char *dir_name = fe.include_dir (lh);
18178
18179   if (!IS_ABSOLUTE_PATH (include_name)
18180       && (dir_name != NULL || comp_dir != NULL))
18181     {
18182       /* Avoid creating a duplicate psymtab for PST.
18183          We do this by comparing INCLUDE_NAME and PST_FILENAME.
18184          Before we do the comparison, however, we need to account
18185          for DIR_NAME and COMP_DIR.
18186          First prepend dir_name (if non-NULL).  If we still don't
18187          have an absolute path prepend comp_dir (if non-NULL).
18188          However, the directory we record in the include-file's
18189          psymtab does not contain COMP_DIR (to match the
18190          corresponding symtab(s)).
18191
18192          Example:
18193
18194          bash$ cd /tmp
18195          bash$ gcc -g ./hello.c
18196          include_name = "hello.c"
18197          dir_name = "."
18198          DW_AT_comp_dir = comp_dir = "/tmp"
18199          DW_AT_name = "./hello.c"
18200
18201       */
18202
18203       if (dir_name != NULL)
18204         {
18205           char *tem = concat (dir_name, SLASH_STRING,
18206                               include_name, (char *)NULL);
18207
18208           make_cleanup (xfree, tem);
18209           include_name = tem;
18210           include_name_to_compare = include_name;
18211         }
18212       if (!IS_ABSOLUTE_PATH (include_name) && comp_dir != NULL)
18213         {
18214           char *tem = concat (comp_dir, SLASH_STRING,
18215                               include_name, (char *)NULL);
18216
18217           make_cleanup (xfree, tem);
18218           include_name_to_compare = tem;
18219         }
18220     }
18221
18222   pst_filename = pst->filename;
18223   if (!IS_ABSOLUTE_PATH (pst_filename) && pst->dirname != NULL)
18224     {
18225       copied_name = concat (pst->dirname, SLASH_STRING,
18226                             pst_filename, (char *)NULL);
18227       pst_filename = copied_name;
18228     }
18229
18230   file_is_pst = FILENAME_CMP (include_name_to_compare, pst_filename) == 0;
18231
18232   if (copied_name != NULL)
18233     xfree (copied_name);
18234
18235   if (file_is_pst)
18236     return NULL;
18237   return include_name;
18238 }
18239
18240 /* State machine to track the state of the line number program.  */
18241
18242 class lnp_state_machine
18243 {
18244 public:
18245   /* Initialize a machine state for the start of a line number
18246      program.  */
18247   lnp_state_machine (gdbarch *arch, line_header *lh, bool record_lines_p);
18248
18249   file_entry *current_file ()
18250   {
18251     /* lh->file_names is 0-based, but the file name numbers in the
18252        statement program are 1-based.  */
18253     return m_line_header->file_name_at (m_file);
18254   }
18255
18256   /* Record the line in the state machine.  END_SEQUENCE is true if
18257      we're processing the end of a sequence.  */
18258   void record_line (bool end_sequence);
18259
18260   /* Check address and if invalid nop-out the rest of the lines in this
18261      sequence.  */
18262   void check_line_address (struct dwarf2_cu *cu,
18263                            const gdb_byte *line_ptr,
18264                            CORE_ADDR lowpc, CORE_ADDR address);
18265
18266   void handle_set_discriminator (unsigned int discriminator)
18267   {
18268     m_discriminator = discriminator;
18269     m_line_has_non_zero_discriminator |= discriminator != 0;
18270   }
18271
18272   /* Handle DW_LNE_set_address.  */
18273   void handle_set_address (CORE_ADDR baseaddr, CORE_ADDR address)
18274   {
18275     m_op_index = 0;
18276     address += baseaddr;
18277     m_address = gdbarch_adjust_dwarf2_line (m_gdbarch, address, false);
18278   }
18279
18280   /* Handle DW_LNS_advance_pc.  */
18281   void handle_advance_pc (CORE_ADDR adjust);
18282
18283   /* Handle a special opcode.  */
18284   void handle_special_opcode (unsigned char op_code);
18285
18286   /* Handle DW_LNS_advance_line.  */
18287   void handle_advance_line (int line_delta)
18288   {
18289     advance_line (line_delta);
18290   }
18291
18292   /* Handle DW_LNS_set_file.  */
18293   void handle_set_file (file_name_index file);
18294
18295   /* Handle DW_LNS_negate_stmt.  */
18296   void handle_negate_stmt ()
18297   {
18298     m_is_stmt = !m_is_stmt;
18299   }
18300
18301   /* Handle DW_LNS_const_add_pc.  */
18302   void handle_const_add_pc ();
18303
18304   /* Handle DW_LNS_fixed_advance_pc.  */
18305   void handle_fixed_advance_pc (CORE_ADDR addr_adj)
18306   {
18307     m_address += gdbarch_adjust_dwarf2_line (m_gdbarch, addr_adj, true);
18308     m_op_index = 0;
18309   }
18310
18311   /* Handle DW_LNS_copy.  */
18312   void handle_copy ()
18313   {
18314     record_line (false);
18315     m_discriminator = 0;
18316   }
18317
18318   /* Handle DW_LNE_end_sequence.  */
18319   void handle_end_sequence ()
18320   {
18321     m_record_line_callback = ::record_line;
18322   }
18323
18324 private:
18325   /* Advance the line by LINE_DELTA.  */
18326   void advance_line (int line_delta)
18327   {
18328     m_line += line_delta;
18329
18330     if (line_delta != 0)
18331       m_line_has_non_zero_discriminator = m_discriminator != 0;
18332   }
18333
18334   gdbarch *m_gdbarch;
18335
18336   /* True if we're recording lines.
18337      Otherwise we're building partial symtabs and are just interested in
18338      finding include files mentioned by the line number program.  */
18339   bool m_record_lines_p;
18340
18341   /* The line number header.  */
18342   line_header *m_line_header;
18343
18344   /* These are part of the standard DWARF line number state machine,
18345      and initialized according to the DWARF spec.  */
18346
18347   unsigned char m_op_index = 0;
18348   /* The line table index (1-based) of the current file.  */
18349   file_name_index m_file = (file_name_index) 1;
18350   unsigned int m_line = 1;
18351
18352   /* These are initialized in the constructor.  */
18353
18354   CORE_ADDR m_address;
18355   bool m_is_stmt;
18356   unsigned int m_discriminator;
18357
18358   /* Additional bits of state we need to track.  */
18359
18360   /* The last file that we called dwarf2_start_subfile for.
18361      This is only used for TLLs.  */
18362   unsigned int m_last_file = 0;
18363   /* The last file a line number was recorded for.  */
18364   struct subfile *m_last_subfile = NULL;
18365
18366   /* The function to call to record a line.  */
18367   record_line_ftype *m_record_line_callback = NULL;
18368
18369   /* The last line number that was recorded, used to coalesce
18370      consecutive entries for the same line.  This can happen, for
18371      example, when discriminators are present.  PR 17276.  */
18372   unsigned int m_last_line = 0;
18373   bool m_line_has_non_zero_discriminator = false;
18374 };
18375
18376 void
18377 lnp_state_machine::handle_advance_pc (CORE_ADDR adjust)
18378 {
18379   CORE_ADDR addr_adj = (((m_op_index + adjust)
18380                          / m_line_header->maximum_ops_per_instruction)
18381                         * m_line_header->minimum_instruction_length);
18382   m_address += gdbarch_adjust_dwarf2_line (m_gdbarch, addr_adj, true);
18383   m_op_index = ((m_op_index + adjust)
18384                 % m_line_header->maximum_ops_per_instruction);
18385 }
18386
18387 void
18388 lnp_state_machine::handle_special_opcode (unsigned char op_code)
18389 {
18390   unsigned char adj_opcode = op_code - m_line_header->opcode_base;
18391   CORE_ADDR addr_adj = (((m_op_index
18392                           + (adj_opcode / m_line_header->line_range))
18393                          / m_line_header->maximum_ops_per_instruction)
18394                         * m_line_header->minimum_instruction_length);
18395   m_address += gdbarch_adjust_dwarf2_line (m_gdbarch, addr_adj, true);
18396   m_op_index = ((m_op_index + (adj_opcode / m_line_header->line_range))
18397                 % m_line_header->maximum_ops_per_instruction);
18398
18399   int line_delta = (m_line_header->line_base
18400                     + (adj_opcode % m_line_header->line_range));
18401   advance_line (line_delta);
18402   record_line (false);
18403   m_discriminator = 0;
18404 }
18405
18406 void
18407 lnp_state_machine::handle_set_file (file_name_index file)
18408 {
18409   m_file = file;
18410
18411   const file_entry *fe = current_file ();
18412   if (fe == NULL)
18413     dwarf2_debug_line_missing_file_complaint ();
18414   else if (m_record_lines_p)
18415     {
18416       const char *dir = fe->include_dir (m_line_header);
18417
18418       m_last_subfile = current_subfile;
18419       m_line_has_non_zero_discriminator = m_discriminator != 0;
18420       dwarf2_start_subfile (fe->name, dir);
18421     }
18422 }
18423
18424 void
18425 lnp_state_machine::handle_const_add_pc ()
18426 {
18427   CORE_ADDR adjust
18428     = (255 - m_line_header->opcode_base) / m_line_header->line_range;
18429
18430   CORE_ADDR addr_adj
18431     = (((m_op_index + adjust)
18432         / m_line_header->maximum_ops_per_instruction)
18433        * m_line_header->minimum_instruction_length);
18434
18435   m_address += gdbarch_adjust_dwarf2_line (m_gdbarch, addr_adj, true);
18436   m_op_index = ((m_op_index + adjust)
18437                 % m_line_header->maximum_ops_per_instruction);
18438 }
18439
18440 /* Ignore this record_line request.  */
18441
18442 static void
18443 noop_record_line (struct subfile *subfile, int line, CORE_ADDR pc)
18444 {
18445   return;
18446 }
18447
18448 /* Return non-zero if we should add LINE to the line number table.
18449    LINE is the line to add, LAST_LINE is the last line that was added,
18450    LAST_SUBFILE is the subfile for LAST_LINE.
18451    LINE_HAS_NON_ZERO_DISCRIMINATOR is non-zero if LINE has ever
18452    had a non-zero discriminator.
18453
18454    We have to be careful in the presence of discriminators.
18455    E.g., for this line:
18456
18457      for (i = 0; i < 100000; i++);
18458
18459    clang can emit four line number entries for that one line,
18460    each with a different discriminator.
18461    See gdb.dwarf2/dw2-single-line-discriminators.exp for an example.
18462
18463    However, we want gdb to coalesce all four entries into one.
18464    Otherwise the user could stepi into the middle of the line and
18465    gdb would get confused about whether the pc really was in the
18466    middle of the line.
18467
18468    Things are further complicated by the fact that two consecutive
18469    line number entries for the same line is a heuristic used by gcc
18470    to denote the end of the prologue.  So we can't just discard duplicate
18471    entries, we have to be selective about it.  The heuristic we use is
18472    that we only collapse consecutive entries for the same line if at least
18473    one of those entries has a non-zero discriminator.  PR 17276.
18474
18475    Note: Addresses in the line number state machine can never go backwards
18476    within one sequence, thus this coalescing is ok.  */
18477
18478 static int
18479 dwarf_record_line_p (unsigned int line, unsigned int last_line,
18480                      int line_has_non_zero_discriminator,
18481                      struct subfile *last_subfile)
18482 {
18483   if (current_subfile != last_subfile)
18484     return 1;
18485   if (line != last_line)
18486     return 1;
18487   /* Same line for the same file that we've seen already.
18488      As a last check, for pr 17276, only record the line if the line
18489      has never had a non-zero discriminator.  */
18490   if (!line_has_non_zero_discriminator)
18491     return 1;
18492   return 0;
18493 }
18494
18495 /* Use P_RECORD_LINE to record line number LINE beginning at address ADDRESS
18496    in the line table of subfile SUBFILE.  */
18497
18498 static void
18499 dwarf_record_line_1 (struct gdbarch *gdbarch, struct subfile *subfile,
18500                      unsigned int line, CORE_ADDR address,
18501                      record_line_ftype p_record_line)
18502 {
18503   CORE_ADDR addr = gdbarch_addr_bits_remove (gdbarch, address);
18504
18505   if (dwarf_line_debug)
18506     {
18507       fprintf_unfiltered (gdb_stdlog,
18508                           "Recording line %u, file %s, address %s\n",
18509                           line, lbasename (subfile->name),
18510                           paddress (gdbarch, address));
18511     }
18512
18513   (*p_record_line) (subfile, line, addr);
18514 }
18515
18516 /* Subroutine of dwarf_decode_lines_1 to simplify it.
18517    Mark the end of a set of line number records.
18518    The arguments are the same as for dwarf_record_line_1.
18519    If SUBFILE is NULL the request is ignored.  */
18520
18521 static void
18522 dwarf_finish_line (struct gdbarch *gdbarch, struct subfile *subfile,
18523                    CORE_ADDR address, record_line_ftype p_record_line)
18524 {
18525   if (subfile == NULL)
18526     return;
18527
18528   if (dwarf_line_debug)
18529     {
18530       fprintf_unfiltered (gdb_stdlog,
18531                           "Finishing current line, file %s, address %s\n",
18532                           lbasename (subfile->name),
18533                           paddress (gdbarch, address));
18534     }
18535
18536   dwarf_record_line_1 (gdbarch, subfile, 0, address, p_record_line);
18537 }
18538
18539 void
18540 lnp_state_machine::record_line (bool end_sequence)
18541 {
18542   if (dwarf_line_debug)
18543     {
18544       fprintf_unfiltered (gdb_stdlog,
18545                           "Processing actual line %u: file %u,"
18546                           " address %s, is_stmt %u, discrim %u\n",
18547                           m_line, to_underlying (m_file),
18548                           paddress (m_gdbarch, m_address),
18549                           m_is_stmt, m_discriminator);
18550     }
18551
18552   file_entry *fe = current_file ();
18553
18554   if (fe == NULL)
18555     dwarf2_debug_line_missing_file_complaint ();
18556   /* For now we ignore lines not starting on an instruction boundary.
18557      But not when processing end_sequence for compatibility with the
18558      previous version of the code.  */
18559   else if (m_op_index == 0 || end_sequence)
18560     {
18561       fe->included_p = 1;
18562       if (m_record_lines_p && m_is_stmt)
18563         {
18564           if (m_last_subfile != current_subfile || end_sequence)
18565             {
18566               dwarf_finish_line (m_gdbarch, m_last_subfile,
18567                                  m_address, m_record_line_callback);
18568             }
18569
18570           if (!end_sequence)
18571             {
18572               if (dwarf_record_line_p (m_line, m_last_line,
18573                                        m_line_has_non_zero_discriminator,
18574                                        m_last_subfile))
18575                 {
18576                   dwarf_record_line_1 (m_gdbarch, current_subfile,
18577                                        m_line, m_address,
18578                                        m_record_line_callback);
18579                 }
18580               m_last_subfile = current_subfile;
18581               m_last_line = m_line;
18582             }
18583         }
18584     }
18585 }
18586
18587 lnp_state_machine::lnp_state_machine (gdbarch *arch, line_header *lh,
18588                                       bool record_lines_p)
18589 {
18590   m_gdbarch = arch;
18591   m_record_lines_p = record_lines_p;
18592   m_line_header = lh;
18593
18594   m_record_line_callback = ::record_line;
18595
18596   /* Call `gdbarch_adjust_dwarf2_line' on the initial 0 address as if there
18597      was a line entry for it so that the backend has a chance to adjust it
18598      and also record it in case it needs it.  This is currently used by MIPS
18599      code, cf. `mips_adjust_dwarf2_line'.  */
18600   m_address = gdbarch_adjust_dwarf2_line (arch, 0, 0);
18601   m_is_stmt = lh->default_is_stmt;
18602   m_discriminator = 0;
18603 }
18604
18605 void
18606 lnp_state_machine::check_line_address (struct dwarf2_cu *cu,
18607                                        const gdb_byte *line_ptr,
18608                                        CORE_ADDR lowpc, CORE_ADDR address)
18609 {
18610   /* If address < lowpc then it's not a usable value, it's outside the
18611      pc range of the CU.  However, we restrict the test to only address
18612      values of zero to preserve GDB's previous behaviour which is to
18613      handle the specific case of a function being GC'd by the linker.  */
18614
18615   if (address == 0 && address < lowpc)
18616     {
18617       /* This line table is for a function which has been
18618          GCd by the linker.  Ignore it.  PR gdb/12528 */
18619
18620       struct objfile *objfile = cu->objfile;
18621       long line_offset = line_ptr - get_debug_line_section (cu)->buffer;
18622
18623       complaint (&symfile_complaints,
18624                  _(".debug_line address at offset 0x%lx is 0 [in module %s]"),
18625                  line_offset, objfile_name (objfile));
18626       m_record_line_callback = noop_record_line;
18627       /* Note: record_line_callback is left as noop_record_line until
18628          we see DW_LNE_end_sequence.  */
18629     }
18630 }
18631
18632 /* Subroutine of dwarf_decode_lines to simplify it.
18633    Process the line number information in LH.
18634    If DECODE_FOR_PST_P is non-zero, all we do is process the line number
18635    program in order to set included_p for every referenced header.  */
18636
18637 static void
18638 dwarf_decode_lines_1 (struct line_header *lh, struct dwarf2_cu *cu,
18639                       const int decode_for_pst_p, CORE_ADDR lowpc)
18640 {
18641   const gdb_byte *line_ptr, *extended_end;
18642   const gdb_byte *line_end;
18643   unsigned int bytes_read, extended_len;
18644   unsigned char op_code, extended_op;
18645   CORE_ADDR baseaddr;
18646   struct objfile *objfile = cu->objfile;
18647   bfd *abfd = objfile->obfd;
18648   struct gdbarch *gdbarch = get_objfile_arch (objfile);
18649   /* True if we're recording line info (as opposed to building partial
18650      symtabs and just interested in finding include files mentioned by
18651      the line number program).  */
18652   bool record_lines_p = !decode_for_pst_p;
18653
18654   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
18655
18656   line_ptr = lh->statement_program_start;
18657   line_end = lh->statement_program_end;
18658
18659   /* Read the statement sequences until there's nothing left.  */
18660   while (line_ptr < line_end)
18661     {
18662       /* The DWARF line number program state machine.  Reset the state
18663          machine at the start of each sequence.  */
18664       lnp_state_machine state_machine (gdbarch, lh, record_lines_p);
18665       bool end_sequence = false;
18666
18667       if (record_lines_p)
18668         {
18669           /* Start a subfile for the current file of the state
18670              machine.  */
18671           const file_entry *fe = state_machine.current_file ();
18672
18673           if (fe != NULL)
18674             dwarf2_start_subfile (fe->name, fe->include_dir (lh));
18675         }
18676
18677       /* Decode the table.  */
18678       while (line_ptr < line_end && !end_sequence)
18679         {
18680           op_code = read_1_byte (abfd, line_ptr);
18681           line_ptr += 1;
18682
18683           if (op_code >= lh->opcode_base)
18684             {
18685               /* Special opcode.  */
18686               state_machine.handle_special_opcode (op_code);
18687             }
18688           else switch (op_code)
18689             {
18690             case DW_LNS_extended_op:
18691               extended_len = read_unsigned_leb128 (abfd, line_ptr,
18692                                                    &bytes_read);
18693               line_ptr += bytes_read;
18694               extended_end = line_ptr + extended_len;
18695               extended_op = read_1_byte (abfd, line_ptr);
18696               line_ptr += 1;
18697               switch (extended_op)
18698                 {
18699                 case DW_LNE_end_sequence:
18700                   state_machine.handle_end_sequence ();
18701                   end_sequence = true;
18702                   break;
18703                 case DW_LNE_set_address:
18704                   {
18705                     CORE_ADDR address
18706                       = read_address (abfd, line_ptr, cu, &bytes_read);
18707                     line_ptr += bytes_read;
18708
18709                     state_machine.check_line_address (cu, line_ptr,
18710                                                       lowpc, address);
18711                     state_machine.handle_set_address (baseaddr, address);
18712                   }
18713                   break;
18714                 case DW_LNE_define_file:
18715                   {
18716                     const char *cur_file;
18717                     unsigned int mod_time, length;
18718                     dir_index dindex;
18719
18720                     cur_file = read_direct_string (abfd, line_ptr,
18721                                                    &bytes_read);
18722                     line_ptr += bytes_read;
18723                     dindex = (dir_index)
18724                       read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
18725                     line_ptr += bytes_read;
18726                     mod_time =
18727                       read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
18728                     line_ptr += bytes_read;
18729                     length =
18730                       read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
18731                     line_ptr += bytes_read;
18732                     lh->add_file_name (cur_file, dindex, mod_time, length);
18733                   }
18734                   break;
18735                 case DW_LNE_set_discriminator:
18736                   {
18737                     /* The discriminator is not interesting to the
18738                        debugger; just ignore it.  We still need to
18739                        check its value though:
18740                        if there are consecutive entries for the same
18741                        (non-prologue) line we want to coalesce them.
18742                        PR 17276.  */
18743                     unsigned int discr
18744                       = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
18745                     line_ptr += bytes_read;
18746
18747                     state_machine.handle_set_discriminator (discr);
18748                   }
18749                   break;
18750                 default:
18751                   complaint (&symfile_complaints,
18752                              _("mangled .debug_line section"));
18753                   return;
18754                 }
18755               /* Make sure that we parsed the extended op correctly.  If e.g.
18756                  we expected a different address size than the producer used,
18757                  we may have read the wrong number of bytes.  */
18758               if (line_ptr != extended_end)
18759                 {
18760                   complaint (&symfile_complaints,
18761                              _("mangled .debug_line section"));
18762                   return;
18763                 }
18764               break;
18765             case DW_LNS_copy:
18766               state_machine.handle_copy ();
18767               break;
18768             case DW_LNS_advance_pc:
18769               {
18770                 CORE_ADDR adjust
18771                   = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
18772                 line_ptr += bytes_read;
18773
18774                 state_machine.handle_advance_pc (adjust);
18775               }
18776               break;
18777             case DW_LNS_advance_line:
18778               {
18779                 int line_delta
18780                   = read_signed_leb128 (abfd, line_ptr, &bytes_read);
18781                 line_ptr += bytes_read;
18782
18783                 state_machine.handle_advance_line (line_delta);
18784               }
18785               break;
18786             case DW_LNS_set_file:
18787               {
18788                 file_name_index file
18789                   = (file_name_index) read_unsigned_leb128 (abfd, line_ptr,
18790                                                             &bytes_read);
18791                 line_ptr += bytes_read;
18792
18793                 state_machine.handle_set_file (file);
18794               }
18795               break;
18796             case DW_LNS_set_column:
18797               (void) read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
18798               line_ptr += bytes_read;
18799               break;
18800             case DW_LNS_negate_stmt:
18801               state_machine.handle_negate_stmt ();
18802               break;
18803             case DW_LNS_set_basic_block:
18804               break;
18805             /* Add to the address register of the state machine the
18806                address increment value corresponding to special opcode
18807                255.  I.e., this value is scaled by the minimum
18808                instruction length since special opcode 255 would have
18809                scaled the increment.  */
18810             case DW_LNS_const_add_pc:
18811               state_machine.handle_const_add_pc ();
18812               break;
18813             case DW_LNS_fixed_advance_pc:
18814               {
18815                 CORE_ADDR addr_adj = read_2_bytes (abfd, line_ptr);
18816                 line_ptr += 2;
18817
18818                 state_machine.handle_fixed_advance_pc (addr_adj);
18819               }
18820               break;
18821             default:
18822               {
18823                 /* Unknown standard opcode, ignore it.  */
18824                 int i;
18825
18826                 for (i = 0; i < lh->standard_opcode_lengths[op_code]; i++)
18827                   {
18828                     (void) read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
18829                     line_ptr += bytes_read;
18830                   }
18831               }
18832             }
18833         }
18834
18835       if (!end_sequence)
18836         dwarf2_debug_line_missing_end_sequence_complaint ();
18837
18838       /* We got a DW_LNE_end_sequence (or we ran off the end of the buffer,
18839          in which case we still finish recording the last line).  */
18840       state_machine.record_line (true);
18841     }
18842 }
18843
18844 /* Decode the Line Number Program (LNP) for the given line_header
18845    structure and CU.  The actual information extracted and the type
18846    of structures created from the LNP depends on the value of PST.
18847
18848    1. If PST is NULL, then this procedure uses the data from the program
18849       to create all necessary symbol tables, and their linetables.
18850
18851    2. If PST is not NULL, this procedure reads the program to determine
18852       the list of files included by the unit represented by PST, and
18853       builds all the associated partial symbol tables.
18854
18855    COMP_DIR is the compilation directory (DW_AT_comp_dir) or NULL if unknown.
18856    It is used for relative paths in the line table.
18857    NOTE: When processing partial symtabs (pst != NULL),
18858    comp_dir == pst->dirname.
18859
18860    NOTE: It is important that psymtabs have the same file name (via strcmp)
18861    as the corresponding symtab.  Since COMP_DIR is not used in the name of the
18862    symtab we don't use it in the name of the psymtabs we create.
18863    E.g. expand_line_sal requires this when finding psymtabs to expand.
18864    A good testcase for this is mb-inline.exp.
18865
18866    LOWPC is the lowest address in CU (or 0 if not known).
18867
18868    Boolean DECODE_MAPPING specifies we need to fully decode .debug_line
18869    for its PC<->lines mapping information.  Otherwise only the filename
18870    table is read in.  */
18871
18872 static void
18873 dwarf_decode_lines (struct line_header *lh, const char *comp_dir,
18874                     struct dwarf2_cu *cu, struct partial_symtab *pst,
18875                     CORE_ADDR lowpc, int decode_mapping)
18876 {
18877   struct objfile *objfile = cu->objfile;
18878   const int decode_for_pst_p = (pst != NULL);
18879
18880   if (decode_mapping)
18881     dwarf_decode_lines_1 (lh, cu, decode_for_pst_p, lowpc);
18882
18883   if (decode_for_pst_p)
18884     {
18885       int file_index;
18886
18887       /* Now that we're done scanning the Line Header Program, we can
18888          create the psymtab of each included file.  */
18889       for (file_index = 0; file_index < lh->file_names.size (); file_index++)
18890         if (lh->file_names[file_index].included_p == 1)
18891           {
18892             const char *include_name =
18893               psymtab_include_file_name (lh, file_index, pst, comp_dir);
18894             if (include_name != NULL)
18895               dwarf2_create_include_psymtab (include_name, pst, objfile);
18896           }
18897     }
18898   else
18899     {
18900       /* Make sure a symtab is created for every file, even files
18901          which contain only variables (i.e. no code with associated
18902          line numbers).  */
18903       struct compunit_symtab *cust = buildsym_compunit_symtab ();
18904       int i;
18905
18906       for (i = 0; i < lh->file_names.size (); i++)
18907         {
18908           file_entry &fe = lh->file_names[i];
18909
18910           dwarf2_start_subfile (fe.name, fe.include_dir (lh));
18911
18912           if (current_subfile->symtab == NULL)
18913             {
18914               current_subfile->symtab
18915                 = allocate_symtab (cust, current_subfile->name);
18916             }
18917           fe.symtab = current_subfile->symtab;
18918         }
18919     }
18920 }
18921
18922 /* Start a subfile for DWARF.  FILENAME is the name of the file and
18923    DIRNAME the name of the source directory which contains FILENAME
18924    or NULL if not known.
18925    This routine tries to keep line numbers from identical absolute and
18926    relative file names in a common subfile.
18927
18928    Using the `list' example from the GDB testsuite, which resides in
18929    /srcdir and compiling it with Irix6.2 cc in /compdir using a filename
18930    of /srcdir/list0.c yields the following debugging information for list0.c:
18931
18932    DW_AT_name:          /srcdir/list0.c
18933    DW_AT_comp_dir:      /compdir
18934    files.files[0].name: list0.h
18935    files.files[0].dir:  /srcdir
18936    files.files[1].name: list0.c
18937    files.files[1].dir:  /srcdir
18938
18939    The line number information for list0.c has to end up in a single
18940    subfile, so that `break /srcdir/list0.c:1' works as expected.
18941    start_subfile will ensure that this happens provided that we pass the
18942    concatenation of files.files[1].dir and files.files[1].name as the
18943    subfile's name.  */
18944
18945 static void
18946 dwarf2_start_subfile (const char *filename, const char *dirname)
18947 {
18948   char *copy = NULL;
18949
18950   /* In order not to lose the line information directory,
18951      we concatenate it to the filename when it makes sense.
18952      Note that the Dwarf3 standard says (speaking of filenames in line
18953      information): ``The directory index is ignored for file names
18954      that represent full path names''.  Thus ignoring dirname in the
18955      `else' branch below isn't an issue.  */
18956
18957   if (!IS_ABSOLUTE_PATH (filename) && dirname != NULL)
18958     {
18959       copy = concat (dirname, SLASH_STRING, filename, (char *)NULL);
18960       filename = copy;
18961     }
18962
18963   start_subfile (filename);
18964
18965   if (copy != NULL)
18966     xfree (copy);
18967 }
18968
18969 /* Start a symtab for DWARF.
18970    NAME, COMP_DIR, LOW_PC are passed to start_symtab.  */
18971
18972 static struct compunit_symtab *
18973 dwarf2_start_symtab (struct dwarf2_cu *cu,
18974                      const char *name, const char *comp_dir, CORE_ADDR low_pc)
18975 {
18976   struct compunit_symtab *cust
18977     = start_symtab (cu->objfile, name, comp_dir, low_pc);
18978
18979   record_debugformat ("DWARF 2");
18980   record_producer (cu->producer);
18981
18982   /* We assume that we're processing GCC output.  */
18983   processing_gcc_compilation = 2;
18984
18985   cu->processing_has_namespace_info = 0;
18986
18987   return cust;
18988 }
18989
18990 static void
18991 var_decode_location (struct attribute *attr, struct symbol *sym,
18992                      struct dwarf2_cu *cu)
18993 {
18994   struct objfile *objfile = cu->objfile;
18995   struct comp_unit_head *cu_header = &cu->header;
18996
18997   /* NOTE drow/2003-01-30: There used to be a comment and some special
18998      code here to turn a symbol with DW_AT_external and a
18999      SYMBOL_VALUE_ADDRESS of 0 into a LOC_UNRESOLVED symbol.  This was
19000      necessary for platforms (maybe Alpha, certainly PowerPC GNU/Linux
19001      with some versions of binutils) where shared libraries could have
19002      relocations against symbols in their debug information - the
19003      minimal symbol would have the right address, but the debug info
19004      would not.  It's no longer necessary, because we will explicitly
19005      apply relocations when we read in the debug information now.  */
19006
19007   /* A DW_AT_location attribute with no contents indicates that a
19008      variable has been optimized away.  */
19009   if (attr_form_is_block (attr) && DW_BLOCK (attr)->size == 0)
19010     {
19011       SYMBOL_ACLASS_INDEX (sym) = LOC_OPTIMIZED_OUT;
19012       return;
19013     }
19014
19015   /* Handle one degenerate form of location expression specially, to
19016      preserve GDB's previous behavior when section offsets are
19017      specified.  If this is just a DW_OP_addr or DW_OP_GNU_addr_index
19018      then mark this symbol as LOC_STATIC.  */
19019
19020   if (attr_form_is_block (attr)
19021       && ((DW_BLOCK (attr)->data[0] == DW_OP_addr
19022            && DW_BLOCK (attr)->size == 1 + cu_header->addr_size)
19023           || (DW_BLOCK (attr)->data[0] == DW_OP_GNU_addr_index
19024               && (DW_BLOCK (attr)->size
19025                   == 1 + leb128_size (&DW_BLOCK (attr)->data[1])))))
19026     {
19027       unsigned int dummy;
19028
19029       if (DW_BLOCK (attr)->data[0] == DW_OP_addr)
19030         SYMBOL_VALUE_ADDRESS (sym) =
19031           read_address (objfile->obfd, DW_BLOCK (attr)->data + 1, cu, &dummy);
19032       else
19033         SYMBOL_VALUE_ADDRESS (sym) =
19034           read_addr_index_from_leb128 (cu, DW_BLOCK (attr)->data + 1, &dummy);
19035       SYMBOL_ACLASS_INDEX (sym) = LOC_STATIC;
19036       fixup_symbol_section (sym, objfile);
19037       SYMBOL_VALUE_ADDRESS (sym) += ANOFFSET (objfile->section_offsets,
19038                                               SYMBOL_SECTION (sym));
19039       return;
19040     }
19041
19042   /* NOTE drow/2002-01-30: It might be worthwhile to have a static
19043      expression evaluator, and use LOC_COMPUTED only when necessary
19044      (i.e. when the value of a register or memory location is
19045      referenced, or a thread-local block, etc.).  Then again, it might
19046      not be worthwhile.  I'm assuming that it isn't unless performance
19047      or memory numbers show me otherwise.  */
19048
19049   dwarf2_symbol_mark_computed (attr, sym, cu, 0);
19050
19051   if (SYMBOL_COMPUTED_OPS (sym)->location_has_loclist)
19052     cu->has_loclist = 1;
19053 }
19054
19055 /* Given a pointer to a DWARF information entry, figure out if we need
19056    to make a symbol table entry for it, and if so, create a new entry
19057    and return a pointer to it.
19058    If TYPE is NULL, determine symbol type from the die, otherwise
19059    used the passed type.
19060    If SPACE is not NULL, use it to hold the new symbol.  If it is
19061    NULL, allocate a new symbol on the objfile's obstack.  */
19062
19063 static struct symbol *
19064 new_symbol_full (struct die_info *die, struct type *type, struct dwarf2_cu *cu,
19065                  struct symbol *space)
19066 {
19067   struct objfile *objfile = cu->objfile;
19068   struct gdbarch *gdbarch = get_objfile_arch (objfile);
19069   struct symbol *sym = NULL;
19070   const char *name;
19071   struct attribute *attr = NULL;
19072   struct attribute *attr2 = NULL;
19073   CORE_ADDR baseaddr;
19074   struct pending **list_to_add = NULL;
19075
19076   int inlined_func = (die->tag == DW_TAG_inlined_subroutine);
19077
19078   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
19079
19080   name = dwarf2_name (die, cu);
19081   if (name)
19082     {
19083       const char *linkagename;
19084       int suppress_add = 0;
19085
19086       if (space)
19087         sym = space;
19088       else
19089         sym = allocate_symbol (objfile);
19090       OBJSTAT (objfile, n_syms++);
19091
19092       /* Cache this symbol's name and the name's demangled form (if any).  */
19093       SYMBOL_SET_LANGUAGE (sym, cu->language, &objfile->objfile_obstack);
19094       linkagename = dwarf2_physname (name, die, cu);
19095       SYMBOL_SET_NAMES (sym, linkagename, strlen (linkagename), 0, objfile);
19096
19097       /* Fortran does not have mangling standard and the mangling does differ
19098          between gfortran, iFort etc.  */
19099       if (cu->language == language_fortran
19100           && symbol_get_demangled_name (&(sym->ginfo)) == NULL)
19101         symbol_set_demangled_name (&(sym->ginfo),
19102                                    dwarf2_full_name (name, die, cu),
19103                                    NULL);
19104
19105       /* Default assumptions.
19106          Use the passed type or decode it from the die.  */
19107       SYMBOL_DOMAIN (sym) = VAR_DOMAIN;
19108       SYMBOL_ACLASS_INDEX (sym) = LOC_OPTIMIZED_OUT;
19109       if (type != NULL)
19110         SYMBOL_TYPE (sym) = type;
19111       else
19112         SYMBOL_TYPE (sym) = die_type (die, cu);
19113       attr = dwarf2_attr (die,
19114                           inlined_func ? DW_AT_call_line : DW_AT_decl_line,
19115                           cu);
19116       if (attr)
19117         {
19118           SYMBOL_LINE (sym) = DW_UNSND (attr);
19119         }
19120
19121       attr = dwarf2_attr (die,
19122                           inlined_func ? DW_AT_call_file : DW_AT_decl_file,
19123                           cu);
19124       if (attr)
19125         {
19126           file_name_index file_index = (file_name_index) DW_UNSND (attr);
19127           struct file_entry *fe;
19128
19129           if (cu->line_header != NULL)
19130             fe = cu->line_header->file_name_at (file_index);
19131           else
19132             fe = NULL;
19133
19134           if (fe == NULL)
19135             complaint (&symfile_complaints,
19136                        _("file index out of range"));
19137           else
19138             symbol_set_symtab (sym, fe->symtab);
19139         }
19140
19141       switch (die->tag)
19142         {
19143         case DW_TAG_label:
19144           attr = dwarf2_attr (die, DW_AT_low_pc, cu);
19145           if (attr)
19146             {
19147               CORE_ADDR addr;
19148
19149               addr = attr_value_as_address (attr);
19150               addr = gdbarch_adjust_dwarf2_addr (gdbarch, addr + baseaddr);
19151               SYMBOL_VALUE_ADDRESS (sym) = addr;
19152             }
19153           SYMBOL_TYPE (sym) = objfile_type (objfile)->builtin_core_addr;
19154           SYMBOL_DOMAIN (sym) = LABEL_DOMAIN;
19155           SYMBOL_ACLASS_INDEX (sym) = LOC_LABEL;
19156           add_symbol_to_list (sym, cu->list_in_scope);
19157           break;
19158         case DW_TAG_subprogram:
19159           /* SYMBOL_BLOCK_VALUE (sym) will be filled in later by
19160              finish_block.  */
19161           SYMBOL_ACLASS_INDEX (sym) = LOC_BLOCK;
19162           attr2 = dwarf2_attr (die, DW_AT_external, cu);
19163           if ((attr2 && (DW_UNSND (attr2) != 0))
19164               || cu->language == language_ada)
19165             {
19166               /* Subprograms marked external are stored as a global symbol.
19167                  Ada subprograms, whether marked external or not, are always
19168                  stored as a global symbol, because we want to be able to
19169                  access them globally.  For instance, we want to be able
19170                  to break on a nested subprogram without having to
19171                  specify the context.  */
19172               list_to_add = &global_symbols;
19173             }
19174           else
19175             {
19176               list_to_add = cu->list_in_scope;
19177             }
19178           break;
19179         case DW_TAG_inlined_subroutine:
19180           /* SYMBOL_BLOCK_VALUE (sym) will be filled in later by
19181              finish_block.  */
19182           SYMBOL_ACLASS_INDEX (sym) = LOC_BLOCK;
19183           SYMBOL_INLINED (sym) = 1;
19184           list_to_add = cu->list_in_scope;
19185           break;
19186         case DW_TAG_template_value_param:
19187           suppress_add = 1;
19188           /* Fall through.  */
19189         case DW_TAG_constant:
19190         case DW_TAG_variable:
19191         case DW_TAG_member:
19192           /* Compilation with minimal debug info may result in
19193              variables with missing type entries.  Change the
19194              misleading `void' type to something sensible.  */
19195           if (TYPE_CODE (SYMBOL_TYPE (sym)) == TYPE_CODE_VOID)
19196             SYMBOL_TYPE (sym) = objfile_type (objfile)->builtin_int;
19197
19198           attr = dwarf2_attr (die, DW_AT_const_value, cu);
19199           /* In the case of DW_TAG_member, we should only be called for
19200              static const members.  */
19201           if (die->tag == DW_TAG_member)
19202             {
19203               /* dwarf2_add_field uses die_is_declaration,
19204                  so we do the same.  */
19205               gdb_assert (die_is_declaration (die, cu));
19206               gdb_assert (attr);
19207             }
19208           if (attr)
19209             {
19210               dwarf2_const_value (attr, sym, cu);
19211               attr2 = dwarf2_attr (die, DW_AT_external, cu);
19212               if (!suppress_add)
19213                 {
19214                   if (attr2 && (DW_UNSND (attr2) != 0))
19215                     list_to_add = &global_symbols;
19216                   else
19217                     list_to_add = cu->list_in_scope;
19218                 }
19219               break;
19220             }
19221           attr = dwarf2_attr (die, DW_AT_location, cu);
19222           if (attr)
19223             {
19224               var_decode_location (attr, sym, cu);
19225               attr2 = dwarf2_attr (die, DW_AT_external, cu);
19226
19227               /* Fortran explicitly imports any global symbols to the local
19228                  scope by DW_TAG_common_block.  */
19229               if (cu->language == language_fortran && die->parent
19230                   && die->parent->tag == DW_TAG_common_block)
19231                 attr2 = NULL;
19232
19233               if (SYMBOL_CLASS (sym) == LOC_STATIC
19234                   && SYMBOL_VALUE_ADDRESS (sym) == 0
19235                   && !dwarf2_per_objfile->has_section_at_zero)
19236                 {
19237                   /* When a static variable is eliminated by the linker,
19238                      the corresponding debug information is not stripped
19239                      out, but the variable address is set to null;
19240                      do not add such variables into symbol table.  */
19241                 }
19242               else if (attr2 && (DW_UNSND (attr2) != 0))
19243                 {
19244                   /* Workaround gfortran PR debug/40040 - it uses
19245                      DW_AT_location for variables in -fPIC libraries which may
19246                      get overriden by other libraries/executable and get
19247                      a different address.  Resolve it by the minimal symbol
19248                      which may come from inferior's executable using copy
19249                      relocation.  Make this workaround only for gfortran as for
19250                      other compilers GDB cannot guess the minimal symbol
19251                      Fortran mangling kind.  */
19252                   if (cu->language == language_fortran && die->parent
19253                       && die->parent->tag == DW_TAG_module
19254                       && cu->producer
19255                       && startswith (cu->producer, "GNU Fortran"))
19256                     SYMBOL_ACLASS_INDEX (sym) = LOC_UNRESOLVED;
19257
19258                   /* A variable with DW_AT_external is never static,
19259                      but it may be block-scoped.  */
19260                   list_to_add = (cu->list_in_scope == &file_symbols
19261                                  ? &global_symbols : cu->list_in_scope);
19262                 }
19263               else
19264                 list_to_add = cu->list_in_scope;
19265             }
19266           else
19267             {
19268               /* We do not know the address of this symbol.
19269                  If it is an external symbol and we have type information
19270                  for it, enter the symbol as a LOC_UNRESOLVED symbol.
19271                  The address of the variable will then be determined from
19272                  the minimal symbol table whenever the variable is
19273                  referenced.  */
19274               attr2 = dwarf2_attr (die, DW_AT_external, cu);
19275
19276               /* Fortran explicitly imports any global symbols to the local
19277                  scope by DW_TAG_common_block.  */
19278               if (cu->language == language_fortran && die->parent
19279                   && die->parent->tag == DW_TAG_common_block)
19280                 {
19281                   /* SYMBOL_CLASS doesn't matter here because
19282                      read_common_block is going to reset it.  */
19283                   if (!suppress_add)
19284                     list_to_add = cu->list_in_scope;
19285                 }
19286               else if (attr2 && (DW_UNSND (attr2) != 0)
19287                        && dwarf2_attr (die, DW_AT_type, cu) != NULL)
19288                 {
19289                   /* A variable with DW_AT_external is never static, but it
19290                      may be block-scoped.  */
19291                   list_to_add = (cu->list_in_scope == &file_symbols
19292                                  ? &global_symbols : cu->list_in_scope);
19293
19294                   SYMBOL_ACLASS_INDEX (sym) = LOC_UNRESOLVED;
19295                 }
19296               else if (!die_is_declaration (die, cu))
19297                 {
19298                   /* Use the default LOC_OPTIMIZED_OUT class.  */
19299                   gdb_assert (SYMBOL_CLASS (sym) == LOC_OPTIMIZED_OUT);
19300                   if (!suppress_add)
19301                     list_to_add = cu->list_in_scope;
19302                 }
19303             }
19304           break;
19305         case DW_TAG_formal_parameter:
19306           /* If we are inside a function, mark this as an argument.  If
19307              not, we might be looking at an argument to an inlined function
19308              when we do not have enough information to show inlined frames;
19309              pretend it's a local variable in that case so that the user can
19310              still see it.  */
19311           if (context_stack_depth > 0
19312               && context_stack[context_stack_depth - 1].name != NULL)
19313             SYMBOL_IS_ARGUMENT (sym) = 1;
19314           attr = dwarf2_attr (die, DW_AT_location, cu);
19315           if (attr)
19316             {
19317               var_decode_location (attr, sym, cu);
19318             }
19319           attr = dwarf2_attr (die, DW_AT_const_value, cu);
19320           if (attr)
19321             {
19322               dwarf2_const_value (attr, sym, cu);
19323             }
19324
19325           list_to_add = cu->list_in_scope;
19326           break;
19327         case DW_TAG_unspecified_parameters:
19328           /* From varargs functions; gdb doesn't seem to have any
19329              interest in this information, so just ignore it for now.
19330              (FIXME?) */
19331           break;
19332         case DW_TAG_template_type_param:
19333           suppress_add = 1;
19334           /* Fall through.  */
19335         case DW_TAG_class_type:
19336         case DW_TAG_interface_type:
19337         case DW_TAG_structure_type:
19338         case DW_TAG_union_type:
19339         case DW_TAG_set_type:
19340         case DW_TAG_enumeration_type:
19341           SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
19342           SYMBOL_DOMAIN (sym) = STRUCT_DOMAIN;
19343
19344           {
19345             /* NOTE: carlton/2003-11-10: C++ class symbols shouldn't
19346                really ever be static objects: otherwise, if you try
19347                to, say, break of a class's method and you're in a file
19348                which doesn't mention that class, it won't work unless
19349                the check for all static symbols in lookup_symbol_aux
19350                saves you.  See the OtherFileClass tests in
19351                gdb.c++/namespace.exp.  */
19352
19353             if (!suppress_add)
19354               {
19355                 list_to_add = (cu->list_in_scope == &file_symbols
19356                                && cu->language == language_cplus
19357                                ? &global_symbols : cu->list_in_scope);
19358
19359                 /* The semantics of C++ state that "struct foo {
19360                    ... }" also defines a typedef for "foo".  */
19361                 if (cu->language == language_cplus
19362                     || cu->language == language_ada
19363                     || cu->language == language_d
19364                     || cu->language == language_rust)
19365                   {
19366                     /* The symbol's name is already allocated along
19367                        with this objfile, so we don't need to
19368                        duplicate it for the type.  */
19369                     if (TYPE_NAME (SYMBOL_TYPE (sym)) == 0)
19370                       TYPE_NAME (SYMBOL_TYPE (sym)) = SYMBOL_SEARCH_NAME (sym);
19371                   }
19372               }
19373           }
19374           break;
19375         case DW_TAG_typedef:
19376           SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
19377           SYMBOL_DOMAIN (sym) = VAR_DOMAIN;
19378           list_to_add = cu->list_in_scope;
19379           break;
19380         case DW_TAG_base_type:
19381         case DW_TAG_subrange_type:
19382           SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
19383           SYMBOL_DOMAIN (sym) = VAR_DOMAIN;
19384           list_to_add = cu->list_in_scope;
19385           break;
19386         case DW_TAG_enumerator:
19387           attr = dwarf2_attr (die, DW_AT_const_value, cu);
19388           if (attr)
19389             {
19390               dwarf2_const_value (attr, sym, cu);
19391             }
19392           {
19393             /* NOTE: carlton/2003-11-10: See comment above in the
19394                DW_TAG_class_type, etc. block.  */
19395
19396             list_to_add = (cu->list_in_scope == &file_symbols
19397                            && cu->language == language_cplus
19398                            ? &global_symbols : cu->list_in_scope);
19399           }
19400           break;
19401         case DW_TAG_imported_declaration:
19402         case DW_TAG_namespace:
19403           SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
19404           list_to_add = &global_symbols;
19405           break;
19406         case DW_TAG_module:
19407           SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
19408           SYMBOL_DOMAIN (sym) = MODULE_DOMAIN;
19409           list_to_add = &global_symbols;
19410           break;
19411         case DW_TAG_common_block:
19412           SYMBOL_ACLASS_INDEX (sym) = LOC_COMMON_BLOCK;
19413           SYMBOL_DOMAIN (sym) = COMMON_BLOCK_DOMAIN;
19414           add_symbol_to_list (sym, cu->list_in_scope);
19415           break;
19416         default:
19417           /* Not a tag we recognize.  Hopefully we aren't processing
19418              trash data, but since we must specifically ignore things
19419              we don't recognize, there is nothing else we should do at
19420              this point.  */
19421           complaint (&symfile_complaints, _("unsupported tag: '%s'"),
19422                      dwarf_tag_name (die->tag));
19423           break;
19424         }
19425
19426       if (suppress_add)
19427         {
19428           sym->hash_next = objfile->template_symbols;
19429           objfile->template_symbols = sym;
19430           list_to_add = NULL;
19431         }
19432
19433       if (list_to_add != NULL)
19434         add_symbol_to_list (sym, list_to_add);
19435
19436       /* For the benefit of old versions of GCC, check for anonymous
19437          namespaces based on the demangled name.  */
19438       if (!cu->processing_has_namespace_info
19439           && cu->language == language_cplus)
19440         cp_scan_for_anonymous_namespaces (sym, objfile);
19441     }
19442   return (sym);
19443 }
19444
19445 /* A wrapper for new_symbol_full that always allocates a new symbol.  */
19446
19447 static struct symbol *
19448 new_symbol (struct die_info *die, struct type *type, struct dwarf2_cu *cu)
19449 {
19450   return new_symbol_full (die, type, cu, NULL);
19451 }
19452
19453 /* Given an attr with a DW_FORM_dataN value in host byte order,
19454    zero-extend it as appropriate for the symbol's type.  The DWARF
19455    standard (v4) is not entirely clear about the meaning of using
19456    DW_FORM_dataN for a constant with a signed type, where the type is
19457    wider than the data.  The conclusion of a discussion on the DWARF
19458    list was that this is unspecified.  We choose to always zero-extend
19459    because that is the interpretation long in use by GCC.  */
19460
19461 static gdb_byte *
19462 dwarf2_const_value_data (const struct attribute *attr, struct obstack *obstack,
19463                          struct dwarf2_cu *cu, LONGEST *value, int bits)
19464 {
19465   struct objfile *objfile = cu->objfile;
19466   enum bfd_endian byte_order = bfd_big_endian (objfile->obfd) ?
19467                                 BFD_ENDIAN_BIG : BFD_ENDIAN_LITTLE;
19468   LONGEST l = DW_UNSND (attr);
19469
19470   if (bits < sizeof (*value) * 8)
19471     {
19472       l &= ((LONGEST) 1 << bits) - 1;
19473       *value = l;
19474     }
19475   else if (bits == sizeof (*value) * 8)
19476     *value = l;
19477   else
19478     {
19479       gdb_byte *bytes = (gdb_byte *) obstack_alloc (obstack, bits / 8);
19480       store_unsigned_integer (bytes, bits / 8, byte_order, l);
19481       return bytes;
19482     }
19483
19484   return NULL;
19485 }
19486
19487 /* Read a constant value from an attribute.  Either set *VALUE, or if
19488    the value does not fit in *VALUE, set *BYTES - either already
19489    allocated on the objfile obstack, or newly allocated on OBSTACK,
19490    or, set *BATON, if we translated the constant to a location
19491    expression.  */
19492
19493 static void
19494 dwarf2_const_value_attr (const struct attribute *attr, struct type *type,
19495                          const char *name, struct obstack *obstack,
19496                          struct dwarf2_cu *cu,
19497                          LONGEST *value, const gdb_byte **bytes,
19498                          struct dwarf2_locexpr_baton **baton)
19499 {
19500   struct objfile *objfile = cu->objfile;
19501   struct comp_unit_head *cu_header = &cu->header;
19502   struct dwarf_block *blk;
19503   enum bfd_endian byte_order = (bfd_big_endian (objfile->obfd) ?
19504                                 BFD_ENDIAN_BIG : BFD_ENDIAN_LITTLE);
19505
19506   *value = 0;
19507   *bytes = NULL;
19508   *baton = NULL;
19509
19510   switch (attr->form)
19511     {
19512     case DW_FORM_addr:
19513     case DW_FORM_GNU_addr_index:
19514       {
19515         gdb_byte *data;
19516
19517         if (TYPE_LENGTH (type) != cu_header->addr_size)
19518           dwarf2_const_value_length_mismatch_complaint (name,
19519                                                         cu_header->addr_size,
19520                                                         TYPE_LENGTH (type));
19521         /* Symbols of this form are reasonably rare, so we just
19522            piggyback on the existing location code rather than writing
19523            a new implementation of symbol_computed_ops.  */
19524         *baton = XOBNEW (obstack, struct dwarf2_locexpr_baton);
19525         (*baton)->per_cu = cu->per_cu;
19526         gdb_assert ((*baton)->per_cu);
19527
19528         (*baton)->size = 2 + cu_header->addr_size;
19529         data = (gdb_byte *) obstack_alloc (obstack, (*baton)->size);
19530         (*baton)->data = data;
19531
19532         data[0] = DW_OP_addr;
19533         store_unsigned_integer (&data[1], cu_header->addr_size,
19534                                 byte_order, DW_ADDR (attr));
19535         data[cu_header->addr_size + 1] = DW_OP_stack_value;
19536       }
19537       break;
19538     case DW_FORM_string:
19539     case DW_FORM_strp:
19540     case DW_FORM_GNU_str_index:
19541     case DW_FORM_GNU_strp_alt:
19542       /* DW_STRING is already allocated on the objfile obstack, point
19543          directly to it.  */
19544       *bytes = (const gdb_byte *) DW_STRING (attr);
19545       break;
19546     case DW_FORM_block1:
19547     case DW_FORM_block2:
19548     case DW_FORM_block4:
19549     case DW_FORM_block:
19550     case DW_FORM_exprloc:
19551     case DW_FORM_data16:
19552       blk = DW_BLOCK (attr);
19553       if (TYPE_LENGTH (type) != blk->size)
19554         dwarf2_const_value_length_mismatch_complaint (name, blk->size,
19555                                                       TYPE_LENGTH (type));
19556       *bytes = blk->data;
19557       break;
19558
19559       /* The DW_AT_const_value attributes are supposed to carry the
19560          symbol's value "represented as it would be on the target
19561          architecture."  By the time we get here, it's already been
19562          converted to host endianness, so we just need to sign- or
19563          zero-extend it as appropriate.  */
19564     case DW_FORM_data1:
19565       *bytes = dwarf2_const_value_data (attr, obstack, cu, value, 8);
19566       break;
19567     case DW_FORM_data2:
19568       *bytes = dwarf2_const_value_data (attr, obstack, cu, value, 16);
19569       break;
19570     case DW_FORM_data4:
19571       *bytes = dwarf2_const_value_data (attr, obstack, cu, value, 32);
19572       break;
19573     case DW_FORM_data8:
19574       *bytes = dwarf2_const_value_data (attr, obstack, cu, value, 64);
19575       break;
19576
19577     case DW_FORM_sdata:
19578     case DW_FORM_implicit_const:
19579       *value = DW_SND (attr);
19580       break;
19581
19582     case DW_FORM_udata:
19583       *value = DW_UNSND (attr);
19584       break;
19585
19586     default:
19587       complaint (&symfile_complaints,
19588                  _("unsupported const value attribute form: '%s'"),
19589                  dwarf_form_name (attr->form));
19590       *value = 0;
19591       break;
19592     }
19593 }
19594
19595
19596 /* Copy constant value from an attribute to a symbol.  */
19597
19598 static void
19599 dwarf2_const_value (const struct attribute *attr, struct symbol *sym,
19600                     struct dwarf2_cu *cu)
19601 {
19602   struct objfile *objfile = cu->objfile;
19603   LONGEST value;
19604   const gdb_byte *bytes;
19605   struct dwarf2_locexpr_baton *baton;
19606
19607   dwarf2_const_value_attr (attr, SYMBOL_TYPE (sym),
19608                            SYMBOL_PRINT_NAME (sym),
19609                            &objfile->objfile_obstack, cu,
19610                            &value, &bytes, &baton);
19611
19612   if (baton != NULL)
19613     {
19614       SYMBOL_LOCATION_BATON (sym) = baton;
19615       SYMBOL_ACLASS_INDEX (sym) = dwarf2_locexpr_index;
19616     }
19617   else if (bytes != NULL)
19618      {
19619       SYMBOL_VALUE_BYTES (sym) = bytes;
19620       SYMBOL_ACLASS_INDEX (sym) = LOC_CONST_BYTES;
19621     }
19622   else
19623     {
19624       SYMBOL_VALUE (sym) = value;
19625       SYMBOL_ACLASS_INDEX (sym) = LOC_CONST;
19626     }
19627 }
19628
19629 /* Return the type of the die in question using its DW_AT_type attribute.  */
19630
19631 static struct type *
19632 die_type (struct die_info *die, struct dwarf2_cu *cu)
19633 {
19634   struct attribute *type_attr;
19635
19636   type_attr = dwarf2_attr (die, DW_AT_type, cu);
19637   if (!type_attr)
19638     {
19639       /* A missing DW_AT_type represents a void type.  */
19640       return objfile_type (cu->objfile)->builtin_void;
19641     }
19642
19643   return lookup_die_type (die, type_attr, cu);
19644 }
19645
19646 /* True iff CU's producer generates GNAT Ada auxiliary information
19647    that allows to find parallel types through that information instead
19648    of having to do expensive parallel lookups by type name.  */
19649
19650 static int
19651 need_gnat_info (struct dwarf2_cu *cu)
19652 {
19653   /* FIXME: brobecker/2010-10-12: As of now, only the AdaCore version
19654      of GNAT produces this auxiliary information, without any indication
19655      that it is produced.  Part of enhancing the FSF version of GNAT
19656      to produce that information will be to put in place an indicator
19657      that we can use in order to determine whether the descriptive type
19658      info is available or not.  One suggestion that has been made is
19659      to use a new attribute, attached to the CU die.  For now, assume
19660      that the descriptive type info is not available.  */
19661   return 0;
19662 }
19663
19664 /* Return the auxiliary type of the die in question using its
19665    DW_AT_GNAT_descriptive_type attribute.  Returns NULL if the
19666    attribute is not present.  */
19667
19668 static struct type *
19669 die_descriptive_type (struct die_info *die, struct dwarf2_cu *cu)
19670 {
19671   struct attribute *type_attr;
19672
19673   type_attr = dwarf2_attr (die, DW_AT_GNAT_descriptive_type, cu);
19674   if (!type_attr)
19675     return NULL;
19676
19677   return lookup_die_type (die, type_attr, cu);
19678 }
19679
19680 /* If DIE has a descriptive_type attribute, then set the TYPE's
19681    descriptive type accordingly.  */
19682
19683 static void
19684 set_descriptive_type (struct type *type, struct die_info *die,
19685                       struct dwarf2_cu *cu)
19686 {
19687   struct type *descriptive_type = die_descriptive_type (die, cu);
19688
19689   if (descriptive_type)
19690     {
19691       ALLOCATE_GNAT_AUX_TYPE (type);
19692       TYPE_DESCRIPTIVE_TYPE (type) = descriptive_type;
19693     }
19694 }
19695
19696 /* Return the containing type of the die in question using its
19697    DW_AT_containing_type attribute.  */
19698
19699 static struct type *
19700 die_containing_type (struct die_info *die, struct dwarf2_cu *cu)
19701 {
19702   struct attribute *type_attr;
19703
19704   type_attr = dwarf2_attr (die, DW_AT_containing_type, cu);
19705   if (!type_attr)
19706     error (_("Dwarf Error: Problem turning containing type into gdb type "
19707              "[in module %s]"), objfile_name (cu->objfile));
19708
19709   return lookup_die_type (die, type_attr, cu);
19710 }
19711
19712 /* Return an error marker type to use for the ill formed type in DIE/CU.  */
19713
19714 static struct type *
19715 build_error_marker_type (struct dwarf2_cu *cu, struct die_info *die)
19716 {
19717   struct objfile *objfile = dwarf2_per_objfile->objfile;
19718   char *message, *saved;
19719
19720   message = xstrprintf (_("<unknown type in %s, CU 0x%x, DIE 0x%x>"),
19721                         objfile_name (objfile),
19722                         to_underlying (cu->header.sect_off),
19723                         to_underlying (die->sect_off));
19724   saved = (char *) obstack_copy0 (&objfile->objfile_obstack,
19725                                   message, strlen (message));
19726   xfree (message);
19727
19728   return init_type (objfile, TYPE_CODE_ERROR, 0, saved);
19729 }
19730
19731 /* Look up the type of DIE in CU using its type attribute ATTR.
19732    ATTR must be one of: DW_AT_type, DW_AT_GNAT_descriptive_type,
19733    DW_AT_containing_type.
19734    If there is no type substitute an error marker.  */
19735
19736 static struct type *
19737 lookup_die_type (struct die_info *die, const struct attribute *attr,
19738                  struct dwarf2_cu *cu)
19739 {
19740   struct objfile *objfile = cu->objfile;
19741   struct type *this_type;
19742
19743   gdb_assert (attr->name == DW_AT_type
19744               || attr->name == DW_AT_GNAT_descriptive_type
19745               || attr->name == DW_AT_containing_type);
19746
19747   /* First see if we have it cached.  */
19748
19749   if (attr->form == DW_FORM_GNU_ref_alt)
19750     {
19751       struct dwarf2_per_cu_data *per_cu;
19752       sect_offset sect_off = dwarf2_get_ref_die_offset (attr);
19753
19754       per_cu = dwarf2_find_containing_comp_unit (sect_off, 1, cu->objfile);
19755       this_type = get_die_type_at_offset (sect_off, per_cu);
19756     }
19757   else if (attr_form_is_ref (attr))
19758     {
19759       sect_offset sect_off = dwarf2_get_ref_die_offset (attr);
19760
19761       this_type = get_die_type_at_offset (sect_off, cu->per_cu);
19762     }
19763   else if (attr->form == DW_FORM_ref_sig8)
19764     {
19765       ULONGEST signature = DW_SIGNATURE (attr);
19766
19767       return get_signatured_type (die, signature, cu);
19768     }
19769   else
19770     {
19771       complaint (&symfile_complaints,
19772                  _("Dwarf Error: Bad type attribute %s in DIE"
19773                    " at 0x%x [in module %s]"),
19774                  dwarf_attr_name (attr->name), to_underlying (die->sect_off),
19775                  objfile_name (objfile));
19776       return build_error_marker_type (cu, die);
19777     }
19778
19779   /* If not cached we need to read it in.  */
19780
19781   if (this_type == NULL)
19782     {
19783       struct die_info *type_die = NULL;
19784       struct dwarf2_cu *type_cu = cu;
19785
19786       if (attr_form_is_ref (attr))
19787         type_die = follow_die_ref (die, attr, &type_cu);
19788       if (type_die == NULL)
19789         return build_error_marker_type (cu, die);
19790       /* If we find the type now, it's probably because the type came
19791          from an inter-CU reference and the type's CU got expanded before
19792          ours.  */
19793       this_type = read_type_die (type_die, type_cu);
19794     }
19795
19796   /* If we still don't have a type use an error marker.  */
19797
19798   if (this_type == NULL)
19799     return build_error_marker_type (cu, die);
19800
19801   return this_type;
19802 }
19803
19804 /* Return the type in DIE, CU.
19805    Returns NULL for invalid types.
19806
19807    This first does a lookup in die_type_hash,
19808    and only reads the die in if necessary.
19809
19810    NOTE: This can be called when reading in partial or full symbols.  */
19811
19812 static struct type *
19813 read_type_die (struct die_info *die, struct dwarf2_cu *cu)
19814 {
19815   struct type *this_type;
19816
19817   this_type = get_die_type (die, cu);
19818   if (this_type)
19819     return this_type;
19820
19821   return read_type_die_1 (die, cu);
19822 }
19823
19824 /* Read the type in DIE, CU.
19825    Returns NULL for invalid types.  */
19826
19827 static struct type *
19828 read_type_die_1 (struct die_info *die, struct dwarf2_cu *cu)
19829 {
19830   struct type *this_type = NULL;
19831
19832   switch (die->tag)
19833     {
19834     case DW_TAG_class_type:
19835     case DW_TAG_interface_type:
19836     case DW_TAG_structure_type:
19837     case DW_TAG_union_type:
19838       this_type = read_structure_type (die, cu);
19839       break;
19840     case DW_TAG_enumeration_type:
19841       this_type = read_enumeration_type (die, cu);
19842       break;
19843     case DW_TAG_subprogram:
19844     case DW_TAG_subroutine_type:
19845     case DW_TAG_inlined_subroutine:
19846       this_type = read_subroutine_type (die, cu);
19847       break;
19848     case DW_TAG_array_type:
19849       this_type = read_array_type (die, cu);
19850       break;
19851     case DW_TAG_set_type:
19852       this_type = read_set_type (die, cu);
19853       break;
19854     case DW_TAG_pointer_type:
19855       this_type = read_tag_pointer_type (die, cu);
19856       break;
19857     case DW_TAG_ptr_to_member_type:
19858       this_type = read_tag_ptr_to_member_type (die, cu);
19859       break;
19860     case DW_TAG_reference_type:
19861       this_type = read_tag_reference_type (die, cu, TYPE_CODE_REF);
19862       break;
19863     case DW_TAG_rvalue_reference_type:
19864       this_type = read_tag_reference_type (die, cu, TYPE_CODE_RVALUE_REF);
19865       break;
19866     case DW_TAG_const_type:
19867       this_type = read_tag_const_type (die, cu);
19868       break;
19869     case DW_TAG_volatile_type:
19870       this_type = read_tag_volatile_type (die, cu);
19871       break;
19872     case DW_TAG_restrict_type:
19873       this_type = read_tag_restrict_type (die, cu);
19874       break;
19875     case DW_TAG_string_type:
19876       this_type = read_tag_string_type (die, cu);
19877       break;
19878     case DW_TAG_typedef:
19879       this_type = read_typedef (die, cu);
19880       break;
19881     case DW_TAG_subrange_type:
19882       this_type = read_subrange_type (die, cu);
19883       break;
19884     case DW_TAG_base_type:
19885       this_type = read_base_type (die, cu);
19886       break;
19887     case DW_TAG_unspecified_type:
19888       this_type = read_unspecified_type (die, cu);
19889       break;
19890     case DW_TAG_namespace:
19891       this_type = read_namespace_type (die, cu);
19892       break;
19893     case DW_TAG_module:
19894       this_type = read_module_type (die, cu);
19895       break;
19896     case DW_TAG_atomic_type:
19897       this_type = read_tag_atomic_type (die, cu);
19898       break;
19899     default:
19900       complaint (&symfile_complaints,
19901                  _("unexpected tag in read_type_die: '%s'"),
19902                  dwarf_tag_name (die->tag));
19903       break;
19904     }
19905
19906   return this_type;
19907 }
19908
19909 /* See if we can figure out if the class lives in a namespace.  We do
19910    this by looking for a member function; its demangled name will
19911    contain namespace info, if there is any.
19912    Return the computed name or NULL.
19913    Space for the result is allocated on the objfile's obstack.
19914    This is the full-die version of guess_partial_die_structure_name.
19915    In this case we know DIE has no useful parent.  */
19916
19917 static char *
19918 guess_full_die_structure_name (struct die_info *die, struct dwarf2_cu *cu)
19919 {
19920   struct die_info *spec_die;
19921   struct dwarf2_cu *spec_cu;
19922   struct die_info *child;
19923
19924   spec_cu = cu;
19925   spec_die = die_specification (die, &spec_cu);
19926   if (spec_die != NULL)
19927     {
19928       die = spec_die;
19929       cu = spec_cu;
19930     }
19931
19932   for (child = die->child;
19933        child != NULL;
19934        child = child->sibling)
19935     {
19936       if (child->tag == DW_TAG_subprogram)
19937         {
19938           const char *linkage_name = dw2_linkage_name (child, cu);
19939
19940           if (linkage_name != NULL)
19941             {
19942               char *actual_name
19943                 = language_class_name_from_physname (cu->language_defn,
19944                                                      linkage_name);
19945               char *name = NULL;
19946
19947               if (actual_name != NULL)
19948                 {
19949                   const char *die_name = dwarf2_name (die, cu);
19950
19951                   if (die_name != NULL
19952                       && strcmp (die_name, actual_name) != 0)
19953                     {
19954                       /* Strip off the class name from the full name.
19955                          We want the prefix.  */
19956                       int die_name_len = strlen (die_name);
19957                       int actual_name_len = strlen (actual_name);
19958
19959                       /* Test for '::' as a sanity check.  */
19960                       if (actual_name_len > die_name_len + 2
19961                           && actual_name[actual_name_len
19962                                          - die_name_len - 1] == ':')
19963                         name = (char *) obstack_copy0 (
19964                           &cu->objfile->per_bfd->storage_obstack,
19965                           actual_name, actual_name_len - die_name_len - 2);
19966                     }
19967                 }
19968               xfree (actual_name);
19969               return name;
19970             }
19971         }
19972     }
19973
19974   return NULL;
19975 }
19976
19977 /* GCC might emit a nameless typedef that has a linkage name.  Determine the
19978    prefix part in such case.  See
19979    http://gcc.gnu.org/bugzilla/show_bug.cgi?id=47510.  */
19980
19981 static const char *
19982 anonymous_struct_prefix (struct die_info *die, struct dwarf2_cu *cu)
19983 {
19984   struct attribute *attr;
19985   const char *base;
19986
19987   if (die->tag != DW_TAG_class_type && die->tag != DW_TAG_interface_type
19988       && die->tag != DW_TAG_structure_type && die->tag != DW_TAG_union_type)
19989     return NULL;
19990
19991   if (dwarf2_string_attr (die, DW_AT_name, cu) != NULL)
19992     return NULL;
19993
19994   attr = dw2_linkage_name_attr (die, cu);
19995   if (attr == NULL || DW_STRING (attr) == NULL)
19996     return NULL;
19997
19998   /* dwarf2_name had to be already called.  */
19999   gdb_assert (DW_STRING_IS_CANONICAL (attr));
20000
20001   /* Strip the base name, keep any leading namespaces/classes.  */
20002   base = strrchr (DW_STRING (attr), ':');
20003   if (base == NULL || base == DW_STRING (attr) || base[-1] != ':')
20004     return "";
20005
20006   return (char *) obstack_copy0 (&cu->objfile->per_bfd->storage_obstack,
20007                                  DW_STRING (attr),
20008                                  &base[-1] - DW_STRING (attr));
20009 }
20010
20011 /* Return the name of the namespace/class that DIE is defined within,
20012    or "" if we can't tell.  The caller should not xfree the result.
20013
20014    For example, if we're within the method foo() in the following
20015    code:
20016
20017    namespace N {
20018      class C {
20019        void foo () {
20020        }
20021      };
20022    }
20023
20024    then determine_prefix on foo's die will return "N::C".  */
20025
20026 static const char *
20027 determine_prefix (struct die_info *die, struct dwarf2_cu *cu)
20028 {
20029   struct die_info *parent, *spec_die;
20030   struct dwarf2_cu *spec_cu;
20031   struct type *parent_type;
20032   const char *retval;
20033
20034   if (cu->language != language_cplus
20035       && cu->language != language_fortran && cu->language != language_d
20036       && cu->language != language_rust)
20037     return "";
20038
20039   retval = anonymous_struct_prefix (die, cu);
20040   if (retval)
20041     return retval;
20042
20043   /* We have to be careful in the presence of DW_AT_specification.
20044      For example, with GCC 3.4, given the code
20045
20046      namespace N {
20047        void foo() {
20048          // Definition of N::foo.
20049        }
20050      }
20051
20052      then we'll have a tree of DIEs like this:
20053
20054      1: DW_TAG_compile_unit
20055        2: DW_TAG_namespace        // N
20056          3: DW_TAG_subprogram     // declaration of N::foo
20057        4: DW_TAG_subprogram       // definition of N::foo
20058             DW_AT_specification   // refers to die #3
20059
20060      Thus, when processing die #4, we have to pretend that we're in
20061      the context of its DW_AT_specification, namely the contex of die
20062      #3.  */
20063   spec_cu = cu;
20064   spec_die = die_specification (die, &spec_cu);
20065   if (spec_die == NULL)
20066     parent = die->parent;
20067   else
20068     {
20069       parent = spec_die->parent;
20070       cu = spec_cu;
20071     }
20072
20073   if (parent == NULL)
20074     return "";
20075   else if (parent->building_fullname)
20076     {
20077       const char *name;
20078       const char *parent_name;
20079
20080       /* It has been seen on RealView 2.2 built binaries,
20081          DW_TAG_template_type_param types actually _defined_ as
20082          children of the parent class:
20083
20084          enum E {};
20085          template class <class Enum> Class{};
20086          Class<enum E> class_e;
20087
20088          1: DW_TAG_class_type (Class)
20089            2: DW_TAG_enumeration_type (E)
20090              3: DW_TAG_enumerator (enum1:0)
20091              3: DW_TAG_enumerator (enum2:1)
20092              ...
20093            2: DW_TAG_template_type_param
20094               DW_AT_type  DW_FORM_ref_udata (E)
20095
20096          Besides being broken debug info, it can put GDB into an
20097          infinite loop.  Consider:
20098
20099          When we're building the full name for Class<E>, we'll start
20100          at Class, and go look over its template type parameters,
20101          finding E.  We'll then try to build the full name of E, and
20102          reach here.  We're now trying to build the full name of E,
20103          and look over the parent DIE for containing scope.  In the
20104          broken case, if we followed the parent DIE of E, we'd again
20105          find Class, and once again go look at its template type
20106          arguments, etc., etc.  Simply don't consider such parent die
20107          as source-level parent of this die (it can't be, the language
20108          doesn't allow it), and break the loop here.  */
20109       name = dwarf2_name (die, cu);
20110       parent_name = dwarf2_name (parent, cu);
20111       complaint (&symfile_complaints,
20112                  _("template param type '%s' defined within parent '%s'"),
20113                  name ? name : "<unknown>",
20114                  parent_name ? parent_name : "<unknown>");
20115       return "";
20116     }
20117   else
20118     switch (parent->tag)
20119       {
20120       case DW_TAG_namespace:
20121         parent_type = read_type_die (parent, cu);
20122         /* GCC 4.0 and 4.1 had a bug (PR c++/28460) where they generated bogus
20123            DW_TAG_namespace DIEs with a name of "::" for the global namespace.
20124            Work around this problem here.  */
20125         if (cu->language == language_cplus
20126             && strcmp (TYPE_TAG_NAME (parent_type), "::") == 0)
20127           return "";
20128         /* We give a name to even anonymous namespaces.  */
20129         return TYPE_TAG_NAME (parent_type);
20130       case DW_TAG_class_type:
20131       case DW_TAG_interface_type:
20132       case DW_TAG_structure_type:
20133       case DW_TAG_union_type:
20134       case DW_TAG_module:
20135         parent_type = read_type_die (parent, cu);
20136         if (TYPE_TAG_NAME (parent_type) != NULL)
20137           return TYPE_TAG_NAME (parent_type);
20138         else
20139           /* An anonymous structure is only allowed non-static data
20140              members; no typedefs, no member functions, et cetera.
20141              So it does not need a prefix.  */
20142           return "";
20143       case DW_TAG_compile_unit:
20144       case DW_TAG_partial_unit:
20145         /* gcc-4.5 -gdwarf-4 can drop the enclosing namespace.  Cope.  */
20146         if (cu->language == language_cplus
20147             && !VEC_empty (dwarf2_section_info_def, dwarf2_per_objfile->types)
20148             && die->child != NULL
20149             && (die->tag == DW_TAG_class_type
20150                 || die->tag == DW_TAG_structure_type
20151                 || die->tag == DW_TAG_union_type))
20152           {
20153             char *name = guess_full_die_structure_name (die, cu);
20154             if (name != NULL)
20155               return name;
20156           }
20157         return "";
20158       case DW_TAG_enumeration_type:
20159         parent_type = read_type_die (parent, cu);
20160         if (TYPE_DECLARED_CLASS (parent_type))
20161           {
20162             if (TYPE_TAG_NAME (parent_type) != NULL)
20163               return TYPE_TAG_NAME (parent_type);
20164             return "";
20165           }
20166         /* Fall through.  */
20167       default:
20168         return determine_prefix (parent, cu);
20169       }
20170 }
20171
20172 /* Return a newly-allocated string formed by concatenating PREFIX and SUFFIX
20173    with appropriate separator.  If PREFIX or SUFFIX is NULL or empty, then
20174    simply copy the SUFFIX or PREFIX, respectively.  If OBS is non-null, perform
20175    an obconcat, otherwise allocate storage for the result.  The CU argument is
20176    used to determine the language and hence, the appropriate separator.  */
20177
20178 #define MAX_SEP_LEN 7  /* strlen ("__") + strlen ("_MOD_")  */
20179
20180 static char *
20181 typename_concat (struct obstack *obs, const char *prefix, const char *suffix,
20182                  int physname, struct dwarf2_cu *cu)
20183 {
20184   const char *lead = "";
20185   const char *sep;
20186
20187   if (suffix == NULL || suffix[0] == '\0'
20188       || prefix == NULL || prefix[0] == '\0')
20189     sep = "";
20190   else if (cu->language == language_d)
20191     {
20192       /* For D, the 'main' function could be defined in any module, but it
20193          should never be prefixed.  */
20194       if (strcmp (suffix, "D main") == 0)
20195         {
20196           prefix = "";
20197           sep = "";
20198         }
20199       else
20200         sep = ".";
20201     }
20202   else if (cu->language == language_fortran && physname)
20203     {
20204       /* This is gfortran specific mangling.  Normally DW_AT_linkage_name or
20205          DW_AT_MIPS_linkage_name is preferred and used instead.  */
20206
20207       lead = "__";
20208       sep = "_MOD_";
20209     }
20210   else
20211     sep = "::";
20212
20213   if (prefix == NULL)
20214     prefix = "";
20215   if (suffix == NULL)
20216     suffix = "";
20217
20218   if (obs == NULL)
20219     {
20220       char *retval
20221         = ((char *)
20222            xmalloc (strlen (prefix) + MAX_SEP_LEN + strlen (suffix) + 1));
20223
20224       strcpy (retval, lead);
20225       strcat (retval, prefix);
20226       strcat (retval, sep);
20227       strcat (retval, suffix);
20228       return retval;
20229     }
20230   else
20231     {
20232       /* We have an obstack.  */
20233       return obconcat (obs, lead, prefix, sep, suffix, (char *) NULL);
20234     }
20235 }
20236
20237 /* Return sibling of die, NULL if no sibling.  */
20238
20239 static struct die_info *
20240 sibling_die (struct die_info *die)
20241 {
20242   return die->sibling;
20243 }
20244
20245 /* Get name of a die, return NULL if not found.  */
20246
20247 static const char *
20248 dwarf2_canonicalize_name (const char *name, struct dwarf2_cu *cu,
20249                           struct obstack *obstack)
20250 {
20251   if (name && cu->language == language_cplus)
20252     {
20253       std::string canon_name = cp_canonicalize_string (name);
20254
20255       if (!canon_name.empty ())
20256         {
20257           if (canon_name != name)
20258             name = (const char *) obstack_copy0 (obstack,
20259                                                  canon_name.c_str (),
20260                                                  canon_name.length ());
20261         }
20262     }
20263
20264   return name;
20265 }
20266
20267 /* Get name of a die, return NULL if not found.
20268    Anonymous namespaces are converted to their magic string.  */
20269
20270 static const char *
20271 dwarf2_name (struct die_info *die, struct dwarf2_cu *cu)
20272 {
20273   struct attribute *attr;
20274
20275   attr = dwarf2_attr (die, DW_AT_name, cu);
20276   if ((!attr || !DW_STRING (attr))
20277       && die->tag != DW_TAG_namespace
20278       && die->tag != DW_TAG_class_type
20279       && die->tag != DW_TAG_interface_type
20280       && die->tag != DW_TAG_structure_type
20281       && die->tag != DW_TAG_union_type)
20282     return NULL;
20283
20284   switch (die->tag)
20285     {
20286     case DW_TAG_compile_unit:
20287     case DW_TAG_partial_unit:
20288       /* Compilation units have a DW_AT_name that is a filename, not
20289          a source language identifier.  */
20290     case DW_TAG_enumeration_type:
20291     case DW_TAG_enumerator:
20292       /* These tags always have simple identifiers already; no need
20293          to canonicalize them.  */
20294       return DW_STRING (attr);
20295
20296     case DW_TAG_namespace:
20297       if (attr != NULL && DW_STRING (attr) != NULL)
20298         return DW_STRING (attr);
20299       return CP_ANONYMOUS_NAMESPACE_STR;
20300
20301     case DW_TAG_class_type:
20302     case DW_TAG_interface_type:
20303     case DW_TAG_structure_type:
20304     case DW_TAG_union_type:
20305       /* Some GCC versions emit spurious DW_AT_name attributes for unnamed
20306          structures or unions.  These were of the form "._%d" in GCC 4.1,
20307          or simply "<anonymous struct>" or "<anonymous union>" in GCC 4.3
20308          and GCC 4.4.  We work around this problem by ignoring these.  */
20309       if (attr && DW_STRING (attr)
20310           && (startswith (DW_STRING (attr), "._")
20311               || startswith (DW_STRING (attr), "<anonymous")))
20312         return NULL;
20313
20314       /* GCC might emit a nameless typedef that has a linkage name.  See
20315          http://gcc.gnu.org/bugzilla/show_bug.cgi?id=47510.  */
20316       if (!attr || DW_STRING (attr) == NULL)
20317         {
20318           char *demangled = NULL;
20319
20320           attr = dw2_linkage_name_attr (die, cu);
20321           if (attr == NULL || DW_STRING (attr) == NULL)
20322             return NULL;
20323
20324           /* Avoid demangling DW_STRING (attr) the second time on a second
20325              call for the same DIE.  */
20326           if (!DW_STRING_IS_CANONICAL (attr))
20327             demangled = gdb_demangle (DW_STRING (attr), DMGL_TYPES);
20328
20329           if (demangled)
20330             {
20331               const char *base;
20332
20333               /* FIXME: we already did this for the partial symbol... */
20334               DW_STRING (attr)
20335                 = ((const char *)
20336                    obstack_copy0 (&cu->objfile->per_bfd->storage_obstack,
20337                                   demangled, strlen (demangled)));
20338               DW_STRING_IS_CANONICAL (attr) = 1;
20339               xfree (demangled);
20340
20341               /* Strip any leading namespaces/classes, keep only the base name.
20342                  DW_AT_name for named DIEs does not contain the prefixes.  */
20343               base = strrchr (DW_STRING (attr), ':');
20344               if (base && base > DW_STRING (attr) && base[-1] == ':')
20345                 return &base[1];
20346               else
20347                 return DW_STRING (attr);
20348             }
20349         }
20350       break;
20351
20352     default:
20353       break;
20354     }
20355
20356   if (!DW_STRING_IS_CANONICAL (attr))
20357     {
20358       DW_STRING (attr)
20359         = dwarf2_canonicalize_name (DW_STRING (attr), cu,
20360                                     &cu->objfile->per_bfd->storage_obstack);
20361       DW_STRING_IS_CANONICAL (attr) = 1;
20362     }
20363   return DW_STRING (attr);
20364 }
20365
20366 /* Return the die that this die in an extension of, or NULL if there
20367    is none.  *EXT_CU is the CU containing DIE on input, and the CU
20368    containing the return value on output.  */
20369
20370 static struct die_info *
20371 dwarf2_extension (struct die_info *die, struct dwarf2_cu **ext_cu)
20372 {
20373   struct attribute *attr;
20374
20375   attr = dwarf2_attr (die, DW_AT_extension, *ext_cu);
20376   if (attr == NULL)
20377     return NULL;
20378
20379   return follow_die_ref (die, attr, ext_cu);
20380 }
20381
20382 /* Convert a DIE tag into its string name.  */
20383
20384 static const char *
20385 dwarf_tag_name (unsigned tag)
20386 {
20387   const char *name = get_DW_TAG_name (tag);
20388
20389   if (name == NULL)
20390     return "DW_TAG_<unknown>";
20391
20392   return name;
20393 }
20394
20395 /* Convert a DWARF attribute code into its string name.  */
20396
20397 static const char *
20398 dwarf_attr_name (unsigned attr)
20399 {
20400   const char *name;
20401
20402 #ifdef MIPS /* collides with DW_AT_HP_block_index */
20403   if (attr == DW_AT_MIPS_fde)
20404     return "DW_AT_MIPS_fde";
20405 #else
20406   if (attr == DW_AT_HP_block_index)
20407     return "DW_AT_HP_block_index";
20408 #endif
20409
20410   name = get_DW_AT_name (attr);
20411
20412   if (name == NULL)
20413     return "DW_AT_<unknown>";
20414
20415   return name;
20416 }
20417
20418 /* Convert a DWARF value form code into its string name.  */
20419
20420 static const char *
20421 dwarf_form_name (unsigned form)
20422 {
20423   const char *name = get_DW_FORM_name (form);
20424
20425   if (name == NULL)
20426     return "DW_FORM_<unknown>";
20427
20428   return name;
20429 }
20430
20431 static const char *
20432 dwarf_bool_name (unsigned mybool)
20433 {
20434   if (mybool)
20435     return "TRUE";
20436   else
20437     return "FALSE";
20438 }
20439
20440 /* Convert a DWARF type code into its string name.  */
20441
20442 static const char *
20443 dwarf_type_encoding_name (unsigned enc)
20444 {
20445   const char *name = get_DW_ATE_name (enc);
20446
20447   if (name == NULL)
20448     return "DW_ATE_<unknown>";
20449
20450   return name;
20451 }
20452
20453 static void
20454 dump_die_shallow (struct ui_file *f, int indent, struct die_info *die)
20455 {
20456   unsigned int i;
20457
20458   print_spaces (indent, f);
20459   fprintf_unfiltered (f, "Die: %s (abbrev %d, offset 0x%x)\n",
20460                       dwarf_tag_name (die->tag), die->abbrev,
20461                       to_underlying (die->sect_off));
20462
20463   if (die->parent != NULL)
20464     {
20465       print_spaces (indent, f);
20466       fprintf_unfiltered (f, "  parent at offset: 0x%x\n",
20467                           to_underlying (die->parent->sect_off));
20468     }
20469
20470   print_spaces (indent, f);
20471   fprintf_unfiltered (f, "  has children: %s\n",
20472            dwarf_bool_name (die->child != NULL));
20473
20474   print_spaces (indent, f);
20475   fprintf_unfiltered (f, "  attributes:\n");
20476
20477   for (i = 0; i < die->num_attrs; ++i)
20478     {
20479       print_spaces (indent, f);
20480       fprintf_unfiltered (f, "    %s (%s) ",
20481                dwarf_attr_name (die->attrs[i].name),
20482                dwarf_form_name (die->attrs[i].form));
20483
20484       switch (die->attrs[i].form)
20485         {
20486         case DW_FORM_addr:
20487         case DW_FORM_GNU_addr_index:
20488           fprintf_unfiltered (f, "address: ");
20489           fputs_filtered (hex_string (DW_ADDR (&die->attrs[i])), f);
20490           break;
20491         case DW_FORM_block2:
20492         case DW_FORM_block4:
20493         case DW_FORM_block:
20494         case DW_FORM_block1:
20495           fprintf_unfiltered (f, "block: size %s",
20496                               pulongest (DW_BLOCK (&die->attrs[i])->size));
20497           break;
20498         case DW_FORM_exprloc:
20499           fprintf_unfiltered (f, "expression: size %s",
20500                               pulongest (DW_BLOCK (&die->attrs[i])->size));
20501           break;
20502         case DW_FORM_data16:
20503           fprintf_unfiltered (f, "constant of 16 bytes");
20504           break;
20505         case DW_FORM_ref_addr:
20506           fprintf_unfiltered (f, "ref address: ");
20507           fputs_filtered (hex_string (DW_UNSND (&die->attrs[i])), f);
20508           break;
20509         case DW_FORM_GNU_ref_alt:
20510           fprintf_unfiltered (f, "alt ref address: ");
20511           fputs_filtered (hex_string (DW_UNSND (&die->attrs[i])), f);
20512           break;
20513         case DW_FORM_ref1:
20514         case DW_FORM_ref2:
20515         case DW_FORM_ref4:
20516         case DW_FORM_ref8:
20517         case DW_FORM_ref_udata:
20518           fprintf_unfiltered (f, "constant ref: 0x%lx (adjusted)",
20519                               (long) (DW_UNSND (&die->attrs[i])));
20520           break;
20521         case DW_FORM_data1:
20522         case DW_FORM_data2:
20523         case DW_FORM_data4:
20524         case DW_FORM_data8:
20525         case DW_FORM_udata:
20526         case DW_FORM_sdata:
20527           fprintf_unfiltered (f, "constant: %s",
20528                               pulongest (DW_UNSND (&die->attrs[i])));
20529           break;
20530         case DW_FORM_sec_offset:
20531           fprintf_unfiltered (f, "section offset: %s",
20532                               pulongest (DW_UNSND (&die->attrs[i])));
20533           break;
20534         case DW_FORM_ref_sig8:
20535           fprintf_unfiltered (f, "signature: %s",
20536                               hex_string (DW_SIGNATURE (&die->attrs[i])));
20537           break;
20538         case DW_FORM_string:
20539         case DW_FORM_strp:
20540         case DW_FORM_line_strp:
20541         case DW_FORM_GNU_str_index:
20542         case DW_FORM_GNU_strp_alt:
20543           fprintf_unfiltered (f, "string: \"%s\" (%s canonicalized)",
20544                    DW_STRING (&die->attrs[i])
20545                    ? DW_STRING (&die->attrs[i]) : "",
20546                    DW_STRING_IS_CANONICAL (&die->attrs[i]) ? "is" : "not");
20547           break;
20548         case DW_FORM_flag:
20549           if (DW_UNSND (&die->attrs[i]))
20550             fprintf_unfiltered (f, "flag: TRUE");
20551           else
20552             fprintf_unfiltered (f, "flag: FALSE");
20553           break;
20554         case DW_FORM_flag_present:
20555           fprintf_unfiltered (f, "flag: TRUE");
20556           break;
20557         case DW_FORM_indirect:
20558           /* The reader will have reduced the indirect form to
20559              the "base form" so this form should not occur.  */
20560           fprintf_unfiltered (f, 
20561                               "unexpected attribute form: DW_FORM_indirect");
20562           break;
20563         case DW_FORM_implicit_const:
20564           fprintf_unfiltered (f, "constant: %s",
20565                               plongest (DW_SND (&die->attrs[i])));
20566           break;
20567         default:
20568           fprintf_unfiltered (f, "unsupported attribute form: %d.",
20569                    die->attrs[i].form);
20570           break;
20571         }
20572       fprintf_unfiltered (f, "\n");
20573     }
20574 }
20575
20576 static void
20577 dump_die_for_error (struct die_info *die)
20578 {
20579   dump_die_shallow (gdb_stderr, 0, die);
20580 }
20581
20582 static void
20583 dump_die_1 (struct ui_file *f, int level, int max_level, struct die_info *die)
20584 {
20585   int indent = level * 4;
20586
20587   gdb_assert (die != NULL);
20588
20589   if (level >= max_level)
20590     return;
20591
20592   dump_die_shallow (f, indent, die);
20593
20594   if (die->child != NULL)
20595     {
20596       print_spaces (indent, f);
20597       fprintf_unfiltered (f, "  Children:");
20598       if (level + 1 < max_level)
20599         {
20600           fprintf_unfiltered (f, "\n");
20601           dump_die_1 (f, level + 1, max_level, die->child);
20602         }
20603       else
20604         {
20605           fprintf_unfiltered (f,
20606                               " [not printed, max nesting level reached]\n");
20607         }
20608     }
20609
20610   if (die->sibling != NULL && level > 0)
20611     {
20612       dump_die_1 (f, level, max_level, die->sibling);
20613     }
20614 }
20615
20616 /* This is called from the pdie macro in gdbinit.in.
20617    It's not static so gcc will keep a copy callable from gdb.  */
20618
20619 void
20620 dump_die (struct die_info *die, int max_level)
20621 {
20622   dump_die_1 (gdb_stdlog, 0, max_level, die);
20623 }
20624
20625 static void
20626 store_in_ref_table (struct die_info *die, struct dwarf2_cu *cu)
20627 {
20628   void **slot;
20629
20630   slot = htab_find_slot_with_hash (cu->die_hash, die,
20631                                    to_underlying (die->sect_off),
20632                                    INSERT);
20633
20634   *slot = die;
20635 }
20636
20637 /* Return DIE offset of ATTR.  Return 0 with complaint if ATTR is not of the
20638    required kind.  */
20639
20640 static sect_offset
20641 dwarf2_get_ref_die_offset (const struct attribute *attr)
20642 {
20643   if (attr_form_is_ref (attr))
20644     return (sect_offset) DW_UNSND (attr);
20645
20646   complaint (&symfile_complaints,
20647              _("unsupported die ref attribute form: '%s'"),
20648              dwarf_form_name (attr->form));
20649   return {};
20650 }
20651
20652 /* Return the constant value held by ATTR.  Return DEFAULT_VALUE if
20653  * the value held by the attribute is not constant.  */
20654
20655 static LONGEST
20656 dwarf2_get_attr_constant_value (const struct attribute *attr, int default_value)
20657 {
20658   if (attr->form == DW_FORM_sdata || attr->form == DW_FORM_implicit_const)
20659     return DW_SND (attr);
20660   else if (attr->form == DW_FORM_udata
20661            || attr->form == DW_FORM_data1
20662            || attr->form == DW_FORM_data2
20663            || attr->form == DW_FORM_data4
20664            || attr->form == DW_FORM_data8)
20665     return DW_UNSND (attr);
20666   else
20667     {
20668       /* For DW_FORM_data16 see attr_form_is_constant.  */
20669       complaint (&symfile_complaints,
20670                  _("Attribute value is not a constant (%s)"),
20671                  dwarf_form_name (attr->form));
20672       return default_value;
20673     }
20674 }
20675
20676 /* Follow reference or signature attribute ATTR of SRC_DIE.
20677    On entry *REF_CU is the CU of SRC_DIE.
20678    On exit *REF_CU is the CU of the result.  */
20679
20680 static struct die_info *
20681 follow_die_ref_or_sig (struct die_info *src_die, const struct attribute *attr,
20682                        struct dwarf2_cu **ref_cu)
20683 {
20684   struct die_info *die;
20685
20686   if (attr_form_is_ref (attr))
20687     die = follow_die_ref (src_die, attr, ref_cu);
20688   else if (attr->form == DW_FORM_ref_sig8)
20689     die = follow_die_sig (src_die, attr, ref_cu);
20690   else
20691     {
20692       dump_die_for_error (src_die);
20693       error (_("Dwarf Error: Expected reference attribute [in module %s]"),
20694              objfile_name ((*ref_cu)->objfile));
20695     }
20696
20697   return die;
20698 }
20699
20700 /* Follow reference OFFSET.
20701    On entry *REF_CU is the CU of the source die referencing OFFSET.
20702    On exit *REF_CU is the CU of the result.
20703    Returns NULL if OFFSET is invalid.  */
20704
20705 static struct die_info *
20706 follow_die_offset (sect_offset sect_off, int offset_in_dwz,
20707                    struct dwarf2_cu **ref_cu)
20708 {
20709   struct die_info temp_die;
20710   struct dwarf2_cu *target_cu, *cu = *ref_cu;
20711
20712   gdb_assert (cu->per_cu != NULL);
20713
20714   target_cu = cu;
20715
20716   if (cu->per_cu->is_debug_types)
20717     {
20718       /* .debug_types CUs cannot reference anything outside their CU.
20719          If they need to, they have to reference a signatured type via
20720          DW_FORM_ref_sig8.  */
20721       if (!offset_in_cu_p (&cu->header, sect_off))
20722         return NULL;
20723     }
20724   else if (offset_in_dwz != cu->per_cu->is_dwz
20725            || !offset_in_cu_p (&cu->header, sect_off))
20726     {
20727       struct dwarf2_per_cu_data *per_cu;
20728
20729       per_cu = dwarf2_find_containing_comp_unit (sect_off, offset_in_dwz,
20730                                                  cu->objfile);
20731
20732       /* If necessary, add it to the queue and load its DIEs.  */
20733       if (maybe_queue_comp_unit (cu, per_cu, cu->language))
20734         load_full_comp_unit (per_cu, cu->language);
20735
20736       target_cu = per_cu->cu;
20737     }
20738   else if (cu->dies == NULL)
20739     {
20740       /* We're loading full DIEs during partial symbol reading.  */
20741       gdb_assert (dwarf2_per_objfile->reading_partial_symbols);
20742       load_full_comp_unit (cu->per_cu, language_minimal);
20743     }
20744
20745   *ref_cu = target_cu;
20746   temp_die.sect_off = sect_off;
20747   return (struct die_info *) htab_find_with_hash (target_cu->die_hash,
20748                                                   &temp_die,
20749                                                   to_underlying (sect_off));
20750 }
20751
20752 /* Follow reference attribute ATTR of SRC_DIE.
20753    On entry *REF_CU is the CU of SRC_DIE.
20754    On exit *REF_CU is the CU of the result.  */
20755
20756 static struct die_info *
20757 follow_die_ref (struct die_info *src_die, const struct attribute *attr,
20758                 struct dwarf2_cu **ref_cu)
20759 {
20760   sect_offset sect_off = dwarf2_get_ref_die_offset (attr);
20761   struct dwarf2_cu *cu = *ref_cu;
20762   struct die_info *die;
20763
20764   die = follow_die_offset (sect_off,
20765                            (attr->form == DW_FORM_GNU_ref_alt
20766                             || cu->per_cu->is_dwz),
20767                            ref_cu);
20768   if (!die)
20769     error (_("Dwarf Error: Cannot find DIE at 0x%x referenced from DIE "
20770            "at 0x%x [in module %s]"),
20771            to_underlying (sect_off), to_underlying (src_die->sect_off),
20772            objfile_name (cu->objfile));
20773
20774   return die;
20775 }
20776
20777 /* Return DWARF block referenced by DW_AT_location of DIE at SECT_OFF at PER_CU.
20778    Returned value is intended for DW_OP_call*.  Returned
20779    dwarf2_locexpr_baton->data has lifetime of PER_CU->OBJFILE.  */
20780
20781 struct dwarf2_locexpr_baton
20782 dwarf2_fetch_die_loc_sect_off (sect_offset sect_off,
20783                                struct dwarf2_per_cu_data *per_cu,
20784                                CORE_ADDR (*get_frame_pc) (void *baton),
20785                                void *baton)
20786 {
20787   struct dwarf2_cu *cu;
20788   struct die_info *die;
20789   struct attribute *attr;
20790   struct dwarf2_locexpr_baton retval;
20791
20792   dw2_setup (per_cu->objfile);
20793
20794   if (per_cu->cu == NULL)
20795     load_cu (per_cu);
20796   cu = per_cu->cu;
20797   if (cu == NULL)
20798     {
20799       /* We shouldn't get here for a dummy CU, but don't crash on the user.
20800          Instead just throw an error, not much else we can do.  */
20801       error (_("Dwarf Error: Dummy CU at 0x%x referenced in module %s"),
20802              to_underlying (sect_off), objfile_name (per_cu->objfile));
20803     }
20804
20805   die = follow_die_offset (sect_off, per_cu->is_dwz, &cu);
20806   if (!die)
20807     error (_("Dwarf Error: Cannot find DIE at 0x%x referenced in module %s"),
20808            to_underlying (sect_off), objfile_name (per_cu->objfile));
20809
20810   attr = dwarf2_attr (die, DW_AT_location, cu);
20811   if (!attr)
20812     {
20813       /* DWARF: "If there is no such attribute, then there is no effect.".
20814          DATA is ignored if SIZE is 0.  */
20815
20816       retval.data = NULL;
20817       retval.size = 0;
20818     }
20819   else if (attr_form_is_section_offset (attr))
20820     {
20821       struct dwarf2_loclist_baton loclist_baton;
20822       CORE_ADDR pc = (*get_frame_pc) (baton);
20823       size_t size;
20824
20825       fill_in_loclist_baton (cu, &loclist_baton, attr);
20826
20827       retval.data = dwarf2_find_location_expression (&loclist_baton,
20828                                                      &size, pc);
20829       retval.size = size;
20830     }
20831   else
20832     {
20833       if (!attr_form_is_block (attr))
20834         error (_("Dwarf Error: DIE at 0x%x referenced in module %s "
20835                  "is neither DW_FORM_block* nor DW_FORM_exprloc"),
20836                to_underlying (sect_off), objfile_name (per_cu->objfile));
20837
20838       retval.data = DW_BLOCK (attr)->data;
20839       retval.size = DW_BLOCK (attr)->size;
20840     }
20841   retval.per_cu = cu->per_cu;
20842
20843   age_cached_comp_units ();
20844
20845   return retval;
20846 }
20847
20848 /* Like dwarf2_fetch_die_loc_sect_off, but take a CU
20849    offset.  */
20850
20851 struct dwarf2_locexpr_baton
20852 dwarf2_fetch_die_loc_cu_off (cu_offset offset_in_cu,
20853                              struct dwarf2_per_cu_data *per_cu,
20854                              CORE_ADDR (*get_frame_pc) (void *baton),
20855                              void *baton)
20856 {
20857   sect_offset sect_off = per_cu->sect_off + to_underlying (offset_in_cu);
20858
20859   return dwarf2_fetch_die_loc_sect_off (sect_off, per_cu, get_frame_pc, baton);
20860 }
20861
20862 /* Write a constant of a given type as target-ordered bytes into
20863    OBSTACK.  */
20864
20865 static const gdb_byte *
20866 write_constant_as_bytes (struct obstack *obstack,
20867                          enum bfd_endian byte_order,
20868                          struct type *type,
20869                          ULONGEST value,
20870                          LONGEST *len)
20871 {
20872   gdb_byte *result;
20873
20874   *len = TYPE_LENGTH (type);
20875   result = (gdb_byte *) obstack_alloc (obstack, *len);
20876   store_unsigned_integer (result, *len, byte_order, value);
20877
20878   return result;
20879 }
20880
20881 /* If the DIE at OFFSET in PER_CU has a DW_AT_const_value, return a
20882    pointer to the constant bytes and set LEN to the length of the
20883    data.  If memory is needed, allocate it on OBSTACK.  If the DIE
20884    does not have a DW_AT_const_value, return NULL.  */
20885
20886 const gdb_byte *
20887 dwarf2_fetch_constant_bytes (sect_offset sect_off,
20888                              struct dwarf2_per_cu_data *per_cu,
20889                              struct obstack *obstack,
20890                              LONGEST *len)
20891 {
20892   struct dwarf2_cu *cu;
20893   struct die_info *die;
20894   struct attribute *attr;
20895   const gdb_byte *result = NULL;
20896   struct type *type;
20897   LONGEST value;
20898   enum bfd_endian byte_order;
20899
20900   dw2_setup (per_cu->objfile);
20901
20902   if (per_cu->cu == NULL)
20903     load_cu (per_cu);
20904   cu = per_cu->cu;
20905   if (cu == NULL)
20906     {
20907       /* We shouldn't get here for a dummy CU, but don't crash on the user.
20908          Instead just throw an error, not much else we can do.  */
20909       error (_("Dwarf Error: Dummy CU at 0x%x referenced in module %s"),
20910              to_underlying (sect_off), objfile_name (per_cu->objfile));
20911     }
20912
20913   die = follow_die_offset (sect_off, per_cu->is_dwz, &cu);
20914   if (!die)
20915     error (_("Dwarf Error: Cannot find DIE at 0x%x referenced in module %s"),
20916            to_underlying (sect_off), objfile_name (per_cu->objfile));
20917
20918
20919   attr = dwarf2_attr (die, DW_AT_const_value, cu);
20920   if (attr == NULL)
20921     return NULL;
20922
20923   byte_order = (bfd_big_endian (per_cu->objfile->obfd)
20924                 ? BFD_ENDIAN_BIG : BFD_ENDIAN_LITTLE);
20925
20926   switch (attr->form)
20927     {
20928     case DW_FORM_addr:
20929     case DW_FORM_GNU_addr_index:
20930       {
20931         gdb_byte *tem;
20932
20933         *len = cu->header.addr_size;
20934         tem = (gdb_byte *) obstack_alloc (obstack, *len);
20935         store_unsigned_integer (tem, *len, byte_order, DW_ADDR (attr));
20936         result = tem;
20937       }
20938       break;
20939     case DW_FORM_string:
20940     case DW_FORM_strp:
20941     case DW_FORM_GNU_str_index:
20942     case DW_FORM_GNU_strp_alt:
20943       /* DW_STRING is already allocated on the objfile obstack, point
20944          directly to it.  */
20945       result = (const gdb_byte *) DW_STRING (attr);
20946       *len = strlen (DW_STRING (attr));
20947       break;
20948     case DW_FORM_block1:
20949     case DW_FORM_block2:
20950     case DW_FORM_block4:
20951     case DW_FORM_block:
20952     case DW_FORM_exprloc:
20953     case DW_FORM_data16:
20954       result = DW_BLOCK (attr)->data;
20955       *len = DW_BLOCK (attr)->size;
20956       break;
20957
20958       /* The DW_AT_const_value attributes are supposed to carry the
20959          symbol's value "represented as it would be on the target
20960          architecture."  By the time we get here, it's already been
20961          converted to host endianness, so we just need to sign- or
20962          zero-extend it as appropriate.  */
20963     case DW_FORM_data1:
20964       type = die_type (die, cu);
20965       result = dwarf2_const_value_data (attr, obstack, cu, &value, 8);
20966       if (result == NULL)
20967         result = write_constant_as_bytes (obstack, byte_order,
20968                                           type, value, len);
20969       break;
20970     case DW_FORM_data2:
20971       type = die_type (die, cu);
20972       result = dwarf2_const_value_data (attr, obstack, cu, &value, 16);
20973       if (result == NULL)
20974         result = write_constant_as_bytes (obstack, byte_order,
20975                                           type, value, len);
20976       break;
20977     case DW_FORM_data4:
20978       type = die_type (die, cu);
20979       result = dwarf2_const_value_data (attr, obstack, cu, &value, 32);
20980       if (result == NULL)
20981         result = write_constant_as_bytes (obstack, byte_order,
20982                                           type, value, len);
20983       break;
20984     case DW_FORM_data8:
20985       type = die_type (die, cu);
20986       result = dwarf2_const_value_data (attr, obstack, cu, &value, 64);
20987       if (result == NULL)
20988         result = write_constant_as_bytes (obstack, byte_order,
20989                                           type, value, len);
20990       break;
20991
20992     case DW_FORM_sdata:
20993     case DW_FORM_implicit_const:
20994       type = die_type (die, cu);
20995       result = write_constant_as_bytes (obstack, byte_order,
20996                                         type, DW_SND (attr), len);
20997       break;
20998
20999     case DW_FORM_udata:
21000       type = die_type (die, cu);
21001       result = write_constant_as_bytes (obstack, byte_order,
21002                                         type, DW_UNSND (attr), len);
21003       break;
21004
21005     default:
21006       complaint (&symfile_complaints,
21007                  _("unsupported const value attribute form: '%s'"),
21008                  dwarf_form_name (attr->form));
21009       break;
21010     }
21011
21012   return result;
21013 }
21014
21015 /* Return the type of the die at OFFSET in PER_CU.  Return NULL if no
21016    valid type for this die is found.  */
21017
21018 struct type *
21019 dwarf2_fetch_die_type_sect_off (sect_offset sect_off,
21020                                 struct dwarf2_per_cu_data *per_cu)
21021 {
21022   struct dwarf2_cu *cu;
21023   struct die_info *die;
21024
21025   dw2_setup (per_cu->objfile);
21026
21027   if (per_cu->cu == NULL)
21028     load_cu (per_cu);
21029   cu = per_cu->cu;
21030   if (!cu)
21031     return NULL;
21032
21033   die = follow_die_offset (sect_off, per_cu->is_dwz, &cu);
21034   if (!die)
21035     return NULL;
21036
21037   return die_type (die, cu);
21038 }
21039
21040 /* Return the type of the DIE at DIE_OFFSET in the CU named by
21041    PER_CU.  */
21042
21043 struct type *
21044 dwarf2_get_die_type (cu_offset die_offset,
21045                      struct dwarf2_per_cu_data *per_cu)
21046 {
21047   dw2_setup (per_cu->objfile);
21048
21049   sect_offset die_offset_sect = per_cu->sect_off + to_underlying (die_offset);
21050   return get_die_type_at_offset (die_offset_sect, per_cu);
21051 }
21052
21053 /* Follow type unit SIG_TYPE referenced by SRC_DIE.
21054    On entry *REF_CU is the CU of SRC_DIE.
21055    On exit *REF_CU is the CU of the result.
21056    Returns NULL if the referenced DIE isn't found.  */
21057
21058 static struct die_info *
21059 follow_die_sig_1 (struct die_info *src_die, struct signatured_type *sig_type,
21060                   struct dwarf2_cu **ref_cu)
21061 {
21062   struct die_info temp_die;
21063   struct dwarf2_cu *sig_cu;
21064   struct die_info *die;
21065
21066   /* While it might be nice to assert sig_type->type == NULL here,
21067      we can get here for DW_AT_imported_declaration where we need
21068      the DIE not the type.  */
21069
21070   /* If necessary, add it to the queue and load its DIEs.  */
21071
21072   if (maybe_queue_comp_unit (*ref_cu, &sig_type->per_cu, language_minimal))
21073     read_signatured_type (sig_type);
21074
21075   sig_cu = sig_type->per_cu.cu;
21076   gdb_assert (sig_cu != NULL);
21077   gdb_assert (to_underlying (sig_type->type_offset_in_section) != 0);
21078   temp_die.sect_off = sig_type->type_offset_in_section;
21079   die = (struct die_info *) htab_find_with_hash (sig_cu->die_hash, &temp_die,
21080                                                  to_underlying (temp_die.sect_off));
21081   if (die)
21082     {
21083       /* For .gdb_index version 7 keep track of included TUs.
21084          http://sourceware.org/bugzilla/show_bug.cgi?id=15021.  */
21085       if (dwarf2_per_objfile->index_table != NULL
21086           && dwarf2_per_objfile->index_table->version <= 7)
21087         {
21088           VEC_safe_push (dwarf2_per_cu_ptr,
21089                          (*ref_cu)->per_cu->imported_symtabs,
21090                          sig_cu->per_cu);
21091         }
21092
21093       *ref_cu = sig_cu;
21094       return die;
21095     }
21096
21097   return NULL;
21098 }
21099
21100 /* Follow signatured type referenced by ATTR in SRC_DIE.
21101    On entry *REF_CU is the CU of SRC_DIE.
21102    On exit *REF_CU is the CU of the result.
21103    The result is the DIE of the type.
21104    If the referenced type cannot be found an error is thrown.  */
21105
21106 static struct die_info *
21107 follow_die_sig (struct die_info *src_die, const struct attribute *attr,
21108                 struct dwarf2_cu **ref_cu)
21109 {
21110   ULONGEST signature = DW_SIGNATURE (attr);
21111   struct signatured_type *sig_type;
21112   struct die_info *die;
21113
21114   gdb_assert (attr->form == DW_FORM_ref_sig8);
21115
21116   sig_type = lookup_signatured_type (*ref_cu, signature);
21117   /* sig_type will be NULL if the signatured type is missing from
21118      the debug info.  */
21119   if (sig_type == NULL)
21120     {
21121       error (_("Dwarf Error: Cannot find signatured DIE %s referenced"
21122                " from DIE at 0x%x [in module %s]"),
21123              hex_string (signature), to_underlying (src_die->sect_off),
21124              objfile_name ((*ref_cu)->objfile));
21125     }
21126
21127   die = follow_die_sig_1 (src_die, sig_type, ref_cu);
21128   if (die == NULL)
21129     {
21130       dump_die_for_error (src_die);
21131       error (_("Dwarf Error: Problem reading signatured DIE %s referenced"
21132                " from DIE at 0x%x [in module %s]"),
21133              hex_string (signature), to_underlying (src_die->sect_off),
21134              objfile_name ((*ref_cu)->objfile));
21135     }
21136
21137   return die;
21138 }
21139
21140 /* Get the type specified by SIGNATURE referenced in DIE/CU,
21141    reading in and processing the type unit if necessary.  */
21142
21143 static struct type *
21144 get_signatured_type (struct die_info *die, ULONGEST signature,
21145                      struct dwarf2_cu *cu)
21146 {
21147   struct signatured_type *sig_type;
21148   struct dwarf2_cu *type_cu;
21149   struct die_info *type_die;
21150   struct type *type;
21151
21152   sig_type = lookup_signatured_type (cu, signature);
21153   /* sig_type will be NULL if the signatured type is missing from
21154      the debug info.  */
21155   if (sig_type == NULL)
21156     {
21157       complaint (&symfile_complaints,
21158                  _("Dwarf Error: Cannot find signatured DIE %s referenced"
21159                    " from DIE at 0x%x [in module %s]"),
21160                  hex_string (signature), to_underlying (die->sect_off),
21161                  objfile_name (dwarf2_per_objfile->objfile));
21162       return build_error_marker_type (cu, die);
21163     }
21164
21165   /* If we already know the type we're done.  */
21166   if (sig_type->type != NULL)
21167     return sig_type->type;
21168
21169   type_cu = cu;
21170   type_die = follow_die_sig_1 (die, sig_type, &type_cu);
21171   if (type_die != NULL)
21172     {
21173       /* N.B. We need to call get_die_type to ensure only one type for this DIE
21174          is created.  This is important, for example, because for c++ classes
21175          we need TYPE_NAME set which is only done by new_symbol.  Blech.  */
21176       type = read_type_die (type_die, type_cu);
21177       if (type == NULL)
21178         {
21179           complaint (&symfile_complaints,
21180                      _("Dwarf Error: Cannot build signatured type %s"
21181                        " referenced from DIE at 0x%x [in module %s]"),
21182                      hex_string (signature), to_underlying (die->sect_off),
21183                      objfile_name (dwarf2_per_objfile->objfile));
21184           type = build_error_marker_type (cu, die);
21185         }
21186     }
21187   else
21188     {
21189       complaint (&symfile_complaints,
21190                  _("Dwarf Error: Problem reading signatured DIE %s referenced"
21191                    " from DIE at 0x%x [in module %s]"),
21192                  hex_string (signature), to_underlying (die->sect_off),
21193                  objfile_name (dwarf2_per_objfile->objfile));
21194       type = build_error_marker_type (cu, die);
21195     }
21196   sig_type->type = type;
21197
21198   return type;
21199 }
21200
21201 /* Get the type specified by the DW_AT_signature ATTR in DIE/CU,
21202    reading in and processing the type unit if necessary.  */
21203
21204 static struct type *
21205 get_DW_AT_signature_type (struct die_info *die, const struct attribute *attr,
21206                           struct dwarf2_cu *cu) /* ARI: editCase function */
21207 {
21208   /* Yes, DW_AT_signature can use a non-ref_sig8 reference.  */
21209   if (attr_form_is_ref (attr))
21210     {
21211       struct dwarf2_cu *type_cu = cu;
21212       struct die_info *type_die = follow_die_ref (die, attr, &type_cu);
21213
21214       return read_type_die (type_die, type_cu);
21215     }
21216   else if (attr->form == DW_FORM_ref_sig8)
21217     {
21218       return get_signatured_type (die, DW_SIGNATURE (attr), cu);
21219     }
21220   else
21221     {
21222       complaint (&symfile_complaints,
21223                  _("Dwarf Error: DW_AT_signature has bad form %s in DIE"
21224                    " at 0x%x [in module %s]"),
21225                  dwarf_form_name (attr->form), to_underlying (die->sect_off),
21226                  objfile_name (dwarf2_per_objfile->objfile));
21227       return build_error_marker_type (cu, die);
21228     }
21229 }
21230
21231 /* Load the DIEs associated with type unit PER_CU into memory.  */
21232
21233 static void
21234 load_full_type_unit (struct dwarf2_per_cu_data *per_cu)
21235 {
21236   struct signatured_type *sig_type;
21237
21238   /* Caller is responsible for ensuring type_unit_groups don't get here.  */
21239   gdb_assert (! IS_TYPE_UNIT_GROUP (per_cu));
21240
21241   /* We have the per_cu, but we need the signatured_type.
21242      Fortunately this is an easy translation.  */
21243   gdb_assert (per_cu->is_debug_types);
21244   sig_type = (struct signatured_type *) per_cu;
21245
21246   gdb_assert (per_cu->cu == NULL);
21247
21248   read_signatured_type (sig_type);
21249
21250   gdb_assert (per_cu->cu != NULL);
21251 }
21252
21253 /* die_reader_func for read_signatured_type.
21254    This is identical to load_full_comp_unit_reader,
21255    but is kept separate for now.  */
21256
21257 static void
21258 read_signatured_type_reader (const struct die_reader_specs *reader,
21259                              const gdb_byte *info_ptr,
21260                              struct die_info *comp_unit_die,
21261                              int has_children,
21262                              void *data)
21263 {
21264   struct dwarf2_cu *cu = reader->cu;
21265
21266   gdb_assert (cu->die_hash == NULL);
21267   cu->die_hash =
21268     htab_create_alloc_ex (cu->header.length / 12,
21269                           die_hash,
21270                           die_eq,
21271                           NULL,
21272                           &cu->comp_unit_obstack,
21273                           hashtab_obstack_allocate,
21274                           dummy_obstack_deallocate);
21275
21276   if (has_children)
21277     comp_unit_die->child = read_die_and_siblings (reader, info_ptr,
21278                                                   &info_ptr, comp_unit_die);
21279   cu->dies = comp_unit_die;
21280   /* comp_unit_die is not stored in die_hash, no need.  */
21281
21282   /* We try not to read any attributes in this function, because not
21283      all CUs needed for references have been loaded yet, and symbol
21284      table processing isn't initialized.  But we have to set the CU language,
21285      or we won't be able to build types correctly.
21286      Similarly, if we do not read the producer, we can not apply
21287      producer-specific interpretation.  */
21288   prepare_one_comp_unit (cu, cu->dies, language_minimal);
21289 }
21290
21291 /* Read in a signatured type and build its CU and DIEs.
21292    If the type is a stub for the real type in a DWO file,
21293    read in the real type from the DWO file as well.  */
21294
21295 static void
21296 read_signatured_type (struct signatured_type *sig_type)
21297 {
21298   struct dwarf2_per_cu_data *per_cu = &sig_type->per_cu;
21299
21300   gdb_assert (per_cu->is_debug_types);
21301   gdb_assert (per_cu->cu == NULL);
21302
21303   init_cutu_and_read_dies (per_cu, NULL, 0, 1,
21304                            read_signatured_type_reader, NULL);
21305   sig_type->per_cu.tu_read = 1;
21306 }
21307
21308 /* Decode simple location descriptions.
21309    Given a pointer to a dwarf block that defines a location, compute
21310    the location and return the value.
21311
21312    NOTE drow/2003-11-18: This function is called in two situations
21313    now: for the address of static or global variables (partial symbols
21314    only) and for offsets into structures which are expected to be
21315    (more or less) constant.  The partial symbol case should go away,
21316    and only the constant case should remain.  That will let this
21317    function complain more accurately.  A few special modes are allowed
21318    without complaint for global variables (for instance, global
21319    register values and thread-local values).
21320
21321    A location description containing no operations indicates that the
21322    object is optimized out.  The return value is 0 for that case.
21323    FIXME drow/2003-11-16: No callers check for this case any more; soon all
21324    callers will only want a very basic result and this can become a
21325    complaint.
21326
21327    Note that stack[0] is unused except as a default error return.  */
21328
21329 static CORE_ADDR
21330 decode_locdesc (struct dwarf_block *blk, struct dwarf2_cu *cu)
21331 {
21332   struct objfile *objfile = cu->objfile;
21333   size_t i;
21334   size_t size = blk->size;
21335   const gdb_byte *data = blk->data;
21336   CORE_ADDR stack[64];
21337   int stacki;
21338   unsigned int bytes_read, unsnd;
21339   gdb_byte op;
21340
21341   i = 0;
21342   stacki = 0;
21343   stack[stacki] = 0;
21344   stack[++stacki] = 0;
21345
21346   while (i < size)
21347     {
21348       op = data[i++];
21349       switch (op)
21350         {
21351         case DW_OP_lit0:
21352         case DW_OP_lit1:
21353         case DW_OP_lit2:
21354         case DW_OP_lit3:
21355         case DW_OP_lit4:
21356         case DW_OP_lit5:
21357         case DW_OP_lit6:
21358         case DW_OP_lit7:
21359         case DW_OP_lit8:
21360         case DW_OP_lit9:
21361         case DW_OP_lit10:
21362         case DW_OP_lit11:
21363         case DW_OP_lit12:
21364         case DW_OP_lit13:
21365         case DW_OP_lit14:
21366         case DW_OP_lit15:
21367         case DW_OP_lit16:
21368         case DW_OP_lit17:
21369         case DW_OP_lit18:
21370         case DW_OP_lit19:
21371         case DW_OP_lit20:
21372         case DW_OP_lit21:
21373         case DW_OP_lit22:
21374         case DW_OP_lit23:
21375         case DW_OP_lit24:
21376         case DW_OP_lit25:
21377         case DW_OP_lit26:
21378         case DW_OP_lit27:
21379         case DW_OP_lit28:
21380         case DW_OP_lit29:
21381         case DW_OP_lit30:
21382         case DW_OP_lit31:
21383           stack[++stacki] = op - DW_OP_lit0;
21384           break;
21385
21386         case DW_OP_reg0:
21387         case DW_OP_reg1:
21388         case DW_OP_reg2:
21389         case DW_OP_reg3:
21390         case DW_OP_reg4:
21391         case DW_OP_reg5:
21392         case DW_OP_reg6:
21393         case DW_OP_reg7:
21394         case DW_OP_reg8:
21395         case DW_OP_reg9:
21396         case DW_OP_reg10:
21397         case DW_OP_reg11:
21398         case DW_OP_reg12:
21399         case DW_OP_reg13:
21400         case DW_OP_reg14:
21401         case DW_OP_reg15:
21402         case DW_OP_reg16:
21403         case DW_OP_reg17:
21404         case DW_OP_reg18:
21405         case DW_OP_reg19:
21406         case DW_OP_reg20:
21407         case DW_OP_reg21:
21408         case DW_OP_reg22:
21409         case DW_OP_reg23:
21410         case DW_OP_reg24:
21411         case DW_OP_reg25:
21412         case DW_OP_reg26:
21413         case DW_OP_reg27:
21414         case DW_OP_reg28:
21415         case DW_OP_reg29:
21416         case DW_OP_reg30:
21417         case DW_OP_reg31:
21418           stack[++stacki] = op - DW_OP_reg0;
21419           if (i < size)
21420             dwarf2_complex_location_expr_complaint ();
21421           break;
21422
21423         case DW_OP_regx:
21424           unsnd = read_unsigned_leb128 (NULL, (data + i), &bytes_read);
21425           i += bytes_read;
21426           stack[++stacki] = unsnd;
21427           if (i < size)
21428             dwarf2_complex_location_expr_complaint ();
21429           break;
21430
21431         case DW_OP_addr:
21432           stack[++stacki] = read_address (objfile->obfd, &data[i],
21433                                           cu, &bytes_read);
21434           i += bytes_read;
21435           break;
21436
21437         case DW_OP_const1u:
21438           stack[++stacki] = read_1_byte (objfile->obfd, &data[i]);
21439           i += 1;
21440           break;
21441
21442         case DW_OP_const1s:
21443           stack[++stacki] = read_1_signed_byte (objfile->obfd, &data[i]);
21444           i += 1;
21445           break;
21446
21447         case DW_OP_const2u:
21448           stack[++stacki] = read_2_bytes (objfile->obfd, &data[i]);
21449           i += 2;
21450           break;
21451
21452         case DW_OP_const2s:
21453           stack[++stacki] = read_2_signed_bytes (objfile->obfd, &data[i]);
21454           i += 2;
21455           break;
21456
21457         case DW_OP_const4u:
21458           stack[++stacki] = read_4_bytes (objfile->obfd, &data[i]);
21459           i += 4;
21460           break;
21461
21462         case DW_OP_const4s:
21463           stack[++stacki] = read_4_signed_bytes (objfile->obfd, &data[i]);
21464           i += 4;
21465           break;
21466
21467         case DW_OP_const8u:
21468           stack[++stacki] = read_8_bytes (objfile->obfd, &data[i]);
21469           i += 8;
21470           break;
21471
21472         case DW_OP_constu:
21473           stack[++stacki] = read_unsigned_leb128 (NULL, (data + i),
21474                                                   &bytes_read);
21475           i += bytes_read;
21476           break;
21477
21478         case DW_OP_consts:
21479           stack[++stacki] = read_signed_leb128 (NULL, (data + i), &bytes_read);
21480           i += bytes_read;
21481           break;
21482
21483         case DW_OP_dup:
21484           stack[stacki + 1] = stack[stacki];
21485           stacki++;
21486           break;
21487
21488         case DW_OP_plus:
21489           stack[stacki - 1] += stack[stacki];
21490           stacki--;
21491           break;
21492
21493         case DW_OP_plus_uconst:
21494           stack[stacki] += read_unsigned_leb128 (NULL, (data + i),
21495                                                  &bytes_read);
21496           i += bytes_read;
21497           break;
21498
21499         case DW_OP_minus:
21500           stack[stacki - 1] -= stack[stacki];
21501           stacki--;
21502           break;
21503
21504         case DW_OP_deref:
21505           /* If we're not the last op, then we definitely can't encode
21506              this using GDB's address_class enum.  This is valid for partial
21507              global symbols, although the variable's address will be bogus
21508              in the psymtab.  */
21509           if (i < size)
21510             dwarf2_complex_location_expr_complaint ();
21511           break;
21512
21513         case DW_OP_GNU_push_tls_address:
21514         case DW_OP_form_tls_address:
21515           /* The top of the stack has the offset from the beginning
21516              of the thread control block at which the variable is located.  */
21517           /* Nothing should follow this operator, so the top of stack would
21518              be returned.  */
21519           /* This is valid for partial global symbols, but the variable's
21520              address will be bogus in the psymtab.  Make it always at least
21521              non-zero to not look as a variable garbage collected by linker
21522              which have DW_OP_addr 0.  */
21523           if (i < size)
21524             dwarf2_complex_location_expr_complaint ();
21525           stack[stacki]++;
21526           break;
21527
21528         case DW_OP_GNU_uninit:
21529           break;
21530
21531         case DW_OP_GNU_addr_index:
21532         case DW_OP_GNU_const_index:
21533           stack[++stacki] = read_addr_index_from_leb128 (cu, &data[i],
21534                                                          &bytes_read);
21535           i += bytes_read;
21536           break;
21537
21538         default:
21539           {
21540             const char *name = get_DW_OP_name (op);
21541
21542             if (name)
21543               complaint (&symfile_complaints, _("unsupported stack op: '%s'"),
21544                          name);
21545             else
21546               complaint (&symfile_complaints, _("unsupported stack op: '%02x'"),
21547                          op);
21548           }
21549
21550           return (stack[stacki]);
21551         }
21552
21553       /* Enforce maximum stack depth of SIZE-1 to avoid writing
21554          outside of the allocated space.  Also enforce minimum>0.  */
21555       if (stacki >= ARRAY_SIZE (stack) - 1)
21556         {
21557           complaint (&symfile_complaints,
21558                      _("location description stack overflow"));
21559           return 0;
21560         }
21561
21562       if (stacki <= 0)
21563         {
21564           complaint (&symfile_complaints,
21565                      _("location description stack underflow"));
21566           return 0;
21567         }
21568     }
21569   return (stack[stacki]);
21570 }
21571
21572 /* memory allocation interface */
21573
21574 static struct dwarf_block *
21575 dwarf_alloc_block (struct dwarf2_cu *cu)
21576 {
21577   return XOBNEW (&cu->comp_unit_obstack, struct dwarf_block);
21578 }
21579
21580 static struct die_info *
21581 dwarf_alloc_die (struct dwarf2_cu *cu, int num_attrs)
21582 {
21583   struct die_info *die;
21584   size_t size = sizeof (struct die_info);
21585
21586   if (num_attrs > 1)
21587     size += (num_attrs - 1) * sizeof (struct attribute);
21588
21589   die = (struct die_info *) obstack_alloc (&cu->comp_unit_obstack, size);
21590   memset (die, 0, sizeof (struct die_info));
21591   return (die);
21592 }
21593
21594 \f
21595 /* Macro support.  */
21596
21597 /* Return file name relative to the compilation directory of file number I in
21598    *LH's file name table.  The result is allocated using xmalloc; the caller is
21599    responsible for freeing it.  */
21600
21601 static char *
21602 file_file_name (int file, struct line_header *lh)
21603 {
21604   /* Is the file number a valid index into the line header's file name
21605      table?  Remember that file numbers start with one, not zero.  */
21606   if (1 <= file && file <= lh->file_names.size ())
21607     {
21608       const file_entry &fe = lh->file_names[file - 1];
21609
21610       if (!IS_ABSOLUTE_PATH (fe.name))
21611         {
21612           const char *dir = fe.include_dir (lh);
21613           if (dir != NULL)
21614             return concat (dir, SLASH_STRING, fe.name, (char *) NULL);
21615         }
21616       return xstrdup (fe.name);
21617     }
21618   else
21619     {
21620       /* The compiler produced a bogus file number.  We can at least
21621          record the macro definitions made in the file, even if we
21622          won't be able to find the file by name.  */
21623       char fake_name[80];
21624
21625       xsnprintf (fake_name, sizeof (fake_name),
21626                  "<bad macro file number %d>", file);
21627
21628       complaint (&symfile_complaints,
21629                  _("bad file number in macro information (%d)"),
21630                  file);
21631
21632       return xstrdup (fake_name);
21633     }
21634 }
21635
21636 /* Return the full name of file number I in *LH's file name table.
21637    Use COMP_DIR as the name of the current directory of the
21638    compilation.  The result is allocated using xmalloc; the caller is
21639    responsible for freeing it.  */
21640 static char *
21641 file_full_name (int file, struct line_header *lh, const char *comp_dir)
21642 {
21643   /* Is the file number a valid index into the line header's file name
21644      table?  Remember that file numbers start with one, not zero.  */
21645   if (1 <= file && file <= lh->file_names.size ())
21646     {
21647       char *relative = file_file_name (file, lh);
21648
21649       if (IS_ABSOLUTE_PATH (relative) || comp_dir == NULL)
21650         return relative;
21651       return reconcat (relative, comp_dir, SLASH_STRING,
21652                        relative, (char *) NULL);
21653     }
21654   else
21655     return file_file_name (file, lh);
21656 }
21657
21658
21659 static struct macro_source_file *
21660 macro_start_file (int file, int line,
21661                   struct macro_source_file *current_file,
21662                   struct line_header *lh)
21663 {
21664   /* File name relative to the compilation directory of this source file.  */
21665   char *file_name = file_file_name (file, lh);
21666
21667   if (! current_file)
21668     {
21669       /* Note: We don't create a macro table for this compilation unit
21670          at all until we actually get a filename.  */
21671       struct macro_table *macro_table = get_macro_table ();
21672
21673       /* If we have no current file, then this must be the start_file
21674          directive for the compilation unit's main source file.  */
21675       current_file = macro_set_main (macro_table, file_name);
21676       macro_define_special (macro_table);
21677     }
21678   else
21679     current_file = macro_include (current_file, line, file_name);
21680
21681   xfree (file_name);
21682
21683   return current_file;
21684 }
21685
21686 static const char *
21687 consume_improper_spaces (const char *p, const char *body)
21688 {
21689   if (*p == ' ')
21690     {
21691       complaint (&symfile_complaints,
21692                  _("macro definition contains spaces "
21693                    "in formal argument list:\n`%s'"),
21694                  body);
21695
21696       while (*p == ' ')
21697         p++;
21698     }
21699
21700   return p;
21701 }
21702
21703
21704 static void
21705 parse_macro_definition (struct macro_source_file *file, int line,
21706                         const char *body)
21707 {
21708   const char *p;
21709
21710   /* The body string takes one of two forms.  For object-like macro
21711      definitions, it should be:
21712
21713         <macro name> " " <definition>
21714
21715      For function-like macro definitions, it should be:
21716
21717         <macro name> "() " <definition>
21718      or
21719         <macro name> "(" <arg name> ( "," <arg name> ) * ") " <definition>
21720
21721      Spaces may appear only where explicitly indicated, and in the
21722      <definition>.
21723
21724      The Dwarf 2 spec says that an object-like macro's name is always
21725      followed by a space, but versions of GCC around March 2002 omit
21726      the space when the macro's definition is the empty string.
21727
21728      The Dwarf 2 spec says that there should be no spaces between the
21729      formal arguments in a function-like macro's formal argument list,
21730      but versions of GCC around March 2002 include spaces after the
21731      commas.  */
21732
21733
21734   /* Find the extent of the macro name.  The macro name is terminated
21735      by either a space or null character (for an object-like macro) or
21736      an opening paren (for a function-like macro).  */
21737   for (p = body; *p; p++)
21738     if (*p == ' ' || *p == '(')
21739       break;
21740
21741   if (*p == ' ' || *p == '\0')
21742     {
21743       /* It's an object-like macro.  */
21744       int name_len = p - body;
21745       char *name = savestring (body, name_len);
21746       const char *replacement;
21747
21748       if (*p == ' ')
21749         replacement = body + name_len + 1;
21750       else
21751         {
21752           dwarf2_macro_malformed_definition_complaint (body);
21753           replacement = body + name_len;
21754         }
21755
21756       macro_define_object (file, line, name, replacement);
21757
21758       xfree (name);
21759     }
21760   else if (*p == '(')
21761     {
21762       /* It's a function-like macro.  */
21763       char *name = savestring (body, p - body);
21764       int argc = 0;
21765       int argv_size = 1;
21766       char **argv = XNEWVEC (char *, argv_size);
21767
21768       p++;
21769
21770       p = consume_improper_spaces (p, body);
21771
21772       /* Parse the formal argument list.  */
21773       while (*p && *p != ')')
21774         {
21775           /* Find the extent of the current argument name.  */
21776           const char *arg_start = p;
21777
21778           while (*p && *p != ',' && *p != ')' && *p != ' ')
21779             p++;
21780
21781           if (! *p || p == arg_start)
21782             dwarf2_macro_malformed_definition_complaint (body);
21783           else
21784             {
21785               /* Make sure argv has room for the new argument.  */
21786               if (argc >= argv_size)
21787                 {
21788                   argv_size *= 2;
21789                   argv = XRESIZEVEC (char *, argv, argv_size);
21790                 }
21791
21792               argv[argc++] = savestring (arg_start, p - arg_start);
21793             }
21794
21795           p = consume_improper_spaces (p, body);
21796
21797           /* Consume the comma, if present.  */
21798           if (*p == ',')
21799             {
21800               p++;
21801
21802               p = consume_improper_spaces (p, body);
21803             }
21804         }
21805
21806       if (*p == ')')
21807         {
21808           p++;
21809
21810           if (*p == ' ')
21811             /* Perfectly formed definition, no complaints.  */
21812             macro_define_function (file, line, name,
21813                                    argc, (const char **) argv,
21814                                    p + 1);
21815           else if (*p == '\0')
21816             {
21817               /* Complain, but do define it.  */
21818               dwarf2_macro_malformed_definition_complaint (body);
21819               macro_define_function (file, line, name,
21820                                      argc, (const char **) argv,
21821                                      p);
21822             }
21823           else
21824             /* Just complain.  */
21825             dwarf2_macro_malformed_definition_complaint (body);
21826         }
21827       else
21828         /* Just complain.  */
21829         dwarf2_macro_malformed_definition_complaint (body);
21830
21831       xfree (name);
21832       {
21833         int i;
21834
21835         for (i = 0; i < argc; i++)
21836           xfree (argv[i]);
21837       }
21838       xfree (argv);
21839     }
21840   else
21841     dwarf2_macro_malformed_definition_complaint (body);
21842 }
21843
21844 /* Skip some bytes from BYTES according to the form given in FORM.
21845    Returns the new pointer.  */
21846
21847 static const gdb_byte *
21848 skip_form_bytes (bfd *abfd, const gdb_byte *bytes, const gdb_byte *buffer_end,
21849                  enum dwarf_form form,
21850                  unsigned int offset_size,
21851                  struct dwarf2_section_info *section)
21852 {
21853   unsigned int bytes_read;
21854
21855   switch (form)
21856     {
21857     case DW_FORM_data1:
21858     case DW_FORM_flag:
21859       ++bytes;
21860       break;
21861
21862     case DW_FORM_data2:
21863       bytes += 2;
21864       break;
21865
21866     case DW_FORM_data4:
21867       bytes += 4;
21868       break;
21869
21870     case DW_FORM_data8:
21871       bytes += 8;
21872       break;
21873
21874     case DW_FORM_data16:
21875       bytes += 16;
21876       break;
21877
21878     case DW_FORM_string:
21879       read_direct_string (abfd, bytes, &bytes_read);
21880       bytes += bytes_read;
21881       break;
21882
21883     case DW_FORM_sec_offset:
21884     case DW_FORM_strp:
21885     case DW_FORM_GNU_strp_alt:
21886       bytes += offset_size;
21887       break;
21888
21889     case DW_FORM_block:
21890       bytes += read_unsigned_leb128 (abfd, bytes, &bytes_read);
21891       bytes += bytes_read;
21892       break;
21893
21894     case DW_FORM_block1:
21895       bytes += 1 + read_1_byte (abfd, bytes);
21896       break;
21897     case DW_FORM_block2:
21898       bytes += 2 + read_2_bytes (abfd, bytes);
21899       break;
21900     case DW_FORM_block4:
21901       bytes += 4 + read_4_bytes (abfd, bytes);
21902       break;
21903
21904     case DW_FORM_sdata:
21905     case DW_FORM_udata:
21906     case DW_FORM_GNU_addr_index:
21907     case DW_FORM_GNU_str_index:
21908       bytes = gdb_skip_leb128 (bytes, buffer_end);
21909       if (bytes == NULL)
21910         {
21911           dwarf2_section_buffer_overflow_complaint (section);
21912           return NULL;
21913         }
21914       break;
21915
21916     case DW_FORM_implicit_const:
21917       break;
21918
21919     default:
21920       {
21921       complain:
21922         complaint (&symfile_complaints,
21923                    _("invalid form 0x%x in `%s'"),
21924                    form, get_section_name (section));
21925         return NULL;
21926       }
21927     }
21928
21929   return bytes;
21930 }
21931
21932 /* A helper for dwarf_decode_macros that handles skipping an unknown
21933    opcode.  Returns an updated pointer to the macro data buffer; or,
21934    on error, issues a complaint and returns NULL.  */
21935
21936 static const gdb_byte *
21937 skip_unknown_opcode (unsigned int opcode,
21938                      const gdb_byte **opcode_definitions,
21939                      const gdb_byte *mac_ptr, const gdb_byte *mac_end,
21940                      bfd *abfd,
21941                      unsigned int offset_size,
21942                      struct dwarf2_section_info *section)
21943 {
21944   unsigned int bytes_read, i;
21945   unsigned long arg;
21946   const gdb_byte *defn;
21947
21948   if (opcode_definitions[opcode] == NULL)
21949     {
21950       complaint (&symfile_complaints,
21951                  _("unrecognized DW_MACFINO opcode 0x%x"),
21952                  opcode);
21953       return NULL;
21954     }
21955
21956   defn = opcode_definitions[opcode];
21957   arg = read_unsigned_leb128 (abfd, defn, &bytes_read);
21958   defn += bytes_read;
21959
21960   for (i = 0; i < arg; ++i)
21961     {
21962       mac_ptr = skip_form_bytes (abfd, mac_ptr, mac_end,
21963                                  (enum dwarf_form) defn[i], offset_size,
21964                                  section);
21965       if (mac_ptr == NULL)
21966         {
21967           /* skip_form_bytes already issued the complaint.  */
21968           return NULL;
21969         }
21970     }
21971
21972   return mac_ptr;
21973 }
21974
21975 /* A helper function which parses the header of a macro section.
21976    If the macro section is the extended (for now called "GNU") type,
21977    then this updates *OFFSET_SIZE.  Returns a pointer to just after
21978    the header, or issues a complaint and returns NULL on error.  */
21979
21980 static const gdb_byte *
21981 dwarf_parse_macro_header (const gdb_byte **opcode_definitions,
21982                           bfd *abfd,
21983                           const gdb_byte *mac_ptr,
21984                           unsigned int *offset_size,
21985                           int section_is_gnu)
21986 {
21987   memset (opcode_definitions, 0, 256 * sizeof (gdb_byte *));
21988
21989   if (section_is_gnu)
21990     {
21991       unsigned int version, flags;
21992
21993       version = read_2_bytes (abfd, mac_ptr);
21994       if (version != 4 && version != 5)
21995         {
21996           complaint (&symfile_complaints,
21997                      _("unrecognized version `%d' in .debug_macro section"),
21998                      version);
21999           return NULL;
22000         }
22001       mac_ptr += 2;
22002
22003       flags = read_1_byte (abfd, mac_ptr);
22004       ++mac_ptr;
22005       *offset_size = (flags & 1) ? 8 : 4;
22006
22007       if ((flags & 2) != 0)
22008         /* We don't need the line table offset.  */
22009         mac_ptr += *offset_size;
22010
22011       /* Vendor opcode descriptions.  */
22012       if ((flags & 4) != 0)
22013         {
22014           unsigned int i, count;
22015
22016           count = read_1_byte (abfd, mac_ptr);
22017           ++mac_ptr;
22018           for (i = 0; i < count; ++i)
22019             {
22020               unsigned int opcode, bytes_read;
22021               unsigned long arg;
22022
22023               opcode = read_1_byte (abfd, mac_ptr);
22024               ++mac_ptr;
22025               opcode_definitions[opcode] = mac_ptr;
22026               arg = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
22027               mac_ptr += bytes_read;
22028               mac_ptr += arg;
22029             }
22030         }
22031     }
22032
22033   return mac_ptr;
22034 }
22035
22036 /* A helper for dwarf_decode_macros that handles the GNU extensions,
22037    including DW_MACRO_import.  */
22038
22039 static void
22040 dwarf_decode_macro_bytes (bfd *abfd,
22041                           const gdb_byte *mac_ptr, const gdb_byte *mac_end,
22042                           struct macro_source_file *current_file,
22043                           struct line_header *lh,
22044                           struct dwarf2_section_info *section,
22045                           int section_is_gnu, int section_is_dwz,
22046                           unsigned int offset_size,
22047                           htab_t include_hash)
22048 {
22049   struct objfile *objfile = dwarf2_per_objfile->objfile;
22050   enum dwarf_macro_record_type macinfo_type;
22051   int at_commandline;
22052   const gdb_byte *opcode_definitions[256];
22053
22054   mac_ptr = dwarf_parse_macro_header (opcode_definitions, abfd, mac_ptr,
22055                                       &offset_size, section_is_gnu);
22056   if (mac_ptr == NULL)
22057     {
22058       /* We already issued a complaint.  */
22059       return;
22060     }
22061
22062   /* Determines if GDB is still before first DW_MACINFO_start_file.  If true
22063      GDB is still reading the definitions from command line.  First
22064      DW_MACINFO_start_file will need to be ignored as it was already executed
22065      to create CURRENT_FILE for the main source holding also the command line
22066      definitions.  On first met DW_MACINFO_start_file this flag is reset to
22067      normally execute all the remaining DW_MACINFO_start_file macinfos.  */
22068
22069   at_commandline = 1;
22070
22071   do
22072     {
22073       /* Do we at least have room for a macinfo type byte?  */
22074       if (mac_ptr >= mac_end)
22075         {
22076           dwarf2_section_buffer_overflow_complaint (section);
22077           break;
22078         }
22079
22080       macinfo_type = (enum dwarf_macro_record_type) read_1_byte (abfd, mac_ptr);
22081       mac_ptr++;
22082
22083       /* Note that we rely on the fact that the corresponding GNU and
22084          DWARF constants are the same.  */
22085       switch (macinfo_type)
22086         {
22087           /* A zero macinfo type indicates the end of the macro
22088              information.  */
22089         case 0:
22090           break;
22091
22092         case DW_MACRO_define:
22093         case DW_MACRO_undef:
22094         case DW_MACRO_define_strp:
22095         case DW_MACRO_undef_strp:
22096         case DW_MACRO_define_sup:
22097         case DW_MACRO_undef_sup:
22098           {
22099             unsigned int bytes_read;
22100             int line;
22101             const char *body;
22102             int is_define;
22103
22104             line = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
22105             mac_ptr += bytes_read;
22106
22107             if (macinfo_type == DW_MACRO_define
22108                 || macinfo_type == DW_MACRO_undef)
22109               {
22110                 body = read_direct_string (abfd, mac_ptr, &bytes_read);
22111                 mac_ptr += bytes_read;
22112               }
22113             else
22114               {
22115                 LONGEST str_offset;
22116
22117                 str_offset = read_offset_1 (abfd, mac_ptr, offset_size);
22118                 mac_ptr += offset_size;
22119
22120                 if (macinfo_type == DW_MACRO_define_sup
22121                     || macinfo_type == DW_MACRO_undef_sup
22122                     || section_is_dwz)
22123                   {
22124                     struct dwz_file *dwz = dwarf2_get_dwz_file ();
22125
22126                     body = read_indirect_string_from_dwz (dwz, str_offset);
22127                   }
22128                 else
22129                   body = read_indirect_string_at_offset (abfd, str_offset);
22130               }
22131
22132             is_define = (macinfo_type == DW_MACRO_define
22133                          || macinfo_type == DW_MACRO_define_strp
22134                          || macinfo_type == DW_MACRO_define_sup);
22135             if (! current_file)
22136               {
22137                 /* DWARF violation as no main source is present.  */
22138                 complaint (&symfile_complaints,
22139                            _("debug info with no main source gives macro %s "
22140                              "on line %d: %s"),
22141                            is_define ? _("definition") : _("undefinition"),
22142                            line, body);
22143                 break;
22144               }
22145             if ((line == 0 && !at_commandline)
22146                 || (line != 0 && at_commandline))
22147               complaint (&symfile_complaints,
22148                          _("debug info gives %s macro %s with %s line %d: %s"),
22149                          at_commandline ? _("command-line") : _("in-file"),
22150                          is_define ? _("definition") : _("undefinition"),
22151                          line == 0 ? _("zero") : _("non-zero"), line, body);
22152
22153             if (is_define)
22154               parse_macro_definition (current_file, line, body);
22155             else
22156               {
22157                 gdb_assert (macinfo_type == DW_MACRO_undef
22158                             || macinfo_type == DW_MACRO_undef_strp
22159                             || macinfo_type == DW_MACRO_undef_sup);
22160                 macro_undef (current_file, line, body);
22161               }
22162           }
22163           break;
22164
22165         case DW_MACRO_start_file:
22166           {
22167             unsigned int bytes_read;
22168             int line, file;
22169
22170             line = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
22171             mac_ptr += bytes_read;
22172             file = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
22173             mac_ptr += bytes_read;
22174
22175             if ((line == 0 && !at_commandline)
22176                 || (line != 0 && at_commandline))
22177               complaint (&symfile_complaints,
22178                          _("debug info gives source %d included "
22179                            "from %s at %s line %d"),
22180                          file, at_commandline ? _("command-line") : _("file"),
22181                          line == 0 ? _("zero") : _("non-zero"), line);
22182
22183             if (at_commandline)
22184               {
22185                 /* This DW_MACRO_start_file was executed in the
22186                    pass one.  */
22187                 at_commandline = 0;
22188               }
22189             else
22190               current_file = macro_start_file (file, line, current_file, lh);
22191           }
22192           break;
22193
22194         case DW_MACRO_end_file:
22195           if (! current_file)
22196             complaint (&symfile_complaints,
22197                        _("macro debug info has an unmatched "
22198                          "`close_file' directive"));
22199           else
22200             {
22201               current_file = current_file->included_by;
22202               if (! current_file)
22203                 {
22204                   enum dwarf_macro_record_type next_type;
22205
22206                   /* GCC circa March 2002 doesn't produce the zero
22207                      type byte marking the end of the compilation
22208                      unit.  Complain if it's not there, but exit no
22209                      matter what.  */
22210
22211                   /* Do we at least have room for a macinfo type byte?  */
22212                   if (mac_ptr >= mac_end)
22213                     {
22214                       dwarf2_section_buffer_overflow_complaint (section);
22215                       return;
22216                     }
22217
22218                   /* We don't increment mac_ptr here, so this is just
22219                      a look-ahead.  */
22220                   next_type
22221                     = (enum dwarf_macro_record_type) read_1_byte (abfd,
22222                                                                   mac_ptr);
22223                   if (next_type != 0)
22224                     complaint (&symfile_complaints,
22225                                _("no terminating 0-type entry for "
22226                                  "macros in `.debug_macinfo' section"));
22227
22228                   return;
22229                 }
22230             }
22231           break;
22232
22233         case DW_MACRO_import:
22234         case DW_MACRO_import_sup:
22235           {
22236             LONGEST offset;
22237             void **slot;
22238             bfd *include_bfd = abfd;
22239             struct dwarf2_section_info *include_section = section;
22240             const gdb_byte *include_mac_end = mac_end;
22241             int is_dwz = section_is_dwz;
22242             const gdb_byte *new_mac_ptr;
22243
22244             offset = read_offset_1 (abfd, mac_ptr, offset_size);
22245             mac_ptr += offset_size;
22246
22247             if (macinfo_type == DW_MACRO_import_sup)
22248               {
22249                 struct dwz_file *dwz = dwarf2_get_dwz_file ();
22250
22251                 dwarf2_read_section (objfile, &dwz->macro);
22252
22253                 include_section = &dwz->macro;
22254                 include_bfd = get_section_bfd_owner (include_section);
22255                 include_mac_end = dwz->macro.buffer + dwz->macro.size;
22256                 is_dwz = 1;
22257               }
22258
22259             new_mac_ptr = include_section->buffer + offset;
22260             slot = htab_find_slot (include_hash, new_mac_ptr, INSERT);
22261
22262             if (*slot != NULL)
22263               {
22264                 /* This has actually happened; see
22265                    http://sourceware.org/bugzilla/show_bug.cgi?id=13568.  */
22266                 complaint (&symfile_complaints,
22267                            _("recursive DW_MACRO_import in "
22268                              ".debug_macro section"));
22269               }
22270             else
22271               {
22272                 *slot = (void *) new_mac_ptr;
22273
22274                 dwarf_decode_macro_bytes (include_bfd, new_mac_ptr,
22275                                           include_mac_end, current_file, lh,
22276                                           section, section_is_gnu, is_dwz,
22277                                           offset_size, include_hash);
22278
22279                 htab_remove_elt (include_hash, (void *) new_mac_ptr);
22280               }
22281           }
22282           break;
22283
22284         case DW_MACINFO_vendor_ext:
22285           if (!section_is_gnu)
22286             {
22287               unsigned int bytes_read;
22288
22289               /* This reads the constant, but since we don't recognize
22290                  any vendor extensions, we ignore it.  */
22291               read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
22292               mac_ptr += bytes_read;
22293               read_direct_string (abfd, mac_ptr, &bytes_read);
22294               mac_ptr += bytes_read;
22295
22296               /* We don't recognize any vendor extensions.  */
22297               break;
22298             }
22299           /* FALLTHROUGH */
22300
22301         default:
22302           mac_ptr = skip_unknown_opcode (macinfo_type, opcode_definitions,
22303                                          mac_ptr, mac_end, abfd, offset_size,
22304                                          section);
22305           if (mac_ptr == NULL)
22306             return;
22307           break;
22308         }
22309     } while (macinfo_type != 0);
22310 }
22311
22312 static void
22313 dwarf_decode_macros (struct dwarf2_cu *cu, unsigned int offset,
22314                      int section_is_gnu)
22315 {
22316   struct objfile *objfile = dwarf2_per_objfile->objfile;
22317   struct line_header *lh = cu->line_header;
22318   bfd *abfd;
22319   const gdb_byte *mac_ptr, *mac_end;
22320   struct macro_source_file *current_file = 0;
22321   enum dwarf_macro_record_type macinfo_type;
22322   unsigned int offset_size = cu->header.offset_size;
22323   const gdb_byte *opcode_definitions[256];
22324   struct cleanup *cleanup;
22325   void **slot;
22326   struct dwarf2_section_info *section;
22327   const char *section_name;
22328
22329   if (cu->dwo_unit != NULL)
22330     {
22331       if (section_is_gnu)
22332         {
22333           section = &cu->dwo_unit->dwo_file->sections.macro;
22334           section_name = ".debug_macro.dwo";
22335         }
22336       else
22337         {
22338           section = &cu->dwo_unit->dwo_file->sections.macinfo;
22339           section_name = ".debug_macinfo.dwo";
22340         }
22341     }
22342   else
22343     {
22344       if (section_is_gnu)
22345         {
22346           section = &dwarf2_per_objfile->macro;
22347           section_name = ".debug_macro";
22348         }
22349       else
22350         {
22351           section = &dwarf2_per_objfile->macinfo;
22352           section_name = ".debug_macinfo";
22353         }
22354     }
22355
22356   dwarf2_read_section (objfile, section);
22357   if (section->buffer == NULL)
22358     {
22359       complaint (&symfile_complaints, _("missing %s section"), section_name);
22360       return;
22361     }
22362   abfd = get_section_bfd_owner (section);
22363
22364   /* First pass: Find the name of the base filename.
22365      This filename is needed in order to process all macros whose definition
22366      (or undefinition) comes from the command line.  These macros are defined
22367      before the first DW_MACINFO_start_file entry, and yet still need to be
22368      associated to the base file.
22369
22370      To determine the base file name, we scan the macro definitions until we
22371      reach the first DW_MACINFO_start_file entry.  We then initialize
22372      CURRENT_FILE accordingly so that any macro definition found before the
22373      first DW_MACINFO_start_file can still be associated to the base file.  */
22374
22375   mac_ptr = section->buffer + offset;
22376   mac_end = section->buffer + section->size;
22377
22378   mac_ptr = dwarf_parse_macro_header (opcode_definitions, abfd, mac_ptr,
22379                                       &offset_size, section_is_gnu);
22380   if (mac_ptr == NULL)
22381     {
22382       /* We already issued a complaint.  */
22383       return;
22384     }
22385
22386   do
22387     {
22388       /* Do we at least have room for a macinfo type byte?  */
22389       if (mac_ptr >= mac_end)
22390         {
22391           /* Complaint is printed during the second pass as GDB will probably
22392              stop the first pass earlier upon finding
22393              DW_MACINFO_start_file.  */
22394           break;
22395         }
22396
22397       macinfo_type = (enum dwarf_macro_record_type) read_1_byte (abfd, mac_ptr);
22398       mac_ptr++;
22399
22400       /* Note that we rely on the fact that the corresponding GNU and
22401          DWARF constants are the same.  */
22402       switch (macinfo_type)
22403         {
22404           /* A zero macinfo type indicates the end of the macro
22405              information.  */
22406         case 0:
22407           break;
22408
22409         case DW_MACRO_define:
22410         case DW_MACRO_undef:
22411           /* Only skip the data by MAC_PTR.  */
22412           {
22413             unsigned int bytes_read;
22414
22415             read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
22416             mac_ptr += bytes_read;
22417             read_direct_string (abfd, mac_ptr, &bytes_read);
22418             mac_ptr += bytes_read;
22419           }
22420           break;
22421
22422         case DW_MACRO_start_file:
22423           {
22424             unsigned int bytes_read;
22425             int line, file;
22426
22427             line = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
22428             mac_ptr += bytes_read;
22429             file = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
22430             mac_ptr += bytes_read;
22431
22432             current_file = macro_start_file (file, line, current_file, lh);
22433           }
22434           break;
22435
22436         case DW_MACRO_end_file:
22437           /* No data to skip by MAC_PTR.  */
22438           break;
22439
22440         case DW_MACRO_define_strp:
22441         case DW_MACRO_undef_strp:
22442         case DW_MACRO_define_sup:
22443         case DW_MACRO_undef_sup:
22444           {
22445             unsigned int bytes_read;
22446
22447             read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
22448             mac_ptr += bytes_read;
22449             mac_ptr += offset_size;
22450           }
22451           break;
22452
22453         case DW_MACRO_import:
22454         case DW_MACRO_import_sup:
22455           /* Note that, according to the spec, a transparent include
22456              chain cannot call DW_MACRO_start_file.  So, we can just
22457              skip this opcode.  */
22458           mac_ptr += offset_size;
22459           break;
22460
22461         case DW_MACINFO_vendor_ext:
22462           /* Only skip the data by MAC_PTR.  */
22463           if (!section_is_gnu)
22464             {
22465               unsigned int bytes_read;
22466
22467               read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
22468               mac_ptr += bytes_read;
22469               read_direct_string (abfd, mac_ptr, &bytes_read);
22470               mac_ptr += bytes_read;
22471             }
22472           /* FALLTHROUGH */
22473
22474         default:
22475           mac_ptr = skip_unknown_opcode (macinfo_type, opcode_definitions,
22476                                          mac_ptr, mac_end, abfd, offset_size,
22477                                          section);
22478           if (mac_ptr == NULL)
22479             return;
22480           break;
22481         }
22482     } while (macinfo_type != 0 && current_file == NULL);
22483
22484   /* Second pass: Process all entries.
22485
22486      Use the AT_COMMAND_LINE flag to determine whether we are still processing
22487      command-line macro definitions/undefinitions.  This flag is unset when we
22488      reach the first DW_MACINFO_start_file entry.  */
22489
22490   htab_up include_hash (htab_create_alloc (1, htab_hash_pointer,
22491                                            htab_eq_pointer,
22492                                            NULL, xcalloc, xfree));
22493   mac_ptr = section->buffer + offset;
22494   slot = htab_find_slot (include_hash.get (), mac_ptr, INSERT);
22495   *slot = (void *) mac_ptr;
22496   dwarf_decode_macro_bytes (abfd, mac_ptr, mac_end,
22497                             current_file, lh, section,
22498                             section_is_gnu, 0, offset_size,
22499                             include_hash.get ());
22500 }
22501
22502 /* Check if the attribute's form is a DW_FORM_block*
22503    if so return true else false.  */
22504
22505 static int
22506 attr_form_is_block (const struct attribute *attr)
22507 {
22508   return (attr == NULL ? 0 :
22509       attr->form == DW_FORM_block1
22510       || attr->form == DW_FORM_block2
22511       || attr->form == DW_FORM_block4
22512       || attr->form == DW_FORM_block
22513       || attr->form == DW_FORM_exprloc);
22514 }
22515
22516 /* Return non-zero if ATTR's value is a section offset --- classes
22517    lineptr, loclistptr, macptr or rangelistptr --- or zero, otherwise.
22518    You may use DW_UNSND (attr) to retrieve such offsets.
22519
22520    Section 7.5.4, "Attribute Encodings", explains that no attribute
22521    may have a value that belongs to more than one of these classes; it
22522    would be ambiguous if we did, because we use the same forms for all
22523    of them.  */
22524
22525 static int
22526 attr_form_is_section_offset (const struct attribute *attr)
22527 {
22528   return (attr->form == DW_FORM_data4
22529           || attr->form == DW_FORM_data8
22530           || attr->form == DW_FORM_sec_offset);
22531 }
22532
22533 /* Return non-zero if ATTR's value falls in the 'constant' class, or
22534    zero otherwise.  When this function returns true, you can apply
22535    dwarf2_get_attr_constant_value to it.
22536
22537    However, note that for some attributes you must check
22538    attr_form_is_section_offset before using this test.  DW_FORM_data4
22539    and DW_FORM_data8 are members of both the constant class, and of
22540    the classes that contain offsets into other debug sections
22541    (lineptr, loclistptr, macptr or rangelistptr).  The DWARF spec says
22542    that, if an attribute's can be either a constant or one of the
22543    section offset classes, DW_FORM_data4 and DW_FORM_data8 should be
22544    taken as section offsets, not constants.
22545
22546    DW_FORM_data16 is not considered as dwarf2_get_attr_constant_value
22547    cannot handle that.  */
22548
22549 static int
22550 attr_form_is_constant (const struct attribute *attr)
22551 {
22552   switch (attr->form)
22553     {
22554     case DW_FORM_sdata:
22555     case DW_FORM_udata:
22556     case DW_FORM_data1:
22557     case DW_FORM_data2:
22558     case DW_FORM_data4:
22559     case DW_FORM_data8:
22560     case DW_FORM_implicit_const:
22561       return 1;
22562     default:
22563       return 0;
22564     }
22565 }
22566
22567
22568 /* DW_ADDR is always stored already as sect_offset; despite for the forms
22569    besides DW_FORM_ref_addr it is stored as cu_offset in the DWARF file.  */
22570
22571 static int
22572 attr_form_is_ref (const struct attribute *attr)
22573 {
22574   switch (attr->form)
22575     {
22576     case DW_FORM_ref_addr:
22577     case DW_FORM_ref1:
22578     case DW_FORM_ref2:
22579     case DW_FORM_ref4:
22580     case DW_FORM_ref8:
22581     case DW_FORM_ref_udata:
22582     case DW_FORM_GNU_ref_alt:
22583       return 1;
22584     default:
22585       return 0;
22586     }
22587 }
22588
22589 /* Return the .debug_loc section to use for CU.
22590    For DWO files use .debug_loc.dwo.  */
22591
22592 static struct dwarf2_section_info *
22593 cu_debug_loc_section (struct dwarf2_cu *cu)
22594 {
22595   if (cu->dwo_unit)
22596     {
22597       struct dwo_sections *sections = &cu->dwo_unit->dwo_file->sections;
22598       
22599       return cu->header.version >= 5 ? &sections->loclists : &sections->loc;
22600     }
22601   return (cu->header.version >= 5 ? &dwarf2_per_objfile->loclists
22602                                   : &dwarf2_per_objfile->loc);
22603 }
22604
22605 /* A helper function that fills in a dwarf2_loclist_baton.  */
22606
22607 static void
22608 fill_in_loclist_baton (struct dwarf2_cu *cu,
22609                        struct dwarf2_loclist_baton *baton,
22610                        const struct attribute *attr)
22611 {
22612   struct dwarf2_section_info *section = cu_debug_loc_section (cu);
22613
22614   dwarf2_read_section (dwarf2_per_objfile->objfile, section);
22615
22616   baton->per_cu = cu->per_cu;
22617   gdb_assert (baton->per_cu);
22618   /* We don't know how long the location list is, but make sure we
22619      don't run off the edge of the section.  */
22620   baton->size = section->size - DW_UNSND (attr);
22621   baton->data = section->buffer + DW_UNSND (attr);
22622   baton->base_address = cu->base_address;
22623   baton->from_dwo = cu->dwo_unit != NULL;
22624 }
22625
22626 static void
22627 dwarf2_symbol_mark_computed (const struct attribute *attr, struct symbol *sym,
22628                              struct dwarf2_cu *cu, int is_block)
22629 {
22630   struct objfile *objfile = dwarf2_per_objfile->objfile;
22631   struct dwarf2_section_info *section = cu_debug_loc_section (cu);
22632
22633   if (attr_form_is_section_offset (attr)
22634       /* .debug_loc{,.dwo} may not exist at all, or the offset may be outside
22635          the section.  If so, fall through to the complaint in the
22636          other branch.  */
22637       && DW_UNSND (attr) < dwarf2_section_size (objfile, section))
22638     {
22639       struct dwarf2_loclist_baton *baton;
22640
22641       baton = XOBNEW (&objfile->objfile_obstack, struct dwarf2_loclist_baton);
22642
22643       fill_in_loclist_baton (cu, baton, attr);
22644
22645       if (cu->base_known == 0)
22646         complaint (&symfile_complaints,
22647                    _("Location list used without "
22648                      "specifying the CU base address."));
22649
22650       SYMBOL_ACLASS_INDEX (sym) = (is_block
22651                                    ? dwarf2_loclist_block_index
22652                                    : dwarf2_loclist_index);
22653       SYMBOL_LOCATION_BATON (sym) = baton;
22654     }
22655   else
22656     {
22657       struct dwarf2_locexpr_baton *baton;
22658
22659       baton = XOBNEW (&objfile->objfile_obstack, struct dwarf2_locexpr_baton);
22660       baton->per_cu = cu->per_cu;
22661       gdb_assert (baton->per_cu);
22662
22663       if (attr_form_is_block (attr))
22664         {
22665           /* Note that we're just copying the block's data pointer
22666              here, not the actual data.  We're still pointing into the
22667              info_buffer for SYM's objfile; right now we never release
22668              that buffer, but when we do clean up properly this may
22669              need to change.  */
22670           baton->size = DW_BLOCK (attr)->size;
22671           baton->data = DW_BLOCK (attr)->data;
22672         }
22673       else
22674         {
22675           dwarf2_invalid_attrib_class_complaint ("location description",
22676                                                  SYMBOL_NATURAL_NAME (sym));
22677           baton->size = 0;
22678         }
22679
22680       SYMBOL_ACLASS_INDEX (sym) = (is_block
22681                                    ? dwarf2_locexpr_block_index
22682                                    : dwarf2_locexpr_index);
22683       SYMBOL_LOCATION_BATON (sym) = baton;
22684     }
22685 }
22686
22687 /* Return the OBJFILE associated with the compilation unit CU.  If CU
22688    came from a separate debuginfo file, then the master objfile is
22689    returned.  */
22690
22691 struct objfile *
22692 dwarf2_per_cu_objfile (struct dwarf2_per_cu_data *per_cu)
22693 {
22694   struct objfile *objfile = per_cu->objfile;
22695
22696   /* Return the master objfile, so that we can report and look up the
22697      correct file containing this variable.  */
22698   if (objfile->separate_debug_objfile_backlink)
22699     objfile = objfile->separate_debug_objfile_backlink;
22700
22701   return objfile;
22702 }
22703
22704 /* Return comp_unit_head for PER_CU, either already available in PER_CU->CU
22705    (CU_HEADERP is unused in such case) or prepare a temporary copy at
22706    CU_HEADERP first.  */
22707
22708 static const struct comp_unit_head *
22709 per_cu_header_read_in (struct comp_unit_head *cu_headerp,
22710                        struct dwarf2_per_cu_data *per_cu)
22711 {
22712   const gdb_byte *info_ptr;
22713
22714   if (per_cu->cu)
22715     return &per_cu->cu->header;
22716
22717   info_ptr = per_cu->section->buffer + to_underlying (per_cu->sect_off);
22718
22719   memset (cu_headerp, 0, sizeof (*cu_headerp));
22720   read_comp_unit_head (cu_headerp, info_ptr, per_cu->section,
22721                        rcuh_kind::COMPILE);
22722
22723   return cu_headerp;
22724 }
22725
22726 /* Return the address size given in the compilation unit header for CU.  */
22727
22728 int
22729 dwarf2_per_cu_addr_size (struct dwarf2_per_cu_data *per_cu)
22730 {
22731   struct comp_unit_head cu_header_local;
22732   const struct comp_unit_head *cu_headerp;
22733
22734   cu_headerp = per_cu_header_read_in (&cu_header_local, per_cu);
22735
22736   return cu_headerp->addr_size;
22737 }
22738
22739 /* Return the offset size given in the compilation unit header for CU.  */
22740
22741 int
22742 dwarf2_per_cu_offset_size (struct dwarf2_per_cu_data *per_cu)
22743 {
22744   struct comp_unit_head cu_header_local;
22745   const struct comp_unit_head *cu_headerp;
22746
22747   cu_headerp = per_cu_header_read_in (&cu_header_local, per_cu);
22748
22749   return cu_headerp->offset_size;
22750 }
22751
22752 /* See its dwarf2loc.h declaration.  */
22753
22754 int
22755 dwarf2_per_cu_ref_addr_size (struct dwarf2_per_cu_data *per_cu)
22756 {
22757   struct comp_unit_head cu_header_local;
22758   const struct comp_unit_head *cu_headerp;
22759
22760   cu_headerp = per_cu_header_read_in (&cu_header_local, per_cu);
22761
22762   if (cu_headerp->version == 2)
22763     return cu_headerp->addr_size;
22764   else
22765     return cu_headerp->offset_size;
22766 }
22767
22768 /* Return the text offset of the CU.  The returned offset comes from
22769    this CU's objfile.  If this objfile came from a separate debuginfo
22770    file, then the offset may be different from the corresponding
22771    offset in the parent objfile.  */
22772
22773 CORE_ADDR
22774 dwarf2_per_cu_text_offset (struct dwarf2_per_cu_data *per_cu)
22775 {
22776   struct objfile *objfile = per_cu->objfile;
22777
22778   return ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
22779 }
22780
22781 /* Return DWARF version number of PER_CU.  */
22782
22783 short
22784 dwarf2_version (struct dwarf2_per_cu_data *per_cu)
22785 {
22786   return per_cu->dwarf_version;
22787 }
22788
22789 /* Locate the .debug_info compilation unit from CU's objfile which contains
22790    the DIE at OFFSET.  Raises an error on failure.  */
22791
22792 static struct dwarf2_per_cu_data *
22793 dwarf2_find_containing_comp_unit (sect_offset sect_off,
22794                                   unsigned int offset_in_dwz,
22795                                   struct objfile *objfile)
22796 {
22797   struct dwarf2_per_cu_data *this_cu;
22798   int low, high;
22799   const sect_offset *cu_off;
22800
22801   low = 0;
22802   high = dwarf2_per_objfile->n_comp_units - 1;
22803   while (high > low)
22804     {
22805       struct dwarf2_per_cu_data *mid_cu;
22806       int mid = low + (high - low) / 2;
22807
22808       mid_cu = dwarf2_per_objfile->all_comp_units[mid];
22809       cu_off = &mid_cu->sect_off;
22810       if (mid_cu->is_dwz > offset_in_dwz
22811           || (mid_cu->is_dwz == offset_in_dwz && *cu_off >= sect_off))
22812         high = mid;
22813       else
22814         low = mid + 1;
22815     }
22816   gdb_assert (low == high);
22817   this_cu = dwarf2_per_objfile->all_comp_units[low];
22818   cu_off = &this_cu->sect_off;
22819   if (this_cu->is_dwz != offset_in_dwz || *cu_off > sect_off)
22820     {
22821       if (low == 0 || this_cu->is_dwz != offset_in_dwz)
22822         error (_("Dwarf Error: could not find partial DIE containing "
22823                "offset 0x%x [in module %s]"),
22824                to_underlying (sect_off), bfd_get_filename (objfile->obfd));
22825
22826       gdb_assert (dwarf2_per_objfile->all_comp_units[low-1]->sect_off
22827                   <= sect_off);
22828       return dwarf2_per_objfile->all_comp_units[low-1];
22829     }
22830   else
22831     {
22832       this_cu = dwarf2_per_objfile->all_comp_units[low];
22833       if (low == dwarf2_per_objfile->n_comp_units - 1
22834           && sect_off >= this_cu->sect_off + this_cu->length)
22835         error (_("invalid dwarf2 offset %u"), to_underlying (sect_off));
22836       gdb_assert (sect_off < this_cu->sect_off + this_cu->length);
22837       return this_cu;
22838     }
22839 }
22840
22841 /* Initialize dwarf2_cu CU, owned by PER_CU.  */
22842
22843 static void
22844 init_one_comp_unit (struct dwarf2_cu *cu, struct dwarf2_per_cu_data *per_cu)
22845 {
22846   memset (cu, 0, sizeof (*cu));
22847   per_cu->cu = cu;
22848   cu->per_cu = per_cu;
22849   cu->objfile = per_cu->objfile;
22850   obstack_init (&cu->comp_unit_obstack);
22851 }
22852
22853 /* Initialize basic fields of dwarf_cu CU according to DIE COMP_UNIT_DIE.  */
22854
22855 static void
22856 prepare_one_comp_unit (struct dwarf2_cu *cu, struct die_info *comp_unit_die,
22857                        enum language pretend_language)
22858 {
22859   struct attribute *attr;
22860
22861   /* Set the language we're debugging.  */
22862   attr = dwarf2_attr (comp_unit_die, DW_AT_language, cu);
22863   if (attr)
22864     set_cu_language (DW_UNSND (attr), cu);
22865   else
22866     {
22867       cu->language = pretend_language;
22868       cu->language_defn = language_def (cu->language);
22869     }
22870
22871   cu->producer = dwarf2_string_attr (comp_unit_die, DW_AT_producer, cu);
22872 }
22873
22874 /* Release one cached compilation unit, CU.  We unlink it from the tree
22875    of compilation units, but we don't remove it from the read_in_chain;
22876    the caller is responsible for that.
22877    NOTE: DATA is a void * because this function is also used as a
22878    cleanup routine.  */
22879
22880 static void
22881 free_heap_comp_unit (void *data)
22882 {
22883   struct dwarf2_cu *cu = (struct dwarf2_cu *) data;
22884
22885   gdb_assert (cu->per_cu != NULL);
22886   cu->per_cu->cu = NULL;
22887   cu->per_cu = NULL;
22888
22889   obstack_free (&cu->comp_unit_obstack, NULL);
22890
22891   xfree (cu);
22892 }
22893
22894 /* This cleanup function is passed the address of a dwarf2_cu on the stack
22895    when we're finished with it.  We can't free the pointer itself, but be
22896    sure to unlink it from the cache.  Also release any associated storage.  */
22897
22898 static void
22899 free_stack_comp_unit (void *data)
22900 {
22901   struct dwarf2_cu *cu = (struct dwarf2_cu *) data;
22902
22903   gdb_assert (cu->per_cu != NULL);
22904   cu->per_cu->cu = NULL;
22905   cu->per_cu = NULL;
22906
22907   obstack_free (&cu->comp_unit_obstack, NULL);
22908   cu->partial_dies = NULL;
22909 }
22910
22911 /* Free all cached compilation units.  */
22912
22913 static void
22914 free_cached_comp_units (void *data)
22915 {
22916   dwarf2_per_objfile->free_cached_comp_units ();
22917 }
22918
22919 /* Increase the age counter on each cached compilation unit, and free
22920    any that are too old.  */
22921
22922 static void
22923 age_cached_comp_units (void)
22924 {
22925   struct dwarf2_per_cu_data *per_cu, **last_chain;
22926
22927   dwarf2_clear_marks (dwarf2_per_objfile->read_in_chain);
22928   per_cu = dwarf2_per_objfile->read_in_chain;
22929   while (per_cu != NULL)
22930     {
22931       per_cu->cu->last_used ++;
22932       if (per_cu->cu->last_used <= dwarf_max_cache_age)
22933         dwarf2_mark (per_cu->cu);
22934       per_cu = per_cu->cu->read_in_chain;
22935     }
22936
22937   per_cu = dwarf2_per_objfile->read_in_chain;
22938   last_chain = &dwarf2_per_objfile->read_in_chain;
22939   while (per_cu != NULL)
22940     {
22941       struct dwarf2_per_cu_data *next_cu;
22942
22943       next_cu = per_cu->cu->read_in_chain;
22944
22945       if (!per_cu->cu->mark)
22946         {
22947           free_heap_comp_unit (per_cu->cu);
22948           *last_chain = next_cu;
22949         }
22950       else
22951         last_chain = &per_cu->cu->read_in_chain;
22952
22953       per_cu = next_cu;
22954     }
22955 }
22956
22957 /* Remove a single compilation unit from the cache.  */
22958
22959 static void
22960 free_one_cached_comp_unit (struct dwarf2_per_cu_data *target_per_cu)
22961 {
22962   struct dwarf2_per_cu_data *per_cu, **last_chain;
22963
22964   per_cu = dwarf2_per_objfile->read_in_chain;
22965   last_chain = &dwarf2_per_objfile->read_in_chain;
22966   while (per_cu != NULL)
22967     {
22968       struct dwarf2_per_cu_data *next_cu;
22969
22970       next_cu = per_cu->cu->read_in_chain;
22971
22972       if (per_cu == target_per_cu)
22973         {
22974           free_heap_comp_unit (per_cu->cu);
22975           per_cu->cu = NULL;
22976           *last_chain = next_cu;
22977           break;
22978         }
22979       else
22980         last_chain = &per_cu->cu->read_in_chain;
22981
22982       per_cu = next_cu;
22983     }
22984 }
22985
22986 /* Release all extra memory associated with OBJFILE.  */
22987
22988 void
22989 dwarf2_free_objfile (struct objfile *objfile)
22990 {
22991   dwarf2_per_objfile
22992     = (struct dwarf2_per_objfile *) objfile_data (objfile,
22993                                                   dwarf2_objfile_data_key);
22994
22995   if (dwarf2_per_objfile == NULL)
22996     return;
22997
22998   dwarf2_per_objfile->~dwarf2_per_objfile ();
22999 }
23000
23001 /* A set of CU "per_cu" pointer, DIE offset, and GDB type pointer.
23002    We store these in a hash table separate from the DIEs, and preserve them
23003    when the DIEs are flushed out of cache.
23004
23005    The CU "per_cu" pointer is needed because offset alone is not enough to
23006    uniquely identify the type.  A file may have multiple .debug_types sections,
23007    or the type may come from a DWO file.  Furthermore, while it's more logical
23008    to use per_cu->section+offset, with Fission the section with the data is in
23009    the DWO file but we don't know that section at the point we need it.
23010    We have to use something in dwarf2_per_cu_data (or the pointer to it)
23011    because we can enter the lookup routine, get_die_type_at_offset, from
23012    outside this file, and thus won't necessarily have PER_CU->cu.
23013    Fortunately, PER_CU is stable for the life of the objfile.  */
23014
23015 struct dwarf2_per_cu_offset_and_type
23016 {
23017   const struct dwarf2_per_cu_data *per_cu;
23018   sect_offset sect_off;
23019   struct type *type;
23020 };
23021
23022 /* Hash function for a dwarf2_per_cu_offset_and_type.  */
23023
23024 static hashval_t
23025 per_cu_offset_and_type_hash (const void *item)
23026 {
23027   const struct dwarf2_per_cu_offset_and_type *ofs
23028     = (const struct dwarf2_per_cu_offset_and_type *) item;
23029
23030   return (uintptr_t) ofs->per_cu + to_underlying (ofs->sect_off);
23031 }
23032
23033 /* Equality function for a dwarf2_per_cu_offset_and_type.  */
23034
23035 static int
23036 per_cu_offset_and_type_eq (const void *item_lhs, const void *item_rhs)
23037 {
23038   const struct dwarf2_per_cu_offset_and_type *ofs_lhs
23039     = (const struct dwarf2_per_cu_offset_and_type *) item_lhs;
23040   const struct dwarf2_per_cu_offset_and_type *ofs_rhs
23041     = (const struct dwarf2_per_cu_offset_and_type *) item_rhs;
23042
23043   return (ofs_lhs->per_cu == ofs_rhs->per_cu
23044           && ofs_lhs->sect_off == ofs_rhs->sect_off);
23045 }
23046
23047 /* Set the type associated with DIE to TYPE.  Save it in CU's hash
23048    table if necessary.  For convenience, return TYPE.
23049
23050    The DIEs reading must have careful ordering to:
23051     * Not cause infite loops trying to read in DIEs as a prerequisite for
23052       reading current DIE.
23053     * Not trying to dereference contents of still incompletely read in types
23054       while reading in other DIEs.
23055     * Enable referencing still incompletely read in types just by a pointer to
23056       the type without accessing its fields.
23057
23058    Therefore caller should follow these rules:
23059      * Try to fetch any prerequisite types we may need to build this DIE type
23060        before building the type and calling set_die_type.
23061      * After building type call set_die_type for current DIE as soon as
23062        possible before fetching more types to complete the current type.
23063      * Make the type as complete as possible before fetching more types.  */
23064
23065 static struct type *
23066 set_die_type (struct die_info *die, struct type *type, struct dwarf2_cu *cu)
23067 {
23068   struct dwarf2_per_cu_offset_and_type **slot, ofs;
23069   struct objfile *objfile = cu->objfile;
23070   struct attribute *attr;
23071   struct dynamic_prop prop;
23072
23073   /* For Ada types, make sure that the gnat-specific data is always
23074      initialized (if not already set).  There are a few types where
23075      we should not be doing so, because the type-specific area is
23076      already used to hold some other piece of info (eg: TYPE_CODE_FLT
23077      where the type-specific area is used to store the floatformat).
23078      But this is not a problem, because the gnat-specific information
23079      is actually not needed for these types.  */
23080   if (need_gnat_info (cu)
23081       && TYPE_CODE (type) != TYPE_CODE_FUNC
23082       && TYPE_CODE (type) != TYPE_CODE_FLT
23083       && TYPE_CODE (type) != TYPE_CODE_METHODPTR
23084       && TYPE_CODE (type) != TYPE_CODE_MEMBERPTR
23085       && TYPE_CODE (type) != TYPE_CODE_METHOD
23086       && !HAVE_GNAT_AUX_INFO (type))
23087     INIT_GNAT_SPECIFIC (type);
23088
23089   /* Read DW_AT_allocated and set in type.  */
23090   attr = dwarf2_attr (die, DW_AT_allocated, cu);
23091   if (attr_form_is_block (attr))
23092     {
23093       if (attr_to_dynamic_prop (attr, die, cu, &prop))
23094         add_dyn_prop (DYN_PROP_ALLOCATED, prop, type, objfile);
23095     }
23096   else if (attr != NULL)
23097     {
23098       complaint (&symfile_complaints,
23099                  _("DW_AT_allocated has the wrong form (%s) at DIE 0x%x"),
23100                  (attr != NULL ? dwarf_form_name (attr->form) : "n/a"),
23101                  to_underlying (die->sect_off));
23102     }
23103
23104   /* Read DW_AT_associated and set in type.  */
23105   attr = dwarf2_attr (die, DW_AT_associated, cu);
23106   if (attr_form_is_block (attr))
23107     {
23108       if (attr_to_dynamic_prop (attr, die, cu, &prop))
23109         add_dyn_prop (DYN_PROP_ASSOCIATED, prop, type, objfile);
23110     }
23111   else if (attr != NULL)
23112     {
23113       complaint (&symfile_complaints,
23114                  _("DW_AT_associated has the wrong form (%s) at DIE 0x%x"),
23115                  (attr != NULL ? dwarf_form_name (attr->form) : "n/a"),
23116                  to_underlying (die->sect_off));
23117     }
23118
23119   /* Read DW_AT_data_location and set in type.  */
23120   attr = dwarf2_attr (die, DW_AT_data_location, cu);
23121   if (attr_to_dynamic_prop (attr, die, cu, &prop))
23122     add_dyn_prop (DYN_PROP_DATA_LOCATION, prop, type, objfile);
23123
23124   if (dwarf2_per_objfile->die_type_hash == NULL)
23125     {
23126       dwarf2_per_objfile->die_type_hash =
23127         htab_create_alloc_ex (127,
23128                               per_cu_offset_and_type_hash,
23129                               per_cu_offset_and_type_eq,
23130                               NULL,
23131                               &objfile->objfile_obstack,
23132                               hashtab_obstack_allocate,
23133                               dummy_obstack_deallocate);
23134     }
23135
23136   ofs.per_cu = cu->per_cu;
23137   ofs.sect_off = die->sect_off;
23138   ofs.type = type;
23139   slot = (struct dwarf2_per_cu_offset_and_type **)
23140     htab_find_slot (dwarf2_per_objfile->die_type_hash, &ofs, INSERT);
23141   if (*slot)
23142     complaint (&symfile_complaints,
23143                _("A problem internal to GDB: DIE 0x%x has type already set"),
23144                to_underlying (die->sect_off));
23145   *slot = XOBNEW (&objfile->objfile_obstack,
23146                   struct dwarf2_per_cu_offset_and_type);
23147   **slot = ofs;
23148   return type;
23149 }
23150
23151 /* Look up the type for the die at SECT_OFF in PER_CU in die_type_hash,
23152    or return NULL if the die does not have a saved type.  */
23153
23154 static struct type *
23155 get_die_type_at_offset (sect_offset sect_off,
23156                         struct dwarf2_per_cu_data *per_cu)
23157 {
23158   struct dwarf2_per_cu_offset_and_type *slot, ofs;
23159
23160   if (dwarf2_per_objfile->die_type_hash == NULL)
23161     return NULL;
23162
23163   ofs.per_cu = per_cu;
23164   ofs.sect_off = sect_off;
23165   slot = ((struct dwarf2_per_cu_offset_and_type *)
23166           htab_find (dwarf2_per_objfile->die_type_hash, &ofs));
23167   if (slot)
23168     return slot->type;
23169   else
23170     return NULL;
23171 }
23172
23173 /* Look up the type for DIE in CU in die_type_hash,
23174    or return NULL if DIE does not have a saved type.  */
23175
23176 static struct type *
23177 get_die_type (struct die_info *die, struct dwarf2_cu *cu)
23178 {
23179   return get_die_type_at_offset (die->sect_off, cu->per_cu);
23180 }
23181
23182 /* Add a dependence relationship from CU to REF_PER_CU.  */
23183
23184 static void
23185 dwarf2_add_dependence (struct dwarf2_cu *cu,
23186                        struct dwarf2_per_cu_data *ref_per_cu)
23187 {
23188   void **slot;
23189
23190   if (cu->dependencies == NULL)
23191     cu->dependencies
23192       = htab_create_alloc_ex (5, htab_hash_pointer, htab_eq_pointer,
23193                               NULL, &cu->comp_unit_obstack,
23194                               hashtab_obstack_allocate,
23195                               dummy_obstack_deallocate);
23196
23197   slot = htab_find_slot (cu->dependencies, ref_per_cu, INSERT);
23198   if (*slot == NULL)
23199     *slot = ref_per_cu;
23200 }
23201
23202 /* Subroutine of dwarf2_mark to pass to htab_traverse.
23203    Set the mark field in every compilation unit in the
23204    cache that we must keep because we are keeping CU.  */
23205
23206 static int
23207 dwarf2_mark_helper (void **slot, void *data)
23208 {
23209   struct dwarf2_per_cu_data *per_cu;
23210
23211   per_cu = (struct dwarf2_per_cu_data *) *slot;
23212
23213   /* cu->dependencies references may not yet have been ever read if QUIT aborts
23214      reading of the chain.  As such dependencies remain valid it is not much
23215      useful to track and undo them during QUIT cleanups.  */
23216   if (per_cu->cu == NULL)
23217     return 1;
23218
23219   if (per_cu->cu->mark)
23220     return 1;
23221   per_cu->cu->mark = 1;
23222
23223   if (per_cu->cu->dependencies != NULL)
23224     htab_traverse (per_cu->cu->dependencies, dwarf2_mark_helper, NULL);
23225
23226   return 1;
23227 }
23228
23229 /* Set the mark field in CU and in every other compilation unit in the
23230    cache that we must keep because we are keeping CU.  */
23231
23232 static void
23233 dwarf2_mark (struct dwarf2_cu *cu)
23234 {
23235   if (cu->mark)
23236     return;
23237   cu->mark = 1;
23238   if (cu->dependencies != NULL)
23239     htab_traverse (cu->dependencies, dwarf2_mark_helper, NULL);
23240 }
23241
23242 static void
23243 dwarf2_clear_marks (struct dwarf2_per_cu_data *per_cu)
23244 {
23245   while (per_cu)
23246     {
23247       per_cu->cu->mark = 0;
23248       per_cu = per_cu->cu->read_in_chain;
23249     }
23250 }
23251
23252 /* Trivial hash function for partial_die_info: the hash value of a DIE
23253    is its offset in .debug_info for this objfile.  */
23254
23255 static hashval_t
23256 partial_die_hash (const void *item)
23257 {
23258   const struct partial_die_info *part_die
23259     = (const struct partial_die_info *) item;
23260
23261   return to_underlying (part_die->sect_off);
23262 }
23263
23264 /* Trivial comparison function for partial_die_info structures: two DIEs
23265    are equal if they have the same offset.  */
23266
23267 static int
23268 partial_die_eq (const void *item_lhs, const void *item_rhs)
23269 {
23270   const struct partial_die_info *part_die_lhs
23271     = (const struct partial_die_info *) item_lhs;
23272   const struct partial_die_info *part_die_rhs
23273     = (const struct partial_die_info *) item_rhs;
23274
23275   return part_die_lhs->sect_off == part_die_rhs->sect_off;
23276 }
23277
23278 static struct cmd_list_element *set_dwarf_cmdlist;
23279 static struct cmd_list_element *show_dwarf_cmdlist;
23280
23281 static void
23282 set_dwarf_cmd (char *args, int from_tty)
23283 {
23284   help_list (set_dwarf_cmdlist, "maintenance set dwarf ", all_commands,
23285              gdb_stdout);
23286 }
23287
23288 static void
23289 show_dwarf_cmd (char *args, int from_tty)
23290 {
23291   cmd_show_list (show_dwarf_cmdlist, from_tty, "");
23292 }
23293
23294 /* Free data associated with OBJFILE, if necessary.  */
23295
23296 static void
23297 dwarf2_per_objfile_free (struct objfile *objfile, void *d)
23298 {
23299   struct dwarf2_per_objfile *data = (struct dwarf2_per_objfile *) d;
23300   int ix;
23301
23302   /* Make sure we don't accidentally use dwarf2_per_objfile while
23303      cleaning up.  */
23304   dwarf2_per_objfile = NULL;
23305
23306   for (ix = 0; ix < data->n_comp_units; ++ix)
23307    VEC_free (dwarf2_per_cu_ptr, data->all_comp_units[ix]->imported_symtabs);
23308
23309   for (ix = 0; ix < data->n_type_units; ++ix)
23310     VEC_free (dwarf2_per_cu_ptr,
23311               data->all_type_units[ix]->per_cu.imported_symtabs);
23312   xfree (data->all_type_units);
23313
23314   VEC_free (dwarf2_section_info_def, data->types);
23315
23316   if (data->dwo_files)
23317     free_dwo_files (data->dwo_files, objfile);
23318   if (data->dwp_file)
23319     gdb_bfd_unref (data->dwp_file->dbfd);
23320
23321   if (data->dwz_file && data->dwz_file->dwz_bfd)
23322     gdb_bfd_unref (data->dwz_file->dwz_bfd);
23323 }
23324
23325 \f
23326 /* The "save gdb-index" command.  */
23327
23328 /* In-memory buffer to prepare data to be written later to a file.  */
23329 class data_buf
23330 {
23331 public:
23332   /* Copy DATA to the end of the buffer.  */
23333   template<typename T>
23334   void append_data (const T &data)
23335   {
23336     std::copy (reinterpret_cast<const gdb_byte *> (&data),
23337                reinterpret_cast<const gdb_byte *> (&data + 1),
23338                grow (sizeof (data)));
23339   }
23340
23341   /* Copy CSTR (a zero-terminated string) to the end of buffer.  The
23342      terminating zero is appended too.  */
23343   void append_cstr0 (const char *cstr)
23344   {
23345     const size_t size = strlen (cstr) + 1;
23346     std::copy (cstr, cstr + size, grow (size));
23347   }
23348
23349   /* Accept a host-format integer in VAL and append it to the buffer
23350      as a target-format integer which is LEN bytes long.  */
23351   void append_uint (size_t len, bfd_endian byte_order, ULONGEST val)
23352   {
23353     ::store_unsigned_integer (grow (len), len, byte_order, val);
23354   }
23355
23356   /* Return the size of the buffer.  */
23357   size_t size () const
23358   {
23359     return m_vec.size ();
23360   }
23361
23362   /* Write the buffer to FILE.  */
23363   void file_write (FILE *file) const
23364   {
23365     if (::fwrite (m_vec.data (), 1, m_vec.size (), file) != m_vec.size ())
23366       error (_("couldn't write data to file"));
23367   }
23368
23369 private:
23370   /* Grow SIZE bytes at the end of the buffer.  Returns a pointer to
23371      the start of the new block.  */
23372   gdb_byte *grow (size_t size)
23373   {
23374     m_vec.resize (m_vec.size () + size);
23375     return &*m_vec.end () - size;
23376   }
23377
23378   gdb::byte_vector m_vec;
23379 };
23380
23381 /* An entry in the symbol table.  */
23382 struct symtab_index_entry
23383 {
23384   /* The name of the symbol.  */
23385   const char *name;
23386   /* The offset of the name in the constant pool.  */
23387   offset_type index_offset;
23388   /* A sorted vector of the indices of all the CUs that hold an object
23389      of this name.  */
23390   std::vector<offset_type> cu_indices;
23391 };
23392
23393 /* The symbol table.  This is a power-of-2-sized hash table.  */
23394 struct mapped_symtab
23395 {
23396   mapped_symtab ()
23397   {
23398     data.resize (1024);
23399   }
23400
23401   offset_type n_elements = 0;
23402   std::vector<symtab_index_entry> data;
23403 };
23404
23405 /* Find a slot in SYMTAB for the symbol NAME.  Returns a reference to
23406    the slot.
23407    
23408    Function is used only during write_hash_table so no index format backward
23409    compatibility is needed.  */
23410
23411 static symtab_index_entry &
23412 find_slot (struct mapped_symtab *symtab, const char *name)
23413 {
23414   offset_type index, step, hash = mapped_index_string_hash (INT_MAX, name);
23415
23416   index = hash & (symtab->data.size () - 1);
23417   step = ((hash * 17) & (symtab->data.size () - 1)) | 1;
23418
23419   for (;;)
23420     {
23421       if (symtab->data[index].name == NULL
23422           || strcmp (name, symtab->data[index].name) == 0)
23423         return symtab->data[index];
23424       index = (index + step) & (symtab->data.size () - 1);
23425     }
23426 }
23427
23428 /* Expand SYMTAB's hash table.  */
23429
23430 static void
23431 hash_expand (struct mapped_symtab *symtab)
23432 {
23433   auto old_entries = std::move (symtab->data);
23434
23435   symtab->data.clear ();
23436   symtab->data.resize (old_entries.size () * 2);
23437
23438   for (auto &it : old_entries)
23439     if (it.name != NULL)
23440       {
23441         auto &ref = find_slot (symtab, it.name);
23442         ref = std::move (it);
23443       }
23444 }
23445
23446 /* Add an entry to SYMTAB.  NAME is the name of the symbol.
23447    CU_INDEX is the index of the CU in which the symbol appears.
23448    IS_STATIC is one if the symbol is static, otherwise zero (global).  */
23449
23450 static void
23451 add_index_entry (struct mapped_symtab *symtab, const char *name,
23452                  int is_static, gdb_index_symbol_kind kind,
23453                  offset_type cu_index)
23454 {
23455   offset_type cu_index_and_attrs;
23456
23457   ++symtab->n_elements;
23458   if (4 * symtab->n_elements / 3 >= symtab->data.size ())
23459     hash_expand (symtab);
23460
23461   symtab_index_entry &slot = find_slot (symtab, name);
23462   if (slot.name == NULL)
23463     {
23464       slot.name = name;
23465       /* index_offset is set later.  */
23466     }
23467
23468   cu_index_and_attrs = 0;
23469   DW2_GDB_INDEX_CU_SET_VALUE (cu_index_and_attrs, cu_index);
23470   DW2_GDB_INDEX_SYMBOL_STATIC_SET_VALUE (cu_index_and_attrs, is_static);
23471   DW2_GDB_INDEX_SYMBOL_KIND_SET_VALUE (cu_index_and_attrs, kind);
23472
23473   /* We don't want to record an index value twice as we want to avoid the
23474      duplication.
23475      We process all global symbols and then all static symbols
23476      (which would allow us to avoid the duplication by only having to check
23477      the last entry pushed), but a symbol could have multiple kinds in one CU.
23478      To keep things simple we don't worry about the duplication here and
23479      sort and uniqufy the list after we've processed all symbols.  */
23480   slot.cu_indices.push_back (cu_index_and_attrs);
23481 }
23482
23483 /* Sort and remove duplicates of all symbols' cu_indices lists.  */
23484
23485 static void
23486 uniquify_cu_indices (struct mapped_symtab *symtab)
23487 {
23488   for (auto &entry : symtab->data)
23489     {
23490       if (entry.name != NULL && !entry.cu_indices.empty ())
23491         {
23492           auto &cu_indices = entry.cu_indices;
23493           std::sort (cu_indices.begin (), cu_indices.end ());
23494           auto from = std::unique (cu_indices.begin (), cu_indices.end ());
23495           cu_indices.erase (from, cu_indices.end ());
23496         }
23497     }
23498 }
23499
23500 /* A form of 'const char *' suitable for container keys.  Only the
23501    pointer is stored.  The strings themselves are compared, not the
23502    pointers.  */
23503 class c_str_view
23504 {
23505 public:
23506   c_str_view (const char *cstr)
23507     : m_cstr (cstr)
23508   {}
23509
23510   bool operator== (const c_str_view &other) const
23511   {
23512     return strcmp (m_cstr, other.m_cstr) == 0;
23513   }
23514
23515 private:
23516   friend class c_str_view_hasher;
23517   const char *const m_cstr;
23518 };
23519
23520 /* A std::unordered_map::hasher for c_str_view that uses the right
23521    hash function for strings in a mapped index.  */
23522 class c_str_view_hasher
23523 {
23524 public:
23525   size_t operator () (const c_str_view &x) const
23526   {
23527     return mapped_index_string_hash (INT_MAX, x.m_cstr);
23528   }
23529 };
23530
23531 /* A std::unordered_map::hasher for std::vector<>.  */
23532 template<typename T>
23533 class vector_hasher
23534 {
23535 public:
23536   size_t operator () (const std::vector<T> &key) const
23537   {
23538     return iterative_hash (key.data (),
23539                            sizeof (key.front ()) * key.size (), 0);
23540   }
23541 };
23542
23543 /* Write the mapped hash table SYMTAB to the data buffer OUTPUT, with
23544    constant pool entries going into the data buffer CPOOL.  */
23545
23546 static void
23547 write_hash_table (mapped_symtab *symtab, data_buf &output, data_buf &cpool)
23548 {
23549   {
23550     /* Elements are sorted vectors of the indices of all the CUs that
23551        hold an object of this name.  */
23552     std::unordered_map<std::vector<offset_type>, offset_type,
23553                        vector_hasher<offset_type>>
23554       symbol_hash_table;
23555
23556     /* We add all the index vectors to the constant pool first, to
23557        ensure alignment is ok.  */
23558     for (symtab_index_entry &entry : symtab->data)
23559       {
23560         if (entry.name == NULL)
23561           continue;
23562         gdb_assert (entry.index_offset == 0);
23563
23564         /* Finding before inserting is faster than always trying to
23565            insert, because inserting always allocates a node, does the
23566            lookup, and then destroys the new node if another node
23567            already had the same key.  C++17 try_emplace will avoid
23568            this.  */
23569         const auto found
23570           = symbol_hash_table.find (entry.cu_indices);
23571         if (found != symbol_hash_table.end ())
23572           {
23573             entry.index_offset = found->second;
23574             continue;
23575           }
23576
23577         symbol_hash_table.emplace (entry.cu_indices, cpool.size ());
23578         entry.index_offset = cpool.size ();
23579         cpool.append_data (MAYBE_SWAP (entry.cu_indices.size ()));
23580         for (const auto index : entry.cu_indices)
23581           cpool.append_data (MAYBE_SWAP (index));
23582       }
23583   }
23584
23585   /* Now write out the hash table.  */
23586   std::unordered_map<c_str_view, offset_type, c_str_view_hasher> str_table;
23587   for (const auto &entry : symtab->data)
23588     {
23589       offset_type str_off, vec_off;
23590
23591       if (entry.name != NULL)
23592         {
23593           const auto insertpair = str_table.emplace (entry.name, cpool.size ());
23594           if (insertpair.second)
23595             cpool.append_cstr0 (entry.name);
23596           str_off = insertpair.first->second;
23597           vec_off = entry.index_offset;
23598         }
23599       else
23600         {
23601           /* While 0 is a valid constant pool index, it is not valid
23602              to have 0 for both offsets.  */
23603           str_off = 0;
23604           vec_off = 0;
23605         }
23606
23607       output.append_data (MAYBE_SWAP (str_off));
23608       output.append_data (MAYBE_SWAP (vec_off));
23609     }
23610 }
23611
23612 typedef std::unordered_map<partial_symtab *, unsigned int> psym_index_map;
23613
23614 /* Helper struct for building the address table.  */
23615 struct addrmap_index_data
23616 {
23617   addrmap_index_data (data_buf &addr_vec_, psym_index_map &cu_index_htab_)
23618     : addr_vec (addr_vec_), cu_index_htab (cu_index_htab_)
23619   {}
23620
23621   struct objfile *objfile;
23622   data_buf &addr_vec;
23623   psym_index_map &cu_index_htab;
23624
23625   /* Non-zero if the previous_* fields are valid.
23626      We can't write an entry until we see the next entry (since it is only then
23627      that we know the end of the entry).  */
23628   int previous_valid;
23629   /* Index of the CU in the table of all CUs in the index file.  */
23630   unsigned int previous_cu_index;
23631   /* Start address of the CU.  */
23632   CORE_ADDR previous_cu_start;
23633 };
23634
23635 /* Write an address entry to ADDR_VEC.  */
23636
23637 static void
23638 add_address_entry (struct objfile *objfile, data_buf &addr_vec,
23639                    CORE_ADDR start, CORE_ADDR end, unsigned int cu_index)
23640 {
23641   CORE_ADDR baseaddr;
23642
23643   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
23644
23645   addr_vec.append_uint (8, BFD_ENDIAN_LITTLE, start - baseaddr);
23646   addr_vec.append_uint (8, BFD_ENDIAN_LITTLE, end - baseaddr);
23647   addr_vec.append_data (MAYBE_SWAP (cu_index));
23648 }
23649
23650 /* Worker function for traversing an addrmap to build the address table.  */
23651
23652 static int
23653 add_address_entry_worker (void *datap, CORE_ADDR start_addr, void *obj)
23654 {
23655   struct addrmap_index_data *data = (struct addrmap_index_data *) datap;
23656   struct partial_symtab *pst = (struct partial_symtab *) obj;
23657
23658   if (data->previous_valid)
23659     add_address_entry (data->objfile, data->addr_vec,
23660                        data->previous_cu_start, start_addr,
23661                        data->previous_cu_index);
23662
23663   data->previous_cu_start = start_addr;
23664   if (pst != NULL)
23665     {
23666       const auto it = data->cu_index_htab.find (pst);
23667       gdb_assert (it != data->cu_index_htab.cend ());
23668       data->previous_cu_index = it->second;
23669       data->previous_valid = 1;
23670     }
23671   else
23672     data->previous_valid = 0;
23673
23674   return 0;
23675 }
23676
23677 /* Write OBJFILE's address map to ADDR_VEC.
23678    CU_INDEX_HTAB is used to map addrmap entries to their CU indices
23679    in the index file.  */
23680
23681 static void
23682 write_address_map (struct objfile *objfile, data_buf &addr_vec,
23683                    psym_index_map &cu_index_htab)
23684 {
23685   struct addrmap_index_data addrmap_index_data (addr_vec, cu_index_htab);
23686
23687   /* When writing the address table, we have to cope with the fact that
23688      the addrmap iterator only provides the start of a region; we have to
23689      wait until the next invocation to get the start of the next region.  */
23690
23691   addrmap_index_data.objfile = objfile;
23692   addrmap_index_data.previous_valid = 0;
23693
23694   addrmap_foreach (objfile->psymtabs_addrmap, add_address_entry_worker,
23695                    &addrmap_index_data);
23696
23697   /* It's highly unlikely the last entry (end address = 0xff...ff)
23698      is valid, but we should still handle it.
23699      The end address is recorded as the start of the next region, but that
23700      doesn't work here.  To cope we pass 0xff...ff, this is a rare situation
23701      anyway.  */
23702   if (addrmap_index_data.previous_valid)
23703     add_address_entry (objfile, addr_vec,
23704                        addrmap_index_data.previous_cu_start, (CORE_ADDR) -1,
23705                        addrmap_index_data.previous_cu_index);
23706 }
23707
23708 /* Return the symbol kind of PSYM.  */
23709
23710 static gdb_index_symbol_kind
23711 symbol_kind (struct partial_symbol *psym)
23712 {
23713   domain_enum domain = PSYMBOL_DOMAIN (psym);
23714   enum address_class aclass = PSYMBOL_CLASS (psym);
23715
23716   switch (domain)
23717     {
23718     case VAR_DOMAIN:
23719       switch (aclass)
23720         {
23721         case LOC_BLOCK:
23722           return GDB_INDEX_SYMBOL_KIND_FUNCTION;
23723         case LOC_TYPEDEF:
23724           return GDB_INDEX_SYMBOL_KIND_TYPE;
23725         case LOC_COMPUTED:
23726         case LOC_CONST_BYTES:
23727         case LOC_OPTIMIZED_OUT:
23728         case LOC_STATIC:
23729           return GDB_INDEX_SYMBOL_KIND_VARIABLE;
23730         case LOC_CONST:
23731           /* Note: It's currently impossible to recognize psyms as enum values
23732              short of reading the type info.  For now punt.  */
23733           return GDB_INDEX_SYMBOL_KIND_VARIABLE;
23734         default:
23735           /* There are other LOC_FOO values that one might want to classify
23736              as variables, but dwarf2read.c doesn't currently use them.  */
23737           return GDB_INDEX_SYMBOL_KIND_OTHER;
23738         }
23739     case STRUCT_DOMAIN:
23740       return GDB_INDEX_SYMBOL_KIND_TYPE;
23741     default:
23742       return GDB_INDEX_SYMBOL_KIND_OTHER;
23743     }
23744 }
23745
23746 /* Add a list of partial symbols to SYMTAB.  */
23747
23748 static void
23749 write_psymbols (struct mapped_symtab *symtab,
23750                 std::unordered_set<partial_symbol *> &psyms_seen,
23751                 struct partial_symbol **psymp,
23752                 int count,
23753                 offset_type cu_index,
23754                 int is_static)
23755 {
23756   for (; count-- > 0; ++psymp)
23757     {
23758       struct partial_symbol *psym = *psymp;
23759
23760       if (SYMBOL_LANGUAGE (psym) == language_ada)
23761         error (_("Ada is not currently supported by the index"));
23762
23763       /* Only add a given psymbol once.  */
23764       if (psyms_seen.insert (psym).second)
23765         {
23766           gdb_index_symbol_kind kind = symbol_kind (psym);
23767
23768           add_index_entry (symtab, SYMBOL_SEARCH_NAME (psym),
23769                            is_static, kind, cu_index);
23770         }
23771     }
23772 }
23773
23774 /* A helper struct used when iterating over debug_types.  */
23775 struct signatured_type_index_data
23776 {
23777   signatured_type_index_data (data_buf &types_list_,
23778                               std::unordered_set<partial_symbol *> &psyms_seen_)
23779     : types_list (types_list_), psyms_seen (psyms_seen_)
23780   {}
23781
23782   struct objfile *objfile;
23783   struct mapped_symtab *symtab;
23784   data_buf &types_list;
23785   std::unordered_set<partial_symbol *> &psyms_seen;
23786   int cu_index;
23787 };
23788
23789 /* A helper function that writes a single signatured_type to an
23790    obstack.  */
23791
23792 static int
23793 write_one_signatured_type (void **slot, void *d)
23794 {
23795   struct signatured_type_index_data *info
23796     = (struct signatured_type_index_data *) d;
23797   struct signatured_type *entry = (struct signatured_type *) *slot;
23798   struct partial_symtab *psymtab = entry->per_cu.v.psymtab;
23799
23800   write_psymbols (info->symtab,
23801                   info->psyms_seen,
23802                   info->objfile->global_psymbols.list
23803                   + psymtab->globals_offset,
23804                   psymtab->n_global_syms, info->cu_index,
23805                   0);
23806   write_psymbols (info->symtab,
23807                   info->psyms_seen,
23808                   info->objfile->static_psymbols.list
23809                   + psymtab->statics_offset,
23810                   psymtab->n_static_syms, info->cu_index,
23811                   1);
23812
23813   info->types_list.append_uint (8, BFD_ENDIAN_LITTLE,
23814                                 to_underlying (entry->per_cu.sect_off));
23815   info->types_list.append_uint (8, BFD_ENDIAN_LITTLE,
23816                                 to_underlying (entry->type_offset_in_tu));
23817   info->types_list.append_uint (8, BFD_ENDIAN_LITTLE, entry->signature);
23818
23819   ++info->cu_index;
23820
23821   return 1;
23822 }
23823
23824 /* Recurse into all "included" dependencies and count their symbols as
23825    if they appeared in this psymtab.  */
23826
23827 static void
23828 recursively_count_psymbols (struct partial_symtab *psymtab,
23829                             size_t &psyms_seen)
23830 {
23831   for (int i = 0; i < psymtab->number_of_dependencies; ++i)
23832     if (psymtab->dependencies[i]->user != NULL)
23833       recursively_count_psymbols (psymtab->dependencies[i],
23834                                   psyms_seen);
23835
23836   psyms_seen += psymtab->n_global_syms;
23837   psyms_seen += psymtab->n_static_syms;
23838 }
23839
23840 /* Recurse into all "included" dependencies and write their symbols as
23841    if they appeared in this psymtab.  */
23842
23843 static void
23844 recursively_write_psymbols (struct objfile *objfile,
23845                             struct partial_symtab *psymtab,
23846                             struct mapped_symtab *symtab,
23847                             std::unordered_set<partial_symbol *> &psyms_seen,
23848                             offset_type cu_index)
23849 {
23850   int i;
23851
23852   for (i = 0; i < psymtab->number_of_dependencies; ++i)
23853     if (psymtab->dependencies[i]->user != NULL)
23854       recursively_write_psymbols (objfile, psymtab->dependencies[i],
23855                                   symtab, psyms_seen, cu_index);
23856
23857   write_psymbols (symtab,
23858                   psyms_seen,
23859                   objfile->global_psymbols.list + psymtab->globals_offset,
23860                   psymtab->n_global_syms, cu_index,
23861                   0);
23862   write_psymbols (symtab,
23863                   psyms_seen,
23864                   objfile->static_psymbols.list + psymtab->statics_offset,
23865                   psymtab->n_static_syms, cu_index,
23866                   1);
23867 }
23868
23869 /* Create an index file for OBJFILE in the directory DIR.  */
23870
23871 static void
23872 write_psymtabs_to_index (struct objfile *objfile, const char *dir)
23873 {
23874   if (dwarf2_per_objfile->using_index)
23875     error (_("Cannot use an index to create the index"));
23876
23877   if (VEC_length (dwarf2_section_info_def, dwarf2_per_objfile->types) > 1)
23878     error (_("Cannot make an index when the file has multiple .debug_types sections"));
23879
23880   if (!objfile->psymtabs || !objfile->psymtabs_addrmap)
23881     return;
23882
23883   struct stat st;
23884   if (stat (objfile_name (objfile), &st) < 0)
23885     perror_with_name (objfile_name (objfile));
23886
23887   std::string filename (std::string (dir) + SLASH_STRING
23888                         + lbasename (objfile_name (objfile)) + INDEX_SUFFIX);
23889
23890   FILE *out_file = gdb_fopen_cloexec (filename.c_str (), "wb").release ();
23891   if (!out_file)
23892     error (_("Can't open `%s' for writing"), filename.c_str ());
23893
23894   /* Order matters here; we want FILE to be closed before FILENAME is
23895      unlinked, because on MS-Windows one cannot delete a file that is
23896      still open.  (Don't call anything here that might throw until
23897      file_closer is created.)  */
23898   gdb::unlinker unlink_file (filename.c_str ());
23899   gdb_file_up close_out_file (out_file);
23900
23901   mapped_symtab symtab;
23902   data_buf cu_list;
23903
23904   /* While we're scanning CU's create a table that maps a psymtab pointer
23905      (which is what addrmap records) to its index (which is what is recorded
23906      in the index file).  This will later be needed to write the address
23907      table.  */
23908   psym_index_map cu_index_htab;
23909   cu_index_htab.reserve (dwarf2_per_objfile->n_comp_units);
23910
23911   /* The CU list is already sorted, so we don't need to do additional
23912      work here.  Also, the debug_types entries do not appear in
23913      all_comp_units, but only in their own hash table.  */
23914
23915   /* The psyms_seen set is potentially going to be largish (~40k
23916      elements when indexing a -g3 build of GDB itself).  Estimate the
23917      number of elements in order to avoid too many rehashes, which
23918      require rebuilding buckets and thus many trips to
23919      malloc/free.  */
23920   size_t psyms_count = 0;
23921   for (int i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
23922     {
23923       struct dwarf2_per_cu_data *per_cu
23924         = dwarf2_per_objfile->all_comp_units[i];
23925       struct partial_symtab *psymtab = per_cu->v.psymtab;
23926
23927       if (psymtab != NULL && psymtab->user == NULL)
23928         recursively_count_psymbols (psymtab, psyms_count);
23929     }
23930   /* Generating an index for gdb itself shows a ratio of
23931      TOTAL_SEEN_SYMS/UNIQUE_SYMS or ~5.  4 seems like a good bet.  */
23932   std::unordered_set<partial_symbol *> psyms_seen (psyms_count / 4);
23933   for (int i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
23934     {
23935       struct dwarf2_per_cu_data *per_cu
23936         = dwarf2_per_objfile->all_comp_units[i];
23937       struct partial_symtab *psymtab = per_cu->v.psymtab;
23938
23939       /* CU of a shared file from 'dwz -m' may be unused by this main file.
23940          It may be referenced from a local scope but in such case it does not
23941          need to be present in .gdb_index.  */
23942       if (psymtab == NULL)
23943         continue;
23944
23945       if (psymtab->user == NULL)
23946         recursively_write_psymbols (objfile, psymtab, &symtab,
23947                                     psyms_seen, i);
23948
23949       const auto insertpair = cu_index_htab.emplace (psymtab, i);
23950       gdb_assert (insertpair.second);
23951
23952       cu_list.append_uint (8, BFD_ENDIAN_LITTLE,
23953                            to_underlying (per_cu->sect_off));
23954       cu_list.append_uint (8, BFD_ENDIAN_LITTLE, per_cu->length);
23955     }
23956
23957   /* Dump the address map.  */
23958   data_buf addr_vec;
23959   write_address_map (objfile, addr_vec, cu_index_htab);
23960
23961   /* Write out the .debug_type entries, if any.  */
23962   data_buf types_cu_list;
23963   if (dwarf2_per_objfile->signatured_types)
23964     {
23965       signatured_type_index_data sig_data (types_cu_list,
23966                                            psyms_seen);
23967
23968       sig_data.objfile = objfile;
23969       sig_data.symtab = &symtab;
23970       sig_data.cu_index = dwarf2_per_objfile->n_comp_units;
23971       htab_traverse_noresize (dwarf2_per_objfile->signatured_types,
23972                               write_one_signatured_type, &sig_data);
23973     }
23974
23975   /* Now that we've processed all symbols we can shrink their cu_indices
23976      lists.  */
23977   uniquify_cu_indices (&symtab);
23978
23979   data_buf symtab_vec, constant_pool;
23980   write_hash_table (&symtab, symtab_vec, constant_pool);
23981
23982   data_buf contents;
23983   const offset_type size_of_contents = 6 * sizeof (offset_type);
23984   offset_type total_len = size_of_contents;
23985
23986   /* The version number.  */
23987   contents.append_data (MAYBE_SWAP (8));
23988
23989   /* The offset of the CU list from the start of the file.  */
23990   contents.append_data (MAYBE_SWAP (total_len));
23991   total_len += cu_list.size ();
23992
23993   /* The offset of the types CU list from the start of the file.  */
23994   contents.append_data (MAYBE_SWAP (total_len));
23995   total_len += types_cu_list.size ();
23996
23997   /* The offset of the address table from the start of the file.  */
23998   contents.append_data (MAYBE_SWAP (total_len));
23999   total_len += addr_vec.size ();
24000
24001   /* The offset of the symbol table from the start of the file.  */
24002   contents.append_data (MAYBE_SWAP (total_len));
24003   total_len += symtab_vec.size ();
24004
24005   /* The offset of the constant pool from the start of the file.  */
24006   contents.append_data (MAYBE_SWAP (total_len));
24007   total_len += constant_pool.size ();
24008
24009   gdb_assert (contents.size () == size_of_contents);
24010
24011   contents.file_write (out_file);
24012   cu_list.file_write (out_file);
24013   types_cu_list.file_write (out_file);
24014   addr_vec.file_write (out_file);
24015   symtab_vec.file_write (out_file);
24016   constant_pool.file_write (out_file);
24017
24018   /* We want to keep the file.  */
24019   unlink_file.keep ();
24020 }
24021
24022 /* Implementation of the `save gdb-index' command.
24023    
24024    Note that the file format used by this command is documented in the
24025    GDB manual.  Any changes here must be documented there.  */
24026
24027 static void
24028 save_gdb_index_command (char *arg, int from_tty)
24029 {
24030   struct objfile *objfile;
24031
24032   if (!arg || !*arg)
24033     error (_("usage: save gdb-index DIRECTORY"));
24034
24035   ALL_OBJFILES (objfile)
24036   {
24037     struct stat st;
24038
24039     /* If the objfile does not correspond to an actual file, skip it.  */
24040     if (stat (objfile_name (objfile), &st) < 0)
24041       continue;
24042
24043     dwarf2_per_objfile
24044       = (struct dwarf2_per_objfile *) objfile_data (objfile,
24045                                                     dwarf2_objfile_data_key);
24046     if (dwarf2_per_objfile)
24047       {
24048
24049         TRY
24050           {
24051             write_psymtabs_to_index (objfile, arg);
24052           }
24053         CATCH (except, RETURN_MASK_ERROR)
24054           {
24055             exception_fprintf (gdb_stderr, except,
24056                                _("Error while writing index for `%s': "),
24057                                objfile_name (objfile));
24058           }
24059         END_CATCH
24060       }
24061   }
24062 }
24063
24064 \f
24065
24066 int dwarf_always_disassemble;
24067
24068 static void
24069 show_dwarf_always_disassemble (struct ui_file *file, int from_tty,
24070                                struct cmd_list_element *c, const char *value)
24071 {
24072   fprintf_filtered (file,
24073                     _("Whether to always disassemble "
24074                       "DWARF expressions is %s.\n"),
24075                     value);
24076 }
24077
24078 static void
24079 show_check_physname (struct ui_file *file, int from_tty,
24080                      struct cmd_list_element *c, const char *value)
24081 {
24082   fprintf_filtered (file,
24083                     _("Whether to check \"physname\" is %s.\n"),
24084                     value);
24085 }
24086
24087 void
24088 _initialize_dwarf2_read (void)
24089 {
24090   struct cmd_list_element *c;
24091
24092   dwarf2_objfile_data_key
24093     = register_objfile_data_with_cleanup (NULL, dwarf2_per_objfile_free);
24094
24095   add_prefix_cmd ("dwarf", class_maintenance, set_dwarf_cmd, _("\
24096 Set DWARF specific variables.\n\
24097 Configure DWARF variables such as the cache size"),
24098                   &set_dwarf_cmdlist, "maintenance set dwarf ",
24099                   0/*allow-unknown*/, &maintenance_set_cmdlist);
24100
24101   add_prefix_cmd ("dwarf", class_maintenance, show_dwarf_cmd, _("\
24102 Show DWARF specific variables\n\
24103 Show DWARF variables such as the cache size"),
24104                   &show_dwarf_cmdlist, "maintenance show dwarf ",
24105                   0/*allow-unknown*/, &maintenance_show_cmdlist);
24106
24107   add_setshow_zinteger_cmd ("max-cache-age", class_obscure,
24108                             &dwarf_max_cache_age, _("\
24109 Set the upper bound on the age of cached DWARF compilation units."), _("\
24110 Show the upper bound on the age of cached DWARF compilation units."), _("\
24111 A higher limit means that cached compilation units will be stored\n\
24112 in memory longer, and more total memory will be used.  Zero disables\n\
24113 caching, which can slow down startup."),
24114                             NULL,
24115                             show_dwarf_max_cache_age,
24116                             &set_dwarf_cmdlist,
24117                             &show_dwarf_cmdlist);
24118
24119   add_setshow_boolean_cmd ("always-disassemble", class_obscure,
24120                            &dwarf_always_disassemble, _("\
24121 Set whether `info address' always disassembles DWARF expressions."), _("\
24122 Show whether `info address' always disassembles DWARF expressions."), _("\
24123 When enabled, DWARF expressions are always printed in an assembly-like\n\
24124 syntax.  When disabled, expressions will be printed in a more\n\
24125 conversational style, when possible."),
24126                            NULL,
24127                            show_dwarf_always_disassemble,
24128                            &set_dwarf_cmdlist,
24129                            &show_dwarf_cmdlist);
24130
24131   add_setshow_zuinteger_cmd ("dwarf-read", no_class, &dwarf_read_debug, _("\
24132 Set debugging of the DWARF reader."), _("\
24133 Show debugging of the DWARF reader."), _("\
24134 When enabled (non-zero), debugging messages are printed during DWARF\n\
24135 reading and symtab expansion.  A value of 1 (one) provides basic\n\
24136 information.  A value greater than 1 provides more verbose information."),
24137                             NULL,
24138                             NULL,
24139                             &setdebuglist, &showdebuglist);
24140
24141   add_setshow_zuinteger_cmd ("dwarf-die", no_class, &dwarf_die_debug, _("\
24142 Set debugging of the DWARF DIE reader."), _("\
24143 Show debugging of the DWARF DIE reader."), _("\
24144 When enabled (non-zero), DIEs are dumped after they are read in.\n\
24145 The value is the maximum depth to print."),
24146                              NULL,
24147                              NULL,
24148                              &setdebuglist, &showdebuglist);
24149
24150   add_setshow_zuinteger_cmd ("dwarf-line", no_class, &dwarf_line_debug, _("\
24151 Set debugging of the dwarf line reader."), _("\
24152 Show debugging of the dwarf line reader."), _("\
24153 When enabled (non-zero), line number entries are dumped as they are read in.\n\
24154 A value of 1 (one) provides basic information.\n\
24155 A value greater than 1 provides more verbose information."),
24156                              NULL,
24157                              NULL,
24158                              &setdebuglist, &showdebuglist);
24159
24160   add_setshow_boolean_cmd ("check-physname", no_class, &check_physname, _("\
24161 Set cross-checking of \"physname\" code against demangler."), _("\
24162 Show cross-checking of \"physname\" code against demangler."), _("\
24163 When enabled, GDB's internal \"physname\" code is checked against\n\
24164 the demangler."),
24165                            NULL, show_check_physname,
24166                            &setdebuglist, &showdebuglist);
24167
24168   add_setshow_boolean_cmd ("use-deprecated-index-sections",
24169                            no_class, &use_deprecated_index_sections, _("\
24170 Set whether to use deprecated gdb_index sections."), _("\
24171 Show whether to use deprecated gdb_index sections."), _("\
24172 When enabled, deprecated .gdb_index sections are used anyway.\n\
24173 Normally they are ignored either because of a missing feature or\n\
24174 performance issue.\n\
24175 Warning: This option must be enabled before gdb reads the file."),
24176                            NULL,
24177                            NULL,
24178                            &setlist, &showlist);
24179
24180   c = add_cmd ("gdb-index", class_files, save_gdb_index_command,
24181                _("\
24182 Save a gdb-index file.\n\
24183 Usage: save gdb-index DIRECTORY"),
24184                &save_cmdlist);
24185   set_cmd_completer (c, filename_completer);
24186
24187   dwarf2_locexpr_index = register_symbol_computed_impl (LOC_COMPUTED,
24188                                                         &dwarf2_locexpr_funcs);
24189   dwarf2_loclist_index = register_symbol_computed_impl (LOC_COMPUTED,
24190                                                         &dwarf2_loclist_funcs);
24191
24192   dwarf2_locexpr_block_index = register_symbol_block_impl (LOC_BLOCK,
24193                                         &dwarf2_block_frame_base_locexpr_funcs);
24194   dwarf2_loclist_block_index = register_symbol_block_impl (LOC_BLOCK,
24195                                         &dwarf2_block_frame_base_loclist_funcs);
24196 }