C++ify dwarf2_per_objfile
[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
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.  */
236   dwarf2_per_objfile (const dwarf2_per_objfile &) = delete;
237   void operator= (const dwarf2_per_objfile &) = delete;
238
239   /* Free all cached compilation units.  */
240   void free_cached_comp_units ();
241 private:
242   /* This function is mapped across the sections and remembers the
243      offset and size of each of the debugging sections we are
244      interested in.  */
245   void locate_sections (bfd *abfd, asection *sectp,
246                         const dwarf2_debug_sections &names);
247
248 public:
249   dwarf2_section_info info {};
250   dwarf2_section_info abbrev {};
251   dwarf2_section_info line {};
252   dwarf2_section_info loc {};
253   dwarf2_section_info loclists {};
254   dwarf2_section_info macinfo {};
255   dwarf2_section_info macro {};
256   dwarf2_section_info str {};
257   dwarf2_section_info line_str {};
258   dwarf2_section_info ranges {};
259   dwarf2_section_info rnglists {};
260   dwarf2_section_info addr {};
261   dwarf2_section_info frame {};
262   dwarf2_section_info eh_frame {};
263   dwarf2_section_info gdb_index {};
264
265   VEC (dwarf2_section_info_def) *types = NULL;
266
267   /* Back link.  */
268   struct objfile *objfile = NULL;
269
270   /* Table of all the compilation units.  This is used to locate
271      the target compilation unit of a particular reference.  */
272   struct dwarf2_per_cu_data **all_comp_units = NULL;
273
274   /* The number of compilation units in ALL_COMP_UNITS.  */
275   int n_comp_units = 0;
276
277   /* The number of .debug_types-related CUs.  */
278   int n_type_units = 0;
279
280   /* The number of elements allocated in all_type_units.
281      If there are skeleton-less TUs, we add them to all_type_units lazily.  */
282   int n_allocated_type_units = 0;
283
284   /* The .debug_types-related CUs (TUs).
285      This is stored in malloc space because we may realloc it.  */
286   struct signatured_type **all_type_units = NULL;
287
288   /* Table of struct type_unit_group objects.
289      The hash key is the DW_AT_stmt_list value.  */
290   htab_t type_unit_groups {};
291
292   /* A table mapping .debug_types signatures to its signatured_type entry.
293      This is NULL if the .debug_types section hasn't been read in yet.  */
294   htab_t signatured_types {};
295
296   /* Type unit statistics, to see how well the scaling improvements
297      are doing.  */
298   struct tu_stats tu_stats {};
299
300   /* A chain of compilation units that are currently read in, so that
301      they can be freed later.  */
302   dwarf2_per_cu_data *read_in_chain = NULL;
303
304   /* A table mapping DW_AT_dwo_name values to struct dwo_file objects.
305      This is NULL if the table hasn't been allocated yet.  */
306   htab_t dwo_files {};
307
308   /* True if we've checked for whether there is a DWP file.  */
309   bool dwp_checked = false;
310
311   /* The DWP file if there is one, or NULL.  */
312   struct dwp_file *dwp_file = NULL;
313
314   /* The shared '.dwz' file, if one exists.  This is used when the
315      original data was compressed using 'dwz -m'.  */
316   struct dwz_file *dwz_file = NULL;
317
318   /* A flag indicating whether this objfile has a section loaded at a
319      VMA of 0.  */
320   bool has_section_at_zero = false;
321
322   /* True if we are using the mapped index,
323      or we are faking it for OBJF_READNOW's sake.  */
324   bool using_index = false;
325
326   /* The mapped index, or NULL if .gdb_index is missing or not being used.  */
327   mapped_index *index_table = NULL;
328
329   /* When using index_table, this keeps track of all quick_file_names entries.
330      TUs typically share line table entries with a CU, so we maintain a
331      separate table of all line table entries to support the sharing.
332      Note that while there can be way more TUs than CUs, we've already
333      sorted all the TUs into "type unit groups", grouped by their
334      DW_AT_stmt_list value.  Therefore the only sharing done here is with a
335      CU and its associated TU group if there is one.  */
336   htab_t quick_file_names_table {};
337
338   /* Set during partial symbol reading, to prevent queueing of full
339      symbols.  */
340   bool reading_partial_symbols = false;
341
342   /* Table mapping type DIEs to their struct type *.
343      This is NULL if not allocated yet.
344      The mapping is done via (CU/TU + DIE offset) -> type.  */
345   htab_t die_type_hash {};
346
347   /* The CUs we recently read.  */
348   VEC (dwarf2_per_cu_ptr) *just_read_cus = NULL;
349
350   /* Table containing line_header indexed by offset and offset_in_dwz.  */
351   htab_t line_header_hash {};
352 };
353
354 static struct dwarf2_per_objfile *dwarf2_per_objfile;
355
356 /* Default names of the debugging sections.  */
357
358 /* Note that if the debugging section has been compressed, it might
359    have a name like .zdebug_info.  */
360
361 static const struct dwarf2_debug_sections dwarf2_elf_names =
362 {
363   { ".debug_info", ".zdebug_info" },
364   { ".debug_abbrev", ".zdebug_abbrev" },
365   { ".debug_line", ".zdebug_line" },
366   { ".debug_loc", ".zdebug_loc" },
367   { ".debug_loclists", ".zdebug_loclists" },
368   { ".debug_macinfo", ".zdebug_macinfo" },
369   { ".debug_macro", ".zdebug_macro" },
370   { ".debug_str", ".zdebug_str" },
371   { ".debug_line_str", ".zdebug_line_str" },
372   { ".debug_ranges", ".zdebug_ranges" },
373   { ".debug_rnglists", ".zdebug_rnglists" },
374   { ".debug_types", ".zdebug_types" },
375   { ".debug_addr", ".zdebug_addr" },
376   { ".debug_frame", ".zdebug_frame" },
377   { ".eh_frame", NULL },
378   { ".gdb_index", ".zgdb_index" },
379   23
380 };
381
382 /* List of DWO/DWP sections.  */
383
384 static const struct dwop_section_names
385 {
386   struct dwarf2_section_names abbrev_dwo;
387   struct dwarf2_section_names info_dwo;
388   struct dwarf2_section_names line_dwo;
389   struct dwarf2_section_names loc_dwo;
390   struct dwarf2_section_names loclists_dwo;
391   struct dwarf2_section_names macinfo_dwo;
392   struct dwarf2_section_names macro_dwo;
393   struct dwarf2_section_names str_dwo;
394   struct dwarf2_section_names str_offsets_dwo;
395   struct dwarf2_section_names types_dwo;
396   struct dwarf2_section_names cu_index;
397   struct dwarf2_section_names tu_index;
398 }
399 dwop_section_names =
400 {
401   { ".debug_abbrev.dwo", ".zdebug_abbrev.dwo" },
402   { ".debug_info.dwo", ".zdebug_info.dwo" },
403   { ".debug_line.dwo", ".zdebug_line.dwo" },
404   { ".debug_loc.dwo", ".zdebug_loc.dwo" },
405   { ".debug_loclists.dwo", ".zdebug_loclists.dwo" },
406   { ".debug_macinfo.dwo", ".zdebug_macinfo.dwo" },
407   { ".debug_macro.dwo", ".zdebug_macro.dwo" },
408   { ".debug_str.dwo", ".zdebug_str.dwo" },
409   { ".debug_str_offsets.dwo", ".zdebug_str_offsets.dwo" },
410   { ".debug_types.dwo", ".zdebug_types.dwo" },
411   { ".debug_cu_index", ".zdebug_cu_index" },
412   { ".debug_tu_index", ".zdebug_tu_index" },
413 };
414
415 /* local data types */
416
417 /* The data in a compilation unit header, after target2host
418    translation, looks like this.  */
419 struct comp_unit_head
420 {
421   unsigned int length;
422   short version;
423   unsigned char addr_size;
424   unsigned char signed_addr_p;
425   sect_offset abbrev_sect_off;
426
427   /* Size of file offsets; either 4 or 8.  */
428   unsigned int offset_size;
429
430   /* Size of the length field; either 4 or 12.  */
431   unsigned int initial_length_size;
432
433   enum dwarf_unit_type unit_type;
434
435   /* Offset to the first byte of this compilation unit header in the
436      .debug_info section, for resolving relative reference dies.  */
437   sect_offset sect_off;
438
439   /* Offset to first die in this cu from the start of the cu.
440      This will be the first byte following the compilation unit header.  */
441   cu_offset first_die_cu_offset;
442
443   /* 64-bit signature of this type unit - it is valid only for
444      UNIT_TYPE DW_UT_type.  */
445   ULONGEST signature;
446
447   /* For types, offset in the type's DIE of the type defined by this TU.  */
448   cu_offset type_cu_offset_in_tu;
449 };
450
451 /* Type used for delaying computation of method physnames.
452    See comments for compute_delayed_physnames.  */
453 struct delayed_method_info
454 {
455   /* The type to which the method is attached, i.e., its parent class.  */
456   struct type *type;
457
458   /* The index of the method in the type's function fieldlists.  */
459   int fnfield_index;
460
461   /* The index of the method in the fieldlist.  */
462   int index;
463
464   /* The name of the DIE.  */
465   const char *name;
466
467   /*  The DIE associated with this method.  */
468   struct die_info *die;
469 };
470
471 typedef struct delayed_method_info delayed_method_info;
472 DEF_VEC_O (delayed_method_info);
473
474 /* Internal state when decoding a particular compilation unit.  */
475 struct dwarf2_cu
476 {
477   /* The objfile containing this compilation unit.  */
478   struct objfile *objfile;
479
480   /* The header of the compilation unit.  */
481   struct comp_unit_head header;
482
483   /* Base address of this compilation unit.  */
484   CORE_ADDR base_address;
485
486   /* Non-zero if base_address has been set.  */
487   int base_known;
488
489   /* The language we are debugging.  */
490   enum language language;
491   const struct language_defn *language_defn;
492
493   const char *producer;
494
495   /* The generic symbol table building routines have separate lists for
496      file scope symbols and all all other scopes (local scopes).  So
497      we need to select the right one to pass to add_symbol_to_list().
498      We do it by keeping a pointer to the correct list in list_in_scope.
499
500      FIXME: The original dwarf code just treated the file scope as the
501      first local scope, and all other local scopes as nested local
502      scopes, and worked fine.  Check to see if we really need to
503      distinguish these in buildsym.c.  */
504   struct pending **list_in_scope;
505
506   /* The abbrev table for this CU.
507      Normally this points to the abbrev table in the objfile.
508      But if DWO_UNIT is non-NULL this is the abbrev table in the DWO file.  */
509   struct abbrev_table *abbrev_table;
510
511   /* Hash table holding all the loaded partial DIEs
512      with partial_die->offset.SECT_OFF as hash.  */
513   htab_t partial_dies;
514
515   /* Storage for things with the same lifetime as this read-in compilation
516      unit, including partial DIEs.  */
517   struct obstack comp_unit_obstack;
518
519   /* When multiple dwarf2_cu structures are living in memory, this field
520      chains them all together, so that they can be released efficiently.
521      We will probably also want a generation counter so that most-recently-used
522      compilation units are cached...  */
523   struct dwarf2_per_cu_data *read_in_chain;
524
525   /* Backlink to our per_cu entry.  */
526   struct dwarf2_per_cu_data *per_cu;
527
528   /* How many compilation units ago was this CU last referenced?  */
529   int last_used;
530
531   /* A hash table of DIE cu_offset for following references with
532      die_info->offset.sect_off as hash.  */
533   htab_t die_hash;
534
535   /* Full DIEs if read in.  */
536   struct die_info *dies;
537
538   /* A set of pointers to dwarf2_per_cu_data objects for compilation
539      units referenced by this one.  Only set during full symbol processing;
540      partial symbol tables do not have dependencies.  */
541   htab_t dependencies;
542
543   /* Header data from the line table, during full symbol processing.  */
544   struct line_header *line_header;
545
546   /* A list of methods which need to have physnames computed
547      after all type information has been read.  */
548   VEC (delayed_method_info) *method_list;
549
550   /* To be copied to symtab->call_site_htab.  */
551   htab_t call_site_htab;
552
553   /* Non-NULL if this CU came from a DWO file.
554      There is an invariant here that is important to remember:
555      Except for attributes copied from the top level DIE in the "main"
556      (or "stub") file in preparation for reading the DWO file
557      (e.g., DW_AT_GNU_addr_base), we KISS: there is only *one* CU.
558      Either there isn't a DWO file (in which case this is NULL and the point
559      is moot), or there is and either we're not going to read it (in which
560      case this is NULL) or there is and we are reading it (in which case this
561      is non-NULL).  */
562   struct dwo_unit *dwo_unit;
563
564   /* The DW_AT_addr_base attribute if present, zero otherwise
565      (zero is a valid value though).
566      Note this value comes from the Fission stub CU/TU's DIE.  */
567   ULONGEST addr_base;
568
569   /* The DW_AT_ranges_base attribute if present, zero otherwise
570      (zero is a valid value though).
571      Note this value comes from the Fission stub CU/TU's DIE.
572      Also note that the value is zero in the non-DWO case so this value can
573      be used without needing to know whether DWO files are in use or not.
574      N.B. This does not apply to DW_AT_ranges appearing in
575      DW_TAG_compile_unit dies.  This is a bit of a wart, consider if ever
576      DW_AT_ranges appeared in the DW_TAG_compile_unit of DWO DIEs: then
577      DW_AT_ranges_base *would* have to be applied, and we'd have to care
578      whether the DW_AT_ranges attribute came from the skeleton or DWO.  */
579   ULONGEST ranges_base;
580
581   /* Mark used when releasing cached dies.  */
582   unsigned int mark : 1;
583
584   /* This CU references .debug_loc.  See the symtab->locations_valid field.
585      This test is imperfect as there may exist optimized debug code not using
586      any location list and still facing inlining issues if handled as
587      unoptimized code.  For a future better test see GCC PR other/32998.  */
588   unsigned int has_loclist : 1;
589
590   /* These cache the results for producer_is_* fields.  CHECKED_PRODUCER is set
591      if all the producer_is_* fields are valid.  This information is cached
592      because profiling CU expansion showed excessive time spent in
593      producer_is_gxx_lt_4_6.  */
594   unsigned int checked_producer : 1;
595   unsigned int producer_is_gxx_lt_4_6 : 1;
596   unsigned int producer_is_gcc_lt_4_3 : 1;
597   unsigned int producer_is_icc : 1;
598
599   /* When set, the file that we're processing is known to have
600      debugging info for C++ namespaces.  GCC 3.3.x did not produce
601      this information, but later versions do.  */
602
603   unsigned int processing_has_namespace_info : 1;
604 };
605
606 /* Persistent data held for a compilation unit, even when not
607    processing it.  We put a pointer to this structure in the
608    read_symtab_private field of the psymtab.  */
609
610 struct dwarf2_per_cu_data
611 {
612   /* The start offset and length of this compilation unit.
613      NOTE: Unlike comp_unit_head.length, this length includes
614      initial_length_size.
615      If the DIE refers to a DWO file, this is always of the original die,
616      not the DWO file.  */
617   sect_offset sect_off;
618   unsigned int length;
619
620   /* DWARF standard version this data has been read from (such as 4 or 5).  */
621   short dwarf_version;
622
623   /* Flag indicating this compilation unit will be read in before
624      any of the current compilation units are processed.  */
625   unsigned int queued : 1;
626
627   /* This flag will be set when reading partial DIEs if we need to load
628      absolutely all DIEs for this compilation unit, instead of just the ones
629      we think are interesting.  It gets set if we look for a DIE in the
630      hash table and don't find it.  */
631   unsigned int load_all_dies : 1;
632
633   /* Non-zero if this CU is from .debug_types.
634      Struct dwarf2_per_cu_data is contained in struct signatured_type iff
635      this is non-zero.  */
636   unsigned int is_debug_types : 1;
637
638   /* Non-zero if this CU is from the .dwz file.  */
639   unsigned int is_dwz : 1;
640
641   /* Non-zero if reading a TU directly from a DWO file, bypassing the stub.
642      This flag is only valid if is_debug_types is true.
643      We can't read a CU directly from a DWO file: There are required
644      attributes in the stub.  */
645   unsigned int reading_dwo_directly : 1;
646
647   /* Non-zero if the TU has been read.
648      This is used to assist the "Stay in DWO Optimization" for Fission:
649      When reading a DWO, it's faster to read TUs from the DWO instead of
650      fetching them from random other DWOs (due to comdat folding).
651      If the TU has already been read, the optimization is unnecessary
652      (and unwise - we don't want to change where gdb thinks the TU lives
653      "midflight").
654      This flag is only valid if is_debug_types is true.  */
655   unsigned int tu_read : 1;
656
657   /* The section this CU/TU lives in.
658      If the DIE refers to a DWO file, this is always the original die,
659      not the DWO file.  */
660   struct dwarf2_section_info *section;
661
662   /* Set to non-NULL iff this CU is currently loaded.  When it gets freed out
663      of the CU cache it gets reset to NULL again.  This is left as NULL for
664      dummy CUs (a CU header, but nothing else).  */
665   struct dwarf2_cu *cu;
666
667   /* The corresponding objfile.
668      Normally we can get the objfile from dwarf2_per_objfile.
669      However we can enter this file with just a "per_cu" handle.  */
670   struct objfile *objfile;
671
672   /* When dwarf2_per_objfile->using_index is true, the 'quick' field
673      is active.  Otherwise, the 'psymtab' field is active.  */
674   union
675   {
676     /* The partial symbol table associated with this compilation unit,
677        or NULL for unread partial units.  */
678     struct partial_symtab *psymtab;
679
680     /* Data needed by the "quick" functions.  */
681     struct dwarf2_per_cu_quick_data *quick;
682   } v;
683
684   /* The CUs we import using DW_TAG_imported_unit.  This is filled in
685      while reading psymtabs, used to compute the psymtab dependencies,
686      and then cleared.  Then it is filled in again while reading full
687      symbols, and only deleted when the objfile is destroyed.
688
689      This is also used to work around a difference between the way gold
690      generates .gdb_index version <=7 and the way gdb does.  Arguably this
691      is a gold bug.  For symbols coming from TUs, gold records in the index
692      the CU that includes the TU instead of the TU itself.  This breaks
693      dw2_lookup_symbol: It assumes that if the index says symbol X lives
694      in CU/TU Y, then one need only expand Y and a subsequent lookup in Y
695      will find X.  Alas TUs live in their own symtab, so after expanding CU Y
696      we need to look in TU Z to find X.  Fortunately, this is akin to
697      DW_TAG_imported_unit, so we just use the same mechanism: For
698      .gdb_index version <=7 this also records the TUs that the CU referred
699      to.  Concurrently with this change gdb was modified to emit version 8
700      indices so we only pay a price for gold generated indices.
701      http://sourceware.org/bugzilla/show_bug.cgi?id=15021.  */
702   VEC (dwarf2_per_cu_ptr) *imported_symtabs;
703 };
704
705 /* Entry in the signatured_types hash table.  */
706
707 struct signatured_type
708 {
709   /* The "per_cu" object of this type.
710      This struct is used iff per_cu.is_debug_types.
711      N.B.: This is the first member so that it's easy to convert pointers
712      between them.  */
713   struct dwarf2_per_cu_data per_cu;
714
715   /* The type's signature.  */
716   ULONGEST signature;
717
718   /* Offset in the TU of the type's DIE, as read from the TU header.
719      If this TU is a DWO stub and the definition lives in a DWO file
720      (specified by DW_AT_GNU_dwo_name), this value is unusable.  */
721   cu_offset type_offset_in_tu;
722
723   /* Offset in the section of the type's DIE.
724      If the definition lives in a DWO file, this is the offset in the
725      .debug_types.dwo section.
726      The value is zero until the actual value is known.
727      Zero is otherwise not a valid section offset.  */
728   sect_offset type_offset_in_section;
729
730   /* Type units are grouped by their DW_AT_stmt_list entry so that they
731      can share them.  This points to the containing symtab.  */
732   struct type_unit_group *type_unit_group;
733
734   /* The type.
735      The first time we encounter this type we fully read it in and install it
736      in the symbol tables.  Subsequent times we only need the type.  */
737   struct type *type;
738
739   /* Containing DWO unit.
740      This field is valid iff per_cu.reading_dwo_directly.  */
741   struct dwo_unit *dwo_unit;
742 };
743
744 typedef struct signatured_type *sig_type_ptr;
745 DEF_VEC_P (sig_type_ptr);
746
747 /* A struct that can be used as a hash key for tables based on DW_AT_stmt_list.
748    This includes type_unit_group and quick_file_names.  */
749
750 struct stmt_list_hash
751 {
752   /* The DWO unit this table is from or NULL if there is none.  */
753   struct dwo_unit *dwo_unit;
754
755   /* Offset in .debug_line or .debug_line.dwo.  */
756   sect_offset line_sect_off;
757 };
758
759 /* Each element of dwarf2_per_objfile->type_unit_groups is a pointer to
760    an object of this type.  */
761
762 struct type_unit_group
763 {
764   /* dwarf2read.c's main "handle" on a TU symtab.
765      To simplify things we create an artificial CU that "includes" all the
766      type units using this stmt_list so that the rest of the code still has
767      a "per_cu" handle on the symtab.
768      This PER_CU is recognized by having no section.  */
769 #define IS_TYPE_UNIT_GROUP(per_cu) ((per_cu)->section == NULL)
770   struct dwarf2_per_cu_data per_cu;
771
772   /* The TUs that share this DW_AT_stmt_list entry.
773      This is added to while parsing type units to build partial symtabs,
774      and is deleted afterwards and not used again.  */
775   VEC (sig_type_ptr) *tus;
776
777   /* The compunit symtab.
778      Type units in a group needn't all be defined in the same source file,
779      so we create an essentially anonymous symtab as the compunit symtab.  */
780   struct compunit_symtab *compunit_symtab;
781
782   /* The data used to construct the hash key.  */
783   struct stmt_list_hash hash;
784
785   /* The number of symtabs from the line header.
786      The value here must match line_header.num_file_names.  */
787   unsigned int num_symtabs;
788
789   /* The symbol tables for this TU (obtained from the files listed in
790      DW_AT_stmt_list).
791      WARNING: The order of entries here must match the order of entries
792      in the line header.  After the first TU using this type_unit_group, the
793      line header for the subsequent TUs is recreated from this.  This is done
794      because we need to use the same symtabs for each TU using the same
795      DW_AT_stmt_list value.  Also note that symtabs may be repeated here,
796      there's no guarantee the line header doesn't have duplicate entries.  */
797   struct symtab **symtabs;
798 };
799
800 /* These sections are what may appear in a (real or virtual) DWO file.  */
801
802 struct dwo_sections
803 {
804   struct dwarf2_section_info abbrev;
805   struct dwarf2_section_info line;
806   struct dwarf2_section_info loc;
807   struct dwarf2_section_info loclists;
808   struct dwarf2_section_info macinfo;
809   struct dwarf2_section_info macro;
810   struct dwarf2_section_info str;
811   struct dwarf2_section_info str_offsets;
812   /* In the case of a virtual DWO file, these two are unused.  */
813   struct dwarf2_section_info info;
814   VEC (dwarf2_section_info_def) *types;
815 };
816
817 /* CUs/TUs in DWP/DWO files.  */
818
819 struct dwo_unit
820 {
821   /* Backlink to the containing struct dwo_file.  */
822   struct dwo_file *dwo_file;
823
824   /* The "id" that distinguishes this CU/TU.
825      .debug_info calls this "dwo_id", .debug_types calls this "signature".
826      Since signatures came first, we stick with it for consistency.  */
827   ULONGEST signature;
828
829   /* The section this CU/TU lives in, in the DWO file.  */
830   struct dwarf2_section_info *section;
831
832   /* Same as dwarf2_per_cu_data:{sect_off,length} but in the DWO section.  */
833   sect_offset sect_off;
834   unsigned int length;
835
836   /* For types, offset in the type's DIE of the type defined by this TU.  */
837   cu_offset type_offset_in_tu;
838 };
839
840 /* include/dwarf2.h defines the DWP section codes.
841    It defines a max value but it doesn't define a min value, which we
842    use for error checking, so provide one.  */
843
844 enum dwp_v2_section_ids
845 {
846   DW_SECT_MIN = 1
847 };
848
849 /* Data for one DWO file.
850
851    This includes virtual DWO files (a virtual DWO file is a DWO file as it
852    appears in a DWP file).  DWP files don't really have DWO files per se -
853    comdat folding of types "loses" the DWO file they came from, and from
854    a high level view DWP files appear to contain a mass of random types.
855    However, to maintain consistency with the non-DWP case we pretend DWP
856    files contain virtual DWO files, and we assign each TU with one virtual
857    DWO file (generally based on the line and abbrev section offsets -
858    a heuristic that seems to work in practice).  */
859
860 struct dwo_file
861 {
862   /* The DW_AT_GNU_dwo_name attribute.
863      For virtual DWO files the name is constructed from the section offsets
864      of abbrev,line,loc,str_offsets so that we combine virtual DWO files
865      from related CU+TUs.  */
866   const char *dwo_name;
867
868   /* The DW_AT_comp_dir attribute.  */
869   const char *comp_dir;
870
871   /* The bfd, when the file is open.  Otherwise this is NULL.
872      This is unused(NULL) for virtual DWO files where we use dwp_file.dbfd.  */
873   bfd *dbfd;
874
875   /* The sections that make up this DWO file.
876      Remember that for virtual DWO files in DWP V2, these are virtual
877      sections (for lack of a better name).  */
878   struct dwo_sections sections;
879
880   /* The CUs in the file.
881      Each element is a struct dwo_unit. Multiple CUs per DWO are supported as
882      an extension to handle LLVM's Link Time Optimization output (where
883      multiple source files may be compiled into a single object/dwo pair). */
884   htab_t cus;
885
886   /* Table of TUs in the file.
887      Each element is a struct dwo_unit.  */
888   htab_t tus;
889 };
890
891 /* These sections are what may appear in a DWP file.  */
892
893 struct dwp_sections
894 {
895   /* These are used by both DWP version 1 and 2.  */
896   struct dwarf2_section_info str;
897   struct dwarf2_section_info cu_index;
898   struct dwarf2_section_info tu_index;
899
900   /* These are only used by DWP version 2 files.
901      In DWP version 1 the .debug_info.dwo, .debug_types.dwo, and other
902      sections are referenced by section number, and are not recorded here.
903      In DWP version 2 there is at most one copy of all these sections, each
904      section being (effectively) comprised of the concatenation of all of the
905      individual sections that exist in the version 1 format.
906      To keep the code simple we treat each of these concatenated pieces as a
907      section itself (a virtual section?).  */
908   struct dwarf2_section_info abbrev;
909   struct dwarf2_section_info info;
910   struct dwarf2_section_info line;
911   struct dwarf2_section_info loc;
912   struct dwarf2_section_info macinfo;
913   struct dwarf2_section_info macro;
914   struct dwarf2_section_info str_offsets;
915   struct dwarf2_section_info types;
916 };
917
918 /* These sections are what may appear in a virtual DWO file in DWP version 1.
919    A virtual DWO file is a DWO file as it appears in a DWP file.  */
920
921 struct virtual_v1_dwo_sections
922 {
923   struct dwarf2_section_info abbrev;
924   struct dwarf2_section_info line;
925   struct dwarf2_section_info loc;
926   struct dwarf2_section_info macinfo;
927   struct dwarf2_section_info macro;
928   struct dwarf2_section_info str_offsets;
929   /* Each DWP hash table entry records one CU or one TU.
930      That is recorded here, and copied to dwo_unit.section.  */
931   struct dwarf2_section_info info_or_types;
932 };
933
934 /* Similar to virtual_v1_dwo_sections, but for DWP version 2.
935    In version 2, the sections of the DWO files are concatenated together
936    and stored in one section of that name.  Thus each ELF section contains
937    several "virtual" sections.  */
938
939 struct virtual_v2_dwo_sections
940 {
941   bfd_size_type abbrev_offset;
942   bfd_size_type abbrev_size;
943
944   bfd_size_type line_offset;
945   bfd_size_type line_size;
946
947   bfd_size_type loc_offset;
948   bfd_size_type loc_size;
949
950   bfd_size_type macinfo_offset;
951   bfd_size_type macinfo_size;
952
953   bfd_size_type macro_offset;
954   bfd_size_type macro_size;
955
956   bfd_size_type str_offsets_offset;
957   bfd_size_type str_offsets_size;
958
959   /* Each DWP hash table entry records one CU or one TU.
960      That is recorded here, and copied to dwo_unit.section.  */
961   bfd_size_type info_or_types_offset;
962   bfd_size_type info_or_types_size;
963 };
964
965 /* Contents of DWP hash tables.  */
966
967 struct dwp_hash_table
968 {
969   uint32_t version, nr_columns;
970   uint32_t nr_units, nr_slots;
971   const gdb_byte *hash_table, *unit_table;
972   union
973   {
974     struct
975     {
976       const gdb_byte *indices;
977     } v1;
978     struct
979     {
980       /* This is indexed by column number and gives the id of the section
981          in that column.  */
982 #define MAX_NR_V2_DWO_SECTIONS \
983   (1 /* .debug_info or .debug_types */ \
984    + 1 /* .debug_abbrev */ \
985    + 1 /* .debug_line */ \
986    + 1 /* .debug_loc */ \
987    + 1 /* .debug_str_offsets */ \
988    + 1 /* .debug_macro or .debug_macinfo */)
989       int section_ids[MAX_NR_V2_DWO_SECTIONS];
990       const gdb_byte *offsets;
991       const gdb_byte *sizes;
992     } v2;
993   } section_pool;
994 };
995
996 /* Data for one DWP file.  */
997
998 struct dwp_file
999 {
1000   /* Name of the file.  */
1001   const char *name;
1002
1003   /* File format version.  */
1004   int version;
1005
1006   /* The bfd.  */
1007   bfd *dbfd;
1008
1009   /* Section info for this file.  */
1010   struct dwp_sections sections;
1011
1012   /* Table of CUs in the file.  */
1013   const struct dwp_hash_table *cus;
1014
1015   /* Table of TUs in the file.  */
1016   const struct dwp_hash_table *tus;
1017
1018   /* Tables of loaded CUs/TUs.  Each entry is a struct dwo_unit *.  */
1019   htab_t loaded_cus;
1020   htab_t loaded_tus;
1021
1022   /* Table to map ELF section numbers to their sections.
1023      This is only needed for the DWP V1 file format.  */
1024   unsigned int num_sections;
1025   asection **elf_sections;
1026 };
1027
1028 /* This represents a '.dwz' file.  */
1029
1030 struct dwz_file
1031 {
1032   /* A dwz file can only contain a few sections.  */
1033   struct dwarf2_section_info abbrev;
1034   struct dwarf2_section_info info;
1035   struct dwarf2_section_info str;
1036   struct dwarf2_section_info line;
1037   struct dwarf2_section_info macro;
1038   struct dwarf2_section_info gdb_index;
1039
1040   /* The dwz's BFD.  */
1041   bfd *dwz_bfd;
1042 };
1043
1044 /* Struct used to pass misc. parameters to read_die_and_children, et
1045    al.  which are used for both .debug_info and .debug_types dies.
1046    All parameters here are unchanging for the life of the call.  This
1047    struct exists to abstract away the constant parameters of die reading.  */
1048
1049 struct die_reader_specs
1050 {
1051   /* The bfd of die_section.  */
1052   bfd* abfd;
1053
1054   /* The CU of the DIE we are parsing.  */
1055   struct dwarf2_cu *cu;
1056
1057   /* Non-NULL if reading a DWO file (including one packaged into a DWP).  */
1058   struct dwo_file *dwo_file;
1059
1060   /* The section the die comes from.
1061      This is either .debug_info or .debug_types, or the .dwo variants.  */
1062   struct dwarf2_section_info *die_section;
1063
1064   /* die_section->buffer.  */
1065   const gdb_byte *buffer;
1066
1067   /* The end of the buffer.  */
1068   const gdb_byte *buffer_end;
1069
1070   /* The value of the DW_AT_comp_dir attribute.  */
1071   const char *comp_dir;
1072 };
1073
1074 /* Type of function passed to init_cutu_and_read_dies, et.al.  */
1075 typedef void (die_reader_func_ftype) (const struct die_reader_specs *reader,
1076                                       const gdb_byte *info_ptr,
1077                                       struct die_info *comp_unit_die,
1078                                       int has_children,
1079                                       void *data);
1080
1081 /* A 1-based directory index.  This is a strong typedef to prevent
1082    accidentally using a directory index as a 0-based index into an
1083    array/vector.  */
1084 enum class dir_index : unsigned int {};
1085
1086 /* Likewise, a 1-based file name index.  */
1087 enum class file_name_index : unsigned int {};
1088
1089 struct file_entry
1090 {
1091   file_entry () = default;
1092
1093   file_entry (const char *name_, dir_index d_index_,
1094               unsigned int mod_time_, unsigned int length_)
1095     : name (name_),
1096       d_index (d_index_),
1097       mod_time (mod_time_),
1098       length (length_)
1099   {}
1100
1101   /* Return the include directory at D_INDEX stored in LH.  Returns
1102      NULL if D_INDEX is out of bounds.  */
1103   const char *include_dir (const line_header *lh) const;
1104
1105   /* The file name.  Note this is an observing pointer.  The memory is
1106      owned by debug_line_buffer.  */
1107   const char *name {};
1108
1109   /* The directory index (1-based).  */
1110   dir_index d_index {};
1111
1112   unsigned int mod_time {};
1113
1114   unsigned int length {};
1115
1116   /* True if referenced by the Line Number Program.  */
1117   bool included_p {};
1118
1119   /* The associated symbol table, if any.  */
1120   struct symtab *symtab {};
1121 };
1122
1123 /* The line number information for a compilation unit (found in the
1124    .debug_line section) begins with a "statement program header",
1125    which contains the following information.  */
1126 struct line_header
1127 {
1128   line_header ()
1129     : offset_in_dwz {}
1130   {}
1131
1132   /* Add an entry to the include directory table.  */
1133   void add_include_dir (const char *include_dir);
1134
1135   /* Add an entry to the file name table.  */
1136   void add_file_name (const char *name, dir_index d_index,
1137                       unsigned int mod_time, unsigned int length);
1138
1139   /* Return the include dir at INDEX (1-based).  Returns NULL if INDEX
1140      is out of bounds.  */
1141   const char *include_dir_at (dir_index index) const
1142   {
1143     /* Convert directory index number (1-based) to vector index
1144        (0-based).  */
1145     size_t vec_index = to_underlying (index) - 1;
1146
1147     if (vec_index >= include_dirs.size ())
1148       return NULL;
1149     return include_dirs[vec_index];
1150   }
1151
1152   /* Return the file name at INDEX (1-based).  Returns NULL if INDEX
1153      is out of bounds.  */
1154   file_entry *file_name_at (file_name_index index)
1155   {
1156     /* Convert file name index number (1-based) to vector index
1157        (0-based).  */
1158     size_t vec_index = to_underlying (index) - 1;
1159
1160     if (vec_index >= file_names.size ())
1161       return NULL;
1162     return &file_names[vec_index];
1163   }
1164
1165   /* Const version of the above.  */
1166   const file_entry *file_name_at (unsigned int index) const
1167   {
1168     if (index >= file_names.size ())
1169       return NULL;
1170     return &file_names[index];
1171   }
1172
1173   /* Offset of line number information in .debug_line section.  */
1174   sect_offset sect_off {};
1175
1176   /* OFFSET is for struct dwz_file associated with dwarf2_per_objfile.  */
1177   unsigned offset_in_dwz : 1; /* Can't initialize bitfields in-class.  */
1178
1179   unsigned int total_length {};
1180   unsigned short version {};
1181   unsigned int header_length {};
1182   unsigned char minimum_instruction_length {};
1183   unsigned char maximum_ops_per_instruction {};
1184   unsigned char default_is_stmt {};
1185   int line_base {};
1186   unsigned char line_range {};
1187   unsigned char opcode_base {};
1188
1189   /* standard_opcode_lengths[i] is the number of operands for the
1190      standard opcode whose value is i.  This means that
1191      standard_opcode_lengths[0] is unused, and the last meaningful
1192      element is standard_opcode_lengths[opcode_base - 1].  */
1193   std::unique_ptr<unsigned char[]> standard_opcode_lengths;
1194
1195   /* The include_directories table.  Note these are observing
1196      pointers.  The memory is owned by debug_line_buffer.  */
1197   std::vector<const char *> include_dirs;
1198
1199   /* The file_names table.  */
1200   std::vector<file_entry> file_names;
1201
1202   /* The start and end of the statement program following this
1203      header.  These point into dwarf2_per_objfile->line_buffer.  */
1204   const gdb_byte *statement_program_start {}, *statement_program_end {};
1205 };
1206
1207 typedef std::unique_ptr<line_header> line_header_up;
1208
1209 const char *
1210 file_entry::include_dir (const line_header *lh) const
1211 {
1212   return lh->include_dir_at (d_index);
1213 }
1214
1215 /* When we construct a partial symbol table entry we only
1216    need this much information.  */
1217 struct partial_die_info
1218   {
1219     /* Offset of this DIE.  */
1220     sect_offset sect_off;
1221
1222     /* DWARF-2 tag for this DIE.  */
1223     ENUM_BITFIELD(dwarf_tag) tag : 16;
1224
1225     /* Assorted flags describing the data found in this DIE.  */
1226     unsigned int has_children : 1;
1227     unsigned int is_external : 1;
1228     unsigned int is_declaration : 1;
1229     unsigned int has_type : 1;
1230     unsigned int has_specification : 1;
1231     unsigned int has_pc_info : 1;
1232     unsigned int may_be_inlined : 1;
1233
1234     /* This DIE has been marked DW_AT_main_subprogram.  */
1235     unsigned int main_subprogram : 1;
1236
1237     /* Flag set if the SCOPE field of this structure has been
1238        computed.  */
1239     unsigned int scope_set : 1;
1240
1241     /* Flag set if the DIE has a byte_size attribute.  */
1242     unsigned int has_byte_size : 1;
1243
1244     /* Flag set if the DIE has a DW_AT_const_value attribute.  */
1245     unsigned int has_const_value : 1;
1246
1247     /* Flag set if any of the DIE's children are template arguments.  */
1248     unsigned int has_template_arguments : 1;
1249
1250     /* Flag set if fixup_partial_die has been called on this die.  */
1251     unsigned int fixup_called : 1;
1252
1253     /* Flag set if DW_TAG_imported_unit uses DW_FORM_GNU_ref_alt.  */
1254     unsigned int is_dwz : 1;
1255
1256     /* Flag set if spec_offset uses DW_FORM_GNU_ref_alt.  */
1257     unsigned int spec_is_dwz : 1;
1258
1259     /* The name of this DIE.  Normally the value of DW_AT_name, but
1260        sometimes a default name for unnamed DIEs.  */
1261     const char *name;
1262
1263     /* The linkage name, if present.  */
1264     const char *linkage_name;
1265
1266     /* The scope to prepend to our children.  This is generally
1267        allocated on the comp_unit_obstack, so will disappear
1268        when this compilation unit leaves the cache.  */
1269     const char *scope;
1270
1271     /* Some data associated with the partial DIE.  The tag determines
1272        which field is live.  */
1273     union
1274     {
1275       /* The location description associated with this DIE, if any.  */
1276       struct dwarf_block *locdesc;
1277       /* The offset of an import, for DW_TAG_imported_unit.  */
1278       sect_offset sect_off;
1279     } d;
1280
1281     /* If HAS_PC_INFO, the PC range associated with this DIE.  */
1282     CORE_ADDR lowpc;
1283     CORE_ADDR highpc;
1284
1285     /* Pointer into the info_buffer (or types_buffer) pointing at the target of
1286        DW_AT_sibling, if any.  */
1287     /* NOTE: This member isn't strictly necessary, read_partial_die could
1288        return DW_AT_sibling values to its caller load_partial_dies.  */
1289     const gdb_byte *sibling;
1290
1291     /* If HAS_SPECIFICATION, the offset of the DIE referred to by
1292        DW_AT_specification (or DW_AT_abstract_origin or
1293        DW_AT_extension).  */
1294     sect_offset spec_offset;
1295
1296     /* Pointers to this DIE's parent, first child, and next sibling,
1297        if any.  */
1298     struct partial_die_info *die_parent, *die_child, *die_sibling;
1299   };
1300
1301 /* This data structure holds the information of an abbrev.  */
1302 struct abbrev_info
1303   {
1304     unsigned int number;        /* number identifying abbrev */
1305     enum dwarf_tag tag;         /* dwarf tag */
1306     unsigned short has_children;                /* boolean */
1307     unsigned short num_attrs;   /* number of attributes */
1308     struct attr_abbrev *attrs;  /* an array of attribute descriptions */
1309     struct abbrev_info *next;   /* next in chain */
1310   };
1311
1312 struct attr_abbrev
1313   {
1314     ENUM_BITFIELD(dwarf_attribute) name : 16;
1315     ENUM_BITFIELD(dwarf_form) form : 16;
1316
1317     /* It is valid only if FORM is DW_FORM_implicit_const.  */
1318     LONGEST implicit_const;
1319   };
1320
1321 /* Size of abbrev_table.abbrev_hash_table.  */
1322 #define ABBREV_HASH_SIZE 121
1323
1324 /* Top level data structure to contain an abbreviation table.  */
1325
1326 struct abbrev_table
1327 {
1328   /* Where the abbrev table came from.
1329      This is used as a sanity check when the table is used.  */
1330   sect_offset sect_off;
1331
1332   /* Storage for the abbrev table.  */
1333   struct obstack abbrev_obstack;
1334
1335   /* Hash table of abbrevs.
1336      This is an array of size ABBREV_HASH_SIZE allocated in abbrev_obstack.
1337      It could be statically allocated, but the previous code didn't so we
1338      don't either.  */
1339   struct abbrev_info **abbrevs;
1340 };
1341
1342 /* Attributes have a name and a value.  */
1343 struct attribute
1344   {
1345     ENUM_BITFIELD(dwarf_attribute) name : 16;
1346     ENUM_BITFIELD(dwarf_form) form : 15;
1347
1348     /* Has DW_STRING already been updated by dwarf2_canonicalize_name?  This
1349        field should be in u.str (existing only for DW_STRING) but it is kept
1350        here for better struct attribute alignment.  */
1351     unsigned int string_is_canonical : 1;
1352
1353     union
1354       {
1355         const char *str;
1356         struct dwarf_block *blk;
1357         ULONGEST unsnd;
1358         LONGEST snd;
1359         CORE_ADDR addr;
1360         ULONGEST signature;
1361       }
1362     u;
1363   };
1364
1365 /* This data structure holds a complete die structure.  */
1366 struct die_info
1367   {
1368     /* DWARF-2 tag for this DIE.  */
1369     ENUM_BITFIELD(dwarf_tag) tag : 16;
1370
1371     /* Number of attributes */
1372     unsigned char num_attrs;
1373
1374     /* True if we're presently building the full type name for the
1375        type derived from this DIE.  */
1376     unsigned char building_fullname : 1;
1377
1378     /* True if this die is in process.  PR 16581.  */
1379     unsigned char in_process : 1;
1380
1381     /* Abbrev number */
1382     unsigned int abbrev;
1383
1384     /* Offset in .debug_info or .debug_types section.  */
1385     sect_offset sect_off;
1386
1387     /* The dies in a compilation unit form an n-ary tree.  PARENT
1388        points to this die's parent; CHILD points to the first child of
1389        this node; and all the children of a given node are chained
1390        together via their SIBLING fields.  */
1391     struct die_info *child;     /* Its first child, if any.  */
1392     struct die_info *sibling;   /* Its next sibling, if any.  */
1393     struct die_info *parent;    /* Its parent, if any.  */
1394
1395     /* An array of attributes, with NUM_ATTRS elements.  There may be
1396        zero, but it's not common and zero-sized arrays are not
1397        sufficiently portable C.  */
1398     struct attribute attrs[1];
1399   };
1400
1401 /* Get at parts of an attribute structure.  */
1402
1403 #define DW_STRING(attr)    ((attr)->u.str)
1404 #define DW_STRING_IS_CANONICAL(attr) ((attr)->string_is_canonical)
1405 #define DW_UNSND(attr)     ((attr)->u.unsnd)
1406 #define DW_BLOCK(attr)     ((attr)->u.blk)
1407 #define DW_SND(attr)       ((attr)->u.snd)
1408 #define DW_ADDR(attr)      ((attr)->u.addr)
1409 #define DW_SIGNATURE(attr) ((attr)->u.signature)
1410
1411 /* Blocks are a bunch of untyped bytes.  */
1412 struct dwarf_block
1413   {
1414     size_t size;
1415
1416     /* Valid only if SIZE is not zero.  */
1417     const gdb_byte *data;
1418   };
1419
1420 #ifndef ATTR_ALLOC_CHUNK
1421 #define ATTR_ALLOC_CHUNK 4
1422 #endif
1423
1424 /* Allocate fields for structs, unions and enums in this size.  */
1425 #ifndef DW_FIELD_ALLOC_CHUNK
1426 #define DW_FIELD_ALLOC_CHUNK 4
1427 #endif
1428
1429 /* FIXME: We might want to set this from BFD via bfd_arch_bits_per_byte,
1430    but this would require a corresponding change in unpack_field_as_long
1431    and friends.  */
1432 static int bits_per_byte = 8;
1433
1434 struct nextfield
1435 {
1436   struct nextfield *next;
1437   int accessibility;
1438   int virtuality;
1439   struct field field;
1440 };
1441
1442 struct nextfnfield
1443 {
1444   struct nextfnfield *next;
1445   struct fn_field fnfield;
1446 };
1447
1448 struct fnfieldlist
1449 {
1450   const char *name;
1451   int length;
1452   struct nextfnfield *head;
1453 };
1454
1455 struct typedef_field_list
1456 {
1457   struct typedef_field field;
1458   struct typedef_field_list *next;
1459 };
1460
1461 /* The routines that read and process dies for a C struct or C++ class
1462    pass lists of data member fields and lists of member function fields
1463    in an instance of a field_info structure, as defined below.  */
1464 struct field_info
1465   {
1466     /* List of data member and baseclasses fields.  */
1467     struct nextfield *fields, *baseclasses;
1468
1469     /* Number of fields (including baseclasses).  */
1470     int nfields;
1471
1472     /* Number of baseclasses.  */
1473     int nbaseclasses;
1474
1475     /* Set if the accesibility of one of the fields is not public.  */
1476     int non_public_fields;
1477
1478     /* Member function fields array, entries are allocated in the order they
1479        are encountered in the object file.  */
1480     struct nextfnfield *fnfields;
1481
1482     /* Member function fieldlist array, contains name of possibly overloaded
1483        member function, number of overloaded member functions and a pointer
1484        to the head of the member function field chain.  */
1485     struct fnfieldlist *fnfieldlists;
1486
1487     /* Number of entries in the fnfieldlists array.  */
1488     int nfnfields;
1489
1490     /* typedefs defined inside this class.  TYPEDEF_FIELD_LIST contains head of
1491        a NULL terminated list of TYPEDEF_FIELD_LIST_COUNT elements.  */
1492     struct typedef_field_list *typedef_field_list;
1493     unsigned typedef_field_list_count;
1494   };
1495
1496 /* One item on the queue of compilation units to read in full symbols
1497    for.  */
1498 struct dwarf2_queue_item
1499 {
1500   struct dwarf2_per_cu_data *per_cu;
1501   enum language pretend_language;
1502   struct dwarf2_queue_item *next;
1503 };
1504
1505 /* The current queue.  */
1506 static struct dwarf2_queue_item *dwarf2_queue, *dwarf2_queue_tail;
1507
1508 /* Loaded secondary compilation units are kept in memory until they
1509    have not been referenced for the processing of this many
1510    compilation units.  Set this to zero to disable caching.  Cache
1511    sizes of up to at least twenty will improve startup time for
1512    typical inter-CU-reference binaries, at an obvious memory cost.  */
1513 static int dwarf_max_cache_age = 5;
1514 static void
1515 show_dwarf_max_cache_age (struct ui_file *file, int from_tty,
1516                           struct cmd_list_element *c, const char *value)
1517 {
1518   fprintf_filtered (file, _("The upper bound on the age of cached "
1519                             "DWARF compilation units is %s.\n"),
1520                     value);
1521 }
1522 \f
1523 /* local function prototypes */
1524
1525 static const char *get_section_name (const struct dwarf2_section_info *);
1526
1527 static const char *get_section_file_name (const struct dwarf2_section_info *);
1528
1529 static void dwarf2_find_base_address (struct die_info *die,
1530                                       struct dwarf2_cu *cu);
1531
1532 static struct partial_symtab *create_partial_symtab
1533   (struct dwarf2_per_cu_data *per_cu, const char *name);
1534
1535 static void dwarf2_build_psymtabs_hard (struct objfile *);
1536
1537 static void scan_partial_symbols (struct partial_die_info *,
1538                                   CORE_ADDR *, CORE_ADDR *,
1539                                   int, struct dwarf2_cu *);
1540
1541 static void add_partial_symbol (struct partial_die_info *,
1542                                 struct dwarf2_cu *);
1543
1544 static void add_partial_namespace (struct partial_die_info *pdi,
1545                                    CORE_ADDR *lowpc, CORE_ADDR *highpc,
1546                                    int set_addrmap, struct dwarf2_cu *cu);
1547
1548 static void add_partial_module (struct partial_die_info *pdi, CORE_ADDR *lowpc,
1549                                 CORE_ADDR *highpc, int set_addrmap,
1550                                 struct dwarf2_cu *cu);
1551
1552 static void add_partial_enumeration (struct partial_die_info *enum_pdi,
1553                                      struct dwarf2_cu *cu);
1554
1555 static void add_partial_subprogram (struct partial_die_info *pdi,
1556                                     CORE_ADDR *lowpc, CORE_ADDR *highpc,
1557                                     int need_pc, struct dwarf2_cu *cu);
1558
1559 static void dwarf2_read_symtab (struct partial_symtab *,
1560                                 struct objfile *);
1561
1562 static void psymtab_to_symtab_1 (struct partial_symtab *);
1563
1564 static struct abbrev_info *abbrev_table_lookup_abbrev
1565   (const struct abbrev_table *, unsigned int);
1566
1567 static struct abbrev_table *abbrev_table_read_table
1568   (struct dwarf2_section_info *, sect_offset);
1569
1570 static void abbrev_table_free (struct abbrev_table *);
1571
1572 static void abbrev_table_free_cleanup (void *);
1573
1574 static void dwarf2_read_abbrevs (struct dwarf2_cu *,
1575                                  struct dwarf2_section_info *);
1576
1577 static void dwarf2_free_abbrev_table (void *);
1578
1579 static unsigned int peek_abbrev_code (bfd *, const gdb_byte *);
1580
1581 static struct partial_die_info *load_partial_dies
1582   (const struct die_reader_specs *, const gdb_byte *, int);
1583
1584 static const gdb_byte *read_partial_die (const struct die_reader_specs *,
1585                                          struct partial_die_info *,
1586                                          struct abbrev_info *,
1587                                          unsigned int,
1588                                          const gdb_byte *);
1589
1590 static struct partial_die_info *find_partial_die (sect_offset, int,
1591                                                   struct dwarf2_cu *);
1592
1593 static void fixup_partial_die (struct partial_die_info *,
1594                                struct dwarf2_cu *);
1595
1596 static const gdb_byte *read_attribute (const struct die_reader_specs *,
1597                                        struct attribute *, struct attr_abbrev *,
1598                                        const gdb_byte *);
1599
1600 static unsigned int read_1_byte (bfd *, const gdb_byte *);
1601
1602 static int read_1_signed_byte (bfd *, const gdb_byte *);
1603
1604 static unsigned int read_2_bytes (bfd *, const gdb_byte *);
1605
1606 static unsigned int read_4_bytes (bfd *, const gdb_byte *);
1607
1608 static ULONGEST read_8_bytes (bfd *, const gdb_byte *);
1609
1610 static CORE_ADDR read_address (bfd *, const gdb_byte *ptr, struct dwarf2_cu *,
1611                                unsigned int *);
1612
1613 static LONGEST read_initial_length (bfd *, const gdb_byte *, unsigned int *);
1614
1615 static LONGEST read_checked_initial_length_and_offset
1616   (bfd *, const gdb_byte *, const struct comp_unit_head *,
1617    unsigned int *, unsigned int *);
1618
1619 static LONGEST read_offset (bfd *, const gdb_byte *,
1620                             const struct comp_unit_head *,
1621                             unsigned int *);
1622
1623 static LONGEST read_offset_1 (bfd *, const gdb_byte *, unsigned int);
1624
1625 static sect_offset read_abbrev_offset (struct dwarf2_section_info *,
1626                                        sect_offset);
1627
1628 static const gdb_byte *read_n_bytes (bfd *, const gdb_byte *, unsigned int);
1629
1630 static const char *read_direct_string (bfd *, const gdb_byte *, unsigned int *);
1631
1632 static const char *read_indirect_string (bfd *, const gdb_byte *,
1633                                          const struct comp_unit_head *,
1634                                          unsigned int *);
1635
1636 static const char *read_indirect_line_string (bfd *, const gdb_byte *,
1637                                               const struct comp_unit_head *,
1638                                               unsigned int *);
1639
1640 static const char *read_indirect_string_from_dwz (struct dwz_file *, LONGEST);
1641
1642 static LONGEST read_signed_leb128 (bfd *, const gdb_byte *, unsigned int *);
1643
1644 static CORE_ADDR read_addr_index_from_leb128 (struct dwarf2_cu *,
1645                                               const gdb_byte *,
1646                                               unsigned int *);
1647
1648 static const char *read_str_index (const struct die_reader_specs *reader,
1649                                    ULONGEST str_index);
1650
1651 static void set_cu_language (unsigned int, struct dwarf2_cu *);
1652
1653 static struct attribute *dwarf2_attr (struct die_info *, unsigned int,
1654                                       struct dwarf2_cu *);
1655
1656 static struct attribute *dwarf2_attr_no_follow (struct die_info *,
1657                                                 unsigned int);
1658
1659 static const char *dwarf2_string_attr (struct die_info *die, unsigned int name,
1660                                        struct dwarf2_cu *cu);
1661
1662 static int dwarf2_flag_true_p (struct die_info *die, unsigned name,
1663                                struct dwarf2_cu *cu);
1664
1665 static int die_is_declaration (struct die_info *, struct dwarf2_cu *cu);
1666
1667 static struct die_info *die_specification (struct die_info *die,
1668                                            struct dwarf2_cu **);
1669
1670 static line_header_up dwarf_decode_line_header (sect_offset sect_off,
1671                                                 struct dwarf2_cu *cu);
1672
1673 static void dwarf_decode_lines (struct line_header *, const char *,
1674                                 struct dwarf2_cu *, struct partial_symtab *,
1675                                 CORE_ADDR, int decode_mapping);
1676
1677 static void dwarf2_start_subfile (const char *, const char *);
1678
1679 static struct compunit_symtab *dwarf2_start_symtab (struct dwarf2_cu *,
1680                                                     const char *, const char *,
1681                                                     CORE_ADDR);
1682
1683 static struct symbol *new_symbol (struct die_info *, struct type *,
1684                                   struct dwarf2_cu *);
1685
1686 static struct symbol *new_symbol_full (struct die_info *, struct type *,
1687                                        struct dwarf2_cu *, struct symbol *);
1688
1689 static void dwarf2_const_value (const struct attribute *, struct symbol *,
1690                                 struct dwarf2_cu *);
1691
1692 static void dwarf2_const_value_attr (const struct attribute *attr,
1693                                      struct type *type,
1694                                      const char *name,
1695                                      struct obstack *obstack,
1696                                      struct dwarf2_cu *cu, LONGEST *value,
1697                                      const gdb_byte **bytes,
1698                                      struct dwarf2_locexpr_baton **baton);
1699
1700 static struct type *die_type (struct die_info *, struct dwarf2_cu *);
1701
1702 static int need_gnat_info (struct dwarf2_cu *);
1703
1704 static struct type *die_descriptive_type (struct die_info *,
1705                                           struct dwarf2_cu *);
1706
1707 static void set_descriptive_type (struct type *, struct die_info *,
1708                                   struct dwarf2_cu *);
1709
1710 static struct type *die_containing_type (struct die_info *,
1711                                          struct dwarf2_cu *);
1712
1713 static struct type *lookup_die_type (struct die_info *, const struct attribute *,
1714                                      struct dwarf2_cu *);
1715
1716 static struct type *read_type_die (struct die_info *, struct dwarf2_cu *);
1717
1718 static struct type *read_type_die_1 (struct die_info *, struct dwarf2_cu *);
1719
1720 static const char *determine_prefix (struct die_info *die, struct dwarf2_cu *);
1721
1722 static char *typename_concat (struct obstack *obs, const char *prefix,
1723                               const char *suffix, int physname,
1724                               struct dwarf2_cu *cu);
1725
1726 static void read_file_scope (struct die_info *, struct dwarf2_cu *);
1727
1728 static void read_type_unit_scope (struct die_info *, struct dwarf2_cu *);
1729
1730 static void read_func_scope (struct die_info *, struct dwarf2_cu *);
1731
1732 static void read_lexical_block_scope (struct die_info *, struct dwarf2_cu *);
1733
1734 static void read_call_site_scope (struct die_info *die, struct dwarf2_cu *cu);
1735
1736 static int dwarf2_ranges_read (unsigned, CORE_ADDR *, CORE_ADDR *,
1737                                struct dwarf2_cu *, struct partial_symtab *);
1738
1739 /* How dwarf2_get_pc_bounds constructed its *LOWPC and *HIGHPC return
1740    values.  Keep the items ordered with increasing constraints compliance.  */
1741 enum pc_bounds_kind
1742 {
1743   /* No attribute DW_AT_low_pc, DW_AT_high_pc or DW_AT_ranges was found.  */
1744   PC_BOUNDS_NOT_PRESENT,
1745
1746   /* Some of the attributes DW_AT_low_pc, DW_AT_high_pc or DW_AT_ranges
1747      were present but they do not form a valid range of PC addresses.  */
1748   PC_BOUNDS_INVALID,
1749
1750   /* Discontiguous range was found - that is DW_AT_ranges was found.  */
1751   PC_BOUNDS_RANGES,
1752
1753   /* Contiguous range was found - DW_AT_low_pc and DW_AT_high_pc were found.  */
1754   PC_BOUNDS_HIGH_LOW,
1755 };
1756
1757 static enum pc_bounds_kind dwarf2_get_pc_bounds (struct die_info *,
1758                                                  CORE_ADDR *, CORE_ADDR *,
1759                                                  struct dwarf2_cu *,
1760                                                  struct partial_symtab *);
1761
1762 static void get_scope_pc_bounds (struct die_info *,
1763                                  CORE_ADDR *, CORE_ADDR *,
1764                                  struct dwarf2_cu *);
1765
1766 static void dwarf2_record_block_ranges (struct die_info *, struct block *,
1767                                         CORE_ADDR, struct dwarf2_cu *);
1768
1769 static void dwarf2_add_field (struct field_info *, struct die_info *,
1770                               struct dwarf2_cu *);
1771
1772 static void dwarf2_attach_fields_to_type (struct field_info *,
1773                                           struct type *, struct dwarf2_cu *);
1774
1775 static void dwarf2_add_member_fn (struct field_info *,
1776                                   struct die_info *, struct type *,
1777                                   struct dwarf2_cu *);
1778
1779 static void dwarf2_attach_fn_fields_to_type (struct field_info *,
1780                                              struct type *,
1781                                              struct dwarf2_cu *);
1782
1783 static void process_structure_scope (struct die_info *, struct dwarf2_cu *);
1784
1785 static void read_common_block (struct die_info *, struct dwarf2_cu *);
1786
1787 static void read_namespace (struct die_info *die, struct dwarf2_cu *);
1788
1789 static void read_module (struct die_info *die, struct dwarf2_cu *cu);
1790
1791 static struct using_direct **using_directives (enum language);
1792
1793 static void read_import_statement (struct die_info *die, struct dwarf2_cu *);
1794
1795 static int read_namespace_alias (struct die_info *die, struct dwarf2_cu *cu);
1796
1797 static struct type *read_module_type (struct die_info *die,
1798                                       struct dwarf2_cu *cu);
1799
1800 static const char *namespace_name (struct die_info *die,
1801                                    int *is_anonymous, struct dwarf2_cu *);
1802
1803 static void process_enumeration_scope (struct die_info *, struct dwarf2_cu *);
1804
1805 static CORE_ADDR decode_locdesc (struct dwarf_block *, struct dwarf2_cu *);
1806
1807 static enum dwarf_array_dim_ordering read_array_order (struct die_info *,
1808                                                        struct dwarf2_cu *);
1809
1810 static struct die_info *read_die_and_siblings_1
1811   (const struct die_reader_specs *, const gdb_byte *, const gdb_byte **,
1812    struct die_info *);
1813
1814 static struct die_info *read_die_and_siblings (const struct die_reader_specs *,
1815                                                const gdb_byte *info_ptr,
1816                                                const gdb_byte **new_info_ptr,
1817                                                struct die_info *parent);
1818
1819 static const gdb_byte *read_full_die_1 (const struct die_reader_specs *,
1820                                         struct die_info **, const gdb_byte *,
1821                                         int *, int);
1822
1823 static const gdb_byte *read_full_die (const struct die_reader_specs *,
1824                                       struct die_info **, const gdb_byte *,
1825                                       int *);
1826
1827 static void process_die (struct die_info *, struct dwarf2_cu *);
1828
1829 static const char *dwarf2_canonicalize_name (const char *, struct dwarf2_cu *,
1830                                              struct obstack *);
1831
1832 static const char *dwarf2_name (struct die_info *die, struct dwarf2_cu *);
1833
1834 static const char *dwarf2_full_name (const char *name,
1835                                      struct die_info *die,
1836                                      struct dwarf2_cu *cu);
1837
1838 static const char *dwarf2_physname (const char *name, struct die_info *die,
1839                                     struct dwarf2_cu *cu);
1840
1841 static struct die_info *dwarf2_extension (struct die_info *die,
1842                                           struct dwarf2_cu **);
1843
1844 static const char *dwarf_tag_name (unsigned int);
1845
1846 static const char *dwarf_attr_name (unsigned int);
1847
1848 static const char *dwarf_form_name (unsigned int);
1849
1850 static const char *dwarf_bool_name (unsigned int);
1851
1852 static const char *dwarf_type_encoding_name (unsigned int);
1853
1854 static struct die_info *sibling_die (struct die_info *);
1855
1856 static void dump_die_shallow (struct ui_file *, int indent, struct die_info *);
1857
1858 static void dump_die_for_error (struct die_info *);
1859
1860 static void dump_die_1 (struct ui_file *, int level, int max_level,
1861                         struct die_info *);
1862
1863 /*static*/ void dump_die (struct die_info *, int max_level);
1864
1865 static void store_in_ref_table (struct die_info *,
1866                                 struct dwarf2_cu *);
1867
1868 static sect_offset dwarf2_get_ref_die_offset (const struct attribute *);
1869
1870 static LONGEST dwarf2_get_attr_constant_value (const struct attribute *, int);
1871
1872 static struct die_info *follow_die_ref_or_sig (struct die_info *,
1873                                                const struct attribute *,
1874                                                struct dwarf2_cu **);
1875
1876 static struct die_info *follow_die_ref (struct die_info *,
1877                                         const struct attribute *,
1878                                         struct dwarf2_cu **);
1879
1880 static struct die_info *follow_die_sig (struct die_info *,
1881                                         const struct attribute *,
1882                                         struct dwarf2_cu **);
1883
1884 static struct type *get_signatured_type (struct die_info *, ULONGEST,
1885                                          struct dwarf2_cu *);
1886
1887 static struct type *get_DW_AT_signature_type (struct die_info *,
1888                                               const struct attribute *,
1889                                               struct dwarf2_cu *);
1890
1891 static void load_full_type_unit (struct dwarf2_per_cu_data *per_cu);
1892
1893 static void read_signatured_type (struct signatured_type *);
1894
1895 static int attr_to_dynamic_prop (const struct attribute *attr,
1896                                  struct die_info *die, struct dwarf2_cu *cu,
1897                                  struct dynamic_prop *prop);
1898
1899 /* memory allocation interface */
1900
1901 static struct dwarf_block *dwarf_alloc_block (struct dwarf2_cu *);
1902
1903 static struct die_info *dwarf_alloc_die (struct dwarf2_cu *, int);
1904
1905 static void dwarf_decode_macros (struct dwarf2_cu *, unsigned int, int);
1906
1907 static int attr_form_is_block (const struct attribute *);
1908
1909 static int attr_form_is_section_offset (const struct attribute *);
1910
1911 static int attr_form_is_constant (const struct attribute *);
1912
1913 static int attr_form_is_ref (const struct attribute *);
1914
1915 static void fill_in_loclist_baton (struct dwarf2_cu *cu,
1916                                    struct dwarf2_loclist_baton *baton,
1917                                    const struct attribute *attr);
1918
1919 static void dwarf2_symbol_mark_computed (const struct attribute *attr,
1920                                          struct symbol *sym,
1921                                          struct dwarf2_cu *cu,
1922                                          int is_block);
1923
1924 static const gdb_byte *skip_one_die (const struct die_reader_specs *reader,
1925                                      const gdb_byte *info_ptr,
1926                                      struct abbrev_info *abbrev);
1927
1928 static void free_stack_comp_unit (void *);
1929
1930 static hashval_t partial_die_hash (const void *item);
1931
1932 static int partial_die_eq (const void *item_lhs, const void *item_rhs);
1933
1934 static struct dwarf2_per_cu_data *dwarf2_find_containing_comp_unit
1935   (sect_offset sect_off, unsigned int offset_in_dwz, struct objfile *objfile);
1936
1937 static void init_one_comp_unit (struct dwarf2_cu *cu,
1938                                 struct dwarf2_per_cu_data *per_cu);
1939
1940 static void prepare_one_comp_unit (struct dwarf2_cu *cu,
1941                                    struct die_info *comp_unit_die,
1942                                    enum language pretend_language);
1943
1944 static void free_heap_comp_unit (void *);
1945
1946 static void free_cached_comp_units (void *);
1947
1948 static void age_cached_comp_units (void);
1949
1950 static void free_one_cached_comp_unit (struct dwarf2_per_cu_data *);
1951
1952 static struct type *set_die_type (struct die_info *, struct type *,
1953                                   struct dwarf2_cu *);
1954
1955 static void create_all_comp_units (struct objfile *);
1956
1957 static int create_all_type_units (struct objfile *);
1958
1959 static void load_full_comp_unit (struct dwarf2_per_cu_data *,
1960                                  enum language);
1961
1962 static void process_full_comp_unit (struct dwarf2_per_cu_data *,
1963                                     enum language);
1964
1965 static void process_full_type_unit (struct dwarf2_per_cu_data *,
1966                                     enum language);
1967
1968 static void dwarf2_add_dependence (struct dwarf2_cu *,
1969                                    struct dwarf2_per_cu_data *);
1970
1971 static void dwarf2_mark (struct dwarf2_cu *);
1972
1973 static void dwarf2_clear_marks (struct dwarf2_per_cu_data *);
1974
1975 static struct type *get_die_type_at_offset (sect_offset,
1976                                             struct dwarf2_per_cu_data *);
1977
1978 static struct type *get_die_type (struct die_info *die, struct dwarf2_cu *cu);
1979
1980 static void dwarf2_release_queue (void *dummy);
1981
1982 static void queue_comp_unit (struct dwarf2_per_cu_data *per_cu,
1983                              enum language pretend_language);
1984
1985 static void process_queue (void);
1986
1987 /* The return type of find_file_and_directory.  Note, the enclosed
1988    string pointers are only valid while this object is valid.  */
1989
1990 struct file_and_directory
1991 {
1992   /* The filename.  This is never NULL.  */
1993   const char *name;
1994
1995   /* The compilation directory.  NULL if not known.  If we needed to
1996      compute a new string, this points to COMP_DIR_STORAGE, otherwise,
1997      points directly to the DW_AT_comp_dir string attribute owned by
1998      the obstack that owns the DIE.  */
1999   const char *comp_dir;
2000
2001   /* If we needed to build a new string for comp_dir, this is what
2002      owns the storage.  */
2003   std::string comp_dir_storage;
2004 };
2005
2006 static file_and_directory find_file_and_directory (struct die_info *die,
2007                                                    struct dwarf2_cu *cu);
2008
2009 static char *file_full_name (int file, struct line_header *lh,
2010                              const char *comp_dir);
2011
2012 /* Expected enum dwarf_unit_type for read_comp_unit_head.  */
2013 enum class rcuh_kind { COMPILE, TYPE };
2014
2015 static const gdb_byte *read_and_check_comp_unit_head
2016   (struct comp_unit_head *header,
2017    struct dwarf2_section_info *section,
2018    struct dwarf2_section_info *abbrev_section, const gdb_byte *info_ptr,
2019    rcuh_kind section_kind);
2020
2021 static void init_cutu_and_read_dies
2022   (struct dwarf2_per_cu_data *this_cu, struct abbrev_table *abbrev_table,
2023    int use_existing_cu, int keep,
2024    die_reader_func_ftype *die_reader_func, void *data);
2025
2026 static void init_cutu_and_read_dies_simple
2027   (struct dwarf2_per_cu_data *this_cu,
2028    die_reader_func_ftype *die_reader_func, void *data);
2029
2030 static htab_t allocate_signatured_type_table (struct objfile *objfile);
2031
2032 static htab_t allocate_dwo_unit_table (struct objfile *objfile);
2033
2034 static struct dwo_unit *lookup_dwo_unit_in_dwp
2035   (struct dwp_file *dwp_file, const char *comp_dir,
2036    ULONGEST signature, int is_debug_types);
2037
2038 static struct dwp_file *get_dwp_file (void);
2039
2040 static struct dwo_unit *lookup_dwo_comp_unit
2041   (struct dwarf2_per_cu_data *, const char *, const char *, ULONGEST);
2042
2043 static struct dwo_unit *lookup_dwo_type_unit
2044   (struct signatured_type *, const char *, const char *);
2045
2046 static void queue_and_load_all_dwo_tus (struct dwarf2_per_cu_data *);
2047
2048 static void free_dwo_file_cleanup (void *);
2049
2050 static void process_cu_includes (void);
2051
2052 static void check_producer (struct dwarf2_cu *cu);
2053
2054 static void free_line_header_voidp (void *arg);
2055 \f
2056 /* Various complaints about symbol reading that don't abort the process.  */
2057
2058 static void
2059 dwarf2_statement_list_fits_in_line_number_section_complaint (void)
2060 {
2061   complaint (&symfile_complaints,
2062              _("statement list doesn't fit in .debug_line section"));
2063 }
2064
2065 static void
2066 dwarf2_debug_line_missing_file_complaint (void)
2067 {
2068   complaint (&symfile_complaints,
2069              _(".debug_line section has line data without a file"));
2070 }
2071
2072 static void
2073 dwarf2_debug_line_missing_end_sequence_complaint (void)
2074 {
2075   complaint (&symfile_complaints,
2076              _(".debug_line section has line "
2077                "program sequence without an end"));
2078 }
2079
2080 static void
2081 dwarf2_complex_location_expr_complaint (void)
2082 {
2083   complaint (&symfile_complaints, _("location expression too complex"));
2084 }
2085
2086 static void
2087 dwarf2_const_value_length_mismatch_complaint (const char *arg1, int arg2,
2088                                               int arg3)
2089 {
2090   complaint (&symfile_complaints,
2091              _("const value length mismatch for '%s', got %d, expected %d"),
2092              arg1, arg2, arg3);
2093 }
2094
2095 static void
2096 dwarf2_section_buffer_overflow_complaint (struct dwarf2_section_info *section)
2097 {
2098   complaint (&symfile_complaints,
2099              _("debug info runs off end of %s section"
2100                " [in module %s]"),
2101              get_section_name (section),
2102              get_section_file_name (section));
2103 }
2104
2105 static void
2106 dwarf2_macro_malformed_definition_complaint (const char *arg1)
2107 {
2108   complaint (&symfile_complaints,
2109              _("macro debug info contains a "
2110                "malformed macro definition:\n`%s'"),
2111              arg1);
2112 }
2113
2114 static void
2115 dwarf2_invalid_attrib_class_complaint (const char *arg1, const char *arg2)
2116 {
2117   complaint (&symfile_complaints,
2118              _("invalid attribute class or form for '%s' in '%s'"),
2119              arg1, arg2);
2120 }
2121
2122 /* Hash function for line_header_hash.  */
2123
2124 static hashval_t
2125 line_header_hash (const struct line_header *ofs)
2126 {
2127   return to_underlying (ofs->sect_off) ^ ofs->offset_in_dwz;
2128 }
2129
2130 /* Hash function for htab_create_alloc_ex for line_header_hash.  */
2131
2132 static hashval_t
2133 line_header_hash_voidp (const void *item)
2134 {
2135   const struct line_header *ofs = (const struct line_header *) item;
2136
2137   return line_header_hash (ofs);
2138 }
2139
2140 /* Equality function for line_header_hash.  */
2141
2142 static int
2143 line_header_eq_voidp (const void *item_lhs, const void *item_rhs)
2144 {
2145   const struct line_header *ofs_lhs = (const struct line_header *) item_lhs;
2146   const struct line_header *ofs_rhs = (const struct line_header *) item_rhs;
2147
2148   return (ofs_lhs->sect_off == ofs_rhs->sect_off
2149           && ofs_lhs->offset_in_dwz == ofs_rhs->offset_in_dwz);
2150 }
2151
2152 \f
2153 #if WORDS_BIGENDIAN
2154
2155 /* Convert VALUE between big- and little-endian.  */
2156 static offset_type
2157 byte_swap (offset_type value)
2158 {
2159   offset_type result;
2160
2161   result = (value & 0xff) << 24;
2162   result |= (value & 0xff00) << 8;
2163   result |= (value & 0xff0000) >> 8;
2164   result |= (value & 0xff000000) >> 24;
2165   return result;
2166 }
2167
2168 #define MAYBE_SWAP(V)  byte_swap (V)
2169
2170 #else
2171 #define MAYBE_SWAP(V) static_cast<offset_type> (V)
2172 #endif /* WORDS_BIGENDIAN */
2173
2174 /* Read the given attribute value as an address, taking the attribute's
2175    form into account.  */
2176
2177 static CORE_ADDR
2178 attr_value_as_address (struct attribute *attr)
2179 {
2180   CORE_ADDR addr;
2181
2182   if (attr->form != DW_FORM_addr && attr->form != DW_FORM_GNU_addr_index)
2183     {
2184       /* Aside from a few clearly defined exceptions, attributes that
2185          contain an address must always be in DW_FORM_addr form.
2186          Unfortunately, some compilers happen to be violating this
2187          requirement by encoding addresses using other forms, such
2188          as DW_FORM_data4 for example.  For those broken compilers,
2189          we try to do our best, without any guarantee of success,
2190          to interpret the address correctly.  It would also be nice
2191          to generate a complaint, but that would require us to maintain
2192          a list of legitimate cases where a non-address form is allowed,
2193          as well as update callers to pass in at least the CU's DWARF
2194          version.  This is more overhead than what we're willing to
2195          expand for a pretty rare case.  */
2196       addr = DW_UNSND (attr);
2197     }
2198   else
2199     addr = DW_ADDR (attr);
2200
2201   return addr;
2202 }
2203
2204 /* The suffix for an index file.  */
2205 #define INDEX_SUFFIX ".gdb-index"
2206
2207 /* See declaration.  */
2208
2209 dwarf2_per_objfile::dwarf2_per_objfile (struct objfile *objfile_,
2210                                         const dwarf2_debug_sections *names)
2211   : objfile (objfile_)
2212 {
2213   if (names == NULL)
2214     names = &dwarf2_elf_names;
2215
2216   bfd *obfd = objfile->obfd;
2217
2218   for (asection *sec = obfd->sections; sec != NULL; sec = sec->next)
2219     locate_sections (obfd, sec, *names);
2220 }
2221
2222 dwarf2_per_objfile::~dwarf2_per_objfile ()
2223 {
2224   /* Cached DIE trees use xmalloc and the comp_unit_obstack.  */
2225   free_cached_comp_units ();
2226
2227   if (quick_file_names_table)
2228     htab_delete (quick_file_names_table);
2229
2230   if (line_header_hash)
2231     htab_delete (line_header_hash);
2232
2233   /* Everything else should be on the objfile obstack.  */
2234 }
2235
2236 /* See declaration.  */
2237
2238 void
2239 dwarf2_per_objfile::free_cached_comp_units ()
2240 {
2241   dwarf2_per_cu_data *per_cu = read_in_chain;
2242   dwarf2_per_cu_data **last_chain = &read_in_chain;
2243   while (per_cu != NULL)
2244     {
2245       dwarf2_per_cu_data *next_cu = per_cu->cu->read_in_chain;
2246
2247       free_heap_comp_unit (per_cu->cu);
2248       *last_chain = next_cu;
2249       per_cu = next_cu;
2250     }
2251 }
2252
2253 /* Try to locate the sections we need for DWARF 2 debugging
2254    information and return true if we have enough to do something.
2255    NAMES points to the dwarf2 section names, or is NULL if the standard
2256    ELF names are used.  */
2257
2258 int
2259 dwarf2_has_info (struct objfile *objfile,
2260                  const struct dwarf2_debug_sections *names)
2261 {
2262   dwarf2_per_objfile = ((struct dwarf2_per_objfile *)
2263                         objfile_data (objfile, dwarf2_objfile_data_key));
2264   if (!dwarf2_per_objfile)
2265     {
2266       /* Initialize per-objfile state.  */
2267       struct dwarf2_per_objfile *data
2268         = XOBNEW (&objfile->objfile_obstack, struct dwarf2_per_objfile);
2269
2270       dwarf2_per_objfile = new (data) struct dwarf2_per_objfile (objfile, names);
2271       set_objfile_data (objfile, dwarf2_objfile_data_key, dwarf2_per_objfile);
2272     }
2273   return (!dwarf2_per_objfile->info.is_virtual
2274           && dwarf2_per_objfile->info.s.section != NULL
2275           && !dwarf2_per_objfile->abbrev.is_virtual
2276           && dwarf2_per_objfile->abbrev.s.section != NULL);
2277 }
2278
2279 /* Return the containing section of virtual section SECTION.  */
2280
2281 static struct dwarf2_section_info *
2282 get_containing_section (const struct dwarf2_section_info *section)
2283 {
2284   gdb_assert (section->is_virtual);
2285   return section->s.containing_section;
2286 }
2287
2288 /* Return the bfd owner of SECTION.  */
2289
2290 static struct bfd *
2291 get_section_bfd_owner (const struct dwarf2_section_info *section)
2292 {
2293   if (section->is_virtual)
2294     {
2295       section = get_containing_section (section);
2296       gdb_assert (!section->is_virtual);
2297     }
2298   return section->s.section->owner;
2299 }
2300
2301 /* Return the bfd section of SECTION.
2302    Returns NULL if the section is not present.  */
2303
2304 static asection *
2305 get_section_bfd_section (const struct dwarf2_section_info *section)
2306 {
2307   if (section->is_virtual)
2308     {
2309       section = get_containing_section (section);
2310       gdb_assert (!section->is_virtual);
2311     }
2312   return section->s.section;
2313 }
2314
2315 /* Return the name of SECTION.  */
2316
2317 static const char *
2318 get_section_name (const struct dwarf2_section_info *section)
2319 {
2320   asection *sectp = get_section_bfd_section (section);
2321
2322   gdb_assert (sectp != NULL);
2323   return bfd_section_name (get_section_bfd_owner (section), sectp);
2324 }
2325
2326 /* Return the name of the file SECTION is in.  */
2327
2328 static const char *
2329 get_section_file_name (const struct dwarf2_section_info *section)
2330 {
2331   bfd *abfd = get_section_bfd_owner (section);
2332
2333   return bfd_get_filename (abfd);
2334 }
2335
2336 /* Return the id of SECTION.
2337    Returns 0 if SECTION doesn't exist.  */
2338
2339 static int
2340 get_section_id (const struct dwarf2_section_info *section)
2341 {
2342   asection *sectp = get_section_bfd_section (section);
2343
2344   if (sectp == NULL)
2345     return 0;
2346   return sectp->id;
2347 }
2348
2349 /* Return the flags of SECTION.
2350    SECTION (or containing section if this is a virtual section) must exist.  */
2351
2352 static int
2353 get_section_flags (const struct dwarf2_section_info *section)
2354 {
2355   asection *sectp = get_section_bfd_section (section);
2356
2357   gdb_assert (sectp != NULL);
2358   return bfd_get_section_flags (sectp->owner, sectp);
2359 }
2360
2361 /* When loading sections, we look either for uncompressed section or for
2362    compressed section names.  */
2363
2364 static int
2365 section_is_p (const char *section_name,
2366               const struct dwarf2_section_names *names)
2367 {
2368   if (names->normal != NULL
2369       && strcmp (section_name, names->normal) == 0)
2370     return 1;
2371   if (names->compressed != NULL
2372       && strcmp (section_name, names->compressed) == 0)
2373     return 1;
2374   return 0;
2375 }
2376
2377 /* See declaration.  */
2378
2379 void
2380 dwarf2_per_objfile::locate_sections (bfd *abfd, asection *sectp,
2381                                      const dwarf2_debug_sections &names)
2382 {
2383   flagword aflag = bfd_get_section_flags (abfd, sectp);
2384
2385   if ((aflag & SEC_HAS_CONTENTS) == 0)
2386     {
2387     }
2388   else if (section_is_p (sectp->name, &names.info))
2389     {
2390       this->info.s.section = sectp;
2391       this->info.size = bfd_get_section_size (sectp);
2392     }
2393   else if (section_is_p (sectp->name, &names.abbrev))
2394     {
2395       this->abbrev.s.section = sectp;
2396       this->abbrev.size = bfd_get_section_size (sectp);
2397     }
2398   else if (section_is_p (sectp->name, &names.line))
2399     {
2400       this->line.s.section = sectp;
2401       this->line.size = bfd_get_section_size (sectp);
2402     }
2403   else if (section_is_p (sectp->name, &names.loc))
2404     {
2405       this->loc.s.section = sectp;
2406       this->loc.size = bfd_get_section_size (sectp);
2407     }
2408   else if (section_is_p (sectp->name, &names.loclists))
2409     {
2410       this->loclists.s.section = sectp;
2411       this->loclists.size = bfd_get_section_size (sectp);
2412     }
2413   else if (section_is_p (sectp->name, &names.macinfo))
2414     {
2415       this->macinfo.s.section = sectp;
2416       this->macinfo.size = bfd_get_section_size (sectp);
2417     }
2418   else if (section_is_p (sectp->name, &names.macro))
2419     {
2420       this->macro.s.section = sectp;
2421       this->macro.size = bfd_get_section_size (sectp);
2422     }
2423   else if (section_is_p (sectp->name, &names.str))
2424     {
2425       this->str.s.section = sectp;
2426       this->str.size = bfd_get_section_size (sectp);
2427     }
2428   else if (section_is_p (sectp->name, &names.line_str))
2429     {
2430       this->line_str.s.section = sectp;
2431       this->line_str.size = bfd_get_section_size (sectp);
2432     }
2433   else if (section_is_p (sectp->name, &names.addr))
2434     {
2435       this->addr.s.section = sectp;
2436       this->addr.size = bfd_get_section_size (sectp);
2437     }
2438   else if (section_is_p (sectp->name, &names.frame))
2439     {
2440       this->frame.s.section = sectp;
2441       this->frame.size = bfd_get_section_size (sectp);
2442     }
2443   else if (section_is_p (sectp->name, &names.eh_frame))
2444     {
2445       this->eh_frame.s.section = sectp;
2446       this->eh_frame.size = bfd_get_section_size (sectp);
2447     }
2448   else if (section_is_p (sectp->name, &names.ranges))
2449     {
2450       this->ranges.s.section = sectp;
2451       this->ranges.size = bfd_get_section_size (sectp);
2452     }
2453   else if (section_is_p (sectp->name, &names.rnglists))
2454     {
2455       this->rnglists.s.section = sectp;
2456       this->rnglists.size = bfd_get_section_size (sectp);
2457     }
2458   else if (section_is_p (sectp->name, &names.types))
2459     {
2460       struct dwarf2_section_info type_section;
2461
2462       memset (&type_section, 0, sizeof (type_section));
2463       type_section.s.section = sectp;
2464       type_section.size = bfd_get_section_size (sectp);
2465
2466       VEC_safe_push (dwarf2_section_info_def, this->types,
2467                      &type_section);
2468     }
2469   else if (section_is_p (sectp->name, &names.gdb_index))
2470     {
2471       this->gdb_index.s.section = sectp;
2472       this->gdb_index.size = bfd_get_section_size (sectp);
2473     }
2474
2475   if ((bfd_get_section_flags (abfd, sectp) & (SEC_LOAD | SEC_ALLOC))
2476       && bfd_section_vma (abfd, sectp) == 0)
2477     this->has_section_at_zero = true;
2478 }
2479
2480 /* A helper function that decides whether a section is empty,
2481    or not present.  */
2482
2483 static int
2484 dwarf2_section_empty_p (const struct dwarf2_section_info *section)
2485 {
2486   if (section->is_virtual)
2487     return section->size == 0;
2488   return section->s.section == NULL || section->size == 0;
2489 }
2490
2491 /* Read the contents of the section INFO.
2492    OBJFILE is the main object file, but not necessarily the file where
2493    the section comes from.  E.g., for DWO files the bfd of INFO is the bfd
2494    of the DWO file.
2495    If the section is compressed, uncompress it before returning.  */
2496
2497 static void
2498 dwarf2_read_section (struct objfile *objfile, struct dwarf2_section_info *info)
2499 {
2500   asection *sectp;
2501   bfd *abfd;
2502   gdb_byte *buf, *retbuf;
2503
2504   if (info->readin)
2505     return;
2506   info->buffer = NULL;
2507   info->readin = 1;
2508
2509   if (dwarf2_section_empty_p (info))
2510     return;
2511
2512   sectp = get_section_bfd_section (info);
2513
2514   /* If this is a virtual section we need to read in the real one first.  */
2515   if (info->is_virtual)
2516     {
2517       struct dwarf2_section_info *containing_section =
2518         get_containing_section (info);
2519
2520       gdb_assert (sectp != NULL);
2521       if ((sectp->flags & SEC_RELOC) != 0)
2522         {
2523           error (_("Dwarf Error: DWP format V2 with relocations is not"
2524                    " supported in section %s [in module %s]"),
2525                  get_section_name (info), get_section_file_name (info));
2526         }
2527       dwarf2_read_section (objfile, containing_section);
2528       /* Other code should have already caught virtual sections that don't
2529          fit.  */
2530       gdb_assert (info->virtual_offset + info->size
2531                   <= containing_section->size);
2532       /* If the real section is empty or there was a problem reading the
2533          section we shouldn't get here.  */
2534       gdb_assert (containing_section->buffer != NULL);
2535       info->buffer = containing_section->buffer + info->virtual_offset;
2536       return;
2537     }
2538
2539   /* If the section has relocations, we must read it ourselves.
2540      Otherwise we attach it to the BFD.  */
2541   if ((sectp->flags & SEC_RELOC) == 0)
2542     {
2543       info->buffer = gdb_bfd_map_section (sectp, &info->size);
2544       return;
2545     }
2546
2547   buf = (gdb_byte *) obstack_alloc (&objfile->objfile_obstack, info->size);
2548   info->buffer = buf;
2549
2550   /* When debugging .o files, we may need to apply relocations; see
2551      http://sourceware.org/ml/gdb-patches/2002-04/msg00136.html .
2552      We never compress sections in .o files, so we only need to
2553      try this when the section is not compressed.  */
2554   retbuf = symfile_relocate_debug_section (objfile, sectp, buf);
2555   if (retbuf != NULL)
2556     {
2557       info->buffer = retbuf;
2558       return;
2559     }
2560
2561   abfd = get_section_bfd_owner (info);
2562   gdb_assert (abfd != NULL);
2563
2564   if (bfd_seek (abfd, sectp->filepos, SEEK_SET) != 0
2565       || bfd_bread (buf, info->size, abfd) != info->size)
2566     {
2567       error (_("Dwarf Error: Can't read DWARF data"
2568                " in section %s [in module %s]"),
2569              bfd_section_name (abfd, sectp), bfd_get_filename (abfd));
2570     }
2571 }
2572
2573 /* A helper function that returns the size of a section in a safe way.
2574    If you are positive that the section has been read before using the
2575    size, then it is safe to refer to the dwarf2_section_info object's
2576    "size" field directly.  In other cases, you must call this
2577    function, because for compressed sections the size field is not set
2578    correctly until the section has been read.  */
2579
2580 static bfd_size_type
2581 dwarf2_section_size (struct objfile *objfile,
2582                      struct dwarf2_section_info *info)
2583 {
2584   if (!info->readin)
2585     dwarf2_read_section (objfile, info);
2586   return info->size;
2587 }
2588
2589 /* Fill in SECTP, BUFP and SIZEP with section info, given OBJFILE and
2590    SECTION_NAME.  */
2591
2592 void
2593 dwarf2_get_section_info (struct objfile *objfile,
2594                          enum dwarf2_section_enum sect,
2595                          asection **sectp, const gdb_byte **bufp,
2596                          bfd_size_type *sizep)
2597 {
2598   struct dwarf2_per_objfile *data
2599     = (struct dwarf2_per_objfile *) objfile_data (objfile,
2600                                                   dwarf2_objfile_data_key);
2601   struct dwarf2_section_info *info;
2602
2603   /* We may see an objfile without any DWARF, in which case we just
2604      return nothing.  */
2605   if (data == NULL)
2606     {
2607       *sectp = NULL;
2608       *bufp = NULL;
2609       *sizep = 0;
2610       return;
2611     }
2612   switch (sect)
2613     {
2614     case DWARF2_DEBUG_FRAME:
2615       info = &data->frame;
2616       break;
2617     case DWARF2_EH_FRAME:
2618       info = &data->eh_frame;
2619       break;
2620     default:
2621       gdb_assert_not_reached ("unexpected section");
2622     }
2623
2624   dwarf2_read_section (objfile, info);
2625
2626   *sectp = get_section_bfd_section (info);
2627   *bufp = info->buffer;
2628   *sizep = info->size;
2629 }
2630
2631 /* A helper function to find the sections for a .dwz file.  */
2632
2633 static void
2634 locate_dwz_sections (bfd *abfd, asection *sectp, void *arg)
2635 {
2636   struct dwz_file *dwz_file = (struct dwz_file *) arg;
2637
2638   /* Note that we only support the standard ELF names, because .dwz
2639      is ELF-only (at the time of writing).  */
2640   if (section_is_p (sectp->name, &dwarf2_elf_names.abbrev))
2641     {
2642       dwz_file->abbrev.s.section = sectp;
2643       dwz_file->abbrev.size = bfd_get_section_size (sectp);
2644     }
2645   else if (section_is_p (sectp->name, &dwarf2_elf_names.info))
2646     {
2647       dwz_file->info.s.section = sectp;
2648       dwz_file->info.size = bfd_get_section_size (sectp);
2649     }
2650   else if (section_is_p (sectp->name, &dwarf2_elf_names.str))
2651     {
2652       dwz_file->str.s.section = sectp;
2653       dwz_file->str.size = bfd_get_section_size (sectp);
2654     }
2655   else if (section_is_p (sectp->name, &dwarf2_elf_names.line))
2656     {
2657       dwz_file->line.s.section = sectp;
2658       dwz_file->line.size = bfd_get_section_size (sectp);
2659     }
2660   else if (section_is_p (sectp->name, &dwarf2_elf_names.macro))
2661     {
2662       dwz_file->macro.s.section = sectp;
2663       dwz_file->macro.size = bfd_get_section_size (sectp);
2664     }
2665   else if (section_is_p (sectp->name, &dwarf2_elf_names.gdb_index))
2666     {
2667       dwz_file->gdb_index.s.section = sectp;
2668       dwz_file->gdb_index.size = bfd_get_section_size (sectp);
2669     }
2670 }
2671
2672 /* Open the separate '.dwz' debug file, if needed.  Return NULL if
2673    there is no .gnu_debugaltlink section in the file.  Error if there
2674    is such a section but the file cannot be found.  */
2675
2676 static struct dwz_file *
2677 dwarf2_get_dwz_file (void)
2678 {
2679   char *data;
2680   struct cleanup *cleanup;
2681   const char *filename;
2682   struct dwz_file *result;
2683   bfd_size_type buildid_len_arg;
2684   size_t buildid_len;
2685   bfd_byte *buildid;
2686
2687   if (dwarf2_per_objfile->dwz_file != NULL)
2688     return dwarf2_per_objfile->dwz_file;
2689
2690   bfd_set_error (bfd_error_no_error);
2691   data = bfd_get_alt_debug_link_info (dwarf2_per_objfile->objfile->obfd,
2692                                       &buildid_len_arg, &buildid);
2693   if (data == NULL)
2694     {
2695       if (bfd_get_error () == bfd_error_no_error)
2696         return NULL;
2697       error (_("could not read '.gnu_debugaltlink' section: %s"),
2698              bfd_errmsg (bfd_get_error ()));
2699     }
2700   cleanup = make_cleanup (xfree, data);
2701   make_cleanup (xfree, buildid);
2702
2703   buildid_len = (size_t) buildid_len_arg;
2704
2705   filename = (const char *) data;
2706
2707   std::string abs_storage;
2708   if (!IS_ABSOLUTE_PATH (filename))
2709     {
2710       char *abs = gdb_realpath (objfile_name (dwarf2_per_objfile->objfile));
2711
2712       make_cleanup (xfree, abs);
2713       abs_storage = ldirname (abs) + SLASH_STRING + filename;
2714       filename = abs_storage.c_str ();
2715     }
2716
2717   /* First try the file name given in the section.  If that doesn't
2718      work, try to use the build-id instead.  */
2719   gdb_bfd_ref_ptr dwz_bfd (gdb_bfd_open (filename, gnutarget, -1));
2720   if (dwz_bfd != NULL)
2721     {
2722       if (!build_id_verify (dwz_bfd.get (), buildid_len, buildid))
2723         dwz_bfd.release ();
2724     }
2725
2726   if (dwz_bfd == NULL)
2727     dwz_bfd = build_id_to_debug_bfd (buildid_len, buildid);
2728
2729   if (dwz_bfd == NULL)
2730     error (_("could not find '.gnu_debugaltlink' file for %s"),
2731            objfile_name (dwarf2_per_objfile->objfile));
2732
2733   result = OBSTACK_ZALLOC (&dwarf2_per_objfile->objfile->objfile_obstack,
2734                            struct dwz_file);
2735   result->dwz_bfd = dwz_bfd.release ();
2736
2737   bfd_map_over_sections (result->dwz_bfd, locate_dwz_sections, result);
2738
2739   do_cleanups (cleanup);
2740
2741   gdb_bfd_record_inclusion (dwarf2_per_objfile->objfile->obfd, result->dwz_bfd);
2742   dwarf2_per_objfile->dwz_file = result;
2743   return result;
2744 }
2745 \f
2746 /* DWARF quick_symbols_functions support.  */
2747
2748 /* TUs can share .debug_line entries, and there can be a lot more TUs than
2749    unique line tables, so we maintain a separate table of all .debug_line
2750    derived entries to support the sharing.
2751    All the quick functions need is the list of file names.  We discard the
2752    line_header when we're done and don't need to record it here.  */
2753 struct quick_file_names
2754 {
2755   /* The data used to construct the hash key.  */
2756   struct stmt_list_hash hash;
2757
2758   /* The number of entries in file_names, real_names.  */
2759   unsigned int num_file_names;
2760
2761   /* The file names from the line table, after being run through
2762      file_full_name.  */
2763   const char **file_names;
2764
2765   /* The file names from the line table after being run through
2766      gdb_realpath.  These are computed lazily.  */
2767   const char **real_names;
2768 };
2769
2770 /* When using the index (and thus not using psymtabs), each CU has an
2771    object of this type.  This is used to hold information needed by
2772    the various "quick" methods.  */
2773 struct dwarf2_per_cu_quick_data
2774 {
2775   /* The file table.  This can be NULL if there was no file table
2776      or it's currently not read in.
2777      NOTE: This points into dwarf2_per_objfile->quick_file_names_table.  */
2778   struct quick_file_names *file_names;
2779
2780   /* The corresponding symbol table.  This is NULL if symbols for this
2781      CU have not yet been read.  */
2782   struct compunit_symtab *compunit_symtab;
2783
2784   /* A temporary mark bit used when iterating over all CUs in
2785      expand_symtabs_matching.  */
2786   unsigned int mark : 1;
2787
2788   /* True if we've tried to read the file table and found there isn't one.
2789      There will be no point in trying to read it again next time.  */
2790   unsigned int no_file_data : 1;
2791 };
2792
2793 /* Utility hash function for a stmt_list_hash.  */
2794
2795 static hashval_t
2796 hash_stmt_list_entry (const struct stmt_list_hash *stmt_list_hash)
2797 {
2798   hashval_t v = 0;
2799
2800   if (stmt_list_hash->dwo_unit != NULL)
2801     v += (uintptr_t) stmt_list_hash->dwo_unit->dwo_file;
2802   v += to_underlying (stmt_list_hash->line_sect_off);
2803   return v;
2804 }
2805
2806 /* Utility equality function for a stmt_list_hash.  */
2807
2808 static int
2809 eq_stmt_list_entry (const struct stmt_list_hash *lhs,
2810                     const struct stmt_list_hash *rhs)
2811 {
2812   if ((lhs->dwo_unit != NULL) != (rhs->dwo_unit != NULL))
2813     return 0;
2814   if (lhs->dwo_unit != NULL
2815       && lhs->dwo_unit->dwo_file != rhs->dwo_unit->dwo_file)
2816     return 0;
2817
2818   return lhs->line_sect_off == rhs->line_sect_off;
2819 }
2820
2821 /* Hash function for a quick_file_names.  */
2822
2823 static hashval_t
2824 hash_file_name_entry (const void *e)
2825 {
2826   const struct quick_file_names *file_data
2827     = (const struct quick_file_names *) e;
2828
2829   return hash_stmt_list_entry (&file_data->hash);
2830 }
2831
2832 /* Equality function for a quick_file_names.  */
2833
2834 static int
2835 eq_file_name_entry (const void *a, const void *b)
2836 {
2837   const struct quick_file_names *ea = (const struct quick_file_names *) a;
2838   const struct quick_file_names *eb = (const struct quick_file_names *) b;
2839
2840   return eq_stmt_list_entry (&ea->hash, &eb->hash);
2841 }
2842
2843 /* Delete function for a quick_file_names.  */
2844
2845 static void
2846 delete_file_name_entry (void *e)
2847 {
2848   struct quick_file_names *file_data = (struct quick_file_names *) e;
2849   int i;
2850
2851   for (i = 0; i < file_data->num_file_names; ++i)
2852     {
2853       xfree ((void*) file_data->file_names[i]);
2854       if (file_data->real_names)
2855         xfree ((void*) file_data->real_names[i]);
2856     }
2857
2858   /* The space for the struct itself lives on objfile_obstack,
2859      so we don't free it here.  */
2860 }
2861
2862 /* Create a quick_file_names hash table.  */
2863
2864 static htab_t
2865 create_quick_file_names_table (unsigned int nr_initial_entries)
2866 {
2867   return htab_create_alloc (nr_initial_entries,
2868                             hash_file_name_entry, eq_file_name_entry,
2869                             delete_file_name_entry, xcalloc, xfree);
2870 }
2871
2872 /* Read in PER_CU->CU.  This function is unrelated to symtabs, symtab would
2873    have to be created afterwards.  You should call age_cached_comp_units after
2874    processing PER_CU->CU.  dw2_setup must have been already called.  */
2875
2876 static void
2877 load_cu (struct dwarf2_per_cu_data *per_cu)
2878 {
2879   if (per_cu->is_debug_types)
2880     load_full_type_unit (per_cu);
2881   else
2882     load_full_comp_unit (per_cu, language_minimal);
2883
2884   if (per_cu->cu == NULL)
2885     return;  /* Dummy CU.  */
2886
2887   dwarf2_find_base_address (per_cu->cu->dies, per_cu->cu);
2888 }
2889
2890 /* Read in the symbols for PER_CU.  */
2891
2892 static void
2893 dw2_do_instantiate_symtab (struct dwarf2_per_cu_data *per_cu)
2894 {
2895   struct cleanup *back_to;
2896
2897   /* Skip type_unit_groups, reading the type units they contain
2898      is handled elsewhere.  */
2899   if (IS_TYPE_UNIT_GROUP (per_cu))
2900     return;
2901
2902   back_to = make_cleanup (dwarf2_release_queue, NULL);
2903
2904   if (dwarf2_per_objfile->using_index
2905       ? per_cu->v.quick->compunit_symtab == NULL
2906       : (per_cu->v.psymtab == NULL || !per_cu->v.psymtab->readin))
2907     {
2908       queue_comp_unit (per_cu, language_minimal);
2909       load_cu (per_cu);
2910
2911       /* If we just loaded a CU from a DWO, and we're working with an index
2912          that may badly handle TUs, load all the TUs in that DWO as well.
2913          http://sourceware.org/bugzilla/show_bug.cgi?id=15021  */
2914       if (!per_cu->is_debug_types
2915           && per_cu->cu != NULL
2916           && per_cu->cu->dwo_unit != NULL
2917           && dwarf2_per_objfile->index_table != NULL
2918           && dwarf2_per_objfile->index_table->version <= 7
2919           /* DWP files aren't supported yet.  */
2920           && get_dwp_file () == NULL)
2921         queue_and_load_all_dwo_tus (per_cu);
2922     }
2923
2924   process_queue ();
2925
2926   /* Age the cache, releasing compilation units that have not
2927      been used recently.  */
2928   age_cached_comp_units ();
2929
2930   do_cleanups (back_to);
2931 }
2932
2933 /* Ensure that the symbols for PER_CU have been read in.  OBJFILE is
2934    the objfile from which this CU came.  Returns the resulting symbol
2935    table.  */
2936
2937 static struct compunit_symtab *
2938 dw2_instantiate_symtab (struct dwarf2_per_cu_data *per_cu)
2939 {
2940   gdb_assert (dwarf2_per_objfile->using_index);
2941   if (!per_cu->v.quick->compunit_symtab)
2942     {
2943       struct cleanup *back_to = make_cleanup (free_cached_comp_units, NULL);
2944       scoped_restore decrementer = increment_reading_symtab ();
2945       dw2_do_instantiate_symtab (per_cu);
2946       process_cu_includes ();
2947       do_cleanups (back_to);
2948     }
2949
2950   return per_cu->v.quick->compunit_symtab;
2951 }
2952
2953 /* Return the CU/TU given its index.
2954
2955    This is intended for loops like:
2956
2957    for (i = 0; i < (dwarf2_per_objfile->n_comp_units
2958                     + dwarf2_per_objfile->n_type_units); ++i)
2959      {
2960        struct dwarf2_per_cu_data *per_cu = dw2_get_cutu (i);
2961
2962        ...;
2963      }
2964 */
2965
2966 static struct dwarf2_per_cu_data *
2967 dw2_get_cutu (int index)
2968 {
2969   if (index >= dwarf2_per_objfile->n_comp_units)
2970     {
2971       index -= dwarf2_per_objfile->n_comp_units;
2972       gdb_assert (index < dwarf2_per_objfile->n_type_units);
2973       return &dwarf2_per_objfile->all_type_units[index]->per_cu;
2974     }
2975
2976   return dwarf2_per_objfile->all_comp_units[index];
2977 }
2978
2979 /* Return the CU given its index.
2980    This differs from dw2_get_cutu in that it's for when you know INDEX
2981    refers to a CU.  */
2982
2983 static struct dwarf2_per_cu_data *
2984 dw2_get_cu (int index)
2985 {
2986   gdb_assert (index >= 0 && index < dwarf2_per_objfile->n_comp_units);
2987
2988   return dwarf2_per_objfile->all_comp_units[index];
2989 }
2990
2991 /* A helper for create_cus_from_index that handles a given list of
2992    CUs.  */
2993
2994 static void
2995 create_cus_from_index_list (struct objfile *objfile,
2996                             const gdb_byte *cu_list, offset_type n_elements,
2997                             struct dwarf2_section_info *section,
2998                             int is_dwz,
2999                             int base_offset)
3000 {
3001   offset_type i;
3002
3003   for (i = 0; i < n_elements; i += 2)
3004     {
3005       gdb_static_assert (sizeof (ULONGEST) >= 8);
3006
3007       sect_offset sect_off
3008         = (sect_offset) extract_unsigned_integer (cu_list, 8, BFD_ENDIAN_LITTLE);
3009       ULONGEST length = extract_unsigned_integer (cu_list + 8, 8, BFD_ENDIAN_LITTLE);
3010       cu_list += 2 * 8;
3011
3012       dwarf2_per_cu_data *the_cu
3013         = OBSTACK_ZALLOC (&objfile->objfile_obstack,
3014                           struct dwarf2_per_cu_data);
3015       the_cu->sect_off = sect_off;
3016       the_cu->length = length;
3017       the_cu->objfile = objfile;
3018       the_cu->section = section;
3019       the_cu->v.quick = OBSTACK_ZALLOC (&objfile->objfile_obstack,
3020                                         struct dwarf2_per_cu_quick_data);
3021       the_cu->is_dwz = is_dwz;
3022       dwarf2_per_objfile->all_comp_units[base_offset + i / 2] = the_cu;
3023     }
3024 }
3025
3026 /* Read the CU list from the mapped index, and use it to create all
3027    the CU objects for this objfile.  */
3028
3029 static void
3030 create_cus_from_index (struct objfile *objfile,
3031                        const gdb_byte *cu_list, offset_type cu_list_elements,
3032                        const gdb_byte *dwz_list, offset_type dwz_elements)
3033 {
3034   struct dwz_file *dwz;
3035
3036   dwarf2_per_objfile->n_comp_units = (cu_list_elements + dwz_elements) / 2;
3037   dwarf2_per_objfile->all_comp_units =
3038     XOBNEWVEC (&objfile->objfile_obstack, struct dwarf2_per_cu_data *,
3039                dwarf2_per_objfile->n_comp_units);
3040
3041   create_cus_from_index_list (objfile, cu_list, cu_list_elements,
3042                               &dwarf2_per_objfile->info, 0, 0);
3043
3044   if (dwz_elements == 0)
3045     return;
3046
3047   dwz = dwarf2_get_dwz_file ();
3048   create_cus_from_index_list (objfile, dwz_list, dwz_elements, &dwz->info, 1,
3049                               cu_list_elements / 2);
3050 }
3051
3052 /* Create the signatured type hash table from the index.  */
3053
3054 static void
3055 create_signatured_type_table_from_index (struct objfile *objfile,
3056                                          struct dwarf2_section_info *section,
3057                                          const gdb_byte *bytes,
3058                                          offset_type elements)
3059 {
3060   offset_type i;
3061   htab_t sig_types_hash;
3062
3063   dwarf2_per_objfile->n_type_units
3064     = dwarf2_per_objfile->n_allocated_type_units
3065     = elements / 3;
3066   dwarf2_per_objfile->all_type_units =
3067     XNEWVEC (struct signatured_type *, dwarf2_per_objfile->n_type_units);
3068
3069   sig_types_hash = allocate_signatured_type_table (objfile);
3070
3071   for (i = 0; i < elements; i += 3)
3072     {
3073       struct signatured_type *sig_type;
3074       ULONGEST signature;
3075       void **slot;
3076       cu_offset type_offset_in_tu;
3077
3078       gdb_static_assert (sizeof (ULONGEST) >= 8);
3079       sect_offset sect_off
3080         = (sect_offset) extract_unsigned_integer (bytes, 8, BFD_ENDIAN_LITTLE);
3081       type_offset_in_tu
3082         = (cu_offset) extract_unsigned_integer (bytes + 8, 8,
3083                                                 BFD_ENDIAN_LITTLE);
3084       signature = extract_unsigned_integer (bytes + 16, 8, BFD_ENDIAN_LITTLE);
3085       bytes += 3 * 8;
3086
3087       sig_type = OBSTACK_ZALLOC (&objfile->objfile_obstack,
3088                                  struct signatured_type);
3089       sig_type->signature = signature;
3090       sig_type->type_offset_in_tu = type_offset_in_tu;
3091       sig_type->per_cu.is_debug_types = 1;
3092       sig_type->per_cu.section = section;
3093       sig_type->per_cu.sect_off = sect_off;
3094       sig_type->per_cu.objfile = objfile;
3095       sig_type->per_cu.v.quick
3096         = OBSTACK_ZALLOC (&objfile->objfile_obstack,
3097                           struct dwarf2_per_cu_quick_data);
3098
3099       slot = htab_find_slot (sig_types_hash, sig_type, INSERT);
3100       *slot = sig_type;
3101
3102       dwarf2_per_objfile->all_type_units[i / 3] = sig_type;
3103     }
3104
3105   dwarf2_per_objfile->signatured_types = sig_types_hash;
3106 }
3107
3108 /* Read the address map data from the mapped index, and use it to
3109    populate the objfile's psymtabs_addrmap.  */
3110
3111 static void
3112 create_addrmap_from_index (struct objfile *objfile, struct mapped_index *index)
3113 {
3114   struct gdbarch *gdbarch = get_objfile_arch (objfile);
3115   const gdb_byte *iter, *end;
3116   struct addrmap *mutable_map;
3117   CORE_ADDR baseaddr;
3118
3119   auto_obstack temp_obstack;
3120
3121   mutable_map = addrmap_create_mutable (&temp_obstack);
3122
3123   iter = index->address_table;
3124   end = iter + index->address_table_size;
3125
3126   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
3127
3128   while (iter < end)
3129     {
3130       ULONGEST hi, lo, cu_index;
3131       lo = extract_unsigned_integer (iter, 8, BFD_ENDIAN_LITTLE);
3132       iter += 8;
3133       hi = extract_unsigned_integer (iter, 8, BFD_ENDIAN_LITTLE);
3134       iter += 8;
3135       cu_index = extract_unsigned_integer (iter, 4, BFD_ENDIAN_LITTLE);
3136       iter += 4;
3137
3138       if (lo > hi)
3139         {
3140           complaint (&symfile_complaints,
3141                      _(".gdb_index address table has invalid range (%s - %s)"),
3142                      hex_string (lo), hex_string (hi));
3143           continue;
3144         }
3145
3146       if (cu_index >= dwarf2_per_objfile->n_comp_units)
3147         {
3148           complaint (&symfile_complaints,
3149                      _(".gdb_index address table has invalid CU number %u"),
3150                      (unsigned) cu_index);
3151           continue;
3152         }
3153
3154       lo = gdbarch_adjust_dwarf2_addr (gdbarch, lo + baseaddr);
3155       hi = gdbarch_adjust_dwarf2_addr (gdbarch, hi + baseaddr);
3156       addrmap_set_empty (mutable_map, lo, hi - 1, dw2_get_cutu (cu_index));
3157     }
3158
3159   objfile->psymtabs_addrmap = addrmap_create_fixed (mutable_map,
3160                                                     &objfile->objfile_obstack);
3161 }
3162
3163 /* The hash function for strings in the mapped index.  This is the same as
3164    SYMBOL_HASH_NEXT, but we keep a separate copy to maintain control over the
3165    implementation.  This is necessary because the hash function is tied to the
3166    format of the mapped index file.  The hash values do not have to match with
3167    SYMBOL_HASH_NEXT.
3168    
3169    Use INT_MAX for INDEX_VERSION if you generate the current index format.  */
3170
3171 static hashval_t
3172 mapped_index_string_hash (int index_version, const void *p)
3173 {
3174   const unsigned char *str = (const unsigned char *) p;
3175   hashval_t r = 0;
3176   unsigned char c;
3177
3178   while ((c = *str++) != 0)
3179     {
3180       if (index_version >= 5)
3181         c = tolower (c);
3182       r = r * 67 + c - 113;
3183     }
3184
3185   return r;
3186 }
3187
3188 /* Find a slot in the mapped index INDEX for the object named NAME.
3189    If NAME is found, set *VEC_OUT to point to the CU vector in the
3190    constant pool and return 1.  If NAME cannot be found, return 0.  */
3191
3192 static int
3193 find_slot_in_mapped_hash (struct mapped_index *index, const char *name,
3194                           offset_type **vec_out)
3195 {
3196   struct cleanup *back_to = make_cleanup (null_cleanup, 0);
3197   offset_type hash;
3198   offset_type slot, step;
3199   int (*cmp) (const char *, const char *);
3200
3201   if (current_language->la_language == language_cplus
3202       || current_language->la_language == language_fortran
3203       || current_language->la_language == language_d)
3204     {
3205       /* NAME is already canonical.  Drop any qualifiers as .gdb_index does
3206          not contain any.  */
3207
3208       if (strchr (name, '(') != NULL)
3209         {
3210           char *without_params = cp_remove_params (name);
3211
3212           if (without_params != NULL)
3213             {
3214               make_cleanup (xfree, without_params);
3215               name = without_params;
3216             }
3217         }
3218     }
3219
3220   /* Index version 4 did not support case insensitive searches.  But the
3221      indices for case insensitive languages are built in lowercase, therefore
3222      simulate our NAME being searched is also lowercased.  */
3223   hash = mapped_index_string_hash ((index->version == 4
3224                                     && case_sensitivity == case_sensitive_off
3225                                     ? 5 : index->version),
3226                                    name);
3227
3228   slot = hash & (index->symbol_table_slots - 1);
3229   step = ((hash * 17) & (index->symbol_table_slots - 1)) | 1;
3230   cmp = (case_sensitivity == case_sensitive_on ? strcmp : strcasecmp);
3231
3232   for (;;)
3233     {
3234       /* Convert a slot number to an offset into the table.  */
3235       offset_type i = 2 * slot;
3236       const char *str;
3237       if (index->symbol_table[i] == 0 && index->symbol_table[i + 1] == 0)
3238         {
3239           do_cleanups (back_to);
3240           return 0;
3241         }
3242
3243       str = index->constant_pool + MAYBE_SWAP (index->symbol_table[i]);
3244       if (!cmp (name, str))
3245         {
3246           *vec_out = (offset_type *) (index->constant_pool
3247                                       + MAYBE_SWAP (index->symbol_table[i + 1]));
3248           do_cleanups (back_to);
3249           return 1;
3250         }
3251
3252       slot = (slot + step) & (index->symbol_table_slots - 1);
3253     }
3254 }
3255
3256 /* A helper function that reads the .gdb_index from SECTION and fills
3257    in MAP.  FILENAME is the name of the file containing the section;
3258    it is used for error reporting.  DEPRECATED_OK is nonzero if it is
3259    ok to use deprecated sections.
3260
3261    CU_LIST, CU_LIST_ELEMENTS, TYPES_LIST, and TYPES_LIST_ELEMENTS are
3262    out parameters that are filled in with information about the CU and
3263    TU lists in the section.
3264
3265    Returns 1 if all went well, 0 otherwise.  */
3266
3267 static int
3268 read_index_from_section (struct objfile *objfile,
3269                          const char *filename,
3270                          int deprecated_ok,
3271                          struct dwarf2_section_info *section,
3272                          struct mapped_index *map,
3273                          const gdb_byte **cu_list,
3274                          offset_type *cu_list_elements,
3275                          const gdb_byte **types_list,
3276                          offset_type *types_list_elements)
3277 {
3278   const gdb_byte *addr;
3279   offset_type version;
3280   offset_type *metadata;
3281   int i;
3282
3283   if (dwarf2_section_empty_p (section))
3284     return 0;
3285
3286   /* Older elfutils strip versions could keep the section in the main
3287      executable while splitting it for the separate debug info file.  */
3288   if ((get_section_flags (section) & SEC_HAS_CONTENTS) == 0)
3289     return 0;
3290
3291   dwarf2_read_section (objfile, section);
3292
3293   addr = section->buffer;
3294   /* Version check.  */
3295   version = MAYBE_SWAP (*(offset_type *) addr);
3296   /* Versions earlier than 3 emitted every copy of a psymbol.  This
3297      causes the index to behave very poorly for certain requests.  Version 3
3298      contained incomplete addrmap.  So, it seems better to just ignore such
3299      indices.  */
3300   if (version < 4)
3301     {
3302       static int warning_printed = 0;
3303       if (!warning_printed)
3304         {
3305           warning (_("Skipping obsolete .gdb_index section in %s."),
3306                    filename);
3307           warning_printed = 1;
3308         }
3309       return 0;
3310     }
3311   /* Index version 4 uses a different hash function than index version
3312      5 and later.
3313
3314      Versions earlier than 6 did not emit psymbols for inlined
3315      functions.  Using these files will cause GDB not to be able to
3316      set breakpoints on inlined functions by name, so we ignore these
3317      indices unless the user has done
3318      "set use-deprecated-index-sections on".  */
3319   if (version < 6 && !deprecated_ok)
3320     {
3321       static int warning_printed = 0;
3322       if (!warning_printed)
3323         {
3324           warning (_("\
3325 Skipping deprecated .gdb_index section in %s.\n\
3326 Do \"set use-deprecated-index-sections on\" before the file is read\n\
3327 to use the section anyway."),
3328                    filename);
3329           warning_printed = 1;
3330         }
3331       return 0;
3332     }
3333   /* Version 7 indices generated by gold refer to the CU for a symbol instead
3334      of the TU (for symbols coming from TUs),
3335      http://sourceware.org/bugzilla/show_bug.cgi?id=15021.
3336      Plus gold-generated indices can have duplicate entries for global symbols,
3337      http://sourceware.org/bugzilla/show_bug.cgi?id=15646.
3338      These are just performance bugs, and we can't distinguish gdb-generated
3339      indices from gold-generated ones, so issue no warning here.  */
3340
3341   /* Indexes with higher version than the one supported by GDB may be no
3342      longer backward compatible.  */
3343   if (version > 8)
3344     return 0;
3345
3346   map->version = version;
3347   map->total_size = section->size;
3348
3349   metadata = (offset_type *) (addr + sizeof (offset_type));
3350
3351   i = 0;
3352   *cu_list = addr + MAYBE_SWAP (metadata[i]);
3353   *cu_list_elements = ((MAYBE_SWAP (metadata[i + 1]) - MAYBE_SWAP (metadata[i]))
3354                        / 8);
3355   ++i;
3356
3357   *types_list = addr + MAYBE_SWAP (metadata[i]);
3358   *types_list_elements = ((MAYBE_SWAP (metadata[i + 1])
3359                            - MAYBE_SWAP (metadata[i]))
3360                           / 8);
3361   ++i;
3362
3363   map->address_table = addr + MAYBE_SWAP (metadata[i]);
3364   map->address_table_size = (MAYBE_SWAP (metadata[i + 1])
3365                              - MAYBE_SWAP (metadata[i]));
3366   ++i;
3367
3368   map->symbol_table = (offset_type *) (addr + MAYBE_SWAP (metadata[i]));
3369   map->symbol_table_slots = ((MAYBE_SWAP (metadata[i + 1])
3370                               - MAYBE_SWAP (metadata[i]))
3371                              / (2 * sizeof (offset_type)));
3372   ++i;
3373
3374   map->constant_pool = (char *) (addr + MAYBE_SWAP (metadata[i]));
3375
3376   return 1;
3377 }
3378
3379
3380 /* Read the index file.  If everything went ok, initialize the "quick"
3381    elements of all the CUs and return 1.  Otherwise, return 0.  */
3382
3383 static int
3384 dwarf2_read_index (struct objfile *objfile)
3385 {
3386   struct mapped_index local_map, *map;
3387   const gdb_byte *cu_list, *types_list, *dwz_list = NULL;
3388   offset_type cu_list_elements, types_list_elements, dwz_list_elements = 0;
3389   struct dwz_file *dwz;
3390
3391   if (!read_index_from_section (objfile, objfile_name (objfile),
3392                                 use_deprecated_index_sections,
3393                                 &dwarf2_per_objfile->gdb_index, &local_map,
3394                                 &cu_list, &cu_list_elements,
3395                                 &types_list, &types_list_elements))
3396     return 0;
3397
3398   /* Don't use the index if it's empty.  */
3399   if (local_map.symbol_table_slots == 0)
3400     return 0;
3401
3402   /* If there is a .dwz file, read it so we can get its CU list as
3403      well.  */
3404   dwz = dwarf2_get_dwz_file ();
3405   if (dwz != NULL)
3406     {
3407       struct mapped_index dwz_map;
3408       const gdb_byte *dwz_types_ignore;
3409       offset_type dwz_types_elements_ignore;
3410
3411       if (!read_index_from_section (objfile, bfd_get_filename (dwz->dwz_bfd),
3412                                     1,
3413                                     &dwz->gdb_index, &dwz_map,
3414                                     &dwz_list, &dwz_list_elements,
3415                                     &dwz_types_ignore,
3416                                     &dwz_types_elements_ignore))
3417         {
3418           warning (_("could not read '.gdb_index' section from %s; skipping"),
3419                    bfd_get_filename (dwz->dwz_bfd));
3420           return 0;
3421         }
3422     }
3423
3424   create_cus_from_index (objfile, cu_list, cu_list_elements, dwz_list,
3425                          dwz_list_elements);
3426
3427   if (types_list_elements)
3428     {
3429       struct dwarf2_section_info *section;
3430
3431       /* We can only handle a single .debug_types when we have an
3432          index.  */
3433       if (VEC_length (dwarf2_section_info_def, dwarf2_per_objfile->types) != 1)
3434         return 0;
3435
3436       section = VEC_index (dwarf2_section_info_def,
3437                            dwarf2_per_objfile->types, 0);
3438
3439       create_signatured_type_table_from_index (objfile, section, types_list,
3440                                                types_list_elements);
3441     }
3442
3443   create_addrmap_from_index (objfile, &local_map);
3444
3445   map = XOBNEW (&objfile->objfile_obstack, struct mapped_index);
3446   *map = local_map;
3447
3448   dwarf2_per_objfile->index_table = map;
3449   dwarf2_per_objfile->using_index = 1;
3450   dwarf2_per_objfile->quick_file_names_table =
3451     create_quick_file_names_table (dwarf2_per_objfile->n_comp_units);
3452
3453   return 1;
3454 }
3455
3456 /* A helper for the "quick" functions which sets the global
3457    dwarf2_per_objfile according to OBJFILE.  */
3458
3459 static void
3460 dw2_setup (struct objfile *objfile)
3461 {
3462   dwarf2_per_objfile = ((struct dwarf2_per_objfile *)
3463                         objfile_data (objfile, dwarf2_objfile_data_key));
3464   gdb_assert (dwarf2_per_objfile);
3465 }
3466
3467 /* die_reader_func for dw2_get_file_names.  */
3468
3469 static void
3470 dw2_get_file_names_reader (const struct die_reader_specs *reader,
3471                            const gdb_byte *info_ptr,
3472                            struct die_info *comp_unit_die,
3473                            int has_children,
3474                            void *data)
3475 {
3476   struct dwarf2_cu *cu = reader->cu;
3477   struct dwarf2_per_cu_data *this_cu = cu->per_cu;  
3478   struct objfile *objfile = dwarf2_per_objfile->objfile;
3479   struct dwarf2_per_cu_data *lh_cu;
3480   struct attribute *attr;
3481   int i;
3482   void **slot;
3483   struct quick_file_names *qfn;
3484
3485   gdb_assert (! this_cu->is_debug_types);
3486
3487   /* Our callers never want to match partial units -- instead they
3488      will match the enclosing full CU.  */
3489   if (comp_unit_die->tag == DW_TAG_partial_unit)
3490     {
3491       this_cu->v.quick->no_file_data = 1;
3492       return;
3493     }
3494
3495   lh_cu = this_cu;
3496   slot = NULL;
3497
3498   line_header_up lh;
3499   sect_offset line_offset {};
3500
3501   attr = dwarf2_attr (comp_unit_die, DW_AT_stmt_list, cu);
3502   if (attr)
3503     {
3504       struct quick_file_names find_entry;
3505
3506       line_offset = (sect_offset) DW_UNSND (attr);
3507
3508       /* We may have already read in this line header (TU line header sharing).
3509          If we have we're done.  */
3510       find_entry.hash.dwo_unit = cu->dwo_unit;
3511       find_entry.hash.line_sect_off = line_offset;
3512       slot = htab_find_slot (dwarf2_per_objfile->quick_file_names_table,
3513                              &find_entry, INSERT);
3514       if (*slot != NULL)
3515         {
3516           lh_cu->v.quick->file_names = (struct quick_file_names *) *slot;
3517           return;
3518         }
3519
3520       lh = dwarf_decode_line_header (line_offset, cu);
3521     }
3522   if (lh == NULL)
3523     {
3524       lh_cu->v.quick->no_file_data = 1;
3525       return;
3526     }
3527
3528   qfn = XOBNEW (&objfile->objfile_obstack, struct quick_file_names);
3529   qfn->hash.dwo_unit = cu->dwo_unit;
3530   qfn->hash.line_sect_off = line_offset;
3531   gdb_assert (slot != NULL);
3532   *slot = qfn;
3533
3534   file_and_directory fnd = find_file_and_directory (comp_unit_die, cu);
3535
3536   qfn->num_file_names = lh->file_names.size ();
3537   qfn->file_names =
3538     XOBNEWVEC (&objfile->objfile_obstack, const char *, lh->file_names.size ());
3539   for (i = 0; i < lh->file_names.size (); ++i)
3540     qfn->file_names[i] = file_full_name (i + 1, lh.get (), fnd.comp_dir);
3541   qfn->real_names = NULL;
3542
3543   lh_cu->v.quick->file_names = qfn;
3544 }
3545
3546 /* A helper for the "quick" functions which attempts to read the line
3547    table for THIS_CU.  */
3548
3549 static struct quick_file_names *
3550 dw2_get_file_names (struct dwarf2_per_cu_data *this_cu)
3551 {
3552   /* This should never be called for TUs.  */
3553   gdb_assert (! this_cu->is_debug_types);
3554   /* Nor type unit groups.  */
3555   gdb_assert (! IS_TYPE_UNIT_GROUP (this_cu));
3556
3557   if (this_cu->v.quick->file_names != NULL)
3558     return this_cu->v.quick->file_names;
3559   /* If we know there is no line data, no point in looking again.  */
3560   if (this_cu->v.quick->no_file_data)
3561     return NULL;
3562
3563   init_cutu_and_read_dies_simple (this_cu, dw2_get_file_names_reader, NULL);
3564
3565   if (this_cu->v.quick->no_file_data)
3566     return NULL;
3567   return this_cu->v.quick->file_names;
3568 }
3569
3570 /* A helper for the "quick" functions which computes and caches the
3571    real path for a given file name from the line table.  */
3572
3573 static const char *
3574 dw2_get_real_path (struct objfile *objfile,
3575                    struct quick_file_names *qfn, int index)
3576 {
3577   if (qfn->real_names == NULL)
3578     qfn->real_names = OBSTACK_CALLOC (&objfile->objfile_obstack,
3579                                       qfn->num_file_names, const char *);
3580
3581   if (qfn->real_names[index] == NULL)
3582     qfn->real_names[index] = gdb_realpath (qfn->file_names[index]);
3583
3584   return qfn->real_names[index];
3585 }
3586
3587 static struct symtab *
3588 dw2_find_last_source_symtab (struct objfile *objfile)
3589 {
3590   struct compunit_symtab *cust;
3591   int index;
3592
3593   dw2_setup (objfile);
3594   index = dwarf2_per_objfile->n_comp_units - 1;
3595   cust = dw2_instantiate_symtab (dw2_get_cutu (index));
3596   if (cust == NULL)
3597     return NULL;
3598   return compunit_primary_filetab (cust);
3599 }
3600
3601 /* Traversal function for dw2_forget_cached_source_info.  */
3602
3603 static int
3604 dw2_free_cached_file_names (void **slot, void *info)
3605 {
3606   struct quick_file_names *file_data = (struct quick_file_names *) *slot;
3607
3608   if (file_data->real_names)
3609     {
3610       int i;
3611
3612       for (i = 0; i < file_data->num_file_names; ++i)
3613         {
3614           xfree ((void*) file_data->real_names[i]);
3615           file_data->real_names[i] = NULL;
3616         }
3617     }
3618
3619   return 1;
3620 }
3621
3622 static void
3623 dw2_forget_cached_source_info (struct objfile *objfile)
3624 {
3625   dw2_setup (objfile);
3626
3627   htab_traverse_noresize (dwarf2_per_objfile->quick_file_names_table,
3628                           dw2_free_cached_file_names, NULL);
3629 }
3630
3631 /* Helper function for dw2_map_symtabs_matching_filename that expands
3632    the symtabs and calls the iterator.  */
3633
3634 static int
3635 dw2_map_expand_apply (struct objfile *objfile,
3636                       struct dwarf2_per_cu_data *per_cu,
3637                       const char *name, const char *real_path,
3638                       gdb::function_view<bool (symtab *)> callback)
3639 {
3640   struct compunit_symtab *last_made = objfile->compunit_symtabs;
3641
3642   /* Don't visit already-expanded CUs.  */
3643   if (per_cu->v.quick->compunit_symtab)
3644     return 0;
3645
3646   /* This may expand more than one symtab, and we want to iterate over
3647      all of them.  */
3648   dw2_instantiate_symtab (per_cu);
3649
3650   return iterate_over_some_symtabs (name, real_path, objfile->compunit_symtabs,
3651                                     last_made, callback);
3652 }
3653
3654 /* Implementation of the map_symtabs_matching_filename method.  */
3655
3656 static bool
3657 dw2_map_symtabs_matching_filename
3658   (struct objfile *objfile, const char *name, const char *real_path,
3659    gdb::function_view<bool (symtab *)> callback)
3660 {
3661   int i;
3662   const char *name_basename = lbasename (name);
3663
3664   dw2_setup (objfile);
3665
3666   /* The rule is CUs specify all the files, including those used by
3667      any TU, so there's no need to scan TUs here.  */
3668
3669   for (i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
3670     {
3671       int j;
3672       struct dwarf2_per_cu_data *per_cu = dw2_get_cu (i);
3673       struct quick_file_names *file_data;
3674
3675       /* We only need to look at symtabs not already expanded.  */
3676       if (per_cu->v.quick->compunit_symtab)
3677         continue;
3678
3679       file_data = dw2_get_file_names (per_cu);
3680       if (file_data == NULL)
3681         continue;
3682
3683       for (j = 0; j < file_data->num_file_names; ++j)
3684         {
3685           const char *this_name = file_data->file_names[j];
3686           const char *this_real_name;
3687
3688           if (compare_filenames_for_search (this_name, name))
3689             {
3690               if (dw2_map_expand_apply (objfile, per_cu, name, real_path,
3691                                         callback))
3692                 return true;
3693               continue;
3694             }
3695
3696           /* Before we invoke realpath, which can get expensive when many
3697              files are involved, do a quick comparison of the basenames.  */
3698           if (! basenames_may_differ
3699               && FILENAME_CMP (lbasename (this_name), name_basename) != 0)
3700             continue;
3701
3702           this_real_name = dw2_get_real_path (objfile, file_data, j);
3703           if (compare_filenames_for_search (this_real_name, name))
3704             {
3705               if (dw2_map_expand_apply (objfile, per_cu, name, real_path,
3706                                         callback))
3707                 return true;
3708               continue;
3709             }
3710
3711           if (real_path != NULL)
3712             {
3713               gdb_assert (IS_ABSOLUTE_PATH (real_path));
3714               gdb_assert (IS_ABSOLUTE_PATH (name));
3715               if (this_real_name != NULL
3716                   && FILENAME_CMP (real_path, this_real_name) == 0)
3717                 {
3718                   if (dw2_map_expand_apply (objfile, per_cu, name, real_path,
3719                                             callback))
3720                     return true;
3721                   continue;
3722                 }
3723             }
3724         }
3725     }
3726
3727   return false;
3728 }
3729
3730 /* Struct used to manage iterating over all CUs looking for a symbol.  */
3731
3732 struct dw2_symtab_iterator
3733 {
3734   /* The internalized form of .gdb_index.  */
3735   struct mapped_index *index;
3736   /* If non-zero, only look for symbols that match BLOCK_INDEX.  */
3737   int want_specific_block;
3738   /* One of GLOBAL_BLOCK or STATIC_BLOCK.
3739      Unused if !WANT_SPECIFIC_BLOCK.  */
3740   int block_index;
3741   /* The kind of symbol we're looking for.  */
3742   domain_enum domain;
3743   /* The list of CUs from the index entry of the symbol,
3744      or NULL if not found.  */
3745   offset_type *vec;
3746   /* The next element in VEC to look at.  */
3747   int next;
3748   /* The number of elements in VEC, or zero if there is no match.  */
3749   int length;
3750   /* Have we seen a global version of the symbol?
3751      If so we can ignore all further global instances.
3752      This is to work around gold/15646, inefficient gold-generated
3753      indices.  */
3754   int global_seen;
3755 };
3756
3757 /* Initialize the index symtab iterator ITER.
3758    If WANT_SPECIFIC_BLOCK is non-zero, only look for symbols
3759    in block BLOCK_INDEX.  Otherwise BLOCK_INDEX is ignored.  */
3760
3761 static void
3762 dw2_symtab_iter_init (struct dw2_symtab_iterator *iter,
3763                       struct mapped_index *index,
3764                       int want_specific_block,
3765                       int block_index,
3766                       domain_enum domain,
3767                       const char *name)
3768 {
3769   iter->index = index;
3770   iter->want_specific_block = want_specific_block;
3771   iter->block_index = block_index;
3772   iter->domain = domain;
3773   iter->next = 0;
3774   iter->global_seen = 0;
3775
3776   if (find_slot_in_mapped_hash (index, name, &iter->vec))
3777     iter->length = MAYBE_SWAP (*iter->vec);
3778   else
3779     {
3780       iter->vec = NULL;
3781       iter->length = 0;
3782     }
3783 }
3784
3785 /* Return the next matching CU or NULL if there are no more.  */
3786
3787 static struct dwarf2_per_cu_data *
3788 dw2_symtab_iter_next (struct dw2_symtab_iterator *iter)
3789 {
3790   for ( ; iter->next < iter->length; ++iter->next)
3791     {
3792       offset_type cu_index_and_attrs =
3793         MAYBE_SWAP (iter->vec[iter->next + 1]);
3794       offset_type cu_index = GDB_INDEX_CU_VALUE (cu_index_and_attrs);
3795       struct dwarf2_per_cu_data *per_cu;
3796       int want_static = iter->block_index != GLOBAL_BLOCK;
3797       /* This value is only valid for index versions >= 7.  */
3798       int is_static = GDB_INDEX_SYMBOL_STATIC_VALUE (cu_index_and_attrs);
3799       gdb_index_symbol_kind symbol_kind =
3800         GDB_INDEX_SYMBOL_KIND_VALUE (cu_index_and_attrs);
3801       /* Only check the symbol attributes if they're present.
3802          Indices prior to version 7 don't record them,
3803          and indices >= 7 may elide them for certain symbols
3804          (gold does this).  */
3805       int attrs_valid =
3806         (iter->index->version >= 7
3807          && symbol_kind != GDB_INDEX_SYMBOL_KIND_NONE);
3808
3809       /* Don't crash on bad data.  */
3810       if (cu_index >= (dwarf2_per_objfile->n_comp_units
3811                        + dwarf2_per_objfile->n_type_units))
3812         {
3813           complaint (&symfile_complaints,
3814                      _(".gdb_index entry has bad CU index"
3815                        " [in module %s]"),
3816                      objfile_name (dwarf2_per_objfile->objfile));
3817           continue;
3818         }
3819
3820       per_cu = dw2_get_cutu (cu_index);
3821
3822       /* Skip if already read in.  */
3823       if (per_cu->v.quick->compunit_symtab)
3824         continue;
3825
3826       /* Check static vs global.  */
3827       if (attrs_valid)
3828         {
3829           if (iter->want_specific_block
3830               && want_static != is_static)
3831             continue;
3832           /* Work around gold/15646.  */
3833           if (!is_static && iter->global_seen)
3834             continue;
3835           if (!is_static)
3836             iter->global_seen = 1;
3837         }
3838
3839       /* Only check the symbol's kind if it has one.  */
3840       if (attrs_valid)
3841         {
3842           switch (iter->domain)
3843             {
3844             case VAR_DOMAIN:
3845               if (symbol_kind != GDB_INDEX_SYMBOL_KIND_VARIABLE
3846                   && symbol_kind != GDB_INDEX_SYMBOL_KIND_FUNCTION
3847                   /* Some types are also in VAR_DOMAIN.  */
3848                   && symbol_kind != GDB_INDEX_SYMBOL_KIND_TYPE)
3849                 continue;
3850               break;
3851             case STRUCT_DOMAIN:
3852               if (symbol_kind != GDB_INDEX_SYMBOL_KIND_TYPE)
3853                 continue;
3854               break;
3855             case LABEL_DOMAIN:
3856               if (symbol_kind != GDB_INDEX_SYMBOL_KIND_OTHER)
3857                 continue;
3858               break;
3859             default:
3860               break;
3861             }
3862         }
3863
3864       ++iter->next;
3865       return per_cu;
3866     }
3867
3868   return NULL;
3869 }
3870
3871 static struct compunit_symtab *
3872 dw2_lookup_symbol (struct objfile *objfile, int block_index,
3873                    const char *name, domain_enum domain)
3874 {
3875   struct compunit_symtab *stab_best = NULL;
3876   struct mapped_index *index;
3877
3878   dw2_setup (objfile);
3879
3880   index = dwarf2_per_objfile->index_table;
3881
3882   /* index is NULL if OBJF_READNOW.  */
3883   if (index)
3884     {
3885       struct dw2_symtab_iterator iter;
3886       struct dwarf2_per_cu_data *per_cu;
3887
3888       dw2_symtab_iter_init (&iter, index, 1, block_index, domain, name);
3889
3890       while ((per_cu = dw2_symtab_iter_next (&iter)) != NULL)
3891         {
3892           struct symbol *sym, *with_opaque = NULL;
3893           struct compunit_symtab *stab = dw2_instantiate_symtab (per_cu);
3894           const struct blockvector *bv = COMPUNIT_BLOCKVECTOR (stab);
3895           struct block *block = BLOCKVECTOR_BLOCK (bv, block_index);
3896
3897           sym = block_find_symbol (block, name, domain,
3898                                    block_find_non_opaque_type_preferred,
3899                                    &with_opaque);
3900
3901           /* Some caution must be observed with overloaded functions
3902              and methods, since the index will not contain any overload
3903              information (but NAME might contain it).  */
3904
3905           if (sym != NULL
3906               && strcmp_iw (SYMBOL_SEARCH_NAME (sym), name) == 0)
3907             return stab;
3908           if (with_opaque != NULL
3909               && strcmp_iw (SYMBOL_SEARCH_NAME (with_opaque), name) == 0)
3910             stab_best = stab;
3911
3912           /* Keep looking through other CUs.  */
3913         }
3914     }
3915
3916   return stab_best;
3917 }
3918
3919 static void
3920 dw2_print_stats (struct objfile *objfile)
3921 {
3922   int i, total, count;
3923
3924   dw2_setup (objfile);
3925   total = dwarf2_per_objfile->n_comp_units + dwarf2_per_objfile->n_type_units;
3926   count = 0;
3927   for (i = 0; i < total; ++i)
3928     {
3929       struct dwarf2_per_cu_data *per_cu = dw2_get_cutu (i);
3930
3931       if (!per_cu->v.quick->compunit_symtab)
3932         ++count;
3933     }
3934   printf_filtered (_("  Number of read CUs: %d\n"), total - count);
3935   printf_filtered (_("  Number of unread CUs: %d\n"), count);
3936 }
3937
3938 /* This dumps minimal information about the index.
3939    It is called via "mt print objfiles".
3940    One use is to verify .gdb_index has been loaded by the
3941    gdb.dwarf2/gdb-index.exp testcase.  */
3942
3943 static void
3944 dw2_dump (struct objfile *objfile)
3945 {
3946   dw2_setup (objfile);
3947   gdb_assert (dwarf2_per_objfile->using_index);
3948   printf_filtered (".gdb_index:");
3949   if (dwarf2_per_objfile->index_table != NULL)
3950     {
3951       printf_filtered (" version %d\n",
3952                        dwarf2_per_objfile->index_table->version);
3953     }
3954   else
3955     printf_filtered (" faked for \"readnow\"\n");
3956   printf_filtered ("\n");
3957 }
3958
3959 static void
3960 dw2_relocate (struct objfile *objfile,
3961               const struct section_offsets *new_offsets,
3962               const struct section_offsets *delta)
3963 {
3964   /* There's nothing to relocate here.  */
3965 }
3966
3967 static void
3968 dw2_expand_symtabs_for_function (struct objfile *objfile,
3969                                  const char *func_name)
3970 {
3971   struct mapped_index *index;
3972
3973   dw2_setup (objfile);
3974
3975   index = dwarf2_per_objfile->index_table;
3976
3977   /* index is NULL if OBJF_READNOW.  */
3978   if (index)
3979     {
3980       struct dw2_symtab_iterator iter;
3981       struct dwarf2_per_cu_data *per_cu;
3982
3983       /* Note: It doesn't matter what we pass for block_index here.  */
3984       dw2_symtab_iter_init (&iter, index, 0, GLOBAL_BLOCK, VAR_DOMAIN,
3985                             func_name);
3986
3987       while ((per_cu = dw2_symtab_iter_next (&iter)) != NULL)
3988         dw2_instantiate_symtab (per_cu);
3989     }
3990 }
3991
3992 static void
3993 dw2_expand_all_symtabs (struct objfile *objfile)
3994 {
3995   int i;
3996
3997   dw2_setup (objfile);
3998
3999   for (i = 0; i < (dwarf2_per_objfile->n_comp_units
4000                    + dwarf2_per_objfile->n_type_units); ++i)
4001     {
4002       struct dwarf2_per_cu_data *per_cu = dw2_get_cutu (i);
4003
4004       dw2_instantiate_symtab (per_cu);
4005     }
4006 }
4007
4008 static void
4009 dw2_expand_symtabs_with_fullname (struct objfile *objfile,
4010                                   const char *fullname)
4011 {
4012   int i;
4013
4014   dw2_setup (objfile);
4015
4016   /* We don't need to consider type units here.
4017      This is only called for examining code, e.g. expand_line_sal.
4018      There can be an order of magnitude (or more) more type units
4019      than comp units, and we avoid them if we can.  */
4020
4021   for (i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
4022     {
4023       int j;
4024       struct dwarf2_per_cu_data *per_cu = dw2_get_cutu (i);
4025       struct quick_file_names *file_data;
4026
4027       /* We only need to look at symtabs not already expanded.  */
4028       if (per_cu->v.quick->compunit_symtab)
4029         continue;
4030
4031       file_data = dw2_get_file_names (per_cu);
4032       if (file_data == NULL)
4033         continue;
4034
4035       for (j = 0; j < file_data->num_file_names; ++j)
4036         {
4037           const char *this_fullname = file_data->file_names[j];
4038
4039           if (filename_cmp (this_fullname, fullname) == 0)
4040             {
4041               dw2_instantiate_symtab (per_cu);
4042               break;
4043             }
4044         }
4045     }
4046 }
4047
4048 static void
4049 dw2_map_matching_symbols (struct objfile *objfile,
4050                           const char * name, domain_enum domain,
4051                           int global,
4052                           int (*callback) (struct block *,
4053                                            struct symbol *, void *),
4054                           void *data, symbol_compare_ftype *match,
4055                           symbol_compare_ftype *ordered_compare)
4056 {
4057   /* Currently unimplemented; used for Ada.  The function can be called if the
4058      current language is Ada for a non-Ada objfile using GNU index.  As Ada
4059      does not look for non-Ada symbols this function should just return.  */
4060 }
4061
4062 static void
4063 dw2_expand_symtabs_matching
4064   (struct objfile *objfile,
4065    gdb::function_view<expand_symtabs_file_matcher_ftype> file_matcher,
4066    gdb::function_view<expand_symtabs_symbol_matcher_ftype> symbol_matcher,
4067    gdb::function_view<expand_symtabs_exp_notify_ftype> expansion_notify,
4068    enum search_domain kind)
4069 {
4070   int i;
4071   offset_type iter;
4072   struct mapped_index *index;
4073
4074   dw2_setup (objfile);
4075
4076   /* index_table is NULL if OBJF_READNOW.  */
4077   if (!dwarf2_per_objfile->index_table)
4078     return;
4079   index = dwarf2_per_objfile->index_table;
4080
4081   if (file_matcher != NULL)
4082     {
4083       htab_up visited_found (htab_create_alloc (10, htab_hash_pointer,
4084                                                 htab_eq_pointer,
4085                                                 NULL, xcalloc, xfree));
4086       htab_up visited_not_found (htab_create_alloc (10, htab_hash_pointer,
4087                                                     htab_eq_pointer,
4088                                                     NULL, xcalloc, xfree));
4089
4090       /* The rule is CUs specify all the files, including those used by
4091          any TU, so there's no need to scan TUs here.  */
4092
4093       for (i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
4094         {
4095           int j;
4096           struct dwarf2_per_cu_data *per_cu = dw2_get_cu (i);
4097           struct quick_file_names *file_data;
4098           void **slot;
4099
4100           QUIT;
4101
4102           per_cu->v.quick->mark = 0;
4103
4104           /* We only need to look at symtabs not already expanded.  */
4105           if (per_cu->v.quick->compunit_symtab)
4106             continue;
4107
4108           file_data = dw2_get_file_names (per_cu);
4109           if (file_data == NULL)
4110             continue;
4111
4112           if (htab_find (visited_not_found.get (), file_data) != NULL)
4113             continue;
4114           else if (htab_find (visited_found.get (), file_data) != NULL)
4115             {
4116               per_cu->v.quick->mark = 1;
4117               continue;
4118             }
4119
4120           for (j = 0; j < file_data->num_file_names; ++j)
4121             {
4122               const char *this_real_name;
4123
4124               if (file_matcher (file_data->file_names[j], false))
4125                 {
4126                   per_cu->v.quick->mark = 1;
4127                   break;
4128                 }
4129
4130               /* Before we invoke realpath, which can get expensive when many
4131                  files are involved, do a quick comparison of the basenames.  */
4132               if (!basenames_may_differ
4133                   && !file_matcher (lbasename (file_data->file_names[j]),
4134                                     true))
4135                 continue;
4136
4137               this_real_name = dw2_get_real_path (objfile, file_data, j);
4138               if (file_matcher (this_real_name, false))
4139                 {
4140                   per_cu->v.quick->mark = 1;
4141                   break;
4142                 }
4143             }
4144
4145           slot = htab_find_slot (per_cu->v.quick->mark
4146                                  ? visited_found.get ()
4147                                  : visited_not_found.get (),
4148                                  file_data, INSERT);
4149           *slot = file_data;
4150         }
4151     }
4152
4153   for (iter = 0; iter < index->symbol_table_slots; ++iter)
4154     {
4155       offset_type idx = 2 * iter;
4156       const char *name;
4157       offset_type *vec, vec_len, vec_idx;
4158       int global_seen = 0;
4159
4160       QUIT;
4161
4162       if (index->symbol_table[idx] == 0 && index->symbol_table[idx + 1] == 0)
4163         continue;
4164
4165       name = index->constant_pool + MAYBE_SWAP (index->symbol_table[idx]);
4166
4167       if (!symbol_matcher (name))
4168         continue;
4169
4170       /* The name was matched, now expand corresponding CUs that were
4171          marked.  */
4172       vec = (offset_type *) (index->constant_pool
4173                              + MAYBE_SWAP (index->symbol_table[idx + 1]));
4174       vec_len = MAYBE_SWAP (vec[0]);
4175       for (vec_idx = 0; vec_idx < vec_len; ++vec_idx)
4176         {
4177           struct dwarf2_per_cu_data *per_cu;
4178           offset_type cu_index_and_attrs = MAYBE_SWAP (vec[vec_idx + 1]);
4179           /* This value is only valid for index versions >= 7.  */
4180           int is_static = GDB_INDEX_SYMBOL_STATIC_VALUE (cu_index_and_attrs);
4181           gdb_index_symbol_kind symbol_kind =
4182             GDB_INDEX_SYMBOL_KIND_VALUE (cu_index_and_attrs);
4183           int cu_index = GDB_INDEX_CU_VALUE (cu_index_and_attrs);
4184           /* Only check the symbol attributes if they're present.
4185              Indices prior to version 7 don't record them,
4186              and indices >= 7 may elide them for certain symbols
4187              (gold does this).  */
4188           int attrs_valid =
4189             (index->version >= 7
4190              && symbol_kind != GDB_INDEX_SYMBOL_KIND_NONE);
4191
4192           /* Work around gold/15646.  */
4193           if (attrs_valid)
4194             {
4195               if (!is_static && global_seen)
4196                 continue;
4197               if (!is_static)
4198                 global_seen = 1;
4199             }
4200
4201           /* Only check the symbol's kind if it has one.  */
4202           if (attrs_valid)
4203             {
4204               switch (kind)
4205                 {
4206                 case VARIABLES_DOMAIN:
4207                   if (symbol_kind != GDB_INDEX_SYMBOL_KIND_VARIABLE)
4208                     continue;
4209                   break;
4210                 case FUNCTIONS_DOMAIN:
4211                   if (symbol_kind != GDB_INDEX_SYMBOL_KIND_FUNCTION)
4212                     continue;
4213                   break;
4214                 case TYPES_DOMAIN:
4215                   if (symbol_kind != GDB_INDEX_SYMBOL_KIND_TYPE)
4216                     continue;
4217                   break;
4218                 default:
4219                   break;
4220                 }
4221             }
4222
4223           /* Don't crash on bad data.  */
4224           if (cu_index >= (dwarf2_per_objfile->n_comp_units
4225                            + dwarf2_per_objfile->n_type_units))
4226             {
4227               complaint (&symfile_complaints,
4228                          _(".gdb_index entry has bad CU index"
4229                            " [in module %s]"), objfile_name (objfile));
4230               continue;
4231             }
4232
4233           per_cu = dw2_get_cutu (cu_index);
4234           if (file_matcher == NULL || per_cu->v.quick->mark)
4235             {
4236               int symtab_was_null =
4237                 (per_cu->v.quick->compunit_symtab == NULL);
4238
4239               dw2_instantiate_symtab (per_cu);
4240
4241               if (expansion_notify != NULL
4242                   && symtab_was_null
4243                   && per_cu->v.quick->compunit_symtab != NULL)
4244                 {
4245                   expansion_notify (per_cu->v.quick->compunit_symtab);
4246                 }
4247             }
4248         }
4249     }
4250 }
4251
4252 /* A helper for dw2_find_pc_sect_compunit_symtab which finds the most specific
4253    symtab.  */
4254
4255 static struct compunit_symtab *
4256 recursively_find_pc_sect_compunit_symtab (struct compunit_symtab *cust,
4257                                           CORE_ADDR pc)
4258 {
4259   int i;
4260
4261   if (COMPUNIT_BLOCKVECTOR (cust) != NULL
4262       && blockvector_contains_pc (COMPUNIT_BLOCKVECTOR (cust), pc))
4263     return cust;
4264
4265   if (cust->includes == NULL)
4266     return NULL;
4267
4268   for (i = 0; cust->includes[i]; ++i)
4269     {
4270       struct compunit_symtab *s = cust->includes[i];
4271
4272       s = recursively_find_pc_sect_compunit_symtab (s, pc);
4273       if (s != NULL)
4274         return s;
4275     }
4276
4277   return NULL;
4278 }
4279
4280 static struct compunit_symtab *
4281 dw2_find_pc_sect_compunit_symtab (struct objfile *objfile,
4282                                   struct bound_minimal_symbol msymbol,
4283                                   CORE_ADDR pc,
4284                                   struct obj_section *section,
4285                                   int warn_if_readin)
4286 {
4287   struct dwarf2_per_cu_data *data;
4288   struct compunit_symtab *result;
4289
4290   dw2_setup (objfile);
4291
4292   if (!objfile->psymtabs_addrmap)
4293     return NULL;
4294
4295   data = (struct dwarf2_per_cu_data *) addrmap_find (objfile->psymtabs_addrmap,
4296                                                      pc);
4297   if (!data)
4298     return NULL;
4299
4300   if (warn_if_readin && data->v.quick->compunit_symtab)
4301     warning (_("(Internal error: pc %s in read in CU, but not in symtab.)"),
4302              paddress (get_objfile_arch (objfile), pc));
4303
4304   result
4305     = recursively_find_pc_sect_compunit_symtab (dw2_instantiate_symtab (data),
4306                                                 pc);
4307   gdb_assert (result != NULL);
4308   return result;
4309 }
4310
4311 static void
4312 dw2_map_symbol_filenames (struct objfile *objfile, symbol_filename_ftype *fun,
4313                           void *data, int need_fullname)
4314 {
4315   int i;
4316   htab_up visited (htab_create_alloc (10, htab_hash_pointer, htab_eq_pointer,
4317                                       NULL, xcalloc, xfree));
4318
4319   dw2_setup (objfile);
4320
4321   /* The rule is CUs specify all the files, including those used by
4322      any TU, so there's no need to scan TUs here.
4323      We can ignore file names coming from already-expanded CUs.  */
4324
4325   for (i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
4326     {
4327       struct dwarf2_per_cu_data *per_cu = dw2_get_cutu (i);
4328
4329       if (per_cu->v.quick->compunit_symtab)
4330         {
4331           void **slot = htab_find_slot (visited.get (),
4332                                         per_cu->v.quick->file_names,
4333                                         INSERT);
4334
4335           *slot = per_cu->v.quick->file_names;
4336         }
4337     }
4338
4339   for (i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
4340     {
4341       int j;
4342       struct dwarf2_per_cu_data *per_cu = dw2_get_cu (i);
4343       struct quick_file_names *file_data;
4344       void **slot;
4345
4346       /* We only need to look at symtabs not already expanded.  */
4347       if (per_cu->v.quick->compunit_symtab)
4348         continue;
4349
4350       file_data = dw2_get_file_names (per_cu);
4351       if (file_data == NULL)
4352         continue;
4353
4354       slot = htab_find_slot (visited.get (), file_data, INSERT);
4355       if (*slot)
4356         {
4357           /* Already visited.  */
4358           continue;
4359         }
4360       *slot = file_data;
4361
4362       for (j = 0; j < file_data->num_file_names; ++j)
4363         {
4364           const char *this_real_name;
4365
4366           if (need_fullname)
4367             this_real_name = dw2_get_real_path (objfile, file_data, j);
4368           else
4369             this_real_name = NULL;
4370           (*fun) (file_data->file_names[j], this_real_name, data);
4371         }
4372     }
4373 }
4374
4375 static int
4376 dw2_has_symbols (struct objfile *objfile)
4377 {
4378   return 1;
4379 }
4380
4381 const struct quick_symbol_functions dwarf2_gdb_index_functions =
4382 {
4383   dw2_has_symbols,
4384   dw2_find_last_source_symtab,
4385   dw2_forget_cached_source_info,
4386   dw2_map_symtabs_matching_filename,
4387   dw2_lookup_symbol,
4388   dw2_print_stats,
4389   dw2_dump,
4390   dw2_relocate,
4391   dw2_expand_symtabs_for_function,
4392   dw2_expand_all_symtabs,
4393   dw2_expand_symtabs_with_fullname,
4394   dw2_map_matching_symbols,
4395   dw2_expand_symtabs_matching,
4396   dw2_find_pc_sect_compunit_symtab,
4397   dw2_map_symbol_filenames
4398 };
4399
4400 /* Initialize for reading DWARF for this objfile.  Return 0 if this
4401    file will use psymtabs, or 1 if using the GNU index.  */
4402
4403 int
4404 dwarf2_initialize_objfile (struct objfile *objfile)
4405 {
4406   /* If we're about to read full symbols, don't bother with the
4407      indices.  In this case we also don't care if some other debug
4408      format is making psymtabs, because they are all about to be
4409      expanded anyway.  */
4410   if ((objfile->flags & OBJF_READNOW))
4411     {
4412       int i;
4413
4414       dwarf2_per_objfile->using_index = 1;
4415       create_all_comp_units (objfile);
4416       create_all_type_units (objfile);
4417       dwarf2_per_objfile->quick_file_names_table =
4418         create_quick_file_names_table (dwarf2_per_objfile->n_comp_units);
4419
4420       for (i = 0; i < (dwarf2_per_objfile->n_comp_units
4421                        + dwarf2_per_objfile->n_type_units); ++i)
4422         {
4423           struct dwarf2_per_cu_data *per_cu = dw2_get_cutu (i);
4424
4425           per_cu->v.quick = OBSTACK_ZALLOC (&objfile->objfile_obstack,
4426                                             struct dwarf2_per_cu_quick_data);
4427         }
4428
4429       /* Return 1 so that gdb sees the "quick" functions.  However,
4430          these functions will be no-ops because we will have expanded
4431          all symtabs.  */
4432       return 1;
4433     }
4434
4435   if (dwarf2_read_index (objfile))
4436     return 1;
4437
4438   return 0;
4439 }
4440
4441 \f
4442
4443 /* Build a partial symbol table.  */
4444
4445 void
4446 dwarf2_build_psymtabs (struct objfile *objfile)
4447 {
4448
4449   if (objfile->global_psymbols.size == 0 && objfile->static_psymbols.size == 0)
4450     {
4451       init_psymbol_list (objfile, 1024);
4452     }
4453
4454   TRY
4455     {
4456       /* This isn't really ideal: all the data we allocate on the
4457          objfile's obstack is still uselessly kept around.  However,
4458          freeing it seems unsafe.  */
4459       psymtab_discarder psymtabs (objfile);
4460       dwarf2_build_psymtabs_hard (objfile);
4461       psymtabs.keep ();
4462     }
4463   CATCH (except, RETURN_MASK_ERROR)
4464     {
4465       exception_print (gdb_stderr, except);
4466     }
4467   END_CATCH
4468 }
4469
4470 /* Return the total length of the CU described by HEADER.  */
4471
4472 static unsigned int
4473 get_cu_length (const struct comp_unit_head *header)
4474 {
4475   return header->initial_length_size + header->length;
4476 }
4477
4478 /* Return TRUE if SECT_OFF is within CU_HEADER.  */
4479
4480 static inline bool
4481 offset_in_cu_p (const comp_unit_head *cu_header, sect_offset sect_off)
4482 {
4483   sect_offset bottom = cu_header->sect_off;
4484   sect_offset top = cu_header->sect_off + get_cu_length (cu_header);
4485
4486   return sect_off >= bottom && sect_off < top;
4487 }
4488
4489 /* Find the base address of the compilation unit for range lists and
4490    location lists.  It will normally be specified by DW_AT_low_pc.
4491    In DWARF-3 draft 4, the base address could be overridden by
4492    DW_AT_entry_pc.  It's been removed, but GCC still uses this for
4493    compilation units with discontinuous ranges.  */
4494
4495 static void
4496 dwarf2_find_base_address (struct die_info *die, struct dwarf2_cu *cu)
4497 {
4498   struct attribute *attr;
4499
4500   cu->base_known = 0;
4501   cu->base_address = 0;
4502
4503   attr = dwarf2_attr (die, DW_AT_entry_pc, cu);
4504   if (attr)
4505     {
4506       cu->base_address = attr_value_as_address (attr);
4507       cu->base_known = 1;
4508     }
4509   else
4510     {
4511       attr = dwarf2_attr (die, DW_AT_low_pc, cu);
4512       if (attr)
4513         {
4514           cu->base_address = attr_value_as_address (attr);
4515           cu->base_known = 1;
4516         }
4517     }
4518 }
4519
4520 /* Read in the comp unit header information from the debug_info at info_ptr.
4521    Use rcuh_kind::COMPILE as the default type if not known by the caller.
4522    NOTE: This leaves members offset, first_die_offset to be filled in
4523    by the caller.  */
4524
4525 static const gdb_byte *
4526 read_comp_unit_head (struct comp_unit_head *cu_header,
4527                      const gdb_byte *info_ptr,
4528                      struct dwarf2_section_info *section,
4529                      rcuh_kind section_kind)
4530 {
4531   int signed_addr;
4532   unsigned int bytes_read;
4533   const char *filename = get_section_file_name (section);
4534   bfd *abfd = get_section_bfd_owner (section);
4535
4536   cu_header->length = read_initial_length (abfd, info_ptr, &bytes_read);
4537   cu_header->initial_length_size = bytes_read;
4538   cu_header->offset_size = (bytes_read == 4) ? 4 : 8;
4539   info_ptr += bytes_read;
4540   cu_header->version = read_2_bytes (abfd, info_ptr);
4541   info_ptr += 2;
4542   if (cu_header->version < 5)
4543     switch (section_kind)
4544       {
4545       case rcuh_kind::COMPILE:
4546         cu_header->unit_type = DW_UT_compile;
4547         break;
4548       case rcuh_kind::TYPE:
4549         cu_header->unit_type = DW_UT_type;
4550         break;
4551       default:
4552         internal_error (__FILE__, __LINE__,
4553                         _("read_comp_unit_head: invalid section_kind"));
4554       }
4555   else
4556     {
4557       cu_header->unit_type = static_cast<enum dwarf_unit_type>
4558                                                  (read_1_byte (abfd, info_ptr));
4559       info_ptr += 1;
4560       switch (cu_header->unit_type)
4561         {
4562         case DW_UT_compile:
4563           if (section_kind != rcuh_kind::COMPILE)
4564             error (_("Dwarf Error: wrong unit_type in compilation unit header "
4565                    "(is DW_UT_compile, should be DW_UT_type) [in module %s]"),
4566                    filename);
4567           break;
4568         case DW_UT_type:
4569           section_kind = rcuh_kind::TYPE;
4570           break;
4571         default:
4572           error (_("Dwarf Error: wrong unit_type in compilation unit header "
4573                  "(is %d, should be %d or %d) [in module %s]"),
4574                  cu_header->unit_type, DW_UT_compile, DW_UT_type, filename);
4575         }
4576
4577       cu_header->addr_size = read_1_byte (abfd, info_ptr);
4578       info_ptr += 1;
4579     }
4580   cu_header->abbrev_sect_off = (sect_offset) read_offset (abfd, info_ptr,
4581                                                           cu_header,
4582                                                           &bytes_read);
4583   info_ptr += bytes_read;
4584   if (cu_header->version < 5)
4585     {
4586       cu_header->addr_size = read_1_byte (abfd, info_ptr);
4587       info_ptr += 1;
4588     }
4589   signed_addr = bfd_get_sign_extend_vma (abfd);
4590   if (signed_addr < 0)
4591     internal_error (__FILE__, __LINE__,
4592                     _("read_comp_unit_head: dwarf from non elf file"));
4593   cu_header->signed_addr_p = signed_addr;
4594
4595   if (section_kind == rcuh_kind::TYPE)
4596     {
4597       LONGEST type_offset;
4598
4599       cu_header->signature = read_8_bytes (abfd, info_ptr);
4600       info_ptr += 8;
4601
4602       type_offset = read_offset (abfd, info_ptr, cu_header, &bytes_read);
4603       info_ptr += bytes_read;
4604       cu_header->type_cu_offset_in_tu = (cu_offset) type_offset;
4605       if (to_underlying (cu_header->type_cu_offset_in_tu) != type_offset)
4606         error (_("Dwarf Error: Too big type_offset in compilation unit "
4607                "header (is %s) [in module %s]"), plongest (type_offset),
4608                filename);
4609     }
4610
4611   return info_ptr;
4612 }
4613
4614 /* Helper function that returns the proper abbrev section for
4615    THIS_CU.  */
4616
4617 static struct dwarf2_section_info *
4618 get_abbrev_section_for_cu (struct dwarf2_per_cu_data *this_cu)
4619 {
4620   struct dwarf2_section_info *abbrev;
4621
4622   if (this_cu->is_dwz)
4623     abbrev = &dwarf2_get_dwz_file ()->abbrev;
4624   else
4625     abbrev = &dwarf2_per_objfile->abbrev;
4626
4627   return abbrev;
4628 }
4629
4630 /* Subroutine of read_and_check_comp_unit_head and
4631    read_and_check_type_unit_head to simplify them.
4632    Perform various error checking on the header.  */
4633
4634 static void
4635 error_check_comp_unit_head (struct comp_unit_head *header,
4636                             struct dwarf2_section_info *section,
4637                             struct dwarf2_section_info *abbrev_section)
4638 {
4639   const char *filename = get_section_file_name (section);
4640
4641   if (header->version < 2 || header->version > 5)
4642     error (_("Dwarf Error: wrong version in compilation unit header "
4643            "(is %d, should be 2, 3, 4 or 5) [in module %s]"), header->version,
4644            filename);
4645
4646   if (to_underlying (header->abbrev_sect_off)
4647       >= dwarf2_section_size (dwarf2_per_objfile->objfile, abbrev_section))
4648     error (_("Dwarf Error: bad offset (0x%x) in compilation unit header "
4649            "(offset 0x%x + 6) [in module %s]"),
4650            to_underlying (header->abbrev_sect_off),
4651            to_underlying (header->sect_off),
4652            filename);
4653
4654   /* Cast to ULONGEST to use 64-bit arithmetic when possible to
4655      avoid potential 32-bit overflow.  */
4656   if (((ULONGEST) header->sect_off + get_cu_length (header))
4657       > section->size)
4658     error (_("Dwarf Error: bad length (0x%x) in compilation unit header "
4659            "(offset 0x%x + 0) [in module %s]"),
4660            header->length, to_underlying (header->sect_off),
4661            filename);
4662 }
4663
4664 /* Read in a CU/TU header and perform some basic error checking.
4665    The contents of the header are stored in HEADER.
4666    The result is a pointer to the start of the first DIE.  */
4667
4668 static const gdb_byte *
4669 read_and_check_comp_unit_head (struct comp_unit_head *header,
4670                                struct dwarf2_section_info *section,
4671                                struct dwarf2_section_info *abbrev_section,
4672                                const gdb_byte *info_ptr,
4673                                rcuh_kind section_kind)
4674 {
4675   const gdb_byte *beg_of_comp_unit = info_ptr;
4676   bfd *abfd = get_section_bfd_owner (section);
4677
4678   header->sect_off = (sect_offset) (beg_of_comp_unit - section->buffer);
4679
4680   info_ptr = read_comp_unit_head (header, info_ptr, section, section_kind);
4681
4682   header->first_die_cu_offset = (cu_offset) (info_ptr - beg_of_comp_unit);
4683
4684   error_check_comp_unit_head (header, section, abbrev_section);
4685
4686   return info_ptr;
4687 }
4688
4689 /* Fetch the abbreviation table offset from a comp or type unit header.  */
4690
4691 static sect_offset
4692 read_abbrev_offset (struct dwarf2_section_info *section,
4693                     sect_offset sect_off)
4694 {
4695   bfd *abfd = get_section_bfd_owner (section);
4696   const gdb_byte *info_ptr;
4697   unsigned int initial_length_size, offset_size;
4698   uint16_t version;
4699
4700   dwarf2_read_section (dwarf2_per_objfile->objfile, section);
4701   info_ptr = section->buffer + to_underlying (sect_off);
4702   read_initial_length (abfd, info_ptr, &initial_length_size);
4703   offset_size = initial_length_size == 4 ? 4 : 8;
4704   info_ptr += initial_length_size;
4705
4706   version = read_2_bytes (abfd, info_ptr);
4707   info_ptr += 2;
4708   if (version >= 5)
4709     {
4710       /* Skip unit type and address size.  */
4711       info_ptr += 2;
4712     }
4713
4714   return (sect_offset) read_offset_1 (abfd, info_ptr, offset_size);
4715 }
4716
4717 /* Allocate a new partial symtab for file named NAME and mark this new
4718    partial symtab as being an include of PST.  */
4719
4720 static void
4721 dwarf2_create_include_psymtab (const char *name, struct partial_symtab *pst,
4722                                struct objfile *objfile)
4723 {
4724   struct partial_symtab *subpst = allocate_psymtab (name, objfile);
4725
4726   if (!IS_ABSOLUTE_PATH (subpst->filename))
4727     {
4728       /* It shares objfile->objfile_obstack.  */
4729       subpst->dirname = pst->dirname;
4730     }
4731
4732   subpst->textlow = 0;
4733   subpst->texthigh = 0;
4734
4735   subpst->dependencies
4736     = XOBNEW (&objfile->objfile_obstack, struct partial_symtab *);
4737   subpst->dependencies[0] = pst;
4738   subpst->number_of_dependencies = 1;
4739
4740   subpst->globals_offset = 0;
4741   subpst->n_global_syms = 0;
4742   subpst->statics_offset = 0;
4743   subpst->n_static_syms = 0;
4744   subpst->compunit_symtab = NULL;
4745   subpst->read_symtab = pst->read_symtab;
4746   subpst->readin = 0;
4747
4748   /* No private part is necessary for include psymtabs.  This property
4749      can be used to differentiate between such include psymtabs and
4750      the regular ones.  */
4751   subpst->read_symtab_private = NULL;
4752 }
4753
4754 /* Read the Line Number Program data and extract the list of files
4755    included by the source file represented by PST.  Build an include
4756    partial symtab for each of these included files.  */
4757
4758 static void
4759 dwarf2_build_include_psymtabs (struct dwarf2_cu *cu,
4760                                struct die_info *die,
4761                                struct partial_symtab *pst)
4762 {
4763   line_header_up lh;
4764   struct attribute *attr;
4765
4766   attr = dwarf2_attr (die, DW_AT_stmt_list, cu);
4767   if (attr)
4768     lh = dwarf_decode_line_header ((sect_offset) DW_UNSND (attr), cu);
4769   if (lh == NULL)
4770     return;  /* No linetable, so no includes.  */
4771
4772   /* NOTE: pst->dirname is DW_AT_comp_dir (if present).  */
4773   dwarf_decode_lines (lh.get (), pst->dirname, cu, pst, pst->textlow, 1);
4774 }
4775
4776 static hashval_t
4777 hash_signatured_type (const void *item)
4778 {
4779   const struct signatured_type *sig_type
4780     = (const struct signatured_type *) item;
4781
4782   /* This drops the top 32 bits of the signature, but is ok for a hash.  */
4783   return sig_type->signature;
4784 }
4785
4786 static int
4787 eq_signatured_type (const void *item_lhs, const void *item_rhs)
4788 {
4789   const struct signatured_type *lhs = (const struct signatured_type *) item_lhs;
4790   const struct signatured_type *rhs = (const struct signatured_type *) item_rhs;
4791
4792   return lhs->signature == rhs->signature;
4793 }
4794
4795 /* Allocate a hash table for signatured types.  */
4796
4797 static htab_t
4798 allocate_signatured_type_table (struct objfile *objfile)
4799 {
4800   return htab_create_alloc_ex (41,
4801                                hash_signatured_type,
4802                                eq_signatured_type,
4803                                NULL,
4804                                &objfile->objfile_obstack,
4805                                hashtab_obstack_allocate,
4806                                dummy_obstack_deallocate);
4807 }
4808
4809 /* A helper function to add a signatured type CU to a table.  */
4810
4811 static int
4812 add_signatured_type_cu_to_table (void **slot, void *datum)
4813 {
4814   struct signatured_type *sigt = (struct signatured_type *) *slot;
4815   struct signatured_type ***datap = (struct signatured_type ***) datum;
4816
4817   **datap = sigt;
4818   ++*datap;
4819
4820   return 1;
4821 }
4822
4823 /* A helper for create_debug_types_hash_table.  Read types from SECTION
4824    and fill them into TYPES_HTAB.  It will process only type units,
4825    therefore DW_UT_type.  */
4826
4827 static void
4828 create_debug_type_hash_table (struct dwo_file *dwo_file,
4829                               dwarf2_section_info *section, htab_t &types_htab,
4830                               rcuh_kind section_kind)
4831 {
4832   struct objfile *objfile = dwarf2_per_objfile->objfile;
4833   struct dwarf2_section_info *abbrev_section;
4834   bfd *abfd;
4835   const gdb_byte *info_ptr, *end_ptr;
4836
4837   abbrev_section = (dwo_file != NULL
4838                     ? &dwo_file->sections.abbrev
4839                     : &dwarf2_per_objfile->abbrev);
4840
4841   if (dwarf_read_debug)
4842     fprintf_unfiltered (gdb_stdlog, "Reading %s for %s:\n",
4843                         get_section_name (section),
4844                         get_section_file_name (abbrev_section));
4845
4846   dwarf2_read_section (objfile, section);
4847   info_ptr = section->buffer;
4848
4849   if (info_ptr == NULL)
4850     return;
4851
4852   /* We can't set abfd until now because the section may be empty or
4853      not present, in which case the bfd is unknown.  */
4854   abfd = get_section_bfd_owner (section);
4855
4856   /* We don't use init_cutu_and_read_dies_simple, or some such, here
4857      because we don't need to read any dies: the signature is in the
4858      header.  */
4859
4860   end_ptr = info_ptr + section->size;
4861   while (info_ptr < end_ptr)
4862     {
4863       struct signatured_type *sig_type;
4864       struct dwo_unit *dwo_tu;
4865       void **slot;
4866       const gdb_byte *ptr = info_ptr;
4867       struct comp_unit_head header;
4868       unsigned int length;
4869
4870       sect_offset sect_off = (sect_offset) (ptr - section->buffer);
4871
4872       /* Initialize it due to a false compiler warning.  */
4873       header.signature = -1;
4874       header.type_cu_offset_in_tu = (cu_offset) -1;
4875
4876       /* We need to read the type's signature in order to build the hash
4877          table, but we don't need anything else just yet.  */
4878
4879       ptr = read_and_check_comp_unit_head (&header, section,
4880                                            abbrev_section, ptr, section_kind);
4881
4882       length = get_cu_length (&header);
4883
4884       /* Skip dummy type units.  */
4885       if (ptr >= info_ptr + length
4886           || peek_abbrev_code (abfd, ptr) == 0
4887           || header.unit_type != DW_UT_type)
4888         {
4889           info_ptr += length;
4890           continue;
4891         }
4892
4893       if (types_htab == NULL)
4894         {
4895           if (dwo_file)
4896             types_htab = allocate_dwo_unit_table (objfile);
4897           else
4898             types_htab = allocate_signatured_type_table (objfile);
4899         }
4900
4901       if (dwo_file)
4902         {
4903           sig_type = NULL;
4904           dwo_tu = OBSTACK_ZALLOC (&objfile->objfile_obstack,
4905                                    struct dwo_unit);
4906           dwo_tu->dwo_file = dwo_file;
4907           dwo_tu->signature = header.signature;
4908           dwo_tu->type_offset_in_tu = header.type_cu_offset_in_tu;
4909           dwo_tu->section = section;
4910           dwo_tu->sect_off = sect_off;
4911           dwo_tu->length = length;
4912         }
4913       else
4914         {
4915           /* N.B.: type_offset is not usable if this type uses a DWO file.
4916              The real type_offset is in the DWO file.  */
4917           dwo_tu = NULL;
4918           sig_type = OBSTACK_ZALLOC (&objfile->objfile_obstack,
4919                                      struct signatured_type);
4920           sig_type->signature = header.signature;
4921           sig_type->type_offset_in_tu = header.type_cu_offset_in_tu;
4922           sig_type->per_cu.objfile = objfile;
4923           sig_type->per_cu.is_debug_types = 1;
4924           sig_type->per_cu.section = section;
4925           sig_type->per_cu.sect_off = sect_off;
4926           sig_type->per_cu.length = length;
4927         }
4928
4929       slot = htab_find_slot (types_htab,
4930                              dwo_file ? (void*) dwo_tu : (void *) sig_type,
4931                              INSERT);
4932       gdb_assert (slot != NULL);
4933       if (*slot != NULL)
4934         {
4935           sect_offset dup_sect_off;
4936
4937           if (dwo_file)
4938             {
4939               const struct dwo_unit *dup_tu
4940                 = (const struct dwo_unit *) *slot;
4941
4942               dup_sect_off = dup_tu->sect_off;
4943             }
4944           else
4945             {
4946               const struct signatured_type *dup_tu
4947                 = (const struct signatured_type *) *slot;
4948
4949               dup_sect_off = dup_tu->per_cu.sect_off;
4950             }
4951
4952           complaint (&symfile_complaints,
4953                      _("debug type entry at offset 0x%x is duplicate to"
4954                        " the entry at offset 0x%x, signature %s"),
4955                      to_underlying (sect_off), to_underlying (dup_sect_off),
4956                      hex_string (header.signature));
4957         }
4958       *slot = dwo_file ? (void *) dwo_tu : (void *) sig_type;
4959
4960       if (dwarf_read_debug > 1)
4961         fprintf_unfiltered (gdb_stdlog, "  offset 0x%x, signature %s\n",
4962                             to_underlying (sect_off),
4963                             hex_string (header.signature));
4964
4965       info_ptr += length;
4966     }
4967 }
4968
4969 /* Create the hash table of all entries in the .debug_types
4970    (or .debug_types.dwo) section(s).
4971    If reading a DWO file, then DWO_FILE is a pointer to the DWO file object,
4972    otherwise it is NULL.
4973
4974    The result is a pointer to the hash table or NULL if there are no types.
4975
4976    Note: This function processes DWO files only, not DWP files.  */
4977
4978 static void
4979 create_debug_types_hash_table (struct dwo_file *dwo_file,
4980                                VEC (dwarf2_section_info_def) *types,
4981                                htab_t &types_htab)
4982 {
4983   int ix;
4984   struct dwarf2_section_info *section;
4985
4986   if (VEC_empty (dwarf2_section_info_def, types))
4987     return;
4988
4989   for (ix = 0;
4990        VEC_iterate (dwarf2_section_info_def, types, ix, section);
4991        ++ix)
4992     create_debug_type_hash_table (dwo_file, section, types_htab,
4993                                   rcuh_kind::TYPE);
4994 }
4995
4996 /* Create the hash table of all entries in the .debug_types section,
4997    and initialize all_type_units.
4998    The result is zero if there is an error (e.g. missing .debug_types section),
4999    otherwise non-zero.  */
5000
5001 static int
5002 create_all_type_units (struct objfile *objfile)
5003 {
5004   htab_t types_htab = NULL;
5005   struct signatured_type **iter;
5006
5007   create_debug_type_hash_table (NULL, &dwarf2_per_objfile->info, types_htab,
5008                                 rcuh_kind::COMPILE);
5009   create_debug_types_hash_table (NULL, dwarf2_per_objfile->types, types_htab);
5010   if (types_htab == NULL)
5011     {
5012       dwarf2_per_objfile->signatured_types = NULL;
5013       return 0;
5014     }
5015
5016   dwarf2_per_objfile->signatured_types = types_htab;
5017
5018   dwarf2_per_objfile->n_type_units
5019     = dwarf2_per_objfile->n_allocated_type_units
5020     = htab_elements (types_htab);
5021   dwarf2_per_objfile->all_type_units =
5022     XNEWVEC (struct signatured_type *, dwarf2_per_objfile->n_type_units);
5023   iter = &dwarf2_per_objfile->all_type_units[0];
5024   htab_traverse_noresize (types_htab, add_signatured_type_cu_to_table, &iter);
5025   gdb_assert (iter - &dwarf2_per_objfile->all_type_units[0]
5026               == dwarf2_per_objfile->n_type_units);
5027
5028   return 1;
5029 }
5030
5031 /* Add an entry for signature SIG to dwarf2_per_objfile->signatured_types.
5032    If SLOT is non-NULL, it is the entry to use in the hash table.
5033    Otherwise we find one.  */
5034
5035 static struct signatured_type *
5036 add_type_unit (ULONGEST sig, void **slot)
5037 {
5038   struct objfile *objfile = dwarf2_per_objfile->objfile;
5039   int n_type_units = dwarf2_per_objfile->n_type_units;
5040   struct signatured_type *sig_type;
5041
5042   gdb_assert (n_type_units <= dwarf2_per_objfile->n_allocated_type_units);
5043   ++n_type_units;
5044   if (n_type_units > dwarf2_per_objfile->n_allocated_type_units)
5045     {
5046       if (dwarf2_per_objfile->n_allocated_type_units == 0)
5047         dwarf2_per_objfile->n_allocated_type_units = 1;
5048       dwarf2_per_objfile->n_allocated_type_units *= 2;
5049       dwarf2_per_objfile->all_type_units
5050         = XRESIZEVEC (struct signatured_type *,
5051                       dwarf2_per_objfile->all_type_units,
5052                       dwarf2_per_objfile->n_allocated_type_units);
5053       ++dwarf2_per_objfile->tu_stats.nr_all_type_units_reallocs;
5054     }
5055   dwarf2_per_objfile->n_type_units = n_type_units;
5056
5057   sig_type = OBSTACK_ZALLOC (&objfile->objfile_obstack,
5058                              struct signatured_type);
5059   dwarf2_per_objfile->all_type_units[n_type_units - 1] = sig_type;
5060   sig_type->signature = sig;
5061   sig_type->per_cu.is_debug_types = 1;
5062   if (dwarf2_per_objfile->using_index)
5063     {
5064       sig_type->per_cu.v.quick =
5065         OBSTACK_ZALLOC (&objfile->objfile_obstack,
5066                         struct dwarf2_per_cu_quick_data);
5067     }
5068
5069   if (slot == NULL)
5070     {
5071       slot = htab_find_slot (dwarf2_per_objfile->signatured_types,
5072                              sig_type, INSERT);
5073     }
5074   gdb_assert (*slot == NULL);
5075   *slot = sig_type;
5076   /* The rest of sig_type must be filled in by the caller.  */
5077   return sig_type;
5078 }
5079
5080 /* Subroutine of lookup_dwo_signatured_type and lookup_dwp_signatured_type.
5081    Fill in SIG_ENTRY with DWO_ENTRY.  */
5082
5083 static void
5084 fill_in_sig_entry_from_dwo_entry (struct objfile *objfile,
5085                                   struct signatured_type *sig_entry,
5086                                   struct dwo_unit *dwo_entry)
5087 {
5088   /* Make sure we're not clobbering something we don't expect to.  */
5089   gdb_assert (! sig_entry->per_cu.queued);
5090   gdb_assert (sig_entry->per_cu.cu == NULL);
5091   if (dwarf2_per_objfile->using_index)
5092     {
5093       gdb_assert (sig_entry->per_cu.v.quick != NULL);
5094       gdb_assert (sig_entry->per_cu.v.quick->compunit_symtab == NULL);
5095     }
5096   else
5097       gdb_assert (sig_entry->per_cu.v.psymtab == NULL);
5098   gdb_assert (sig_entry->signature == dwo_entry->signature);
5099   gdb_assert (to_underlying (sig_entry->type_offset_in_section) == 0);
5100   gdb_assert (sig_entry->type_unit_group == NULL);
5101   gdb_assert (sig_entry->dwo_unit == NULL);
5102
5103   sig_entry->per_cu.section = dwo_entry->section;
5104   sig_entry->per_cu.sect_off = dwo_entry->sect_off;
5105   sig_entry->per_cu.length = dwo_entry->length;
5106   sig_entry->per_cu.reading_dwo_directly = 1;
5107   sig_entry->per_cu.objfile = objfile;
5108   sig_entry->type_offset_in_tu = dwo_entry->type_offset_in_tu;
5109   sig_entry->dwo_unit = dwo_entry;
5110 }
5111
5112 /* Subroutine of lookup_signatured_type.
5113    If we haven't read the TU yet, create the signatured_type data structure
5114    for a TU to be read in directly from a DWO file, bypassing the stub.
5115    This is the "Stay in DWO Optimization": When there is no DWP file and we're
5116    using .gdb_index, then when reading a CU we want to stay in the DWO file
5117    containing that CU.  Otherwise we could end up reading several other DWO
5118    files (due to comdat folding) to process the transitive closure of all the
5119    mentioned TUs, and that can be slow.  The current DWO file will have every
5120    type signature that it needs.
5121    We only do this for .gdb_index because in the psymtab case we already have
5122    to read all the DWOs to build the type unit groups.  */
5123
5124 static struct signatured_type *
5125 lookup_dwo_signatured_type (struct dwarf2_cu *cu, ULONGEST sig)
5126 {
5127   struct objfile *objfile = dwarf2_per_objfile->objfile;
5128   struct dwo_file *dwo_file;
5129   struct dwo_unit find_dwo_entry, *dwo_entry;
5130   struct signatured_type find_sig_entry, *sig_entry;
5131   void **slot;
5132
5133   gdb_assert (cu->dwo_unit && dwarf2_per_objfile->using_index);
5134
5135   /* If TU skeletons have been removed then we may not have read in any
5136      TUs yet.  */
5137   if (dwarf2_per_objfile->signatured_types == NULL)
5138     {
5139       dwarf2_per_objfile->signatured_types
5140         = allocate_signatured_type_table (objfile);
5141     }
5142
5143   /* We only ever need to read in one copy of a signatured type.
5144      Use the global signatured_types array to do our own comdat-folding
5145      of types.  If this is the first time we're reading this TU, and
5146      the TU has an entry in .gdb_index, replace the recorded data from
5147      .gdb_index with this TU.  */
5148
5149   find_sig_entry.signature = sig;
5150   slot = htab_find_slot (dwarf2_per_objfile->signatured_types,
5151                          &find_sig_entry, INSERT);
5152   sig_entry = (struct signatured_type *) *slot;
5153
5154   /* We can get here with the TU already read, *or* in the process of being
5155      read.  Don't reassign the global entry to point to this DWO if that's
5156      the case.  Also note that if the TU is already being read, it may not
5157      have come from a DWO, the program may be a mix of Fission-compiled
5158      code and non-Fission-compiled code.  */
5159
5160   /* Have we already tried to read this TU?
5161      Note: sig_entry can be NULL if the skeleton TU was removed (thus it
5162      needn't exist in the global table yet).  */
5163   if (sig_entry != NULL && sig_entry->per_cu.tu_read)
5164     return sig_entry;
5165
5166   /* Note: cu->dwo_unit is the dwo_unit that references this TU, not the
5167      dwo_unit of the TU itself.  */
5168   dwo_file = cu->dwo_unit->dwo_file;
5169
5170   /* Ok, this is the first time we're reading this TU.  */
5171   if (dwo_file->tus == NULL)
5172     return NULL;
5173   find_dwo_entry.signature = sig;
5174   dwo_entry = (struct dwo_unit *) htab_find (dwo_file->tus, &find_dwo_entry);
5175   if (dwo_entry == NULL)
5176     return NULL;
5177
5178   /* If the global table doesn't have an entry for this TU, add one.  */
5179   if (sig_entry == NULL)
5180     sig_entry = add_type_unit (sig, slot);
5181
5182   fill_in_sig_entry_from_dwo_entry (objfile, sig_entry, dwo_entry);
5183   sig_entry->per_cu.tu_read = 1;
5184   return sig_entry;
5185 }
5186
5187 /* Subroutine of lookup_signatured_type.
5188    Look up the type for signature SIG, and if we can't find SIG in .gdb_index
5189    then try the DWP file.  If the TU stub (skeleton) has been removed then
5190    it won't be in .gdb_index.  */
5191
5192 static struct signatured_type *
5193 lookup_dwp_signatured_type (struct dwarf2_cu *cu, ULONGEST sig)
5194 {
5195   struct objfile *objfile = dwarf2_per_objfile->objfile;
5196   struct dwp_file *dwp_file = get_dwp_file ();
5197   struct dwo_unit *dwo_entry;
5198   struct signatured_type find_sig_entry, *sig_entry;
5199   void **slot;
5200
5201   gdb_assert (cu->dwo_unit && dwarf2_per_objfile->using_index);
5202   gdb_assert (dwp_file != NULL);
5203
5204   /* If TU skeletons have been removed then we may not have read in any
5205      TUs yet.  */
5206   if (dwarf2_per_objfile->signatured_types == NULL)
5207     {
5208       dwarf2_per_objfile->signatured_types
5209         = allocate_signatured_type_table (objfile);
5210     }
5211
5212   find_sig_entry.signature = sig;
5213   slot = htab_find_slot (dwarf2_per_objfile->signatured_types,
5214                          &find_sig_entry, INSERT);
5215   sig_entry = (struct signatured_type *) *slot;
5216
5217   /* Have we already tried to read this TU?
5218      Note: sig_entry can be NULL if the skeleton TU was removed (thus it
5219      needn't exist in the global table yet).  */
5220   if (sig_entry != NULL)
5221     return sig_entry;
5222
5223   if (dwp_file->tus == NULL)
5224     return NULL;
5225   dwo_entry = lookup_dwo_unit_in_dwp (dwp_file, NULL,
5226                                       sig, 1 /* is_debug_types */);
5227   if (dwo_entry == NULL)
5228     return NULL;
5229
5230   sig_entry = add_type_unit (sig, slot);
5231   fill_in_sig_entry_from_dwo_entry (objfile, sig_entry, dwo_entry);
5232
5233   return sig_entry;
5234 }
5235
5236 /* Lookup a signature based type for DW_FORM_ref_sig8.
5237    Returns NULL if signature SIG is not present in the table.
5238    It is up to the caller to complain about this.  */
5239
5240 static struct signatured_type *
5241 lookup_signatured_type (struct dwarf2_cu *cu, ULONGEST sig)
5242 {
5243   if (cu->dwo_unit
5244       && dwarf2_per_objfile->using_index)
5245     {
5246       /* We're in a DWO/DWP file, and we're using .gdb_index.
5247          These cases require special processing.  */
5248       if (get_dwp_file () == NULL)
5249         return lookup_dwo_signatured_type (cu, sig);
5250       else
5251         return lookup_dwp_signatured_type (cu, sig);
5252     }
5253   else
5254     {
5255       struct signatured_type find_entry, *entry;
5256
5257       if (dwarf2_per_objfile->signatured_types == NULL)
5258         return NULL;
5259       find_entry.signature = sig;
5260       entry = ((struct signatured_type *)
5261                htab_find (dwarf2_per_objfile->signatured_types, &find_entry));
5262       return entry;
5263     }
5264 }
5265 \f
5266 /* Low level DIE reading support.  */
5267
5268 /* Initialize a die_reader_specs struct from a dwarf2_cu struct.  */
5269
5270 static void
5271 init_cu_die_reader (struct die_reader_specs *reader,
5272                     struct dwarf2_cu *cu,
5273                     struct dwarf2_section_info *section,
5274                     struct dwo_file *dwo_file)
5275 {
5276   gdb_assert (section->readin && section->buffer != NULL);
5277   reader->abfd = get_section_bfd_owner (section);
5278   reader->cu = cu;
5279   reader->dwo_file = dwo_file;
5280   reader->die_section = section;
5281   reader->buffer = section->buffer;
5282   reader->buffer_end = section->buffer + section->size;
5283   reader->comp_dir = NULL;
5284 }
5285
5286 /* Subroutine of init_cutu_and_read_dies to simplify it.
5287    Read in the rest of a CU/TU top level DIE from DWO_UNIT.
5288    There's just a lot of work to do, and init_cutu_and_read_dies is big enough
5289    already.
5290
5291    STUB_COMP_UNIT_DIE is for the stub DIE, we copy over certain attributes
5292    from it to the DIE in the DWO.  If NULL we are skipping the stub.
5293    STUB_COMP_DIR is similar to STUB_COMP_UNIT_DIE: When reading a TU directly
5294    from the DWO file, bypassing the stub, it contains the DW_AT_comp_dir
5295    attribute of the referencing CU.  At most one of STUB_COMP_UNIT_DIE and
5296    STUB_COMP_DIR may be non-NULL.
5297    *RESULT_READER,*RESULT_INFO_PTR,*RESULT_COMP_UNIT_DIE,*RESULT_HAS_CHILDREN
5298    are filled in with the info of the DIE from the DWO file.
5299    ABBREV_TABLE_PROVIDED is non-zero if the caller of init_cutu_and_read_dies
5300    provided an abbrev table to use.
5301    The result is non-zero if a valid (non-dummy) DIE was found.  */
5302
5303 static int
5304 read_cutu_die_from_dwo (struct dwarf2_per_cu_data *this_cu,
5305                         struct dwo_unit *dwo_unit,
5306                         int abbrev_table_provided,
5307                         struct die_info *stub_comp_unit_die,
5308                         const char *stub_comp_dir,
5309                         struct die_reader_specs *result_reader,
5310                         const gdb_byte **result_info_ptr,
5311                         struct die_info **result_comp_unit_die,
5312                         int *result_has_children)
5313 {
5314   struct objfile *objfile = dwarf2_per_objfile->objfile;
5315   struct dwarf2_cu *cu = this_cu->cu;
5316   struct dwarf2_section_info *section;
5317   bfd *abfd;
5318   const gdb_byte *begin_info_ptr, *info_ptr;
5319   ULONGEST signature; /* Or dwo_id.  */
5320   struct attribute *comp_dir, *stmt_list, *low_pc, *high_pc, *ranges;
5321   int i,num_extra_attrs;
5322   struct dwarf2_section_info *dwo_abbrev_section;
5323   struct attribute *attr;
5324   struct die_info *comp_unit_die;
5325
5326   /* At most one of these may be provided.  */
5327   gdb_assert ((stub_comp_unit_die != NULL) + (stub_comp_dir != NULL) <= 1);
5328
5329   /* These attributes aren't processed until later:
5330      DW_AT_stmt_list, DW_AT_low_pc, DW_AT_high_pc, DW_AT_ranges.
5331      DW_AT_comp_dir is used now, to find the DWO file, but it is also
5332      referenced later.  However, these attributes are found in the stub
5333      which we won't have later.  In order to not impose this complication
5334      on the rest of the code, we read them here and copy them to the
5335      DWO CU/TU die.  */
5336
5337   stmt_list = NULL;
5338   low_pc = NULL;
5339   high_pc = NULL;
5340   ranges = NULL;
5341   comp_dir = NULL;
5342
5343   if (stub_comp_unit_die != NULL)
5344     {
5345       /* For TUs in DWO files, the DW_AT_stmt_list attribute lives in the
5346          DWO file.  */
5347       if (! this_cu->is_debug_types)
5348         stmt_list = dwarf2_attr (stub_comp_unit_die, DW_AT_stmt_list, cu);
5349       low_pc = dwarf2_attr (stub_comp_unit_die, DW_AT_low_pc, cu);
5350       high_pc = dwarf2_attr (stub_comp_unit_die, DW_AT_high_pc, cu);
5351       ranges = dwarf2_attr (stub_comp_unit_die, DW_AT_ranges, cu);
5352       comp_dir = dwarf2_attr (stub_comp_unit_die, DW_AT_comp_dir, cu);
5353
5354       /* There should be a DW_AT_addr_base attribute here (if needed).
5355          We need the value before we can process DW_FORM_GNU_addr_index.  */
5356       cu->addr_base = 0;
5357       attr = dwarf2_attr (stub_comp_unit_die, DW_AT_GNU_addr_base, cu);
5358       if (attr)
5359         cu->addr_base = DW_UNSND (attr);
5360
5361       /* There should be a DW_AT_ranges_base attribute here (if needed).
5362          We need the value before we can process DW_AT_ranges.  */
5363       cu->ranges_base = 0;
5364       attr = dwarf2_attr (stub_comp_unit_die, DW_AT_GNU_ranges_base, cu);
5365       if (attr)
5366         cu->ranges_base = DW_UNSND (attr);
5367     }
5368   else if (stub_comp_dir != NULL)
5369     {
5370       /* Reconstruct the comp_dir attribute to simplify the code below.  */
5371       comp_dir = XOBNEW (&cu->comp_unit_obstack, struct attribute);
5372       comp_dir->name = DW_AT_comp_dir;
5373       comp_dir->form = DW_FORM_string;
5374       DW_STRING_IS_CANONICAL (comp_dir) = 0;
5375       DW_STRING (comp_dir) = stub_comp_dir;
5376     }
5377
5378   /* Set up for reading the DWO CU/TU.  */
5379   cu->dwo_unit = dwo_unit;
5380   section = dwo_unit->section;
5381   dwarf2_read_section (objfile, section);
5382   abfd = get_section_bfd_owner (section);
5383   begin_info_ptr = info_ptr = (section->buffer
5384                                + to_underlying (dwo_unit->sect_off));
5385   dwo_abbrev_section = &dwo_unit->dwo_file->sections.abbrev;
5386   init_cu_die_reader (result_reader, cu, section, dwo_unit->dwo_file);
5387
5388   if (this_cu->is_debug_types)
5389     {
5390       struct signatured_type *sig_type = (struct signatured_type *) this_cu;
5391
5392       info_ptr = read_and_check_comp_unit_head (&cu->header, section,
5393                                                 dwo_abbrev_section,
5394                                                 info_ptr, rcuh_kind::TYPE);
5395       /* This is not an assert because it can be caused by bad debug info.  */
5396       if (sig_type->signature != cu->header.signature)
5397         {
5398           error (_("Dwarf Error: signature mismatch %s vs %s while reading"
5399                    " TU at offset 0x%x [in module %s]"),
5400                  hex_string (sig_type->signature),
5401                  hex_string (cu->header.signature),
5402                  to_underlying (dwo_unit->sect_off),
5403                  bfd_get_filename (abfd));
5404         }
5405       gdb_assert (dwo_unit->sect_off == cu->header.sect_off);
5406       /* For DWOs coming from DWP files, we don't know the CU length
5407          nor the type's offset in the TU until now.  */
5408       dwo_unit->length = get_cu_length (&cu->header);
5409       dwo_unit->type_offset_in_tu = cu->header.type_cu_offset_in_tu;
5410
5411       /* Establish the type offset that can be used to lookup the type.
5412          For DWO files, we don't know it until now.  */
5413       sig_type->type_offset_in_section
5414         = dwo_unit->sect_off + to_underlying (dwo_unit->type_offset_in_tu);
5415     }
5416   else
5417     {
5418       info_ptr = read_and_check_comp_unit_head (&cu->header, section,
5419                                                 dwo_abbrev_section,
5420                                                 info_ptr, rcuh_kind::COMPILE);
5421       gdb_assert (dwo_unit->sect_off == cu->header.sect_off);
5422       /* For DWOs coming from DWP files, we don't know the CU length
5423          until now.  */
5424       dwo_unit->length = get_cu_length (&cu->header);
5425     }
5426
5427   /* Replace the CU's original abbrev table with the DWO's.
5428      Reminder: We can't read the abbrev table until we've read the header.  */
5429   if (abbrev_table_provided)
5430     {
5431       /* Don't free the provided abbrev table, the caller of
5432          init_cutu_and_read_dies owns it.  */
5433       dwarf2_read_abbrevs (cu, dwo_abbrev_section);
5434       /* Ensure the DWO abbrev table gets freed.  */
5435       make_cleanup (dwarf2_free_abbrev_table, cu);
5436     }
5437   else
5438     {
5439       dwarf2_free_abbrev_table (cu);
5440       dwarf2_read_abbrevs (cu, dwo_abbrev_section);
5441       /* Leave any existing abbrev table cleanup as is.  */
5442     }
5443
5444   /* Read in the die, but leave space to copy over the attributes
5445      from the stub.  This has the benefit of simplifying the rest of
5446      the code - all the work to maintain the illusion of a single
5447      DW_TAG_{compile,type}_unit DIE is done here.  */
5448   num_extra_attrs = ((stmt_list != NULL)
5449                      + (low_pc != NULL)
5450                      + (high_pc != NULL)
5451                      + (ranges != NULL)
5452                      + (comp_dir != NULL));
5453   info_ptr = read_full_die_1 (result_reader, result_comp_unit_die, info_ptr,
5454                               result_has_children, num_extra_attrs);
5455
5456   /* Copy over the attributes from the stub to the DIE we just read in.  */
5457   comp_unit_die = *result_comp_unit_die;
5458   i = comp_unit_die->num_attrs;
5459   if (stmt_list != NULL)
5460     comp_unit_die->attrs[i++] = *stmt_list;
5461   if (low_pc != NULL)
5462     comp_unit_die->attrs[i++] = *low_pc;
5463   if (high_pc != NULL)
5464     comp_unit_die->attrs[i++] = *high_pc;
5465   if (ranges != NULL)
5466     comp_unit_die->attrs[i++] = *ranges;
5467   if (comp_dir != NULL)
5468     comp_unit_die->attrs[i++] = *comp_dir;
5469   comp_unit_die->num_attrs += num_extra_attrs;
5470
5471   if (dwarf_die_debug)
5472     {
5473       fprintf_unfiltered (gdb_stdlog,
5474                           "Read die from %s@0x%x of %s:\n",
5475                           get_section_name (section),
5476                           (unsigned) (begin_info_ptr - section->buffer),
5477                           bfd_get_filename (abfd));
5478       dump_die (comp_unit_die, dwarf_die_debug);
5479     }
5480
5481   /* Save the comp_dir attribute.  If there is no DWP file then we'll read
5482      TUs by skipping the stub and going directly to the entry in the DWO file.
5483      However, skipping the stub means we won't get DW_AT_comp_dir, so we have
5484      to get it via circuitous means.  Blech.  */
5485   if (comp_dir != NULL)
5486     result_reader->comp_dir = DW_STRING (comp_dir);
5487
5488   /* Skip dummy compilation units.  */
5489   if (info_ptr >= begin_info_ptr + dwo_unit->length
5490       || peek_abbrev_code (abfd, info_ptr) == 0)
5491     return 0;
5492
5493   *result_info_ptr = info_ptr;
5494   return 1;
5495 }
5496
5497 /* Subroutine of init_cutu_and_read_dies to simplify it.
5498    Look up the DWO unit specified by COMP_UNIT_DIE of THIS_CU.
5499    Returns NULL if the specified DWO unit cannot be found.  */
5500
5501 static struct dwo_unit *
5502 lookup_dwo_unit (struct dwarf2_per_cu_data *this_cu,
5503                  struct die_info *comp_unit_die)
5504 {
5505   struct dwarf2_cu *cu = this_cu->cu;
5506   struct attribute *attr;
5507   ULONGEST signature;
5508   struct dwo_unit *dwo_unit;
5509   const char *comp_dir, *dwo_name;
5510
5511   gdb_assert (cu != NULL);
5512
5513   /* Yeah, we look dwo_name up again, but it simplifies the code.  */
5514   dwo_name = dwarf2_string_attr (comp_unit_die, DW_AT_GNU_dwo_name, cu);
5515   comp_dir = dwarf2_string_attr (comp_unit_die, DW_AT_comp_dir, cu);
5516
5517   if (this_cu->is_debug_types)
5518     {
5519       struct signatured_type *sig_type;
5520
5521       /* Since this_cu is the first member of struct signatured_type,
5522          we can go from a pointer to one to a pointer to the other.  */
5523       sig_type = (struct signatured_type *) this_cu;
5524       signature = sig_type->signature;
5525       dwo_unit = lookup_dwo_type_unit (sig_type, dwo_name, comp_dir);
5526     }
5527   else
5528     {
5529       struct attribute *attr;
5530
5531       attr = dwarf2_attr (comp_unit_die, DW_AT_GNU_dwo_id, cu);
5532       if (! attr)
5533         error (_("Dwarf Error: missing dwo_id for dwo_name %s"
5534                  " [in module %s]"),
5535                dwo_name, objfile_name (this_cu->objfile));
5536       signature = DW_UNSND (attr);
5537       dwo_unit = lookup_dwo_comp_unit (this_cu, dwo_name, comp_dir,
5538                                        signature);
5539     }
5540
5541   return dwo_unit;
5542 }
5543
5544 /* Subroutine of init_cutu_and_read_dies to simplify it.
5545    See it for a description of the parameters.
5546    Read a TU directly from a DWO file, bypassing the stub.
5547
5548    Note: This function could be a little bit simpler if we shared cleanups
5549    with our caller, init_cutu_and_read_dies.  That's generally a fragile thing
5550    to do, so we keep this function self-contained.  Or we could move this
5551    into our caller, but it's complex enough already.  */
5552
5553 static void
5554 init_tu_and_read_dwo_dies (struct dwarf2_per_cu_data *this_cu,
5555                            int use_existing_cu, int keep,
5556                            die_reader_func_ftype *die_reader_func,
5557                            void *data)
5558 {
5559   struct dwarf2_cu *cu;
5560   struct signatured_type *sig_type;
5561   struct cleanup *cleanups, *free_cu_cleanup = NULL;
5562   struct die_reader_specs reader;
5563   const gdb_byte *info_ptr;
5564   struct die_info *comp_unit_die;
5565   int has_children;
5566
5567   /* Verify we can do the following downcast, and that we have the
5568      data we need.  */
5569   gdb_assert (this_cu->is_debug_types && this_cu->reading_dwo_directly);
5570   sig_type = (struct signatured_type *) this_cu;
5571   gdb_assert (sig_type->dwo_unit != NULL);
5572
5573   cleanups = make_cleanup (null_cleanup, NULL);
5574
5575   if (use_existing_cu && this_cu->cu != NULL)
5576     {
5577       gdb_assert (this_cu->cu->dwo_unit == sig_type->dwo_unit);
5578       cu = this_cu->cu;
5579       /* There's no need to do the rereading_dwo_cu handling that
5580          init_cutu_and_read_dies does since we don't read the stub.  */
5581     }
5582   else
5583     {
5584       /* If !use_existing_cu, this_cu->cu must be NULL.  */
5585       gdb_assert (this_cu->cu == NULL);
5586       cu = XNEW (struct dwarf2_cu);
5587       init_one_comp_unit (cu, this_cu);
5588       /* If an error occurs while loading, release our storage.  */
5589       free_cu_cleanup = make_cleanup (free_heap_comp_unit, cu);
5590     }
5591
5592   /* A future optimization, if needed, would be to use an existing
5593      abbrev table.  When reading DWOs with skeletonless TUs, all the TUs
5594      could share abbrev tables.  */
5595
5596   if (read_cutu_die_from_dwo (this_cu, sig_type->dwo_unit,
5597                               0 /* abbrev_table_provided */,
5598                               NULL /* stub_comp_unit_die */,
5599                               sig_type->dwo_unit->dwo_file->comp_dir,
5600                               &reader, &info_ptr,
5601                               &comp_unit_die, &has_children) == 0)
5602     {
5603       /* Dummy die.  */
5604       do_cleanups (cleanups);
5605       return;
5606     }
5607
5608   /* All the "real" work is done here.  */
5609   die_reader_func (&reader, info_ptr, comp_unit_die, has_children, data);
5610
5611   /* This duplicates the code in init_cutu_and_read_dies,
5612      but the alternative is making the latter more complex.
5613      This function is only for the special case of using DWO files directly:
5614      no point in overly complicating the general case just to handle this.  */
5615   if (free_cu_cleanup != NULL)
5616     {
5617       if (keep)
5618         {
5619           /* We've successfully allocated this compilation unit.  Let our
5620              caller clean it up when finished with it.  */
5621           discard_cleanups (free_cu_cleanup);
5622
5623           /* We can only discard free_cu_cleanup and all subsequent cleanups.
5624              So we have to manually free the abbrev table.  */
5625           dwarf2_free_abbrev_table (cu);
5626
5627           /* Link this CU into read_in_chain.  */
5628           this_cu->cu->read_in_chain = dwarf2_per_objfile->read_in_chain;
5629           dwarf2_per_objfile->read_in_chain = this_cu;
5630         }
5631       else
5632         do_cleanups (free_cu_cleanup);
5633     }
5634
5635   do_cleanups (cleanups);
5636 }
5637
5638 /* Initialize a CU (or TU) and read its DIEs.
5639    If the CU defers to a DWO file, read the DWO file as well.
5640
5641    ABBREV_TABLE, if non-NULL, is the abbreviation table to use.
5642    Otherwise the table specified in the comp unit header is read in and used.
5643    This is an optimization for when we already have the abbrev table.
5644
5645    If USE_EXISTING_CU is non-zero, and THIS_CU->cu is non-NULL, then use it.
5646    Otherwise, a new CU is allocated with xmalloc.
5647
5648    If KEEP is non-zero, then if we allocated a dwarf2_cu we add it to
5649    read_in_chain.  Otherwise the dwarf2_cu data is freed at the end.
5650
5651    WARNING: If THIS_CU is a "dummy CU" (used as filler by the incremental
5652    linker) then DIE_READER_FUNC will not get called.  */
5653
5654 static void
5655 init_cutu_and_read_dies (struct dwarf2_per_cu_data *this_cu,
5656                          struct abbrev_table *abbrev_table,
5657                          int use_existing_cu, int keep,
5658                          die_reader_func_ftype *die_reader_func,
5659                          void *data)
5660 {
5661   struct objfile *objfile = dwarf2_per_objfile->objfile;
5662   struct dwarf2_section_info *section = this_cu->section;
5663   bfd *abfd = get_section_bfd_owner (section);
5664   struct dwarf2_cu *cu;
5665   const gdb_byte *begin_info_ptr, *info_ptr;
5666   struct die_reader_specs reader;
5667   struct die_info *comp_unit_die;
5668   int has_children;
5669   struct attribute *attr;
5670   struct cleanup *cleanups, *free_cu_cleanup = NULL;
5671   struct signatured_type *sig_type = NULL;
5672   struct dwarf2_section_info *abbrev_section;
5673   /* Non-zero if CU currently points to a DWO file and we need to
5674      reread it.  When this happens we need to reread the skeleton die
5675      before we can reread the DWO file (this only applies to CUs, not TUs).  */
5676   int rereading_dwo_cu = 0;
5677
5678   if (dwarf_die_debug)
5679     fprintf_unfiltered (gdb_stdlog, "Reading %s unit at offset 0x%x\n",
5680                         this_cu->is_debug_types ? "type" : "comp",
5681                         to_underlying (this_cu->sect_off));
5682
5683   if (use_existing_cu)
5684     gdb_assert (keep);
5685
5686   /* If we're reading a TU directly from a DWO file, including a virtual DWO
5687      file (instead of going through the stub), short-circuit all of this.  */
5688   if (this_cu->reading_dwo_directly)
5689     {
5690       /* Narrow down the scope of possibilities to have to understand.  */
5691       gdb_assert (this_cu->is_debug_types);
5692       gdb_assert (abbrev_table == NULL);
5693       init_tu_and_read_dwo_dies (this_cu, use_existing_cu, keep,
5694                                  die_reader_func, data);
5695       return;
5696     }
5697
5698   cleanups = make_cleanup (null_cleanup, NULL);
5699
5700   /* This is cheap if the section is already read in.  */
5701   dwarf2_read_section (objfile, section);
5702
5703   begin_info_ptr = info_ptr = section->buffer + to_underlying (this_cu->sect_off);
5704
5705   abbrev_section = get_abbrev_section_for_cu (this_cu);
5706
5707   if (use_existing_cu && this_cu->cu != NULL)
5708     {
5709       cu = this_cu->cu;
5710       /* If this CU is from a DWO file we need to start over, we need to
5711          refetch the attributes from the skeleton CU.
5712          This could be optimized by retrieving those attributes from when we
5713          were here the first time: the previous comp_unit_die was stored in
5714          comp_unit_obstack.  But there's no data yet that we need this
5715          optimization.  */
5716       if (cu->dwo_unit != NULL)
5717         rereading_dwo_cu = 1;
5718     }
5719   else
5720     {
5721       /* If !use_existing_cu, this_cu->cu must be NULL.  */
5722       gdb_assert (this_cu->cu == NULL);
5723       cu = XNEW (struct dwarf2_cu);
5724       init_one_comp_unit (cu, this_cu);
5725       /* If an error occurs while loading, release our storage.  */
5726       free_cu_cleanup = make_cleanup (free_heap_comp_unit, cu);
5727     }
5728
5729   /* Get the header.  */
5730   if (to_underlying (cu->header.first_die_cu_offset) != 0 && !rereading_dwo_cu)
5731     {
5732       /* We already have the header, there's no need to read it in again.  */
5733       info_ptr += to_underlying (cu->header.first_die_cu_offset);
5734     }
5735   else
5736     {
5737       if (this_cu->is_debug_types)
5738         {
5739           info_ptr = read_and_check_comp_unit_head (&cu->header, section,
5740                                                     abbrev_section, info_ptr,
5741                                                     rcuh_kind::TYPE);
5742
5743           /* Since per_cu is the first member of struct signatured_type,
5744              we can go from a pointer to one to a pointer to the other.  */
5745           sig_type = (struct signatured_type *) this_cu;
5746           gdb_assert (sig_type->signature == cu->header.signature);
5747           gdb_assert (sig_type->type_offset_in_tu
5748                       == cu->header.type_cu_offset_in_tu);
5749           gdb_assert (this_cu->sect_off == cu->header.sect_off);
5750
5751           /* LENGTH has not been set yet for type units if we're
5752              using .gdb_index.  */
5753           this_cu->length = get_cu_length (&cu->header);
5754
5755           /* Establish the type offset that can be used to lookup the type.  */
5756           sig_type->type_offset_in_section =
5757             this_cu->sect_off + to_underlying (sig_type->type_offset_in_tu);
5758
5759           this_cu->dwarf_version = cu->header.version;
5760         }
5761       else
5762         {
5763           info_ptr = read_and_check_comp_unit_head (&cu->header, section,
5764                                                     abbrev_section,
5765                                                     info_ptr,
5766                                                     rcuh_kind::COMPILE);
5767
5768           gdb_assert (this_cu->sect_off == cu->header.sect_off);
5769           gdb_assert (this_cu->length == get_cu_length (&cu->header));
5770           this_cu->dwarf_version = cu->header.version;
5771         }
5772     }
5773
5774   /* Skip dummy compilation units.  */
5775   if (info_ptr >= begin_info_ptr + this_cu->length
5776       || peek_abbrev_code (abfd, info_ptr) == 0)
5777     {
5778       do_cleanups (cleanups);
5779       return;
5780     }
5781
5782   /* If we don't have them yet, read the abbrevs for this compilation unit.
5783      And if we need to read them now, make sure they're freed when we're
5784      done.  Note that it's important that if the CU had an abbrev table
5785      on entry we don't free it when we're done: Somewhere up the call stack
5786      it may be in use.  */
5787   if (abbrev_table != NULL)
5788     {
5789       gdb_assert (cu->abbrev_table == NULL);
5790       gdb_assert (cu->header.abbrev_sect_off == abbrev_table->sect_off);
5791       cu->abbrev_table = abbrev_table;
5792     }
5793   else if (cu->abbrev_table == NULL)
5794     {
5795       dwarf2_read_abbrevs (cu, abbrev_section);
5796       make_cleanup (dwarf2_free_abbrev_table, cu);
5797     }
5798   else if (rereading_dwo_cu)
5799     {
5800       dwarf2_free_abbrev_table (cu);
5801       dwarf2_read_abbrevs (cu, abbrev_section);
5802     }
5803
5804   /* Read the top level CU/TU die.  */
5805   init_cu_die_reader (&reader, cu, section, NULL);
5806   info_ptr = read_full_die (&reader, &comp_unit_die, info_ptr, &has_children);
5807
5808   /* If we are in a DWO stub, process it and then read in the "real" CU/TU
5809      from the DWO file.
5810      Note that if USE_EXISTING_OK != 0, and THIS_CU->cu already contains a
5811      DWO CU, that this test will fail (the attribute will not be present).  */
5812   attr = dwarf2_attr (comp_unit_die, DW_AT_GNU_dwo_name, cu);
5813   if (attr)
5814     {
5815       struct dwo_unit *dwo_unit;
5816       struct die_info *dwo_comp_unit_die;
5817
5818       if (has_children)
5819         {
5820           complaint (&symfile_complaints,
5821                      _("compilation unit with DW_AT_GNU_dwo_name"
5822                        " has children (offset 0x%x) [in module %s]"),
5823                      to_underlying (this_cu->sect_off), bfd_get_filename (abfd));
5824         }
5825       dwo_unit = lookup_dwo_unit (this_cu, comp_unit_die);
5826       if (dwo_unit != NULL)
5827         {
5828           if (read_cutu_die_from_dwo (this_cu, dwo_unit,
5829                                       abbrev_table != NULL,
5830                                       comp_unit_die, NULL,
5831                                       &reader, &info_ptr,
5832                                       &dwo_comp_unit_die, &has_children) == 0)
5833             {
5834               /* Dummy die.  */
5835               do_cleanups (cleanups);
5836               return;
5837             }
5838           comp_unit_die = dwo_comp_unit_die;
5839         }
5840       else
5841         {
5842           /* Yikes, we couldn't find the rest of the DIE, we only have
5843              the stub.  A complaint has already been logged.  There's
5844              not much more we can do except pass on the stub DIE to
5845              die_reader_func.  We don't want to throw an error on bad
5846              debug info.  */
5847         }
5848     }
5849
5850   /* All of the above is setup for this call.  Yikes.  */
5851   die_reader_func (&reader, info_ptr, comp_unit_die, has_children, data);
5852
5853   /* Done, clean up.  */
5854   if (free_cu_cleanup != NULL)
5855     {
5856       if (keep)
5857         {
5858           /* We've successfully allocated this compilation unit.  Let our
5859              caller clean it up when finished with it.  */
5860           discard_cleanups (free_cu_cleanup);
5861
5862           /* We can only discard free_cu_cleanup and all subsequent cleanups.
5863              So we have to manually free the abbrev table.  */
5864           dwarf2_free_abbrev_table (cu);
5865
5866           /* Link this CU into read_in_chain.  */
5867           this_cu->cu->read_in_chain = dwarf2_per_objfile->read_in_chain;
5868           dwarf2_per_objfile->read_in_chain = this_cu;
5869         }
5870       else
5871         do_cleanups (free_cu_cleanup);
5872     }
5873
5874   do_cleanups (cleanups);
5875 }
5876
5877 /* Read CU/TU THIS_CU but do not follow DW_AT_GNU_dwo_name if present.
5878    DWO_FILE, if non-NULL, is the DWO file to read (the caller is assumed
5879    to have already done the lookup to find the DWO file).
5880
5881    The caller is required to fill in THIS_CU->section, THIS_CU->offset, and
5882    THIS_CU->is_debug_types, but nothing else.
5883
5884    We fill in THIS_CU->length.
5885
5886    WARNING: If THIS_CU is a "dummy CU" (used as filler by the incremental
5887    linker) then DIE_READER_FUNC will not get called.
5888
5889    THIS_CU->cu is always freed when done.
5890    This is done in order to not leave THIS_CU->cu in a state where we have
5891    to care whether it refers to the "main" CU or the DWO CU.  */
5892
5893 static void
5894 init_cutu_and_read_dies_no_follow (struct dwarf2_per_cu_data *this_cu,
5895                                    struct dwo_file *dwo_file,
5896                                    die_reader_func_ftype *die_reader_func,
5897                                    void *data)
5898 {
5899   struct objfile *objfile = dwarf2_per_objfile->objfile;
5900   struct dwarf2_section_info *section = this_cu->section;
5901   bfd *abfd = get_section_bfd_owner (section);
5902   struct dwarf2_section_info *abbrev_section;
5903   struct dwarf2_cu cu;
5904   const gdb_byte *begin_info_ptr, *info_ptr;
5905   struct die_reader_specs reader;
5906   struct cleanup *cleanups;
5907   struct die_info *comp_unit_die;
5908   int has_children;
5909
5910   if (dwarf_die_debug)
5911     fprintf_unfiltered (gdb_stdlog, "Reading %s unit at offset 0x%x\n",
5912                         this_cu->is_debug_types ? "type" : "comp",
5913                         to_underlying (this_cu->sect_off));
5914
5915   gdb_assert (this_cu->cu == NULL);
5916
5917   abbrev_section = (dwo_file != NULL
5918                     ? &dwo_file->sections.abbrev
5919                     : get_abbrev_section_for_cu (this_cu));
5920
5921   /* This is cheap if the section is already read in.  */
5922   dwarf2_read_section (objfile, section);
5923
5924   init_one_comp_unit (&cu, this_cu);
5925
5926   cleanups = make_cleanup (free_stack_comp_unit, &cu);
5927
5928   begin_info_ptr = info_ptr = section->buffer + to_underlying (this_cu->sect_off);
5929   info_ptr = read_and_check_comp_unit_head (&cu.header, section,
5930                                             abbrev_section, info_ptr,
5931                                             (this_cu->is_debug_types
5932                                              ? rcuh_kind::TYPE
5933                                              : rcuh_kind::COMPILE));
5934
5935   this_cu->length = get_cu_length (&cu.header);
5936
5937   /* Skip dummy compilation units.  */
5938   if (info_ptr >= begin_info_ptr + this_cu->length
5939       || peek_abbrev_code (abfd, info_ptr) == 0)
5940     {
5941       do_cleanups (cleanups);
5942       return;
5943     }
5944
5945   dwarf2_read_abbrevs (&cu, abbrev_section);
5946   make_cleanup (dwarf2_free_abbrev_table, &cu);
5947
5948   init_cu_die_reader (&reader, &cu, section, dwo_file);
5949   info_ptr = read_full_die (&reader, &comp_unit_die, info_ptr, &has_children);
5950
5951   die_reader_func (&reader, info_ptr, comp_unit_die, has_children, data);
5952
5953   do_cleanups (cleanups);
5954 }
5955
5956 /* Read a CU/TU, except that this does not look for DW_AT_GNU_dwo_name and
5957    does not lookup the specified DWO file.
5958    This cannot be used to read DWO files.
5959
5960    THIS_CU->cu is always freed when done.
5961    This is done in order to not leave THIS_CU->cu in a state where we have
5962    to care whether it refers to the "main" CU or the DWO CU.
5963    We can revisit this if the data shows there's a performance issue.  */
5964
5965 static void
5966 init_cutu_and_read_dies_simple (struct dwarf2_per_cu_data *this_cu,
5967                                 die_reader_func_ftype *die_reader_func,
5968                                 void *data)
5969 {
5970   init_cutu_and_read_dies_no_follow (this_cu, NULL, die_reader_func, data);
5971 }
5972 \f
5973 /* Type Unit Groups.
5974
5975    Type Unit Groups are a way to collapse the set of all TUs (type units) into
5976    a more manageable set.  The grouping is done by DW_AT_stmt_list entry
5977    so that all types coming from the same compilation (.o file) are grouped
5978    together.  A future step could be to put the types in the same symtab as
5979    the CU the types ultimately came from.  */
5980
5981 static hashval_t
5982 hash_type_unit_group (const void *item)
5983 {
5984   const struct type_unit_group *tu_group
5985     = (const struct type_unit_group *) item;
5986
5987   return hash_stmt_list_entry (&tu_group->hash);
5988 }
5989
5990 static int
5991 eq_type_unit_group (const void *item_lhs, const void *item_rhs)
5992 {
5993   const struct type_unit_group *lhs = (const struct type_unit_group *) item_lhs;
5994   const struct type_unit_group *rhs = (const struct type_unit_group *) item_rhs;
5995
5996   return eq_stmt_list_entry (&lhs->hash, &rhs->hash);
5997 }
5998
5999 /* Allocate a hash table for type unit groups.  */
6000
6001 static htab_t
6002 allocate_type_unit_groups_table (void)
6003 {
6004   return htab_create_alloc_ex (3,
6005                                hash_type_unit_group,
6006                                eq_type_unit_group,
6007                                NULL,
6008                                &dwarf2_per_objfile->objfile->objfile_obstack,
6009                                hashtab_obstack_allocate,
6010                                dummy_obstack_deallocate);
6011 }
6012
6013 /* Type units that don't have DW_AT_stmt_list are grouped into their own
6014    partial symtabs.  We combine several TUs per psymtab to not let the size
6015    of any one psymtab grow too big.  */
6016 #define NO_STMT_LIST_TYPE_UNIT_PSYMTAB (1 << 31)
6017 #define NO_STMT_LIST_TYPE_UNIT_PSYMTAB_SIZE 10
6018
6019 /* Helper routine for get_type_unit_group.
6020    Create the type_unit_group object used to hold one or more TUs.  */
6021
6022 static struct type_unit_group *
6023 create_type_unit_group (struct dwarf2_cu *cu, sect_offset line_offset_struct)
6024 {
6025   struct objfile *objfile = dwarf2_per_objfile->objfile;
6026   struct dwarf2_per_cu_data *per_cu;
6027   struct type_unit_group *tu_group;
6028
6029   tu_group = OBSTACK_ZALLOC (&objfile->objfile_obstack,
6030                              struct type_unit_group);
6031   per_cu = &tu_group->per_cu;
6032   per_cu->objfile = objfile;
6033
6034   if (dwarf2_per_objfile->using_index)
6035     {
6036       per_cu->v.quick = OBSTACK_ZALLOC (&objfile->objfile_obstack,
6037                                         struct dwarf2_per_cu_quick_data);
6038     }
6039   else
6040     {
6041       unsigned int line_offset = to_underlying (line_offset_struct);
6042       struct partial_symtab *pst;
6043       char *name;
6044
6045       /* Give the symtab a useful name for debug purposes.  */
6046       if ((line_offset & NO_STMT_LIST_TYPE_UNIT_PSYMTAB) != 0)
6047         name = xstrprintf ("<type_units_%d>",
6048                            (line_offset & ~NO_STMT_LIST_TYPE_UNIT_PSYMTAB));
6049       else
6050         name = xstrprintf ("<type_units_at_0x%x>", line_offset);
6051
6052       pst = create_partial_symtab (per_cu, name);
6053       pst->anonymous = 1;
6054
6055       xfree (name);
6056     }
6057
6058   tu_group->hash.dwo_unit = cu->dwo_unit;
6059   tu_group->hash.line_sect_off = line_offset_struct;
6060
6061   return tu_group;
6062 }
6063
6064 /* Look up the type_unit_group for type unit CU, and create it if necessary.
6065    STMT_LIST is a DW_AT_stmt_list attribute.  */
6066
6067 static struct type_unit_group *
6068 get_type_unit_group (struct dwarf2_cu *cu, const struct attribute *stmt_list)
6069 {
6070   struct tu_stats *tu_stats = &dwarf2_per_objfile->tu_stats;
6071   struct type_unit_group *tu_group;
6072   void **slot;
6073   unsigned int line_offset;
6074   struct type_unit_group type_unit_group_for_lookup;
6075
6076   if (dwarf2_per_objfile->type_unit_groups == NULL)
6077     {
6078       dwarf2_per_objfile->type_unit_groups =
6079         allocate_type_unit_groups_table ();
6080     }
6081
6082   /* Do we need to create a new group, or can we use an existing one?  */
6083
6084   if (stmt_list)
6085     {
6086       line_offset = DW_UNSND (stmt_list);
6087       ++tu_stats->nr_symtab_sharers;
6088     }
6089   else
6090     {
6091       /* Ugh, no stmt_list.  Rare, but we have to handle it.
6092          We can do various things here like create one group per TU or
6093          spread them over multiple groups to split up the expansion work.
6094          To avoid worst case scenarios (too many groups or too large groups)
6095          we, umm, group them in bunches.  */
6096       line_offset = (NO_STMT_LIST_TYPE_UNIT_PSYMTAB
6097                      | (tu_stats->nr_stmt_less_type_units
6098                         / NO_STMT_LIST_TYPE_UNIT_PSYMTAB_SIZE));
6099       ++tu_stats->nr_stmt_less_type_units;
6100     }
6101
6102   type_unit_group_for_lookup.hash.dwo_unit = cu->dwo_unit;
6103   type_unit_group_for_lookup.hash.line_sect_off = (sect_offset) line_offset;
6104   slot = htab_find_slot (dwarf2_per_objfile->type_unit_groups,
6105                          &type_unit_group_for_lookup, INSERT);
6106   if (*slot != NULL)
6107     {
6108       tu_group = (struct type_unit_group *) *slot;
6109       gdb_assert (tu_group != NULL);
6110     }
6111   else
6112     {
6113       sect_offset line_offset_struct = (sect_offset) line_offset;
6114       tu_group = create_type_unit_group (cu, line_offset_struct);
6115       *slot = tu_group;
6116       ++tu_stats->nr_symtabs;
6117     }
6118
6119   return tu_group;
6120 }
6121 \f
6122 /* Partial symbol tables.  */
6123
6124 /* Create a psymtab named NAME and assign it to PER_CU.
6125
6126    The caller must fill in the following details:
6127    dirname, textlow, texthigh.  */
6128
6129 static struct partial_symtab *
6130 create_partial_symtab (struct dwarf2_per_cu_data *per_cu, const char *name)
6131 {
6132   struct objfile *objfile = per_cu->objfile;
6133   struct partial_symtab *pst;
6134
6135   pst = start_psymtab_common (objfile, name, 0,
6136                               objfile->global_psymbols.next,
6137                               objfile->static_psymbols.next);
6138
6139   pst->psymtabs_addrmap_supported = 1;
6140
6141   /* This is the glue that links PST into GDB's symbol API.  */
6142   pst->read_symtab_private = per_cu;
6143   pst->read_symtab = dwarf2_read_symtab;
6144   per_cu->v.psymtab = pst;
6145
6146   return pst;
6147 }
6148
6149 /* The DATA object passed to process_psymtab_comp_unit_reader has this
6150    type.  */
6151
6152 struct process_psymtab_comp_unit_data
6153 {
6154   /* True if we are reading a DW_TAG_partial_unit.  */
6155
6156   int want_partial_unit;
6157
6158   /* The "pretend" language that is used if the CU doesn't declare a
6159      language.  */
6160
6161   enum language pretend_language;
6162 };
6163
6164 /* die_reader_func for process_psymtab_comp_unit.  */
6165
6166 static void
6167 process_psymtab_comp_unit_reader (const struct die_reader_specs *reader,
6168                                   const gdb_byte *info_ptr,
6169                                   struct die_info *comp_unit_die,
6170                                   int has_children,
6171                                   void *data)
6172 {
6173   struct dwarf2_cu *cu = reader->cu;
6174   struct objfile *objfile = cu->objfile;
6175   struct gdbarch *gdbarch = get_objfile_arch (objfile);
6176   struct dwarf2_per_cu_data *per_cu = cu->per_cu;
6177   CORE_ADDR baseaddr;
6178   CORE_ADDR best_lowpc = 0, best_highpc = 0;
6179   struct partial_symtab *pst;
6180   enum pc_bounds_kind cu_bounds_kind;
6181   const char *filename;
6182   struct process_psymtab_comp_unit_data *info
6183     = (struct process_psymtab_comp_unit_data *) data;
6184
6185   if (comp_unit_die->tag == DW_TAG_partial_unit && !info->want_partial_unit)
6186     return;
6187
6188   gdb_assert (! per_cu->is_debug_types);
6189
6190   prepare_one_comp_unit (cu, comp_unit_die, info->pretend_language);
6191
6192   cu->list_in_scope = &file_symbols;
6193
6194   /* Allocate a new partial symbol table structure.  */
6195   filename = dwarf2_string_attr (comp_unit_die, DW_AT_name, cu);
6196   if (filename == NULL)
6197     filename = "";
6198
6199   pst = create_partial_symtab (per_cu, filename);
6200
6201   /* This must be done before calling dwarf2_build_include_psymtabs.  */
6202   pst->dirname = dwarf2_string_attr (comp_unit_die, DW_AT_comp_dir, cu);
6203
6204   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
6205
6206   dwarf2_find_base_address (comp_unit_die, cu);
6207
6208   /* Possibly set the default values of LOWPC and HIGHPC from
6209      `DW_AT_ranges'.  */
6210   cu_bounds_kind = dwarf2_get_pc_bounds (comp_unit_die, &best_lowpc,
6211                                          &best_highpc, cu, pst);
6212   if (cu_bounds_kind == PC_BOUNDS_HIGH_LOW && best_lowpc < best_highpc)
6213     /* Store the contiguous range if it is not empty; it can be empty for
6214        CUs with no code.  */
6215     addrmap_set_empty (objfile->psymtabs_addrmap,
6216                        gdbarch_adjust_dwarf2_addr (gdbarch,
6217                                                    best_lowpc + baseaddr),
6218                        gdbarch_adjust_dwarf2_addr (gdbarch,
6219                                                    best_highpc + baseaddr) - 1,
6220                        pst);
6221
6222   /* Check if comp unit has_children.
6223      If so, read the rest of the partial symbols from this comp unit.
6224      If not, there's no more debug_info for this comp unit.  */
6225   if (has_children)
6226     {
6227       struct partial_die_info *first_die;
6228       CORE_ADDR lowpc, highpc;
6229
6230       lowpc = ((CORE_ADDR) -1);
6231       highpc = ((CORE_ADDR) 0);
6232
6233       first_die = load_partial_dies (reader, info_ptr, 1);
6234
6235       scan_partial_symbols (first_die, &lowpc, &highpc,
6236                             cu_bounds_kind <= PC_BOUNDS_INVALID, cu);
6237
6238       /* If we didn't find a lowpc, set it to highpc to avoid
6239          complaints from `maint check'.  */
6240       if (lowpc == ((CORE_ADDR) -1))
6241         lowpc = highpc;
6242
6243       /* If the compilation unit didn't have an explicit address range,
6244          then use the information extracted from its child dies.  */
6245       if (cu_bounds_kind <= PC_BOUNDS_INVALID)
6246         {
6247           best_lowpc = lowpc;
6248           best_highpc = highpc;
6249         }
6250     }
6251   pst->textlow = gdbarch_adjust_dwarf2_addr (gdbarch, best_lowpc + baseaddr);
6252   pst->texthigh = gdbarch_adjust_dwarf2_addr (gdbarch, best_highpc + baseaddr);
6253
6254   end_psymtab_common (objfile, pst);
6255
6256   if (!VEC_empty (dwarf2_per_cu_ptr, cu->per_cu->imported_symtabs))
6257     {
6258       int i;
6259       int len = VEC_length (dwarf2_per_cu_ptr, cu->per_cu->imported_symtabs);
6260       struct dwarf2_per_cu_data *iter;
6261
6262       /* Fill in 'dependencies' here; we fill in 'users' in a
6263          post-pass.  */
6264       pst->number_of_dependencies = len;
6265       pst->dependencies =
6266         XOBNEWVEC (&objfile->objfile_obstack, struct partial_symtab *, len);
6267       for (i = 0;
6268            VEC_iterate (dwarf2_per_cu_ptr, cu->per_cu->imported_symtabs,
6269                         i, iter);
6270            ++i)
6271         pst->dependencies[i] = iter->v.psymtab;
6272
6273       VEC_free (dwarf2_per_cu_ptr, cu->per_cu->imported_symtabs);
6274     }
6275
6276   /* Get the list of files included in the current compilation unit,
6277      and build a psymtab for each of them.  */
6278   dwarf2_build_include_psymtabs (cu, comp_unit_die, pst);
6279
6280   if (dwarf_read_debug)
6281     {
6282       struct gdbarch *gdbarch = get_objfile_arch (objfile);
6283
6284       fprintf_unfiltered (gdb_stdlog,
6285                           "Psymtab for %s unit @0x%x: %s - %s"
6286                           ", %d global, %d static syms\n",
6287                           per_cu->is_debug_types ? "type" : "comp",
6288                           to_underlying (per_cu->sect_off),
6289                           paddress (gdbarch, pst->textlow),
6290                           paddress (gdbarch, pst->texthigh),
6291                           pst->n_global_syms, pst->n_static_syms);
6292     }
6293 }
6294
6295 /* Subroutine of dwarf2_build_psymtabs_hard to simplify it.
6296    Process compilation unit THIS_CU for a psymtab.  */
6297
6298 static void
6299 process_psymtab_comp_unit (struct dwarf2_per_cu_data *this_cu,
6300                            int want_partial_unit,
6301                            enum language pretend_language)
6302 {
6303   struct process_psymtab_comp_unit_data info;
6304
6305   /* If this compilation unit was already read in, free the
6306      cached copy in order to read it in again.  This is
6307      necessary because we skipped some symbols when we first
6308      read in the compilation unit (see load_partial_dies).
6309      This problem could be avoided, but the benefit is unclear.  */
6310   if (this_cu->cu != NULL)
6311     free_one_cached_comp_unit (this_cu);
6312
6313   gdb_assert (! this_cu->is_debug_types);
6314   info.want_partial_unit = want_partial_unit;
6315   info.pretend_language = pretend_language;
6316   init_cutu_and_read_dies (this_cu, NULL, 0, 0,
6317                            process_psymtab_comp_unit_reader,
6318                            &info);
6319
6320   /* Age out any secondary CUs.  */
6321   age_cached_comp_units ();
6322 }
6323
6324 /* Reader function for build_type_psymtabs.  */
6325
6326 static void
6327 build_type_psymtabs_reader (const struct die_reader_specs *reader,
6328                             const gdb_byte *info_ptr,
6329                             struct die_info *type_unit_die,
6330                             int has_children,
6331                             void *data)
6332 {
6333   struct objfile *objfile = dwarf2_per_objfile->objfile;
6334   struct dwarf2_cu *cu = reader->cu;
6335   struct dwarf2_per_cu_data *per_cu = cu->per_cu;
6336   struct signatured_type *sig_type;
6337   struct type_unit_group *tu_group;
6338   struct attribute *attr;
6339   struct partial_die_info *first_die;
6340   CORE_ADDR lowpc, highpc;
6341   struct partial_symtab *pst;
6342
6343   gdb_assert (data == NULL);
6344   gdb_assert (per_cu->is_debug_types);
6345   sig_type = (struct signatured_type *) per_cu;
6346
6347   if (! has_children)
6348     return;
6349
6350   attr = dwarf2_attr_no_follow (type_unit_die, DW_AT_stmt_list);
6351   tu_group = get_type_unit_group (cu, attr);
6352
6353   VEC_safe_push (sig_type_ptr, tu_group->tus, sig_type);
6354
6355   prepare_one_comp_unit (cu, type_unit_die, language_minimal);
6356   cu->list_in_scope = &file_symbols;
6357   pst = create_partial_symtab (per_cu, "");
6358   pst->anonymous = 1;
6359
6360   first_die = load_partial_dies (reader, info_ptr, 1);
6361
6362   lowpc = (CORE_ADDR) -1;
6363   highpc = (CORE_ADDR) 0;
6364   scan_partial_symbols (first_die, &lowpc, &highpc, 0, cu);
6365
6366   end_psymtab_common (objfile, pst);
6367 }
6368
6369 /* Struct used to sort TUs by their abbreviation table offset.  */
6370
6371 struct tu_abbrev_offset
6372 {
6373   struct signatured_type *sig_type;
6374   sect_offset abbrev_offset;
6375 };
6376
6377 /* Helper routine for build_type_psymtabs_1, passed to qsort.  */
6378
6379 static int
6380 sort_tu_by_abbrev_offset (const void *ap, const void *bp)
6381 {
6382   const struct tu_abbrev_offset * const *a
6383     = (const struct tu_abbrev_offset * const*) ap;
6384   const struct tu_abbrev_offset * const *b
6385     = (const struct tu_abbrev_offset * const*) bp;
6386   sect_offset aoff = (*a)->abbrev_offset;
6387   sect_offset boff = (*b)->abbrev_offset;
6388
6389   return (aoff > boff) - (aoff < boff);
6390 }
6391
6392 /* Efficiently read all the type units.
6393    This does the bulk of the work for build_type_psymtabs.
6394
6395    The efficiency is because we sort TUs by the abbrev table they use and
6396    only read each abbrev table once.  In one program there are 200K TUs
6397    sharing 8K abbrev tables.
6398
6399    The main purpose of this function is to support building the
6400    dwarf2_per_objfile->type_unit_groups table.
6401    TUs typically share the DW_AT_stmt_list of the CU they came from, so we
6402    can collapse the search space by grouping them by stmt_list.
6403    The savings can be significant, in the same program from above the 200K TUs
6404    share 8K stmt_list tables.
6405
6406    FUNC is expected to call get_type_unit_group, which will create the
6407    struct type_unit_group if necessary and add it to
6408    dwarf2_per_objfile->type_unit_groups.  */
6409
6410 static void
6411 build_type_psymtabs_1 (void)
6412 {
6413   struct tu_stats *tu_stats = &dwarf2_per_objfile->tu_stats;
6414   struct cleanup *cleanups;
6415   struct abbrev_table *abbrev_table;
6416   sect_offset abbrev_offset;
6417   struct tu_abbrev_offset *sorted_by_abbrev;
6418   int i;
6419
6420   /* It's up to the caller to not call us multiple times.  */
6421   gdb_assert (dwarf2_per_objfile->type_unit_groups == NULL);
6422
6423   if (dwarf2_per_objfile->n_type_units == 0)
6424     return;
6425
6426   /* TUs typically share abbrev tables, and there can be way more TUs than
6427      abbrev tables.  Sort by abbrev table to reduce the number of times we
6428      read each abbrev table in.
6429      Alternatives are to punt or to maintain a cache of abbrev tables.
6430      This is simpler and efficient enough for now.
6431
6432      Later we group TUs by their DW_AT_stmt_list value (as this defines the
6433      symtab to use).  Typically TUs with the same abbrev offset have the same
6434      stmt_list value too so in practice this should work well.
6435
6436      The basic algorithm here is:
6437
6438       sort TUs by abbrev table
6439       for each TU with same abbrev table:
6440         read abbrev table if first user
6441         read TU top level DIE
6442           [IWBN if DWO skeletons had DW_AT_stmt_list]
6443         call FUNC  */
6444
6445   if (dwarf_read_debug)
6446     fprintf_unfiltered (gdb_stdlog, "Building type unit groups ...\n");
6447
6448   /* Sort in a separate table to maintain the order of all_type_units
6449      for .gdb_index: TU indices directly index all_type_units.  */
6450   sorted_by_abbrev = XNEWVEC (struct tu_abbrev_offset,
6451                               dwarf2_per_objfile->n_type_units);
6452   for (i = 0; i < dwarf2_per_objfile->n_type_units; ++i)
6453     {
6454       struct signatured_type *sig_type = dwarf2_per_objfile->all_type_units[i];
6455
6456       sorted_by_abbrev[i].sig_type = sig_type;
6457       sorted_by_abbrev[i].abbrev_offset =
6458         read_abbrev_offset (sig_type->per_cu.section,
6459                             sig_type->per_cu.sect_off);
6460     }
6461   cleanups = make_cleanup (xfree, sorted_by_abbrev);
6462   qsort (sorted_by_abbrev, dwarf2_per_objfile->n_type_units,
6463          sizeof (struct tu_abbrev_offset), sort_tu_by_abbrev_offset);
6464
6465   abbrev_offset = (sect_offset) ~(unsigned) 0;
6466   abbrev_table = NULL;
6467   make_cleanup (abbrev_table_free_cleanup, &abbrev_table);
6468
6469   for (i = 0; i < dwarf2_per_objfile->n_type_units; ++i)
6470     {
6471       const struct tu_abbrev_offset *tu = &sorted_by_abbrev[i];
6472
6473       /* Switch to the next abbrev table if necessary.  */
6474       if (abbrev_table == NULL
6475           || tu->abbrev_offset != abbrev_offset)
6476         {
6477           if (abbrev_table != NULL)
6478             {
6479               abbrev_table_free (abbrev_table);
6480               /* Reset to NULL in case abbrev_table_read_table throws
6481                  an error: abbrev_table_free_cleanup will get called.  */
6482               abbrev_table = NULL;
6483             }
6484           abbrev_offset = tu->abbrev_offset;
6485           abbrev_table =
6486             abbrev_table_read_table (&dwarf2_per_objfile->abbrev,
6487                                      abbrev_offset);
6488           ++tu_stats->nr_uniq_abbrev_tables;
6489         }
6490
6491       init_cutu_and_read_dies (&tu->sig_type->per_cu, abbrev_table, 0, 0,
6492                                build_type_psymtabs_reader, NULL);
6493     }
6494
6495   do_cleanups (cleanups);
6496 }
6497
6498 /* Print collected type unit statistics.  */
6499
6500 static void
6501 print_tu_stats (void)
6502 {
6503   struct tu_stats *tu_stats = &dwarf2_per_objfile->tu_stats;
6504
6505   fprintf_unfiltered (gdb_stdlog, "Type unit statistics:\n");
6506   fprintf_unfiltered (gdb_stdlog, "  %d TUs\n",
6507                       dwarf2_per_objfile->n_type_units);
6508   fprintf_unfiltered (gdb_stdlog, "  %d uniq abbrev tables\n",
6509                       tu_stats->nr_uniq_abbrev_tables);
6510   fprintf_unfiltered (gdb_stdlog, "  %d symtabs from stmt_list entries\n",
6511                       tu_stats->nr_symtabs);
6512   fprintf_unfiltered (gdb_stdlog, "  %d symtab sharers\n",
6513                       tu_stats->nr_symtab_sharers);
6514   fprintf_unfiltered (gdb_stdlog, "  %d type units without a stmt_list\n",
6515                       tu_stats->nr_stmt_less_type_units);
6516   fprintf_unfiltered (gdb_stdlog, "  %d all_type_units reallocs\n",
6517                       tu_stats->nr_all_type_units_reallocs);
6518 }
6519
6520 /* Traversal function for build_type_psymtabs.  */
6521
6522 static int
6523 build_type_psymtab_dependencies (void **slot, void *info)
6524 {
6525   struct objfile *objfile = dwarf2_per_objfile->objfile;
6526   struct type_unit_group *tu_group = (struct type_unit_group *) *slot;
6527   struct dwarf2_per_cu_data *per_cu = &tu_group->per_cu;
6528   struct partial_symtab *pst = per_cu->v.psymtab;
6529   int len = VEC_length (sig_type_ptr, tu_group->tus);
6530   struct signatured_type *iter;
6531   int i;
6532
6533   gdb_assert (len > 0);
6534   gdb_assert (IS_TYPE_UNIT_GROUP (per_cu));
6535
6536   pst->number_of_dependencies = len;
6537   pst->dependencies =
6538     XOBNEWVEC (&objfile->objfile_obstack, struct partial_symtab *, len);
6539   for (i = 0;
6540        VEC_iterate (sig_type_ptr, tu_group->tus, i, iter);
6541        ++i)
6542     {
6543       gdb_assert (iter->per_cu.is_debug_types);
6544       pst->dependencies[i] = iter->per_cu.v.psymtab;
6545       iter->type_unit_group = tu_group;
6546     }
6547
6548   VEC_free (sig_type_ptr, tu_group->tus);
6549
6550   return 1;
6551 }
6552
6553 /* Subroutine of dwarf2_build_psymtabs_hard to simplify it.
6554    Build partial symbol tables for the .debug_types comp-units.  */
6555
6556 static void
6557 build_type_psymtabs (struct objfile *objfile)
6558 {
6559   if (! create_all_type_units (objfile))
6560     return;
6561
6562   build_type_psymtabs_1 ();
6563 }
6564
6565 /* Traversal function for process_skeletonless_type_unit.
6566    Read a TU in a DWO file and build partial symbols for it.  */
6567
6568 static int
6569 process_skeletonless_type_unit (void **slot, void *info)
6570 {
6571   struct dwo_unit *dwo_unit = (struct dwo_unit *) *slot;
6572   struct objfile *objfile = (struct objfile *) info;
6573   struct signatured_type find_entry, *entry;
6574
6575   /* If this TU doesn't exist in the global table, add it and read it in.  */
6576
6577   if (dwarf2_per_objfile->signatured_types == NULL)
6578     {
6579       dwarf2_per_objfile->signatured_types
6580         = allocate_signatured_type_table (objfile);
6581     }
6582
6583   find_entry.signature = dwo_unit->signature;
6584   slot = htab_find_slot (dwarf2_per_objfile->signatured_types, &find_entry,
6585                          INSERT);
6586   /* If we've already seen this type there's nothing to do.  What's happening
6587      is we're doing our own version of comdat-folding here.  */
6588   if (*slot != NULL)
6589     return 1;
6590
6591   /* This does the job that create_all_type_units would have done for
6592      this TU.  */
6593   entry = add_type_unit (dwo_unit->signature, slot);
6594   fill_in_sig_entry_from_dwo_entry (objfile, entry, dwo_unit);
6595   *slot = entry;
6596
6597   /* This does the job that build_type_psymtabs_1 would have done.  */
6598   init_cutu_and_read_dies (&entry->per_cu, NULL, 0, 0,
6599                            build_type_psymtabs_reader, NULL);
6600
6601   return 1;
6602 }
6603
6604 /* Traversal function for process_skeletonless_type_units.  */
6605
6606 static int
6607 process_dwo_file_for_skeletonless_type_units (void **slot, void *info)
6608 {
6609   struct dwo_file *dwo_file = (struct dwo_file *) *slot;
6610
6611   if (dwo_file->tus != NULL)
6612     {
6613       htab_traverse_noresize (dwo_file->tus,
6614                               process_skeletonless_type_unit, info);
6615     }
6616
6617   return 1;
6618 }
6619
6620 /* Scan all TUs of DWO files, verifying we've processed them.
6621    This is needed in case a TU was emitted without its skeleton.
6622    Note: This can't be done until we know what all the DWO files are.  */
6623
6624 static void
6625 process_skeletonless_type_units (struct objfile *objfile)
6626 {
6627   /* Skeletonless TUs in DWP files without .gdb_index is not supported yet.  */
6628   if (get_dwp_file () == NULL
6629       && dwarf2_per_objfile->dwo_files != NULL)
6630     {
6631       htab_traverse_noresize (dwarf2_per_objfile->dwo_files,
6632                               process_dwo_file_for_skeletonless_type_units,
6633                               objfile);
6634     }
6635 }
6636
6637 /* A cleanup function that clears objfile's psymtabs_addrmap field.  */
6638
6639 static void
6640 psymtabs_addrmap_cleanup (void *o)
6641 {
6642   struct objfile *objfile = (struct objfile *) o;
6643
6644   objfile->psymtabs_addrmap = NULL;
6645 }
6646
6647 /* Compute the 'user' field for each psymtab in OBJFILE.  */
6648
6649 static void
6650 set_partial_user (struct objfile *objfile)
6651 {
6652   int i;
6653
6654   for (i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
6655     {
6656       struct dwarf2_per_cu_data *per_cu = dw2_get_cutu (i);
6657       struct partial_symtab *pst = per_cu->v.psymtab;
6658       int j;
6659
6660       if (pst == NULL)
6661         continue;
6662
6663       for (j = 0; j < pst->number_of_dependencies; ++j)
6664         {
6665           /* Set the 'user' field only if it is not already set.  */
6666           if (pst->dependencies[j]->user == NULL)
6667             pst->dependencies[j]->user = pst;
6668         }
6669     }
6670 }
6671
6672 /* Build the partial symbol table by doing a quick pass through the
6673    .debug_info and .debug_abbrev sections.  */
6674
6675 static void
6676 dwarf2_build_psymtabs_hard (struct objfile *objfile)
6677 {
6678   struct cleanup *back_to, *addrmap_cleanup;
6679   int i;
6680
6681   if (dwarf_read_debug)
6682     {
6683       fprintf_unfiltered (gdb_stdlog, "Building psymtabs of objfile %s ...\n",
6684                           objfile_name (objfile));
6685     }
6686
6687   dwarf2_per_objfile->reading_partial_symbols = 1;
6688
6689   dwarf2_read_section (objfile, &dwarf2_per_objfile->info);
6690
6691   /* Any cached compilation units will be linked by the per-objfile
6692      read_in_chain.  Make sure to free them when we're done.  */
6693   back_to = make_cleanup (free_cached_comp_units, NULL);
6694
6695   build_type_psymtabs (objfile);
6696
6697   create_all_comp_units (objfile);
6698
6699   /* Create a temporary address map on a temporary obstack.  We later
6700      copy this to the final obstack.  */
6701   auto_obstack temp_obstack;
6702   objfile->psymtabs_addrmap = addrmap_create_mutable (&temp_obstack);
6703   addrmap_cleanup = make_cleanup (psymtabs_addrmap_cleanup, objfile);
6704
6705   for (i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
6706     {
6707       struct dwarf2_per_cu_data *per_cu = dw2_get_cutu (i);
6708
6709       process_psymtab_comp_unit (per_cu, 0, language_minimal);
6710     }
6711
6712   /* This has to wait until we read the CUs, we need the list of DWOs.  */
6713   process_skeletonless_type_units (objfile);
6714
6715   /* Now that all TUs have been processed we can fill in the dependencies.  */
6716   if (dwarf2_per_objfile->type_unit_groups != NULL)
6717     {
6718       htab_traverse_noresize (dwarf2_per_objfile->type_unit_groups,
6719                               build_type_psymtab_dependencies, NULL);
6720     }
6721
6722   if (dwarf_read_debug)
6723     print_tu_stats ();
6724
6725   set_partial_user (objfile);
6726
6727   objfile->psymtabs_addrmap = addrmap_create_fixed (objfile->psymtabs_addrmap,
6728                                                     &objfile->objfile_obstack);
6729   discard_cleanups (addrmap_cleanup);
6730
6731   do_cleanups (back_to);
6732
6733   if (dwarf_read_debug)
6734     fprintf_unfiltered (gdb_stdlog, "Done building psymtabs of %s\n",
6735                         objfile_name (objfile));
6736 }
6737
6738 /* die_reader_func for load_partial_comp_unit.  */
6739
6740 static void
6741 load_partial_comp_unit_reader (const struct die_reader_specs *reader,
6742                                const gdb_byte *info_ptr,
6743                                struct die_info *comp_unit_die,
6744                                int has_children,
6745                                void *data)
6746 {
6747   struct dwarf2_cu *cu = reader->cu;
6748
6749   prepare_one_comp_unit (cu, comp_unit_die, language_minimal);
6750
6751   /* Check if comp unit has_children.
6752      If so, read the rest of the partial symbols from this comp unit.
6753      If not, there's no more debug_info for this comp unit.  */
6754   if (has_children)
6755     load_partial_dies (reader, info_ptr, 0);
6756 }
6757
6758 /* Load the partial DIEs for a secondary CU into memory.
6759    This is also used when rereading a primary CU with load_all_dies.  */
6760
6761 static void
6762 load_partial_comp_unit (struct dwarf2_per_cu_data *this_cu)
6763 {
6764   init_cutu_and_read_dies (this_cu, NULL, 1, 1,
6765                            load_partial_comp_unit_reader, NULL);
6766 }
6767
6768 static void
6769 read_comp_units_from_section (struct objfile *objfile,
6770                               struct dwarf2_section_info *section,
6771                               unsigned int is_dwz,
6772                               int *n_allocated,
6773                               int *n_comp_units,
6774                               struct dwarf2_per_cu_data ***all_comp_units)
6775 {
6776   const gdb_byte *info_ptr;
6777   bfd *abfd = get_section_bfd_owner (section);
6778
6779   if (dwarf_read_debug)
6780     fprintf_unfiltered (gdb_stdlog, "Reading %s for %s\n",
6781                         get_section_name (section),
6782                         get_section_file_name (section));
6783
6784   dwarf2_read_section (objfile, section);
6785
6786   info_ptr = section->buffer;
6787
6788   while (info_ptr < section->buffer + section->size)
6789     {
6790       unsigned int length, initial_length_size;
6791       struct dwarf2_per_cu_data *this_cu;
6792
6793       sect_offset sect_off = (sect_offset) (info_ptr - section->buffer);
6794
6795       /* Read just enough information to find out where the next
6796          compilation unit is.  */
6797       length = read_initial_length (abfd, info_ptr, &initial_length_size);
6798
6799       /* Save the compilation unit for later lookup.  */
6800       this_cu = XOBNEW (&objfile->objfile_obstack, struct dwarf2_per_cu_data);
6801       memset (this_cu, 0, sizeof (*this_cu));
6802       this_cu->sect_off = sect_off;
6803       this_cu->length = length + initial_length_size;
6804       this_cu->is_dwz = is_dwz;
6805       this_cu->objfile = objfile;
6806       this_cu->section = section;
6807
6808       if (*n_comp_units == *n_allocated)
6809         {
6810           *n_allocated *= 2;
6811           *all_comp_units = XRESIZEVEC (struct dwarf2_per_cu_data *,
6812                                         *all_comp_units, *n_allocated);
6813         }
6814       (*all_comp_units)[*n_comp_units] = this_cu;
6815       ++*n_comp_units;
6816
6817       info_ptr = info_ptr + this_cu->length;
6818     }
6819 }
6820
6821 /* Create a list of all compilation units in OBJFILE.
6822    This is only done for -readnow and building partial symtabs.  */
6823
6824 static void
6825 create_all_comp_units (struct objfile *objfile)
6826 {
6827   int n_allocated;
6828   int n_comp_units;
6829   struct dwarf2_per_cu_data **all_comp_units;
6830   struct dwz_file *dwz;
6831
6832   n_comp_units = 0;
6833   n_allocated = 10;
6834   all_comp_units = XNEWVEC (struct dwarf2_per_cu_data *, n_allocated);
6835
6836   read_comp_units_from_section (objfile, &dwarf2_per_objfile->info, 0,
6837                                 &n_allocated, &n_comp_units, &all_comp_units);
6838
6839   dwz = dwarf2_get_dwz_file ();
6840   if (dwz != NULL)
6841     read_comp_units_from_section (objfile, &dwz->info, 1,
6842                                   &n_allocated, &n_comp_units,
6843                                   &all_comp_units);
6844
6845   dwarf2_per_objfile->all_comp_units = XOBNEWVEC (&objfile->objfile_obstack,
6846                                                   struct dwarf2_per_cu_data *,
6847                                                   n_comp_units);
6848   memcpy (dwarf2_per_objfile->all_comp_units, all_comp_units,
6849           n_comp_units * sizeof (struct dwarf2_per_cu_data *));
6850   xfree (all_comp_units);
6851   dwarf2_per_objfile->n_comp_units = n_comp_units;
6852 }
6853
6854 /* Process all loaded DIEs for compilation unit CU, starting at
6855    FIRST_DIE.  The caller should pass SET_ADDRMAP == 1 if the compilation
6856    unit DIE did not have PC info (DW_AT_low_pc and DW_AT_high_pc, or
6857    DW_AT_ranges).  See the comments of add_partial_subprogram on how
6858    SET_ADDRMAP is used and how *LOWPC and *HIGHPC are updated.  */
6859
6860 static void
6861 scan_partial_symbols (struct partial_die_info *first_die, CORE_ADDR *lowpc,
6862                       CORE_ADDR *highpc, int set_addrmap,
6863                       struct dwarf2_cu *cu)
6864 {
6865   struct partial_die_info *pdi;
6866
6867   /* Now, march along the PDI's, descending into ones which have
6868      interesting children but skipping the children of the other ones,
6869      until we reach the end of the compilation unit.  */
6870
6871   pdi = first_die;
6872
6873   while (pdi != NULL)
6874     {
6875       fixup_partial_die (pdi, cu);
6876
6877       /* Anonymous namespaces or modules have no name but have interesting
6878          children, so we need to look at them.  Ditto for anonymous
6879          enums.  */
6880
6881       if (pdi->name != NULL || pdi->tag == DW_TAG_namespace
6882           || pdi->tag == DW_TAG_module || pdi->tag == DW_TAG_enumeration_type
6883           || pdi->tag == DW_TAG_imported_unit)
6884         {
6885           switch (pdi->tag)
6886             {
6887             case DW_TAG_subprogram:
6888               add_partial_subprogram (pdi, lowpc, highpc, set_addrmap, cu);
6889               break;
6890             case DW_TAG_constant:
6891             case DW_TAG_variable:
6892             case DW_TAG_typedef:
6893             case DW_TAG_union_type:
6894               if (!pdi->is_declaration)
6895                 {
6896                   add_partial_symbol (pdi, cu);
6897                 }
6898               break;
6899             case DW_TAG_class_type:
6900             case DW_TAG_interface_type:
6901             case DW_TAG_structure_type:
6902               if (!pdi->is_declaration)
6903                 {
6904                   add_partial_symbol (pdi, cu);
6905                 }
6906               if (cu->language == language_rust && pdi->has_children)
6907                 scan_partial_symbols (pdi->die_child, lowpc, highpc,
6908                                       set_addrmap, cu);
6909               break;
6910             case DW_TAG_enumeration_type:
6911               if (!pdi->is_declaration)
6912                 add_partial_enumeration (pdi, cu);
6913               break;
6914             case DW_TAG_base_type:
6915             case DW_TAG_subrange_type:
6916               /* File scope base type definitions are added to the partial
6917                  symbol table.  */
6918               add_partial_symbol (pdi, cu);
6919               break;
6920             case DW_TAG_namespace:
6921               add_partial_namespace (pdi, lowpc, highpc, set_addrmap, cu);
6922               break;
6923             case DW_TAG_module:
6924               add_partial_module (pdi, lowpc, highpc, set_addrmap, cu);
6925               break;
6926             case DW_TAG_imported_unit:
6927               {
6928                 struct dwarf2_per_cu_data *per_cu;
6929
6930                 /* For now we don't handle imported units in type units.  */
6931                 if (cu->per_cu->is_debug_types)
6932                   {
6933                     error (_("Dwarf Error: DW_TAG_imported_unit is not"
6934                              " supported in type units [in module %s]"),
6935                            objfile_name (cu->objfile));
6936                   }
6937
6938                 per_cu = dwarf2_find_containing_comp_unit (pdi->d.sect_off,
6939                                                            pdi->is_dwz,
6940                                                            cu->objfile);
6941
6942                 /* Go read the partial unit, if needed.  */
6943                 if (per_cu->v.psymtab == NULL)
6944                   process_psymtab_comp_unit (per_cu, 1, cu->language);
6945
6946                 VEC_safe_push (dwarf2_per_cu_ptr,
6947                                cu->per_cu->imported_symtabs, per_cu);
6948               }
6949               break;
6950             case DW_TAG_imported_declaration:
6951               add_partial_symbol (pdi, cu);
6952               break;
6953             default:
6954               break;
6955             }
6956         }
6957
6958       /* If the die has a sibling, skip to the sibling.  */
6959
6960       pdi = pdi->die_sibling;
6961     }
6962 }
6963
6964 /* Functions used to compute the fully scoped name of a partial DIE.
6965
6966    Normally, this is simple.  For C++, the parent DIE's fully scoped
6967    name is concatenated with "::" and the partial DIE's name.
6968    Enumerators are an exception; they use the scope of their parent
6969    enumeration type, i.e. the name of the enumeration type is not
6970    prepended to the enumerator.
6971
6972    There are two complexities.  One is DW_AT_specification; in this
6973    case "parent" means the parent of the target of the specification,
6974    instead of the direct parent of the DIE.  The other is compilers
6975    which do not emit DW_TAG_namespace; in this case we try to guess
6976    the fully qualified name of structure types from their members'
6977    linkage names.  This must be done using the DIE's children rather
6978    than the children of any DW_AT_specification target.  We only need
6979    to do this for structures at the top level, i.e. if the target of
6980    any DW_AT_specification (if any; otherwise the DIE itself) does not
6981    have a parent.  */
6982
6983 /* Compute the scope prefix associated with PDI's parent, in
6984    compilation unit CU.  The result will be allocated on CU's
6985    comp_unit_obstack, or a copy of the already allocated PDI->NAME
6986    field.  NULL is returned if no prefix is necessary.  */
6987 static const char *
6988 partial_die_parent_scope (struct partial_die_info *pdi,
6989                           struct dwarf2_cu *cu)
6990 {
6991   const char *grandparent_scope;
6992   struct partial_die_info *parent, *real_pdi;
6993
6994   /* We need to look at our parent DIE; if we have a DW_AT_specification,
6995      then this means the parent of the specification DIE.  */
6996
6997   real_pdi = pdi;
6998   while (real_pdi->has_specification)
6999     real_pdi = find_partial_die (real_pdi->spec_offset,
7000                                  real_pdi->spec_is_dwz, cu);
7001
7002   parent = real_pdi->die_parent;
7003   if (parent == NULL)
7004     return NULL;
7005
7006   if (parent->scope_set)
7007     return parent->scope;
7008
7009   fixup_partial_die (parent, cu);
7010
7011   grandparent_scope = partial_die_parent_scope (parent, cu);
7012
7013   /* GCC 4.0 and 4.1 had a bug (PR c++/28460) where they generated bogus
7014      DW_TAG_namespace DIEs with a name of "::" for the global namespace.
7015      Work around this problem here.  */
7016   if (cu->language == language_cplus
7017       && parent->tag == DW_TAG_namespace
7018       && strcmp (parent->name, "::") == 0
7019       && grandparent_scope == NULL)
7020     {
7021       parent->scope = NULL;
7022       parent->scope_set = 1;
7023       return NULL;
7024     }
7025
7026   if (pdi->tag == DW_TAG_enumerator)
7027     /* Enumerators should not get the name of the enumeration as a prefix.  */
7028     parent->scope = grandparent_scope;
7029   else if (parent->tag == DW_TAG_namespace
7030       || parent->tag == DW_TAG_module
7031       || parent->tag == DW_TAG_structure_type
7032       || parent->tag == DW_TAG_class_type
7033       || parent->tag == DW_TAG_interface_type
7034       || parent->tag == DW_TAG_union_type
7035       || parent->tag == DW_TAG_enumeration_type)
7036     {
7037       if (grandparent_scope == NULL)
7038         parent->scope = parent->name;
7039       else
7040         parent->scope = typename_concat (&cu->comp_unit_obstack,
7041                                          grandparent_scope,
7042                                          parent->name, 0, cu);
7043     }
7044   else
7045     {
7046       /* FIXME drow/2004-04-01: What should we be doing with
7047          function-local names?  For partial symbols, we should probably be
7048          ignoring them.  */
7049       complaint (&symfile_complaints,
7050                  _("unhandled containing DIE tag %d for DIE at %d"),
7051                  parent->tag, to_underlying (pdi->sect_off));
7052       parent->scope = grandparent_scope;
7053     }
7054
7055   parent->scope_set = 1;
7056   return parent->scope;
7057 }
7058
7059 /* Return the fully scoped name associated with PDI, from compilation unit
7060    CU.  The result will be allocated with malloc.  */
7061
7062 static char *
7063 partial_die_full_name (struct partial_die_info *pdi,
7064                        struct dwarf2_cu *cu)
7065 {
7066   const char *parent_scope;
7067
7068   /* If this is a template instantiation, we can not work out the
7069      template arguments from partial DIEs.  So, unfortunately, we have
7070      to go through the full DIEs.  At least any work we do building
7071      types here will be reused if full symbols are loaded later.  */
7072   if (pdi->has_template_arguments)
7073     {
7074       fixup_partial_die (pdi, cu);
7075
7076       if (pdi->name != NULL && strchr (pdi->name, '<') == NULL)
7077         {
7078           struct die_info *die;
7079           struct attribute attr;
7080           struct dwarf2_cu *ref_cu = cu;
7081
7082           /* DW_FORM_ref_addr is using section offset.  */
7083           attr.name = (enum dwarf_attribute) 0;
7084           attr.form = DW_FORM_ref_addr;
7085           attr.u.unsnd = to_underlying (pdi->sect_off);
7086           die = follow_die_ref (NULL, &attr, &ref_cu);
7087
7088           return xstrdup (dwarf2_full_name (NULL, die, ref_cu));
7089         }
7090     }
7091
7092   parent_scope = partial_die_parent_scope (pdi, cu);
7093   if (parent_scope == NULL)
7094     return NULL;
7095   else
7096     return typename_concat (NULL, parent_scope, pdi->name, 0, cu);
7097 }
7098
7099 static void
7100 add_partial_symbol (struct partial_die_info *pdi, struct dwarf2_cu *cu)
7101 {
7102   struct objfile *objfile = cu->objfile;
7103   struct gdbarch *gdbarch = get_objfile_arch (objfile);
7104   CORE_ADDR addr = 0;
7105   const char *actual_name = NULL;
7106   CORE_ADDR baseaddr;
7107   char *built_actual_name;
7108
7109   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
7110
7111   built_actual_name = partial_die_full_name (pdi, cu);
7112   if (built_actual_name != NULL)
7113     actual_name = built_actual_name;
7114
7115   if (actual_name == NULL)
7116     actual_name = pdi->name;
7117
7118   switch (pdi->tag)
7119     {
7120     case DW_TAG_subprogram:
7121       addr = gdbarch_adjust_dwarf2_addr (gdbarch, pdi->lowpc + baseaddr);
7122       if (pdi->is_external || cu->language == language_ada)
7123         {
7124           /* brobecker/2007-12-26: Normally, only "external" DIEs are part
7125              of the global scope.  But in Ada, we want to be able to access
7126              nested procedures globally.  So all Ada subprograms are stored
7127              in the global scope.  */
7128           add_psymbol_to_list (actual_name, strlen (actual_name),
7129                                built_actual_name != NULL,
7130                                VAR_DOMAIN, LOC_BLOCK,
7131                                &objfile->global_psymbols,
7132                                addr, cu->language, objfile);
7133         }
7134       else
7135         {
7136           add_psymbol_to_list (actual_name, strlen (actual_name),
7137                                built_actual_name != NULL,
7138                                VAR_DOMAIN, LOC_BLOCK,
7139                                &objfile->static_psymbols,
7140                                addr, cu->language, objfile);
7141         }
7142
7143       if (pdi->main_subprogram && actual_name != NULL)
7144         set_objfile_main_name (objfile, actual_name, cu->language);
7145       break;
7146     case DW_TAG_constant:
7147       {
7148         struct psymbol_allocation_list *list;
7149
7150         if (pdi->is_external)
7151           list = &objfile->global_psymbols;
7152         else
7153           list = &objfile->static_psymbols;
7154         add_psymbol_to_list (actual_name, strlen (actual_name),
7155                              built_actual_name != NULL, VAR_DOMAIN, LOC_STATIC,
7156                              list, 0, cu->language, objfile);
7157       }
7158       break;
7159     case DW_TAG_variable:
7160       if (pdi->d.locdesc)
7161         addr = decode_locdesc (pdi->d.locdesc, cu);
7162
7163       if (pdi->d.locdesc
7164           && addr == 0
7165           && !dwarf2_per_objfile->has_section_at_zero)
7166         {
7167           /* A global or static variable may also have been stripped
7168              out by the linker if unused, in which case its address
7169              will be nullified; do not add such variables into partial
7170              symbol table then.  */
7171         }
7172       else if (pdi->is_external)
7173         {
7174           /* Global Variable.
7175              Don't enter into the minimal symbol tables as there is
7176              a minimal symbol table entry from the ELF symbols already.
7177              Enter into partial symbol table if it has a location
7178              descriptor or a type.
7179              If the location descriptor is missing, new_symbol will create
7180              a LOC_UNRESOLVED symbol, the address of the variable will then
7181              be determined from the minimal symbol table whenever the variable
7182              is referenced.
7183              The address for the partial symbol table entry is not
7184              used by GDB, but it comes in handy for debugging partial symbol
7185              table building.  */
7186
7187           if (pdi->d.locdesc || pdi->has_type)
7188             add_psymbol_to_list (actual_name, strlen (actual_name),
7189                                  built_actual_name != NULL,
7190                                  VAR_DOMAIN, LOC_STATIC,
7191                                  &objfile->global_psymbols,
7192                                  addr + baseaddr,
7193                                  cu->language, objfile);
7194         }
7195       else
7196         {
7197           int has_loc = pdi->d.locdesc != NULL;
7198
7199           /* Static Variable.  Skip symbols whose value we cannot know (those
7200              without location descriptors or constant values).  */
7201           if (!has_loc && !pdi->has_const_value)
7202             {
7203               xfree (built_actual_name);
7204               return;
7205             }
7206
7207           add_psymbol_to_list (actual_name, strlen (actual_name),
7208                                built_actual_name != NULL,
7209                                VAR_DOMAIN, LOC_STATIC,
7210                                &objfile->static_psymbols,
7211                                has_loc ? addr + baseaddr : (CORE_ADDR) 0,
7212                                cu->language, objfile);
7213         }
7214       break;
7215     case DW_TAG_typedef:
7216     case DW_TAG_base_type:
7217     case DW_TAG_subrange_type:
7218       add_psymbol_to_list (actual_name, strlen (actual_name),
7219                            built_actual_name != NULL,
7220                            VAR_DOMAIN, LOC_TYPEDEF,
7221                            &objfile->static_psymbols,
7222                            0, cu->language, objfile);
7223       break;
7224     case DW_TAG_imported_declaration:
7225     case DW_TAG_namespace:
7226       add_psymbol_to_list (actual_name, strlen (actual_name),
7227                            built_actual_name != NULL,
7228                            VAR_DOMAIN, LOC_TYPEDEF,
7229                            &objfile->global_psymbols,
7230                            0, cu->language, objfile);
7231       break;
7232     case DW_TAG_module:
7233       add_psymbol_to_list (actual_name, strlen (actual_name),
7234                            built_actual_name != NULL,
7235                            MODULE_DOMAIN, LOC_TYPEDEF,
7236                            &objfile->global_psymbols,
7237                            0, cu->language, objfile);
7238       break;
7239     case DW_TAG_class_type:
7240     case DW_TAG_interface_type:
7241     case DW_TAG_structure_type:
7242     case DW_TAG_union_type:
7243     case DW_TAG_enumeration_type:
7244       /* Skip external references.  The DWARF standard says in the section
7245          about "Structure, Union, and Class Type Entries": "An incomplete
7246          structure, union or class type is represented by a structure,
7247          union or class entry that does not have a byte size attribute
7248          and that has a DW_AT_declaration attribute."  */
7249       if (!pdi->has_byte_size && pdi->is_declaration)
7250         {
7251           xfree (built_actual_name);
7252           return;
7253         }
7254
7255       /* NOTE: carlton/2003-10-07: See comment in new_symbol about
7256          static vs. global.  */
7257       add_psymbol_to_list (actual_name, strlen (actual_name),
7258                            built_actual_name != NULL,
7259                            STRUCT_DOMAIN, LOC_TYPEDEF,
7260                            cu->language == language_cplus
7261                            ? &objfile->global_psymbols
7262                            : &objfile->static_psymbols,
7263                            0, cu->language, objfile);
7264
7265       break;
7266     case DW_TAG_enumerator:
7267       add_psymbol_to_list (actual_name, strlen (actual_name),
7268                            built_actual_name != NULL,
7269                            VAR_DOMAIN, LOC_CONST,
7270                            cu->language == language_cplus
7271                            ? &objfile->global_psymbols
7272                            : &objfile->static_psymbols,
7273                            0, cu->language, objfile);
7274       break;
7275     default:
7276       break;
7277     }
7278
7279   xfree (built_actual_name);
7280 }
7281
7282 /* Read a partial die corresponding to a namespace; also, add a symbol
7283    corresponding to that namespace to the symbol table.  NAMESPACE is
7284    the name of the enclosing namespace.  */
7285
7286 static void
7287 add_partial_namespace (struct partial_die_info *pdi,
7288                        CORE_ADDR *lowpc, CORE_ADDR *highpc,
7289                        int set_addrmap, struct dwarf2_cu *cu)
7290 {
7291   /* Add a symbol for the namespace.  */
7292
7293   add_partial_symbol (pdi, cu);
7294
7295   /* Now scan partial symbols in that namespace.  */
7296
7297   if (pdi->has_children)
7298     scan_partial_symbols (pdi->die_child, lowpc, highpc, set_addrmap, cu);
7299 }
7300
7301 /* Read a partial die corresponding to a Fortran module.  */
7302
7303 static void
7304 add_partial_module (struct partial_die_info *pdi, CORE_ADDR *lowpc,
7305                     CORE_ADDR *highpc, int set_addrmap, struct dwarf2_cu *cu)
7306 {
7307   /* Add a symbol for the namespace.  */
7308
7309   add_partial_symbol (pdi, cu);
7310
7311   /* Now scan partial symbols in that module.  */
7312
7313   if (pdi->has_children)
7314     scan_partial_symbols (pdi->die_child, lowpc, highpc, set_addrmap, cu);
7315 }
7316
7317 /* Read a partial die corresponding to a subprogram and create a partial
7318    symbol for that subprogram.  When the CU language allows it, this
7319    routine also defines a partial symbol for each nested subprogram
7320    that this subprogram contains.  If SET_ADDRMAP is true, record the
7321    covered ranges in the addrmap.  Set *LOWPC and *HIGHPC to the lowest
7322    and highest PC values found in PDI.
7323
7324    PDI may also be a lexical block, in which case we simply search
7325    recursively for subprograms defined inside that lexical block.
7326    Again, this is only performed when the CU language allows this
7327    type of definitions.  */
7328
7329 static void
7330 add_partial_subprogram (struct partial_die_info *pdi,
7331                         CORE_ADDR *lowpc, CORE_ADDR *highpc,
7332                         int set_addrmap, struct dwarf2_cu *cu)
7333 {
7334   if (pdi->tag == DW_TAG_subprogram)
7335     {
7336       if (pdi->has_pc_info)
7337         {
7338           if (pdi->lowpc < *lowpc)
7339             *lowpc = pdi->lowpc;
7340           if (pdi->highpc > *highpc)
7341             *highpc = pdi->highpc;
7342           if (set_addrmap)
7343             {
7344               struct objfile *objfile = cu->objfile;
7345               struct gdbarch *gdbarch = get_objfile_arch (objfile);
7346               CORE_ADDR baseaddr;
7347               CORE_ADDR highpc;
7348               CORE_ADDR lowpc;
7349
7350               baseaddr = ANOFFSET (objfile->section_offsets,
7351                                    SECT_OFF_TEXT (objfile));
7352               lowpc = gdbarch_adjust_dwarf2_addr (gdbarch,
7353                                                   pdi->lowpc + baseaddr);
7354               highpc = gdbarch_adjust_dwarf2_addr (gdbarch,
7355                                                    pdi->highpc + baseaddr);
7356               addrmap_set_empty (objfile->psymtabs_addrmap, lowpc, highpc - 1,
7357                                  cu->per_cu->v.psymtab);
7358             }
7359         }
7360
7361       if (pdi->has_pc_info || (!pdi->is_external && pdi->may_be_inlined))
7362         {
7363           if (!pdi->is_declaration)
7364             /* Ignore subprogram DIEs that do not have a name, they are
7365                illegal.  Do not emit a complaint at this point, we will
7366                do so when we convert this psymtab into a symtab.  */
7367             if (pdi->name)
7368               add_partial_symbol (pdi, cu);
7369         }
7370     }
7371
7372   if (! pdi->has_children)
7373     return;
7374
7375   if (cu->language == language_ada)
7376     {
7377       pdi = pdi->die_child;
7378       while (pdi != NULL)
7379         {
7380           fixup_partial_die (pdi, cu);
7381           if (pdi->tag == DW_TAG_subprogram
7382               || pdi->tag == DW_TAG_lexical_block)
7383             add_partial_subprogram (pdi, lowpc, highpc, set_addrmap, cu);
7384           pdi = pdi->die_sibling;
7385         }
7386     }
7387 }
7388
7389 /* Read a partial die corresponding to an enumeration type.  */
7390
7391 static void
7392 add_partial_enumeration (struct partial_die_info *enum_pdi,
7393                          struct dwarf2_cu *cu)
7394 {
7395   struct partial_die_info *pdi;
7396
7397   if (enum_pdi->name != NULL)
7398     add_partial_symbol (enum_pdi, cu);
7399
7400   pdi = enum_pdi->die_child;
7401   while (pdi)
7402     {
7403       if (pdi->tag != DW_TAG_enumerator || pdi->name == NULL)
7404         complaint (&symfile_complaints, _("malformed enumerator DIE ignored"));
7405       else
7406         add_partial_symbol (pdi, cu);
7407       pdi = pdi->die_sibling;
7408     }
7409 }
7410
7411 /* Return the initial uleb128 in the die at INFO_PTR.  */
7412
7413 static unsigned int
7414 peek_abbrev_code (bfd *abfd, const gdb_byte *info_ptr)
7415 {
7416   unsigned int bytes_read;
7417
7418   return read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
7419 }
7420
7421 /* Read the initial uleb128 in the die at INFO_PTR in compilation unit CU.
7422    Return the corresponding abbrev, or NULL if the number is zero (indicating
7423    an empty DIE).  In either case *BYTES_READ will be set to the length of
7424    the initial number.  */
7425
7426 static struct abbrev_info *
7427 peek_die_abbrev (const gdb_byte *info_ptr, unsigned int *bytes_read,
7428                  struct dwarf2_cu *cu)
7429 {
7430   bfd *abfd = cu->objfile->obfd;
7431   unsigned int abbrev_number;
7432   struct abbrev_info *abbrev;
7433
7434   abbrev_number = read_unsigned_leb128 (abfd, info_ptr, bytes_read);
7435
7436   if (abbrev_number == 0)
7437     return NULL;
7438
7439   abbrev = abbrev_table_lookup_abbrev (cu->abbrev_table, abbrev_number);
7440   if (!abbrev)
7441     {
7442       error (_("Dwarf Error: Could not find abbrev number %d in %s"
7443                " at offset 0x%x [in module %s]"),
7444              abbrev_number, cu->per_cu->is_debug_types ? "TU" : "CU",
7445              to_underlying (cu->header.sect_off), bfd_get_filename (abfd));
7446     }
7447
7448   return abbrev;
7449 }
7450
7451 /* Scan the debug information for CU starting at INFO_PTR in buffer BUFFER.
7452    Returns a pointer to the end of a series of DIEs, terminated by an empty
7453    DIE.  Any children of the skipped DIEs will also be skipped.  */
7454
7455 static const gdb_byte *
7456 skip_children (const struct die_reader_specs *reader, const gdb_byte *info_ptr)
7457 {
7458   struct dwarf2_cu *cu = reader->cu;
7459   struct abbrev_info *abbrev;
7460   unsigned int bytes_read;
7461
7462   while (1)
7463     {
7464       abbrev = peek_die_abbrev (info_ptr, &bytes_read, cu);
7465       if (abbrev == NULL)
7466         return info_ptr + bytes_read;
7467       else
7468         info_ptr = skip_one_die (reader, info_ptr + bytes_read, abbrev);
7469     }
7470 }
7471
7472 /* Scan the debug information for CU starting at INFO_PTR in buffer BUFFER.
7473    INFO_PTR should point just after the initial uleb128 of a DIE, and the
7474    abbrev corresponding to that skipped uleb128 should be passed in
7475    ABBREV.  Returns a pointer to this DIE's sibling, skipping any
7476    children.  */
7477
7478 static const gdb_byte *
7479 skip_one_die (const struct die_reader_specs *reader, const gdb_byte *info_ptr,
7480               struct abbrev_info *abbrev)
7481 {
7482   unsigned int bytes_read;
7483   struct attribute attr;
7484   bfd *abfd = reader->abfd;
7485   struct dwarf2_cu *cu = reader->cu;
7486   const gdb_byte *buffer = reader->buffer;
7487   const gdb_byte *buffer_end = reader->buffer_end;
7488   unsigned int form, i;
7489
7490   for (i = 0; i < abbrev->num_attrs; i++)
7491     {
7492       /* The only abbrev we care about is DW_AT_sibling.  */
7493       if (abbrev->attrs[i].name == DW_AT_sibling)
7494         {
7495           read_attribute (reader, &attr, &abbrev->attrs[i], info_ptr);
7496           if (attr.form == DW_FORM_ref_addr)
7497             complaint (&symfile_complaints,
7498                        _("ignoring absolute DW_AT_sibling"));
7499           else
7500             {
7501               sect_offset off = dwarf2_get_ref_die_offset (&attr);
7502               const gdb_byte *sibling_ptr = buffer + to_underlying (off);
7503
7504               if (sibling_ptr < info_ptr)
7505                 complaint (&symfile_complaints,
7506                            _("DW_AT_sibling points backwards"));
7507               else if (sibling_ptr > reader->buffer_end)
7508                 dwarf2_section_buffer_overflow_complaint (reader->die_section);
7509               else
7510                 return sibling_ptr;
7511             }
7512         }
7513
7514       /* If it isn't DW_AT_sibling, skip this attribute.  */
7515       form = abbrev->attrs[i].form;
7516     skip_attribute:
7517       switch (form)
7518         {
7519         case DW_FORM_ref_addr:
7520           /* In DWARF 2, DW_FORM_ref_addr is address sized; in DWARF 3
7521              and later it is offset sized.  */
7522           if (cu->header.version == 2)
7523             info_ptr += cu->header.addr_size;
7524           else
7525             info_ptr += cu->header.offset_size;
7526           break;
7527         case DW_FORM_GNU_ref_alt:
7528           info_ptr += cu->header.offset_size;
7529           break;
7530         case DW_FORM_addr:
7531           info_ptr += cu->header.addr_size;
7532           break;
7533         case DW_FORM_data1:
7534         case DW_FORM_ref1:
7535         case DW_FORM_flag:
7536           info_ptr += 1;
7537           break;
7538         case DW_FORM_flag_present:
7539         case DW_FORM_implicit_const:
7540           break;
7541         case DW_FORM_data2:
7542         case DW_FORM_ref2:
7543           info_ptr += 2;
7544           break;
7545         case DW_FORM_data4:
7546         case DW_FORM_ref4:
7547           info_ptr += 4;
7548           break;
7549         case DW_FORM_data8:
7550         case DW_FORM_ref8:
7551         case DW_FORM_ref_sig8:
7552           info_ptr += 8;
7553           break;
7554         case DW_FORM_data16:
7555           info_ptr += 16;
7556           break;
7557         case DW_FORM_string:
7558           read_direct_string (abfd, info_ptr, &bytes_read);
7559           info_ptr += bytes_read;
7560           break;
7561         case DW_FORM_sec_offset:
7562         case DW_FORM_strp:
7563         case DW_FORM_GNU_strp_alt:
7564           info_ptr += cu->header.offset_size;
7565           break;
7566         case DW_FORM_exprloc:
7567         case DW_FORM_block:
7568           info_ptr += read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
7569           info_ptr += bytes_read;
7570           break;
7571         case DW_FORM_block1:
7572           info_ptr += 1 + read_1_byte (abfd, info_ptr);
7573           break;
7574         case DW_FORM_block2:
7575           info_ptr += 2 + read_2_bytes (abfd, info_ptr);
7576           break;
7577         case DW_FORM_block4:
7578           info_ptr += 4 + read_4_bytes (abfd, info_ptr);
7579           break;
7580         case DW_FORM_sdata:
7581         case DW_FORM_udata:
7582         case DW_FORM_ref_udata:
7583         case DW_FORM_GNU_addr_index:
7584         case DW_FORM_GNU_str_index:
7585           info_ptr = safe_skip_leb128 (info_ptr, buffer_end);
7586           break;
7587         case DW_FORM_indirect:
7588           form = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
7589           info_ptr += bytes_read;
7590           /* We need to continue parsing from here, so just go back to
7591              the top.  */
7592           goto skip_attribute;
7593
7594         default:
7595           error (_("Dwarf Error: Cannot handle %s "
7596                    "in DWARF reader [in module %s]"),
7597                  dwarf_form_name (form),
7598                  bfd_get_filename (abfd));
7599         }
7600     }
7601
7602   if (abbrev->has_children)
7603     return skip_children (reader, info_ptr);
7604   else
7605     return info_ptr;
7606 }
7607
7608 /* Locate ORIG_PDI's sibling.
7609    INFO_PTR should point to the start of the next DIE after ORIG_PDI.  */
7610
7611 static const gdb_byte *
7612 locate_pdi_sibling (const struct die_reader_specs *reader,
7613                     struct partial_die_info *orig_pdi,
7614                     const gdb_byte *info_ptr)
7615 {
7616   /* Do we know the sibling already?  */
7617
7618   if (orig_pdi->sibling)
7619     return orig_pdi->sibling;
7620
7621   /* Are there any children to deal with?  */
7622
7623   if (!orig_pdi->has_children)
7624     return info_ptr;
7625
7626   /* Skip the children the long way.  */
7627
7628   return skip_children (reader, info_ptr);
7629 }
7630
7631 /* Expand this partial symbol table into a full symbol table.  SELF is
7632    not NULL.  */
7633
7634 static void
7635 dwarf2_read_symtab (struct partial_symtab *self,
7636                     struct objfile *objfile)
7637 {
7638   if (self->readin)
7639     {
7640       warning (_("bug: psymtab for %s is already read in."),
7641                self->filename);
7642     }
7643   else
7644     {
7645       if (info_verbose)
7646         {
7647           printf_filtered (_("Reading in symbols for %s..."),
7648                            self->filename);
7649           gdb_flush (gdb_stdout);
7650         }
7651
7652       /* Restore our global data.  */
7653       dwarf2_per_objfile
7654         = (struct dwarf2_per_objfile *) objfile_data (objfile,
7655                                                       dwarf2_objfile_data_key);
7656
7657       /* If this psymtab is constructed from a debug-only objfile, the
7658          has_section_at_zero flag will not necessarily be correct.  We
7659          can get the correct value for this flag by looking at the data
7660          associated with the (presumably stripped) associated objfile.  */
7661       if (objfile->separate_debug_objfile_backlink)
7662         {
7663           struct dwarf2_per_objfile *dpo_backlink
7664             = ((struct dwarf2_per_objfile *)
7665                objfile_data (objfile->separate_debug_objfile_backlink,
7666                              dwarf2_objfile_data_key));
7667
7668           dwarf2_per_objfile->has_section_at_zero
7669             = dpo_backlink->has_section_at_zero;
7670         }
7671
7672       dwarf2_per_objfile->reading_partial_symbols = 0;
7673
7674       psymtab_to_symtab_1 (self);
7675
7676       /* Finish up the debug error message.  */
7677       if (info_verbose)
7678         printf_filtered (_("done.\n"));
7679     }
7680
7681   process_cu_includes ();
7682 }
7683 \f
7684 /* Reading in full CUs.  */
7685
7686 /* Add PER_CU to the queue.  */
7687
7688 static void
7689 queue_comp_unit (struct dwarf2_per_cu_data *per_cu,
7690                  enum language pretend_language)
7691 {
7692   struct dwarf2_queue_item *item;
7693
7694   per_cu->queued = 1;
7695   item = XNEW (struct dwarf2_queue_item);
7696   item->per_cu = per_cu;
7697   item->pretend_language = pretend_language;
7698   item->next = NULL;
7699
7700   if (dwarf2_queue == NULL)
7701     dwarf2_queue = item;
7702   else
7703     dwarf2_queue_tail->next = item;
7704
7705   dwarf2_queue_tail = item;
7706 }
7707
7708 /* If PER_CU is not yet queued, add it to the queue.
7709    If DEPENDENT_CU is non-NULL, it has a reference to PER_CU so add a
7710    dependency.
7711    The result is non-zero if PER_CU was queued, otherwise the result is zero
7712    meaning either PER_CU is already queued or it is already loaded.
7713
7714    N.B. There is an invariant here that if a CU is queued then it is loaded.
7715    The caller is required to load PER_CU if we return non-zero.  */
7716
7717 static int
7718 maybe_queue_comp_unit (struct dwarf2_cu *dependent_cu,
7719                        struct dwarf2_per_cu_data *per_cu,
7720                        enum language pretend_language)
7721 {
7722   /* We may arrive here during partial symbol reading, if we need full
7723      DIEs to process an unusual case (e.g. template arguments).  Do
7724      not queue PER_CU, just tell our caller to load its DIEs.  */
7725   if (dwarf2_per_objfile->reading_partial_symbols)
7726     {
7727       if (per_cu->cu == NULL || per_cu->cu->dies == NULL)
7728         return 1;
7729       return 0;
7730     }
7731
7732   /* Mark the dependence relation so that we don't flush PER_CU
7733      too early.  */
7734   if (dependent_cu != NULL)
7735     dwarf2_add_dependence (dependent_cu, per_cu);
7736
7737   /* If it's already on the queue, we have nothing to do.  */
7738   if (per_cu->queued)
7739     return 0;
7740
7741   /* If the compilation unit is already loaded, just mark it as
7742      used.  */
7743   if (per_cu->cu != NULL)
7744     {
7745       per_cu->cu->last_used = 0;
7746       return 0;
7747     }
7748
7749   /* Add it to the queue.  */
7750   queue_comp_unit (per_cu, pretend_language);
7751
7752   return 1;
7753 }
7754
7755 /* Process the queue.  */
7756
7757 static void
7758 process_queue (void)
7759 {
7760   struct dwarf2_queue_item *item, *next_item;
7761
7762   if (dwarf_read_debug)
7763     {
7764       fprintf_unfiltered (gdb_stdlog,
7765                           "Expanding one or more symtabs of objfile %s ...\n",
7766                           objfile_name (dwarf2_per_objfile->objfile));
7767     }
7768
7769   /* The queue starts out with one item, but following a DIE reference
7770      may load a new CU, adding it to the end of the queue.  */
7771   for (item = dwarf2_queue; item != NULL; dwarf2_queue = item = next_item)
7772     {
7773       if ((dwarf2_per_objfile->using_index
7774            ? !item->per_cu->v.quick->compunit_symtab
7775            : (item->per_cu->v.psymtab && !item->per_cu->v.psymtab->readin))
7776           /* Skip dummy CUs.  */
7777           && item->per_cu->cu != NULL)
7778         {
7779           struct dwarf2_per_cu_data *per_cu = item->per_cu;
7780           unsigned int debug_print_threshold;
7781           char buf[100];
7782
7783           if (per_cu->is_debug_types)
7784             {
7785               struct signatured_type *sig_type =
7786                 (struct signatured_type *) per_cu;
7787
7788               sprintf (buf, "TU %s at offset 0x%x",
7789                        hex_string (sig_type->signature),
7790                        to_underlying (per_cu->sect_off));
7791               /* There can be 100s of TUs.
7792                  Only print them in verbose mode.  */
7793               debug_print_threshold = 2;
7794             }
7795           else
7796             {
7797               sprintf (buf, "CU at offset 0x%x",
7798                        to_underlying (per_cu->sect_off));
7799               debug_print_threshold = 1;
7800             }
7801
7802           if (dwarf_read_debug >= debug_print_threshold)
7803             fprintf_unfiltered (gdb_stdlog, "Expanding symtab of %s\n", buf);
7804
7805           if (per_cu->is_debug_types)
7806             process_full_type_unit (per_cu, item->pretend_language);
7807           else
7808             process_full_comp_unit (per_cu, item->pretend_language);
7809
7810           if (dwarf_read_debug >= debug_print_threshold)
7811             fprintf_unfiltered (gdb_stdlog, "Done expanding %s\n", buf);
7812         }
7813
7814       item->per_cu->queued = 0;
7815       next_item = item->next;
7816       xfree (item);
7817     }
7818
7819   dwarf2_queue_tail = NULL;
7820
7821   if (dwarf_read_debug)
7822     {
7823       fprintf_unfiltered (gdb_stdlog, "Done expanding symtabs of %s.\n",
7824                           objfile_name (dwarf2_per_objfile->objfile));
7825     }
7826 }
7827
7828 /* Free all allocated queue entries.  This function only releases anything if
7829    an error was thrown; if the queue was processed then it would have been
7830    freed as we went along.  */
7831
7832 static void
7833 dwarf2_release_queue (void *dummy)
7834 {
7835   struct dwarf2_queue_item *item, *last;
7836
7837   item = dwarf2_queue;
7838   while (item)
7839     {
7840       /* Anything still marked queued is likely to be in an
7841          inconsistent state, so discard it.  */
7842       if (item->per_cu->queued)
7843         {
7844           if (item->per_cu->cu != NULL)
7845             free_one_cached_comp_unit (item->per_cu);
7846           item->per_cu->queued = 0;
7847         }
7848
7849       last = item;
7850       item = item->next;
7851       xfree (last);
7852     }
7853
7854   dwarf2_queue = dwarf2_queue_tail = NULL;
7855 }
7856
7857 /* Read in full symbols for PST, and anything it depends on.  */
7858
7859 static void
7860 psymtab_to_symtab_1 (struct partial_symtab *pst)
7861 {
7862   struct dwarf2_per_cu_data *per_cu;
7863   int i;
7864
7865   if (pst->readin)
7866     return;
7867
7868   for (i = 0; i < pst->number_of_dependencies; i++)
7869     if (!pst->dependencies[i]->readin
7870         && pst->dependencies[i]->user == NULL)
7871       {
7872         /* Inform about additional files that need to be read in.  */
7873         if (info_verbose)
7874           {
7875             /* FIXME: i18n: Need to make this a single string.  */
7876             fputs_filtered (" ", gdb_stdout);
7877             wrap_here ("");
7878             fputs_filtered ("and ", gdb_stdout);
7879             wrap_here ("");
7880             printf_filtered ("%s...", pst->dependencies[i]->filename);
7881             wrap_here ("");     /* Flush output.  */
7882             gdb_flush (gdb_stdout);
7883           }
7884         psymtab_to_symtab_1 (pst->dependencies[i]);
7885       }
7886
7887   per_cu = (struct dwarf2_per_cu_data *) pst->read_symtab_private;
7888
7889   if (per_cu == NULL)
7890     {
7891       /* It's an include file, no symbols to read for it.
7892          Everything is in the parent symtab.  */
7893       pst->readin = 1;
7894       return;
7895     }
7896
7897   dw2_do_instantiate_symtab (per_cu);
7898 }
7899
7900 /* Trivial hash function for die_info: the hash value of a DIE
7901    is its offset in .debug_info for this objfile.  */
7902
7903 static hashval_t
7904 die_hash (const void *item)
7905 {
7906   const struct die_info *die = (const struct die_info *) item;
7907
7908   return to_underlying (die->sect_off);
7909 }
7910
7911 /* Trivial comparison function for die_info structures: two DIEs
7912    are equal if they have the same offset.  */
7913
7914 static int
7915 die_eq (const void *item_lhs, const void *item_rhs)
7916 {
7917   const struct die_info *die_lhs = (const struct die_info *) item_lhs;
7918   const struct die_info *die_rhs = (const struct die_info *) item_rhs;
7919
7920   return die_lhs->sect_off == die_rhs->sect_off;
7921 }
7922
7923 /* die_reader_func for load_full_comp_unit.
7924    This is identical to read_signatured_type_reader,
7925    but is kept separate for now.  */
7926
7927 static void
7928 load_full_comp_unit_reader (const struct die_reader_specs *reader,
7929                             const gdb_byte *info_ptr,
7930                             struct die_info *comp_unit_die,
7931                             int has_children,
7932                             void *data)
7933 {
7934   struct dwarf2_cu *cu = reader->cu;
7935   enum language *language_ptr = (enum language *) data;
7936
7937   gdb_assert (cu->die_hash == NULL);
7938   cu->die_hash =
7939     htab_create_alloc_ex (cu->header.length / 12,
7940                           die_hash,
7941                           die_eq,
7942                           NULL,
7943                           &cu->comp_unit_obstack,
7944                           hashtab_obstack_allocate,
7945                           dummy_obstack_deallocate);
7946
7947   if (has_children)
7948     comp_unit_die->child = read_die_and_siblings (reader, info_ptr,
7949                                                   &info_ptr, comp_unit_die);
7950   cu->dies = comp_unit_die;
7951   /* comp_unit_die is not stored in die_hash, no need.  */
7952
7953   /* We try not to read any attributes in this function, because not
7954      all CUs needed for references have been loaded yet, and symbol
7955      table processing isn't initialized.  But we have to set the CU language,
7956      or we won't be able to build types correctly.
7957      Similarly, if we do not read the producer, we can not apply
7958      producer-specific interpretation.  */
7959   prepare_one_comp_unit (cu, cu->dies, *language_ptr);
7960 }
7961
7962 /* Load the DIEs associated with PER_CU into memory.  */
7963
7964 static void
7965 load_full_comp_unit (struct dwarf2_per_cu_data *this_cu,
7966                      enum language pretend_language)
7967 {
7968   gdb_assert (! this_cu->is_debug_types);
7969
7970   init_cutu_and_read_dies (this_cu, NULL, 1, 1,
7971                            load_full_comp_unit_reader, &pretend_language);
7972 }
7973
7974 /* Add a DIE to the delayed physname list.  */
7975
7976 static void
7977 add_to_method_list (struct type *type, int fnfield_index, int index,
7978                     const char *name, struct die_info *die,
7979                     struct dwarf2_cu *cu)
7980 {
7981   struct delayed_method_info mi;
7982   mi.type = type;
7983   mi.fnfield_index = fnfield_index;
7984   mi.index = index;
7985   mi.name = name;
7986   mi.die = die;
7987   VEC_safe_push (delayed_method_info, cu->method_list, &mi);
7988 }
7989
7990 /* A cleanup for freeing the delayed method list.  */
7991
7992 static void
7993 free_delayed_list (void *ptr)
7994 {
7995   struct dwarf2_cu *cu = (struct dwarf2_cu *) ptr;
7996   if (cu->method_list != NULL)
7997     {
7998       VEC_free (delayed_method_info, cu->method_list);
7999       cu->method_list = NULL;
8000     }
8001 }
8002
8003 /* Compute the physnames of any methods on the CU's method list.
8004
8005    The computation of method physnames is delayed in order to avoid the
8006    (bad) condition that one of the method's formal parameters is of an as yet
8007    incomplete type.  */
8008
8009 static void
8010 compute_delayed_physnames (struct dwarf2_cu *cu)
8011 {
8012   int i;
8013   struct delayed_method_info *mi;
8014   for (i = 0; VEC_iterate (delayed_method_info, cu->method_list, i, mi) ; ++i)
8015     {
8016       const char *physname;
8017       struct fn_fieldlist *fn_flp
8018         = &TYPE_FN_FIELDLIST (mi->type, mi->fnfield_index);
8019       physname = dwarf2_physname (mi->name, mi->die, cu);
8020       TYPE_FN_FIELD_PHYSNAME (fn_flp->fn_fields, mi->index)
8021         = physname ? physname : "";
8022     }
8023 }
8024
8025 /* Go objects should be embedded in a DW_TAG_module DIE,
8026    and it's not clear if/how imported objects will appear.
8027    To keep Go support simple until that's worked out,
8028    go back through what we've read and create something usable.
8029    We could do this while processing each DIE, and feels kinda cleaner,
8030    but that way is more invasive.
8031    This is to, for example, allow the user to type "p var" or "b main"
8032    without having to specify the package name, and allow lookups
8033    of module.object to work in contexts that use the expression
8034    parser.  */
8035
8036 static void
8037 fixup_go_packaging (struct dwarf2_cu *cu)
8038 {
8039   char *package_name = NULL;
8040   struct pending *list;
8041   int i;
8042
8043   for (list = global_symbols; list != NULL; list = list->next)
8044     {
8045       for (i = 0; i < list->nsyms; ++i)
8046         {
8047           struct symbol *sym = list->symbol[i];
8048
8049           if (SYMBOL_LANGUAGE (sym) == language_go
8050               && SYMBOL_CLASS (sym) == LOC_BLOCK)
8051             {
8052               char *this_package_name = go_symbol_package_name (sym);
8053
8054               if (this_package_name == NULL)
8055                 continue;
8056               if (package_name == NULL)
8057                 package_name = this_package_name;
8058               else
8059                 {
8060                   if (strcmp (package_name, this_package_name) != 0)
8061                     complaint (&symfile_complaints,
8062                                _("Symtab %s has objects from two different Go packages: %s and %s"),
8063                                (symbol_symtab (sym) != NULL
8064                                 ? symtab_to_filename_for_display
8065                                     (symbol_symtab (sym))
8066                                 : objfile_name (cu->objfile)),
8067                                this_package_name, package_name);
8068                   xfree (this_package_name);
8069                 }
8070             }
8071         }
8072     }
8073
8074   if (package_name != NULL)
8075     {
8076       struct objfile *objfile = cu->objfile;
8077       const char *saved_package_name
8078         = (const char *) obstack_copy0 (&objfile->per_bfd->storage_obstack,
8079                                         package_name,
8080                                         strlen (package_name));
8081       struct type *type = init_type (objfile, TYPE_CODE_MODULE, 0,
8082                                      saved_package_name);
8083       struct symbol *sym;
8084
8085       TYPE_TAG_NAME (type) = TYPE_NAME (type);
8086
8087       sym = allocate_symbol (objfile);
8088       SYMBOL_SET_LANGUAGE (sym, language_go, &objfile->objfile_obstack);
8089       SYMBOL_SET_NAMES (sym, saved_package_name,
8090                         strlen (saved_package_name), 0, objfile);
8091       /* This is not VAR_DOMAIN because we want a way to ensure a lookup of,
8092          e.g., "main" finds the "main" module and not C's main().  */
8093       SYMBOL_DOMAIN (sym) = STRUCT_DOMAIN;
8094       SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
8095       SYMBOL_TYPE (sym) = type;
8096
8097       add_symbol_to_list (sym, &global_symbols);
8098
8099       xfree (package_name);
8100     }
8101 }
8102
8103 /* Return the symtab for PER_CU.  This works properly regardless of
8104    whether we're using the index or psymtabs.  */
8105
8106 static struct compunit_symtab *
8107 get_compunit_symtab (struct dwarf2_per_cu_data *per_cu)
8108 {
8109   return (dwarf2_per_objfile->using_index
8110           ? per_cu->v.quick->compunit_symtab
8111           : per_cu->v.psymtab->compunit_symtab);
8112 }
8113
8114 /* A helper function for computing the list of all symbol tables
8115    included by PER_CU.  */
8116
8117 static void
8118 recursively_compute_inclusions (VEC (compunit_symtab_ptr) **result,
8119                                 htab_t all_children, htab_t all_type_symtabs,
8120                                 struct dwarf2_per_cu_data *per_cu,
8121                                 struct compunit_symtab *immediate_parent)
8122 {
8123   void **slot;
8124   int ix;
8125   struct compunit_symtab *cust;
8126   struct dwarf2_per_cu_data *iter;
8127
8128   slot = htab_find_slot (all_children, per_cu, INSERT);
8129   if (*slot != NULL)
8130     {
8131       /* This inclusion and its children have been processed.  */
8132       return;
8133     }
8134
8135   *slot = per_cu;
8136   /* Only add a CU if it has a symbol table.  */
8137   cust = get_compunit_symtab (per_cu);
8138   if (cust != NULL)
8139     {
8140       /* If this is a type unit only add its symbol table if we haven't
8141          seen it yet (type unit per_cu's can share symtabs).  */
8142       if (per_cu->is_debug_types)
8143         {
8144           slot = htab_find_slot (all_type_symtabs, cust, INSERT);
8145           if (*slot == NULL)
8146             {
8147               *slot = cust;
8148               VEC_safe_push (compunit_symtab_ptr, *result, cust);
8149               if (cust->user == NULL)
8150                 cust->user = immediate_parent;
8151             }
8152         }
8153       else
8154         {
8155           VEC_safe_push (compunit_symtab_ptr, *result, cust);
8156           if (cust->user == NULL)
8157             cust->user = immediate_parent;
8158         }
8159     }
8160
8161   for (ix = 0;
8162        VEC_iterate (dwarf2_per_cu_ptr, per_cu->imported_symtabs, ix, iter);
8163        ++ix)
8164     {
8165       recursively_compute_inclusions (result, all_children,
8166                                       all_type_symtabs, iter, cust);
8167     }
8168 }
8169
8170 /* Compute the compunit_symtab 'includes' fields for the compunit_symtab of
8171    PER_CU.  */
8172
8173 static void
8174 compute_compunit_symtab_includes (struct dwarf2_per_cu_data *per_cu)
8175 {
8176   gdb_assert (! per_cu->is_debug_types);
8177
8178   if (!VEC_empty (dwarf2_per_cu_ptr, per_cu->imported_symtabs))
8179     {
8180       int ix, len;
8181       struct dwarf2_per_cu_data *per_cu_iter;
8182       struct compunit_symtab *compunit_symtab_iter;
8183       VEC (compunit_symtab_ptr) *result_symtabs = NULL;
8184       htab_t all_children, all_type_symtabs;
8185       struct compunit_symtab *cust = get_compunit_symtab (per_cu);
8186
8187       /* If we don't have a symtab, we can just skip this case.  */
8188       if (cust == NULL)
8189         return;
8190
8191       all_children = htab_create_alloc (1, htab_hash_pointer, htab_eq_pointer,
8192                                         NULL, xcalloc, xfree);
8193       all_type_symtabs = htab_create_alloc (1, htab_hash_pointer, htab_eq_pointer,
8194                                             NULL, xcalloc, xfree);
8195
8196       for (ix = 0;
8197            VEC_iterate (dwarf2_per_cu_ptr, per_cu->imported_symtabs,
8198                         ix, per_cu_iter);
8199            ++ix)
8200         {
8201           recursively_compute_inclusions (&result_symtabs, all_children,
8202                                           all_type_symtabs, per_cu_iter,
8203                                           cust);
8204         }
8205
8206       /* Now we have a transitive closure of all the included symtabs.  */
8207       len = VEC_length (compunit_symtab_ptr, result_symtabs);
8208       cust->includes
8209         = XOBNEWVEC (&dwarf2_per_objfile->objfile->objfile_obstack,
8210                      struct compunit_symtab *, len + 1);
8211       for (ix = 0;
8212            VEC_iterate (compunit_symtab_ptr, result_symtabs, ix,
8213                         compunit_symtab_iter);
8214            ++ix)
8215         cust->includes[ix] = compunit_symtab_iter;
8216       cust->includes[len] = NULL;
8217
8218       VEC_free (compunit_symtab_ptr, result_symtabs);
8219       htab_delete (all_children);
8220       htab_delete (all_type_symtabs);
8221     }
8222 }
8223
8224 /* Compute the 'includes' field for the symtabs of all the CUs we just
8225    read.  */
8226
8227 static void
8228 process_cu_includes (void)
8229 {
8230   int ix;
8231   struct dwarf2_per_cu_data *iter;
8232
8233   for (ix = 0;
8234        VEC_iterate (dwarf2_per_cu_ptr, dwarf2_per_objfile->just_read_cus,
8235                     ix, iter);
8236        ++ix)
8237     {
8238       if (! iter->is_debug_types)
8239         compute_compunit_symtab_includes (iter);
8240     }
8241
8242   VEC_free (dwarf2_per_cu_ptr, dwarf2_per_objfile->just_read_cus);
8243 }
8244
8245 /* Generate full symbol information for PER_CU, whose DIEs have
8246    already been loaded into memory.  */
8247
8248 static void
8249 process_full_comp_unit (struct dwarf2_per_cu_data *per_cu,
8250                         enum language pretend_language)
8251 {
8252   struct dwarf2_cu *cu = per_cu->cu;
8253   struct objfile *objfile = per_cu->objfile;
8254   struct gdbarch *gdbarch = get_objfile_arch (objfile);
8255   CORE_ADDR lowpc, highpc;
8256   struct compunit_symtab *cust;
8257   struct cleanup *back_to, *delayed_list_cleanup;
8258   CORE_ADDR baseaddr;
8259   struct block *static_block;
8260   CORE_ADDR addr;
8261
8262   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
8263
8264   buildsym_init ();
8265   back_to = make_cleanup (really_free_pendings, NULL);
8266   delayed_list_cleanup = make_cleanup (free_delayed_list, cu);
8267
8268   cu->list_in_scope = &file_symbols;
8269
8270   cu->language = pretend_language;
8271   cu->language_defn = language_def (cu->language);
8272
8273   /* Do line number decoding in read_file_scope () */
8274   process_die (cu->dies, cu);
8275
8276   /* For now fudge the Go package.  */
8277   if (cu->language == language_go)
8278     fixup_go_packaging (cu);
8279
8280   /* Now that we have processed all the DIEs in the CU, all the types 
8281      should be complete, and it should now be safe to compute all of the
8282      physnames.  */
8283   compute_delayed_physnames (cu);
8284   do_cleanups (delayed_list_cleanup);
8285
8286   /* Some compilers don't define a DW_AT_high_pc attribute for the
8287      compilation unit.  If the DW_AT_high_pc is missing, synthesize
8288      it, by scanning the DIE's below the compilation unit.  */
8289   get_scope_pc_bounds (cu->dies, &lowpc, &highpc, cu);
8290
8291   addr = gdbarch_adjust_dwarf2_addr (gdbarch, highpc + baseaddr);
8292   static_block = end_symtab_get_static_block (addr, 0, 1);
8293
8294   /* If the comp unit has DW_AT_ranges, it may have discontiguous ranges.
8295      Also, DW_AT_ranges may record ranges not belonging to any child DIEs
8296      (such as virtual method tables).  Record the ranges in STATIC_BLOCK's
8297      addrmap to help ensure it has an accurate map of pc values belonging to
8298      this comp unit.  */
8299   dwarf2_record_block_ranges (cu->dies, static_block, baseaddr, cu);
8300
8301   cust = end_symtab_from_static_block (static_block,
8302                                        SECT_OFF_TEXT (objfile), 0);
8303
8304   if (cust != NULL)
8305     {
8306       int gcc_4_minor = producer_is_gcc_ge_4 (cu->producer);
8307
8308       /* Set symtab language to language from DW_AT_language.  If the
8309          compilation is from a C file generated by language preprocessors, do
8310          not set the language if it was already deduced by start_subfile.  */
8311       if (!(cu->language == language_c
8312             && COMPUNIT_FILETABS (cust)->language != language_unknown))
8313         COMPUNIT_FILETABS (cust)->language = cu->language;
8314
8315       /* GCC-4.0 has started to support -fvar-tracking.  GCC-3.x still can
8316          produce DW_AT_location with location lists but it can be possibly
8317          invalid without -fvar-tracking.  Still up to GCC-4.4.x incl. 4.4.0
8318          there were bugs in prologue debug info, fixed later in GCC-4.5
8319          by "unwind info for epilogues" patch (which is not directly related).
8320
8321          For -gdwarf-4 type units LOCATIONS_VALID indication is fortunately not
8322          needed, it would be wrong due to missing DW_AT_producer there.
8323
8324          Still one can confuse GDB by using non-standard GCC compilation
8325          options - this waits on GCC PR other/32998 (-frecord-gcc-switches).
8326          */ 
8327       if (cu->has_loclist && gcc_4_minor >= 5)
8328         cust->locations_valid = 1;
8329
8330       if (gcc_4_minor >= 5)
8331         cust->epilogue_unwind_valid = 1;
8332
8333       cust->call_site_htab = cu->call_site_htab;
8334     }
8335
8336   if (dwarf2_per_objfile->using_index)
8337     per_cu->v.quick->compunit_symtab = cust;
8338   else
8339     {
8340       struct partial_symtab *pst = per_cu->v.psymtab;
8341       pst->compunit_symtab = cust;
8342       pst->readin = 1;
8343     }
8344
8345   /* Push it for inclusion processing later.  */
8346   VEC_safe_push (dwarf2_per_cu_ptr, dwarf2_per_objfile->just_read_cus, per_cu);
8347
8348   do_cleanups (back_to);
8349 }
8350
8351 /* Generate full symbol information for type unit PER_CU, whose DIEs have
8352    already been loaded into memory.  */
8353
8354 static void
8355 process_full_type_unit (struct dwarf2_per_cu_data *per_cu,
8356                         enum language pretend_language)
8357 {
8358   struct dwarf2_cu *cu = per_cu->cu;
8359   struct objfile *objfile = per_cu->objfile;
8360   struct compunit_symtab *cust;
8361   struct cleanup *back_to, *delayed_list_cleanup;
8362   struct signatured_type *sig_type;
8363
8364   gdb_assert (per_cu->is_debug_types);
8365   sig_type = (struct signatured_type *) per_cu;
8366
8367   buildsym_init ();
8368   back_to = make_cleanup (really_free_pendings, NULL);
8369   delayed_list_cleanup = make_cleanup (free_delayed_list, cu);
8370
8371   cu->list_in_scope = &file_symbols;
8372
8373   cu->language = pretend_language;
8374   cu->language_defn = language_def (cu->language);
8375
8376   /* The symbol tables are set up in read_type_unit_scope.  */
8377   process_die (cu->dies, cu);
8378
8379   /* For now fudge the Go package.  */
8380   if (cu->language == language_go)
8381     fixup_go_packaging (cu);
8382
8383   /* Now that we have processed all the DIEs in the CU, all the types 
8384      should be complete, and it should now be safe to compute all of the
8385      physnames.  */
8386   compute_delayed_physnames (cu);
8387   do_cleanups (delayed_list_cleanup);
8388
8389   /* TUs share symbol tables.
8390      If this is the first TU to use this symtab, complete the construction
8391      of it with end_expandable_symtab.  Otherwise, complete the addition of
8392      this TU's symbols to the existing symtab.  */
8393   if (sig_type->type_unit_group->compunit_symtab == NULL)
8394     {
8395       cust = end_expandable_symtab (0, SECT_OFF_TEXT (objfile));
8396       sig_type->type_unit_group->compunit_symtab = cust;
8397
8398       if (cust != NULL)
8399         {
8400           /* Set symtab language to language from DW_AT_language.  If the
8401              compilation is from a C file generated by language preprocessors,
8402              do not set the language if it was already deduced by
8403              start_subfile.  */
8404           if (!(cu->language == language_c
8405                 && COMPUNIT_FILETABS (cust)->language != language_c))
8406             COMPUNIT_FILETABS (cust)->language = cu->language;
8407         }
8408     }
8409   else
8410     {
8411       augment_type_symtab ();
8412       cust = sig_type->type_unit_group->compunit_symtab;
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   do_cleanups (back_to);
8425 }
8426
8427 /* Process an imported unit DIE.  */
8428
8429 static void
8430 process_imported_unit_die (struct die_info *die, struct dwarf2_cu *cu)
8431 {
8432   struct attribute *attr;
8433
8434   /* For now we don't handle imported units in type units.  */
8435   if (cu->per_cu->is_debug_types)
8436     {
8437       error (_("Dwarf Error: DW_TAG_imported_unit is not"
8438                " supported in type units [in module %s]"),
8439              objfile_name (cu->objfile));
8440     }
8441
8442   attr = dwarf2_attr (die, DW_AT_import, cu);
8443   if (attr != NULL)
8444     {
8445       sect_offset sect_off = dwarf2_get_ref_die_offset (attr);
8446       bool is_dwz = (attr->form == DW_FORM_GNU_ref_alt || cu->per_cu->is_dwz);
8447       dwarf2_per_cu_data *per_cu
8448         = dwarf2_find_containing_comp_unit (sect_off, is_dwz, cu->objfile);
8449
8450       /* If necessary, add it to the queue and load its DIEs.  */
8451       if (maybe_queue_comp_unit (cu, per_cu, cu->language))
8452         load_full_comp_unit (per_cu, cu->language);
8453
8454       VEC_safe_push (dwarf2_per_cu_ptr, cu->per_cu->imported_symtabs,
8455                      per_cu);
8456     }
8457 }
8458
8459 /* Reset the in_process bit of a die.  */
8460
8461 static void
8462 reset_die_in_process (void *arg)
8463 {
8464   struct die_info *die = (struct die_info *) arg;
8465
8466   die->in_process = 0;
8467 }
8468
8469 /* Process a die and its children.  */
8470
8471 static void
8472 process_die (struct die_info *die, struct dwarf2_cu *cu)
8473 {
8474   struct cleanup *in_process;
8475
8476   /* We should only be processing those not already in process.  */
8477   gdb_assert (!die->in_process);
8478
8479   die->in_process = 1;
8480   in_process = make_cleanup (reset_die_in_process,die);
8481
8482   switch (die->tag)
8483     {
8484     case DW_TAG_padding:
8485       break;
8486     case DW_TAG_compile_unit:
8487     case DW_TAG_partial_unit:
8488       read_file_scope (die, cu);
8489       break;
8490     case DW_TAG_type_unit:
8491       read_type_unit_scope (die, cu);
8492       break;
8493     case DW_TAG_subprogram:
8494     case DW_TAG_inlined_subroutine:
8495       read_func_scope (die, cu);
8496       break;
8497     case DW_TAG_lexical_block:
8498     case DW_TAG_try_block:
8499     case DW_TAG_catch_block:
8500       read_lexical_block_scope (die, cu);
8501       break;
8502     case DW_TAG_call_site:
8503     case DW_TAG_GNU_call_site:
8504       read_call_site_scope (die, cu);
8505       break;
8506     case DW_TAG_class_type:
8507     case DW_TAG_interface_type:
8508     case DW_TAG_structure_type:
8509     case DW_TAG_union_type:
8510       process_structure_scope (die, cu);
8511       break;
8512     case DW_TAG_enumeration_type:
8513       process_enumeration_scope (die, cu);
8514       break;
8515
8516     /* These dies have a type, but processing them does not create
8517        a symbol or recurse to process the children.  Therefore we can
8518        read them on-demand through read_type_die.  */
8519     case DW_TAG_subroutine_type:
8520     case DW_TAG_set_type:
8521     case DW_TAG_array_type:
8522     case DW_TAG_pointer_type:
8523     case DW_TAG_ptr_to_member_type:
8524     case DW_TAG_reference_type:
8525     case DW_TAG_rvalue_reference_type:
8526     case DW_TAG_string_type:
8527       break;
8528
8529     case DW_TAG_base_type:
8530     case DW_TAG_subrange_type:
8531     case DW_TAG_typedef:
8532       /* Add a typedef symbol for the type definition, if it has a
8533          DW_AT_name.  */
8534       new_symbol (die, read_type_die (die, cu), cu);
8535       break;
8536     case DW_TAG_common_block:
8537       read_common_block (die, cu);
8538       break;
8539     case DW_TAG_common_inclusion:
8540       break;
8541     case DW_TAG_namespace:
8542       cu->processing_has_namespace_info = 1;
8543       read_namespace (die, cu);
8544       break;
8545     case DW_TAG_module:
8546       cu->processing_has_namespace_info = 1;
8547       read_module (die, cu);
8548       break;
8549     case DW_TAG_imported_declaration:
8550       cu->processing_has_namespace_info = 1;
8551       if (read_namespace_alias (die, cu))
8552         break;
8553       /* The declaration is not a global namespace alias: fall through.  */
8554     case DW_TAG_imported_module:
8555       cu->processing_has_namespace_info = 1;
8556       if (die->child != NULL && (die->tag == DW_TAG_imported_declaration
8557                                  || cu->language != language_fortran))
8558         complaint (&symfile_complaints, _("Tag '%s' has unexpected children"),
8559                    dwarf_tag_name (die->tag));
8560       read_import_statement (die, cu);
8561       break;
8562
8563     case DW_TAG_imported_unit:
8564       process_imported_unit_die (die, cu);
8565       break;
8566
8567     default:
8568       new_symbol (die, NULL, cu);
8569       break;
8570     }
8571
8572   do_cleanups (in_process);
8573 }
8574 \f
8575 /* DWARF name computation.  */
8576
8577 /* A helper function for dwarf2_compute_name which determines whether DIE
8578    needs to have the name of the scope prepended to the name listed in the
8579    die.  */
8580
8581 static int
8582 die_needs_namespace (struct die_info *die, struct dwarf2_cu *cu)
8583 {
8584   struct attribute *attr;
8585
8586   switch (die->tag)
8587     {
8588     case DW_TAG_namespace:
8589     case DW_TAG_typedef:
8590     case DW_TAG_class_type:
8591     case DW_TAG_interface_type:
8592     case DW_TAG_structure_type:
8593     case DW_TAG_union_type:
8594     case DW_TAG_enumeration_type:
8595     case DW_TAG_enumerator:
8596     case DW_TAG_subprogram:
8597     case DW_TAG_inlined_subroutine:
8598     case DW_TAG_member:
8599     case DW_TAG_imported_declaration:
8600       return 1;
8601
8602     case DW_TAG_variable:
8603     case DW_TAG_constant:
8604       /* We only need to prefix "globally" visible variables.  These include
8605          any variable marked with DW_AT_external or any variable that
8606          lives in a namespace.  [Variables in anonymous namespaces
8607          require prefixing, but they are not DW_AT_external.]  */
8608
8609       if (dwarf2_attr (die, DW_AT_specification, cu))
8610         {
8611           struct dwarf2_cu *spec_cu = cu;
8612
8613           return die_needs_namespace (die_specification (die, &spec_cu),
8614                                       spec_cu);
8615         }
8616
8617       attr = dwarf2_attr (die, DW_AT_external, cu);
8618       if (attr == NULL && die->parent->tag != DW_TAG_namespace
8619           && die->parent->tag != DW_TAG_module)
8620         return 0;
8621       /* A variable in a lexical block of some kind does not need a
8622          namespace, even though in C++ such variables may be external
8623          and have a mangled name.  */
8624       if (die->parent->tag ==  DW_TAG_lexical_block
8625           || die->parent->tag ==  DW_TAG_try_block
8626           || die->parent->tag ==  DW_TAG_catch_block
8627           || die->parent->tag == DW_TAG_subprogram)
8628         return 0;
8629       return 1;
8630
8631     default:
8632       return 0;
8633     }
8634 }
8635
8636 /* Compute the fully qualified name of DIE in CU.  If PHYSNAME is nonzero,
8637    compute the physname for the object, which include a method's:
8638    - formal parameters (C++),
8639    - receiver type (Go),
8640
8641    The term "physname" is a bit confusing.
8642    For C++, for example, it is the demangled name.
8643    For Go, for example, it's the mangled name.
8644
8645    For Ada, return the DIE's linkage name rather than the fully qualified
8646    name.  PHYSNAME is ignored..
8647
8648    The result is allocated on the objfile_obstack and canonicalized.  */
8649
8650 static const char *
8651 dwarf2_compute_name (const char *name,
8652                      struct die_info *die, struct dwarf2_cu *cu,
8653                      int physname)
8654 {
8655   struct objfile *objfile = cu->objfile;
8656
8657   if (name == NULL)
8658     name = dwarf2_name (die, cu);
8659
8660   /* For Fortran GDB prefers DW_AT_*linkage_name for the physname if present
8661      but otherwise compute it by typename_concat inside GDB.
8662      FIXME: Actually this is not really true, or at least not always true.
8663      It's all very confusing.  SYMBOL_SET_NAMES doesn't try to demangle
8664      Fortran names because there is no mangling standard.  So new_symbol_full
8665      will set the demangled name to the result of dwarf2_full_name, and it is
8666      the demangled name that GDB uses if it exists.  */
8667   if (cu->language == language_ada
8668       || (cu->language == language_fortran && physname))
8669     {
8670       /* For Ada unit, we prefer the linkage name over the name, as
8671          the former contains the exported name, which the user expects
8672          to be able to reference.  Ideally, we want the user to be able
8673          to reference this entity using either natural or linkage name,
8674          but we haven't started looking at this enhancement yet.  */
8675       const char *linkage_name;
8676
8677       linkage_name = dwarf2_string_attr (die, DW_AT_linkage_name, cu);
8678       if (linkage_name == NULL)
8679         linkage_name = dwarf2_string_attr (die, DW_AT_MIPS_linkage_name, cu);
8680       if (linkage_name != NULL)
8681         return linkage_name;
8682     }
8683
8684   /* These are the only languages we know how to qualify names in.  */
8685   if (name != NULL
8686       && (cu->language == language_cplus
8687           || cu->language == language_fortran || cu->language == language_d
8688           || cu->language == language_rust))
8689     {
8690       if (die_needs_namespace (die, cu))
8691         {
8692           long length;
8693           const char *prefix;
8694           const char *canonical_name = NULL;
8695
8696           string_file buf;
8697
8698           prefix = determine_prefix (die, cu);
8699           if (*prefix != '\0')
8700             {
8701               char *prefixed_name = typename_concat (NULL, prefix, name,
8702                                                      physname, cu);
8703
8704               buf.puts (prefixed_name);
8705               xfree (prefixed_name);
8706             }
8707           else
8708             buf.puts (name);
8709
8710           /* Template parameters may be specified in the DIE's DW_AT_name, or
8711              as children with DW_TAG_template_type_param or
8712              DW_TAG_value_type_param.  If the latter, add them to the name
8713              here.  If the name already has template parameters, then
8714              skip this step; some versions of GCC emit both, and
8715              it is more efficient to use the pre-computed name.
8716
8717              Something to keep in mind about this process: it is very
8718              unlikely, or in some cases downright impossible, to produce
8719              something that will match the mangled name of a function.
8720              If the definition of the function has the same debug info,
8721              we should be able to match up with it anyway.  But fallbacks
8722              using the minimal symbol, for instance to find a method
8723              implemented in a stripped copy of libstdc++, will not work.
8724              If we do not have debug info for the definition, we will have to
8725              match them up some other way.
8726
8727              When we do name matching there is a related problem with function
8728              templates; two instantiated function templates are allowed to
8729              differ only by their return types, which we do not add here.  */
8730
8731           if (cu->language == language_cplus && strchr (name, '<') == NULL)
8732             {
8733               struct attribute *attr;
8734               struct die_info *child;
8735               int first = 1;
8736
8737               die->building_fullname = 1;
8738
8739               for (child = die->child; child != NULL; child = child->sibling)
8740                 {
8741                   struct type *type;
8742                   LONGEST value;
8743                   const gdb_byte *bytes;
8744                   struct dwarf2_locexpr_baton *baton;
8745                   struct value *v;
8746
8747                   if (child->tag != DW_TAG_template_type_param
8748                       && child->tag != DW_TAG_template_value_param)
8749                     continue;
8750
8751                   if (first)
8752                     {
8753                       buf.puts ("<");
8754                       first = 0;
8755                     }
8756                   else
8757                     buf.puts (", ");
8758
8759                   attr = dwarf2_attr (child, DW_AT_type, cu);
8760                   if (attr == NULL)
8761                     {
8762                       complaint (&symfile_complaints,
8763                                  _("template parameter missing DW_AT_type"));
8764                       buf.puts ("UNKNOWN_TYPE");
8765                       continue;
8766                     }
8767                   type = die_type (child, cu);
8768
8769                   if (child->tag == DW_TAG_template_type_param)
8770                     {
8771                       c_print_type (type, "", &buf, -1, 0, &type_print_raw_options);
8772                       continue;
8773                     }
8774
8775                   attr = dwarf2_attr (child, DW_AT_const_value, cu);
8776                   if (attr == NULL)
8777                     {
8778                       complaint (&symfile_complaints,
8779                                  _("template parameter missing "
8780                                    "DW_AT_const_value"));
8781                       buf.puts ("UNKNOWN_VALUE");
8782                       continue;
8783                     }
8784
8785                   dwarf2_const_value_attr (attr, type, name,
8786                                            &cu->comp_unit_obstack, cu,
8787                                            &value, &bytes, &baton);
8788
8789                   if (TYPE_NOSIGN (type))
8790                     /* GDB prints characters as NUMBER 'CHAR'.  If that's
8791                        changed, this can use value_print instead.  */
8792                     c_printchar (value, type, &buf);
8793                   else
8794                     {
8795                       struct value_print_options opts;
8796
8797                       if (baton != NULL)
8798                         v = dwarf2_evaluate_loc_desc (type, NULL,
8799                                                       baton->data,
8800                                                       baton->size,
8801                                                       baton->per_cu);
8802                       else if (bytes != NULL)
8803                         {
8804                           v = allocate_value (type);
8805                           memcpy (value_contents_writeable (v), bytes,
8806                                   TYPE_LENGTH (type));
8807                         }
8808                       else
8809                         v = value_from_longest (type, value);
8810
8811                       /* Specify decimal so that we do not depend on
8812                          the radix.  */
8813                       get_formatted_print_options (&opts, 'd');
8814                       opts.raw = 1;
8815                       value_print (v, &buf, &opts);
8816                       release_value (v);
8817                       value_free (v);
8818                     }
8819                 }
8820
8821               die->building_fullname = 0;
8822
8823               if (!first)
8824                 {
8825                   /* Close the argument list, with a space if necessary
8826                      (nested templates).  */
8827                   if (!buf.empty () && buf.string ().back () == '>')
8828                     buf.puts (" >");
8829                   else
8830                     buf.puts (">");
8831                 }
8832             }
8833
8834           /* For C++ methods, append formal parameter type
8835              information, if PHYSNAME.  */
8836
8837           if (physname && die->tag == DW_TAG_subprogram
8838               && cu->language == language_cplus)
8839             {
8840               struct type *type = read_type_die (die, cu);
8841
8842               c_type_print_args (type, &buf, 1, cu->language,
8843                                  &type_print_raw_options);
8844
8845               if (cu->language == language_cplus)
8846                 {
8847                   /* Assume that an artificial first parameter is
8848                      "this", but do not crash if it is not.  RealView
8849                      marks unnamed (and thus unused) parameters as
8850                      artificial; there is no way to differentiate
8851                      the two cases.  */
8852                   if (TYPE_NFIELDS (type) > 0
8853                       && TYPE_FIELD_ARTIFICIAL (type, 0)
8854                       && TYPE_CODE (TYPE_FIELD_TYPE (type, 0)) == TYPE_CODE_PTR
8855                       && TYPE_CONST (TYPE_TARGET_TYPE (TYPE_FIELD_TYPE (type,
8856                                                                         0))))
8857                     buf.puts (" const");
8858                 }
8859             }
8860
8861           const std::string &intermediate_name = buf.string ();
8862
8863           if (cu->language == language_cplus)
8864             canonical_name
8865               = dwarf2_canonicalize_name (intermediate_name.c_str (), cu,
8866                                           &objfile->per_bfd->storage_obstack);
8867
8868           /* If we only computed INTERMEDIATE_NAME, or if
8869              INTERMEDIATE_NAME is already canonical, then we need to
8870              copy it to the appropriate obstack.  */
8871           if (canonical_name == NULL || canonical_name == intermediate_name.c_str ())
8872             name = ((const char *)
8873                     obstack_copy0 (&objfile->per_bfd->storage_obstack,
8874                                    intermediate_name.c_str (),
8875                                    intermediate_name.length ()));
8876           else
8877             name = canonical_name;
8878         }
8879     }
8880
8881   return name;
8882 }
8883
8884 /* Return the fully qualified name of DIE, based on its DW_AT_name.
8885    If scope qualifiers are appropriate they will be added.  The result
8886    will be allocated on the storage_obstack, or NULL if the DIE does
8887    not have a name.  NAME may either be from a previous call to
8888    dwarf2_name or NULL.
8889
8890    The output string will be canonicalized (if C++).  */
8891
8892 static const char *
8893 dwarf2_full_name (const char *name, struct die_info *die, struct dwarf2_cu *cu)
8894 {
8895   return dwarf2_compute_name (name, die, cu, 0);
8896 }
8897
8898 /* Construct a physname for the given DIE in CU.  NAME may either be
8899    from a previous call to dwarf2_name or NULL.  The result will be
8900    allocated on the objfile_objstack or NULL if the DIE does not have a
8901    name.
8902
8903    The output string will be canonicalized (if C++).  */
8904
8905 static const char *
8906 dwarf2_physname (const char *name, struct die_info *die, struct dwarf2_cu *cu)
8907 {
8908   struct objfile *objfile = cu->objfile;
8909   const char *retval, *mangled = NULL, *canon = NULL;
8910   struct cleanup *back_to;
8911   int need_copy = 1;
8912
8913   /* In this case dwarf2_compute_name is just a shortcut not building anything
8914      on its own.  */
8915   if (!die_needs_namespace (die, cu))
8916     return dwarf2_compute_name (name, die, cu, 1);
8917
8918   back_to = make_cleanup (null_cleanup, NULL);
8919
8920   mangled = dwarf2_string_attr (die, DW_AT_linkage_name, cu);
8921   if (mangled == NULL)
8922     mangled = dwarf2_string_attr (die, DW_AT_MIPS_linkage_name, cu);
8923
8924   /* rustc emits invalid values for DW_AT_linkage_name.  Ignore these.
8925      See https://github.com/rust-lang/rust/issues/32925.  */
8926   if (cu->language == language_rust && mangled != NULL
8927       && strchr (mangled, '{') != NULL)
8928     mangled = NULL;
8929
8930   /* DW_AT_linkage_name is missing in some cases - depend on what GDB
8931      has computed.  */
8932   if (mangled != NULL)
8933     {
8934       char *demangled;
8935
8936       /* Use DMGL_RET_DROP for C++ template functions to suppress their return
8937          type.  It is easier for GDB users to search for such functions as
8938          `name(params)' than `long name(params)'.  In such case the minimal
8939          symbol names do not match the full symbol names but for template
8940          functions there is never a need to look up their definition from their
8941          declaration so the only disadvantage remains the minimal symbol
8942          variant `long name(params)' does not have the proper inferior type.
8943          */
8944
8945       if (cu->language == language_go)
8946         {
8947           /* This is a lie, but we already lie to the caller new_symbol_full.
8948              new_symbol_full assumes we return the mangled name.
8949              This just undoes that lie until things are cleaned up.  */
8950           demangled = NULL;
8951         }
8952       else
8953         {
8954           demangled = gdb_demangle (mangled,
8955                                     (DMGL_PARAMS | DMGL_ANSI | DMGL_RET_DROP));
8956         }
8957       if (demangled)
8958         {
8959           make_cleanup (xfree, demangled);
8960           canon = demangled;
8961         }
8962       else
8963         {
8964           canon = mangled;
8965           need_copy = 0;
8966         }
8967     }
8968
8969   if (canon == NULL || check_physname)
8970     {
8971       const char *physname = dwarf2_compute_name (name, die, cu, 1);
8972
8973       if (canon != NULL && strcmp (physname, canon) != 0)
8974         {
8975           /* It may not mean a bug in GDB.  The compiler could also
8976              compute DW_AT_linkage_name incorrectly.  But in such case
8977              GDB would need to be bug-to-bug compatible.  */
8978
8979           complaint (&symfile_complaints,
8980                      _("Computed physname <%s> does not match demangled <%s> "
8981                        "(from linkage <%s>) - DIE at 0x%x [in module %s]"),
8982                      physname, canon, mangled, to_underlying (die->sect_off),
8983                      objfile_name (objfile));
8984
8985           /* Prefer DW_AT_linkage_name (in the CANON form) - when it
8986              is available here - over computed PHYSNAME.  It is safer
8987              against both buggy GDB and buggy compilers.  */
8988
8989           retval = canon;
8990         }
8991       else
8992         {
8993           retval = physname;
8994           need_copy = 0;
8995         }
8996     }
8997   else
8998     retval = canon;
8999
9000   if (need_copy)
9001     retval = ((const char *)
9002               obstack_copy0 (&objfile->per_bfd->storage_obstack,
9003                              retval, strlen (retval)));
9004
9005   do_cleanups (back_to);
9006   return retval;
9007 }
9008
9009 /* Inspect DIE in CU for a namespace alias.  If one exists, record
9010    a new symbol for it.
9011
9012    Returns 1 if a namespace alias was recorded, 0 otherwise.  */
9013
9014 static int
9015 read_namespace_alias (struct die_info *die, struct dwarf2_cu *cu)
9016 {
9017   struct attribute *attr;
9018
9019   /* If the die does not have a name, this is not a namespace
9020      alias.  */
9021   attr = dwarf2_attr (die, DW_AT_name, cu);
9022   if (attr != NULL)
9023     {
9024       int num;
9025       struct die_info *d = die;
9026       struct dwarf2_cu *imported_cu = cu;
9027
9028       /* If the compiler has nested DW_AT_imported_declaration DIEs,
9029          keep inspecting DIEs until we hit the underlying import.  */
9030 #define MAX_NESTED_IMPORTED_DECLARATIONS 100
9031       for (num = 0; num  < MAX_NESTED_IMPORTED_DECLARATIONS; ++num)
9032         {
9033           attr = dwarf2_attr (d, DW_AT_import, cu);
9034           if (attr == NULL)
9035             break;
9036
9037           d = follow_die_ref (d, attr, &imported_cu);
9038           if (d->tag != DW_TAG_imported_declaration)
9039             break;
9040         }
9041
9042       if (num == MAX_NESTED_IMPORTED_DECLARATIONS)
9043         {
9044           complaint (&symfile_complaints,
9045                      _("DIE at 0x%x has too many recursively imported "
9046                        "declarations"), to_underlying (d->sect_off));
9047           return 0;
9048         }
9049
9050       if (attr != NULL)
9051         {
9052           struct type *type;
9053           sect_offset sect_off = dwarf2_get_ref_die_offset (attr);
9054
9055           type = get_die_type_at_offset (sect_off, cu->per_cu);
9056           if (type != NULL && TYPE_CODE (type) == TYPE_CODE_NAMESPACE)
9057             {
9058               /* This declaration is a global namespace alias.  Add
9059                  a symbol for it whose type is the aliased namespace.  */
9060               new_symbol (die, type, cu);
9061               return 1;
9062             }
9063         }
9064     }
9065
9066   return 0;
9067 }
9068
9069 /* Return the using directives repository (global or local?) to use in the
9070    current context for LANGUAGE.
9071
9072    For Ada, imported declarations can materialize renamings, which *may* be
9073    global.  However it is impossible (for now?) in DWARF to distinguish
9074    "external" imported declarations and "static" ones.  As all imported
9075    declarations seem to be static in all other languages, make them all CU-wide
9076    global only in Ada.  */
9077
9078 static struct using_direct **
9079 using_directives (enum language language)
9080 {
9081   if (language == language_ada && context_stack_depth == 0)
9082     return &global_using_directives;
9083   else
9084     return &local_using_directives;
9085 }
9086
9087 /* Read the import statement specified by the given die and record it.  */
9088
9089 static void
9090 read_import_statement (struct die_info *die, struct dwarf2_cu *cu)
9091 {
9092   struct objfile *objfile = cu->objfile;
9093   struct attribute *import_attr;
9094   struct die_info *imported_die, *child_die;
9095   struct dwarf2_cu *imported_cu;
9096   const char *imported_name;
9097   const char *imported_name_prefix;
9098   const char *canonical_name;
9099   const char *import_alias;
9100   const char *imported_declaration = NULL;
9101   const char *import_prefix;
9102   VEC (const_char_ptr) *excludes = NULL;
9103   struct cleanup *cleanups;
9104
9105   import_attr = dwarf2_attr (die, DW_AT_import, cu);
9106   if (import_attr == NULL)
9107     {
9108       complaint (&symfile_complaints, _("Tag '%s' has no DW_AT_import"),
9109                  dwarf_tag_name (die->tag));
9110       return;
9111     }
9112
9113   imported_cu = cu;
9114   imported_die = follow_die_ref_or_sig (die, import_attr, &imported_cu);
9115   imported_name = dwarf2_name (imported_die, imported_cu);
9116   if (imported_name == NULL)
9117     {
9118       /* GCC bug: https://bugzilla.redhat.com/show_bug.cgi?id=506524
9119
9120         The import in the following code:
9121         namespace A
9122           {
9123             typedef int B;
9124           }
9125
9126         int main ()
9127           {
9128             using A::B;
9129             B b;
9130             return b;
9131           }
9132
9133         ...
9134          <2><51>: Abbrev Number: 3 (DW_TAG_imported_declaration)
9135             <52>   DW_AT_decl_file   : 1
9136             <53>   DW_AT_decl_line   : 6
9137             <54>   DW_AT_import      : <0x75>
9138          <2><58>: Abbrev Number: 4 (DW_TAG_typedef)
9139             <59>   DW_AT_name        : B
9140             <5b>   DW_AT_decl_file   : 1
9141             <5c>   DW_AT_decl_line   : 2
9142             <5d>   DW_AT_type        : <0x6e>
9143         ...
9144          <1><75>: Abbrev Number: 7 (DW_TAG_base_type)
9145             <76>   DW_AT_byte_size   : 4
9146             <77>   DW_AT_encoding    : 5        (signed)
9147
9148         imports the wrong die ( 0x75 instead of 0x58 ).
9149         This case will be ignored until the gcc bug is fixed.  */
9150       return;
9151     }
9152
9153   /* Figure out the local name after import.  */
9154   import_alias = dwarf2_name (die, cu);
9155
9156   /* Figure out where the statement is being imported to.  */
9157   import_prefix = determine_prefix (die, cu);
9158
9159   /* Figure out what the scope of the imported die is and prepend it
9160      to the name of the imported die.  */
9161   imported_name_prefix = determine_prefix (imported_die, imported_cu);
9162
9163   if (imported_die->tag != DW_TAG_namespace
9164       && imported_die->tag != DW_TAG_module)
9165     {
9166       imported_declaration = imported_name;
9167       canonical_name = imported_name_prefix;
9168     }
9169   else if (strlen (imported_name_prefix) > 0)
9170     canonical_name = obconcat (&objfile->objfile_obstack,
9171                                imported_name_prefix,
9172                                (cu->language == language_d ? "." : "::"),
9173                                imported_name, (char *) NULL);
9174   else
9175     canonical_name = imported_name;
9176
9177   cleanups = make_cleanup (VEC_cleanup (const_char_ptr), &excludes);
9178
9179   if (die->tag == DW_TAG_imported_module && cu->language == language_fortran)
9180     for (child_die = die->child; child_die && child_die->tag;
9181          child_die = sibling_die (child_die))
9182       {
9183         /* DWARF-4: A Fortran use statement with a “rename list” may be
9184            represented by an imported module entry with an import attribute
9185            referring to the module and owned entries corresponding to those
9186            entities that are renamed as part of being imported.  */
9187
9188         if (child_die->tag != DW_TAG_imported_declaration)
9189           {
9190             complaint (&symfile_complaints,
9191                        _("child DW_TAG_imported_declaration expected "
9192                          "- DIE at 0x%x [in module %s]"),
9193                        to_underlying (child_die->sect_off), objfile_name (objfile));
9194             continue;
9195           }
9196
9197         import_attr = dwarf2_attr (child_die, DW_AT_import, cu);
9198         if (import_attr == NULL)
9199           {
9200             complaint (&symfile_complaints, _("Tag '%s' has no DW_AT_import"),
9201                        dwarf_tag_name (child_die->tag));
9202             continue;
9203           }
9204
9205         imported_cu = cu;
9206         imported_die = follow_die_ref_or_sig (child_die, import_attr,
9207                                               &imported_cu);
9208         imported_name = dwarf2_name (imported_die, imported_cu);
9209         if (imported_name == NULL)
9210           {
9211             complaint (&symfile_complaints,
9212                        _("child DW_TAG_imported_declaration has unknown "
9213                          "imported name - DIE at 0x%x [in module %s]"),
9214                        to_underlying (child_die->sect_off), objfile_name (objfile));
9215             continue;
9216           }
9217
9218         VEC_safe_push (const_char_ptr, excludes, imported_name);
9219
9220         process_die (child_die, cu);
9221       }
9222
9223   add_using_directive (using_directives (cu->language),
9224                        import_prefix,
9225                        canonical_name,
9226                        import_alias,
9227                        imported_declaration,
9228                        excludes,
9229                        0,
9230                        &objfile->objfile_obstack);
9231
9232   do_cleanups (cleanups);
9233 }
9234
9235 /* Check for possibly missing DW_AT_comp_dir with relative .debug_line
9236    directory paths.  GCC SVN r127613 (new option -fdebug-prefix-map) fixed
9237    this, it was first present in GCC release 4.3.0.  */
9238
9239 static int
9240 producer_is_gcc_lt_4_3 (struct dwarf2_cu *cu)
9241 {
9242   if (!cu->checked_producer)
9243     check_producer (cu);
9244
9245   return cu->producer_is_gcc_lt_4_3;
9246 }
9247
9248 static file_and_directory
9249 find_file_and_directory (struct die_info *die, struct dwarf2_cu *cu)
9250 {
9251   file_and_directory res;
9252
9253   /* Find the filename.  Do not use dwarf2_name here, since the filename
9254      is not a source language identifier.  */
9255   res.name = dwarf2_string_attr (die, DW_AT_name, cu);
9256   res.comp_dir = dwarf2_string_attr (die, DW_AT_comp_dir, cu);
9257
9258   if (res.comp_dir == NULL
9259       && producer_is_gcc_lt_4_3 (cu) && res.name != NULL
9260       && IS_ABSOLUTE_PATH (res.name))
9261     {
9262       res.comp_dir_storage = ldirname (res.name);
9263       if (!res.comp_dir_storage.empty ())
9264         res.comp_dir = res.comp_dir_storage.c_str ();
9265     }
9266   if (res.comp_dir != NULL)
9267     {
9268       /* Irix 6.2 native cc prepends <machine>.: to the compilation
9269          directory, get rid of it.  */
9270       const char *cp = strchr (res.comp_dir, ':');
9271
9272       if (cp && cp != res.comp_dir && cp[-1] == '.' && cp[1] == '/')
9273         res.comp_dir = cp + 1;
9274     }
9275
9276   if (res.name == NULL)
9277     res.name = "<unknown>";
9278
9279   return res;
9280 }
9281
9282 /* Handle DW_AT_stmt_list for a compilation unit.
9283    DIE is the DW_TAG_compile_unit die for CU.
9284    COMP_DIR is the compilation directory.  LOWPC is passed to
9285    dwarf_decode_lines.  See dwarf_decode_lines comments about it.  */
9286
9287 static void
9288 handle_DW_AT_stmt_list (struct die_info *die, struct dwarf2_cu *cu,
9289                         const char *comp_dir, CORE_ADDR lowpc) /* ARI: editCase function */
9290 {
9291   struct objfile *objfile = dwarf2_per_objfile->objfile;
9292   struct attribute *attr;
9293   struct line_header line_header_local;
9294   hashval_t line_header_local_hash;
9295   unsigned u;
9296   void **slot;
9297   int decode_mapping;
9298
9299   gdb_assert (! cu->per_cu->is_debug_types);
9300
9301   attr = dwarf2_attr (die, DW_AT_stmt_list, cu);
9302   if (attr == NULL)
9303     return;
9304
9305   sect_offset line_offset = (sect_offset) DW_UNSND (attr);
9306
9307   /* The line header hash table is only created if needed (it exists to
9308      prevent redundant reading of the line table for partial_units).
9309      If we're given a partial_unit, we'll need it.  If we're given a
9310      compile_unit, then use the line header hash table if it's already
9311      created, but don't create one just yet.  */
9312
9313   if (dwarf2_per_objfile->line_header_hash == NULL
9314       && die->tag == DW_TAG_partial_unit)
9315     {
9316       dwarf2_per_objfile->line_header_hash
9317         = htab_create_alloc_ex (127, line_header_hash_voidp,
9318                                 line_header_eq_voidp,
9319                                 free_line_header_voidp,
9320                                 &objfile->objfile_obstack,
9321                                 hashtab_obstack_allocate,
9322                                 dummy_obstack_deallocate);
9323     }
9324
9325   line_header_local.sect_off = line_offset;
9326   line_header_local.offset_in_dwz = cu->per_cu->is_dwz;
9327   line_header_local_hash = line_header_hash (&line_header_local);
9328   if (dwarf2_per_objfile->line_header_hash != NULL)
9329     {
9330       slot = htab_find_slot_with_hash (dwarf2_per_objfile->line_header_hash,
9331                                        &line_header_local,
9332                                        line_header_local_hash, NO_INSERT);
9333
9334       /* For DW_TAG_compile_unit we need info like symtab::linetable which
9335          is not present in *SLOT (since if there is something in *SLOT then
9336          it will be for a partial_unit).  */
9337       if (die->tag == DW_TAG_partial_unit && slot != NULL)
9338         {
9339           gdb_assert (*slot != NULL);
9340           cu->line_header = (struct line_header *) *slot;
9341           return;
9342         }
9343     }
9344
9345   /* dwarf_decode_line_header does not yet provide sufficient information.
9346      We always have to call also dwarf_decode_lines for it.  */
9347   line_header_up lh = dwarf_decode_line_header (line_offset, cu);
9348   if (lh == NULL)
9349     return;
9350   cu->line_header = lh.get ();
9351
9352   if (dwarf2_per_objfile->line_header_hash == NULL)
9353     slot = NULL;
9354   else
9355     {
9356       slot = htab_find_slot_with_hash (dwarf2_per_objfile->line_header_hash,
9357                                        &line_header_local,
9358                                        line_header_local_hash, INSERT);
9359       gdb_assert (slot != NULL);
9360     }
9361   if (slot != NULL && *slot == NULL)
9362     {
9363       /* This newly decoded line number information unit will be owned
9364          by line_header_hash hash table.  */
9365       *slot = cu->line_header;
9366     }
9367   else
9368     {
9369       /* We cannot free any current entry in (*slot) as that struct line_header
9370          may be already used by multiple CUs.  Create only temporary decoded
9371          line_header for this CU - it may happen at most once for each line
9372          number information unit.  And if we're not using line_header_hash
9373          then this is what we want as well.  */
9374       gdb_assert (die->tag != DW_TAG_partial_unit);
9375     }
9376   decode_mapping = (die->tag != DW_TAG_partial_unit);
9377   dwarf_decode_lines (cu->line_header, comp_dir, cu, NULL, lowpc,
9378                       decode_mapping);
9379
9380   lh.release ();
9381 }
9382
9383 /* Process DW_TAG_compile_unit or DW_TAG_partial_unit.  */
9384
9385 static void
9386 read_file_scope (struct die_info *die, struct dwarf2_cu *cu)
9387 {
9388   struct objfile *objfile = dwarf2_per_objfile->objfile;
9389   struct gdbarch *gdbarch = get_objfile_arch (objfile);
9390   CORE_ADDR lowpc = ((CORE_ADDR) -1);
9391   CORE_ADDR highpc = ((CORE_ADDR) 0);
9392   struct attribute *attr;
9393   struct die_info *child_die;
9394   CORE_ADDR baseaddr;
9395
9396   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
9397
9398   get_scope_pc_bounds (die, &lowpc, &highpc, cu);
9399
9400   /* If we didn't find a lowpc, set it to highpc to avoid complaints
9401      from finish_block.  */
9402   if (lowpc == ((CORE_ADDR) -1))
9403     lowpc = highpc;
9404   lowpc = gdbarch_adjust_dwarf2_addr (gdbarch, lowpc + baseaddr);
9405
9406   file_and_directory fnd = find_file_and_directory (die, cu);
9407
9408   prepare_one_comp_unit (cu, die, cu->language);
9409
9410   /* The XLCL doesn't generate DW_LANG_OpenCL because this attribute is not
9411      standardised yet.  As a workaround for the language detection we fall
9412      back to the DW_AT_producer string.  */
9413   if (cu->producer && strstr (cu->producer, "IBM XL C for OpenCL") != NULL)
9414     cu->language = language_opencl;
9415
9416   /* Similar hack for Go.  */
9417   if (cu->producer && strstr (cu->producer, "GNU Go ") != NULL)
9418     set_cu_language (DW_LANG_Go, cu);
9419
9420   dwarf2_start_symtab (cu, fnd.name, fnd.comp_dir, lowpc);
9421
9422   /* Decode line number information if present.  We do this before
9423      processing child DIEs, so that the line header table is available
9424      for DW_AT_decl_file.  */
9425   handle_DW_AT_stmt_list (die, cu, fnd.comp_dir, lowpc);
9426
9427   /* Process all dies in compilation unit.  */
9428   if (die->child != NULL)
9429     {
9430       child_die = die->child;
9431       while (child_die && child_die->tag)
9432         {
9433           process_die (child_die, cu);
9434           child_die = sibling_die (child_die);
9435         }
9436     }
9437
9438   /* Decode macro information, if present.  Dwarf 2 macro information
9439      refers to information in the line number info statement program
9440      header, so we can only read it if we've read the header
9441      successfully.  */
9442   attr = dwarf2_attr (die, DW_AT_macros, cu);
9443   if (attr == NULL)
9444     attr = dwarf2_attr (die, DW_AT_GNU_macros, cu);
9445   if (attr && cu->line_header)
9446     {
9447       if (dwarf2_attr (die, DW_AT_macro_info, cu))
9448         complaint (&symfile_complaints,
9449                    _("CU refers to both DW_AT_macros and DW_AT_macro_info"));
9450
9451       dwarf_decode_macros (cu, DW_UNSND (attr), 1);
9452     }
9453   else
9454     {
9455       attr = dwarf2_attr (die, DW_AT_macro_info, cu);
9456       if (attr && cu->line_header)
9457         {
9458           unsigned int macro_offset = DW_UNSND (attr);
9459
9460           dwarf_decode_macros (cu, macro_offset, 0);
9461         }
9462     }
9463 }
9464
9465 /* TU version of handle_DW_AT_stmt_list for read_type_unit_scope.
9466    Create the set of symtabs used by this TU, or if this TU is sharing
9467    symtabs with another TU and the symtabs have already been created
9468    then restore those symtabs in the line header.
9469    We don't need the pc/line-number mapping for type units.  */
9470
9471 static void
9472 setup_type_unit_groups (struct die_info *die, struct dwarf2_cu *cu)
9473 {
9474   struct dwarf2_per_cu_data *per_cu = cu->per_cu;
9475   struct type_unit_group *tu_group;
9476   int first_time;
9477   struct attribute *attr;
9478   unsigned int i;
9479   struct signatured_type *sig_type;
9480
9481   gdb_assert (per_cu->is_debug_types);
9482   sig_type = (struct signatured_type *) per_cu;
9483
9484   attr = dwarf2_attr (die, DW_AT_stmt_list, cu);
9485
9486   /* If we're using .gdb_index (includes -readnow) then
9487      per_cu->type_unit_group may not have been set up yet.  */
9488   if (sig_type->type_unit_group == NULL)
9489     sig_type->type_unit_group = get_type_unit_group (cu, attr);
9490   tu_group = sig_type->type_unit_group;
9491
9492   /* If we've already processed this stmt_list there's no real need to
9493      do it again, we could fake it and just recreate the part we need
9494      (file name,index -> symtab mapping).  If data shows this optimization
9495      is useful we can do it then.  */
9496   first_time = tu_group->compunit_symtab == NULL;
9497
9498   /* We have to handle the case of both a missing DW_AT_stmt_list or bad
9499      debug info.  */
9500   line_header_up lh;
9501   if (attr != NULL)
9502     {
9503       sect_offset line_offset = (sect_offset) DW_UNSND (attr);
9504       lh = dwarf_decode_line_header (line_offset, cu);
9505     }
9506   if (lh == NULL)
9507     {
9508       if (first_time)
9509         dwarf2_start_symtab (cu, "", NULL, 0);
9510       else
9511         {
9512           gdb_assert (tu_group->symtabs == NULL);
9513           restart_symtab (tu_group->compunit_symtab, "", 0);
9514         }
9515       return;
9516     }
9517
9518   cu->line_header = lh.get ();
9519
9520   if (first_time)
9521     {
9522       struct compunit_symtab *cust = dwarf2_start_symtab (cu, "", NULL, 0);
9523
9524       /* Note: We don't assign tu_group->compunit_symtab yet because we're
9525          still initializing it, and our caller (a few levels up)
9526          process_full_type_unit still needs to know if this is the first
9527          time.  */
9528
9529       tu_group->num_symtabs = lh->file_names.size ();
9530       tu_group->symtabs = XNEWVEC (struct symtab *, lh->file_names.size ());
9531
9532       for (i = 0; i < lh->file_names.size (); ++i)
9533         {
9534           file_entry &fe = lh->file_names[i];
9535
9536           dwarf2_start_subfile (fe.name, fe.include_dir (lh.get ()));
9537
9538           if (current_subfile->symtab == NULL)
9539             {
9540               /* NOTE: start_subfile will recognize when it's been passed
9541                  a file it has already seen.  So we can't assume there's a
9542                  simple mapping from lh->file_names to subfiles, plus
9543                  lh->file_names may contain dups.  */
9544               current_subfile->symtab
9545                 = allocate_symtab (cust, current_subfile->name);
9546             }
9547
9548           fe.symtab = current_subfile->symtab;
9549           tu_group->symtabs[i] = fe.symtab;
9550         }
9551     }
9552   else
9553     {
9554       restart_symtab (tu_group->compunit_symtab, "", 0);
9555
9556       for (i = 0; i < lh->file_names.size (); ++i)
9557         {
9558           struct file_entry *fe = &lh->file_names[i];
9559
9560           fe->symtab = tu_group->symtabs[i];
9561         }
9562     }
9563
9564   lh.release ();
9565
9566   /* The main symtab is allocated last.  Type units don't have DW_AT_name
9567      so they don't have a "real" (so to speak) symtab anyway.
9568      There is later code that will assign the main symtab to all symbols
9569      that don't have one.  We need to handle the case of a symbol with a
9570      missing symtab (DW_AT_decl_file) anyway.  */
9571 }
9572
9573 /* Process DW_TAG_type_unit.
9574    For TUs we want to skip the first top level sibling if it's not the
9575    actual type being defined by this TU.  In this case the first top
9576    level sibling is there to provide context only.  */
9577
9578 static void
9579 read_type_unit_scope (struct die_info *die, struct dwarf2_cu *cu)
9580 {
9581   struct die_info *child_die;
9582
9583   prepare_one_comp_unit (cu, die, language_minimal);
9584
9585   /* Initialize (or reinitialize) the machinery for building symtabs.
9586      We do this before processing child DIEs, so that the line header table
9587      is available for DW_AT_decl_file.  */
9588   setup_type_unit_groups (die, cu);
9589
9590   if (die->child != NULL)
9591     {
9592       child_die = die->child;
9593       while (child_die && child_die->tag)
9594         {
9595           process_die (child_die, cu);
9596           child_die = sibling_die (child_die);
9597         }
9598     }
9599 }
9600 \f
9601 /* DWO/DWP files.
9602
9603    http://gcc.gnu.org/wiki/DebugFission
9604    http://gcc.gnu.org/wiki/DebugFissionDWP
9605
9606    To simplify handling of both DWO files ("object" files with the DWARF info)
9607    and DWP files (a file with the DWOs packaged up into one file), we treat
9608    DWP files as having a collection of virtual DWO files.  */
9609
9610 static hashval_t
9611 hash_dwo_file (const void *item)
9612 {
9613   const struct dwo_file *dwo_file = (const struct dwo_file *) item;
9614   hashval_t hash;
9615
9616   hash = htab_hash_string (dwo_file->dwo_name);
9617   if (dwo_file->comp_dir != NULL)
9618     hash += htab_hash_string (dwo_file->comp_dir);
9619   return hash;
9620 }
9621
9622 static int
9623 eq_dwo_file (const void *item_lhs, const void *item_rhs)
9624 {
9625   const struct dwo_file *lhs = (const struct dwo_file *) item_lhs;
9626   const struct dwo_file *rhs = (const struct dwo_file *) item_rhs;
9627
9628   if (strcmp (lhs->dwo_name, rhs->dwo_name) != 0)
9629     return 0;
9630   if (lhs->comp_dir == NULL || rhs->comp_dir == NULL)
9631     return lhs->comp_dir == rhs->comp_dir;
9632   return strcmp (lhs->comp_dir, rhs->comp_dir) == 0;
9633 }
9634
9635 /* Allocate a hash table for DWO files.  */
9636
9637 static htab_t
9638 allocate_dwo_file_hash_table (void)
9639 {
9640   struct objfile *objfile = dwarf2_per_objfile->objfile;
9641
9642   return htab_create_alloc_ex (41,
9643                                hash_dwo_file,
9644                                eq_dwo_file,
9645                                NULL,
9646                                &objfile->objfile_obstack,
9647                                hashtab_obstack_allocate,
9648                                dummy_obstack_deallocate);
9649 }
9650
9651 /* Lookup DWO file DWO_NAME.  */
9652
9653 static void **
9654 lookup_dwo_file_slot (const char *dwo_name, const char *comp_dir)
9655 {
9656   struct dwo_file find_entry;
9657   void **slot;
9658
9659   if (dwarf2_per_objfile->dwo_files == NULL)
9660     dwarf2_per_objfile->dwo_files = allocate_dwo_file_hash_table ();
9661
9662   memset (&find_entry, 0, sizeof (find_entry));
9663   find_entry.dwo_name = dwo_name;
9664   find_entry.comp_dir = comp_dir;
9665   slot = htab_find_slot (dwarf2_per_objfile->dwo_files, &find_entry, INSERT);
9666
9667   return slot;
9668 }
9669
9670 static hashval_t
9671 hash_dwo_unit (const void *item)
9672 {
9673   const struct dwo_unit *dwo_unit = (const struct dwo_unit *) item;
9674
9675   /* This drops the top 32 bits of the id, but is ok for a hash.  */
9676   return dwo_unit->signature;
9677 }
9678
9679 static int
9680 eq_dwo_unit (const void *item_lhs, const void *item_rhs)
9681 {
9682   const struct dwo_unit *lhs = (const struct dwo_unit *) item_lhs;
9683   const struct dwo_unit *rhs = (const struct dwo_unit *) item_rhs;
9684
9685   /* The signature is assumed to be unique within the DWO file.
9686      So while object file CU dwo_id's always have the value zero,
9687      that's OK, assuming each object file DWO file has only one CU,
9688      and that's the rule for now.  */
9689   return lhs->signature == rhs->signature;
9690 }
9691
9692 /* Allocate a hash table for DWO CUs,TUs.
9693    There is one of these tables for each of CUs,TUs for each DWO file.  */
9694
9695 static htab_t
9696 allocate_dwo_unit_table (struct objfile *objfile)
9697 {
9698   /* Start out with a pretty small number.
9699      Generally DWO files contain only one CU and maybe some TUs.  */
9700   return htab_create_alloc_ex (3,
9701                                hash_dwo_unit,
9702                                eq_dwo_unit,
9703                                NULL,
9704                                &objfile->objfile_obstack,
9705                                hashtab_obstack_allocate,
9706                                dummy_obstack_deallocate);
9707 }
9708
9709 /* Structure used to pass data to create_dwo_debug_info_hash_table_reader.  */
9710
9711 struct create_dwo_cu_data
9712 {
9713   struct dwo_file *dwo_file;
9714   struct dwo_unit dwo_unit;
9715 };
9716
9717 /* die_reader_func for create_dwo_cu.  */
9718
9719 static void
9720 create_dwo_cu_reader (const struct die_reader_specs *reader,
9721                       const gdb_byte *info_ptr,
9722                       struct die_info *comp_unit_die,
9723                       int has_children,
9724                       void *datap)
9725 {
9726   struct dwarf2_cu *cu = reader->cu;
9727   sect_offset sect_off = cu->per_cu->sect_off;
9728   struct dwarf2_section_info *section = cu->per_cu->section;
9729   struct create_dwo_cu_data *data = (struct create_dwo_cu_data *) datap;
9730   struct dwo_file *dwo_file = data->dwo_file;
9731   struct dwo_unit *dwo_unit = &data->dwo_unit;
9732   struct attribute *attr;
9733
9734   attr = dwarf2_attr (comp_unit_die, DW_AT_GNU_dwo_id, cu);
9735   if (attr == NULL)
9736     {
9737       complaint (&symfile_complaints,
9738                  _("Dwarf Error: debug entry at offset 0x%x is missing"
9739                    " its dwo_id [in module %s]"),
9740                  to_underlying (sect_off), dwo_file->dwo_name);
9741       return;
9742     }
9743
9744   dwo_unit->dwo_file = dwo_file;
9745   dwo_unit->signature = DW_UNSND (attr);
9746   dwo_unit->section = section;
9747   dwo_unit->sect_off = sect_off;
9748   dwo_unit->length = cu->per_cu->length;
9749
9750   if (dwarf_read_debug)
9751     fprintf_unfiltered (gdb_stdlog, "  offset 0x%x, dwo_id %s\n",
9752                         to_underlying (sect_off),
9753                         hex_string (dwo_unit->signature));
9754 }
9755
9756 /* Create the dwo_units for the CUs in a DWO_FILE.
9757    Note: This function processes DWO files only, not DWP files.  */
9758
9759 static void
9760 create_cus_hash_table (struct dwo_file &dwo_file, dwarf2_section_info &section,
9761                        htab_t &cus_htab)
9762 {
9763   struct objfile *objfile = dwarf2_per_objfile->objfile;
9764   const struct dwarf2_section_info *abbrev_section = &dwo_file.sections.abbrev;
9765   const gdb_byte *info_ptr, *end_ptr;
9766
9767   dwarf2_read_section (objfile, &section);
9768   info_ptr = section.buffer;
9769
9770   if (info_ptr == NULL)
9771     return;
9772
9773   if (dwarf_read_debug)
9774     {
9775       fprintf_unfiltered (gdb_stdlog, "Reading %s for %s:\n",
9776                           get_section_name (&section),
9777                           get_section_file_name (&section));
9778     }
9779
9780   end_ptr = info_ptr + section.size;
9781   while (info_ptr < end_ptr)
9782     {
9783       struct dwarf2_per_cu_data per_cu;
9784       struct create_dwo_cu_data create_dwo_cu_data;
9785       struct dwo_unit *dwo_unit;
9786       void **slot;
9787       sect_offset sect_off = (sect_offset) (info_ptr - section.buffer);
9788
9789       memset (&create_dwo_cu_data.dwo_unit, 0,
9790               sizeof (create_dwo_cu_data.dwo_unit));
9791       memset (&per_cu, 0, sizeof (per_cu));
9792       per_cu.objfile = objfile;
9793       per_cu.is_debug_types = 0;
9794       per_cu.sect_off = sect_offset (info_ptr - section.buffer);
9795       per_cu.section = &section;
9796
9797       init_cutu_and_read_dies_no_follow (
9798           &per_cu, &dwo_file, create_dwo_cu_reader, &create_dwo_cu_data);
9799       info_ptr += per_cu.length;
9800
9801       // If the unit could not be parsed, skip it.
9802       if (create_dwo_cu_data.dwo_unit.dwo_file == NULL)
9803         continue;
9804
9805       if (cus_htab == NULL)
9806         cus_htab = allocate_dwo_unit_table (objfile);
9807
9808       dwo_unit = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_unit);
9809       *dwo_unit = create_dwo_cu_data.dwo_unit;
9810       slot = htab_find_slot (cus_htab, dwo_unit, INSERT);
9811       gdb_assert (slot != NULL);
9812       if (*slot != NULL)
9813         {
9814           const struct dwo_unit *dup_cu = (const struct dwo_unit *)*slot;
9815           sect_offset dup_sect_off = dup_cu->sect_off;
9816
9817           complaint (&symfile_complaints,
9818                      _("debug cu entry at offset 0x%x is duplicate to"
9819                        " the entry at offset 0x%x, signature %s"),
9820                      to_underlying (sect_off), to_underlying (dup_sect_off),
9821                      hex_string (dwo_unit->signature));
9822         }
9823       *slot = (void *)dwo_unit;
9824     }
9825 }
9826
9827 /* DWP file .debug_{cu,tu}_index section format:
9828    [ref: http://gcc.gnu.org/wiki/DebugFissionDWP]
9829
9830    DWP Version 1:
9831
9832    Both index sections have the same format, and serve to map a 64-bit
9833    signature to a set of section numbers.  Each section begins with a header,
9834    followed by a hash table of 64-bit signatures, a parallel table of 32-bit
9835    indexes, and a pool of 32-bit section numbers.  The index sections will be
9836    aligned at 8-byte boundaries in the file.
9837
9838    The index section header consists of:
9839
9840     V, 32 bit version number
9841     -, 32 bits unused
9842     N, 32 bit number of compilation units or type units in the index
9843     M, 32 bit number of slots in the hash table
9844
9845    Numbers are recorded using the byte order of the application binary.
9846
9847    The hash table begins at offset 16 in the section, and consists of an array
9848    of M 64-bit slots.  Each slot contains a 64-bit signature (using the byte
9849    order of the application binary).  Unused slots in the hash table are 0.
9850    (We rely on the extreme unlikeliness of a signature being exactly 0.)
9851
9852    The parallel table begins immediately after the hash table
9853    (at offset 16 + 8 * M from the beginning of the section), and consists of an
9854    array of 32-bit indexes (using the byte order of the application binary),
9855    corresponding 1-1 with slots in the hash table.  Each entry in the parallel
9856    table contains a 32-bit index into the pool of section numbers.  For unused
9857    hash table slots, the corresponding entry in the parallel table will be 0.
9858
9859    The pool of section numbers begins immediately following the hash table
9860    (at offset 16 + 12 * M from the beginning of the section).  The pool of
9861    section numbers consists of an array of 32-bit words (using the byte order
9862    of the application binary).  Each item in the array is indexed starting
9863    from 0.  The hash table entry provides the index of the first section
9864    number in the set.  Additional section numbers in the set follow, and the
9865    set is terminated by a 0 entry (section number 0 is not used in ELF).
9866
9867    In each set of section numbers, the .debug_info.dwo or .debug_types.dwo
9868    section must be the first entry in the set, and the .debug_abbrev.dwo must
9869    be the second entry. Other members of the set may follow in any order.
9870
9871    ---
9872
9873    DWP Version 2:
9874
9875    DWP Version 2 combines all the .debug_info, etc. sections into one,
9876    and the entries in the index tables are now offsets into these sections.
9877    CU offsets begin at 0.  TU offsets begin at the size of the .debug_info
9878    section.
9879
9880    Index Section Contents:
9881     Header
9882     Hash Table of Signatures   dwp_hash_table.hash_table
9883     Parallel Table of Indices  dwp_hash_table.unit_table
9884     Table of Section Offsets   dwp_hash_table.v2.{section_ids,offsets}
9885     Table of Section Sizes     dwp_hash_table.v2.sizes
9886
9887    The index section header consists of:
9888
9889     V, 32 bit version number
9890     L, 32 bit number of columns in the table of section offsets
9891     N, 32 bit number of compilation units or type units in the index
9892     M, 32 bit number of slots in the hash table
9893
9894    Numbers are recorded using the byte order of the application binary.
9895
9896    The hash table has the same format as version 1.
9897    The parallel table of indices has the same format as version 1,
9898    except that the entries are origin-1 indices into the table of sections
9899    offsets and the table of section sizes.
9900
9901    The table of offsets begins immediately following the parallel table
9902    (at offset 16 + 12 * M from the beginning of the section).  The table is
9903    a two-dimensional array of 32-bit words (using the byte order of the
9904    application binary), with L columns and N+1 rows, in row-major order.
9905    Each row in the array is indexed starting from 0.  The first row provides
9906    a key to the remaining rows: each column in this row provides an identifier
9907    for a debug section, and the offsets in the same column of subsequent rows
9908    refer to that section.  The section identifiers are:
9909
9910     DW_SECT_INFO         1  .debug_info.dwo
9911     DW_SECT_TYPES        2  .debug_types.dwo
9912     DW_SECT_ABBREV       3  .debug_abbrev.dwo
9913     DW_SECT_LINE         4  .debug_line.dwo
9914     DW_SECT_LOC          5  .debug_loc.dwo
9915     DW_SECT_STR_OFFSETS  6  .debug_str_offsets.dwo
9916     DW_SECT_MACINFO      7  .debug_macinfo.dwo
9917     DW_SECT_MACRO        8  .debug_macro.dwo
9918
9919    The offsets provided by the CU and TU index sections are the base offsets
9920    for the contributions made by each CU or TU to the corresponding section
9921    in the package file.  Each CU and TU header contains an abbrev_offset
9922    field, used to find the abbreviations table for that CU or TU within the
9923    contribution to the .debug_abbrev.dwo section for that CU or TU, and should
9924    be interpreted as relative to the base offset given in the index section.
9925    Likewise, offsets into .debug_line.dwo from DW_AT_stmt_list attributes
9926    should be interpreted as relative to the base offset for .debug_line.dwo,
9927    and offsets into other debug sections obtained from DWARF attributes should
9928    also be interpreted as relative to the corresponding base offset.
9929
9930    The table of sizes begins immediately following the table of offsets.
9931    Like the table of offsets, it is a two-dimensional array of 32-bit words,
9932    with L columns and N rows, in row-major order.  Each row in the array is
9933    indexed starting from 1 (row 0 is shared by the two tables).
9934
9935    ---
9936
9937    Hash table lookup is handled the same in version 1 and 2:
9938
9939    We assume that N and M will not exceed 2^32 - 1.
9940    The size of the hash table, M, must be 2^k such that 2^k > 3*N/2.
9941
9942    Given a 64-bit compilation unit signature or a type signature S, an entry
9943    in the hash table is located as follows:
9944
9945    1) Calculate a primary hash H = S & MASK(k), where MASK(k) is a mask with
9946       the low-order k bits all set to 1.
9947
9948    2) Calculate a secondary hash H' = (((S >> 32) & MASK(k)) | 1).
9949
9950    3) If the hash table entry at index H matches the signature, use that
9951       entry.  If the hash table entry at index H is unused (all zeroes),
9952       terminate the search: the signature is not present in the table.
9953
9954    4) Let H = (H + H') modulo M. Repeat at Step 3.
9955
9956    Because M > N and H' and M are relatively prime, the search is guaranteed
9957    to stop at an unused slot or find the match.  */
9958
9959 /* Create a hash table to map DWO IDs to their CU/TU entry in
9960    .debug_{info,types}.dwo in DWP_FILE.
9961    Returns NULL if there isn't one.
9962    Note: This function processes DWP files only, not DWO files.  */
9963
9964 static struct dwp_hash_table *
9965 create_dwp_hash_table (struct dwp_file *dwp_file, int is_debug_types)
9966 {
9967   struct objfile *objfile = dwarf2_per_objfile->objfile;
9968   bfd *dbfd = dwp_file->dbfd;
9969   const gdb_byte *index_ptr, *index_end;
9970   struct dwarf2_section_info *index;
9971   uint32_t version, nr_columns, nr_units, nr_slots;
9972   struct dwp_hash_table *htab;
9973
9974   if (is_debug_types)
9975     index = &dwp_file->sections.tu_index;
9976   else
9977     index = &dwp_file->sections.cu_index;
9978
9979   if (dwarf2_section_empty_p (index))
9980     return NULL;
9981   dwarf2_read_section (objfile, index);
9982
9983   index_ptr = index->buffer;
9984   index_end = index_ptr + index->size;
9985
9986   version = read_4_bytes (dbfd, index_ptr);
9987   index_ptr += 4;
9988   if (version == 2)
9989     nr_columns = read_4_bytes (dbfd, index_ptr);
9990   else
9991     nr_columns = 0;
9992   index_ptr += 4;
9993   nr_units = read_4_bytes (dbfd, index_ptr);
9994   index_ptr += 4;
9995   nr_slots = read_4_bytes (dbfd, index_ptr);
9996   index_ptr += 4;
9997
9998   if (version != 1 && version != 2)
9999     {
10000       error (_("Dwarf Error: unsupported DWP file version (%s)"
10001                " [in module %s]"),
10002              pulongest (version), dwp_file->name);
10003     }
10004   if (nr_slots != (nr_slots & -nr_slots))
10005     {
10006       error (_("Dwarf Error: number of slots in DWP hash table (%s)"
10007                " is not power of 2 [in module %s]"),
10008              pulongest (nr_slots), dwp_file->name);
10009     }
10010
10011   htab = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwp_hash_table);
10012   htab->version = version;
10013   htab->nr_columns = nr_columns;
10014   htab->nr_units = nr_units;
10015   htab->nr_slots = nr_slots;
10016   htab->hash_table = index_ptr;
10017   htab->unit_table = htab->hash_table + sizeof (uint64_t) * nr_slots;
10018
10019   /* Exit early if the table is empty.  */
10020   if (nr_slots == 0 || nr_units == 0
10021       || (version == 2 && nr_columns == 0))
10022     {
10023       /* All must be zero.  */
10024       if (nr_slots != 0 || nr_units != 0
10025           || (version == 2 && nr_columns != 0))
10026         {
10027           complaint (&symfile_complaints,
10028                      _("Empty DWP but nr_slots,nr_units,nr_columns not"
10029                        " all zero [in modules %s]"),
10030                      dwp_file->name);
10031         }
10032       return htab;
10033     }
10034
10035   if (version == 1)
10036     {
10037       htab->section_pool.v1.indices =
10038         htab->unit_table + sizeof (uint32_t) * nr_slots;
10039       /* It's harder to decide whether the section is too small in v1.
10040          V1 is deprecated anyway so we punt.  */
10041     }
10042   else
10043     {
10044       const gdb_byte *ids_ptr = htab->unit_table + sizeof (uint32_t) * nr_slots;
10045       int *ids = htab->section_pool.v2.section_ids;
10046       /* Reverse map for error checking.  */
10047       int ids_seen[DW_SECT_MAX + 1];
10048       int i;
10049
10050       if (nr_columns < 2)
10051         {
10052           error (_("Dwarf Error: bad DWP hash table, too few columns"
10053                    " in section table [in module %s]"),
10054                  dwp_file->name);
10055         }
10056       if (nr_columns > MAX_NR_V2_DWO_SECTIONS)
10057         {
10058           error (_("Dwarf Error: bad DWP hash table, too many columns"
10059                    " in section table [in module %s]"),
10060                  dwp_file->name);
10061         }
10062       memset (ids, 255, (DW_SECT_MAX + 1) * sizeof (int32_t));
10063       memset (ids_seen, 255, (DW_SECT_MAX + 1) * sizeof (int32_t));
10064       for (i = 0; i < nr_columns; ++i)
10065         {
10066           int id = read_4_bytes (dbfd, ids_ptr + i * sizeof (uint32_t));
10067
10068           if (id < DW_SECT_MIN || id > DW_SECT_MAX)
10069             {
10070               error (_("Dwarf Error: bad DWP hash table, bad section id %d"
10071                        " in section table [in module %s]"),
10072                      id, dwp_file->name);
10073             }
10074           if (ids_seen[id] != -1)
10075             {
10076               error (_("Dwarf Error: bad DWP hash table, duplicate section"
10077                        " id %d in section table [in module %s]"),
10078                      id, dwp_file->name);
10079             }
10080           ids_seen[id] = i;
10081           ids[i] = id;
10082         }
10083       /* Must have exactly one info or types section.  */
10084       if (((ids_seen[DW_SECT_INFO] != -1)
10085            + (ids_seen[DW_SECT_TYPES] != -1))
10086           != 1)
10087         {
10088           error (_("Dwarf Error: bad DWP hash table, missing/duplicate"
10089                    " DWO info/types section [in module %s]"),
10090                  dwp_file->name);
10091         }
10092       /* Must have an abbrev section.  */
10093       if (ids_seen[DW_SECT_ABBREV] == -1)
10094         {
10095           error (_("Dwarf Error: bad DWP hash table, missing DWO abbrev"
10096                    " section [in module %s]"),
10097                  dwp_file->name);
10098         }
10099       htab->section_pool.v2.offsets = ids_ptr + sizeof (uint32_t) * nr_columns;
10100       htab->section_pool.v2.sizes =
10101         htab->section_pool.v2.offsets + (sizeof (uint32_t)
10102                                          * nr_units * nr_columns);
10103       if ((htab->section_pool.v2.sizes + (sizeof (uint32_t)
10104                                           * nr_units * nr_columns))
10105           > index_end)
10106         {
10107           error (_("Dwarf Error: DWP index section is corrupt (too small)"
10108                    " [in module %s]"),
10109                  dwp_file->name);
10110         }
10111     }
10112
10113   return htab;
10114 }
10115
10116 /* Update SECTIONS with the data from SECTP.
10117
10118    This function is like the other "locate" section routines that are
10119    passed to bfd_map_over_sections, but in this context the sections to
10120    read comes from the DWP V1 hash table, not the full ELF section table.
10121
10122    The result is non-zero for success, or zero if an error was found.  */
10123
10124 static int
10125 locate_v1_virtual_dwo_sections (asection *sectp,
10126                                 struct virtual_v1_dwo_sections *sections)
10127 {
10128   const struct dwop_section_names *names = &dwop_section_names;
10129
10130   if (section_is_p (sectp->name, &names->abbrev_dwo))
10131     {
10132       /* There can be only one.  */
10133       if (sections->abbrev.s.section != NULL)
10134         return 0;
10135       sections->abbrev.s.section = sectp;
10136       sections->abbrev.size = bfd_get_section_size (sectp);
10137     }
10138   else if (section_is_p (sectp->name, &names->info_dwo)
10139            || section_is_p (sectp->name, &names->types_dwo))
10140     {
10141       /* There can be only one.  */
10142       if (sections->info_or_types.s.section != NULL)
10143         return 0;
10144       sections->info_or_types.s.section = sectp;
10145       sections->info_or_types.size = bfd_get_section_size (sectp);
10146     }
10147   else if (section_is_p (sectp->name, &names->line_dwo))
10148     {
10149       /* There can be only one.  */
10150       if (sections->line.s.section != NULL)
10151         return 0;
10152       sections->line.s.section = sectp;
10153       sections->line.size = bfd_get_section_size (sectp);
10154     }
10155   else if (section_is_p (sectp->name, &names->loc_dwo))
10156     {
10157       /* There can be only one.  */
10158       if (sections->loc.s.section != NULL)
10159         return 0;
10160       sections->loc.s.section = sectp;
10161       sections->loc.size = bfd_get_section_size (sectp);
10162     }
10163   else if (section_is_p (sectp->name, &names->macinfo_dwo))
10164     {
10165       /* There can be only one.  */
10166       if (sections->macinfo.s.section != NULL)
10167         return 0;
10168       sections->macinfo.s.section = sectp;
10169       sections->macinfo.size = bfd_get_section_size (sectp);
10170     }
10171   else if (section_is_p (sectp->name, &names->macro_dwo))
10172     {
10173       /* There can be only one.  */
10174       if (sections->macro.s.section != NULL)
10175         return 0;
10176       sections->macro.s.section = sectp;
10177       sections->macro.size = bfd_get_section_size (sectp);
10178     }
10179   else if (section_is_p (sectp->name, &names->str_offsets_dwo))
10180     {
10181       /* There can be only one.  */
10182       if (sections->str_offsets.s.section != NULL)
10183         return 0;
10184       sections->str_offsets.s.section = sectp;
10185       sections->str_offsets.size = bfd_get_section_size (sectp);
10186     }
10187   else
10188     {
10189       /* No other kind of section is valid.  */
10190       return 0;
10191     }
10192
10193   return 1;
10194 }
10195
10196 /* Create a dwo_unit object for the DWO unit with signature SIGNATURE.
10197    UNIT_INDEX is the index of the DWO unit in the DWP hash table.
10198    COMP_DIR is the DW_AT_comp_dir attribute of the referencing CU.
10199    This is for DWP version 1 files.  */
10200
10201 static struct dwo_unit *
10202 create_dwo_unit_in_dwp_v1 (struct dwp_file *dwp_file,
10203                            uint32_t unit_index,
10204                            const char *comp_dir,
10205                            ULONGEST signature, int is_debug_types)
10206 {
10207   struct objfile *objfile = dwarf2_per_objfile->objfile;
10208   const struct dwp_hash_table *dwp_htab =
10209     is_debug_types ? dwp_file->tus : dwp_file->cus;
10210   bfd *dbfd = dwp_file->dbfd;
10211   const char *kind = is_debug_types ? "TU" : "CU";
10212   struct dwo_file *dwo_file;
10213   struct dwo_unit *dwo_unit;
10214   struct virtual_v1_dwo_sections sections;
10215   void **dwo_file_slot;
10216   char *virtual_dwo_name;
10217   struct cleanup *cleanups;
10218   int i;
10219
10220   gdb_assert (dwp_file->version == 1);
10221
10222   if (dwarf_read_debug)
10223     {
10224       fprintf_unfiltered (gdb_stdlog, "Reading %s %s/%s in DWP V1 file: %s\n",
10225                           kind,
10226                           pulongest (unit_index), hex_string (signature),
10227                           dwp_file->name);
10228     }
10229
10230   /* Fetch the sections of this DWO unit.
10231      Put a limit on the number of sections we look for so that bad data
10232      doesn't cause us to loop forever.  */
10233
10234 #define MAX_NR_V1_DWO_SECTIONS \
10235   (1 /* .debug_info or .debug_types */ \
10236    + 1 /* .debug_abbrev */ \
10237    + 1 /* .debug_line */ \
10238    + 1 /* .debug_loc */ \
10239    + 1 /* .debug_str_offsets */ \
10240    + 1 /* .debug_macro or .debug_macinfo */ \
10241    + 1 /* trailing zero */)
10242
10243   memset (&sections, 0, sizeof (sections));
10244   cleanups = make_cleanup (null_cleanup, 0);
10245
10246   for (i = 0; i < MAX_NR_V1_DWO_SECTIONS; ++i)
10247     {
10248       asection *sectp;
10249       uint32_t section_nr =
10250         read_4_bytes (dbfd,
10251                       dwp_htab->section_pool.v1.indices
10252                       + (unit_index + i) * sizeof (uint32_t));
10253
10254       if (section_nr == 0)
10255         break;
10256       if (section_nr >= dwp_file->num_sections)
10257         {
10258           error (_("Dwarf Error: bad DWP hash table, section number too large"
10259                    " [in module %s]"),
10260                  dwp_file->name);
10261         }
10262
10263       sectp = dwp_file->elf_sections[section_nr];
10264       if (! locate_v1_virtual_dwo_sections (sectp, &sections))
10265         {
10266           error (_("Dwarf Error: bad DWP hash table, invalid section found"
10267                    " [in module %s]"),
10268                  dwp_file->name);
10269         }
10270     }
10271
10272   if (i < 2
10273       || dwarf2_section_empty_p (&sections.info_or_types)
10274       || dwarf2_section_empty_p (&sections.abbrev))
10275     {
10276       error (_("Dwarf Error: bad DWP hash table, missing DWO sections"
10277                " [in module %s]"),
10278              dwp_file->name);
10279     }
10280   if (i == MAX_NR_V1_DWO_SECTIONS)
10281     {
10282       error (_("Dwarf Error: bad DWP hash table, too many DWO sections"
10283                " [in module %s]"),
10284              dwp_file->name);
10285     }
10286
10287   /* It's easier for the rest of the code if we fake a struct dwo_file and
10288      have dwo_unit "live" in that.  At least for now.
10289
10290      The DWP file can be made up of a random collection of CUs and TUs.
10291      However, for each CU + set of TUs that came from the same original DWO
10292      file, we can combine them back into a virtual DWO file to save space
10293      (fewer struct dwo_file objects to allocate).  Remember that for really
10294      large apps there can be on the order of 8K CUs and 200K TUs, or more.  */
10295
10296   virtual_dwo_name =
10297     xstrprintf ("virtual-dwo/%d-%d-%d-%d",
10298                 get_section_id (&sections.abbrev),
10299                 get_section_id (&sections.line),
10300                 get_section_id (&sections.loc),
10301                 get_section_id (&sections.str_offsets));
10302   make_cleanup (xfree, virtual_dwo_name);
10303   /* Can we use an existing virtual DWO file?  */
10304   dwo_file_slot = lookup_dwo_file_slot (virtual_dwo_name, comp_dir);
10305   /* Create one if necessary.  */
10306   if (*dwo_file_slot == NULL)
10307     {
10308       if (dwarf_read_debug)
10309         {
10310           fprintf_unfiltered (gdb_stdlog, "Creating virtual DWO: %s\n",
10311                               virtual_dwo_name);
10312         }
10313       dwo_file = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_file);
10314       dwo_file->dwo_name
10315         = (const char *) obstack_copy0 (&objfile->objfile_obstack,
10316                                         virtual_dwo_name,
10317                                         strlen (virtual_dwo_name));
10318       dwo_file->comp_dir = comp_dir;
10319       dwo_file->sections.abbrev = sections.abbrev;
10320       dwo_file->sections.line = sections.line;
10321       dwo_file->sections.loc = sections.loc;
10322       dwo_file->sections.macinfo = sections.macinfo;
10323       dwo_file->sections.macro = sections.macro;
10324       dwo_file->sections.str_offsets = sections.str_offsets;
10325       /* The "str" section is global to the entire DWP file.  */
10326       dwo_file->sections.str = dwp_file->sections.str;
10327       /* The info or types section is assigned below to dwo_unit,
10328          there's no need to record it in dwo_file.
10329          Also, we can't simply record type sections in dwo_file because
10330          we record a pointer into the vector in dwo_unit.  As we collect more
10331          types we'll grow the vector and eventually have to reallocate space
10332          for it, invalidating all copies of pointers into the previous
10333          contents.  */
10334       *dwo_file_slot = dwo_file;
10335     }
10336   else
10337     {
10338       if (dwarf_read_debug)
10339         {
10340           fprintf_unfiltered (gdb_stdlog, "Using existing virtual DWO: %s\n",
10341                               virtual_dwo_name);
10342         }
10343       dwo_file = (struct dwo_file *) *dwo_file_slot;
10344     }
10345   do_cleanups (cleanups);
10346
10347   dwo_unit = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_unit);
10348   dwo_unit->dwo_file = dwo_file;
10349   dwo_unit->signature = signature;
10350   dwo_unit->section =
10351     XOBNEW (&objfile->objfile_obstack, struct dwarf2_section_info);
10352   *dwo_unit->section = sections.info_or_types;
10353   /* dwo_unit->{offset,length,type_offset_in_tu} are set later.  */
10354
10355   return dwo_unit;
10356 }
10357
10358 /* Subroutine of create_dwo_unit_in_dwp_v2 to simplify it.
10359    Given a pointer to the containing section SECTION, and OFFSET,SIZE of the
10360    piece within that section used by a TU/CU, return a virtual section
10361    of just that piece.  */
10362
10363 static struct dwarf2_section_info
10364 create_dwp_v2_section (struct dwarf2_section_info *section,
10365                        bfd_size_type offset, bfd_size_type size)
10366 {
10367   struct dwarf2_section_info result;
10368   asection *sectp;
10369
10370   gdb_assert (section != NULL);
10371   gdb_assert (!section->is_virtual);
10372
10373   memset (&result, 0, sizeof (result));
10374   result.s.containing_section = section;
10375   result.is_virtual = 1;
10376
10377   if (size == 0)
10378     return result;
10379
10380   sectp = get_section_bfd_section (section);
10381
10382   /* Flag an error if the piece denoted by OFFSET,SIZE is outside the
10383      bounds of the real section.  This is a pretty-rare event, so just
10384      flag an error (easier) instead of a warning and trying to cope.  */
10385   if (sectp == NULL
10386       || offset + size > bfd_get_section_size (sectp))
10387     {
10388       bfd *abfd = sectp->owner;
10389
10390       error (_("Dwarf Error: Bad DWP V2 section info, doesn't fit"
10391                " in section %s [in module %s]"),
10392              sectp ? bfd_section_name (abfd, sectp) : "<unknown>",
10393              objfile_name (dwarf2_per_objfile->objfile));
10394     }
10395
10396   result.virtual_offset = offset;
10397   result.size = size;
10398   return result;
10399 }
10400
10401 /* Create a dwo_unit object for the DWO unit with signature SIGNATURE.
10402    UNIT_INDEX is the index of the DWO unit in the DWP hash table.
10403    COMP_DIR is the DW_AT_comp_dir attribute of the referencing CU.
10404    This is for DWP version 2 files.  */
10405
10406 static struct dwo_unit *
10407 create_dwo_unit_in_dwp_v2 (struct dwp_file *dwp_file,
10408                            uint32_t unit_index,
10409                            const char *comp_dir,
10410                            ULONGEST signature, int is_debug_types)
10411 {
10412   struct objfile *objfile = dwarf2_per_objfile->objfile;
10413   const struct dwp_hash_table *dwp_htab =
10414     is_debug_types ? dwp_file->tus : dwp_file->cus;
10415   bfd *dbfd = dwp_file->dbfd;
10416   const char *kind = is_debug_types ? "TU" : "CU";
10417   struct dwo_file *dwo_file;
10418   struct dwo_unit *dwo_unit;
10419   struct virtual_v2_dwo_sections sections;
10420   void **dwo_file_slot;
10421   char *virtual_dwo_name;
10422   struct cleanup *cleanups;
10423   int i;
10424
10425   gdb_assert (dwp_file->version == 2);
10426
10427   if (dwarf_read_debug)
10428     {
10429       fprintf_unfiltered (gdb_stdlog, "Reading %s %s/%s in DWP V2 file: %s\n",
10430                           kind,
10431                           pulongest (unit_index), hex_string (signature),
10432                           dwp_file->name);
10433     }
10434
10435   /* Fetch the section offsets of this DWO unit.  */
10436
10437   memset (&sections, 0, sizeof (sections));
10438   cleanups = make_cleanup (null_cleanup, 0);
10439
10440   for (i = 0; i < dwp_htab->nr_columns; ++i)
10441     {
10442       uint32_t offset = read_4_bytes (dbfd,
10443                                       dwp_htab->section_pool.v2.offsets
10444                                       + (((unit_index - 1) * dwp_htab->nr_columns
10445                                           + i)
10446                                          * sizeof (uint32_t)));
10447       uint32_t size = read_4_bytes (dbfd,
10448                                     dwp_htab->section_pool.v2.sizes
10449                                     + (((unit_index - 1) * dwp_htab->nr_columns
10450                                         + i)
10451                                        * sizeof (uint32_t)));
10452
10453       switch (dwp_htab->section_pool.v2.section_ids[i])
10454         {
10455         case DW_SECT_INFO:
10456         case DW_SECT_TYPES:
10457           sections.info_or_types_offset = offset;
10458           sections.info_or_types_size = size;
10459           break;
10460         case DW_SECT_ABBREV:
10461           sections.abbrev_offset = offset;
10462           sections.abbrev_size = size;
10463           break;
10464         case DW_SECT_LINE:
10465           sections.line_offset = offset;
10466           sections.line_size = size;
10467           break;
10468         case DW_SECT_LOC:
10469           sections.loc_offset = offset;
10470           sections.loc_size = size;
10471           break;
10472         case DW_SECT_STR_OFFSETS:
10473           sections.str_offsets_offset = offset;
10474           sections.str_offsets_size = size;
10475           break;
10476         case DW_SECT_MACINFO:
10477           sections.macinfo_offset = offset;
10478           sections.macinfo_size = size;
10479           break;
10480         case DW_SECT_MACRO:
10481           sections.macro_offset = offset;
10482           sections.macro_size = size;
10483           break;
10484         }
10485     }
10486
10487   /* It's easier for the rest of the code if we fake a struct dwo_file and
10488      have dwo_unit "live" in that.  At least for now.
10489
10490      The DWP file can be made up of a random collection of CUs and TUs.
10491      However, for each CU + set of TUs that came from the same original DWO
10492      file, we can combine them back into a virtual DWO file to save space
10493      (fewer struct dwo_file objects to allocate).  Remember that for really
10494      large apps there can be on the order of 8K CUs and 200K TUs, or more.  */
10495
10496   virtual_dwo_name =
10497     xstrprintf ("virtual-dwo/%ld-%ld-%ld-%ld",
10498                 (long) (sections.abbrev_size ? sections.abbrev_offset : 0),
10499                 (long) (sections.line_size ? sections.line_offset : 0),
10500                 (long) (sections.loc_size ? sections.loc_offset : 0),
10501                 (long) (sections.str_offsets_size
10502                         ? sections.str_offsets_offset : 0));
10503   make_cleanup (xfree, virtual_dwo_name);
10504   /* Can we use an existing virtual DWO file?  */
10505   dwo_file_slot = lookup_dwo_file_slot (virtual_dwo_name, comp_dir);
10506   /* Create one if necessary.  */
10507   if (*dwo_file_slot == NULL)
10508     {
10509       if (dwarf_read_debug)
10510         {
10511           fprintf_unfiltered (gdb_stdlog, "Creating virtual DWO: %s\n",
10512                               virtual_dwo_name);
10513         }
10514       dwo_file = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_file);
10515       dwo_file->dwo_name
10516         = (const char *) obstack_copy0 (&objfile->objfile_obstack,
10517                                         virtual_dwo_name,
10518                                         strlen (virtual_dwo_name));
10519       dwo_file->comp_dir = comp_dir;
10520       dwo_file->sections.abbrev =
10521         create_dwp_v2_section (&dwp_file->sections.abbrev,
10522                                sections.abbrev_offset, sections.abbrev_size);
10523       dwo_file->sections.line =
10524         create_dwp_v2_section (&dwp_file->sections.line,
10525                                sections.line_offset, sections.line_size);
10526       dwo_file->sections.loc =
10527         create_dwp_v2_section (&dwp_file->sections.loc,
10528                                sections.loc_offset, sections.loc_size);
10529       dwo_file->sections.macinfo =
10530         create_dwp_v2_section (&dwp_file->sections.macinfo,
10531                                sections.macinfo_offset, sections.macinfo_size);
10532       dwo_file->sections.macro =
10533         create_dwp_v2_section (&dwp_file->sections.macro,
10534                                sections.macro_offset, sections.macro_size);
10535       dwo_file->sections.str_offsets =
10536         create_dwp_v2_section (&dwp_file->sections.str_offsets,
10537                                sections.str_offsets_offset,
10538                                sections.str_offsets_size);
10539       /* The "str" section is global to the entire DWP file.  */
10540       dwo_file->sections.str = dwp_file->sections.str;
10541       /* The info or types section is assigned below to dwo_unit,
10542          there's no need to record it in dwo_file.
10543          Also, we can't simply record type sections in dwo_file because
10544          we record a pointer into the vector in dwo_unit.  As we collect more
10545          types we'll grow the vector and eventually have to reallocate space
10546          for it, invalidating all copies of pointers into the previous
10547          contents.  */
10548       *dwo_file_slot = dwo_file;
10549     }
10550   else
10551     {
10552       if (dwarf_read_debug)
10553         {
10554           fprintf_unfiltered (gdb_stdlog, "Using existing virtual DWO: %s\n",
10555                               virtual_dwo_name);
10556         }
10557       dwo_file = (struct dwo_file *) *dwo_file_slot;
10558     }
10559   do_cleanups (cleanups);
10560
10561   dwo_unit = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_unit);
10562   dwo_unit->dwo_file = dwo_file;
10563   dwo_unit->signature = signature;
10564   dwo_unit->section =
10565     XOBNEW (&objfile->objfile_obstack, struct dwarf2_section_info);
10566   *dwo_unit->section = create_dwp_v2_section (is_debug_types
10567                                               ? &dwp_file->sections.types
10568                                               : &dwp_file->sections.info,
10569                                               sections.info_or_types_offset,
10570                                               sections.info_or_types_size);
10571   /* dwo_unit->{offset,length,type_offset_in_tu} are set later.  */
10572
10573   return dwo_unit;
10574 }
10575
10576 /* Lookup the DWO unit with SIGNATURE in DWP_FILE.
10577    Returns NULL if the signature isn't found.  */
10578
10579 static struct dwo_unit *
10580 lookup_dwo_unit_in_dwp (struct dwp_file *dwp_file, const char *comp_dir,
10581                         ULONGEST signature, int is_debug_types)
10582 {
10583   const struct dwp_hash_table *dwp_htab =
10584     is_debug_types ? dwp_file->tus : dwp_file->cus;
10585   bfd *dbfd = dwp_file->dbfd;
10586   uint32_t mask = dwp_htab->nr_slots - 1;
10587   uint32_t hash = signature & mask;
10588   uint32_t hash2 = ((signature >> 32) & mask) | 1;
10589   unsigned int i;
10590   void **slot;
10591   struct dwo_unit find_dwo_cu;
10592
10593   memset (&find_dwo_cu, 0, sizeof (find_dwo_cu));
10594   find_dwo_cu.signature = signature;
10595   slot = htab_find_slot (is_debug_types
10596                          ? dwp_file->loaded_tus
10597                          : dwp_file->loaded_cus,
10598                          &find_dwo_cu, INSERT);
10599
10600   if (*slot != NULL)
10601     return (struct dwo_unit *) *slot;
10602
10603   /* Use a for loop so that we don't loop forever on bad debug info.  */
10604   for (i = 0; i < dwp_htab->nr_slots; ++i)
10605     {
10606       ULONGEST signature_in_table;
10607
10608       signature_in_table =
10609         read_8_bytes (dbfd, dwp_htab->hash_table + hash * sizeof (uint64_t));
10610       if (signature_in_table == signature)
10611         {
10612           uint32_t unit_index =
10613             read_4_bytes (dbfd,
10614                           dwp_htab->unit_table + hash * sizeof (uint32_t));
10615
10616           if (dwp_file->version == 1)
10617             {
10618               *slot = create_dwo_unit_in_dwp_v1 (dwp_file, unit_index,
10619                                                  comp_dir, signature,
10620                                                  is_debug_types);
10621             }
10622           else
10623             {
10624               *slot = create_dwo_unit_in_dwp_v2 (dwp_file, unit_index,
10625                                                  comp_dir, signature,
10626                                                  is_debug_types);
10627             }
10628           return (struct dwo_unit *) *slot;
10629         }
10630       if (signature_in_table == 0)
10631         return NULL;
10632       hash = (hash + hash2) & mask;
10633     }
10634
10635   error (_("Dwarf Error: bad DWP hash table, lookup didn't terminate"
10636            " [in module %s]"),
10637          dwp_file->name);
10638 }
10639
10640 /* Subroutine of open_dwo_file,open_dwp_file to simplify them.
10641    Open the file specified by FILE_NAME and hand it off to BFD for
10642    preliminary analysis.  Return a newly initialized bfd *, which
10643    includes a canonicalized copy of FILE_NAME.
10644    If IS_DWP is TRUE, we're opening a DWP file, otherwise a DWO file.
10645    SEARCH_CWD is true if the current directory is to be searched.
10646    It will be searched before debug-file-directory.
10647    If successful, the file is added to the bfd include table of the
10648    objfile's bfd (see gdb_bfd_record_inclusion).
10649    If unable to find/open the file, return NULL.
10650    NOTE: This function is derived from symfile_bfd_open.  */
10651
10652 static gdb_bfd_ref_ptr
10653 try_open_dwop_file (const char *file_name, int is_dwp, int search_cwd)
10654 {
10655   int desc, flags;
10656   char *absolute_name;
10657   /* Blech.  OPF_TRY_CWD_FIRST also disables searching the path list if
10658      FILE_NAME contains a '/'.  So we can't use it.  Instead prepend "."
10659      to debug_file_directory.  */
10660   char *search_path;
10661   static const char dirname_separator_string[] = { DIRNAME_SEPARATOR, '\0' };
10662
10663   if (search_cwd)
10664     {
10665       if (*debug_file_directory != '\0')
10666         search_path = concat (".", dirname_separator_string,
10667                               debug_file_directory, (char *) NULL);
10668       else
10669         search_path = xstrdup (".");
10670     }
10671   else
10672     search_path = xstrdup (debug_file_directory);
10673
10674   flags = OPF_RETURN_REALPATH;
10675   if (is_dwp)
10676     flags |= OPF_SEARCH_IN_PATH;
10677   desc = openp (search_path, flags, file_name,
10678                 O_RDONLY | O_BINARY, &absolute_name);
10679   xfree (search_path);
10680   if (desc < 0)
10681     return NULL;
10682
10683   gdb_bfd_ref_ptr sym_bfd (gdb_bfd_open (absolute_name, gnutarget, desc));
10684   xfree (absolute_name);
10685   if (sym_bfd == NULL)
10686     return NULL;
10687   bfd_set_cacheable (sym_bfd.get (), 1);
10688
10689   if (!bfd_check_format (sym_bfd.get (), bfd_object))
10690     return NULL;
10691
10692   /* Success.  Record the bfd as having been included by the objfile's bfd.
10693      This is important because things like demangled_names_hash lives in the
10694      objfile's per_bfd space and may have references to things like symbol
10695      names that live in the DWO/DWP file's per_bfd space.  PR 16426.  */
10696   gdb_bfd_record_inclusion (dwarf2_per_objfile->objfile->obfd, sym_bfd.get ());
10697
10698   return sym_bfd;
10699 }
10700
10701 /* Try to open DWO file FILE_NAME.
10702    COMP_DIR is the DW_AT_comp_dir attribute.
10703    The result is the bfd handle of the file.
10704    If there is a problem finding or opening the file, return NULL.
10705    Upon success, the canonicalized path of the file is stored in the bfd,
10706    same as symfile_bfd_open.  */
10707
10708 static gdb_bfd_ref_ptr
10709 open_dwo_file (const char *file_name, const char *comp_dir)
10710 {
10711   if (IS_ABSOLUTE_PATH (file_name))
10712     return try_open_dwop_file (file_name, 0 /*is_dwp*/, 0 /*search_cwd*/);
10713
10714   /* Before trying the search path, try DWO_NAME in COMP_DIR.  */
10715
10716   if (comp_dir != NULL)
10717     {
10718       char *path_to_try = concat (comp_dir, SLASH_STRING,
10719                                   file_name, (char *) NULL);
10720
10721       /* NOTE: If comp_dir is a relative path, this will also try the
10722          search path, which seems useful.  */
10723       gdb_bfd_ref_ptr abfd (try_open_dwop_file (path_to_try, 0 /*is_dwp*/,
10724                                                 1 /*search_cwd*/));
10725       xfree (path_to_try);
10726       if (abfd != NULL)
10727         return abfd;
10728     }
10729
10730   /* That didn't work, try debug-file-directory, which, despite its name,
10731      is a list of paths.  */
10732
10733   if (*debug_file_directory == '\0')
10734     return NULL;
10735
10736   return try_open_dwop_file (file_name, 0 /*is_dwp*/, 1 /*search_cwd*/);
10737 }
10738
10739 /* This function is mapped across the sections and remembers the offset and
10740    size of each of the DWO debugging sections we are interested in.  */
10741
10742 static void
10743 dwarf2_locate_dwo_sections (bfd *abfd, asection *sectp, void *dwo_sections_ptr)
10744 {
10745   struct dwo_sections *dwo_sections = (struct dwo_sections *) dwo_sections_ptr;
10746   const struct dwop_section_names *names = &dwop_section_names;
10747
10748   if (section_is_p (sectp->name, &names->abbrev_dwo))
10749     {
10750       dwo_sections->abbrev.s.section = sectp;
10751       dwo_sections->abbrev.size = bfd_get_section_size (sectp);
10752     }
10753   else if (section_is_p (sectp->name, &names->info_dwo))
10754     {
10755       dwo_sections->info.s.section = sectp;
10756       dwo_sections->info.size = bfd_get_section_size (sectp);
10757     }
10758   else if (section_is_p (sectp->name, &names->line_dwo))
10759     {
10760       dwo_sections->line.s.section = sectp;
10761       dwo_sections->line.size = bfd_get_section_size (sectp);
10762     }
10763   else if (section_is_p (sectp->name, &names->loc_dwo))
10764     {
10765       dwo_sections->loc.s.section = sectp;
10766       dwo_sections->loc.size = bfd_get_section_size (sectp);
10767     }
10768   else if (section_is_p (sectp->name, &names->macinfo_dwo))
10769     {
10770       dwo_sections->macinfo.s.section = sectp;
10771       dwo_sections->macinfo.size = bfd_get_section_size (sectp);
10772     }
10773   else if (section_is_p (sectp->name, &names->macro_dwo))
10774     {
10775       dwo_sections->macro.s.section = sectp;
10776       dwo_sections->macro.size = bfd_get_section_size (sectp);
10777     }
10778   else if (section_is_p (sectp->name, &names->str_dwo))
10779     {
10780       dwo_sections->str.s.section = sectp;
10781       dwo_sections->str.size = bfd_get_section_size (sectp);
10782     }
10783   else if (section_is_p (sectp->name, &names->str_offsets_dwo))
10784     {
10785       dwo_sections->str_offsets.s.section = sectp;
10786       dwo_sections->str_offsets.size = bfd_get_section_size (sectp);
10787     }
10788   else if (section_is_p (sectp->name, &names->types_dwo))
10789     {
10790       struct dwarf2_section_info type_section;
10791
10792       memset (&type_section, 0, sizeof (type_section));
10793       type_section.s.section = sectp;
10794       type_section.size = bfd_get_section_size (sectp);
10795       VEC_safe_push (dwarf2_section_info_def, dwo_sections->types,
10796                      &type_section);
10797     }
10798 }
10799
10800 /* Initialize the use of the DWO file specified by DWO_NAME and referenced
10801    by PER_CU.  This is for the non-DWP case.
10802    The result is NULL if DWO_NAME can't be found.  */
10803
10804 static struct dwo_file *
10805 open_and_init_dwo_file (struct dwarf2_per_cu_data *per_cu,
10806                         const char *dwo_name, const char *comp_dir)
10807 {
10808   struct objfile *objfile = dwarf2_per_objfile->objfile;
10809   struct dwo_file *dwo_file;
10810   struct cleanup *cleanups;
10811
10812   gdb_bfd_ref_ptr dbfd (open_dwo_file (dwo_name, comp_dir));
10813   if (dbfd == NULL)
10814     {
10815       if (dwarf_read_debug)
10816         fprintf_unfiltered (gdb_stdlog, "DWO file not found: %s\n", dwo_name);
10817       return NULL;
10818     }
10819   dwo_file = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_file);
10820   dwo_file->dwo_name = dwo_name;
10821   dwo_file->comp_dir = comp_dir;
10822   dwo_file->dbfd = dbfd.release ();
10823
10824   cleanups = make_cleanup (free_dwo_file_cleanup, dwo_file);
10825
10826   bfd_map_over_sections (dwo_file->dbfd, dwarf2_locate_dwo_sections,
10827                          &dwo_file->sections);
10828
10829   create_cus_hash_table (*dwo_file, dwo_file->sections.info, dwo_file->cus);
10830
10831   create_debug_types_hash_table (dwo_file, dwo_file->sections.types,
10832                                  dwo_file->tus);
10833
10834   discard_cleanups (cleanups);
10835
10836   if (dwarf_read_debug)
10837     fprintf_unfiltered (gdb_stdlog, "DWO file found: %s\n", dwo_name);
10838
10839   return dwo_file;
10840 }
10841
10842 /* This function is mapped across the sections and remembers the offset and
10843    size of each of the DWP debugging sections common to version 1 and 2 that
10844    we are interested in.  */
10845
10846 static void
10847 dwarf2_locate_common_dwp_sections (bfd *abfd, asection *sectp,
10848                                    void *dwp_file_ptr)
10849 {
10850   struct dwp_file *dwp_file = (struct dwp_file *) dwp_file_ptr;
10851   const struct dwop_section_names *names = &dwop_section_names;
10852   unsigned int elf_section_nr = elf_section_data (sectp)->this_idx;
10853
10854   /* Record the ELF section number for later lookup: this is what the
10855      .debug_cu_index,.debug_tu_index tables use in DWP V1.  */
10856   gdb_assert (elf_section_nr < dwp_file->num_sections);
10857   dwp_file->elf_sections[elf_section_nr] = sectp;
10858
10859   /* Look for specific sections that we need.  */
10860   if (section_is_p (sectp->name, &names->str_dwo))
10861     {
10862       dwp_file->sections.str.s.section = sectp;
10863       dwp_file->sections.str.size = bfd_get_section_size (sectp);
10864     }
10865   else if (section_is_p (sectp->name, &names->cu_index))
10866     {
10867       dwp_file->sections.cu_index.s.section = sectp;
10868       dwp_file->sections.cu_index.size = bfd_get_section_size (sectp);
10869     }
10870   else if (section_is_p (sectp->name, &names->tu_index))
10871     {
10872       dwp_file->sections.tu_index.s.section = sectp;
10873       dwp_file->sections.tu_index.size = bfd_get_section_size (sectp);
10874     }
10875 }
10876
10877 /* This function is mapped across the sections and remembers the offset and
10878    size of each of the DWP version 2 debugging sections that we are interested
10879    in.  This is split into a separate function because we don't know if we
10880    have version 1 or 2 until we parse the cu_index/tu_index sections.  */
10881
10882 static void
10883 dwarf2_locate_v2_dwp_sections (bfd *abfd, asection *sectp, void *dwp_file_ptr)
10884 {
10885   struct dwp_file *dwp_file = (struct dwp_file *) dwp_file_ptr;
10886   const struct dwop_section_names *names = &dwop_section_names;
10887   unsigned int elf_section_nr = elf_section_data (sectp)->this_idx;
10888
10889   /* Record the ELF section number for later lookup: this is what the
10890      .debug_cu_index,.debug_tu_index tables use in DWP V1.  */
10891   gdb_assert (elf_section_nr < dwp_file->num_sections);
10892   dwp_file->elf_sections[elf_section_nr] = sectp;
10893
10894   /* Look for specific sections that we need.  */
10895   if (section_is_p (sectp->name, &names->abbrev_dwo))
10896     {
10897       dwp_file->sections.abbrev.s.section = sectp;
10898       dwp_file->sections.abbrev.size = bfd_get_section_size (sectp);
10899     }
10900   else if (section_is_p (sectp->name, &names->info_dwo))
10901     {
10902       dwp_file->sections.info.s.section = sectp;
10903       dwp_file->sections.info.size = bfd_get_section_size (sectp);
10904     }
10905   else if (section_is_p (sectp->name, &names->line_dwo))
10906     {
10907       dwp_file->sections.line.s.section = sectp;
10908       dwp_file->sections.line.size = bfd_get_section_size (sectp);
10909     }
10910   else if (section_is_p (sectp->name, &names->loc_dwo))
10911     {
10912       dwp_file->sections.loc.s.section = sectp;
10913       dwp_file->sections.loc.size = bfd_get_section_size (sectp);
10914     }
10915   else if (section_is_p (sectp->name, &names->macinfo_dwo))
10916     {
10917       dwp_file->sections.macinfo.s.section = sectp;
10918       dwp_file->sections.macinfo.size = bfd_get_section_size (sectp);
10919     }
10920   else if (section_is_p (sectp->name, &names->macro_dwo))
10921     {
10922       dwp_file->sections.macro.s.section = sectp;
10923       dwp_file->sections.macro.size = bfd_get_section_size (sectp);
10924     }
10925   else if (section_is_p (sectp->name, &names->str_offsets_dwo))
10926     {
10927       dwp_file->sections.str_offsets.s.section = sectp;
10928       dwp_file->sections.str_offsets.size = bfd_get_section_size (sectp);
10929     }
10930   else if (section_is_p (sectp->name, &names->types_dwo))
10931     {
10932       dwp_file->sections.types.s.section = sectp;
10933       dwp_file->sections.types.size = bfd_get_section_size (sectp);
10934     }
10935 }
10936
10937 /* Hash function for dwp_file loaded CUs/TUs.  */
10938
10939 static hashval_t
10940 hash_dwp_loaded_cutus (const void *item)
10941 {
10942   const struct dwo_unit *dwo_unit = (const struct dwo_unit *) item;
10943
10944   /* This drops the top 32 bits of the signature, but is ok for a hash.  */
10945   return dwo_unit->signature;
10946 }
10947
10948 /* Equality function for dwp_file loaded CUs/TUs.  */
10949
10950 static int
10951 eq_dwp_loaded_cutus (const void *a, const void *b)
10952 {
10953   const struct dwo_unit *dua = (const struct dwo_unit *) a;
10954   const struct dwo_unit *dub = (const struct dwo_unit *) b;
10955
10956   return dua->signature == dub->signature;
10957 }
10958
10959 /* Allocate a hash table for dwp_file loaded CUs/TUs.  */
10960
10961 static htab_t
10962 allocate_dwp_loaded_cutus_table (struct objfile *objfile)
10963 {
10964   return htab_create_alloc_ex (3,
10965                                hash_dwp_loaded_cutus,
10966                                eq_dwp_loaded_cutus,
10967                                NULL,
10968                                &objfile->objfile_obstack,
10969                                hashtab_obstack_allocate,
10970                                dummy_obstack_deallocate);
10971 }
10972
10973 /* Try to open DWP file FILE_NAME.
10974    The result is the bfd handle of the file.
10975    If there is a problem finding or opening the file, return NULL.
10976    Upon success, the canonicalized path of the file is stored in the bfd,
10977    same as symfile_bfd_open.  */
10978
10979 static gdb_bfd_ref_ptr
10980 open_dwp_file (const char *file_name)
10981 {
10982   gdb_bfd_ref_ptr abfd (try_open_dwop_file (file_name, 1 /*is_dwp*/,
10983                                             1 /*search_cwd*/));
10984   if (abfd != NULL)
10985     return abfd;
10986
10987   /* Work around upstream bug 15652.
10988      http://sourceware.org/bugzilla/show_bug.cgi?id=15652
10989      [Whether that's a "bug" is debatable, but it is getting in our way.]
10990      We have no real idea where the dwp file is, because gdb's realpath-ing
10991      of the executable's path may have discarded the needed info.
10992      [IWBN if the dwp file name was recorded in the executable, akin to
10993      .gnu_debuglink, but that doesn't exist yet.]
10994      Strip the directory from FILE_NAME and search again.  */
10995   if (*debug_file_directory != '\0')
10996     {
10997       /* Don't implicitly search the current directory here.
10998          If the user wants to search "." to handle this case,
10999          it must be added to debug-file-directory.  */
11000       return try_open_dwop_file (lbasename (file_name), 1 /*is_dwp*/,
11001                                  0 /*search_cwd*/);
11002     }
11003
11004   return NULL;
11005 }
11006
11007 /* Initialize the use of the DWP file for the current objfile.
11008    By convention the name of the DWP file is ${objfile}.dwp.
11009    The result is NULL if it can't be found.  */
11010
11011 static struct dwp_file *
11012 open_and_init_dwp_file (void)
11013 {
11014   struct objfile *objfile = dwarf2_per_objfile->objfile;
11015   struct dwp_file *dwp_file;
11016
11017   /* Try to find first .dwp for the binary file before any symbolic links
11018      resolving.  */
11019
11020   /* If the objfile is a debug file, find the name of the real binary
11021      file and get the name of dwp file from there.  */
11022   std::string dwp_name;
11023   if (objfile->separate_debug_objfile_backlink != NULL)
11024     {
11025       struct objfile *backlink = objfile->separate_debug_objfile_backlink;
11026       const char *backlink_basename = lbasename (backlink->original_name);
11027
11028       dwp_name = ldirname (objfile->original_name) + SLASH_STRING + backlink_basename;
11029     }
11030   else
11031     dwp_name = objfile->original_name;
11032
11033   dwp_name += ".dwp";
11034
11035   gdb_bfd_ref_ptr dbfd (open_dwp_file (dwp_name.c_str ()));
11036   if (dbfd == NULL
11037       && strcmp (objfile->original_name, objfile_name (objfile)) != 0)
11038     {
11039       /* Try to find .dwp for the binary file after gdb_realpath resolving.  */
11040       dwp_name = objfile_name (objfile);
11041       dwp_name += ".dwp";
11042       dbfd = open_dwp_file (dwp_name.c_str ());
11043     }
11044
11045   if (dbfd == NULL)
11046     {
11047       if (dwarf_read_debug)
11048         fprintf_unfiltered (gdb_stdlog, "DWP file not found: %s\n", dwp_name.c_str ());
11049       return NULL;
11050     }
11051   dwp_file = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwp_file);
11052   dwp_file->name = bfd_get_filename (dbfd.get ());
11053   dwp_file->dbfd = dbfd.release ();
11054
11055   /* +1: section 0 is unused */
11056   dwp_file->num_sections = bfd_count_sections (dwp_file->dbfd) + 1;
11057   dwp_file->elf_sections =
11058     OBSTACK_CALLOC (&objfile->objfile_obstack,
11059                     dwp_file->num_sections, asection *);
11060
11061   bfd_map_over_sections (dwp_file->dbfd, dwarf2_locate_common_dwp_sections,
11062                          dwp_file);
11063
11064   dwp_file->cus = create_dwp_hash_table (dwp_file, 0);
11065
11066   dwp_file->tus = create_dwp_hash_table (dwp_file, 1);
11067
11068   /* The DWP file version is stored in the hash table.  Oh well.  */
11069   if (dwp_file->cus->version != dwp_file->tus->version)
11070     {
11071       /* Technically speaking, we should try to limp along, but this is
11072          pretty bizarre.  We use pulongest here because that's the established
11073          portability solution (e.g, we cannot use %u for uint32_t).  */
11074       error (_("Dwarf Error: DWP file CU version %s doesn't match"
11075                " TU version %s [in DWP file %s]"),
11076              pulongest (dwp_file->cus->version),
11077              pulongest (dwp_file->tus->version), dwp_name.c_str ());
11078     }
11079   dwp_file->version = dwp_file->cus->version;
11080
11081   if (dwp_file->version == 2)
11082     bfd_map_over_sections (dwp_file->dbfd, dwarf2_locate_v2_dwp_sections,
11083                            dwp_file);
11084
11085   dwp_file->loaded_cus = allocate_dwp_loaded_cutus_table (objfile);
11086   dwp_file->loaded_tus = allocate_dwp_loaded_cutus_table (objfile);
11087
11088   if (dwarf_read_debug)
11089     {
11090       fprintf_unfiltered (gdb_stdlog, "DWP file found: %s\n", dwp_file->name);
11091       fprintf_unfiltered (gdb_stdlog,
11092                           "    %s CUs, %s TUs\n",
11093                           pulongest (dwp_file->cus ? dwp_file->cus->nr_units : 0),
11094                           pulongest (dwp_file->tus ? dwp_file->tus->nr_units : 0));
11095     }
11096
11097   return dwp_file;
11098 }
11099
11100 /* Wrapper around open_and_init_dwp_file, only open it once.  */
11101
11102 static struct dwp_file *
11103 get_dwp_file (void)
11104 {
11105   if (! dwarf2_per_objfile->dwp_checked)
11106     {
11107       dwarf2_per_objfile->dwp_file = open_and_init_dwp_file ();
11108       dwarf2_per_objfile->dwp_checked = 1;
11109     }
11110   return dwarf2_per_objfile->dwp_file;
11111 }
11112
11113 /* Subroutine of lookup_dwo_comp_unit, lookup_dwo_type_unit.
11114    Look up the CU/TU with signature SIGNATURE, either in DWO file DWO_NAME
11115    or in the DWP file for the objfile, referenced by THIS_UNIT.
11116    If non-NULL, comp_dir is the DW_AT_comp_dir attribute.
11117    IS_DEBUG_TYPES is non-zero if reading a TU, otherwise read a CU.
11118
11119    This is called, for example, when wanting to read a variable with a
11120    complex location.  Therefore we don't want to do file i/o for every call.
11121    Therefore we don't want to look for a DWO file on every call.
11122    Therefore we first see if we've already seen SIGNATURE in a DWP file,
11123    then we check if we've already seen DWO_NAME, and only THEN do we check
11124    for a DWO file.
11125
11126    The result is a pointer to the dwo_unit object or NULL if we didn't find it
11127    (dwo_id mismatch or couldn't find the DWO/DWP file).  */
11128
11129 static struct dwo_unit *
11130 lookup_dwo_cutu (struct dwarf2_per_cu_data *this_unit,
11131                  const char *dwo_name, const char *comp_dir,
11132                  ULONGEST signature, int is_debug_types)
11133 {
11134   struct objfile *objfile = dwarf2_per_objfile->objfile;
11135   const char *kind = is_debug_types ? "TU" : "CU";
11136   void **dwo_file_slot;
11137   struct dwo_file *dwo_file;
11138   struct dwp_file *dwp_file;
11139
11140   /* First see if there's a DWP file.
11141      If we have a DWP file but didn't find the DWO inside it, don't
11142      look for the original DWO file.  It makes gdb behave differently
11143      depending on whether one is debugging in the build tree.  */
11144
11145   dwp_file = get_dwp_file ();
11146   if (dwp_file != NULL)
11147     {
11148       const struct dwp_hash_table *dwp_htab =
11149         is_debug_types ? dwp_file->tus : dwp_file->cus;
11150
11151       if (dwp_htab != NULL)
11152         {
11153           struct dwo_unit *dwo_cutu =
11154             lookup_dwo_unit_in_dwp (dwp_file, comp_dir,
11155                                     signature, is_debug_types);
11156
11157           if (dwo_cutu != NULL)
11158             {
11159               if (dwarf_read_debug)
11160                 {
11161                   fprintf_unfiltered (gdb_stdlog,
11162                                       "Virtual DWO %s %s found: @%s\n",
11163                                       kind, hex_string (signature),
11164                                       host_address_to_string (dwo_cutu));
11165                 }
11166               return dwo_cutu;
11167             }
11168         }
11169     }
11170   else
11171     {
11172       /* No DWP file, look for the DWO file.  */
11173
11174       dwo_file_slot = lookup_dwo_file_slot (dwo_name, comp_dir);
11175       if (*dwo_file_slot == NULL)
11176         {
11177           /* Read in the file and build a table of the CUs/TUs it contains.  */
11178           *dwo_file_slot = open_and_init_dwo_file (this_unit, dwo_name, comp_dir);
11179         }
11180       /* NOTE: This will be NULL if unable to open the file.  */
11181       dwo_file = (struct dwo_file *) *dwo_file_slot;
11182
11183       if (dwo_file != NULL)
11184         {
11185           struct dwo_unit *dwo_cutu = NULL;
11186
11187           if (is_debug_types && dwo_file->tus)
11188             {
11189               struct dwo_unit find_dwo_cutu;
11190
11191               memset (&find_dwo_cutu, 0, sizeof (find_dwo_cutu));
11192               find_dwo_cutu.signature = signature;
11193               dwo_cutu
11194                 = (struct dwo_unit *) htab_find (dwo_file->tus, &find_dwo_cutu);
11195             }
11196           else if (!is_debug_types && dwo_file->cus)
11197             {
11198               struct dwo_unit find_dwo_cutu;
11199
11200               memset (&find_dwo_cutu, 0, sizeof (find_dwo_cutu));
11201               find_dwo_cutu.signature = signature;
11202               dwo_cutu = (struct dwo_unit *)htab_find (dwo_file->cus,
11203                                                        &find_dwo_cutu);
11204             }
11205
11206           if (dwo_cutu != NULL)
11207             {
11208               if (dwarf_read_debug)
11209                 {
11210                   fprintf_unfiltered (gdb_stdlog, "DWO %s %s(%s) found: @%s\n",
11211                                       kind, dwo_name, hex_string (signature),
11212                                       host_address_to_string (dwo_cutu));
11213                 }
11214               return dwo_cutu;
11215             }
11216         }
11217     }
11218
11219   /* We didn't find it.  This could mean a dwo_id mismatch, or
11220      someone deleted the DWO/DWP file, or the search path isn't set up
11221      correctly to find the file.  */
11222
11223   if (dwarf_read_debug)
11224     {
11225       fprintf_unfiltered (gdb_stdlog, "DWO %s %s(%s) not found\n",
11226                           kind, dwo_name, hex_string (signature));
11227     }
11228
11229   /* This is a warning and not a complaint because it can be caused by
11230      pilot error (e.g., user accidentally deleting the DWO).  */
11231   {
11232     /* Print the name of the DWP file if we looked there, helps the user
11233        better diagnose the problem.  */
11234     char *dwp_text = NULL;
11235     struct cleanup *cleanups;
11236
11237     if (dwp_file != NULL)
11238       dwp_text = xstrprintf (" [in DWP file %s]", lbasename (dwp_file->name));
11239     cleanups = make_cleanup (xfree, dwp_text);
11240
11241     warning (_("Could not find DWO %s %s(%s)%s referenced by %s at offset 0x%x"
11242                " [in module %s]"),
11243              kind, dwo_name, hex_string (signature),
11244              dwp_text != NULL ? dwp_text : "",
11245              this_unit->is_debug_types ? "TU" : "CU",
11246              to_underlying (this_unit->sect_off), objfile_name (objfile));
11247
11248     do_cleanups (cleanups);
11249   }
11250   return NULL;
11251 }
11252
11253 /* Lookup the DWO CU DWO_NAME/SIGNATURE referenced from THIS_CU.
11254    See lookup_dwo_cutu_unit for details.  */
11255
11256 static struct dwo_unit *
11257 lookup_dwo_comp_unit (struct dwarf2_per_cu_data *this_cu,
11258                       const char *dwo_name, const char *comp_dir,
11259                       ULONGEST signature)
11260 {
11261   return lookup_dwo_cutu (this_cu, dwo_name, comp_dir, signature, 0);
11262 }
11263
11264 /* Lookup the DWO TU DWO_NAME/SIGNATURE referenced from THIS_TU.
11265    See lookup_dwo_cutu_unit for details.  */
11266
11267 static struct dwo_unit *
11268 lookup_dwo_type_unit (struct signatured_type *this_tu,
11269                       const char *dwo_name, const char *comp_dir)
11270 {
11271   return lookup_dwo_cutu (&this_tu->per_cu, dwo_name, comp_dir, this_tu->signature, 1);
11272 }
11273
11274 /* Traversal function for queue_and_load_all_dwo_tus.  */
11275
11276 static int
11277 queue_and_load_dwo_tu (void **slot, void *info)
11278 {
11279   struct dwo_unit *dwo_unit = (struct dwo_unit *) *slot;
11280   struct dwarf2_per_cu_data *per_cu = (struct dwarf2_per_cu_data *) info;
11281   ULONGEST signature = dwo_unit->signature;
11282   struct signatured_type *sig_type =
11283     lookup_dwo_signatured_type (per_cu->cu, signature);
11284
11285   if (sig_type != NULL)
11286     {
11287       struct dwarf2_per_cu_data *sig_cu = &sig_type->per_cu;
11288
11289       /* We pass NULL for DEPENDENT_CU because we don't yet know if there's
11290          a real dependency of PER_CU on SIG_TYPE.  That is detected later
11291          while processing PER_CU.  */
11292       if (maybe_queue_comp_unit (NULL, sig_cu, per_cu->cu->language))
11293         load_full_type_unit (sig_cu);
11294       VEC_safe_push (dwarf2_per_cu_ptr, per_cu->imported_symtabs, sig_cu);
11295     }
11296
11297   return 1;
11298 }
11299
11300 /* Queue all TUs contained in the DWO of PER_CU to be read in.
11301    The DWO may have the only definition of the type, though it may not be
11302    referenced anywhere in PER_CU.  Thus we have to load *all* its TUs.
11303    http://sourceware.org/bugzilla/show_bug.cgi?id=15021  */
11304
11305 static void
11306 queue_and_load_all_dwo_tus (struct dwarf2_per_cu_data *per_cu)
11307 {
11308   struct dwo_unit *dwo_unit;
11309   struct dwo_file *dwo_file;
11310
11311   gdb_assert (!per_cu->is_debug_types);
11312   gdb_assert (get_dwp_file () == NULL);
11313   gdb_assert (per_cu->cu != NULL);
11314
11315   dwo_unit = per_cu->cu->dwo_unit;
11316   gdb_assert (dwo_unit != NULL);
11317
11318   dwo_file = dwo_unit->dwo_file;
11319   if (dwo_file->tus != NULL)
11320     htab_traverse_noresize (dwo_file->tus, queue_and_load_dwo_tu, per_cu);
11321 }
11322
11323 /* Free all resources associated with DWO_FILE.
11324    Close the DWO file and munmap the sections.
11325    All memory should be on the objfile obstack.  */
11326
11327 static void
11328 free_dwo_file (struct dwo_file *dwo_file, struct objfile *objfile)
11329 {
11330
11331   /* Note: dbfd is NULL for virtual DWO files.  */
11332   gdb_bfd_unref (dwo_file->dbfd);
11333
11334   VEC_free (dwarf2_section_info_def, dwo_file->sections.types);
11335 }
11336
11337 /* Wrapper for free_dwo_file for use in cleanups.  */
11338
11339 static void
11340 free_dwo_file_cleanup (void *arg)
11341 {
11342   struct dwo_file *dwo_file = (struct dwo_file *) arg;
11343   struct objfile *objfile = dwarf2_per_objfile->objfile;
11344
11345   free_dwo_file (dwo_file, objfile);
11346 }
11347
11348 /* Traversal function for free_dwo_files.  */
11349
11350 static int
11351 free_dwo_file_from_slot (void **slot, void *info)
11352 {
11353   struct dwo_file *dwo_file = (struct dwo_file *) *slot;
11354   struct objfile *objfile = (struct objfile *) info;
11355
11356   free_dwo_file (dwo_file, objfile);
11357
11358   return 1;
11359 }
11360
11361 /* Free all resources associated with DWO_FILES.  */
11362
11363 static void
11364 free_dwo_files (htab_t dwo_files, struct objfile *objfile)
11365 {
11366   htab_traverse_noresize (dwo_files, free_dwo_file_from_slot, objfile);
11367 }
11368 \f
11369 /* Read in various DIEs.  */
11370
11371 /* qsort helper for inherit_abstract_dies.  */
11372
11373 static int
11374 unsigned_int_compar (const void *ap, const void *bp)
11375 {
11376   unsigned int a = *(unsigned int *) ap;
11377   unsigned int b = *(unsigned int *) bp;
11378
11379   return (a > b) - (b > a);
11380 }
11381
11382 /* DW_AT_abstract_origin inherits whole DIEs (not just their attributes).
11383    Inherit only the children of the DW_AT_abstract_origin DIE not being
11384    already referenced by DW_AT_abstract_origin from the children of the
11385    current DIE.  */
11386
11387 static void
11388 inherit_abstract_dies (struct die_info *die, struct dwarf2_cu *cu)
11389 {
11390   struct die_info *child_die;
11391   unsigned die_children_count;
11392   /* CU offsets which were referenced by children of the current DIE.  */
11393   sect_offset *offsets;
11394   sect_offset *offsets_end, *offsetp;
11395   /* Parent of DIE - referenced by DW_AT_abstract_origin.  */
11396   struct die_info *origin_die;
11397   /* Iterator of the ORIGIN_DIE children.  */
11398   struct die_info *origin_child_die;
11399   struct cleanup *cleanups;
11400   struct attribute *attr;
11401   struct dwarf2_cu *origin_cu;
11402   struct pending **origin_previous_list_in_scope;
11403
11404   attr = dwarf2_attr (die, DW_AT_abstract_origin, cu);
11405   if (!attr)
11406     return;
11407
11408   /* Note that following die references may follow to a die in a
11409      different cu.  */
11410
11411   origin_cu = cu;
11412   origin_die = follow_die_ref (die, attr, &origin_cu);
11413
11414   /* We're inheriting ORIGIN's children into the scope we'd put DIE's
11415      symbols in.  */
11416   origin_previous_list_in_scope = origin_cu->list_in_scope;
11417   origin_cu->list_in_scope = cu->list_in_scope;
11418
11419   if (die->tag != origin_die->tag
11420       && !(die->tag == DW_TAG_inlined_subroutine
11421            && origin_die->tag == DW_TAG_subprogram))
11422     complaint (&symfile_complaints,
11423                _("DIE 0x%x and its abstract origin 0x%x have different tags"),
11424                to_underlying (die->sect_off),
11425                to_underlying (origin_die->sect_off));
11426
11427   child_die = die->child;
11428   die_children_count = 0;
11429   while (child_die && child_die->tag)
11430     {
11431       child_die = sibling_die (child_die);
11432       die_children_count++;
11433     }
11434   offsets = XNEWVEC (sect_offset, die_children_count);
11435   cleanups = make_cleanup (xfree, offsets);
11436
11437   offsets_end = offsets;
11438   for (child_die = die->child;
11439        child_die && child_die->tag;
11440        child_die = sibling_die (child_die))
11441     {
11442       struct die_info *child_origin_die;
11443       struct dwarf2_cu *child_origin_cu;
11444
11445       /* We are trying to process concrete instance entries:
11446          DW_TAG_call_site DIEs indeed have a DW_AT_abstract_origin tag, but
11447          it's not relevant to our analysis here. i.e. detecting DIEs that are
11448          present in the abstract instance but not referenced in the concrete
11449          one.  */
11450       if (child_die->tag == DW_TAG_call_site
11451           || child_die->tag == DW_TAG_GNU_call_site)
11452         continue;
11453
11454       /* For each CHILD_DIE, find the corresponding child of
11455          ORIGIN_DIE.  If there is more than one layer of
11456          DW_AT_abstract_origin, follow them all; there shouldn't be,
11457          but GCC versions at least through 4.4 generate this (GCC PR
11458          40573).  */
11459       child_origin_die = child_die;
11460       child_origin_cu = cu;
11461       while (1)
11462         {
11463           attr = dwarf2_attr (child_origin_die, DW_AT_abstract_origin,
11464                               child_origin_cu);
11465           if (attr == NULL)
11466             break;
11467           child_origin_die = follow_die_ref (child_origin_die, attr,
11468                                              &child_origin_cu);
11469         }
11470
11471       /* According to DWARF3 3.3.8.2 #3 new entries without their abstract
11472          counterpart may exist.  */
11473       if (child_origin_die != child_die)
11474         {
11475           if (child_die->tag != child_origin_die->tag
11476               && !(child_die->tag == DW_TAG_inlined_subroutine
11477                    && child_origin_die->tag == DW_TAG_subprogram))
11478             complaint (&symfile_complaints,
11479                        _("Child DIE 0x%x and its abstract origin 0x%x have "
11480                          "different tags"),
11481                        to_underlying (child_die->sect_off),
11482                        to_underlying (child_origin_die->sect_off));
11483           if (child_origin_die->parent != origin_die)
11484             complaint (&symfile_complaints,
11485                        _("Child DIE 0x%x and its abstract origin 0x%x have "
11486                          "different parents"),
11487                        to_underlying (child_die->sect_off),
11488                        to_underlying (child_origin_die->sect_off));
11489           else
11490             *offsets_end++ = child_origin_die->sect_off;
11491         }
11492     }
11493   qsort (offsets, offsets_end - offsets, sizeof (*offsets),
11494          unsigned_int_compar);
11495   for (offsetp = offsets + 1; offsetp < offsets_end; offsetp++)
11496     if (offsetp[-1] == *offsetp)
11497       complaint (&symfile_complaints,
11498                  _("Multiple children of DIE 0x%x refer "
11499                    "to DIE 0x%x as their abstract origin"),
11500                  to_underlying (die->sect_off), to_underlying (*offsetp));
11501
11502   offsetp = offsets;
11503   origin_child_die = origin_die->child;
11504   while (origin_child_die && origin_child_die->tag)
11505     {
11506       /* Is ORIGIN_CHILD_DIE referenced by any of the DIE children?  */
11507       while (offsetp < offsets_end
11508              && *offsetp < origin_child_die->sect_off)
11509         offsetp++;
11510       if (offsetp >= offsets_end
11511           || *offsetp > origin_child_die->sect_off)
11512         {
11513           /* Found that ORIGIN_CHILD_DIE is really not referenced.
11514              Check whether we're already processing ORIGIN_CHILD_DIE.
11515              This can happen with mutually referenced abstract_origins.
11516              PR 16581.  */
11517           if (!origin_child_die->in_process)
11518             process_die (origin_child_die, origin_cu);
11519         }
11520       origin_child_die = sibling_die (origin_child_die);
11521     }
11522   origin_cu->list_in_scope = origin_previous_list_in_scope;
11523
11524   do_cleanups (cleanups);
11525 }
11526
11527 static void
11528 read_func_scope (struct die_info *die, struct dwarf2_cu *cu)
11529 {
11530   struct objfile *objfile = cu->objfile;
11531   struct gdbarch *gdbarch = get_objfile_arch (objfile);
11532   struct context_stack *newobj;
11533   CORE_ADDR lowpc;
11534   CORE_ADDR highpc;
11535   struct die_info *child_die;
11536   struct attribute *attr, *call_line, *call_file;
11537   const char *name;
11538   CORE_ADDR baseaddr;
11539   struct block *block;
11540   int inlined_func = (die->tag == DW_TAG_inlined_subroutine);
11541   VEC (symbolp) *template_args = NULL;
11542   struct template_symbol *templ_func = NULL;
11543
11544   if (inlined_func)
11545     {
11546       /* If we do not have call site information, we can't show the
11547          caller of this inlined function.  That's too confusing, so
11548          only use the scope for local variables.  */
11549       call_line = dwarf2_attr (die, DW_AT_call_line, cu);
11550       call_file = dwarf2_attr (die, DW_AT_call_file, cu);
11551       if (call_line == NULL || call_file == NULL)
11552         {
11553           read_lexical_block_scope (die, cu);
11554           return;
11555         }
11556     }
11557
11558   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
11559
11560   name = dwarf2_name (die, cu);
11561
11562   /* Ignore functions with missing or empty names.  These are actually
11563      illegal according to the DWARF standard.  */
11564   if (name == NULL)
11565     {
11566       complaint (&symfile_complaints,
11567                  _("missing name for subprogram DIE at %d"),
11568                  to_underlying (die->sect_off));
11569       return;
11570     }
11571
11572   /* Ignore functions with missing or invalid low and high pc attributes.  */
11573   if (dwarf2_get_pc_bounds (die, &lowpc, &highpc, cu, NULL)
11574       <= PC_BOUNDS_INVALID)
11575     {
11576       attr = dwarf2_attr (die, DW_AT_external, cu);
11577       if (!attr || !DW_UNSND (attr))
11578         complaint (&symfile_complaints,
11579                    _("cannot get low and high bounds "
11580                      "for subprogram DIE at %d"),
11581                    to_underlying (die->sect_off));
11582       return;
11583     }
11584
11585   lowpc = gdbarch_adjust_dwarf2_addr (gdbarch, lowpc + baseaddr);
11586   highpc = gdbarch_adjust_dwarf2_addr (gdbarch, highpc + baseaddr);
11587
11588   /* If we have any template arguments, then we must allocate a
11589      different sort of symbol.  */
11590   for (child_die = die->child; child_die; child_die = sibling_die (child_die))
11591     {
11592       if (child_die->tag == DW_TAG_template_type_param
11593           || child_die->tag == DW_TAG_template_value_param)
11594         {
11595           templ_func = allocate_template_symbol (objfile);
11596           templ_func->base.is_cplus_template_function = 1;
11597           break;
11598         }
11599     }
11600
11601   newobj = push_context (0, lowpc);
11602   newobj->name = new_symbol_full (die, read_type_die (die, cu), cu,
11603                                (struct symbol *) templ_func);
11604
11605   /* If there is a location expression for DW_AT_frame_base, record
11606      it.  */
11607   attr = dwarf2_attr (die, DW_AT_frame_base, cu);
11608   if (attr)
11609     dwarf2_symbol_mark_computed (attr, newobj->name, cu, 1);
11610
11611   /* If there is a location for the static link, record it.  */
11612   newobj->static_link = NULL;
11613   attr = dwarf2_attr (die, DW_AT_static_link, cu);
11614   if (attr)
11615     {
11616       newobj->static_link
11617         = XOBNEW (&objfile->objfile_obstack, struct dynamic_prop);
11618       attr_to_dynamic_prop (attr, die, cu, newobj->static_link);
11619     }
11620
11621   cu->list_in_scope = &local_symbols;
11622
11623   if (die->child != NULL)
11624     {
11625       child_die = die->child;
11626       while (child_die && child_die->tag)
11627         {
11628           if (child_die->tag == DW_TAG_template_type_param
11629               || child_die->tag == DW_TAG_template_value_param)
11630             {
11631               struct symbol *arg = new_symbol (child_die, NULL, cu);
11632
11633               if (arg != NULL)
11634                 VEC_safe_push (symbolp, template_args, arg);
11635             }
11636           else
11637             process_die (child_die, cu);
11638           child_die = sibling_die (child_die);
11639         }
11640     }
11641
11642   inherit_abstract_dies (die, cu);
11643
11644   /* If we have a DW_AT_specification, we might need to import using
11645      directives from the context of the specification DIE.  See the
11646      comment in determine_prefix.  */
11647   if (cu->language == language_cplus
11648       && dwarf2_attr (die, DW_AT_specification, cu))
11649     {
11650       struct dwarf2_cu *spec_cu = cu;
11651       struct die_info *spec_die = die_specification (die, &spec_cu);
11652
11653       while (spec_die)
11654         {
11655           child_die = spec_die->child;
11656           while (child_die && child_die->tag)
11657             {
11658               if (child_die->tag == DW_TAG_imported_module)
11659                 process_die (child_die, spec_cu);
11660               child_die = sibling_die (child_die);
11661             }
11662
11663           /* In some cases, GCC generates specification DIEs that
11664              themselves contain DW_AT_specification attributes.  */
11665           spec_die = die_specification (spec_die, &spec_cu);
11666         }
11667     }
11668
11669   newobj = pop_context ();
11670   /* Make a block for the local symbols within.  */
11671   block = finish_block (newobj->name, &local_symbols, newobj->old_blocks,
11672                         newobj->static_link, lowpc, highpc);
11673
11674   /* For C++, set the block's scope.  */
11675   if ((cu->language == language_cplus
11676        || cu->language == language_fortran
11677        || cu->language == language_d
11678        || cu->language == language_rust)
11679       && cu->processing_has_namespace_info)
11680     block_set_scope (block, determine_prefix (die, cu),
11681                      &objfile->objfile_obstack);
11682
11683   /* If we have address ranges, record them.  */
11684   dwarf2_record_block_ranges (die, block, baseaddr, cu);
11685
11686   gdbarch_make_symbol_special (gdbarch, newobj->name, objfile);
11687
11688   /* Attach template arguments to function.  */
11689   if (! VEC_empty (symbolp, template_args))
11690     {
11691       gdb_assert (templ_func != NULL);
11692
11693       templ_func->n_template_arguments = VEC_length (symbolp, template_args);
11694       templ_func->template_arguments
11695         = XOBNEWVEC (&objfile->objfile_obstack, struct symbol *,
11696                      templ_func->n_template_arguments);
11697       memcpy (templ_func->template_arguments,
11698               VEC_address (symbolp, template_args),
11699               (templ_func->n_template_arguments * sizeof (struct symbol *)));
11700       VEC_free (symbolp, template_args);
11701     }
11702
11703   /* In C++, we can have functions nested inside functions (e.g., when
11704      a function declares a class that has methods).  This means that
11705      when we finish processing a function scope, we may need to go
11706      back to building a containing block's symbol lists.  */
11707   local_symbols = newobj->locals;
11708   local_using_directives = newobj->local_using_directives;
11709
11710   /* If we've finished processing a top-level function, subsequent
11711      symbols go in the file symbol list.  */
11712   if (outermost_context_p ())
11713     cu->list_in_scope = &file_symbols;
11714 }
11715
11716 /* Process all the DIES contained within a lexical block scope.  Start
11717    a new scope, process the dies, and then close the scope.  */
11718
11719 static void
11720 read_lexical_block_scope (struct die_info *die, struct dwarf2_cu *cu)
11721 {
11722   struct objfile *objfile = cu->objfile;
11723   struct gdbarch *gdbarch = get_objfile_arch (objfile);
11724   struct context_stack *newobj;
11725   CORE_ADDR lowpc, highpc;
11726   struct die_info *child_die;
11727   CORE_ADDR baseaddr;
11728
11729   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
11730
11731   /* Ignore blocks with missing or invalid low and high pc attributes.  */
11732   /* ??? Perhaps consider discontiguous blocks defined by DW_AT_ranges
11733      as multiple lexical blocks?  Handling children in a sane way would
11734      be nasty.  Might be easier to properly extend generic blocks to
11735      describe ranges.  */
11736   switch (dwarf2_get_pc_bounds (die, &lowpc, &highpc, cu, NULL))
11737     {
11738     case PC_BOUNDS_NOT_PRESENT:
11739       /* DW_TAG_lexical_block has no attributes, process its children as if
11740          there was no wrapping by that DW_TAG_lexical_block.
11741          GCC does no longer produces such DWARF since GCC r224161.  */
11742       for (child_die = die->child;
11743            child_die != NULL && child_die->tag;
11744            child_die = sibling_die (child_die))
11745         process_die (child_die, cu);
11746       return;
11747     case PC_BOUNDS_INVALID:
11748       return;
11749     }
11750   lowpc = gdbarch_adjust_dwarf2_addr (gdbarch, lowpc + baseaddr);
11751   highpc = gdbarch_adjust_dwarf2_addr (gdbarch, highpc + baseaddr);
11752
11753   push_context (0, lowpc);
11754   if (die->child != NULL)
11755     {
11756       child_die = die->child;
11757       while (child_die && child_die->tag)
11758         {
11759           process_die (child_die, cu);
11760           child_die = sibling_die (child_die);
11761         }
11762     }
11763   inherit_abstract_dies (die, cu);
11764   newobj = pop_context ();
11765
11766   if (local_symbols != NULL || local_using_directives != NULL)
11767     {
11768       struct block *block
11769         = finish_block (0, &local_symbols, newobj->old_blocks, NULL,
11770                         newobj->start_addr, highpc);
11771
11772       /* Note that recording ranges after traversing children, as we
11773          do here, means that recording a parent's ranges entails
11774          walking across all its children's ranges as they appear in
11775          the address map, which is quadratic behavior.
11776
11777          It would be nicer to record the parent's ranges before
11778          traversing its children, simply overriding whatever you find
11779          there.  But since we don't even decide whether to create a
11780          block until after we've traversed its children, that's hard
11781          to do.  */
11782       dwarf2_record_block_ranges (die, block, baseaddr, cu);
11783     }
11784   local_symbols = newobj->locals;
11785   local_using_directives = newobj->local_using_directives;
11786 }
11787
11788 /* Read in DW_TAG_call_site and insert it to CU->call_site_htab.  */
11789
11790 static void
11791 read_call_site_scope (struct die_info *die, struct dwarf2_cu *cu)
11792 {
11793   struct objfile *objfile = cu->objfile;
11794   struct gdbarch *gdbarch = get_objfile_arch (objfile);
11795   CORE_ADDR pc, baseaddr;
11796   struct attribute *attr;
11797   struct call_site *call_site, call_site_local;
11798   void **slot;
11799   int nparams;
11800   struct die_info *child_die;
11801
11802   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
11803
11804   attr = dwarf2_attr (die, DW_AT_call_return_pc, cu);
11805   if (attr == NULL)
11806     {
11807       /* This was a pre-DWARF-5 GNU extension alias
11808          for DW_AT_call_return_pc.  */
11809       attr = dwarf2_attr (die, DW_AT_low_pc, cu);
11810     }
11811   if (!attr)
11812     {
11813       complaint (&symfile_complaints,
11814                  _("missing DW_AT_call_return_pc for DW_TAG_call_site "
11815                    "DIE 0x%x [in module %s]"),
11816                  to_underlying (die->sect_off), objfile_name (objfile));
11817       return;
11818     }
11819   pc = attr_value_as_address (attr) + baseaddr;
11820   pc = gdbarch_adjust_dwarf2_addr (gdbarch, pc);
11821
11822   if (cu->call_site_htab == NULL)
11823     cu->call_site_htab = htab_create_alloc_ex (16, core_addr_hash, core_addr_eq,
11824                                                NULL, &objfile->objfile_obstack,
11825                                                hashtab_obstack_allocate, NULL);
11826   call_site_local.pc = pc;
11827   slot = htab_find_slot (cu->call_site_htab, &call_site_local, INSERT);
11828   if (*slot != NULL)
11829     {
11830       complaint (&symfile_complaints,
11831                  _("Duplicate PC %s for DW_TAG_call_site "
11832                    "DIE 0x%x [in module %s]"),
11833                  paddress (gdbarch, pc), to_underlying (die->sect_off),
11834                  objfile_name (objfile));
11835       return;
11836     }
11837
11838   /* Count parameters at the caller.  */
11839
11840   nparams = 0;
11841   for (child_die = die->child; child_die && child_die->tag;
11842        child_die = sibling_die (child_die))
11843     {
11844       if (child_die->tag != DW_TAG_call_site_parameter
11845           && child_die->tag != DW_TAG_GNU_call_site_parameter)
11846         {
11847           complaint (&symfile_complaints,
11848                      _("Tag %d is not DW_TAG_call_site_parameter in "
11849                        "DW_TAG_call_site child DIE 0x%x [in module %s]"),
11850                      child_die->tag, to_underlying (child_die->sect_off),
11851                      objfile_name (objfile));
11852           continue;
11853         }
11854
11855       nparams++;
11856     }
11857
11858   call_site
11859     = ((struct call_site *)
11860        obstack_alloc (&objfile->objfile_obstack,
11861                       sizeof (*call_site)
11862                       + (sizeof (*call_site->parameter) * (nparams - 1))));
11863   *slot = call_site;
11864   memset (call_site, 0, sizeof (*call_site) - sizeof (*call_site->parameter));
11865   call_site->pc = pc;
11866
11867   if (dwarf2_flag_true_p (die, DW_AT_call_tail_call, cu)
11868       || dwarf2_flag_true_p (die, DW_AT_GNU_tail_call, cu))
11869     {
11870       struct die_info *func_die;
11871
11872       /* Skip also over DW_TAG_inlined_subroutine.  */
11873       for (func_die = die->parent;
11874            func_die && func_die->tag != DW_TAG_subprogram
11875            && func_die->tag != DW_TAG_subroutine_type;
11876            func_die = func_die->parent);
11877
11878       /* DW_AT_call_all_calls is a superset
11879          of DW_AT_call_all_tail_calls.  */
11880       if (func_die
11881           && !dwarf2_flag_true_p (func_die, DW_AT_call_all_calls, cu)
11882           && !dwarf2_flag_true_p (func_die, DW_AT_GNU_all_call_sites, cu)
11883           && !dwarf2_flag_true_p (func_die, DW_AT_call_all_tail_calls, cu)
11884           && !dwarf2_flag_true_p (func_die, DW_AT_GNU_all_tail_call_sites, cu))
11885         {
11886           /* TYPE_TAIL_CALL_LIST is not interesting in functions where it is
11887              not complete.  But keep CALL_SITE for look ups via call_site_htab,
11888              both the initial caller containing the real return address PC and
11889              the final callee containing the current PC of a chain of tail
11890              calls do not need to have the tail call list complete.  But any
11891              function candidate for a virtual tail call frame searched via
11892              TYPE_TAIL_CALL_LIST must have the tail call list complete to be
11893              determined unambiguously.  */
11894         }
11895       else
11896         {
11897           struct type *func_type = NULL;
11898
11899           if (func_die)
11900             func_type = get_die_type (func_die, cu);
11901           if (func_type != NULL)
11902             {
11903               gdb_assert (TYPE_CODE (func_type) == TYPE_CODE_FUNC);
11904
11905               /* Enlist this call site to the function.  */
11906               call_site->tail_call_next = TYPE_TAIL_CALL_LIST (func_type);
11907               TYPE_TAIL_CALL_LIST (func_type) = call_site;
11908             }
11909           else
11910             complaint (&symfile_complaints,
11911                        _("Cannot find function owning DW_TAG_call_site "
11912                          "DIE 0x%x [in module %s]"),
11913                        to_underlying (die->sect_off), objfile_name (objfile));
11914         }
11915     }
11916
11917   attr = dwarf2_attr (die, DW_AT_call_target, cu);
11918   if (attr == NULL)
11919     attr = dwarf2_attr (die, DW_AT_GNU_call_site_target, cu);
11920   if (attr == NULL)
11921     attr = dwarf2_attr (die, DW_AT_call_origin, cu);
11922   if (attr == NULL)
11923     {
11924       /* This was a pre-DWARF-5 GNU extension alias for DW_AT_call_origin.  */
11925       attr = dwarf2_attr (die, DW_AT_abstract_origin, cu);
11926     }
11927   SET_FIELD_DWARF_BLOCK (call_site->target, NULL);
11928   if (!attr || (attr_form_is_block (attr) && DW_BLOCK (attr)->size == 0))
11929     /* Keep NULL DWARF_BLOCK.  */;
11930   else if (attr_form_is_block (attr))
11931     {
11932       struct dwarf2_locexpr_baton *dlbaton;
11933
11934       dlbaton = XOBNEW (&objfile->objfile_obstack, struct dwarf2_locexpr_baton);
11935       dlbaton->data = DW_BLOCK (attr)->data;
11936       dlbaton->size = DW_BLOCK (attr)->size;
11937       dlbaton->per_cu = cu->per_cu;
11938
11939       SET_FIELD_DWARF_BLOCK (call_site->target, dlbaton);
11940     }
11941   else if (attr_form_is_ref (attr))
11942     {
11943       struct dwarf2_cu *target_cu = cu;
11944       struct die_info *target_die;
11945
11946       target_die = follow_die_ref (die, attr, &target_cu);
11947       gdb_assert (target_cu->objfile == objfile);
11948       if (die_is_declaration (target_die, target_cu))
11949         {
11950           const char *target_physname;
11951
11952           /* Prefer the mangled name; otherwise compute the demangled one.  */
11953           target_physname = dwarf2_string_attr (target_die,
11954                                                 DW_AT_linkage_name,
11955                                                 target_cu);
11956           if (target_physname == NULL)
11957             target_physname = dwarf2_string_attr (target_die,
11958                                                  DW_AT_MIPS_linkage_name,
11959                                                  target_cu);
11960           if (target_physname == NULL)
11961             target_physname = dwarf2_physname (NULL, target_die, target_cu);
11962           if (target_physname == NULL)
11963             complaint (&symfile_complaints,
11964                        _("DW_AT_call_target target DIE has invalid "
11965                          "physname, for referencing DIE 0x%x [in module %s]"),
11966                        to_underlying (die->sect_off), objfile_name (objfile));
11967           else
11968             SET_FIELD_PHYSNAME (call_site->target, target_physname);
11969         }
11970       else
11971         {
11972           CORE_ADDR lowpc;
11973
11974           /* DW_AT_entry_pc should be preferred.  */
11975           if (dwarf2_get_pc_bounds (target_die, &lowpc, NULL, target_cu, NULL)
11976               <= PC_BOUNDS_INVALID)
11977             complaint (&symfile_complaints,
11978                        _("DW_AT_call_target target DIE has invalid "
11979                          "low pc, for referencing DIE 0x%x [in module %s]"),
11980                        to_underlying (die->sect_off), objfile_name (objfile));
11981           else
11982             {
11983               lowpc = gdbarch_adjust_dwarf2_addr (gdbarch, lowpc + baseaddr);
11984               SET_FIELD_PHYSADDR (call_site->target, lowpc);
11985             }
11986         }
11987     }
11988   else
11989     complaint (&symfile_complaints,
11990                _("DW_TAG_call_site DW_AT_call_target is neither "
11991                  "block nor reference, for DIE 0x%x [in module %s]"),
11992                to_underlying (die->sect_off), objfile_name (objfile));
11993
11994   call_site->per_cu = cu->per_cu;
11995
11996   for (child_die = die->child;
11997        child_die && child_die->tag;
11998        child_die = sibling_die (child_die))
11999     {
12000       struct call_site_parameter *parameter;
12001       struct attribute *loc, *origin;
12002
12003       if (child_die->tag != DW_TAG_call_site_parameter
12004           && child_die->tag != DW_TAG_GNU_call_site_parameter)
12005         {
12006           /* Already printed the complaint above.  */
12007           continue;
12008         }
12009
12010       gdb_assert (call_site->parameter_count < nparams);
12011       parameter = &call_site->parameter[call_site->parameter_count];
12012
12013       /* DW_AT_location specifies the register number or DW_AT_abstract_origin
12014          specifies DW_TAG_formal_parameter.  Value of the data assumed for the
12015          register is contained in DW_AT_call_value.  */
12016
12017       loc = dwarf2_attr (child_die, DW_AT_location, cu);
12018       origin = dwarf2_attr (child_die, DW_AT_call_parameter, cu);
12019       if (origin == NULL)
12020         {
12021           /* This was a pre-DWARF-5 GNU extension alias
12022              for DW_AT_call_parameter.  */
12023           origin = dwarf2_attr (child_die, DW_AT_abstract_origin, cu);
12024         }
12025       if (loc == NULL && origin != NULL && attr_form_is_ref (origin))
12026         {
12027           parameter->kind = CALL_SITE_PARAMETER_PARAM_OFFSET;
12028
12029           sect_offset sect_off
12030             = (sect_offset) dwarf2_get_ref_die_offset (origin);
12031           if (!offset_in_cu_p (&cu->header, sect_off))
12032             {
12033               /* As DW_OP_GNU_parameter_ref uses CU-relative offset this
12034                  binding can be done only inside one CU.  Such referenced DIE
12035                  therefore cannot be even moved to DW_TAG_partial_unit.  */
12036               complaint (&symfile_complaints,
12037                          _("DW_AT_call_parameter offset is not in CU for "
12038                            "DW_TAG_call_site child DIE 0x%x [in module %s]"),
12039                          to_underlying (child_die->sect_off),
12040                          objfile_name (objfile));
12041               continue;
12042             }
12043           parameter->u.param_cu_off
12044             = (cu_offset) (sect_off - cu->header.sect_off);
12045         }
12046       else if (loc == NULL || origin != NULL || !attr_form_is_block (loc))
12047         {
12048           complaint (&symfile_complaints,
12049                      _("No DW_FORM_block* DW_AT_location for "
12050                        "DW_TAG_call_site child DIE 0x%x [in module %s]"),
12051                      to_underlying (child_die->sect_off), objfile_name (objfile));
12052           continue;
12053         }
12054       else
12055         {
12056           parameter->u.dwarf_reg = dwarf_block_to_dwarf_reg
12057             (DW_BLOCK (loc)->data, &DW_BLOCK (loc)->data[DW_BLOCK (loc)->size]);
12058           if (parameter->u.dwarf_reg != -1)
12059             parameter->kind = CALL_SITE_PARAMETER_DWARF_REG;
12060           else if (dwarf_block_to_sp_offset (gdbarch, DW_BLOCK (loc)->data,
12061                                     &DW_BLOCK (loc)->data[DW_BLOCK (loc)->size],
12062                                              &parameter->u.fb_offset))
12063             parameter->kind = CALL_SITE_PARAMETER_FB_OFFSET;
12064           else
12065             {
12066               complaint (&symfile_complaints,
12067                          _("Only single DW_OP_reg or DW_OP_fbreg is supported "
12068                            "for DW_FORM_block* DW_AT_location is supported for "
12069                            "DW_TAG_call_site child DIE 0x%x "
12070                            "[in module %s]"),
12071                          to_underlying (child_die->sect_off),
12072                          objfile_name (objfile));
12073               continue;
12074             }
12075         }
12076
12077       attr = dwarf2_attr (child_die, DW_AT_call_value, cu);
12078       if (attr == NULL)
12079         attr = dwarf2_attr (child_die, DW_AT_GNU_call_site_value, cu);
12080       if (!attr_form_is_block (attr))
12081         {
12082           complaint (&symfile_complaints,
12083                      _("No DW_FORM_block* DW_AT_call_value for "
12084                        "DW_TAG_call_site child DIE 0x%x [in module %s]"),
12085                      to_underlying (child_die->sect_off),
12086                      objfile_name (objfile));
12087           continue;
12088         }
12089       parameter->value = DW_BLOCK (attr)->data;
12090       parameter->value_size = DW_BLOCK (attr)->size;
12091
12092       /* Parameters are not pre-cleared by memset above.  */
12093       parameter->data_value = NULL;
12094       parameter->data_value_size = 0;
12095       call_site->parameter_count++;
12096
12097       attr = dwarf2_attr (child_die, DW_AT_call_data_value, cu);
12098       if (attr == NULL)
12099         attr = dwarf2_attr (child_die, DW_AT_GNU_call_site_data_value, cu);
12100       if (attr)
12101         {
12102           if (!attr_form_is_block (attr))
12103             complaint (&symfile_complaints,
12104                        _("No DW_FORM_block* DW_AT_call_data_value for "
12105                          "DW_TAG_call_site child DIE 0x%x [in module %s]"),
12106                        to_underlying (child_die->sect_off),
12107                        objfile_name (objfile));
12108           else
12109             {
12110               parameter->data_value = DW_BLOCK (attr)->data;
12111               parameter->data_value_size = DW_BLOCK (attr)->size;
12112             }
12113         }
12114     }
12115 }
12116
12117 /* Call CALLBACK from DW_AT_ranges attribute value OFFSET
12118    reading .debug_rnglists.
12119    Callback's type should be:
12120     void (CORE_ADDR range_beginning, CORE_ADDR range_end)
12121    Return true if the attributes are present and valid, otherwise,
12122    return false.  */
12123
12124 template <typename Callback>
12125 static bool
12126 dwarf2_rnglists_process (unsigned offset, struct dwarf2_cu *cu,
12127                          Callback &&callback)
12128 {
12129   struct objfile *objfile = cu->objfile;
12130   struct gdbarch *gdbarch = get_objfile_arch (objfile);
12131   struct comp_unit_head *cu_header = &cu->header;
12132   bfd *obfd = objfile->obfd;
12133   unsigned int addr_size = cu_header->addr_size;
12134   CORE_ADDR mask = ~(~(CORE_ADDR)1 << (addr_size * 8 - 1));
12135   /* Base address selection entry.  */
12136   CORE_ADDR base;
12137   int found_base;
12138   unsigned int dummy;
12139   const gdb_byte *buffer;
12140   CORE_ADDR low = 0;
12141   CORE_ADDR high = 0;
12142   CORE_ADDR baseaddr;
12143   bool overflow = false;
12144
12145   found_base = cu->base_known;
12146   base = cu->base_address;
12147
12148   dwarf2_read_section (objfile, &dwarf2_per_objfile->rnglists);
12149   if (offset >= dwarf2_per_objfile->rnglists.size)
12150     {
12151       complaint (&symfile_complaints,
12152                  _("Offset %d out of bounds for DW_AT_ranges attribute"),
12153                  offset);
12154       return false;
12155     }
12156   buffer = dwarf2_per_objfile->rnglists.buffer + offset;
12157
12158   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
12159
12160   while (1)
12161     {
12162       /* Initialize it due to a false compiler warning.  */
12163       CORE_ADDR range_beginning = 0, range_end = 0;
12164       const gdb_byte *buf_end = (dwarf2_per_objfile->rnglists.buffer
12165                                  + dwarf2_per_objfile->rnglists.size);
12166       unsigned int bytes_read;
12167
12168       if (buffer == buf_end)
12169         {
12170           overflow = true;
12171           break;
12172         }
12173       const auto rlet = static_cast<enum dwarf_range_list_entry>(*buffer++);
12174       switch (rlet)
12175         {
12176         case DW_RLE_end_of_list:
12177           break;
12178         case DW_RLE_base_address:
12179           if (buffer + cu->header.addr_size > buf_end)
12180             {
12181               overflow = true;
12182               break;
12183             }
12184           base = read_address (obfd, buffer, cu, &bytes_read);
12185           found_base = 1;
12186           buffer += bytes_read;
12187           break;
12188         case DW_RLE_start_length:
12189           if (buffer + cu->header.addr_size > buf_end)
12190             {
12191               overflow = true;
12192               break;
12193             }
12194           range_beginning = read_address (obfd, buffer, cu, &bytes_read);
12195           buffer += bytes_read;
12196           range_end = (range_beginning
12197                        + read_unsigned_leb128 (obfd, buffer, &bytes_read));
12198           buffer += bytes_read;
12199           if (buffer > buf_end)
12200             {
12201               overflow = true;
12202               break;
12203             }
12204           break;
12205         case DW_RLE_offset_pair:
12206           range_beginning = read_unsigned_leb128 (obfd, buffer, &bytes_read);
12207           buffer += bytes_read;
12208           if (buffer > buf_end)
12209             {
12210               overflow = true;
12211               break;
12212             }
12213           range_end = read_unsigned_leb128 (obfd, buffer, &bytes_read);
12214           buffer += bytes_read;
12215           if (buffer > buf_end)
12216             {
12217               overflow = true;
12218               break;
12219             }
12220           break;
12221         case DW_RLE_start_end:
12222           if (buffer + 2 * cu->header.addr_size > buf_end)
12223             {
12224               overflow = true;
12225               break;
12226             }
12227           range_beginning = read_address (obfd, buffer, cu, &bytes_read);
12228           buffer += bytes_read;
12229           range_end = read_address (obfd, buffer, cu, &bytes_read);
12230           buffer += bytes_read;
12231           break;
12232         default:
12233           complaint (&symfile_complaints,
12234                      _("Invalid .debug_rnglists data (no base address)"));
12235           return false;
12236         }
12237       if (rlet == DW_RLE_end_of_list || overflow)
12238         break;
12239       if (rlet == DW_RLE_base_address)
12240         continue;
12241
12242       if (!found_base)
12243         {
12244           /* We have no valid base address for the ranges
12245              data.  */
12246           complaint (&symfile_complaints,
12247                      _("Invalid .debug_rnglists data (no base address)"));
12248           return false;
12249         }
12250
12251       if (range_beginning > range_end)
12252         {
12253           /* Inverted range entries are invalid.  */
12254           complaint (&symfile_complaints,
12255                      _("Invalid .debug_rnglists data (inverted range)"));
12256           return false;
12257         }
12258
12259       /* Empty range entries have no effect.  */
12260       if (range_beginning == range_end)
12261         continue;
12262
12263       range_beginning += base;
12264       range_end += base;
12265
12266       /* A not-uncommon case of bad debug info.
12267          Don't pollute the addrmap with bad data.  */
12268       if (range_beginning + baseaddr == 0
12269           && !dwarf2_per_objfile->has_section_at_zero)
12270         {
12271           complaint (&symfile_complaints,
12272                      _(".debug_rnglists entry has start address of zero"
12273                        " [in module %s]"), objfile_name (objfile));
12274           continue;
12275         }
12276
12277       callback (range_beginning, range_end);
12278     }
12279
12280   if (overflow)
12281     {
12282       complaint (&symfile_complaints,
12283                  _("Offset %d is not terminated "
12284                    "for DW_AT_ranges attribute"),
12285                  offset);
12286       return false;
12287     }
12288
12289   return true;
12290 }
12291
12292 /* Call CALLBACK from DW_AT_ranges attribute value OFFSET reading .debug_ranges.
12293    Callback's type should be:
12294     void (CORE_ADDR range_beginning, CORE_ADDR range_end)
12295    Return 1 if the attributes are present and valid, otherwise, return 0.  */
12296
12297 template <typename Callback>
12298 static int
12299 dwarf2_ranges_process (unsigned offset, struct dwarf2_cu *cu,
12300                        Callback &&callback)
12301 {
12302   struct objfile *objfile = cu->objfile;
12303   struct gdbarch *gdbarch = get_objfile_arch (objfile);
12304   struct comp_unit_head *cu_header = &cu->header;
12305   bfd *obfd = objfile->obfd;
12306   unsigned int addr_size = cu_header->addr_size;
12307   CORE_ADDR mask = ~(~(CORE_ADDR)1 << (addr_size * 8 - 1));
12308   /* Base address selection entry.  */
12309   CORE_ADDR base;
12310   int found_base;
12311   unsigned int dummy;
12312   const gdb_byte *buffer;
12313   CORE_ADDR baseaddr;
12314
12315   if (cu_header->version >= 5)
12316     return dwarf2_rnglists_process (offset, cu, callback);
12317
12318   found_base = cu->base_known;
12319   base = cu->base_address;
12320
12321   dwarf2_read_section (objfile, &dwarf2_per_objfile->ranges);
12322   if (offset >= dwarf2_per_objfile->ranges.size)
12323     {
12324       complaint (&symfile_complaints,
12325                  _("Offset %d out of bounds for DW_AT_ranges attribute"),
12326                  offset);
12327       return 0;
12328     }
12329   buffer = dwarf2_per_objfile->ranges.buffer + offset;
12330
12331   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
12332
12333   while (1)
12334     {
12335       CORE_ADDR range_beginning, range_end;
12336
12337       range_beginning = read_address (obfd, buffer, cu, &dummy);
12338       buffer += addr_size;
12339       range_end = read_address (obfd, buffer, cu, &dummy);
12340       buffer += addr_size;
12341       offset += 2 * addr_size;
12342
12343       /* An end of list marker is a pair of zero addresses.  */
12344       if (range_beginning == 0 && range_end == 0)
12345         /* Found the end of list entry.  */
12346         break;
12347
12348       /* Each base address selection entry is a pair of 2 values.
12349          The first is the largest possible address, the second is
12350          the base address.  Check for a base address here.  */
12351       if ((range_beginning & mask) == mask)
12352         {
12353           /* If we found the largest possible address, then we already
12354              have the base address in range_end.  */
12355           base = range_end;
12356           found_base = 1;
12357           continue;
12358         }
12359
12360       if (!found_base)
12361         {
12362           /* We have no valid base address for the ranges
12363              data.  */
12364           complaint (&symfile_complaints,
12365                      _("Invalid .debug_ranges data (no base address)"));
12366           return 0;
12367         }
12368
12369       if (range_beginning > range_end)
12370         {
12371           /* Inverted range entries are invalid.  */
12372           complaint (&symfile_complaints,
12373                      _("Invalid .debug_ranges data (inverted range)"));
12374           return 0;
12375         }
12376
12377       /* Empty range entries have no effect.  */
12378       if (range_beginning == range_end)
12379         continue;
12380
12381       range_beginning += base;
12382       range_end += base;
12383
12384       /* A not-uncommon case of bad debug info.
12385          Don't pollute the addrmap with bad data.  */
12386       if (range_beginning + baseaddr == 0
12387           && !dwarf2_per_objfile->has_section_at_zero)
12388         {
12389           complaint (&symfile_complaints,
12390                      _(".debug_ranges entry has start address of zero"
12391                        " [in module %s]"), objfile_name (objfile));
12392           continue;
12393         }
12394
12395       callback (range_beginning, range_end);
12396     }
12397
12398   return 1;
12399 }
12400
12401 /* Get low and high pc attributes from DW_AT_ranges attribute value OFFSET.
12402    Return 1 if the attributes are present and valid, otherwise, return 0.
12403    If RANGES_PST is not NULL we should setup `objfile->psymtabs_addrmap'.  */
12404
12405 static int
12406 dwarf2_ranges_read (unsigned offset, CORE_ADDR *low_return,
12407                     CORE_ADDR *high_return, struct dwarf2_cu *cu,
12408                     struct partial_symtab *ranges_pst)
12409 {
12410   struct objfile *objfile = cu->objfile;
12411   struct gdbarch *gdbarch = get_objfile_arch (objfile);
12412   const CORE_ADDR baseaddr = ANOFFSET (objfile->section_offsets,
12413                                        SECT_OFF_TEXT (objfile));
12414   int low_set = 0;
12415   CORE_ADDR low = 0;
12416   CORE_ADDR high = 0;
12417   int retval;
12418
12419   retval = dwarf2_ranges_process (offset, cu,
12420     [&] (CORE_ADDR range_beginning, CORE_ADDR range_end)
12421     {
12422       if (ranges_pst != NULL)
12423         {
12424           CORE_ADDR lowpc;
12425           CORE_ADDR highpc;
12426
12427           lowpc = gdbarch_adjust_dwarf2_addr (gdbarch,
12428                                               range_beginning + baseaddr);
12429           highpc = gdbarch_adjust_dwarf2_addr (gdbarch,
12430                                                range_end + baseaddr);
12431           addrmap_set_empty (objfile->psymtabs_addrmap, lowpc, highpc - 1,
12432                              ranges_pst);
12433         }
12434
12435       /* FIXME: This is recording everything as a low-high
12436          segment of consecutive addresses.  We should have a
12437          data structure for discontiguous block ranges
12438          instead.  */
12439       if (! low_set)
12440         {
12441           low = range_beginning;
12442           high = range_end;
12443           low_set = 1;
12444         }
12445       else
12446         {
12447           if (range_beginning < low)
12448             low = range_beginning;
12449           if (range_end > high)
12450             high = range_end;
12451         }
12452     });
12453   if (!retval)
12454     return 0;
12455
12456   if (! low_set)
12457     /* If the first entry is an end-of-list marker, the range
12458        describes an empty scope, i.e. no instructions.  */
12459     return 0;
12460
12461   if (low_return)
12462     *low_return = low;
12463   if (high_return)
12464     *high_return = high;
12465   return 1;
12466 }
12467
12468 /* Get low and high pc attributes from a die.  See enum pc_bounds_kind
12469    definition for the return value.  *LOWPC and *HIGHPC are set iff
12470    neither PC_BOUNDS_NOT_PRESENT nor PC_BOUNDS_INVALID are returned.  */
12471
12472 static enum pc_bounds_kind
12473 dwarf2_get_pc_bounds (struct die_info *die, CORE_ADDR *lowpc,
12474                       CORE_ADDR *highpc, struct dwarf2_cu *cu,
12475                       struct partial_symtab *pst)
12476 {
12477   struct attribute *attr;
12478   struct attribute *attr_high;
12479   CORE_ADDR low = 0;
12480   CORE_ADDR high = 0;
12481   enum pc_bounds_kind ret;
12482
12483   attr_high = dwarf2_attr (die, DW_AT_high_pc, cu);
12484   if (attr_high)
12485     {
12486       attr = dwarf2_attr (die, DW_AT_low_pc, cu);
12487       if (attr)
12488         {
12489           low = attr_value_as_address (attr);
12490           high = attr_value_as_address (attr_high);
12491           if (cu->header.version >= 4 && attr_form_is_constant (attr_high))
12492             high += low;
12493         }
12494       else
12495         /* Found high w/o low attribute.  */
12496         return PC_BOUNDS_INVALID;
12497
12498       /* Found consecutive range of addresses.  */
12499       ret = PC_BOUNDS_HIGH_LOW;
12500     }
12501   else
12502     {
12503       attr = dwarf2_attr (die, DW_AT_ranges, cu);
12504       if (attr != NULL)
12505         {
12506           /* DW_AT_ranges_base does not apply to DIEs from the DWO skeleton.
12507              We take advantage of the fact that DW_AT_ranges does not appear
12508              in DW_TAG_compile_unit of DWO files.  */
12509           int need_ranges_base = die->tag != DW_TAG_compile_unit;
12510           unsigned int ranges_offset = (DW_UNSND (attr)
12511                                         + (need_ranges_base
12512                                            ? cu->ranges_base
12513                                            : 0));
12514
12515           /* Value of the DW_AT_ranges attribute is the offset in the
12516              .debug_ranges section.  */
12517           if (!dwarf2_ranges_read (ranges_offset, &low, &high, cu, pst))
12518             return PC_BOUNDS_INVALID;
12519           /* Found discontinuous range of addresses.  */
12520           ret = PC_BOUNDS_RANGES;
12521         }
12522       else
12523         return PC_BOUNDS_NOT_PRESENT;
12524     }
12525
12526   /* read_partial_die has also the strict LOW < HIGH requirement.  */
12527   if (high <= low)
12528     return PC_BOUNDS_INVALID;
12529
12530   /* When using the GNU linker, .gnu.linkonce. sections are used to
12531      eliminate duplicate copies of functions and vtables and such.
12532      The linker will arbitrarily choose one and discard the others.
12533      The AT_*_pc values for such functions refer to local labels in
12534      these sections.  If the section from that file was discarded, the
12535      labels are not in the output, so the relocs get a value of 0.
12536      If this is a discarded function, mark the pc bounds as invalid,
12537      so that GDB will ignore it.  */
12538   if (low == 0 && !dwarf2_per_objfile->has_section_at_zero)
12539     return PC_BOUNDS_INVALID;
12540
12541   *lowpc = low;
12542   if (highpc)
12543     *highpc = high;
12544   return ret;
12545 }
12546
12547 /* Assuming that DIE represents a subprogram DIE or a lexical block, get
12548    its low and high PC addresses.  Do nothing if these addresses could not
12549    be determined.  Otherwise, set LOWPC to the low address if it is smaller,
12550    and HIGHPC to the high address if greater than HIGHPC.  */
12551
12552 static void
12553 dwarf2_get_subprogram_pc_bounds (struct die_info *die,
12554                                  CORE_ADDR *lowpc, CORE_ADDR *highpc,
12555                                  struct dwarf2_cu *cu)
12556 {
12557   CORE_ADDR low, high;
12558   struct die_info *child = die->child;
12559
12560   if (dwarf2_get_pc_bounds (die, &low, &high, cu, NULL) >= PC_BOUNDS_RANGES)
12561     {
12562       *lowpc = std::min (*lowpc, low);
12563       *highpc = std::max (*highpc, high);
12564     }
12565
12566   /* If the language does not allow nested subprograms (either inside
12567      subprograms or lexical blocks), we're done.  */
12568   if (cu->language != language_ada)
12569     return;
12570
12571   /* Check all the children of the given DIE.  If it contains nested
12572      subprograms, then check their pc bounds.  Likewise, we need to
12573      check lexical blocks as well, as they may also contain subprogram
12574      definitions.  */
12575   while (child && child->tag)
12576     {
12577       if (child->tag == DW_TAG_subprogram
12578           || child->tag == DW_TAG_lexical_block)
12579         dwarf2_get_subprogram_pc_bounds (child, lowpc, highpc, cu);
12580       child = sibling_die (child);
12581     }
12582 }
12583
12584 /* Get the low and high pc's represented by the scope DIE, and store
12585    them in *LOWPC and *HIGHPC.  If the correct values can't be
12586    determined, set *LOWPC to -1 and *HIGHPC to 0.  */
12587
12588 static void
12589 get_scope_pc_bounds (struct die_info *die,
12590                      CORE_ADDR *lowpc, CORE_ADDR *highpc,
12591                      struct dwarf2_cu *cu)
12592 {
12593   CORE_ADDR best_low = (CORE_ADDR) -1;
12594   CORE_ADDR best_high = (CORE_ADDR) 0;
12595   CORE_ADDR current_low, current_high;
12596
12597   if (dwarf2_get_pc_bounds (die, &current_low, &current_high, cu, NULL)
12598       >= PC_BOUNDS_RANGES)
12599     {
12600       best_low = current_low;
12601       best_high = current_high;
12602     }
12603   else
12604     {
12605       struct die_info *child = die->child;
12606
12607       while (child && child->tag)
12608         {
12609           switch (child->tag) {
12610           case DW_TAG_subprogram:
12611             dwarf2_get_subprogram_pc_bounds (child, &best_low, &best_high, cu);
12612             break;
12613           case DW_TAG_namespace:
12614           case DW_TAG_module:
12615             /* FIXME: carlton/2004-01-16: Should we do this for
12616                DW_TAG_class_type/DW_TAG_structure_type, too?  I think
12617                that current GCC's always emit the DIEs corresponding
12618                to definitions of methods of classes as children of a
12619                DW_TAG_compile_unit or DW_TAG_namespace (as opposed to
12620                the DIEs giving the declarations, which could be
12621                anywhere).  But I don't see any reason why the
12622                standards says that they have to be there.  */
12623             get_scope_pc_bounds (child, &current_low, &current_high, cu);
12624
12625             if (current_low != ((CORE_ADDR) -1))
12626               {
12627                 best_low = std::min (best_low, current_low);
12628                 best_high = std::max (best_high, current_high);
12629               }
12630             break;
12631           default:
12632             /* Ignore.  */
12633             break;
12634           }
12635
12636           child = sibling_die (child);
12637         }
12638     }
12639
12640   *lowpc = best_low;
12641   *highpc = best_high;
12642 }
12643
12644 /* Record the address ranges for BLOCK, offset by BASEADDR, as given
12645    in DIE.  */
12646
12647 static void
12648 dwarf2_record_block_ranges (struct die_info *die, struct block *block,
12649                             CORE_ADDR baseaddr, struct dwarf2_cu *cu)
12650 {
12651   struct objfile *objfile = cu->objfile;
12652   struct gdbarch *gdbarch = get_objfile_arch (objfile);
12653   struct attribute *attr;
12654   struct attribute *attr_high;
12655
12656   attr_high = dwarf2_attr (die, DW_AT_high_pc, cu);
12657   if (attr_high)
12658     {
12659       attr = dwarf2_attr (die, DW_AT_low_pc, cu);
12660       if (attr)
12661         {
12662           CORE_ADDR low = attr_value_as_address (attr);
12663           CORE_ADDR high = attr_value_as_address (attr_high);
12664
12665           if (cu->header.version >= 4 && attr_form_is_constant (attr_high))
12666             high += low;
12667
12668           low = gdbarch_adjust_dwarf2_addr (gdbarch, low + baseaddr);
12669           high = gdbarch_adjust_dwarf2_addr (gdbarch, high + baseaddr);
12670           record_block_range (block, low, high - 1);
12671         }
12672     }
12673
12674   attr = dwarf2_attr (die, DW_AT_ranges, cu);
12675   if (attr)
12676     {
12677       bfd *obfd = objfile->obfd;
12678       /* DW_AT_ranges_base does not apply to DIEs from the DWO skeleton.
12679          We take advantage of the fact that DW_AT_ranges does not appear
12680          in DW_TAG_compile_unit of DWO files.  */
12681       int need_ranges_base = die->tag != DW_TAG_compile_unit;
12682
12683       /* The value of the DW_AT_ranges attribute is the offset of the
12684          address range list in the .debug_ranges section.  */
12685       unsigned long offset = (DW_UNSND (attr)
12686                               + (need_ranges_base ? cu->ranges_base : 0));
12687       const gdb_byte *buffer;
12688
12689       /* For some target architectures, but not others, the
12690          read_address function sign-extends the addresses it returns.
12691          To recognize base address selection entries, we need a
12692          mask.  */
12693       unsigned int addr_size = cu->header.addr_size;
12694       CORE_ADDR base_select_mask = ~(~(CORE_ADDR)1 << (addr_size * 8 - 1));
12695
12696       /* The base address, to which the next pair is relative.  Note
12697          that this 'base' is a DWARF concept: most entries in a range
12698          list are relative, to reduce the number of relocs against the
12699          debugging information.  This is separate from this function's
12700          'baseaddr' argument, which GDB uses to relocate debugging
12701          information from a shared library based on the address at
12702          which the library was loaded.  */
12703       CORE_ADDR base = cu->base_address;
12704       int base_known = cu->base_known;
12705
12706       dwarf2_ranges_process (offset, cu,
12707         [&] (CORE_ADDR start, CORE_ADDR end)
12708         {
12709           start += baseaddr;
12710           end += baseaddr;
12711           start = gdbarch_adjust_dwarf2_addr (gdbarch, start);
12712           end = gdbarch_adjust_dwarf2_addr (gdbarch, end);
12713           record_block_range (block, start, end - 1);
12714         });
12715     }
12716 }
12717
12718 /* Check whether the producer field indicates either of GCC < 4.6, or the
12719    Intel C/C++ compiler, and cache the result in CU.  */
12720
12721 static void
12722 check_producer (struct dwarf2_cu *cu)
12723 {
12724   int major, minor;
12725
12726   if (cu->producer == NULL)
12727     {
12728       /* For unknown compilers expect their behavior is DWARF version
12729          compliant.
12730
12731          GCC started to support .debug_types sections by -gdwarf-4 since
12732          gcc-4.5.x.  As the .debug_types sections are missing DW_AT_producer
12733          for their space efficiency GDB cannot workaround gcc-4.5.x -gdwarf-4
12734          combination.  gcc-4.5.x -gdwarf-4 binaries have DW_AT_accessibility
12735          interpreted incorrectly by GDB now - GCC PR debug/48229.  */
12736     }
12737   else if (producer_is_gcc (cu->producer, &major, &minor))
12738     {
12739       cu->producer_is_gxx_lt_4_6 = major < 4 || (major == 4 && minor < 6);
12740       cu->producer_is_gcc_lt_4_3 = major < 4 || (major == 4 && minor < 3);
12741     }
12742   else if (startswith (cu->producer, "Intel(R) C"))
12743     cu->producer_is_icc = 1;
12744   else
12745     {
12746       /* For other non-GCC compilers, expect their behavior is DWARF version
12747          compliant.  */
12748     }
12749
12750   cu->checked_producer = 1;
12751 }
12752
12753 /* Check for GCC PR debug/45124 fix which is not present in any G++ version up
12754    to 4.5.any while it is present already in G++ 4.6.0 - the PR has been fixed
12755    during 4.6.0 experimental.  */
12756
12757 static int
12758 producer_is_gxx_lt_4_6 (struct dwarf2_cu *cu)
12759 {
12760   if (!cu->checked_producer)
12761     check_producer (cu);
12762
12763   return cu->producer_is_gxx_lt_4_6;
12764 }
12765
12766 /* Return the default accessibility type if it is not overriden by
12767    DW_AT_accessibility.  */
12768
12769 static enum dwarf_access_attribute
12770 dwarf2_default_access_attribute (struct die_info *die, struct dwarf2_cu *cu)
12771 {
12772   if (cu->header.version < 3 || producer_is_gxx_lt_4_6 (cu))
12773     {
12774       /* The default DWARF 2 accessibility for members is public, the default
12775          accessibility for inheritance is private.  */
12776
12777       if (die->tag != DW_TAG_inheritance)
12778         return DW_ACCESS_public;
12779       else
12780         return DW_ACCESS_private;
12781     }
12782   else
12783     {
12784       /* DWARF 3+ defines the default accessibility a different way.  The same
12785          rules apply now for DW_TAG_inheritance as for the members and it only
12786          depends on the container kind.  */
12787
12788       if (die->parent->tag == DW_TAG_class_type)
12789         return DW_ACCESS_private;
12790       else
12791         return DW_ACCESS_public;
12792     }
12793 }
12794
12795 /* Look for DW_AT_data_member_location.  Set *OFFSET to the byte
12796    offset.  If the attribute was not found return 0, otherwise return
12797    1.  If it was found but could not properly be handled, set *OFFSET
12798    to 0.  */
12799
12800 static int
12801 handle_data_member_location (struct die_info *die, struct dwarf2_cu *cu,
12802                              LONGEST *offset)
12803 {
12804   struct attribute *attr;
12805
12806   attr = dwarf2_attr (die, DW_AT_data_member_location, cu);
12807   if (attr != NULL)
12808     {
12809       *offset = 0;
12810
12811       /* Note that we do not check for a section offset first here.
12812          This is because DW_AT_data_member_location is new in DWARF 4,
12813          so if we see it, we can assume that a constant form is really
12814          a constant and not a section offset.  */
12815       if (attr_form_is_constant (attr))
12816         *offset = dwarf2_get_attr_constant_value (attr, 0);
12817       else if (attr_form_is_section_offset (attr))
12818         dwarf2_complex_location_expr_complaint ();
12819       else if (attr_form_is_block (attr))
12820         *offset = decode_locdesc (DW_BLOCK (attr), cu);
12821       else
12822         dwarf2_complex_location_expr_complaint ();
12823
12824       return 1;
12825     }
12826
12827   return 0;
12828 }
12829
12830 /* Add an aggregate field to the field list.  */
12831
12832 static void
12833 dwarf2_add_field (struct field_info *fip, struct die_info *die,
12834                   struct dwarf2_cu *cu)
12835 {
12836   struct objfile *objfile = cu->objfile;
12837   struct gdbarch *gdbarch = get_objfile_arch (objfile);
12838   struct nextfield *new_field;
12839   struct attribute *attr;
12840   struct field *fp;
12841   const char *fieldname = "";
12842
12843   /* Allocate a new field list entry and link it in.  */
12844   new_field = XNEW (struct nextfield);
12845   make_cleanup (xfree, new_field);
12846   memset (new_field, 0, sizeof (struct nextfield));
12847
12848   if (die->tag == DW_TAG_inheritance)
12849     {
12850       new_field->next = fip->baseclasses;
12851       fip->baseclasses = new_field;
12852     }
12853   else
12854     {
12855       new_field->next = fip->fields;
12856       fip->fields = new_field;
12857     }
12858   fip->nfields++;
12859
12860   attr = dwarf2_attr (die, DW_AT_accessibility, cu);
12861   if (attr)
12862     new_field->accessibility = DW_UNSND (attr);
12863   else
12864     new_field->accessibility = dwarf2_default_access_attribute (die, cu);
12865   if (new_field->accessibility != DW_ACCESS_public)
12866     fip->non_public_fields = 1;
12867
12868   attr = dwarf2_attr (die, DW_AT_virtuality, cu);
12869   if (attr)
12870     new_field->virtuality = DW_UNSND (attr);
12871   else
12872     new_field->virtuality = DW_VIRTUALITY_none;
12873
12874   fp = &new_field->field;
12875
12876   if (die->tag == DW_TAG_member && ! die_is_declaration (die, cu))
12877     {
12878       LONGEST offset;
12879
12880       /* Data member other than a C++ static data member.  */
12881
12882       /* Get type of field.  */
12883       fp->type = die_type (die, cu);
12884
12885       SET_FIELD_BITPOS (*fp, 0);
12886
12887       /* Get bit size of field (zero if none).  */
12888       attr = dwarf2_attr (die, DW_AT_bit_size, cu);
12889       if (attr)
12890         {
12891           FIELD_BITSIZE (*fp) = DW_UNSND (attr);
12892         }
12893       else
12894         {
12895           FIELD_BITSIZE (*fp) = 0;
12896         }
12897
12898       /* Get bit offset of field.  */
12899       if (handle_data_member_location (die, cu, &offset))
12900         SET_FIELD_BITPOS (*fp, offset * bits_per_byte);
12901       attr = dwarf2_attr (die, DW_AT_bit_offset, cu);
12902       if (attr)
12903         {
12904           if (gdbarch_bits_big_endian (gdbarch))
12905             {
12906               /* For big endian bits, the DW_AT_bit_offset gives the
12907                  additional bit offset from the MSB of the containing
12908                  anonymous object to the MSB of the field.  We don't
12909                  have to do anything special since we don't need to
12910                  know the size of the anonymous object.  */
12911               SET_FIELD_BITPOS (*fp, FIELD_BITPOS (*fp) + DW_UNSND (attr));
12912             }
12913           else
12914             {
12915               /* For little endian bits, compute the bit offset to the
12916                  MSB of the anonymous object, subtract off the number of
12917                  bits from the MSB of the field to the MSB of the
12918                  object, and then subtract off the number of bits of
12919                  the field itself.  The result is the bit offset of
12920                  the LSB of the field.  */
12921               int anonymous_size;
12922               int bit_offset = DW_UNSND (attr);
12923
12924               attr = dwarf2_attr (die, DW_AT_byte_size, cu);
12925               if (attr)
12926                 {
12927                   /* The size of the anonymous object containing
12928                      the bit field is explicit, so use the
12929                      indicated size (in bytes).  */
12930                   anonymous_size = DW_UNSND (attr);
12931                 }
12932               else
12933                 {
12934                   /* The size of the anonymous object containing
12935                      the bit field must be inferred from the type
12936                      attribute of the data member containing the
12937                      bit field.  */
12938                   anonymous_size = TYPE_LENGTH (fp->type);
12939                 }
12940               SET_FIELD_BITPOS (*fp,
12941                                 (FIELD_BITPOS (*fp)
12942                                  + anonymous_size * bits_per_byte
12943                                  - bit_offset - FIELD_BITSIZE (*fp)));
12944             }
12945         }
12946       attr = dwarf2_attr (die, DW_AT_data_bit_offset, cu);
12947       if (attr != NULL)
12948         SET_FIELD_BITPOS (*fp, (FIELD_BITPOS (*fp)
12949                                 + dwarf2_get_attr_constant_value (attr, 0)));
12950
12951       /* Get name of field.  */
12952       fieldname = dwarf2_name (die, cu);
12953       if (fieldname == NULL)
12954         fieldname = "";
12955
12956       /* The name is already allocated along with this objfile, so we don't
12957          need to duplicate it for the type.  */
12958       fp->name = fieldname;
12959
12960       /* Change accessibility for artificial fields (e.g. virtual table
12961          pointer or virtual base class pointer) to private.  */
12962       if (dwarf2_attr (die, DW_AT_artificial, cu))
12963         {
12964           FIELD_ARTIFICIAL (*fp) = 1;
12965           new_field->accessibility = DW_ACCESS_private;
12966           fip->non_public_fields = 1;
12967         }
12968     }
12969   else if (die->tag == DW_TAG_member || die->tag == DW_TAG_variable)
12970     {
12971       /* C++ static member.  */
12972
12973       /* NOTE: carlton/2002-11-05: It should be a DW_TAG_member that
12974          is a declaration, but all versions of G++ as of this writing
12975          (so through at least 3.2.1) incorrectly generate
12976          DW_TAG_variable tags.  */
12977
12978       const char *physname;
12979
12980       /* Get name of field.  */
12981       fieldname = dwarf2_name (die, cu);
12982       if (fieldname == NULL)
12983         return;
12984
12985       attr = dwarf2_attr (die, DW_AT_const_value, cu);
12986       if (attr
12987           /* Only create a symbol if this is an external value.
12988              new_symbol checks this and puts the value in the global symbol
12989              table, which we want.  If it is not external, new_symbol
12990              will try to put the value in cu->list_in_scope which is wrong.  */
12991           && dwarf2_flag_true_p (die, DW_AT_external, cu))
12992         {
12993           /* A static const member, not much different than an enum as far as
12994              we're concerned, except that we can support more types.  */
12995           new_symbol (die, NULL, cu);
12996         }
12997
12998       /* Get physical name.  */
12999       physname = dwarf2_physname (fieldname, die, cu);
13000
13001       /* The name is already allocated along with this objfile, so we don't
13002          need to duplicate it for the type.  */
13003       SET_FIELD_PHYSNAME (*fp, physname ? physname : "");
13004       FIELD_TYPE (*fp) = die_type (die, cu);
13005       FIELD_NAME (*fp) = fieldname;
13006     }
13007   else if (die->tag == DW_TAG_inheritance)
13008     {
13009       LONGEST offset;
13010
13011       /* C++ base class field.  */
13012       if (handle_data_member_location (die, cu, &offset))
13013         SET_FIELD_BITPOS (*fp, offset * bits_per_byte);
13014       FIELD_BITSIZE (*fp) = 0;
13015       FIELD_TYPE (*fp) = die_type (die, cu);
13016       FIELD_NAME (*fp) = type_name_no_tag (fp->type);
13017       fip->nbaseclasses++;
13018     }
13019 }
13020
13021 /* Add a typedef defined in the scope of the FIP's class.  */
13022
13023 static void
13024 dwarf2_add_typedef (struct field_info *fip, struct die_info *die,
13025                     struct dwarf2_cu *cu)
13026 {
13027   struct typedef_field_list *new_field;
13028   struct typedef_field *fp;
13029
13030   /* Allocate a new field list entry and link it in.  */
13031   new_field = XCNEW (struct typedef_field_list);
13032   make_cleanup (xfree, new_field);
13033
13034   gdb_assert (die->tag == DW_TAG_typedef);
13035
13036   fp = &new_field->field;
13037
13038   /* Get name of field.  */
13039   fp->name = dwarf2_name (die, cu);
13040   if (fp->name == NULL)
13041     return;
13042
13043   fp->type = read_type_die (die, cu);
13044
13045   new_field->next = fip->typedef_field_list;
13046   fip->typedef_field_list = new_field;
13047   fip->typedef_field_list_count++;
13048 }
13049
13050 /* Create the vector of fields, and attach it to the type.  */
13051
13052 static void
13053 dwarf2_attach_fields_to_type (struct field_info *fip, struct type *type,
13054                               struct dwarf2_cu *cu)
13055 {
13056   int nfields = fip->nfields;
13057
13058   /* Record the field count, allocate space for the array of fields,
13059      and create blank accessibility bitfields if necessary.  */
13060   TYPE_NFIELDS (type) = nfields;
13061   TYPE_FIELDS (type) = (struct field *)
13062     TYPE_ALLOC (type, sizeof (struct field) * nfields);
13063   memset (TYPE_FIELDS (type), 0, sizeof (struct field) * nfields);
13064
13065   if (fip->non_public_fields && cu->language != language_ada)
13066     {
13067       ALLOCATE_CPLUS_STRUCT_TYPE (type);
13068
13069       TYPE_FIELD_PRIVATE_BITS (type) =
13070         (B_TYPE *) TYPE_ALLOC (type, B_BYTES (nfields));
13071       B_CLRALL (TYPE_FIELD_PRIVATE_BITS (type), nfields);
13072
13073       TYPE_FIELD_PROTECTED_BITS (type) =
13074         (B_TYPE *) TYPE_ALLOC (type, B_BYTES (nfields));
13075       B_CLRALL (TYPE_FIELD_PROTECTED_BITS (type), nfields);
13076
13077       TYPE_FIELD_IGNORE_BITS (type) =
13078         (B_TYPE *) TYPE_ALLOC (type, B_BYTES (nfields));
13079       B_CLRALL (TYPE_FIELD_IGNORE_BITS (type), nfields);
13080     }
13081
13082   /* If the type has baseclasses, allocate and clear a bit vector for
13083      TYPE_FIELD_VIRTUAL_BITS.  */
13084   if (fip->nbaseclasses && cu->language != language_ada)
13085     {
13086       int num_bytes = B_BYTES (fip->nbaseclasses);
13087       unsigned char *pointer;
13088
13089       ALLOCATE_CPLUS_STRUCT_TYPE (type);
13090       pointer = (unsigned char *) TYPE_ALLOC (type, num_bytes);
13091       TYPE_FIELD_VIRTUAL_BITS (type) = pointer;
13092       B_CLRALL (TYPE_FIELD_VIRTUAL_BITS (type), fip->nbaseclasses);
13093       TYPE_N_BASECLASSES (type) = fip->nbaseclasses;
13094     }
13095
13096   /* Copy the saved-up fields into the field vector.  Start from the head of
13097      the list, adding to the tail of the field array, so that they end up in
13098      the same order in the array in which they were added to the list.  */
13099   while (nfields-- > 0)
13100     {
13101       struct nextfield *fieldp;
13102
13103       if (fip->fields)
13104         {
13105           fieldp = fip->fields;
13106           fip->fields = fieldp->next;
13107         }
13108       else
13109         {
13110           fieldp = fip->baseclasses;
13111           fip->baseclasses = fieldp->next;
13112         }
13113
13114       TYPE_FIELD (type, nfields) = fieldp->field;
13115       switch (fieldp->accessibility)
13116         {
13117         case DW_ACCESS_private:
13118           if (cu->language != language_ada)
13119             SET_TYPE_FIELD_PRIVATE (type, nfields);
13120           break;
13121
13122         case DW_ACCESS_protected:
13123           if (cu->language != language_ada)
13124             SET_TYPE_FIELD_PROTECTED (type, nfields);
13125           break;
13126
13127         case DW_ACCESS_public:
13128           break;
13129
13130         default:
13131           /* Unknown accessibility.  Complain and treat it as public.  */
13132           {
13133             complaint (&symfile_complaints, _("unsupported accessibility %d"),
13134                        fieldp->accessibility);
13135           }
13136           break;
13137         }
13138       if (nfields < fip->nbaseclasses)
13139         {
13140           switch (fieldp->virtuality)
13141             {
13142             case DW_VIRTUALITY_virtual:
13143             case DW_VIRTUALITY_pure_virtual:
13144               if (cu->language == language_ada)
13145                 error (_("unexpected virtuality in component of Ada type"));
13146               SET_TYPE_FIELD_VIRTUAL (type, nfields);
13147               break;
13148             }
13149         }
13150     }
13151 }
13152
13153 /* Return true if this member function is a constructor, false
13154    otherwise.  */
13155
13156 static int
13157 dwarf2_is_constructor (struct die_info *die, struct dwarf2_cu *cu)
13158 {
13159   const char *fieldname;
13160   const char *type_name;
13161   int len;
13162
13163   if (die->parent == NULL)
13164     return 0;
13165
13166   if (die->parent->tag != DW_TAG_structure_type
13167       && die->parent->tag != DW_TAG_union_type
13168       && die->parent->tag != DW_TAG_class_type)
13169     return 0;
13170
13171   fieldname = dwarf2_name (die, cu);
13172   type_name = dwarf2_name (die->parent, cu);
13173   if (fieldname == NULL || type_name == NULL)
13174     return 0;
13175
13176   len = strlen (fieldname);
13177   return (strncmp (fieldname, type_name, len) == 0
13178           && (type_name[len] == '\0' || type_name[len] == '<'));
13179 }
13180
13181 /* Add a member function to the proper fieldlist.  */
13182
13183 static void
13184 dwarf2_add_member_fn (struct field_info *fip, struct die_info *die,
13185                       struct type *type, struct dwarf2_cu *cu)
13186 {
13187   struct objfile *objfile = cu->objfile;
13188   struct attribute *attr;
13189   struct fnfieldlist *flp;
13190   int i;
13191   struct fn_field *fnp;
13192   const char *fieldname;
13193   struct nextfnfield *new_fnfield;
13194   struct type *this_type;
13195   enum dwarf_access_attribute accessibility;
13196
13197   if (cu->language == language_ada)
13198     error (_("unexpected member function in Ada type"));
13199
13200   /* Get name of member function.  */
13201   fieldname = dwarf2_name (die, cu);
13202   if (fieldname == NULL)
13203     return;
13204
13205   /* Look up member function name in fieldlist.  */
13206   for (i = 0; i < fip->nfnfields; i++)
13207     {
13208       if (strcmp (fip->fnfieldlists[i].name, fieldname) == 0)
13209         break;
13210     }
13211
13212   /* Create new list element if necessary.  */
13213   if (i < fip->nfnfields)
13214     flp = &fip->fnfieldlists[i];
13215   else
13216     {
13217       if ((fip->nfnfields % DW_FIELD_ALLOC_CHUNK) == 0)
13218         {
13219           fip->fnfieldlists = (struct fnfieldlist *)
13220             xrealloc (fip->fnfieldlists,
13221                       (fip->nfnfields + DW_FIELD_ALLOC_CHUNK)
13222                       * sizeof (struct fnfieldlist));
13223           if (fip->nfnfields == 0)
13224             make_cleanup (free_current_contents, &fip->fnfieldlists);
13225         }
13226       flp = &fip->fnfieldlists[fip->nfnfields];
13227       flp->name = fieldname;
13228       flp->length = 0;
13229       flp->head = NULL;
13230       i = fip->nfnfields++;
13231     }
13232
13233   /* Create a new member function field and chain it to the field list
13234      entry.  */
13235   new_fnfield = XNEW (struct nextfnfield);
13236   make_cleanup (xfree, new_fnfield);
13237   memset (new_fnfield, 0, sizeof (struct nextfnfield));
13238   new_fnfield->next = flp->head;
13239   flp->head = new_fnfield;
13240   flp->length++;
13241
13242   /* Fill in the member function field info.  */
13243   fnp = &new_fnfield->fnfield;
13244
13245   /* Delay processing of the physname until later.  */
13246   if (cu->language == language_cplus)
13247     {
13248       add_to_method_list (type, i, flp->length - 1, fieldname,
13249                           die, cu);
13250     }
13251   else
13252     {
13253       const char *physname = dwarf2_physname (fieldname, die, cu);
13254       fnp->physname = physname ? physname : "";
13255     }
13256
13257   fnp->type = alloc_type (objfile);
13258   this_type = read_type_die (die, cu);
13259   if (this_type && TYPE_CODE (this_type) == TYPE_CODE_FUNC)
13260     {
13261       int nparams = TYPE_NFIELDS (this_type);
13262
13263       /* TYPE is the domain of this method, and THIS_TYPE is the type
13264            of the method itself (TYPE_CODE_METHOD).  */
13265       smash_to_method_type (fnp->type, type,
13266                             TYPE_TARGET_TYPE (this_type),
13267                             TYPE_FIELDS (this_type),
13268                             TYPE_NFIELDS (this_type),
13269                             TYPE_VARARGS (this_type));
13270
13271       /* Handle static member functions.
13272          Dwarf2 has no clean way to discern C++ static and non-static
13273          member functions.  G++ helps GDB by marking the first
13274          parameter for non-static member functions (which is the this
13275          pointer) as artificial.  We obtain this information from
13276          read_subroutine_type via TYPE_FIELD_ARTIFICIAL.  */
13277       if (nparams == 0 || TYPE_FIELD_ARTIFICIAL (this_type, 0) == 0)
13278         fnp->voffset = VOFFSET_STATIC;
13279     }
13280   else
13281     complaint (&symfile_complaints, _("member function type missing for '%s'"),
13282                dwarf2_full_name (fieldname, die, cu));
13283
13284   /* Get fcontext from DW_AT_containing_type if present.  */
13285   if (dwarf2_attr (die, DW_AT_containing_type, cu) != NULL)
13286     fnp->fcontext = die_containing_type (die, cu);
13287
13288   /* dwarf2 doesn't have stubbed physical names, so the setting of is_const and
13289      is_volatile is irrelevant, as it is needed by gdb_mangle_name only.  */
13290
13291   /* Get accessibility.  */
13292   attr = dwarf2_attr (die, DW_AT_accessibility, cu);
13293   if (attr)
13294     accessibility = (enum dwarf_access_attribute) DW_UNSND (attr);
13295   else
13296     accessibility = dwarf2_default_access_attribute (die, cu);
13297   switch (accessibility)
13298     {
13299     case DW_ACCESS_private:
13300       fnp->is_private = 1;
13301       break;
13302     case DW_ACCESS_protected:
13303       fnp->is_protected = 1;
13304       break;
13305     }
13306
13307   /* Check for artificial methods.  */
13308   attr = dwarf2_attr (die, DW_AT_artificial, cu);
13309   if (attr && DW_UNSND (attr) != 0)
13310     fnp->is_artificial = 1;
13311
13312   fnp->is_constructor = dwarf2_is_constructor (die, cu);
13313
13314   /* Get index in virtual function table if it is a virtual member
13315      function.  For older versions of GCC, this is an offset in the
13316      appropriate virtual table, as specified by DW_AT_containing_type.
13317      For everyone else, it is an expression to be evaluated relative
13318      to the object address.  */
13319
13320   attr = dwarf2_attr (die, DW_AT_vtable_elem_location, cu);
13321   if (attr)
13322     {
13323       if (attr_form_is_block (attr) && DW_BLOCK (attr)->size > 0)
13324         {
13325           if (DW_BLOCK (attr)->data[0] == DW_OP_constu)
13326             {
13327               /* Old-style GCC.  */
13328               fnp->voffset = decode_locdesc (DW_BLOCK (attr), cu) + 2;
13329             }
13330           else if (DW_BLOCK (attr)->data[0] == DW_OP_deref
13331                    || (DW_BLOCK (attr)->size > 1
13332                        && DW_BLOCK (attr)->data[0] == DW_OP_deref_size
13333                        && DW_BLOCK (attr)->data[1] == cu->header.addr_size))
13334             {
13335               fnp->voffset = decode_locdesc (DW_BLOCK (attr), cu);
13336               if ((fnp->voffset % cu->header.addr_size) != 0)
13337                 dwarf2_complex_location_expr_complaint ();
13338               else
13339                 fnp->voffset /= cu->header.addr_size;
13340               fnp->voffset += 2;
13341             }
13342           else
13343             dwarf2_complex_location_expr_complaint ();
13344
13345           if (!fnp->fcontext)
13346             {
13347               /* If there is no `this' field and no DW_AT_containing_type,
13348                  we cannot actually find a base class context for the
13349                  vtable!  */
13350               if (TYPE_NFIELDS (this_type) == 0
13351                   || !TYPE_FIELD_ARTIFICIAL (this_type, 0))
13352                 {
13353                   complaint (&symfile_complaints,
13354                              _("cannot determine context for virtual member "
13355                                "function \"%s\" (offset %d)"),
13356                              fieldname, to_underlying (die->sect_off));
13357                 }
13358               else
13359                 {
13360                   fnp->fcontext
13361                     = TYPE_TARGET_TYPE (TYPE_FIELD_TYPE (this_type, 0));
13362                 }
13363             }
13364         }
13365       else if (attr_form_is_section_offset (attr))
13366         {
13367           dwarf2_complex_location_expr_complaint ();
13368         }
13369       else
13370         {
13371           dwarf2_invalid_attrib_class_complaint ("DW_AT_vtable_elem_location",
13372                                                  fieldname);
13373         }
13374     }
13375   else
13376     {
13377       attr = dwarf2_attr (die, DW_AT_virtuality, cu);
13378       if (attr && DW_UNSND (attr))
13379         {
13380           /* GCC does this, as of 2008-08-25; PR debug/37237.  */
13381           complaint (&symfile_complaints,
13382                      _("Member function \"%s\" (offset %d) is virtual "
13383                        "but the vtable offset is not specified"),
13384                      fieldname, to_underlying (die->sect_off));
13385           ALLOCATE_CPLUS_STRUCT_TYPE (type);
13386           TYPE_CPLUS_DYNAMIC (type) = 1;
13387         }
13388     }
13389 }
13390
13391 /* Create the vector of member function fields, and attach it to the type.  */
13392
13393 static void
13394 dwarf2_attach_fn_fields_to_type (struct field_info *fip, struct type *type,
13395                                  struct dwarf2_cu *cu)
13396 {
13397   struct fnfieldlist *flp;
13398   int i;
13399
13400   if (cu->language == language_ada)
13401     error (_("unexpected member functions in Ada type"));
13402
13403   ALLOCATE_CPLUS_STRUCT_TYPE (type);
13404   TYPE_FN_FIELDLISTS (type) = (struct fn_fieldlist *)
13405     TYPE_ALLOC (type, sizeof (struct fn_fieldlist) * fip->nfnfields);
13406
13407   for (i = 0, flp = fip->fnfieldlists; i < fip->nfnfields; i++, flp++)
13408     {
13409       struct nextfnfield *nfp = flp->head;
13410       struct fn_fieldlist *fn_flp = &TYPE_FN_FIELDLIST (type, i);
13411       int k;
13412
13413       TYPE_FN_FIELDLIST_NAME (type, i) = flp->name;
13414       TYPE_FN_FIELDLIST_LENGTH (type, i) = flp->length;
13415       fn_flp->fn_fields = (struct fn_field *)
13416         TYPE_ALLOC (type, sizeof (struct fn_field) * flp->length);
13417       for (k = flp->length; (k--, nfp); nfp = nfp->next)
13418         fn_flp->fn_fields[k] = nfp->fnfield;
13419     }
13420
13421   TYPE_NFN_FIELDS (type) = fip->nfnfields;
13422 }
13423
13424 /* Returns non-zero if NAME is the name of a vtable member in CU's
13425    language, zero otherwise.  */
13426 static int
13427 is_vtable_name (const char *name, struct dwarf2_cu *cu)
13428 {
13429   static const char vptr[] = "_vptr";
13430   static const char vtable[] = "vtable";
13431
13432   /* Look for the C++ form of the vtable.  */
13433   if (startswith (name, vptr) && is_cplus_marker (name[sizeof (vptr) - 1]))
13434     return 1;
13435
13436   return 0;
13437 }
13438
13439 /* GCC outputs unnamed structures that are really pointers to member
13440    functions, with the ABI-specified layout.  If TYPE describes
13441    such a structure, smash it into a member function type.
13442
13443    GCC shouldn't do this; it should just output pointer to member DIEs.
13444    This is GCC PR debug/28767.  */
13445
13446 static void
13447 quirk_gcc_member_function_pointer (struct type *type, struct objfile *objfile)
13448 {
13449   struct type *pfn_type, *self_type, *new_type;
13450
13451   /* Check for a structure with no name and two children.  */
13452   if (TYPE_CODE (type) != TYPE_CODE_STRUCT || TYPE_NFIELDS (type) != 2)
13453     return;
13454
13455   /* Check for __pfn and __delta members.  */
13456   if (TYPE_FIELD_NAME (type, 0) == NULL
13457       || strcmp (TYPE_FIELD_NAME (type, 0), "__pfn") != 0
13458       || TYPE_FIELD_NAME (type, 1) == NULL
13459       || strcmp (TYPE_FIELD_NAME (type, 1), "__delta") != 0)
13460     return;
13461
13462   /* Find the type of the method.  */
13463   pfn_type = TYPE_FIELD_TYPE (type, 0);
13464   if (pfn_type == NULL
13465       || TYPE_CODE (pfn_type) != TYPE_CODE_PTR
13466       || TYPE_CODE (TYPE_TARGET_TYPE (pfn_type)) != TYPE_CODE_FUNC)
13467     return;
13468
13469   /* Look for the "this" argument.  */
13470   pfn_type = TYPE_TARGET_TYPE (pfn_type);
13471   if (TYPE_NFIELDS (pfn_type) == 0
13472       /* || TYPE_FIELD_TYPE (pfn_type, 0) == NULL */
13473       || TYPE_CODE (TYPE_FIELD_TYPE (pfn_type, 0)) != TYPE_CODE_PTR)
13474     return;
13475
13476   self_type = TYPE_TARGET_TYPE (TYPE_FIELD_TYPE (pfn_type, 0));
13477   new_type = alloc_type (objfile);
13478   smash_to_method_type (new_type, self_type, TYPE_TARGET_TYPE (pfn_type),
13479                         TYPE_FIELDS (pfn_type), TYPE_NFIELDS (pfn_type),
13480                         TYPE_VARARGS (pfn_type));
13481   smash_to_methodptr_type (type, new_type);
13482 }
13483
13484 /* Return non-zero if the CU's PRODUCER string matches the Intel C/C++ compiler
13485    (icc).  */
13486
13487 static int
13488 producer_is_icc (struct dwarf2_cu *cu)
13489 {
13490   if (!cu->checked_producer)
13491     check_producer (cu);
13492
13493   return cu->producer_is_icc;
13494 }
13495
13496 /* Called when we find the DIE that starts a structure or union scope
13497    (definition) to create a type for the structure or union.  Fill in
13498    the type's name and general properties; the members will not be
13499    processed until process_structure_scope.  A symbol table entry for
13500    the type will also not be done until process_structure_scope (assuming
13501    the type has a name).
13502
13503    NOTE: we need to call these functions regardless of whether or not the
13504    DIE has a DW_AT_name attribute, since it might be an anonymous
13505    structure or union.  This gets the type entered into our set of
13506    user defined types.  */
13507
13508 static struct type *
13509 read_structure_type (struct die_info *die, struct dwarf2_cu *cu)
13510 {
13511   struct objfile *objfile = cu->objfile;
13512   struct type *type;
13513   struct attribute *attr;
13514   const char *name;
13515
13516   /* If the definition of this type lives in .debug_types, read that type.
13517      Don't follow DW_AT_specification though, that will take us back up
13518      the chain and we want to go down.  */
13519   attr = dwarf2_attr_no_follow (die, DW_AT_signature);
13520   if (attr)
13521     {
13522       type = get_DW_AT_signature_type (die, attr, cu);
13523
13524       /* The type's CU may not be the same as CU.
13525          Ensure TYPE is recorded with CU in die_type_hash.  */
13526       return set_die_type (die, type, cu);
13527     }
13528
13529   type = alloc_type (objfile);
13530   INIT_CPLUS_SPECIFIC (type);
13531
13532   name = dwarf2_name (die, cu);
13533   if (name != NULL)
13534     {
13535       if (cu->language == language_cplus
13536           || cu->language == language_d
13537           || cu->language == language_rust)
13538         {
13539           const char *full_name = dwarf2_full_name (name, die, cu);
13540
13541           /* dwarf2_full_name might have already finished building the DIE's
13542              type.  If so, there is no need to continue.  */
13543           if (get_die_type (die, cu) != NULL)
13544             return get_die_type (die, cu);
13545
13546           TYPE_TAG_NAME (type) = full_name;
13547           if (die->tag == DW_TAG_structure_type
13548               || die->tag == DW_TAG_class_type)
13549             TYPE_NAME (type) = TYPE_TAG_NAME (type);
13550         }
13551       else
13552         {
13553           /* The name is already allocated along with this objfile, so
13554              we don't need to duplicate it for the type.  */
13555           TYPE_TAG_NAME (type) = name;
13556           if (die->tag == DW_TAG_class_type)
13557             TYPE_NAME (type) = TYPE_TAG_NAME (type);
13558         }
13559     }
13560
13561   if (die->tag == DW_TAG_structure_type)
13562     {
13563       TYPE_CODE (type) = TYPE_CODE_STRUCT;
13564     }
13565   else if (die->tag == DW_TAG_union_type)
13566     {
13567       TYPE_CODE (type) = TYPE_CODE_UNION;
13568     }
13569   else
13570     {
13571       TYPE_CODE (type) = TYPE_CODE_STRUCT;
13572     }
13573
13574   if (cu->language == language_cplus && die->tag == DW_TAG_class_type)
13575     TYPE_DECLARED_CLASS (type) = 1;
13576
13577   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
13578   if (attr)
13579     {
13580       if (attr_form_is_constant (attr))
13581         TYPE_LENGTH (type) = DW_UNSND (attr);
13582       else
13583         {
13584           /* For the moment, dynamic type sizes are not supported
13585              by GDB's struct type.  The actual size is determined
13586              on-demand when resolving the type of a given object,
13587              so set the type's length to zero for now.  Otherwise,
13588              we record an expression as the length, and that expression
13589              could lead to a very large value, which could eventually
13590              lead to us trying to allocate that much memory when creating
13591              a value of that type.  */
13592           TYPE_LENGTH (type) = 0;
13593         }
13594     }
13595   else
13596     {
13597       TYPE_LENGTH (type) = 0;
13598     }
13599
13600   if (producer_is_icc (cu) && (TYPE_LENGTH (type) == 0))
13601     {
13602       /* ICC does not output the required DW_AT_declaration
13603          on incomplete types, but gives them a size of zero.  */
13604       TYPE_STUB (type) = 1;
13605     }
13606   else
13607     TYPE_STUB_SUPPORTED (type) = 1;
13608
13609   if (die_is_declaration (die, cu))
13610     TYPE_STUB (type) = 1;
13611   else if (attr == NULL && die->child == NULL
13612            && producer_is_realview (cu->producer))
13613     /* RealView does not output the required DW_AT_declaration
13614        on incomplete types.  */
13615     TYPE_STUB (type) = 1;
13616
13617   /* We need to add the type field to the die immediately so we don't
13618      infinitely recurse when dealing with pointers to the structure
13619      type within the structure itself.  */
13620   set_die_type (die, type, cu);
13621
13622   /* set_die_type should be already done.  */
13623   set_descriptive_type (type, die, cu);
13624
13625   return type;
13626 }
13627
13628 /* Finish creating a structure or union type, including filling in
13629    its members and creating a symbol for it.  */
13630
13631 static void
13632 process_structure_scope (struct die_info *die, struct dwarf2_cu *cu)
13633 {
13634   struct objfile *objfile = cu->objfile;
13635   struct die_info *child_die;
13636   struct type *type;
13637
13638   type = get_die_type (die, cu);
13639   if (type == NULL)
13640     type = read_structure_type (die, cu);
13641
13642   if (die->child != NULL && ! die_is_declaration (die, cu))
13643     {
13644       struct field_info fi;
13645       VEC (symbolp) *template_args = NULL;
13646       struct cleanup *back_to = make_cleanup (null_cleanup, 0);
13647
13648       memset (&fi, 0, sizeof (struct field_info));
13649
13650       child_die = die->child;
13651
13652       while (child_die && child_die->tag)
13653         {
13654           if (child_die->tag == DW_TAG_member
13655               || child_die->tag == DW_TAG_variable)
13656             {
13657               /* NOTE: carlton/2002-11-05: A C++ static data member
13658                  should be a DW_TAG_member that is a declaration, but
13659                  all versions of G++ as of this writing (so through at
13660                  least 3.2.1) incorrectly generate DW_TAG_variable
13661                  tags for them instead.  */
13662               dwarf2_add_field (&fi, child_die, cu);
13663             }
13664           else if (child_die->tag == DW_TAG_subprogram)
13665             {
13666               /* Rust doesn't have member functions in the C++ sense.
13667                  However, it does emit ordinary functions as children
13668                  of a struct DIE.  */
13669               if (cu->language == language_rust)
13670                 read_func_scope (child_die, cu);
13671               else
13672                 {
13673                   /* C++ member function.  */
13674                   dwarf2_add_member_fn (&fi, child_die, type, cu);
13675                 }
13676             }
13677           else if (child_die->tag == DW_TAG_inheritance)
13678             {
13679               /* C++ base class field.  */
13680               dwarf2_add_field (&fi, child_die, cu);
13681             }
13682           else if (child_die->tag == DW_TAG_typedef)
13683             dwarf2_add_typedef (&fi, child_die, cu);
13684           else if (child_die->tag == DW_TAG_template_type_param
13685                    || child_die->tag == DW_TAG_template_value_param)
13686             {
13687               struct symbol *arg = new_symbol (child_die, NULL, cu);
13688
13689               if (arg != NULL)
13690                 VEC_safe_push (symbolp, template_args, arg);
13691             }
13692
13693           child_die = sibling_die (child_die);
13694         }
13695
13696       /* Attach template arguments to type.  */
13697       if (! VEC_empty (symbolp, template_args))
13698         {
13699           ALLOCATE_CPLUS_STRUCT_TYPE (type);
13700           TYPE_N_TEMPLATE_ARGUMENTS (type)
13701             = VEC_length (symbolp, template_args);
13702           TYPE_TEMPLATE_ARGUMENTS (type)
13703             = XOBNEWVEC (&objfile->objfile_obstack,
13704                          struct symbol *,
13705                          TYPE_N_TEMPLATE_ARGUMENTS (type));
13706           memcpy (TYPE_TEMPLATE_ARGUMENTS (type),
13707                   VEC_address (symbolp, template_args),
13708                   (TYPE_N_TEMPLATE_ARGUMENTS (type)
13709                    * sizeof (struct symbol *)));
13710           VEC_free (symbolp, template_args);
13711         }
13712
13713       /* Attach fields and member functions to the type.  */
13714       if (fi.nfields)
13715         dwarf2_attach_fields_to_type (&fi, type, cu);
13716       if (fi.nfnfields)
13717         {
13718           dwarf2_attach_fn_fields_to_type (&fi, type, cu);
13719
13720           /* Get the type which refers to the base class (possibly this
13721              class itself) which contains the vtable pointer for the current
13722              class from the DW_AT_containing_type attribute.  This use of
13723              DW_AT_containing_type is a GNU extension.  */
13724
13725           if (dwarf2_attr (die, DW_AT_containing_type, cu) != NULL)
13726             {
13727               struct type *t = die_containing_type (die, cu);
13728
13729               set_type_vptr_basetype (type, t);
13730               if (type == t)
13731                 {
13732                   int i;
13733
13734                   /* Our own class provides vtbl ptr.  */
13735                   for (i = TYPE_NFIELDS (t) - 1;
13736                        i >= TYPE_N_BASECLASSES (t);
13737                        --i)
13738                     {
13739                       const char *fieldname = TYPE_FIELD_NAME (t, i);
13740
13741                       if (is_vtable_name (fieldname, cu))
13742                         {
13743                           set_type_vptr_fieldno (type, i);
13744                           break;
13745                         }
13746                     }
13747
13748                   /* Complain if virtual function table field not found.  */
13749                   if (i < TYPE_N_BASECLASSES (t))
13750                     complaint (&symfile_complaints,
13751                                _("virtual function table pointer "
13752                                  "not found when defining class '%s'"),
13753                                TYPE_TAG_NAME (type) ? TYPE_TAG_NAME (type) :
13754                                "");
13755                 }
13756               else
13757                 {
13758                   set_type_vptr_fieldno (type, TYPE_VPTR_FIELDNO (t));
13759                 }
13760             }
13761           else if (cu->producer
13762                    && startswith (cu->producer, "IBM(R) XL C/C++ Advanced Edition"))
13763             {
13764               /* The IBM XLC compiler does not provide direct indication
13765                  of the containing type, but the vtable pointer is
13766                  always named __vfp.  */
13767
13768               int i;
13769
13770               for (i = TYPE_NFIELDS (type) - 1;
13771                    i >= TYPE_N_BASECLASSES (type);
13772                    --i)
13773                 {
13774                   if (strcmp (TYPE_FIELD_NAME (type, i), "__vfp") == 0)
13775                     {
13776                       set_type_vptr_fieldno (type, i);
13777                       set_type_vptr_basetype (type, type);
13778                       break;
13779                     }
13780                 }
13781             }
13782         }
13783
13784       /* Copy fi.typedef_field_list linked list elements content into the
13785          allocated array TYPE_TYPEDEF_FIELD_ARRAY (type).  */
13786       if (fi.typedef_field_list)
13787         {
13788           int i = fi.typedef_field_list_count;
13789
13790           ALLOCATE_CPLUS_STRUCT_TYPE (type);
13791           TYPE_TYPEDEF_FIELD_ARRAY (type)
13792             = ((struct typedef_field *)
13793                TYPE_ALLOC (type, sizeof (TYPE_TYPEDEF_FIELD (type, 0)) * i));
13794           TYPE_TYPEDEF_FIELD_COUNT (type) = i;
13795
13796           /* Reverse the list order to keep the debug info elements order.  */
13797           while (--i >= 0)
13798             {
13799               struct typedef_field *dest, *src;
13800
13801               dest = &TYPE_TYPEDEF_FIELD (type, i);
13802               src = &fi.typedef_field_list->field;
13803               fi.typedef_field_list = fi.typedef_field_list->next;
13804               *dest = *src;
13805             }
13806         }
13807
13808       do_cleanups (back_to);
13809     }
13810
13811   quirk_gcc_member_function_pointer (type, objfile);
13812
13813   /* NOTE: carlton/2004-03-16: GCC 3.4 (or at least one of its
13814      snapshots) has been known to create a die giving a declaration
13815      for a class that has, as a child, a die giving a definition for a
13816      nested class.  So we have to process our children even if the
13817      current die is a declaration.  Normally, of course, a declaration
13818      won't have any children at all.  */
13819
13820   child_die = die->child;
13821
13822   while (child_die != NULL && child_die->tag)
13823     {
13824       if (child_die->tag == DW_TAG_member
13825           || child_die->tag == DW_TAG_variable
13826           || child_die->tag == DW_TAG_inheritance
13827           || child_die->tag == DW_TAG_template_value_param
13828           || child_die->tag == DW_TAG_template_type_param)
13829         {
13830           /* Do nothing.  */
13831         }
13832       else
13833         process_die (child_die, cu);
13834
13835       child_die = sibling_die (child_die);
13836     }
13837
13838   /* Do not consider external references.  According to the DWARF standard,
13839      these DIEs are identified by the fact that they have no byte_size
13840      attribute, and a declaration attribute.  */
13841   if (dwarf2_attr (die, DW_AT_byte_size, cu) != NULL
13842       || !die_is_declaration (die, cu))
13843     new_symbol (die, type, cu);
13844 }
13845
13846 /* Assuming DIE is an enumeration type, and TYPE is its associated type,
13847    update TYPE using some information only available in DIE's children.  */
13848
13849 static void
13850 update_enumeration_type_from_children (struct die_info *die,
13851                                        struct type *type,
13852                                        struct dwarf2_cu *cu)
13853 {
13854   struct die_info *child_die;
13855   int unsigned_enum = 1;
13856   int flag_enum = 1;
13857   ULONGEST mask = 0;
13858
13859   auto_obstack obstack;
13860
13861   for (child_die = die->child;
13862        child_die != NULL && child_die->tag;
13863        child_die = sibling_die (child_die))
13864     {
13865       struct attribute *attr;
13866       LONGEST value;
13867       const gdb_byte *bytes;
13868       struct dwarf2_locexpr_baton *baton;
13869       const char *name;
13870
13871       if (child_die->tag != DW_TAG_enumerator)
13872         continue;
13873
13874       attr = dwarf2_attr (child_die, DW_AT_const_value, cu);
13875       if (attr == NULL)
13876         continue;
13877
13878       name = dwarf2_name (child_die, cu);
13879       if (name == NULL)
13880         name = "<anonymous enumerator>";
13881
13882       dwarf2_const_value_attr (attr, type, name, &obstack, cu,
13883                                &value, &bytes, &baton);
13884       if (value < 0)
13885         {
13886           unsigned_enum = 0;
13887           flag_enum = 0;
13888         }
13889       else if ((mask & value) != 0)
13890         flag_enum = 0;
13891       else
13892         mask |= value;
13893
13894       /* If we already know that the enum type is neither unsigned, nor
13895          a flag type, no need to look at the rest of the enumerates.  */
13896       if (!unsigned_enum && !flag_enum)
13897         break;
13898     }
13899
13900   if (unsigned_enum)
13901     TYPE_UNSIGNED (type) = 1;
13902   if (flag_enum)
13903     TYPE_FLAG_ENUM (type) = 1;
13904 }
13905
13906 /* Given a DW_AT_enumeration_type die, set its type.  We do not
13907    complete the type's fields yet, or create any symbols.  */
13908
13909 static struct type *
13910 read_enumeration_type (struct die_info *die, struct dwarf2_cu *cu)
13911 {
13912   struct objfile *objfile = cu->objfile;
13913   struct type *type;
13914   struct attribute *attr;
13915   const char *name;
13916
13917   /* If the definition of this type lives in .debug_types, read that type.
13918      Don't follow DW_AT_specification though, that will take us back up
13919      the chain and we want to go down.  */
13920   attr = dwarf2_attr_no_follow (die, DW_AT_signature);
13921   if (attr)
13922     {
13923       type = get_DW_AT_signature_type (die, attr, cu);
13924
13925       /* The type's CU may not be the same as CU.
13926          Ensure TYPE is recorded with CU in die_type_hash.  */
13927       return set_die_type (die, type, cu);
13928     }
13929
13930   type = alloc_type (objfile);
13931
13932   TYPE_CODE (type) = TYPE_CODE_ENUM;
13933   name = dwarf2_full_name (NULL, die, cu);
13934   if (name != NULL)
13935     TYPE_TAG_NAME (type) = name;
13936
13937   attr = dwarf2_attr (die, DW_AT_type, cu);
13938   if (attr != NULL)
13939     {
13940       struct type *underlying_type = die_type (die, cu);
13941
13942       TYPE_TARGET_TYPE (type) = underlying_type;
13943     }
13944
13945   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
13946   if (attr)
13947     {
13948       TYPE_LENGTH (type) = DW_UNSND (attr);
13949     }
13950   else
13951     {
13952       TYPE_LENGTH (type) = 0;
13953     }
13954
13955   /* The enumeration DIE can be incomplete.  In Ada, any type can be
13956      declared as private in the package spec, and then defined only
13957      inside the package body.  Such types are known as Taft Amendment
13958      Types.  When another package uses such a type, an incomplete DIE
13959      may be generated by the compiler.  */
13960   if (die_is_declaration (die, cu))
13961     TYPE_STUB (type) = 1;
13962
13963   /* Finish the creation of this type by using the enum's children.
13964      We must call this even when the underlying type has been provided
13965      so that we can determine if we're looking at a "flag" enum.  */
13966   update_enumeration_type_from_children (die, type, cu);
13967
13968   /* If this type has an underlying type that is not a stub, then we
13969      may use its attributes.  We always use the "unsigned" attribute
13970      in this situation, because ordinarily we guess whether the type
13971      is unsigned -- but the guess can be wrong and the underlying type
13972      can tell us the reality.  However, we defer to a local size
13973      attribute if one exists, because this lets the compiler override
13974      the underlying type if needed.  */
13975   if (TYPE_TARGET_TYPE (type) != NULL && !TYPE_STUB (TYPE_TARGET_TYPE (type)))
13976     {
13977       TYPE_UNSIGNED (type) = TYPE_UNSIGNED (TYPE_TARGET_TYPE (type));
13978       if (TYPE_LENGTH (type) == 0)
13979         TYPE_LENGTH (type) = TYPE_LENGTH (TYPE_TARGET_TYPE (type));
13980     }
13981
13982   TYPE_DECLARED_CLASS (type) = dwarf2_flag_true_p (die, DW_AT_enum_class, cu);
13983
13984   return set_die_type (die, type, cu);
13985 }
13986
13987 /* Given a pointer to a die which begins an enumeration, process all
13988    the dies that define the members of the enumeration, and create the
13989    symbol for the enumeration type.
13990
13991    NOTE: We reverse the order of the element list.  */
13992
13993 static void
13994 process_enumeration_scope (struct die_info *die, struct dwarf2_cu *cu)
13995 {
13996   struct type *this_type;
13997
13998   this_type = get_die_type (die, cu);
13999   if (this_type == NULL)
14000     this_type = read_enumeration_type (die, cu);
14001
14002   if (die->child != NULL)
14003     {
14004       struct die_info *child_die;
14005       struct symbol *sym;
14006       struct field *fields = NULL;
14007       int num_fields = 0;
14008       const char *name;
14009
14010       child_die = die->child;
14011       while (child_die && child_die->tag)
14012         {
14013           if (child_die->tag != DW_TAG_enumerator)
14014             {
14015               process_die (child_die, cu);
14016             }
14017           else
14018             {
14019               name = dwarf2_name (child_die, cu);
14020               if (name)
14021                 {
14022                   sym = new_symbol (child_die, this_type, cu);
14023
14024                   if ((num_fields % DW_FIELD_ALLOC_CHUNK) == 0)
14025                     {
14026                       fields = (struct field *)
14027                         xrealloc (fields,
14028                                   (num_fields + DW_FIELD_ALLOC_CHUNK)
14029                                   * sizeof (struct field));
14030                     }
14031
14032                   FIELD_NAME (fields[num_fields]) = SYMBOL_LINKAGE_NAME (sym);
14033                   FIELD_TYPE (fields[num_fields]) = NULL;
14034                   SET_FIELD_ENUMVAL (fields[num_fields], SYMBOL_VALUE (sym));
14035                   FIELD_BITSIZE (fields[num_fields]) = 0;
14036
14037                   num_fields++;
14038                 }
14039             }
14040
14041           child_die = sibling_die (child_die);
14042         }
14043
14044       if (num_fields)
14045         {
14046           TYPE_NFIELDS (this_type) = num_fields;
14047           TYPE_FIELDS (this_type) = (struct field *)
14048             TYPE_ALLOC (this_type, sizeof (struct field) * num_fields);
14049           memcpy (TYPE_FIELDS (this_type), fields,
14050                   sizeof (struct field) * num_fields);
14051           xfree (fields);
14052         }
14053     }
14054
14055   /* If we are reading an enum from a .debug_types unit, and the enum
14056      is a declaration, and the enum is not the signatured type in the
14057      unit, then we do not want to add a symbol for it.  Adding a
14058      symbol would in some cases obscure the true definition of the
14059      enum, giving users an incomplete type when the definition is
14060      actually available.  Note that we do not want to do this for all
14061      enums which are just declarations, because C++0x allows forward
14062      enum declarations.  */
14063   if (cu->per_cu->is_debug_types
14064       && die_is_declaration (die, cu))
14065     {
14066       struct signatured_type *sig_type;
14067
14068       sig_type = (struct signatured_type *) cu->per_cu;
14069       gdb_assert (to_underlying (sig_type->type_offset_in_section) != 0);
14070       if (sig_type->type_offset_in_section != die->sect_off)
14071         return;
14072     }
14073
14074   new_symbol (die, this_type, cu);
14075 }
14076
14077 /* Extract all information from a DW_TAG_array_type DIE and put it in
14078    the DIE's type field.  For now, this only handles one dimensional
14079    arrays.  */
14080
14081 static struct type *
14082 read_array_type (struct die_info *die, struct dwarf2_cu *cu)
14083 {
14084   struct objfile *objfile = cu->objfile;
14085   struct die_info *child_die;
14086   struct type *type;
14087   struct type *element_type, *range_type, *index_type;
14088   struct type **range_types = NULL;
14089   struct attribute *attr;
14090   int ndim = 0;
14091   struct cleanup *back_to;
14092   const char *name;
14093   unsigned int bit_stride = 0;
14094
14095   element_type = die_type (die, cu);
14096
14097   /* The die_type call above may have already set the type for this DIE.  */
14098   type = get_die_type (die, cu);
14099   if (type)
14100     return type;
14101
14102   attr = dwarf2_attr (die, DW_AT_byte_stride, cu);
14103   if (attr != NULL)
14104     bit_stride = DW_UNSND (attr) * 8;
14105
14106   attr = dwarf2_attr (die, DW_AT_bit_stride, cu);
14107   if (attr != NULL)
14108     bit_stride = DW_UNSND (attr);
14109
14110   /* Irix 6.2 native cc creates array types without children for
14111      arrays with unspecified length.  */
14112   if (die->child == NULL)
14113     {
14114       index_type = objfile_type (objfile)->builtin_int;
14115       range_type = create_static_range_type (NULL, index_type, 0, -1);
14116       type = create_array_type_with_stride (NULL, element_type, range_type,
14117                                             bit_stride);
14118       return set_die_type (die, type, cu);
14119     }
14120
14121   back_to = make_cleanup (null_cleanup, NULL);
14122   child_die = die->child;
14123   while (child_die && child_die->tag)
14124     {
14125       if (child_die->tag == DW_TAG_subrange_type)
14126         {
14127           struct type *child_type = read_type_die (child_die, cu);
14128
14129           if (child_type != NULL)
14130             {
14131               /* The range type was succesfully read.  Save it for the
14132                  array type creation.  */
14133               if ((ndim % DW_FIELD_ALLOC_CHUNK) == 0)
14134                 {
14135                   range_types = (struct type **)
14136                     xrealloc (range_types, (ndim + DW_FIELD_ALLOC_CHUNK)
14137                               * sizeof (struct type *));
14138                   if (ndim == 0)
14139                     make_cleanup (free_current_contents, &range_types);
14140                 }
14141               range_types[ndim++] = child_type;
14142             }
14143         }
14144       child_die = sibling_die (child_die);
14145     }
14146
14147   /* Dwarf2 dimensions are output from left to right, create the
14148      necessary array types in backwards order.  */
14149
14150   type = element_type;
14151
14152   if (read_array_order (die, cu) == DW_ORD_col_major)
14153     {
14154       int i = 0;
14155
14156       while (i < ndim)
14157         type = create_array_type_with_stride (NULL, type, range_types[i++],
14158                                               bit_stride);
14159     }
14160   else
14161     {
14162       while (ndim-- > 0)
14163         type = create_array_type_with_stride (NULL, type, range_types[ndim],
14164                                               bit_stride);
14165     }
14166
14167   /* Understand Dwarf2 support for vector types (like they occur on
14168      the PowerPC w/ AltiVec).  Gcc just adds another attribute to the
14169      array type.  This is not part of the Dwarf2/3 standard yet, but a
14170      custom vendor extension.  The main difference between a regular
14171      array and the vector variant is that vectors are passed by value
14172      to functions.  */
14173   attr = dwarf2_attr (die, DW_AT_GNU_vector, cu);
14174   if (attr)
14175     make_vector_type (type);
14176
14177   /* The DIE may have DW_AT_byte_size set.  For example an OpenCL
14178      implementation may choose to implement triple vectors using this
14179      attribute.  */
14180   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
14181   if (attr)
14182     {
14183       if (DW_UNSND (attr) >= TYPE_LENGTH (type))
14184         TYPE_LENGTH (type) = DW_UNSND (attr);
14185       else
14186         complaint (&symfile_complaints,
14187                    _("DW_AT_byte_size for array type smaller "
14188                      "than the total size of elements"));
14189     }
14190
14191   name = dwarf2_name (die, cu);
14192   if (name)
14193     TYPE_NAME (type) = name;
14194
14195   /* Install the type in the die.  */
14196   set_die_type (die, type, cu);
14197
14198   /* set_die_type should be already done.  */
14199   set_descriptive_type (type, die, cu);
14200
14201   do_cleanups (back_to);
14202
14203   return type;
14204 }
14205
14206 static enum dwarf_array_dim_ordering
14207 read_array_order (struct die_info *die, struct dwarf2_cu *cu)
14208 {
14209   struct attribute *attr;
14210
14211   attr = dwarf2_attr (die, DW_AT_ordering, cu);
14212
14213   if (attr)
14214     return (enum dwarf_array_dim_ordering) DW_SND (attr);
14215
14216   /* GNU F77 is a special case, as at 08/2004 array type info is the
14217      opposite order to the dwarf2 specification, but data is still
14218      laid out as per normal fortran.
14219
14220      FIXME: dsl/2004-8-20: If G77 is ever fixed, this will also need
14221      version checking.  */
14222
14223   if (cu->language == language_fortran
14224       && cu->producer && strstr (cu->producer, "GNU F77"))
14225     {
14226       return DW_ORD_row_major;
14227     }
14228
14229   switch (cu->language_defn->la_array_ordering)
14230     {
14231     case array_column_major:
14232       return DW_ORD_col_major;
14233     case array_row_major:
14234     default:
14235       return DW_ORD_row_major;
14236     };
14237 }
14238
14239 /* Extract all information from a DW_TAG_set_type DIE and put it in
14240    the DIE's type field.  */
14241
14242 static struct type *
14243 read_set_type (struct die_info *die, struct dwarf2_cu *cu)
14244 {
14245   struct type *domain_type, *set_type;
14246   struct attribute *attr;
14247
14248   domain_type = die_type (die, cu);
14249
14250   /* The die_type call above may have already set the type for this DIE.  */
14251   set_type = get_die_type (die, cu);
14252   if (set_type)
14253     return set_type;
14254
14255   set_type = create_set_type (NULL, domain_type);
14256
14257   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
14258   if (attr)
14259     TYPE_LENGTH (set_type) = DW_UNSND (attr);
14260
14261   return set_die_type (die, set_type, cu);
14262 }
14263
14264 /* A helper for read_common_block that creates a locexpr baton.
14265    SYM is the symbol which we are marking as computed.
14266    COMMON_DIE is the DIE for the common block.
14267    COMMON_LOC is the location expression attribute for the common
14268    block itself.
14269    MEMBER_LOC is the location expression attribute for the particular
14270    member of the common block that we are processing.
14271    CU is the CU from which the above come.  */
14272
14273 static void
14274 mark_common_block_symbol_computed (struct symbol *sym,
14275                                    struct die_info *common_die,
14276                                    struct attribute *common_loc,
14277                                    struct attribute *member_loc,
14278                                    struct dwarf2_cu *cu)
14279 {
14280   struct objfile *objfile = dwarf2_per_objfile->objfile;
14281   struct dwarf2_locexpr_baton *baton;
14282   gdb_byte *ptr;
14283   unsigned int cu_off;
14284   enum bfd_endian byte_order = gdbarch_byte_order (get_objfile_arch (objfile));
14285   LONGEST offset = 0;
14286
14287   gdb_assert (common_loc && member_loc);
14288   gdb_assert (attr_form_is_block (common_loc));
14289   gdb_assert (attr_form_is_block (member_loc)
14290               || attr_form_is_constant (member_loc));
14291
14292   baton = XOBNEW (&objfile->objfile_obstack, struct dwarf2_locexpr_baton);
14293   baton->per_cu = cu->per_cu;
14294   gdb_assert (baton->per_cu);
14295
14296   baton->size = 5 /* DW_OP_call4 */ + 1 /* DW_OP_plus */;
14297
14298   if (attr_form_is_constant (member_loc))
14299     {
14300       offset = dwarf2_get_attr_constant_value (member_loc, 0);
14301       baton->size += 1 /* DW_OP_addr */ + cu->header.addr_size;
14302     }
14303   else
14304     baton->size += DW_BLOCK (member_loc)->size;
14305
14306   ptr = (gdb_byte *) obstack_alloc (&objfile->objfile_obstack, baton->size);
14307   baton->data = ptr;
14308
14309   *ptr++ = DW_OP_call4;
14310   cu_off = common_die->sect_off - cu->per_cu->sect_off;
14311   store_unsigned_integer (ptr, 4, byte_order, cu_off);
14312   ptr += 4;
14313
14314   if (attr_form_is_constant (member_loc))
14315     {
14316       *ptr++ = DW_OP_addr;
14317       store_unsigned_integer (ptr, cu->header.addr_size, byte_order, offset);
14318       ptr += cu->header.addr_size;
14319     }
14320   else
14321     {
14322       /* We have to copy the data here, because DW_OP_call4 will only
14323          use a DW_AT_location attribute.  */
14324       memcpy (ptr, DW_BLOCK (member_loc)->data, DW_BLOCK (member_loc)->size);
14325       ptr += DW_BLOCK (member_loc)->size;
14326     }
14327
14328   *ptr++ = DW_OP_plus;
14329   gdb_assert (ptr - baton->data == baton->size);
14330
14331   SYMBOL_LOCATION_BATON (sym) = baton;
14332   SYMBOL_ACLASS_INDEX (sym) = dwarf2_locexpr_index;
14333 }
14334
14335 /* Create appropriate locally-scoped variables for all the
14336    DW_TAG_common_block entries.  Also create a struct common_block
14337    listing all such variables for `info common'.  COMMON_BLOCK_DOMAIN
14338    is used to sepate the common blocks name namespace from regular
14339    variable names.  */
14340
14341 static void
14342 read_common_block (struct die_info *die, struct dwarf2_cu *cu)
14343 {
14344   struct attribute *attr;
14345
14346   attr = dwarf2_attr (die, DW_AT_location, cu);
14347   if (attr)
14348     {
14349       /* Support the .debug_loc offsets.  */
14350       if (attr_form_is_block (attr))
14351         {
14352           /* Ok.  */
14353         }
14354       else if (attr_form_is_section_offset (attr))
14355         {
14356           dwarf2_complex_location_expr_complaint ();
14357           attr = NULL;
14358         }
14359       else
14360         {
14361           dwarf2_invalid_attrib_class_complaint ("DW_AT_location",
14362                                                  "common block member");
14363           attr = NULL;
14364         }
14365     }
14366
14367   if (die->child != NULL)
14368     {
14369       struct objfile *objfile = cu->objfile;
14370       struct die_info *child_die;
14371       size_t n_entries = 0, size;
14372       struct common_block *common_block;
14373       struct symbol *sym;
14374
14375       for (child_die = die->child;
14376            child_die && child_die->tag;
14377            child_die = sibling_die (child_die))
14378         ++n_entries;
14379
14380       size = (sizeof (struct common_block)
14381               + (n_entries - 1) * sizeof (struct symbol *));
14382       common_block
14383         = (struct common_block *) obstack_alloc (&objfile->objfile_obstack,
14384                                                  size);
14385       memset (common_block->contents, 0, n_entries * sizeof (struct symbol *));
14386       common_block->n_entries = 0;
14387
14388       for (child_die = die->child;
14389            child_die && child_die->tag;
14390            child_die = sibling_die (child_die))
14391         {
14392           /* Create the symbol in the DW_TAG_common_block block in the current
14393              symbol scope.  */
14394           sym = new_symbol (child_die, NULL, cu);
14395           if (sym != NULL)
14396             {
14397               struct attribute *member_loc;
14398
14399               common_block->contents[common_block->n_entries++] = sym;
14400
14401               member_loc = dwarf2_attr (child_die, DW_AT_data_member_location,
14402                                         cu);
14403               if (member_loc)
14404                 {
14405                   /* GDB has handled this for a long time, but it is
14406                      not specified by DWARF.  It seems to have been
14407                      emitted by gfortran at least as recently as:
14408                      http://gcc.gnu.org/bugzilla/show_bug.cgi?id=23057.  */
14409                   complaint (&symfile_complaints,
14410                              _("Variable in common block has "
14411                                "DW_AT_data_member_location "
14412                                "- DIE at 0x%x [in module %s]"),
14413                              to_underlying (child_die->sect_off),
14414                              objfile_name (cu->objfile));
14415
14416                   if (attr_form_is_section_offset (member_loc))
14417                     dwarf2_complex_location_expr_complaint ();
14418                   else if (attr_form_is_constant (member_loc)
14419                            || attr_form_is_block (member_loc))
14420                     {
14421                       if (attr)
14422                         mark_common_block_symbol_computed (sym, die, attr,
14423                                                            member_loc, cu);
14424                     }
14425                   else
14426                     dwarf2_complex_location_expr_complaint ();
14427                 }
14428             }
14429         }
14430
14431       sym = new_symbol (die, objfile_type (objfile)->builtin_void, cu);
14432       SYMBOL_VALUE_COMMON_BLOCK (sym) = common_block;
14433     }
14434 }
14435
14436 /* Create a type for a C++ namespace.  */
14437
14438 static struct type *
14439 read_namespace_type (struct die_info *die, struct dwarf2_cu *cu)
14440 {
14441   struct objfile *objfile = cu->objfile;
14442   const char *previous_prefix, *name;
14443   int is_anonymous;
14444   struct type *type;
14445
14446   /* For extensions, reuse the type of the original namespace.  */
14447   if (dwarf2_attr (die, DW_AT_extension, cu) != NULL)
14448     {
14449       struct die_info *ext_die;
14450       struct dwarf2_cu *ext_cu = cu;
14451
14452       ext_die = dwarf2_extension (die, &ext_cu);
14453       type = read_type_die (ext_die, ext_cu);
14454
14455       /* EXT_CU may not be the same as CU.
14456          Ensure TYPE is recorded with CU in die_type_hash.  */
14457       return set_die_type (die, type, cu);
14458     }
14459
14460   name = namespace_name (die, &is_anonymous, cu);
14461
14462   /* Now build the name of the current namespace.  */
14463
14464   previous_prefix = determine_prefix (die, cu);
14465   if (previous_prefix[0] != '\0')
14466     name = typename_concat (&objfile->objfile_obstack,
14467                             previous_prefix, name, 0, cu);
14468
14469   /* Create the type.  */
14470   type = init_type (objfile, TYPE_CODE_NAMESPACE, 0, name);
14471   TYPE_TAG_NAME (type) = TYPE_NAME (type);
14472
14473   return set_die_type (die, type, cu);
14474 }
14475
14476 /* Read a namespace scope.  */
14477
14478 static void
14479 read_namespace (struct die_info *die, struct dwarf2_cu *cu)
14480 {
14481   struct objfile *objfile = cu->objfile;
14482   int is_anonymous;
14483
14484   /* Add a symbol associated to this if we haven't seen the namespace
14485      before.  Also, add a using directive if it's an anonymous
14486      namespace.  */
14487
14488   if (dwarf2_attr (die, DW_AT_extension, cu) == NULL)
14489     {
14490       struct type *type;
14491
14492       type = read_type_die (die, cu);
14493       new_symbol (die, type, cu);
14494
14495       namespace_name (die, &is_anonymous, cu);
14496       if (is_anonymous)
14497         {
14498           const char *previous_prefix = determine_prefix (die, cu);
14499
14500           add_using_directive (using_directives (cu->language),
14501                                previous_prefix, TYPE_NAME (type), NULL,
14502                                NULL, NULL, 0, &objfile->objfile_obstack);
14503         }
14504     }
14505
14506   if (die->child != NULL)
14507     {
14508       struct die_info *child_die = die->child;
14509
14510       while (child_die && child_die->tag)
14511         {
14512           process_die (child_die, cu);
14513           child_die = sibling_die (child_die);
14514         }
14515     }
14516 }
14517
14518 /* Read a Fortran module as type.  This DIE can be only a declaration used for
14519    imported module.  Still we need that type as local Fortran "use ... only"
14520    declaration imports depend on the created type in determine_prefix.  */
14521
14522 static struct type *
14523 read_module_type (struct die_info *die, struct dwarf2_cu *cu)
14524 {
14525   struct objfile *objfile = cu->objfile;
14526   const char *module_name;
14527   struct type *type;
14528
14529   module_name = dwarf2_name (die, cu);
14530   if (!module_name)
14531     complaint (&symfile_complaints,
14532                _("DW_TAG_module has no name, offset 0x%x"),
14533                to_underlying (die->sect_off));
14534   type = init_type (objfile, TYPE_CODE_MODULE, 0, module_name);
14535
14536   /* determine_prefix uses TYPE_TAG_NAME.  */
14537   TYPE_TAG_NAME (type) = TYPE_NAME (type);
14538
14539   return set_die_type (die, type, cu);
14540 }
14541
14542 /* Read a Fortran module.  */
14543
14544 static void
14545 read_module (struct die_info *die, struct dwarf2_cu *cu)
14546 {
14547   struct die_info *child_die = die->child;
14548   struct type *type;
14549
14550   type = read_type_die (die, cu);
14551   new_symbol (die, type, cu);
14552
14553   while (child_die && child_die->tag)
14554     {
14555       process_die (child_die, cu);
14556       child_die = sibling_die (child_die);
14557     }
14558 }
14559
14560 /* Return the name of the namespace represented by DIE.  Set
14561    *IS_ANONYMOUS to tell whether or not the namespace is an anonymous
14562    namespace.  */
14563
14564 static const char *
14565 namespace_name (struct die_info *die, int *is_anonymous, struct dwarf2_cu *cu)
14566 {
14567   struct die_info *current_die;
14568   const char *name = NULL;
14569
14570   /* Loop through the extensions until we find a name.  */
14571
14572   for (current_die = die;
14573        current_die != NULL;
14574        current_die = dwarf2_extension (die, &cu))
14575     {
14576       /* We don't use dwarf2_name here so that we can detect the absence
14577          of a name -> anonymous namespace.  */
14578       name = dwarf2_string_attr (die, DW_AT_name, cu);
14579
14580       if (name != NULL)
14581         break;
14582     }
14583
14584   /* Is it an anonymous namespace?  */
14585
14586   *is_anonymous = (name == NULL);
14587   if (*is_anonymous)
14588     name = CP_ANONYMOUS_NAMESPACE_STR;
14589
14590   return name;
14591 }
14592
14593 /* Extract all information from a DW_TAG_pointer_type DIE and add to
14594    the user defined type vector.  */
14595
14596 static struct type *
14597 read_tag_pointer_type (struct die_info *die, struct dwarf2_cu *cu)
14598 {
14599   struct gdbarch *gdbarch = get_objfile_arch (cu->objfile);
14600   struct comp_unit_head *cu_header = &cu->header;
14601   struct type *type;
14602   struct attribute *attr_byte_size;
14603   struct attribute *attr_address_class;
14604   int byte_size, addr_class;
14605   struct type *target_type;
14606
14607   target_type = die_type (die, cu);
14608
14609   /* The die_type call above may have already set the type for this DIE.  */
14610   type = get_die_type (die, cu);
14611   if (type)
14612     return type;
14613
14614   type = lookup_pointer_type (target_type);
14615
14616   attr_byte_size = dwarf2_attr (die, DW_AT_byte_size, cu);
14617   if (attr_byte_size)
14618     byte_size = DW_UNSND (attr_byte_size);
14619   else
14620     byte_size = cu_header->addr_size;
14621
14622   attr_address_class = dwarf2_attr (die, DW_AT_address_class, cu);
14623   if (attr_address_class)
14624     addr_class = DW_UNSND (attr_address_class);
14625   else
14626     addr_class = DW_ADDR_none;
14627
14628   /* If the pointer size or address class is different than the
14629      default, create a type variant marked as such and set the
14630      length accordingly.  */
14631   if (TYPE_LENGTH (type) != byte_size || addr_class != DW_ADDR_none)
14632     {
14633       if (gdbarch_address_class_type_flags_p (gdbarch))
14634         {
14635           int type_flags;
14636
14637           type_flags = gdbarch_address_class_type_flags
14638                          (gdbarch, byte_size, addr_class);
14639           gdb_assert ((type_flags & ~TYPE_INSTANCE_FLAG_ADDRESS_CLASS_ALL)
14640                       == 0);
14641           type = make_type_with_address_space (type, type_flags);
14642         }
14643       else if (TYPE_LENGTH (type) != byte_size)
14644         {
14645           complaint (&symfile_complaints,
14646                      _("invalid pointer size %d"), byte_size);
14647         }
14648       else
14649         {
14650           /* Should we also complain about unhandled address classes?  */
14651         }
14652     }
14653
14654   TYPE_LENGTH (type) = byte_size;
14655   return set_die_type (die, type, cu);
14656 }
14657
14658 /* Extract all information from a DW_TAG_ptr_to_member_type DIE and add to
14659    the user defined type vector.  */
14660
14661 static struct type *
14662 read_tag_ptr_to_member_type (struct die_info *die, struct dwarf2_cu *cu)
14663 {
14664   struct type *type;
14665   struct type *to_type;
14666   struct type *domain;
14667
14668   to_type = die_type (die, cu);
14669   domain = die_containing_type (die, cu);
14670
14671   /* The calls above may have already set the type for this DIE.  */
14672   type = get_die_type (die, cu);
14673   if (type)
14674     return type;
14675
14676   if (TYPE_CODE (check_typedef (to_type)) == TYPE_CODE_METHOD)
14677     type = lookup_methodptr_type (to_type);
14678   else if (TYPE_CODE (check_typedef (to_type)) == TYPE_CODE_FUNC)
14679     {
14680       struct type *new_type = alloc_type (cu->objfile);
14681
14682       smash_to_method_type (new_type, domain, TYPE_TARGET_TYPE (to_type),
14683                             TYPE_FIELDS (to_type), TYPE_NFIELDS (to_type),
14684                             TYPE_VARARGS (to_type));
14685       type = lookup_methodptr_type (new_type);
14686     }
14687   else
14688     type = lookup_memberptr_type (to_type, domain);
14689
14690   return set_die_type (die, type, cu);
14691 }
14692
14693 /* Extract all information from a DW_TAG_{rvalue_,}reference_type DIE and add to
14694    the user defined type vector.  */
14695
14696 static struct type *
14697 read_tag_reference_type (struct die_info *die, struct dwarf2_cu *cu,
14698                           enum type_code refcode)
14699 {
14700   struct comp_unit_head *cu_header = &cu->header;
14701   struct type *type, *target_type;
14702   struct attribute *attr;
14703
14704   gdb_assert (refcode == TYPE_CODE_REF || refcode == TYPE_CODE_RVALUE_REF);
14705
14706   target_type = die_type (die, cu);
14707
14708   /* The die_type call above may have already set the type for this DIE.  */
14709   type = get_die_type (die, cu);
14710   if (type)
14711     return type;
14712
14713   type = lookup_reference_type (target_type, refcode);
14714   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
14715   if (attr)
14716     {
14717       TYPE_LENGTH (type) = DW_UNSND (attr);
14718     }
14719   else
14720     {
14721       TYPE_LENGTH (type) = cu_header->addr_size;
14722     }
14723   return set_die_type (die, type, cu);
14724 }
14725
14726 /* Add the given cv-qualifiers to the element type of the array.  GCC
14727    outputs DWARF type qualifiers that apply to an array, not the
14728    element type.  But GDB relies on the array element type to carry
14729    the cv-qualifiers.  This mimics section 6.7.3 of the C99
14730    specification.  */
14731
14732 static struct type *
14733 add_array_cv_type (struct die_info *die, struct dwarf2_cu *cu,
14734                    struct type *base_type, int cnst, int voltl)
14735 {
14736   struct type *el_type, *inner_array;
14737
14738   base_type = copy_type (base_type);
14739   inner_array = base_type;
14740
14741   while (TYPE_CODE (TYPE_TARGET_TYPE (inner_array)) == TYPE_CODE_ARRAY)
14742     {
14743       TYPE_TARGET_TYPE (inner_array) =
14744         copy_type (TYPE_TARGET_TYPE (inner_array));
14745       inner_array = TYPE_TARGET_TYPE (inner_array);
14746     }
14747
14748   el_type = TYPE_TARGET_TYPE (inner_array);
14749   cnst |= TYPE_CONST (el_type);
14750   voltl |= TYPE_VOLATILE (el_type);
14751   TYPE_TARGET_TYPE (inner_array) = make_cv_type (cnst, voltl, el_type, NULL);
14752
14753   return set_die_type (die, base_type, cu);
14754 }
14755
14756 static struct type *
14757 read_tag_const_type (struct die_info *die, struct dwarf2_cu *cu)
14758 {
14759   struct type *base_type, *cv_type;
14760
14761   base_type = die_type (die, cu);
14762
14763   /* The die_type call above may have already set the type for this DIE.  */
14764   cv_type = get_die_type (die, cu);
14765   if (cv_type)
14766     return cv_type;
14767
14768   /* In case the const qualifier is applied to an array type, the element type
14769      is so qualified, not the array type (section 6.7.3 of C99).  */
14770   if (TYPE_CODE (base_type) == TYPE_CODE_ARRAY)
14771     return add_array_cv_type (die, cu, base_type, 1, 0);
14772
14773   cv_type = make_cv_type (1, TYPE_VOLATILE (base_type), base_type, 0);
14774   return set_die_type (die, cv_type, cu);
14775 }
14776
14777 static struct type *
14778 read_tag_volatile_type (struct die_info *die, struct dwarf2_cu *cu)
14779 {
14780   struct type *base_type, *cv_type;
14781
14782   base_type = die_type (die, cu);
14783
14784   /* The die_type call above may have already set the type for this DIE.  */
14785   cv_type = get_die_type (die, cu);
14786   if (cv_type)
14787     return cv_type;
14788
14789   /* In case the volatile qualifier is applied to an array type, the
14790      element type is so qualified, not the array type (section 6.7.3
14791      of C99).  */
14792   if (TYPE_CODE (base_type) == TYPE_CODE_ARRAY)
14793     return add_array_cv_type (die, cu, base_type, 0, 1);
14794
14795   cv_type = make_cv_type (TYPE_CONST (base_type), 1, base_type, 0);
14796   return set_die_type (die, cv_type, cu);
14797 }
14798
14799 /* Handle DW_TAG_restrict_type.  */
14800
14801 static struct type *
14802 read_tag_restrict_type (struct die_info *die, struct dwarf2_cu *cu)
14803 {
14804   struct type *base_type, *cv_type;
14805
14806   base_type = die_type (die, cu);
14807
14808   /* The die_type call above may have already set the type for this DIE.  */
14809   cv_type = get_die_type (die, cu);
14810   if (cv_type)
14811     return cv_type;
14812
14813   cv_type = make_restrict_type (base_type);
14814   return set_die_type (die, cv_type, cu);
14815 }
14816
14817 /* Handle DW_TAG_atomic_type.  */
14818
14819 static struct type *
14820 read_tag_atomic_type (struct die_info *die, struct dwarf2_cu *cu)
14821 {
14822   struct type *base_type, *cv_type;
14823
14824   base_type = die_type (die, cu);
14825
14826   /* The die_type call above may have already set the type for this DIE.  */
14827   cv_type = get_die_type (die, cu);
14828   if (cv_type)
14829     return cv_type;
14830
14831   cv_type = make_atomic_type (base_type);
14832   return set_die_type (die, cv_type, cu);
14833 }
14834
14835 /* Extract all information from a DW_TAG_string_type DIE and add to
14836    the user defined type vector.  It isn't really a user defined type,
14837    but it behaves like one, with other DIE's using an AT_user_def_type
14838    attribute to reference it.  */
14839
14840 static struct type *
14841 read_tag_string_type (struct die_info *die, struct dwarf2_cu *cu)
14842 {
14843   struct objfile *objfile = cu->objfile;
14844   struct gdbarch *gdbarch = get_objfile_arch (objfile);
14845   struct type *type, *range_type, *index_type, *char_type;
14846   struct attribute *attr;
14847   unsigned int length;
14848
14849   attr = dwarf2_attr (die, DW_AT_string_length, cu);
14850   if (attr)
14851     {
14852       length = DW_UNSND (attr);
14853     }
14854   else
14855     {
14856       /* Check for the DW_AT_byte_size attribute.  */
14857       attr = dwarf2_attr (die, DW_AT_byte_size, cu);
14858       if (attr)
14859         {
14860           length = DW_UNSND (attr);
14861         }
14862       else
14863         {
14864           length = 1;
14865         }
14866     }
14867
14868   index_type = objfile_type (objfile)->builtin_int;
14869   range_type = create_static_range_type (NULL, index_type, 1, length);
14870   char_type = language_string_char_type (cu->language_defn, gdbarch);
14871   type = create_string_type (NULL, char_type, range_type);
14872
14873   return set_die_type (die, type, cu);
14874 }
14875
14876 /* Assuming that DIE corresponds to a function, returns nonzero
14877    if the function is prototyped.  */
14878
14879 static int
14880 prototyped_function_p (struct die_info *die, struct dwarf2_cu *cu)
14881 {
14882   struct attribute *attr;
14883
14884   attr = dwarf2_attr (die, DW_AT_prototyped, cu);
14885   if (attr && (DW_UNSND (attr) != 0))
14886     return 1;
14887
14888   /* The DWARF standard implies that the DW_AT_prototyped attribute
14889      is only meaninful for C, but the concept also extends to other
14890      languages that allow unprototyped functions (Eg: Objective C).
14891      For all other languages, assume that functions are always
14892      prototyped.  */
14893   if (cu->language != language_c
14894       && cu->language != language_objc
14895       && cu->language != language_opencl)
14896     return 1;
14897
14898   /* RealView does not emit DW_AT_prototyped.  We can not distinguish
14899      prototyped and unprototyped functions; default to prototyped,
14900      since that is more common in modern code (and RealView warns
14901      about unprototyped functions).  */
14902   if (producer_is_realview (cu->producer))
14903     return 1;
14904
14905   return 0;
14906 }
14907
14908 /* Handle DIES due to C code like:
14909
14910    struct foo
14911    {
14912    int (*funcp)(int a, long l);
14913    int b;
14914    };
14915
14916    ('funcp' generates a DW_TAG_subroutine_type DIE).  */
14917
14918 static struct type *
14919 read_subroutine_type (struct die_info *die, struct dwarf2_cu *cu)
14920 {
14921   struct objfile *objfile = cu->objfile;
14922   struct type *type;            /* Type that this function returns.  */
14923   struct type *ftype;           /* Function that returns above type.  */
14924   struct attribute *attr;
14925
14926   type = die_type (die, cu);
14927
14928   /* The die_type call above may have already set the type for this DIE.  */
14929   ftype = get_die_type (die, cu);
14930   if (ftype)
14931     return ftype;
14932
14933   ftype = lookup_function_type (type);
14934
14935   if (prototyped_function_p (die, cu))
14936     TYPE_PROTOTYPED (ftype) = 1;
14937
14938   /* Store the calling convention in the type if it's available in
14939      the subroutine die.  Otherwise set the calling convention to
14940      the default value DW_CC_normal.  */
14941   attr = dwarf2_attr (die, DW_AT_calling_convention, cu);
14942   if (attr)
14943     TYPE_CALLING_CONVENTION (ftype) = DW_UNSND (attr);
14944   else if (cu->producer && strstr (cu->producer, "IBM XL C for OpenCL"))
14945     TYPE_CALLING_CONVENTION (ftype) = DW_CC_GDB_IBM_OpenCL;
14946   else
14947     TYPE_CALLING_CONVENTION (ftype) = DW_CC_normal;
14948
14949   /* Record whether the function returns normally to its caller or not
14950      if the DWARF producer set that information.  */
14951   attr = dwarf2_attr (die, DW_AT_noreturn, cu);
14952   if (attr && (DW_UNSND (attr) != 0))
14953     TYPE_NO_RETURN (ftype) = 1;
14954
14955   /* We need to add the subroutine type to the die immediately so
14956      we don't infinitely recurse when dealing with parameters
14957      declared as the same subroutine type.  */
14958   set_die_type (die, ftype, cu);
14959
14960   if (die->child != NULL)
14961     {
14962       struct type *void_type = objfile_type (objfile)->builtin_void;
14963       struct die_info *child_die;
14964       int nparams, iparams;
14965
14966       /* Count the number of parameters.
14967          FIXME: GDB currently ignores vararg functions, but knows about
14968          vararg member functions.  */
14969       nparams = 0;
14970       child_die = die->child;
14971       while (child_die && child_die->tag)
14972         {
14973           if (child_die->tag == DW_TAG_formal_parameter)
14974             nparams++;
14975           else if (child_die->tag == DW_TAG_unspecified_parameters)
14976             TYPE_VARARGS (ftype) = 1;
14977           child_die = sibling_die (child_die);
14978         }
14979
14980       /* Allocate storage for parameters and fill them in.  */
14981       TYPE_NFIELDS (ftype) = nparams;
14982       TYPE_FIELDS (ftype) = (struct field *)
14983         TYPE_ZALLOC (ftype, nparams * sizeof (struct field));
14984
14985       /* TYPE_FIELD_TYPE must never be NULL.  Pre-fill the array to ensure it
14986          even if we error out during the parameters reading below.  */
14987       for (iparams = 0; iparams < nparams; iparams++)
14988         TYPE_FIELD_TYPE (ftype, iparams) = void_type;
14989
14990       iparams = 0;
14991       child_die = die->child;
14992       while (child_die && child_die->tag)
14993         {
14994           if (child_die->tag == DW_TAG_formal_parameter)
14995             {
14996               struct type *arg_type;
14997
14998               /* DWARF version 2 has no clean way to discern C++
14999                  static and non-static member functions.  G++ helps
15000                  GDB by marking the first parameter for non-static
15001                  member functions (which is the this pointer) as
15002                  artificial.  We pass this information to
15003                  dwarf2_add_member_fn via TYPE_FIELD_ARTIFICIAL.
15004
15005                  DWARF version 3 added DW_AT_object_pointer, which GCC
15006                  4.5 does not yet generate.  */
15007               attr = dwarf2_attr (child_die, DW_AT_artificial, cu);
15008               if (attr)
15009                 TYPE_FIELD_ARTIFICIAL (ftype, iparams) = DW_UNSND (attr);
15010               else
15011                 TYPE_FIELD_ARTIFICIAL (ftype, iparams) = 0;
15012               arg_type = die_type (child_die, cu);
15013
15014               /* RealView does not mark THIS as const, which the testsuite
15015                  expects.  GCC marks THIS as const in method definitions,
15016                  but not in the class specifications (GCC PR 43053).  */
15017               if (cu->language == language_cplus && !TYPE_CONST (arg_type)
15018                   && TYPE_FIELD_ARTIFICIAL (ftype, iparams))
15019                 {
15020                   int is_this = 0;
15021                   struct dwarf2_cu *arg_cu = cu;
15022                   const char *name = dwarf2_name (child_die, cu);
15023
15024                   attr = dwarf2_attr (die, DW_AT_object_pointer, cu);
15025                   if (attr)
15026                     {
15027                       /* If the compiler emits this, use it.  */
15028                       if (follow_die_ref (die, attr, &arg_cu) == child_die)
15029                         is_this = 1;
15030                     }
15031                   else if (name && strcmp (name, "this") == 0)
15032                     /* Function definitions will have the argument names.  */
15033                     is_this = 1;
15034                   else if (name == NULL && iparams == 0)
15035                     /* Declarations may not have the names, so like
15036                        elsewhere in GDB, assume an artificial first
15037                        argument is "this".  */
15038                     is_this = 1;
15039
15040                   if (is_this)
15041                     arg_type = make_cv_type (1, TYPE_VOLATILE (arg_type),
15042                                              arg_type, 0);
15043                 }
15044
15045               TYPE_FIELD_TYPE (ftype, iparams) = arg_type;
15046               iparams++;
15047             }
15048           child_die = sibling_die (child_die);
15049         }
15050     }
15051
15052   return ftype;
15053 }
15054
15055 static struct type *
15056 read_typedef (struct die_info *die, struct dwarf2_cu *cu)
15057 {
15058   struct objfile *objfile = cu->objfile;
15059   const char *name = NULL;
15060   struct type *this_type, *target_type;
15061
15062   name = dwarf2_full_name (NULL, die, cu);
15063   this_type = init_type (objfile, TYPE_CODE_TYPEDEF, 0, name);
15064   TYPE_TARGET_STUB (this_type) = 1;
15065   set_die_type (die, this_type, cu);
15066   target_type = die_type (die, cu);
15067   if (target_type != this_type)
15068     TYPE_TARGET_TYPE (this_type) = target_type;
15069   else
15070     {
15071       /* Self-referential typedefs are, it seems, not allowed by the DWARF
15072          spec and cause infinite loops in GDB.  */
15073       complaint (&symfile_complaints,
15074                  _("Self-referential DW_TAG_typedef "
15075                    "- DIE at 0x%x [in module %s]"),
15076                  to_underlying (die->sect_off), objfile_name (objfile));
15077       TYPE_TARGET_TYPE (this_type) = NULL;
15078     }
15079   return this_type;
15080 }
15081
15082 /* Allocate a floating-point type of size BITS and name NAME.  Pass NAME_HINT
15083    (which may be different from NAME) to the architecture back-end to allow
15084    it to guess the correct format if necessary.  */
15085
15086 static struct type *
15087 dwarf2_init_float_type (struct objfile *objfile, int bits, const char *name,
15088                         const char *name_hint)
15089 {
15090   struct gdbarch *gdbarch = get_objfile_arch (objfile);
15091   const struct floatformat **format;
15092   struct type *type;
15093
15094   format = gdbarch_floatformat_for_type (gdbarch, name_hint, bits);
15095   if (format)
15096     type = init_float_type (objfile, bits, name, format);
15097   else
15098     type = init_type (objfile, TYPE_CODE_ERROR, bits / TARGET_CHAR_BIT, name);
15099
15100   return type;
15101 }
15102
15103 /* Find a representation of a given base type and install
15104    it in the TYPE field of the die.  */
15105
15106 static struct type *
15107 read_base_type (struct die_info *die, struct dwarf2_cu *cu)
15108 {
15109   struct objfile *objfile = cu->objfile;
15110   struct type *type;
15111   struct attribute *attr;
15112   int encoding = 0, bits = 0;
15113   const char *name;
15114
15115   attr = dwarf2_attr (die, DW_AT_encoding, cu);
15116   if (attr)
15117     {
15118       encoding = DW_UNSND (attr);
15119     }
15120   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
15121   if (attr)
15122     {
15123       bits = DW_UNSND (attr) * TARGET_CHAR_BIT;
15124     }
15125   name = dwarf2_name (die, cu);
15126   if (!name)
15127     {
15128       complaint (&symfile_complaints,
15129                  _("DW_AT_name missing from DW_TAG_base_type"));
15130     }
15131
15132   switch (encoding)
15133     {
15134       case DW_ATE_address:
15135         /* Turn DW_ATE_address into a void * pointer.  */
15136         type = init_type (objfile, TYPE_CODE_VOID, 1, NULL);
15137         type = init_pointer_type (objfile, bits, name, type);
15138         break;
15139       case DW_ATE_boolean:
15140         type = init_boolean_type (objfile, bits, 1, name);
15141         break;
15142       case DW_ATE_complex_float:
15143         type = dwarf2_init_float_type (objfile, bits / 2, NULL, name);
15144         type = init_complex_type (objfile, name, type);
15145         break;
15146       case DW_ATE_decimal_float:
15147         type = init_decfloat_type (objfile, bits, name);
15148         break;
15149       case DW_ATE_float:
15150         type = dwarf2_init_float_type (objfile, bits, name, name);
15151         break;
15152       case DW_ATE_signed:
15153         type = init_integer_type (objfile, bits, 0, name);
15154         break;
15155       case DW_ATE_unsigned:
15156         if (cu->language == language_fortran
15157             && name
15158             && startswith (name, "character("))
15159           type = init_character_type (objfile, bits, 1, name);
15160         else
15161           type = init_integer_type (objfile, bits, 1, name);
15162         break;
15163       case DW_ATE_signed_char:
15164         if (cu->language == language_ada || cu->language == language_m2
15165             || cu->language == language_pascal
15166             || cu->language == language_fortran)
15167           type = init_character_type (objfile, bits, 0, name);
15168         else
15169           type = init_integer_type (objfile, bits, 0, name);
15170         break;
15171       case DW_ATE_unsigned_char:
15172         if (cu->language == language_ada || cu->language == language_m2
15173             || cu->language == language_pascal
15174             || cu->language == language_fortran
15175             || cu->language == language_rust)
15176           type = init_character_type (objfile, bits, 1, name);
15177         else
15178           type = init_integer_type (objfile, bits, 1, name);
15179         break;
15180       case DW_ATE_UTF:
15181         {
15182           gdbarch *arch = get_objfile_arch (objfile);
15183
15184           if (bits == 16)
15185             type = builtin_type (arch)->builtin_char16;
15186           else if (bits == 32)
15187             type = builtin_type (arch)->builtin_char32;
15188           else
15189             {
15190               complaint (&symfile_complaints,
15191                          _("unsupported DW_ATE_UTF bit size: '%d'"),
15192                          bits);
15193               type = init_integer_type (objfile, bits, 1, name);
15194             }
15195           return set_die_type (die, type, cu);
15196         }
15197         break;
15198
15199       default:
15200         complaint (&symfile_complaints, _("unsupported DW_AT_encoding: '%s'"),
15201                    dwarf_type_encoding_name (encoding));
15202         type = init_type (objfile, TYPE_CODE_ERROR,
15203                           bits / TARGET_CHAR_BIT, name);
15204         break;
15205     }
15206
15207   if (name && strcmp (name, "char") == 0)
15208     TYPE_NOSIGN (type) = 1;
15209
15210   return set_die_type (die, type, cu);
15211 }
15212
15213 /* Parse dwarf attribute if it's a block, reference or constant and put the
15214    resulting value of the attribute into struct bound_prop.
15215    Returns 1 if ATTR could be resolved into PROP, 0 otherwise.  */
15216
15217 static int
15218 attr_to_dynamic_prop (const struct attribute *attr, struct die_info *die,
15219                       struct dwarf2_cu *cu, struct dynamic_prop *prop)
15220 {
15221   struct dwarf2_property_baton *baton;
15222   struct obstack *obstack = &cu->objfile->objfile_obstack;
15223
15224   if (attr == NULL || prop == NULL)
15225     return 0;
15226
15227   if (attr_form_is_block (attr))
15228     {
15229       baton = XOBNEW (obstack, struct dwarf2_property_baton);
15230       baton->referenced_type = NULL;
15231       baton->locexpr.per_cu = cu->per_cu;
15232       baton->locexpr.size = DW_BLOCK (attr)->size;
15233       baton->locexpr.data = DW_BLOCK (attr)->data;
15234       prop->data.baton = baton;
15235       prop->kind = PROP_LOCEXPR;
15236       gdb_assert (prop->data.baton != NULL);
15237     }
15238   else if (attr_form_is_ref (attr))
15239     {
15240       struct dwarf2_cu *target_cu = cu;
15241       struct die_info *target_die;
15242       struct attribute *target_attr;
15243
15244       target_die = follow_die_ref (die, attr, &target_cu);
15245       target_attr = dwarf2_attr (target_die, DW_AT_location, target_cu);
15246       if (target_attr == NULL)
15247         target_attr = dwarf2_attr (target_die, DW_AT_data_member_location,
15248                                    target_cu);
15249       if (target_attr == NULL)
15250         return 0;
15251
15252       switch (target_attr->name)
15253         {
15254           case DW_AT_location:
15255             if (attr_form_is_section_offset (target_attr))
15256               {
15257                 baton = XOBNEW (obstack, struct dwarf2_property_baton);
15258                 baton->referenced_type = die_type (target_die, target_cu);
15259                 fill_in_loclist_baton (cu, &baton->loclist, target_attr);
15260                 prop->data.baton = baton;
15261                 prop->kind = PROP_LOCLIST;
15262                 gdb_assert (prop->data.baton != NULL);
15263               }
15264             else if (attr_form_is_block (target_attr))
15265               {
15266                 baton = XOBNEW (obstack, struct dwarf2_property_baton);
15267                 baton->referenced_type = die_type (target_die, target_cu);
15268                 baton->locexpr.per_cu = cu->per_cu;
15269                 baton->locexpr.size = DW_BLOCK (target_attr)->size;
15270                 baton->locexpr.data = DW_BLOCK (target_attr)->data;
15271                 prop->data.baton = baton;
15272                 prop->kind = PROP_LOCEXPR;
15273                 gdb_assert (prop->data.baton != NULL);
15274               }
15275             else
15276               {
15277                 dwarf2_invalid_attrib_class_complaint ("DW_AT_location",
15278                                                        "dynamic property");
15279                 return 0;
15280               }
15281             break;
15282           case DW_AT_data_member_location:
15283             {
15284               LONGEST offset;
15285
15286               if (!handle_data_member_location (target_die, target_cu,
15287                                                 &offset))
15288                 return 0;
15289
15290               baton = XOBNEW (obstack, struct dwarf2_property_baton);
15291               baton->referenced_type = read_type_die (target_die->parent,
15292                                                       target_cu);
15293               baton->offset_info.offset = offset;
15294               baton->offset_info.type = die_type (target_die, target_cu);
15295               prop->data.baton = baton;
15296               prop->kind = PROP_ADDR_OFFSET;
15297               break;
15298             }
15299         }
15300     }
15301   else if (attr_form_is_constant (attr))
15302     {
15303       prop->data.const_val = dwarf2_get_attr_constant_value (attr, 0);
15304       prop->kind = PROP_CONST;
15305     }
15306   else
15307     {
15308       dwarf2_invalid_attrib_class_complaint (dwarf_form_name (attr->form),
15309                                              dwarf2_name (die, cu));
15310       return 0;
15311     }
15312
15313   return 1;
15314 }
15315
15316 /* Read the given DW_AT_subrange DIE.  */
15317
15318 static struct type *
15319 read_subrange_type (struct die_info *die, struct dwarf2_cu *cu)
15320 {
15321   struct type *base_type, *orig_base_type;
15322   struct type *range_type;
15323   struct attribute *attr;
15324   struct dynamic_prop low, high;
15325   int low_default_is_valid;
15326   int high_bound_is_count = 0;
15327   const char *name;
15328   LONGEST negative_mask;
15329
15330   orig_base_type = die_type (die, cu);
15331   /* If ORIG_BASE_TYPE is a typedef, it will not be TYPE_UNSIGNED,
15332      whereas the real type might be.  So, we use ORIG_BASE_TYPE when
15333      creating the range type, but we use the result of check_typedef
15334      when examining properties of the type.  */
15335   base_type = check_typedef (orig_base_type);
15336
15337   /* The die_type call above may have already set the type for this DIE.  */
15338   range_type = get_die_type (die, cu);
15339   if (range_type)
15340     return range_type;
15341
15342   low.kind = PROP_CONST;
15343   high.kind = PROP_CONST;
15344   high.data.const_val = 0;
15345
15346   /* Set LOW_DEFAULT_IS_VALID if current language and DWARF version allow
15347      omitting DW_AT_lower_bound.  */
15348   switch (cu->language)
15349     {
15350     case language_c:
15351     case language_cplus:
15352       low.data.const_val = 0;
15353       low_default_is_valid = 1;
15354       break;
15355     case language_fortran:
15356       low.data.const_val = 1;
15357       low_default_is_valid = 1;
15358       break;
15359     case language_d:
15360     case language_objc:
15361     case language_rust:
15362       low.data.const_val = 0;
15363       low_default_is_valid = (cu->header.version >= 4);
15364       break;
15365     case language_ada:
15366     case language_m2:
15367     case language_pascal:
15368       low.data.const_val = 1;
15369       low_default_is_valid = (cu->header.version >= 4);
15370       break;
15371     default:
15372       low.data.const_val = 0;
15373       low_default_is_valid = 0;
15374       break;
15375     }
15376
15377   attr = dwarf2_attr (die, DW_AT_lower_bound, cu);
15378   if (attr)
15379     attr_to_dynamic_prop (attr, die, cu, &low);
15380   else if (!low_default_is_valid)
15381     complaint (&symfile_complaints, _("Missing DW_AT_lower_bound "
15382                                       "- DIE at 0x%x [in module %s]"),
15383                to_underlying (die->sect_off), objfile_name (cu->objfile));
15384
15385   attr = dwarf2_attr (die, DW_AT_upper_bound, cu);
15386   if (!attr_to_dynamic_prop (attr, die, cu, &high))
15387     {
15388       attr = dwarf2_attr (die, DW_AT_count, cu);
15389       if (attr_to_dynamic_prop (attr, die, cu, &high))
15390         {
15391           /* If bounds are constant do the final calculation here.  */
15392           if (low.kind == PROP_CONST && high.kind == PROP_CONST)
15393             high.data.const_val = low.data.const_val + high.data.const_val - 1;
15394           else
15395             high_bound_is_count = 1;
15396         }
15397     }
15398
15399   /* Dwarf-2 specifications explicitly allows to create subrange types
15400      without specifying a base type.
15401      In that case, the base type must be set to the type of
15402      the lower bound, upper bound or count, in that order, if any of these
15403      three attributes references an object that has a type.
15404      If no base type is found, the Dwarf-2 specifications say that
15405      a signed integer type of size equal to the size of an address should
15406      be used.
15407      For the following C code: `extern char gdb_int [];'
15408      GCC produces an empty range DIE.
15409      FIXME: muller/2010-05-28: Possible references to object for low bound,
15410      high bound or count are not yet handled by this code.  */
15411   if (TYPE_CODE (base_type) == TYPE_CODE_VOID)
15412     {
15413       struct objfile *objfile = cu->objfile;
15414       struct gdbarch *gdbarch = get_objfile_arch (objfile);
15415       int addr_size = gdbarch_addr_bit (gdbarch) /8;
15416       struct type *int_type = objfile_type (objfile)->builtin_int;
15417
15418       /* Test "int", "long int", and "long long int" objfile types,
15419          and select the first one having a size above or equal to the
15420          architecture address size.  */
15421       if (int_type && TYPE_LENGTH (int_type) >= addr_size)
15422         base_type = int_type;
15423       else
15424         {
15425           int_type = objfile_type (objfile)->builtin_long;
15426           if (int_type && TYPE_LENGTH (int_type) >= addr_size)
15427             base_type = int_type;
15428           else
15429             {
15430               int_type = objfile_type (objfile)->builtin_long_long;
15431               if (int_type && TYPE_LENGTH (int_type) >= addr_size)
15432                 base_type = int_type;
15433             }
15434         }
15435     }
15436
15437   /* Normally, the DWARF producers are expected to use a signed
15438      constant form (Eg. DW_FORM_sdata) to express negative bounds.
15439      But this is unfortunately not always the case, as witnessed
15440      with GCC, for instance, where the ambiguous DW_FORM_dataN form
15441      is used instead.  To work around that ambiguity, we treat
15442      the bounds as signed, and thus sign-extend their values, when
15443      the base type is signed.  */
15444   negative_mask =
15445     -((LONGEST) 1 << (TYPE_LENGTH (base_type) * TARGET_CHAR_BIT - 1));
15446   if (low.kind == PROP_CONST
15447       && !TYPE_UNSIGNED (base_type) && (low.data.const_val & negative_mask))
15448     low.data.const_val |= negative_mask;
15449   if (high.kind == PROP_CONST
15450       && !TYPE_UNSIGNED (base_type) && (high.data.const_val & negative_mask))
15451     high.data.const_val |= negative_mask;
15452
15453   range_type = create_range_type (NULL, orig_base_type, &low, &high);
15454
15455   if (high_bound_is_count)
15456     TYPE_RANGE_DATA (range_type)->flag_upper_bound_is_count = 1;
15457
15458   /* Ada expects an empty array on no boundary attributes.  */
15459   if (attr == NULL && cu->language != language_ada)
15460     TYPE_HIGH_BOUND_KIND (range_type) = PROP_UNDEFINED;
15461
15462   name = dwarf2_name (die, cu);
15463   if (name)
15464     TYPE_NAME (range_type) = name;
15465
15466   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
15467   if (attr)
15468     TYPE_LENGTH (range_type) = DW_UNSND (attr);
15469
15470   set_die_type (die, range_type, cu);
15471
15472   /* set_die_type should be already done.  */
15473   set_descriptive_type (range_type, die, cu);
15474
15475   return range_type;
15476 }
15477
15478 static struct type *
15479 read_unspecified_type (struct die_info *die, struct dwarf2_cu *cu)
15480 {
15481   struct type *type;
15482
15483   /* For now, we only support the C meaning of an unspecified type: void.  */
15484
15485   type = init_type (cu->objfile, TYPE_CODE_VOID, 0, NULL);
15486   TYPE_NAME (type) = dwarf2_name (die, cu);
15487
15488   return set_die_type (die, type, cu);
15489 }
15490
15491 /* Read a single die and all its descendents.  Set the die's sibling
15492    field to NULL; set other fields in the die correctly, and set all
15493    of the descendents' fields correctly.  Set *NEW_INFO_PTR to the
15494    location of the info_ptr after reading all of those dies.  PARENT
15495    is the parent of the die in question.  */
15496
15497 static struct die_info *
15498 read_die_and_children (const struct die_reader_specs *reader,
15499                        const gdb_byte *info_ptr,
15500                        const gdb_byte **new_info_ptr,
15501                        struct die_info *parent)
15502 {
15503   struct die_info *die;
15504   const gdb_byte *cur_ptr;
15505   int has_children;
15506
15507   cur_ptr = read_full_die_1 (reader, &die, info_ptr, &has_children, 0);
15508   if (die == NULL)
15509     {
15510       *new_info_ptr = cur_ptr;
15511       return NULL;
15512     }
15513   store_in_ref_table (die, reader->cu);
15514
15515   if (has_children)
15516     die->child = read_die_and_siblings_1 (reader, cur_ptr, new_info_ptr, die);
15517   else
15518     {
15519       die->child = NULL;
15520       *new_info_ptr = cur_ptr;
15521     }
15522
15523   die->sibling = NULL;
15524   die->parent = parent;
15525   return die;
15526 }
15527
15528 /* Read a die, all of its descendents, and all of its siblings; set
15529    all of the fields of all of the dies correctly.  Arguments are as
15530    in read_die_and_children.  */
15531
15532 static struct die_info *
15533 read_die_and_siblings_1 (const struct die_reader_specs *reader,
15534                          const gdb_byte *info_ptr,
15535                          const gdb_byte **new_info_ptr,
15536                          struct die_info *parent)
15537 {
15538   struct die_info *first_die, *last_sibling;
15539   const gdb_byte *cur_ptr;
15540
15541   cur_ptr = info_ptr;
15542   first_die = last_sibling = NULL;
15543
15544   while (1)
15545     {
15546       struct die_info *die
15547         = read_die_and_children (reader, cur_ptr, &cur_ptr, parent);
15548
15549       if (die == NULL)
15550         {
15551           *new_info_ptr = cur_ptr;
15552           return first_die;
15553         }
15554
15555       if (!first_die)
15556         first_die = die;
15557       else
15558         last_sibling->sibling = die;
15559
15560       last_sibling = die;
15561     }
15562 }
15563
15564 /* Read a die, all of its descendents, and all of its siblings; set
15565    all of the fields of all of the dies correctly.  Arguments are as
15566    in read_die_and_children.
15567    This the main entry point for reading a DIE and all its children.  */
15568
15569 static struct die_info *
15570 read_die_and_siblings (const struct die_reader_specs *reader,
15571                        const gdb_byte *info_ptr,
15572                        const gdb_byte **new_info_ptr,
15573                        struct die_info *parent)
15574 {
15575   struct die_info *die = read_die_and_siblings_1 (reader, info_ptr,
15576                                                   new_info_ptr, parent);
15577
15578   if (dwarf_die_debug)
15579     {
15580       fprintf_unfiltered (gdb_stdlog,
15581                           "Read die from %s@0x%x of %s:\n",
15582                           get_section_name (reader->die_section),
15583                           (unsigned) (info_ptr - reader->die_section->buffer),
15584                           bfd_get_filename (reader->abfd));
15585       dump_die (die, dwarf_die_debug);
15586     }
15587
15588   return die;
15589 }
15590
15591 /* Read a die and all its attributes, leave space for NUM_EXTRA_ATTRS
15592    attributes.
15593    The caller is responsible for filling in the extra attributes
15594    and updating (*DIEP)->num_attrs.
15595    Set DIEP to point to a newly allocated die with its information,
15596    except for its child, sibling, and parent fields.
15597    Set HAS_CHILDREN to tell whether the die has children or not.  */
15598
15599 static const gdb_byte *
15600 read_full_die_1 (const struct die_reader_specs *reader,
15601                  struct die_info **diep, const gdb_byte *info_ptr,
15602                  int *has_children, int num_extra_attrs)
15603 {
15604   unsigned int abbrev_number, bytes_read, i;
15605   struct abbrev_info *abbrev;
15606   struct die_info *die;
15607   struct dwarf2_cu *cu = reader->cu;
15608   bfd *abfd = reader->abfd;
15609
15610   sect_offset sect_off = (sect_offset) (info_ptr - reader->buffer);
15611   abbrev_number = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
15612   info_ptr += bytes_read;
15613   if (!abbrev_number)
15614     {
15615       *diep = NULL;
15616       *has_children = 0;
15617       return info_ptr;
15618     }
15619
15620   abbrev = abbrev_table_lookup_abbrev (cu->abbrev_table, abbrev_number);
15621   if (!abbrev)
15622     error (_("Dwarf Error: could not find abbrev number %d [in module %s]"),
15623            abbrev_number,
15624            bfd_get_filename (abfd));
15625
15626   die = dwarf_alloc_die (cu, abbrev->num_attrs + num_extra_attrs);
15627   die->sect_off = sect_off;
15628   die->tag = abbrev->tag;
15629   die->abbrev = abbrev_number;
15630
15631   /* Make the result usable.
15632      The caller needs to update num_attrs after adding the extra
15633      attributes.  */
15634   die->num_attrs = abbrev->num_attrs;
15635
15636   for (i = 0; i < abbrev->num_attrs; ++i)
15637     info_ptr = read_attribute (reader, &die->attrs[i], &abbrev->attrs[i],
15638                                info_ptr);
15639
15640   *diep = die;
15641   *has_children = abbrev->has_children;
15642   return info_ptr;
15643 }
15644
15645 /* Read a die and all its attributes.
15646    Set DIEP to point to a newly allocated die with its information,
15647    except for its child, sibling, and parent fields.
15648    Set HAS_CHILDREN to tell whether the die has children or not.  */
15649
15650 static const gdb_byte *
15651 read_full_die (const struct die_reader_specs *reader,
15652                struct die_info **diep, const gdb_byte *info_ptr,
15653                int *has_children)
15654 {
15655   const gdb_byte *result;
15656
15657   result = read_full_die_1 (reader, diep, info_ptr, has_children, 0);
15658
15659   if (dwarf_die_debug)
15660     {
15661       fprintf_unfiltered (gdb_stdlog,
15662                           "Read die from %s@0x%x of %s:\n",
15663                           get_section_name (reader->die_section),
15664                           (unsigned) (info_ptr - reader->die_section->buffer),
15665                           bfd_get_filename (reader->abfd));
15666       dump_die (*diep, dwarf_die_debug);
15667     }
15668
15669   return result;
15670 }
15671 \f
15672 /* Abbreviation tables.
15673
15674    In DWARF version 2, the description of the debugging information is
15675    stored in a separate .debug_abbrev section.  Before we read any
15676    dies from a section we read in all abbreviations and install them
15677    in a hash table.  */
15678
15679 /* Allocate space for a struct abbrev_info object in ABBREV_TABLE.  */
15680
15681 static struct abbrev_info *
15682 abbrev_table_alloc_abbrev (struct abbrev_table *abbrev_table)
15683 {
15684   struct abbrev_info *abbrev;
15685
15686   abbrev = XOBNEW (&abbrev_table->abbrev_obstack, struct abbrev_info);
15687   memset (abbrev, 0, sizeof (struct abbrev_info));
15688
15689   return abbrev;
15690 }
15691
15692 /* Add an abbreviation to the table.  */
15693
15694 static void
15695 abbrev_table_add_abbrev (struct abbrev_table *abbrev_table,
15696                          unsigned int abbrev_number,
15697                          struct abbrev_info *abbrev)
15698 {
15699   unsigned int hash_number;
15700
15701   hash_number = abbrev_number % ABBREV_HASH_SIZE;
15702   abbrev->next = abbrev_table->abbrevs[hash_number];
15703   abbrev_table->abbrevs[hash_number] = abbrev;
15704 }
15705
15706 /* Look up an abbrev in the table.
15707    Returns NULL if the abbrev is not found.  */
15708
15709 static struct abbrev_info *
15710 abbrev_table_lookup_abbrev (const struct abbrev_table *abbrev_table,
15711                             unsigned int abbrev_number)
15712 {
15713   unsigned int hash_number;
15714   struct abbrev_info *abbrev;
15715
15716   hash_number = abbrev_number % ABBREV_HASH_SIZE;
15717   abbrev = abbrev_table->abbrevs[hash_number];
15718
15719   while (abbrev)
15720     {
15721       if (abbrev->number == abbrev_number)
15722         return abbrev;
15723       abbrev = abbrev->next;
15724     }
15725   return NULL;
15726 }
15727
15728 /* Read in an abbrev table.  */
15729
15730 static struct abbrev_table *
15731 abbrev_table_read_table (struct dwarf2_section_info *section,
15732                          sect_offset sect_off)
15733 {
15734   struct objfile *objfile = dwarf2_per_objfile->objfile;
15735   bfd *abfd = get_section_bfd_owner (section);
15736   struct abbrev_table *abbrev_table;
15737   const gdb_byte *abbrev_ptr;
15738   struct abbrev_info *cur_abbrev;
15739   unsigned int abbrev_number, bytes_read, abbrev_name;
15740   unsigned int abbrev_form;
15741   struct attr_abbrev *cur_attrs;
15742   unsigned int allocated_attrs;
15743
15744   abbrev_table = XNEW (struct abbrev_table);
15745   abbrev_table->sect_off = sect_off;
15746   obstack_init (&abbrev_table->abbrev_obstack);
15747   abbrev_table->abbrevs =
15748     XOBNEWVEC (&abbrev_table->abbrev_obstack, struct abbrev_info *,
15749                ABBREV_HASH_SIZE);
15750   memset (abbrev_table->abbrevs, 0,
15751           ABBREV_HASH_SIZE * sizeof (struct abbrev_info *));
15752
15753   dwarf2_read_section (objfile, section);
15754   abbrev_ptr = section->buffer + to_underlying (sect_off);
15755   abbrev_number = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
15756   abbrev_ptr += bytes_read;
15757
15758   allocated_attrs = ATTR_ALLOC_CHUNK;
15759   cur_attrs = XNEWVEC (struct attr_abbrev, allocated_attrs);
15760
15761   /* Loop until we reach an abbrev number of 0.  */
15762   while (abbrev_number)
15763     {
15764       cur_abbrev = abbrev_table_alloc_abbrev (abbrev_table);
15765
15766       /* read in abbrev header */
15767       cur_abbrev->number = abbrev_number;
15768       cur_abbrev->tag
15769         = (enum dwarf_tag) read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
15770       abbrev_ptr += bytes_read;
15771       cur_abbrev->has_children = read_1_byte (abfd, abbrev_ptr);
15772       abbrev_ptr += 1;
15773
15774       /* now read in declarations */
15775       for (;;)
15776         {
15777           LONGEST implicit_const;
15778
15779           abbrev_name = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
15780           abbrev_ptr += bytes_read;
15781           abbrev_form = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
15782           abbrev_ptr += bytes_read;
15783           if (abbrev_form == DW_FORM_implicit_const)
15784             {
15785               implicit_const = read_signed_leb128 (abfd, abbrev_ptr,
15786                                                    &bytes_read);
15787               abbrev_ptr += bytes_read;
15788             }
15789           else
15790             {
15791               /* Initialize it due to a false compiler warning.  */
15792               implicit_const = -1;
15793             }
15794
15795           if (abbrev_name == 0)
15796             break;
15797
15798           if (cur_abbrev->num_attrs == allocated_attrs)
15799             {
15800               allocated_attrs += ATTR_ALLOC_CHUNK;
15801               cur_attrs
15802                 = XRESIZEVEC (struct attr_abbrev, cur_attrs, allocated_attrs);
15803             }
15804
15805           cur_attrs[cur_abbrev->num_attrs].name
15806             = (enum dwarf_attribute) abbrev_name;
15807           cur_attrs[cur_abbrev->num_attrs].form
15808             = (enum dwarf_form) abbrev_form;
15809           cur_attrs[cur_abbrev->num_attrs].implicit_const = implicit_const;
15810           ++cur_abbrev->num_attrs;
15811         }
15812
15813       cur_abbrev->attrs =
15814         XOBNEWVEC (&abbrev_table->abbrev_obstack, struct attr_abbrev,
15815                    cur_abbrev->num_attrs);
15816       memcpy (cur_abbrev->attrs, cur_attrs,
15817               cur_abbrev->num_attrs * sizeof (struct attr_abbrev));
15818
15819       abbrev_table_add_abbrev (abbrev_table, abbrev_number, cur_abbrev);
15820
15821       /* Get next abbreviation.
15822          Under Irix6 the abbreviations for a compilation unit are not
15823          always properly terminated with an abbrev number of 0.
15824          Exit loop if we encounter an abbreviation which we have
15825          already read (which means we are about to read the abbreviations
15826          for the next compile unit) or if the end of the abbreviation
15827          table is reached.  */
15828       if ((unsigned int) (abbrev_ptr - section->buffer) >= section->size)
15829         break;
15830       abbrev_number = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
15831       abbrev_ptr += bytes_read;
15832       if (abbrev_table_lookup_abbrev (abbrev_table, abbrev_number) != NULL)
15833         break;
15834     }
15835
15836   xfree (cur_attrs);
15837   return abbrev_table;
15838 }
15839
15840 /* Free the resources held by ABBREV_TABLE.  */
15841
15842 static void
15843 abbrev_table_free (struct abbrev_table *abbrev_table)
15844 {
15845   obstack_free (&abbrev_table->abbrev_obstack, NULL);
15846   xfree (abbrev_table);
15847 }
15848
15849 /* Same as abbrev_table_free but as a cleanup.
15850    We pass in a pointer to the pointer to the table so that we can
15851    set the pointer to NULL when we're done.  It also simplifies
15852    build_type_psymtabs_1.  */
15853
15854 static void
15855 abbrev_table_free_cleanup (void *table_ptr)
15856 {
15857   struct abbrev_table **abbrev_table_ptr = (struct abbrev_table **) table_ptr;
15858
15859   if (*abbrev_table_ptr != NULL)
15860     abbrev_table_free (*abbrev_table_ptr);
15861   *abbrev_table_ptr = NULL;
15862 }
15863
15864 /* Read the abbrev table for CU from ABBREV_SECTION.  */
15865
15866 static void
15867 dwarf2_read_abbrevs (struct dwarf2_cu *cu,
15868                      struct dwarf2_section_info *abbrev_section)
15869 {
15870   cu->abbrev_table =
15871     abbrev_table_read_table (abbrev_section, cu->header.abbrev_sect_off);
15872 }
15873
15874 /* Release the memory used by the abbrev table for a compilation unit.  */
15875
15876 static void
15877 dwarf2_free_abbrev_table (void *ptr_to_cu)
15878 {
15879   struct dwarf2_cu *cu = (struct dwarf2_cu *) ptr_to_cu;
15880
15881   if (cu->abbrev_table != NULL)
15882     abbrev_table_free (cu->abbrev_table);
15883   /* Set this to NULL so that we SEGV if we try to read it later,
15884      and also because free_comp_unit verifies this is NULL.  */
15885   cu->abbrev_table = NULL;
15886 }
15887 \f
15888 /* Returns nonzero if TAG represents a type that we might generate a partial
15889    symbol for.  */
15890
15891 static int
15892 is_type_tag_for_partial (int tag)
15893 {
15894   switch (tag)
15895     {
15896 #if 0
15897     /* Some types that would be reasonable to generate partial symbols for,
15898        that we don't at present.  */
15899     case DW_TAG_array_type:
15900     case DW_TAG_file_type:
15901     case DW_TAG_ptr_to_member_type:
15902     case DW_TAG_set_type:
15903     case DW_TAG_string_type:
15904     case DW_TAG_subroutine_type:
15905 #endif
15906     case DW_TAG_base_type:
15907     case DW_TAG_class_type:
15908     case DW_TAG_interface_type:
15909     case DW_TAG_enumeration_type:
15910     case DW_TAG_structure_type:
15911     case DW_TAG_subrange_type:
15912     case DW_TAG_typedef:
15913     case DW_TAG_union_type:
15914       return 1;
15915     default:
15916       return 0;
15917     }
15918 }
15919
15920 /* Load all DIEs that are interesting for partial symbols into memory.  */
15921
15922 static struct partial_die_info *
15923 load_partial_dies (const struct die_reader_specs *reader,
15924                    const gdb_byte *info_ptr, int building_psymtab)
15925 {
15926   struct dwarf2_cu *cu = reader->cu;
15927   struct objfile *objfile = cu->objfile;
15928   struct partial_die_info *part_die;
15929   struct partial_die_info *parent_die, *last_die, *first_die = NULL;
15930   struct abbrev_info *abbrev;
15931   unsigned int bytes_read;
15932   unsigned int load_all = 0;
15933   int nesting_level = 1;
15934
15935   parent_die = NULL;
15936   last_die = NULL;
15937
15938   gdb_assert (cu->per_cu != NULL);
15939   if (cu->per_cu->load_all_dies)
15940     load_all = 1;
15941
15942   cu->partial_dies
15943     = htab_create_alloc_ex (cu->header.length / 12,
15944                             partial_die_hash,
15945                             partial_die_eq,
15946                             NULL,
15947                             &cu->comp_unit_obstack,
15948                             hashtab_obstack_allocate,
15949                             dummy_obstack_deallocate);
15950
15951   part_die = XOBNEW (&cu->comp_unit_obstack, struct partial_die_info);
15952
15953   while (1)
15954     {
15955       abbrev = peek_die_abbrev (info_ptr, &bytes_read, cu);
15956
15957       /* A NULL abbrev means the end of a series of children.  */
15958       if (abbrev == NULL)
15959         {
15960           if (--nesting_level == 0)
15961             {
15962               /* PART_DIE was probably the last thing allocated on the
15963                  comp_unit_obstack, so we could call obstack_free
15964                  here.  We don't do that because the waste is small,
15965                  and will be cleaned up when we're done with this
15966                  compilation unit.  This way, we're also more robust
15967                  against other users of the comp_unit_obstack.  */
15968               return first_die;
15969             }
15970           info_ptr += bytes_read;
15971           last_die = parent_die;
15972           parent_die = parent_die->die_parent;
15973           continue;
15974         }
15975
15976       /* Check for template arguments.  We never save these; if
15977          they're seen, we just mark the parent, and go on our way.  */
15978       if (parent_die != NULL
15979           && cu->language == language_cplus
15980           && (abbrev->tag == DW_TAG_template_type_param
15981               || abbrev->tag == DW_TAG_template_value_param))
15982         {
15983           parent_die->has_template_arguments = 1;
15984
15985           if (!load_all)
15986             {
15987               /* We don't need a partial DIE for the template argument.  */
15988               info_ptr = skip_one_die (reader, info_ptr + bytes_read, abbrev);
15989               continue;
15990             }
15991         }
15992
15993       /* We only recurse into c++ subprograms looking for template arguments.
15994          Skip their other children.  */
15995       if (!load_all
15996           && cu->language == language_cplus
15997           && parent_die != NULL
15998           && parent_die->tag == DW_TAG_subprogram)
15999         {
16000           info_ptr = skip_one_die (reader, info_ptr + bytes_read, abbrev);
16001           continue;
16002         }
16003
16004       /* Check whether this DIE is interesting enough to save.  Normally
16005          we would not be interested in members here, but there may be
16006          later variables referencing them via DW_AT_specification (for
16007          static members).  */
16008       if (!load_all
16009           && !is_type_tag_for_partial (abbrev->tag)
16010           && abbrev->tag != DW_TAG_constant
16011           && abbrev->tag != DW_TAG_enumerator
16012           && abbrev->tag != DW_TAG_subprogram
16013           && abbrev->tag != DW_TAG_lexical_block
16014           && abbrev->tag != DW_TAG_variable
16015           && abbrev->tag != DW_TAG_namespace
16016           && abbrev->tag != DW_TAG_module
16017           && abbrev->tag != DW_TAG_member
16018           && abbrev->tag != DW_TAG_imported_unit
16019           && abbrev->tag != DW_TAG_imported_declaration)
16020         {
16021           /* Otherwise we skip to the next sibling, if any.  */
16022           info_ptr = skip_one_die (reader, info_ptr + bytes_read, abbrev);
16023           continue;
16024         }
16025
16026       info_ptr = read_partial_die (reader, part_die, abbrev, bytes_read,
16027                                    info_ptr);
16028
16029       /* This two-pass algorithm for processing partial symbols has a
16030          high cost in cache pressure.  Thus, handle some simple cases
16031          here which cover the majority of C partial symbols.  DIEs
16032          which neither have specification tags in them, nor could have
16033          specification tags elsewhere pointing at them, can simply be
16034          processed and discarded.
16035
16036          This segment is also optional; scan_partial_symbols and
16037          add_partial_symbol will handle these DIEs if we chain
16038          them in normally.  When compilers which do not emit large
16039          quantities of duplicate debug information are more common,
16040          this code can probably be removed.  */
16041
16042       /* Any complete simple types at the top level (pretty much all
16043          of them, for a language without namespaces), can be processed
16044          directly.  */
16045       if (parent_die == NULL
16046           && part_die->has_specification == 0
16047           && part_die->is_declaration == 0
16048           && ((part_die->tag == DW_TAG_typedef && !part_die->has_children)
16049               || part_die->tag == DW_TAG_base_type
16050               || part_die->tag == DW_TAG_subrange_type))
16051         {
16052           if (building_psymtab && part_die->name != NULL)
16053             add_psymbol_to_list (part_die->name, strlen (part_die->name), 0,
16054                                  VAR_DOMAIN, LOC_TYPEDEF,
16055                                  &objfile->static_psymbols,
16056                                  0, cu->language, objfile);
16057           info_ptr = locate_pdi_sibling (reader, part_die, info_ptr);
16058           continue;
16059         }
16060
16061       /* The exception for DW_TAG_typedef with has_children above is
16062          a workaround of GCC PR debug/47510.  In the case of this complaint
16063          type_name_no_tag_or_error will error on such types later.
16064
16065          GDB skipped children of DW_TAG_typedef by the shortcut above and then
16066          it could not find the child DIEs referenced later, this is checked
16067          above.  In correct DWARF DW_TAG_typedef should have no children.  */
16068
16069       if (part_die->tag == DW_TAG_typedef && part_die->has_children)
16070         complaint (&symfile_complaints,
16071                    _("DW_TAG_typedef has childen - GCC PR debug/47510 bug "
16072                      "- DIE at 0x%x [in module %s]"),
16073                    to_underlying (part_die->sect_off), objfile_name (objfile));
16074
16075       /* If we're at the second level, and we're an enumerator, and
16076          our parent has no specification (meaning possibly lives in a
16077          namespace elsewhere), then we can add the partial symbol now
16078          instead of queueing it.  */
16079       if (part_die->tag == DW_TAG_enumerator
16080           && parent_die != NULL
16081           && parent_die->die_parent == NULL
16082           && parent_die->tag == DW_TAG_enumeration_type
16083           && parent_die->has_specification == 0)
16084         {
16085           if (part_die->name == NULL)
16086             complaint (&symfile_complaints,
16087                        _("malformed enumerator DIE ignored"));
16088           else if (building_psymtab)
16089             add_psymbol_to_list (part_die->name, strlen (part_die->name), 0,
16090                                  VAR_DOMAIN, LOC_CONST,
16091                                  cu->language == language_cplus
16092                                  ? &objfile->global_psymbols
16093                                  : &objfile->static_psymbols,
16094                                  0, cu->language, objfile);
16095
16096           info_ptr = locate_pdi_sibling (reader, part_die, info_ptr);
16097           continue;
16098         }
16099
16100       /* We'll save this DIE so link it in.  */
16101       part_die->die_parent = parent_die;
16102       part_die->die_sibling = NULL;
16103       part_die->die_child = NULL;
16104
16105       if (last_die && last_die == parent_die)
16106         last_die->die_child = part_die;
16107       else if (last_die)
16108         last_die->die_sibling = part_die;
16109
16110       last_die = part_die;
16111
16112       if (first_die == NULL)
16113         first_die = part_die;
16114
16115       /* Maybe add the DIE to the hash table.  Not all DIEs that we
16116          find interesting need to be in the hash table, because we
16117          also have the parent/sibling/child chains; only those that we
16118          might refer to by offset later during partial symbol reading.
16119
16120          For now this means things that might have be the target of a
16121          DW_AT_specification, DW_AT_abstract_origin, or
16122          DW_AT_extension.  DW_AT_extension will refer only to
16123          namespaces; DW_AT_abstract_origin refers to functions (and
16124          many things under the function DIE, but we do not recurse
16125          into function DIEs during partial symbol reading) and
16126          possibly variables as well; DW_AT_specification refers to
16127          declarations.  Declarations ought to have the DW_AT_declaration
16128          flag.  It happens that GCC forgets to put it in sometimes, but
16129          only for functions, not for types.
16130
16131          Adding more things than necessary to the hash table is harmless
16132          except for the performance cost.  Adding too few will result in
16133          wasted time in find_partial_die, when we reread the compilation
16134          unit with load_all_dies set.  */
16135
16136       if (load_all
16137           || abbrev->tag == DW_TAG_constant
16138           || abbrev->tag == DW_TAG_subprogram
16139           || abbrev->tag == DW_TAG_variable
16140           || abbrev->tag == DW_TAG_namespace
16141           || part_die->is_declaration)
16142         {
16143           void **slot;
16144
16145           slot = htab_find_slot_with_hash (cu->partial_dies, part_die,
16146                                            to_underlying (part_die->sect_off),
16147                                            INSERT);
16148           *slot = part_die;
16149         }
16150
16151       part_die = XOBNEW (&cu->comp_unit_obstack, struct partial_die_info);
16152
16153       /* For some DIEs we want to follow their children (if any).  For C
16154          we have no reason to follow the children of structures; for other
16155          languages we have to, so that we can get at method physnames
16156          to infer fully qualified class names, for DW_AT_specification,
16157          and for C++ template arguments.  For C++, we also look one level
16158          inside functions to find template arguments (if the name of the
16159          function does not already contain the template arguments).
16160
16161          For Ada, we need to scan the children of subprograms and lexical
16162          blocks as well because Ada allows the definition of nested
16163          entities that could be interesting for the debugger, such as
16164          nested subprograms for instance.  */
16165       if (last_die->has_children
16166           && (load_all
16167               || last_die->tag == DW_TAG_namespace
16168               || last_die->tag == DW_TAG_module
16169               || last_die->tag == DW_TAG_enumeration_type
16170               || (cu->language == language_cplus
16171                   && last_die->tag == DW_TAG_subprogram
16172                   && (last_die->name == NULL
16173                       || strchr (last_die->name, '<') == NULL))
16174               || (cu->language != language_c
16175                   && (last_die->tag == DW_TAG_class_type
16176                       || last_die->tag == DW_TAG_interface_type
16177                       || last_die->tag == DW_TAG_structure_type
16178                       || last_die->tag == DW_TAG_union_type))
16179               || (cu->language == language_ada
16180                   && (last_die->tag == DW_TAG_subprogram
16181                       || last_die->tag == DW_TAG_lexical_block))))
16182         {
16183           nesting_level++;
16184           parent_die = last_die;
16185           continue;
16186         }
16187
16188       /* Otherwise we skip to the next sibling, if any.  */
16189       info_ptr = locate_pdi_sibling (reader, last_die, info_ptr);
16190
16191       /* Back to the top, do it again.  */
16192     }
16193 }
16194
16195 /* Read a minimal amount of information into the minimal die structure.  */
16196
16197 static const gdb_byte *
16198 read_partial_die (const struct die_reader_specs *reader,
16199                   struct partial_die_info *part_die,
16200                   struct abbrev_info *abbrev, unsigned int abbrev_len,
16201                   const gdb_byte *info_ptr)
16202 {
16203   struct dwarf2_cu *cu = reader->cu;
16204   struct objfile *objfile = cu->objfile;
16205   const gdb_byte *buffer = reader->buffer;
16206   unsigned int i;
16207   struct attribute attr;
16208   int has_low_pc_attr = 0;
16209   int has_high_pc_attr = 0;
16210   int high_pc_relative = 0;
16211
16212   memset (part_die, 0, sizeof (struct partial_die_info));
16213
16214   part_die->sect_off = (sect_offset) (info_ptr - buffer);
16215
16216   info_ptr += abbrev_len;
16217
16218   if (abbrev == NULL)
16219     return info_ptr;
16220
16221   part_die->tag = abbrev->tag;
16222   part_die->has_children = abbrev->has_children;
16223
16224   for (i = 0; i < abbrev->num_attrs; ++i)
16225     {
16226       info_ptr = read_attribute (reader, &attr, &abbrev->attrs[i], info_ptr);
16227
16228       /* Store the data if it is of an attribute we want to keep in a
16229          partial symbol table.  */
16230       switch (attr.name)
16231         {
16232         case DW_AT_name:
16233           switch (part_die->tag)
16234             {
16235             case DW_TAG_compile_unit:
16236             case DW_TAG_partial_unit:
16237             case DW_TAG_type_unit:
16238               /* Compilation units have a DW_AT_name that is a filename, not
16239                  a source language identifier.  */
16240             case DW_TAG_enumeration_type:
16241             case DW_TAG_enumerator:
16242               /* These tags always have simple identifiers already; no need
16243                  to canonicalize them.  */
16244               part_die->name = DW_STRING (&attr);
16245               break;
16246             default:
16247               part_die->name
16248                 = dwarf2_canonicalize_name (DW_STRING (&attr), cu,
16249                                             &objfile->per_bfd->storage_obstack);
16250               break;
16251             }
16252           break;
16253         case DW_AT_linkage_name:
16254         case DW_AT_MIPS_linkage_name:
16255           /* Note that both forms of linkage name might appear.  We
16256              assume they will be the same, and we only store the last
16257              one we see.  */
16258           if (cu->language == language_ada)
16259             part_die->name = DW_STRING (&attr);
16260           part_die->linkage_name = DW_STRING (&attr);
16261           break;
16262         case DW_AT_low_pc:
16263           has_low_pc_attr = 1;
16264           part_die->lowpc = attr_value_as_address (&attr);
16265           break;
16266         case DW_AT_high_pc:
16267           has_high_pc_attr = 1;
16268           part_die->highpc = attr_value_as_address (&attr);
16269           if (cu->header.version >= 4 && attr_form_is_constant (&attr))
16270                 high_pc_relative = 1;
16271           break;
16272         case DW_AT_location:
16273           /* Support the .debug_loc offsets.  */
16274           if (attr_form_is_block (&attr))
16275             {
16276                part_die->d.locdesc = DW_BLOCK (&attr);
16277             }
16278           else if (attr_form_is_section_offset (&attr))
16279             {
16280               dwarf2_complex_location_expr_complaint ();
16281             }
16282           else
16283             {
16284               dwarf2_invalid_attrib_class_complaint ("DW_AT_location",
16285                                                      "partial symbol information");
16286             }
16287           break;
16288         case DW_AT_external:
16289           part_die->is_external = DW_UNSND (&attr);
16290           break;
16291         case DW_AT_declaration:
16292           part_die->is_declaration = DW_UNSND (&attr);
16293           break;
16294         case DW_AT_type:
16295           part_die->has_type = 1;
16296           break;
16297         case DW_AT_abstract_origin:
16298         case DW_AT_specification:
16299         case DW_AT_extension:
16300           part_die->has_specification = 1;
16301           part_die->spec_offset = dwarf2_get_ref_die_offset (&attr);
16302           part_die->spec_is_dwz = (attr.form == DW_FORM_GNU_ref_alt
16303                                    || cu->per_cu->is_dwz);
16304           break;
16305         case DW_AT_sibling:
16306           /* Ignore absolute siblings, they might point outside of
16307              the current compile unit.  */
16308           if (attr.form == DW_FORM_ref_addr)
16309             complaint (&symfile_complaints,
16310                        _("ignoring absolute DW_AT_sibling"));
16311           else
16312             {
16313               sect_offset off = dwarf2_get_ref_die_offset (&attr);
16314               const gdb_byte *sibling_ptr = buffer + to_underlying (off);
16315
16316               if (sibling_ptr < info_ptr)
16317                 complaint (&symfile_complaints,
16318                            _("DW_AT_sibling points backwards"));
16319               else if (sibling_ptr > reader->buffer_end)
16320                 dwarf2_section_buffer_overflow_complaint (reader->die_section);
16321               else
16322                 part_die->sibling = sibling_ptr;
16323             }
16324           break;
16325         case DW_AT_byte_size:
16326           part_die->has_byte_size = 1;
16327           break;
16328         case DW_AT_const_value:
16329           part_die->has_const_value = 1;
16330           break;
16331         case DW_AT_calling_convention:
16332           /* DWARF doesn't provide a way to identify a program's source-level
16333              entry point.  DW_AT_calling_convention attributes are only meant
16334              to describe functions' calling conventions.
16335
16336              However, because it's a necessary piece of information in
16337              Fortran, and before DWARF 4 DW_CC_program was the only
16338              piece of debugging information whose definition refers to
16339              a 'main program' at all, several compilers marked Fortran
16340              main programs with DW_CC_program --- even when those
16341              functions use the standard calling conventions.
16342
16343              Although DWARF now specifies a way to provide this
16344              information, we support this practice for backward
16345              compatibility.  */
16346           if (DW_UNSND (&attr) == DW_CC_program
16347               && cu->language == language_fortran)
16348             part_die->main_subprogram = 1;
16349           break;
16350         case DW_AT_inline:
16351           if (DW_UNSND (&attr) == DW_INL_inlined
16352               || DW_UNSND (&attr) == DW_INL_declared_inlined)
16353             part_die->may_be_inlined = 1;
16354           break;
16355
16356         case DW_AT_import:
16357           if (part_die->tag == DW_TAG_imported_unit)
16358             {
16359               part_die->d.sect_off = dwarf2_get_ref_die_offset (&attr);
16360               part_die->is_dwz = (attr.form == DW_FORM_GNU_ref_alt
16361                                   || cu->per_cu->is_dwz);
16362             }
16363           break;
16364
16365         case DW_AT_main_subprogram:
16366           part_die->main_subprogram = DW_UNSND (&attr);
16367           break;
16368
16369         default:
16370           break;
16371         }
16372     }
16373
16374   if (high_pc_relative)
16375     part_die->highpc += part_die->lowpc;
16376
16377   if (has_low_pc_attr && has_high_pc_attr)
16378     {
16379       /* When using the GNU linker, .gnu.linkonce. sections are used to
16380          eliminate duplicate copies of functions and vtables and such.
16381          The linker will arbitrarily choose one and discard the others.
16382          The AT_*_pc values for such functions refer to local labels in
16383          these sections.  If the section from that file was discarded, the
16384          labels are not in the output, so the relocs get a value of 0.
16385          If this is a discarded function, mark the pc bounds as invalid,
16386          so that GDB will ignore it.  */
16387       if (part_die->lowpc == 0 && !dwarf2_per_objfile->has_section_at_zero)
16388         {
16389           struct gdbarch *gdbarch = get_objfile_arch (objfile);
16390
16391           complaint (&symfile_complaints,
16392                      _("DW_AT_low_pc %s is zero "
16393                        "for DIE at 0x%x [in module %s]"),
16394                      paddress (gdbarch, part_die->lowpc),
16395                      to_underlying (part_die->sect_off), objfile_name (objfile));
16396         }
16397       /* dwarf2_get_pc_bounds has also the strict low < high requirement.  */
16398       else if (part_die->lowpc >= part_die->highpc)
16399         {
16400           struct gdbarch *gdbarch = get_objfile_arch (objfile);
16401
16402           complaint (&symfile_complaints,
16403                      _("DW_AT_low_pc %s is not < DW_AT_high_pc %s "
16404                        "for DIE at 0x%x [in module %s]"),
16405                      paddress (gdbarch, part_die->lowpc),
16406                      paddress (gdbarch, part_die->highpc),
16407                      to_underlying (part_die->sect_off),
16408                      objfile_name (objfile));
16409         }
16410       else
16411         part_die->has_pc_info = 1;
16412     }
16413
16414   return info_ptr;
16415 }
16416
16417 /* Find a cached partial DIE at OFFSET in CU.  */
16418
16419 static struct partial_die_info *
16420 find_partial_die_in_comp_unit (sect_offset sect_off, struct dwarf2_cu *cu)
16421 {
16422   struct partial_die_info *lookup_die = NULL;
16423   struct partial_die_info part_die;
16424
16425   part_die.sect_off = sect_off;
16426   lookup_die = ((struct partial_die_info *)
16427                 htab_find_with_hash (cu->partial_dies, &part_die,
16428                                      to_underlying (sect_off)));
16429
16430   return lookup_die;
16431 }
16432
16433 /* Find a partial DIE at OFFSET, which may or may not be in CU,
16434    except in the case of .debug_types DIEs which do not reference
16435    outside their CU (they do however referencing other types via
16436    DW_FORM_ref_sig8).  */
16437
16438 static struct partial_die_info *
16439 find_partial_die (sect_offset sect_off, int offset_in_dwz, struct dwarf2_cu *cu)
16440 {
16441   struct objfile *objfile = cu->objfile;
16442   struct dwarf2_per_cu_data *per_cu = NULL;
16443   struct partial_die_info *pd = NULL;
16444
16445   if (offset_in_dwz == cu->per_cu->is_dwz
16446       && offset_in_cu_p (&cu->header, sect_off))
16447     {
16448       pd = find_partial_die_in_comp_unit (sect_off, cu);
16449       if (pd != NULL)
16450         return pd;
16451       /* We missed recording what we needed.
16452          Load all dies and try again.  */
16453       per_cu = cu->per_cu;
16454     }
16455   else
16456     {
16457       /* TUs don't reference other CUs/TUs (except via type signatures).  */
16458       if (cu->per_cu->is_debug_types)
16459         {
16460           error (_("Dwarf Error: Type Unit at offset 0x%x contains"
16461                    " external reference to offset 0x%x [in module %s].\n"),
16462                  to_underlying (cu->header.sect_off), to_underlying (sect_off),
16463                  bfd_get_filename (objfile->obfd));
16464         }
16465       per_cu = dwarf2_find_containing_comp_unit (sect_off, offset_in_dwz,
16466                                                  objfile);
16467
16468       if (per_cu->cu == NULL || per_cu->cu->partial_dies == NULL)
16469         load_partial_comp_unit (per_cu);
16470
16471       per_cu->cu->last_used = 0;
16472       pd = find_partial_die_in_comp_unit (sect_off, per_cu->cu);
16473     }
16474
16475   /* If we didn't find it, and not all dies have been loaded,
16476      load them all and try again.  */
16477
16478   if (pd == NULL && per_cu->load_all_dies == 0)
16479     {
16480       per_cu->load_all_dies = 1;
16481
16482       /* This is nasty.  When we reread the DIEs, somewhere up the call chain
16483          THIS_CU->cu may already be in use.  So we can't just free it and
16484          replace its DIEs with the ones we read in.  Instead, we leave those
16485          DIEs alone (which can still be in use, e.g. in scan_partial_symbols),
16486          and clobber THIS_CU->cu->partial_dies with the hash table for the new
16487          set.  */
16488       load_partial_comp_unit (per_cu);
16489
16490       pd = find_partial_die_in_comp_unit (sect_off, per_cu->cu);
16491     }
16492
16493   if (pd == NULL)
16494     internal_error (__FILE__, __LINE__,
16495                     _("could not find partial DIE 0x%x "
16496                       "in cache [from module %s]\n"),
16497                     to_underlying (sect_off), bfd_get_filename (objfile->obfd));
16498   return pd;
16499 }
16500
16501 /* See if we can figure out if the class lives in a namespace.  We do
16502    this by looking for a member function; its demangled name will
16503    contain namespace info, if there is any.  */
16504
16505 static void
16506 guess_partial_die_structure_name (struct partial_die_info *struct_pdi,
16507                                   struct dwarf2_cu *cu)
16508 {
16509   /* NOTE: carlton/2003-10-07: Getting the info this way changes
16510      what template types look like, because the demangler
16511      frequently doesn't give the same name as the debug info.  We
16512      could fix this by only using the demangled name to get the
16513      prefix (but see comment in read_structure_type).  */
16514
16515   struct partial_die_info *real_pdi;
16516   struct partial_die_info *child_pdi;
16517
16518   /* If this DIE (this DIE's specification, if any) has a parent, then
16519      we should not do this.  We'll prepend the parent's fully qualified
16520      name when we create the partial symbol.  */
16521
16522   real_pdi = struct_pdi;
16523   while (real_pdi->has_specification)
16524     real_pdi = find_partial_die (real_pdi->spec_offset,
16525                                  real_pdi->spec_is_dwz, cu);
16526
16527   if (real_pdi->die_parent != NULL)
16528     return;
16529
16530   for (child_pdi = struct_pdi->die_child;
16531        child_pdi != NULL;
16532        child_pdi = child_pdi->die_sibling)
16533     {
16534       if (child_pdi->tag == DW_TAG_subprogram
16535           && child_pdi->linkage_name != NULL)
16536         {
16537           char *actual_class_name
16538             = language_class_name_from_physname (cu->language_defn,
16539                                                  child_pdi->linkage_name);
16540           if (actual_class_name != NULL)
16541             {
16542               struct_pdi->name
16543                 = ((const char *)
16544                    obstack_copy0 (&cu->objfile->per_bfd->storage_obstack,
16545                                   actual_class_name,
16546                                   strlen (actual_class_name)));
16547               xfree (actual_class_name);
16548             }
16549           break;
16550         }
16551     }
16552 }
16553
16554 /* Adjust PART_DIE before generating a symbol for it.  This function
16555    may set the is_external flag or change the DIE's name.  */
16556
16557 static void
16558 fixup_partial_die (struct partial_die_info *part_die,
16559                    struct dwarf2_cu *cu)
16560 {
16561   /* Once we've fixed up a die, there's no point in doing so again.
16562      This also avoids a memory leak if we were to call
16563      guess_partial_die_structure_name multiple times.  */
16564   if (part_die->fixup_called)
16565     return;
16566
16567   /* If we found a reference attribute and the DIE has no name, try
16568      to find a name in the referred to DIE.  */
16569
16570   if (part_die->name == NULL && part_die->has_specification)
16571     {
16572       struct partial_die_info *spec_die;
16573
16574       spec_die = find_partial_die (part_die->spec_offset,
16575                                    part_die->spec_is_dwz, cu);
16576
16577       fixup_partial_die (spec_die, cu);
16578
16579       if (spec_die->name)
16580         {
16581           part_die->name = spec_die->name;
16582
16583           /* Copy DW_AT_external attribute if it is set.  */
16584           if (spec_die->is_external)
16585             part_die->is_external = spec_die->is_external;
16586         }
16587     }
16588
16589   /* Set default names for some unnamed DIEs.  */
16590
16591   if (part_die->name == NULL && part_die->tag == DW_TAG_namespace)
16592     part_die->name = CP_ANONYMOUS_NAMESPACE_STR;
16593
16594   /* If there is no parent die to provide a namespace, and there are
16595      children, see if we can determine the namespace from their linkage
16596      name.  */
16597   if (cu->language == language_cplus
16598       && !VEC_empty (dwarf2_section_info_def, dwarf2_per_objfile->types)
16599       && part_die->die_parent == NULL
16600       && part_die->has_children
16601       && (part_die->tag == DW_TAG_class_type
16602           || part_die->tag == DW_TAG_structure_type
16603           || part_die->tag == DW_TAG_union_type))
16604     guess_partial_die_structure_name (part_die, cu);
16605
16606   /* GCC might emit a nameless struct or union that has a linkage
16607      name.  See http://gcc.gnu.org/bugzilla/show_bug.cgi?id=47510.  */
16608   if (part_die->name == NULL
16609       && (part_die->tag == DW_TAG_class_type
16610           || part_die->tag == DW_TAG_interface_type
16611           || part_die->tag == DW_TAG_structure_type
16612           || part_die->tag == DW_TAG_union_type)
16613       && part_die->linkage_name != NULL)
16614     {
16615       char *demangled;
16616
16617       demangled = gdb_demangle (part_die->linkage_name, DMGL_TYPES);
16618       if (demangled)
16619         {
16620           const char *base;
16621
16622           /* Strip any leading namespaces/classes, keep only the base name.
16623              DW_AT_name for named DIEs does not contain the prefixes.  */
16624           base = strrchr (demangled, ':');
16625           if (base && base > demangled && base[-1] == ':')
16626             base++;
16627           else
16628             base = demangled;
16629
16630           part_die->name
16631             = ((const char *)
16632                obstack_copy0 (&cu->objfile->per_bfd->storage_obstack,
16633                               base, strlen (base)));
16634           xfree (demangled);
16635         }
16636     }
16637
16638   part_die->fixup_called = 1;
16639 }
16640
16641 /* Read an attribute value described by an attribute form.  */
16642
16643 static const gdb_byte *
16644 read_attribute_value (const struct die_reader_specs *reader,
16645                       struct attribute *attr, unsigned form,
16646                       LONGEST implicit_const, const gdb_byte *info_ptr)
16647 {
16648   struct dwarf2_cu *cu = reader->cu;
16649   struct objfile *objfile = cu->objfile;
16650   struct gdbarch *gdbarch = get_objfile_arch (objfile);
16651   bfd *abfd = reader->abfd;
16652   struct comp_unit_head *cu_header = &cu->header;
16653   unsigned int bytes_read;
16654   struct dwarf_block *blk;
16655
16656   attr->form = (enum dwarf_form) form;
16657   switch (form)
16658     {
16659     case DW_FORM_ref_addr:
16660       if (cu->header.version == 2)
16661         DW_UNSND (attr) = read_address (abfd, info_ptr, cu, &bytes_read);
16662       else
16663         DW_UNSND (attr) = read_offset (abfd, info_ptr,
16664                                        &cu->header, &bytes_read);
16665       info_ptr += bytes_read;
16666       break;
16667     case DW_FORM_GNU_ref_alt:
16668       DW_UNSND (attr) = read_offset (abfd, info_ptr, &cu->header, &bytes_read);
16669       info_ptr += bytes_read;
16670       break;
16671     case DW_FORM_addr:
16672       DW_ADDR (attr) = read_address (abfd, info_ptr, cu, &bytes_read);
16673       DW_ADDR (attr) = gdbarch_adjust_dwarf2_addr (gdbarch, DW_ADDR (attr));
16674       info_ptr += bytes_read;
16675       break;
16676     case DW_FORM_block2:
16677       blk = dwarf_alloc_block (cu);
16678       blk->size = read_2_bytes (abfd, info_ptr);
16679       info_ptr += 2;
16680       blk->data = read_n_bytes (abfd, info_ptr, blk->size);
16681       info_ptr += blk->size;
16682       DW_BLOCK (attr) = blk;
16683       break;
16684     case DW_FORM_block4:
16685       blk = dwarf_alloc_block (cu);
16686       blk->size = read_4_bytes (abfd, info_ptr);
16687       info_ptr += 4;
16688       blk->data = read_n_bytes (abfd, info_ptr, blk->size);
16689       info_ptr += blk->size;
16690       DW_BLOCK (attr) = blk;
16691       break;
16692     case DW_FORM_data2:
16693       DW_UNSND (attr) = read_2_bytes (abfd, info_ptr);
16694       info_ptr += 2;
16695       break;
16696     case DW_FORM_data4:
16697       DW_UNSND (attr) = read_4_bytes (abfd, info_ptr);
16698       info_ptr += 4;
16699       break;
16700     case DW_FORM_data8:
16701       DW_UNSND (attr) = read_8_bytes (abfd, info_ptr);
16702       info_ptr += 8;
16703       break;
16704     case DW_FORM_data16:
16705       blk = dwarf_alloc_block (cu);
16706       blk->size = 16;
16707       blk->data = read_n_bytes (abfd, info_ptr, 16);
16708       info_ptr += 16;
16709       DW_BLOCK (attr) = blk;
16710       break;
16711     case DW_FORM_sec_offset:
16712       DW_UNSND (attr) = read_offset (abfd, info_ptr, &cu->header, &bytes_read);
16713       info_ptr += bytes_read;
16714       break;
16715     case DW_FORM_string:
16716       DW_STRING (attr) = read_direct_string (abfd, info_ptr, &bytes_read);
16717       DW_STRING_IS_CANONICAL (attr) = 0;
16718       info_ptr += bytes_read;
16719       break;
16720     case DW_FORM_strp:
16721       if (!cu->per_cu->is_dwz)
16722         {
16723           DW_STRING (attr) = read_indirect_string (abfd, info_ptr, cu_header,
16724                                                    &bytes_read);
16725           DW_STRING_IS_CANONICAL (attr) = 0;
16726           info_ptr += bytes_read;
16727           break;
16728         }
16729       /* FALLTHROUGH */
16730     case DW_FORM_line_strp:
16731       if (!cu->per_cu->is_dwz)
16732         {
16733           DW_STRING (attr) = read_indirect_line_string (abfd, info_ptr,
16734                                                         cu_header, &bytes_read);
16735           DW_STRING_IS_CANONICAL (attr) = 0;
16736           info_ptr += bytes_read;
16737           break;
16738         }
16739       /* FALLTHROUGH */
16740     case DW_FORM_GNU_strp_alt:
16741       {
16742         struct dwz_file *dwz = dwarf2_get_dwz_file ();
16743         LONGEST str_offset = read_offset (abfd, info_ptr, cu_header,
16744                                           &bytes_read);
16745
16746         DW_STRING (attr) = read_indirect_string_from_dwz (dwz, str_offset);
16747         DW_STRING_IS_CANONICAL (attr) = 0;
16748         info_ptr += bytes_read;
16749       }
16750       break;
16751     case DW_FORM_exprloc:
16752     case DW_FORM_block:
16753       blk = dwarf_alloc_block (cu);
16754       blk->size = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
16755       info_ptr += bytes_read;
16756       blk->data = read_n_bytes (abfd, info_ptr, blk->size);
16757       info_ptr += blk->size;
16758       DW_BLOCK (attr) = blk;
16759       break;
16760     case DW_FORM_block1:
16761       blk = dwarf_alloc_block (cu);
16762       blk->size = read_1_byte (abfd, info_ptr);
16763       info_ptr += 1;
16764       blk->data = read_n_bytes (abfd, info_ptr, blk->size);
16765       info_ptr += blk->size;
16766       DW_BLOCK (attr) = blk;
16767       break;
16768     case DW_FORM_data1:
16769       DW_UNSND (attr) = read_1_byte (abfd, info_ptr);
16770       info_ptr += 1;
16771       break;
16772     case DW_FORM_flag:
16773       DW_UNSND (attr) = read_1_byte (abfd, info_ptr);
16774       info_ptr += 1;
16775       break;
16776     case DW_FORM_flag_present:
16777       DW_UNSND (attr) = 1;
16778       break;
16779     case DW_FORM_sdata:
16780       DW_SND (attr) = read_signed_leb128 (abfd, info_ptr, &bytes_read);
16781       info_ptr += bytes_read;
16782       break;
16783     case DW_FORM_udata:
16784       DW_UNSND (attr) = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
16785       info_ptr += bytes_read;
16786       break;
16787     case DW_FORM_ref1:
16788       DW_UNSND (attr) = (to_underlying (cu->header.sect_off)
16789                          + read_1_byte (abfd, info_ptr));
16790       info_ptr += 1;
16791       break;
16792     case DW_FORM_ref2:
16793       DW_UNSND (attr) = (to_underlying (cu->header.sect_off)
16794                          + read_2_bytes (abfd, info_ptr));
16795       info_ptr += 2;
16796       break;
16797     case DW_FORM_ref4:
16798       DW_UNSND (attr) = (to_underlying (cu->header.sect_off)
16799                          + read_4_bytes (abfd, info_ptr));
16800       info_ptr += 4;
16801       break;
16802     case DW_FORM_ref8:
16803       DW_UNSND (attr) = (to_underlying (cu->header.sect_off)
16804                          + read_8_bytes (abfd, info_ptr));
16805       info_ptr += 8;
16806       break;
16807     case DW_FORM_ref_sig8:
16808       DW_SIGNATURE (attr) = read_8_bytes (abfd, info_ptr);
16809       info_ptr += 8;
16810       break;
16811     case DW_FORM_ref_udata:
16812       DW_UNSND (attr) = (to_underlying (cu->header.sect_off)
16813                          + read_unsigned_leb128 (abfd, info_ptr, &bytes_read));
16814       info_ptr += bytes_read;
16815       break;
16816     case DW_FORM_indirect:
16817       form = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
16818       info_ptr += bytes_read;
16819       if (form == DW_FORM_implicit_const)
16820         {
16821           implicit_const = read_signed_leb128 (abfd, info_ptr, &bytes_read);
16822           info_ptr += bytes_read;
16823         }
16824       info_ptr = read_attribute_value (reader, attr, form, implicit_const,
16825                                        info_ptr);
16826       break;
16827     case DW_FORM_implicit_const:
16828       DW_SND (attr) = implicit_const;
16829       break;
16830     case DW_FORM_GNU_addr_index:
16831       if (reader->dwo_file == NULL)
16832         {
16833           /* For now flag a hard error.
16834              Later we can turn this into a complaint.  */
16835           error (_("Dwarf Error: %s found in non-DWO CU [in module %s]"),
16836                  dwarf_form_name (form),
16837                  bfd_get_filename (abfd));
16838         }
16839       DW_ADDR (attr) = read_addr_index_from_leb128 (cu, info_ptr, &bytes_read);
16840       info_ptr += bytes_read;
16841       break;
16842     case DW_FORM_GNU_str_index:
16843       if (reader->dwo_file == NULL)
16844         {
16845           /* For now flag a hard error.
16846              Later we can turn this into a complaint if warranted.  */
16847           error (_("Dwarf Error: %s found in non-DWO CU [in module %s]"),
16848                  dwarf_form_name (form),
16849                  bfd_get_filename (abfd));
16850         }
16851       {
16852         ULONGEST str_index =
16853           read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
16854
16855         DW_STRING (attr) = read_str_index (reader, str_index);
16856         DW_STRING_IS_CANONICAL (attr) = 0;
16857         info_ptr += bytes_read;
16858       }
16859       break;
16860     default:
16861       error (_("Dwarf Error: Cannot handle %s in DWARF reader [in module %s]"),
16862              dwarf_form_name (form),
16863              bfd_get_filename (abfd));
16864     }
16865
16866   /* Super hack.  */
16867   if (cu->per_cu->is_dwz && attr_form_is_ref (attr))
16868     attr->form = DW_FORM_GNU_ref_alt;
16869
16870   /* We have seen instances where the compiler tried to emit a byte
16871      size attribute of -1 which ended up being encoded as an unsigned
16872      0xffffffff.  Although 0xffffffff is technically a valid size value,
16873      an object of this size seems pretty unlikely so we can relatively
16874      safely treat these cases as if the size attribute was invalid and
16875      treat them as zero by default.  */
16876   if (attr->name == DW_AT_byte_size
16877       && form == DW_FORM_data4
16878       && DW_UNSND (attr) >= 0xffffffff)
16879     {
16880       complaint
16881         (&symfile_complaints,
16882          _("Suspicious DW_AT_byte_size value treated as zero instead of %s"),
16883          hex_string (DW_UNSND (attr)));
16884       DW_UNSND (attr) = 0;
16885     }
16886
16887   return info_ptr;
16888 }
16889
16890 /* Read an attribute described by an abbreviated attribute.  */
16891
16892 static const gdb_byte *
16893 read_attribute (const struct die_reader_specs *reader,
16894                 struct attribute *attr, struct attr_abbrev *abbrev,
16895                 const gdb_byte *info_ptr)
16896 {
16897   attr->name = abbrev->name;
16898   return read_attribute_value (reader, attr, abbrev->form,
16899                                abbrev->implicit_const, info_ptr);
16900 }
16901
16902 /* Read dwarf information from a buffer.  */
16903
16904 static unsigned int
16905 read_1_byte (bfd *abfd, const gdb_byte *buf)
16906 {
16907   return bfd_get_8 (abfd, buf);
16908 }
16909
16910 static int
16911 read_1_signed_byte (bfd *abfd, const gdb_byte *buf)
16912 {
16913   return bfd_get_signed_8 (abfd, buf);
16914 }
16915
16916 static unsigned int
16917 read_2_bytes (bfd *abfd, const gdb_byte *buf)
16918 {
16919   return bfd_get_16 (abfd, buf);
16920 }
16921
16922 static int
16923 read_2_signed_bytes (bfd *abfd, const gdb_byte *buf)
16924 {
16925   return bfd_get_signed_16 (abfd, buf);
16926 }
16927
16928 static unsigned int
16929 read_4_bytes (bfd *abfd, const gdb_byte *buf)
16930 {
16931   return bfd_get_32 (abfd, buf);
16932 }
16933
16934 static int
16935 read_4_signed_bytes (bfd *abfd, const gdb_byte *buf)
16936 {
16937   return bfd_get_signed_32 (abfd, buf);
16938 }
16939
16940 static ULONGEST
16941 read_8_bytes (bfd *abfd, const gdb_byte *buf)
16942 {
16943   return bfd_get_64 (abfd, buf);
16944 }
16945
16946 static CORE_ADDR
16947 read_address (bfd *abfd, const gdb_byte *buf, struct dwarf2_cu *cu,
16948               unsigned int *bytes_read)
16949 {
16950   struct comp_unit_head *cu_header = &cu->header;
16951   CORE_ADDR retval = 0;
16952
16953   if (cu_header->signed_addr_p)
16954     {
16955       switch (cu_header->addr_size)
16956         {
16957         case 2:
16958           retval = bfd_get_signed_16 (abfd, buf);
16959           break;
16960         case 4:
16961           retval = bfd_get_signed_32 (abfd, buf);
16962           break;
16963         case 8:
16964           retval = bfd_get_signed_64 (abfd, buf);
16965           break;
16966         default:
16967           internal_error (__FILE__, __LINE__,
16968                           _("read_address: bad switch, signed [in module %s]"),
16969                           bfd_get_filename (abfd));
16970         }
16971     }
16972   else
16973     {
16974       switch (cu_header->addr_size)
16975         {
16976         case 2:
16977           retval = bfd_get_16 (abfd, buf);
16978           break;
16979         case 4:
16980           retval = bfd_get_32 (abfd, buf);
16981           break;
16982         case 8:
16983           retval = bfd_get_64 (abfd, buf);
16984           break;
16985         default:
16986           internal_error (__FILE__, __LINE__,
16987                           _("read_address: bad switch, "
16988                             "unsigned [in module %s]"),
16989                           bfd_get_filename (abfd));
16990         }
16991     }
16992
16993   *bytes_read = cu_header->addr_size;
16994   return retval;
16995 }
16996
16997 /* Read the initial length from a section.  The (draft) DWARF 3
16998    specification allows the initial length to take up either 4 bytes
16999    or 12 bytes.  If the first 4 bytes are 0xffffffff, then the next 8
17000    bytes describe the length and all offsets will be 8 bytes in length
17001    instead of 4.
17002
17003    An older, non-standard 64-bit format is also handled by this
17004    function.  The older format in question stores the initial length
17005    as an 8-byte quantity without an escape value.  Lengths greater
17006    than 2^32 aren't very common which means that the initial 4 bytes
17007    is almost always zero.  Since a length value of zero doesn't make
17008    sense for the 32-bit format, this initial zero can be considered to
17009    be an escape value which indicates the presence of the older 64-bit
17010    format.  As written, the code can't detect (old format) lengths
17011    greater than 4GB.  If it becomes necessary to handle lengths
17012    somewhat larger than 4GB, we could allow other small values (such
17013    as the non-sensical values of 1, 2, and 3) to also be used as
17014    escape values indicating the presence of the old format.
17015
17016    The value returned via bytes_read should be used to increment the
17017    relevant pointer after calling read_initial_length().
17018
17019    [ Note:  read_initial_length() and read_offset() are based on the
17020      document entitled "DWARF Debugging Information Format", revision
17021      3, draft 8, dated November 19, 2001.  This document was obtained
17022      from:
17023
17024         http://reality.sgiweb.org/davea/dwarf3-draft8-011125.pdf
17025
17026      This document is only a draft and is subject to change.  (So beware.)
17027
17028      Details regarding the older, non-standard 64-bit format were
17029      determined empirically by examining 64-bit ELF files produced by
17030      the SGI toolchain on an IRIX 6.5 machine.
17031
17032      - Kevin, July 16, 2002
17033    ] */
17034
17035 static LONGEST
17036 read_initial_length (bfd *abfd, const gdb_byte *buf, unsigned int *bytes_read)
17037 {
17038   LONGEST length = bfd_get_32 (abfd, buf);
17039
17040   if (length == 0xffffffff)
17041     {
17042       length = bfd_get_64 (abfd, buf + 4);
17043       *bytes_read = 12;
17044     }
17045   else if (length == 0)
17046     {
17047       /* Handle the (non-standard) 64-bit DWARF2 format used by IRIX.  */
17048       length = bfd_get_64 (abfd, buf);
17049       *bytes_read = 8;
17050     }
17051   else
17052     {
17053       *bytes_read = 4;
17054     }
17055
17056   return length;
17057 }
17058
17059 /* Cover function for read_initial_length.
17060    Returns the length of the object at BUF, and stores the size of the
17061    initial length in *BYTES_READ and stores the size that offsets will be in
17062    *OFFSET_SIZE.
17063    If the initial length size is not equivalent to that specified in
17064    CU_HEADER then issue a complaint.
17065    This is useful when reading non-comp-unit headers.  */
17066
17067 static LONGEST
17068 read_checked_initial_length_and_offset (bfd *abfd, const gdb_byte *buf,
17069                                         const struct comp_unit_head *cu_header,
17070                                         unsigned int *bytes_read,
17071                                         unsigned int *offset_size)
17072 {
17073   LONGEST length = read_initial_length (abfd, buf, bytes_read);
17074
17075   gdb_assert (cu_header->initial_length_size == 4
17076               || cu_header->initial_length_size == 8
17077               || cu_header->initial_length_size == 12);
17078
17079   if (cu_header->initial_length_size != *bytes_read)
17080     complaint (&symfile_complaints,
17081                _("intermixed 32-bit and 64-bit DWARF sections"));
17082
17083   *offset_size = (*bytes_read == 4) ? 4 : 8;
17084   return length;
17085 }
17086
17087 /* Read an offset from the data stream.  The size of the offset is
17088    given by cu_header->offset_size.  */
17089
17090 static LONGEST
17091 read_offset (bfd *abfd, const gdb_byte *buf,
17092              const struct comp_unit_head *cu_header,
17093              unsigned int *bytes_read)
17094 {
17095   LONGEST offset = read_offset_1 (abfd, buf, cu_header->offset_size);
17096
17097   *bytes_read = cu_header->offset_size;
17098   return offset;
17099 }
17100
17101 /* Read an offset from the data stream.  */
17102
17103 static LONGEST
17104 read_offset_1 (bfd *abfd, const gdb_byte *buf, unsigned int offset_size)
17105 {
17106   LONGEST retval = 0;
17107
17108   switch (offset_size)
17109     {
17110     case 4:
17111       retval = bfd_get_32 (abfd, buf);
17112       break;
17113     case 8:
17114       retval = bfd_get_64 (abfd, buf);
17115       break;
17116     default:
17117       internal_error (__FILE__, __LINE__,
17118                       _("read_offset_1: bad switch [in module %s]"),
17119                       bfd_get_filename (abfd));
17120     }
17121
17122   return retval;
17123 }
17124
17125 static const gdb_byte *
17126 read_n_bytes (bfd *abfd, const gdb_byte *buf, unsigned int size)
17127 {
17128   /* If the size of a host char is 8 bits, we can return a pointer
17129      to the buffer, otherwise we have to copy the data to a buffer
17130      allocated on the temporary obstack.  */
17131   gdb_assert (HOST_CHAR_BIT == 8);
17132   return buf;
17133 }
17134
17135 static const char *
17136 read_direct_string (bfd *abfd, const gdb_byte *buf,
17137                     unsigned int *bytes_read_ptr)
17138 {
17139   /* If the size of a host char is 8 bits, we can return a pointer
17140      to the string, otherwise we have to copy the string to a buffer
17141      allocated on the temporary obstack.  */
17142   gdb_assert (HOST_CHAR_BIT == 8);
17143   if (*buf == '\0')
17144     {
17145       *bytes_read_ptr = 1;
17146       return NULL;
17147     }
17148   *bytes_read_ptr = strlen ((const char *) buf) + 1;
17149   return (const char *) buf;
17150 }
17151
17152 /* Return pointer to string at section SECT offset STR_OFFSET with error
17153    reporting strings FORM_NAME and SECT_NAME.  */
17154
17155 static const char *
17156 read_indirect_string_at_offset_from (bfd *abfd, LONGEST str_offset,
17157                                      struct dwarf2_section_info *sect,
17158                                      const char *form_name,
17159                                      const char *sect_name)
17160 {
17161   dwarf2_read_section (dwarf2_per_objfile->objfile, sect);
17162   if (sect->buffer == NULL)
17163     error (_("%s used without %s section [in module %s]"),
17164            form_name, sect_name, bfd_get_filename (abfd));
17165   if (str_offset >= sect->size)
17166     error (_("%s pointing outside of %s section [in module %s]"),
17167            form_name, sect_name, bfd_get_filename (abfd));
17168   gdb_assert (HOST_CHAR_BIT == 8);
17169   if (sect->buffer[str_offset] == '\0')
17170     return NULL;
17171   return (const char *) (sect->buffer + str_offset);
17172 }
17173
17174 /* Return pointer to string at .debug_str offset STR_OFFSET.  */
17175
17176 static const char *
17177 read_indirect_string_at_offset (bfd *abfd, LONGEST str_offset)
17178 {
17179   return read_indirect_string_at_offset_from (abfd, str_offset,
17180                                               &dwarf2_per_objfile->str,
17181                                               "DW_FORM_strp", ".debug_str");
17182 }
17183
17184 /* Return pointer to string at .debug_line_str offset STR_OFFSET.  */
17185
17186 static const char *
17187 read_indirect_line_string_at_offset (bfd *abfd, LONGEST str_offset)
17188 {
17189   return read_indirect_string_at_offset_from (abfd, str_offset,
17190                                               &dwarf2_per_objfile->line_str,
17191                                               "DW_FORM_line_strp",
17192                                               ".debug_line_str");
17193 }
17194
17195 /* Read a string at offset STR_OFFSET in the .debug_str section from
17196    the .dwz file DWZ.  Throw an error if the offset is too large.  If
17197    the string consists of a single NUL byte, return NULL; otherwise
17198    return a pointer to the string.  */
17199
17200 static const char *
17201 read_indirect_string_from_dwz (struct dwz_file *dwz, LONGEST str_offset)
17202 {
17203   dwarf2_read_section (dwarf2_per_objfile->objfile, &dwz->str);
17204
17205   if (dwz->str.buffer == NULL)
17206     error (_("DW_FORM_GNU_strp_alt used without .debug_str "
17207              "section [in module %s]"),
17208            bfd_get_filename (dwz->dwz_bfd));
17209   if (str_offset >= dwz->str.size)
17210     error (_("DW_FORM_GNU_strp_alt pointing outside of "
17211              ".debug_str section [in module %s]"),
17212            bfd_get_filename (dwz->dwz_bfd));
17213   gdb_assert (HOST_CHAR_BIT == 8);
17214   if (dwz->str.buffer[str_offset] == '\0')
17215     return NULL;
17216   return (const char *) (dwz->str.buffer + str_offset);
17217 }
17218
17219 /* Return pointer to string at .debug_str offset as read from BUF.
17220    BUF is assumed to be in a compilation unit described by CU_HEADER.
17221    Return *BYTES_READ_PTR count of bytes read from BUF.  */
17222
17223 static const char *
17224 read_indirect_string (bfd *abfd, const gdb_byte *buf,
17225                       const struct comp_unit_head *cu_header,
17226                       unsigned int *bytes_read_ptr)
17227 {
17228   LONGEST str_offset = read_offset (abfd, buf, cu_header, bytes_read_ptr);
17229
17230   return read_indirect_string_at_offset (abfd, str_offset);
17231 }
17232
17233 /* Return pointer to string at .debug_line_str offset as read from BUF.
17234    BUF is assumed to be in a compilation unit described by CU_HEADER.
17235    Return *BYTES_READ_PTR count of bytes read from BUF.  */
17236
17237 static const char *
17238 read_indirect_line_string (bfd *abfd, const gdb_byte *buf,
17239                            const struct comp_unit_head *cu_header,
17240                            unsigned int *bytes_read_ptr)
17241 {
17242   LONGEST str_offset = read_offset (abfd, buf, cu_header, bytes_read_ptr);
17243
17244   return read_indirect_line_string_at_offset (abfd, str_offset);
17245 }
17246
17247 ULONGEST
17248 read_unsigned_leb128 (bfd *abfd, const gdb_byte *buf,
17249                           unsigned int *bytes_read_ptr)
17250 {
17251   ULONGEST result;
17252   unsigned int num_read;
17253   int shift;
17254   unsigned char byte;
17255
17256   result = 0;
17257   shift = 0;
17258   num_read = 0;
17259   while (1)
17260     {
17261       byte = bfd_get_8 (abfd, buf);
17262       buf++;
17263       num_read++;
17264       result |= ((ULONGEST) (byte & 127) << shift);
17265       if ((byte & 128) == 0)
17266         {
17267           break;
17268         }
17269       shift += 7;
17270     }
17271   *bytes_read_ptr = num_read;
17272   return result;
17273 }
17274
17275 static LONGEST
17276 read_signed_leb128 (bfd *abfd, const gdb_byte *buf,
17277                     unsigned int *bytes_read_ptr)
17278 {
17279   LONGEST result;
17280   int shift, num_read;
17281   unsigned char byte;
17282
17283   result = 0;
17284   shift = 0;
17285   num_read = 0;
17286   while (1)
17287     {
17288       byte = bfd_get_8 (abfd, buf);
17289       buf++;
17290       num_read++;
17291       result |= ((LONGEST) (byte & 127) << shift);
17292       shift += 7;
17293       if ((byte & 128) == 0)
17294         {
17295           break;
17296         }
17297     }
17298   if ((shift < 8 * sizeof (result)) && (byte & 0x40))
17299     result |= -(((LONGEST) 1) << shift);
17300   *bytes_read_ptr = num_read;
17301   return result;
17302 }
17303
17304 /* Given index ADDR_INDEX in .debug_addr, fetch the value.
17305    ADDR_BASE is the DW_AT_GNU_addr_base attribute or zero.
17306    ADDR_SIZE is the size of addresses from the CU header.  */
17307
17308 static CORE_ADDR
17309 read_addr_index_1 (unsigned int addr_index, ULONGEST addr_base, int addr_size)
17310 {
17311   struct objfile *objfile = dwarf2_per_objfile->objfile;
17312   bfd *abfd = objfile->obfd;
17313   const gdb_byte *info_ptr;
17314
17315   dwarf2_read_section (objfile, &dwarf2_per_objfile->addr);
17316   if (dwarf2_per_objfile->addr.buffer == NULL)
17317     error (_("DW_FORM_addr_index used without .debug_addr section [in module %s]"),
17318            objfile_name (objfile));
17319   if (addr_base + addr_index * addr_size >= dwarf2_per_objfile->addr.size)
17320     error (_("DW_FORM_addr_index pointing outside of "
17321              ".debug_addr section [in module %s]"),
17322            objfile_name (objfile));
17323   info_ptr = (dwarf2_per_objfile->addr.buffer
17324               + addr_base + addr_index * addr_size);
17325   if (addr_size == 4)
17326     return bfd_get_32 (abfd, info_ptr);
17327   else
17328     return bfd_get_64 (abfd, info_ptr);
17329 }
17330
17331 /* Given index ADDR_INDEX in .debug_addr, fetch the value.  */
17332
17333 static CORE_ADDR
17334 read_addr_index (struct dwarf2_cu *cu, unsigned int addr_index)
17335 {
17336   return read_addr_index_1 (addr_index, cu->addr_base, cu->header.addr_size);
17337 }
17338
17339 /* Given a pointer to an leb128 value, fetch the value from .debug_addr.  */
17340
17341 static CORE_ADDR
17342 read_addr_index_from_leb128 (struct dwarf2_cu *cu, const gdb_byte *info_ptr,
17343                              unsigned int *bytes_read)
17344 {
17345   bfd *abfd = cu->objfile->obfd;
17346   unsigned int addr_index = read_unsigned_leb128 (abfd, info_ptr, bytes_read);
17347
17348   return read_addr_index (cu, addr_index);
17349 }
17350
17351 /* Data structure to pass results from dwarf2_read_addr_index_reader
17352    back to dwarf2_read_addr_index.  */
17353
17354 struct dwarf2_read_addr_index_data
17355 {
17356   ULONGEST addr_base;
17357   int addr_size;
17358 };
17359
17360 /* die_reader_func for dwarf2_read_addr_index.  */
17361
17362 static void
17363 dwarf2_read_addr_index_reader (const struct die_reader_specs *reader,
17364                                const gdb_byte *info_ptr,
17365                                struct die_info *comp_unit_die,
17366                                int has_children,
17367                                void *data)
17368 {
17369   struct dwarf2_cu *cu = reader->cu;
17370   struct dwarf2_read_addr_index_data *aidata =
17371     (struct dwarf2_read_addr_index_data *) data;
17372
17373   aidata->addr_base = cu->addr_base;
17374   aidata->addr_size = cu->header.addr_size;
17375 }
17376
17377 /* Given an index in .debug_addr, fetch the value.
17378    NOTE: This can be called during dwarf expression evaluation,
17379    long after the debug information has been read, and thus per_cu->cu
17380    may no longer exist.  */
17381
17382 CORE_ADDR
17383 dwarf2_read_addr_index (struct dwarf2_per_cu_data *per_cu,
17384                         unsigned int addr_index)
17385 {
17386   struct objfile *objfile = per_cu->objfile;
17387   struct dwarf2_cu *cu = per_cu->cu;
17388   ULONGEST addr_base;
17389   int addr_size;
17390
17391   /* This is intended to be called from outside this file.  */
17392   dw2_setup (objfile);
17393
17394   /* We need addr_base and addr_size.
17395      If we don't have PER_CU->cu, we have to get it.
17396      Nasty, but the alternative is storing the needed info in PER_CU,
17397      which at this point doesn't seem justified: it's not clear how frequently
17398      it would get used and it would increase the size of every PER_CU.
17399      Entry points like dwarf2_per_cu_addr_size do a similar thing
17400      so we're not in uncharted territory here.
17401      Alas we need to be a bit more complicated as addr_base is contained
17402      in the DIE.
17403
17404      We don't need to read the entire CU(/TU).
17405      We just need the header and top level die.
17406
17407      IWBN to use the aging mechanism to let us lazily later discard the CU.
17408      For now we skip this optimization.  */
17409
17410   if (cu != NULL)
17411     {
17412       addr_base = cu->addr_base;
17413       addr_size = cu->header.addr_size;
17414     }
17415   else
17416     {
17417       struct dwarf2_read_addr_index_data aidata;
17418
17419       /* Note: We can't use init_cutu_and_read_dies_simple here,
17420          we need addr_base.  */
17421       init_cutu_and_read_dies (per_cu, NULL, 0, 0,
17422                                dwarf2_read_addr_index_reader, &aidata);
17423       addr_base = aidata.addr_base;
17424       addr_size = aidata.addr_size;
17425     }
17426
17427   return read_addr_index_1 (addr_index, addr_base, addr_size);
17428 }
17429
17430 /* Given a DW_FORM_GNU_str_index, fetch the string.
17431    This is only used by the Fission support.  */
17432
17433 static const char *
17434 read_str_index (const struct die_reader_specs *reader, ULONGEST str_index)
17435 {
17436   struct objfile *objfile = dwarf2_per_objfile->objfile;
17437   const char *objf_name = objfile_name (objfile);
17438   bfd *abfd = objfile->obfd;
17439   struct dwarf2_cu *cu = reader->cu;
17440   struct dwarf2_section_info *str_section = &reader->dwo_file->sections.str;
17441   struct dwarf2_section_info *str_offsets_section =
17442     &reader->dwo_file->sections.str_offsets;
17443   const gdb_byte *info_ptr;
17444   ULONGEST str_offset;
17445   static const char form_name[] = "DW_FORM_GNU_str_index";
17446
17447   dwarf2_read_section (objfile, str_section);
17448   dwarf2_read_section (objfile, str_offsets_section);
17449   if (str_section->buffer == NULL)
17450     error (_("%s used without .debug_str.dwo section"
17451              " in CU at offset 0x%x [in module %s]"),
17452            form_name, to_underlying (cu->header.sect_off), objf_name);
17453   if (str_offsets_section->buffer == NULL)
17454     error (_("%s used without .debug_str_offsets.dwo section"
17455              " in CU at offset 0x%x [in module %s]"),
17456            form_name, to_underlying (cu->header.sect_off), objf_name);
17457   if (str_index * cu->header.offset_size >= str_offsets_section->size)
17458     error (_("%s pointing outside of .debug_str_offsets.dwo"
17459              " section in CU at offset 0x%x [in module %s]"),
17460            form_name, to_underlying (cu->header.sect_off), objf_name);
17461   info_ptr = (str_offsets_section->buffer
17462               + str_index * cu->header.offset_size);
17463   if (cu->header.offset_size == 4)
17464     str_offset = bfd_get_32 (abfd, info_ptr);
17465   else
17466     str_offset = bfd_get_64 (abfd, info_ptr);
17467   if (str_offset >= str_section->size)
17468     error (_("Offset from %s pointing outside of"
17469              " .debug_str.dwo section in CU at offset 0x%x [in module %s]"),
17470            form_name, to_underlying (cu->header.sect_off), objf_name);
17471   return (const char *) (str_section->buffer + str_offset);
17472 }
17473
17474 /* Return the length of an LEB128 number in BUF.  */
17475
17476 static int
17477 leb128_size (const gdb_byte *buf)
17478 {
17479   const gdb_byte *begin = buf;
17480   gdb_byte byte;
17481
17482   while (1)
17483     {
17484       byte = *buf++;
17485       if ((byte & 128) == 0)
17486         return buf - begin;
17487     }
17488 }
17489
17490 static void
17491 set_cu_language (unsigned int lang, struct dwarf2_cu *cu)
17492 {
17493   switch (lang)
17494     {
17495     case DW_LANG_C89:
17496     case DW_LANG_C99:
17497     case DW_LANG_C11:
17498     case DW_LANG_C:
17499     case DW_LANG_UPC:
17500       cu->language = language_c;
17501       break;
17502     case DW_LANG_Java:
17503     case DW_LANG_C_plus_plus:
17504     case DW_LANG_C_plus_plus_11:
17505     case DW_LANG_C_plus_plus_14:
17506       cu->language = language_cplus;
17507       break;
17508     case DW_LANG_D:
17509       cu->language = language_d;
17510       break;
17511     case DW_LANG_Fortran77:
17512     case DW_LANG_Fortran90:
17513     case DW_LANG_Fortran95:
17514     case DW_LANG_Fortran03:
17515     case DW_LANG_Fortran08:
17516       cu->language = language_fortran;
17517       break;
17518     case DW_LANG_Go:
17519       cu->language = language_go;
17520       break;
17521     case DW_LANG_Mips_Assembler:
17522       cu->language = language_asm;
17523       break;
17524     case DW_LANG_Ada83:
17525     case DW_LANG_Ada95:
17526       cu->language = language_ada;
17527       break;
17528     case DW_LANG_Modula2:
17529       cu->language = language_m2;
17530       break;
17531     case DW_LANG_Pascal83:
17532       cu->language = language_pascal;
17533       break;
17534     case DW_LANG_ObjC:
17535       cu->language = language_objc;
17536       break;
17537     case DW_LANG_Rust:
17538     case DW_LANG_Rust_old:
17539       cu->language = language_rust;
17540       break;
17541     case DW_LANG_Cobol74:
17542     case DW_LANG_Cobol85:
17543     default:
17544       cu->language = language_minimal;
17545       break;
17546     }
17547   cu->language_defn = language_def (cu->language);
17548 }
17549
17550 /* Return the named attribute or NULL if not there.  */
17551
17552 static struct attribute *
17553 dwarf2_attr (struct die_info *die, unsigned int name, struct dwarf2_cu *cu)
17554 {
17555   for (;;)
17556     {
17557       unsigned int i;
17558       struct attribute *spec = NULL;
17559
17560       for (i = 0; i < die->num_attrs; ++i)
17561         {
17562           if (die->attrs[i].name == name)
17563             return &die->attrs[i];
17564           if (die->attrs[i].name == DW_AT_specification
17565               || die->attrs[i].name == DW_AT_abstract_origin)
17566             spec = &die->attrs[i];
17567         }
17568
17569       if (!spec)
17570         break;
17571
17572       die = follow_die_ref (die, spec, &cu);
17573     }
17574
17575   return NULL;
17576 }
17577
17578 /* Return the named attribute or NULL if not there,
17579    but do not follow DW_AT_specification, etc.
17580    This is for use in contexts where we're reading .debug_types dies.
17581    Following DW_AT_specification, DW_AT_abstract_origin will take us
17582    back up the chain, and we want to go down.  */
17583
17584 static struct attribute *
17585 dwarf2_attr_no_follow (struct die_info *die, unsigned int name)
17586 {
17587   unsigned int i;
17588
17589   for (i = 0; i < die->num_attrs; ++i)
17590     if (die->attrs[i].name == name)
17591       return &die->attrs[i];
17592
17593   return NULL;
17594 }
17595
17596 /* Return the string associated with a string-typed attribute, or NULL if it
17597    is either not found or is of an incorrect type.  */
17598
17599 static const char *
17600 dwarf2_string_attr (struct die_info *die, unsigned int name, struct dwarf2_cu *cu)
17601 {
17602   struct attribute *attr;
17603   const char *str = NULL;
17604
17605   attr = dwarf2_attr (die, name, cu);
17606
17607   if (attr != NULL)
17608     {
17609       if (attr->form == DW_FORM_strp || attr->form == DW_FORM_line_strp
17610           || attr->form == DW_FORM_string || attr->form == DW_FORM_GNU_strp_alt)
17611         str = DW_STRING (attr);
17612       else
17613         complaint (&symfile_complaints,
17614                    _("string type expected for attribute %s for "
17615                      "DIE at 0x%x in module %s"),
17616                    dwarf_attr_name (name), to_underlying (die->sect_off),
17617                    objfile_name (cu->objfile));
17618     }
17619
17620   return str;
17621 }
17622
17623 /* Return non-zero iff the attribute NAME is defined for the given DIE,
17624    and holds a non-zero value.  This function should only be used for
17625    DW_FORM_flag or DW_FORM_flag_present attributes.  */
17626
17627 static int
17628 dwarf2_flag_true_p (struct die_info *die, unsigned name, struct dwarf2_cu *cu)
17629 {
17630   struct attribute *attr = dwarf2_attr (die, name, cu);
17631
17632   return (attr && DW_UNSND (attr));
17633 }
17634
17635 static int
17636 die_is_declaration (struct die_info *die, struct dwarf2_cu *cu)
17637 {
17638   /* A DIE is a declaration if it has a DW_AT_declaration attribute
17639      which value is non-zero.  However, we have to be careful with
17640      DIEs having a DW_AT_specification attribute, because dwarf2_attr()
17641      (via dwarf2_flag_true_p) follows this attribute.  So we may
17642      end up accidently finding a declaration attribute that belongs
17643      to a different DIE referenced by the specification attribute,
17644      even though the given DIE does not have a declaration attribute.  */
17645   return (dwarf2_flag_true_p (die, DW_AT_declaration, cu)
17646           && dwarf2_attr (die, DW_AT_specification, cu) == NULL);
17647 }
17648
17649 /* Return the die giving the specification for DIE, if there is
17650    one.  *SPEC_CU is the CU containing DIE on input, and the CU
17651    containing the return value on output.  If there is no
17652    specification, but there is an abstract origin, that is
17653    returned.  */
17654
17655 static struct die_info *
17656 die_specification (struct die_info *die, struct dwarf2_cu **spec_cu)
17657 {
17658   struct attribute *spec_attr = dwarf2_attr (die, DW_AT_specification,
17659                                              *spec_cu);
17660
17661   if (spec_attr == NULL)
17662     spec_attr = dwarf2_attr (die, DW_AT_abstract_origin, *spec_cu);
17663
17664   if (spec_attr == NULL)
17665     return NULL;
17666   else
17667     return follow_die_ref (die, spec_attr, spec_cu);
17668 }
17669
17670 /* Stub for free_line_header to match void * callback types.  */
17671
17672 static void
17673 free_line_header_voidp (void *arg)
17674 {
17675   struct line_header *lh = (struct line_header *) arg;
17676
17677   delete lh;
17678 }
17679
17680 void
17681 line_header::add_include_dir (const char *include_dir)
17682 {
17683   if (dwarf_line_debug >= 2)
17684     fprintf_unfiltered (gdb_stdlog, "Adding dir %zu: %s\n",
17685                         include_dirs.size () + 1, include_dir);
17686
17687   include_dirs.push_back (include_dir);
17688 }
17689
17690 void
17691 line_header::add_file_name (const char *name,
17692                             dir_index d_index,
17693                             unsigned int mod_time,
17694                             unsigned int length)
17695 {
17696   if (dwarf_line_debug >= 2)
17697     fprintf_unfiltered (gdb_stdlog, "Adding file %u: %s\n",
17698                         (unsigned) file_names.size () + 1, name);
17699
17700   file_names.emplace_back (name, d_index, mod_time, length);
17701 }
17702
17703 /* A convenience function to find the proper .debug_line section for a CU.  */
17704
17705 static struct dwarf2_section_info *
17706 get_debug_line_section (struct dwarf2_cu *cu)
17707 {
17708   struct dwarf2_section_info *section;
17709
17710   /* For TUs in DWO files, the DW_AT_stmt_list attribute lives in the
17711      DWO file.  */
17712   if (cu->dwo_unit && cu->per_cu->is_debug_types)
17713     section = &cu->dwo_unit->dwo_file->sections.line;
17714   else if (cu->per_cu->is_dwz)
17715     {
17716       struct dwz_file *dwz = dwarf2_get_dwz_file ();
17717
17718       section = &dwz->line;
17719     }
17720   else
17721     section = &dwarf2_per_objfile->line;
17722
17723   return section;
17724 }
17725
17726 /* Read directory or file name entry format, starting with byte of
17727    format count entries, ULEB128 pairs of entry formats, ULEB128 of
17728    entries count and the entries themselves in the described entry
17729    format.  */
17730
17731 static void
17732 read_formatted_entries (bfd *abfd, const gdb_byte **bufp,
17733                         struct line_header *lh,
17734                         const struct comp_unit_head *cu_header,
17735                         void (*callback) (struct line_header *lh,
17736                                           const char *name,
17737                                           dir_index d_index,
17738                                           unsigned int mod_time,
17739                                           unsigned int length))
17740 {
17741   gdb_byte format_count, formati;
17742   ULONGEST data_count, datai;
17743   const gdb_byte *buf = *bufp;
17744   const gdb_byte *format_header_data;
17745   int i;
17746   unsigned int bytes_read;
17747
17748   format_count = read_1_byte (abfd, buf);
17749   buf += 1;
17750   format_header_data = buf;
17751   for (formati = 0; formati < format_count; formati++)
17752     {
17753       read_unsigned_leb128 (abfd, buf, &bytes_read);
17754       buf += bytes_read;
17755       read_unsigned_leb128 (abfd, buf, &bytes_read);
17756       buf += bytes_read;
17757     }
17758
17759   data_count = read_unsigned_leb128 (abfd, buf, &bytes_read);
17760   buf += bytes_read;
17761   for (datai = 0; datai < data_count; datai++)
17762     {
17763       const gdb_byte *format = format_header_data;
17764       struct file_entry fe;
17765
17766       for (formati = 0; formati < format_count; formati++)
17767         {
17768           ULONGEST content_type = read_unsigned_leb128 (abfd, format, &bytes_read);
17769           format += bytes_read;
17770
17771           ULONGEST form  = read_unsigned_leb128 (abfd, format, &bytes_read);
17772           format += bytes_read;
17773
17774           gdb::optional<const char *> string;
17775           gdb::optional<unsigned int> uint;
17776
17777           switch (form)
17778             {
17779             case DW_FORM_string:
17780               string.emplace (read_direct_string (abfd, buf, &bytes_read));
17781               buf += bytes_read;
17782               break;
17783
17784             case DW_FORM_line_strp:
17785               string.emplace (read_indirect_line_string (abfd, buf,
17786                                                          cu_header,
17787                                                          &bytes_read));
17788               buf += bytes_read;
17789               break;
17790
17791             case DW_FORM_data1:
17792               uint.emplace (read_1_byte (abfd, buf));
17793               buf += 1;
17794               break;
17795
17796             case DW_FORM_data2:
17797               uint.emplace (read_2_bytes (abfd, buf));
17798               buf += 2;
17799               break;
17800
17801             case DW_FORM_data4:
17802               uint.emplace (read_4_bytes (abfd, buf));
17803               buf += 4;
17804               break;
17805
17806             case DW_FORM_data8:
17807               uint.emplace (read_8_bytes (abfd, buf));
17808               buf += 8;
17809               break;
17810
17811             case DW_FORM_udata:
17812               uint.emplace (read_unsigned_leb128 (abfd, buf, &bytes_read));
17813               buf += bytes_read;
17814               break;
17815
17816             case DW_FORM_block:
17817               /* It is valid only for DW_LNCT_timestamp which is ignored by
17818                  current GDB.  */
17819               break;
17820             }
17821
17822           switch (content_type)
17823             {
17824             case DW_LNCT_path:
17825               if (string.has_value ())
17826                 fe.name = *string;
17827               break;
17828             case DW_LNCT_directory_index:
17829               if (uint.has_value ())
17830                 fe.d_index = (dir_index) *uint;
17831               break;
17832             case DW_LNCT_timestamp:
17833               if (uint.has_value ())
17834                 fe.mod_time = *uint;
17835               break;
17836             case DW_LNCT_size:
17837               if (uint.has_value ())
17838                 fe.length = *uint;
17839               break;
17840             case DW_LNCT_MD5:
17841               break;
17842             default:
17843               complaint (&symfile_complaints,
17844                          _("Unknown format content type %s"),
17845                          pulongest (content_type));
17846             }
17847         }
17848
17849       callback (lh, fe.name, fe.d_index, fe.mod_time, fe.length);
17850     }
17851
17852   *bufp = buf;
17853 }
17854
17855 /* Read the statement program header starting at OFFSET in
17856    .debug_line, or .debug_line.dwo.  Return a pointer
17857    to a struct line_header, allocated using xmalloc.
17858    Returns NULL if there is a problem reading the header, e.g., if it
17859    has a version we don't understand.
17860
17861    NOTE: the strings in the include directory and file name tables of
17862    the returned object point into the dwarf line section buffer,
17863    and must not be freed.  */
17864
17865 static line_header_up
17866 dwarf_decode_line_header (sect_offset sect_off, struct dwarf2_cu *cu)
17867 {
17868   const gdb_byte *line_ptr;
17869   unsigned int bytes_read, offset_size;
17870   int i;
17871   const char *cur_dir, *cur_file;
17872   struct dwarf2_section_info *section;
17873   bfd *abfd;
17874
17875   section = get_debug_line_section (cu);
17876   dwarf2_read_section (dwarf2_per_objfile->objfile, section);
17877   if (section->buffer == NULL)
17878     {
17879       if (cu->dwo_unit && cu->per_cu->is_debug_types)
17880         complaint (&symfile_complaints, _("missing .debug_line.dwo section"));
17881       else
17882         complaint (&symfile_complaints, _("missing .debug_line section"));
17883       return 0;
17884     }
17885
17886   /* We can't do this until we know the section is non-empty.
17887      Only then do we know we have such a section.  */
17888   abfd = get_section_bfd_owner (section);
17889
17890   /* Make sure that at least there's room for the total_length field.
17891      That could be 12 bytes long, but we're just going to fudge that.  */
17892   if (to_underlying (sect_off) + 4 >= section->size)
17893     {
17894       dwarf2_statement_list_fits_in_line_number_section_complaint ();
17895       return 0;
17896     }
17897
17898   line_header_up lh (new line_header ());
17899
17900   lh->sect_off = sect_off;
17901   lh->offset_in_dwz = cu->per_cu->is_dwz;
17902
17903   line_ptr = section->buffer + to_underlying (sect_off);
17904
17905   /* Read in the header.  */
17906   lh->total_length =
17907     read_checked_initial_length_and_offset (abfd, line_ptr, &cu->header,
17908                                             &bytes_read, &offset_size);
17909   line_ptr += bytes_read;
17910   if (line_ptr + lh->total_length > (section->buffer + section->size))
17911     {
17912       dwarf2_statement_list_fits_in_line_number_section_complaint ();
17913       return 0;
17914     }
17915   lh->statement_program_end = line_ptr + lh->total_length;
17916   lh->version = read_2_bytes (abfd, line_ptr);
17917   line_ptr += 2;
17918   if (lh->version > 5)
17919     {
17920       /* This is a version we don't understand.  The format could have
17921          changed in ways we don't handle properly so just punt.  */
17922       complaint (&symfile_complaints,
17923                  _("unsupported version in .debug_line section"));
17924       return NULL;
17925     }
17926   if (lh->version >= 5)
17927     {
17928       gdb_byte segment_selector_size;
17929
17930       /* Skip address size.  */
17931       read_1_byte (abfd, line_ptr);
17932       line_ptr += 1;
17933
17934       segment_selector_size = read_1_byte (abfd, line_ptr);
17935       line_ptr += 1;
17936       if (segment_selector_size != 0)
17937         {
17938           complaint (&symfile_complaints,
17939                      _("unsupported segment selector size %u "
17940                        "in .debug_line section"),
17941                      segment_selector_size);
17942           return NULL;
17943         }
17944     }
17945   lh->header_length = read_offset_1 (abfd, line_ptr, offset_size);
17946   line_ptr += offset_size;
17947   lh->minimum_instruction_length = read_1_byte (abfd, line_ptr);
17948   line_ptr += 1;
17949   if (lh->version >= 4)
17950     {
17951       lh->maximum_ops_per_instruction = read_1_byte (abfd, line_ptr);
17952       line_ptr += 1;
17953     }
17954   else
17955     lh->maximum_ops_per_instruction = 1;
17956
17957   if (lh->maximum_ops_per_instruction == 0)
17958     {
17959       lh->maximum_ops_per_instruction = 1;
17960       complaint (&symfile_complaints,
17961                  _("invalid maximum_ops_per_instruction "
17962                    "in `.debug_line' section"));
17963     }
17964
17965   lh->default_is_stmt = read_1_byte (abfd, line_ptr);
17966   line_ptr += 1;
17967   lh->line_base = read_1_signed_byte (abfd, line_ptr);
17968   line_ptr += 1;
17969   lh->line_range = read_1_byte (abfd, line_ptr);
17970   line_ptr += 1;
17971   lh->opcode_base = read_1_byte (abfd, line_ptr);
17972   line_ptr += 1;
17973   lh->standard_opcode_lengths.reset (new unsigned char[lh->opcode_base]);
17974
17975   lh->standard_opcode_lengths[0] = 1;  /* This should never be used anyway.  */
17976   for (i = 1; i < lh->opcode_base; ++i)
17977     {
17978       lh->standard_opcode_lengths[i] = read_1_byte (abfd, line_ptr);
17979       line_ptr += 1;
17980     }
17981
17982   if (lh->version >= 5)
17983     {
17984       /* Read directory table.  */
17985       read_formatted_entries (abfd, &line_ptr, lh.get (), &cu->header,
17986                               [] (struct line_header *lh, const char *name,
17987                                   dir_index d_index, unsigned int mod_time,
17988                                   unsigned int length)
17989         {
17990           lh->add_include_dir (name);
17991         });
17992
17993       /* Read file name table.  */
17994       read_formatted_entries (abfd, &line_ptr, lh.get (), &cu->header,
17995                               [] (struct line_header *lh, const char *name,
17996                                   dir_index d_index, unsigned int mod_time,
17997                                   unsigned int length)
17998         {
17999           lh->add_file_name (name, d_index, mod_time, length);
18000         });
18001     }
18002   else
18003     {
18004       /* Read directory table.  */
18005       while ((cur_dir = read_direct_string (abfd, line_ptr, &bytes_read)) != NULL)
18006         {
18007           line_ptr += bytes_read;
18008           lh->add_include_dir (cur_dir);
18009         }
18010       line_ptr += bytes_read;
18011
18012       /* Read file name table.  */
18013       while ((cur_file = read_direct_string (abfd, line_ptr, &bytes_read)) != NULL)
18014         {
18015           unsigned int mod_time, length;
18016           dir_index d_index;
18017
18018           line_ptr += bytes_read;
18019           d_index = (dir_index) read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
18020           line_ptr += bytes_read;
18021           mod_time = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
18022           line_ptr += bytes_read;
18023           length = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
18024           line_ptr += bytes_read;
18025
18026           lh->add_file_name (cur_file, d_index, mod_time, length);
18027         }
18028       line_ptr += bytes_read;
18029     }
18030   lh->statement_program_start = line_ptr;
18031
18032   if (line_ptr > (section->buffer + section->size))
18033     complaint (&symfile_complaints,
18034                _("line number info header doesn't "
18035                  "fit in `.debug_line' section"));
18036
18037   return lh;
18038 }
18039
18040 /* Subroutine of dwarf_decode_lines to simplify it.
18041    Return the file name of the psymtab for included file FILE_INDEX
18042    in line header LH of PST.
18043    COMP_DIR is the compilation directory (DW_AT_comp_dir) or NULL if unknown.
18044    If space for the result is malloc'd, it will be freed by a cleanup.
18045    Returns NULL if FILE_INDEX should be ignored, i.e., it is pst->filename.
18046
18047    The function creates dangling cleanup registration.  */
18048
18049 static const char *
18050 psymtab_include_file_name (const struct line_header *lh, int file_index,
18051                            const struct partial_symtab *pst,
18052                            const char *comp_dir)
18053 {
18054   const file_entry &fe = lh->file_names[file_index];
18055   const char *include_name = fe.name;
18056   const char *include_name_to_compare = include_name;
18057   const char *pst_filename;
18058   char *copied_name = NULL;
18059   int file_is_pst;
18060
18061   const char *dir_name = fe.include_dir (lh);
18062
18063   if (!IS_ABSOLUTE_PATH (include_name)
18064       && (dir_name != NULL || comp_dir != NULL))
18065     {
18066       /* Avoid creating a duplicate psymtab for PST.
18067          We do this by comparing INCLUDE_NAME and PST_FILENAME.
18068          Before we do the comparison, however, we need to account
18069          for DIR_NAME and COMP_DIR.
18070          First prepend dir_name (if non-NULL).  If we still don't
18071          have an absolute path prepend comp_dir (if non-NULL).
18072          However, the directory we record in the include-file's
18073          psymtab does not contain COMP_DIR (to match the
18074          corresponding symtab(s)).
18075
18076          Example:
18077
18078          bash$ cd /tmp
18079          bash$ gcc -g ./hello.c
18080          include_name = "hello.c"
18081          dir_name = "."
18082          DW_AT_comp_dir = comp_dir = "/tmp"
18083          DW_AT_name = "./hello.c"
18084
18085       */
18086
18087       if (dir_name != NULL)
18088         {
18089           char *tem = concat (dir_name, SLASH_STRING,
18090                               include_name, (char *)NULL);
18091
18092           make_cleanup (xfree, tem);
18093           include_name = tem;
18094           include_name_to_compare = include_name;
18095         }
18096       if (!IS_ABSOLUTE_PATH (include_name) && comp_dir != NULL)
18097         {
18098           char *tem = concat (comp_dir, SLASH_STRING,
18099                               include_name, (char *)NULL);
18100
18101           make_cleanup (xfree, tem);
18102           include_name_to_compare = tem;
18103         }
18104     }
18105
18106   pst_filename = pst->filename;
18107   if (!IS_ABSOLUTE_PATH (pst_filename) && pst->dirname != NULL)
18108     {
18109       copied_name = concat (pst->dirname, SLASH_STRING,
18110                             pst_filename, (char *)NULL);
18111       pst_filename = copied_name;
18112     }
18113
18114   file_is_pst = FILENAME_CMP (include_name_to_compare, pst_filename) == 0;
18115
18116   if (copied_name != NULL)
18117     xfree (copied_name);
18118
18119   if (file_is_pst)
18120     return NULL;
18121   return include_name;
18122 }
18123
18124 /* State machine to track the state of the line number program.  */
18125
18126 class lnp_state_machine
18127 {
18128 public:
18129   /* Initialize a machine state for the start of a line number
18130      program.  */
18131   lnp_state_machine (gdbarch *arch, line_header *lh, bool record_lines_p);
18132
18133   file_entry *current_file ()
18134   {
18135     /* lh->file_names is 0-based, but the file name numbers in the
18136        statement program are 1-based.  */
18137     return m_line_header->file_name_at (m_file);
18138   }
18139
18140   /* Record the line in the state machine.  END_SEQUENCE is true if
18141      we're processing the end of a sequence.  */
18142   void record_line (bool end_sequence);
18143
18144   /* Check address and if invalid nop-out the rest of the lines in this
18145      sequence.  */
18146   void check_line_address (struct dwarf2_cu *cu,
18147                            const gdb_byte *line_ptr,
18148                            CORE_ADDR lowpc, CORE_ADDR address);
18149
18150   void handle_set_discriminator (unsigned int discriminator)
18151   {
18152     m_discriminator = discriminator;
18153     m_line_has_non_zero_discriminator |= discriminator != 0;
18154   }
18155
18156   /* Handle DW_LNE_set_address.  */
18157   void handle_set_address (CORE_ADDR baseaddr, CORE_ADDR address)
18158   {
18159     m_op_index = 0;
18160     address += baseaddr;
18161     m_address = gdbarch_adjust_dwarf2_line (m_gdbarch, address, false);
18162   }
18163
18164   /* Handle DW_LNS_advance_pc.  */
18165   void handle_advance_pc (CORE_ADDR adjust);
18166
18167   /* Handle a special opcode.  */
18168   void handle_special_opcode (unsigned char op_code);
18169
18170   /* Handle DW_LNS_advance_line.  */
18171   void handle_advance_line (int line_delta)
18172   {
18173     advance_line (line_delta);
18174   }
18175
18176   /* Handle DW_LNS_set_file.  */
18177   void handle_set_file (file_name_index file);
18178
18179   /* Handle DW_LNS_negate_stmt.  */
18180   void handle_negate_stmt ()
18181   {
18182     m_is_stmt = !m_is_stmt;
18183   }
18184
18185   /* Handle DW_LNS_const_add_pc.  */
18186   void handle_const_add_pc ();
18187
18188   /* Handle DW_LNS_fixed_advance_pc.  */
18189   void handle_fixed_advance_pc (CORE_ADDR addr_adj)
18190   {
18191     m_address += gdbarch_adjust_dwarf2_line (m_gdbarch, addr_adj, true);
18192     m_op_index = 0;
18193   }
18194
18195   /* Handle DW_LNS_copy.  */
18196   void handle_copy ()
18197   {
18198     record_line (false);
18199     m_discriminator = 0;
18200   }
18201
18202   /* Handle DW_LNE_end_sequence.  */
18203   void handle_end_sequence ()
18204   {
18205     m_record_line_callback = ::record_line;
18206   }
18207
18208 private:
18209   /* Advance the line by LINE_DELTA.  */
18210   void advance_line (int line_delta)
18211   {
18212     m_line += line_delta;
18213
18214     if (line_delta != 0)
18215       m_line_has_non_zero_discriminator = m_discriminator != 0;
18216   }
18217
18218   gdbarch *m_gdbarch;
18219
18220   /* True if we're recording lines.
18221      Otherwise we're building partial symtabs and are just interested in
18222      finding include files mentioned by the line number program.  */
18223   bool m_record_lines_p;
18224
18225   /* The line number header.  */
18226   line_header *m_line_header;
18227
18228   /* These are part of the standard DWARF line number state machine,
18229      and initialized according to the DWARF spec.  */
18230
18231   unsigned char m_op_index = 0;
18232   /* The line table index (1-based) of the current file.  */
18233   file_name_index m_file = (file_name_index) 1;
18234   unsigned int m_line = 1;
18235
18236   /* These are initialized in the constructor.  */
18237
18238   CORE_ADDR m_address;
18239   bool m_is_stmt;
18240   unsigned int m_discriminator;
18241
18242   /* Additional bits of state we need to track.  */
18243
18244   /* The last file that we called dwarf2_start_subfile for.
18245      This is only used for TLLs.  */
18246   unsigned int m_last_file = 0;
18247   /* The last file a line number was recorded for.  */
18248   struct subfile *m_last_subfile = NULL;
18249
18250   /* The function to call to record a line.  */
18251   record_line_ftype *m_record_line_callback = NULL;
18252
18253   /* The last line number that was recorded, used to coalesce
18254      consecutive entries for the same line.  This can happen, for
18255      example, when discriminators are present.  PR 17276.  */
18256   unsigned int m_last_line = 0;
18257   bool m_line_has_non_zero_discriminator = false;
18258 };
18259
18260 void
18261 lnp_state_machine::handle_advance_pc (CORE_ADDR adjust)
18262 {
18263   CORE_ADDR addr_adj = (((m_op_index + adjust)
18264                          / m_line_header->maximum_ops_per_instruction)
18265                         * m_line_header->minimum_instruction_length);
18266   m_address += gdbarch_adjust_dwarf2_line (m_gdbarch, addr_adj, true);
18267   m_op_index = ((m_op_index + adjust)
18268                 % m_line_header->maximum_ops_per_instruction);
18269 }
18270
18271 void
18272 lnp_state_machine::handle_special_opcode (unsigned char op_code)
18273 {
18274   unsigned char adj_opcode = op_code - m_line_header->opcode_base;
18275   CORE_ADDR addr_adj = (((m_op_index
18276                           + (adj_opcode / m_line_header->line_range))
18277                          / m_line_header->maximum_ops_per_instruction)
18278                         * m_line_header->minimum_instruction_length);
18279   m_address += gdbarch_adjust_dwarf2_line (m_gdbarch, addr_adj, true);
18280   m_op_index = ((m_op_index + (adj_opcode / m_line_header->line_range))
18281                 % m_line_header->maximum_ops_per_instruction);
18282
18283   int line_delta = (m_line_header->line_base
18284                     + (adj_opcode % m_line_header->line_range));
18285   advance_line (line_delta);
18286   record_line (false);
18287   m_discriminator = 0;
18288 }
18289
18290 void
18291 lnp_state_machine::handle_set_file (file_name_index file)
18292 {
18293   m_file = file;
18294
18295   const file_entry *fe = current_file ();
18296   if (fe == NULL)
18297     dwarf2_debug_line_missing_file_complaint ();
18298   else if (m_record_lines_p)
18299     {
18300       const char *dir = fe->include_dir (m_line_header);
18301
18302       m_last_subfile = current_subfile;
18303       m_line_has_non_zero_discriminator = m_discriminator != 0;
18304       dwarf2_start_subfile (fe->name, dir);
18305     }
18306 }
18307
18308 void
18309 lnp_state_machine::handle_const_add_pc ()
18310 {
18311   CORE_ADDR adjust
18312     = (255 - m_line_header->opcode_base) / m_line_header->line_range;
18313
18314   CORE_ADDR addr_adj
18315     = (((m_op_index + adjust)
18316         / m_line_header->maximum_ops_per_instruction)
18317        * m_line_header->minimum_instruction_length);
18318
18319   m_address += gdbarch_adjust_dwarf2_line (m_gdbarch, addr_adj, true);
18320   m_op_index = ((m_op_index + adjust)
18321                 % m_line_header->maximum_ops_per_instruction);
18322 }
18323
18324 /* Ignore this record_line request.  */
18325
18326 static void
18327 noop_record_line (struct subfile *subfile, int line, CORE_ADDR pc)
18328 {
18329   return;
18330 }
18331
18332 /* Return non-zero if we should add LINE to the line number table.
18333    LINE is the line to add, LAST_LINE is the last line that was added,
18334    LAST_SUBFILE is the subfile for LAST_LINE.
18335    LINE_HAS_NON_ZERO_DISCRIMINATOR is non-zero if LINE has ever
18336    had a non-zero discriminator.
18337
18338    We have to be careful in the presence of discriminators.
18339    E.g., for this line:
18340
18341      for (i = 0; i < 100000; i++);
18342
18343    clang can emit four line number entries for that one line,
18344    each with a different discriminator.
18345    See gdb.dwarf2/dw2-single-line-discriminators.exp for an example.
18346
18347    However, we want gdb to coalesce all four entries into one.
18348    Otherwise the user could stepi into the middle of the line and
18349    gdb would get confused about whether the pc really was in the
18350    middle of the line.
18351
18352    Things are further complicated by the fact that two consecutive
18353    line number entries for the same line is a heuristic used by gcc
18354    to denote the end of the prologue.  So we can't just discard duplicate
18355    entries, we have to be selective about it.  The heuristic we use is
18356    that we only collapse consecutive entries for the same line if at least
18357    one of those entries has a non-zero discriminator.  PR 17276.
18358
18359    Note: Addresses in the line number state machine can never go backwards
18360    within one sequence, thus this coalescing is ok.  */
18361
18362 static int
18363 dwarf_record_line_p (unsigned int line, unsigned int last_line,
18364                      int line_has_non_zero_discriminator,
18365                      struct subfile *last_subfile)
18366 {
18367   if (current_subfile != last_subfile)
18368     return 1;
18369   if (line != last_line)
18370     return 1;
18371   /* Same line for the same file that we've seen already.
18372      As a last check, for pr 17276, only record the line if the line
18373      has never had a non-zero discriminator.  */
18374   if (!line_has_non_zero_discriminator)
18375     return 1;
18376   return 0;
18377 }
18378
18379 /* Use P_RECORD_LINE to record line number LINE beginning at address ADDRESS
18380    in the line table of subfile SUBFILE.  */
18381
18382 static void
18383 dwarf_record_line_1 (struct gdbarch *gdbarch, struct subfile *subfile,
18384                      unsigned int line, CORE_ADDR address,
18385                      record_line_ftype p_record_line)
18386 {
18387   CORE_ADDR addr = gdbarch_addr_bits_remove (gdbarch, address);
18388
18389   if (dwarf_line_debug)
18390     {
18391       fprintf_unfiltered (gdb_stdlog,
18392                           "Recording line %u, file %s, address %s\n",
18393                           line, lbasename (subfile->name),
18394                           paddress (gdbarch, address));
18395     }
18396
18397   (*p_record_line) (subfile, line, addr);
18398 }
18399
18400 /* Subroutine of dwarf_decode_lines_1 to simplify it.
18401    Mark the end of a set of line number records.
18402    The arguments are the same as for dwarf_record_line_1.
18403    If SUBFILE is NULL the request is ignored.  */
18404
18405 static void
18406 dwarf_finish_line (struct gdbarch *gdbarch, struct subfile *subfile,
18407                    CORE_ADDR address, record_line_ftype p_record_line)
18408 {
18409   if (subfile == NULL)
18410     return;
18411
18412   if (dwarf_line_debug)
18413     {
18414       fprintf_unfiltered (gdb_stdlog,
18415                           "Finishing current line, file %s, address %s\n",
18416                           lbasename (subfile->name),
18417                           paddress (gdbarch, address));
18418     }
18419
18420   dwarf_record_line_1 (gdbarch, subfile, 0, address, p_record_line);
18421 }
18422
18423 void
18424 lnp_state_machine::record_line (bool end_sequence)
18425 {
18426   if (dwarf_line_debug)
18427     {
18428       fprintf_unfiltered (gdb_stdlog,
18429                           "Processing actual line %u: file %u,"
18430                           " address %s, is_stmt %u, discrim %u\n",
18431                           m_line, to_underlying (m_file),
18432                           paddress (m_gdbarch, m_address),
18433                           m_is_stmt, m_discriminator);
18434     }
18435
18436   file_entry *fe = current_file ();
18437
18438   if (fe == NULL)
18439     dwarf2_debug_line_missing_file_complaint ();
18440   /* For now we ignore lines not starting on an instruction boundary.
18441      But not when processing end_sequence for compatibility with the
18442      previous version of the code.  */
18443   else if (m_op_index == 0 || end_sequence)
18444     {
18445       fe->included_p = 1;
18446       if (m_record_lines_p && m_is_stmt)
18447         {
18448           if (m_last_subfile != current_subfile || end_sequence)
18449             {
18450               dwarf_finish_line (m_gdbarch, m_last_subfile,
18451                                  m_address, m_record_line_callback);
18452             }
18453
18454           if (!end_sequence)
18455             {
18456               if (dwarf_record_line_p (m_line, m_last_line,
18457                                        m_line_has_non_zero_discriminator,
18458                                        m_last_subfile))
18459                 {
18460                   dwarf_record_line_1 (m_gdbarch, current_subfile,
18461                                        m_line, m_address,
18462                                        m_record_line_callback);
18463                 }
18464               m_last_subfile = current_subfile;
18465               m_last_line = m_line;
18466             }
18467         }
18468     }
18469 }
18470
18471 lnp_state_machine::lnp_state_machine (gdbarch *arch, line_header *lh,
18472                                       bool record_lines_p)
18473 {
18474   m_gdbarch = arch;
18475   m_record_lines_p = record_lines_p;
18476   m_line_header = lh;
18477
18478   m_record_line_callback = ::record_line;
18479
18480   /* Call `gdbarch_adjust_dwarf2_line' on the initial 0 address as if there
18481      was a line entry for it so that the backend has a chance to adjust it
18482      and also record it in case it needs it.  This is currently used by MIPS
18483      code, cf. `mips_adjust_dwarf2_line'.  */
18484   m_address = gdbarch_adjust_dwarf2_line (arch, 0, 0);
18485   m_is_stmt = lh->default_is_stmt;
18486   m_discriminator = 0;
18487 }
18488
18489 void
18490 lnp_state_machine::check_line_address (struct dwarf2_cu *cu,
18491                                        const gdb_byte *line_ptr,
18492                                        CORE_ADDR lowpc, CORE_ADDR address)
18493 {
18494   /* If address < lowpc then it's not a usable value, it's outside the
18495      pc range of the CU.  However, we restrict the test to only address
18496      values of zero to preserve GDB's previous behaviour which is to
18497      handle the specific case of a function being GC'd by the linker.  */
18498
18499   if (address == 0 && address < lowpc)
18500     {
18501       /* This line table is for a function which has been
18502          GCd by the linker.  Ignore it.  PR gdb/12528 */
18503
18504       struct objfile *objfile = cu->objfile;
18505       long line_offset = line_ptr - get_debug_line_section (cu)->buffer;
18506
18507       complaint (&symfile_complaints,
18508                  _(".debug_line address at offset 0x%lx is 0 [in module %s]"),
18509                  line_offset, objfile_name (objfile));
18510       m_record_line_callback = noop_record_line;
18511       /* Note: record_line_callback is left as noop_record_line until
18512          we see DW_LNE_end_sequence.  */
18513     }
18514 }
18515
18516 /* Subroutine of dwarf_decode_lines to simplify it.
18517    Process the line number information in LH.
18518    If DECODE_FOR_PST_P is non-zero, all we do is process the line number
18519    program in order to set included_p for every referenced header.  */
18520
18521 static void
18522 dwarf_decode_lines_1 (struct line_header *lh, struct dwarf2_cu *cu,
18523                       const int decode_for_pst_p, CORE_ADDR lowpc)
18524 {
18525   const gdb_byte *line_ptr, *extended_end;
18526   const gdb_byte *line_end;
18527   unsigned int bytes_read, extended_len;
18528   unsigned char op_code, extended_op;
18529   CORE_ADDR baseaddr;
18530   struct objfile *objfile = cu->objfile;
18531   bfd *abfd = objfile->obfd;
18532   struct gdbarch *gdbarch = get_objfile_arch (objfile);
18533   /* True if we're recording line info (as opposed to building partial
18534      symtabs and just interested in finding include files mentioned by
18535      the line number program).  */
18536   bool record_lines_p = !decode_for_pst_p;
18537
18538   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
18539
18540   line_ptr = lh->statement_program_start;
18541   line_end = lh->statement_program_end;
18542
18543   /* Read the statement sequences until there's nothing left.  */
18544   while (line_ptr < line_end)
18545     {
18546       /* The DWARF line number program state machine.  Reset the state
18547          machine at the start of each sequence.  */
18548       lnp_state_machine state_machine (gdbarch, lh, record_lines_p);
18549       bool end_sequence = false;
18550
18551       if (record_lines_p)
18552         {
18553           /* Start a subfile for the current file of the state
18554              machine.  */
18555           const file_entry *fe = state_machine.current_file ();
18556
18557           if (fe != NULL)
18558             dwarf2_start_subfile (fe->name, fe->include_dir (lh));
18559         }
18560
18561       /* Decode the table.  */
18562       while (line_ptr < line_end && !end_sequence)
18563         {
18564           op_code = read_1_byte (abfd, line_ptr);
18565           line_ptr += 1;
18566
18567           if (op_code >= lh->opcode_base)
18568             {
18569               /* Special opcode.  */
18570               state_machine.handle_special_opcode (op_code);
18571             }
18572           else switch (op_code)
18573             {
18574             case DW_LNS_extended_op:
18575               extended_len = read_unsigned_leb128 (abfd, line_ptr,
18576                                                    &bytes_read);
18577               line_ptr += bytes_read;
18578               extended_end = line_ptr + extended_len;
18579               extended_op = read_1_byte (abfd, line_ptr);
18580               line_ptr += 1;
18581               switch (extended_op)
18582                 {
18583                 case DW_LNE_end_sequence:
18584                   state_machine.handle_end_sequence ();
18585                   end_sequence = true;
18586                   break;
18587                 case DW_LNE_set_address:
18588                   {
18589                     CORE_ADDR address
18590                       = read_address (abfd, line_ptr, cu, &bytes_read);
18591                     line_ptr += bytes_read;
18592
18593                     state_machine.check_line_address (cu, line_ptr,
18594                                                       lowpc, address);
18595                     state_machine.handle_set_address (baseaddr, address);
18596                   }
18597                   break;
18598                 case DW_LNE_define_file:
18599                   {
18600                     const char *cur_file;
18601                     unsigned int mod_time, length;
18602                     dir_index dindex;
18603
18604                     cur_file = read_direct_string (abfd, line_ptr,
18605                                                    &bytes_read);
18606                     line_ptr += bytes_read;
18607                     dindex = (dir_index)
18608                       read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
18609                     line_ptr += bytes_read;
18610                     mod_time =
18611                       read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
18612                     line_ptr += bytes_read;
18613                     length =
18614                       read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
18615                     line_ptr += bytes_read;
18616                     lh->add_file_name (cur_file, dindex, mod_time, length);
18617                   }
18618                   break;
18619                 case DW_LNE_set_discriminator:
18620                   {
18621                     /* The discriminator is not interesting to the
18622                        debugger; just ignore it.  We still need to
18623                        check its value though:
18624                        if there are consecutive entries for the same
18625                        (non-prologue) line we want to coalesce them.
18626                        PR 17276.  */
18627                     unsigned int discr
18628                       = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
18629                     line_ptr += bytes_read;
18630
18631                     state_machine.handle_set_discriminator (discr);
18632                   }
18633                   break;
18634                 default:
18635                   complaint (&symfile_complaints,
18636                              _("mangled .debug_line section"));
18637                   return;
18638                 }
18639               /* Make sure that we parsed the extended op correctly.  If e.g.
18640                  we expected a different address size than the producer used,
18641                  we may have read the wrong number of bytes.  */
18642               if (line_ptr != extended_end)
18643                 {
18644                   complaint (&symfile_complaints,
18645                              _("mangled .debug_line section"));
18646                   return;
18647                 }
18648               break;
18649             case DW_LNS_copy:
18650               state_machine.handle_copy ();
18651               break;
18652             case DW_LNS_advance_pc:
18653               {
18654                 CORE_ADDR adjust
18655                   = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
18656                 line_ptr += bytes_read;
18657
18658                 state_machine.handle_advance_pc (adjust);
18659               }
18660               break;
18661             case DW_LNS_advance_line:
18662               {
18663                 int line_delta
18664                   = read_signed_leb128 (abfd, line_ptr, &bytes_read);
18665                 line_ptr += bytes_read;
18666
18667                 state_machine.handle_advance_line (line_delta);
18668               }
18669               break;
18670             case DW_LNS_set_file:
18671               {
18672                 file_name_index file
18673                   = (file_name_index) read_unsigned_leb128 (abfd, line_ptr,
18674                                                             &bytes_read);
18675                 line_ptr += bytes_read;
18676
18677                 state_machine.handle_set_file (file);
18678               }
18679               break;
18680             case DW_LNS_set_column:
18681               (void) read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
18682               line_ptr += bytes_read;
18683               break;
18684             case DW_LNS_negate_stmt:
18685               state_machine.handle_negate_stmt ();
18686               break;
18687             case DW_LNS_set_basic_block:
18688               break;
18689             /* Add to the address register of the state machine the
18690                address increment value corresponding to special opcode
18691                255.  I.e., this value is scaled by the minimum
18692                instruction length since special opcode 255 would have
18693                scaled the increment.  */
18694             case DW_LNS_const_add_pc:
18695               state_machine.handle_const_add_pc ();
18696               break;
18697             case DW_LNS_fixed_advance_pc:
18698               {
18699                 CORE_ADDR addr_adj = read_2_bytes (abfd, line_ptr);
18700                 line_ptr += 2;
18701
18702                 state_machine.handle_fixed_advance_pc (addr_adj);
18703               }
18704               break;
18705             default:
18706               {
18707                 /* Unknown standard opcode, ignore it.  */
18708                 int i;
18709
18710                 for (i = 0; i < lh->standard_opcode_lengths[op_code]; i++)
18711                   {
18712                     (void) read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
18713                     line_ptr += bytes_read;
18714                   }
18715               }
18716             }
18717         }
18718
18719       if (!end_sequence)
18720         dwarf2_debug_line_missing_end_sequence_complaint ();
18721
18722       /* We got a DW_LNE_end_sequence (or we ran off the end of the buffer,
18723          in which case we still finish recording the last line).  */
18724       state_machine.record_line (true);
18725     }
18726 }
18727
18728 /* Decode the Line Number Program (LNP) for the given line_header
18729    structure and CU.  The actual information extracted and the type
18730    of structures created from the LNP depends on the value of PST.
18731
18732    1. If PST is NULL, then this procedure uses the data from the program
18733       to create all necessary symbol tables, and their linetables.
18734
18735    2. If PST is not NULL, this procedure reads the program to determine
18736       the list of files included by the unit represented by PST, and
18737       builds all the associated partial symbol tables.
18738
18739    COMP_DIR is the compilation directory (DW_AT_comp_dir) or NULL if unknown.
18740    It is used for relative paths in the line table.
18741    NOTE: When processing partial symtabs (pst != NULL),
18742    comp_dir == pst->dirname.
18743
18744    NOTE: It is important that psymtabs have the same file name (via strcmp)
18745    as the corresponding symtab.  Since COMP_DIR is not used in the name of the
18746    symtab we don't use it in the name of the psymtabs we create.
18747    E.g. expand_line_sal requires this when finding psymtabs to expand.
18748    A good testcase for this is mb-inline.exp.
18749
18750    LOWPC is the lowest address in CU (or 0 if not known).
18751
18752    Boolean DECODE_MAPPING specifies we need to fully decode .debug_line
18753    for its PC<->lines mapping information.  Otherwise only the filename
18754    table is read in.  */
18755
18756 static void
18757 dwarf_decode_lines (struct line_header *lh, const char *comp_dir,
18758                     struct dwarf2_cu *cu, struct partial_symtab *pst,
18759                     CORE_ADDR lowpc, int decode_mapping)
18760 {
18761   struct objfile *objfile = cu->objfile;
18762   const int decode_for_pst_p = (pst != NULL);
18763
18764   if (decode_mapping)
18765     dwarf_decode_lines_1 (lh, cu, decode_for_pst_p, lowpc);
18766
18767   if (decode_for_pst_p)
18768     {
18769       int file_index;
18770
18771       /* Now that we're done scanning the Line Header Program, we can
18772          create the psymtab of each included file.  */
18773       for (file_index = 0; file_index < lh->file_names.size (); file_index++)
18774         if (lh->file_names[file_index].included_p == 1)
18775           {
18776             const char *include_name =
18777               psymtab_include_file_name (lh, file_index, pst, comp_dir);
18778             if (include_name != NULL)
18779               dwarf2_create_include_psymtab (include_name, pst, objfile);
18780           }
18781     }
18782   else
18783     {
18784       /* Make sure a symtab is created for every file, even files
18785          which contain only variables (i.e. no code with associated
18786          line numbers).  */
18787       struct compunit_symtab *cust = buildsym_compunit_symtab ();
18788       int i;
18789
18790       for (i = 0; i < lh->file_names.size (); i++)
18791         {
18792           file_entry &fe = lh->file_names[i];
18793
18794           dwarf2_start_subfile (fe.name, fe.include_dir (lh));
18795
18796           if (current_subfile->symtab == NULL)
18797             {
18798               current_subfile->symtab
18799                 = allocate_symtab (cust, current_subfile->name);
18800             }
18801           fe.symtab = current_subfile->symtab;
18802         }
18803     }
18804 }
18805
18806 /* Start a subfile for DWARF.  FILENAME is the name of the file and
18807    DIRNAME the name of the source directory which contains FILENAME
18808    or NULL if not known.
18809    This routine tries to keep line numbers from identical absolute and
18810    relative file names in a common subfile.
18811
18812    Using the `list' example from the GDB testsuite, which resides in
18813    /srcdir and compiling it with Irix6.2 cc in /compdir using a filename
18814    of /srcdir/list0.c yields the following debugging information for list0.c:
18815
18816    DW_AT_name:          /srcdir/list0.c
18817    DW_AT_comp_dir:      /compdir
18818    files.files[0].name: list0.h
18819    files.files[0].dir:  /srcdir
18820    files.files[1].name: list0.c
18821    files.files[1].dir:  /srcdir
18822
18823    The line number information for list0.c has to end up in a single
18824    subfile, so that `break /srcdir/list0.c:1' works as expected.
18825    start_subfile will ensure that this happens provided that we pass the
18826    concatenation of files.files[1].dir and files.files[1].name as the
18827    subfile's name.  */
18828
18829 static void
18830 dwarf2_start_subfile (const char *filename, const char *dirname)
18831 {
18832   char *copy = NULL;
18833
18834   /* In order not to lose the line information directory,
18835      we concatenate it to the filename when it makes sense.
18836      Note that the Dwarf3 standard says (speaking of filenames in line
18837      information): ``The directory index is ignored for file names
18838      that represent full path names''.  Thus ignoring dirname in the
18839      `else' branch below isn't an issue.  */
18840
18841   if (!IS_ABSOLUTE_PATH (filename) && dirname != NULL)
18842     {
18843       copy = concat (dirname, SLASH_STRING, filename, (char *)NULL);
18844       filename = copy;
18845     }
18846
18847   start_subfile (filename);
18848
18849   if (copy != NULL)
18850     xfree (copy);
18851 }
18852
18853 /* Start a symtab for DWARF.
18854    NAME, COMP_DIR, LOW_PC are passed to start_symtab.  */
18855
18856 static struct compunit_symtab *
18857 dwarf2_start_symtab (struct dwarf2_cu *cu,
18858                      const char *name, const char *comp_dir, CORE_ADDR low_pc)
18859 {
18860   struct compunit_symtab *cust
18861     = start_symtab (cu->objfile, name, comp_dir, low_pc);
18862
18863   record_debugformat ("DWARF 2");
18864   record_producer (cu->producer);
18865
18866   /* We assume that we're processing GCC output.  */
18867   processing_gcc_compilation = 2;
18868
18869   cu->processing_has_namespace_info = 0;
18870
18871   return cust;
18872 }
18873
18874 static void
18875 var_decode_location (struct attribute *attr, struct symbol *sym,
18876                      struct dwarf2_cu *cu)
18877 {
18878   struct objfile *objfile = cu->objfile;
18879   struct comp_unit_head *cu_header = &cu->header;
18880
18881   /* NOTE drow/2003-01-30: There used to be a comment and some special
18882      code here to turn a symbol with DW_AT_external and a
18883      SYMBOL_VALUE_ADDRESS of 0 into a LOC_UNRESOLVED symbol.  This was
18884      necessary for platforms (maybe Alpha, certainly PowerPC GNU/Linux
18885      with some versions of binutils) where shared libraries could have
18886      relocations against symbols in their debug information - the
18887      minimal symbol would have the right address, but the debug info
18888      would not.  It's no longer necessary, because we will explicitly
18889      apply relocations when we read in the debug information now.  */
18890
18891   /* A DW_AT_location attribute with no contents indicates that a
18892      variable has been optimized away.  */
18893   if (attr_form_is_block (attr) && DW_BLOCK (attr)->size == 0)
18894     {
18895       SYMBOL_ACLASS_INDEX (sym) = LOC_OPTIMIZED_OUT;
18896       return;
18897     }
18898
18899   /* Handle one degenerate form of location expression specially, to
18900      preserve GDB's previous behavior when section offsets are
18901      specified.  If this is just a DW_OP_addr or DW_OP_GNU_addr_index
18902      then mark this symbol as LOC_STATIC.  */
18903
18904   if (attr_form_is_block (attr)
18905       && ((DW_BLOCK (attr)->data[0] == DW_OP_addr
18906            && DW_BLOCK (attr)->size == 1 + cu_header->addr_size)
18907           || (DW_BLOCK (attr)->data[0] == DW_OP_GNU_addr_index
18908               && (DW_BLOCK (attr)->size
18909                   == 1 + leb128_size (&DW_BLOCK (attr)->data[1])))))
18910     {
18911       unsigned int dummy;
18912
18913       if (DW_BLOCK (attr)->data[0] == DW_OP_addr)
18914         SYMBOL_VALUE_ADDRESS (sym) =
18915           read_address (objfile->obfd, DW_BLOCK (attr)->data + 1, cu, &dummy);
18916       else
18917         SYMBOL_VALUE_ADDRESS (sym) =
18918           read_addr_index_from_leb128 (cu, DW_BLOCK (attr)->data + 1, &dummy);
18919       SYMBOL_ACLASS_INDEX (sym) = LOC_STATIC;
18920       fixup_symbol_section (sym, objfile);
18921       SYMBOL_VALUE_ADDRESS (sym) += ANOFFSET (objfile->section_offsets,
18922                                               SYMBOL_SECTION (sym));
18923       return;
18924     }
18925
18926   /* NOTE drow/2002-01-30: It might be worthwhile to have a static
18927      expression evaluator, and use LOC_COMPUTED only when necessary
18928      (i.e. when the value of a register or memory location is
18929      referenced, or a thread-local block, etc.).  Then again, it might
18930      not be worthwhile.  I'm assuming that it isn't unless performance
18931      or memory numbers show me otherwise.  */
18932
18933   dwarf2_symbol_mark_computed (attr, sym, cu, 0);
18934
18935   if (SYMBOL_COMPUTED_OPS (sym)->location_has_loclist)
18936     cu->has_loclist = 1;
18937 }
18938
18939 /* Given a pointer to a DWARF information entry, figure out if we need
18940    to make a symbol table entry for it, and if so, create a new entry
18941    and return a pointer to it.
18942    If TYPE is NULL, determine symbol type from the die, otherwise
18943    used the passed type.
18944    If SPACE is not NULL, use it to hold the new symbol.  If it is
18945    NULL, allocate a new symbol on the objfile's obstack.  */
18946
18947 static struct symbol *
18948 new_symbol_full (struct die_info *die, struct type *type, struct dwarf2_cu *cu,
18949                  struct symbol *space)
18950 {
18951   struct objfile *objfile = cu->objfile;
18952   struct gdbarch *gdbarch = get_objfile_arch (objfile);
18953   struct symbol *sym = NULL;
18954   const char *name;
18955   struct attribute *attr = NULL;
18956   struct attribute *attr2 = NULL;
18957   CORE_ADDR baseaddr;
18958   struct pending **list_to_add = NULL;
18959
18960   int inlined_func = (die->tag == DW_TAG_inlined_subroutine);
18961
18962   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
18963
18964   name = dwarf2_name (die, cu);
18965   if (name)
18966     {
18967       const char *linkagename;
18968       int suppress_add = 0;
18969
18970       if (space)
18971         sym = space;
18972       else
18973         sym = allocate_symbol (objfile);
18974       OBJSTAT (objfile, n_syms++);
18975
18976       /* Cache this symbol's name and the name's demangled form (if any).  */
18977       SYMBOL_SET_LANGUAGE (sym, cu->language, &objfile->objfile_obstack);
18978       linkagename = dwarf2_physname (name, die, cu);
18979       SYMBOL_SET_NAMES (sym, linkagename, strlen (linkagename), 0, objfile);
18980
18981       /* Fortran does not have mangling standard and the mangling does differ
18982          between gfortran, iFort etc.  */
18983       if (cu->language == language_fortran
18984           && symbol_get_demangled_name (&(sym->ginfo)) == NULL)
18985         symbol_set_demangled_name (&(sym->ginfo),
18986                                    dwarf2_full_name (name, die, cu),
18987                                    NULL);
18988
18989       /* Default assumptions.
18990          Use the passed type or decode it from the die.  */
18991       SYMBOL_DOMAIN (sym) = VAR_DOMAIN;
18992       SYMBOL_ACLASS_INDEX (sym) = LOC_OPTIMIZED_OUT;
18993       if (type != NULL)
18994         SYMBOL_TYPE (sym) = type;
18995       else
18996         SYMBOL_TYPE (sym) = die_type (die, cu);
18997       attr = dwarf2_attr (die,
18998                           inlined_func ? DW_AT_call_line : DW_AT_decl_line,
18999                           cu);
19000       if (attr)
19001         {
19002           SYMBOL_LINE (sym) = DW_UNSND (attr);
19003         }
19004
19005       attr = dwarf2_attr (die,
19006                           inlined_func ? DW_AT_call_file : DW_AT_decl_file,
19007                           cu);
19008       if (attr)
19009         {
19010           file_name_index file_index = (file_name_index) DW_UNSND (attr);
19011           struct file_entry *fe;
19012
19013           if (cu->line_header != NULL)
19014             fe = cu->line_header->file_name_at (file_index);
19015           else
19016             fe = NULL;
19017
19018           if (fe == NULL)
19019             complaint (&symfile_complaints,
19020                        _("file index out of range"));
19021           else
19022             symbol_set_symtab (sym, fe->symtab);
19023         }
19024
19025       switch (die->tag)
19026         {
19027         case DW_TAG_label:
19028           attr = dwarf2_attr (die, DW_AT_low_pc, cu);
19029           if (attr)
19030             {
19031               CORE_ADDR addr;
19032
19033               addr = attr_value_as_address (attr);
19034               addr = gdbarch_adjust_dwarf2_addr (gdbarch, addr + baseaddr);
19035               SYMBOL_VALUE_ADDRESS (sym) = addr;
19036             }
19037           SYMBOL_TYPE (sym) = objfile_type (objfile)->builtin_core_addr;
19038           SYMBOL_DOMAIN (sym) = LABEL_DOMAIN;
19039           SYMBOL_ACLASS_INDEX (sym) = LOC_LABEL;
19040           add_symbol_to_list (sym, cu->list_in_scope);
19041           break;
19042         case DW_TAG_subprogram:
19043           /* SYMBOL_BLOCK_VALUE (sym) will be filled in later by
19044              finish_block.  */
19045           SYMBOL_ACLASS_INDEX (sym) = LOC_BLOCK;
19046           attr2 = dwarf2_attr (die, DW_AT_external, cu);
19047           if ((attr2 && (DW_UNSND (attr2) != 0))
19048               || cu->language == language_ada)
19049             {
19050               /* Subprograms marked external are stored as a global symbol.
19051                  Ada subprograms, whether marked external or not, are always
19052                  stored as a global symbol, because we want to be able to
19053                  access them globally.  For instance, we want to be able
19054                  to break on a nested subprogram without having to
19055                  specify the context.  */
19056               list_to_add = &global_symbols;
19057             }
19058           else
19059             {
19060               list_to_add = cu->list_in_scope;
19061             }
19062           break;
19063         case DW_TAG_inlined_subroutine:
19064           /* SYMBOL_BLOCK_VALUE (sym) will be filled in later by
19065              finish_block.  */
19066           SYMBOL_ACLASS_INDEX (sym) = LOC_BLOCK;
19067           SYMBOL_INLINED (sym) = 1;
19068           list_to_add = cu->list_in_scope;
19069           break;
19070         case DW_TAG_template_value_param:
19071           suppress_add = 1;
19072           /* Fall through.  */
19073         case DW_TAG_constant:
19074         case DW_TAG_variable:
19075         case DW_TAG_member:
19076           /* Compilation with minimal debug info may result in
19077              variables with missing type entries.  Change the
19078              misleading `void' type to something sensible.  */
19079           if (TYPE_CODE (SYMBOL_TYPE (sym)) == TYPE_CODE_VOID)
19080             SYMBOL_TYPE (sym)
19081               = objfile_type (objfile)->nodebug_data_symbol;
19082
19083           attr = dwarf2_attr (die, DW_AT_const_value, cu);
19084           /* In the case of DW_TAG_member, we should only be called for
19085              static const members.  */
19086           if (die->tag == DW_TAG_member)
19087             {
19088               /* dwarf2_add_field uses die_is_declaration,
19089                  so we do the same.  */
19090               gdb_assert (die_is_declaration (die, cu));
19091               gdb_assert (attr);
19092             }
19093           if (attr)
19094             {
19095               dwarf2_const_value (attr, sym, cu);
19096               attr2 = dwarf2_attr (die, DW_AT_external, cu);
19097               if (!suppress_add)
19098                 {
19099                   if (attr2 && (DW_UNSND (attr2) != 0))
19100                     list_to_add = &global_symbols;
19101                   else
19102                     list_to_add = cu->list_in_scope;
19103                 }
19104               break;
19105             }
19106           attr = dwarf2_attr (die, DW_AT_location, cu);
19107           if (attr)
19108             {
19109               var_decode_location (attr, sym, cu);
19110               attr2 = dwarf2_attr (die, DW_AT_external, cu);
19111
19112               /* Fortran explicitly imports any global symbols to the local
19113                  scope by DW_TAG_common_block.  */
19114               if (cu->language == language_fortran && die->parent
19115                   && die->parent->tag == DW_TAG_common_block)
19116                 attr2 = NULL;
19117
19118               if (SYMBOL_CLASS (sym) == LOC_STATIC
19119                   && SYMBOL_VALUE_ADDRESS (sym) == 0
19120                   && !dwarf2_per_objfile->has_section_at_zero)
19121                 {
19122                   /* When a static variable is eliminated by the linker,
19123                      the corresponding debug information is not stripped
19124                      out, but the variable address is set to null;
19125                      do not add such variables into symbol table.  */
19126                 }
19127               else if (attr2 && (DW_UNSND (attr2) != 0))
19128                 {
19129                   /* Workaround gfortran PR debug/40040 - it uses
19130                      DW_AT_location for variables in -fPIC libraries which may
19131                      get overriden by other libraries/executable and get
19132                      a different address.  Resolve it by the minimal symbol
19133                      which may come from inferior's executable using copy
19134                      relocation.  Make this workaround only for gfortran as for
19135                      other compilers GDB cannot guess the minimal symbol
19136                      Fortran mangling kind.  */
19137                   if (cu->language == language_fortran && die->parent
19138                       && die->parent->tag == DW_TAG_module
19139                       && cu->producer
19140                       && startswith (cu->producer, "GNU Fortran"))
19141                     SYMBOL_ACLASS_INDEX (sym) = LOC_UNRESOLVED;
19142
19143                   /* A variable with DW_AT_external is never static,
19144                      but it may be block-scoped.  */
19145                   list_to_add = (cu->list_in_scope == &file_symbols
19146                                  ? &global_symbols : cu->list_in_scope);
19147                 }
19148               else
19149                 list_to_add = cu->list_in_scope;
19150             }
19151           else
19152             {
19153               /* We do not know the address of this symbol.
19154                  If it is an external symbol and we have type information
19155                  for it, enter the symbol as a LOC_UNRESOLVED symbol.
19156                  The address of the variable will then be determined from
19157                  the minimal symbol table whenever the variable is
19158                  referenced.  */
19159               attr2 = dwarf2_attr (die, DW_AT_external, cu);
19160
19161               /* Fortran explicitly imports any global symbols to the local
19162                  scope by DW_TAG_common_block.  */
19163               if (cu->language == language_fortran && die->parent
19164                   && die->parent->tag == DW_TAG_common_block)
19165                 {
19166                   /* SYMBOL_CLASS doesn't matter here because
19167                      read_common_block is going to reset it.  */
19168                   if (!suppress_add)
19169                     list_to_add = cu->list_in_scope;
19170                 }
19171               else if (attr2 && (DW_UNSND (attr2) != 0)
19172                        && dwarf2_attr (die, DW_AT_type, cu) != NULL)
19173                 {
19174                   /* A variable with DW_AT_external is never static, but it
19175                      may be block-scoped.  */
19176                   list_to_add = (cu->list_in_scope == &file_symbols
19177                                  ? &global_symbols : cu->list_in_scope);
19178
19179                   SYMBOL_ACLASS_INDEX (sym) = LOC_UNRESOLVED;
19180                 }
19181               else if (!die_is_declaration (die, cu))
19182                 {
19183                   /* Use the default LOC_OPTIMIZED_OUT class.  */
19184                   gdb_assert (SYMBOL_CLASS (sym) == LOC_OPTIMIZED_OUT);
19185                   if (!suppress_add)
19186                     list_to_add = cu->list_in_scope;
19187                 }
19188             }
19189           break;
19190         case DW_TAG_formal_parameter:
19191           /* If we are inside a function, mark this as an argument.  If
19192              not, we might be looking at an argument to an inlined function
19193              when we do not have enough information to show inlined frames;
19194              pretend it's a local variable in that case so that the user can
19195              still see it.  */
19196           if (context_stack_depth > 0
19197               && context_stack[context_stack_depth - 1].name != NULL)
19198             SYMBOL_IS_ARGUMENT (sym) = 1;
19199           attr = dwarf2_attr (die, DW_AT_location, cu);
19200           if (attr)
19201             {
19202               var_decode_location (attr, sym, cu);
19203             }
19204           attr = dwarf2_attr (die, DW_AT_const_value, cu);
19205           if (attr)
19206             {
19207               dwarf2_const_value (attr, sym, cu);
19208             }
19209
19210           list_to_add = cu->list_in_scope;
19211           break;
19212         case DW_TAG_unspecified_parameters:
19213           /* From varargs functions; gdb doesn't seem to have any
19214              interest in this information, so just ignore it for now.
19215              (FIXME?) */
19216           break;
19217         case DW_TAG_template_type_param:
19218           suppress_add = 1;
19219           /* Fall through.  */
19220         case DW_TAG_class_type:
19221         case DW_TAG_interface_type:
19222         case DW_TAG_structure_type:
19223         case DW_TAG_union_type:
19224         case DW_TAG_set_type:
19225         case DW_TAG_enumeration_type:
19226           SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
19227           SYMBOL_DOMAIN (sym) = STRUCT_DOMAIN;
19228
19229           {
19230             /* NOTE: carlton/2003-11-10: C++ class symbols shouldn't
19231                really ever be static objects: otherwise, if you try
19232                to, say, break of a class's method and you're in a file
19233                which doesn't mention that class, it won't work unless
19234                the check for all static symbols in lookup_symbol_aux
19235                saves you.  See the OtherFileClass tests in
19236                gdb.c++/namespace.exp.  */
19237
19238             if (!suppress_add)
19239               {
19240                 list_to_add = (cu->list_in_scope == &file_symbols
19241                                && cu->language == language_cplus
19242                                ? &global_symbols : cu->list_in_scope);
19243
19244                 /* The semantics of C++ state that "struct foo {
19245                    ... }" also defines a typedef for "foo".  */
19246                 if (cu->language == language_cplus
19247                     || cu->language == language_ada
19248                     || cu->language == language_d
19249                     || cu->language == language_rust)
19250                   {
19251                     /* The symbol's name is already allocated along
19252                        with this objfile, so we don't need to
19253                        duplicate it for the type.  */
19254                     if (TYPE_NAME (SYMBOL_TYPE (sym)) == 0)
19255                       TYPE_NAME (SYMBOL_TYPE (sym)) = SYMBOL_SEARCH_NAME (sym);
19256                   }
19257               }
19258           }
19259           break;
19260         case DW_TAG_typedef:
19261           SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
19262           SYMBOL_DOMAIN (sym) = VAR_DOMAIN;
19263           list_to_add = cu->list_in_scope;
19264           break;
19265         case DW_TAG_base_type:
19266         case DW_TAG_subrange_type:
19267           SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
19268           SYMBOL_DOMAIN (sym) = VAR_DOMAIN;
19269           list_to_add = cu->list_in_scope;
19270           break;
19271         case DW_TAG_enumerator:
19272           attr = dwarf2_attr (die, DW_AT_const_value, cu);
19273           if (attr)
19274             {
19275               dwarf2_const_value (attr, sym, cu);
19276             }
19277           {
19278             /* NOTE: carlton/2003-11-10: See comment above in the
19279                DW_TAG_class_type, etc. block.  */
19280
19281             list_to_add = (cu->list_in_scope == &file_symbols
19282                            && cu->language == language_cplus
19283                            ? &global_symbols : cu->list_in_scope);
19284           }
19285           break;
19286         case DW_TAG_imported_declaration:
19287         case DW_TAG_namespace:
19288           SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
19289           list_to_add = &global_symbols;
19290           break;
19291         case DW_TAG_module:
19292           SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
19293           SYMBOL_DOMAIN (sym) = MODULE_DOMAIN;
19294           list_to_add = &global_symbols;
19295           break;
19296         case DW_TAG_common_block:
19297           SYMBOL_ACLASS_INDEX (sym) = LOC_COMMON_BLOCK;
19298           SYMBOL_DOMAIN (sym) = COMMON_BLOCK_DOMAIN;
19299           add_symbol_to_list (sym, cu->list_in_scope);
19300           break;
19301         default:
19302           /* Not a tag we recognize.  Hopefully we aren't processing
19303              trash data, but since we must specifically ignore things
19304              we don't recognize, there is nothing else we should do at
19305              this point.  */
19306           complaint (&symfile_complaints, _("unsupported tag: '%s'"),
19307                      dwarf_tag_name (die->tag));
19308           break;
19309         }
19310
19311       if (suppress_add)
19312         {
19313           sym->hash_next = objfile->template_symbols;
19314           objfile->template_symbols = sym;
19315           list_to_add = NULL;
19316         }
19317
19318       if (list_to_add != NULL)
19319         add_symbol_to_list (sym, list_to_add);
19320
19321       /* For the benefit of old versions of GCC, check for anonymous
19322          namespaces based on the demangled name.  */
19323       if (!cu->processing_has_namespace_info
19324           && cu->language == language_cplus)
19325         cp_scan_for_anonymous_namespaces (sym, objfile);
19326     }
19327   return (sym);
19328 }
19329
19330 /* A wrapper for new_symbol_full that always allocates a new symbol.  */
19331
19332 static struct symbol *
19333 new_symbol (struct die_info *die, struct type *type, struct dwarf2_cu *cu)
19334 {
19335   return new_symbol_full (die, type, cu, NULL);
19336 }
19337
19338 /* Given an attr with a DW_FORM_dataN value in host byte order,
19339    zero-extend it as appropriate for the symbol's type.  The DWARF
19340    standard (v4) is not entirely clear about the meaning of using
19341    DW_FORM_dataN for a constant with a signed type, where the type is
19342    wider than the data.  The conclusion of a discussion on the DWARF
19343    list was that this is unspecified.  We choose to always zero-extend
19344    because that is the interpretation long in use by GCC.  */
19345
19346 static gdb_byte *
19347 dwarf2_const_value_data (const struct attribute *attr, struct obstack *obstack,
19348                          struct dwarf2_cu *cu, LONGEST *value, int bits)
19349 {
19350   struct objfile *objfile = cu->objfile;
19351   enum bfd_endian byte_order = bfd_big_endian (objfile->obfd) ?
19352                                 BFD_ENDIAN_BIG : BFD_ENDIAN_LITTLE;
19353   LONGEST l = DW_UNSND (attr);
19354
19355   if (bits < sizeof (*value) * 8)
19356     {
19357       l &= ((LONGEST) 1 << bits) - 1;
19358       *value = l;
19359     }
19360   else if (bits == sizeof (*value) * 8)
19361     *value = l;
19362   else
19363     {
19364       gdb_byte *bytes = (gdb_byte *) obstack_alloc (obstack, bits / 8);
19365       store_unsigned_integer (bytes, bits / 8, byte_order, l);
19366       return bytes;
19367     }
19368
19369   return NULL;
19370 }
19371
19372 /* Read a constant value from an attribute.  Either set *VALUE, or if
19373    the value does not fit in *VALUE, set *BYTES - either already
19374    allocated on the objfile obstack, or newly allocated on OBSTACK,
19375    or, set *BATON, if we translated the constant to a location
19376    expression.  */
19377
19378 static void
19379 dwarf2_const_value_attr (const struct attribute *attr, struct type *type,
19380                          const char *name, struct obstack *obstack,
19381                          struct dwarf2_cu *cu,
19382                          LONGEST *value, const gdb_byte **bytes,
19383                          struct dwarf2_locexpr_baton **baton)
19384 {
19385   struct objfile *objfile = cu->objfile;
19386   struct comp_unit_head *cu_header = &cu->header;
19387   struct dwarf_block *blk;
19388   enum bfd_endian byte_order = (bfd_big_endian (objfile->obfd) ?
19389                                 BFD_ENDIAN_BIG : BFD_ENDIAN_LITTLE);
19390
19391   *value = 0;
19392   *bytes = NULL;
19393   *baton = NULL;
19394
19395   switch (attr->form)
19396     {
19397     case DW_FORM_addr:
19398     case DW_FORM_GNU_addr_index:
19399       {
19400         gdb_byte *data;
19401
19402         if (TYPE_LENGTH (type) != cu_header->addr_size)
19403           dwarf2_const_value_length_mismatch_complaint (name,
19404                                                         cu_header->addr_size,
19405                                                         TYPE_LENGTH (type));
19406         /* Symbols of this form are reasonably rare, so we just
19407            piggyback on the existing location code rather than writing
19408            a new implementation of symbol_computed_ops.  */
19409         *baton = XOBNEW (obstack, struct dwarf2_locexpr_baton);
19410         (*baton)->per_cu = cu->per_cu;
19411         gdb_assert ((*baton)->per_cu);
19412
19413         (*baton)->size = 2 + cu_header->addr_size;
19414         data = (gdb_byte *) obstack_alloc (obstack, (*baton)->size);
19415         (*baton)->data = data;
19416
19417         data[0] = DW_OP_addr;
19418         store_unsigned_integer (&data[1], cu_header->addr_size,
19419                                 byte_order, DW_ADDR (attr));
19420         data[cu_header->addr_size + 1] = DW_OP_stack_value;
19421       }
19422       break;
19423     case DW_FORM_string:
19424     case DW_FORM_strp:
19425     case DW_FORM_GNU_str_index:
19426     case DW_FORM_GNU_strp_alt:
19427       /* DW_STRING is already allocated on the objfile obstack, point
19428          directly to it.  */
19429       *bytes = (const gdb_byte *) DW_STRING (attr);
19430       break;
19431     case DW_FORM_block1:
19432     case DW_FORM_block2:
19433     case DW_FORM_block4:
19434     case DW_FORM_block:
19435     case DW_FORM_exprloc:
19436     case DW_FORM_data16:
19437       blk = DW_BLOCK (attr);
19438       if (TYPE_LENGTH (type) != blk->size)
19439         dwarf2_const_value_length_mismatch_complaint (name, blk->size,
19440                                                       TYPE_LENGTH (type));
19441       *bytes = blk->data;
19442       break;
19443
19444       /* The DW_AT_const_value attributes are supposed to carry the
19445          symbol's value "represented as it would be on the target
19446          architecture."  By the time we get here, it's already been
19447          converted to host endianness, so we just need to sign- or
19448          zero-extend it as appropriate.  */
19449     case DW_FORM_data1:
19450       *bytes = dwarf2_const_value_data (attr, obstack, cu, value, 8);
19451       break;
19452     case DW_FORM_data2:
19453       *bytes = dwarf2_const_value_data (attr, obstack, cu, value, 16);
19454       break;
19455     case DW_FORM_data4:
19456       *bytes = dwarf2_const_value_data (attr, obstack, cu, value, 32);
19457       break;
19458     case DW_FORM_data8:
19459       *bytes = dwarf2_const_value_data (attr, obstack, cu, value, 64);
19460       break;
19461
19462     case DW_FORM_sdata:
19463       *value = DW_SND (attr);
19464       break;
19465
19466     case DW_FORM_udata:
19467       *value = DW_UNSND (attr);
19468       break;
19469
19470     default:
19471       complaint (&symfile_complaints,
19472                  _("unsupported const value attribute form: '%s'"),
19473                  dwarf_form_name (attr->form));
19474       *value = 0;
19475       break;
19476     }
19477 }
19478
19479
19480 /* Copy constant value from an attribute to a symbol.  */
19481
19482 static void
19483 dwarf2_const_value (const struct attribute *attr, struct symbol *sym,
19484                     struct dwarf2_cu *cu)
19485 {
19486   struct objfile *objfile = cu->objfile;
19487   LONGEST value;
19488   const gdb_byte *bytes;
19489   struct dwarf2_locexpr_baton *baton;
19490
19491   dwarf2_const_value_attr (attr, SYMBOL_TYPE (sym),
19492                            SYMBOL_PRINT_NAME (sym),
19493                            &objfile->objfile_obstack, cu,
19494                            &value, &bytes, &baton);
19495
19496   if (baton != NULL)
19497     {
19498       SYMBOL_LOCATION_BATON (sym) = baton;
19499       SYMBOL_ACLASS_INDEX (sym) = dwarf2_locexpr_index;
19500     }
19501   else if (bytes != NULL)
19502      {
19503       SYMBOL_VALUE_BYTES (sym) = bytes;
19504       SYMBOL_ACLASS_INDEX (sym) = LOC_CONST_BYTES;
19505     }
19506   else
19507     {
19508       SYMBOL_VALUE (sym) = value;
19509       SYMBOL_ACLASS_INDEX (sym) = LOC_CONST;
19510     }
19511 }
19512
19513 /* Return the type of the die in question using its DW_AT_type attribute.  */
19514
19515 static struct type *
19516 die_type (struct die_info *die, struct dwarf2_cu *cu)
19517 {
19518   struct attribute *type_attr;
19519
19520   type_attr = dwarf2_attr (die, DW_AT_type, cu);
19521   if (!type_attr)
19522     {
19523       /* A missing DW_AT_type represents a void type.  */
19524       return objfile_type (cu->objfile)->builtin_void;
19525     }
19526
19527   return lookup_die_type (die, type_attr, cu);
19528 }
19529
19530 /* True iff CU's producer generates GNAT Ada auxiliary information
19531    that allows to find parallel types through that information instead
19532    of having to do expensive parallel lookups by type name.  */
19533
19534 static int
19535 need_gnat_info (struct dwarf2_cu *cu)
19536 {
19537   /* FIXME: brobecker/2010-10-12: As of now, only the AdaCore version
19538      of GNAT produces this auxiliary information, without any indication
19539      that it is produced.  Part of enhancing the FSF version of GNAT
19540      to produce that information will be to put in place an indicator
19541      that we can use in order to determine whether the descriptive type
19542      info is available or not.  One suggestion that has been made is
19543      to use a new attribute, attached to the CU die.  For now, assume
19544      that the descriptive type info is not available.  */
19545   return 0;
19546 }
19547
19548 /* Return the auxiliary type of the die in question using its
19549    DW_AT_GNAT_descriptive_type attribute.  Returns NULL if the
19550    attribute is not present.  */
19551
19552 static struct type *
19553 die_descriptive_type (struct die_info *die, struct dwarf2_cu *cu)
19554 {
19555   struct attribute *type_attr;
19556
19557   type_attr = dwarf2_attr (die, DW_AT_GNAT_descriptive_type, cu);
19558   if (!type_attr)
19559     return NULL;
19560
19561   return lookup_die_type (die, type_attr, cu);
19562 }
19563
19564 /* If DIE has a descriptive_type attribute, then set the TYPE's
19565    descriptive type accordingly.  */
19566
19567 static void
19568 set_descriptive_type (struct type *type, struct die_info *die,
19569                       struct dwarf2_cu *cu)
19570 {
19571   struct type *descriptive_type = die_descriptive_type (die, cu);
19572
19573   if (descriptive_type)
19574     {
19575       ALLOCATE_GNAT_AUX_TYPE (type);
19576       TYPE_DESCRIPTIVE_TYPE (type) = descriptive_type;
19577     }
19578 }
19579
19580 /* Return the containing type of the die in question using its
19581    DW_AT_containing_type attribute.  */
19582
19583 static struct type *
19584 die_containing_type (struct die_info *die, struct dwarf2_cu *cu)
19585 {
19586   struct attribute *type_attr;
19587
19588   type_attr = dwarf2_attr (die, DW_AT_containing_type, cu);
19589   if (!type_attr)
19590     error (_("Dwarf Error: Problem turning containing type into gdb type "
19591              "[in module %s]"), objfile_name (cu->objfile));
19592
19593   return lookup_die_type (die, type_attr, cu);
19594 }
19595
19596 /* Return an error marker type to use for the ill formed type in DIE/CU.  */
19597
19598 static struct type *
19599 build_error_marker_type (struct dwarf2_cu *cu, struct die_info *die)
19600 {
19601   struct objfile *objfile = dwarf2_per_objfile->objfile;
19602   char *message, *saved;
19603
19604   message = xstrprintf (_("<unknown type in %s, CU 0x%x, DIE 0x%x>"),
19605                         objfile_name (objfile),
19606                         to_underlying (cu->header.sect_off),
19607                         to_underlying (die->sect_off));
19608   saved = (char *) obstack_copy0 (&objfile->objfile_obstack,
19609                                   message, strlen (message));
19610   xfree (message);
19611
19612   return init_type (objfile, TYPE_CODE_ERROR, 0, saved);
19613 }
19614
19615 /* Look up the type of DIE in CU using its type attribute ATTR.
19616    ATTR must be one of: DW_AT_type, DW_AT_GNAT_descriptive_type,
19617    DW_AT_containing_type.
19618    If there is no type substitute an error marker.  */
19619
19620 static struct type *
19621 lookup_die_type (struct die_info *die, const struct attribute *attr,
19622                  struct dwarf2_cu *cu)
19623 {
19624   struct objfile *objfile = cu->objfile;
19625   struct type *this_type;
19626
19627   gdb_assert (attr->name == DW_AT_type
19628               || attr->name == DW_AT_GNAT_descriptive_type
19629               || attr->name == DW_AT_containing_type);
19630
19631   /* First see if we have it cached.  */
19632
19633   if (attr->form == DW_FORM_GNU_ref_alt)
19634     {
19635       struct dwarf2_per_cu_data *per_cu;
19636       sect_offset sect_off = dwarf2_get_ref_die_offset (attr);
19637
19638       per_cu = dwarf2_find_containing_comp_unit (sect_off, 1, cu->objfile);
19639       this_type = get_die_type_at_offset (sect_off, per_cu);
19640     }
19641   else if (attr_form_is_ref (attr))
19642     {
19643       sect_offset sect_off = dwarf2_get_ref_die_offset (attr);
19644
19645       this_type = get_die_type_at_offset (sect_off, cu->per_cu);
19646     }
19647   else if (attr->form == DW_FORM_ref_sig8)
19648     {
19649       ULONGEST signature = DW_SIGNATURE (attr);
19650
19651       return get_signatured_type (die, signature, cu);
19652     }
19653   else
19654     {
19655       complaint (&symfile_complaints,
19656                  _("Dwarf Error: Bad type attribute %s in DIE"
19657                    " at 0x%x [in module %s]"),
19658                  dwarf_attr_name (attr->name), to_underlying (die->sect_off),
19659                  objfile_name (objfile));
19660       return build_error_marker_type (cu, die);
19661     }
19662
19663   /* If not cached we need to read it in.  */
19664
19665   if (this_type == NULL)
19666     {
19667       struct die_info *type_die = NULL;
19668       struct dwarf2_cu *type_cu = cu;
19669
19670       if (attr_form_is_ref (attr))
19671         type_die = follow_die_ref (die, attr, &type_cu);
19672       if (type_die == NULL)
19673         return build_error_marker_type (cu, die);
19674       /* If we find the type now, it's probably because the type came
19675          from an inter-CU reference and the type's CU got expanded before
19676          ours.  */
19677       this_type = read_type_die (type_die, type_cu);
19678     }
19679
19680   /* If we still don't have a type use an error marker.  */
19681
19682   if (this_type == NULL)
19683     return build_error_marker_type (cu, die);
19684
19685   return this_type;
19686 }
19687
19688 /* Return the type in DIE, CU.
19689    Returns NULL for invalid types.
19690
19691    This first does a lookup in die_type_hash,
19692    and only reads the die in if necessary.
19693
19694    NOTE: This can be called when reading in partial or full symbols.  */
19695
19696 static struct type *
19697 read_type_die (struct die_info *die, struct dwarf2_cu *cu)
19698 {
19699   struct type *this_type;
19700
19701   this_type = get_die_type (die, cu);
19702   if (this_type)
19703     return this_type;
19704
19705   return read_type_die_1 (die, cu);
19706 }
19707
19708 /* Read the type in DIE, CU.
19709    Returns NULL for invalid types.  */
19710
19711 static struct type *
19712 read_type_die_1 (struct die_info *die, struct dwarf2_cu *cu)
19713 {
19714   struct type *this_type = NULL;
19715
19716   switch (die->tag)
19717     {
19718     case DW_TAG_class_type:
19719     case DW_TAG_interface_type:
19720     case DW_TAG_structure_type:
19721     case DW_TAG_union_type:
19722       this_type = read_structure_type (die, cu);
19723       break;
19724     case DW_TAG_enumeration_type:
19725       this_type = read_enumeration_type (die, cu);
19726       break;
19727     case DW_TAG_subprogram:
19728     case DW_TAG_subroutine_type:
19729     case DW_TAG_inlined_subroutine:
19730       this_type = read_subroutine_type (die, cu);
19731       break;
19732     case DW_TAG_array_type:
19733       this_type = read_array_type (die, cu);
19734       break;
19735     case DW_TAG_set_type:
19736       this_type = read_set_type (die, cu);
19737       break;
19738     case DW_TAG_pointer_type:
19739       this_type = read_tag_pointer_type (die, cu);
19740       break;
19741     case DW_TAG_ptr_to_member_type:
19742       this_type = read_tag_ptr_to_member_type (die, cu);
19743       break;
19744     case DW_TAG_reference_type:
19745       this_type = read_tag_reference_type (die, cu, TYPE_CODE_REF);
19746       break;
19747     case DW_TAG_rvalue_reference_type:
19748       this_type = read_tag_reference_type (die, cu, TYPE_CODE_RVALUE_REF);
19749       break;
19750     case DW_TAG_const_type:
19751       this_type = read_tag_const_type (die, cu);
19752       break;
19753     case DW_TAG_volatile_type:
19754       this_type = read_tag_volatile_type (die, cu);
19755       break;
19756     case DW_TAG_restrict_type:
19757       this_type = read_tag_restrict_type (die, cu);
19758       break;
19759     case DW_TAG_string_type:
19760       this_type = read_tag_string_type (die, cu);
19761       break;
19762     case DW_TAG_typedef:
19763       this_type = read_typedef (die, cu);
19764       break;
19765     case DW_TAG_subrange_type:
19766       this_type = read_subrange_type (die, cu);
19767       break;
19768     case DW_TAG_base_type:
19769       this_type = read_base_type (die, cu);
19770       break;
19771     case DW_TAG_unspecified_type:
19772       this_type = read_unspecified_type (die, cu);
19773       break;
19774     case DW_TAG_namespace:
19775       this_type = read_namespace_type (die, cu);
19776       break;
19777     case DW_TAG_module:
19778       this_type = read_module_type (die, cu);
19779       break;
19780     case DW_TAG_atomic_type:
19781       this_type = read_tag_atomic_type (die, cu);
19782       break;
19783     default:
19784       complaint (&symfile_complaints,
19785                  _("unexpected tag in read_type_die: '%s'"),
19786                  dwarf_tag_name (die->tag));
19787       break;
19788     }
19789
19790   return this_type;
19791 }
19792
19793 /* See if we can figure out if the class lives in a namespace.  We do
19794    this by looking for a member function; its demangled name will
19795    contain namespace info, if there is any.
19796    Return the computed name or NULL.
19797    Space for the result is allocated on the objfile's obstack.
19798    This is the full-die version of guess_partial_die_structure_name.
19799    In this case we know DIE has no useful parent.  */
19800
19801 static char *
19802 guess_full_die_structure_name (struct die_info *die, struct dwarf2_cu *cu)
19803 {
19804   struct die_info *spec_die;
19805   struct dwarf2_cu *spec_cu;
19806   struct die_info *child;
19807
19808   spec_cu = cu;
19809   spec_die = die_specification (die, &spec_cu);
19810   if (spec_die != NULL)
19811     {
19812       die = spec_die;
19813       cu = spec_cu;
19814     }
19815
19816   for (child = die->child;
19817        child != NULL;
19818        child = child->sibling)
19819     {
19820       if (child->tag == DW_TAG_subprogram)
19821         {
19822           const char *linkage_name;
19823
19824           linkage_name = dwarf2_string_attr (child, DW_AT_linkage_name, cu);
19825           if (linkage_name == NULL)
19826             linkage_name = dwarf2_string_attr (child, DW_AT_MIPS_linkage_name,
19827                                                cu);
19828           if (linkage_name != NULL)
19829             {
19830               char *actual_name
19831                 = language_class_name_from_physname (cu->language_defn,
19832                                                      linkage_name);
19833               char *name = NULL;
19834
19835               if (actual_name != NULL)
19836                 {
19837                   const char *die_name = dwarf2_name (die, cu);
19838
19839                   if (die_name != NULL
19840                       && strcmp (die_name, actual_name) != 0)
19841                     {
19842                       /* Strip off the class name from the full name.
19843                          We want the prefix.  */
19844                       int die_name_len = strlen (die_name);
19845                       int actual_name_len = strlen (actual_name);
19846
19847                       /* Test for '::' as a sanity check.  */
19848                       if (actual_name_len > die_name_len + 2
19849                           && actual_name[actual_name_len
19850                                          - die_name_len - 1] == ':')
19851                         name = (char *) obstack_copy0 (
19852                           &cu->objfile->per_bfd->storage_obstack,
19853                           actual_name, actual_name_len - die_name_len - 2);
19854                     }
19855                 }
19856               xfree (actual_name);
19857               return name;
19858             }
19859         }
19860     }
19861
19862   return NULL;
19863 }
19864
19865 /* GCC might emit a nameless typedef that has a linkage name.  Determine the
19866    prefix part in such case.  See
19867    http://gcc.gnu.org/bugzilla/show_bug.cgi?id=47510.  */
19868
19869 static const char *
19870 anonymous_struct_prefix (struct die_info *die, struct dwarf2_cu *cu)
19871 {
19872   struct attribute *attr;
19873   const char *base;
19874
19875   if (die->tag != DW_TAG_class_type && die->tag != DW_TAG_interface_type
19876       && die->tag != DW_TAG_structure_type && die->tag != DW_TAG_union_type)
19877     return NULL;
19878
19879   if (dwarf2_string_attr (die, DW_AT_name, cu) != NULL)
19880     return NULL;
19881
19882   attr = dwarf2_attr (die, DW_AT_linkage_name, cu);
19883   if (attr == NULL)
19884     attr = dwarf2_attr (die, DW_AT_MIPS_linkage_name, cu);
19885   if (attr == NULL || DW_STRING (attr) == NULL)
19886     return NULL;
19887
19888   /* dwarf2_name had to be already called.  */
19889   gdb_assert (DW_STRING_IS_CANONICAL (attr));
19890
19891   /* Strip the base name, keep any leading namespaces/classes.  */
19892   base = strrchr (DW_STRING (attr), ':');
19893   if (base == NULL || base == DW_STRING (attr) || base[-1] != ':')
19894     return "";
19895
19896   return (char *) obstack_copy0 (&cu->objfile->per_bfd->storage_obstack,
19897                                  DW_STRING (attr),
19898                                  &base[-1] - DW_STRING (attr));
19899 }
19900
19901 /* Return the name of the namespace/class that DIE is defined within,
19902    or "" if we can't tell.  The caller should not xfree the result.
19903
19904    For example, if we're within the method foo() in the following
19905    code:
19906
19907    namespace N {
19908      class C {
19909        void foo () {
19910        }
19911      };
19912    }
19913
19914    then determine_prefix on foo's die will return "N::C".  */
19915
19916 static const char *
19917 determine_prefix (struct die_info *die, struct dwarf2_cu *cu)
19918 {
19919   struct die_info *parent, *spec_die;
19920   struct dwarf2_cu *spec_cu;
19921   struct type *parent_type;
19922   const char *retval;
19923
19924   if (cu->language != language_cplus
19925       && cu->language != language_fortran && cu->language != language_d
19926       && cu->language != language_rust)
19927     return "";
19928
19929   retval = anonymous_struct_prefix (die, cu);
19930   if (retval)
19931     return retval;
19932
19933   /* We have to be careful in the presence of DW_AT_specification.
19934      For example, with GCC 3.4, given the code
19935
19936      namespace N {
19937        void foo() {
19938          // Definition of N::foo.
19939        }
19940      }
19941
19942      then we'll have a tree of DIEs like this:
19943
19944      1: DW_TAG_compile_unit
19945        2: DW_TAG_namespace        // N
19946          3: DW_TAG_subprogram     // declaration of N::foo
19947        4: DW_TAG_subprogram       // definition of N::foo
19948             DW_AT_specification   // refers to die #3
19949
19950      Thus, when processing die #4, we have to pretend that we're in
19951      the context of its DW_AT_specification, namely the contex of die
19952      #3.  */
19953   spec_cu = cu;
19954   spec_die = die_specification (die, &spec_cu);
19955   if (spec_die == NULL)
19956     parent = die->parent;
19957   else
19958     {
19959       parent = spec_die->parent;
19960       cu = spec_cu;
19961     }
19962
19963   if (parent == NULL)
19964     return "";
19965   else if (parent->building_fullname)
19966     {
19967       const char *name;
19968       const char *parent_name;
19969
19970       /* It has been seen on RealView 2.2 built binaries,
19971          DW_TAG_template_type_param types actually _defined_ as
19972          children of the parent class:
19973
19974          enum E {};
19975          template class <class Enum> Class{};
19976          Class<enum E> class_e;
19977
19978          1: DW_TAG_class_type (Class)
19979            2: DW_TAG_enumeration_type (E)
19980              3: DW_TAG_enumerator (enum1:0)
19981              3: DW_TAG_enumerator (enum2:1)
19982              ...
19983            2: DW_TAG_template_type_param
19984               DW_AT_type  DW_FORM_ref_udata (E)
19985
19986          Besides being broken debug info, it can put GDB into an
19987          infinite loop.  Consider:
19988
19989          When we're building the full name for Class<E>, we'll start
19990          at Class, and go look over its template type parameters,
19991          finding E.  We'll then try to build the full name of E, and
19992          reach here.  We're now trying to build the full name of E,
19993          and look over the parent DIE for containing scope.  In the
19994          broken case, if we followed the parent DIE of E, we'd again
19995          find Class, and once again go look at its template type
19996          arguments, etc., etc.  Simply don't consider such parent die
19997          as source-level parent of this die (it can't be, the language
19998          doesn't allow it), and break the loop here.  */
19999       name = dwarf2_name (die, cu);
20000       parent_name = dwarf2_name (parent, cu);
20001       complaint (&symfile_complaints,
20002                  _("template param type '%s' defined within parent '%s'"),
20003                  name ? name : "<unknown>",
20004                  parent_name ? parent_name : "<unknown>");
20005       return "";
20006     }
20007   else
20008     switch (parent->tag)
20009       {
20010       case DW_TAG_namespace:
20011         parent_type = read_type_die (parent, cu);
20012         /* GCC 4.0 and 4.1 had a bug (PR c++/28460) where they generated bogus
20013            DW_TAG_namespace DIEs with a name of "::" for the global namespace.
20014            Work around this problem here.  */
20015         if (cu->language == language_cplus
20016             && strcmp (TYPE_TAG_NAME (parent_type), "::") == 0)
20017           return "";
20018         /* We give a name to even anonymous namespaces.  */
20019         return TYPE_TAG_NAME (parent_type);
20020       case DW_TAG_class_type:
20021       case DW_TAG_interface_type:
20022       case DW_TAG_structure_type:
20023       case DW_TAG_union_type:
20024       case DW_TAG_module:
20025         parent_type = read_type_die (parent, cu);
20026         if (TYPE_TAG_NAME (parent_type) != NULL)
20027           return TYPE_TAG_NAME (parent_type);
20028         else
20029           /* An anonymous structure is only allowed non-static data
20030              members; no typedefs, no member functions, et cetera.
20031              So it does not need a prefix.  */
20032           return "";
20033       case DW_TAG_compile_unit:
20034       case DW_TAG_partial_unit:
20035         /* gcc-4.5 -gdwarf-4 can drop the enclosing namespace.  Cope.  */
20036         if (cu->language == language_cplus
20037             && !VEC_empty (dwarf2_section_info_def, dwarf2_per_objfile->types)
20038             && die->child != NULL
20039             && (die->tag == DW_TAG_class_type
20040                 || die->tag == DW_TAG_structure_type
20041                 || die->tag == DW_TAG_union_type))
20042           {
20043             char *name = guess_full_die_structure_name (die, cu);
20044             if (name != NULL)
20045               return name;
20046           }
20047         return "";
20048       case DW_TAG_enumeration_type:
20049         parent_type = read_type_die (parent, cu);
20050         if (TYPE_DECLARED_CLASS (parent_type))
20051           {
20052             if (TYPE_TAG_NAME (parent_type) != NULL)
20053               return TYPE_TAG_NAME (parent_type);
20054             return "";
20055           }
20056         /* Fall through.  */
20057       default:
20058         return determine_prefix (parent, cu);
20059       }
20060 }
20061
20062 /* Return a newly-allocated string formed by concatenating PREFIX and SUFFIX
20063    with appropriate separator.  If PREFIX or SUFFIX is NULL or empty, then
20064    simply copy the SUFFIX or PREFIX, respectively.  If OBS is non-null, perform
20065    an obconcat, otherwise allocate storage for the result.  The CU argument is
20066    used to determine the language and hence, the appropriate separator.  */
20067
20068 #define MAX_SEP_LEN 7  /* strlen ("__") + strlen ("_MOD_")  */
20069
20070 static char *
20071 typename_concat (struct obstack *obs, const char *prefix, const char *suffix,
20072                  int physname, struct dwarf2_cu *cu)
20073 {
20074   const char *lead = "";
20075   const char *sep;
20076
20077   if (suffix == NULL || suffix[0] == '\0'
20078       || prefix == NULL || prefix[0] == '\0')
20079     sep = "";
20080   else if (cu->language == language_d)
20081     {
20082       /* For D, the 'main' function could be defined in any module, but it
20083          should never be prefixed.  */
20084       if (strcmp (suffix, "D main") == 0)
20085         {
20086           prefix = "";
20087           sep = "";
20088         }
20089       else
20090         sep = ".";
20091     }
20092   else if (cu->language == language_fortran && physname)
20093     {
20094       /* This is gfortran specific mangling.  Normally DW_AT_linkage_name or
20095          DW_AT_MIPS_linkage_name is preferred and used instead.  */
20096
20097       lead = "__";
20098       sep = "_MOD_";
20099     }
20100   else
20101     sep = "::";
20102
20103   if (prefix == NULL)
20104     prefix = "";
20105   if (suffix == NULL)
20106     suffix = "";
20107
20108   if (obs == NULL)
20109     {
20110       char *retval
20111         = ((char *)
20112            xmalloc (strlen (prefix) + MAX_SEP_LEN + strlen (suffix) + 1));
20113
20114       strcpy (retval, lead);
20115       strcat (retval, prefix);
20116       strcat (retval, sep);
20117       strcat (retval, suffix);
20118       return retval;
20119     }
20120   else
20121     {
20122       /* We have an obstack.  */
20123       return obconcat (obs, lead, prefix, sep, suffix, (char *) NULL);
20124     }
20125 }
20126
20127 /* Return sibling of die, NULL if no sibling.  */
20128
20129 static struct die_info *
20130 sibling_die (struct die_info *die)
20131 {
20132   return die->sibling;
20133 }
20134
20135 /* Get name of a die, return NULL if not found.  */
20136
20137 static const char *
20138 dwarf2_canonicalize_name (const char *name, struct dwarf2_cu *cu,
20139                           struct obstack *obstack)
20140 {
20141   if (name && cu->language == language_cplus)
20142     {
20143       std::string canon_name = cp_canonicalize_string (name);
20144
20145       if (!canon_name.empty ())
20146         {
20147           if (canon_name != name)
20148             name = (const char *) obstack_copy0 (obstack,
20149                                                  canon_name.c_str (),
20150                                                  canon_name.length ());
20151         }
20152     }
20153
20154   return name;
20155 }
20156
20157 /* Get name of a die, return NULL if not found.
20158    Anonymous namespaces are converted to their magic string.  */
20159
20160 static const char *
20161 dwarf2_name (struct die_info *die, struct dwarf2_cu *cu)
20162 {
20163   struct attribute *attr;
20164
20165   attr = dwarf2_attr (die, DW_AT_name, cu);
20166   if ((!attr || !DW_STRING (attr))
20167       && die->tag != DW_TAG_namespace
20168       && die->tag != DW_TAG_class_type
20169       && die->tag != DW_TAG_interface_type
20170       && die->tag != DW_TAG_structure_type
20171       && die->tag != DW_TAG_union_type)
20172     return NULL;
20173
20174   switch (die->tag)
20175     {
20176     case DW_TAG_compile_unit:
20177     case DW_TAG_partial_unit:
20178       /* Compilation units have a DW_AT_name that is a filename, not
20179          a source language identifier.  */
20180     case DW_TAG_enumeration_type:
20181     case DW_TAG_enumerator:
20182       /* These tags always have simple identifiers already; no need
20183          to canonicalize them.  */
20184       return DW_STRING (attr);
20185
20186     case DW_TAG_namespace:
20187       if (attr != NULL && DW_STRING (attr) != NULL)
20188         return DW_STRING (attr);
20189       return CP_ANONYMOUS_NAMESPACE_STR;
20190
20191     case DW_TAG_class_type:
20192     case DW_TAG_interface_type:
20193     case DW_TAG_structure_type:
20194     case DW_TAG_union_type:
20195       /* Some GCC versions emit spurious DW_AT_name attributes for unnamed
20196          structures or unions.  These were of the form "._%d" in GCC 4.1,
20197          or simply "<anonymous struct>" or "<anonymous union>" in GCC 4.3
20198          and GCC 4.4.  We work around this problem by ignoring these.  */
20199       if (attr && DW_STRING (attr)
20200           && (startswith (DW_STRING (attr), "._")
20201               || startswith (DW_STRING (attr), "<anonymous")))
20202         return NULL;
20203
20204       /* GCC might emit a nameless typedef that has a linkage name.  See
20205          http://gcc.gnu.org/bugzilla/show_bug.cgi?id=47510.  */
20206       if (!attr || DW_STRING (attr) == NULL)
20207         {
20208           char *demangled = NULL;
20209
20210           attr = dwarf2_attr (die, DW_AT_linkage_name, cu);
20211           if (attr == NULL)
20212             attr = dwarf2_attr (die, DW_AT_MIPS_linkage_name, cu);
20213
20214           if (attr == NULL || DW_STRING (attr) == NULL)
20215             return NULL;
20216
20217           /* Avoid demangling DW_STRING (attr) the second time on a second
20218              call for the same DIE.  */
20219           if (!DW_STRING_IS_CANONICAL (attr))
20220             demangled = gdb_demangle (DW_STRING (attr), DMGL_TYPES);
20221
20222           if (demangled)
20223             {
20224               const char *base;
20225
20226               /* FIXME: we already did this for the partial symbol... */
20227               DW_STRING (attr)
20228                 = ((const char *)
20229                    obstack_copy0 (&cu->objfile->per_bfd->storage_obstack,
20230                                   demangled, strlen (demangled)));
20231               DW_STRING_IS_CANONICAL (attr) = 1;
20232               xfree (demangled);
20233
20234               /* Strip any leading namespaces/classes, keep only the base name.
20235                  DW_AT_name for named DIEs does not contain the prefixes.  */
20236               base = strrchr (DW_STRING (attr), ':');
20237               if (base && base > DW_STRING (attr) && base[-1] == ':')
20238                 return &base[1];
20239               else
20240                 return DW_STRING (attr);
20241             }
20242         }
20243       break;
20244
20245     default:
20246       break;
20247     }
20248
20249   if (!DW_STRING_IS_CANONICAL (attr))
20250     {
20251       DW_STRING (attr)
20252         = dwarf2_canonicalize_name (DW_STRING (attr), cu,
20253                                     &cu->objfile->per_bfd->storage_obstack);
20254       DW_STRING_IS_CANONICAL (attr) = 1;
20255     }
20256   return DW_STRING (attr);
20257 }
20258
20259 /* Return the die that this die in an extension of, or NULL if there
20260    is none.  *EXT_CU is the CU containing DIE on input, and the CU
20261    containing the return value on output.  */
20262
20263 static struct die_info *
20264 dwarf2_extension (struct die_info *die, struct dwarf2_cu **ext_cu)
20265 {
20266   struct attribute *attr;
20267
20268   attr = dwarf2_attr (die, DW_AT_extension, *ext_cu);
20269   if (attr == NULL)
20270     return NULL;
20271
20272   return follow_die_ref (die, attr, ext_cu);
20273 }
20274
20275 /* Convert a DIE tag into its string name.  */
20276
20277 static const char *
20278 dwarf_tag_name (unsigned tag)
20279 {
20280   const char *name = get_DW_TAG_name (tag);
20281
20282   if (name == NULL)
20283     return "DW_TAG_<unknown>";
20284
20285   return name;
20286 }
20287
20288 /* Convert a DWARF attribute code into its string name.  */
20289
20290 static const char *
20291 dwarf_attr_name (unsigned attr)
20292 {
20293   const char *name;
20294
20295 #ifdef MIPS /* collides with DW_AT_HP_block_index */
20296   if (attr == DW_AT_MIPS_fde)
20297     return "DW_AT_MIPS_fde";
20298 #else
20299   if (attr == DW_AT_HP_block_index)
20300     return "DW_AT_HP_block_index";
20301 #endif
20302
20303   name = get_DW_AT_name (attr);
20304
20305   if (name == NULL)
20306     return "DW_AT_<unknown>";
20307
20308   return name;
20309 }
20310
20311 /* Convert a DWARF value form code into its string name.  */
20312
20313 static const char *
20314 dwarf_form_name (unsigned form)
20315 {
20316   const char *name = get_DW_FORM_name (form);
20317
20318   if (name == NULL)
20319     return "DW_FORM_<unknown>";
20320
20321   return name;
20322 }
20323
20324 static const char *
20325 dwarf_bool_name (unsigned mybool)
20326 {
20327   if (mybool)
20328     return "TRUE";
20329   else
20330     return "FALSE";
20331 }
20332
20333 /* Convert a DWARF type code into its string name.  */
20334
20335 static const char *
20336 dwarf_type_encoding_name (unsigned enc)
20337 {
20338   const char *name = get_DW_ATE_name (enc);
20339
20340   if (name == NULL)
20341     return "DW_ATE_<unknown>";
20342
20343   return name;
20344 }
20345
20346 static void
20347 dump_die_shallow (struct ui_file *f, int indent, struct die_info *die)
20348 {
20349   unsigned int i;
20350
20351   print_spaces (indent, f);
20352   fprintf_unfiltered (f, "Die: %s (abbrev %d, offset 0x%x)\n",
20353                       dwarf_tag_name (die->tag), die->abbrev,
20354                       to_underlying (die->sect_off));
20355
20356   if (die->parent != NULL)
20357     {
20358       print_spaces (indent, f);
20359       fprintf_unfiltered (f, "  parent at offset: 0x%x\n",
20360                           to_underlying (die->parent->sect_off));
20361     }
20362
20363   print_spaces (indent, f);
20364   fprintf_unfiltered (f, "  has children: %s\n",
20365            dwarf_bool_name (die->child != NULL));
20366
20367   print_spaces (indent, f);
20368   fprintf_unfiltered (f, "  attributes:\n");
20369
20370   for (i = 0; i < die->num_attrs; ++i)
20371     {
20372       print_spaces (indent, f);
20373       fprintf_unfiltered (f, "    %s (%s) ",
20374                dwarf_attr_name (die->attrs[i].name),
20375                dwarf_form_name (die->attrs[i].form));
20376
20377       switch (die->attrs[i].form)
20378         {
20379         case DW_FORM_addr:
20380         case DW_FORM_GNU_addr_index:
20381           fprintf_unfiltered (f, "address: ");
20382           fputs_filtered (hex_string (DW_ADDR (&die->attrs[i])), f);
20383           break;
20384         case DW_FORM_block2:
20385         case DW_FORM_block4:
20386         case DW_FORM_block:
20387         case DW_FORM_block1:
20388           fprintf_unfiltered (f, "block: size %s",
20389                               pulongest (DW_BLOCK (&die->attrs[i])->size));
20390           break;
20391         case DW_FORM_exprloc:
20392           fprintf_unfiltered (f, "expression: size %s",
20393                               pulongest (DW_BLOCK (&die->attrs[i])->size));
20394           break;
20395         case DW_FORM_data16:
20396           fprintf_unfiltered (f, "constant of 16 bytes");
20397           break;
20398         case DW_FORM_ref_addr:
20399           fprintf_unfiltered (f, "ref address: ");
20400           fputs_filtered (hex_string (DW_UNSND (&die->attrs[i])), f);
20401           break;
20402         case DW_FORM_GNU_ref_alt:
20403           fprintf_unfiltered (f, "alt ref address: ");
20404           fputs_filtered (hex_string (DW_UNSND (&die->attrs[i])), f);
20405           break;
20406         case DW_FORM_ref1:
20407         case DW_FORM_ref2:
20408         case DW_FORM_ref4:
20409         case DW_FORM_ref8:
20410         case DW_FORM_ref_udata:
20411           fprintf_unfiltered (f, "constant ref: 0x%lx (adjusted)",
20412                               (long) (DW_UNSND (&die->attrs[i])));
20413           break;
20414         case DW_FORM_data1:
20415         case DW_FORM_data2:
20416         case DW_FORM_data4:
20417         case DW_FORM_data8:
20418         case DW_FORM_udata:
20419         case DW_FORM_sdata:
20420           fprintf_unfiltered (f, "constant: %s",
20421                               pulongest (DW_UNSND (&die->attrs[i])));
20422           break;
20423         case DW_FORM_sec_offset:
20424           fprintf_unfiltered (f, "section offset: %s",
20425                               pulongest (DW_UNSND (&die->attrs[i])));
20426           break;
20427         case DW_FORM_ref_sig8:
20428           fprintf_unfiltered (f, "signature: %s",
20429                               hex_string (DW_SIGNATURE (&die->attrs[i])));
20430           break;
20431         case DW_FORM_string:
20432         case DW_FORM_strp:
20433         case DW_FORM_line_strp:
20434         case DW_FORM_GNU_str_index:
20435         case DW_FORM_GNU_strp_alt:
20436           fprintf_unfiltered (f, "string: \"%s\" (%s canonicalized)",
20437                    DW_STRING (&die->attrs[i])
20438                    ? DW_STRING (&die->attrs[i]) : "",
20439                    DW_STRING_IS_CANONICAL (&die->attrs[i]) ? "is" : "not");
20440           break;
20441         case DW_FORM_flag:
20442           if (DW_UNSND (&die->attrs[i]))
20443             fprintf_unfiltered (f, "flag: TRUE");
20444           else
20445             fprintf_unfiltered (f, "flag: FALSE");
20446           break;
20447         case DW_FORM_flag_present:
20448           fprintf_unfiltered (f, "flag: TRUE");
20449           break;
20450         case DW_FORM_indirect:
20451           /* The reader will have reduced the indirect form to
20452              the "base form" so this form should not occur.  */
20453           fprintf_unfiltered (f, 
20454                               "unexpected attribute form: DW_FORM_indirect");
20455           break;
20456         default:
20457           fprintf_unfiltered (f, "unsupported attribute form: %d.",
20458                    die->attrs[i].form);
20459           break;
20460         }
20461       fprintf_unfiltered (f, "\n");
20462     }
20463 }
20464
20465 static void
20466 dump_die_for_error (struct die_info *die)
20467 {
20468   dump_die_shallow (gdb_stderr, 0, die);
20469 }
20470
20471 static void
20472 dump_die_1 (struct ui_file *f, int level, int max_level, struct die_info *die)
20473 {
20474   int indent = level * 4;
20475
20476   gdb_assert (die != NULL);
20477
20478   if (level >= max_level)
20479     return;
20480
20481   dump_die_shallow (f, indent, die);
20482
20483   if (die->child != NULL)
20484     {
20485       print_spaces (indent, f);
20486       fprintf_unfiltered (f, "  Children:");
20487       if (level + 1 < max_level)
20488         {
20489           fprintf_unfiltered (f, "\n");
20490           dump_die_1 (f, level + 1, max_level, die->child);
20491         }
20492       else
20493         {
20494           fprintf_unfiltered (f,
20495                               " [not printed, max nesting level reached]\n");
20496         }
20497     }
20498
20499   if (die->sibling != NULL && level > 0)
20500     {
20501       dump_die_1 (f, level, max_level, die->sibling);
20502     }
20503 }
20504
20505 /* This is called from the pdie macro in gdbinit.in.
20506    It's not static so gcc will keep a copy callable from gdb.  */
20507
20508 void
20509 dump_die (struct die_info *die, int max_level)
20510 {
20511   dump_die_1 (gdb_stdlog, 0, max_level, die);
20512 }
20513
20514 static void
20515 store_in_ref_table (struct die_info *die, struct dwarf2_cu *cu)
20516 {
20517   void **slot;
20518
20519   slot = htab_find_slot_with_hash (cu->die_hash, die,
20520                                    to_underlying (die->sect_off),
20521                                    INSERT);
20522
20523   *slot = die;
20524 }
20525
20526 /* Return DIE offset of ATTR.  Return 0 with complaint if ATTR is not of the
20527    required kind.  */
20528
20529 static sect_offset
20530 dwarf2_get_ref_die_offset (const struct attribute *attr)
20531 {
20532   if (attr_form_is_ref (attr))
20533     return (sect_offset) DW_UNSND (attr);
20534
20535   complaint (&symfile_complaints,
20536              _("unsupported die ref attribute form: '%s'"),
20537              dwarf_form_name (attr->form));
20538   return {};
20539 }
20540
20541 /* Return the constant value held by ATTR.  Return DEFAULT_VALUE if
20542  * the value held by the attribute is not constant.  */
20543
20544 static LONGEST
20545 dwarf2_get_attr_constant_value (const struct attribute *attr, int default_value)
20546 {
20547   if (attr->form == DW_FORM_sdata)
20548     return DW_SND (attr);
20549   else if (attr->form == DW_FORM_udata
20550            || attr->form == DW_FORM_data1
20551            || attr->form == DW_FORM_data2
20552            || attr->form == DW_FORM_data4
20553            || attr->form == DW_FORM_data8)
20554     return DW_UNSND (attr);
20555   else
20556     {
20557       /* For DW_FORM_data16 see attr_form_is_constant.  */
20558       complaint (&symfile_complaints,
20559                  _("Attribute value is not a constant (%s)"),
20560                  dwarf_form_name (attr->form));
20561       return default_value;
20562     }
20563 }
20564
20565 /* Follow reference or signature attribute ATTR of SRC_DIE.
20566    On entry *REF_CU is the CU of SRC_DIE.
20567    On exit *REF_CU is the CU of the result.  */
20568
20569 static struct die_info *
20570 follow_die_ref_or_sig (struct die_info *src_die, const struct attribute *attr,
20571                        struct dwarf2_cu **ref_cu)
20572 {
20573   struct die_info *die;
20574
20575   if (attr_form_is_ref (attr))
20576     die = follow_die_ref (src_die, attr, ref_cu);
20577   else if (attr->form == DW_FORM_ref_sig8)
20578     die = follow_die_sig (src_die, attr, ref_cu);
20579   else
20580     {
20581       dump_die_for_error (src_die);
20582       error (_("Dwarf Error: Expected reference attribute [in module %s]"),
20583              objfile_name ((*ref_cu)->objfile));
20584     }
20585
20586   return die;
20587 }
20588
20589 /* Follow reference OFFSET.
20590    On entry *REF_CU is the CU of the source die referencing OFFSET.
20591    On exit *REF_CU is the CU of the result.
20592    Returns NULL if OFFSET is invalid.  */
20593
20594 static struct die_info *
20595 follow_die_offset (sect_offset sect_off, int offset_in_dwz,
20596                    struct dwarf2_cu **ref_cu)
20597 {
20598   struct die_info temp_die;
20599   struct dwarf2_cu *target_cu, *cu = *ref_cu;
20600
20601   gdb_assert (cu->per_cu != NULL);
20602
20603   target_cu = cu;
20604
20605   if (cu->per_cu->is_debug_types)
20606     {
20607       /* .debug_types CUs cannot reference anything outside their CU.
20608          If they need to, they have to reference a signatured type via
20609          DW_FORM_ref_sig8.  */
20610       if (!offset_in_cu_p (&cu->header, sect_off))
20611         return NULL;
20612     }
20613   else if (offset_in_dwz != cu->per_cu->is_dwz
20614            || !offset_in_cu_p (&cu->header, sect_off))
20615     {
20616       struct dwarf2_per_cu_data *per_cu;
20617
20618       per_cu = dwarf2_find_containing_comp_unit (sect_off, offset_in_dwz,
20619                                                  cu->objfile);
20620
20621       /* If necessary, add it to the queue and load its DIEs.  */
20622       if (maybe_queue_comp_unit (cu, per_cu, cu->language))
20623         load_full_comp_unit (per_cu, cu->language);
20624
20625       target_cu = per_cu->cu;
20626     }
20627   else if (cu->dies == NULL)
20628     {
20629       /* We're loading full DIEs during partial symbol reading.  */
20630       gdb_assert (dwarf2_per_objfile->reading_partial_symbols);
20631       load_full_comp_unit (cu->per_cu, language_minimal);
20632     }
20633
20634   *ref_cu = target_cu;
20635   temp_die.sect_off = sect_off;
20636   return (struct die_info *) htab_find_with_hash (target_cu->die_hash,
20637                                                   &temp_die,
20638                                                   to_underlying (sect_off));
20639 }
20640
20641 /* Follow reference attribute ATTR of SRC_DIE.
20642    On entry *REF_CU is the CU of SRC_DIE.
20643    On exit *REF_CU is the CU of the result.  */
20644
20645 static struct die_info *
20646 follow_die_ref (struct die_info *src_die, const struct attribute *attr,
20647                 struct dwarf2_cu **ref_cu)
20648 {
20649   sect_offset sect_off = dwarf2_get_ref_die_offset (attr);
20650   struct dwarf2_cu *cu = *ref_cu;
20651   struct die_info *die;
20652
20653   die = follow_die_offset (sect_off,
20654                            (attr->form == DW_FORM_GNU_ref_alt
20655                             || cu->per_cu->is_dwz),
20656                            ref_cu);
20657   if (!die)
20658     error (_("Dwarf Error: Cannot find DIE at 0x%x referenced from DIE "
20659            "at 0x%x [in module %s]"),
20660            to_underlying (sect_off), to_underlying (src_die->sect_off),
20661            objfile_name (cu->objfile));
20662
20663   return die;
20664 }
20665
20666 /* Return DWARF block referenced by DW_AT_location of DIE at SECT_OFF at PER_CU.
20667    Returned value is intended for DW_OP_call*.  Returned
20668    dwarf2_locexpr_baton->data has lifetime of PER_CU->OBJFILE.  */
20669
20670 struct dwarf2_locexpr_baton
20671 dwarf2_fetch_die_loc_sect_off (sect_offset sect_off,
20672                                struct dwarf2_per_cu_data *per_cu,
20673                                CORE_ADDR (*get_frame_pc) (void *baton),
20674                                void *baton)
20675 {
20676   struct dwarf2_cu *cu;
20677   struct die_info *die;
20678   struct attribute *attr;
20679   struct dwarf2_locexpr_baton retval;
20680
20681   dw2_setup (per_cu->objfile);
20682
20683   if (per_cu->cu == NULL)
20684     load_cu (per_cu);
20685   cu = per_cu->cu;
20686   if (cu == NULL)
20687     {
20688       /* We shouldn't get here for a dummy CU, but don't crash on the user.
20689          Instead just throw an error, not much else we can do.  */
20690       error (_("Dwarf Error: Dummy CU at 0x%x referenced in module %s"),
20691              to_underlying (sect_off), objfile_name (per_cu->objfile));
20692     }
20693
20694   die = follow_die_offset (sect_off, per_cu->is_dwz, &cu);
20695   if (!die)
20696     error (_("Dwarf Error: Cannot find DIE at 0x%x referenced in module %s"),
20697            to_underlying (sect_off), objfile_name (per_cu->objfile));
20698
20699   attr = dwarf2_attr (die, DW_AT_location, cu);
20700   if (!attr)
20701     {
20702       /* DWARF: "If there is no such attribute, then there is no effect.".
20703          DATA is ignored if SIZE is 0.  */
20704
20705       retval.data = NULL;
20706       retval.size = 0;
20707     }
20708   else if (attr_form_is_section_offset (attr))
20709     {
20710       struct dwarf2_loclist_baton loclist_baton;
20711       CORE_ADDR pc = (*get_frame_pc) (baton);
20712       size_t size;
20713
20714       fill_in_loclist_baton (cu, &loclist_baton, attr);
20715
20716       retval.data = dwarf2_find_location_expression (&loclist_baton,
20717                                                      &size, pc);
20718       retval.size = size;
20719     }
20720   else
20721     {
20722       if (!attr_form_is_block (attr))
20723         error (_("Dwarf Error: DIE at 0x%x referenced in module %s "
20724                  "is neither DW_FORM_block* nor DW_FORM_exprloc"),
20725                to_underlying (sect_off), objfile_name (per_cu->objfile));
20726
20727       retval.data = DW_BLOCK (attr)->data;
20728       retval.size = DW_BLOCK (attr)->size;
20729     }
20730   retval.per_cu = cu->per_cu;
20731
20732   age_cached_comp_units ();
20733
20734   return retval;
20735 }
20736
20737 /* Like dwarf2_fetch_die_loc_sect_off, but take a CU
20738    offset.  */
20739
20740 struct dwarf2_locexpr_baton
20741 dwarf2_fetch_die_loc_cu_off (cu_offset offset_in_cu,
20742                              struct dwarf2_per_cu_data *per_cu,
20743                              CORE_ADDR (*get_frame_pc) (void *baton),
20744                              void *baton)
20745 {
20746   sect_offset sect_off = per_cu->sect_off + to_underlying (offset_in_cu);
20747
20748   return dwarf2_fetch_die_loc_sect_off (sect_off, per_cu, get_frame_pc, baton);
20749 }
20750
20751 /* Write a constant of a given type as target-ordered bytes into
20752    OBSTACK.  */
20753
20754 static const gdb_byte *
20755 write_constant_as_bytes (struct obstack *obstack,
20756                          enum bfd_endian byte_order,
20757                          struct type *type,
20758                          ULONGEST value,
20759                          LONGEST *len)
20760 {
20761   gdb_byte *result;
20762
20763   *len = TYPE_LENGTH (type);
20764   result = (gdb_byte *) obstack_alloc (obstack, *len);
20765   store_unsigned_integer (result, *len, byte_order, value);
20766
20767   return result;
20768 }
20769
20770 /* If the DIE at OFFSET in PER_CU has a DW_AT_const_value, return a
20771    pointer to the constant bytes and set LEN to the length of the
20772    data.  If memory is needed, allocate it on OBSTACK.  If the DIE
20773    does not have a DW_AT_const_value, return NULL.  */
20774
20775 const gdb_byte *
20776 dwarf2_fetch_constant_bytes (sect_offset sect_off,
20777                              struct dwarf2_per_cu_data *per_cu,
20778                              struct obstack *obstack,
20779                              LONGEST *len)
20780 {
20781   struct dwarf2_cu *cu;
20782   struct die_info *die;
20783   struct attribute *attr;
20784   const gdb_byte *result = NULL;
20785   struct type *type;
20786   LONGEST value;
20787   enum bfd_endian byte_order;
20788
20789   dw2_setup (per_cu->objfile);
20790
20791   if (per_cu->cu == NULL)
20792     load_cu (per_cu);
20793   cu = per_cu->cu;
20794   if (cu == NULL)
20795     {
20796       /* We shouldn't get here for a dummy CU, but don't crash on the user.
20797          Instead just throw an error, not much else we can do.  */
20798       error (_("Dwarf Error: Dummy CU at 0x%x referenced in module %s"),
20799              to_underlying (sect_off), objfile_name (per_cu->objfile));
20800     }
20801
20802   die = follow_die_offset (sect_off, per_cu->is_dwz, &cu);
20803   if (!die)
20804     error (_("Dwarf Error: Cannot find DIE at 0x%x referenced in module %s"),
20805            to_underlying (sect_off), objfile_name (per_cu->objfile));
20806
20807
20808   attr = dwarf2_attr (die, DW_AT_const_value, cu);
20809   if (attr == NULL)
20810     return NULL;
20811
20812   byte_order = (bfd_big_endian (per_cu->objfile->obfd)
20813                 ? BFD_ENDIAN_BIG : BFD_ENDIAN_LITTLE);
20814
20815   switch (attr->form)
20816     {
20817     case DW_FORM_addr:
20818     case DW_FORM_GNU_addr_index:
20819       {
20820         gdb_byte *tem;
20821
20822         *len = cu->header.addr_size;
20823         tem = (gdb_byte *) obstack_alloc (obstack, *len);
20824         store_unsigned_integer (tem, *len, byte_order, DW_ADDR (attr));
20825         result = tem;
20826       }
20827       break;
20828     case DW_FORM_string:
20829     case DW_FORM_strp:
20830     case DW_FORM_GNU_str_index:
20831     case DW_FORM_GNU_strp_alt:
20832       /* DW_STRING is already allocated on the objfile obstack, point
20833          directly to it.  */
20834       result = (const gdb_byte *) DW_STRING (attr);
20835       *len = strlen (DW_STRING (attr));
20836       break;
20837     case DW_FORM_block1:
20838     case DW_FORM_block2:
20839     case DW_FORM_block4:
20840     case DW_FORM_block:
20841     case DW_FORM_exprloc:
20842     case DW_FORM_data16:
20843       result = DW_BLOCK (attr)->data;
20844       *len = DW_BLOCK (attr)->size;
20845       break;
20846
20847       /* The DW_AT_const_value attributes are supposed to carry the
20848          symbol's value "represented as it would be on the target
20849          architecture."  By the time we get here, it's already been
20850          converted to host endianness, so we just need to sign- or
20851          zero-extend it as appropriate.  */
20852     case DW_FORM_data1:
20853       type = die_type (die, cu);
20854       result = dwarf2_const_value_data (attr, obstack, cu, &value, 8);
20855       if (result == NULL)
20856         result = write_constant_as_bytes (obstack, byte_order,
20857                                           type, value, len);
20858       break;
20859     case DW_FORM_data2:
20860       type = die_type (die, cu);
20861       result = dwarf2_const_value_data (attr, obstack, cu, &value, 16);
20862       if (result == NULL)
20863         result = write_constant_as_bytes (obstack, byte_order,
20864                                           type, value, len);
20865       break;
20866     case DW_FORM_data4:
20867       type = die_type (die, cu);
20868       result = dwarf2_const_value_data (attr, obstack, cu, &value, 32);
20869       if (result == NULL)
20870         result = write_constant_as_bytes (obstack, byte_order,
20871                                           type, value, len);
20872       break;
20873     case DW_FORM_data8:
20874       type = die_type (die, cu);
20875       result = dwarf2_const_value_data (attr, obstack, cu, &value, 64);
20876       if (result == NULL)
20877         result = write_constant_as_bytes (obstack, byte_order,
20878                                           type, value, len);
20879       break;
20880
20881     case DW_FORM_sdata:
20882       type = die_type (die, cu);
20883       result = write_constant_as_bytes (obstack, byte_order,
20884                                         type, DW_SND (attr), len);
20885       break;
20886
20887     case DW_FORM_udata:
20888       type = die_type (die, cu);
20889       result = write_constant_as_bytes (obstack, byte_order,
20890                                         type, DW_UNSND (attr), len);
20891       break;
20892
20893     default:
20894       complaint (&symfile_complaints,
20895                  _("unsupported const value attribute form: '%s'"),
20896                  dwarf_form_name (attr->form));
20897       break;
20898     }
20899
20900   return result;
20901 }
20902
20903 /* Return the type of the die at OFFSET in PER_CU.  Return NULL if no
20904    valid type for this die is found.  */
20905
20906 struct type *
20907 dwarf2_fetch_die_type_sect_off (sect_offset sect_off,
20908                                 struct dwarf2_per_cu_data *per_cu)
20909 {
20910   struct dwarf2_cu *cu;
20911   struct die_info *die;
20912
20913   dw2_setup (per_cu->objfile);
20914
20915   if (per_cu->cu == NULL)
20916     load_cu (per_cu);
20917   cu = per_cu->cu;
20918   if (!cu)
20919     return NULL;
20920
20921   die = follow_die_offset (sect_off, per_cu->is_dwz, &cu);
20922   if (!die)
20923     return NULL;
20924
20925   return die_type (die, cu);
20926 }
20927
20928 /* Return the type of the DIE at DIE_OFFSET in the CU named by
20929    PER_CU.  */
20930
20931 struct type *
20932 dwarf2_get_die_type (cu_offset die_offset,
20933                      struct dwarf2_per_cu_data *per_cu)
20934 {
20935   dw2_setup (per_cu->objfile);
20936
20937   sect_offset die_offset_sect = per_cu->sect_off + to_underlying (die_offset);
20938   return get_die_type_at_offset (die_offset_sect, per_cu);
20939 }
20940
20941 /* Follow type unit SIG_TYPE referenced by SRC_DIE.
20942    On entry *REF_CU is the CU of SRC_DIE.
20943    On exit *REF_CU is the CU of the result.
20944    Returns NULL if the referenced DIE isn't found.  */
20945
20946 static struct die_info *
20947 follow_die_sig_1 (struct die_info *src_die, struct signatured_type *sig_type,
20948                   struct dwarf2_cu **ref_cu)
20949 {
20950   struct die_info temp_die;
20951   struct dwarf2_cu *sig_cu;
20952   struct die_info *die;
20953
20954   /* While it might be nice to assert sig_type->type == NULL here,
20955      we can get here for DW_AT_imported_declaration where we need
20956      the DIE not the type.  */
20957
20958   /* If necessary, add it to the queue and load its DIEs.  */
20959
20960   if (maybe_queue_comp_unit (*ref_cu, &sig_type->per_cu, language_minimal))
20961     read_signatured_type (sig_type);
20962
20963   sig_cu = sig_type->per_cu.cu;
20964   gdb_assert (sig_cu != NULL);
20965   gdb_assert (to_underlying (sig_type->type_offset_in_section) != 0);
20966   temp_die.sect_off = sig_type->type_offset_in_section;
20967   die = (struct die_info *) htab_find_with_hash (sig_cu->die_hash, &temp_die,
20968                                                  to_underlying (temp_die.sect_off));
20969   if (die)
20970     {
20971       /* For .gdb_index version 7 keep track of included TUs.
20972          http://sourceware.org/bugzilla/show_bug.cgi?id=15021.  */
20973       if (dwarf2_per_objfile->index_table != NULL
20974           && dwarf2_per_objfile->index_table->version <= 7)
20975         {
20976           VEC_safe_push (dwarf2_per_cu_ptr,
20977                          (*ref_cu)->per_cu->imported_symtabs,
20978                          sig_cu->per_cu);
20979         }
20980
20981       *ref_cu = sig_cu;
20982       return die;
20983     }
20984
20985   return NULL;
20986 }
20987
20988 /* Follow signatured type referenced by ATTR in SRC_DIE.
20989    On entry *REF_CU is the CU of SRC_DIE.
20990    On exit *REF_CU is the CU of the result.
20991    The result is the DIE of the type.
20992    If the referenced type cannot be found an error is thrown.  */
20993
20994 static struct die_info *
20995 follow_die_sig (struct die_info *src_die, const struct attribute *attr,
20996                 struct dwarf2_cu **ref_cu)
20997 {
20998   ULONGEST signature = DW_SIGNATURE (attr);
20999   struct signatured_type *sig_type;
21000   struct die_info *die;
21001
21002   gdb_assert (attr->form == DW_FORM_ref_sig8);
21003
21004   sig_type = lookup_signatured_type (*ref_cu, signature);
21005   /* sig_type will be NULL if the signatured type is missing from
21006      the debug info.  */
21007   if (sig_type == NULL)
21008     {
21009       error (_("Dwarf Error: Cannot find signatured DIE %s referenced"
21010                " from DIE at 0x%x [in module %s]"),
21011              hex_string (signature), to_underlying (src_die->sect_off),
21012              objfile_name ((*ref_cu)->objfile));
21013     }
21014
21015   die = follow_die_sig_1 (src_die, sig_type, ref_cu);
21016   if (die == NULL)
21017     {
21018       dump_die_for_error (src_die);
21019       error (_("Dwarf Error: Problem reading signatured DIE %s referenced"
21020                " from DIE at 0x%x [in module %s]"),
21021              hex_string (signature), to_underlying (src_die->sect_off),
21022              objfile_name ((*ref_cu)->objfile));
21023     }
21024
21025   return die;
21026 }
21027
21028 /* Get the type specified by SIGNATURE referenced in DIE/CU,
21029    reading in and processing the type unit if necessary.  */
21030
21031 static struct type *
21032 get_signatured_type (struct die_info *die, ULONGEST signature,
21033                      struct dwarf2_cu *cu)
21034 {
21035   struct signatured_type *sig_type;
21036   struct dwarf2_cu *type_cu;
21037   struct die_info *type_die;
21038   struct type *type;
21039
21040   sig_type = lookup_signatured_type (cu, signature);
21041   /* sig_type will be NULL if the signatured type is missing from
21042      the debug info.  */
21043   if (sig_type == NULL)
21044     {
21045       complaint (&symfile_complaints,
21046                  _("Dwarf Error: Cannot find signatured DIE %s referenced"
21047                    " from DIE at 0x%x [in module %s]"),
21048                  hex_string (signature), to_underlying (die->sect_off),
21049                  objfile_name (dwarf2_per_objfile->objfile));
21050       return build_error_marker_type (cu, die);
21051     }
21052
21053   /* If we already know the type we're done.  */
21054   if (sig_type->type != NULL)
21055     return sig_type->type;
21056
21057   type_cu = cu;
21058   type_die = follow_die_sig_1 (die, sig_type, &type_cu);
21059   if (type_die != NULL)
21060     {
21061       /* N.B. We need to call get_die_type to ensure only one type for this DIE
21062          is created.  This is important, for example, because for c++ classes
21063          we need TYPE_NAME set which is only done by new_symbol.  Blech.  */
21064       type = read_type_die (type_die, type_cu);
21065       if (type == NULL)
21066         {
21067           complaint (&symfile_complaints,
21068                      _("Dwarf Error: Cannot build signatured type %s"
21069                        " referenced from DIE at 0x%x [in module %s]"),
21070                      hex_string (signature), to_underlying (die->sect_off),
21071                      objfile_name (dwarf2_per_objfile->objfile));
21072           type = build_error_marker_type (cu, die);
21073         }
21074     }
21075   else
21076     {
21077       complaint (&symfile_complaints,
21078                  _("Dwarf Error: Problem reading signatured DIE %s referenced"
21079                    " from DIE at 0x%x [in module %s]"),
21080                  hex_string (signature), to_underlying (die->sect_off),
21081                  objfile_name (dwarf2_per_objfile->objfile));
21082       type = build_error_marker_type (cu, die);
21083     }
21084   sig_type->type = type;
21085
21086   return type;
21087 }
21088
21089 /* Get the type specified by the DW_AT_signature ATTR in DIE/CU,
21090    reading in and processing the type unit if necessary.  */
21091
21092 static struct type *
21093 get_DW_AT_signature_type (struct die_info *die, const struct attribute *attr,
21094                           struct dwarf2_cu *cu) /* ARI: editCase function */
21095 {
21096   /* Yes, DW_AT_signature can use a non-ref_sig8 reference.  */
21097   if (attr_form_is_ref (attr))
21098     {
21099       struct dwarf2_cu *type_cu = cu;
21100       struct die_info *type_die = follow_die_ref (die, attr, &type_cu);
21101
21102       return read_type_die (type_die, type_cu);
21103     }
21104   else if (attr->form == DW_FORM_ref_sig8)
21105     {
21106       return get_signatured_type (die, DW_SIGNATURE (attr), cu);
21107     }
21108   else
21109     {
21110       complaint (&symfile_complaints,
21111                  _("Dwarf Error: DW_AT_signature has bad form %s in DIE"
21112                    " at 0x%x [in module %s]"),
21113                  dwarf_form_name (attr->form), to_underlying (die->sect_off),
21114                  objfile_name (dwarf2_per_objfile->objfile));
21115       return build_error_marker_type (cu, die);
21116     }
21117 }
21118
21119 /* Load the DIEs associated with type unit PER_CU into memory.  */
21120
21121 static void
21122 load_full_type_unit (struct dwarf2_per_cu_data *per_cu)
21123 {
21124   struct signatured_type *sig_type;
21125
21126   /* Caller is responsible for ensuring type_unit_groups don't get here.  */
21127   gdb_assert (! IS_TYPE_UNIT_GROUP (per_cu));
21128
21129   /* We have the per_cu, but we need the signatured_type.
21130      Fortunately this is an easy translation.  */
21131   gdb_assert (per_cu->is_debug_types);
21132   sig_type = (struct signatured_type *) per_cu;
21133
21134   gdb_assert (per_cu->cu == NULL);
21135
21136   read_signatured_type (sig_type);
21137
21138   gdb_assert (per_cu->cu != NULL);
21139 }
21140
21141 /* die_reader_func for read_signatured_type.
21142    This is identical to load_full_comp_unit_reader,
21143    but is kept separate for now.  */
21144
21145 static void
21146 read_signatured_type_reader (const struct die_reader_specs *reader,
21147                              const gdb_byte *info_ptr,
21148                              struct die_info *comp_unit_die,
21149                              int has_children,
21150                              void *data)
21151 {
21152   struct dwarf2_cu *cu = reader->cu;
21153
21154   gdb_assert (cu->die_hash == NULL);
21155   cu->die_hash =
21156     htab_create_alloc_ex (cu->header.length / 12,
21157                           die_hash,
21158                           die_eq,
21159                           NULL,
21160                           &cu->comp_unit_obstack,
21161                           hashtab_obstack_allocate,
21162                           dummy_obstack_deallocate);
21163
21164   if (has_children)
21165     comp_unit_die->child = read_die_and_siblings (reader, info_ptr,
21166                                                   &info_ptr, comp_unit_die);
21167   cu->dies = comp_unit_die;
21168   /* comp_unit_die is not stored in die_hash, no need.  */
21169
21170   /* We try not to read any attributes in this function, because not
21171      all CUs needed for references have been loaded yet, and symbol
21172      table processing isn't initialized.  But we have to set the CU language,
21173      or we won't be able to build types correctly.
21174      Similarly, if we do not read the producer, we can not apply
21175      producer-specific interpretation.  */
21176   prepare_one_comp_unit (cu, cu->dies, language_minimal);
21177 }
21178
21179 /* Read in a signatured type and build its CU and DIEs.
21180    If the type is a stub for the real type in a DWO file,
21181    read in the real type from the DWO file as well.  */
21182
21183 static void
21184 read_signatured_type (struct signatured_type *sig_type)
21185 {
21186   struct dwarf2_per_cu_data *per_cu = &sig_type->per_cu;
21187
21188   gdb_assert (per_cu->is_debug_types);
21189   gdb_assert (per_cu->cu == NULL);
21190
21191   init_cutu_and_read_dies (per_cu, NULL, 0, 1,
21192                            read_signatured_type_reader, NULL);
21193   sig_type->per_cu.tu_read = 1;
21194 }
21195
21196 /* Decode simple location descriptions.
21197    Given a pointer to a dwarf block that defines a location, compute
21198    the location and return the value.
21199
21200    NOTE drow/2003-11-18: This function is called in two situations
21201    now: for the address of static or global variables (partial symbols
21202    only) and for offsets into structures which are expected to be
21203    (more or less) constant.  The partial symbol case should go away,
21204    and only the constant case should remain.  That will let this
21205    function complain more accurately.  A few special modes are allowed
21206    without complaint for global variables (for instance, global
21207    register values and thread-local values).
21208
21209    A location description containing no operations indicates that the
21210    object is optimized out.  The return value is 0 for that case.
21211    FIXME drow/2003-11-16: No callers check for this case any more; soon all
21212    callers will only want a very basic result and this can become a
21213    complaint.
21214
21215    Note that stack[0] is unused except as a default error return.  */
21216
21217 static CORE_ADDR
21218 decode_locdesc (struct dwarf_block *blk, struct dwarf2_cu *cu)
21219 {
21220   struct objfile *objfile = cu->objfile;
21221   size_t i;
21222   size_t size = blk->size;
21223   const gdb_byte *data = blk->data;
21224   CORE_ADDR stack[64];
21225   int stacki;
21226   unsigned int bytes_read, unsnd;
21227   gdb_byte op;
21228
21229   i = 0;
21230   stacki = 0;
21231   stack[stacki] = 0;
21232   stack[++stacki] = 0;
21233
21234   while (i < size)
21235     {
21236       op = data[i++];
21237       switch (op)
21238         {
21239         case DW_OP_lit0:
21240         case DW_OP_lit1:
21241         case DW_OP_lit2:
21242         case DW_OP_lit3:
21243         case DW_OP_lit4:
21244         case DW_OP_lit5:
21245         case DW_OP_lit6:
21246         case DW_OP_lit7:
21247         case DW_OP_lit8:
21248         case DW_OP_lit9:
21249         case DW_OP_lit10:
21250         case DW_OP_lit11:
21251         case DW_OP_lit12:
21252         case DW_OP_lit13:
21253         case DW_OP_lit14:
21254         case DW_OP_lit15:
21255         case DW_OP_lit16:
21256         case DW_OP_lit17:
21257         case DW_OP_lit18:
21258         case DW_OP_lit19:
21259         case DW_OP_lit20:
21260         case DW_OP_lit21:
21261         case DW_OP_lit22:
21262         case DW_OP_lit23:
21263         case DW_OP_lit24:
21264         case DW_OP_lit25:
21265         case DW_OP_lit26:
21266         case DW_OP_lit27:
21267         case DW_OP_lit28:
21268         case DW_OP_lit29:
21269         case DW_OP_lit30:
21270         case DW_OP_lit31:
21271           stack[++stacki] = op - DW_OP_lit0;
21272           break;
21273
21274         case DW_OP_reg0:
21275         case DW_OP_reg1:
21276         case DW_OP_reg2:
21277         case DW_OP_reg3:
21278         case DW_OP_reg4:
21279         case DW_OP_reg5:
21280         case DW_OP_reg6:
21281         case DW_OP_reg7:
21282         case DW_OP_reg8:
21283         case DW_OP_reg9:
21284         case DW_OP_reg10:
21285         case DW_OP_reg11:
21286         case DW_OP_reg12:
21287         case DW_OP_reg13:
21288         case DW_OP_reg14:
21289         case DW_OP_reg15:
21290         case DW_OP_reg16:
21291         case DW_OP_reg17:
21292         case DW_OP_reg18:
21293         case DW_OP_reg19:
21294         case DW_OP_reg20:
21295         case DW_OP_reg21:
21296         case DW_OP_reg22:
21297         case DW_OP_reg23:
21298         case DW_OP_reg24:
21299         case DW_OP_reg25:
21300         case DW_OP_reg26:
21301         case DW_OP_reg27:
21302         case DW_OP_reg28:
21303         case DW_OP_reg29:
21304         case DW_OP_reg30:
21305         case DW_OP_reg31:
21306           stack[++stacki] = op - DW_OP_reg0;
21307           if (i < size)
21308             dwarf2_complex_location_expr_complaint ();
21309           break;
21310
21311         case DW_OP_regx:
21312           unsnd = read_unsigned_leb128 (NULL, (data + i), &bytes_read);
21313           i += bytes_read;
21314           stack[++stacki] = unsnd;
21315           if (i < size)
21316             dwarf2_complex_location_expr_complaint ();
21317           break;
21318
21319         case DW_OP_addr:
21320           stack[++stacki] = read_address (objfile->obfd, &data[i],
21321                                           cu, &bytes_read);
21322           i += bytes_read;
21323           break;
21324
21325         case DW_OP_const1u:
21326           stack[++stacki] = read_1_byte (objfile->obfd, &data[i]);
21327           i += 1;
21328           break;
21329
21330         case DW_OP_const1s:
21331           stack[++stacki] = read_1_signed_byte (objfile->obfd, &data[i]);
21332           i += 1;
21333           break;
21334
21335         case DW_OP_const2u:
21336           stack[++stacki] = read_2_bytes (objfile->obfd, &data[i]);
21337           i += 2;
21338           break;
21339
21340         case DW_OP_const2s:
21341           stack[++stacki] = read_2_signed_bytes (objfile->obfd, &data[i]);
21342           i += 2;
21343           break;
21344
21345         case DW_OP_const4u:
21346           stack[++stacki] = read_4_bytes (objfile->obfd, &data[i]);
21347           i += 4;
21348           break;
21349
21350         case DW_OP_const4s:
21351           stack[++stacki] = read_4_signed_bytes (objfile->obfd, &data[i]);
21352           i += 4;
21353           break;
21354
21355         case DW_OP_const8u:
21356           stack[++stacki] = read_8_bytes (objfile->obfd, &data[i]);
21357           i += 8;
21358           break;
21359
21360         case DW_OP_constu:
21361           stack[++stacki] = read_unsigned_leb128 (NULL, (data + i),
21362                                                   &bytes_read);
21363           i += bytes_read;
21364           break;
21365
21366         case DW_OP_consts:
21367           stack[++stacki] = read_signed_leb128 (NULL, (data + i), &bytes_read);
21368           i += bytes_read;
21369           break;
21370
21371         case DW_OP_dup:
21372           stack[stacki + 1] = stack[stacki];
21373           stacki++;
21374           break;
21375
21376         case DW_OP_plus:
21377           stack[stacki - 1] += stack[stacki];
21378           stacki--;
21379           break;
21380
21381         case DW_OP_plus_uconst:
21382           stack[stacki] += read_unsigned_leb128 (NULL, (data + i),
21383                                                  &bytes_read);
21384           i += bytes_read;
21385           break;
21386
21387         case DW_OP_minus:
21388           stack[stacki - 1] -= stack[stacki];
21389           stacki--;
21390           break;
21391
21392         case DW_OP_deref:
21393           /* If we're not the last op, then we definitely can't encode
21394              this using GDB's address_class enum.  This is valid for partial
21395              global symbols, although the variable's address will be bogus
21396              in the psymtab.  */
21397           if (i < size)
21398             dwarf2_complex_location_expr_complaint ();
21399           break;
21400
21401         case DW_OP_GNU_push_tls_address:
21402         case DW_OP_form_tls_address:
21403           /* The top of the stack has the offset from the beginning
21404              of the thread control block at which the variable is located.  */
21405           /* Nothing should follow this operator, so the top of stack would
21406              be returned.  */
21407           /* This is valid for partial global symbols, but the variable's
21408              address will be bogus in the psymtab.  Make it always at least
21409              non-zero to not look as a variable garbage collected by linker
21410              which have DW_OP_addr 0.  */
21411           if (i < size)
21412             dwarf2_complex_location_expr_complaint ();
21413           stack[stacki]++;
21414           break;
21415
21416         case DW_OP_GNU_uninit:
21417           break;
21418
21419         case DW_OP_GNU_addr_index:
21420         case DW_OP_GNU_const_index:
21421           stack[++stacki] = read_addr_index_from_leb128 (cu, &data[i],
21422                                                          &bytes_read);
21423           i += bytes_read;
21424           break;
21425
21426         default:
21427           {
21428             const char *name = get_DW_OP_name (op);
21429
21430             if (name)
21431               complaint (&symfile_complaints, _("unsupported stack op: '%s'"),
21432                          name);
21433             else
21434               complaint (&symfile_complaints, _("unsupported stack op: '%02x'"),
21435                          op);
21436           }
21437
21438           return (stack[stacki]);
21439         }
21440
21441       /* Enforce maximum stack depth of SIZE-1 to avoid writing
21442          outside of the allocated space.  Also enforce minimum>0.  */
21443       if (stacki >= ARRAY_SIZE (stack) - 1)
21444         {
21445           complaint (&symfile_complaints,
21446                      _("location description stack overflow"));
21447           return 0;
21448         }
21449
21450       if (stacki <= 0)
21451         {
21452           complaint (&symfile_complaints,
21453                      _("location description stack underflow"));
21454           return 0;
21455         }
21456     }
21457   return (stack[stacki]);
21458 }
21459
21460 /* memory allocation interface */
21461
21462 static struct dwarf_block *
21463 dwarf_alloc_block (struct dwarf2_cu *cu)
21464 {
21465   return XOBNEW (&cu->comp_unit_obstack, struct dwarf_block);
21466 }
21467
21468 static struct die_info *
21469 dwarf_alloc_die (struct dwarf2_cu *cu, int num_attrs)
21470 {
21471   struct die_info *die;
21472   size_t size = sizeof (struct die_info);
21473
21474   if (num_attrs > 1)
21475     size += (num_attrs - 1) * sizeof (struct attribute);
21476
21477   die = (struct die_info *) obstack_alloc (&cu->comp_unit_obstack, size);
21478   memset (die, 0, sizeof (struct die_info));
21479   return (die);
21480 }
21481
21482 \f
21483 /* Macro support.  */
21484
21485 /* Return file name relative to the compilation directory of file number I in
21486    *LH's file name table.  The result is allocated using xmalloc; the caller is
21487    responsible for freeing it.  */
21488
21489 static char *
21490 file_file_name (int file, struct line_header *lh)
21491 {
21492   /* Is the file number a valid index into the line header's file name
21493      table?  Remember that file numbers start with one, not zero.  */
21494   if (1 <= file && file <= lh->file_names.size ())
21495     {
21496       const file_entry &fe = lh->file_names[file - 1];
21497
21498       if (!IS_ABSOLUTE_PATH (fe.name))
21499         {
21500           const char *dir = fe.include_dir (lh);
21501           if (dir != NULL)
21502             return concat (dir, SLASH_STRING, fe.name, (char *) NULL);
21503         }
21504       return xstrdup (fe.name);
21505     }
21506   else
21507     {
21508       /* The compiler produced a bogus file number.  We can at least
21509          record the macro definitions made in the file, even if we
21510          won't be able to find the file by name.  */
21511       char fake_name[80];
21512
21513       xsnprintf (fake_name, sizeof (fake_name),
21514                  "<bad macro file number %d>", file);
21515
21516       complaint (&symfile_complaints,
21517                  _("bad file number in macro information (%d)"),
21518                  file);
21519
21520       return xstrdup (fake_name);
21521     }
21522 }
21523
21524 /* Return the full name of file number I in *LH's file name table.
21525    Use COMP_DIR as the name of the current directory of the
21526    compilation.  The result is allocated using xmalloc; the caller is
21527    responsible for freeing it.  */
21528 static char *
21529 file_full_name (int file, struct line_header *lh, const char *comp_dir)
21530 {
21531   /* Is the file number a valid index into the line header's file name
21532      table?  Remember that file numbers start with one, not zero.  */
21533   if (1 <= file && file <= lh->file_names.size ())
21534     {
21535       char *relative = file_file_name (file, lh);
21536
21537       if (IS_ABSOLUTE_PATH (relative) || comp_dir == NULL)
21538         return relative;
21539       return reconcat (relative, comp_dir, SLASH_STRING,
21540                        relative, (char *) NULL);
21541     }
21542   else
21543     return file_file_name (file, lh);
21544 }
21545
21546
21547 static struct macro_source_file *
21548 macro_start_file (int file, int line,
21549                   struct macro_source_file *current_file,
21550                   struct line_header *lh)
21551 {
21552   /* File name relative to the compilation directory of this source file.  */
21553   char *file_name = file_file_name (file, lh);
21554
21555   if (! current_file)
21556     {
21557       /* Note: We don't create a macro table for this compilation unit
21558          at all until we actually get a filename.  */
21559       struct macro_table *macro_table = get_macro_table ();
21560
21561       /* If we have no current file, then this must be the start_file
21562          directive for the compilation unit's main source file.  */
21563       current_file = macro_set_main (macro_table, file_name);
21564       macro_define_special (macro_table);
21565     }
21566   else
21567     current_file = macro_include (current_file, line, file_name);
21568
21569   xfree (file_name);
21570
21571   return current_file;
21572 }
21573
21574
21575 /* Copy the LEN characters at BUF to a xmalloc'ed block of memory,
21576    followed by a null byte.  */
21577 static char *
21578 copy_string (const char *buf, int len)
21579 {
21580   char *s = (char *) xmalloc (len + 1);
21581
21582   memcpy (s, buf, len);
21583   s[len] = '\0';
21584   return s;
21585 }
21586
21587
21588 static const char *
21589 consume_improper_spaces (const char *p, const char *body)
21590 {
21591   if (*p == ' ')
21592     {
21593       complaint (&symfile_complaints,
21594                  _("macro definition contains spaces "
21595                    "in formal argument list:\n`%s'"),
21596                  body);
21597
21598       while (*p == ' ')
21599         p++;
21600     }
21601
21602   return p;
21603 }
21604
21605
21606 static void
21607 parse_macro_definition (struct macro_source_file *file, int line,
21608                         const char *body)
21609 {
21610   const char *p;
21611
21612   /* The body string takes one of two forms.  For object-like macro
21613      definitions, it should be:
21614
21615         <macro name> " " <definition>
21616
21617      For function-like macro definitions, it should be:
21618
21619         <macro name> "() " <definition>
21620      or
21621         <macro name> "(" <arg name> ( "," <arg name> ) * ") " <definition>
21622
21623      Spaces may appear only where explicitly indicated, and in the
21624      <definition>.
21625
21626      The Dwarf 2 spec says that an object-like macro's name is always
21627      followed by a space, but versions of GCC around March 2002 omit
21628      the space when the macro's definition is the empty string.
21629
21630      The Dwarf 2 spec says that there should be no spaces between the
21631      formal arguments in a function-like macro's formal argument list,
21632      but versions of GCC around March 2002 include spaces after the
21633      commas.  */
21634
21635
21636   /* Find the extent of the macro name.  The macro name is terminated
21637      by either a space or null character (for an object-like macro) or
21638      an opening paren (for a function-like macro).  */
21639   for (p = body; *p; p++)
21640     if (*p == ' ' || *p == '(')
21641       break;
21642
21643   if (*p == ' ' || *p == '\0')
21644     {
21645       /* It's an object-like macro.  */
21646       int name_len = p - body;
21647       char *name = copy_string (body, name_len);
21648       const char *replacement;
21649
21650       if (*p == ' ')
21651         replacement = body + name_len + 1;
21652       else
21653         {
21654           dwarf2_macro_malformed_definition_complaint (body);
21655           replacement = body + name_len;
21656         }
21657
21658       macro_define_object (file, line, name, replacement);
21659
21660       xfree (name);
21661     }
21662   else if (*p == '(')
21663     {
21664       /* It's a function-like macro.  */
21665       char *name = copy_string (body, p - body);
21666       int argc = 0;
21667       int argv_size = 1;
21668       char **argv = XNEWVEC (char *, argv_size);
21669
21670       p++;
21671
21672       p = consume_improper_spaces (p, body);
21673
21674       /* Parse the formal argument list.  */
21675       while (*p && *p != ')')
21676         {
21677           /* Find the extent of the current argument name.  */
21678           const char *arg_start = p;
21679
21680           while (*p && *p != ',' && *p != ')' && *p != ' ')
21681             p++;
21682
21683           if (! *p || p == arg_start)
21684             dwarf2_macro_malformed_definition_complaint (body);
21685           else
21686             {
21687               /* Make sure argv has room for the new argument.  */
21688               if (argc >= argv_size)
21689                 {
21690                   argv_size *= 2;
21691                   argv = XRESIZEVEC (char *, argv, argv_size);
21692                 }
21693
21694               argv[argc++] = copy_string (arg_start, p - arg_start);
21695             }
21696
21697           p = consume_improper_spaces (p, body);
21698
21699           /* Consume the comma, if present.  */
21700           if (*p == ',')
21701             {
21702               p++;
21703
21704               p = consume_improper_spaces (p, body);
21705             }
21706         }
21707
21708       if (*p == ')')
21709         {
21710           p++;
21711
21712           if (*p == ' ')
21713             /* Perfectly formed definition, no complaints.  */
21714             macro_define_function (file, line, name,
21715                                    argc, (const char **) argv,
21716                                    p + 1);
21717           else if (*p == '\0')
21718             {
21719               /* Complain, but do define it.  */
21720               dwarf2_macro_malformed_definition_complaint (body);
21721               macro_define_function (file, line, name,
21722                                      argc, (const char **) argv,
21723                                      p);
21724             }
21725           else
21726             /* Just complain.  */
21727             dwarf2_macro_malformed_definition_complaint (body);
21728         }
21729       else
21730         /* Just complain.  */
21731         dwarf2_macro_malformed_definition_complaint (body);
21732
21733       xfree (name);
21734       {
21735         int i;
21736
21737         for (i = 0; i < argc; i++)
21738           xfree (argv[i]);
21739       }
21740       xfree (argv);
21741     }
21742   else
21743     dwarf2_macro_malformed_definition_complaint (body);
21744 }
21745
21746 /* Skip some bytes from BYTES according to the form given in FORM.
21747    Returns the new pointer.  */
21748
21749 static const gdb_byte *
21750 skip_form_bytes (bfd *abfd, const gdb_byte *bytes, const gdb_byte *buffer_end,
21751                  enum dwarf_form form,
21752                  unsigned int offset_size,
21753                  struct dwarf2_section_info *section)
21754 {
21755   unsigned int bytes_read;
21756
21757   switch (form)
21758     {
21759     case DW_FORM_data1:
21760     case DW_FORM_flag:
21761       ++bytes;
21762       break;
21763
21764     case DW_FORM_data2:
21765       bytes += 2;
21766       break;
21767
21768     case DW_FORM_data4:
21769       bytes += 4;
21770       break;
21771
21772     case DW_FORM_data8:
21773       bytes += 8;
21774       break;
21775
21776     case DW_FORM_data16:
21777       bytes += 16;
21778       break;
21779
21780     case DW_FORM_string:
21781       read_direct_string (abfd, bytes, &bytes_read);
21782       bytes += bytes_read;
21783       break;
21784
21785     case DW_FORM_sec_offset:
21786     case DW_FORM_strp:
21787     case DW_FORM_GNU_strp_alt:
21788       bytes += offset_size;
21789       break;
21790
21791     case DW_FORM_block:
21792       bytes += read_unsigned_leb128 (abfd, bytes, &bytes_read);
21793       bytes += bytes_read;
21794       break;
21795
21796     case DW_FORM_block1:
21797       bytes += 1 + read_1_byte (abfd, bytes);
21798       break;
21799     case DW_FORM_block2:
21800       bytes += 2 + read_2_bytes (abfd, bytes);
21801       break;
21802     case DW_FORM_block4:
21803       bytes += 4 + read_4_bytes (abfd, bytes);
21804       break;
21805
21806     case DW_FORM_sdata:
21807     case DW_FORM_udata:
21808     case DW_FORM_GNU_addr_index:
21809     case DW_FORM_GNU_str_index:
21810       bytes = gdb_skip_leb128 (bytes, buffer_end);
21811       if (bytes == NULL)
21812         {
21813           dwarf2_section_buffer_overflow_complaint (section);
21814           return NULL;
21815         }
21816       break;
21817
21818     default:
21819       {
21820       complain:
21821         complaint (&symfile_complaints,
21822                    _("invalid form 0x%x in `%s'"),
21823                    form, get_section_name (section));
21824         return NULL;
21825       }
21826     }
21827
21828   return bytes;
21829 }
21830
21831 /* A helper for dwarf_decode_macros that handles skipping an unknown
21832    opcode.  Returns an updated pointer to the macro data buffer; or,
21833    on error, issues a complaint and returns NULL.  */
21834
21835 static const gdb_byte *
21836 skip_unknown_opcode (unsigned int opcode,
21837                      const gdb_byte **opcode_definitions,
21838                      const gdb_byte *mac_ptr, const gdb_byte *mac_end,
21839                      bfd *abfd,
21840                      unsigned int offset_size,
21841                      struct dwarf2_section_info *section)
21842 {
21843   unsigned int bytes_read, i;
21844   unsigned long arg;
21845   const gdb_byte *defn;
21846
21847   if (opcode_definitions[opcode] == NULL)
21848     {
21849       complaint (&symfile_complaints,
21850                  _("unrecognized DW_MACFINO opcode 0x%x"),
21851                  opcode);
21852       return NULL;
21853     }
21854
21855   defn = opcode_definitions[opcode];
21856   arg = read_unsigned_leb128 (abfd, defn, &bytes_read);
21857   defn += bytes_read;
21858
21859   for (i = 0; i < arg; ++i)
21860     {
21861       mac_ptr = skip_form_bytes (abfd, mac_ptr, mac_end,
21862                                  (enum dwarf_form) defn[i], offset_size,
21863                                  section);
21864       if (mac_ptr == NULL)
21865         {
21866           /* skip_form_bytes already issued the complaint.  */
21867           return NULL;
21868         }
21869     }
21870
21871   return mac_ptr;
21872 }
21873
21874 /* A helper function which parses the header of a macro section.
21875    If the macro section is the extended (for now called "GNU") type,
21876    then this updates *OFFSET_SIZE.  Returns a pointer to just after
21877    the header, or issues a complaint and returns NULL on error.  */
21878
21879 static const gdb_byte *
21880 dwarf_parse_macro_header (const gdb_byte **opcode_definitions,
21881                           bfd *abfd,
21882                           const gdb_byte *mac_ptr,
21883                           unsigned int *offset_size,
21884                           int section_is_gnu)
21885 {
21886   memset (opcode_definitions, 0, 256 * sizeof (gdb_byte *));
21887
21888   if (section_is_gnu)
21889     {
21890       unsigned int version, flags;
21891
21892       version = read_2_bytes (abfd, mac_ptr);
21893       if (version != 4 && version != 5)
21894         {
21895           complaint (&symfile_complaints,
21896                      _("unrecognized version `%d' in .debug_macro section"),
21897                      version);
21898           return NULL;
21899         }
21900       mac_ptr += 2;
21901
21902       flags = read_1_byte (abfd, mac_ptr);
21903       ++mac_ptr;
21904       *offset_size = (flags & 1) ? 8 : 4;
21905
21906       if ((flags & 2) != 0)
21907         /* We don't need the line table offset.  */
21908         mac_ptr += *offset_size;
21909
21910       /* Vendor opcode descriptions.  */
21911       if ((flags & 4) != 0)
21912         {
21913           unsigned int i, count;
21914
21915           count = read_1_byte (abfd, mac_ptr);
21916           ++mac_ptr;
21917           for (i = 0; i < count; ++i)
21918             {
21919               unsigned int opcode, bytes_read;
21920               unsigned long arg;
21921
21922               opcode = read_1_byte (abfd, mac_ptr);
21923               ++mac_ptr;
21924               opcode_definitions[opcode] = mac_ptr;
21925               arg = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
21926               mac_ptr += bytes_read;
21927               mac_ptr += arg;
21928             }
21929         }
21930     }
21931
21932   return mac_ptr;
21933 }
21934
21935 /* A helper for dwarf_decode_macros that handles the GNU extensions,
21936    including DW_MACRO_import.  */
21937
21938 static void
21939 dwarf_decode_macro_bytes (bfd *abfd,
21940                           const gdb_byte *mac_ptr, const gdb_byte *mac_end,
21941                           struct macro_source_file *current_file,
21942                           struct line_header *lh,
21943                           struct dwarf2_section_info *section,
21944                           int section_is_gnu, int section_is_dwz,
21945                           unsigned int offset_size,
21946                           htab_t include_hash)
21947 {
21948   struct objfile *objfile = dwarf2_per_objfile->objfile;
21949   enum dwarf_macro_record_type macinfo_type;
21950   int at_commandline;
21951   const gdb_byte *opcode_definitions[256];
21952
21953   mac_ptr = dwarf_parse_macro_header (opcode_definitions, abfd, mac_ptr,
21954                                       &offset_size, section_is_gnu);
21955   if (mac_ptr == NULL)
21956     {
21957       /* We already issued a complaint.  */
21958       return;
21959     }
21960
21961   /* Determines if GDB is still before first DW_MACINFO_start_file.  If true
21962      GDB is still reading the definitions from command line.  First
21963      DW_MACINFO_start_file will need to be ignored as it was already executed
21964      to create CURRENT_FILE for the main source holding also the command line
21965      definitions.  On first met DW_MACINFO_start_file this flag is reset to
21966      normally execute all the remaining DW_MACINFO_start_file macinfos.  */
21967
21968   at_commandline = 1;
21969
21970   do
21971     {
21972       /* Do we at least have room for a macinfo type byte?  */
21973       if (mac_ptr >= mac_end)
21974         {
21975           dwarf2_section_buffer_overflow_complaint (section);
21976           break;
21977         }
21978
21979       macinfo_type = (enum dwarf_macro_record_type) read_1_byte (abfd, mac_ptr);
21980       mac_ptr++;
21981
21982       /* Note that we rely on the fact that the corresponding GNU and
21983          DWARF constants are the same.  */
21984       switch (macinfo_type)
21985         {
21986           /* A zero macinfo type indicates the end of the macro
21987              information.  */
21988         case 0:
21989           break;
21990
21991         case DW_MACRO_define:
21992         case DW_MACRO_undef:
21993         case DW_MACRO_define_strp:
21994         case DW_MACRO_undef_strp:
21995         case DW_MACRO_define_sup:
21996         case DW_MACRO_undef_sup:
21997           {
21998             unsigned int bytes_read;
21999             int line;
22000             const char *body;
22001             int is_define;
22002
22003             line = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
22004             mac_ptr += bytes_read;
22005
22006             if (macinfo_type == DW_MACRO_define
22007                 || macinfo_type == DW_MACRO_undef)
22008               {
22009                 body = read_direct_string (abfd, mac_ptr, &bytes_read);
22010                 mac_ptr += bytes_read;
22011               }
22012             else
22013               {
22014                 LONGEST str_offset;
22015
22016                 str_offset = read_offset_1 (abfd, mac_ptr, offset_size);
22017                 mac_ptr += offset_size;
22018
22019                 if (macinfo_type == DW_MACRO_define_sup
22020                     || macinfo_type == DW_MACRO_undef_sup
22021                     || section_is_dwz)
22022                   {
22023                     struct dwz_file *dwz = dwarf2_get_dwz_file ();
22024
22025                     body = read_indirect_string_from_dwz (dwz, str_offset);
22026                   }
22027                 else
22028                   body = read_indirect_string_at_offset (abfd, str_offset);
22029               }
22030
22031             is_define = (macinfo_type == DW_MACRO_define
22032                          || macinfo_type == DW_MACRO_define_strp
22033                          || macinfo_type == DW_MACRO_define_sup);
22034             if (! current_file)
22035               {
22036                 /* DWARF violation as no main source is present.  */
22037                 complaint (&symfile_complaints,
22038                            _("debug info with no main source gives macro %s "
22039                              "on line %d: %s"),
22040                            is_define ? _("definition") : _("undefinition"),
22041                            line, body);
22042                 break;
22043               }
22044             if ((line == 0 && !at_commandline)
22045                 || (line != 0 && at_commandline))
22046               complaint (&symfile_complaints,
22047                          _("debug info gives %s macro %s with %s line %d: %s"),
22048                          at_commandline ? _("command-line") : _("in-file"),
22049                          is_define ? _("definition") : _("undefinition"),
22050                          line == 0 ? _("zero") : _("non-zero"), line, body);
22051
22052             if (is_define)
22053               parse_macro_definition (current_file, line, body);
22054             else
22055               {
22056                 gdb_assert (macinfo_type == DW_MACRO_undef
22057                             || macinfo_type == DW_MACRO_undef_strp
22058                             || macinfo_type == DW_MACRO_undef_sup);
22059                 macro_undef (current_file, line, body);
22060               }
22061           }
22062           break;
22063
22064         case DW_MACRO_start_file:
22065           {
22066             unsigned int bytes_read;
22067             int line, file;
22068
22069             line = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
22070             mac_ptr += bytes_read;
22071             file = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
22072             mac_ptr += bytes_read;
22073
22074             if ((line == 0 && !at_commandline)
22075                 || (line != 0 && at_commandline))
22076               complaint (&symfile_complaints,
22077                          _("debug info gives source %d included "
22078                            "from %s at %s line %d"),
22079                          file, at_commandline ? _("command-line") : _("file"),
22080                          line == 0 ? _("zero") : _("non-zero"), line);
22081
22082             if (at_commandline)
22083               {
22084                 /* This DW_MACRO_start_file was executed in the
22085                    pass one.  */
22086                 at_commandline = 0;
22087               }
22088             else
22089               current_file = macro_start_file (file, line, current_file, lh);
22090           }
22091           break;
22092
22093         case DW_MACRO_end_file:
22094           if (! current_file)
22095             complaint (&symfile_complaints,
22096                        _("macro debug info has an unmatched "
22097                          "`close_file' directive"));
22098           else
22099             {
22100               current_file = current_file->included_by;
22101               if (! current_file)
22102                 {
22103                   enum dwarf_macro_record_type next_type;
22104
22105                   /* GCC circa March 2002 doesn't produce the zero
22106                      type byte marking the end of the compilation
22107                      unit.  Complain if it's not there, but exit no
22108                      matter what.  */
22109
22110                   /* Do we at least have room for a macinfo type byte?  */
22111                   if (mac_ptr >= mac_end)
22112                     {
22113                       dwarf2_section_buffer_overflow_complaint (section);
22114                       return;
22115                     }
22116
22117                   /* We don't increment mac_ptr here, so this is just
22118                      a look-ahead.  */
22119                   next_type
22120                     = (enum dwarf_macro_record_type) read_1_byte (abfd,
22121                                                                   mac_ptr);
22122                   if (next_type != 0)
22123                     complaint (&symfile_complaints,
22124                                _("no terminating 0-type entry for "
22125                                  "macros in `.debug_macinfo' section"));
22126
22127                   return;
22128                 }
22129             }
22130           break;
22131
22132         case DW_MACRO_import:
22133         case DW_MACRO_import_sup:
22134           {
22135             LONGEST offset;
22136             void **slot;
22137             bfd *include_bfd = abfd;
22138             struct dwarf2_section_info *include_section = section;
22139             const gdb_byte *include_mac_end = mac_end;
22140             int is_dwz = section_is_dwz;
22141             const gdb_byte *new_mac_ptr;
22142
22143             offset = read_offset_1 (abfd, mac_ptr, offset_size);
22144             mac_ptr += offset_size;
22145
22146             if (macinfo_type == DW_MACRO_import_sup)
22147               {
22148                 struct dwz_file *dwz = dwarf2_get_dwz_file ();
22149
22150                 dwarf2_read_section (objfile, &dwz->macro);
22151
22152                 include_section = &dwz->macro;
22153                 include_bfd = get_section_bfd_owner (include_section);
22154                 include_mac_end = dwz->macro.buffer + dwz->macro.size;
22155                 is_dwz = 1;
22156               }
22157
22158             new_mac_ptr = include_section->buffer + offset;
22159             slot = htab_find_slot (include_hash, new_mac_ptr, INSERT);
22160
22161             if (*slot != NULL)
22162               {
22163                 /* This has actually happened; see
22164                    http://sourceware.org/bugzilla/show_bug.cgi?id=13568.  */
22165                 complaint (&symfile_complaints,
22166                            _("recursive DW_MACRO_import in "
22167                              ".debug_macro section"));
22168               }
22169             else
22170               {
22171                 *slot = (void *) new_mac_ptr;
22172
22173                 dwarf_decode_macro_bytes (include_bfd, new_mac_ptr,
22174                                           include_mac_end, current_file, lh,
22175                                           section, section_is_gnu, is_dwz,
22176                                           offset_size, include_hash);
22177
22178                 htab_remove_elt (include_hash, (void *) new_mac_ptr);
22179               }
22180           }
22181           break;
22182
22183         case DW_MACINFO_vendor_ext:
22184           if (!section_is_gnu)
22185             {
22186               unsigned int bytes_read;
22187
22188               /* This reads the constant, but since we don't recognize
22189                  any vendor extensions, we ignore it.  */
22190               read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
22191               mac_ptr += bytes_read;
22192               read_direct_string (abfd, mac_ptr, &bytes_read);
22193               mac_ptr += bytes_read;
22194
22195               /* We don't recognize any vendor extensions.  */
22196               break;
22197             }
22198           /* FALLTHROUGH */
22199
22200         default:
22201           mac_ptr = skip_unknown_opcode (macinfo_type, opcode_definitions,
22202                                          mac_ptr, mac_end, abfd, offset_size,
22203                                          section);
22204           if (mac_ptr == NULL)
22205             return;
22206           break;
22207         }
22208     } while (macinfo_type != 0);
22209 }
22210
22211 static void
22212 dwarf_decode_macros (struct dwarf2_cu *cu, unsigned int offset,
22213                      int section_is_gnu)
22214 {
22215   struct objfile *objfile = dwarf2_per_objfile->objfile;
22216   struct line_header *lh = cu->line_header;
22217   bfd *abfd;
22218   const gdb_byte *mac_ptr, *mac_end;
22219   struct macro_source_file *current_file = 0;
22220   enum dwarf_macro_record_type macinfo_type;
22221   unsigned int offset_size = cu->header.offset_size;
22222   const gdb_byte *opcode_definitions[256];
22223   struct cleanup *cleanup;
22224   void **slot;
22225   struct dwarf2_section_info *section;
22226   const char *section_name;
22227
22228   if (cu->dwo_unit != NULL)
22229     {
22230       if (section_is_gnu)
22231         {
22232           section = &cu->dwo_unit->dwo_file->sections.macro;
22233           section_name = ".debug_macro.dwo";
22234         }
22235       else
22236         {
22237           section = &cu->dwo_unit->dwo_file->sections.macinfo;
22238           section_name = ".debug_macinfo.dwo";
22239         }
22240     }
22241   else
22242     {
22243       if (section_is_gnu)
22244         {
22245           section = &dwarf2_per_objfile->macro;
22246           section_name = ".debug_macro";
22247         }
22248       else
22249         {
22250           section = &dwarf2_per_objfile->macinfo;
22251           section_name = ".debug_macinfo";
22252         }
22253     }
22254
22255   dwarf2_read_section (objfile, section);
22256   if (section->buffer == NULL)
22257     {
22258       complaint (&symfile_complaints, _("missing %s section"), section_name);
22259       return;
22260     }
22261   abfd = get_section_bfd_owner (section);
22262
22263   /* First pass: Find the name of the base filename.
22264      This filename is needed in order to process all macros whose definition
22265      (or undefinition) comes from the command line.  These macros are defined
22266      before the first DW_MACINFO_start_file entry, and yet still need to be
22267      associated to the base file.
22268
22269      To determine the base file name, we scan the macro definitions until we
22270      reach the first DW_MACINFO_start_file entry.  We then initialize
22271      CURRENT_FILE accordingly so that any macro definition found before the
22272      first DW_MACINFO_start_file can still be associated to the base file.  */
22273
22274   mac_ptr = section->buffer + offset;
22275   mac_end = section->buffer + section->size;
22276
22277   mac_ptr = dwarf_parse_macro_header (opcode_definitions, abfd, mac_ptr,
22278                                       &offset_size, section_is_gnu);
22279   if (mac_ptr == NULL)
22280     {
22281       /* We already issued a complaint.  */
22282       return;
22283     }
22284
22285   do
22286     {
22287       /* Do we at least have room for a macinfo type byte?  */
22288       if (mac_ptr >= mac_end)
22289         {
22290           /* Complaint is printed during the second pass as GDB will probably
22291              stop the first pass earlier upon finding
22292              DW_MACINFO_start_file.  */
22293           break;
22294         }
22295
22296       macinfo_type = (enum dwarf_macro_record_type) read_1_byte (abfd, mac_ptr);
22297       mac_ptr++;
22298
22299       /* Note that we rely on the fact that the corresponding GNU and
22300          DWARF constants are the same.  */
22301       switch (macinfo_type)
22302         {
22303           /* A zero macinfo type indicates the end of the macro
22304              information.  */
22305         case 0:
22306           break;
22307
22308         case DW_MACRO_define:
22309         case DW_MACRO_undef:
22310           /* Only skip the data by MAC_PTR.  */
22311           {
22312             unsigned int bytes_read;
22313
22314             read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
22315             mac_ptr += bytes_read;
22316             read_direct_string (abfd, mac_ptr, &bytes_read);
22317             mac_ptr += bytes_read;
22318           }
22319           break;
22320
22321         case DW_MACRO_start_file:
22322           {
22323             unsigned int bytes_read;
22324             int line, file;
22325
22326             line = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
22327             mac_ptr += bytes_read;
22328             file = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
22329             mac_ptr += bytes_read;
22330
22331             current_file = macro_start_file (file, line, current_file, lh);
22332           }
22333           break;
22334
22335         case DW_MACRO_end_file:
22336           /* No data to skip by MAC_PTR.  */
22337           break;
22338
22339         case DW_MACRO_define_strp:
22340         case DW_MACRO_undef_strp:
22341         case DW_MACRO_define_sup:
22342         case DW_MACRO_undef_sup:
22343           {
22344             unsigned int bytes_read;
22345
22346             read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
22347             mac_ptr += bytes_read;
22348             mac_ptr += offset_size;
22349           }
22350           break;
22351
22352         case DW_MACRO_import:
22353         case DW_MACRO_import_sup:
22354           /* Note that, according to the spec, a transparent include
22355              chain cannot call DW_MACRO_start_file.  So, we can just
22356              skip this opcode.  */
22357           mac_ptr += offset_size;
22358           break;
22359
22360         case DW_MACINFO_vendor_ext:
22361           /* Only skip the data by MAC_PTR.  */
22362           if (!section_is_gnu)
22363             {
22364               unsigned int bytes_read;
22365
22366               read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
22367               mac_ptr += bytes_read;
22368               read_direct_string (abfd, mac_ptr, &bytes_read);
22369               mac_ptr += bytes_read;
22370             }
22371           /* FALLTHROUGH */
22372
22373         default:
22374           mac_ptr = skip_unknown_opcode (macinfo_type, opcode_definitions,
22375                                          mac_ptr, mac_end, abfd, offset_size,
22376                                          section);
22377           if (mac_ptr == NULL)
22378             return;
22379           break;
22380         }
22381     } while (macinfo_type != 0 && current_file == NULL);
22382
22383   /* Second pass: Process all entries.
22384
22385      Use the AT_COMMAND_LINE flag to determine whether we are still processing
22386      command-line macro definitions/undefinitions.  This flag is unset when we
22387      reach the first DW_MACINFO_start_file entry.  */
22388
22389   htab_up include_hash (htab_create_alloc (1, htab_hash_pointer,
22390                                            htab_eq_pointer,
22391                                            NULL, xcalloc, xfree));
22392   mac_ptr = section->buffer + offset;
22393   slot = htab_find_slot (include_hash.get (), mac_ptr, INSERT);
22394   *slot = (void *) mac_ptr;
22395   dwarf_decode_macro_bytes (abfd, mac_ptr, mac_end,
22396                             current_file, lh, section,
22397                             section_is_gnu, 0, offset_size,
22398                             include_hash.get ());
22399 }
22400
22401 /* Check if the attribute's form is a DW_FORM_block*
22402    if so return true else false.  */
22403
22404 static int
22405 attr_form_is_block (const struct attribute *attr)
22406 {
22407   return (attr == NULL ? 0 :
22408       attr->form == DW_FORM_block1
22409       || attr->form == DW_FORM_block2
22410       || attr->form == DW_FORM_block4
22411       || attr->form == DW_FORM_block
22412       || attr->form == DW_FORM_exprloc);
22413 }
22414
22415 /* Return non-zero if ATTR's value is a section offset --- classes
22416    lineptr, loclistptr, macptr or rangelistptr --- or zero, otherwise.
22417    You may use DW_UNSND (attr) to retrieve such offsets.
22418
22419    Section 7.5.4, "Attribute Encodings", explains that no attribute
22420    may have a value that belongs to more than one of these classes; it
22421    would be ambiguous if we did, because we use the same forms for all
22422    of them.  */
22423
22424 static int
22425 attr_form_is_section_offset (const struct attribute *attr)
22426 {
22427   return (attr->form == DW_FORM_data4
22428           || attr->form == DW_FORM_data8
22429           || attr->form == DW_FORM_sec_offset);
22430 }
22431
22432 /* Return non-zero if ATTR's value falls in the 'constant' class, or
22433    zero otherwise.  When this function returns true, you can apply
22434    dwarf2_get_attr_constant_value to it.
22435
22436    However, note that for some attributes you must check
22437    attr_form_is_section_offset before using this test.  DW_FORM_data4
22438    and DW_FORM_data8 are members of both the constant class, and of
22439    the classes that contain offsets into other debug sections
22440    (lineptr, loclistptr, macptr or rangelistptr).  The DWARF spec says
22441    that, if an attribute's can be either a constant or one of the
22442    section offset classes, DW_FORM_data4 and DW_FORM_data8 should be
22443    taken as section offsets, not constants.
22444
22445    DW_FORM_data16 is not considered as dwarf2_get_attr_constant_value
22446    cannot handle that.  */
22447
22448 static int
22449 attr_form_is_constant (const struct attribute *attr)
22450 {
22451   switch (attr->form)
22452     {
22453     case DW_FORM_sdata:
22454     case DW_FORM_udata:
22455     case DW_FORM_data1:
22456     case DW_FORM_data2:
22457     case DW_FORM_data4:
22458     case DW_FORM_data8:
22459       return 1;
22460     default:
22461       return 0;
22462     }
22463 }
22464
22465
22466 /* DW_ADDR is always stored already as sect_offset; despite for the forms
22467    besides DW_FORM_ref_addr it is stored as cu_offset in the DWARF file.  */
22468
22469 static int
22470 attr_form_is_ref (const struct attribute *attr)
22471 {
22472   switch (attr->form)
22473     {
22474     case DW_FORM_ref_addr:
22475     case DW_FORM_ref1:
22476     case DW_FORM_ref2:
22477     case DW_FORM_ref4:
22478     case DW_FORM_ref8:
22479     case DW_FORM_ref_udata:
22480     case DW_FORM_GNU_ref_alt:
22481       return 1;
22482     default:
22483       return 0;
22484     }
22485 }
22486
22487 /* Return the .debug_loc section to use for CU.
22488    For DWO files use .debug_loc.dwo.  */
22489
22490 static struct dwarf2_section_info *
22491 cu_debug_loc_section (struct dwarf2_cu *cu)
22492 {
22493   if (cu->dwo_unit)
22494     {
22495       struct dwo_sections *sections = &cu->dwo_unit->dwo_file->sections;
22496       
22497       return cu->header.version >= 5 ? &sections->loclists : &sections->loc;
22498     }
22499   return (cu->header.version >= 5 ? &dwarf2_per_objfile->loclists
22500                                   : &dwarf2_per_objfile->loc);
22501 }
22502
22503 /* A helper function that fills in a dwarf2_loclist_baton.  */
22504
22505 static void
22506 fill_in_loclist_baton (struct dwarf2_cu *cu,
22507                        struct dwarf2_loclist_baton *baton,
22508                        const struct attribute *attr)
22509 {
22510   struct dwarf2_section_info *section = cu_debug_loc_section (cu);
22511
22512   dwarf2_read_section (dwarf2_per_objfile->objfile, section);
22513
22514   baton->per_cu = cu->per_cu;
22515   gdb_assert (baton->per_cu);
22516   /* We don't know how long the location list is, but make sure we
22517      don't run off the edge of the section.  */
22518   baton->size = section->size - DW_UNSND (attr);
22519   baton->data = section->buffer + DW_UNSND (attr);
22520   baton->base_address = cu->base_address;
22521   baton->from_dwo = cu->dwo_unit != NULL;
22522 }
22523
22524 static void
22525 dwarf2_symbol_mark_computed (const struct attribute *attr, struct symbol *sym,
22526                              struct dwarf2_cu *cu, int is_block)
22527 {
22528   struct objfile *objfile = dwarf2_per_objfile->objfile;
22529   struct dwarf2_section_info *section = cu_debug_loc_section (cu);
22530
22531   if (attr_form_is_section_offset (attr)
22532       /* .debug_loc{,.dwo} may not exist at all, or the offset may be outside
22533          the section.  If so, fall through to the complaint in the
22534          other branch.  */
22535       && DW_UNSND (attr) < dwarf2_section_size (objfile, section))
22536     {
22537       struct dwarf2_loclist_baton *baton;
22538
22539       baton = XOBNEW (&objfile->objfile_obstack, struct dwarf2_loclist_baton);
22540
22541       fill_in_loclist_baton (cu, baton, attr);
22542
22543       if (cu->base_known == 0)
22544         complaint (&symfile_complaints,
22545                    _("Location list used without "
22546                      "specifying the CU base address."));
22547
22548       SYMBOL_ACLASS_INDEX (sym) = (is_block
22549                                    ? dwarf2_loclist_block_index
22550                                    : dwarf2_loclist_index);
22551       SYMBOL_LOCATION_BATON (sym) = baton;
22552     }
22553   else
22554     {
22555       struct dwarf2_locexpr_baton *baton;
22556
22557       baton = XOBNEW (&objfile->objfile_obstack, struct dwarf2_locexpr_baton);
22558       baton->per_cu = cu->per_cu;
22559       gdb_assert (baton->per_cu);
22560
22561       if (attr_form_is_block (attr))
22562         {
22563           /* Note that we're just copying the block's data pointer
22564              here, not the actual data.  We're still pointing into the
22565              info_buffer for SYM's objfile; right now we never release
22566              that buffer, but when we do clean up properly this may
22567              need to change.  */
22568           baton->size = DW_BLOCK (attr)->size;
22569           baton->data = DW_BLOCK (attr)->data;
22570         }
22571       else
22572         {
22573           dwarf2_invalid_attrib_class_complaint ("location description",
22574                                                  SYMBOL_NATURAL_NAME (sym));
22575           baton->size = 0;
22576         }
22577
22578       SYMBOL_ACLASS_INDEX (sym) = (is_block
22579                                    ? dwarf2_locexpr_block_index
22580                                    : dwarf2_locexpr_index);
22581       SYMBOL_LOCATION_BATON (sym) = baton;
22582     }
22583 }
22584
22585 /* Return the OBJFILE associated with the compilation unit CU.  If CU
22586    came from a separate debuginfo file, then the master objfile is
22587    returned.  */
22588
22589 struct objfile *
22590 dwarf2_per_cu_objfile (struct dwarf2_per_cu_data *per_cu)
22591 {
22592   struct objfile *objfile = per_cu->objfile;
22593
22594   /* Return the master objfile, so that we can report and look up the
22595      correct file containing this variable.  */
22596   if (objfile->separate_debug_objfile_backlink)
22597     objfile = objfile->separate_debug_objfile_backlink;
22598
22599   return objfile;
22600 }
22601
22602 /* Return comp_unit_head for PER_CU, either already available in PER_CU->CU
22603    (CU_HEADERP is unused in such case) or prepare a temporary copy at
22604    CU_HEADERP first.  */
22605
22606 static const struct comp_unit_head *
22607 per_cu_header_read_in (struct comp_unit_head *cu_headerp,
22608                        struct dwarf2_per_cu_data *per_cu)
22609 {
22610   const gdb_byte *info_ptr;
22611
22612   if (per_cu->cu)
22613     return &per_cu->cu->header;
22614
22615   info_ptr = per_cu->section->buffer + to_underlying (per_cu->sect_off);
22616
22617   memset (cu_headerp, 0, sizeof (*cu_headerp));
22618   read_comp_unit_head (cu_headerp, info_ptr, per_cu->section,
22619                        rcuh_kind::COMPILE);
22620
22621   return cu_headerp;
22622 }
22623
22624 /* Return the address size given in the compilation unit header for CU.  */
22625
22626 int
22627 dwarf2_per_cu_addr_size (struct dwarf2_per_cu_data *per_cu)
22628 {
22629   struct comp_unit_head cu_header_local;
22630   const struct comp_unit_head *cu_headerp;
22631
22632   cu_headerp = per_cu_header_read_in (&cu_header_local, per_cu);
22633
22634   return cu_headerp->addr_size;
22635 }
22636
22637 /* Return the offset size given in the compilation unit header for CU.  */
22638
22639 int
22640 dwarf2_per_cu_offset_size (struct dwarf2_per_cu_data *per_cu)
22641 {
22642   struct comp_unit_head cu_header_local;
22643   const struct comp_unit_head *cu_headerp;
22644
22645   cu_headerp = per_cu_header_read_in (&cu_header_local, per_cu);
22646
22647   return cu_headerp->offset_size;
22648 }
22649
22650 /* See its dwarf2loc.h declaration.  */
22651
22652 int
22653 dwarf2_per_cu_ref_addr_size (struct dwarf2_per_cu_data *per_cu)
22654 {
22655   struct comp_unit_head cu_header_local;
22656   const struct comp_unit_head *cu_headerp;
22657
22658   cu_headerp = per_cu_header_read_in (&cu_header_local, per_cu);
22659
22660   if (cu_headerp->version == 2)
22661     return cu_headerp->addr_size;
22662   else
22663     return cu_headerp->offset_size;
22664 }
22665
22666 /* Return the text offset of the CU.  The returned offset comes from
22667    this CU's objfile.  If this objfile came from a separate debuginfo
22668    file, then the offset may be different from the corresponding
22669    offset in the parent objfile.  */
22670
22671 CORE_ADDR
22672 dwarf2_per_cu_text_offset (struct dwarf2_per_cu_data *per_cu)
22673 {
22674   struct objfile *objfile = per_cu->objfile;
22675
22676   return ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
22677 }
22678
22679 /* Return DWARF version number of PER_CU.  */
22680
22681 short
22682 dwarf2_version (struct dwarf2_per_cu_data *per_cu)
22683 {
22684   return per_cu->dwarf_version;
22685 }
22686
22687 /* Locate the .debug_info compilation unit from CU's objfile which contains
22688    the DIE at OFFSET.  Raises an error on failure.  */
22689
22690 static struct dwarf2_per_cu_data *
22691 dwarf2_find_containing_comp_unit (sect_offset sect_off,
22692                                   unsigned int offset_in_dwz,
22693                                   struct objfile *objfile)
22694 {
22695   struct dwarf2_per_cu_data *this_cu;
22696   int low, high;
22697   const sect_offset *cu_off;
22698
22699   low = 0;
22700   high = dwarf2_per_objfile->n_comp_units - 1;
22701   while (high > low)
22702     {
22703       struct dwarf2_per_cu_data *mid_cu;
22704       int mid = low + (high - low) / 2;
22705
22706       mid_cu = dwarf2_per_objfile->all_comp_units[mid];
22707       cu_off = &mid_cu->sect_off;
22708       if (mid_cu->is_dwz > offset_in_dwz
22709           || (mid_cu->is_dwz == offset_in_dwz && *cu_off >= sect_off))
22710         high = mid;
22711       else
22712         low = mid + 1;
22713     }
22714   gdb_assert (low == high);
22715   this_cu = dwarf2_per_objfile->all_comp_units[low];
22716   cu_off = &this_cu->sect_off;
22717   if (this_cu->is_dwz != offset_in_dwz || *cu_off > sect_off)
22718     {
22719       if (low == 0 || this_cu->is_dwz != offset_in_dwz)
22720         error (_("Dwarf Error: could not find partial DIE containing "
22721                "offset 0x%x [in module %s]"),
22722                to_underlying (sect_off), bfd_get_filename (objfile->obfd));
22723
22724       gdb_assert (dwarf2_per_objfile->all_comp_units[low-1]->sect_off
22725                   <= sect_off);
22726       return dwarf2_per_objfile->all_comp_units[low-1];
22727     }
22728   else
22729     {
22730       this_cu = dwarf2_per_objfile->all_comp_units[low];
22731       if (low == dwarf2_per_objfile->n_comp_units - 1
22732           && sect_off >= this_cu->sect_off + this_cu->length)
22733         error (_("invalid dwarf2 offset %u"), to_underlying (sect_off));
22734       gdb_assert (sect_off < this_cu->sect_off + this_cu->length);
22735       return this_cu;
22736     }
22737 }
22738
22739 /* Initialize dwarf2_cu CU, owned by PER_CU.  */
22740
22741 static void
22742 init_one_comp_unit (struct dwarf2_cu *cu, struct dwarf2_per_cu_data *per_cu)
22743 {
22744   memset (cu, 0, sizeof (*cu));
22745   per_cu->cu = cu;
22746   cu->per_cu = per_cu;
22747   cu->objfile = per_cu->objfile;
22748   obstack_init (&cu->comp_unit_obstack);
22749 }
22750
22751 /* Initialize basic fields of dwarf_cu CU according to DIE COMP_UNIT_DIE.  */
22752
22753 static void
22754 prepare_one_comp_unit (struct dwarf2_cu *cu, struct die_info *comp_unit_die,
22755                        enum language pretend_language)
22756 {
22757   struct attribute *attr;
22758
22759   /* Set the language we're debugging.  */
22760   attr = dwarf2_attr (comp_unit_die, DW_AT_language, cu);
22761   if (attr)
22762     set_cu_language (DW_UNSND (attr), cu);
22763   else
22764     {
22765       cu->language = pretend_language;
22766       cu->language_defn = language_def (cu->language);
22767     }
22768
22769   cu->producer = dwarf2_string_attr (comp_unit_die, DW_AT_producer, cu);
22770 }
22771
22772 /* Release one cached compilation unit, CU.  We unlink it from the tree
22773    of compilation units, but we don't remove it from the read_in_chain;
22774    the caller is responsible for that.
22775    NOTE: DATA is a void * because this function is also used as a
22776    cleanup routine.  */
22777
22778 static void
22779 free_heap_comp_unit (void *data)
22780 {
22781   struct dwarf2_cu *cu = (struct dwarf2_cu *) data;
22782
22783   gdb_assert (cu->per_cu != NULL);
22784   cu->per_cu->cu = NULL;
22785   cu->per_cu = NULL;
22786
22787   obstack_free (&cu->comp_unit_obstack, NULL);
22788
22789   xfree (cu);
22790 }
22791
22792 /* This cleanup function is passed the address of a dwarf2_cu on the stack
22793    when we're finished with it.  We can't free the pointer itself, but be
22794    sure to unlink it from the cache.  Also release any associated storage.  */
22795
22796 static void
22797 free_stack_comp_unit (void *data)
22798 {
22799   struct dwarf2_cu *cu = (struct dwarf2_cu *) data;
22800
22801   gdb_assert (cu->per_cu != NULL);
22802   cu->per_cu->cu = NULL;
22803   cu->per_cu = NULL;
22804
22805   obstack_free (&cu->comp_unit_obstack, NULL);
22806   cu->partial_dies = NULL;
22807 }
22808
22809 /* Free all cached compilation units.  */
22810
22811 static void
22812 free_cached_comp_units (void *data)
22813 {
22814   dwarf2_per_objfile->free_cached_comp_units ();
22815 }
22816
22817 /* Increase the age counter on each cached compilation unit, and free
22818    any that are too old.  */
22819
22820 static void
22821 age_cached_comp_units (void)
22822 {
22823   struct dwarf2_per_cu_data *per_cu, **last_chain;
22824
22825   dwarf2_clear_marks (dwarf2_per_objfile->read_in_chain);
22826   per_cu = dwarf2_per_objfile->read_in_chain;
22827   while (per_cu != NULL)
22828     {
22829       per_cu->cu->last_used ++;
22830       if (per_cu->cu->last_used <= dwarf_max_cache_age)
22831         dwarf2_mark (per_cu->cu);
22832       per_cu = per_cu->cu->read_in_chain;
22833     }
22834
22835   per_cu = dwarf2_per_objfile->read_in_chain;
22836   last_chain = &dwarf2_per_objfile->read_in_chain;
22837   while (per_cu != NULL)
22838     {
22839       struct dwarf2_per_cu_data *next_cu;
22840
22841       next_cu = per_cu->cu->read_in_chain;
22842
22843       if (!per_cu->cu->mark)
22844         {
22845           free_heap_comp_unit (per_cu->cu);
22846           *last_chain = next_cu;
22847         }
22848       else
22849         last_chain = &per_cu->cu->read_in_chain;
22850
22851       per_cu = next_cu;
22852     }
22853 }
22854
22855 /* Remove a single compilation unit from the cache.  */
22856
22857 static void
22858 free_one_cached_comp_unit (struct dwarf2_per_cu_data *target_per_cu)
22859 {
22860   struct dwarf2_per_cu_data *per_cu, **last_chain;
22861
22862   per_cu = dwarf2_per_objfile->read_in_chain;
22863   last_chain = &dwarf2_per_objfile->read_in_chain;
22864   while (per_cu != NULL)
22865     {
22866       struct dwarf2_per_cu_data *next_cu;
22867
22868       next_cu = per_cu->cu->read_in_chain;
22869
22870       if (per_cu == target_per_cu)
22871         {
22872           free_heap_comp_unit (per_cu->cu);
22873           per_cu->cu = NULL;
22874           *last_chain = next_cu;
22875           break;
22876         }
22877       else
22878         last_chain = &per_cu->cu->read_in_chain;
22879
22880       per_cu = next_cu;
22881     }
22882 }
22883
22884 /* Release all extra memory associated with OBJFILE.  */
22885
22886 void
22887 dwarf2_free_objfile (struct objfile *objfile)
22888 {
22889   dwarf2_per_objfile
22890     = (struct dwarf2_per_objfile *) objfile_data (objfile,
22891                                                   dwarf2_objfile_data_key);
22892
22893   if (dwarf2_per_objfile == NULL)
22894     return;
22895
22896   dwarf2_per_objfile->~dwarf2_per_objfile ();
22897 }
22898
22899 /* A set of CU "per_cu" pointer, DIE offset, and GDB type pointer.
22900    We store these in a hash table separate from the DIEs, and preserve them
22901    when the DIEs are flushed out of cache.
22902
22903    The CU "per_cu" pointer is needed because offset alone is not enough to
22904    uniquely identify the type.  A file may have multiple .debug_types sections,
22905    or the type may come from a DWO file.  Furthermore, while it's more logical
22906    to use per_cu->section+offset, with Fission the section with the data is in
22907    the DWO file but we don't know that section at the point we need it.
22908    We have to use something in dwarf2_per_cu_data (or the pointer to it)
22909    because we can enter the lookup routine, get_die_type_at_offset, from
22910    outside this file, and thus won't necessarily have PER_CU->cu.
22911    Fortunately, PER_CU is stable for the life of the objfile.  */
22912
22913 struct dwarf2_per_cu_offset_and_type
22914 {
22915   const struct dwarf2_per_cu_data *per_cu;
22916   sect_offset sect_off;
22917   struct type *type;
22918 };
22919
22920 /* Hash function for a dwarf2_per_cu_offset_and_type.  */
22921
22922 static hashval_t
22923 per_cu_offset_and_type_hash (const void *item)
22924 {
22925   const struct dwarf2_per_cu_offset_and_type *ofs
22926     = (const struct dwarf2_per_cu_offset_and_type *) item;
22927
22928   return (uintptr_t) ofs->per_cu + to_underlying (ofs->sect_off);
22929 }
22930
22931 /* Equality function for a dwarf2_per_cu_offset_and_type.  */
22932
22933 static int
22934 per_cu_offset_and_type_eq (const void *item_lhs, const void *item_rhs)
22935 {
22936   const struct dwarf2_per_cu_offset_and_type *ofs_lhs
22937     = (const struct dwarf2_per_cu_offset_and_type *) item_lhs;
22938   const struct dwarf2_per_cu_offset_and_type *ofs_rhs
22939     = (const struct dwarf2_per_cu_offset_and_type *) item_rhs;
22940
22941   return (ofs_lhs->per_cu == ofs_rhs->per_cu
22942           && ofs_lhs->sect_off == ofs_rhs->sect_off);
22943 }
22944
22945 /* Set the type associated with DIE to TYPE.  Save it in CU's hash
22946    table if necessary.  For convenience, return TYPE.
22947
22948    The DIEs reading must have careful ordering to:
22949     * Not cause infite loops trying to read in DIEs as a prerequisite for
22950       reading current DIE.
22951     * Not trying to dereference contents of still incompletely read in types
22952       while reading in other DIEs.
22953     * Enable referencing still incompletely read in types just by a pointer to
22954       the type without accessing its fields.
22955
22956    Therefore caller should follow these rules:
22957      * Try to fetch any prerequisite types we may need to build this DIE type
22958        before building the type and calling set_die_type.
22959      * After building type call set_die_type for current DIE as soon as
22960        possible before fetching more types to complete the current type.
22961      * Make the type as complete as possible before fetching more types.  */
22962
22963 static struct type *
22964 set_die_type (struct die_info *die, struct type *type, struct dwarf2_cu *cu)
22965 {
22966   struct dwarf2_per_cu_offset_and_type **slot, ofs;
22967   struct objfile *objfile = cu->objfile;
22968   struct attribute *attr;
22969   struct dynamic_prop prop;
22970
22971   /* For Ada types, make sure that the gnat-specific data is always
22972      initialized (if not already set).  There are a few types where
22973      we should not be doing so, because the type-specific area is
22974      already used to hold some other piece of info (eg: TYPE_CODE_FLT
22975      where the type-specific area is used to store the floatformat).
22976      But this is not a problem, because the gnat-specific information
22977      is actually not needed for these types.  */
22978   if (need_gnat_info (cu)
22979       && TYPE_CODE (type) != TYPE_CODE_FUNC
22980       && TYPE_CODE (type) != TYPE_CODE_FLT
22981       && TYPE_CODE (type) != TYPE_CODE_METHODPTR
22982       && TYPE_CODE (type) != TYPE_CODE_MEMBERPTR
22983       && TYPE_CODE (type) != TYPE_CODE_METHOD
22984       && !HAVE_GNAT_AUX_INFO (type))
22985     INIT_GNAT_SPECIFIC (type);
22986
22987   /* Read DW_AT_allocated and set in type.  */
22988   attr = dwarf2_attr (die, DW_AT_allocated, cu);
22989   if (attr_form_is_block (attr))
22990     {
22991       if (attr_to_dynamic_prop (attr, die, cu, &prop))
22992         add_dyn_prop (DYN_PROP_ALLOCATED, prop, type, objfile);
22993     }
22994   else if (attr != NULL)
22995     {
22996       complaint (&symfile_complaints,
22997                  _("DW_AT_allocated has the wrong form (%s) at DIE 0x%x"),
22998                  (attr != NULL ? dwarf_form_name (attr->form) : "n/a"),
22999                  to_underlying (die->sect_off));
23000     }
23001
23002   /* Read DW_AT_associated and set in type.  */
23003   attr = dwarf2_attr (die, DW_AT_associated, cu);
23004   if (attr_form_is_block (attr))
23005     {
23006       if (attr_to_dynamic_prop (attr, die, cu, &prop))
23007         add_dyn_prop (DYN_PROP_ASSOCIATED, prop, type, objfile);
23008     }
23009   else if (attr != NULL)
23010     {
23011       complaint (&symfile_complaints,
23012                  _("DW_AT_associated has the wrong form (%s) at DIE 0x%x"),
23013                  (attr != NULL ? dwarf_form_name (attr->form) : "n/a"),
23014                  to_underlying (die->sect_off));
23015     }
23016
23017   /* Read DW_AT_data_location and set in type.  */
23018   attr = dwarf2_attr (die, DW_AT_data_location, cu);
23019   if (attr_to_dynamic_prop (attr, die, cu, &prop))
23020     add_dyn_prop (DYN_PROP_DATA_LOCATION, prop, type, objfile);
23021
23022   if (dwarf2_per_objfile->die_type_hash == NULL)
23023     {
23024       dwarf2_per_objfile->die_type_hash =
23025         htab_create_alloc_ex (127,
23026                               per_cu_offset_and_type_hash,
23027                               per_cu_offset_and_type_eq,
23028                               NULL,
23029                               &objfile->objfile_obstack,
23030                               hashtab_obstack_allocate,
23031                               dummy_obstack_deallocate);
23032     }
23033
23034   ofs.per_cu = cu->per_cu;
23035   ofs.sect_off = die->sect_off;
23036   ofs.type = type;
23037   slot = (struct dwarf2_per_cu_offset_and_type **)
23038     htab_find_slot (dwarf2_per_objfile->die_type_hash, &ofs, INSERT);
23039   if (*slot)
23040     complaint (&symfile_complaints,
23041                _("A problem internal to GDB: DIE 0x%x has type already set"),
23042                to_underlying (die->sect_off));
23043   *slot = XOBNEW (&objfile->objfile_obstack,
23044                   struct dwarf2_per_cu_offset_and_type);
23045   **slot = ofs;
23046   return type;
23047 }
23048
23049 /* Look up the type for the die at SECT_OFF in PER_CU in die_type_hash,
23050    or return NULL if the die does not have a saved type.  */
23051
23052 static struct type *
23053 get_die_type_at_offset (sect_offset sect_off,
23054                         struct dwarf2_per_cu_data *per_cu)
23055 {
23056   struct dwarf2_per_cu_offset_and_type *slot, ofs;
23057
23058   if (dwarf2_per_objfile->die_type_hash == NULL)
23059     return NULL;
23060
23061   ofs.per_cu = per_cu;
23062   ofs.sect_off = sect_off;
23063   slot = ((struct dwarf2_per_cu_offset_and_type *)
23064           htab_find (dwarf2_per_objfile->die_type_hash, &ofs));
23065   if (slot)
23066     return slot->type;
23067   else
23068     return NULL;
23069 }
23070
23071 /* Look up the type for DIE in CU in die_type_hash,
23072    or return NULL if DIE does not have a saved type.  */
23073
23074 static struct type *
23075 get_die_type (struct die_info *die, struct dwarf2_cu *cu)
23076 {
23077   return get_die_type_at_offset (die->sect_off, cu->per_cu);
23078 }
23079
23080 /* Add a dependence relationship from CU to REF_PER_CU.  */
23081
23082 static void
23083 dwarf2_add_dependence (struct dwarf2_cu *cu,
23084                        struct dwarf2_per_cu_data *ref_per_cu)
23085 {
23086   void **slot;
23087
23088   if (cu->dependencies == NULL)
23089     cu->dependencies
23090       = htab_create_alloc_ex (5, htab_hash_pointer, htab_eq_pointer,
23091                               NULL, &cu->comp_unit_obstack,
23092                               hashtab_obstack_allocate,
23093                               dummy_obstack_deallocate);
23094
23095   slot = htab_find_slot (cu->dependencies, ref_per_cu, INSERT);
23096   if (*slot == NULL)
23097     *slot = ref_per_cu;
23098 }
23099
23100 /* Subroutine of dwarf2_mark to pass to htab_traverse.
23101    Set the mark field in every compilation unit in the
23102    cache that we must keep because we are keeping CU.  */
23103
23104 static int
23105 dwarf2_mark_helper (void **slot, void *data)
23106 {
23107   struct dwarf2_per_cu_data *per_cu;
23108
23109   per_cu = (struct dwarf2_per_cu_data *) *slot;
23110
23111   /* cu->dependencies references may not yet have been ever read if QUIT aborts
23112      reading of the chain.  As such dependencies remain valid it is not much
23113      useful to track and undo them during QUIT cleanups.  */
23114   if (per_cu->cu == NULL)
23115     return 1;
23116
23117   if (per_cu->cu->mark)
23118     return 1;
23119   per_cu->cu->mark = 1;
23120
23121   if (per_cu->cu->dependencies != NULL)
23122     htab_traverse (per_cu->cu->dependencies, dwarf2_mark_helper, NULL);
23123
23124   return 1;
23125 }
23126
23127 /* Set the mark field in CU and in every other compilation unit in the
23128    cache that we must keep because we are keeping CU.  */
23129
23130 static void
23131 dwarf2_mark (struct dwarf2_cu *cu)
23132 {
23133   if (cu->mark)
23134     return;
23135   cu->mark = 1;
23136   if (cu->dependencies != NULL)
23137     htab_traverse (cu->dependencies, dwarf2_mark_helper, NULL);
23138 }
23139
23140 static void
23141 dwarf2_clear_marks (struct dwarf2_per_cu_data *per_cu)
23142 {
23143   while (per_cu)
23144     {
23145       per_cu->cu->mark = 0;
23146       per_cu = per_cu->cu->read_in_chain;
23147     }
23148 }
23149
23150 /* Trivial hash function for partial_die_info: the hash value of a DIE
23151    is its offset in .debug_info for this objfile.  */
23152
23153 static hashval_t
23154 partial_die_hash (const void *item)
23155 {
23156   const struct partial_die_info *part_die
23157     = (const struct partial_die_info *) item;
23158
23159   return to_underlying (part_die->sect_off);
23160 }
23161
23162 /* Trivial comparison function for partial_die_info structures: two DIEs
23163    are equal if they have the same offset.  */
23164
23165 static int
23166 partial_die_eq (const void *item_lhs, const void *item_rhs)
23167 {
23168   const struct partial_die_info *part_die_lhs
23169     = (const struct partial_die_info *) item_lhs;
23170   const struct partial_die_info *part_die_rhs
23171     = (const struct partial_die_info *) item_rhs;
23172
23173   return part_die_lhs->sect_off == part_die_rhs->sect_off;
23174 }
23175
23176 static struct cmd_list_element *set_dwarf_cmdlist;
23177 static struct cmd_list_element *show_dwarf_cmdlist;
23178
23179 static void
23180 set_dwarf_cmd (char *args, int from_tty)
23181 {
23182   help_list (set_dwarf_cmdlist, "maintenance set dwarf ", all_commands,
23183              gdb_stdout);
23184 }
23185
23186 static void
23187 show_dwarf_cmd (char *args, int from_tty)
23188 {
23189   cmd_show_list (show_dwarf_cmdlist, from_tty, "");
23190 }
23191
23192 /* Free data associated with OBJFILE, if necessary.  */
23193
23194 static void
23195 dwarf2_per_objfile_free (struct objfile *objfile, void *d)
23196 {
23197   struct dwarf2_per_objfile *data = (struct dwarf2_per_objfile *) d;
23198   int ix;
23199
23200   /* Make sure we don't accidentally use dwarf2_per_objfile while
23201      cleaning up.  */
23202   dwarf2_per_objfile = NULL;
23203
23204   for (ix = 0; ix < data->n_comp_units; ++ix)
23205    VEC_free (dwarf2_per_cu_ptr, data->all_comp_units[ix]->imported_symtabs);
23206
23207   for (ix = 0; ix < data->n_type_units; ++ix)
23208     VEC_free (dwarf2_per_cu_ptr,
23209               data->all_type_units[ix]->per_cu.imported_symtabs);
23210   xfree (data->all_type_units);
23211
23212   VEC_free (dwarf2_section_info_def, data->types);
23213
23214   if (data->dwo_files)
23215     free_dwo_files (data->dwo_files, objfile);
23216   if (data->dwp_file)
23217     gdb_bfd_unref (data->dwp_file->dbfd);
23218
23219   if (data->dwz_file && data->dwz_file->dwz_bfd)
23220     gdb_bfd_unref (data->dwz_file->dwz_bfd);
23221 }
23222
23223 \f
23224 /* The "save gdb-index" command.  */
23225
23226 /* In-memory buffer to prepare data to be written later to a file.  */
23227 class data_buf
23228 {
23229 public:
23230   /* Copy DATA to the end of the buffer.  */
23231   template<typename T>
23232   void append_data (const T &data)
23233   {
23234     std::copy (reinterpret_cast<const gdb_byte *> (&data),
23235                reinterpret_cast<const gdb_byte *> (&data + 1),
23236                grow (sizeof (data)));
23237   }
23238
23239   /* Copy CSTR (a zero-terminated string) to the end of buffer.  The
23240      terminating zero is appended too.  */
23241   void append_cstr0 (const char *cstr)
23242   {
23243     const size_t size = strlen (cstr) + 1;
23244     std::copy (cstr, cstr + size, grow (size));
23245   }
23246
23247   /* Accept a host-format integer in VAL and append it to the buffer
23248      as a target-format integer which is LEN bytes long.  */
23249   void append_uint (size_t len, bfd_endian byte_order, ULONGEST val)
23250   {
23251     ::store_unsigned_integer (grow (len), len, byte_order, val);
23252   }
23253
23254   /* Return the size of the buffer.  */
23255   size_t size () const
23256   {
23257     return m_vec.size ();
23258   }
23259
23260   /* Write the buffer to FILE.  */
23261   void file_write (FILE *file) const
23262   {
23263     if (::fwrite (m_vec.data (), 1, m_vec.size (), file) != m_vec.size ())
23264       error (_("couldn't write data to file"));
23265   }
23266
23267 private:
23268   /* Grow SIZE bytes at the end of the buffer.  Returns a pointer to
23269      the start of the new block.  */
23270   gdb_byte *grow (size_t size)
23271   {
23272     m_vec.resize (m_vec.size () + size);
23273     return &*m_vec.end () - size;
23274   }
23275
23276   gdb::byte_vector m_vec;
23277 };
23278
23279 /* An entry in the symbol table.  */
23280 struct symtab_index_entry
23281 {
23282   /* The name of the symbol.  */
23283   const char *name;
23284   /* The offset of the name in the constant pool.  */
23285   offset_type index_offset;
23286   /* A sorted vector of the indices of all the CUs that hold an object
23287      of this name.  */
23288   std::vector<offset_type> cu_indices;
23289 };
23290
23291 /* The symbol table.  This is a power-of-2-sized hash table.  */
23292 struct mapped_symtab
23293 {
23294   mapped_symtab ()
23295   {
23296     data.resize (1024);
23297   }
23298
23299   offset_type n_elements = 0;
23300   std::vector<symtab_index_entry> data;
23301 };
23302
23303 /* Find a slot in SYMTAB for the symbol NAME.  Returns a reference to
23304    the slot.
23305    
23306    Function is used only during write_hash_table so no index format backward
23307    compatibility is needed.  */
23308
23309 static symtab_index_entry &
23310 find_slot (struct mapped_symtab *symtab, const char *name)
23311 {
23312   offset_type index, step, hash = mapped_index_string_hash (INT_MAX, name);
23313
23314   index = hash & (symtab->data.size () - 1);
23315   step = ((hash * 17) & (symtab->data.size () - 1)) | 1;
23316
23317   for (;;)
23318     {
23319       if (symtab->data[index].name == NULL
23320           || strcmp (name, symtab->data[index].name) == 0)
23321         return symtab->data[index];
23322       index = (index + step) & (symtab->data.size () - 1);
23323     }
23324 }
23325
23326 /* Expand SYMTAB's hash table.  */
23327
23328 static void
23329 hash_expand (struct mapped_symtab *symtab)
23330 {
23331   auto old_entries = std::move (symtab->data);
23332
23333   symtab->data.clear ();
23334   symtab->data.resize (old_entries.size () * 2);
23335
23336   for (auto &it : old_entries)
23337     if (it.name != NULL)
23338       {
23339         auto &ref = find_slot (symtab, it.name);
23340         ref = std::move (it);
23341       }
23342 }
23343
23344 /* Add an entry to SYMTAB.  NAME is the name of the symbol.
23345    CU_INDEX is the index of the CU in which the symbol appears.
23346    IS_STATIC is one if the symbol is static, otherwise zero (global).  */
23347
23348 static void
23349 add_index_entry (struct mapped_symtab *symtab, const char *name,
23350                  int is_static, gdb_index_symbol_kind kind,
23351                  offset_type cu_index)
23352 {
23353   offset_type cu_index_and_attrs;
23354
23355   ++symtab->n_elements;
23356   if (4 * symtab->n_elements / 3 >= symtab->data.size ())
23357     hash_expand (symtab);
23358
23359   symtab_index_entry &slot = find_slot (symtab, name);
23360   if (slot.name == NULL)
23361     {
23362       slot.name = name;
23363       /* index_offset is set later.  */
23364     }
23365
23366   cu_index_and_attrs = 0;
23367   DW2_GDB_INDEX_CU_SET_VALUE (cu_index_and_attrs, cu_index);
23368   DW2_GDB_INDEX_SYMBOL_STATIC_SET_VALUE (cu_index_and_attrs, is_static);
23369   DW2_GDB_INDEX_SYMBOL_KIND_SET_VALUE (cu_index_and_attrs, kind);
23370
23371   /* We don't want to record an index value twice as we want to avoid the
23372      duplication.
23373      We process all global symbols and then all static symbols
23374      (which would allow us to avoid the duplication by only having to check
23375      the last entry pushed), but a symbol could have multiple kinds in one CU.
23376      To keep things simple we don't worry about the duplication here and
23377      sort and uniqufy the list after we've processed all symbols.  */
23378   slot.cu_indices.push_back (cu_index_and_attrs);
23379 }
23380
23381 /* Sort and remove duplicates of all symbols' cu_indices lists.  */
23382
23383 static void
23384 uniquify_cu_indices (struct mapped_symtab *symtab)
23385 {
23386   for (auto &entry : symtab->data)
23387     {
23388       if (entry.name != NULL && !entry.cu_indices.empty ())
23389         {
23390           auto &cu_indices = entry.cu_indices;
23391           std::sort (cu_indices.begin (), cu_indices.end ());
23392           auto from = std::unique (cu_indices.begin (), cu_indices.end ());
23393           cu_indices.erase (from, cu_indices.end ());
23394         }
23395     }
23396 }
23397
23398 /* A form of 'const char *' suitable for container keys.  Only the
23399    pointer is stored.  The strings themselves are compared, not the
23400    pointers.  */
23401 class c_str_view
23402 {
23403 public:
23404   c_str_view (const char *cstr)
23405     : m_cstr (cstr)
23406   {}
23407
23408   bool operator== (const c_str_view &other) const
23409   {
23410     return strcmp (m_cstr, other.m_cstr) == 0;
23411   }
23412
23413 private:
23414   friend class c_str_view_hasher;
23415   const char *const m_cstr;
23416 };
23417
23418 /* A std::unordered_map::hasher for c_str_view that uses the right
23419    hash function for strings in a mapped index.  */
23420 class c_str_view_hasher
23421 {
23422 public:
23423   size_t operator () (const c_str_view &x) const
23424   {
23425     return mapped_index_string_hash (INT_MAX, x.m_cstr);
23426   }
23427 };
23428
23429 /* A std::unordered_map::hasher for std::vector<>.  */
23430 template<typename T>
23431 class vector_hasher
23432 {
23433 public:
23434   size_t operator () (const std::vector<T> &key) const
23435   {
23436     return iterative_hash (key.data (),
23437                            sizeof (key.front ()) * key.size (), 0);
23438   }
23439 };
23440
23441 /* Write the mapped hash table SYMTAB to the data buffer OUTPUT, with
23442    constant pool entries going into the data buffer CPOOL.  */
23443
23444 static void
23445 write_hash_table (mapped_symtab *symtab, data_buf &output, data_buf &cpool)
23446 {
23447   {
23448     /* Elements are sorted vectors of the indices of all the CUs that
23449        hold an object of this name.  */
23450     std::unordered_map<std::vector<offset_type>, offset_type,
23451                        vector_hasher<offset_type>>
23452       symbol_hash_table;
23453
23454     /* We add all the index vectors to the constant pool first, to
23455        ensure alignment is ok.  */
23456     for (symtab_index_entry &entry : symtab->data)
23457       {
23458         if (entry.name == NULL)
23459           continue;
23460         gdb_assert (entry.index_offset == 0);
23461
23462         /* Finding before inserting is faster than always trying to
23463            insert, because inserting always allocates a node, does the
23464            lookup, and then destroys the new node if another node
23465            already had the same key.  C++17 try_emplace will avoid
23466            this.  */
23467         const auto found
23468           = symbol_hash_table.find (entry.cu_indices);
23469         if (found != symbol_hash_table.end ())
23470           {
23471             entry.index_offset = found->second;
23472             continue;
23473           }
23474
23475         symbol_hash_table.emplace (entry.cu_indices, cpool.size ());
23476         entry.index_offset = cpool.size ();
23477         cpool.append_data (MAYBE_SWAP (entry.cu_indices.size ()));
23478         for (const auto index : entry.cu_indices)
23479           cpool.append_data (MAYBE_SWAP (index));
23480       }
23481   }
23482
23483   /* Now write out the hash table.  */
23484   std::unordered_map<c_str_view, offset_type, c_str_view_hasher> str_table;
23485   for (const auto &entry : symtab->data)
23486     {
23487       offset_type str_off, vec_off;
23488
23489       if (entry.name != NULL)
23490         {
23491           const auto insertpair = str_table.emplace (entry.name, cpool.size ());
23492           if (insertpair.second)
23493             cpool.append_cstr0 (entry.name);
23494           str_off = insertpair.first->second;
23495           vec_off = entry.index_offset;
23496         }
23497       else
23498         {
23499           /* While 0 is a valid constant pool index, it is not valid
23500              to have 0 for both offsets.  */
23501           str_off = 0;
23502           vec_off = 0;
23503         }
23504
23505       output.append_data (MAYBE_SWAP (str_off));
23506       output.append_data (MAYBE_SWAP (vec_off));
23507     }
23508 }
23509
23510 typedef std::unordered_map<partial_symtab *, unsigned int> psym_index_map;
23511
23512 /* Helper struct for building the address table.  */
23513 struct addrmap_index_data
23514 {
23515   addrmap_index_data (data_buf &addr_vec_, psym_index_map &cu_index_htab_)
23516     : addr_vec (addr_vec_), cu_index_htab (cu_index_htab_)
23517   {}
23518
23519   struct objfile *objfile;
23520   data_buf &addr_vec;
23521   psym_index_map &cu_index_htab;
23522
23523   /* Non-zero if the previous_* fields are valid.
23524      We can't write an entry until we see the next entry (since it is only then
23525      that we know the end of the entry).  */
23526   int previous_valid;
23527   /* Index of the CU in the table of all CUs in the index file.  */
23528   unsigned int previous_cu_index;
23529   /* Start address of the CU.  */
23530   CORE_ADDR previous_cu_start;
23531 };
23532
23533 /* Write an address entry to ADDR_VEC.  */
23534
23535 static void
23536 add_address_entry (struct objfile *objfile, data_buf &addr_vec,
23537                    CORE_ADDR start, CORE_ADDR end, unsigned int cu_index)
23538 {
23539   CORE_ADDR baseaddr;
23540
23541   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
23542
23543   addr_vec.append_uint (8, BFD_ENDIAN_LITTLE, start - baseaddr);
23544   addr_vec.append_uint (8, BFD_ENDIAN_LITTLE, end - baseaddr);
23545   addr_vec.append_data (MAYBE_SWAP (cu_index));
23546 }
23547
23548 /* Worker function for traversing an addrmap to build the address table.  */
23549
23550 static int
23551 add_address_entry_worker (void *datap, CORE_ADDR start_addr, void *obj)
23552 {
23553   struct addrmap_index_data *data = (struct addrmap_index_data *) datap;
23554   struct partial_symtab *pst = (struct partial_symtab *) obj;
23555
23556   if (data->previous_valid)
23557     add_address_entry (data->objfile, data->addr_vec,
23558                        data->previous_cu_start, start_addr,
23559                        data->previous_cu_index);
23560
23561   data->previous_cu_start = start_addr;
23562   if (pst != NULL)
23563     {
23564       const auto it = data->cu_index_htab.find (pst);
23565       gdb_assert (it != data->cu_index_htab.cend ());
23566       data->previous_cu_index = it->second;
23567       data->previous_valid = 1;
23568     }
23569   else
23570     data->previous_valid = 0;
23571
23572   return 0;
23573 }
23574
23575 /* Write OBJFILE's address map to ADDR_VEC.
23576    CU_INDEX_HTAB is used to map addrmap entries to their CU indices
23577    in the index file.  */
23578
23579 static void
23580 write_address_map (struct objfile *objfile, data_buf &addr_vec,
23581                    psym_index_map &cu_index_htab)
23582 {
23583   struct addrmap_index_data addrmap_index_data (addr_vec, cu_index_htab);
23584
23585   /* When writing the address table, we have to cope with the fact that
23586      the addrmap iterator only provides the start of a region; we have to
23587      wait until the next invocation to get the start of the next region.  */
23588
23589   addrmap_index_data.objfile = objfile;
23590   addrmap_index_data.previous_valid = 0;
23591
23592   addrmap_foreach (objfile->psymtabs_addrmap, add_address_entry_worker,
23593                    &addrmap_index_data);
23594
23595   /* It's highly unlikely the last entry (end address = 0xff...ff)
23596      is valid, but we should still handle it.
23597      The end address is recorded as the start of the next region, but that
23598      doesn't work here.  To cope we pass 0xff...ff, this is a rare situation
23599      anyway.  */
23600   if (addrmap_index_data.previous_valid)
23601     add_address_entry (objfile, addr_vec,
23602                        addrmap_index_data.previous_cu_start, (CORE_ADDR) -1,
23603                        addrmap_index_data.previous_cu_index);
23604 }
23605
23606 /* Return the symbol kind of PSYM.  */
23607
23608 static gdb_index_symbol_kind
23609 symbol_kind (struct partial_symbol *psym)
23610 {
23611   domain_enum domain = PSYMBOL_DOMAIN (psym);
23612   enum address_class aclass = PSYMBOL_CLASS (psym);
23613
23614   switch (domain)
23615     {
23616     case VAR_DOMAIN:
23617       switch (aclass)
23618         {
23619         case LOC_BLOCK:
23620           return GDB_INDEX_SYMBOL_KIND_FUNCTION;
23621         case LOC_TYPEDEF:
23622           return GDB_INDEX_SYMBOL_KIND_TYPE;
23623         case LOC_COMPUTED:
23624         case LOC_CONST_BYTES:
23625         case LOC_OPTIMIZED_OUT:
23626         case LOC_STATIC:
23627           return GDB_INDEX_SYMBOL_KIND_VARIABLE;
23628         case LOC_CONST:
23629           /* Note: It's currently impossible to recognize psyms as enum values
23630              short of reading the type info.  For now punt.  */
23631           return GDB_INDEX_SYMBOL_KIND_VARIABLE;
23632         default:
23633           /* There are other LOC_FOO values that one might want to classify
23634              as variables, but dwarf2read.c doesn't currently use them.  */
23635           return GDB_INDEX_SYMBOL_KIND_OTHER;
23636         }
23637     case STRUCT_DOMAIN:
23638       return GDB_INDEX_SYMBOL_KIND_TYPE;
23639     default:
23640       return GDB_INDEX_SYMBOL_KIND_OTHER;
23641     }
23642 }
23643
23644 /* Add a list of partial symbols to SYMTAB.  */
23645
23646 static void
23647 write_psymbols (struct mapped_symtab *symtab,
23648                 std::unordered_set<partial_symbol *> &psyms_seen,
23649                 struct partial_symbol **psymp,
23650                 int count,
23651                 offset_type cu_index,
23652                 int is_static)
23653 {
23654   for (; count-- > 0; ++psymp)
23655     {
23656       struct partial_symbol *psym = *psymp;
23657
23658       if (SYMBOL_LANGUAGE (psym) == language_ada)
23659         error (_("Ada is not currently supported by the index"));
23660
23661       /* Only add a given psymbol once.  */
23662       if (psyms_seen.insert (psym).second)
23663         {
23664           gdb_index_symbol_kind kind = symbol_kind (psym);
23665
23666           add_index_entry (symtab, SYMBOL_SEARCH_NAME (psym),
23667                            is_static, kind, cu_index);
23668         }
23669     }
23670 }
23671
23672 /* A helper struct used when iterating over debug_types.  */
23673 struct signatured_type_index_data
23674 {
23675   signatured_type_index_data (data_buf &types_list_,
23676                               std::unordered_set<partial_symbol *> &psyms_seen_)
23677     : types_list (types_list_), psyms_seen (psyms_seen_)
23678   {}
23679
23680   struct objfile *objfile;
23681   struct mapped_symtab *symtab;
23682   data_buf &types_list;
23683   std::unordered_set<partial_symbol *> &psyms_seen;
23684   int cu_index;
23685 };
23686
23687 /* A helper function that writes a single signatured_type to an
23688    obstack.  */
23689
23690 static int
23691 write_one_signatured_type (void **slot, void *d)
23692 {
23693   struct signatured_type_index_data *info
23694     = (struct signatured_type_index_data *) d;
23695   struct signatured_type *entry = (struct signatured_type *) *slot;
23696   struct partial_symtab *psymtab = entry->per_cu.v.psymtab;
23697
23698   write_psymbols (info->symtab,
23699                   info->psyms_seen,
23700                   info->objfile->global_psymbols.list
23701                   + psymtab->globals_offset,
23702                   psymtab->n_global_syms, info->cu_index,
23703                   0);
23704   write_psymbols (info->symtab,
23705                   info->psyms_seen,
23706                   info->objfile->static_psymbols.list
23707                   + psymtab->statics_offset,
23708                   psymtab->n_static_syms, info->cu_index,
23709                   1);
23710
23711   info->types_list.append_uint (8, BFD_ENDIAN_LITTLE,
23712                                 to_underlying (entry->per_cu.sect_off));
23713   info->types_list.append_uint (8, BFD_ENDIAN_LITTLE,
23714                                 to_underlying (entry->type_offset_in_tu));
23715   info->types_list.append_uint (8, BFD_ENDIAN_LITTLE, entry->signature);
23716
23717   ++info->cu_index;
23718
23719   return 1;
23720 }
23721
23722 /* Recurse into all "included" dependencies and count their symbols as
23723    if they appeared in this psymtab.  */
23724
23725 static void
23726 recursively_count_psymbols (struct partial_symtab *psymtab,
23727                             size_t &psyms_seen)
23728 {
23729   for (int i = 0; i < psymtab->number_of_dependencies; ++i)
23730     if (psymtab->dependencies[i]->user != NULL)
23731       recursively_count_psymbols (psymtab->dependencies[i],
23732                                   psyms_seen);
23733
23734   psyms_seen += psymtab->n_global_syms;
23735   psyms_seen += psymtab->n_static_syms;
23736 }
23737
23738 /* Recurse into all "included" dependencies and write their symbols as
23739    if they appeared in this psymtab.  */
23740
23741 static void
23742 recursively_write_psymbols (struct objfile *objfile,
23743                             struct partial_symtab *psymtab,
23744                             struct mapped_symtab *symtab,
23745                             std::unordered_set<partial_symbol *> &psyms_seen,
23746                             offset_type cu_index)
23747 {
23748   int i;
23749
23750   for (i = 0; i < psymtab->number_of_dependencies; ++i)
23751     if (psymtab->dependencies[i]->user != NULL)
23752       recursively_write_psymbols (objfile, psymtab->dependencies[i],
23753                                   symtab, psyms_seen, cu_index);
23754
23755   write_psymbols (symtab,
23756                   psyms_seen,
23757                   objfile->global_psymbols.list + psymtab->globals_offset,
23758                   psymtab->n_global_syms, cu_index,
23759                   0);
23760   write_psymbols (symtab,
23761                   psyms_seen,
23762                   objfile->static_psymbols.list + psymtab->statics_offset,
23763                   psymtab->n_static_syms, cu_index,
23764                   1);
23765 }
23766
23767 /* Closes FILE on scope exit.  */
23768 struct file_closer
23769 {
23770   explicit file_closer (FILE *file)
23771     : m_file (file)
23772   {}
23773
23774   ~file_closer ()
23775   { fclose (m_file); }
23776
23777 private:
23778   FILE *m_file;
23779 };
23780
23781 /* Create an index file for OBJFILE in the directory DIR.  */
23782
23783 static void
23784 write_psymtabs_to_index (struct objfile *objfile, const char *dir)
23785 {
23786   if (dwarf2_per_objfile->using_index)
23787     error (_("Cannot use an index to create the index"));
23788
23789   if (VEC_length (dwarf2_section_info_def, dwarf2_per_objfile->types) > 1)
23790     error (_("Cannot make an index when the file has multiple .debug_types sections"));
23791
23792   if (!objfile->psymtabs || !objfile->psymtabs_addrmap)
23793     return;
23794
23795   struct stat st;
23796   if (stat (objfile_name (objfile), &st) < 0)
23797     perror_with_name (objfile_name (objfile));
23798
23799   std::string filename (std::string (dir) + SLASH_STRING
23800                         + lbasename (objfile_name (objfile)) + INDEX_SUFFIX);
23801
23802   FILE *out_file = gdb_fopen_cloexec (filename.c_str (), "wb");
23803   if (!out_file)
23804     error (_("Can't open `%s' for writing"), filename.c_str ());
23805
23806   /* Order matters here; we want FILE to be closed before FILENAME is
23807      unlinked, because on MS-Windows one cannot delete a file that is
23808      still open.  (Don't call anything here that might throw until
23809      file_closer is created.)  */
23810   gdb::unlinker unlink_file (filename.c_str ());
23811   file_closer close_out_file (out_file);
23812
23813   mapped_symtab symtab;
23814   data_buf cu_list;
23815
23816   /* While we're scanning CU's create a table that maps a psymtab pointer
23817      (which is what addrmap records) to its index (which is what is recorded
23818      in the index file).  This will later be needed to write the address
23819      table.  */
23820   psym_index_map cu_index_htab;
23821   cu_index_htab.reserve (dwarf2_per_objfile->n_comp_units);
23822
23823   /* The CU list is already sorted, so we don't need to do additional
23824      work here.  Also, the debug_types entries do not appear in
23825      all_comp_units, but only in their own hash table.  */
23826
23827   /* The psyms_seen set is potentially going to be largish (~40k
23828      elements when indexing a -g3 build of GDB itself).  Estimate the
23829      number of elements in order to avoid too many rehashes, which
23830      require rebuilding buckets and thus many trips to
23831      malloc/free.  */
23832   size_t psyms_count = 0;
23833   for (int i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
23834     {
23835       struct dwarf2_per_cu_data *per_cu
23836         = dwarf2_per_objfile->all_comp_units[i];
23837       struct partial_symtab *psymtab = per_cu->v.psymtab;
23838
23839       if (psymtab != NULL && psymtab->user == NULL)
23840         recursively_count_psymbols (psymtab, psyms_count);
23841     }
23842   /* Generating an index for gdb itself shows a ratio of
23843      TOTAL_SEEN_SYMS/UNIQUE_SYMS or ~5.  4 seems like a good bet.  */
23844   std::unordered_set<partial_symbol *> psyms_seen (psyms_count / 4);
23845   for (int i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
23846     {
23847       struct dwarf2_per_cu_data *per_cu
23848         = dwarf2_per_objfile->all_comp_units[i];
23849       struct partial_symtab *psymtab = per_cu->v.psymtab;
23850
23851       /* CU of a shared file from 'dwz -m' may be unused by this main file.
23852          It may be referenced from a local scope but in such case it does not
23853          need to be present in .gdb_index.  */
23854       if (psymtab == NULL)
23855         continue;
23856
23857       if (psymtab->user == NULL)
23858         recursively_write_psymbols (objfile, psymtab, &symtab,
23859                                     psyms_seen, i);
23860
23861       const auto insertpair = cu_index_htab.emplace (psymtab, i);
23862       gdb_assert (insertpair.second);
23863
23864       cu_list.append_uint (8, BFD_ENDIAN_LITTLE,
23865                            to_underlying (per_cu->sect_off));
23866       cu_list.append_uint (8, BFD_ENDIAN_LITTLE, per_cu->length);
23867     }
23868
23869   /* Dump the address map.  */
23870   data_buf addr_vec;
23871   write_address_map (objfile, addr_vec, cu_index_htab);
23872
23873   /* Write out the .debug_type entries, if any.  */
23874   data_buf types_cu_list;
23875   if (dwarf2_per_objfile->signatured_types)
23876     {
23877       signatured_type_index_data sig_data (types_cu_list,
23878                                            psyms_seen);
23879
23880       sig_data.objfile = objfile;
23881       sig_data.symtab = &symtab;
23882       sig_data.cu_index = dwarf2_per_objfile->n_comp_units;
23883       htab_traverse_noresize (dwarf2_per_objfile->signatured_types,
23884                               write_one_signatured_type, &sig_data);
23885     }
23886
23887   /* Now that we've processed all symbols we can shrink their cu_indices
23888      lists.  */
23889   uniquify_cu_indices (&symtab);
23890
23891   data_buf symtab_vec, constant_pool;
23892   write_hash_table (&symtab, symtab_vec, constant_pool);
23893
23894   data_buf contents;
23895   const offset_type size_of_contents = 6 * sizeof (offset_type);
23896   offset_type total_len = size_of_contents;
23897
23898   /* The version number.  */
23899   contents.append_data (MAYBE_SWAP (8));
23900
23901   /* The offset of the CU list from the start of the file.  */
23902   contents.append_data (MAYBE_SWAP (total_len));
23903   total_len += cu_list.size ();
23904
23905   /* The offset of the types CU list from the start of the file.  */
23906   contents.append_data (MAYBE_SWAP (total_len));
23907   total_len += types_cu_list.size ();
23908
23909   /* The offset of the address table from the start of the file.  */
23910   contents.append_data (MAYBE_SWAP (total_len));
23911   total_len += addr_vec.size ();
23912
23913   /* The offset of the symbol table from the start of the file.  */
23914   contents.append_data (MAYBE_SWAP (total_len));
23915   total_len += symtab_vec.size ();
23916
23917   /* The offset of the constant pool from the start of the file.  */
23918   contents.append_data (MAYBE_SWAP (total_len));
23919   total_len += constant_pool.size ();
23920
23921   gdb_assert (contents.size () == size_of_contents);
23922
23923   contents.file_write (out_file);
23924   cu_list.file_write (out_file);
23925   types_cu_list.file_write (out_file);
23926   addr_vec.file_write (out_file);
23927   symtab_vec.file_write (out_file);
23928   constant_pool.file_write (out_file);
23929
23930   /* We want to keep the file.  */
23931   unlink_file.keep ();
23932 }
23933
23934 /* Implementation of the `save gdb-index' command.
23935    
23936    Note that the file format used by this command is documented in the
23937    GDB manual.  Any changes here must be documented there.  */
23938
23939 static void
23940 save_gdb_index_command (char *arg, int from_tty)
23941 {
23942   struct objfile *objfile;
23943
23944   if (!arg || !*arg)
23945     error (_("usage: save gdb-index DIRECTORY"));
23946
23947   ALL_OBJFILES (objfile)
23948   {
23949     struct stat st;
23950
23951     /* If the objfile does not correspond to an actual file, skip it.  */
23952     if (stat (objfile_name (objfile), &st) < 0)
23953       continue;
23954
23955     dwarf2_per_objfile
23956       = (struct dwarf2_per_objfile *) objfile_data (objfile,
23957                                                     dwarf2_objfile_data_key);
23958     if (dwarf2_per_objfile)
23959       {
23960
23961         TRY
23962           {
23963             write_psymtabs_to_index (objfile, arg);
23964           }
23965         CATCH (except, RETURN_MASK_ERROR)
23966           {
23967             exception_fprintf (gdb_stderr, except,
23968                                _("Error while writing index for `%s': "),
23969                                objfile_name (objfile));
23970           }
23971         END_CATCH
23972       }
23973   }
23974 }
23975
23976 \f
23977
23978 int dwarf_always_disassemble;
23979
23980 static void
23981 show_dwarf_always_disassemble (struct ui_file *file, int from_tty,
23982                                struct cmd_list_element *c, const char *value)
23983 {
23984   fprintf_filtered (file,
23985                     _("Whether to always disassemble "
23986                       "DWARF expressions is %s.\n"),
23987                     value);
23988 }
23989
23990 static void
23991 show_check_physname (struct ui_file *file, int from_tty,
23992                      struct cmd_list_element *c, const char *value)
23993 {
23994   fprintf_filtered (file,
23995                     _("Whether to check \"physname\" is %s.\n"),
23996                     value);
23997 }
23998
23999 void _initialize_dwarf2_read (void);
24000
24001 void
24002 _initialize_dwarf2_read (void)
24003 {
24004   struct cmd_list_element *c;
24005
24006   dwarf2_objfile_data_key
24007     = register_objfile_data_with_cleanup (NULL, dwarf2_per_objfile_free);
24008
24009   add_prefix_cmd ("dwarf", class_maintenance, set_dwarf_cmd, _("\
24010 Set DWARF specific variables.\n\
24011 Configure DWARF variables such as the cache size"),
24012                   &set_dwarf_cmdlist, "maintenance set dwarf ",
24013                   0/*allow-unknown*/, &maintenance_set_cmdlist);
24014
24015   add_prefix_cmd ("dwarf", class_maintenance, show_dwarf_cmd, _("\
24016 Show DWARF specific variables\n\
24017 Show DWARF variables such as the cache size"),
24018                   &show_dwarf_cmdlist, "maintenance show dwarf ",
24019                   0/*allow-unknown*/, &maintenance_show_cmdlist);
24020
24021   add_setshow_zinteger_cmd ("max-cache-age", class_obscure,
24022                             &dwarf_max_cache_age, _("\
24023 Set the upper bound on the age of cached DWARF compilation units."), _("\
24024 Show the upper bound on the age of cached DWARF compilation units."), _("\
24025 A higher limit means that cached compilation units will be stored\n\
24026 in memory longer, and more total memory will be used.  Zero disables\n\
24027 caching, which can slow down startup."),
24028                             NULL,
24029                             show_dwarf_max_cache_age,
24030                             &set_dwarf_cmdlist,
24031                             &show_dwarf_cmdlist);
24032
24033   add_setshow_boolean_cmd ("always-disassemble", class_obscure,
24034                            &dwarf_always_disassemble, _("\
24035 Set whether `info address' always disassembles DWARF expressions."), _("\
24036 Show whether `info address' always disassembles DWARF expressions."), _("\
24037 When enabled, DWARF expressions are always printed in an assembly-like\n\
24038 syntax.  When disabled, expressions will be printed in a more\n\
24039 conversational style, when possible."),
24040                            NULL,
24041                            show_dwarf_always_disassemble,
24042                            &set_dwarf_cmdlist,
24043                            &show_dwarf_cmdlist);
24044
24045   add_setshow_zuinteger_cmd ("dwarf-read", no_class, &dwarf_read_debug, _("\
24046 Set debugging of the DWARF reader."), _("\
24047 Show debugging of the DWARF reader."), _("\
24048 When enabled (non-zero), debugging messages are printed during DWARF\n\
24049 reading and symtab expansion.  A value of 1 (one) provides basic\n\
24050 information.  A value greater than 1 provides more verbose information."),
24051                             NULL,
24052                             NULL,
24053                             &setdebuglist, &showdebuglist);
24054
24055   add_setshow_zuinteger_cmd ("dwarf-die", no_class, &dwarf_die_debug, _("\
24056 Set debugging of the DWARF DIE reader."), _("\
24057 Show debugging of the DWARF DIE reader."), _("\
24058 When enabled (non-zero), DIEs are dumped after they are read in.\n\
24059 The value is the maximum depth to print."),
24060                              NULL,
24061                              NULL,
24062                              &setdebuglist, &showdebuglist);
24063
24064   add_setshow_zuinteger_cmd ("dwarf-line", no_class, &dwarf_line_debug, _("\
24065 Set debugging of the dwarf line reader."), _("\
24066 Show debugging of the dwarf line reader."), _("\
24067 When enabled (non-zero), line number entries are dumped as they are read in.\n\
24068 A value of 1 (one) provides basic information.\n\
24069 A value greater than 1 provides more verbose information."),
24070                              NULL,
24071                              NULL,
24072                              &setdebuglist, &showdebuglist);
24073
24074   add_setshow_boolean_cmd ("check-physname", no_class, &check_physname, _("\
24075 Set cross-checking of \"physname\" code against demangler."), _("\
24076 Show cross-checking of \"physname\" code against demangler."), _("\
24077 When enabled, GDB's internal \"physname\" code is checked against\n\
24078 the demangler."),
24079                            NULL, show_check_physname,
24080                            &setdebuglist, &showdebuglist);
24081
24082   add_setshow_boolean_cmd ("use-deprecated-index-sections",
24083                            no_class, &use_deprecated_index_sections, _("\
24084 Set whether to use deprecated gdb_index sections."), _("\
24085 Show whether to use deprecated gdb_index sections."), _("\
24086 When enabled, deprecated .gdb_index sections are used anyway.\n\
24087 Normally they are ignored either because of a missing feature or\n\
24088 performance issue.\n\
24089 Warning: This option must be enabled before gdb reads the file."),
24090                            NULL,
24091                            NULL,
24092                            &setlist, &showlist);
24093
24094   c = add_cmd ("gdb-index", class_files, save_gdb_index_command,
24095                _("\
24096 Save a gdb-index file.\n\
24097 Usage: save gdb-index DIRECTORY"),
24098                &save_cmdlist);
24099   set_cmd_completer (c, filename_completer);
24100
24101   dwarf2_locexpr_index = register_symbol_computed_impl (LOC_COMPUTED,
24102                                                         &dwarf2_locexpr_funcs);
24103   dwarf2_loclist_index = register_symbol_computed_impl (LOC_COMPUTED,
24104                                                         &dwarf2_loclist_funcs);
24105
24106   dwarf2_locexpr_block_index = register_symbol_block_impl (LOC_BLOCK,
24107                                         &dwarf2_block_frame_base_locexpr_funcs);
24108   dwarf2_loclist_block_index = register_symbol_block_impl (LOC_BLOCK,
24109                                         &dwarf2_block_frame_base_loclist_funcs);
24110 }