Stop assuming no-debug-info variables have type int
[external/binutils.git] / gdb / dwarf2read.c
1 /* DWARF 2 debugging format support for GDB.
2
3    Copyright (C) 1994-2017 Free Software Foundation, Inc.
4
5    Adapted by Gary Funck (gary@intrepid.com), Intrepid Technology,
6    Inc.  with support from Florida State University (under contract
7    with the Ada Joint Program Office), and Silicon Graphics, Inc.
8    Initial contribution by Brent Benson, Harris Computer Systems, Inc.,
9    based on Fred Fish's (Cygnus Support) implementation of DWARF 1
10    support.
11
12    This file is part of GDB.
13
14    This program is free software; you can redistribute it and/or modify
15    it under the terms of the GNU General Public License as published by
16    the Free Software Foundation; either version 3 of the License, or
17    (at your option) any later version.
18
19    This program is distributed in the hope that it will be useful,
20    but WITHOUT ANY WARRANTY; without even the implied warranty of
21    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
22    GNU General Public License for more details.
23
24    You should have received a copy of the GNU General Public License
25    along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
26
27 /* FIXME: Various die-reading functions need to be more careful with
28    reading off the end of the section.
29    E.g., load_partial_dies, read_partial_die.  */
30
31 #include "defs.h"
32 #include "bfd.h"
33 #include "elf-bfd.h"
34 #include "symtab.h"
35 #include "gdbtypes.h"
36 #include "objfiles.h"
37 #include "dwarf2.h"
38 #include "buildsym.h"
39 #include "demangle.h"
40 #include "gdb-demangle.h"
41 #include "expression.h"
42 #include "filenames.h"  /* for DOSish file names */
43 #include "macrotab.h"
44 #include "language.h"
45 #include "complaints.h"
46 #include "bcache.h"
47 #include "dwarf2expr.h"
48 #include "dwarf2loc.h"
49 #include "cp-support.h"
50 #include "hashtab.h"
51 #include "command.h"
52 #include "gdbcmd.h"
53 #include "block.h"
54 #include "addrmap.h"
55 #include "typeprint.h"
56 #include "psympriv.h"
57 #include <sys/stat.h>
58 #include "completer.h"
59 #include "vec.h"
60 #include "c-lang.h"
61 #include "go-lang.h"
62 #include "valprint.h"
63 #include "gdbcore.h" /* for gnutarget */
64 #include "gdb/gdb-index.h"
65 #include <ctype.h>
66 #include "gdb_bfd.h"
67 #include "f-lang.h"
68 #include "source.h"
69 #include "filestuff.h"
70 #include "build-id.h"
71 #include "namespace.h"
72 #include "common/gdb_unlinker.h"
73 #include "common/function-view.h"
74 #include "common/gdb_optional.h"
75 #include "common/underlying.h"
76 #include "common/byte-vector.h"
77 #include "filename-seen-cache.h"
78 #include <fcntl.h>
79 #include <sys/types.h>
80 #include <algorithm>
81 #include <unordered_set>
82 #include <unordered_map>
83
84 typedef struct symbol *symbolp;
85 DEF_VEC_P (symbolp);
86
87 /* When == 1, print basic high level tracing messages.
88    When > 1, be more verbose.
89    This is in contrast to the low level DIE reading of dwarf_die_debug.  */
90 static unsigned int dwarf_read_debug = 0;
91
92 /* When non-zero, dump DIEs after they are read in.  */
93 static unsigned int dwarf_die_debug = 0;
94
95 /* When non-zero, dump line number entries as they are read in.  */
96 static unsigned int dwarf_line_debug = 0;
97
98 /* When non-zero, cross-check physname against demangler.  */
99 static int check_physname = 0;
100
101 /* When non-zero, do not reject deprecated .gdb_index sections.  */
102 static int use_deprecated_index_sections = 0;
103
104 static const struct objfile_data *dwarf2_objfile_data_key;
105
106 /* The "aclass" indices for various kinds of computed DWARF symbols.  */
107
108 static int dwarf2_locexpr_index;
109 static int dwarf2_loclist_index;
110 static int dwarf2_locexpr_block_index;
111 static int dwarf2_loclist_block_index;
112
113 /* A descriptor for dwarf sections.
114
115    S.ASECTION, SIZE are typically initialized when the objfile is first
116    scanned.  BUFFER, READIN are filled in later when the section is read.
117    If the section contained compressed data then SIZE is updated to record
118    the uncompressed size of the section.
119
120    DWP file format V2 introduces a wrinkle that is easiest to handle by
121    creating the concept of virtual sections contained within a real section.
122    In DWP V2 the sections of the input DWO files are concatenated together
123    into one section, but section offsets are kept relative to the original
124    input section.
125    If this is a virtual dwp-v2 section, S.CONTAINING_SECTION is a backlink to
126    the real section this "virtual" section is contained in, and BUFFER,SIZE
127    describe the virtual section.  */
128
129 struct dwarf2_section_info
130 {
131   union
132   {
133     /* If this is a real section, the bfd section.  */
134     asection *section;
135     /* If this is a virtual section, pointer to the containing ("real")
136        section.  */
137     struct dwarf2_section_info *containing_section;
138   } s;
139   /* Pointer to section data, only valid if readin.  */
140   const gdb_byte *buffer;
141   /* The size of the section, real or virtual.  */
142   bfd_size_type size;
143   /* If this is a virtual section, the offset in the real section.
144      Only valid if is_virtual.  */
145   bfd_size_type virtual_offset;
146   /* True if we have tried to read this section.  */
147   char readin;
148   /* True if this is a virtual section, False otherwise.
149      This specifies which of s.section and s.containing_section to use.  */
150   char is_virtual;
151 };
152
153 typedef struct dwarf2_section_info dwarf2_section_info_def;
154 DEF_VEC_O (dwarf2_section_info_def);
155
156 /* All offsets in the index are of this type.  It must be
157    architecture-independent.  */
158 typedef uint32_t offset_type;
159
160 DEF_VEC_I (offset_type);
161
162 /* Ensure only legit values are used.  */
163 #define DW2_GDB_INDEX_SYMBOL_STATIC_SET_VALUE(cu_index, value) \
164   do { \
165     gdb_assert ((unsigned int) (value) <= 1); \
166     GDB_INDEX_SYMBOL_STATIC_SET_VALUE((cu_index), (value)); \
167   } while (0)
168
169 /* Ensure only legit values are used.  */
170 #define DW2_GDB_INDEX_SYMBOL_KIND_SET_VALUE(cu_index, value) \
171   do { \
172     gdb_assert ((value) >= GDB_INDEX_SYMBOL_KIND_TYPE \
173                 && (value) <= GDB_INDEX_SYMBOL_KIND_OTHER); \
174     GDB_INDEX_SYMBOL_KIND_SET_VALUE((cu_index), (value)); \
175   } while (0)
176
177 /* Ensure we don't use more than the alloted nuber of bits for the CU.  */
178 #define DW2_GDB_INDEX_CU_SET_VALUE(cu_index, value) \
179   do { \
180     gdb_assert (((value) & ~GDB_INDEX_CU_MASK) == 0); \
181     GDB_INDEX_CU_SET_VALUE((cu_index), (value)); \
182   } while (0)
183
184 /* A description of the mapped index.  The file format is described in
185    a comment by the code that writes the index.  */
186 struct mapped_index
187 {
188   /* Index data format version.  */
189   int version;
190
191   /* The total length of the buffer.  */
192   off_t total_size;
193
194   /* A pointer to the address table data.  */
195   const gdb_byte *address_table;
196
197   /* Size of the address table data in bytes.  */
198   offset_type address_table_size;
199
200   /* The symbol table, implemented as a hash table.  */
201   const offset_type *symbol_table;
202
203   /* Size in slots, each slot is 2 offset_types.  */
204   offset_type symbol_table_slots;
205
206   /* A pointer to the constant pool.  */
207   const char *constant_pool;
208 };
209
210 typedef struct dwarf2_per_cu_data *dwarf2_per_cu_ptr;
211 DEF_VEC_P (dwarf2_per_cu_ptr);
212
213 struct tu_stats
214 {
215   int nr_uniq_abbrev_tables;
216   int nr_symtabs;
217   int nr_symtab_sharers;
218   int nr_stmt_less_type_units;
219   int nr_all_type_units_reallocs;
220 };
221
222 /* Collection of data recorded per objfile.
223    This hangs off of dwarf2_objfile_data_key.  */
224
225 struct dwarf2_per_objfile
226 {
227   /* Construct a dwarf2_per_objfile for OBJFILE.  NAMES points to the
228      dwarf2 section names, or is NULL if the standard ELF names are
229      used.  */
230   dwarf2_per_objfile (struct objfile *objfile,
231                       const dwarf2_debug_sections *names);
232
233   ~dwarf2_per_objfile ();
234
235   /* Disable copy.  */
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   /* Table containing all filenames.  This is an optional because the
354      table is lazily constructed on first access.  */
355   gdb::optional<filename_seen_cache> filenames_cache;
356 };
357
358 static struct dwarf2_per_objfile *dwarf2_per_objfile;
359
360 /* Default names of the debugging sections.  */
361
362 /* Note that if the debugging section has been compressed, it might
363    have a name like .zdebug_info.  */
364
365 static const struct dwarf2_debug_sections dwarf2_elf_names =
366 {
367   { ".debug_info", ".zdebug_info" },
368   { ".debug_abbrev", ".zdebug_abbrev" },
369   { ".debug_line", ".zdebug_line" },
370   { ".debug_loc", ".zdebug_loc" },
371   { ".debug_loclists", ".zdebug_loclists" },
372   { ".debug_macinfo", ".zdebug_macinfo" },
373   { ".debug_macro", ".zdebug_macro" },
374   { ".debug_str", ".zdebug_str" },
375   { ".debug_line_str", ".zdebug_line_str" },
376   { ".debug_ranges", ".zdebug_ranges" },
377   { ".debug_rnglists", ".zdebug_rnglists" },
378   { ".debug_types", ".zdebug_types" },
379   { ".debug_addr", ".zdebug_addr" },
380   { ".debug_frame", ".zdebug_frame" },
381   { ".eh_frame", NULL },
382   { ".gdb_index", ".zgdb_index" },
383   23
384 };
385
386 /* List of DWO/DWP sections.  */
387
388 static const struct dwop_section_names
389 {
390   struct dwarf2_section_names abbrev_dwo;
391   struct dwarf2_section_names info_dwo;
392   struct dwarf2_section_names line_dwo;
393   struct dwarf2_section_names loc_dwo;
394   struct dwarf2_section_names loclists_dwo;
395   struct dwarf2_section_names macinfo_dwo;
396   struct dwarf2_section_names macro_dwo;
397   struct dwarf2_section_names str_dwo;
398   struct dwarf2_section_names str_offsets_dwo;
399   struct dwarf2_section_names types_dwo;
400   struct dwarf2_section_names cu_index;
401   struct dwarf2_section_names tu_index;
402 }
403 dwop_section_names =
404 {
405   { ".debug_abbrev.dwo", ".zdebug_abbrev.dwo" },
406   { ".debug_info.dwo", ".zdebug_info.dwo" },
407   { ".debug_line.dwo", ".zdebug_line.dwo" },
408   { ".debug_loc.dwo", ".zdebug_loc.dwo" },
409   { ".debug_loclists.dwo", ".zdebug_loclists.dwo" },
410   { ".debug_macinfo.dwo", ".zdebug_macinfo.dwo" },
411   { ".debug_macro.dwo", ".zdebug_macro.dwo" },
412   { ".debug_str.dwo", ".zdebug_str.dwo" },
413   { ".debug_str_offsets.dwo", ".zdebug_str_offsets.dwo" },
414   { ".debug_types.dwo", ".zdebug_types.dwo" },
415   { ".debug_cu_index", ".zdebug_cu_index" },
416   { ".debug_tu_index", ".zdebug_tu_index" },
417 };
418
419 /* local data types */
420
421 /* The data in a compilation unit header, after target2host
422    translation, looks like this.  */
423 struct comp_unit_head
424 {
425   unsigned int length;
426   short version;
427   unsigned char addr_size;
428   unsigned char signed_addr_p;
429   sect_offset abbrev_sect_off;
430
431   /* Size of file offsets; either 4 or 8.  */
432   unsigned int offset_size;
433
434   /* Size of the length field; either 4 or 12.  */
435   unsigned int initial_length_size;
436
437   enum dwarf_unit_type unit_type;
438
439   /* Offset to the first byte of this compilation unit header in the
440      .debug_info section, for resolving relative reference dies.  */
441   sect_offset sect_off;
442
443   /* Offset to first die in this cu from the start of the cu.
444      This will be the first byte following the compilation unit header.  */
445   cu_offset first_die_cu_offset;
446
447   /* 64-bit signature of this type unit - it is valid only for
448      UNIT_TYPE DW_UT_type.  */
449   ULONGEST signature;
450
451   /* For types, offset in the type's DIE of the type defined by this TU.  */
452   cu_offset type_cu_offset_in_tu;
453 };
454
455 /* Type used for delaying computation of method physnames.
456    See comments for compute_delayed_physnames.  */
457 struct delayed_method_info
458 {
459   /* The type to which the method is attached, i.e., its parent class.  */
460   struct type *type;
461
462   /* The index of the method in the type's function fieldlists.  */
463   int fnfield_index;
464
465   /* The index of the method in the fieldlist.  */
466   int index;
467
468   /* The name of the DIE.  */
469   const char *name;
470
471   /*  The DIE associated with this method.  */
472   struct die_info *die;
473 };
474
475 typedef struct delayed_method_info delayed_method_info;
476 DEF_VEC_O (delayed_method_info);
477
478 /* Internal state when decoding a particular compilation unit.  */
479 struct dwarf2_cu
480 {
481   /* The objfile containing this compilation unit.  */
482   struct objfile *objfile;
483
484   /* The header of the compilation unit.  */
485   struct comp_unit_head header;
486
487   /* Base address of this compilation unit.  */
488   CORE_ADDR base_address;
489
490   /* Non-zero if base_address has been set.  */
491   int base_known;
492
493   /* The language we are debugging.  */
494   enum language language;
495   const struct language_defn *language_defn;
496
497   const char *producer;
498
499   /* The generic symbol table building routines have separate lists for
500      file scope symbols and all all other scopes (local scopes).  So
501      we need to select the right one to pass to add_symbol_to_list().
502      We do it by keeping a pointer to the correct list in list_in_scope.
503
504      FIXME: The original dwarf code just treated the file scope as the
505      first local scope, and all other local scopes as nested local
506      scopes, and worked fine.  Check to see if we really need to
507      distinguish these in buildsym.c.  */
508   struct pending **list_in_scope;
509
510   /* The abbrev table for this CU.
511      Normally this points to the abbrev table in the objfile.
512      But if DWO_UNIT is non-NULL this is the abbrev table in the DWO file.  */
513   struct abbrev_table *abbrev_table;
514
515   /* Hash table holding all the loaded partial DIEs
516      with partial_die->offset.SECT_OFF as hash.  */
517   htab_t partial_dies;
518
519   /* Storage for things with the same lifetime as this read-in compilation
520      unit, including partial DIEs.  */
521   struct obstack comp_unit_obstack;
522
523   /* When multiple dwarf2_cu structures are living in memory, this field
524      chains them all together, so that they can be released efficiently.
525      We will probably also want a generation counter so that most-recently-used
526      compilation units are cached...  */
527   struct dwarf2_per_cu_data *read_in_chain;
528
529   /* Backlink to our per_cu entry.  */
530   struct dwarf2_per_cu_data *per_cu;
531
532   /* How many compilation units ago was this CU last referenced?  */
533   int last_used;
534
535   /* A hash table of DIE cu_offset for following references with
536      die_info->offset.sect_off as hash.  */
537   htab_t die_hash;
538
539   /* Full DIEs if read in.  */
540   struct die_info *dies;
541
542   /* A set of pointers to dwarf2_per_cu_data objects for compilation
543      units referenced by this one.  Only set during full symbol processing;
544      partial symbol tables do not have dependencies.  */
545   htab_t dependencies;
546
547   /* Header data from the line table, during full symbol processing.  */
548   struct line_header *line_header;
549   /* Non-NULL if LINE_HEADER is owned by this DWARF_CU.  Otherwise,
550      it's owned by dwarf2_per_objfile::line_header_hash.  If non-NULL,
551      this is the DW_TAG_compile_unit die for this CU.  We'll hold on
552      to the line header as long as this DIE is being processed.  See
553      process_die_scope.  */
554   die_info *line_header_die_owner;
555
556   /* A list of methods which need to have physnames computed
557      after all type information has been read.  */
558   VEC (delayed_method_info) *method_list;
559
560   /* To be copied to symtab->call_site_htab.  */
561   htab_t call_site_htab;
562
563   /* Non-NULL if this CU came from a DWO file.
564      There is an invariant here that is important to remember:
565      Except for attributes copied from the top level DIE in the "main"
566      (or "stub") file in preparation for reading the DWO file
567      (e.g., DW_AT_GNU_addr_base), we KISS: there is only *one* CU.
568      Either there isn't a DWO file (in which case this is NULL and the point
569      is moot), or there is and either we're not going to read it (in which
570      case this is NULL) or there is and we are reading it (in which case this
571      is non-NULL).  */
572   struct dwo_unit *dwo_unit;
573
574   /* The DW_AT_addr_base attribute if present, zero otherwise
575      (zero is a valid value though).
576      Note this value comes from the Fission stub CU/TU's DIE.  */
577   ULONGEST addr_base;
578
579   /* The DW_AT_ranges_base attribute if present, zero otherwise
580      (zero is a valid value though).
581      Note this value comes from the Fission stub CU/TU's DIE.
582      Also note that the value is zero in the non-DWO case so this value can
583      be used without needing to know whether DWO files are in use or not.
584      N.B. This does not apply to DW_AT_ranges appearing in
585      DW_TAG_compile_unit dies.  This is a bit of a wart, consider if ever
586      DW_AT_ranges appeared in the DW_TAG_compile_unit of DWO DIEs: then
587      DW_AT_ranges_base *would* have to be applied, and we'd have to care
588      whether the DW_AT_ranges attribute came from the skeleton or DWO.  */
589   ULONGEST ranges_base;
590
591   /* Mark used when releasing cached dies.  */
592   unsigned int mark : 1;
593
594   /* This CU references .debug_loc.  See the symtab->locations_valid field.
595      This test is imperfect as there may exist optimized debug code not using
596      any location list and still facing inlining issues if handled as
597      unoptimized code.  For a future better test see GCC PR other/32998.  */
598   unsigned int has_loclist : 1;
599
600   /* These cache the results for producer_is_* fields.  CHECKED_PRODUCER is set
601      if all the producer_is_* fields are valid.  This information is cached
602      because profiling CU expansion showed excessive time spent in
603      producer_is_gxx_lt_4_6.  */
604   unsigned int checked_producer : 1;
605   unsigned int producer_is_gxx_lt_4_6 : 1;
606   unsigned int producer_is_gcc_lt_4_3 : 1;
607   unsigned int producer_is_icc : 1;
608
609   /* When set, the file that we're processing is known to have
610      debugging info for C++ namespaces.  GCC 3.3.x did not produce
611      this information, but later versions do.  */
612
613   unsigned int processing_has_namespace_info : 1;
614 };
615
616 /* Persistent data held for a compilation unit, even when not
617    processing it.  We put a pointer to this structure in the
618    read_symtab_private field of the psymtab.  */
619
620 struct dwarf2_per_cu_data
621 {
622   /* The start offset and length of this compilation unit.
623      NOTE: Unlike comp_unit_head.length, this length includes
624      initial_length_size.
625      If the DIE refers to a DWO file, this is always of the original die,
626      not the DWO file.  */
627   sect_offset sect_off;
628   unsigned int length;
629
630   /* DWARF standard version this data has been read from (such as 4 or 5).  */
631   short dwarf_version;
632
633   /* Flag indicating this compilation unit will be read in before
634      any of the current compilation units are processed.  */
635   unsigned int queued : 1;
636
637   /* This flag will be set when reading partial DIEs if we need to load
638      absolutely all DIEs for this compilation unit, instead of just the ones
639      we think are interesting.  It gets set if we look for a DIE in the
640      hash table and don't find it.  */
641   unsigned int load_all_dies : 1;
642
643   /* Non-zero if this CU is from .debug_types.
644      Struct dwarf2_per_cu_data is contained in struct signatured_type iff
645      this is non-zero.  */
646   unsigned int is_debug_types : 1;
647
648   /* Non-zero if this CU is from the .dwz file.  */
649   unsigned int is_dwz : 1;
650
651   /* Non-zero if reading a TU directly from a DWO file, bypassing the stub.
652      This flag is only valid if is_debug_types is true.
653      We can't read a CU directly from a DWO file: There are required
654      attributes in the stub.  */
655   unsigned int reading_dwo_directly : 1;
656
657   /* Non-zero if the TU has been read.
658      This is used to assist the "Stay in DWO Optimization" for Fission:
659      When reading a DWO, it's faster to read TUs from the DWO instead of
660      fetching them from random other DWOs (due to comdat folding).
661      If the TU has already been read, the optimization is unnecessary
662      (and unwise - we don't want to change where gdb thinks the TU lives
663      "midflight").
664      This flag is only valid if is_debug_types is true.  */
665   unsigned int tu_read : 1;
666
667   /* The section this CU/TU lives in.
668      If the DIE refers to a DWO file, this is always the original die,
669      not the DWO file.  */
670   struct dwarf2_section_info *section;
671
672   /* Set to non-NULL iff this CU is currently loaded.  When it gets freed out
673      of the CU cache it gets reset to NULL again.  This is left as NULL for
674      dummy CUs (a CU header, but nothing else).  */
675   struct dwarf2_cu *cu;
676
677   /* The corresponding objfile.
678      Normally we can get the objfile from dwarf2_per_objfile.
679      However we can enter this file with just a "per_cu" handle.  */
680   struct objfile *objfile;
681
682   /* When dwarf2_per_objfile->using_index is true, the 'quick' field
683      is active.  Otherwise, the 'psymtab' field is active.  */
684   union
685   {
686     /* The partial symbol table associated with this compilation unit,
687        or NULL for unread partial units.  */
688     struct partial_symtab *psymtab;
689
690     /* Data needed by the "quick" functions.  */
691     struct dwarf2_per_cu_quick_data *quick;
692   } v;
693
694   /* The CUs we import using DW_TAG_imported_unit.  This is filled in
695      while reading psymtabs, used to compute the psymtab dependencies,
696      and then cleared.  Then it is filled in again while reading full
697      symbols, and only deleted when the objfile is destroyed.
698
699      This is also used to work around a difference between the way gold
700      generates .gdb_index version <=7 and the way gdb does.  Arguably this
701      is a gold bug.  For symbols coming from TUs, gold records in the index
702      the CU that includes the TU instead of the TU itself.  This breaks
703      dw2_lookup_symbol: It assumes that if the index says symbol X lives
704      in CU/TU Y, then one need only expand Y and a subsequent lookup in Y
705      will find X.  Alas TUs live in their own symtab, so after expanding CU Y
706      we need to look in TU Z to find X.  Fortunately, this is akin to
707      DW_TAG_imported_unit, so we just use the same mechanism: For
708      .gdb_index version <=7 this also records the TUs that the CU referred
709      to.  Concurrently with this change gdb was modified to emit version 8
710      indices so we only pay a price for gold generated indices.
711      http://sourceware.org/bugzilla/show_bug.cgi?id=15021.  */
712   VEC (dwarf2_per_cu_ptr) *imported_symtabs;
713 };
714
715 /* Entry in the signatured_types hash table.  */
716
717 struct signatured_type
718 {
719   /* The "per_cu" object of this type.
720      This struct is used iff per_cu.is_debug_types.
721      N.B.: This is the first member so that it's easy to convert pointers
722      between them.  */
723   struct dwarf2_per_cu_data per_cu;
724
725   /* The type's signature.  */
726   ULONGEST signature;
727
728   /* Offset in the TU of the type's DIE, as read from the TU header.
729      If this TU is a DWO stub and the definition lives in a DWO file
730      (specified by DW_AT_GNU_dwo_name), this value is unusable.  */
731   cu_offset type_offset_in_tu;
732
733   /* Offset in the section of the type's DIE.
734      If the definition lives in a DWO file, this is the offset in the
735      .debug_types.dwo section.
736      The value is zero until the actual value is known.
737      Zero is otherwise not a valid section offset.  */
738   sect_offset type_offset_in_section;
739
740   /* Type units are grouped by their DW_AT_stmt_list entry so that they
741      can share them.  This points to the containing symtab.  */
742   struct type_unit_group *type_unit_group;
743
744   /* The type.
745      The first time we encounter this type we fully read it in and install it
746      in the symbol tables.  Subsequent times we only need the type.  */
747   struct type *type;
748
749   /* Containing DWO unit.
750      This field is valid iff per_cu.reading_dwo_directly.  */
751   struct dwo_unit *dwo_unit;
752 };
753
754 typedef struct signatured_type *sig_type_ptr;
755 DEF_VEC_P (sig_type_ptr);
756
757 /* A struct that can be used as a hash key for tables based on DW_AT_stmt_list.
758    This includes type_unit_group and quick_file_names.  */
759
760 struct stmt_list_hash
761 {
762   /* The DWO unit this table is from or NULL if there is none.  */
763   struct dwo_unit *dwo_unit;
764
765   /* Offset in .debug_line or .debug_line.dwo.  */
766   sect_offset line_sect_off;
767 };
768
769 /* Each element of dwarf2_per_objfile->type_unit_groups is a pointer to
770    an object of this type.  */
771
772 struct type_unit_group
773 {
774   /* dwarf2read.c's main "handle" on a TU symtab.
775      To simplify things we create an artificial CU that "includes" all the
776      type units using this stmt_list so that the rest of the code still has
777      a "per_cu" handle on the symtab.
778      This PER_CU is recognized by having no section.  */
779 #define IS_TYPE_UNIT_GROUP(per_cu) ((per_cu)->section == NULL)
780   struct dwarf2_per_cu_data per_cu;
781
782   /* The TUs that share this DW_AT_stmt_list entry.
783      This is added to while parsing type units to build partial symtabs,
784      and is deleted afterwards and not used again.  */
785   VEC (sig_type_ptr) *tus;
786
787   /* The compunit symtab.
788      Type units in a group needn't all be defined in the same source file,
789      so we create an essentially anonymous symtab as the compunit symtab.  */
790   struct compunit_symtab *compunit_symtab;
791
792   /* The data used to construct the hash key.  */
793   struct stmt_list_hash hash;
794
795   /* The number of symtabs from the line header.
796      The value here must match line_header.num_file_names.  */
797   unsigned int num_symtabs;
798
799   /* The symbol tables for this TU (obtained from the files listed in
800      DW_AT_stmt_list).
801      WARNING: The order of entries here must match the order of entries
802      in the line header.  After the first TU using this type_unit_group, the
803      line header for the subsequent TUs is recreated from this.  This is done
804      because we need to use the same symtabs for each TU using the same
805      DW_AT_stmt_list value.  Also note that symtabs may be repeated here,
806      there's no guarantee the line header doesn't have duplicate entries.  */
807   struct symtab **symtabs;
808 };
809
810 /* These sections are what may appear in a (real or virtual) DWO file.  */
811
812 struct dwo_sections
813 {
814   struct dwarf2_section_info abbrev;
815   struct dwarf2_section_info line;
816   struct dwarf2_section_info loc;
817   struct dwarf2_section_info loclists;
818   struct dwarf2_section_info macinfo;
819   struct dwarf2_section_info macro;
820   struct dwarf2_section_info str;
821   struct dwarf2_section_info str_offsets;
822   /* In the case of a virtual DWO file, these two are unused.  */
823   struct dwarf2_section_info info;
824   VEC (dwarf2_section_info_def) *types;
825 };
826
827 /* CUs/TUs in DWP/DWO files.  */
828
829 struct dwo_unit
830 {
831   /* Backlink to the containing struct dwo_file.  */
832   struct dwo_file *dwo_file;
833
834   /* The "id" that distinguishes this CU/TU.
835      .debug_info calls this "dwo_id", .debug_types calls this "signature".
836      Since signatures came first, we stick with it for consistency.  */
837   ULONGEST signature;
838
839   /* The section this CU/TU lives in, in the DWO file.  */
840   struct dwarf2_section_info *section;
841
842   /* Same as dwarf2_per_cu_data:{sect_off,length} but in the DWO section.  */
843   sect_offset sect_off;
844   unsigned int length;
845
846   /* For types, offset in the type's DIE of the type defined by this TU.  */
847   cu_offset type_offset_in_tu;
848 };
849
850 /* include/dwarf2.h defines the DWP section codes.
851    It defines a max value but it doesn't define a min value, which we
852    use for error checking, so provide one.  */
853
854 enum dwp_v2_section_ids
855 {
856   DW_SECT_MIN = 1
857 };
858
859 /* Data for one DWO file.
860
861    This includes virtual DWO files (a virtual DWO file is a DWO file as it
862    appears in a DWP file).  DWP files don't really have DWO files per se -
863    comdat folding of types "loses" the DWO file they came from, and from
864    a high level view DWP files appear to contain a mass of random types.
865    However, to maintain consistency with the non-DWP case we pretend DWP
866    files contain virtual DWO files, and we assign each TU with one virtual
867    DWO file (generally based on the line and abbrev section offsets -
868    a heuristic that seems to work in practice).  */
869
870 struct dwo_file
871 {
872   /* The DW_AT_GNU_dwo_name attribute.
873      For virtual DWO files the name is constructed from the section offsets
874      of abbrev,line,loc,str_offsets so that we combine virtual DWO files
875      from related CU+TUs.  */
876   const char *dwo_name;
877
878   /* The DW_AT_comp_dir attribute.  */
879   const char *comp_dir;
880
881   /* The bfd, when the file is open.  Otherwise this is NULL.
882      This is unused(NULL) for virtual DWO files where we use dwp_file.dbfd.  */
883   bfd *dbfd;
884
885   /* The sections that make up this DWO file.
886      Remember that for virtual DWO files in DWP V2, these are virtual
887      sections (for lack of a better name).  */
888   struct dwo_sections sections;
889
890   /* The CUs in the file.
891      Each element is a struct dwo_unit. Multiple CUs per DWO are supported as
892      an extension to handle LLVM's Link Time Optimization output (where
893      multiple source files may be compiled into a single object/dwo pair). */
894   htab_t cus;
895
896   /* Table of TUs in the file.
897      Each element is a struct dwo_unit.  */
898   htab_t tus;
899 };
900
901 /* These sections are what may appear in a DWP file.  */
902
903 struct dwp_sections
904 {
905   /* These are used by both DWP version 1 and 2.  */
906   struct dwarf2_section_info str;
907   struct dwarf2_section_info cu_index;
908   struct dwarf2_section_info tu_index;
909
910   /* These are only used by DWP version 2 files.
911      In DWP version 1 the .debug_info.dwo, .debug_types.dwo, and other
912      sections are referenced by section number, and are not recorded here.
913      In DWP version 2 there is at most one copy of all these sections, each
914      section being (effectively) comprised of the concatenation of all of the
915      individual sections that exist in the version 1 format.
916      To keep the code simple we treat each of these concatenated pieces as a
917      section itself (a virtual section?).  */
918   struct dwarf2_section_info abbrev;
919   struct dwarf2_section_info info;
920   struct dwarf2_section_info line;
921   struct dwarf2_section_info loc;
922   struct dwarf2_section_info macinfo;
923   struct dwarf2_section_info macro;
924   struct dwarf2_section_info str_offsets;
925   struct dwarf2_section_info types;
926 };
927
928 /* These sections are what may appear in a virtual DWO file in DWP version 1.
929    A virtual DWO file is a DWO file as it appears in a DWP file.  */
930
931 struct virtual_v1_dwo_sections
932 {
933   struct dwarf2_section_info abbrev;
934   struct dwarf2_section_info line;
935   struct dwarf2_section_info loc;
936   struct dwarf2_section_info macinfo;
937   struct dwarf2_section_info macro;
938   struct dwarf2_section_info str_offsets;
939   /* Each DWP hash table entry records one CU or one TU.
940      That is recorded here, and copied to dwo_unit.section.  */
941   struct dwarf2_section_info info_or_types;
942 };
943
944 /* Similar to virtual_v1_dwo_sections, but for DWP version 2.
945    In version 2, the sections of the DWO files are concatenated together
946    and stored in one section of that name.  Thus each ELF section contains
947    several "virtual" sections.  */
948
949 struct virtual_v2_dwo_sections
950 {
951   bfd_size_type abbrev_offset;
952   bfd_size_type abbrev_size;
953
954   bfd_size_type line_offset;
955   bfd_size_type line_size;
956
957   bfd_size_type loc_offset;
958   bfd_size_type loc_size;
959
960   bfd_size_type macinfo_offset;
961   bfd_size_type macinfo_size;
962
963   bfd_size_type macro_offset;
964   bfd_size_type macro_size;
965
966   bfd_size_type str_offsets_offset;
967   bfd_size_type str_offsets_size;
968
969   /* Each DWP hash table entry records one CU or one TU.
970      That is recorded here, and copied to dwo_unit.section.  */
971   bfd_size_type info_or_types_offset;
972   bfd_size_type info_or_types_size;
973 };
974
975 /* Contents of DWP hash tables.  */
976
977 struct dwp_hash_table
978 {
979   uint32_t version, nr_columns;
980   uint32_t nr_units, nr_slots;
981   const gdb_byte *hash_table, *unit_table;
982   union
983   {
984     struct
985     {
986       const gdb_byte *indices;
987     } v1;
988     struct
989     {
990       /* This is indexed by column number and gives the id of the section
991          in that column.  */
992 #define MAX_NR_V2_DWO_SECTIONS \
993   (1 /* .debug_info or .debug_types */ \
994    + 1 /* .debug_abbrev */ \
995    + 1 /* .debug_line */ \
996    + 1 /* .debug_loc */ \
997    + 1 /* .debug_str_offsets */ \
998    + 1 /* .debug_macro or .debug_macinfo */)
999       int section_ids[MAX_NR_V2_DWO_SECTIONS];
1000       const gdb_byte *offsets;
1001       const gdb_byte *sizes;
1002     } v2;
1003   } section_pool;
1004 };
1005
1006 /* Data for one DWP file.  */
1007
1008 struct dwp_file
1009 {
1010   /* Name of the file.  */
1011   const char *name;
1012
1013   /* File format version.  */
1014   int version;
1015
1016   /* The bfd.  */
1017   bfd *dbfd;
1018
1019   /* Section info for this file.  */
1020   struct dwp_sections sections;
1021
1022   /* Table of CUs in the file.  */
1023   const struct dwp_hash_table *cus;
1024
1025   /* Table of TUs in the file.  */
1026   const struct dwp_hash_table *tus;
1027
1028   /* Tables of loaded CUs/TUs.  Each entry is a struct dwo_unit *.  */
1029   htab_t loaded_cus;
1030   htab_t loaded_tus;
1031
1032   /* Table to map ELF section numbers to their sections.
1033      This is only needed for the DWP V1 file format.  */
1034   unsigned int num_sections;
1035   asection **elf_sections;
1036 };
1037
1038 /* This represents a '.dwz' file.  */
1039
1040 struct dwz_file
1041 {
1042   /* A dwz file can only contain a few sections.  */
1043   struct dwarf2_section_info abbrev;
1044   struct dwarf2_section_info info;
1045   struct dwarf2_section_info str;
1046   struct dwarf2_section_info line;
1047   struct dwarf2_section_info macro;
1048   struct dwarf2_section_info gdb_index;
1049
1050   /* The dwz's BFD.  */
1051   bfd *dwz_bfd;
1052 };
1053
1054 /* Struct used to pass misc. parameters to read_die_and_children, et
1055    al.  which are used for both .debug_info and .debug_types dies.
1056    All parameters here are unchanging for the life of the call.  This
1057    struct exists to abstract away the constant parameters of die reading.  */
1058
1059 struct die_reader_specs
1060 {
1061   /* The bfd of die_section.  */
1062   bfd* abfd;
1063
1064   /* The CU of the DIE we are parsing.  */
1065   struct dwarf2_cu *cu;
1066
1067   /* Non-NULL if reading a DWO file (including one packaged into a DWP).  */
1068   struct dwo_file *dwo_file;
1069
1070   /* The section the die comes from.
1071      This is either .debug_info or .debug_types, or the .dwo variants.  */
1072   struct dwarf2_section_info *die_section;
1073
1074   /* die_section->buffer.  */
1075   const gdb_byte *buffer;
1076
1077   /* The end of the buffer.  */
1078   const gdb_byte *buffer_end;
1079
1080   /* The value of the DW_AT_comp_dir attribute.  */
1081   const char *comp_dir;
1082 };
1083
1084 /* Type of function passed to init_cutu_and_read_dies, et.al.  */
1085 typedef void (die_reader_func_ftype) (const struct die_reader_specs *reader,
1086                                       const gdb_byte *info_ptr,
1087                                       struct die_info *comp_unit_die,
1088                                       int has_children,
1089                                       void *data);
1090
1091 /* A 1-based directory index.  This is a strong typedef to prevent
1092    accidentally using a directory index as a 0-based index into an
1093    array/vector.  */
1094 enum class dir_index : unsigned int {};
1095
1096 /* Likewise, a 1-based file name index.  */
1097 enum class file_name_index : unsigned int {};
1098
1099 struct file_entry
1100 {
1101   file_entry () = default;
1102
1103   file_entry (const char *name_, dir_index d_index_,
1104               unsigned int mod_time_, unsigned int length_)
1105     : name (name_),
1106       d_index (d_index_),
1107       mod_time (mod_time_),
1108       length (length_)
1109   {}
1110
1111   /* Return the include directory at D_INDEX stored in LH.  Returns
1112      NULL if D_INDEX is out of bounds.  */
1113   const char *include_dir (const line_header *lh) const;
1114
1115   /* The file name.  Note this is an observing pointer.  The memory is
1116      owned by debug_line_buffer.  */
1117   const char *name {};
1118
1119   /* The directory index (1-based).  */
1120   dir_index d_index {};
1121
1122   unsigned int mod_time {};
1123
1124   unsigned int length {};
1125
1126   /* True if referenced by the Line Number Program.  */
1127   bool included_p {};
1128
1129   /* The associated symbol table, if any.  */
1130   struct symtab *symtab {};
1131 };
1132
1133 /* The line number information for a compilation unit (found in the
1134    .debug_line section) begins with a "statement program header",
1135    which contains the following information.  */
1136 struct line_header
1137 {
1138   line_header ()
1139     : offset_in_dwz {}
1140   {}
1141
1142   /* Add an entry to the include directory table.  */
1143   void add_include_dir (const char *include_dir);
1144
1145   /* Add an entry to the file name table.  */
1146   void add_file_name (const char *name, dir_index d_index,
1147                       unsigned int mod_time, unsigned int length);
1148
1149   /* Return the include dir at INDEX (1-based).  Returns NULL if INDEX
1150      is out of bounds.  */
1151   const char *include_dir_at (dir_index index) const
1152   {
1153     /* Convert directory index number (1-based) to vector index
1154        (0-based).  */
1155     size_t vec_index = to_underlying (index) - 1;
1156
1157     if (vec_index >= include_dirs.size ())
1158       return NULL;
1159     return include_dirs[vec_index];
1160   }
1161
1162   /* Return the file name at INDEX (1-based).  Returns NULL if INDEX
1163      is out of bounds.  */
1164   file_entry *file_name_at (file_name_index index)
1165   {
1166     /* Convert file name index number (1-based) to vector index
1167        (0-based).  */
1168     size_t vec_index = to_underlying (index) - 1;
1169
1170     if (vec_index >= file_names.size ())
1171       return NULL;
1172     return &file_names[vec_index];
1173   }
1174
1175   /* Const version of the above.  */
1176   const file_entry *file_name_at (unsigned int index) const
1177   {
1178     if (index >= file_names.size ())
1179       return NULL;
1180     return &file_names[index];
1181   }
1182
1183   /* Offset of line number information in .debug_line section.  */
1184   sect_offset sect_off {};
1185
1186   /* OFFSET is for struct dwz_file associated with dwarf2_per_objfile.  */
1187   unsigned offset_in_dwz : 1; /* Can't initialize bitfields in-class.  */
1188
1189   unsigned int total_length {};
1190   unsigned short version {};
1191   unsigned int header_length {};
1192   unsigned char minimum_instruction_length {};
1193   unsigned char maximum_ops_per_instruction {};
1194   unsigned char default_is_stmt {};
1195   int line_base {};
1196   unsigned char line_range {};
1197   unsigned char opcode_base {};
1198
1199   /* standard_opcode_lengths[i] is the number of operands for the
1200      standard opcode whose value is i.  This means that
1201      standard_opcode_lengths[0] is unused, and the last meaningful
1202      element is standard_opcode_lengths[opcode_base - 1].  */
1203   std::unique_ptr<unsigned char[]> standard_opcode_lengths;
1204
1205   /* The include_directories table.  Note these are observing
1206      pointers.  The memory is owned by debug_line_buffer.  */
1207   std::vector<const char *> include_dirs;
1208
1209   /* The file_names table.  */
1210   std::vector<file_entry> file_names;
1211
1212   /* The start and end of the statement program following this
1213      header.  These point into dwarf2_per_objfile->line_buffer.  */
1214   const gdb_byte *statement_program_start {}, *statement_program_end {};
1215 };
1216
1217 typedef std::unique_ptr<line_header> line_header_up;
1218
1219 const char *
1220 file_entry::include_dir (const line_header *lh) const
1221 {
1222   return lh->include_dir_at (d_index);
1223 }
1224
1225 /* When we construct a partial symbol table entry we only
1226    need this much information.  */
1227 struct partial_die_info
1228   {
1229     /* Offset of this DIE.  */
1230     sect_offset sect_off;
1231
1232     /* DWARF-2 tag for this DIE.  */
1233     ENUM_BITFIELD(dwarf_tag) tag : 16;
1234
1235     /* Assorted flags describing the data found in this DIE.  */
1236     unsigned int has_children : 1;
1237     unsigned int is_external : 1;
1238     unsigned int is_declaration : 1;
1239     unsigned int has_type : 1;
1240     unsigned int has_specification : 1;
1241     unsigned int has_pc_info : 1;
1242     unsigned int may_be_inlined : 1;
1243
1244     /* This DIE has been marked DW_AT_main_subprogram.  */
1245     unsigned int main_subprogram : 1;
1246
1247     /* Flag set if the SCOPE field of this structure has been
1248        computed.  */
1249     unsigned int scope_set : 1;
1250
1251     /* Flag set if the DIE has a byte_size attribute.  */
1252     unsigned int has_byte_size : 1;
1253
1254     /* Flag set if the DIE has a DW_AT_const_value attribute.  */
1255     unsigned int has_const_value : 1;
1256
1257     /* Flag set if any of the DIE's children are template arguments.  */
1258     unsigned int has_template_arguments : 1;
1259
1260     /* Flag set if fixup_partial_die has been called on this die.  */
1261     unsigned int fixup_called : 1;
1262
1263     /* Flag set if DW_TAG_imported_unit uses DW_FORM_GNU_ref_alt.  */
1264     unsigned int is_dwz : 1;
1265
1266     /* Flag set if spec_offset uses DW_FORM_GNU_ref_alt.  */
1267     unsigned int spec_is_dwz : 1;
1268
1269     /* The name of this DIE.  Normally the value of DW_AT_name, but
1270        sometimes a default name for unnamed DIEs.  */
1271     const char *name;
1272
1273     /* The linkage name, if present.  */
1274     const char *linkage_name;
1275
1276     /* The scope to prepend to our children.  This is generally
1277        allocated on the comp_unit_obstack, so will disappear
1278        when this compilation unit leaves the cache.  */
1279     const char *scope;
1280
1281     /* Some data associated with the partial DIE.  The tag determines
1282        which field is live.  */
1283     union
1284     {
1285       /* The location description associated with this DIE, if any.  */
1286       struct dwarf_block *locdesc;
1287       /* The offset of an import, for DW_TAG_imported_unit.  */
1288       sect_offset sect_off;
1289     } d;
1290
1291     /* If HAS_PC_INFO, the PC range associated with this DIE.  */
1292     CORE_ADDR lowpc;
1293     CORE_ADDR highpc;
1294
1295     /* Pointer into the info_buffer (or types_buffer) pointing at the target of
1296        DW_AT_sibling, if any.  */
1297     /* NOTE: This member isn't strictly necessary, read_partial_die could
1298        return DW_AT_sibling values to its caller load_partial_dies.  */
1299     const gdb_byte *sibling;
1300
1301     /* If HAS_SPECIFICATION, the offset of the DIE referred to by
1302        DW_AT_specification (or DW_AT_abstract_origin or
1303        DW_AT_extension).  */
1304     sect_offset spec_offset;
1305
1306     /* Pointers to this DIE's parent, first child, and next sibling,
1307        if any.  */
1308     struct partial_die_info *die_parent, *die_child, *die_sibling;
1309   };
1310
1311 /* This data structure holds the information of an abbrev.  */
1312 struct abbrev_info
1313   {
1314     unsigned int number;        /* number identifying abbrev */
1315     enum dwarf_tag tag;         /* dwarf tag */
1316     unsigned short has_children;                /* boolean */
1317     unsigned short num_attrs;   /* number of attributes */
1318     struct attr_abbrev *attrs;  /* an array of attribute descriptions */
1319     struct abbrev_info *next;   /* next in chain */
1320   };
1321
1322 struct attr_abbrev
1323   {
1324     ENUM_BITFIELD(dwarf_attribute) name : 16;
1325     ENUM_BITFIELD(dwarf_form) form : 16;
1326
1327     /* It is valid only if FORM is DW_FORM_implicit_const.  */
1328     LONGEST implicit_const;
1329   };
1330
1331 /* Size of abbrev_table.abbrev_hash_table.  */
1332 #define ABBREV_HASH_SIZE 121
1333
1334 /* Top level data structure to contain an abbreviation table.  */
1335
1336 struct abbrev_table
1337 {
1338   /* Where the abbrev table came from.
1339      This is used as a sanity check when the table is used.  */
1340   sect_offset sect_off;
1341
1342   /* Storage for the abbrev table.  */
1343   struct obstack abbrev_obstack;
1344
1345   /* Hash table of abbrevs.
1346      This is an array of size ABBREV_HASH_SIZE allocated in abbrev_obstack.
1347      It could be statically allocated, but the previous code didn't so we
1348      don't either.  */
1349   struct abbrev_info **abbrevs;
1350 };
1351
1352 /* Attributes have a name and a value.  */
1353 struct attribute
1354   {
1355     ENUM_BITFIELD(dwarf_attribute) name : 16;
1356     ENUM_BITFIELD(dwarf_form) form : 15;
1357
1358     /* Has DW_STRING already been updated by dwarf2_canonicalize_name?  This
1359        field should be in u.str (existing only for DW_STRING) but it is kept
1360        here for better struct attribute alignment.  */
1361     unsigned int string_is_canonical : 1;
1362
1363     union
1364       {
1365         const char *str;
1366         struct dwarf_block *blk;
1367         ULONGEST unsnd;
1368         LONGEST snd;
1369         CORE_ADDR addr;
1370         ULONGEST signature;
1371       }
1372     u;
1373   };
1374
1375 /* This data structure holds a complete die structure.  */
1376 struct die_info
1377   {
1378     /* DWARF-2 tag for this DIE.  */
1379     ENUM_BITFIELD(dwarf_tag) tag : 16;
1380
1381     /* Number of attributes */
1382     unsigned char num_attrs;
1383
1384     /* True if we're presently building the full type name for the
1385        type derived from this DIE.  */
1386     unsigned char building_fullname : 1;
1387
1388     /* True if this die is in process.  PR 16581.  */
1389     unsigned char in_process : 1;
1390
1391     /* Abbrev number */
1392     unsigned int abbrev;
1393
1394     /* Offset in .debug_info or .debug_types section.  */
1395     sect_offset sect_off;
1396
1397     /* The dies in a compilation unit form an n-ary tree.  PARENT
1398        points to this die's parent; CHILD points to the first child of
1399        this node; and all the children of a given node are chained
1400        together via their SIBLING fields.  */
1401     struct die_info *child;     /* Its first child, if any.  */
1402     struct die_info *sibling;   /* Its next sibling, if any.  */
1403     struct die_info *parent;    /* Its parent, if any.  */
1404
1405     /* An array of attributes, with NUM_ATTRS elements.  There may be
1406        zero, but it's not common and zero-sized arrays are not
1407        sufficiently portable C.  */
1408     struct attribute attrs[1];
1409   };
1410
1411 /* Get at parts of an attribute structure.  */
1412
1413 #define DW_STRING(attr)    ((attr)->u.str)
1414 #define DW_STRING_IS_CANONICAL(attr) ((attr)->string_is_canonical)
1415 #define DW_UNSND(attr)     ((attr)->u.unsnd)
1416 #define DW_BLOCK(attr)     ((attr)->u.blk)
1417 #define DW_SND(attr)       ((attr)->u.snd)
1418 #define DW_ADDR(attr)      ((attr)->u.addr)
1419 #define DW_SIGNATURE(attr) ((attr)->u.signature)
1420
1421 /* Blocks are a bunch of untyped bytes.  */
1422 struct dwarf_block
1423   {
1424     size_t size;
1425
1426     /* Valid only if SIZE is not zero.  */
1427     const gdb_byte *data;
1428   };
1429
1430 #ifndef ATTR_ALLOC_CHUNK
1431 #define ATTR_ALLOC_CHUNK 4
1432 #endif
1433
1434 /* Allocate fields for structs, unions and enums in this size.  */
1435 #ifndef DW_FIELD_ALLOC_CHUNK
1436 #define DW_FIELD_ALLOC_CHUNK 4
1437 #endif
1438
1439 /* FIXME: We might want to set this from BFD via bfd_arch_bits_per_byte,
1440    but this would require a corresponding change in unpack_field_as_long
1441    and friends.  */
1442 static int bits_per_byte = 8;
1443
1444 struct nextfield
1445 {
1446   struct nextfield *next;
1447   int accessibility;
1448   int virtuality;
1449   struct field field;
1450 };
1451
1452 struct nextfnfield
1453 {
1454   struct nextfnfield *next;
1455   struct fn_field fnfield;
1456 };
1457
1458 struct fnfieldlist
1459 {
1460   const char *name;
1461   int length;
1462   struct nextfnfield *head;
1463 };
1464
1465 struct typedef_field_list
1466 {
1467   struct typedef_field field;
1468   struct typedef_field_list *next;
1469 };
1470
1471 /* The routines that read and process dies for a C struct or C++ class
1472    pass lists of data member fields and lists of member function fields
1473    in an instance of a field_info structure, as defined below.  */
1474 struct field_info
1475   {
1476     /* List of data member and baseclasses fields.  */
1477     struct nextfield *fields, *baseclasses;
1478
1479     /* Number of fields (including baseclasses).  */
1480     int nfields;
1481
1482     /* Number of baseclasses.  */
1483     int nbaseclasses;
1484
1485     /* Set if the accesibility of one of the fields is not public.  */
1486     int non_public_fields;
1487
1488     /* Member function fields array, entries are allocated in the order they
1489        are encountered in the object file.  */
1490     struct nextfnfield *fnfields;
1491
1492     /* Member function fieldlist array, contains name of possibly overloaded
1493        member function, number of overloaded member functions and a pointer
1494        to the head of the member function field chain.  */
1495     struct fnfieldlist *fnfieldlists;
1496
1497     /* Number of entries in the fnfieldlists array.  */
1498     int nfnfields;
1499
1500     /* typedefs defined inside this class.  TYPEDEF_FIELD_LIST contains head of
1501        a NULL terminated list of TYPEDEF_FIELD_LIST_COUNT elements.  */
1502     struct typedef_field_list *typedef_field_list;
1503     unsigned typedef_field_list_count;
1504   };
1505
1506 /* One item on the queue of compilation units to read in full symbols
1507    for.  */
1508 struct dwarf2_queue_item
1509 {
1510   struct dwarf2_per_cu_data *per_cu;
1511   enum language pretend_language;
1512   struct dwarf2_queue_item *next;
1513 };
1514
1515 /* The current queue.  */
1516 static struct dwarf2_queue_item *dwarf2_queue, *dwarf2_queue_tail;
1517
1518 /* Loaded secondary compilation units are kept in memory until they
1519    have not been referenced for the processing of this many
1520    compilation units.  Set this to zero to disable caching.  Cache
1521    sizes of up to at least twenty will improve startup time for
1522    typical inter-CU-reference binaries, at an obvious memory cost.  */
1523 static int dwarf_max_cache_age = 5;
1524 static void
1525 show_dwarf_max_cache_age (struct ui_file *file, int from_tty,
1526                           struct cmd_list_element *c, const char *value)
1527 {
1528   fprintf_filtered (file, _("The upper bound on the age of cached "
1529                             "DWARF compilation units is %s.\n"),
1530                     value);
1531 }
1532 \f
1533 /* local function prototypes */
1534
1535 static const char *get_section_name (const struct dwarf2_section_info *);
1536
1537 static const char *get_section_file_name (const struct dwarf2_section_info *);
1538
1539 static void dwarf2_find_base_address (struct die_info *die,
1540                                       struct dwarf2_cu *cu);
1541
1542 static struct partial_symtab *create_partial_symtab
1543   (struct dwarf2_per_cu_data *per_cu, const char *name);
1544
1545 static void build_type_psymtabs_reader (const struct die_reader_specs *reader,
1546                                         const gdb_byte *info_ptr,
1547                                         struct die_info *type_unit_die,
1548                                         int has_children, void *data);
1549
1550 static void dwarf2_build_psymtabs_hard (struct objfile *);
1551
1552 static void scan_partial_symbols (struct partial_die_info *,
1553                                   CORE_ADDR *, CORE_ADDR *,
1554                                   int, struct dwarf2_cu *);
1555
1556 static void add_partial_symbol (struct partial_die_info *,
1557                                 struct dwarf2_cu *);
1558
1559 static void add_partial_namespace (struct partial_die_info *pdi,
1560                                    CORE_ADDR *lowpc, CORE_ADDR *highpc,
1561                                    int set_addrmap, struct dwarf2_cu *cu);
1562
1563 static void add_partial_module (struct partial_die_info *pdi, CORE_ADDR *lowpc,
1564                                 CORE_ADDR *highpc, int set_addrmap,
1565                                 struct dwarf2_cu *cu);
1566
1567 static void add_partial_enumeration (struct partial_die_info *enum_pdi,
1568                                      struct dwarf2_cu *cu);
1569
1570 static void add_partial_subprogram (struct partial_die_info *pdi,
1571                                     CORE_ADDR *lowpc, CORE_ADDR *highpc,
1572                                     int need_pc, struct dwarf2_cu *cu);
1573
1574 static void dwarf2_read_symtab (struct partial_symtab *,
1575                                 struct objfile *);
1576
1577 static void psymtab_to_symtab_1 (struct partial_symtab *);
1578
1579 static struct abbrev_info *abbrev_table_lookup_abbrev
1580   (const struct abbrev_table *, unsigned int);
1581
1582 static struct abbrev_table *abbrev_table_read_table
1583   (struct dwarf2_section_info *, sect_offset);
1584
1585 static void abbrev_table_free (struct abbrev_table *);
1586
1587 static void abbrev_table_free_cleanup (void *);
1588
1589 static void dwarf2_read_abbrevs (struct dwarf2_cu *,
1590                                  struct dwarf2_section_info *);
1591
1592 static void dwarf2_free_abbrev_table (void *);
1593
1594 static unsigned int peek_abbrev_code (bfd *, const gdb_byte *);
1595
1596 static struct partial_die_info *load_partial_dies
1597   (const struct die_reader_specs *, const gdb_byte *, int);
1598
1599 static const gdb_byte *read_partial_die (const struct die_reader_specs *,
1600                                          struct partial_die_info *,
1601                                          struct abbrev_info *,
1602                                          unsigned int,
1603                                          const gdb_byte *);
1604
1605 static struct partial_die_info *find_partial_die (sect_offset, int,
1606                                                   struct dwarf2_cu *);
1607
1608 static void fixup_partial_die (struct partial_die_info *,
1609                                struct dwarf2_cu *);
1610
1611 static const gdb_byte *read_attribute (const struct die_reader_specs *,
1612                                        struct attribute *, struct attr_abbrev *,
1613                                        const gdb_byte *);
1614
1615 static unsigned int read_1_byte (bfd *, const gdb_byte *);
1616
1617 static int read_1_signed_byte (bfd *, const gdb_byte *);
1618
1619 static unsigned int read_2_bytes (bfd *, const gdb_byte *);
1620
1621 static unsigned int read_4_bytes (bfd *, const gdb_byte *);
1622
1623 static ULONGEST read_8_bytes (bfd *, const gdb_byte *);
1624
1625 static CORE_ADDR read_address (bfd *, const gdb_byte *ptr, struct dwarf2_cu *,
1626                                unsigned int *);
1627
1628 static LONGEST read_initial_length (bfd *, const gdb_byte *, unsigned int *);
1629
1630 static LONGEST read_checked_initial_length_and_offset
1631   (bfd *, const gdb_byte *, const struct comp_unit_head *,
1632    unsigned int *, unsigned int *);
1633
1634 static LONGEST read_offset (bfd *, const gdb_byte *,
1635                             const struct comp_unit_head *,
1636                             unsigned int *);
1637
1638 static LONGEST read_offset_1 (bfd *, const gdb_byte *, unsigned int);
1639
1640 static sect_offset read_abbrev_offset (struct dwarf2_section_info *,
1641                                        sect_offset);
1642
1643 static const gdb_byte *read_n_bytes (bfd *, const gdb_byte *, unsigned int);
1644
1645 static const char *read_direct_string (bfd *, const gdb_byte *, unsigned int *);
1646
1647 static const char *read_indirect_string (bfd *, const gdb_byte *,
1648                                          const struct comp_unit_head *,
1649                                          unsigned int *);
1650
1651 static const char *read_indirect_line_string (bfd *, const gdb_byte *,
1652                                               const struct comp_unit_head *,
1653                                               unsigned int *);
1654
1655 static const char *read_indirect_string_from_dwz (struct dwz_file *, LONGEST);
1656
1657 static LONGEST read_signed_leb128 (bfd *, const gdb_byte *, unsigned int *);
1658
1659 static CORE_ADDR read_addr_index_from_leb128 (struct dwarf2_cu *,
1660                                               const gdb_byte *,
1661                                               unsigned int *);
1662
1663 static const char *read_str_index (const struct die_reader_specs *reader,
1664                                    ULONGEST str_index);
1665
1666 static void set_cu_language (unsigned int, struct dwarf2_cu *);
1667
1668 static struct attribute *dwarf2_attr (struct die_info *, unsigned int,
1669                                       struct dwarf2_cu *);
1670
1671 static struct attribute *dwarf2_attr_no_follow (struct die_info *,
1672                                                 unsigned int);
1673
1674 static const char *dwarf2_string_attr (struct die_info *die, unsigned int name,
1675                                        struct dwarf2_cu *cu);
1676
1677 static int dwarf2_flag_true_p (struct die_info *die, unsigned name,
1678                                struct dwarf2_cu *cu);
1679
1680 static int die_is_declaration (struct die_info *, struct dwarf2_cu *cu);
1681
1682 static struct die_info *die_specification (struct die_info *die,
1683                                            struct dwarf2_cu **);
1684
1685 static line_header_up dwarf_decode_line_header (sect_offset sect_off,
1686                                                 struct dwarf2_cu *cu);
1687
1688 static void dwarf_decode_lines (struct line_header *, const char *,
1689                                 struct dwarf2_cu *, struct partial_symtab *,
1690                                 CORE_ADDR, int decode_mapping);
1691
1692 static void dwarf2_start_subfile (const char *, const char *);
1693
1694 static struct compunit_symtab *dwarf2_start_symtab (struct dwarf2_cu *,
1695                                                     const char *, const char *,
1696                                                     CORE_ADDR);
1697
1698 static struct symbol *new_symbol (struct die_info *, struct type *,
1699                                   struct dwarf2_cu *);
1700
1701 static struct symbol *new_symbol_full (struct die_info *, struct type *,
1702                                        struct dwarf2_cu *, struct symbol *);
1703
1704 static void dwarf2_const_value (const struct attribute *, struct symbol *,
1705                                 struct dwarf2_cu *);
1706
1707 static void dwarf2_const_value_attr (const struct attribute *attr,
1708                                      struct type *type,
1709                                      const char *name,
1710                                      struct obstack *obstack,
1711                                      struct dwarf2_cu *cu, LONGEST *value,
1712                                      const gdb_byte **bytes,
1713                                      struct dwarf2_locexpr_baton **baton);
1714
1715 static struct type *die_type (struct die_info *, struct dwarf2_cu *);
1716
1717 static int need_gnat_info (struct dwarf2_cu *);
1718
1719 static struct type *die_descriptive_type (struct die_info *,
1720                                           struct dwarf2_cu *);
1721
1722 static void set_descriptive_type (struct type *, struct die_info *,
1723                                   struct dwarf2_cu *);
1724
1725 static struct type *die_containing_type (struct die_info *,
1726                                          struct dwarf2_cu *);
1727
1728 static struct type *lookup_die_type (struct die_info *, const struct attribute *,
1729                                      struct dwarf2_cu *);
1730
1731 static struct type *read_type_die (struct die_info *, struct dwarf2_cu *);
1732
1733 static struct type *read_type_die_1 (struct die_info *, struct dwarf2_cu *);
1734
1735 static const char *determine_prefix (struct die_info *die, struct dwarf2_cu *);
1736
1737 static char *typename_concat (struct obstack *obs, const char *prefix,
1738                               const char *suffix, int physname,
1739                               struct dwarf2_cu *cu);
1740
1741 static void read_file_scope (struct die_info *, struct dwarf2_cu *);
1742
1743 static void read_type_unit_scope (struct die_info *, struct dwarf2_cu *);
1744
1745 static void read_func_scope (struct die_info *, struct dwarf2_cu *);
1746
1747 static void read_lexical_block_scope (struct die_info *, struct dwarf2_cu *);
1748
1749 static void read_call_site_scope (struct die_info *die, struct dwarf2_cu *cu);
1750
1751 static int dwarf2_ranges_read (unsigned, CORE_ADDR *, CORE_ADDR *,
1752                                struct dwarf2_cu *, struct partial_symtab *);
1753
1754 /* How dwarf2_get_pc_bounds constructed its *LOWPC and *HIGHPC return
1755    values.  Keep the items ordered with increasing constraints compliance.  */
1756 enum pc_bounds_kind
1757 {
1758   /* No attribute DW_AT_low_pc, DW_AT_high_pc or DW_AT_ranges was found.  */
1759   PC_BOUNDS_NOT_PRESENT,
1760
1761   /* Some of the attributes DW_AT_low_pc, DW_AT_high_pc or DW_AT_ranges
1762      were present but they do not form a valid range of PC addresses.  */
1763   PC_BOUNDS_INVALID,
1764
1765   /* Discontiguous range was found - that is DW_AT_ranges was found.  */
1766   PC_BOUNDS_RANGES,
1767
1768   /* Contiguous range was found - DW_AT_low_pc and DW_AT_high_pc were found.  */
1769   PC_BOUNDS_HIGH_LOW,
1770 };
1771
1772 static enum pc_bounds_kind dwarf2_get_pc_bounds (struct die_info *,
1773                                                  CORE_ADDR *, CORE_ADDR *,
1774                                                  struct dwarf2_cu *,
1775                                                  struct partial_symtab *);
1776
1777 static void get_scope_pc_bounds (struct die_info *,
1778                                  CORE_ADDR *, CORE_ADDR *,
1779                                  struct dwarf2_cu *);
1780
1781 static void dwarf2_record_block_ranges (struct die_info *, struct block *,
1782                                         CORE_ADDR, struct dwarf2_cu *);
1783
1784 static void dwarf2_add_field (struct field_info *, struct die_info *,
1785                               struct dwarf2_cu *);
1786
1787 static void dwarf2_attach_fields_to_type (struct field_info *,
1788                                           struct type *, struct dwarf2_cu *);
1789
1790 static void dwarf2_add_member_fn (struct field_info *,
1791                                   struct die_info *, struct type *,
1792                                   struct dwarf2_cu *);
1793
1794 static void dwarf2_attach_fn_fields_to_type (struct field_info *,
1795                                              struct type *,
1796                                              struct dwarf2_cu *);
1797
1798 static void process_structure_scope (struct die_info *, struct dwarf2_cu *);
1799
1800 static void read_common_block (struct die_info *, struct dwarf2_cu *);
1801
1802 static void read_namespace (struct die_info *die, struct dwarf2_cu *);
1803
1804 static void read_module (struct die_info *die, struct dwarf2_cu *cu);
1805
1806 static struct using_direct **using_directives (enum language);
1807
1808 static void read_import_statement (struct die_info *die, struct dwarf2_cu *);
1809
1810 static int read_namespace_alias (struct die_info *die, struct dwarf2_cu *cu);
1811
1812 static struct type *read_module_type (struct die_info *die,
1813                                       struct dwarf2_cu *cu);
1814
1815 static const char *namespace_name (struct die_info *die,
1816                                    int *is_anonymous, struct dwarf2_cu *);
1817
1818 static void process_enumeration_scope (struct die_info *, struct dwarf2_cu *);
1819
1820 static CORE_ADDR decode_locdesc (struct dwarf_block *, struct dwarf2_cu *);
1821
1822 static enum dwarf_array_dim_ordering read_array_order (struct die_info *,
1823                                                        struct dwarf2_cu *);
1824
1825 static struct die_info *read_die_and_siblings_1
1826   (const struct die_reader_specs *, const gdb_byte *, const gdb_byte **,
1827    struct die_info *);
1828
1829 static struct die_info *read_die_and_siblings (const struct die_reader_specs *,
1830                                                const gdb_byte *info_ptr,
1831                                                const gdb_byte **new_info_ptr,
1832                                                struct die_info *parent);
1833
1834 static const gdb_byte *read_full_die_1 (const struct die_reader_specs *,
1835                                         struct die_info **, const gdb_byte *,
1836                                         int *, int);
1837
1838 static const gdb_byte *read_full_die (const struct die_reader_specs *,
1839                                       struct die_info **, const gdb_byte *,
1840                                       int *);
1841
1842 static void process_die (struct die_info *, struct dwarf2_cu *);
1843
1844 static const char *dwarf2_canonicalize_name (const char *, struct dwarf2_cu *,
1845                                              struct obstack *);
1846
1847 static const char *dwarf2_name (struct die_info *die, struct dwarf2_cu *);
1848
1849 static const char *dwarf2_full_name (const char *name,
1850                                      struct die_info *die,
1851                                      struct dwarf2_cu *cu);
1852
1853 static const char *dwarf2_physname (const char *name, struct die_info *die,
1854                                     struct dwarf2_cu *cu);
1855
1856 static struct die_info *dwarf2_extension (struct die_info *die,
1857                                           struct dwarf2_cu **);
1858
1859 static const char *dwarf_tag_name (unsigned int);
1860
1861 static const char *dwarf_attr_name (unsigned int);
1862
1863 static const char *dwarf_form_name (unsigned int);
1864
1865 static const char *dwarf_bool_name (unsigned int);
1866
1867 static const char *dwarf_type_encoding_name (unsigned int);
1868
1869 static struct die_info *sibling_die (struct die_info *);
1870
1871 static void dump_die_shallow (struct ui_file *, int indent, struct die_info *);
1872
1873 static void dump_die_for_error (struct die_info *);
1874
1875 static void dump_die_1 (struct ui_file *, int level, int max_level,
1876                         struct die_info *);
1877
1878 /*static*/ void dump_die (struct die_info *, int max_level);
1879
1880 static void store_in_ref_table (struct die_info *,
1881                                 struct dwarf2_cu *);
1882
1883 static sect_offset dwarf2_get_ref_die_offset (const struct attribute *);
1884
1885 static LONGEST dwarf2_get_attr_constant_value (const struct attribute *, int);
1886
1887 static struct die_info *follow_die_ref_or_sig (struct die_info *,
1888                                                const struct attribute *,
1889                                                struct dwarf2_cu **);
1890
1891 static struct die_info *follow_die_ref (struct die_info *,
1892                                         const struct attribute *,
1893                                         struct dwarf2_cu **);
1894
1895 static struct die_info *follow_die_sig (struct die_info *,
1896                                         const struct attribute *,
1897                                         struct dwarf2_cu **);
1898
1899 static struct type *get_signatured_type (struct die_info *, ULONGEST,
1900                                          struct dwarf2_cu *);
1901
1902 static struct type *get_DW_AT_signature_type (struct die_info *,
1903                                               const struct attribute *,
1904                                               struct dwarf2_cu *);
1905
1906 static void load_full_type_unit (struct dwarf2_per_cu_data *per_cu);
1907
1908 static void read_signatured_type (struct signatured_type *);
1909
1910 static int attr_to_dynamic_prop (const struct attribute *attr,
1911                                  struct die_info *die, struct dwarf2_cu *cu,
1912                                  struct dynamic_prop *prop);
1913
1914 /* memory allocation interface */
1915
1916 static struct dwarf_block *dwarf_alloc_block (struct dwarf2_cu *);
1917
1918 static struct die_info *dwarf_alloc_die (struct dwarf2_cu *, int);
1919
1920 static void dwarf_decode_macros (struct dwarf2_cu *, unsigned int, int);
1921
1922 static int attr_form_is_block (const struct attribute *);
1923
1924 static int attr_form_is_section_offset (const struct attribute *);
1925
1926 static int attr_form_is_constant (const struct attribute *);
1927
1928 static int attr_form_is_ref (const struct attribute *);
1929
1930 static void fill_in_loclist_baton (struct dwarf2_cu *cu,
1931                                    struct dwarf2_loclist_baton *baton,
1932                                    const struct attribute *attr);
1933
1934 static void dwarf2_symbol_mark_computed (const struct attribute *attr,
1935                                          struct symbol *sym,
1936                                          struct dwarf2_cu *cu,
1937                                          int is_block);
1938
1939 static const gdb_byte *skip_one_die (const struct die_reader_specs *reader,
1940                                      const gdb_byte *info_ptr,
1941                                      struct abbrev_info *abbrev);
1942
1943 static void free_stack_comp_unit (void *);
1944
1945 static hashval_t partial_die_hash (const void *item);
1946
1947 static int partial_die_eq (const void *item_lhs, const void *item_rhs);
1948
1949 static struct dwarf2_per_cu_data *dwarf2_find_containing_comp_unit
1950   (sect_offset sect_off, unsigned int offset_in_dwz, struct objfile *objfile);
1951
1952 static void init_one_comp_unit (struct dwarf2_cu *cu,
1953                                 struct dwarf2_per_cu_data *per_cu);
1954
1955 static void prepare_one_comp_unit (struct dwarf2_cu *cu,
1956                                    struct die_info *comp_unit_die,
1957                                    enum language pretend_language);
1958
1959 static void free_heap_comp_unit (void *);
1960
1961 static void free_cached_comp_units (void *);
1962
1963 static void age_cached_comp_units (void);
1964
1965 static void free_one_cached_comp_unit (struct dwarf2_per_cu_data *);
1966
1967 static struct type *set_die_type (struct die_info *, struct type *,
1968                                   struct dwarf2_cu *);
1969
1970 static void create_all_comp_units (struct objfile *);
1971
1972 static int create_all_type_units (struct objfile *);
1973
1974 static void load_full_comp_unit (struct dwarf2_per_cu_data *,
1975                                  enum language);
1976
1977 static void process_full_comp_unit (struct dwarf2_per_cu_data *,
1978                                     enum language);
1979
1980 static void process_full_type_unit (struct dwarf2_per_cu_data *,
1981                                     enum language);
1982
1983 static void dwarf2_add_dependence (struct dwarf2_cu *,
1984                                    struct dwarf2_per_cu_data *);
1985
1986 static void dwarf2_mark (struct dwarf2_cu *);
1987
1988 static void dwarf2_clear_marks (struct dwarf2_per_cu_data *);
1989
1990 static struct type *get_die_type_at_offset (sect_offset,
1991                                             struct dwarf2_per_cu_data *);
1992
1993 static struct type *get_die_type (struct die_info *die, struct dwarf2_cu *cu);
1994
1995 static void dwarf2_release_queue (void *dummy);
1996
1997 static void queue_comp_unit (struct dwarf2_per_cu_data *per_cu,
1998                              enum language pretend_language);
1999
2000 static void process_queue (void);
2001
2002 /* The return type of find_file_and_directory.  Note, the enclosed
2003    string pointers are only valid while this object is valid.  */
2004
2005 struct file_and_directory
2006 {
2007   /* The filename.  This is never NULL.  */
2008   const char *name;
2009
2010   /* The compilation directory.  NULL if not known.  If we needed to
2011      compute a new string, this points to COMP_DIR_STORAGE, otherwise,
2012      points directly to the DW_AT_comp_dir string attribute owned by
2013      the obstack that owns the DIE.  */
2014   const char *comp_dir;
2015
2016   /* If we needed to build a new string for comp_dir, this is what
2017      owns the storage.  */
2018   std::string comp_dir_storage;
2019 };
2020
2021 static file_and_directory find_file_and_directory (struct die_info *die,
2022                                                    struct dwarf2_cu *cu);
2023
2024 static char *file_full_name (int file, struct line_header *lh,
2025                              const char *comp_dir);
2026
2027 /* Expected enum dwarf_unit_type for read_comp_unit_head.  */
2028 enum class rcuh_kind { COMPILE, TYPE };
2029
2030 static const gdb_byte *read_and_check_comp_unit_head
2031   (struct comp_unit_head *header,
2032    struct dwarf2_section_info *section,
2033    struct dwarf2_section_info *abbrev_section, const gdb_byte *info_ptr,
2034    rcuh_kind section_kind);
2035
2036 static void init_cutu_and_read_dies
2037   (struct dwarf2_per_cu_data *this_cu, struct abbrev_table *abbrev_table,
2038    int use_existing_cu, int keep,
2039    die_reader_func_ftype *die_reader_func, void *data);
2040
2041 static void init_cutu_and_read_dies_simple
2042   (struct dwarf2_per_cu_data *this_cu,
2043    die_reader_func_ftype *die_reader_func, void *data);
2044
2045 static htab_t allocate_signatured_type_table (struct objfile *objfile);
2046
2047 static htab_t allocate_dwo_unit_table (struct objfile *objfile);
2048
2049 static struct dwo_unit *lookup_dwo_unit_in_dwp
2050   (struct dwp_file *dwp_file, const char *comp_dir,
2051    ULONGEST signature, int is_debug_types);
2052
2053 static struct dwp_file *get_dwp_file (void);
2054
2055 static struct dwo_unit *lookup_dwo_comp_unit
2056   (struct dwarf2_per_cu_data *, const char *, const char *, ULONGEST);
2057
2058 static struct dwo_unit *lookup_dwo_type_unit
2059   (struct signatured_type *, const char *, const char *);
2060
2061 static void queue_and_load_all_dwo_tus (struct dwarf2_per_cu_data *);
2062
2063 static void free_dwo_file_cleanup (void *);
2064
2065 static void process_cu_includes (void);
2066
2067 static void check_producer (struct dwarf2_cu *cu);
2068
2069 static void free_line_header_voidp (void *arg);
2070 \f
2071 /* Various complaints about symbol reading that don't abort the process.  */
2072
2073 static void
2074 dwarf2_statement_list_fits_in_line_number_section_complaint (void)
2075 {
2076   complaint (&symfile_complaints,
2077              _("statement list doesn't fit in .debug_line section"));
2078 }
2079
2080 static void
2081 dwarf2_debug_line_missing_file_complaint (void)
2082 {
2083   complaint (&symfile_complaints,
2084              _(".debug_line section has line data without a file"));
2085 }
2086
2087 static void
2088 dwarf2_debug_line_missing_end_sequence_complaint (void)
2089 {
2090   complaint (&symfile_complaints,
2091              _(".debug_line section has line "
2092                "program sequence without an end"));
2093 }
2094
2095 static void
2096 dwarf2_complex_location_expr_complaint (void)
2097 {
2098   complaint (&symfile_complaints, _("location expression too complex"));
2099 }
2100
2101 static void
2102 dwarf2_const_value_length_mismatch_complaint (const char *arg1, int arg2,
2103                                               int arg3)
2104 {
2105   complaint (&symfile_complaints,
2106              _("const value length mismatch for '%s', got %d, expected %d"),
2107              arg1, arg2, arg3);
2108 }
2109
2110 static void
2111 dwarf2_section_buffer_overflow_complaint (struct dwarf2_section_info *section)
2112 {
2113   complaint (&symfile_complaints,
2114              _("debug info runs off end of %s section"
2115                " [in module %s]"),
2116              get_section_name (section),
2117              get_section_file_name (section));
2118 }
2119
2120 static void
2121 dwarf2_macro_malformed_definition_complaint (const char *arg1)
2122 {
2123   complaint (&symfile_complaints,
2124              _("macro debug info contains a "
2125                "malformed macro definition:\n`%s'"),
2126              arg1);
2127 }
2128
2129 static void
2130 dwarf2_invalid_attrib_class_complaint (const char *arg1, const char *arg2)
2131 {
2132   complaint (&symfile_complaints,
2133              _("invalid attribute class or form for '%s' in '%s'"),
2134              arg1, arg2);
2135 }
2136
2137 /* Hash function for line_header_hash.  */
2138
2139 static hashval_t
2140 line_header_hash (const struct line_header *ofs)
2141 {
2142   return to_underlying (ofs->sect_off) ^ ofs->offset_in_dwz;
2143 }
2144
2145 /* Hash function for htab_create_alloc_ex for line_header_hash.  */
2146
2147 static hashval_t
2148 line_header_hash_voidp (const void *item)
2149 {
2150   const struct line_header *ofs = (const struct line_header *) item;
2151
2152   return line_header_hash (ofs);
2153 }
2154
2155 /* Equality function for line_header_hash.  */
2156
2157 static int
2158 line_header_eq_voidp (const void *item_lhs, const void *item_rhs)
2159 {
2160   const struct line_header *ofs_lhs = (const struct line_header *) item_lhs;
2161   const struct line_header *ofs_rhs = (const struct line_header *) item_rhs;
2162
2163   return (ofs_lhs->sect_off == ofs_rhs->sect_off
2164           && ofs_lhs->offset_in_dwz == ofs_rhs->offset_in_dwz);
2165 }
2166
2167 \f
2168 #if WORDS_BIGENDIAN
2169
2170 /* Convert VALUE between big- and little-endian.  */
2171 static offset_type
2172 byte_swap (offset_type value)
2173 {
2174   offset_type result;
2175
2176   result = (value & 0xff) << 24;
2177   result |= (value & 0xff00) << 8;
2178   result |= (value & 0xff0000) >> 8;
2179   result |= (value & 0xff000000) >> 24;
2180   return result;
2181 }
2182
2183 #define MAYBE_SWAP(V)  byte_swap (V)
2184
2185 #else
2186 #define MAYBE_SWAP(V) static_cast<offset_type> (V)
2187 #endif /* WORDS_BIGENDIAN */
2188
2189 /* Read the given attribute value as an address, taking the attribute's
2190    form into account.  */
2191
2192 static CORE_ADDR
2193 attr_value_as_address (struct attribute *attr)
2194 {
2195   CORE_ADDR addr;
2196
2197   if (attr->form != DW_FORM_addr && attr->form != DW_FORM_GNU_addr_index)
2198     {
2199       /* Aside from a few clearly defined exceptions, attributes that
2200          contain an address must always be in DW_FORM_addr form.
2201          Unfortunately, some compilers happen to be violating this
2202          requirement by encoding addresses using other forms, such
2203          as DW_FORM_data4 for example.  For those broken compilers,
2204          we try to do our best, without any guarantee of success,
2205          to interpret the address correctly.  It would also be nice
2206          to generate a complaint, but that would require us to maintain
2207          a list of legitimate cases where a non-address form is allowed,
2208          as well as update callers to pass in at least the CU's DWARF
2209          version.  This is more overhead than what we're willing to
2210          expand for a pretty rare case.  */
2211       addr = DW_UNSND (attr);
2212     }
2213   else
2214     addr = DW_ADDR (attr);
2215
2216   return addr;
2217 }
2218
2219 /* The suffix for an index file.  */
2220 #define INDEX_SUFFIX ".gdb-index"
2221
2222 /* See declaration.  */
2223
2224 dwarf2_per_objfile::dwarf2_per_objfile (struct objfile *objfile_,
2225                                         const dwarf2_debug_sections *names)
2226   : objfile (objfile_)
2227 {
2228   if (names == NULL)
2229     names = &dwarf2_elf_names;
2230
2231   bfd *obfd = objfile->obfd;
2232
2233   for (asection *sec = obfd->sections; sec != NULL; sec = sec->next)
2234     locate_sections (obfd, sec, *names);
2235 }
2236
2237 dwarf2_per_objfile::~dwarf2_per_objfile ()
2238 {
2239   /* Cached DIE trees use xmalloc and the comp_unit_obstack.  */
2240   free_cached_comp_units ();
2241
2242   if (quick_file_names_table)
2243     htab_delete (quick_file_names_table);
2244
2245   if (line_header_hash)
2246     htab_delete (line_header_hash);
2247
2248   /* Everything else should be on the objfile obstack.  */
2249 }
2250
2251 /* See declaration.  */
2252
2253 void
2254 dwarf2_per_objfile::free_cached_comp_units ()
2255 {
2256   dwarf2_per_cu_data *per_cu = read_in_chain;
2257   dwarf2_per_cu_data **last_chain = &read_in_chain;
2258   while (per_cu != NULL)
2259     {
2260       dwarf2_per_cu_data *next_cu = per_cu->cu->read_in_chain;
2261
2262       free_heap_comp_unit (per_cu->cu);
2263       *last_chain = next_cu;
2264       per_cu = next_cu;
2265     }
2266 }
2267
2268 /* Try to locate the sections we need for DWARF 2 debugging
2269    information and return true if we have enough to do something.
2270    NAMES points to the dwarf2 section names, or is NULL if the standard
2271    ELF names are used.  */
2272
2273 int
2274 dwarf2_has_info (struct objfile *objfile,
2275                  const struct dwarf2_debug_sections *names)
2276 {
2277   dwarf2_per_objfile = ((struct dwarf2_per_objfile *)
2278                         objfile_data (objfile, dwarf2_objfile_data_key));
2279   if (!dwarf2_per_objfile)
2280     {
2281       /* Initialize per-objfile state.  */
2282       struct dwarf2_per_objfile *data
2283         = XOBNEW (&objfile->objfile_obstack, struct dwarf2_per_objfile);
2284
2285       dwarf2_per_objfile = new (data) struct dwarf2_per_objfile (objfile, names);
2286       set_objfile_data (objfile, dwarf2_objfile_data_key, dwarf2_per_objfile);
2287     }
2288   return (!dwarf2_per_objfile->info.is_virtual
2289           && dwarf2_per_objfile->info.s.section != NULL
2290           && !dwarf2_per_objfile->abbrev.is_virtual
2291           && dwarf2_per_objfile->abbrev.s.section != NULL);
2292 }
2293
2294 /* Return the containing section of virtual section SECTION.  */
2295
2296 static struct dwarf2_section_info *
2297 get_containing_section (const struct dwarf2_section_info *section)
2298 {
2299   gdb_assert (section->is_virtual);
2300   return section->s.containing_section;
2301 }
2302
2303 /* Return the bfd owner of SECTION.  */
2304
2305 static struct bfd *
2306 get_section_bfd_owner (const struct dwarf2_section_info *section)
2307 {
2308   if (section->is_virtual)
2309     {
2310       section = get_containing_section (section);
2311       gdb_assert (!section->is_virtual);
2312     }
2313   return section->s.section->owner;
2314 }
2315
2316 /* Return the bfd section of SECTION.
2317    Returns NULL if the section is not present.  */
2318
2319 static asection *
2320 get_section_bfd_section (const struct dwarf2_section_info *section)
2321 {
2322   if (section->is_virtual)
2323     {
2324       section = get_containing_section (section);
2325       gdb_assert (!section->is_virtual);
2326     }
2327   return section->s.section;
2328 }
2329
2330 /* Return the name of SECTION.  */
2331
2332 static const char *
2333 get_section_name (const struct dwarf2_section_info *section)
2334 {
2335   asection *sectp = get_section_bfd_section (section);
2336
2337   gdb_assert (sectp != NULL);
2338   return bfd_section_name (get_section_bfd_owner (section), sectp);
2339 }
2340
2341 /* Return the name of the file SECTION is in.  */
2342
2343 static const char *
2344 get_section_file_name (const struct dwarf2_section_info *section)
2345 {
2346   bfd *abfd = get_section_bfd_owner (section);
2347
2348   return bfd_get_filename (abfd);
2349 }
2350
2351 /* Return the id of SECTION.
2352    Returns 0 if SECTION doesn't exist.  */
2353
2354 static int
2355 get_section_id (const struct dwarf2_section_info *section)
2356 {
2357   asection *sectp = get_section_bfd_section (section);
2358
2359   if (sectp == NULL)
2360     return 0;
2361   return sectp->id;
2362 }
2363
2364 /* Return the flags of SECTION.
2365    SECTION (or containing section if this is a virtual section) must exist.  */
2366
2367 static int
2368 get_section_flags (const struct dwarf2_section_info *section)
2369 {
2370   asection *sectp = get_section_bfd_section (section);
2371
2372   gdb_assert (sectp != NULL);
2373   return bfd_get_section_flags (sectp->owner, sectp);
2374 }
2375
2376 /* When loading sections, we look either for uncompressed section or for
2377    compressed section names.  */
2378
2379 static int
2380 section_is_p (const char *section_name,
2381               const struct dwarf2_section_names *names)
2382 {
2383   if (names->normal != NULL
2384       && strcmp (section_name, names->normal) == 0)
2385     return 1;
2386   if (names->compressed != NULL
2387       && strcmp (section_name, names->compressed) == 0)
2388     return 1;
2389   return 0;
2390 }
2391
2392 /* See declaration.  */
2393
2394 void
2395 dwarf2_per_objfile::locate_sections (bfd *abfd, asection *sectp,
2396                                      const dwarf2_debug_sections &names)
2397 {
2398   flagword aflag = bfd_get_section_flags (abfd, sectp);
2399
2400   if ((aflag & SEC_HAS_CONTENTS) == 0)
2401     {
2402     }
2403   else if (section_is_p (sectp->name, &names.info))
2404     {
2405       this->info.s.section = sectp;
2406       this->info.size = bfd_get_section_size (sectp);
2407     }
2408   else if (section_is_p (sectp->name, &names.abbrev))
2409     {
2410       this->abbrev.s.section = sectp;
2411       this->abbrev.size = bfd_get_section_size (sectp);
2412     }
2413   else if (section_is_p (sectp->name, &names.line))
2414     {
2415       this->line.s.section = sectp;
2416       this->line.size = bfd_get_section_size (sectp);
2417     }
2418   else if (section_is_p (sectp->name, &names.loc))
2419     {
2420       this->loc.s.section = sectp;
2421       this->loc.size = bfd_get_section_size (sectp);
2422     }
2423   else if (section_is_p (sectp->name, &names.loclists))
2424     {
2425       this->loclists.s.section = sectp;
2426       this->loclists.size = bfd_get_section_size (sectp);
2427     }
2428   else if (section_is_p (sectp->name, &names.macinfo))
2429     {
2430       this->macinfo.s.section = sectp;
2431       this->macinfo.size = bfd_get_section_size (sectp);
2432     }
2433   else if (section_is_p (sectp->name, &names.macro))
2434     {
2435       this->macro.s.section = sectp;
2436       this->macro.size = bfd_get_section_size (sectp);
2437     }
2438   else if (section_is_p (sectp->name, &names.str))
2439     {
2440       this->str.s.section = sectp;
2441       this->str.size = bfd_get_section_size (sectp);
2442     }
2443   else if (section_is_p (sectp->name, &names.line_str))
2444     {
2445       this->line_str.s.section = sectp;
2446       this->line_str.size = bfd_get_section_size (sectp);
2447     }
2448   else if (section_is_p (sectp->name, &names.addr))
2449     {
2450       this->addr.s.section = sectp;
2451       this->addr.size = bfd_get_section_size (sectp);
2452     }
2453   else if (section_is_p (sectp->name, &names.frame))
2454     {
2455       this->frame.s.section = sectp;
2456       this->frame.size = bfd_get_section_size (sectp);
2457     }
2458   else if (section_is_p (sectp->name, &names.eh_frame))
2459     {
2460       this->eh_frame.s.section = sectp;
2461       this->eh_frame.size = bfd_get_section_size (sectp);
2462     }
2463   else if (section_is_p (sectp->name, &names.ranges))
2464     {
2465       this->ranges.s.section = sectp;
2466       this->ranges.size = bfd_get_section_size (sectp);
2467     }
2468   else if (section_is_p (sectp->name, &names.rnglists))
2469     {
2470       this->rnglists.s.section = sectp;
2471       this->rnglists.size = bfd_get_section_size (sectp);
2472     }
2473   else if (section_is_p (sectp->name, &names.types))
2474     {
2475       struct dwarf2_section_info type_section;
2476
2477       memset (&type_section, 0, sizeof (type_section));
2478       type_section.s.section = sectp;
2479       type_section.size = bfd_get_section_size (sectp);
2480
2481       VEC_safe_push (dwarf2_section_info_def, this->types,
2482                      &type_section);
2483     }
2484   else if (section_is_p (sectp->name, &names.gdb_index))
2485     {
2486       this->gdb_index.s.section = sectp;
2487       this->gdb_index.size = bfd_get_section_size (sectp);
2488     }
2489
2490   if ((bfd_get_section_flags (abfd, sectp) & (SEC_LOAD | SEC_ALLOC))
2491       && bfd_section_vma (abfd, sectp) == 0)
2492     this->has_section_at_zero = true;
2493 }
2494
2495 /* A helper function that decides whether a section is empty,
2496    or not present.  */
2497
2498 static int
2499 dwarf2_section_empty_p (const struct dwarf2_section_info *section)
2500 {
2501   if (section->is_virtual)
2502     return section->size == 0;
2503   return section->s.section == NULL || section->size == 0;
2504 }
2505
2506 /* Read the contents of the section INFO.
2507    OBJFILE is the main object file, but not necessarily the file where
2508    the section comes from.  E.g., for DWO files the bfd of INFO is the bfd
2509    of the DWO file.
2510    If the section is compressed, uncompress it before returning.  */
2511
2512 static void
2513 dwarf2_read_section (struct objfile *objfile, struct dwarf2_section_info *info)
2514 {
2515   asection *sectp;
2516   bfd *abfd;
2517   gdb_byte *buf, *retbuf;
2518
2519   if (info->readin)
2520     return;
2521   info->buffer = NULL;
2522   info->readin = 1;
2523
2524   if (dwarf2_section_empty_p (info))
2525     return;
2526
2527   sectp = get_section_bfd_section (info);
2528
2529   /* If this is a virtual section we need to read in the real one first.  */
2530   if (info->is_virtual)
2531     {
2532       struct dwarf2_section_info *containing_section =
2533         get_containing_section (info);
2534
2535       gdb_assert (sectp != NULL);
2536       if ((sectp->flags & SEC_RELOC) != 0)
2537         {
2538           error (_("Dwarf Error: DWP format V2 with relocations is not"
2539                    " supported in section %s [in module %s]"),
2540                  get_section_name (info), get_section_file_name (info));
2541         }
2542       dwarf2_read_section (objfile, containing_section);
2543       /* Other code should have already caught virtual sections that don't
2544          fit.  */
2545       gdb_assert (info->virtual_offset + info->size
2546                   <= containing_section->size);
2547       /* If the real section is empty or there was a problem reading the
2548          section we shouldn't get here.  */
2549       gdb_assert (containing_section->buffer != NULL);
2550       info->buffer = containing_section->buffer + info->virtual_offset;
2551       return;
2552     }
2553
2554   /* If the section has relocations, we must read it ourselves.
2555      Otherwise we attach it to the BFD.  */
2556   if ((sectp->flags & SEC_RELOC) == 0)
2557     {
2558       info->buffer = gdb_bfd_map_section (sectp, &info->size);
2559       return;
2560     }
2561
2562   buf = (gdb_byte *) obstack_alloc (&objfile->objfile_obstack, info->size);
2563   info->buffer = buf;
2564
2565   /* When debugging .o files, we may need to apply relocations; see
2566      http://sourceware.org/ml/gdb-patches/2002-04/msg00136.html .
2567      We never compress sections in .o files, so we only need to
2568      try this when the section is not compressed.  */
2569   retbuf = symfile_relocate_debug_section (objfile, sectp, buf);
2570   if (retbuf != NULL)
2571     {
2572       info->buffer = retbuf;
2573       return;
2574     }
2575
2576   abfd = get_section_bfd_owner (info);
2577   gdb_assert (abfd != NULL);
2578
2579   if (bfd_seek (abfd, sectp->filepos, SEEK_SET) != 0
2580       || bfd_bread (buf, info->size, abfd) != info->size)
2581     {
2582       error (_("Dwarf Error: Can't read DWARF data"
2583                " in section %s [in module %s]"),
2584              bfd_section_name (abfd, sectp), bfd_get_filename (abfd));
2585     }
2586 }
2587
2588 /* A helper function that returns the size of a section in a safe way.
2589    If you are positive that the section has been read before using the
2590    size, then it is safe to refer to the dwarf2_section_info object's
2591    "size" field directly.  In other cases, you must call this
2592    function, because for compressed sections the size field is not set
2593    correctly until the section has been read.  */
2594
2595 static bfd_size_type
2596 dwarf2_section_size (struct objfile *objfile,
2597                      struct dwarf2_section_info *info)
2598 {
2599   if (!info->readin)
2600     dwarf2_read_section (objfile, info);
2601   return info->size;
2602 }
2603
2604 /* Fill in SECTP, BUFP and SIZEP with section info, given OBJFILE and
2605    SECTION_NAME.  */
2606
2607 void
2608 dwarf2_get_section_info (struct objfile *objfile,
2609                          enum dwarf2_section_enum sect,
2610                          asection **sectp, const gdb_byte **bufp,
2611                          bfd_size_type *sizep)
2612 {
2613   struct dwarf2_per_objfile *data
2614     = (struct dwarf2_per_objfile *) objfile_data (objfile,
2615                                                   dwarf2_objfile_data_key);
2616   struct dwarf2_section_info *info;
2617
2618   /* We may see an objfile without any DWARF, in which case we just
2619      return nothing.  */
2620   if (data == NULL)
2621     {
2622       *sectp = NULL;
2623       *bufp = NULL;
2624       *sizep = 0;
2625       return;
2626     }
2627   switch (sect)
2628     {
2629     case DWARF2_DEBUG_FRAME:
2630       info = &data->frame;
2631       break;
2632     case DWARF2_EH_FRAME:
2633       info = &data->eh_frame;
2634       break;
2635     default:
2636       gdb_assert_not_reached ("unexpected section");
2637     }
2638
2639   dwarf2_read_section (objfile, info);
2640
2641   *sectp = get_section_bfd_section (info);
2642   *bufp = info->buffer;
2643   *sizep = info->size;
2644 }
2645
2646 /* A helper function to find the sections for a .dwz file.  */
2647
2648 static void
2649 locate_dwz_sections (bfd *abfd, asection *sectp, void *arg)
2650 {
2651   struct dwz_file *dwz_file = (struct dwz_file *) arg;
2652
2653   /* Note that we only support the standard ELF names, because .dwz
2654      is ELF-only (at the time of writing).  */
2655   if (section_is_p (sectp->name, &dwarf2_elf_names.abbrev))
2656     {
2657       dwz_file->abbrev.s.section = sectp;
2658       dwz_file->abbrev.size = bfd_get_section_size (sectp);
2659     }
2660   else if (section_is_p (sectp->name, &dwarf2_elf_names.info))
2661     {
2662       dwz_file->info.s.section = sectp;
2663       dwz_file->info.size = bfd_get_section_size (sectp);
2664     }
2665   else if (section_is_p (sectp->name, &dwarf2_elf_names.str))
2666     {
2667       dwz_file->str.s.section = sectp;
2668       dwz_file->str.size = bfd_get_section_size (sectp);
2669     }
2670   else if (section_is_p (sectp->name, &dwarf2_elf_names.line))
2671     {
2672       dwz_file->line.s.section = sectp;
2673       dwz_file->line.size = bfd_get_section_size (sectp);
2674     }
2675   else if (section_is_p (sectp->name, &dwarf2_elf_names.macro))
2676     {
2677       dwz_file->macro.s.section = sectp;
2678       dwz_file->macro.size = bfd_get_section_size (sectp);
2679     }
2680   else if (section_is_p (sectp->name, &dwarf2_elf_names.gdb_index))
2681     {
2682       dwz_file->gdb_index.s.section = sectp;
2683       dwz_file->gdb_index.size = bfd_get_section_size (sectp);
2684     }
2685 }
2686
2687 /* Open the separate '.dwz' debug file, if needed.  Return NULL if
2688    there is no .gnu_debugaltlink section in the file.  Error if there
2689    is such a section but the file cannot be found.  */
2690
2691 static struct dwz_file *
2692 dwarf2_get_dwz_file (void)
2693 {
2694   char *data;
2695   struct cleanup *cleanup;
2696   const char *filename;
2697   struct dwz_file *result;
2698   bfd_size_type buildid_len_arg;
2699   size_t buildid_len;
2700   bfd_byte *buildid;
2701
2702   if (dwarf2_per_objfile->dwz_file != NULL)
2703     return dwarf2_per_objfile->dwz_file;
2704
2705   bfd_set_error (bfd_error_no_error);
2706   data = bfd_get_alt_debug_link_info (dwarf2_per_objfile->objfile->obfd,
2707                                       &buildid_len_arg, &buildid);
2708   if (data == NULL)
2709     {
2710       if (bfd_get_error () == bfd_error_no_error)
2711         return NULL;
2712       error (_("could not read '.gnu_debugaltlink' section: %s"),
2713              bfd_errmsg (bfd_get_error ()));
2714     }
2715   cleanup = make_cleanup (xfree, data);
2716   make_cleanup (xfree, buildid);
2717
2718   buildid_len = (size_t) buildid_len_arg;
2719
2720   filename = (const char *) data;
2721
2722   std::string abs_storage;
2723   if (!IS_ABSOLUTE_PATH (filename))
2724     {
2725       gdb::unique_xmalloc_ptr<char> abs
2726         = gdb_realpath (objfile_name (dwarf2_per_objfile->objfile));
2727
2728       abs_storage = ldirname (abs.get ()) + SLASH_STRING + filename;
2729       filename = abs_storage.c_str ();
2730     }
2731
2732   /* First try the file name given in the section.  If that doesn't
2733      work, try to use the build-id instead.  */
2734   gdb_bfd_ref_ptr dwz_bfd (gdb_bfd_open (filename, gnutarget, -1));
2735   if (dwz_bfd != NULL)
2736     {
2737       if (!build_id_verify (dwz_bfd.get (), buildid_len, buildid))
2738         dwz_bfd.release ();
2739     }
2740
2741   if (dwz_bfd == NULL)
2742     dwz_bfd = build_id_to_debug_bfd (buildid_len, buildid);
2743
2744   if (dwz_bfd == NULL)
2745     error (_("could not find '.gnu_debugaltlink' file for %s"),
2746            objfile_name (dwarf2_per_objfile->objfile));
2747
2748   result = OBSTACK_ZALLOC (&dwarf2_per_objfile->objfile->objfile_obstack,
2749                            struct dwz_file);
2750   result->dwz_bfd = dwz_bfd.release ();
2751
2752   bfd_map_over_sections (result->dwz_bfd, locate_dwz_sections, result);
2753
2754   do_cleanups (cleanup);
2755
2756   gdb_bfd_record_inclusion (dwarf2_per_objfile->objfile->obfd, result->dwz_bfd);
2757   dwarf2_per_objfile->dwz_file = result;
2758   return result;
2759 }
2760 \f
2761 /* DWARF quick_symbols_functions support.  */
2762
2763 /* TUs can share .debug_line entries, and there can be a lot more TUs than
2764    unique line tables, so we maintain a separate table of all .debug_line
2765    derived entries to support the sharing.
2766    All the quick functions need is the list of file names.  We discard the
2767    line_header when we're done and don't need to record it here.  */
2768 struct quick_file_names
2769 {
2770   /* The data used to construct the hash key.  */
2771   struct stmt_list_hash hash;
2772
2773   /* The number of entries in file_names, real_names.  */
2774   unsigned int num_file_names;
2775
2776   /* The file names from the line table, after being run through
2777      file_full_name.  */
2778   const char **file_names;
2779
2780   /* The file names from the line table after being run through
2781      gdb_realpath.  These are computed lazily.  */
2782   const char **real_names;
2783 };
2784
2785 /* When using the index (and thus not using psymtabs), each CU has an
2786    object of this type.  This is used to hold information needed by
2787    the various "quick" methods.  */
2788 struct dwarf2_per_cu_quick_data
2789 {
2790   /* The file table.  This can be NULL if there was no file table
2791      or it's currently not read in.
2792      NOTE: This points into dwarf2_per_objfile->quick_file_names_table.  */
2793   struct quick_file_names *file_names;
2794
2795   /* The corresponding symbol table.  This is NULL if symbols for this
2796      CU have not yet been read.  */
2797   struct compunit_symtab *compunit_symtab;
2798
2799   /* A temporary mark bit used when iterating over all CUs in
2800      expand_symtabs_matching.  */
2801   unsigned int mark : 1;
2802
2803   /* True if we've tried to read the file table and found there isn't one.
2804      There will be no point in trying to read it again next time.  */
2805   unsigned int no_file_data : 1;
2806 };
2807
2808 /* Utility hash function for a stmt_list_hash.  */
2809
2810 static hashval_t
2811 hash_stmt_list_entry (const struct stmt_list_hash *stmt_list_hash)
2812 {
2813   hashval_t v = 0;
2814
2815   if (stmt_list_hash->dwo_unit != NULL)
2816     v += (uintptr_t) stmt_list_hash->dwo_unit->dwo_file;
2817   v += to_underlying (stmt_list_hash->line_sect_off);
2818   return v;
2819 }
2820
2821 /* Utility equality function for a stmt_list_hash.  */
2822
2823 static int
2824 eq_stmt_list_entry (const struct stmt_list_hash *lhs,
2825                     const struct stmt_list_hash *rhs)
2826 {
2827   if ((lhs->dwo_unit != NULL) != (rhs->dwo_unit != NULL))
2828     return 0;
2829   if (lhs->dwo_unit != NULL
2830       && lhs->dwo_unit->dwo_file != rhs->dwo_unit->dwo_file)
2831     return 0;
2832
2833   return lhs->line_sect_off == rhs->line_sect_off;
2834 }
2835
2836 /* Hash function for a quick_file_names.  */
2837
2838 static hashval_t
2839 hash_file_name_entry (const void *e)
2840 {
2841   const struct quick_file_names *file_data
2842     = (const struct quick_file_names *) e;
2843
2844   return hash_stmt_list_entry (&file_data->hash);
2845 }
2846
2847 /* Equality function for a quick_file_names.  */
2848
2849 static int
2850 eq_file_name_entry (const void *a, const void *b)
2851 {
2852   const struct quick_file_names *ea = (const struct quick_file_names *) a;
2853   const struct quick_file_names *eb = (const struct quick_file_names *) b;
2854
2855   return eq_stmt_list_entry (&ea->hash, &eb->hash);
2856 }
2857
2858 /* Delete function for a quick_file_names.  */
2859
2860 static void
2861 delete_file_name_entry (void *e)
2862 {
2863   struct quick_file_names *file_data = (struct quick_file_names *) e;
2864   int i;
2865
2866   for (i = 0; i < file_data->num_file_names; ++i)
2867     {
2868       xfree ((void*) file_data->file_names[i]);
2869       if (file_data->real_names)
2870         xfree ((void*) file_data->real_names[i]);
2871     }
2872
2873   /* The space for the struct itself lives on objfile_obstack,
2874      so we don't free it here.  */
2875 }
2876
2877 /* Create a quick_file_names hash table.  */
2878
2879 static htab_t
2880 create_quick_file_names_table (unsigned int nr_initial_entries)
2881 {
2882   return htab_create_alloc (nr_initial_entries,
2883                             hash_file_name_entry, eq_file_name_entry,
2884                             delete_file_name_entry, xcalloc, xfree);
2885 }
2886
2887 /* Read in PER_CU->CU.  This function is unrelated to symtabs, symtab would
2888    have to be created afterwards.  You should call age_cached_comp_units after
2889    processing PER_CU->CU.  dw2_setup must have been already called.  */
2890
2891 static void
2892 load_cu (struct dwarf2_per_cu_data *per_cu)
2893 {
2894   if (per_cu->is_debug_types)
2895     load_full_type_unit (per_cu);
2896   else
2897     load_full_comp_unit (per_cu, language_minimal);
2898
2899   if (per_cu->cu == NULL)
2900     return;  /* Dummy CU.  */
2901
2902   dwarf2_find_base_address (per_cu->cu->dies, per_cu->cu);
2903 }
2904
2905 /* Read in the symbols for PER_CU.  */
2906
2907 static void
2908 dw2_do_instantiate_symtab (struct dwarf2_per_cu_data *per_cu)
2909 {
2910   struct cleanup *back_to;
2911
2912   /* Skip type_unit_groups, reading the type units they contain
2913      is handled elsewhere.  */
2914   if (IS_TYPE_UNIT_GROUP (per_cu))
2915     return;
2916
2917   back_to = make_cleanup (dwarf2_release_queue, NULL);
2918
2919   if (dwarf2_per_objfile->using_index
2920       ? per_cu->v.quick->compunit_symtab == NULL
2921       : (per_cu->v.psymtab == NULL || !per_cu->v.psymtab->readin))
2922     {
2923       queue_comp_unit (per_cu, language_minimal);
2924       load_cu (per_cu);
2925
2926       /* If we just loaded a CU from a DWO, and we're working with an index
2927          that may badly handle TUs, load all the TUs in that DWO as well.
2928          http://sourceware.org/bugzilla/show_bug.cgi?id=15021  */
2929       if (!per_cu->is_debug_types
2930           && per_cu->cu != NULL
2931           && per_cu->cu->dwo_unit != NULL
2932           && dwarf2_per_objfile->index_table != NULL
2933           && dwarf2_per_objfile->index_table->version <= 7
2934           /* DWP files aren't supported yet.  */
2935           && get_dwp_file () == NULL)
2936         queue_and_load_all_dwo_tus (per_cu);
2937     }
2938
2939   process_queue ();
2940
2941   /* Age the cache, releasing compilation units that have not
2942      been used recently.  */
2943   age_cached_comp_units ();
2944
2945   do_cleanups (back_to);
2946 }
2947
2948 /* Ensure that the symbols for PER_CU have been read in.  OBJFILE is
2949    the objfile from which this CU came.  Returns the resulting symbol
2950    table.  */
2951
2952 static struct compunit_symtab *
2953 dw2_instantiate_symtab (struct dwarf2_per_cu_data *per_cu)
2954 {
2955   gdb_assert (dwarf2_per_objfile->using_index);
2956   if (!per_cu->v.quick->compunit_symtab)
2957     {
2958       struct cleanup *back_to = make_cleanup (free_cached_comp_units, NULL);
2959       scoped_restore decrementer = increment_reading_symtab ();
2960       dw2_do_instantiate_symtab (per_cu);
2961       process_cu_includes ();
2962       do_cleanups (back_to);
2963     }
2964
2965   return per_cu->v.quick->compunit_symtab;
2966 }
2967
2968 /* Return the CU/TU given its index.
2969
2970    This is intended for loops like:
2971
2972    for (i = 0; i < (dwarf2_per_objfile->n_comp_units
2973                     + dwarf2_per_objfile->n_type_units); ++i)
2974      {
2975        struct dwarf2_per_cu_data *per_cu = dw2_get_cutu (i);
2976
2977        ...;
2978      }
2979 */
2980
2981 static struct dwarf2_per_cu_data *
2982 dw2_get_cutu (int index)
2983 {
2984   if (index >= dwarf2_per_objfile->n_comp_units)
2985     {
2986       index -= dwarf2_per_objfile->n_comp_units;
2987       gdb_assert (index < dwarf2_per_objfile->n_type_units);
2988       return &dwarf2_per_objfile->all_type_units[index]->per_cu;
2989     }
2990
2991   return dwarf2_per_objfile->all_comp_units[index];
2992 }
2993
2994 /* Return the CU given its index.
2995    This differs from dw2_get_cutu in that it's for when you know INDEX
2996    refers to a CU.  */
2997
2998 static struct dwarf2_per_cu_data *
2999 dw2_get_cu (int index)
3000 {
3001   gdb_assert (index >= 0 && index < dwarf2_per_objfile->n_comp_units);
3002
3003   return dwarf2_per_objfile->all_comp_units[index];
3004 }
3005
3006 /* A helper for create_cus_from_index that handles a given list of
3007    CUs.  */
3008
3009 static void
3010 create_cus_from_index_list (struct objfile *objfile,
3011                             const gdb_byte *cu_list, offset_type n_elements,
3012                             struct dwarf2_section_info *section,
3013                             int is_dwz,
3014                             int base_offset)
3015 {
3016   offset_type i;
3017
3018   for (i = 0; i < n_elements; i += 2)
3019     {
3020       gdb_static_assert (sizeof (ULONGEST) >= 8);
3021
3022       sect_offset sect_off
3023         = (sect_offset) extract_unsigned_integer (cu_list, 8, BFD_ENDIAN_LITTLE);
3024       ULONGEST length = extract_unsigned_integer (cu_list + 8, 8, BFD_ENDIAN_LITTLE);
3025       cu_list += 2 * 8;
3026
3027       dwarf2_per_cu_data *the_cu
3028         = OBSTACK_ZALLOC (&objfile->objfile_obstack,
3029                           struct dwarf2_per_cu_data);
3030       the_cu->sect_off = sect_off;
3031       the_cu->length = length;
3032       the_cu->objfile = objfile;
3033       the_cu->section = section;
3034       the_cu->v.quick = OBSTACK_ZALLOC (&objfile->objfile_obstack,
3035                                         struct dwarf2_per_cu_quick_data);
3036       the_cu->is_dwz = is_dwz;
3037       dwarf2_per_objfile->all_comp_units[base_offset + i / 2] = the_cu;
3038     }
3039 }
3040
3041 /* Read the CU list from the mapped index, and use it to create all
3042    the CU objects for this objfile.  */
3043
3044 static void
3045 create_cus_from_index (struct objfile *objfile,
3046                        const gdb_byte *cu_list, offset_type cu_list_elements,
3047                        const gdb_byte *dwz_list, offset_type dwz_elements)
3048 {
3049   struct dwz_file *dwz;
3050
3051   dwarf2_per_objfile->n_comp_units = (cu_list_elements + dwz_elements) / 2;
3052   dwarf2_per_objfile->all_comp_units =
3053     XOBNEWVEC (&objfile->objfile_obstack, struct dwarf2_per_cu_data *,
3054                dwarf2_per_objfile->n_comp_units);
3055
3056   create_cus_from_index_list (objfile, cu_list, cu_list_elements,
3057                               &dwarf2_per_objfile->info, 0, 0);
3058
3059   if (dwz_elements == 0)
3060     return;
3061
3062   dwz = dwarf2_get_dwz_file ();
3063   create_cus_from_index_list (objfile, dwz_list, dwz_elements, &dwz->info, 1,
3064                               cu_list_elements / 2);
3065 }
3066
3067 /* Create the signatured type hash table from the index.  */
3068
3069 static void
3070 create_signatured_type_table_from_index (struct objfile *objfile,
3071                                          struct dwarf2_section_info *section,
3072                                          const gdb_byte *bytes,
3073                                          offset_type elements)
3074 {
3075   offset_type i;
3076   htab_t sig_types_hash;
3077
3078   dwarf2_per_objfile->n_type_units
3079     = dwarf2_per_objfile->n_allocated_type_units
3080     = elements / 3;
3081   dwarf2_per_objfile->all_type_units =
3082     XNEWVEC (struct signatured_type *, dwarf2_per_objfile->n_type_units);
3083
3084   sig_types_hash = allocate_signatured_type_table (objfile);
3085
3086   for (i = 0; i < elements; i += 3)
3087     {
3088       struct signatured_type *sig_type;
3089       ULONGEST signature;
3090       void **slot;
3091       cu_offset type_offset_in_tu;
3092
3093       gdb_static_assert (sizeof (ULONGEST) >= 8);
3094       sect_offset sect_off
3095         = (sect_offset) extract_unsigned_integer (bytes, 8, BFD_ENDIAN_LITTLE);
3096       type_offset_in_tu
3097         = (cu_offset) extract_unsigned_integer (bytes + 8, 8,
3098                                                 BFD_ENDIAN_LITTLE);
3099       signature = extract_unsigned_integer (bytes + 16, 8, BFD_ENDIAN_LITTLE);
3100       bytes += 3 * 8;
3101
3102       sig_type = OBSTACK_ZALLOC (&objfile->objfile_obstack,
3103                                  struct signatured_type);
3104       sig_type->signature = signature;
3105       sig_type->type_offset_in_tu = type_offset_in_tu;
3106       sig_type->per_cu.is_debug_types = 1;
3107       sig_type->per_cu.section = section;
3108       sig_type->per_cu.sect_off = sect_off;
3109       sig_type->per_cu.objfile = objfile;
3110       sig_type->per_cu.v.quick
3111         = OBSTACK_ZALLOC (&objfile->objfile_obstack,
3112                           struct dwarf2_per_cu_quick_data);
3113
3114       slot = htab_find_slot (sig_types_hash, sig_type, INSERT);
3115       *slot = sig_type;
3116
3117       dwarf2_per_objfile->all_type_units[i / 3] = sig_type;
3118     }
3119
3120   dwarf2_per_objfile->signatured_types = sig_types_hash;
3121 }
3122
3123 /* Read the address map data from the mapped index, and use it to
3124    populate the objfile's psymtabs_addrmap.  */
3125
3126 static void
3127 create_addrmap_from_index (struct objfile *objfile, struct mapped_index *index)
3128 {
3129   struct gdbarch *gdbarch = get_objfile_arch (objfile);
3130   const gdb_byte *iter, *end;
3131   struct addrmap *mutable_map;
3132   CORE_ADDR baseaddr;
3133
3134   auto_obstack temp_obstack;
3135
3136   mutable_map = addrmap_create_mutable (&temp_obstack);
3137
3138   iter = index->address_table;
3139   end = iter + index->address_table_size;
3140
3141   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
3142
3143   while (iter < end)
3144     {
3145       ULONGEST hi, lo, cu_index;
3146       lo = extract_unsigned_integer (iter, 8, BFD_ENDIAN_LITTLE);
3147       iter += 8;
3148       hi = extract_unsigned_integer (iter, 8, BFD_ENDIAN_LITTLE);
3149       iter += 8;
3150       cu_index = extract_unsigned_integer (iter, 4, BFD_ENDIAN_LITTLE);
3151       iter += 4;
3152
3153       if (lo > hi)
3154         {
3155           complaint (&symfile_complaints,
3156                      _(".gdb_index address table has invalid range (%s - %s)"),
3157                      hex_string (lo), hex_string (hi));
3158           continue;
3159         }
3160
3161       if (cu_index >= dwarf2_per_objfile->n_comp_units)
3162         {
3163           complaint (&symfile_complaints,
3164                      _(".gdb_index address table has invalid CU number %u"),
3165                      (unsigned) cu_index);
3166           continue;
3167         }
3168
3169       lo = gdbarch_adjust_dwarf2_addr (gdbarch, lo + baseaddr);
3170       hi = gdbarch_adjust_dwarf2_addr (gdbarch, hi + baseaddr);
3171       addrmap_set_empty (mutable_map, lo, hi - 1, dw2_get_cutu (cu_index));
3172     }
3173
3174   objfile->psymtabs_addrmap = addrmap_create_fixed (mutable_map,
3175                                                     &objfile->objfile_obstack);
3176 }
3177
3178 /* The hash function for strings in the mapped index.  This is the same as
3179    SYMBOL_HASH_NEXT, but we keep a separate copy to maintain control over the
3180    implementation.  This is necessary because the hash function is tied to the
3181    format of the mapped index file.  The hash values do not have to match with
3182    SYMBOL_HASH_NEXT.
3183    
3184    Use INT_MAX for INDEX_VERSION if you generate the current index format.  */
3185
3186 static hashval_t
3187 mapped_index_string_hash (int index_version, const void *p)
3188 {
3189   const unsigned char *str = (const unsigned char *) p;
3190   hashval_t r = 0;
3191   unsigned char c;
3192
3193   while ((c = *str++) != 0)
3194     {
3195       if (index_version >= 5)
3196         c = tolower (c);
3197       r = r * 67 + c - 113;
3198     }
3199
3200   return r;
3201 }
3202
3203 /* Find a slot in the mapped index INDEX for the object named NAME.
3204    If NAME is found, set *VEC_OUT to point to the CU vector in the
3205    constant pool and return 1.  If NAME cannot be found, return 0.  */
3206
3207 static int
3208 find_slot_in_mapped_hash (struct mapped_index *index, const char *name,
3209                           offset_type **vec_out)
3210 {
3211   struct cleanup *back_to = make_cleanup (null_cleanup, 0);
3212   offset_type hash;
3213   offset_type slot, step;
3214   int (*cmp) (const char *, const char *);
3215
3216   if (current_language->la_language == language_cplus
3217       || current_language->la_language == language_fortran
3218       || current_language->la_language == language_d)
3219     {
3220       /* NAME is already canonical.  Drop any qualifiers as .gdb_index does
3221          not contain any.  */
3222
3223       if (strchr (name, '(') != NULL)
3224         {
3225           char *without_params = cp_remove_params (name);
3226
3227           if (without_params != NULL)
3228             {
3229               make_cleanup (xfree, without_params);
3230               name = without_params;
3231             }
3232         }
3233     }
3234
3235   /* Index version 4 did not support case insensitive searches.  But the
3236      indices for case insensitive languages are built in lowercase, therefore
3237      simulate our NAME being searched is also lowercased.  */
3238   hash = mapped_index_string_hash ((index->version == 4
3239                                     && case_sensitivity == case_sensitive_off
3240                                     ? 5 : index->version),
3241                                    name);
3242
3243   slot = hash & (index->symbol_table_slots - 1);
3244   step = ((hash * 17) & (index->symbol_table_slots - 1)) | 1;
3245   cmp = (case_sensitivity == case_sensitive_on ? strcmp : strcasecmp);
3246
3247   for (;;)
3248     {
3249       /* Convert a slot number to an offset into the table.  */
3250       offset_type i = 2 * slot;
3251       const char *str;
3252       if (index->symbol_table[i] == 0 && index->symbol_table[i + 1] == 0)
3253         {
3254           do_cleanups (back_to);
3255           return 0;
3256         }
3257
3258       str = index->constant_pool + MAYBE_SWAP (index->symbol_table[i]);
3259       if (!cmp (name, str))
3260         {
3261           *vec_out = (offset_type *) (index->constant_pool
3262                                       + MAYBE_SWAP (index->symbol_table[i + 1]));
3263           do_cleanups (back_to);
3264           return 1;
3265         }
3266
3267       slot = (slot + step) & (index->symbol_table_slots - 1);
3268     }
3269 }
3270
3271 /* A helper function that reads the .gdb_index from SECTION and fills
3272    in MAP.  FILENAME is the name of the file containing the section;
3273    it is used for error reporting.  DEPRECATED_OK is nonzero if it is
3274    ok to use deprecated sections.
3275
3276    CU_LIST, CU_LIST_ELEMENTS, TYPES_LIST, and TYPES_LIST_ELEMENTS are
3277    out parameters that are filled in with information about the CU and
3278    TU lists in the section.
3279
3280    Returns 1 if all went well, 0 otherwise.  */
3281
3282 static int
3283 read_index_from_section (struct objfile *objfile,
3284                          const char *filename,
3285                          int deprecated_ok,
3286                          struct dwarf2_section_info *section,
3287                          struct mapped_index *map,
3288                          const gdb_byte **cu_list,
3289                          offset_type *cu_list_elements,
3290                          const gdb_byte **types_list,
3291                          offset_type *types_list_elements)
3292 {
3293   const gdb_byte *addr;
3294   offset_type version;
3295   offset_type *metadata;
3296   int i;
3297
3298   if (dwarf2_section_empty_p (section))
3299     return 0;
3300
3301   /* Older elfutils strip versions could keep the section in the main
3302      executable while splitting it for the separate debug info file.  */
3303   if ((get_section_flags (section) & SEC_HAS_CONTENTS) == 0)
3304     return 0;
3305
3306   dwarf2_read_section (objfile, section);
3307
3308   addr = section->buffer;
3309   /* Version check.  */
3310   version = MAYBE_SWAP (*(offset_type *) addr);
3311   /* Versions earlier than 3 emitted every copy of a psymbol.  This
3312      causes the index to behave very poorly for certain requests.  Version 3
3313      contained incomplete addrmap.  So, it seems better to just ignore such
3314      indices.  */
3315   if (version < 4)
3316     {
3317       static int warning_printed = 0;
3318       if (!warning_printed)
3319         {
3320           warning (_("Skipping obsolete .gdb_index section in %s."),
3321                    filename);
3322           warning_printed = 1;
3323         }
3324       return 0;
3325     }
3326   /* Index version 4 uses a different hash function than index version
3327      5 and later.
3328
3329      Versions earlier than 6 did not emit psymbols for inlined
3330      functions.  Using these files will cause GDB not to be able to
3331      set breakpoints on inlined functions by name, so we ignore these
3332      indices unless the user has done
3333      "set use-deprecated-index-sections on".  */
3334   if (version < 6 && !deprecated_ok)
3335     {
3336       static int warning_printed = 0;
3337       if (!warning_printed)
3338         {
3339           warning (_("\
3340 Skipping deprecated .gdb_index section in %s.\n\
3341 Do \"set use-deprecated-index-sections on\" before the file is read\n\
3342 to use the section anyway."),
3343                    filename);
3344           warning_printed = 1;
3345         }
3346       return 0;
3347     }
3348   /* Version 7 indices generated by gold refer to the CU for a symbol instead
3349      of the TU (for symbols coming from TUs),
3350      http://sourceware.org/bugzilla/show_bug.cgi?id=15021.
3351      Plus gold-generated indices can have duplicate entries for global symbols,
3352      http://sourceware.org/bugzilla/show_bug.cgi?id=15646.
3353      These are just performance bugs, and we can't distinguish gdb-generated
3354      indices from gold-generated ones, so issue no warning here.  */
3355
3356   /* Indexes with higher version than the one supported by GDB may be no
3357      longer backward compatible.  */
3358   if (version > 8)
3359     return 0;
3360
3361   map->version = version;
3362   map->total_size = section->size;
3363
3364   metadata = (offset_type *) (addr + sizeof (offset_type));
3365
3366   i = 0;
3367   *cu_list = addr + MAYBE_SWAP (metadata[i]);
3368   *cu_list_elements = ((MAYBE_SWAP (metadata[i + 1]) - MAYBE_SWAP (metadata[i]))
3369                        / 8);
3370   ++i;
3371
3372   *types_list = addr + MAYBE_SWAP (metadata[i]);
3373   *types_list_elements = ((MAYBE_SWAP (metadata[i + 1])
3374                            - MAYBE_SWAP (metadata[i]))
3375                           / 8);
3376   ++i;
3377
3378   map->address_table = addr + MAYBE_SWAP (metadata[i]);
3379   map->address_table_size = (MAYBE_SWAP (metadata[i + 1])
3380                              - MAYBE_SWAP (metadata[i]));
3381   ++i;
3382
3383   map->symbol_table = (offset_type *) (addr + MAYBE_SWAP (metadata[i]));
3384   map->symbol_table_slots = ((MAYBE_SWAP (metadata[i + 1])
3385                               - MAYBE_SWAP (metadata[i]))
3386                              / (2 * sizeof (offset_type)));
3387   ++i;
3388
3389   map->constant_pool = (char *) (addr + MAYBE_SWAP (metadata[i]));
3390
3391   return 1;
3392 }
3393
3394
3395 /* Read the index file.  If everything went ok, initialize the "quick"
3396    elements of all the CUs and return 1.  Otherwise, return 0.  */
3397
3398 static int
3399 dwarf2_read_index (struct objfile *objfile)
3400 {
3401   struct mapped_index local_map, *map;
3402   const gdb_byte *cu_list, *types_list, *dwz_list = NULL;
3403   offset_type cu_list_elements, types_list_elements, dwz_list_elements = 0;
3404   struct dwz_file *dwz;
3405
3406   if (!read_index_from_section (objfile, objfile_name (objfile),
3407                                 use_deprecated_index_sections,
3408                                 &dwarf2_per_objfile->gdb_index, &local_map,
3409                                 &cu_list, &cu_list_elements,
3410                                 &types_list, &types_list_elements))
3411     return 0;
3412
3413   /* Don't use the index if it's empty.  */
3414   if (local_map.symbol_table_slots == 0)
3415     return 0;
3416
3417   /* If there is a .dwz file, read it so we can get its CU list as
3418      well.  */
3419   dwz = dwarf2_get_dwz_file ();
3420   if (dwz != NULL)
3421     {
3422       struct mapped_index dwz_map;
3423       const gdb_byte *dwz_types_ignore;
3424       offset_type dwz_types_elements_ignore;
3425
3426       if (!read_index_from_section (objfile, bfd_get_filename (dwz->dwz_bfd),
3427                                     1,
3428                                     &dwz->gdb_index, &dwz_map,
3429                                     &dwz_list, &dwz_list_elements,
3430                                     &dwz_types_ignore,
3431                                     &dwz_types_elements_ignore))
3432         {
3433           warning (_("could not read '.gdb_index' section from %s; skipping"),
3434                    bfd_get_filename (dwz->dwz_bfd));
3435           return 0;
3436         }
3437     }
3438
3439   create_cus_from_index (objfile, cu_list, cu_list_elements, dwz_list,
3440                          dwz_list_elements);
3441
3442   if (types_list_elements)
3443     {
3444       struct dwarf2_section_info *section;
3445
3446       /* We can only handle a single .debug_types when we have an
3447          index.  */
3448       if (VEC_length (dwarf2_section_info_def, dwarf2_per_objfile->types) != 1)
3449         return 0;
3450
3451       section = VEC_index (dwarf2_section_info_def,
3452                            dwarf2_per_objfile->types, 0);
3453
3454       create_signatured_type_table_from_index (objfile, section, types_list,
3455                                                types_list_elements);
3456     }
3457
3458   create_addrmap_from_index (objfile, &local_map);
3459
3460   map = XOBNEW (&objfile->objfile_obstack, struct mapped_index);
3461   *map = local_map;
3462
3463   dwarf2_per_objfile->index_table = map;
3464   dwarf2_per_objfile->using_index = 1;
3465   dwarf2_per_objfile->quick_file_names_table =
3466     create_quick_file_names_table (dwarf2_per_objfile->n_comp_units);
3467
3468   return 1;
3469 }
3470
3471 /* A helper for the "quick" functions which sets the global
3472    dwarf2_per_objfile according to OBJFILE.  */
3473
3474 static void
3475 dw2_setup (struct objfile *objfile)
3476 {
3477   dwarf2_per_objfile = ((struct dwarf2_per_objfile *)
3478                         objfile_data (objfile, dwarf2_objfile_data_key));
3479   gdb_assert (dwarf2_per_objfile);
3480 }
3481
3482 /* die_reader_func for dw2_get_file_names.  */
3483
3484 static void
3485 dw2_get_file_names_reader (const struct die_reader_specs *reader,
3486                            const gdb_byte *info_ptr,
3487                            struct die_info *comp_unit_die,
3488                            int has_children,
3489                            void *data)
3490 {
3491   struct dwarf2_cu *cu = reader->cu;
3492   struct dwarf2_per_cu_data *this_cu = cu->per_cu;  
3493   struct objfile *objfile = dwarf2_per_objfile->objfile;
3494   struct dwarf2_per_cu_data *lh_cu;
3495   struct attribute *attr;
3496   int i;
3497   void **slot;
3498   struct quick_file_names *qfn;
3499
3500   gdb_assert (! this_cu->is_debug_types);
3501
3502   /* Our callers never want to match partial units -- instead they
3503      will match the enclosing full CU.  */
3504   if (comp_unit_die->tag == DW_TAG_partial_unit)
3505     {
3506       this_cu->v.quick->no_file_data = 1;
3507       return;
3508     }
3509
3510   lh_cu = this_cu;
3511   slot = NULL;
3512
3513   line_header_up lh;
3514   sect_offset line_offset {};
3515
3516   attr = dwarf2_attr (comp_unit_die, DW_AT_stmt_list, cu);
3517   if (attr)
3518     {
3519       struct quick_file_names find_entry;
3520
3521       line_offset = (sect_offset) DW_UNSND (attr);
3522
3523       /* We may have already read in this line header (TU line header sharing).
3524          If we have we're done.  */
3525       find_entry.hash.dwo_unit = cu->dwo_unit;
3526       find_entry.hash.line_sect_off = line_offset;
3527       slot = htab_find_slot (dwarf2_per_objfile->quick_file_names_table,
3528                              &find_entry, INSERT);
3529       if (*slot != NULL)
3530         {
3531           lh_cu->v.quick->file_names = (struct quick_file_names *) *slot;
3532           return;
3533         }
3534
3535       lh = dwarf_decode_line_header (line_offset, cu);
3536     }
3537   if (lh == NULL)
3538     {
3539       lh_cu->v.quick->no_file_data = 1;
3540       return;
3541     }
3542
3543   qfn = XOBNEW (&objfile->objfile_obstack, struct quick_file_names);
3544   qfn->hash.dwo_unit = cu->dwo_unit;
3545   qfn->hash.line_sect_off = line_offset;
3546   gdb_assert (slot != NULL);
3547   *slot = qfn;
3548
3549   file_and_directory fnd = find_file_and_directory (comp_unit_die, cu);
3550
3551   qfn->num_file_names = lh->file_names.size ();
3552   qfn->file_names =
3553     XOBNEWVEC (&objfile->objfile_obstack, const char *, lh->file_names.size ());
3554   for (i = 0; i < lh->file_names.size (); ++i)
3555     qfn->file_names[i] = file_full_name (i + 1, lh.get (), fnd.comp_dir);
3556   qfn->real_names = NULL;
3557
3558   lh_cu->v.quick->file_names = qfn;
3559 }
3560
3561 /* A helper for the "quick" functions which attempts to read the line
3562    table for THIS_CU.  */
3563
3564 static struct quick_file_names *
3565 dw2_get_file_names (struct dwarf2_per_cu_data *this_cu)
3566 {
3567   /* This should never be called for TUs.  */
3568   gdb_assert (! this_cu->is_debug_types);
3569   /* Nor type unit groups.  */
3570   gdb_assert (! IS_TYPE_UNIT_GROUP (this_cu));
3571
3572   if (this_cu->v.quick->file_names != NULL)
3573     return this_cu->v.quick->file_names;
3574   /* If we know there is no line data, no point in looking again.  */
3575   if (this_cu->v.quick->no_file_data)
3576     return NULL;
3577
3578   init_cutu_and_read_dies_simple (this_cu, dw2_get_file_names_reader, NULL);
3579
3580   if (this_cu->v.quick->no_file_data)
3581     return NULL;
3582   return this_cu->v.quick->file_names;
3583 }
3584
3585 /* A helper for the "quick" functions which computes and caches the
3586    real path for a given file name from the line table.  */
3587
3588 static const char *
3589 dw2_get_real_path (struct objfile *objfile,
3590                    struct quick_file_names *qfn, int index)
3591 {
3592   if (qfn->real_names == NULL)
3593     qfn->real_names = OBSTACK_CALLOC (&objfile->objfile_obstack,
3594                                       qfn->num_file_names, const char *);
3595
3596   if (qfn->real_names[index] == NULL)
3597     qfn->real_names[index] = gdb_realpath (qfn->file_names[index]).release ();
3598
3599   return qfn->real_names[index];
3600 }
3601
3602 static struct symtab *
3603 dw2_find_last_source_symtab (struct objfile *objfile)
3604 {
3605   struct compunit_symtab *cust;
3606   int index;
3607
3608   dw2_setup (objfile);
3609   index = dwarf2_per_objfile->n_comp_units - 1;
3610   cust = dw2_instantiate_symtab (dw2_get_cutu (index));
3611   if (cust == NULL)
3612     return NULL;
3613   return compunit_primary_filetab (cust);
3614 }
3615
3616 /* Traversal function for dw2_forget_cached_source_info.  */
3617
3618 static int
3619 dw2_free_cached_file_names (void **slot, void *info)
3620 {
3621   struct quick_file_names *file_data = (struct quick_file_names *) *slot;
3622
3623   if (file_data->real_names)
3624     {
3625       int i;
3626
3627       for (i = 0; i < file_data->num_file_names; ++i)
3628         {
3629           xfree ((void*) file_data->real_names[i]);
3630           file_data->real_names[i] = NULL;
3631         }
3632     }
3633
3634   return 1;
3635 }
3636
3637 static void
3638 dw2_forget_cached_source_info (struct objfile *objfile)
3639 {
3640   dw2_setup (objfile);
3641
3642   htab_traverse_noresize (dwarf2_per_objfile->quick_file_names_table,
3643                           dw2_free_cached_file_names, NULL);
3644 }
3645
3646 /* Helper function for dw2_map_symtabs_matching_filename that expands
3647    the symtabs and calls the iterator.  */
3648
3649 static int
3650 dw2_map_expand_apply (struct objfile *objfile,
3651                       struct dwarf2_per_cu_data *per_cu,
3652                       const char *name, const char *real_path,
3653                       gdb::function_view<bool (symtab *)> callback)
3654 {
3655   struct compunit_symtab *last_made = objfile->compunit_symtabs;
3656
3657   /* Don't visit already-expanded CUs.  */
3658   if (per_cu->v.quick->compunit_symtab)
3659     return 0;
3660
3661   /* This may expand more than one symtab, and we want to iterate over
3662      all of them.  */
3663   dw2_instantiate_symtab (per_cu);
3664
3665   return iterate_over_some_symtabs (name, real_path, objfile->compunit_symtabs,
3666                                     last_made, callback);
3667 }
3668
3669 /* Implementation of the map_symtabs_matching_filename method.  */
3670
3671 static bool
3672 dw2_map_symtabs_matching_filename
3673   (struct objfile *objfile, const char *name, const char *real_path,
3674    gdb::function_view<bool (symtab *)> callback)
3675 {
3676   int i;
3677   const char *name_basename = lbasename (name);
3678
3679   dw2_setup (objfile);
3680
3681   /* The rule is CUs specify all the files, including those used by
3682      any TU, so there's no need to scan TUs here.  */
3683
3684   for (i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
3685     {
3686       int j;
3687       struct dwarf2_per_cu_data *per_cu = dw2_get_cu (i);
3688       struct quick_file_names *file_data;
3689
3690       /* We only need to look at symtabs not already expanded.  */
3691       if (per_cu->v.quick->compunit_symtab)
3692         continue;
3693
3694       file_data = dw2_get_file_names (per_cu);
3695       if (file_data == NULL)
3696         continue;
3697
3698       for (j = 0; j < file_data->num_file_names; ++j)
3699         {
3700           const char *this_name = file_data->file_names[j];
3701           const char *this_real_name;
3702
3703           if (compare_filenames_for_search (this_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           /* Before we invoke realpath, which can get expensive when many
3712              files are involved, do a quick comparison of the basenames.  */
3713           if (! basenames_may_differ
3714               && FILENAME_CMP (lbasename (this_name), name_basename) != 0)
3715             continue;
3716
3717           this_real_name = dw2_get_real_path (objfile, file_data, j);
3718           if (compare_filenames_for_search (this_real_name, name))
3719             {
3720               if (dw2_map_expand_apply (objfile, per_cu, name, real_path,
3721                                         callback))
3722                 return true;
3723               continue;
3724             }
3725
3726           if (real_path != NULL)
3727             {
3728               gdb_assert (IS_ABSOLUTE_PATH (real_path));
3729               gdb_assert (IS_ABSOLUTE_PATH (name));
3730               if (this_real_name != NULL
3731                   && FILENAME_CMP (real_path, this_real_name) == 0)
3732                 {
3733                   if (dw2_map_expand_apply (objfile, per_cu, name, real_path,
3734                                             callback))
3735                     return true;
3736                   continue;
3737                 }
3738             }
3739         }
3740     }
3741
3742   return false;
3743 }
3744
3745 /* Struct used to manage iterating over all CUs looking for a symbol.  */
3746
3747 struct dw2_symtab_iterator
3748 {
3749   /* The internalized form of .gdb_index.  */
3750   struct mapped_index *index;
3751   /* If non-zero, only look for symbols that match BLOCK_INDEX.  */
3752   int want_specific_block;
3753   /* One of GLOBAL_BLOCK or STATIC_BLOCK.
3754      Unused if !WANT_SPECIFIC_BLOCK.  */
3755   int block_index;
3756   /* The kind of symbol we're looking for.  */
3757   domain_enum domain;
3758   /* The list of CUs from the index entry of the symbol,
3759      or NULL if not found.  */
3760   offset_type *vec;
3761   /* The next element in VEC to look at.  */
3762   int next;
3763   /* The number of elements in VEC, or zero if there is no match.  */
3764   int length;
3765   /* Have we seen a global version of the symbol?
3766      If so we can ignore all further global instances.
3767      This is to work around gold/15646, inefficient gold-generated
3768      indices.  */
3769   int global_seen;
3770 };
3771
3772 /* Initialize the index symtab iterator ITER.
3773    If WANT_SPECIFIC_BLOCK is non-zero, only look for symbols
3774    in block BLOCK_INDEX.  Otherwise BLOCK_INDEX is ignored.  */
3775
3776 static void
3777 dw2_symtab_iter_init (struct dw2_symtab_iterator *iter,
3778                       struct mapped_index *index,
3779                       int want_specific_block,
3780                       int block_index,
3781                       domain_enum domain,
3782                       const char *name)
3783 {
3784   iter->index = index;
3785   iter->want_specific_block = want_specific_block;
3786   iter->block_index = block_index;
3787   iter->domain = domain;
3788   iter->next = 0;
3789   iter->global_seen = 0;
3790
3791   if (find_slot_in_mapped_hash (index, name, &iter->vec))
3792     iter->length = MAYBE_SWAP (*iter->vec);
3793   else
3794     {
3795       iter->vec = NULL;
3796       iter->length = 0;
3797     }
3798 }
3799
3800 /* Return the next matching CU or NULL if there are no more.  */
3801
3802 static struct dwarf2_per_cu_data *
3803 dw2_symtab_iter_next (struct dw2_symtab_iterator *iter)
3804 {
3805   for ( ; iter->next < iter->length; ++iter->next)
3806     {
3807       offset_type cu_index_and_attrs =
3808         MAYBE_SWAP (iter->vec[iter->next + 1]);
3809       offset_type cu_index = GDB_INDEX_CU_VALUE (cu_index_and_attrs);
3810       struct dwarf2_per_cu_data *per_cu;
3811       int want_static = iter->block_index != GLOBAL_BLOCK;
3812       /* This value is only valid for index versions >= 7.  */
3813       int is_static = GDB_INDEX_SYMBOL_STATIC_VALUE (cu_index_and_attrs);
3814       gdb_index_symbol_kind symbol_kind =
3815         GDB_INDEX_SYMBOL_KIND_VALUE (cu_index_and_attrs);
3816       /* Only check the symbol attributes if they're present.
3817          Indices prior to version 7 don't record them,
3818          and indices >= 7 may elide them for certain symbols
3819          (gold does this).  */
3820       int attrs_valid =
3821         (iter->index->version >= 7
3822          && symbol_kind != GDB_INDEX_SYMBOL_KIND_NONE);
3823
3824       /* Don't crash on bad data.  */
3825       if (cu_index >= (dwarf2_per_objfile->n_comp_units
3826                        + dwarf2_per_objfile->n_type_units))
3827         {
3828           complaint (&symfile_complaints,
3829                      _(".gdb_index entry has bad CU index"
3830                        " [in module %s]"),
3831                      objfile_name (dwarf2_per_objfile->objfile));
3832           continue;
3833         }
3834
3835       per_cu = dw2_get_cutu (cu_index);
3836
3837       /* Skip if already read in.  */
3838       if (per_cu->v.quick->compunit_symtab)
3839         continue;
3840
3841       /* Check static vs global.  */
3842       if (attrs_valid)
3843         {
3844           if (iter->want_specific_block
3845               && want_static != is_static)
3846             continue;
3847           /* Work around gold/15646.  */
3848           if (!is_static && iter->global_seen)
3849             continue;
3850           if (!is_static)
3851             iter->global_seen = 1;
3852         }
3853
3854       /* Only check the symbol's kind if it has one.  */
3855       if (attrs_valid)
3856         {
3857           switch (iter->domain)
3858             {
3859             case VAR_DOMAIN:
3860               if (symbol_kind != GDB_INDEX_SYMBOL_KIND_VARIABLE
3861                   && symbol_kind != GDB_INDEX_SYMBOL_KIND_FUNCTION
3862                   /* Some types are also in VAR_DOMAIN.  */
3863                   && symbol_kind != GDB_INDEX_SYMBOL_KIND_TYPE)
3864                 continue;
3865               break;
3866             case STRUCT_DOMAIN:
3867               if (symbol_kind != GDB_INDEX_SYMBOL_KIND_TYPE)
3868                 continue;
3869               break;
3870             case LABEL_DOMAIN:
3871               if (symbol_kind != GDB_INDEX_SYMBOL_KIND_OTHER)
3872                 continue;
3873               break;
3874             default:
3875               break;
3876             }
3877         }
3878
3879       ++iter->next;
3880       return per_cu;
3881     }
3882
3883   return NULL;
3884 }
3885
3886 static struct compunit_symtab *
3887 dw2_lookup_symbol (struct objfile *objfile, int block_index,
3888                    const char *name, domain_enum domain)
3889 {
3890   struct compunit_symtab *stab_best = NULL;
3891   struct mapped_index *index;
3892
3893   dw2_setup (objfile);
3894
3895   index = dwarf2_per_objfile->index_table;
3896
3897   /* index is NULL if OBJF_READNOW.  */
3898   if (index)
3899     {
3900       struct dw2_symtab_iterator iter;
3901       struct dwarf2_per_cu_data *per_cu;
3902
3903       dw2_symtab_iter_init (&iter, index, 1, block_index, domain, name);
3904
3905       while ((per_cu = dw2_symtab_iter_next (&iter)) != NULL)
3906         {
3907           struct symbol *sym, *with_opaque = NULL;
3908           struct compunit_symtab *stab = dw2_instantiate_symtab (per_cu);
3909           const struct blockvector *bv = COMPUNIT_BLOCKVECTOR (stab);
3910           struct block *block = BLOCKVECTOR_BLOCK (bv, block_index);
3911
3912           sym = block_find_symbol (block, name, domain,
3913                                    block_find_non_opaque_type_preferred,
3914                                    &with_opaque);
3915
3916           /* Some caution must be observed with overloaded functions
3917              and methods, since the index will not contain any overload
3918              information (but NAME might contain it).  */
3919
3920           if (sym != NULL
3921               && SYMBOL_MATCHES_SEARCH_NAME (sym, name))
3922             return stab;
3923           if (with_opaque != NULL
3924               && SYMBOL_MATCHES_SEARCH_NAME (with_opaque, name))
3925             stab_best = stab;
3926
3927           /* Keep looking through other CUs.  */
3928         }
3929     }
3930
3931   return stab_best;
3932 }
3933
3934 static void
3935 dw2_print_stats (struct objfile *objfile)
3936 {
3937   int i, total, count;
3938
3939   dw2_setup (objfile);
3940   total = dwarf2_per_objfile->n_comp_units + dwarf2_per_objfile->n_type_units;
3941   count = 0;
3942   for (i = 0; i < total; ++i)
3943     {
3944       struct dwarf2_per_cu_data *per_cu = dw2_get_cutu (i);
3945
3946       if (!per_cu->v.quick->compunit_symtab)
3947         ++count;
3948     }
3949   printf_filtered (_("  Number of read CUs: %d\n"), total - count);
3950   printf_filtered (_("  Number of unread CUs: %d\n"), count);
3951 }
3952
3953 /* This dumps minimal information about the index.
3954    It is called via "mt print objfiles".
3955    One use is to verify .gdb_index has been loaded by the
3956    gdb.dwarf2/gdb-index.exp testcase.  */
3957
3958 static void
3959 dw2_dump (struct objfile *objfile)
3960 {
3961   dw2_setup (objfile);
3962   gdb_assert (dwarf2_per_objfile->using_index);
3963   printf_filtered (".gdb_index:");
3964   if (dwarf2_per_objfile->index_table != NULL)
3965     {
3966       printf_filtered (" version %d\n",
3967                        dwarf2_per_objfile->index_table->version);
3968     }
3969   else
3970     printf_filtered (" faked for \"readnow\"\n");
3971   printf_filtered ("\n");
3972 }
3973
3974 static void
3975 dw2_relocate (struct objfile *objfile,
3976               const struct section_offsets *new_offsets,
3977               const struct section_offsets *delta)
3978 {
3979   /* There's nothing to relocate here.  */
3980 }
3981
3982 static void
3983 dw2_expand_symtabs_for_function (struct objfile *objfile,
3984                                  const char *func_name)
3985 {
3986   struct mapped_index *index;
3987
3988   dw2_setup (objfile);
3989
3990   index = dwarf2_per_objfile->index_table;
3991
3992   /* index is NULL if OBJF_READNOW.  */
3993   if (index)
3994     {
3995       struct dw2_symtab_iterator iter;
3996       struct dwarf2_per_cu_data *per_cu;
3997
3998       /* Note: It doesn't matter what we pass for block_index here.  */
3999       dw2_symtab_iter_init (&iter, index, 0, GLOBAL_BLOCK, VAR_DOMAIN,
4000                             func_name);
4001
4002       while ((per_cu = dw2_symtab_iter_next (&iter)) != NULL)
4003         dw2_instantiate_symtab (per_cu);
4004     }
4005 }
4006
4007 static void
4008 dw2_expand_all_symtabs (struct objfile *objfile)
4009 {
4010   int i;
4011
4012   dw2_setup (objfile);
4013
4014   for (i = 0; i < (dwarf2_per_objfile->n_comp_units
4015                    + dwarf2_per_objfile->n_type_units); ++i)
4016     {
4017       struct dwarf2_per_cu_data *per_cu = dw2_get_cutu (i);
4018
4019       dw2_instantiate_symtab (per_cu);
4020     }
4021 }
4022
4023 static void
4024 dw2_expand_symtabs_with_fullname (struct objfile *objfile,
4025                                   const char *fullname)
4026 {
4027   int i;
4028
4029   dw2_setup (objfile);
4030
4031   /* We don't need to consider type units here.
4032      This is only called for examining code, e.g. expand_line_sal.
4033      There can be an order of magnitude (or more) more type units
4034      than comp units, and we avoid them if we can.  */
4035
4036   for (i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
4037     {
4038       int j;
4039       struct dwarf2_per_cu_data *per_cu = dw2_get_cutu (i);
4040       struct quick_file_names *file_data;
4041
4042       /* We only need to look at symtabs not already expanded.  */
4043       if (per_cu->v.quick->compunit_symtab)
4044         continue;
4045
4046       file_data = dw2_get_file_names (per_cu);
4047       if (file_data == NULL)
4048         continue;
4049
4050       for (j = 0; j < file_data->num_file_names; ++j)
4051         {
4052           const char *this_fullname = file_data->file_names[j];
4053
4054           if (filename_cmp (this_fullname, fullname) == 0)
4055             {
4056               dw2_instantiate_symtab (per_cu);
4057               break;
4058             }
4059         }
4060     }
4061 }
4062
4063 static void
4064 dw2_map_matching_symbols (struct objfile *objfile,
4065                           const char * name, domain_enum domain,
4066                           int global,
4067                           int (*callback) (struct block *,
4068                                            struct symbol *, void *),
4069                           void *data, symbol_compare_ftype *match,
4070                           symbol_compare_ftype *ordered_compare)
4071 {
4072   /* Currently unimplemented; used for Ada.  The function can be called if the
4073      current language is Ada for a non-Ada objfile using GNU index.  As Ada
4074      does not look for non-Ada symbols this function should just return.  */
4075 }
4076
4077 static void
4078 dw2_expand_symtabs_matching
4079   (struct objfile *objfile,
4080    gdb::function_view<expand_symtabs_file_matcher_ftype> file_matcher,
4081    gdb::function_view<expand_symtabs_symbol_matcher_ftype> symbol_matcher,
4082    gdb::function_view<expand_symtabs_exp_notify_ftype> expansion_notify,
4083    enum search_domain kind)
4084 {
4085   int i;
4086   offset_type iter;
4087   struct mapped_index *index;
4088
4089   dw2_setup (objfile);
4090
4091   /* index_table is NULL if OBJF_READNOW.  */
4092   if (!dwarf2_per_objfile->index_table)
4093     return;
4094   index = dwarf2_per_objfile->index_table;
4095
4096   if (file_matcher != NULL)
4097     {
4098       htab_up visited_found (htab_create_alloc (10, htab_hash_pointer,
4099                                                 htab_eq_pointer,
4100                                                 NULL, xcalloc, xfree));
4101       htab_up visited_not_found (htab_create_alloc (10, htab_hash_pointer,
4102                                                     htab_eq_pointer,
4103                                                     NULL, xcalloc, xfree));
4104
4105       /* The rule is CUs specify all the files, including those used by
4106          any TU, so there's no need to scan TUs here.  */
4107
4108       for (i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
4109         {
4110           int j;
4111           struct dwarf2_per_cu_data *per_cu = dw2_get_cu (i);
4112           struct quick_file_names *file_data;
4113           void **slot;
4114
4115           QUIT;
4116
4117           per_cu->v.quick->mark = 0;
4118
4119           /* We only need to look at symtabs not already expanded.  */
4120           if (per_cu->v.quick->compunit_symtab)
4121             continue;
4122
4123           file_data = dw2_get_file_names (per_cu);
4124           if (file_data == NULL)
4125             continue;
4126
4127           if (htab_find (visited_not_found.get (), file_data) != NULL)
4128             continue;
4129           else if (htab_find (visited_found.get (), file_data) != NULL)
4130             {
4131               per_cu->v.quick->mark = 1;
4132               continue;
4133             }
4134
4135           for (j = 0; j < file_data->num_file_names; ++j)
4136             {
4137               const char *this_real_name;
4138
4139               if (file_matcher (file_data->file_names[j], false))
4140                 {
4141                   per_cu->v.quick->mark = 1;
4142                   break;
4143                 }
4144
4145               /* Before we invoke realpath, which can get expensive when many
4146                  files are involved, do a quick comparison of the basenames.  */
4147               if (!basenames_may_differ
4148                   && !file_matcher (lbasename (file_data->file_names[j]),
4149                                     true))
4150                 continue;
4151
4152               this_real_name = dw2_get_real_path (objfile, file_data, j);
4153               if (file_matcher (this_real_name, false))
4154                 {
4155                   per_cu->v.quick->mark = 1;
4156                   break;
4157                 }
4158             }
4159
4160           slot = htab_find_slot (per_cu->v.quick->mark
4161                                  ? visited_found.get ()
4162                                  : visited_not_found.get (),
4163                                  file_data, INSERT);
4164           *slot = file_data;
4165         }
4166     }
4167
4168   for (iter = 0; iter < index->symbol_table_slots; ++iter)
4169     {
4170       offset_type idx = 2 * iter;
4171       const char *name;
4172       offset_type *vec, vec_len, vec_idx;
4173       int global_seen = 0;
4174
4175       QUIT;
4176
4177       if (index->symbol_table[idx] == 0 && index->symbol_table[idx + 1] == 0)
4178         continue;
4179
4180       name = index->constant_pool + MAYBE_SWAP (index->symbol_table[idx]);
4181
4182       if (!symbol_matcher (name))
4183         continue;
4184
4185       /* The name was matched, now expand corresponding CUs that were
4186          marked.  */
4187       vec = (offset_type *) (index->constant_pool
4188                              + MAYBE_SWAP (index->symbol_table[idx + 1]));
4189       vec_len = MAYBE_SWAP (vec[0]);
4190       for (vec_idx = 0; vec_idx < vec_len; ++vec_idx)
4191         {
4192           struct dwarf2_per_cu_data *per_cu;
4193           offset_type cu_index_and_attrs = MAYBE_SWAP (vec[vec_idx + 1]);
4194           /* This value is only valid for index versions >= 7.  */
4195           int is_static = GDB_INDEX_SYMBOL_STATIC_VALUE (cu_index_and_attrs);
4196           gdb_index_symbol_kind symbol_kind =
4197             GDB_INDEX_SYMBOL_KIND_VALUE (cu_index_and_attrs);
4198           int cu_index = GDB_INDEX_CU_VALUE (cu_index_and_attrs);
4199           /* Only check the symbol attributes if they're present.
4200              Indices prior to version 7 don't record them,
4201              and indices >= 7 may elide them for certain symbols
4202              (gold does this).  */
4203           int attrs_valid =
4204             (index->version >= 7
4205              && symbol_kind != GDB_INDEX_SYMBOL_KIND_NONE);
4206
4207           /* Work around gold/15646.  */
4208           if (attrs_valid)
4209             {
4210               if (!is_static && global_seen)
4211                 continue;
4212               if (!is_static)
4213                 global_seen = 1;
4214             }
4215
4216           /* Only check the symbol's kind if it has one.  */
4217           if (attrs_valid)
4218             {
4219               switch (kind)
4220                 {
4221                 case VARIABLES_DOMAIN:
4222                   if (symbol_kind != GDB_INDEX_SYMBOL_KIND_VARIABLE)
4223                     continue;
4224                   break;
4225                 case FUNCTIONS_DOMAIN:
4226                   if (symbol_kind != GDB_INDEX_SYMBOL_KIND_FUNCTION)
4227                     continue;
4228                   break;
4229                 case TYPES_DOMAIN:
4230                   if (symbol_kind != GDB_INDEX_SYMBOL_KIND_TYPE)
4231                     continue;
4232                   break;
4233                 default:
4234                   break;
4235                 }
4236             }
4237
4238           /* Don't crash on bad data.  */
4239           if (cu_index >= (dwarf2_per_objfile->n_comp_units
4240                            + dwarf2_per_objfile->n_type_units))
4241             {
4242               complaint (&symfile_complaints,
4243                          _(".gdb_index entry has bad CU index"
4244                            " [in module %s]"), objfile_name (objfile));
4245               continue;
4246             }
4247
4248           per_cu = dw2_get_cutu (cu_index);
4249           if (file_matcher == NULL || per_cu->v.quick->mark)
4250             {
4251               int symtab_was_null =
4252                 (per_cu->v.quick->compunit_symtab == NULL);
4253
4254               dw2_instantiate_symtab (per_cu);
4255
4256               if (expansion_notify != NULL
4257                   && symtab_was_null
4258                   && per_cu->v.quick->compunit_symtab != NULL)
4259                 {
4260                   expansion_notify (per_cu->v.quick->compunit_symtab);
4261                 }
4262             }
4263         }
4264     }
4265 }
4266
4267 /* A helper for dw2_find_pc_sect_compunit_symtab which finds the most specific
4268    symtab.  */
4269
4270 static struct compunit_symtab *
4271 recursively_find_pc_sect_compunit_symtab (struct compunit_symtab *cust,
4272                                           CORE_ADDR pc)
4273 {
4274   int i;
4275
4276   if (COMPUNIT_BLOCKVECTOR (cust) != NULL
4277       && blockvector_contains_pc (COMPUNIT_BLOCKVECTOR (cust), pc))
4278     return cust;
4279
4280   if (cust->includes == NULL)
4281     return NULL;
4282
4283   for (i = 0; cust->includes[i]; ++i)
4284     {
4285       struct compunit_symtab *s = cust->includes[i];
4286
4287       s = recursively_find_pc_sect_compunit_symtab (s, pc);
4288       if (s != NULL)
4289         return s;
4290     }
4291
4292   return NULL;
4293 }
4294
4295 static struct compunit_symtab *
4296 dw2_find_pc_sect_compunit_symtab (struct objfile *objfile,
4297                                   struct bound_minimal_symbol msymbol,
4298                                   CORE_ADDR pc,
4299                                   struct obj_section *section,
4300                                   int warn_if_readin)
4301 {
4302   struct dwarf2_per_cu_data *data;
4303   struct compunit_symtab *result;
4304
4305   dw2_setup (objfile);
4306
4307   if (!objfile->psymtabs_addrmap)
4308     return NULL;
4309
4310   data = (struct dwarf2_per_cu_data *) addrmap_find (objfile->psymtabs_addrmap,
4311                                                      pc);
4312   if (!data)
4313     return NULL;
4314
4315   if (warn_if_readin && data->v.quick->compunit_symtab)
4316     warning (_("(Internal error: pc %s in read in CU, but not in symtab.)"),
4317              paddress (get_objfile_arch (objfile), pc));
4318
4319   result
4320     = recursively_find_pc_sect_compunit_symtab (dw2_instantiate_symtab (data),
4321                                                 pc);
4322   gdb_assert (result != NULL);
4323   return result;
4324 }
4325
4326 static void
4327 dw2_map_symbol_filenames (struct objfile *objfile, symbol_filename_ftype *fun,
4328                           void *data, int need_fullname)
4329 {
4330   dw2_setup (objfile);
4331
4332   if (!dwarf2_per_objfile->filenames_cache)
4333     {
4334       dwarf2_per_objfile->filenames_cache.emplace ();
4335
4336       htab_up visited (htab_create_alloc (10,
4337                                           htab_hash_pointer, htab_eq_pointer,
4338                                           NULL, xcalloc, xfree));
4339
4340       /* The rule is CUs specify all the files, including those used
4341          by any TU, so there's no need to scan TUs here.  We can
4342          ignore file names coming from already-expanded CUs.  */
4343
4344       for (int i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
4345         {
4346           struct dwarf2_per_cu_data *per_cu = dw2_get_cutu (i);
4347
4348           if (per_cu->v.quick->compunit_symtab)
4349             {
4350               void **slot = htab_find_slot (visited.get (),
4351                                             per_cu->v.quick->file_names,
4352                                             INSERT);
4353
4354               *slot = per_cu->v.quick->file_names;
4355             }
4356         }
4357
4358       for (int i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
4359         {
4360           int j;
4361           struct dwarf2_per_cu_data *per_cu = dw2_get_cu (i);
4362           struct quick_file_names *file_data;
4363           void **slot;
4364
4365           /* We only need to look at symtabs not already expanded.  */
4366           if (per_cu->v.quick->compunit_symtab)
4367             continue;
4368
4369           file_data = dw2_get_file_names (per_cu);
4370           if (file_data == NULL)
4371             continue;
4372
4373           slot = htab_find_slot (visited.get (), file_data, INSERT);
4374           if (*slot)
4375             {
4376               /* Already visited.  */
4377               continue;
4378             }
4379           *slot = file_data;
4380
4381           for (int j = 0; j < file_data->num_file_names; ++j)
4382             {
4383               const char *filename = file_data->file_names[j];
4384               dwarf2_per_objfile->filenames_cache->seen (filename);
4385             }
4386         }
4387     }
4388
4389   dwarf2_per_objfile->filenames_cache->traverse ([&] (const char *filename)
4390     {
4391       gdb::unique_xmalloc_ptr<char> this_real_name;
4392
4393       if (need_fullname)
4394         this_real_name = gdb_realpath (filename);
4395       (*fun) (filename, this_real_name.get (), data);
4396     });
4397 }
4398
4399 static int
4400 dw2_has_symbols (struct objfile *objfile)
4401 {
4402   return 1;
4403 }
4404
4405 const struct quick_symbol_functions dwarf2_gdb_index_functions =
4406 {
4407   dw2_has_symbols,
4408   dw2_find_last_source_symtab,
4409   dw2_forget_cached_source_info,
4410   dw2_map_symtabs_matching_filename,
4411   dw2_lookup_symbol,
4412   dw2_print_stats,
4413   dw2_dump,
4414   dw2_relocate,
4415   dw2_expand_symtabs_for_function,
4416   dw2_expand_all_symtabs,
4417   dw2_expand_symtabs_with_fullname,
4418   dw2_map_matching_symbols,
4419   dw2_expand_symtabs_matching,
4420   dw2_find_pc_sect_compunit_symtab,
4421   dw2_map_symbol_filenames
4422 };
4423
4424 /* Initialize for reading DWARF for this objfile.  Return 0 if this
4425    file will use psymtabs, or 1 if using the GNU index.  */
4426
4427 int
4428 dwarf2_initialize_objfile (struct objfile *objfile)
4429 {
4430   /* If we're about to read full symbols, don't bother with the
4431      indices.  In this case we also don't care if some other debug
4432      format is making psymtabs, because they are all about to be
4433      expanded anyway.  */
4434   if ((objfile->flags & OBJF_READNOW))
4435     {
4436       int i;
4437
4438       dwarf2_per_objfile->using_index = 1;
4439       create_all_comp_units (objfile);
4440       create_all_type_units (objfile);
4441       dwarf2_per_objfile->quick_file_names_table =
4442         create_quick_file_names_table (dwarf2_per_objfile->n_comp_units);
4443
4444       for (i = 0; i < (dwarf2_per_objfile->n_comp_units
4445                        + dwarf2_per_objfile->n_type_units); ++i)
4446         {
4447           struct dwarf2_per_cu_data *per_cu = dw2_get_cutu (i);
4448
4449           per_cu->v.quick = OBSTACK_ZALLOC (&objfile->objfile_obstack,
4450                                             struct dwarf2_per_cu_quick_data);
4451         }
4452
4453       /* Return 1 so that gdb sees the "quick" functions.  However,
4454          these functions will be no-ops because we will have expanded
4455          all symtabs.  */
4456       return 1;
4457     }
4458
4459   if (dwarf2_read_index (objfile))
4460     return 1;
4461
4462   return 0;
4463 }
4464
4465 \f
4466
4467 /* Build a partial symbol table.  */
4468
4469 void
4470 dwarf2_build_psymtabs (struct objfile *objfile)
4471 {
4472
4473   if (objfile->global_psymbols.size == 0 && objfile->static_psymbols.size == 0)
4474     {
4475       init_psymbol_list (objfile, 1024);
4476     }
4477
4478   TRY
4479     {
4480       /* This isn't really ideal: all the data we allocate on the
4481          objfile's obstack is still uselessly kept around.  However,
4482          freeing it seems unsafe.  */
4483       psymtab_discarder psymtabs (objfile);
4484       dwarf2_build_psymtabs_hard (objfile);
4485       psymtabs.keep ();
4486     }
4487   CATCH (except, RETURN_MASK_ERROR)
4488     {
4489       exception_print (gdb_stderr, except);
4490     }
4491   END_CATCH
4492 }
4493
4494 /* Return the total length of the CU described by HEADER.  */
4495
4496 static unsigned int
4497 get_cu_length (const struct comp_unit_head *header)
4498 {
4499   return header->initial_length_size + header->length;
4500 }
4501
4502 /* Return TRUE if SECT_OFF is within CU_HEADER.  */
4503
4504 static inline bool
4505 offset_in_cu_p (const comp_unit_head *cu_header, sect_offset sect_off)
4506 {
4507   sect_offset bottom = cu_header->sect_off;
4508   sect_offset top = cu_header->sect_off + get_cu_length (cu_header);
4509
4510   return sect_off >= bottom && sect_off < top;
4511 }
4512
4513 /* Find the base address of the compilation unit for range lists and
4514    location lists.  It will normally be specified by DW_AT_low_pc.
4515    In DWARF-3 draft 4, the base address could be overridden by
4516    DW_AT_entry_pc.  It's been removed, but GCC still uses this for
4517    compilation units with discontinuous ranges.  */
4518
4519 static void
4520 dwarf2_find_base_address (struct die_info *die, struct dwarf2_cu *cu)
4521 {
4522   struct attribute *attr;
4523
4524   cu->base_known = 0;
4525   cu->base_address = 0;
4526
4527   attr = dwarf2_attr (die, DW_AT_entry_pc, cu);
4528   if (attr)
4529     {
4530       cu->base_address = attr_value_as_address (attr);
4531       cu->base_known = 1;
4532     }
4533   else
4534     {
4535       attr = dwarf2_attr (die, DW_AT_low_pc, cu);
4536       if (attr)
4537         {
4538           cu->base_address = attr_value_as_address (attr);
4539           cu->base_known = 1;
4540         }
4541     }
4542 }
4543
4544 /* Read in the comp unit header information from the debug_info at info_ptr.
4545    Use rcuh_kind::COMPILE as the default type if not known by the caller.
4546    NOTE: This leaves members offset, first_die_offset to be filled in
4547    by the caller.  */
4548
4549 static const gdb_byte *
4550 read_comp_unit_head (struct comp_unit_head *cu_header,
4551                      const gdb_byte *info_ptr,
4552                      struct dwarf2_section_info *section,
4553                      rcuh_kind section_kind)
4554 {
4555   int signed_addr;
4556   unsigned int bytes_read;
4557   const char *filename = get_section_file_name (section);
4558   bfd *abfd = get_section_bfd_owner (section);
4559
4560   cu_header->length = read_initial_length (abfd, info_ptr, &bytes_read);
4561   cu_header->initial_length_size = bytes_read;
4562   cu_header->offset_size = (bytes_read == 4) ? 4 : 8;
4563   info_ptr += bytes_read;
4564   cu_header->version = read_2_bytes (abfd, info_ptr);
4565   info_ptr += 2;
4566   if (cu_header->version < 5)
4567     switch (section_kind)
4568       {
4569       case rcuh_kind::COMPILE:
4570         cu_header->unit_type = DW_UT_compile;
4571         break;
4572       case rcuh_kind::TYPE:
4573         cu_header->unit_type = DW_UT_type;
4574         break;
4575       default:
4576         internal_error (__FILE__, __LINE__,
4577                         _("read_comp_unit_head: invalid section_kind"));
4578       }
4579   else
4580     {
4581       cu_header->unit_type = static_cast<enum dwarf_unit_type>
4582                                                  (read_1_byte (abfd, info_ptr));
4583       info_ptr += 1;
4584       switch (cu_header->unit_type)
4585         {
4586         case DW_UT_compile:
4587           if (section_kind != rcuh_kind::COMPILE)
4588             error (_("Dwarf Error: wrong unit_type in compilation unit header "
4589                    "(is DW_UT_compile, should be DW_UT_type) [in module %s]"),
4590                    filename);
4591           break;
4592         case DW_UT_type:
4593           section_kind = rcuh_kind::TYPE;
4594           break;
4595         default:
4596           error (_("Dwarf Error: wrong unit_type in compilation unit header "
4597                  "(is %d, should be %d or %d) [in module %s]"),
4598                  cu_header->unit_type, DW_UT_compile, DW_UT_type, filename);
4599         }
4600
4601       cu_header->addr_size = read_1_byte (abfd, info_ptr);
4602       info_ptr += 1;
4603     }
4604   cu_header->abbrev_sect_off = (sect_offset) read_offset (abfd, info_ptr,
4605                                                           cu_header,
4606                                                           &bytes_read);
4607   info_ptr += bytes_read;
4608   if (cu_header->version < 5)
4609     {
4610       cu_header->addr_size = read_1_byte (abfd, info_ptr);
4611       info_ptr += 1;
4612     }
4613   signed_addr = bfd_get_sign_extend_vma (abfd);
4614   if (signed_addr < 0)
4615     internal_error (__FILE__, __LINE__,
4616                     _("read_comp_unit_head: dwarf from non elf file"));
4617   cu_header->signed_addr_p = signed_addr;
4618
4619   if (section_kind == rcuh_kind::TYPE)
4620     {
4621       LONGEST type_offset;
4622
4623       cu_header->signature = read_8_bytes (abfd, info_ptr);
4624       info_ptr += 8;
4625
4626       type_offset = read_offset (abfd, info_ptr, cu_header, &bytes_read);
4627       info_ptr += bytes_read;
4628       cu_header->type_cu_offset_in_tu = (cu_offset) type_offset;
4629       if (to_underlying (cu_header->type_cu_offset_in_tu) != type_offset)
4630         error (_("Dwarf Error: Too big type_offset in compilation unit "
4631                "header (is %s) [in module %s]"), plongest (type_offset),
4632                filename);
4633     }
4634
4635   return info_ptr;
4636 }
4637
4638 /* Helper function that returns the proper abbrev section for
4639    THIS_CU.  */
4640
4641 static struct dwarf2_section_info *
4642 get_abbrev_section_for_cu (struct dwarf2_per_cu_data *this_cu)
4643 {
4644   struct dwarf2_section_info *abbrev;
4645
4646   if (this_cu->is_dwz)
4647     abbrev = &dwarf2_get_dwz_file ()->abbrev;
4648   else
4649     abbrev = &dwarf2_per_objfile->abbrev;
4650
4651   return abbrev;
4652 }
4653
4654 /* Subroutine of read_and_check_comp_unit_head and
4655    read_and_check_type_unit_head to simplify them.
4656    Perform various error checking on the header.  */
4657
4658 static void
4659 error_check_comp_unit_head (struct comp_unit_head *header,
4660                             struct dwarf2_section_info *section,
4661                             struct dwarf2_section_info *abbrev_section)
4662 {
4663   const char *filename = get_section_file_name (section);
4664
4665   if (header->version < 2 || header->version > 5)
4666     error (_("Dwarf Error: wrong version in compilation unit header "
4667            "(is %d, should be 2, 3, 4 or 5) [in module %s]"), header->version,
4668            filename);
4669
4670   if (to_underlying (header->abbrev_sect_off)
4671       >= dwarf2_section_size (dwarf2_per_objfile->objfile, abbrev_section))
4672     error (_("Dwarf Error: bad offset (0x%x) in compilation unit header "
4673            "(offset 0x%x + 6) [in module %s]"),
4674            to_underlying (header->abbrev_sect_off),
4675            to_underlying (header->sect_off),
4676            filename);
4677
4678   /* Cast to ULONGEST to use 64-bit arithmetic when possible to
4679      avoid potential 32-bit overflow.  */
4680   if (((ULONGEST) header->sect_off + get_cu_length (header))
4681       > section->size)
4682     error (_("Dwarf Error: bad length (0x%x) in compilation unit header "
4683            "(offset 0x%x + 0) [in module %s]"),
4684            header->length, to_underlying (header->sect_off),
4685            filename);
4686 }
4687
4688 /* Read in a CU/TU header and perform some basic error checking.
4689    The contents of the header are stored in HEADER.
4690    The result is a pointer to the start of the first DIE.  */
4691
4692 static const gdb_byte *
4693 read_and_check_comp_unit_head (struct comp_unit_head *header,
4694                                struct dwarf2_section_info *section,
4695                                struct dwarf2_section_info *abbrev_section,
4696                                const gdb_byte *info_ptr,
4697                                rcuh_kind section_kind)
4698 {
4699   const gdb_byte *beg_of_comp_unit = info_ptr;
4700   bfd *abfd = get_section_bfd_owner (section);
4701
4702   header->sect_off = (sect_offset) (beg_of_comp_unit - section->buffer);
4703
4704   info_ptr = read_comp_unit_head (header, info_ptr, section, section_kind);
4705
4706   header->first_die_cu_offset = (cu_offset) (info_ptr - beg_of_comp_unit);
4707
4708   error_check_comp_unit_head (header, section, abbrev_section);
4709
4710   return info_ptr;
4711 }
4712
4713 /* Fetch the abbreviation table offset from a comp or type unit header.  */
4714
4715 static sect_offset
4716 read_abbrev_offset (struct dwarf2_section_info *section,
4717                     sect_offset sect_off)
4718 {
4719   bfd *abfd = get_section_bfd_owner (section);
4720   const gdb_byte *info_ptr;
4721   unsigned int initial_length_size, offset_size;
4722   uint16_t version;
4723
4724   dwarf2_read_section (dwarf2_per_objfile->objfile, section);
4725   info_ptr = section->buffer + to_underlying (sect_off);
4726   read_initial_length (abfd, info_ptr, &initial_length_size);
4727   offset_size = initial_length_size == 4 ? 4 : 8;
4728   info_ptr += initial_length_size;
4729
4730   version = read_2_bytes (abfd, info_ptr);
4731   info_ptr += 2;
4732   if (version >= 5)
4733     {
4734       /* Skip unit type and address size.  */
4735       info_ptr += 2;
4736     }
4737
4738   return (sect_offset) read_offset_1 (abfd, info_ptr, offset_size);
4739 }
4740
4741 /* Allocate a new partial symtab for file named NAME and mark this new
4742    partial symtab as being an include of PST.  */
4743
4744 static void
4745 dwarf2_create_include_psymtab (const char *name, struct partial_symtab *pst,
4746                                struct objfile *objfile)
4747 {
4748   struct partial_symtab *subpst = allocate_psymtab (name, objfile);
4749
4750   if (!IS_ABSOLUTE_PATH (subpst->filename))
4751     {
4752       /* It shares objfile->objfile_obstack.  */
4753       subpst->dirname = pst->dirname;
4754     }
4755
4756   subpst->textlow = 0;
4757   subpst->texthigh = 0;
4758
4759   subpst->dependencies
4760     = XOBNEW (&objfile->objfile_obstack, struct partial_symtab *);
4761   subpst->dependencies[0] = pst;
4762   subpst->number_of_dependencies = 1;
4763
4764   subpst->globals_offset = 0;
4765   subpst->n_global_syms = 0;
4766   subpst->statics_offset = 0;
4767   subpst->n_static_syms = 0;
4768   subpst->compunit_symtab = NULL;
4769   subpst->read_symtab = pst->read_symtab;
4770   subpst->readin = 0;
4771
4772   /* No private part is necessary for include psymtabs.  This property
4773      can be used to differentiate between such include psymtabs and
4774      the regular ones.  */
4775   subpst->read_symtab_private = NULL;
4776 }
4777
4778 /* Read the Line Number Program data and extract the list of files
4779    included by the source file represented by PST.  Build an include
4780    partial symtab for each of these included files.  */
4781
4782 static void
4783 dwarf2_build_include_psymtabs (struct dwarf2_cu *cu,
4784                                struct die_info *die,
4785                                struct partial_symtab *pst)
4786 {
4787   line_header_up lh;
4788   struct attribute *attr;
4789
4790   attr = dwarf2_attr (die, DW_AT_stmt_list, cu);
4791   if (attr)
4792     lh = dwarf_decode_line_header ((sect_offset) DW_UNSND (attr), cu);
4793   if (lh == NULL)
4794     return;  /* No linetable, so no includes.  */
4795
4796   /* NOTE: pst->dirname is DW_AT_comp_dir (if present).  */
4797   dwarf_decode_lines (lh.get (), pst->dirname, cu, pst, pst->textlow, 1);
4798 }
4799
4800 static hashval_t
4801 hash_signatured_type (const void *item)
4802 {
4803   const struct signatured_type *sig_type
4804     = (const struct signatured_type *) item;
4805
4806   /* This drops the top 32 bits of the signature, but is ok for a hash.  */
4807   return sig_type->signature;
4808 }
4809
4810 static int
4811 eq_signatured_type (const void *item_lhs, const void *item_rhs)
4812 {
4813   const struct signatured_type *lhs = (const struct signatured_type *) item_lhs;
4814   const struct signatured_type *rhs = (const struct signatured_type *) item_rhs;
4815
4816   return lhs->signature == rhs->signature;
4817 }
4818
4819 /* Allocate a hash table for signatured types.  */
4820
4821 static htab_t
4822 allocate_signatured_type_table (struct objfile *objfile)
4823 {
4824   return htab_create_alloc_ex (41,
4825                                hash_signatured_type,
4826                                eq_signatured_type,
4827                                NULL,
4828                                &objfile->objfile_obstack,
4829                                hashtab_obstack_allocate,
4830                                dummy_obstack_deallocate);
4831 }
4832
4833 /* A helper function to add a signatured type CU to a table.  */
4834
4835 static int
4836 add_signatured_type_cu_to_table (void **slot, void *datum)
4837 {
4838   struct signatured_type *sigt = (struct signatured_type *) *slot;
4839   struct signatured_type ***datap = (struct signatured_type ***) datum;
4840
4841   **datap = sigt;
4842   ++*datap;
4843
4844   return 1;
4845 }
4846
4847 /* A helper for create_debug_types_hash_table.  Read types from SECTION
4848    and fill them into TYPES_HTAB.  It will process only type units,
4849    therefore DW_UT_type.  */
4850
4851 static void
4852 create_debug_type_hash_table (struct dwo_file *dwo_file,
4853                               dwarf2_section_info *section, htab_t &types_htab,
4854                               rcuh_kind section_kind)
4855 {
4856   struct objfile *objfile = dwarf2_per_objfile->objfile;
4857   struct dwarf2_section_info *abbrev_section;
4858   bfd *abfd;
4859   const gdb_byte *info_ptr, *end_ptr;
4860
4861   abbrev_section = (dwo_file != NULL
4862                     ? &dwo_file->sections.abbrev
4863                     : &dwarf2_per_objfile->abbrev);
4864
4865   if (dwarf_read_debug)
4866     fprintf_unfiltered (gdb_stdlog, "Reading %s for %s:\n",
4867                         get_section_name (section),
4868                         get_section_file_name (abbrev_section));
4869
4870   dwarf2_read_section (objfile, section);
4871   info_ptr = section->buffer;
4872
4873   if (info_ptr == NULL)
4874     return;
4875
4876   /* We can't set abfd until now because the section may be empty or
4877      not present, in which case the bfd is unknown.  */
4878   abfd = get_section_bfd_owner (section);
4879
4880   /* We don't use init_cutu_and_read_dies_simple, or some such, here
4881      because we don't need to read any dies: the signature is in the
4882      header.  */
4883
4884   end_ptr = info_ptr + section->size;
4885   while (info_ptr < end_ptr)
4886     {
4887       struct signatured_type *sig_type;
4888       struct dwo_unit *dwo_tu;
4889       void **slot;
4890       const gdb_byte *ptr = info_ptr;
4891       struct comp_unit_head header;
4892       unsigned int length;
4893
4894       sect_offset sect_off = (sect_offset) (ptr - section->buffer);
4895
4896       /* Initialize it due to a false compiler warning.  */
4897       header.signature = -1;
4898       header.type_cu_offset_in_tu = (cu_offset) -1;
4899
4900       /* We need to read the type's signature in order to build the hash
4901          table, but we don't need anything else just yet.  */
4902
4903       ptr = read_and_check_comp_unit_head (&header, section,
4904                                            abbrev_section, ptr, section_kind);
4905
4906       length = get_cu_length (&header);
4907
4908       /* Skip dummy type units.  */
4909       if (ptr >= info_ptr + length
4910           || peek_abbrev_code (abfd, ptr) == 0
4911           || header.unit_type != DW_UT_type)
4912         {
4913           info_ptr += length;
4914           continue;
4915         }
4916
4917       if (types_htab == NULL)
4918         {
4919           if (dwo_file)
4920             types_htab = allocate_dwo_unit_table (objfile);
4921           else
4922             types_htab = allocate_signatured_type_table (objfile);
4923         }
4924
4925       if (dwo_file)
4926         {
4927           sig_type = NULL;
4928           dwo_tu = OBSTACK_ZALLOC (&objfile->objfile_obstack,
4929                                    struct dwo_unit);
4930           dwo_tu->dwo_file = dwo_file;
4931           dwo_tu->signature = header.signature;
4932           dwo_tu->type_offset_in_tu = header.type_cu_offset_in_tu;
4933           dwo_tu->section = section;
4934           dwo_tu->sect_off = sect_off;
4935           dwo_tu->length = length;
4936         }
4937       else
4938         {
4939           /* N.B.: type_offset is not usable if this type uses a DWO file.
4940              The real type_offset is in the DWO file.  */
4941           dwo_tu = NULL;
4942           sig_type = OBSTACK_ZALLOC (&objfile->objfile_obstack,
4943                                      struct signatured_type);
4944           sig_type->signature = header.signature;
4945           sig_type->type_offset_in_tu = header.type_cu_offset_in_tu;
4946           sig_type->per_cu.objfile = objfile;
4947           sig_type->per_cu.is_debug_types = 1;
4948           sig_type->per_cu.section = section;
4949           sig_type->per_cu.sect_off = sect_off;
4950           sig_type->per_cu.length = length;
4951         }
4952
4953       slot = htab_find_slot (types_htab,
4954                              dwo_file ? (void*) dwo_tu : (void *) sig_type,
4955                              INSERT);
4956       gdb_assert (slot != NULL);
4957       if (*slot != NULL)
4958         {
4959           sect_offset dup_sect_off;
4960
4961           if (dwo_file)
4962             {
4963               const struct dwo_unit *dup_tu
4964                 = (const struct dwo_unit *) *slot;
4965
4966               dup_sect_off = dup_tu->sect_off;
4967             }
4968           else
4969             {
4970               const struct signatured_type *dup_tu
4971                 = (const struct signatured_type *) *slot;
4972
4973               dup_sect_off = dup_tu->per_cu.sect_off;
4974             }
4975
4976           complaint (&symfile_complaints,
4977                      _("debug type entry at offset 0x%x is duplicate to"
4978                        " the entry at offset 0x%x, signature %s"),
4979                      to_underlying (sect_off), to_underlying (dup_sect_off),
4980                      hex_string (header.signature));
4981         }
4982       *slot = dwo_file ? (void *) dwo_tu : (void *) sig_type;
4983
4984       if (dwarf_read_debug > 1)
4985         fprintf_unfiltered (gdb_stdlog, "  offset 0x%x, signature %s\n",
4986                             to_underlying (sect_off),
4987                             hex_string (header.signature));
4988
4989       info_ptr += length;
4990     }
4991 }
4992
4993 /* Create the hash table of all entries in the .debug_types
4994    (or .debug_types.dwo) section(s).
4995    If reading a DWO file, then DWO_FILE is a pointer to the DWO file object,
4996    otherwise it is NULL.
4997
4998    The result is a pointer to the hash table or NULL if there are no types.
4999
5000    Note: This function processes DWO files only, not DWP files.  */
5001
5002 static void
5003 create_debug_types_hash_table (struct dwo_file *dwo_file,
5004                                VEC (dwarf2_section_info_def) *types,
5005                                htab_t &types_htab)
5006 {
5007   int ix;
5008   struct dwarf2_section_info *section;
5009
5010   if (VEC_empty (dwarf2_section_info_def, types))
5011     return;
5012
5013   for (ix = 0;
5014        VEC_iterate (dwarf2_section_info_def, types, ix, section);
5015        ++ix)
5016     create_debug_type_hash_table (dwo_file, section, types_htab,
5017                                   rcuh_kind::TYPE);
5018 }
5019
5020 /* Create the hash table of all entries in the .debug_types section,
5021    and initialize all_type_units.
5022    The result is zero if there is an error (e.g. missing .debug_types section),
5023    otherwise non-zero.  */
5024
5025 static int
5026 create_all_type_units (struct objfile *objfile)
5027 {
5028   htab_t types_htab = NULL;
5029   struct signatured_type **iter;
5030
5031   create_debug_type_hash_table (NULL, &dwarf2_per_objfile->info, types_htab,
5032                                 rcuh_kind::COMPILE);
5033   create_debug_types_hash_table (NULL, dwarf2_per_objfile->types, types_htab);
5034   if (types_htab == NULL)
5035     {
5036       dwarf2_per_objfile->signatured_types = NULL;
5037       return 0;
5038     }
5039
5040   dwarf2_per_objfile->signatured_types = types_htab;
5041
5042   dwarf2_per_objfile->n_type_units
5043     = dwarf2_per_objfile->n_allocated_type_units
5044     = htab_elements (types_htab);
5045   dwarf2_per_objfile->all_type_units =
5046     XNEWVEC (struct signatured_type *, dwarf2_per_objfile->n_type_units);
5047   iter = &dwarf2_per_objfile->all_type_units[0];
5048   htab_traverse_noresize (types_htab, add_signatured_type_cu_to_table, &iter);
5049   gdb_assert (iter - &dwarf2_per_objfile->all_type_units[0]
5050               == dwarf2_per_objfile->n_type_units);
5051
5052   return 1;
5053 }
5054
5055 /* Add an entry for signature SIG to dwarf2_per_objfile->signatured_types.
5056    If SLOT is non-NULL, it is the entry to use in the hash table.
5057    Otherwise we find one.  */
5058
5059 static struct signatured_type *
5060 add_type_unit (ULONGEST sig, void **slot)
5061 {
5062   struct objfile *objfile = dwarf2_per_objfile->objfile;
5063   int n_type_units = dwarf2_per_objfile->n_type_units;
5064   struct signatured_type *sig_type;
5065
5066   gdb_assert (n_type_units <= dwarf2_per_objfile->n_allocated_type_units);
5067   ++n_type_units;
5068   if (n_type_units > dwarf2_per_objfile->n_allocated_type_units)
5069     {
5070       if (dwarf2_per_objfile->n_allocated_type_units == 0)
5071         dwarf2_per_objfile->n_allocated_type_units = 1;
5072       dwarf2_per_objfile->n_allocated_type_units *= 2;
5073       dwarf2_per_objfile->all_type_units
5074         = XRESIZEVEC (struct signatured_type *,
5075                       dwarf2_per_objfile->all_type_units,
5076                       dwarf2_per_objfile->n_allocated_type_units);
5077       ++dwarf2_per_objfile->tu_stats.nr_all_type_units_reallocs;
5078     }
5079   dwarf2_per_objfile->n_type_units = n_type_units;
5080
5081   sig_type = OBSTACK_ZALLOC (&objfile->objfile_obstack,
5082                              struct signatured_type);
5083   dwarf2_per_objfile->all_type_units[n_type_units - 1] = sig_type;
5084   sig_type->signature = sig;
5085   sig_type->per_cu.is_debug_types = 1;
5086   if (dwarf2_per_objfile->using_index)
5087     {
5088       sig_type->per_cu.v.quick =
5089         OBSTACK_ZALLOC (&objfile->objfile_obstack,
5090                         struct dwarf2_per_cu_quick_data);
5091     }
5092
5093   if (slot == NULL)
5094     {
5095       slot = htab_find_slot (dwarf2_per_objfile->signatured_types,
5096                              sig_type, INSERT);
5097     }
5098   gdb_assert (*slot == NULL);
5099   *slot = sig_type;
5100   /* The rest of sig_type must be filled in by the caller.  */
5101   return sig_type;
5102 }
5103
5104 /* Subroutine of lookup_dwo_signatured_type and lookup_dwp_signatured_type.
5105    Fill in SIG_ENTRY with DWO_ENTRY.  */
5106
5107 static void
5108 fill_in_sig_entry_from_dwo_entry (struct objfile *objfile,
5109                                   struct signatured_type *sig_entry,
5110                                   struct dwo_unit *dwo_entry)
5111 {
5112   /* Make sure we're not clobbering something we don't expect to.  */
5113   gdb_assert (! sig_entry->per_cu.queued);
5114   gdb_assert (sig_entry->per_cu.cu == NULL);
5115   if (dwarf2_per_objfile->using_index)
5116     {
5117       gdb_assert (sig_entry->per_cu.v.quick != NULL);
5118       gdb_assert (sig_entry->per_cu.v.quick->compunit_symtab == NULL);
5119     }
5120   else
5121       gdb_assert (sig_entry->per_cu.v.psymtab == NULL);
5122   gdb_assert (sig_entry->signature == dwo_entry->signature);
5123   gdb_assert (to_underlying (sig_entry->type_offset_in_section) == 0);
5124   gdb_assert (sig_entry->type_unit_group == NULL);
5125   gdb_assert (sig_entry->dwo_unit == NULL);
5126
5127   sig_entry->per_cu.section = dwo_entry->section;
5128   sig_entry->per_cu.sect_off = dwo_entry->sect_off;
5129   sig_entry->per_cu.length = dwo_entry->length;
5130   sig_entry->per_cu.reading_dwo_directly = 1;
5131   sig_entry->per_cu.objfile = objfile;
5132   sig_entry->type_offset_in_tu = dwo_entry->type_offset_in_tu;
5133   sig_entry->dwo_unit = dwo_entry;
5134 }
5135
5136 /* Subroutine of lookup_signatured_type.
5137    If we haven't read the TU yet, create the signatured_type data structure
5138    for a TU to be read in directly from a DWO file, bypassing the stub.
5139    This is the "Stay in DWO Optimization": When there is no DWP file and we're
5140    using .gdb_index, then when reading a CU we want to stay in the DWO file
5141    containing that CU.  Otherwise we could end up reading several other DWO
5142    files (due to comdat folding) to process the transitive closure of all the
5143    mentioned TUs, and that can be slow.  The current DWO file will have every
5144    type signature that it needs.
5145    We only do this for .gdb_index because in the psymtab case we already have
5146    to read all the DWOs to build the type unit groups.  */
5147
5148 static struct signatured_type *
5149 lookup_dwo_signatured_type (struct dwarf2_cu *cu, ULONGEST sig)
5150 {
5151   struct objfile *objfile = dwarf2_per_objfile->objfile;
5152   struct dwo_file *dwo_file;
5153   struct dwo_unit find_dwo_entry, *dwo_entry;
5154   struct signatured_type find_sig_entry, *sig_entry;
5155   void **slot;
5156
5157   gdb_assert (cu->dwo_unit && dwarf2_per_objfile->using_index);
5158
5159   /* If TU skeletons have been removed then we may not have read in any
5160      TUs yet.  */
5161   if (dwarf2_per_objfile->signatured_types == NULL)
5162     {
5163       dwarf2_per_objfile->signatured_types
5164         = allocate_signatured_type_table (objfile);
5165     }
5166
5167   /* We only ever need to read in one copy of a signatured type.
5168      Use the global signatured_types array to do our own comdat-folding
5169      of types.  If this is the first time we're reading this TU, and
5170      the TU has an entry in .gdb_index, replace the recorded data from
5171      .gdb_index with this TU.  */
5172
5173   find_sig_entry.signature = sig;
5174   slot = htab_find_slot (dwarf2_per_objfile->signatured_types,
5175                          &find_sig_entry, INSERT);
5176   sig_entry = (struct signatured_type *) *slot;
5177
5178   /* We can get here with the TU already read, *or* in the process of being
5179      read.  Don't reassign the global entry to point to this DWO if that's
5180      the case.  Also note that if the TU is already being read, it may not
5181      have come from a DWO, the program may be a mix of Fission-compiled
5182      code and non-Fission-compiled code.  */
5183
5184   /* Have we already tried to read this TU?
5185      Note: sig_entry can be NULL if the skeleton TU was removed (thus it
5186      needn't exist in the global table yet).  */
5187   if (sig_entry != NULL && sig_entry->per_cu.tu_read)
5188     return sig_entry;
5189
5190   /* Note: cu->dwo_unit is the dwo_unit that references this TU, not the
5191      dwo_unit of the TU itself.  */
5192   dwo_file = cu->dwo_unit->dwo_file;
5193
5194   /* Ok, this is the first time we're reading this TU.  */
5195   if (dwo_file->tus == NULL)
5196     return NULL;
5197   find_dwo_entry.signature = sig;
5198   dwo_entry = (struct dwo_unit *) htab_find (dwo_file->tus, &find_dwo_entry);
5199   if (dwo_entry == NULL)
5200     return NULL;
5201
5202   /* If the global table doesn't have an entry for this TU, add one.  */
5203   if (sig_entry == NULL)
5204     sig_entry = add_type_unit (sig, slot);
5205
5206   fill_in_sig_entry_from_dwo_entry (objfile, sig_entry, dwo_entry);
5207   sig_entry->per_cu.tu_read = 1;
5208   return sig_entry;
5209 }
5210
5211 /* Subroutine of lookup_signatured_type.
5212    Look up the type for signature SIG, and if we can't find SIG in .gdb_index
5213    then try the DWP file.  If the TU stub (skeleton) has been removed then
5214    it won't be in .gdb_index.  */
5215
5216 static struct signatured_type *
5217 lookup_dwp_signatured_type (struct dwarf2_cu *cu, ULONGEST sig)
5218 {
5219   struct objfile *objfile = dwarf2_per_objfile->objfile;
5220   struct dwp_file *dwp_file = get_dwp_file ();
5221   struct dwo_unit *dwo_entry;
5222   struct signatured_type find_sig_entry, *sig_entry;
5223   void **slot;
5224
5225   gdb_assert (cu->dwo_unit && dwarf2_per_objfile->using_index);
5226   gdb_assert (dwp_file != NULL);
5227
5228   /* If TU skeletons have been removed then we may not have read in any
5229      TUs yet.  */
5230   if (dwarf2_per_objfile->signatured_types == NULL)
5231     {
5232       dwarf2_per_objfile->signatured_types
5233         = allocate_signatured_type_table (objfile);
5234     }
5235
5236   find_sig_entry.signature = sig;
5237   slot = htab_find_slot (dwarf2_per_objfile->signatured_types,
5238                          &find_sig_entry, INSERT);
5239   sig_entry = (struct signatured_type *) *slot;
5240
5241   /* Have we already tried to read this TU?
5242      Note: sig_entry can be NULL if the skeleton TU was removed (thus it
5243      needn't exist in the global table yet).  */
5244   if (sig_entry != NULL)
5245     return sig_entry;
5246
5247   if (dwp_file->tus == NULL)
5248     return NULL;
5249   dwo_entry = lookup_dwo_unit_in_dwp (dwp_file, NULL,
5250                                       sig, 1 /* is_debug_types */);
5251   if (dwo_entry == NULL)
5252     return NULL;
5253
5254   sig_entry = add_type_unit (sig, slot);
5255   fill_in_sig_entry_from_dwo_entry (objfile, sig_entry, dwo_entry);
5256
5257   return sig_entry;
5258 }
5259
5260 /* Lookup a signature based type for DW_FORM_ref_sig8.
5261    Returns NULL if signature SIG is not present in the table.
5262    It is up to the caller to complain about this.  */
5263
5264 static struct signatured_type *
5265 lookup_signatured_type (struct dwarf2_cu *cu, ULONGEST sig)
5266 {
5267   if (cu->dwo_unit
5268       && dwarf2_per_objfile->using_index)
5269     {
5270       /* We're in a DWO/DWP file, and we're using .gdb_index.
5271          These cases require special processing.  */
5272       if (get_dwp_file () == NULL)
5273         return lookup_dwo_signatured_type (cu, sig);
5274       else
5275         return lookup_dwp_signatured_type (cu, sig);
5276     }
5277   else
5278     {
5279       struct signatured_type find_entry, *entry;
5280
5281       if (dwarf2_per_objfile->signatured_types == NULL)
5282         return NULL;
5283       find_entry.signature = sig;
5284       entry = ((struct signatured_type *)
5285                htab_find (dwarf2_per_objfile->signatured_types, &find_entry));
5286       return entry;
5287     }
5288 }
5289 \f
5290 /* Low level DIE reading support.  */
5291
5292 /* Initialize a die_reader_specs struct from a dwarf2_cu struct.  */
5293
5294 static void
5295 init_cu_die_reader (struct die_reader_specs *reader,
5296                     struct dwarf2_cu *cu,
5297                     struct dwarf2_section_info *section,
5298                     struct dwo_file *dwo_file)
5299 {
5300   gdb_assert (section->readin && section->buffer != NULL);
5301   reader->abfd = get_section_bfd_owner (section);
5302   reader->cu = cu;
5303   reader->dwo_file = dwo_file;
5304   reader->die_section = section;
5305   reader->buffer = section->buffer;
5306   reader->buffer_end = section->buffer + section->size;
5307   reader->comp_dir = NULL;
5308 }
5309
5310 /* Subroutine of init_cutu_and_read_dies to simplify it.
5311    Read in the rest of a CU/TU top level DIE from DWO_UNIT.
5312    There's just a lot of work to do, and init_cutu_and_read_dies is big enough
5313    already.
5314
5315    STUB_COMP_UNIT_DIE is for the stub DIE, we copy over certain attributes
5316    from it to the DIE in the DWO.  If NULL we are skipping the stub.
5317    STUB_COMP_DIR is similar to STUB_COMP_UNIT_DIE: When reading a TU directly
5318    from the DWO file, bypassing the stub, it contains the DW_AT_comp_dir
5319    attribute of the referencing CU.  At most one of STUB_COMP_UNIT_DIE and
5320    STUB_COMP_DIR may be non-NULL.
5321    *RESULT_READER,*RESULT_INFO_PTR,*RESULT_COMP_UNIT_DIE,*RESULT_HAS_CHILDREN
5322    are filled in with the info of the DIE from the DWO file.
5323    ABBREV_TABLE_PROVIDED is non-zero if the caller of init_cutu_and_read_dies
5324    provided an abbrev table to use.
5325    The result is non-zero if a valid (non-dummy) DIE was found.  */
5326
5327 static int
5328 read_cutu_die_from_dwo (struct dwarf2_per_cu_data *this_cu,
5329                         struct dwo_unit *dwo_unit,
5330                         int abbrev_table_provided,
5331                         struct die_info *stub_comp_unit_die,
5332                         const char *stub_comp_dir,
5333                         struct die_reader_specs *result_reader,
5334                         const gdb_byte **result_info_ptr,
5335                         struct die_info **result_comp_unit_die,
5336                         int *result_has_children)
5337 {
5338   struct objfile *objfile = dwarf2_per_objfile->objfile;
5339   struct dwarf2_cu *cu = this_cu->cu;
5340   struct dwarf2_section_info *section;
5341   bfd *abfd;
5342   const gdb_byte *begin_info_ptr, *info_ptr;
5343   ULONGEST signature; /* Or dwo_id.  */
5344   struct attribute *comp_dir, *stmt_list, *low_pc, *high_pc, *ranges;
5345   int i,num_extra_attrs;
5346   struct dwarf2_section_info *dwo_abbrev_section;
5347   struct attribute *attr;
5348   struct die_info *comp_unit_die;
5349
5350   /* At most one of these may be provided.  */
5351   gdb_assert ((stub_comp_unit_die != NULL) + (stub_comp_dir != NULL) <= 1);
5352
5353   /* These attributes aren't processed until later:
5354      DW_AT_stmt_list, DW_AT_low_pc, DW_AT_high_pc, DW_AT_ranges.
5355      DW_AT_comp_dir is used now, to find the DWO file, but it is also
5356      referenced later.  However, these attributes are found in the stub
5357      which we won't have later.  In order to not impose this complication
5358      on the rest of the code, we read them here and copy them to the
5359      DWO CU/TU die.  */
5360
5361   stmt_list = NULL;
5362   low_pc = NULL;
5363   high_pc = NULL;
5364   ranges = NULL;
5365   comp_dir = NULL;
5366
5367   if (stub_comp_unit_die != NULL)
5368     {
5369       /* For TUs in DWO files, the DW_AT_stmt_list attribute lives in the
5370          DWO file.  */
5371       if (! this_cu->is_debug_types)
5372         stmt_list = dwarf2_attr (stub_comp_unit_die, DW_AT_stmt_list, cu);
5373       low_pc = dwarf2_attr (stub_comp_unit_die, DW_AT_low_pc, cu);
5374       high_pc = dwarf2_attr (stub_comp_unit_die, DW_AT_high_pc, cu);
5375       ranges = dwarf2_attr (stub_comp_unit_die, DW_AT_ranges, cu);
5376       comp_dir = dwarf2_attr (stub_comp_unit_die, DW_AT_comp_dir, cu);
5377
5378       /* There should be a DW_AT_addr_base attribute here (if needed).
5379          We need the value before we can process DW_FORM_GNU_addr_index.  */
5380       cu->addr_base = 0;
5381       attr = dwarf2_attr (stub_comp_unit_die, DW_AT_GNU_addr_base, cu);
5382       if (attr)
5383         cu->addr_base = DW_UNSND (attr);
5384
5385       /* There should be a DW_AT_ranges_base attribute here (if needed).
5386          We need the value before we can process DW_AT_ranges.  */
5387       cu->ranges_base = 0;
5388       attr = dwarf2_attr (stub_comp_unit_die, DW_AT_GNU_ranges_base, cu);
5389       if (attr)
5390         cu->ranges_base = DW_UNSND (attr);
5391     }
5392   else if (stub_comp_dir != NULL)
5393     {
5394       /* Reconstruct the comp_dir attribute to simplify the code below.  */
5395       comp_dir = XOBNEW (&cu->comp_unit_obstack, struct attribute);
5396       comp_dir->name = DW_AT_comp_dir;
5397       comp_dir->form = DW_FORM_string;
5398       DW_STRING_IS_CANONICAL (comp_dir) = 0;
5399       DW_STRING (comp_dir) = stub_comp_dir;
5400     }
5401
5402   /* Set up for reading the DWO CU/TU.  */
5403   cu->dwo_unit = dwo_unit;
5404   section = dwo_unit->section;
5405   dwarf2_read_section (objfile, section);
5406   abfd = get_section_bfd_owner (section);
5407   begin_info_ptr = info_ptr = (section->buffer
5408                                + to_underlying (dwo_unit->sect_off));
5409   dwo_abbrev_section = &dwo_unit->dwo_file->sections.abbrev;
5410   init_cu_die_reader (result_reader, cu, section, dwo_unit->dwo_file);
5411
5412   if (this_cu->is_debug_types)
5413     {
5414       struct signatured_type *sig_type = (struct signatured_type *) this_cu;
5415
5416       info_ptr = read_and_check_comp_unit_head (&cu->header, section,
5417                                                 dwo_abbrev_section,
5418                                                 info_ptr, rcuh_kind::TYPE);
5419       /* This is not an assert because it can be caused by bad debug info.  */
5420       if (sig_type->signature != cu->header.signature)
5421         {
5422           error (_("Dwarf Error: signature mismatch %s vs %s while reading"
5423                    " TU at offset 0x%x [in module %s]"),
5424                  hex_string (sig_type->signature),
5425                  hex_string (cu->header.signature),
5426                  to_underlying (dwo_unit->sect_off),
5427                  bfd_get_filename (abfd));
5428         }
5429       gdb_assert (dwo_unit->sect_off == cu->header.sect_off);
5430       /* For DWOs coming from DWP files, we don't know the CU length
5431          nor the type's offset in the TU until now.  */
5432       dwo_unit->length = get_cu_length (&cu->header);
5433       dwo_unit->type_offset_in_tu = cu->header.type_cu_offset_in_tu;
5434
5435       /* Establish the type offset that can be used to lookup the type.
5436          For DWO files, we don't know it until now.  */
5437       sig_type->type_offset_in_section
5438         = dwo_unit->sect_off + to_underlying (dwo_unit->type_offset_in_tu);
5439     }
5440   else
5441     {
5442       info_ptr = read_and_check_comp_unit_head (&cu->header, section,
5443                                                 dwo_abbrev_section,
5444                                                 info_ptr, rcuh_kind::COMPILE);
5445       gdb_assert (dwo_unit->sect_off == cu->header.sect_off);
5446       /* For DWOs coming from DWP files, we don't know the CU length
5447          until now.  */
5448       dwo_unit->length = get_cu_length (&cu->header);
5449     }
5450
5451   /* Replace the CU's original abbrev table with the DWO's.
5452      Reminder: We can't read the abbrev table until we've read the header.  */
5453   if (abbrev_table_provided)
5454     {
5455       /* Don't free the provided abbrev table, the caller of
5456          init_cutu_and_read_dies owns it.  */
5457       dwarf2_read_abbrevs (cu, dwo_abbrev_section);
5458       /* Ensure the DWO abbrev table gets freed.  */
5459       make_cleanup (dwarf2_free_abbrev_table, cu);
5460     }
5461   else
5462     {
5463       dwarf2_free_abbrev_table (cu);
5464       dwarf2_read_abbrevs (cu, dwo_abbrev_section);
5465       /* Leave any existing abbrev table cleanup as is.  */
5466     }
5467
5468   /* Read in the die, but leave space to copy over the attributes
5469      from the stub.  This has the benefit of simplifying the rest of
5470      the code - all the work to maintain the illusion of a single
5471      DW_TAG_{compile,type}_unit DIE is done here.  */
5472   num_extra_attrs = ((stmt_list != NULL)
5473                      + (low_pc != NULL)
5474                      + (high_pc != NULL)
5475                      + (ranges != NULL)
5476                      + (comp_dir != NULL));
5477   info_ptr = read_full_die_1 (result_reader, result_comp_unit_die, info_ptr,
5478                               result_has_children, num_extra_attrs);
5479
5480   /* Copy over the attributes from the stub to the DIE we just read in.  */
5481   comp_unit_die = *result_comp_unit_die;
5482   i = comp_unit_die->num_attrs;
5483   if (stmt_list != NULL)
5484     comp_unit_die->attrs[i++] = *stmt_list;
5485   if (low_pc != NULL)
5486     comp_unit_die->attrs[i++] = *low_pc;
5487   if (high_pc != NULL)
5488     comp_unit_die->attrs[i++] = *high_pc;
5489   if (ranges != NULL)
5490     comp_unit_die->attrs[i++] = *ranges;
5491   if (comp_dir != NULL)
5492     comp_unit_die->attrs[i++] = *comp_dir;
5493   comp_unit_die->num_attrs += num_extra_attrs;
5494
5495   if (dwarf_die_debug)
5496     {
5497       fprintf_unfiltered (gdb_stdlog,
5498                           "Read die from %s@0x%x of %s:\n",
5499                           get_section_name (section),
5500                           (unsigned) (begin_info_ptr - section->buffer),
5501                           bfd_get_filename (abfd));
5502       dump_die (comp_unit_die, dwarf_die_debug);
5503     }
5504
5505   /* Save the comp_dir attribute.  If there is no DWP file then we'll read
5506      TUs by skipping the stub and going directly to the entry in the DWO file.
5507      However, skipping the stub means we won't get DW_AT_comp_dir, so we have
5508      to get it via circuitous means.  Blech.  */
5509   if (comp_dir != NULL)
5510     result_reader->comp_dir = DW_STRING (comp_dir);
5511
5512   /* Skip dummy compilation units.  */
5513   if (info_ptr >= begin_info_ptr + dwo_unit->length
5514       || peek_abbrev_code (abfd, info_ptr) == 0)
5515     return 0;
5516
5517   *result_info_ptr = info_ptr;
5518   return 1;
5519 }
5520
5521 /* Subroutine of init_cutu_and_read_dies to simplify it.
5522    Look up the DWO unit specified by COMP_UNIT_DIE of THIS_CU.
5523    Returns NULL if the specified DWO unit cannot be found.  */
5524
5525 static struct dwo_unit *
5526 lookup_dwo_unit (struct dwarf2_per_cu_data *this_cu,
5527                  struct die_info *comp_unit_die)
5528 {
5529   struct dwarf2_cu *cu = this_cu->cu;
5530   struct attribute *attr;
5531   ULONGEST signature;
5532   struct dwo_unit *dwo_unit;
5533   const char *comp_dir, *dwo_name;
5534
5535   gdb_assert (cu != NULL);
5536
5537   /* Yeah, we look dwo_name up again, but it simplifies the code.  */
5538   dwo_name = dwarf2_string_attr (comp_unit_die, DW_AT_GNU_dwo_name, cu);
5539   comp_dir = dwarf2_string_attr (comp_unit_die, DW_AT_comp_dir, cu);
5540
5541   if (this_cu->is_debug_types)
5542     {
5543       struct signatured_type *sig_type;
5544
5545       /* Since this_cu is the first member of struct signatured_type,
5546          we can go from a pointer to one to a pointer to the other.  */
5547       sig_type = (struct signatured_type *) this_cu;
5548       signature = sig_type->signature;
5549       dwo_unit = lookup_dwo_type_unit (sig_type, dwo_name, comp_dir);
5550     }
5551   else
5552     {
5553       struct attribute *attr;
5554
5555       attr = dwarf2_attr (comp_unit_die, DW_AT_GNU_dwo_id, cu);
5556       if (! attr)
5557         error (_("Dwarf Error: missing dwo_id for dwo_name %s"
5558                  " [in module %s]"),
5559                dwo_name, objfile_name (this_cu->objfile));
5560       signature = DW_UNSND (attr);
5561       dwo_unit = lookup_dwo_comp_unit (this_cu, dwo_name, comp_dir,
5562                                        signature);
5563     }
5564
5565   return dwo_unit;
5566 }
5567
5568 /* Subroutine of init_cutu_and_read_dies to simplify it.
5569    See it for a description of the parameters.
5570    Read a TU directly from a DWO file, bypassing the stub.
5571
5572    Note: This function could be a little bit simpler if we shared cleanups
5573    with our caller, init_cutu_and_read_dies.  That's generally a fragile thing
5574    to do, so we keep this function self-contained.  Or we could move this
5575    into our caller, but it's complex enough already.  */
5576
5577 static void
5578 init_tu_and_read_dwo_dies (struct dwarf2_per_cu_data *this_cu,
5579                            int use_existing_cu, int keep,
5580                            die_reader_func_ftype *die_reader_func,
5581                            void *data)
5582 {
5583   struct dwarf2_cu *cu;
5584   struct signatured_type *sig_type;
5585   struct cleanup *cleanups, *free_cu_cleanup = NULL;
5586   struct die_reader_specs reader;
5587   const gdb_byte *info_ptr;
5588   struct die_info *comp_unit_die;
5589   int has_children;
5590
5591   /* Verify we can do the following downcast, and that we have the
5592      data we need.  */
5593   gdb_assert (this_cu->is_debug_types && this_cu->reading_dwo_directly);
5594   sig_type = (struct signatured_type *) this_cu;
5595   gdb_assert (sig_type->dwo_unit != NULL);
5596
5597   cleanups = make_cleanup (null_cleanup, NULL);
5598
5599   if (use_existing_cu && this_cu->cu != NULL)
5600     {
5601       gdb_assert (this_cu->cu->dwo_unit == sig_type->dwo_unit);
5602       cu = this_cu->cu;
5603       /* There's no need to do the rereading_dwo_cu handling that
5604          init_cutu_and_read_dies does since we don't read the stub.  */
5605     }
5606   else
5607     {
5608       /* If !use_existing_cu, this_cu->cu must be NULL.  */
5609       gdb_assert (this_cu->cu == NULL);
5610       cu = XNEW (struct dwarf2_cu);
5611       init_one_comp_unit (cu, this_cu);
5612       /* If an error occurs while loading, release our storage.  */
5613       free_cu_cleanup = make_cleanup (free_heap_comp_unit, cu);
5614     }
5615
5616   /* A future optimization, if needed, would be to use an existing
5617      abbrev table.  When reading DWOs with skeletonless TUs, all the TUs
5618      could share abbrev tables.  */
5619
5620   if (read_cutu_die_from_dwo (this_cu, sig_type->dwo_unit,
5621                               0 /* abbrev_table_provided */,
5622                               NULL /* stub_comp_unit_die */,
5623                               sig_type->dwo_unit->dwo_file->comp_dir,
5624                               &reader, &info_ptr,
5625                               &comp_unit_die, &has_children) == 0)
5626     {
5627       /* Dummy die.  */
5628       do_cleanups (cleanups);
5629       return;
5630     }
5631
5632   /* All the "real" work is done here.  */
5633   die_reader_func (&reader, info_ptr, comp_unit_die, has_children, data);
5634
5635   /* This duplicates the code in init_cutu_and_read_dies,
5636      but the alternative is making the latter more complex.
5637      This function is only for the special case of using DWO files directly:
5638      no point in overly complicating the general case just to handle this.  */
5639   if (free_cu_cleanup != NULL)
5640     {
5641       if (keep)
5642         {
5643           /* We've successfully allocated this compilation unit.  Let our
5644              caller clean it up when finished with it.  */
5645           discard_cleanups (free_cu_cleanup);
5646
5647           /* We can only discard free_cu_cleanup and all subsequent cleanups.
5648              So we have to manually free the abbrev table.  */
5649           dwarf2_free_abbrev_table (cu);
5650
5651           /* Link this CU into read_in_chain.  */
5652           this_cu->cu->read_in_chain = dwarf2_per_objfile->read_in_chain;
5653           dwarf2_per_objfile->read_in_chain = this_cu;
5654         }
5655       else
5656         do_cleanups (free_cu_cleanup);
5657     }
5658
5659   do_cleanups (cleanups);
5660 }
5661
5662 /* Initialize a CU (or TU) and read its DIEs.
5663    If the CU defers to a DWO file, read the DWO file as well.
5664
5665    ABBREV_TABLE, if non-NULL, is the abbreviation table to use.
5666    Otherwise the table specified in the comp unit header is read in and used.
5667    This is an optimization for when we already have the abbrev table.
5668
5669    If USE_EXISTING_CU is non-zero, and THIS_CU->cu is non-NULL, then use it.
5670    Otherwise, a new CU is allocated with xmalloc.
5671
5672    If KEEP is non-zero, then if we allocated a dwarf2_cu we add it to
5673    read_in_chain.  Otherwise the dwarf2_cu data is freed at the end.
5674
5675    WARNING: If THIS_CU is a "dummy CU" (used as filler by the incremental
5676    linker) then DIE_READER_FUNC will not get called.  */
5677
5678 static void
5679 init_cutu_and_read_dies (struct dwarf2_per_cu_data *this_cu,
5680                          struct abbrev_table *abbrev_table,
5681                          int use_existing_cu, int keep,
5682                          die_reader_func_ftype *die_reader_func,
5683                          void *data)
5684 {
5685   struct objfile *objfile = dwarf2_per_objfile->objfile;
5686   struct dwarf2_section_info *section = this_cu->section;
5687   bfd *abfd = get_section_bfd_owner (section);
5688   struct dwarf2_cu *cu;
5689   const gdb_byte *begin_info_ptr, *info_ptr;
5690   struct die_reader_specs reader;
5691   struct die_info *comp_unit_die;
5692   int has_children;
5693   struct attribute *attr;
5694   struct cleanup *cleanups, *free_cu_cleanup = NULL;
5695   struct signatured_type *sig_type = NULL;
5696   struct dwarf2_section_info *abbrev_section;
5697   /* Non-zero if CU currently points to a DWO file and we need to
5698      reread it.  When this happens we need to reread the skeleton die
5699      before we can reread the DWO file (this only applies to CUs, not TUs).  */
5700   int rereading_dwo_cu = 0;
5701
5702   if (dwarf_die_debug)
5703     fprintf_unfiltered (gdb_stdlog, "Reading %s unit at offset 0x%x\n",
5704                         this_cu->is_debug_types ? "type" : "comp",
5705                         to_underlying (this_cu->sect_off));
5706
5707   if (use_existing_cu)
5708     gdb_assert (keep);
5709
5710   /* If we're reading a TU directly from a DWO file, including a virtual DWO
5711      file (instead of going through the stub), short-circuit all of this.  */
5712   if (this_cu->reading_dwo_directly)
5713     {
5714       /* Narrow down the scope of possibilities to have to understand.  */
5715       gdb_assert (this_cu->is_debug_types);
5716       gdb_assert (abbrev_table == NULL);
5717       init_tu_and_read_dwo_dies (this_cu, use_existing_cu, keep,
5718                                  die_reader_func, data);
5719       return;
5720     }
5721
5722   cleanups = make_cleanup (null_cleanup, NULL);
5723
5724   /* This is cheap if the section is already read in.  */
5725   dwarf2_read_section (objfile, section);
5726
5727   begin_info_ptr = info_ptr = section->buffer + to_underlying (this_cu->sect_off);
5728
5729   abbrev_section = get_abbrev_section_for_cu (this_cu);
5730
5731   if (use_existing_cu && this_cu->cu != NULL)
5732     {
5733       cu = this_cu->cu;
5734       /* If this CU is from a DWO file we need to start over, we need to
5735          refetch the attributes from the skeleton CU.
5736          This could be optimized by retrieving those attributes from when we
5737          were here the first time: the previous comp_unit_die was stored in
5738          comp_unit_obstack.  But there's no data yet that we need this
5739          optimization.  */
5740       if (cu->dwo_unit != NULL)
5741         rereading_dwo_cu = 1;
5742     }
5743   else
5744     {
5745       /* If !use_existing_cu, this_cu->cu must be NULL.  */
5746       gdb_assert (this_cu->cu == NULL);
5747       cu = XNEW (struct dwarf2_cu);
5748       init_one_comp_unit (cu, this_cu);
5749       /* If an error occurs while loading, release our storage.  */
5750       free_cu_cleanup = make_cleanup (free_heap_comp_unit, cu);
5751     }
5752
5753   /* Get the header.  */
5754   if (to_underlying (cu->header.first_die_cu_offset) != 0 && !rereading_dwo_cu)
5755     {
5756       /* We already have the header, there's no need to read it in again.  */
5757       info_ptr += to_underlying (cu->header.first_die_cu_offset);
5758     }
5759   else
5760     {
5761       if (this_cu->is_debug_types)
5762         {
5763           info_ptr = read_and_check_comp_unit_head (&cu->header, section,
5764                                                     abbrev_section, info_ptr,
5765                                                     rcuh_kind::TYPE);
5766
5767           /* Since per_cu is the first member of struct signatured_type,
5768              we can go from a pointer to one to a pointer to the other.  */
5769           sig_type = (struct signatured_type *) this_cu;
5770           gdb_assert (sig_type->signature == cu->header.signature);
5771           gdb_assert (sig_type->type_offset_in_tu
5772                       == cu->header.type_cu_offset_in_tu);
5773           gdb_assert (this_cu->sect_off == cu->header.sect_off);
5774
5775           /* LENGTH has not been set yet for type units if we're
5776              using .gdb_index.  */
5777           this_cu->length = get_cu_length (&cu->header);
5778
5779           /* Establish the type offset that can be used to lookup the type.  */
5780           sig_type->type_offset_in_section =
5781             this_cu->sect_off + to_underlying (sig_type->type_offset_in_tu);
5782
5783           this_cu->dwarf_version = cu->header.version;
5784         }
5785       else
5786         {
5787           info_ptr = read_and_check_comp_unit_head (&cu->header, section,
5788                                                     abbrev_section,
5789                                                     info_ptr,
5790                                                     rcuh_kind::COMPILE);
5791
5792           gdb_assert (this_cu->sect_off == cu->header.sect_off);
5793           gdb_assert (this_cu->length == get_cu_length (&cu->header));
5794           this_cu->dwarf_version = cu->header.version;
5795         }
5796     }
5797
5798   /* Skip dummy compilation units.  */
5799   if (info_ptr >= begin_info_ptr + this_cu->length
5800       || peek_abbrev_code (abfd, info_ptr) == 0)
5801     {
5802       do_cleanups (cleanups);
5803       return;
5804     }
5805
5806   /* If we don't have them yet, read the abbrevs for this compilation unit.
5807      And if we need to read them now, make sure they're freed when we're
5808      done.  Note that it's important that if the CU had an abbrev table
5809      on entry we don't free it when we're done: Somewhere up the call stack
5810      it may be in use.  */
5811   if (abbrev_table != NULL)
5812     {
5813       gdb_assert (cu->abbrev_table == NULL);
5814       gdb_assert (cu->header.abbrev_sect_off == abbrev_table->sect_off);
5815       cu->abbrev_table = abbrev_table;
5816     }
5817   else if (cu->abbrev_table == NULL)
5818     {
5819       dwarf2_read_abbrevs (cu, abbrev_section);
5820       make_cleanup (dwarf2_free_abbrev_table, cu);
5821     }
5822   else if (rereading_dwo_cu)
5823     {
5824       dwarf2_free_abbrev_table (cu);
5825       dwarf2_read_abbrevs (cu, abbrev_section);
5826     }
5827
5828   /* Read the top level CU/TU die.  */
5829   init_cu_die_reader (&reader, cu, section, NULL);
5830   info_ptr = read_full_die (&reader, &comp_unit_die, info_ptr, &has_children);
5831
5832   /* If we are in a DWO stub, process it and then read in the "real" CU/TU
5833      from the DWO file.
5834      Note that if USE_EXISTING_OK != 0, and THIS_CU->cu already contains a
5835      DWO CU, that this test will fail (the attribute will not be present).  */
5836   attr = dwarf2_attr (comp_unit_die, DW_AT_GNU_dwo_name, cu);
5837   if (attr)
5838     {
5839       struct dwo_unit *dwo_unit;
5840       struct die_info *dwo_comp_unit_die;
5841
5842       if (has_children)
5843         {
5844           complaint (&symfile_complaints,
5845                      _("compilation unit with DW_AT_GNU_dwo_name"
5846                        " has children (offset 0x%x) [in module %s]"),
5847                      to_underlying (this_cu->sect_off), bfd_get_filename (abfd));
5848         }
5849       dwo_unit = lookup_dwo_unit (this_cu, comp_unit_die);
5850       if (dwo_unit != NULL)
5851         {
5852           if (read_cutu_die_from_dwo (this_cu, dwo_unit,
5853                                       abbrev_table != NULL,
5854                                       comp_unit_die, NULL,
5855                                       &reader, &info_ptr,
5856                                       &dwo_comp_unit_die, &has_children) == 0)
5857             {
5858               /* Dummy die.  */
5859               do_cleanups (cleanups);
5860               return;
5861             }
5862           comp_unit_die = dwo_comp_unit_die;
5863         }
5864       else
5865         {
5866           /* Yikes, we couldn't find the rest of the DIE, we only have
5867              the stub.  A complaint has already been logged.  There's
5868              not much more we can do except pass on the stub DIE to
5869              die_reader_func.  We don't want to throw an error on bad
5870              debug info.  */
5871         }
5872     }
5873
5874   /* All of the above is setup for this call.  Yikes.  */
5875   die_reader_func (&reader, info_ptr, comp_unit_die, has_children, data);
5876
5877   /* Done, clean up.  */
5878   if (free_cu_cleanup != NULL)
5879     {
5880       if (keep)
5881         {
5882           /* We've successfully allocated this compilation unit.  Let our
5883              caller clean it up when finished with it.  */
5884           discard_cleanups (free_cu_cleanup);
5885
5886           /* We can only discard free_cu_cleanup and all subsequent cleanups.
5887              So we have to manually free the abbrev table.  */
5888           dwarf2_free_abbrev_table (cu);
5889
5890           /* Link this CU into read_in_chain.  */
5891           this_cu->cu->read_in_chain = dwarf2_per_objfile->read_in_chain;
5892           dwarf2_per_objfile->read_in_chain = this_cu;
5893         }
5894       else
5895         do_cleanups (free_cu_cleanup);
5896     }
5897
5898   do_cleanups (cleanups);
5899 }
5900
5901 /* Read CU/TU THIS_CU but do not follow DW_AT_GNU_dwo_name if present.
5902    DWO_FILE, if non-NULL, is the DWO file to read (the caller is assumed
5903    to have already done the lookup to find the DWO file).
5904
5905    The caller is required to fill in THIS_CU->section, THIS_CU->offset, and
5906    THIS_CU->is_debug_types, but nothing else.
5907
5908    We fill in THIS_CU->length.
5909
5910    WARNING: If THIS_CU is a "dummy CU" (used as filler by the incremental
5911    linker) then DIE_READER_FUNC will not get called.
5912
5913    THIS_CU->cu is always freed when done.
5914    This is done in order to not leave THIS_CU->cu in a state where we have
5915    to care whether it refers to the "main" CU or the DWO CU.  */
5916
5917 static void
5918 init_cutu_and_read_dies_no_follow (struct dwarf2_per_cu_data *this_cu,
5919                                    struct dwo_file *dwo_file,
5920                                    die_reader_func_ftype *die_reader_func,
5921                                    void *data)
5922 {
5923   struct objfile *objfile = dwarf2_per_objfile->objfile;
5924   struct dwarf2_section_info *section = this_cu->section;
5925   bfd *abfd = get_section_bfd_owner (section);
5926   struct dwarf2_section_info *abbrev_section;
5927   struct dwarf2_cu cu;
5928   const gdb_byte *begin_info_ptr, *info_ptr;
5929   struct die_reader_specs reader;
5930   struct cleanup *cleanups;
5931   struct die_info *comp_unit_die;
5932   int has_children;
5933
5934   if (dwarf_die_debug)
5935     fprintf_unfiltered (gdb_stdlog, "Reading %s unit at offset 0x%x\n",
5936                         this_cu->is_debug_types ? "type" : "comp",
5937                         to_underlying (this_cu->sect_off));
5938
5939   gdb_assert (this_cu->cu == NULL);
5940
5941   abbrev_section = (dwo_file != NULL
5942                     ? &dwo_file->sections.abbrev
5943                     : get_abbrev_section_for_cu (this_cu));
5944
5945   /* This is cheap if the section is already read in.  */
5946   dwarf2_read_section (objfile, section);
5947
5948   init_one_comp_unit (&cu, this_cu);
5949
5950   cleanups = make_cleanup (free_stack_comp_unit, &cu);
5951
5952   begin_info_ptr = info_ptr = section->buffer + to_underlying (this_cu->sect_off);
5953   info_ptr = read_and_check_comp_unit_head (&cu.header, section,
5954                                             abbrev_section, info_ptr,
5955                                             (this_cu->is_debug_types
5956                                              ? rcuh_kind::TYPE
5957                                              : rcuh_kind::COMPILE));
5958
5959   this_cu->length = get_cu_length (&cu.header);
5960
5961   /* Skip dummy compilation units.  */
5962   if (info_ptr >= begin_info_ptr + this_cu->length
5963       || peek_abbrev_code (abfd, info_ptr) == 0)
5964     {
5965       do_cleanups (cleanups);
5966       return;
5967     }
5968
5969   dwarf2_read_abbrevs (&cu, abbrev_section);
5970   make_cleanup (dwarf2_free_abbrev_table, &cu);
5971
5972   init_cu_die_reader (&reader, &cu, section, dwo_file);
5973   info_ptr = read_full_die (&reader, &comp_unit_die, info_ptr, &has_children);
5974
5975   die_reader_func (&reader, info_ptr, comp_unit_die, has_children, data);
5976
5977   do_cleanups (cleanups);
5978 }
5979
5980 /* Read a CU/TU, except that this does not look for DW_AT_GNU_dwo_name and
5981    does not lookup the specified DWO file.
5982    This cannot be used to read DWO files.
5983
5984    THIS_CU->cu is always freed when done.
5985    This is done in order to not leave THIS_CU->cu in a state where we have
5986    to care whether it refers to the "main" CU or the DWO CU.
5987    We can revisit this if the data shows there's a performance issue.  */
5988
5989 static void
5990 init_cutu_and_read_dies_simple (struct dwarf2_per_cu_data *this_cu,
5991                                 die_reader_func_ftype *die_reader_func,
5992                                 void *data)
5993 {
5994   init_cutu_and_read_dies_no_follow (this_cu, NULL, die_reader_func, data);
5995 }
5996 \f
5997 /* Type Unit Groups.
5998
5999    Type Unit Groups are a way to collapse the set of all TUs (type units) into
6000    a more manageable set.  The grouping is done by DW_AT_stmt_list entry
6001    so that all types coming from the same compilation (.o file) are grouped
6002    together.  A future step could be to put the types in the same symtab as
6003    the CU the types ultimately came from.  */
6004
6005 static hashval_t
6006 hash_type_unit_group (const void *item)
6007 {
6008   const struct type_unit_group *tu_group
6009     = (const struct type_unit_group *) item;
6010
6011   return hash_stmt_list_entry (&tu_group->hash);
6012 }
6013
6014 static int
6015 eq_type_unit_group (const void *item_lhs, const void *item_rhs)
6016 {
6017   const struct type_unit_group *lhs = (const struct type_unit_group *) item_lhs;
6018   const struct type_unit_group *rhs = (const struct type_unit_group *) item_rhs;
6019
6020   return eq_stmt_list_entry (&lhs->hash, &rhs->hash);
6021 }
6022
6023 /* Allocate a hash table for type unit groups.  */
6024
6025 static htab_t
6026 allocate_type_unit_groups_table (void)
6027 {
6028   return htab_create_alloc_ex (3,
6029                                hash_type_unit_group,
6030                                eq_type_unit_group,
6031                                NULL,
6032                                &dwarf2_per_objfile->objfile->objfile_obstack,
6033                                hashtab_obstack_allocate,
6034                                dummy_obstack_deallocate);
6035 }
6036
6037 /* Type units that don't have DW_AT_stmt_list are grouped into their own
6038    partial symtabs.  We combine several TUs per psymtab to not let the size
6039    of any one psymtab grow too big.  */
6040 #define NO_STMT_LIST_TYPE_UNIT_PSYMTAB (1 << 31)
6041 #define NO_STMT_LIST_TYPE_UNIT_PSYMTAB_SIZE 10
6042
6043 /* Helper routine for get_type_unit_group.
6044    Create the type_unit_group object used to hold one or more TUs.  */
6045
6046 static struct type_unit_group *
6047 create_type_unit_group (struct dwarf2_cu *cu, sect_offset line_offset_struct)
6048 {
6049   struct objfile *objfile = dwarf2_per_objfile->objfile;
6050   struct dwarf2_per_cu_data *per_cu;
6051   struct type_unit_group *tu_group;
6052
6053   tu_group = OBSTACK_ZALLOC (&objfile->objfile_obstack,
6054                              struct type_unit_group);
6055   per_cu = &tu_group->per_cu;
6056   per_cu->objfile = objfile;
6057
6058   if (dwarf2_per_objfile->using_index)
6059     {
6060       per_cu->v.quick = OBSTACK_ZALLOC (&objfile->objfile_obstack,
6061                                         struct dwarf2_per_cu_quick_data);
6062     }
6063   else
6064     {
6065       unsigned int line_offset = to_underlying (line_offset_struct);
6066       struct partial_symtab *pst;
6067       char *name;
6068
6069       /* Give the symtab a useful name for debug purposes.  */
6070       if ((line_offset & NO_STMT_LIST_TYPE_UNIT_PSYMTAB) != 0)
6071         name = xstrprintf ("<type_units_%d>",
6072                            (line_offset & ~NO_STMT_LIST_TYPE_UNIT_PSYMTAB));
6073       else
6074         name = xstrprintf ("<type_units_at_0x%x>", line_offset);
6075
6076       pst = create_partial_symtab (per_cu, name);
6077       pst->anonymous = 1;
6078
6079       xfree (name);
6080     }
6081
6082   tu_group->hash.dwo_unit = cu->dwo_unit;
6083   tu_group->hash.line_sect_off = line_offset_struct;
6084
6085   return tu_group;
6086 }
6087
6088 /* Look up the type_unit_group for type unit CU, and create it if necessary.
6089    STMT_LIST is a DW_AT_stmt_list attribute.  */
6090
6091 static struct type_unit_group *
6092 get_type_unit_group (struct dwarf2_cu *cu, const struct attribute *stmt_list)
6093 {
6094   struct tu_stats *tu_stats = &dwarf2_per_objfile->tu_stats;
6095   struct type_unit_group *tu_group;
6096   void **slot;
6097   unsigned int line_offset;
6098   struct type_unit_group type_unit_group_for_lookup;
6099
6100   if (dwarf2_per_objfile->type_unit_groups == NULL)
6101     {
6102       dwarf2_per_objfile->type_unit_groups =
6103         allocate_type_unit_groups_table ();
6104     }
6105
6106   /* Do we need to create a new group, or can we use an existing one?  */
6107
6108   if (stmt_list)
6109     {
6110       line_offset = DW_UNSND (stmt_list);
6111       ++tu_stats->nr_symtab_sharers;
6112     }
6113   else
6114     {
6115       /* Ugh, no stmt_list.  Rare, but we have to handle it.
6116          We can do various things here like create one group per TU or
6117          spread them over multiple groups to split up the expansion work.
6118          To avoid worst case scenarios (too many groups or too large groups)
6119          we, umm, group them in bunches.  */
6120       line_offset = (NO_STMT_LIST_TYPE_UNIT_PSYMTAB
6121                      | (tu_stats->nr_stmt_less_type_units
6122                         / NO_STMT_LIST_TYPE_UNIT_PSYMTAB_SIZE));
6123       ++tu_stats->nr_stmt_less_type_units;
6124     }
6125
6126   type_unit_group_for_lookup.hash.dwo_unit = cu->dwo_unit;
6127   type_unit_group_for_lookup.hash.line_sect_off = (sect_offset) line_offset;
6128   slot = htab_find_slot (dwarf2_per_objfile->type_unit_groups,
6129                          &type_unit_group_for_lookup, INSERT);
6130   if (*slot != NULL)
6131     {
6132       tu_group = (struct type_unit_group *) *slot;
6133       gdb_assert (tu_group != NULL);
6134     }
6135   else
6136     {
6137       sect_offset line_offset_struct = (sect_offset) line_offset;
6138       tu_group = create_type_unit_group (cu, line_offset_struct);
6139       *slot = tu_group;
6140       ++tu_stats->nr_symtabs;
6141     }
6142
6143   return tu_group;
6144 }
6145 \f
6146 /* Partial symbol tables.  */
6147
6148 /* Create a psymtab named NAME and assign it to PER_CU.
6149
6150    The caller must fill in the following details:
6151    dirname, textlow, texthigh.  */
6152
6153 static struct partial_symtab *
6154 create_partial_symtab (struct dwarf2_per_cu_data *per_cu, const char *name)
6155 {
6156   struct objfile *objfile = per_cu->objfile;
6157   struct partial_symtab *pst;
6158
6159   pst = start_psymtab_common (objfile, name, 0,
6160                               objfile->global_psymbols.next,
6161                               objfile->static_psymbols.next);
6162
6163   pst->psymtabs_addrmap_supported = 1;
6164
6165   /* This is the glue that links PST into GDB's symbol API.  */
6166   pst->read_symtab_private = per_cu;
6167   pst->read_symtab = dwarf2_read_symtab;
6168   per_cu->v.psymtab = pst;
6169
6170   return pst;
6171 }
6172
6173 /* The DATA object passed to process_psymtab_comp_unit_reader has this
6174    type.  */
6175
6176 struct process_psymtab_comp_unit_data
6177 {
6178   /* True if we are reading a DW_TAG_partial_unit.  */
6179
6180   int want_partial_unit;
6181
6182   /* The "pretend" language that is used if the CU doesn't declare a
6183      language.  */
6184
6185   enum language pretend_language;
6186 };
6187
6188 /* die_reader_func for process_psymtab_comp_unit.  */
6189
6190 static void
6191 process_psymtab_comp_unit_reader (const struct die_reader_specs *reader,
6192                                   const gdb_byte *info_ptr,
6193                                   struct die_info *comp_unit_die,
6194                                   int has_children,
6195                                   void *data)
6196 {
6197   struct dwarf2_cu *cu = reader->cu;
6198   struct objfile *objfile = cu->objfile;
6199   struct gdbarch *gdbarch = get_objfile_arch (objfile);
6200   struct dwarf2_per_cu_data *per_cu = cu->per_cu;
6201   CORE_ADDR baseaddr;
6202   CORE_ADDR best_lowpc = 0, best_highpc = 0;
6203   struct partial_symtab *pst;
6204   enum pc_bounds_kind cu_bounds_kind;
6205   const char *filename;
6206   struct process_psymtab_comp_unit_data *info
6207     = (struct process_psymtab_comp_unit_data *) data;
6208
6209   if (comp_unit_die->tag == DW_TAG_partial_unit && !info->want_partial_unit)
6210     return;
6211
6212   gdb_assert (! per_cu->is_debug_types);
6213
6214   prepare_one_comp_unit (cu, comp_unit_die, info->pretend_language);
6215
6216   cu->list_in_scope = &file_symbols;
6217
6218   /* Allocate a new partial symbol table structure.  */
6219   filename = dwarf2_string_attr (comp_unit_die, DW_AT_name, cu);
6220   if (filename == NULL)
6221     filename = "";
6222
6223   pst = create_partial_symtab (per_cu, filename);
6224
6225   /* This must be done before calling dwarf2_build_include_psymtabs.  */
6226   pst->dirname = dwarf2_string_attr (comp_unit_die, DW_AT_comp_dir, cu);
6227
6228   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
6229
6230   dwarf2_find_base_address (comp_unit_die, cu);
6231
6232   /* Possibly set the default values of LOWPC and HIGHPC from
6233      `DW_AT_ranges'.  */
6234   cu_bounds_kind = dwarf2_get_pc_bounds (comp_unit_die, &best_lowpc,
6235                                          &best_highpc, cu, pst);
6236   if (cu_bounds_kind == PC_BOUNDS_HIGH_LOW && best_lowpc < best_highpc)
6237     /* Store the contiguous range if it is not empty; it can be empty for
6238        CUs with no code.  */
6239     addrmap_set_empty (objfile->psymtabs_addrmap,
6240                        gdbarch_adjust_dwarf2_addr (gdbarch,
6241                                                    best_lowpc + baseaddr),
6242                        gdbarch_adjust_dwarf2_addr (gdbarch,
6243                                                    best_highpc + baseaddr) - 1,
6244                        pst);
6245
6246   /* Check if comp unit has_children.
6247      If so, read the rest of the partial symbols from this comp unit.
6248      If not, there's no more debug_info for this comp unit.  */
6249   if (has_children)
6250     {
6251       struct partial_die_info *first_die;
6252       CORE_ADDR lowpc, highpc;
6253
6254       lowpc = ((CORE_ADDR) -1);
6255       highpc = ((CORE_ADDR) 0);
6256
6257       first_die = load_partial_dies (reader, info_ptr, 1);
6258
6259       scan_partial_symbols (first_die, &lowpc, &highpc,
6260                             cu_bounds_kind <= PC_BOUNDS_INVALID, cu);
6261
6262       /* If we didn't find a lowpc, set it to highpc to avoid
6263          complaints from `maint check'.  */
6264       if (lowpc == ((CORE_ADDR) -1))
6265         lowpc = highpc;
6266
6267       /* If the compilation unit didn't have an explicit address range,
6268          then use the information extracted from its child dies.  */
6269       if (cu_bounds_kind <= PC_BOUNDS_INVALID)
6270         {
6271           best_lowpc = lowpc;
6272           best_highpc = highpc;
6273         }
6274     }
6275   pst->textlow = gdbarch_adjust_dwarf2_addr (gdbarch, best_lowpc + baseaddr);
6276   pst->texthigh = gdbarch_adjust_dwarf2_addr (gdbarch, best_highpc + baseaddr);
6277
6278   end_psymtab_common (objfile, pst);
6279
6280   if (!VEC_empty (dwarf2_per_cu_ptr, cu->per_cu->imported_symtabs))
6281     {
6282       int i;
6283       int len = VEC_length (dwarf2_per_cu_ptr, cu->per_cu->imported_symtabs);
6284       struct dwarf2_per_cu_data *iter;
6285
6286       /* Fill in 'dependencies' here; we fill in 'users' in a
6287          post-pass.  */
6288       pst->number_of_dependencies = len;
6289       pst->dependencies =
6290         XOBNEWVEC (&objfile->objfile_obstack, struct partial_symtab *, len);
6291       for (i = 0;
6292            VEC_iterate (dwarf2_per_cu_ptr, cu->per_cu->imported_symtabs,
6293                         i, iter);
6294            ++i)
6295         pst->dependencies[i] = iter->v.psymtab;
6296
6297       VEC_free (dwarf2_per_cu_ptr, cu->per_cu->imported_symtabs);
6298     }
6299
6300   /* Get the list of files included in the current compilation unit,
6301      and build a psymtab for each of them.  */
6302   dwarf2_build_include_psymtabs (cu, comp_unit_die, pst);
6303
6304   if (dwarf_read_debug)
6305     {
6306       struct gdbarch *gdbarch = get_objfile_arch (objfile);
6307
6308       fprintf_unfiltered (gdb_stdlog,
6309                           "Psymtab for %s unit @0x%x: %s - %s"
6310                           ", %d global, %d static syms\n",
6311                           per_cu->is_debug_types ? "type" : "comp",
6312                           to_underlying (per_cu->sect_off),
6313                           paddress (gdbarch, pst->textlow),
6314                           paddress (gdbarch, pst->texthigh),
6315                           pst->n_global_syms, pst->n_static_syms);
6316     }
6317 }
6318
6319 /* Subroutine of dwarf2_build_psymtabs_hard to simplify it.
6320    Process compilation unit THIS_CU for a psymtab.  */
6321
6322 static void
6323 process_psymtab_comp_unit (struct dwarf2_per_cu_data *this_cu,
6324                            int want_partial_unit,
6325                            enum language pretend_language)
6326 {
6327   /* If this compilation unit was already read in, free the
6328      cached copy in order to read it in again.  This is
6329      necessary because we skipped some symbols when we first
6330      read in the compilation unit (see load_partial_dies).
6331      This problem could be avoided, but the benefit is unclear.  */
6332   if (this_cu->cu != NULL)
6333     free_one_cached_comp_unit (this_cu);
6334
6335   if (this_cu->is_debug_types)
6336     init_cutu_and_read_dies (this_cu, NULL, 0, 0, build_type_psymtabs_reader,
6337                              NULL);
6338   else
6339     {
6340       process_psymtab_comp_unit_data info;
6341       info.want_partial_unit = want_partial_unit;
6342       info.pretend_language = pretend_language;
6343       init_cutu_and_read_dies (this_cu, NULL, 0, 0,
6344                                process_psymtab_comp_unit_reader, &info);
6345     }
6346
6347   /* Age out any secondary CUs.  */
6348   age_cached_comp_units ();
6349 }
6350
6351 /* Reader function for build_type_psymtabs.  */
6352
6353 static void
6354 build_type_psymtabs_reader (const struct die_reader_specs *reader,
6355                             const gdb_byte *info_ptr,
6356                             struct die_info *type_unit_die,
6357                             int has_children,
6358                             void *data)
6359 {
6360   struct objfile *objfile = dwarf2_per_objfile->objfile;
6361   struct dwarf2_cu *cu = reader->cu;
6362   struct dwarf2_per_cu_data *per_cu = cu->per_cu;
6363   struct signatured_type *sig_type;
6364   struct type_unit_group *tu_group;
6365   struct attribute *attr;
6366   struct partial_die_info *first_die;
6367   CORE_ADDR lowpc, highpc;
6368   struct partial_symtab *pst;
6369
6370   gdb_assert (data == NULL);
6371   gdb_assert (per_cu->is_debug_types);
6372   sig_type = (struct signatured_type *) per_cu;
6373
6374   if (! has_children)
6375     return;
6376
6377   attr = dwarf2_attr_no_follow (type_unit_die, DW_AT_stmt_list);
6378   tu_group = get_type_unit_group (cu, attr);
6379
6380   VEC_safe_push (sig_type_ptr, tu_group->tus, sig_type);
6381
6382   prepare_one_comp_unit (cu, type_unit_die, language_minimal);
6383   cu->list_in_scope = &file_symbols;
6384   pst = create_partial_symtab (per_cu, "");
6385   pst->anonymous = 1;
6386
6387   first_die = load_partial_dies (reader, info_ptr, 1);
6388
6389   lowpc = (CORE_ADDR) -1;
6390   highpc = (CORE_ADDR) 0;
6391   scan_partial_symbols (first_die, &lowpc, &highpc, 0, cu);
6392
6393   end_psymtab_common (objfile, pst);
6394 }
6395
6396 /* Struct used to sort TUs by their abbreviation table offset.  */
6397
6398 struct tu_abbrev_offset
6399 {
6400   struct signatured_type *sig_type;
6401   sect_offset abbrev_offset;
6402 };
6403
6404 /* Helper routine for build_type_psymtabs_1, passed to qsort.  */
6405
6406 static int
6407 sort_tu_by_abbrev_offset (const void *ap, const void *bp)
6408 {
6409   const struct tu_abbrev_offset * const *a
6410     = (const struct tu_abbrev_offset * const*) ap;
6411   const struct tu_abbrev_offset * const *b
6412     = (const struct tu_abbrev_offset * const*) bp;
6413   sect_offset aoff = (*a)->abbrev_offset;
6414   sect_offset boff = (*b)->abbrev_offset;
6415
6416   return (aoff > boff) - (aoff < boff);
6417 }
6418
6419 /* Efficiently read all the type units.
6420    This does the bulk of the work for build_type_psymtabs.
6421
6422    The efficiency is because we sort TUs by the abbrev table they use and
6423    only read each abbrev table once.  In one program there are 200K TUs
6424    sharing 8K abbrev tables.
6425
6426    The main purpose of this function is to support building the
6427    dwarf2_per_objfile->type_unit_groups table.
6428    TUs typically share the DW_AT_stmt_list of the CU they came from, so we
6429    can collapse the search space by grouping them by stmt_list.
6430    The savings can be significant, in the same program from above the 200K TUs
6431    share 8K stmt_list tables.
6432
6433    FUNC is expected to call get_type_unit_group, which will create the
6434    struct type_unit_group if necessary and add it to
6435    dwarf2_per_objfile->type_unit_groups.  */
6436
6437 static void
6438 build_type_psymtabs_1 (void)
6439 {
6440   struct tu_stats *tu_stats = &dwarf2_per_objfile->tu_stats;
6441   struct cleanup *cleanups;
6442   struct abbrev_table *abbrev_table;
6443   sect_offset abbrev_offset;
6444   struct tu_abbrev_offset *sorted_by_abbrev;
6445   int i;
6446
6447   /* It's up to the caller to not call us multiple times.  */
6448   gdb_assert (dwarf2_per_objfile->type_unit_groups == NULL);
6449
6450   if (dwarf2_per_objfile->n_type_units == 0)
6451     return;
6452
6453   /* TUs typically share abbrev tables, and there can be way more TUs than
6454      abbrev tables.  Sort by abbrev table to reduce the number of times we
6455      read each abbrev table in.
6456      Alternatives are to punt or to maintain a cache of abbrev tables.
6457      This is simpler and efficient enough for now.
6458
6459      Later we group TUs by their DW_AT_stmt_list value (as this defines the
6460      symtab to use).  Typically TUs with the same abbrev offset have the same
6461      stmt_list value too so in practice this should work well.
6462
6463      The basic algorithm here is:
6464
6465       sort TUs by abbrev table
6466       for each TU with same abbrev table:
6467         read abbrev table if first user
6468         read TU top level DIE
6469           [IWBN if DWO skeletons had DW_AT_stmt_list]
6470         call FUNC  */
6471
6472   if (dwarf_read_debug)
6473     fprintf_unfiltered (gdb_stdlog, "Building type unit groups ...\n");
6474
6475   /* Sort in a separate table to maintain the order of all_type_units
6476      for .gdb_index: TU indices directly index all_type_units.  */
6477   sorted_by_abbrev = XNEWVEC (struct tu_abbrev_offset,
6478                               dwarf2_per_objfile->n_type_units);
6479   for (i = 0; i < dwarf2_per_objfile->n_type_units; ++i)
6480     {
6481       struct signatured_type *sig_type = dwarf2_per_objfile->all_type_units[i];
6482
6483       sorted_by_abbrev[i].sig_type = sig_type;
6484       sorted_by_abbrev[i].abbrev_offset =
6485         read_abbrev_offset (sig_type->per_cu.section,
6486                             sig_type->per_cu.sect_off);
6487     }
6488   cleanups = make_cleanup (xfree, sorted_by_abbrev);
6489   qsort (sorted_by_abbrev, dwarf2_per_objfile->n_type_units,
6490          sizeof (struct tu_abbrev_offset), sort_tu_by_abbrev_offset);
6491
6492   abbrev_offset = (sect_offset) ~(unsigned) 0;
6493   abbrev_table = NULL;
6494   make_cleanup (abbrev_table_free_cleanup, &abbrev_table);
6495
6496   for (i = 0; i < dwarf2_per_objfile->n_type_units; ++i)
6497     {
6498       const struct tu_abbrev_offset *tu = &sorted_by_abbrev[i];
6499
6500       /* Switch to the next abbrev table if necessary.  */
6501       if (abbrev_table == NULL
6502           || tu->abbrev_offset != abbrev_offset)
6503         {
6504           if (abbrev_table != NULL)
6505             {
6506               abbrev_table_free (abbrev_table);
6507               /* Reset to NULL in case abbrev_table_read_table throws
6508                  an error: abbrev_table_free_cleanup will get called.  */
6509               abbrev_table = NULL;
6510             }
6511           abbrev_offset = tu->abbrev_offset;
6512           abbrev_table =
6513             abbrev_table_read_table (&dwarf2_per_objfile->abbrev,
6514                                      abbrev_offset);
6515           ++tu_stats->nr_uniq_abbrev_tables;
6516         }
6517
6518       init_cutu_and_read_dies (&tu->sig_type->per_cu, abbrev_table, 0, 0,
6519                                build_type_psymtabs_reader, NULL);
6520     }
6521
6522   do_cleanups (cleanups);
6523 }
6524
6525 /* Print collected type unit statistics.  */
6526
6527 static void
6528 print_tu_stats (void)
6529 {
6530   struct tu_stats *tu_stats = &dwarf2_per_objfile->tu_stats;
6531
6532   fprintf_unfiltered (gdb_stdlog, "Type unit statistics:\n");
6533   fprintf_unfiltered (gdb_stdlog, "  %d TUs\n",
6534                       dwarf2_per_objfile->n_type_units);
6535   fprintf_unfiltered (gdb_stdlog, "  %d uniq abbrev tables\n",
6536                       tu_stats->nr_uniq_abbrev_tables);
6537   fprintf_unfiltered (gdb_stdlog, "  %d symtabs from stmt_list entries\n",
6538                       tu_stats->nr_symtabs);
6539   fprintf_unfiltered (gdb_stdlog, "  %d symtab sharers\n",
6540                       tu_stats->nr_symtab_sharers);
6541   fprintf_unfiltered (gdb_stdlog, "  %d type units without a stmt_list\n",
6542                       tu_stats->nr_stmt_less_type_units);
6543   fprintf_unfiltered (gdb_stdlog, "  %d all_type_units reallocs\n",
6544                       tu_stats->nr_all_type_units_reallocs);
6545 }
6546
6547 /* Traversal function for build_type_psymtabs.  */
6548
6549 static int
6550 build_type_psymtab_dependencies (void **slot, void *info)
6551 {
6552   struct objfile *objfile = dwarf2_per_objfile->objfile;
6553   struct type_unit_group *tu_group = (struct type_unit_group *) *slot;
6554   struct dwarf2_per_cu_data *per_cu = &tu_group->per_cu;
6555   struct partial_symtab *pst = per_cu->v.psymtab;
6556   int len = VEC_length (sig_type_ptr, tu_group->tus);
6557   struct signatured_type *iter;
6558   int i;
6559
6560   gdb_assert (len > 0);
6561   gdb_assert (IS_TYPE_UNIT_GROUP (per_cu));
6562
6563   pst->number_of_dependencies = len;
6564   pst->dependencies =
6565     XOBNEWVEC (&objfile->objfile_obstack, struct partial_symtab *, len);
6566   for (i = 0;
6567        VEC_iterate (sig_type_ptr, tu_group->tus, i, iter);
6568        ++i)
6569     {
6570       gdb_assert (iter->per_cu.is_debug_types);
6571       pst->dependencies[i] = iter->per_cu.v.psymtab;
6572       iter->type_unit_group = tu_group;
6573     }
6574
6575   VEC_free (sig_type_ptr, tu_group->tus);
6576
6577   return 1;
6578 }
6579
6580 /* Subroutine of dwarf2_build_psymtabs_hard to simplify it.
6581    Build partial symbol tables for the .debug_types comp-units.  */
6582
6583 static void
6584 build_type_psymtabs (struct objfile *objfile)
6585 {
6586   if (! create_all_type_units (objfile))
6587     return;
6588
6589   build_type_psymtabs_1 ();
6590 }
6591
6592 /* Traversal function for process_skeletonless_type_unit.
6593    Read a TU in a DWO file and build partial symbols for it.  */
6594
6595 static int
6596 process_skeletonless_type_unit (void **slot, void *info)
6597 {
6598   struct dwo_unit *dwo_unit = (struct dwo_unit *) *slot;
6599   struct objfile *objfile = (struct objfile *) info;
6600   struct signatured_type find_entry, *entry;
6601
6602   /* If this TU doesn't exist in the global table, add it and read it in.  */
6603
6604   if (dwarf2_per_objfile->signatured_types == NULL)
6605     {
6606       dwarf2_per_objfile->signatured_types
6607         = allocate_signatured_type_table (objfile);
6608     }
6609
6610   find_entry.signature = dwo_unit->signature;
6611   slot = htab_find_slot (dwarf2_per_objfile->signatured_types, &find_entry,
6612                          INSERT);
6613   /* If we've already seen this type there's nothing to do.  What's happening
6614      is we're doing our own version of comdat-folding here.  */
6615   if (*slot != NULL)
6616     return 1;
6617
6618   /* This does the job that create_all_type_units would have done for
6619      this TU.  */
6620   entry = add_type_unit (dwo_unit->signature, slot);
6621   fill_in_sig_entry_from_dwo_entry (objfile, entry, dwo_unit);
6622   *slot = entry;
6623
6624   /* This does the job that build_type_psymtabs_1 would have done.  */
6625   init_cutu_and_read_dies (&entry->per_cu, NULL, 0, 0,
6626                            build_type_psymtabs_reader, NULL);
6627
6628   return 1;
6629 }
6630
6631 /* Traversal function for process_skeletonless_type_units.  */
6632
6633 static int
6634 process_dwo_file_for_skeletonless_type_units (void **slot, void *info)
6635 {
6636   struct dwo_file *dwo_file = (struct dwo_file *) *slot;
6637
6638   if (dwo_file->tus != NULL)
6639     {
6640       htab_traverse_noresize (dwo_file->tus,
6641                               process_skeletonless_type_unit, info);
6642     }
6643
6644   return 1;
6645 }
6646
6647 /* Scan all TUs of DWO files, verifying we've processed them.
6648    This is needed in case a TU was emitted without its skeleton.
6649    Note: This can't be done until we know what all the DWO files are.  */
6650
6651 static void
6652 process_skeletonless_type_units (struct objfile *objfile)
6653 {
6654   /* Skeletonless TUs in DWP files without .gdb_index is not supported yet.  */
6655   if (get_dwp_file () == NULL
6656       && dwarf2_per_objfile->dwo_files != NULL)
6657     {
6658       htab_traverse_noresize (dwarf2_per_objfile->dwo_files,
6659                               process_dwo_file_for_skeletonless_type_units,
6660                               objfile);
6661     }
6662 }
6663
6664 /* A cleanup function that clears objfile's psymtabs_addrmap field.  */
6665
6666 static void
6667 psymtabs_addrmap_cleanup (void *o)
6668 {
6669   struct objfile *objfile = (struct objfile *) o;
6670
6671   objfile->psymtabs_addrmap = NULL;
6672 }
6673
6674 /* Compute the 'user' field for each psymtab in OBJFILE.  */
6675
6676 static void
6677 set_partial_user (struct objfile *objfile)
6678 {
6679   int i;
6680
6681   for (i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
6682     {
6683       struct dwarf2_per_cu_data *per_cu = dw2_get_cutu (i);
6684       struct partial_symtab *pst = per_cu->v.psymtab;
6685       int j;
6686
6687       if (pst == NULL)
6688         continue;
6689
6690       for (j = 0; j < pst->number_of_dependencies; ++j)
6691         {
6692           /* Set the 'user' field only if it is not already set.  */
6693           if (pst->dependencies[j]->user == NULL)
6694             pst->dependencies[j]->user = pst;
6695         }
6696     }
6697 }
6698
6699 /* Build the partial symbol table by doing a quick pass through the
6700    .debug_info and .debug_abbrev sections.  */
6701
6702 static void
6703 dwarf2_build_psymtabs_hard (struct objfile *objfile)
6704 {
6705   struct cleanup *back_to, *addrmap_cleanup;
6706   int i;
6707
6708   if (dwarf_read_debug)
6709     {
6710       fprintf_unfiltered (gdb_stdlog, "Building psymtabs of objfile %s ...\n",
6711                           objfile_name (objfile));
6712     }
6713
6714   dwarf2_per_objfile->reading_partial_symbols = 1;
6715
6716   dwarf2_read_section (objfile, &dwarf2_per_objfile->info);
6717
6718   /* Any cached compilation units will be linked by the per-objfile
6719      read_in_chain.  Make sure to free them when we're done.  */
6720   back_to = make_cleanup (free_cached_comp_units, NULL);
6721
6722   build_type_psymtabs (objfile);
6723
6724   create_all_comp_units (objfile);
6725
6726   /* Create a temporary address map on a temporary obstack.  We later
6727      copy this to the final obstack.  */
6728   auto_obstack temp_obstack;
6729   objfile->psymtabs_addrmap = addrmap_create_mutable (&temp_obstack);
6730   addrmap_cleanup = make_cleanup (psymtabs_addrmap_cleanup, objfile);
6731
6732   for (i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
6733     {
6734       struct dwarf2_per_cu_data *per_cu = dw2_get_cutu (i);
6735
6736       process_psymtab_comp_unit (per_cu, 0, language_minimal);
6737     }
6738
6739   /* This has to wait until we read the CUs, we need the list of DWOs.  */
6740   process_skeletonless_type_units (objfile);
6741
6742   /* Now that all TUs have been processed we can fill in the dependencies.  */
6743   if (dwarf2_per_objfile->type_unit_groups != NULL)
6744     {
6745       htab_traverse_noresize (dwarf2_per_objfile->type_unit_groups,
6746                               build_type_psymtab_dependencies, NULL);
6747     }
6748
6749   if (dwarf_read_debug)
6750     print_tu_stats ();
6751
6752   set_partial_user (objfile);
6753
6754   objfile->psymtabs_addrmap = addrmap_create_fixed (objfile->psymtabs_addrmap,
6755                                                     &objfile->objfile_obstack);
6756   discard_cleanups (addrmap_cleanup);
6757
6758   do_cleanups (back_to);
6759
6760   if (dwarf_read_debug)
6761     fprintf_unfiltered (gdb_stdlog, "Done building psymtabs of %s\n",
6762                         objfile_name (objfile));
6763 }
6764
6765 /* die_reader_func for load_partial_comp_unit.  */
6766
6767 static void
6768 load_partial_comp_unit_reader (const struct die_reader_specs *reader,
6769                                const gdb_byte *info_ptr,
6770                                struct die_info *comp_unit_die,
6771                                int has_children,
6772                                void *data)
6773 {
6774   struct dwarf2_cu *cu = reader->cu;
6775
6776   prepare_one_comp_unit (cu, comp_unit_die, language_minimal);
6777
6778   /* Check if comp unit has_children.
6779      If so, read the rest of the partial symbols from this comp unit.
6780      If not, there's no more debug_info for this comp unit.  */
6781   if (has_children)
6782     load_partial_dies (reader, info_ptr, 0);
6783 }
6784
6785 /* Load the partial DIEs for a secondary CU into memory.
6786    This is also used when rereading a primary CU with load_all_dies.  */
6787
6788 static void
6789 load_partial_comp_unit (struct dwarf2_per_cu_data *this_cu)
6790 {
6791   init_cutu_and_read_dies (this_cu, NULL, 1, 1,
6792                            load_partial_comp_unit_reader, NULL);
6793 }
6794
6795 static void
6796 read_comp_units_from_section (struct objfile *objfile,
6797                               struct dwarf2_section_info *section,
6798                               struct dwarf2_section_info *abbrev_section,
6799                               unsigned int is_dwz,
6800                               int *n_allocated,
6801                               int *n_comp_units,
6802                               struct dwarf2_per_cu_data ***all_comp_units)
6803 {
6804   const gdb_byte *info_ptr;
6805   bfd *abfd = get_section_bfd_owner (section);
6806
6807   if (dwarf_read_debug)
6808     fprintf_unfiltered (gdb_stdlog, "Reading %s for %s\n",
6809                         get_section_name (section),
6810                         get_section_file_name (section));
6811
6812   dwarf2_read_section (objfile, section);
6813
6814   info_ptr = section->buffer;
6815
6816   while (info_ptr < section->buffer + section->size)
6817     {
6818       struct dwarf2_per_cu_data *this_cu;
6819
6820       sect_offset sect_off = (sect_offset) (info_ptr - section->buffer);
6821
6822       comp_unit_head cu_header;
6823       read_and_check_comp_unit_head (&cu_header, section, abbrev_section,
6824                                      info_ptr, rcuh_kind::COMPILE);
6825
6826       /* Save the compilation unit for later lookup.  */
6827       if (cu_header.unit_type != DW_UT_type)
6828         {
6829           this_cu = XOBNEW (&objfile->objfile_obstack,
6830                             struct dwarf2_per_cu_data);
6831           memset (this_cu, 0, sizeof (*this_cu));
6832         }
6833       else
6834         {
6835           auto sig_type = XOBNEW (&objfile->objfile_obstack,
6836                                   struct signatured_type);
6837           memset (sig_type, 0, sizeof (*sig_type));
6838           sig_type->signature = cu_header.signature;
6839           sig_type->type_offset_in_tu = cu_header.type_cu_offset_in_tu;
6840           this_cu = &sig_type->per_cu;
6841         }
6842       this_cu->is_debug_types = (cu_header.unit_type == DW_UT_type);
6843       this_cu->sect_off = sect_off;
6844       this_cu->length = cu_header.length + cu_header.initial_length_size;
6845       this_cu->is_dwz = is_dwz;
6846       this_cu->objfile = objfile;
6847       this_cu->section = section;
6848
6849       if (*n_comp_units == *n_allocated)
6850         {
6851           *n_allocated *= 2;
6852           *all_comp_units = XRESIZEVEC (struct dwarf2_per_cu_data *,
6853                                         *all_comp_units, *n_allocated);
6854         }
6855       (*all_comp_units)[*n_comp_units] = this_cu;
6856       ++*n_comp_units;
6857
6858       info_ptr = info_ptr + this_cu->length;
6859     }
6860 }
6861
6862 /* Create a list of all compilation units in OBJFILE.
6863    This is only done for -readnow and building partial symtabs.  */
6864
6865 static void
6866 create_all_comp_units (struct objfile *objfile)
6867 {
6868   int n_allocated;
6869   int n_comp_units;
6870   struct dwarf2_per_cu_data **all_comp_units;
6871   struct dwz_file *dwz;
6872
6873   n_comp_units = 0;
6874   n_allocated = 10;
6875   all_comp_units = XNEWVEC (struct dwarf2_per_cu_data *, n_allocated);
6876
6877   read_comp_units_from_section (objfile, &dwarf2_per_objfile->info,
6878                                 &dwarf2_per_objfile->abbrev, 0,
6879                                 &n_allocated, &n_comp_units, &all_comp_units);
6880
6881   dwz = dwarf2_get_dwz_file ();
6882   if (dwz != NULL)
6883     read_comp_units_from_section (objfile, &dwz->info, &dwz->abbrev, 1,
6884                                   &n_allocated, &n_comp_units,
6885                                   &all_comp_units);
6886
6887   dwarf2_per_objfile->all_comp_units = XOBNEWVEC (&objfile->objfile_obstack,
6888                                                   struct dwarf2_per_cu_data *,
6889                                                   n_comp_units);
6890   memcpy (dwarf2_per_objfile->all_comp_units, all_comp_units,
6891           n_comp_units * sizeof (struct dwarf2_per_cu_data *));
6892   xfree (all_comp_units);
6893   dwarf2_per_objfile->n_comp_units = n_comp_units;
6894 }
6895
6896 /* Process all loaded DIEs for compilation unit CU, starting at
6897    FIRST_DIE.  The caller should pass SET_ADDRMAP == 1 if the compilation
6898    unit DIE did not have PC info (DW_AT_low_pc and DW_AT_high_pc, or
6899    DW_AT_ranges).  See the comments of add_partial_subprogram on how
6900    SET_ADDRMAP is used and how *LOWPC and *HIGHPC are updated.  */
6901
6902 static void
6903 scan_partial_symbols (struct partial_die_info *first_die, CORE_ADDR *lowpc,
6904                       CORE_ADDR *highpc, int set_addrmap,
6905                       struct dwarf2_cu *cu)
6906 {
6907   struct partial_die_info *pdi;
6908
6909   /* Now, march along the PDI's, descending into ones which have
6910      interesting children but skipping the children of the other ones,
6911      until we reach the end of the compilation unit.  */
6912
6913   pdi = first_die;
6914
6915   while (pdi != NULL)
6916     {
6917       fixup_partial_die (pdi, cu);
6918
6919       /* Anonymous namespaces or modules have no name but have interesting
6920          children, so we need to look at them.  Ditto for anonymous
6921          enums.  */
6922
6923       if (pdi->name != NULL || pdi->tag == DW_TAG_namespace
6924           || pdi->tag == DW_TAG_module || pdi->tag == DW_TAG_enumeration_type
6925           || pdi->tag == DW_TAG_imported_unit)
6926         {
6927           switch (pdi->tag)
6928             {
6929             case DW_TAG_subprogram:
6930               add_partial_subprogram (pdi, lowpc, highpc, set_addrmap, cu);
6931               break;
6932             case DW_TAG_constant:
6933             case DW_TAG_variable:
6934             case DW_TAG_typedef:
6935             case DW_TAG_union_type:
6936               if (!pdi->is_declaration)
6937                 {
6938                   add_partial_symbol (pdi, cu);
6939                 }
6940               break;
6941             case DW_TAG_class_type:
6942             case DW_TAG_interface_type:
6943             case DW_TAG_structure_type:
6944               if (!pdi->is_declaration)
6945                 {
6946                   add_partial_symbol (pdi, cu);
6947                 }
6948               if (cu->language == language_rust && pdi->has_children)
6949                 scan_partial_symbols (pdi->die_child, lowpc, highpc,
6950                                       set_addrmap, cu);
6951               break;
6952             case DW_TAG_enumeration_type:
6953               if (!pdi->is_declaration)
6954                 add_partial_enumeration (pdi, cu);
6955               break;
6956             case DW_TAG_base_type:
6957             case DW_TAG_subrange_type:
6958               /* File scope base type definitions are added to the partial
6959                  symbol table.  */
6960               add_partial_symbol (pdi, cu);
6961               break;
6962             case DW_TAG_namespace:
6963               add_partial_namespace (pdi, lowpc, highpc, set_addrmap, cu);
6964               break;
6965             case DW_TAG_module:
6966               add_partial_module (pdi, lowpc, highpc, set_addrmap, cu);
6967               break;
6968             case DW_TAG_imported_unit:
6969               {
6970                 struct dwarf2_per_cu_data *per_cu;
6971
6972                 /* For now we don't handle imported units in type units.  */
6973                 if (cu->per_cu->is_debug_types)
6974                   {
6975                     error (_("Dwarf Error: DW_TAG_imported_unit is not"
6976                              " supported in type units [in module %s]"),
6977                            objfile_name (cu->objfile));
6978                   }
6979
6980                 per_cu = dwarf2_find_containing_comp_unit (pdi->d.sect_off,
6981                                                            pdi->is_dwz,
6982                                                            cu->objfile);
6983
6984                 /* Go read the partial unit, if needed.  */
6985                 if (per_cu->v.psymtab == NULL)
6986                   process_psymtab_comp_unit (per_cu, 1, cu->language);
6987
6988                 VEC_safe_push (dwarf2_per_cu_ptr,
6989                                cu->per_cu->imported_symtabs, per_cu);
6990               }
6991               break;
6992             case DW_TAG_imported_declaration:
6993               add_partial_symbol (pdi, cu);
6994               break;
6995             default:
6996               break;
6997             }
6998         }
6999
7000       /* If the die has a sibling, skip to the sibling.  */
7001
7002       pdi = pdi->die_sibling;
7003     }
7004 }
7005
7006 /* Functions used to compute the fully scoped name of a partial DIE.
7007
7008    Normally, this is simple.  For C++, the parent DIE's fully scoped
7009    name is concatenated with "::" and the partial DIE's name.
7010    Enumerators are an exception; they use the scope of their parent
7011    enumeration type, i.e. the name of the enumeration type is not
7012    prepended to the enumerator.
7013
7014    There are two complexities.  One is DW_AT_specification; in this
7015    case "parent" means the parent of the target of the specification,
7016    instead of the direct parent of the DIE.  The other is compilers
7017    which do not emit DW_TAG_namespace; in this case we try to guess
7018    the fully qualified name of structure types from their members'
7019    linkage names.  This must be done using the DIE's children rather
7020    than the children of any DW_AT_specification target.  We only need
7021    to do this for structures at the top level, i.e. if the target of
7022    any DW_AT_specification (if any; otherwise the DIE itself) does not
7023    have a parent.  */
7024
7025 /* Compute the scope prefix associated with PDI's parent, in
7026    compilation unit CU.  The result will be allocated on CU's
7027    comp_unit_obstack, or a copy of the already allocated PDI->NAME
7028    field.  NULL is returned if no prefix is necessary.  */
7029 static const char *
7030 partial_die_parent_scope (struct partial_die_info *pdi,
7031                           struct dwarf2_cu *cu)
7032 {
7033   const char *grandparent_scope;
7034   struct partial_die_info *parent, *real_pdi;
7035
7036   /* We need to look at our parent DIE; if we have a DW_AT_specification,
7037      then this means the parent of the specification DIE.  */
7038
7039   real_pdi = pdi;
7040   while (real_pdi->has_specification)
7041     real_pdi = find_partial_die (real_pdi->spec_offset,
7042                                  real_pdi->spec_is_dwz, cu);
7043
7044   parent = real_pdi->die_parent;
7045   if (parent == NULL)
7046     return NULL;
7047
7048   if (parent->scope_set)
7049     return parent->scope;
7050
7051   fixup_partial_die (parent, cu);
7052
7053   grandparent_scope = partial_die_parent_scope (parent, cu);
7054
7055   /* GCC 4.0 and 4.1 had a bug (PR c++/28460) where they generated bogus
7056      DW_TAG_namespace DIEs with a name of "::" for the global namespace.
7057      Work around this problem here.  */
7058   if (cu->language == language_cplus
7059       && parent->tag == DW_TAG_namespace
7060       && strcmp (parent->name, "::") == 0
7061       && grandparent_scope == NULL)
7062     {
7063       parent->scope = NULL;
7064       parent->scope_set = 1;
7065       return NULL;
7066     }
7067
7068   if (pdi->tag == DW_TAG_enumerator)
7069     /* Enumerators should not get the name of the enumeration as a prefix.  */
7070     parent->scope = grandparent_scope;
7071   else if (parent->tag == DW_TAG_namespace
7072       || parent->tag == DW_TAG_module
7073       || parent->tag == DW_TAG_structure_type
7074       || parent->tag == DW_TAG_class_type
7075       || parent->tag == DW_TAG_interface_type
7076       || parent->tag == DW_TAG_union_type
7077       || parent->tag == DW_TAG_enumeration_type)
7078     {
7079       if (grandparent_scope == NULL)
7080         parent->scope = parent->name;
7081       else
7082         parent->scope = typename_concat (&cu->comp_unit_obstack,
7083                                          grandparent_scope,
7084                                          parent->name, 0, cu);
7085     }
7086   else
7087     {
7088       /* FIXME drow/2004-04-01: What should we be doing with
7089          function-local names?  For partial symbols, we should probably be
7090          ignoring them.  */
7091       complaint (&symfile_complaints,
7092                  _("unhandled containing DIE tag %d for DIE at %d"),
7093                  parent->tag, to_underlying (pdi->sect_off));
7094       parent->scope = grandparent_scope;
7095     }
7096
7097   parent->scope_set = 1;
7098   return parent->scope;
7099 }
7100
7101 /* Return the fully scoped name associated with PDI, from compilation unit
7102    CU.  The result will be allocated with malloc.  */
7103
7104 static char *
7105 partial_die_full_name (struct partial_die_info *pdi,
7106                        struct dwarf2_cu *cu)
7107 {
7108   const char *parent_scope;
7109
7110   /* If this is a template instantiation, we can not work out the
7111      template arguments from partial DIEs.  So, unfortunately, we have
7112      to go through the full DIEs.  At least any work we do building
7113      types here will be reused if full symbols are loaded later.  */
7114   if (pdi->has_template_arguments)
7115     {
7116       fixup_partial_die (pdi, cu);
7117
7118       if (pdi->name != NULL && strchr (pdi->name, '<') == NULL)
7119         {
7120           struct die_info *die;
7121           struct attribute attr;
7122           struct dwarf2_cu *ref_cu = cu;
7123
7124           /* DW_FORM_ref_addr is using section offset.  */
7125           attr.name = (enum dwarf_attribute) 0;
7126           attr.form = DW_FORM_ref_addr;
7127           attr.u.unsnd = to_underlying (pdi->sect_off);
7128           die = follow_die_ref (NULL, &attr, &ref_cu);
7129
7130           return xstrdup (dwarf2_full_name (NULL, die, ref_cu));
7131         }
7132     }
7133
7134   parent_scope = partial_die_parent_scope (pdi, cu);
7135   if (parent_scope == NULL)
7136     return NULL;
7137   else
7138     return typename_concat (NULL, parent_scope, pdi->name, 0, cu);
7139 }
7140
7141 static void
7142 add_partial_symbol (struct partial_die_info *pdi, struct dwarf2_cu *cu)
7143 {
7144   struct objfile *objfile = cu->objfile;
7145   struct gdbarch *gdbarch = get_objfile_arch (objfile);
7146   CORE_ADDR addr = 0;
7147   const char *actual_name = NULL;
7148   CORE_ADDR baseaddr;
7149   char *built_actual_name;
7150
7151   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
7152
7153   built_actual_name = partial_die_full_name (pdi, cu);
7154   if (built_actual_name != NULL)
7155     actual_name = built_actual_name;
7156
7157   if (actual_name == NULL)
7158     actual_name = pdi->name;
7159
7160   switch (pdi->tag)
7161     {
7162     case DW_TAG_subprogram:
7163       addr = gdbarch_adjust_dwarf2_addr (gdbarch, pdi->lowpc + baseaddr);
7164       if (pdi->is_external || cu->language == language_ada)
7165         {
7166           /* brobecker/2007-12-26: Normally, only "external" DIEs are part
7167              of the global scope.  But in Ada, we want to be able to access
7168              nested procedures globally.  So all Ada subprograms are stored
7169              in the global scope.  */
7170           add_psymbol_to_list (actual_name, strlen (actual_name),
7171                                built_actual_name != NULL,
7172                                VAR_DOMAIN, LOC_BLOCK,
7173                                &objfile->global_psymbols,
7174                                addr, cu->language, objfile);
7175         }
7176       else
7177         {
7178           add_psymbol_to_list (actual_name, strlen (actual_name),
7179                                built_actual_name != NULL,
7180                                VAR_DOMAIN, LOC_BLOCK,
7181                                &objfile->static_psymbols,
7182                                addr, cu->language, objfile);
7183         }
7184
7185       if (pdi->main_subprogram && actual_name != NULL)
7186         set_objfile_main_name (objfile, actual_name, cu->language);
7187       break;
7188     case DW_TAG_constant:
7189       {
7190         struct psymbol_allocation_list *list;
7191
7192         if (pdi->is_external)
7193           list = &objfile->global_psymbols;
7194         else
7195           list = &objfile->static_psymbols;
7196         add_psymbol_to_list (actual_name, strlen (actual_name),
7197                              built_actual_name != NULL, VAR_DOMAIN, LOC_STATIC,
7198                              list, 0, cu->language, objfile);
7199       }
7200       break;
7201     case DW_TAG_variable:
7202       if (pdi->d.locdesc)
7203         addr = decode_locdesc (pdi->d.locdesc, cu);
7204
7205       if (pdi->d.locdesc
7206           && addr == 0
7207           && !dwarf2_per_objfile->has_section_at_zero)
7208         {
7209           /* A global or static variable may also have been stripped
7210              out by the linker if unused, in which case its address
7211              will be nullified; do not add such variables into partial
7212              symbol table then.  */
7213         }
7214       else if (pdi->is_external)
7215         {
7216           /* Global Variable.
7217              Don't enter into the minimal symbol tables as there is
7218              a minimal symbol table entry from the ELF symbols already.
7219              Enter into partial symbol table if it has a location
7220              descriptor or a type.
7221              If the location descriptor is missing, new_symbol will create
7222              a LOC_UNRESOLVED symbol, the address of the variable will then
7223              be determined from the minimal symbol table whenever the variable
7224              is referenced.
7225              The address for the partial symbol table entry is not
7226              used by GDB, but it comes in handy for debugging partial symbol
7227              table building.  */
7228
7229           if (pdi->d.locdesc || pdi->has_type)
7230             add_psymbol_to_list (actual_name, strlen (actual_name),
7231                                  built_actual_name != NULL,
7232                                  VAR_DOMAIN, LOC_STATIC,
7233                                  &objfile->global_psymbols,
7234                                  addr + baseaddr,
7235                                  cu->language, objfile);
7236         }
7237       else
7238         {
7239           int has_loc = pdi->d.locdesc != NULL;
7240
7241           /* Static Variable.  Skip symbols whose value we cannot know (those
7242              without location descriptors or constant values).  */
7243           if (!has_loc && !pdi->has_const_value)
7244             {
7245               xfree (built_actual_name);
7246               return;
7247             }
7248
7249           add_psymbol_to_list (actual_name, strlen (actual_name),
7250                                built_actual_name != NULL,
7251                                VAR_DOMAIN, LOC_STATIC,
7252                                &objfile->static_psymbols,
7253                                has_loc ? addr + baseaddr : (CORE_ADDR) 0,
7254                                cu->language, objfile);
7255         }
7256       break;
7257     case DW_TAG_typedef:
7258     case DW_TAG_base_type:
7259     case DW_TAG_subrange_type:
7260       add_psymbol_to_list (actual_name, strlen (actual_name),
7261                            built_actual_name != NULL,
7262                            VAR_DOMAIN, LOC_TYPEDEF,
7263                            &objfile->static_psymbols,
7264                            0, cu->language, objfile);
7265       break;
7266     case DW_TAG_imported_declaration:
7267     case DW_TAG_namespace:
7268       add_psymbol_to_list (actual_name, strlen (actual_name),
7269                            built_actual_name != NULL,
7270                            VAR_DOMAIN, LOC_TYPEDEF,
7271                            &objfile->global_psymbols,
7272                            0, cu->language, objfile);
7273       break;
7274     case DW_TAG_module:
7275       add_psymbol_to_list (actual_name, strlen (actual_name),
7276                            built_actual_name != NULL,
7277                            MODULE_DOMAIN, LOC_TYPEDEF,
7278                            &objfile->global_psymbols,
7279                            0, cu->language, objfile);
7280       break;
7281     case DW_TAG_class_type:
7282     case DW_TAG_interface_type:
7283     case DW_TAG_structure_type:
7284     case DW_TAG_union_type:
7285     case DW_TAG_enumeration_type:
7286       /* Skip external references.  The DWARF standard says in the section
7287          about "Structure, Union, and Class Type Entries": "An incomplete
7288          structure, union or class type is represented by a structure,
7289          union or class entry that does not have a byte size attribute
7290          and that has a DW_AT_declaration attribute."  */
7291       if (!pdi->has_byte_size && pdi->is_declaration)
7292         {
7293           xfree (built_actual_name);
7294           return;
7295         }
7296
7297       /* NOTE: carlton/2003-10-07: See comment in new_symbol about
7298          static vs. global.  */
7299       add_psymbol_to_list (actual_name, strlen (actual_name),
7300                            built_actual_name != NULL,
7301                            STRUCT_DOMAIN, LOC_TYPEDEF,
7302                            cu->language == language_cplus
7303                            ? &objfile->global_psymbols
7304                            : &objfile->static_psymbols,
7305                            0, cu->language, objfile);
7306
7307       break;
7308     case DW_TAG_enumerator:
7309       add_psymbol_to_list (actual_name, strlen (actual_name),
7310                            built_actual_name != NULL,
7311                            VAR_DOMAIN, LOC_CONST,
7312                            cu->language == language_cplus
7313                            ? &objfile->global_psymbols
7314                            : &objfile->static_psymbols,
7315                            0, cu->language, objfile);
7316       break;
7317     default:
7318       break;
7319     }
7320
7321   xfree (built_actual_name);
7322 }
7323
7324 /* Read a partial die corresponding to a namespace; also, add a symbol
7325    corresponding to that namespace to the symbol table.  NAMESPACE is
7326    the name of the enclosing namespace.  */
7327
7328 static void
7329 add_partial_namespace (struct partial_die_info *pdi,
7330                        CORE_ADDR *lowpc, CORE_ADDR *highpc,
7331                        int set_addrmap, struct dwarf2_cu *cu)
7332 {
7333   /* Add a symbol for the namespace.  */
7334
7335   add_partial_symbol (pdi, cu);
7336
7337   /* Now scan partial symbols in that namespace.  */
7338
7339   if (pdi->has_children)
7340     scan_partial_symbols (pdi->die_child, lowpc, highpc, set_addrmap, cu);
7341 }
7342
7343 /* Read a partial die corresponding to a Fortran module.  */
7344
7345 static void
7346 add_partial_module (struct partial_die_info *pdi, CORE_ADDR *lowpc,
7347                     CORE_ADDR *highpc, int set_addrmap, struct dwarf2_cu *cu)
7348 {
7349   /* Add a symbol for the namespace.  */
7350
7351   add_partial_symbol (pdi, cu);
7352
7353   /* Now scan partial symbols in that module.  */
7354
7355   if (pdi->has_children)
7356     scan_partial_symbols (pdi->die_child, lowpc, highpc, set_addrmap, cu);
7357 }
7358
7359 /* Read a partial die corresponding to a subprogram and create a partial
7360    symbol for that subprogram.  When the CU language allows it, this
7361    routine also defines a partial symbol for each nested subprogram
7362    that this subprogram contains.  If SET_ADDRMAP is true, record the
7363    covered ranges in the addrmap.  Set *LOWPC and *HIGHPC to the lowest
7364    and highest PC values found in PDI.
7365
7366    PDI may also be a lexical block, in which case we simply search
7367    recursively for subprograms defined inside that lexical block.
7368    Again, this is only performed when the CU language allows this
7369    type of definitions.  */
7370
7371 static void
7372 add_partial_subprogram (struct partial_die_info *pdi,
7373                         CORE_ADDR *lowpc, CORE_ADDR *highpc,
7374                         int set_addrmap, struct dwarf2_cu *cu)
7375 {
7376   if (pdi->tag == DW_TAG_subprogram)
7377     {
7378       if (pdi->has_pc_info)
7379         {
7380           if (pdi->lowpc < *lowpc)
7381             *lowpc = pdi->lowpc;
7382           if (pdi->highpc > *highpc)
7383             *highpc = pdi->highpc;
7384           if (set_addrmap)
7385             {
7386               struct objfile *objfile = cu->objfile;
7387               struct gdbarch *gdbarch = get_objfile_arch (objfile);
7388               CORE_ADDR baseaddr;
7389               CORE_ADDR highpc;
7390               CORE_ADDR lowpc;
7391
7392               baseaddr = ANOFFSET (objfile->section_offsets,
7393                                    SECT_OFF_TEXT (objfile));
7394               lowpc = gdbarch_adjust_dwarf2_addr (gdbarch,
7395                                                   pdi->lowpc + baseaddr);
7396               highpc = gdbarch_adjust_dwarf2_addr (gdbarch,
7397                                                    pdi->highpc + baseaddr);
7398               addrmap_set_empty (objfile->psymtabs_addrmap, lowpc, highpc - 1,
7399                                  cu->per_cu->v.psymtab);
7400             }
7401         }
7402
7403       if (pdi->has_pc_info || (!pdi->is_external && pdi->may_be_inlined))
7404         {
7405           if (!pdi->is_declaration)
7406             /* Ignore subprogram DIEs that do not have a name, they are
7407                illegal.  Do not emit a complaint at this point, we will
7408                do so when we convert this psymtab into a symtab.  */
7409             if (pdi->name)
7410               add_partial_symbol (pdi, cu);
7411         }
7412     }
7413
7414   if (! pdi->has_children)
7415     return;
7416
7417   if (cu->language == language_ada)
7418     {
7419       pdi = pdi->die_child;
7420       while (pdi != NULL)
7421         {
7422           fixup_partial_die (pdi, cu);
7423           if (pdi->tag == DW_TAG_subprogram
7424               || pdi->tag == DW_TAG_lexical_block)
7425             add_partial_subprogram (pdi, lowpc, highpc, set_addrmap, cu);
7426           pdi = pdi->die_sibling;
7427         }
7428     }
7429 }
7430
7431 /* Read a partial die corresponding to an enumeration type.  */
7432
7433 static void
7434 add_partial_enumeration (struct partial_die_info *enum_pdi,
7435                          struct dwarf2_cu *cu)
7436 {
7437   struct partial_die_info *pdi;
7438
7439   if (enum_pdi->name != NULL)
7440     add_partial_symbol (enum_pdi, cu);
7441
7442   pdi = enum_pdi->die_child;
7443   while (pdi)
7444     {
7445       if (pdi->tag != DW_TAG_enumerator || pdi->name == NULL)
7446         complaint (&symfile_complaints, _("malformed enumerator DIE ignored"));
7447       else
7448         add_partial_symbol (pdi, cu);
7449       pdi = pdi->die_sibling;
7450     }
7451 }
7452
7453 /* Return the initial uleb128 in the die at INFO_PTR.  */
7454
7455 static unsigned int
7456 peek_abbrev_code (bfd *abfd, const gdb_byte *info_ptr)
7457 {
7458   unsigned int bytes_read;
7459
7460   return read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
7461 }
7462
7463 /* Read the initial uleb128 in the die at INFO_PTR in compilation unit CU.
7464    Return the corresponding abbrev, or NULL if the number is zero (indicating
7465    an empty DIE).  In either case *BYTES_READ will be set to the length of
7466    the initial number.  */
7467
7468 static struct abbrev_info *
7469 peek_die_abbrev (const gdb_byte *info_ptr, unsigned int *bytes_read,
7470                  struct dwarf2_cu *cu)
7471 {
7472   bfd *abfd = cu->objfile->obfd;
7473   unsigned int abbrev_number;
7474   struct abbrev_info *abbrev;
7475
7476   abbrev_number = read_unsigned_leb128 (abfd, info_ptr, bytes_read);
7477
7478   if (abbrev_number == 0)
7479     return NULL;
7480
7481   abbrev = abbrev_table_lookup_abbrev (cu->abbrev_table, abbrev_number);
7482   if (!abbrev)
7483     {
7484       error (_("Dwarf Error: Could not find abbrev number %d in %s"
7485                " at offset 0x%x [in module %s]"),
7486              abbrev_number, cu->per_cu->is_debug_types ? "TU" : "CU",
7487              to_underlying (cu->header.sect_off), bfd_get_filename (abfd));
7488     }
7489
7490   return abbrev;
7491 }
7492
7493 /* Scan the debug information for CU starting at INFO_PTR in buffer BUFFER.
7494    Returns a pointer to the end of a series of DIEs, terminated by an empty
7495    DIE.  Any children of the skipped DIEs will also be skipped.  */
7496
7497 static const gdb_byte *
7498 skip_children (const struct die_reader_specs *reader, const gdb_byte *info_ptr)
7499 {
7500   struct dwarf2_cu *cu = reader->cu;
7501   struct abbrev_info *abbrev;
7502   unsigned int bytes_read;
7503
7504   while (1)
7505     {
7506       abbrev = peek_die_abbrev (info_ptr, &bytes_read, cu);
7507       if (abbrev == NULL)
7508         return info_ptr + bytes_read;
7509       else
7510         info_ptr = skip_one_die (reader, info_ptr + bytes_read, abbrev);
7511     }
7512 }
7513
7514 /* Scan the debug information for CU starting at INFO_PTR in buffer BUFFER.
7515    INFO_PTR should point just after the initial uleb128 of a DIE, and the
7516    abbrev corresponding to that skipped uleb128 should be passed in
7517    ABBREV.  Returns a pointer to this DIE's sibling, skipping any
7518    children.  */
7519
7520 static const gdb_byte *
7521 skip_one_die (const struct die_reader_specs *reader, const gdb_byte *info_ptr,
7522               struct abbrev_info *abbrev)
7523 {
7524   unsigned int bytes_read;
7525   struct attribute attr;
7526   bfd *abfd = reader->abfd;
7527   struct dwarf2_cu *cu = reader->cu;
7528   const gdb_byte *buffer = reader->buffer;
7529   const gdb_byte *buffer_end = reader->buffer_end;
7530   unsigned int form, i;
7531
7532   for (i = 0; i < abbrev->num_attrs; i++)
7533     {
7534       /* The only abbrev we care about is DW_AT_sibling.  */
7535       if (abbrev->attrs[i].name == DW_AT_sibling)
7536         {
7537           read_attribute (reader, &attr, &abbrev->attrs[i], info_ptr);
7538           if (attr.form == DW_FORM_ref_addr)
7539             complaint (&symfile_complaints,
7540                        _("ignoring absolute DW_AT_sibling"));
7541           else
7542             {
7543               sect_offset off = dwarf2_get_ref_die_offset (&attr);
7544               const gdb_byte *sibling_ptr = buffer + to_underlying (off);
7545
7546               if (sibling_ptr < info_ptr)
7547                 complaint (&symfile_complaints,
7548                            _("DW_AT_sibling points backwards"));
7549               else if (sibling_ptr > reader->buffer_end)
7550                 dwarf2_section_buffer_overflow_complaint (reader->die_section);
7551               else
7552                 return sibling_ptr;
7553             }
7554         }
7555
7556       /* If it isn't DW_AT_sibling, skip this attribute.  */
7557       form = abbrev->attrs[i].form;
7558     skip_attribute:
7559       switch (form)
7560         {
7561         case DW_FORM_ref_addr:
7562           /* In DWARF 2, DW_FORM_ref_addr is address sized; in DWARF 3
7563              and later it is offset sized.  */
7564           if (cu->header.version == 2)
7565             info_ptr += cu->header.addr_size;
7566           else
7567             info_ptr += cu->header.offset_size;
7568           break;
7569         case DW_FORM_GNU_ref_alt:
7570           info_ptr += cu->header.offset_size;
7571           break;
7572         case DW_FORM_addr:
7573           info_ptr += cu->header.addr_size;
7574           break;
7575         case DW_FORM_data1:
7576         case DW_FORM_ref1:
7577         case DW_FORM_flag:
7578           info_ptr += 1;
7579           break;
7580         case DW_FORM_flag_present:
7581         case DW_FORM_implicit_const:
7582           break;
7583         case DW_FORM_data2:
7584         case DW_FORM_ref2:
7585           info_ptr += 2;
7586           break;
7587         case DW_FORM_data4:
7588         case DW_FORM_ref4:
7589           info_ptr += 4;
7590           break;
7591         case DW_FORM_data8:
7592         case DW_FORM_ref8:
7593         case DW_FORM_ref_sig8:
7594           info_ptr += 8;
7595           break;
7596         case DW_FORM_data16:
7597           info_ptr += 16;
7598           break;
7599         case DW_FORM_string:
7600           read_direct_string (abfd, info_ptr, &bytes_read);
7601           info_ptr += bytes_read;
7602           break;
7603         case DW_FORM_sec_offset:
7604         case DW_FORM_strp:
7605         case DW_FORM_GNU_strp_alt:
7606           info_ptr += cu->header.offset_size;
7607           break;
7608         case DW_FORM_exprloc:
7609         case DW_FORM_block:
7610           info_ptr += read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
7611           info_ptr += bytes_read;
7612           break;
7613         case DW_FORM_block1:
7614           info_ptr += 1 + read_1_byte (abfd, info_ptr);
7615           break;
7616         case DW_FORM_block2:
7617           info_ptr += 2 + read_2_bytes (abfd, info_ptr);
7618           break;
7619         case DW_FORM_block4:
7620           info_ptr += 4 + read_4_bytes (abfd, info_ptr);
7621           break;
7622         case DW_FORM_sdata:
7623         case DW_FORM_udata:
7624         case DW_FORM_ref_udata:
7625         case DW_FORM_GNU_addr_index:
7626         case DW_FORM_GNU_str_index:
7627           info_ptr = safe_skip_leb128 (info_ptr, buffer_end);
7628           break;
7629         case DW_FORM_indirect:
7630           form = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
7631           info_ptr += bytes_read;
7632           /* We need to continue parsing from here, so just go back to
7633              the top.  */
7634           goto skip_attribute;
7635
7636         default:
7637           error (_("Dwarf Error: Cannot handle %s "
7638                    "in DWARF reader [in module %s]"),
7639                  dwarf_form_name (form),
7640                  bfd_get_filename (abfd));
7641         }
7642     }
7643
7644   if (abbrev->has_children)
7645     return skip_children (reader, info_ptr);
7646   else
7647     return info_ptr;
7648 }
7649
7650 /* Locate ORIG_PDI's sibling.
7651    INFO_PTR should point to the start of the next DIE after ORIG_PDI.  */
7652
7653 static const gdb_byte *
7654 locate_pdi_sibling (const struct die_reader_specs *reader,
7655                     struct partial_die_info *orig_pdi,
7656                     const gdb_byte *info_ptr)
7657 {
7658   /* Do we know the sibling already?  */
7659
7660   if (orig_pdi->sibling)
7661     return orig_pdi->sibling;
7662
7663   /* Are there any children to deal with?  */
7664
7665   if (!orig_pdi->has_children)
7666     return info_ptr;
7667
7668   /* Skip the children the long way.  */
7669
7670   return skip_children (reader, info_ptr);
7671 }
7672
7673 /* Expand this partial symbol table into a full symbol table.  SELF is
7674    not NULL.  */
7675
7676 static void
7677 dwarf2_read_symtab (struct partial_symtab *self,
7678                     struct objfile *objfile)
7679 {
7680   if (self->readin)
7681     {
7682       warning (_("bug: psymtab for %s is already read in."),
7683                self->filename);
7684     }
7685   else
7686     {
7687       if (info_verbose)
7688         {
7689           printf_filtered (_("Reading in symbols for %s..."),
7690                            self->filename);
7691           gdb_flush (gdb_stdout);
7692         }
7693
7694       /* Restore our global data.  */
7695       dwarf2_per_objfile
7696         = (struct dwarf2_per_objfile *) objfile_data (objfile,
7697                                                       dwarf2_objfile_data_key);
7698
7699       /* If this psymtab is constructed from a debug-only objfile, the
7700          has_section_at_zero flag will not necessarily be correct.  We
7701          can get the correct value for this flag by looking at the data
7702          associated with the (presumably stripped) associated objfile.  */
7703       if (objfile->separate_debug_objfile_backlink)
7704         {
7705           struct dwarf2_per_objfile *dpo_backlink
7706             = ((struct dwarf2_per_objfile *)
7707                objfile_data (objfile->separate_debug_objfile_backlink,
7708                              dwarf2_objfile_data_key));
7709
7710           dwarf2_per_objfile->has_section_at_zero
7711             = dpo_backlink->has_section_at_zero;
7712         }
7713
7714       dwarf2_per_objfile->reading_partial_symbols = 0;
7715
7716       psymtab_to_symtab_1 (self);
7717
7718       /* Finish up the debug error message.  */
7719       if (info_verbose)
7720         printf_filtered (_("done.\n"));
7721     }
7722
7723   process_cu_includes ();
7724 }
7725 \f
7726 /* Reading in full CUs.  */
7727
7728 /* Add PER_CU to the queue.  */
7729
7730 static void
7731 queue_comp_unit (struct dwarf2_per_cu_data *per_cu,
7732                  enum language pretend_language)
7733 {
7734   struct dwarf2_queue_item *item;
7735
7736   per_cu->queued = 1;
7737   item = XNEW (struct dwarf2_queue_item);
7738   item->per_cu = per_cu;
7739   item->pretend_language = pretend_language;
7740   item->next = NULL;
7741
7742   if (dwarf2_queue == NULL)
7743     dwarf2_queue = item;
7744   else
7745     dwarf2_queue_tail->next = item;
7746
7747   dwarf2_queue_tail = item;
7748 }
7749
7750 /* If PER_CU is not yet queued, add it to the queue.
7751    If DEPENDENT_CU is non-NULL, it has a reference to PER_CU so add a
7752    dependency.
7753    The result is non-zero if PER_CU was queued, otherwise the result is zero
7754    meaning either PER_CU is already queued or it is already loaded.
7755
7756    N.B. There is an invariant here that if a CU is queued then it is loaded.
7757    The caller is required to load PER_CU if we return non-zero.  */
7758
7759 static int
7760 maybe_queue_comp_unit (struct dwarf2_cu *dependent_cu,
7761                        struct dwarf2_per_cu_data *per_cu,
7762                        enum language pretend_language)
7763 {
7764   /* We may arrive here during partial symbol reading, if we need full
7765      DIEs to process an unusual case (e.g. template arguments).  Do
7766      not queue PER_CU, just tell our caller to load its DIEs.  */
7767   if (dwarf2_per_objfile->reading_partial_symbols)
7768     {
7769       if (per_cu->cu == NULL || per_cu->cu->dies == NULL)
7770         return 1;
7771       return 0;
7772     }
7773
7774   /* Mark the dependence relation so that we don't flush PER_CU
7775      too early.  */
7776   if (dependent_cu != NULL)
7777     dwarf2_add_dependence (dependent_cu, per_cu);
7778
7779   /* If it's already on the queue, we have nothing to do.  */
7780   if (per_cu->queued)
7781     return 0;
7782
7783   /* If the compilation unit is already loaded, just mark it as
7784      used.  */
7785   if (per_cu->cu != NULL)
7786     {
7787       per_cu->cu->last_used = 0;
7788       return 0;
7789     }
7790
7791   /* Add it to the queue.  */
7792   queue_comp_unit (per_cu, pretend_language);
7793
7794   return 1;
7795 }
7796
7797 /* Process the queue.  */
7798
7799 static void
7800 process_queue (void)
7801 {
7802   struct dwarf2_queue_item *item, *next_item;
7803
7804   if (dwarf_read_debug)
7805     {
7806       fprintf_unfiltered (gdb_stdlog,
7807                           "Expanding one or more symtabs of objfile %s ...\n",
7808                           objfile_name (dwarf2_per_objfile->objfile));
7809     }
7810
7811   /* The queue starts out with one item, but following a DIE reference
7812      may load a new CU, adding it to the end of the queue.  */
7813   for (item = dwarf2_queue; item != NULL; dwarf2_queue = item = next_item)
7814     {
7815       if ((dwarf2_per_objfile->using_index
7816            ? !item->per_cu->v.quick->compunit_symtab
7817            : (item->per_cu->v.psymtab && !item->per_cu->v.psymtab->readin))
7818           /* Skip dummy CUs.  */
7819           && item->per_cu->cu != NULL)
7820         {
7821           struct dwarf2_per_cu_data *per_cu = item->per_cu;
7822           unsigned int debug_print_threshold;
7823           char buf[100];
7824
7825           if (per_cu->is_debug_types)
7826             {
7827               struct signatured_type *sig_type =
7828                 (struct signatured_type *) per_cu;
7829
7830               sprintf (buf, "TU %s at offset 0x%x",
7831                        hex_string (sig_type->signature),
7832                        to_underlying (per_cu->sect_off));
7833               /* There can be 100s of TUs.
7834                  Only print them in verbose mode.  */
7835               debug_print_threshold = 2;
7836             }
7837           else
7838             {
7839               sprintf (buf, "CU at offset 0x%x",
7840                        to_underlying (per_cu->sect_off));
7841               debug_print_threshold = 1;
7842             }
7843
7844           if (dwarf_read_debug >= debug_print_threshold)
7845             fprintf_unfiltered (gdb_stdlog, "Expanding symtab of %s\n", buf);
7846
7847           if (per_cu->is_debug_types)
7848             process_full_type_unit (per_cu, item->pretend_language);
7849           else
7850             process_full_comp_unit (per_cu, item->pretend_language);
7851
7852           if (dwarf_read_debug >= debug_print_threshold)
7853             fprintf_unfiltered (gdb_stdlog, "Done expanding %s\n", buf);
7854         }
7855
7856       item->per_cu->queued = 0;
7857       next_item = item->next;
7858       xfree (item);
7859     }
7860
7861   dwarf2_queue_tail = NULL;
7862
7863   if (dwarf_read_debug)
7864     {
7865       fprintf_unfiltered (gdb_stdlog, "Done expanding symtabs of %s.\n",
7866                           objfile_name (dwarf2_per_objfile->objfile));
7867     }
7868 }
7869
7870 /* Free all allocated queue entries.  This function only releases anything if
7871    an error was thrown; if the queue was processed then it would have been
7872    freed as we went along.  */
7873
7874 static void
7875 dwarf2_release_queue (void *dummy)
7876 {
7877   struct dwarf2_queue_item *item, *last;
7878
7879   item = dwarf2_queue;
7880   while (item)
7881     {
7882       /* Anything still marked queued is likely to be in an
7883          inconsistent state, so discard it.  */
7884       if (item->per_cu->queued)
7885         {
7886           if (item->per_cu->cu != NULL)
7887             free_one_cached_comp_unit (item->per_cu);
7888           item->per_cu->queued = 0;
7889         }
7890
7891       last = item;
7892       item = item->next;
7893       xfree (last);
7894     }
7895
7896   dwarf2_queue = dwarf2_queue_tail = NULL;
7897 }
7898
7899 /* Read in full symbols for PST, and anything it depends on.  */
7900
7901 static void
7902 psymtab_to_symtab_1 (struct partial_symtab *pst)
7903 {
7904   struct dwarf2_per_cu_data *per_cu;
7905   int i;
7906
7907   if (pst->readin)
7908     return;
7909
7910   for (i = 0; i < pst->number_of_dependencies; i++)
7911     if (!pst->dependencies[i]->readin
7912         && pst->dependencies[i]->user == NULL)
7913       {
7914         /* Inform about additional files that need to be read in.  */
7915         if (info_verbose)
7916           {
7917             /* FIXME: i18n: Need to make this a single string.  */
7918             fputs_filtered (" ", gdb_stdout);
7919             wrap_here ("");
7920             fputs_filtered ("and ", gdb_stdout);
7921             wrap_here ("");
7922             printf_filtered ("%s...", pst->dependencies[i]->filename);
7923             wrap_here ("");     /* Flush output.  */
7924             gdb_flush (gdb_stdout);
7925           }
7926         psymtab_to_symtab_1 (pst->dependencies[i]);
7927       }
7928
7929   per_cu = (struct dwarf2_per_cu_data *) pst->read_symtab_private;
7930
7931   if (per_cu == NULL)
7932     {
7933       /* It's an include file, no symbols to read for it.
7934          Everything is in the parent symtab.  */
7935       pst->readin = 1;
7936       return;
7937     }
7938
7939   dw2_do_instantiate_symtab (per_cu);
7940 }
7941
7942 /* Trivial hash function for die_info: the hash value of a DIE
7943    is its offset in .debug_info for this objfile.  */
7944
7945 static hashval_t
7946 die_hash (const void *item)
7947 {
7948   const struct die_info *die = (const struct die_info *) item;
7949
7950   return to_underlying (die->sect_off);
7951 }
7952
7953 /* Trivial comparison function for die_info structures: two DIEs
7954    are equal if they have the same offset.  */
7955
7956 static int
7957 die_eq (const void *item_lhs, const void *item_rhs)
7958 {
7959   const struct die_info *die_lhs = (const struct die_info *) item_lhs;
7960   const struct die_info *die_rhs = (const struct die_info *) item_rhs;
7961
7962   return die_lhs->sect_off == die_rhs->sect_off;
7963 }
7964
7965 /* die_reader_func for load_full_comp_unit.
7966    This is identical to read_signatured_type_reader,
7967    but is kept separate for now.  */
7968
7969 static void
7970 load_full_comp_unit_reader (const struct die_reader_specs *reader,
7971                             const gdb_byte *info_ptr,
7972                             struct die_info *comp_unit_die,
7973                             int has_children,
7974                             void *data)
7975 {
7976   struct dwarf2_cu *cu = reader->cu;
7977   enum language *language_ptr = (enum language *) data;
7978
7979   gdb_assert (cu->die_hash == NULL);
7980   cu->die_hash =
7981     htab_create_alloc_ex (cu->header.length / 12,
7982                           die_hash,
7983                           die_eq,
7984                           NULL,
7985                           &cu->comp_unit_obstack,
7986                           hashtab_obstack_allocate,
7987                           dummy_obstack_deallocate);
7988
7989   if (has_children)
7990     comp_unit_die->child = read_die_and_siblings (reader, info_ptr,
7991                                                   &info_ptr, comp_unit_die);
7992   cu->dies = comp_unit_die;
7993   /* comp_unit_die is not stored in die_hash, no need.  */
7994
7995   /* We try not to read any attributes in this function, because not
7996      all CUs needed for references have been loaded yet, and symbol
7997      table processing isn't initialized.  But we have to set the CU language,
7998      or we won't be able to build types correctly.
7999      Similarly, if we do not read the producer, we can not apply
8000      producer-specific interpretation.  */
8001   prepare_one_comp_unit (cu, cu->dies, *language_ptr);
8002 }
8003
8004 /* Load the DIEs associated with PER_CU into memory.  */
8005
8006 static void
8007 load_full_comp_unit (struct dwarf2_per_cu_data *this_cu,
8008                      enum language pretend_language)
8009 {
8010   gdb_assert (! this_cu->is_debug_types);
8011
8012   init_cutu_and_read_dies (this_cu, NULL, 1, 1,
8013                            load_full_comp_unit_reader, &pretend_language);
8014 }
8015
8016 /* Add a DIE to the delayed physname list.  */
8017
8018 static void
8019 add_to_method_list (struct type *type, int fnfield_index, int index,
8020                     const char *name, struct die_info *die,
8021                     struct dwarf2_cu *cu)
8022 {
8023   struct delayed_method_info mi;
8024   mi.type = type;
8025   mi.fnfield_index = fnfield_index;
8026   mi.index = index;
8027   mi.name = name;
8028   mi.die = die;
8029   VEC_safe_push (delayed_method_info, cu->method_list, &mi);
8030 }
8031
8032 /* A cleanup for freeing the delayed method list.  */
8033
8034 static void
8035 free_delayed_list (void *ptr)
8036 {
8037   struct dwarf2_cu *cu = (struct dwarf2_cu *) ptr;
8038   if (cu->method_list != NULL)
8039     {
8040       VEC_free (delayed_method_info, cu->method_list);
8041       cu->method_list = NULL;
8042     }
8043 }
8044
8045 /* Compute the physnames of any methods on the CU's method list.
8046
8047    The computation of method physnames is delayed in order to avoid the
8048    (bad) condition that one of the method's formal parameters is of an as yet
8049    incomplete type.  */
8050
8051 static void
8052 compute_delayed_physnames (struct dwarf2_cu *cu)
8053 {
8054   int i;
8055   struct delayed_method_info *mi;
8056   for (i = 0; VEC_iterate (delayed_method_info, cu->method_list, i, mi) ; ++i)
8057     {
8058       const char *physname;
8059       struct fn_fieldlist *fn_flp
8060         = &TYPE_FN_FIELDLIST (mi->type, mi->fnfield_index);
8061       physname = dwarf2_physname (mi->name, mi->die, cu);
8062       TYPE_FN_FIELD_PHYSNAME (fn_flp->fn_fields, mi->index)
8063         = physname ? physname : "";
8064     }
8065 }
8066
8067 /* Go objects should be embedded in a DW_TAG_module DIE,
8068    and it's not clear if/how imported objects will appear.
8069    To keep Go support simple until that's worked out,
8070    go back through what we've read and create something usable.
8071    We could do this while processing each DIE, and feels kinda cleaner,
8072    but that way is more invasive.
8073    This is to, for example, allow the user to type "p var" or "b main"
8074    without having to specify the package name, and allow lookups
8075    of module.object to work in contexts that use the expression
8076    parser.  */
8077
8078 static void
8079 fixup_go_packaging (struct dwarf2_cu *cu)
8080 {
8081   char *package_name = NULL;
8082   struct pending *list;
8083   int i;
8084
8085   for (list = global_symbols; list != NULL; list = list->next)
8086     {
8087       for (i = 0; i < list->nsyms; ++i)
8088         {
8089           struct symbol *sym = list->symbol[i];
8090
8091           if (SYMBOL_LANGUAGE (sym) == language_go
8092               && SYMBOL_CLASS (sym) == LOC_BLOCK)
8093             {
8094               char *this_package_name = go_symbol_package_name (sym);
8095
8096               if (this_package_name == NULL)
8097                 continue;
8098               if (package_name == NULL)
8099                 package_name = this_package_name;
8100               else
8101                 {
8102                   if (strcmp (package_name, this_package_name) != 0)
8103                     complaint (&symfile_complaints,
8104                                _("Symtab %s has objects from two different Go packages: %s and %s"),
8105                                (symbol_symtab (sym) != NULL
8106                                 ? symtab_to_filename_for_display
8107                                     (symbol_symtab (sym))
8108                                 : objfile_name (cu->objfile)),
8109                                this_package_name, package_name);
8110                   xfree (this_package_name);
8111                 }
8112             }
8113         }
8114     }
8115
8116   if (package_name != NULL)
8117     {
8118       struct objfile *objfile = cu->objfile;
8119       const char *saved_package_name
8120         = (const char *) obstack_copy0 (&objfile->per_bfd->storage_obstack,
8121                                         package_name,
8122                                         strlen (package_name));
8123       struct type *type = init_type (objfile, TYPE_CODE_MODULE, 0,
8124                                      saved_package_name);
8125       struct symbol *sym;
8126
8127       TYPE_TAG_NAME (type) = TYPE_NAME (type);
8128
8129       sym = allocate_symbol (objfile);
8130       SYMBOL_SET_LANGUAGE (sym, language_go, &objfile->objfile_obstack);
8131       SYMBOL_SET_NAMES (sym, saved_package_name,
8132                         strlen (saved_package_name), 0, objfile);
8133       /* This is not VAR_DOMAIN because we want a way to ensure a lookup of,
8134          e.g., "main" finds the "main" module and not C's main().  */
8135       SYMBOL_DOMAIN (sym) = STRUCT_DOMAIN;
8136       SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
8137       SYMBOL_TYPE (sym) = type;
8138
8139       add_symbol_to_list (sym, &global_symbols);
8140
8141       xfree (package_name);
8142     }
8143 }
8144
8145 /* Return the symtab for PER_CU.  This works properly regardless of
8146    whether we're using the index or psymtabs.  */
8147
8148 static struct compunit_symtab *
8149 get_compunit_symtab (struct dwarf2_per_cu_data *per_cu)
8150 {
8151   return (dwarf2_per_objfile->using_index
8152           ? per_cu->v.quick->compunit_symtab
8153           : per_cu->v.psymtab->compunit_symtab);
8154 }
8155
8156 /* A helper function for computing the list of all symbol tables
8157    included by PER_CU.  */
8158
8159 static void
8160 recursively_compute_inclusions (VEC (compunit_symtab_ptr) **result,
8161                                 htab_t all_children, htab_t all_type_symtabs,
8162                                 struct dwarf2_per_cu_data *per_cu,
8163                                 struct compunit_symtab *immediate_parent)
8164 {
8165   void **slot;
8166   int ix;
8167   struct compunit_symtab *cust;
8168   struct dwarf2_per_cu_data *iter;
8169
8170   slot = htab_find_slot (all_children, per_cu, INSERT);
8171   if (*slot != NULL)
8172     {
8173       /* This inclusion and its children have been processed.  */
8174       return;
8175     }
8176
8177   *slot = per_cu;
8178   /* Only add a CU if it has a symbol table.  */
8179   cust = get_compunit_symtab (per_cu);
8180   if (cust != NULL)
8181     {
8182       /* If this is a type unit only add its symbol table if we haven't
8183          seen it yet (type unit per_cu's can share symtabs).  */
8184       if (per_cu->is_debug_types)
8185         {
8186           slot = htab_find_slot (all_type_symtabs, cust, INSERT);
8187           if (*slot == NULL)
8188             {
8189               *slot = cust;
8190               VEC_safe_push (compunit_symtab_ptr, *result, cust);
8191               if (cust->user == NULL)
8192                 cust->user = immediate_parent;
8193             }
8194         }
8195       else
8196         {
8197           VEC_safe_push (compunit_symtab_ptr, *result, cust);
8198           if (cust->user == NULL)
8199             cust->user = immediate_parent;
8200         }
8201     }
8202
8203   for (ix = 0;
8204        VEC_iterate (dwarf2_per_cu_ptr, per_cu->imported_symtabs, ix, iter);
8205        ++ix)
8206     {
8207       recursively_compute_inclusions (result, all_children,
8208                                       all_type_symtabs, iter, cust);
8209     }
8210 }
8211
8212 /* Compute the compunit_symtab 'includes' fields for the compunit_symtab of
8213    PER_CU.  */
8214
8215 static void
8216 compute_compunit_symtab_includes (struct dwarf2_per_cu_data *per_cu)
8217 {
8218   gdb_assert (! per_cu->is_debug_types);
8219
8220   if (!VEC_empty (dwarf2_per_cu_ptr, per_cu->imported_symtabs))
8221     {
8222       int ix, len;
8223       struct dwarf2_per_cu_data *per_cu_iter;
8224       struct compunit_symtab *compunit_symtab_iter;
8225       VEC (compunit_symtab_ptr) *result_symtabs = NULL;
8226       htab_t all_children, all_type_symtabs;
8227       struct compunit_symtab *cust = get_compunit_symtab (per_cu);
8228
8229       /* If we don't have a symtab, we can just skip this case.  */
8230       if (cust == NULL)
8231         return;
8232
8233       all_children = htab_create_alloc (1, htab_hash_pointer, htab_eq_pointer,
8234                                         NULL, xcalloc, xfree);
8235       all_type_symtabs = htab_create_alloc (1, htab_hash_pointer, htab_eq_pointer,
8236                                             NULL, xcalloc, xfree);
8237
8238       for (ix = 0;
8239            VEC_iterate (dwarf2_per_cu_ptr, per_cu->imported_symtabs,
8240                         ix, per_cu_iter);
8241            ++ix)
8242         {
8243           recursively_compute_inclusions (&result_symtabs, all_children,
8244                                           all_type_symtabs, per_cu_iter,
8245                                           cust);
8246         }
8247
8248       /* Now we have a transitive closure of all the included symtabs.  */
8249       len = VEC_length (compunit_symtab_ptr, result_symtabs);
8250       cust->includes
8251         = XOBNEWVEC (&dwarf2_per_objfile->objfile->objfile_obstack,
8252                      struct compunit_symtab *, len + 1);
8253       for (ix = 0;
8254            VEC_iterate (compunit_symtab_ptr, result_symtabs, ix,
8255                         compunit_symtab_iter);
8256            ++ix)
8257         cust->includes[ix] = compunit_symtab_iter;
8258       cust->includes[len] = NULL;
8259
8260       VEC_free (compunit_symtab_ptr, result_symtabs);
8261       htab_delete (all_children);
8262       htab_delete (all_type_symtabs);
8263     }
8264 }
8265
8266 /* Compute the 'includes' field for the symtabs of all the CUs we just
8267    read.  */
8268
8269 static void
8270 process_cu_includes (void)
8271 {
8272   int ix;
8273   struct dwarf2_per_cu_data *iter;
8274
8275   for (ix = 0;
8276        VEC_iterate (dwarf2_per_cu_ptr, dwarf2_per_objfile->just_read_cus,
8277                     ix, iter);
8278        ++ix)
8279     {
8280       if (! iter->is_debug_types)
8281         compute_compunit_symtab_includes (iter);
8282     }
8283
8284   VEC_free (dwarf2_per_cu_ptr, dwarf2_per_objfile->just_read_cus);
8285 }
8286
8287 /* Generate full symbol information for PER_CU, whose DIEs have
8288    already been loaded into memory.  */
8289
8290 static void
8291 process_full_comp_unit (struct dwarf2_per_cu_data *per_cu,
8292                         enum language pretend_language)
8293 {
8294   struct dwarf2_cu *cu = per_cu->cu;
8295   struct objfile *objfile = per_cu->objfile;
8296   struct gdbarch *gdbarch = get_objfile_arch (objfile);
8297   CORE_ADDR lowpc, highpc;
8298   struct compunit_symtab *cust;
8299   struct cleanup *back_to, *delayed_list_cleanup;
8300   CORE_ADDR baseaddr;
8301   struct block *static_block;
8302   CORE_ADDR addr;
8303
8304   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
8305
8306   buildsym_init ();
8307   back_to = make_cleanup (really_free_pendings, NULL);
8308   delayed_list_cleanup = make_cleanup (free_delayed_list, cu);
8309
8310   cu->list_in_scope = &file_symbols;
8311
8312   cu->language = pretend_language;
8313   cu->language_defn = language_def (cu->language);
8314
8315   /* Do line number decoding in read_file_scope () */
8316   process_die (cu->dies, cu);
8317
8318   /* For now fudge the Go package.  */
8319   if (cu->language == language_go)
8320     fixup_go_packaging (cu);
8321
8322   /* Now that we have processed all the DIEs in the CU, all the types 
8323      should be complete, and it should now be safe to compute all of the
8324      physnames.  */
8325   compute_delayed_physnames (cu);
8326   do_cleanups (delayed_list_cleanup);
8327
8328   /* Some compilers don't define a DW_AT_high_pc attribute for the
8329      compilation unit.  If the DW_AT_high_pc is missing, synthesize
8330      it, by scanning the DIE's below the compilation unit.  */
8331   get_scope_pc_bounds (cu->dies, &lowpc, &highpc, cu);
8332
8333   addr = gdbarch_adjust_dwarf2_addr (gdbarch, highpc + baseaddr);
8334   static_block = end_symtab_get_static_block (addr, 0, 1);
8335
8336   /* If the comp unit has DW_AT_ranges, it may have discontiguous ranges.
8337      Also, DW_AT_ranges may record ranges not belonging to any child DIEs
8338      (such as virtual method tables).  Record the ranges in STATIC_BLOCK's
8339      addrmap to help ensure it has an accurate map of pc values belonging to
8340      this comp unit.  */
8341   dwarf2_record_block_ranges (cu->dies, static_block, baseaddr, cu);
8342
8343   cust = end_symtab_from_static_block (static_block,
8344                                        SECT_OFF_TEXT (objfile), 0);
8345
8346   if (cust != NULL)
8347     {
8348       int gcc_4_minor = producer_is_gcc_ge_4 (cu->producer);
8349
8350       /* Set symtab language to language from DW_AT_language.  If the
8351          compilation is from a C file generated by language preprocessors, do
8352          not set the language if it was already deduced by start_subfile.  */
8353       if (!(cu->language == language_c
8354             && COMPUNIT_FILETABS (cust)->language != language_unknown))
8355         COMPUNIT_FILETABS (cust)->language = cu->language;
8356
8357       /* GCC-4.0 has started to support -fvar-tracking.  GCC-3.x still can
8358          produce DW_AT_location with location lists but it can be possibly
8359          invalid without -fvar-tracking.  Still up to GCC-4.4.x incl. 4.4.0
8360          there were bugs in prologue debug info, fixed later in GCC-4.5
8361          by "unwind info for epilogues" patch (which is not directly related).
8362
8363          For -gdwarf-4 type units LOCATIONS_VALID indication is fortunately not
8364          needed, it would be wrong due to missing DW_AT_producer there.
8365
8366          Still one can confuse GDB by using non-standard GCC compilation
8367          options - this waits on GCC PR other/32998 (-frecord-gcc-switches).
8368          */ 
8369       if (cu->has_loclist && gcc_4_minor >= 5)
8370         cust->locations_valid = 1;
8371
8372       if (gcc_4_minor >= 5)
8373         cust->epilogue_unwind_valid = 1;
8374
8375       cust->call_site_htab = cu->call_site_htab;
8376     }
8377
8378   if (dwarf2_per_objfile->using_index)
8379     per_cu->v.quick->compunit_symtab = cust;
8380   else
8381     {
8382       struct partial_symtab *pst = per_cu->v.psymtab;
8383       pst->compunit_symtab = cust;
8384       pst->readin = 1;
8385     }
8386
8387   /* Push it for inclusion processing later.  */
8388   VEC_safe_push (dwarf2_per_cu_ptr, dwarf2_per_objfile->just_read_cus, per_cu);
8389
8390   do_cleanups (back_to);
8391 }
8392
8393 /* Generate full symbol information for type unit PER_CU, whose DIEs have
8394    already been loaded into memory.  */
8395
8396 static void
8397 process_full_type_unit (struct dwarf2_per_cu_data *per_cu,
8398                         enum language pretend_language)
8399 {
8400   struct dwarf2_cu *cu = per_cu->cu;
8401   struct objfile *objfile = per_cu->objfile;
8402   struct compunit_symtab *cust;
8403   struct cleanup *back_to, *delayed_list_cleanup;
8404   struct signatured_type *sig_type;
8405
8406   gdb_assert (per_cu->is_debug_types);
8407   sig_type = (struct signatured_type *) per_cu;
8408
8409   buildsym_init ();
8410   back_to = make_cleanup (really_free_pendings, NULL);
8411   delayed_list_cleanup = make_cleanup (free_delayed_list, cu);
8412
8413   cu->list_in_scope = &file_symbols;
8414
8415   cu->language = pretend_language;
8416   cu->language_defn = language_def (cu->language);
8417
8418   /* The symbol tables are set up in read_type_unit_scope.  */
8419   process_die (cu->dies, cu);
8420
8421   /* For now fudge the Go package.  */
8422   if (cu->language == language_go)
8423     fixup_go_packaging (cu);
8424
8425   /* Now that we have processed all the DIEs in the CU, all the types 
8426      should be complete, and it should now be safe to compute all of the
8427      physnames.  */
8428   compute_delayed_physnames (cu);
8429   do_cleanups (delayed_list_cleanup);
8430
8431   /* TUs share symbol tables.
8432      If this is the first TU to use this symtab, complete the construction
8433      of it with end_expandable_symtab.  Otherwise, complete the addition of
8434      this TU's symbols to the existing symtab.  */
8435   if (sig_type->type_unit_group->compunit_symtab == NULL)
8436     {
8437       cust = end_expandable_symtab (0, SECT_OFF_TEXT (objfile));
8438       sig_type->type_unit_group->compunit_symtab = cust;
8439
8440       if (cust != NULL)
8441         {
8442           /* Set symtab language to language from DW_AT_language.  If the
8443              compilation is from a C file generated by language preprocessors,
8444              do not set the language if it was already deduced by
8445              start_subfile.  */
8446           if (!(cu->language == language_c
8447                 && COMPUNIT_FILETABS (cust)->language != language_c))
8448             COMPUNIT_FILETABS (cust)->language = cu->language;
8449         }
8450     }
8451   else
8452     {
8453       augment_type_symtab ();
8454       cust = sig_type->type_unit_group->compunit_symtab;
8455     }
8456
8457   if (dwarf2_per_objfile->using_index)
8458     per_cu->v.quick->compunit_symtab = cust;
8459   else
8460     {
8461       struct partial_symtab *pst = per_cu->v.psymtab;
8462       pst->compunit_symtab = cust;
8463       pst->readin = 1;
8464     }
8465
8466   do_cleanups (back_to);
8467 }
8468
8469 /* Process an imported unit DIE.  */
8470
8471 static void
8472 process_imported_unit_die (struct die_info *die, struct dwarf2_cu *cu)
8473 {
8474   struct attribute *attr;
8475
8476   /* For now we don't handle imported units in type units.  */
8477   if (cu->per_cu->is_debug_types)
8478     {
8479       error (_("Dwarf Error: DW_TAG_imported_unit is not"
8480                " supported in type units [in module %s]"),
8481              objfile_name (cu->objfile));
8482     }
8483
8484   attr = dwarf2_attr (die, DW_AT_import, cu);
8485   if (attr != NULL)
8486     {
8487       sect_offset sect_off = dwarf2_get_ref_die_offset (attr);
8488       bool is_dwz = (attr->form == DW_FORM_GNU_ref_alt || cu->per_cu->is_dwz);
8489       dwarf2_per_cu_data *per_cu
8490         = dwarf2_find_containing_comp_unit (sect_off, is_dwz, cu->objfile);
8491
8492       /* If necessary, add it to the queue and load its DIEs.  */
8493       if (maybe_queue_comp_unit (cu, per_cu, cu->language))
8494         load_full_comp_unit (per_cu, cu->language);
8495
8496       VEC_safe_push (dwarf2_per_cu_ptr, cu->per_cu->imported_symtabs,
8497                      per_cu);
8498     }
8499 }
8500
8501 /* RAII object that represents a process_die scope: i.e.,
8502    starts/finishes processing a DIE.  */
8503 class process_die_scope
8504 {
8505 public:
8506   process_die_scope (die_info *die, dwarf2_cu *cu)
8507     : m_die (die), m_cu (cu)
8508   {
8509     /* We should only be processing DIEs not already in process.  */
8510     gdb_assert (!m_die->in_process);
8511     m_die->in_process = true;
8512   }
8513
8514   ~process_die_scope ()
8515   {
8516     m_die->in_process = false;
8517
8518     /* If we're done processing the DIE for the CU that owns the line
8519        header, we don't need the line header anymore.  */
8520     if (m_cu->line_header_die_owner == m_die)
8521       {
8522         delete m_cu->line_header;
8523         m_cu->line_header = NULL;
8524         m_cu->line_header_die_owner = NULL;
8525       }
8526   }
8527
8528 private:
8529   die_info *m_die;
8530   dwarf2_cu *m_cu;
8531 };
8532
8533 /* Process a die and its children.  */
8534
8535 static void
8536 process_die (struct die_info *die, struct dwarf2_cu *cu)
8537 {
8538   process_die_scope scope (die, cu);
8539
8540   switch (die->tag)
8541     {
8542     case DW_TAG_padding:
8543       break;
8544     case DW_TAG_compile_unit:
8545     case DW_TAG_partial_unit:
8546       read_file_scope (die, cu);
8547       break;
8548     case DW_TAG_type_unit:
8549       read_type_unit_scope (die, cu);
8550       break;
8551     case DW_TAG_subprogram:
8552     case DW_TAG_inlined_subroutine:
8553       read_func_scope (die, cu);
8554       break;
8555     case DW_TAG_lexical_block:
8556     case DW_TAG_try_block:
8557     case DW_TAG_catch_block:
8558       read_lexical_block_scope (die, cu);
8559       break;
8560     case DW_TAG_call_site:
8561     case DW_TAG_GNU_call_site:
8562       read_call_site_scope (die, cu);
8563       break;
8564     case DW_TAG_class_type:
8565     case DW_TAG_interface_type:
8566     case DW_TAG_structure_type:
8567     case DW_TAG_union_type:
8568       process_structure_scope (die, cu);
8569       break;
8570     case DW_TAG_enumeration_type:
8571       process_enumeration_scope (die, cu);
8572       break;
8573
8574     /* These dies have a type, but processing them does not create
8575        a symbol or recurse to process the children.  Therefore we can
8576        read them on-demand through read_type_die.  */
8577     case DW_TAG_subroutine_type:
8578     case DW_TAG_set_type:
8579     case DW_TAG_array_type:
8580     case DW_TAG_pointer_type:
8581     case DW_TAG_ptr_to_member_type:
8582     case DW_TAG_reference_type:
8583     case DW_TAG_rvalue_reference_type:
8584     case DW_TAG_string_type:
8585       break;
8586
8587     case DW_TAG_base_type:
8588     case DW_TAG_subrange_type:
8589     case DW_TAG_typedef:
8590       /* Add a typedef symbol for the type definition, if it has a
8591          DW_AT_name.  */
8592       new_symbol (die, read_type_die (die, cu), cu);
8593       break;
8594     case DW_TAG_common_block:
8595       read_common_block (die, cu);
8596       break;
8597     case DW_TAG_common_inclusion:
8598       break;
8599     case DW_TAG_namespace:
8600       cu->processing_has_namespace_info = 1;
8601       read_namespace (die, cu);
8602       break;
8603     case DW_TAG_module:
8604       cu->processing_has_namespace_info = 1;
8605       read_module (die, cu);
8606       break;
8607     case DW_TAG_imported_declaration:
8608       cu->processing_has_namespace_info = 1;
8609       if (read_namespace_alias (die, cu))
8610         break;
8611       /* The declaration is not a global namespace alias: fall through.  */
8612     case DW_TAG_imported_module:
8613       cu->processing_has_namespace_info = 1;
8614       if (die->child != NULL && (die->tag == DW_TAG_imported_declaration
8615                                  || cu->language != language_fortran))
8616         complaint (&symfile_complaints, _("Tag '%s' has unexpected children"),
8617                    dwarf_tag_name (die->tag));
8618       read_import_statement (die, cu);
8619       break;
8620
8621     case DW_TAG_imported_unit:
8622       process_imported_unit_die (die, cu);
8623       break;
8624
8625     default:
8626       new_symbol (die, NULL, cu);
8627       break;
8628     }
8629 }
8630 \f
8631 /* DWARF name computation.  */
8632
8633 /* A helper function for dwarf2_compute_name which determines whether DIE
8634    needs to have the name of the scope prepended to the name listed in the
8635    die.  */
8636
8637 static int
8638 die_needs_namespace (struct die_info *die, struct dwarf2_cu *cu)
8639 {
8640   struct attribute *attr;
8641
8642   switch (die->tag)
8643     {
8644     case DW_TAG_namespace:
8645     case DW_TAG_typedef:
8646     case DW_TAG_class_type:
8647     case DW_TAG_interface_type:
8648     case DW_TAG_structure_type:
8649     case DW_TAG_union_type:
8650     case DW_TAG_enumeration_type:
8651     case DW_TAG_enumerator:
8652     case DW_TAG_subprogram:
8653     case DW_TAG_inlined_subroutine:
8654     case DW_TAG_member:
8655     case DW_TAG_imported_declaration:
8656       return 1;
8657
8658     case DW_TAG_variable:
8659     case DW_TAG_constant:
8660       /* We only need to prefix "globally" visible variables.  These include
8661          any variable marked with DW_AT_external or any variable that
8662          lives in a namespace.  [Variables in anonymous namespaces
8663          require prefixing, but they are not DW_AT_external.]  */
8664
8665       if (dwarf2_attr (die, DW_AT_specification, cu))
8666         {
8667           struct dwarf2_cu *spec_cu = cu;
8668
8669           return die_needs_namespace (die_specification (die, &spec_cu),
8670                                       spec_cu);
8671         }
8672
8673       attr = dwarf2_attr (die, DW_AT_external, cu);
8674       if (attr == NULL && die->parent->tag != DW_TAG_namespace
8675           && die->parent->tag != DW_TAG_module)
8676         return 0;
8677       /* A variable in a lexical block of some kind does not need a
8678          namespace, even though in C++ such variables may be external
8679          and have a mangled name.  */
8680       if (die->parent->tag ==  DW_TAG_lexical_block
8681           || die->parent->tag ==  DW_TAG_try_block
8682           || die->parent->tag ==  DW_TAG_catch_block
8683           || die->parent->tag == DW_TAG_subprogram)
8684         return 0;
8685       return 1;
8686
8687     default:
8688       return 0;
8689     }
8690 }
8691
8692 /* Compute the fully qualified name of DIE in CU.  If PHYSNAME is nonzero,
8693    compute the physname for the object, which include a method's:
8694    - formal parameters (C++),
8695    - receiver type (Go),
8696
8697    The term "physname" is a bit confusing.
8698    For C++, for example, it is the demangled name.
8699    For Go, for example, it's the mangled name.
8700
8701    For Ada, return the DIE's linkage name rather than the fully qualified
8702    name.  PHYSNAME is ignored..
8703
8704    The result is allocated on the objfile_obstack and canonicalized.  */
8705
8706 static const char *
8707 dwarf2_compute_name (const char *name,
8708                      struct die_info *die, struct dwarf2_cu *cu,
8709                      int physname)
8710 {
8711   struct objfile *objfile = cu->objfile;
8712
8713   if (name == NULL)
8714     name = dwarf2_name (die, cu);
8715
8716   /* For Fortran GDB prefers DW_AT_*linkage_name for the physname if present
8717      but otherwise compute it by typename_concat inside GDB.
8718      FIXME: Actually this is not really true, or at least not always true.
8719      It's all very confusing.  SYMBOL_SET_NAMES doesn't try to demangle
8720      Fortran names because there is no mangling standard.  So new_symbol_full
8721      will set the demangled name to the result of dwarf2_full_name, and it is
8722      the demangled name that GDB uses if it exists.  */
8723   if (cu->language == language_ada
8724       || (cu->language == language_fortran && physname))
8725     {
8726       /* For Ada unit, we prefer the linkage name over the name, as
8727          the former contains the exported name, which the user expects
8728          to be able to reference.  Ideally, we want the user to be able
8729          to reference this entity using either natural or linkage name,
8730          but we haven't started looking at this enhancement yet.  */
8731       const char *linkage_name;
8732
8733       linkage_name = dwarf2_string_attr (die, DW_AT_linkage_name, cu);
8734       if (linkage_name == NULL)
8735         linkage_name = dwarf2_string_attr (die, DW_AT_MIPS_linkage_name, cu);
8736       if (linkage_name != NULL)
8737         return linkage_name;
8738     }
8739
8740   /* These are the only languages we know how to qualify names in.  */
8741   if (name != NULL
8742       && (cu->language == language_cplus
8743           || cu->language == language_fortran || cu->language == language_d
8744           || cu->language == language_rust))
8745     {
8746       if (die_needs_namespace (die, cu))
8747         {
8748           long length;
8749           const char *prefix;
8750           const char *canonical_name = NULL;
8751
8752           string_file buf;
8753
8754           prefix = determine_prefix (die, cu);
8755           if (*prefix != '\0')
8756             {
8757               char *prefixed_name = typename_concat (NULL, prefix, name,
8758                                                      physname, cu);
8759
8760               buf.puts (prefixed_name);
8761               xfree (prefixed_name);
8762             }
8763           else
8764             buf.puts (name);
8765
8766           /* Template parameters may be specified in the DIE's DW_AT_name, or
8767              as children with DW_TAG_template_type_param or
8768              DW_TAG_value_type_param.  If the latter, add them to the name
8769              here.  If the name already has template parameters, then
8770              skip this step; some versions of GCC emit both, and
8771              it is more efficient to use the pre-computed name.
8772
8773              Something to keep in mind about this process: it is very
8774              unlikely, or in some cases downright impossible, to produce
8775              something that will match the mangled name of a function.
8776              If the definition of the function has the same debug info,
8777              we should be able to match up with it anyway.  But fallbacks
8778              using the minimal symbol, for instance to find a method
8779              implemented in a stripped copy of libstdc++, will not work.
8780              If we do not have debug info for the definition, we will have to
8781              match them up some other way.
8782
8783              When we do name matching there is a related problem with function
8784              templates; two instantiated function templates are allowed to
8785              differ only by their return types, which we do not add here.  */
8786
8787           if (cu->language == language_cplus && strchr (name, '<') == NULL)
8788             {
8789               struct attribute *attr;
8790               struct die_info *child;
8791               int first = 1;
8792
8793               die->building_fullname = 1;
8794
8795               for (child = die->child; child != NULL; child = child->sibling)
8796                 {
8797                   struct type *type;
8798                   LONGEST value;
8799                   const gdb_byte *bytes;
8800                   struct dwarf2_locexpr_baton *baton;
8801                   struct value *v;
8802
8803                   if (child->tag != DW_TAG_template_type_param
8804                       && child->tag != DW_TAG_template_value_param)
8805                     continue;
8806
8807                   if (first)
8808                     {
8809                       buf.puts ("<");
8810                       first = 0;
8811                     }
8812                   else
8813                     buf.puts (", ");
8814
8815                   attr = dwarf2_attr (child, DW_AT_type, cu);
8816                   if (attr == NULL)
8817                     {
8818                       complaint (&symfile_complaints,
8819                                  _("template parameter missing DW_AT_type"));
8820                       buf.puts ("UNKNOWN_TYPE");
8821                       continue;
8822                     }
8823                   type = die_type (child, cu);
8824
8825                   if (child->tag == DW_TAG_template_type_param)
8826                     {
8827                       c_print_type (type, "", &buf, -1, 0, &type_print_raw_options);
8828                       continue;
8829                     }
8830
8831                   attr = dwarf2_attr (child, DW_AT_const_value, cu);
8832                   if (attr == NULL)
8833                     {
8834                       complaint (&symfile_complaints,
8835                                  _("template parameter missing "
8836                                    "DW_AT_const_value"));
8837                       buf.puts ("UNKNOWN_VALUE");
8838                       continue;
8839                     }
8840
8841                   dwarf2_const_value_attr (attr, type, name,
8842                                            &cu->comp_unit_obstack, cu,
8843                                            &value, &bytes, &baton);
8844
8845                   if (TYPE_NOSIGN (type))
8846                     /* GDB prints characters as NUMBER 'CHAR'.  If that's
8847                        changed, this can use value_print instead.  */
8848                     c_printchar (value, type, &buf);
8849                   else
8850                     {
8851                       struct value_print_options opts;
8852
8853                       if (baton != NULL)
8854                         v = dwarf2_evaluate_loc_desc (type, NULL,
8855                                                       baton->data,
8856                                                       baton->size,
8857                                                       baton->per_cu);
8858                       else if (bytes != NULL)
8859                         {
8860                           v = allocate_value (type);
8861                           memcpy (value_contents_writeable (v), bytes,
8862                                   TYPE_LENGTH (type));
8863                         }
8864                       else
8865                         v = value_from_longest (type, value);
8866
8867                       /* Specify decimal so that we do not depend on
8868                          the radix.  */
8869                       get_formatted_print_options (&opts, 'd');
8870                       opts.raw = 1;
8871                       value_print (v, &buf, &opts);
8872                       release_value (v);
8873                       value_free (v);
8874                     }
8875                 }
8876
8877               die->building_fullname = 0;
8878
8879               if (!first)
8880                 {
8881                   /* Close the argument list, with a space if necessary
8882                      (nested templates).  */
8883                   if (!buf.empty () && buf.string ().back () == '>')
8884                     buf.puts (" >");
8885                   else
8886                     buf.puts (">");
8887                 }
8888             }
8889
8890           /* For C++ methods, append formal parameter type
8891              information, if PHYSNAME.  */
8892
8893           if (physname && die->tag == DW_TAG_subprogram
8894               && cu->language == language_cplus)
8895             {
8896               struct type *type = read_type_die (die, cu);
8897
8898               c_type_print_args (type, &buf, 1, cu->language,
8899                                  &type_print_raw_options);
8900
8901               if (cu->language == language_cplus)
8902                 {
8903                   /* Assume that an artificial first parameter is
8904                      "this", but do not crash if it is not.  RealView
8905                      marks unnamed (and thus unused) parameters as
8906                      artificial; there is no way to differentiate
8907                      the two cases.  */
8908                   if (TYPE_NFIELDS (type) > 0
8909                       && TYPE_FIELD_ARTIFICIAL (type, 0)
8910                       && TYPE_CODE (TYPE_FIELD_TYPE (type, 0)) == TYPE_CODE_PTR
8911                       && TYPE_CONST (TYPE_TARGET_TYPE (TYPE_FIELD_TYPE (type,
8912                                                                         0))))
8913                     buf.puts (" const");
8914                 }
8915             }
8916
8917           const std::string &intermediate_name = buf.string ();
8918
8919           if (cu->language == language_cplus)
8920             canonical_name
8921               = dwarf2_canonicalize_name (intermediate_name.c_str (), cu,
8922                                           &objfile->per_bfd->storage_obstack);
8923
8924           /* If we only computed INTERMEDIATE_NAME, or if
8925              INTERMEDIATE_NAME is already canonical, then we need to
8926              copy it to the appropriate obstack.  */
8927           if (canonical_name == NULL || canonical_name == intermediate_name.c_str ())
8928             name = ((const char *)
8929                     obstack_copy0 (&objfile->per_bfd->storage_obstack,
8930                                    intermediate_name.c_str (),
8931                                    intermediate_name.length ()));
8932           else
8933             name = canonical_name;
8934         }
8935     }
8936
8937   return name;
8938 }
8939
8940 /* Return the fully qualified name of DIE, based on its DW_AT_name.
8941    If scope qualifiers are appropriate they will be added.  The result
8942    will be allocated on the storage_obstack, or NULL if the DIE does
8943    not have a name.  NAME may either be from a previous call to
8944    dwarf2_name or NULL.
8945
8946    The output string will be canonicalized (if C++).  */
8947
8948 static const char *
8949 dwarf2_full_name (const char *name, struct die_info *die, struct dwarf2_cu *cu)
8950 {
8951   return dwarf2_compute_name (name, die, cu, 0);
8952 }
8953
8954 /* Construct a physname for the given DIE in CU.  NAME may either be
8955    from a previous call to dwarf2_name or NULL.  The result will be
8956    allocated on the objfile_objstack or NULL if the DIE does not have a
8957    name.
8958
8959    The output string will be canonicalized (if C++).  */
8960
8961 static const char *
8962 dwarf2_physname (const char *name, struct die_info *die, struct dwarf2_cu *cu)
8963 {
8964   struct objfile *objfile = cu->objfile;
8965   const char *retval, *mangled = NULL, *canon = NULL;
8966   struct cleanup *back_to;
8967   int need_copy = 1;
8968
8969   /* In this case dwarf2_compute_name is just a shortcut not building anything
8970      on its own.  */
8971   if (!die_needs_namespace (die, cu))
8972     return dwarf2_compute_name (name, die, cu, 1);
8973
8974   back_to = make_cleanup (null_cleanup, NULL);
8975
8976   mangled = dwarf2_string_attr (die, DW_AT_linkage_name, cu);
8977   if (mangled == NULL)
8978     mangled = dwarf2_string_attr (die, DW_AT_MIPS_linkage_name, cu);
8979
8980   /* rustc emits invalid values for DW_AT_linkage_name.  Ignore these.
8981      See https://github.com/rust-lang/rust/issues/32925.  */
8982   if (cu->language == language_rust && mangled != NULL
8983       && strchr (mangled, '{') != NULL)
8984     mangled = NULL;
8985
8986   /* DW_AT_linkage_name is missing in some cases - depend on what GDB
8987      has computed.  */
8988   if (mangled != NULL)
8989     {
8990       char *demangled;
8991
8992       /* Use DMGL_RET_DROP for C++ template functions to suppress their return
8993          type.  It is easier for GDB users to search for such functions as
8994          `name(params)' than `long name(params)'.  In such case the minimal
8995          symbol names do not match the full symbol names but for template
8996          functions there is never a need to look up their definition from their
8997          declaration so the only disadvantage remains the minimal symbol
8998          variant `long name(params)' does not have the proper inferior type.
8999          */
9000
9001       if (cu->language == language_go)
9002         {
9003           /* This is a lie, but we already lie to the caller new_symbol_full.
9004              new_symbol_full assumes we return the mangled name.
9005              This just undoes that lie until things are cleaned up.  */
9006           demangled = NULL;
9007         }
9008       else
9009         {
9010           demangled = gdb_demangle (mangled,
9011                                     (DMGL_PARAMS | DMGL_ANSI | DMGL_RET_DROP));
9012         }
9013       if (demangled)
9014         {
9015           make_cleanup (xfree, demangled);
9016           canon = demangled;
9017         }
9018       else
9019         {
9020           canon = mangled;
9021           need_copy = 0;
9022         }
9023     }
9024
9025   if (canon == NULL || check_physname)
9026     {
9027       const char *physname = dwarf2_compute_name (name, die, cu, 1);
9028
9029       if (canon != NULL && strcmp (physname, canon) != 0)
9030         {
9031           /* It may not mean a bug in GDB.  The compiler could also
9032              compute DW_AT_linkage_name incorrectly.  But in such case
9033              GDB would need to be bug-to-bug compatible.  */
9034
9035           complaint (&symfile_complaints,
9036                      _("Computed physname <%s> does not match demangled <%s> "
9037                        "(from linkage <%s>) - DIE at 0x%x [in module %s]"),
9038                      physname, canon, mangled, to_underlying (die->sect_off),
9039                      objfile_name (objfile));
9040
9041           /* Prefer DW_AT_linkage_name (in the CANON form) - when it
9042              is available here - over computed PHYSNAME.  It is safer
9043              against both buggy GDB and buggy compilers.  */
9044
9045           retval = canon;
9046         }
9047       else
9048         {
9049           retval = physname;
9050           need_copy = 0;
9051         }
9052     }
9053   else
9054     retval = canon;
9055
9056   if (need_copy)
9057     retval = ((const char *)
9058               obstack_copy0 (&objfile->per_bfd->storage_obstack,
9059                              retval, strlen (retval)));
9060
9061   do_cleanups (back_to);
9062   return retval;
9063 }
9064
9065 /* Inspect DIE in CU for a namespace alias.  If one exists, record
9066    a new symbol for it.
9067
9068    Returns 1 if a namespace alias was recorded, 0 otherwise.  */
9069
9070 static int
9071 read_namespace_alias (struct die_info *die, struct dwarf2_cu *cu)
9072 {
9073   struct attribute *attr;
9074
9075   /* If the die does not have a name, this is not a namespace
9076      alias.  */
9077   attr = dwarf2_attr (die, DW_AT_name, cu);
9078   if (attr != NULL)
9079     {
9080       int num;
9081       struct die_info *d = die;
9082       struct dwarf2_cu *imported_cu = cu;
9083
9084       /* If the compiler has nested DW_AT_imported_declaration DIEs,
9085          keep inspecting DIEs until we hit the underlying import.  */
9086 #define MAX_NESTED_IMPORTED_DECLARATIONS 100
9087       for (num = 0; num  < MAX_NESTED_IMPORTED_DECLARATIONS; ++num)
9088         {
9089           attr = dwarf2_attr (d, DW_AT_import, cu);
9090           if (attr == NULL)
9091             break;
9092
9093           d = follow_die_ref (d, attr, &imported_cu);
9094           if (d->tag != DW_TAG_imported_declaration)
9095             break;
9096         }
9097
9098       if (num == MAX_NESTED_IMPORTED_DECLARATIONS)
9099         {
9100           complaint (&symfile_complaints,
9101                      _("DIE at 0x%x has too many recursively imported "
9102                        "declarations"), to_underlying (d->sect_off));
9103           return 0;
9104         }
9105
9106       if (attr != NULL)
9107         {
9108           struct type *type;
9109           sect_offset sect_off = dwarf2_get_ref_die_offset (attr);
9110
9111           type = get_die_type_at_offset (sect_off, cu->per_cu);
9112           if (type != NULL && TYPE_CODE (type) == TYPE_CODE_NAMESPACE)
9113             {
9114               /* This declaration is a global namespace alias.  Add
9115                  a symbol for it whose type is the aliased namespace.  */
9116               new_symbol (die, type, cu);
9117               return 1;
9118             }
9119         }
9120     }
9121
9122   return 0;
9123 }
9124
9125 /* Return the using directives repository (global or local?) to use in the
9126    current context for LANGUAGE.
9127
9128    For Ada, imported declarations can materialize renamings, which *may* be
9129    global.  However it is impossible (for now?) in DWARF to distinguish
9130    "external" imported declarations and "static" ones.  As all imported
9131    declarations seem to be static in all other languages, make them all CU-wide
9132    global only in Ada.  */
9133
9134 static struct using_direct **
9135 using_directives (enum language language)
9136 {
9137   if (language == language_ada && context_stack_depth == 0)
9138     return &global_using_directives;
9139   else
9140     return &local_using_directives;
9141 }
9142
9143 /* Read the import statement specified by the given die and record it.  */
9144
9145 static void
9146 read_import_statement (struct die_info *die, struct dwarf2_cu *cu)
9147 {
9148   struct objfile *objfile = cu->objfile;
9149   struct attribute *import_attr;
9150   struct die_info *imported_die, *child_die;
9151   struct dwarf2_cu *imported_cu;
9152   const char *imported_name;
9153   const char *imported_name_prefix;
9154   const char *canonical_name;
9155   const char *import_alias;
9156   const char *imported_declaration = NULL;
9157   const char *import_prefix;
9158   VEC (const_char_ptr) *excludes = NULL;
9159   struct cleanup *cleanups;
9160
9161   import_attr = dwarf2_attr (die, DW_AT_import, cu);
9162   if (import_attr == NULL)
9163     {
9164       complaint (&symfile_complaints, _("Tag '%s' has no DW_AT_import"),
9165                  dwarf_tag_name (die->tag));
9166       return;
9167     }
9168
9169   imported_cu = cu;
9170   imported_die = follow_die_ref_or_sig (die, import_attr, &imported_cu);
9171   imported_name = dwarf2_name (imported_die, imported_cu);
9172   if (imported_name == NULL)
9173     {
9174       /* GCC bug: https://bugzilla.redhat.com/show_bug.cgi?id=506524
9175
9176         The import in the following code:
9177         namespace A
9178           {
9179             typedef int B;
9180           }
9181
9182         int main ()
9183           {
9184             using A::B;
9185             B b;
9186             return b;
9187           }
9188
9189         ...
9190          <2><51>: Abbrev Number: 3 (DW_TAG_imported_declaration)
9191             <52>   DW_AT_decl_file   : 1
9192             <53>   DW_AT_decl_line   : 6
9193             <54>   DW_AT_import      : <0x75>
9194          <2><58>: Abbrev Number: 4 (DW_TAG_typedef)
9195             <59>   DW_AT_name        : B
9196             <5b>   DW_AT_decl_file   : 1
9197             <5c>   DW_AT_decl_line   : 2
9198             <5d>   DW_AT_type        : <0x6e>
9199         ...
9200          <1><75>: Abbrev Number: 7 (DW_TAG_base_type)
9201             <76>   DW_AT_byte_size   : 4
9202             <77>   DW_AT_encoding    : 5        (signed)
9203
9204         imports the wrong die ( 0x75 instead of 0x58 ).
9205         This case will be ignored until the gcc bug is fixed.  */
9206       return;
9207     }
9208
9209   /* Figure out the local name after import.  */
9210   import_alias = dwarf2_name (die, cu);
9211
9212   /* Figure out where the statement is being imported to.  */
9213   import_prefix = determine_prefix (die, cu);
9214
9215   /* Figure out what the scope of the imported die is and prepend it
9216      to the name of the imported die.  */
9217   imported_name_prefix = determine_prefix (imported_die, imported_cu);
9218
9219   if (imported_die->tag != DW_TAG_namespace
9220       && imported_die->tag != DW_TAG_module)
9221     {
9222       imported_declaration = imported_name;
9223       canonical_name = imported_name_prefix;
9224     }
9225   else if (strlen (imported_name_prefix) > 0)
9226     canonical_name = obconcat (&objfile->objfile_obstack,
9227                                imported_name_prefix,
9228                                (cu->language == language_d ? "." : "::"),
9229                                imported_name, (char *) NULL);
9230   else
9231     canonical_name = imported_name;
9232
9233   cleanups = make_cleanup (VEC_cleanup (const_char_ptr), &excludes);
9234
9235   if (die->tag == DW_TAG_imported_module && cu->language == language_fortran)
9236     for (child_die = die->child; child_die && child_die->tag;
9237          child_die = sibling_die (child_die))
9238       {
9239         /* DWARF-4: A Fortran use statement with a “rename list” may be
9240            represented by an imported module entry with an import attribute
9241            referring to the module and owned entries corresponding to those
9242            entities that are renamed as part of being imported.  */
9243
9244         if (child_die->tag != DW_TAG_imported_declaration)
9245           {
9246             complaint (&symfile_complaints,
9247                        _("child DW_TAG_imported_declaration expected "
9248                          "- DIE at 0x%x [in module %s]"),
9249                        to_underlying (child_die->sect_off), objfile_name (objfile));
9250             continue;
9251           }
9252
9253         import_attr = dwarf2_attr (child_die, DW_AT_import, cu);
9254         if (import_attr == NULL)
9255           {
9256             complaint (&symfile_complaints, _("Tag '%s' has no DW_AT_import"),
9257                        dwarf_tag_name (child_die->tag));
9258             continue;
9259           }
9260
9261         imported_cu = cu;
9262         imported_die = follow_die_ref_or_sig (child_die, import_attr,
9263                                               &imported_cu);
9264         imported_name = dwarf2_name (imported_die, imported_cu);
9265         if (imported_name == NULL)
9266           {
9267             complaint (&symfile_complaints,
9268                        _("child DW_TAG_imported_declaration has unknown "
9269                          "imported name - DIE at 0x%x [in module %s]"),
9270                        to_underlying (child_die->sect_off), objfile_name (objfile));
9271             continue;
9272           }
9273
9274         VEC_safe_push (const_char_ptr, excludes, imported_name);
9275
9276         process_die (child_die, cu);
9277       }
9278
9279   add_using_directive (using_directives (cu->language),
9280                        import_prefix,
9281                        canonical_name,
9282                        import_alias,
9283                        imported_declaration,
9284                        excludes,
9285                        0,
9286                        &objfile->objfile_obstack);
9287
9288   do_cleanups (cleanups);
9289 }
9290
9291 /* Check for possibly missing DW_AT_comp_dir with relative .debug_line
9292    directory paths.  GCC SVN r127613 (new option -fdebug-prefix-map) fixed
9293    this, it was first present in GCC release 4.3.0.  */
9294
9295 static int
9296 producer_is_gcc_lt_4_3 (struct dwarf2_cu *cu)
9297 {
9298   if (!cu->checked_producer)
9299     check_producer (cu);
9300
9301   return cu->producer_is_gcc_lt_4_3;
9302 }
9303
9304 static file_and_directory
9305 find_file_and_directory (struct die_info *die, struct dwarf2_cu *cu)
9306 {
9307   file_and_directory res;
9308
9309   /* Find the filename.  Do not use dwarf2_name here, since the filename
9310      is not a source language identifier.  */
9311   res.name = dwarf2_string_attr (die, DW_AT_name, cu);
9312   res.comp_dir = dwarf2_string_attr (die, DW_AT_comp_dir, cu);
9313
9314   if (res.comp_dir == NULL
9315       && producer_is_gcc_lt_4_3 (cu) && res.name != NULL
9316       && IS_ABSOLUTE_PATH (res.name))
9317     {
9318       res.comp_dir_storage = ldirname (res.name);
9319       if (!res.comp_dir_storage.empty ())
9320         res.comp_dir = res.comp_dir_storage.c_str ();
9321     }
9322   if (res.comp_dir != NULL)
9323     {
9324       /* Irix 6.2 native cc prepends <machine>.: to the compilation
9325          directory, get rid of it.  */
9326       const char *cp = strchr (res.comp_dir, ':');
9327
9328       if (cp && cp != res.comp_dir && cp[-1] == '.' && cp[1] == '/')
9329         res.comp_dir = cp + 1;
9330     }
9331
9332   if (res.name == NULL)
9333     res.name = "<unknown>";
9334
9335   return res;
9336 }
9337
9338 /* Handle DW_AT_stmt_list for a compilation unit.
9339    DIE is the DW_TAG_compile_unit die for CU.
9340    COMP_DIR is the compilation directory.  LOWPC is passed to
9341    dwarf_decode_lines.  See dwarf_decode_lines comments about it.  */
9342
9343 static void
9344 handle_DW_AT_stmt_list (struct die_info *die, struct dwarf2_cu *cu,
9345                         const char *comp_dir, CORE_ADDR lowpc) /* ARI: editCase function */
9346 {
9347   struct objfile *objfile = dwarf2_per_objfile->objfile;
9348   struct attribute *attr;
9349   struct line_header line_header_local;
9350   hashval_t line_header_local_hash;
9351   unsigned u;
9352   void **slot;
9353   int decode_mapping;
9354
9355   gdb_assert (! cu->per_cu->is_debug_types);
9356
9357   attr = dwarf2_attr (die, DW_AT_stmt_list, cu);
9358   if (attr == NULL)
9359     return;
9360
9361   sect_offset line_offset = (sect_offset) DW_UNSND (attr);
9362
9363   /* The line header hash table is only created if needed (it exists to
9364      prevent redundant reading of the line table for partial_units).
9365      If we're given a partial_unit, we'll need it.  If we're given a
9366      compile_unit, then use the line header hash table if it's already
9367      created, but don't create one just yet.  */
9368
9369   if (dwarf2_per_objfile->line_header_hash == NULL
9370       && die->tag == DW_TAG_partial_unit)
9371     {
9372       dwarf2_per_objfile->line_header_hash
9373         = htab_create_alloc_ex (127, line_header_hash_voidp,
9374                                 line_header_eq_voidp,
9375                                 free_line_header_voidp,
9376                                 &objfile->objfile_obstack,
9377                                 hashtab_obstack_allocate,
9378                                 dummy_obstack_deallocate);
9379     }
9380
9381   line_header_local.sect_off = line_offset;
9382   line_header_local.offset_in_dwz = cu->per_cu->is_dwz;
9383   line_header_local_hash = line_header_hash (&line_header_local);
9384   if (dwarf2_per_objfile->line_header_hash != NULL)
9385     {
9386       slot = htab_find_slot_with_hash (dwarf2_per_objfile->line_header_hash,
9387                                        &line_header_local,
9388                                        line_header_local_hash, NO_INSERT);
9389
9390       /* For DW_TAG_compile_unit we need info like symtab::linetable which
9391          is not present in *SLOT (since if there is something in *SLOT then
9392          it will be for a partial_unit).  */
9393       if (die->tag == DW_TAG_partial_unit && slot != NULL)
9394         {
9395           gdb_assert (*slot != NULL);
9396           cu->line_header = (struct line_header *) *slot;
9397           return;
9398         }
9399     }
9400
9401   /* dwarf_decode_line_header does not yet provide sufficient information.
9402      We always have to call also dwarf_decode_lines for it.  */
9403   line_header_up lh = dwarf_decode_line_header (line_offset, cu);
9404   if (lh == NULL)
9405     return;
9406
9407   cu->line_header = lh.release ();
9408   cu->line_header_die_owner = die;
9409
9410   if (dwarf2_per_objfile->line_header_hash == NULL)
9411     slot = NULL;
9412   else
9413     {
9414       slot = htab_find_slot_with_hash (dwarf2_per_objfile->line_header_hash,
9415                                        &line_header_local,
9416                                        line_header_local_hash, INSERT);
9417       gdb_assert (slot != NULL);
9418     }
9419   if (slot != NULL && *slot == NULL)
9420     {
9421       /* This newly decoded line number information unit will be owned
9422          by line_header_hash hash table.  */
9423       *slot = cu->line_header;
9424       cu->line_header_die_owner = NULL;
9425     }
9426   else
9427     {
9428       /* We cannot free any current entry in (*slot) as that struct line_header
9429          may be already used by multiple CUs.  Create only temporary decoded
9430          line_header for this CU - it may happen at most once for each line
9431          number information unit.  And if we're not using line_header_hash
9432          then this is what we want as well.  */
9433       gdb_assert (die->tag != DW_TAG_partial_unit);
9434     }
9435   decode_mapping = (die->tag != DW_TAG_partial_unit);
9436   dwarf_decode_lines (cu->line_header, comp_dir, cu, NULL, lowpc,
9437                       decode_mapping);
9438
9439 }
9440
9441 /* Process DW_TAG_compile_unit or DW_TAG_partial_unit.  */
9442
9443 static void
9444 read_file_scope (struct die_info *die, struct dwarf2_cu *cu)
9445 {
9446   struct objfile *objfile = dwarf2_per_objfile->objfile;
9447   struct gdbarch *gdbarch = get_objfile_arch (objfile);
9448   CORE_ADDR lowpc = ((CORE_ADDR) -1);
9449   CORE_ADDR highpc = ((CORE_ADDR) 0);
9450   struct attribute *attr;
9451   struct die_info *child_die;
9452   CORE_ADDR baseaddr;
9453
9454   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
9455
9456   get_scope_pc_bounds (die, &lowpc, &highpc, cu);
9457
9458   /* If we didn't find a lowpc, set it to highpc to avoid complaints
9459      from finish_block.  */
9460   if (lowpc == ((CORE_ADDR) -1))
9461     lowpc = highpc;
9462   lowpc = gdbarch_adjust_dwarf2_addr (gdbarch, lowpc + baseaddr);
9463
9464   file_and_directory fnd = find_file_and_directory (die, cu);
9465
9466   prepare_one_comp_unit (cu, die, cu->language);
9467
9468   /* The XLCL doesn't generate DW_LANG_OpenCL because this attribute is not
9469      standardised yet.  As a workaround for the language detection we fall
9470      back to the DW_AT_producer string.  */
9471   if (cu->producer && strstr (cu->producer, "IBM XL C for OpenCL") != NULL)
9472     cu->language = language_opencl;
9473
9474   /* Similar hack for Go.  */
9475   if (cu->producer && strstr (cu->producer, "GNU Go ") != NULL)
9476     set_cu_language (DW_LANG_Go, cu);
9477
9478   dwarf2_start_symtab (cu, fnd.name, fnd.comp_dir, lowpc);
9479
9480   /* Decode line number information if present.  We do this before
9481      processing child DIEs, so that the line header table is available
9482      for DW_AT_decl_file.  */
9483   handle_DW_AT_stmt_list (die, cu, fnd.comp_dir, lowpc);
9484
9485   /* Process all dies in compilation unit.  */
9486   if (die->child != NULL)
9487     {
9488       child_die = die->child;
9489       while (child_die && child_die->tag)
9490         {
9491           process_die (child_die, cu);
9492           child_die = sibling_die (child_die);
9493         }
9494     }
9495
9496   /* Decode macro information, if present.  Dwarf 2 macro information
9497      refers to information in the line number info statement program
9498      header, so we can only read it if we've read the header
9499      successfully.  */
9500   attr = dwarf2_attr (die, DW_AT_macros, cu);
9501   if (attr == NULL)
9502     attr = dwarf2_attr (die, DW_AT_GNU_macros, cu);
9503   if (attr && cu->line_header)
9504     {
9505       if (dwarf2_attr (die, DW_AT_macro_info, cu))
9506         complaint (&symfile_complaints,
9507                    _("CU refers to both DW_AT_macros and DW_AT_macro_info"));
9508
9509       dwarf_decode_macros (cu, DW_UNSND (attr), 1);
9510     }
9511   else
9512     {
9513       attr = dwarf2_attr (die, DW_AT_macro_info, cu);
9514       if (attr && cu->line_header)
9515         {
9516           unsigned int macro_offset = DW_UNSND (attr);
9517
9518           dwarf_decode_macros (cu, macro_offset, 0);
9519         }
9520     }
9521 }
9522
9523 /* TU version of handle_DW_AT_stmt_list for read_type_unit_scope.
9524    Create the set of symtabs used by this TU, or if this TU is sharing
9525    symtabs with another TU and the symtabs have already been created
9526    then restore those symtabs in the line header.
9527    We don't need the pc/line-number mapping for type units.  */
9528
9529 static void
9530 setup_type_unit_groups (struct die_info *die, struct dwarf2_cu *cu)
9531 {
9532   struct dwarf2_per_cu_data *per_cu = cu->per_cu;
9533   struct type_unit_group *tu_group;
9534   int first_time;
9535   struct attribute *attr;
9536   unsigned int i;
9537   struct signatured_type *sig_type;
9538
9539   gdb_assert (per_cu->is_debug_types);
9540   sig_type = (struct signatured_type *) per_cu;
9541
9542   attr = dwarf2_attr (die, DW_AT_stmt_list, cu);
9543
9544   /* If we're using .gdb_index (includes -readnow) then
9545      per_cu->type_unit_group may not have been set up yet.  */
9546   if (sig_type->type_unit_group == NULL)
9547     sig_type->type_unit_group = get_type_unit_group (cu, attr);
9548   tu_group = sig_type->type_unit_group;
9549
9550   /* If we've already processed this stmt_list there's no real need to
9551      do it again, we could fake it and just recreate the part we need
9552      (file name,index -> symtab mapping).  If data shows this optimization
9553      is useful we can do it then.  */
9554   first_time = tu_group->compunit_symtab == NULL;
9555
9556   /* We have to handle the case of both a missing DW_AT_stmt_list or bad
9557      debug info.  */
9558   line_header_up lh;
9559   if (attr != NULL)
9560     {
9561       sect_offset line_offset = (sect_offset) DW_UNSND (attr);
9562       lh = dwarf_decode_line_header (line_offset, cu);
9563     }
9564   if (lh == NULL)
9565     {
9566       if (first_time)
9567         dwarf2_start_symtab (cu, "", NULL, 0);
9568       else
9569         {
9570           gdb_assert (tu_group->symtabs == NULL);
9571           restart_symtab (tu_group->compunit_symtab, "", 0);
9572         }
9573       return;
9574     }
9575
9576   cu->line_header = lh.release ();
9577   cu->line_header_die_owner = die;
9578
9579   if (first_time)
9580     {
9581       struct compunit_symtab *cust = dwarf2_start_symtab (cu, "", NULL, 0);
9582
9583       /* Note: We don't assign tu_group->compunit_symtab yet because we're
9584          still initializing it, and our caller (a few levels up)
9585          process_full_type_unit still needs to know if this is the first
9586          time.  */
9587
9588       tu_group->num_symtabs = cu->line_header->file_names.size ();
9589       tu_group->symtabs = XNEWVEC (struct symtab *,
9590                                    cu->line_header->file_names.size ());
9591
9592       for (i = 0; i < cu->line_header->file_names.size (); ++i)
9593         {
9594           file_entry &fe = cu->line_header->file_names[i];
9595
9596           dwarf2_start_subfile (fe.name, fe.include_dir (cu->line_header));
9597
9598           if (current_subfile->symtab == NULL)
9599             {
9600               /* NOTE: start_subfile will recognize when it's been
9601                  passed a file it has already seen.  So we can't
9602                  assume there's a simple mapping from
9603                  cu->line_header->file_names to subfiles, plus
9604                  cu->line_header->file_names may contain dups.  */
9605               current_subfile->symtab
9606                 = allocate_symtab (cust, current_subfile->name);
9607             }
9608
9609           fe.symtab = current_subfile->symtab;
9610           tu_group->symtabs[i] = fe.symtab;
9611         }
9612     }
9613   else
9614     {
9615       restart_symtab (tu_group->compunit_symtab, "", 0);
9616
9617       for (i = 0; i < cu->line_header->file_names.size (); ++i)
9618         {
9619           file_entry &fe = cu->line_header->file_names[i];
9620
9621           fe.symtab = tu_group->symtabs[i];
9622         }
9623     }
9624
9625   /* The main symtab is allocated last.  Type units don't have DW_AT_name
9626      so they don't have a "real" (so to speak) symtab anyway.
9627      There is later code that will assign the main symtab to all symbols
9628      that don't have one.  We need to handle the case of a symbol with a
9629      missing symtab (DW_AT_decl_file) anyway.  */
9630 }
9631
9632 /* Process DW_TAG_type_unit.
9633    For TUs we want to skip the first top level sibling if it's not the
9634    actual type being defined by this TU.  In this case the first top
9635    level sibling is there to provide context only.  */
9636
9637 static void
9638 read_type_unit_scope (struct die_info *die, struct dwarf2_cu *cu)
9639 {
9640   struct die_info *child_die;
9641
9642   prepare_one_comp_unit (cu, die, language_minimal);
9643
9644   /* Initialize (or reinitialize) the machinery for building symtabs.
9645      We do this before processing child DIEs, so that the line header table
9646      is available for DW_AT_decl_file.  */
9647   setup_type_unit_groups (die, cu);
9648
9649   if (die->child != NULL)
9650     {
9651       child_die = die->child;
9652       while (child_die && child_die->tag)
9653         {
9654           process_die (child_die, cu);
9655           child_die = sibling_die (child_die);
9656         }
9657     }
9658 }
9659 \f
9660 /* DWO/DWP files.
9661
9662    http://gcc.gnu.org/wiki/DebugFission
9663    http://gcc.gnu.org/wiki/DebugFissionDWP
9664
9665    To simplify handling of both DWO files ("object" files with the DWARF info)
9666    and DWP files (a file with the DWOs packaged up into one file), we treat
9667    DWP files as having a collection of virtual DWO files.  */
9668
9669 static hashval_t
9670 hash_dwo_file (const void *item)
9671 {
9672   const struct dwo_file *dwo_file = (const struct dwo_file *) item;
9673   hashval_t hash;
9674
9675   hash = htab_hash_string (dwo_file->dwo_name);
9676   if (dwo_file->comp_dir != NULL)
9677     hash += htab_hash_string (dwo_file->comp_dir);
9678   return hash;
9679 }
9680
9681 static int
9682 eq_dwo_file (const void *item_lhs, const void *item_rhs)
9683 {
9684   const struct dwo_file *lhs = (const struct dwo_file *) item_lhs;
9685   const struct dwo_file *rhs = (const struct dwo_file *) item_rhs;
9686
9687   if (strcmp (lhs->dwo_name, rhs->dwo_name) != 0)
9688     return 0;
9689   if (lhs->comp_dir == NULL || rhs->comp_dir == NULL)
9690     return lhs->comp_dir == rhs->comp_dir;
9691   return strcmp (lhs->comp_dir, rhs->comp_dir) == 0;
9692 }
9693
9694 /* Allocate a hash table for DWO files.  */
9695
9696 static htab_t
9697 allocate_dwo_file_hash_table (void)
9698 {
9699   struct objfile *objfile = dwarf2_per_objfile->objfile;
9700
9701   return htab_create_alloc_ex (41,
9702                                hash_dwo_file,
9703                                eq_dwo_file,
9704                                NULL,
9705                                &objfile->objfile_obstack,
9706                                hashtab_obstack_allocate,
9707                                dummy_obstack_deallocate);
9708 }
9709
9710 /* Lookup DWO file DWO_NAME.  */
9711
9712 static void **
9713 lookup_dwo_file_slot (const char *dwo_name, const char *comp_dir)
9714 {
9715   struct dwo_file find_entry;
9716   void **slot;
9717
9718   if (dwarf2_per_objfile->dwo_files == NULL)
9719     dwarf2_per_objfile->dwo_files = allocate_dwo_file_hash_table ();
9720
9721   memset (&find_entry, 0, sizeof (find_entry));
9722   find_entry.dwo_name = dwo_name;
9723   find_entry.comp_dir = comp_dir;
9724   slot = htab_find_slot (dwarf2_per_objfile->dwo_files, &find_entry, INSERT);
9725
9726   return slot;
9727 }
9728
9729 static hashval_t
9730 hash_dwo_unit (const void *item)
9731 {
9732   const struct dwo_unit *dwo_unit = (const struct dwo_unit *) item;
9733
9734   /* This drops the top 32 bits of the id, but is ok for a hash.  */
9735   return dwo_unit->signature;
9736 }
9737
9738 static int
9739 eq_dwo_unit (const void *item_lhs, const void *item_rhs)
9740 {
9741   const struct dwo_unit *lhs = (const struct dwo_unit *) item_lhs;
9742   const struct dwo_unit *rhs = (const struct dwo_unit *) item_rhs;
9743
9744   /* The signature is assumed to be unique within the DWO file.
9745      So while object file CU dwo_id's always have the value zero,
9746      that's OK, assuming each object file DWO file has only one CU,
9747      and that's the rule for now.  */
9748   return lhs->signature == rhs->signature;
9749 }
9750
9751 /* Allocate a hash table for DWO CUs,TUs.
9752    There is one of these tables for each of CUs,TUs for each DWO file.  */
9753
9754 static htab_t
9755 allocate_dwo_unit_table (struct objfile *objfile)
9756 {
9757   /* Start out with a pretty small number.
9758      Generally DWO files contain only one CU and maybe some TUs.  */
9759   return htab_create_alloc_ex (3,
9760                                hash_dwo_unit,
9761                                eq_dwo_unit,
9762                                NULL,
9763                                &objfile->objfile_obstack,
9764                                hashtab_obstack_allocate,
9765                                dummy_obstack_deallocate);
9766 }
9767
9768 /* Structure used to pass data to create_dwo_debug_info_hash_table_reader.  */
9769
9770 struct create_dwo_cu_data
9771 {
9772   struct dwo_file *dwo_file;
9773   struct dwo_unit dwo_unit;
9774 };
9775
9776 /* die_reader_func for create_dwo_cu.  */
9777
9778 static void
9779 create_dwo_cu_reader (const struct die_reader_specs *reader,
9780                       const gdb_byte *info_ptr,
9781                       struct die_info *comp_unit_die,
9782                       int has_children,
9783                       void *datap)
9784 {
9785   struct dwarf2_cu *cu = reader->cu;
9786   sect_offset sect_off = cu->per_cu->sect_off;
9787   struct dwarf2_section_info *section = cu->per_cu->section;
9788   struct create_dwo_cu_data *data = (struct create_dwo_cu_data *) datap;
9789   struct dwo_file *dwo_file = data->dwo_file;
9790   struct dwo_unit *dwo_unit = &data->dwo_unit;
9791   struct attribute *attr;
9792
9793   attr = dwarf2_attr (comp_unit_die, DW_AT_GNU_dwo_id, cu);
9794   if (attr == NULL)
9795     {
9796       complaint (&symfile_complaints,
9797                  _("Dwarf Error: debug entry at offset 0x%x is missing"
9798                    " its dwo_id [in module %s]"),
9799                  to_underlying (sect_off), dwo_file->dwo_name);
9800       return;
9801     }
9802
9803   dwo_unit->dwo_file = dwo_file;
9804   dwo_unit->signature = DW_UNSND (attr);
9805   dwo_unit->section = section;
9806   dwo_unit->sect_off = sect_off;
9807   dwo_unit->length = cu->per_cu->length;
9808
9809   if (dwarf_read_debug)
9810     fprintf_unfiltered (gdb_stdlog, "  offset 0x%x, dwo_id %s\n",
9811                         to_underlying (sect_off),
9812                         hex_string (dwo_unit->signature));
9813 }
9814
9815 /* Create the dwo_units for the CUs in a DWO_FILE.
9816    Note: This function processes DWO files only, not DWP files.  */
9817
9818 static void
9819 create_cus_hash_table (struct dwo_file &dwo_file, dwarf2_section_info &section,
9820                        htab_t &cus_htab)
9821 {
9822   struct objfile *objfile = dwarf2_per_objfile->objfile;
9823   const struct dwarf2_section_info *abbrev_section = &dwo_file.sections.abbrev;
9824   const gdb_byte *info_ptr, *end_ptr;
9825
9826   dwarf2_read_section (objfile, &section);
9827   info_ptr = section.buffer;
9828
9829   if (info_ptr == NULL)
9830     return;
9831
9832   if (dwarf_read_debug)
9833     {
9834       fprintf_unfiltered (gdb_stdlog, "Reading %s for %s:\n",
9835                           get_section_name (&section),
9836                           get_section_file_name (&section));
9837     }
9838
9839   end_ptr = info_ptr + section.size;
9840   while (info_ptr < end_ptr)
9841     {
9842       struct dwarf2_per_cu_data per_cu;
9843       struct create_dwo_cu_data create_dwo_cu_data;
9844       struct dwo_unit *dwo_unit;
9845       void **slot;
9846       sect_offset sect_off = (sect_offset) (info_ptr - section.buffer);
9847
9848       memset (&create_dwo_cu_data.dwo_unit, 0,
9849               sizeof (create_dwo_cu_data.dwo_unit));
9850       memset (&per_cu, 0, sizeof (per_cu));
9851       per_cu.objfile = objfile;
9852       per_cu.is_debug_types = 0;
9853       per_cu.sect_off = sect_offset (info_ptr - section.buffer);
9854       per_cu.section = &section;
9855       create_dwo_cu_data.dwo_file = &dwo_file;
9856
9857       init_cutu_and_read_dies_no_follow (
9858           &per_cu, &dwo_file, create_dwo_cu_reader, &create_dwo_cu_data);
9859       info_ptr += per_cu.length;
9860
9861       // If the unit could not be parsed, skip it.
9862       if (create_dwo_cu_data.dwo_unit.dwo_file == NULL)
9863         continue;
9864
9865       if (cus_htab == NULL)
9866         cus_htab = allocate_dwo_unit_table (objfile);
9867
9868       dwo_unit = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_unit);
9869       *dwo_unit = create_dwo_cu_data.dwo_unit;
9870       slot = htab_find_slot (cus_htab, dwo_unit, INSERT);
9871       gdb_assert (slot != NULL);
9872       if (*slot != NULL)
9873         {
9874           const struct dwo_unit *dup_cu = (const struct dwo_unit *)*slot;
9875           sect_offset dup_sect_off = dup_cu->sect_off;
9876
9877           complaint (&symfile_complaints,
9878                      _("debug cu entry at offset 0x%x is duplicate to"
9879                        " the entry at offset 0x%x, signature %s"),
9880                      to_underlying (sect_off), to_underlying (dup_sect_off),
9881                      hex_string (dwo_unit->signature));
9882         }
9883       *slot = (void *)dwo_unit;
9884     }
9885 }
9886
9887 /* DWP file .debug_{cu,tu}_index section format:
9888    [ref: http://gcc.gnu.org/wiki/DebugFissionDWP]
9889
9890    DWP Version 1:
9891
9892    Both index sections have the same format, and serve to map a 64-bit
9893    signature to a set of section numbers.  Each section begins with a header,
9894    followed by a hash table of 64-bit signatures, a parallel table of 32-bit
9895    indexes, and a pool of 32-bit section numbers.  The index sections will be
9896    aligned at 8-byte boundaries in the file.
9897
9898    The index section header consists of:
9899
9900     V, 32 bit version number
9901     -, 32 bits unused
9902     N, 32 bit number of compilation units or type units in the index
9903     M, 32 bit number of slots in the hash table
9904
9905    Numbers are recorded using the byte order of the application binary.
9906
9907    The hash table begins at offset 16 in the section, and consists of an array
9908    of M 64-bit slots.  Each slot contains a 64-bit signature (using the byte
9909    order of the application binary).  Unused slots in the hash table are 0.
9910    (We rely on the extreme unlikeliness of a signature being exactly 0.)
9911
9912    The parallel table begins immediately after the hash table
9913    (at offset 16 + 8 * M from the beginning of the section), and consists of an
9914    array of 32-bit indexes (using the byte order of the application binary),
9915    corresponding 1-1 with slots in the hash table.  Each entry in the parallel
9916    table contains a 32-bit index into the pool of section numbers.  For unused
9917    hash table slots, the corresponding entry in the parallel table will be 0.
9918
9919    The pool of section numbers begins immediately following the hash table
9920    (at offset 16 + 12 * M from the beginning of the section).  The pool of
9921    section numbers consists of an array of 32-bit words (using the byte order
9922    of the application binary).  Each item in the array is indexed starting
9923    from 0.  The hash table entry provides the index of the first section
9924    number in the set.  Additional section numbers in the set follow, and the
9925    set is terminated by a 0 entry (section number 0 is not used in ELF).
9926
9927    In each set of section numbers, the .debug_info.dwo or .debug_types.dwo
9928    section must be the first entry in the set, and the .debug_abbrev.dwo must
9929    be the second entry. Other members of the set may follow in any order.
9930
9931    ---
9932
9933    DWP Version 2:
9934
9935    DWP Version 2 combines all the .debug_info, etc. sections into one,
9936    and the entries in the index tables are now offsets into these sections.
9937    CU offsets begin at 0.  TU offsets begin at the size of the .debug_info
9938    section.
9939
9940    Index Section Contents:
9941     Header
9942     Hash Table of Signatures   dwp_hash_table.hash_table
9943     Parallel Table of Indices  dwp_hash_table.unit_table
9944     Table of Section Offsets   dwp_hash_table.v2.{section_ids,offsets}
9945     Table of Section Sizes     dwp_hash_table.v2.sizes
9946
9947    The index section header consists of:
9948
9949     V, 32 bit version number
9950     L, 32 bit number of columns in the table of section offsets
9951     N, 32 bit number of compilation units or type units in the index
9952     M, 32 bit number of slots in the hash table
9953
9954    Numbers are recorded using the byte order of the application binary.
9955
9956    The hash table has the same format as version 1.
9957    The parallel table of indices has the same format as version 1,
9958    except that the entries are origin-1 indices into the table of sections
9959    offsets and the table of section sizes.
9960
9961    The table of offsets begins immediately following the parallel table
9962    (at offset 16 + 12 * M from the beginning of the section).  The table is
9963    a two-dimensional array of 32-bit words (using the byte order of the
9964    application binary), with L columns and N+1 rows, in row-major order.
9965    Each row in the array is indexed starting from 0.  The first row provides
9966    a key to the remaining rows: each column in this row provides an identifier
9967    for a debug section, and the offsets in the same column of subsequent rows
9968    refer to that section.  The section identifiers are:
9969
9970     DW_SECT_INFO         1  .debug_info.dwo
9971     DW_SECT_TYPES        2  .debug_types.dwo
9972     DW_SECT_ABBREV       3  .debug_abbrev.dwo
9973     DW_SECT_LINE         4  .debug_line.dwo
9974     DW_SECT_LOC          5  .debug_loc.dwo
9975     DW_SECT_STR_OFFSETS  6  .debug_str_offsets.dwo
9976     DW_SECT_MACINFO      7  .debug_macinfo.dwo
9977     DW_SECT_MACRO        8  .debug_macro.dwo
9978
9979    The offsets provided by the CU and TU index sections are the base offsets
9980    for the contributions made by each CU or TU to the corresponding section
9981    in the package file.  Each CU and TU header contains an abbrev_offset
9982    field, used to find the abbreviations table for that CU or TU within the
9983    contribution to the .debug_abbrev.dwo section for that CU or TU, and should
9984    be interpreted as relative to the base offset given in the index section.
9985    Likewise, offsets into .debug_line.dwo from DW_AT_stmt_list attributes
9986    should be interpreted as relative to the base offset for .debug_line.dwo,
9987    and offsets into other debug sections obtained from DWARF attributes should
9988    also be interpreted as relative to the corresponding base offset.
9989
9990    The table of sizes begins immediately following the table of offsets.
9991    Like the table of offsets, it is a two-dimensional array of 32-bit words,
9992    with L columns and N rows, in row-major order.  Each row in the array is
9993    indexed starting from 1 (row 0 is shared by the two tables).
9994
9995    ---
9996
9997    Hash table lookup is handled the same in version 1 and 2:
9998
9999    We assume that N and M will not exceed 2^32 - 1.
10000    The size of the hash table, M, must be 2^k such that 2^k > 3*N/2.
10001
10002    Given a 64-bit compilation unit signature or a type signature S, an entry
10003    in the hash table is located as follows:
10004
10005    1) Calculate a primary hash H = S & MASK(k), where MASK(k) is a mask with
10006       the low-order k bits all set to 1.
10007
10008    2) Calculate a secondary hash H' = (((S >> 32) & MASK(k)) | 1).
10009
10010    3) If the hash table entry at index H matches the signature, use that
10011       entry.  If the hash table entry at index H is unused (all zeroes),
10012       terminate the search: the signature is not present in the table.
10013
10014    4) Let H = (H + H') modulo M. Repeat at Step 3.
10015
10016    Because M > N and H' and M are relatively prime, the search is guaranteed
10017    to stop at an unused slot or find the match.  */
10018
10019 /* Create a hash table to map DWO IDs to their CU/TU entry in
10020    .debug_{info,types}.dwo in DWP_FILE.
10021    Returns NULL if there isn't one.
10022    Note: This function processes DWP files only, not DWO files.  */
10023
10024 static struct dwp_hash_table *
10025 create_dwp_hash_table (struct dwp_file *dwp_file, int is_debug_types)
10026 {
10027   struct objfile *objfile = dwarf2_per_objfile->objfile;
10028   bfd *dbfd = dwp_file->dbfd;
10029   const gdb_byte *index_ptr, *index_end;
10030   struct dwarf2_section_info *index;
10031   uint32_t version, nr_columns, nr_units, nr_slots;
10032   struct dwp_hash_table *htab;
10033
10034   if (is_debug_types)
10035     index = &dwp_file->sections.tu_index;
10036   else
10037     index = &dwp_file->sections.cu_index;
10038
10039   if (dwarf2_section_empty_p (index))
10040     return NULL;
10041   dwarf2_read_section (objfile, index);
10042
10043   index_ptr = index->buffer;
10044   index_end = index_ptr + index->size;
10045
10046   version = read_4_bytes (dbfd, index_ptr);
10047   index_ptr += 4;
10048   if (version == 2)
10049     nr_columns = read_4_bytes (dbfd, index_ptr);
10050   else
10051     nr_columns = 0;
10052   index_ptr += 4;
10053   nr_units = read_4_bytes (dbfd, index_ptr);
10054   index_ptr += 4;
10055   nr_slots = read_4_bytes (dbfd, index_ptr);
10056   index_ptr += 4;
10057
10058   if (version != 1 && version != 2)
10059     {
10060       error (_("Dwarf Error: unsupported DWP file version (%s)"
10061                " [in module %s]"),
10062              pulongest (version), dwp_file->name);
10063     }
10064   if (nr_slots != (nr_slots & -nr_slots))
10065     {
10066       error (_("Dwarf Error: number of slots in DWP hash table (%s)"
10067                " is not power of 2 [in module %s]"),
10068              pulongest (nr_slots), dwp_file->name);
10069     }
10070
10071   htab = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwp_hash_table);
10072   htab->version = version;
10073   htab->nr_columns = nr_columns;
10074   htab->nr_units = nr_units;
10075   htab->nr_slots = nr_slots;
10076   htab->hash_table = index_ptr;
10077   htab->unit_table = htab->hash_table + sizeof (uint64_t) * nr_slots;
10078
10079   /* Exit early if the table is empty.  */
10080   if (nr_slots == 0 || nr_units == 0
10081       || (version == 2 && nr_columns == 0))
10082     {
10083       /* All must be zero.  */
10084       if (nr_slots != 0 || nr_units != 0
10085           || (version == 2 && nr_columns != 0))
10086         {
10087           complaint (&symfile_complaints,
10088                      _("Empty DWP but nr_slots,nr_units,nr_columns not"
10089                        " all zero [in modules %s]"),
10090                      dwp_file->name);
10091         }
10092       return htab;
10093     }
10094
10095   if (version == 1)
10096     {
10097       htab->section_pool.v1.indices =
10098         htab->unit_table + sizeof (uint32_t) * nr_slots;
10099       /* It's harder to decide whether the section is too small in v1.
10100          V1 is deprecated anyway so we punt.  */
10101     }
10102   else
10103     {
10104       const gdb_byte *ids_ptr = htab->unit_table + sizeof (uint32_t) * nr_slots;
10105       int *ids = htab->section_pool.v2.section_ids;
10106       /* Reverse map for error checking.  */
10107       int ids_seen[DW_SECT_MAX + 1];
10108       int i;
10109
10110       if (nr_columns < 2)
10111         {
10112           error (_("Dwarf Error: bad DWP hash table, too few columns"
10113                    " in section table [in module %s]"),
10114                  dwp_file->name);
10115         }
10116       if (nr_columns > MAX_NR_V2_DWO_SECTIONS)
10117         {
10118           error (_("Dwarf Error: bad DWP hash table, too many columns"
10119                    " in section table [in module %s]"),
10120                  dwp_file->name);
10121         }
10122       memset (ids, 255, (DW_SECT_MAX + 1) * sizeof (int32_t));
10123       memset (ids_seen, 255, (DW_SECT_MAX + 1) * sizeof (int32_t));
10124       for (i = 0; i < nr_columns; ++i)
10125         {
10126           int id = read_4_bytes (dbfd, ids_ptr + i * sizeof (uint32_t));
10127
10128           if (id < DW_SECT_MIN || id > DW_SECT_MAX)
10129             {
10130               error (_("Dwarf Error: bad DWP hash table, bad section id %d"
10131                        " in section table [in module %s]"),
10132                      id, dwp_file->name);
10133             }
10134           if (ids_seen[id] != -1)
10135             {
10136               error (_("Dwarf Error: bad DWP hash table, duplicate section"
10137                        " id %d in section table [in module %s]"),
10138                      id, dwp_file->name);
10139             }
10140           ids_seen[id] = i;
10141           ids[i] = id;
10142         }
10143       /* Must have exactly one info or types section.  */
10144       if (((ids_seen[DW_SECT_INFO] != -1)
10145            + (ids_seen[DW_SECT_TYPES] != -1))
10146           != 1)
10147         {
10148           error (_("Dwarf Error: bad DWP hash table, missing/duplicate"
10149                    " DWO info/types section [in module %s]"),
10150                  dwp_file->name);
10151         }
10152       /* Must have an abbrev section.  */
10153       if (ids_seen[DW_SECT_ABBREV] == -1)
10154         {
10155           error (_("Dwarf Error: bad DWP hash table, missing DWO abbrev"
10156                    " section [in module %s]"),
10157                  dwp_file->name);
10158         }
10159       htab->section_pool.v2.offsets = ids_ptr + sizeof (uint32_t) * nr_columns;
10160       htab->section_pool.v2.sizes =
10161         htab->section_pool.v2.offsets + (sizeof (uint32_t)
10162                                          * nr_units * nr_columns);
10163       if ((htab->section_pool.v2.sizes + (sizeof (uint32_t)
10164                                           * nr_units * nr_columns))
10165           > index_end)
10166         {
10167           error (_("Dwarf Error: DWP index section is corrupt (too small)"
10168                    " [in module %s]"),
10169                  dwp_file->name);
10170         }
10171     }
10172
10173   return htab;
10174 }
10175
10176 /* Update SECTIONS with the data from SECTP.
10177
10178    This function is like the other "locate" section routines that are
10179    passed to bfd_map_over_sections, but in this context the sections to
10180    read comes from the DWP V1 hash table, not the full ELF section table.
10181
10182    The result is non-zero for success, or zero if an error was found.  */
10183
10184 static int
10185 locate_v1_virtual_dwo_sections (asection *sectp,
10186                                 struct virtual_v1_dwo_sections *sections)
10187 {
10188   const struct dwop_section_names *names = &dwop_section_names;
10189
10190   if (section_is_p (sectp->name, &names->abbrev_dwo))
10191     {
10192       /* There can be only one.  */
10193       if (sections->abbrev.s.section != NULL)
10194         return 0;
10195       sections->abbrev.s.section = sectp;
10196       sections->abbrev.size = bfd_get_section_size (sectp);
10197     }
10198   else if (section_is_p (sectp->name, &names->info_dwo)
10199            || section_is_p (sectp->name, &names->types_dwo))
10200     {
10201       /* There can be only one.  */
10202       if (sections->info_or_types.s.section != NULL)
10203         return 0;
10204       sections->info_or_types.s.section = sectp;
10205       sections->info_or_types.size = bfd_get_section_size (sectp);
10206     }
10207   else if (section_is_p (sectp->name, &names->line_dwo))
10208     {
10209       /* There can be only one.  */
10210       if (sections->line.s.section != NULL)
10211         return 0;
10212       sections->line.s.section = sectp;
10213       sections->line.size = bfd_get_section_size (sectp);
10214     }
10215   else if (section_is_p (sectp->name, &names->loc_dwo))
10216     {
10217       /* There can be only one.  */
10218       if (sections->loc.s.section != NULL)
10219         return 0;
10220       sections->loc.s.section = sectp;
10221       sections->loc.size = bfd_get_section_size (sectp);
10222     }
10223   else if (section_is_p (sectp->name, &names->macinfo_dwo))
10224     {
10225       /* There can be only one.  */
10226       if (sections->macinfo.s.section != NULL)
10227         return 0;
10228       sections->macinfo.s.section = sectp;
10229       sections->macinfo.size = bfd_get_section_size (sectp);
10230     }
10231   else if (section_is_p (sectp->name, &names->macro_dwo))
10232     {
10233       /* There can be only one.  */
10234       if (sections->macro.s.section != NULL)
10235         return 0;
10236       sections->macro.s.section = sectp;
10237       sections->macro.size = bfd_get_section_size (sectp);
10238     }
10239   else if (section_is_p (sectp->name, &names->str_offsets_dwo))
10240     {
10241       /* There can be only one.  */
10242       if (sections->str_offsets.s.section != NULL)
10243         return 0;
10244       sections->str_offsets.s.section = sectp;
10245       sections->str_offsets.size = bfd_get_section_size (sectp);
10246     }
10247   else
10248     {
10249       /* No other kind of section is valid.  */
10250       return 0;
10251     }
10252
10253   return 1;
10254 }
10255
10256 /* Create a dwo_unit object for the DWO unit with signature SIGNATURE.
10257    UNIT_INDEX is the index of the DWO unit in the DWP hash table.
10258    COMP_DIR is the DW_AT_comp_dir attribute of the referencing CU.
10259    This is for DWP version 1 files.  */
10260
10261 static struct dwo_unit *
10262 create_dwo_unit_in_dwp_v1 (struct dwp_file *dwp_file,
10263                            uint32_t unit_index,
10264                            const char *comp_dir,
10265                            ULONGEST signature, int is_debug_types)
10266 {
10267   struct objfile *objfile = dwarf2_per_objfile->objfile;
10268   const struct dwp_hash_table *dwp_htab =
10269     is_debug_types ? dwp_file->tus : dwp_file->cus;
10270   bfd *dbfd = dwp_file->dbfd;
10271   const char *kind = is_debug_types ? "TU" : "CU";
10272   struct dwo_file *dwo_file;
10273   struct dwo_unit *dwo_unit;
10274   struct virtual_v1_dwo_sections sections;
10275   void **dwo_file_slot;
10276   char *virtual_dwo_name;
10277   struct cleanup *cleanups;
10278   int i;
10279
10280   gdb_assert (dwp_file->version == 1);
10281
10282   if (dwarf_read_debug)
10283     {
10284       fprintf_unfiltered (gdb_stdlog, "Reading %s %s/%s in DWP V1 file: %s\n",
10285                           kind,
10286                           pulongest (unit_index), hex_string (signature),
10287                           dwp_file->name);
10288     }
10289
10290   /* Fetch the sections of this DWO unit.
10291      Put a limit on the number of sections we look for so that bad data
10292      doesn't cause us to loop forever.  */
10293
10294 #define MAX_NR_V1_DWO_SECTIONS \
10295   (1 /* .debug_info or .debug_types */ \
10296    + 1 /* .debug_abbrev */ \
10297    + 1 /* .debug_line */ \
10298    + 1 /* .debug_loc */ \
10299    + 1 /* .debug_str_offsets */ \
10300    + 1 /* .debug_macro or .debug_macinfo */ \
10301    + 1 /* trailing zero */)
10302
10303   memset (&sections, 0, sizeof (sections));
10304   cleanups = make_cleanup (null_cleanup, 0);
10305
10306   for (i = 0; i < MAX_NR_V1_DWO_SECTIONS; ++i)
10307     {
10308       asection *sectp;
10309       uint32_t section_nr =
10310         read_4_bytes (dbfd,
10311                       dwp_htab->section_pool.v1.indices
10312                       + (unit_index + i) * sizeof (uint32_t));
10313
10314       if (section_nr == 0)
10315         break;
10316       if (section_nr >= dwp_file->num_sections)
10317         {
10318           error (_("Dwarf Error: bad DWP hash table, section number too large"
10319                    " [in module %s]"),
10320                  dwp_file->name);
10321         }
10322
10323       sectp = dwp_file->elf_sections[section_nr];
10324       if (! locate_v1_virtual_dwo_sections (sectp, &sections))
10325         {
10326           error (_("Dwarf Error: bad DWP hash table, invalid section found"
10327                    " [in module %s]"),
10328                  dwp_file->name);
10329         }
10330     }
10331
10332   if (i < 2
10333       || dwarf2_section_empty_p (&sections.info_or_types)
10334       || dwarf2_section_empty_p (&sections.abbrev))
10335     {
10336       error (_("Dwarf Error: bad DWP hash table, missing DWO sections"
10337                " [in module %s]"),
10338              dwp_file->name);
10339     }
10340   if (i == MAX_NR_V1_DWO_SECTIONS)
10341     {
10342       error (_("Dwarf Error: bad DWP hash table, too many DWO sections"
10343                " [in module %s]"),
10344              dwp_file->name);
10345     }
10346
10347   /* It's easier for the rest of the code if we fake a struct dwo_file and
10348      have dwo_unit "live" in that.  At least for now.
10349
10350      The DWP file can be made up of a random collection of CUs and TUs.
10351      However, for each CU + set of TUs that came from the same original DWO
10352      file, we can combine them back into a virtual DWO file to save space
10353      (fewer struct dwo_file objects to allocate).  Remember that for really
10354      large apps there can be on the order of 8K CUs and 200K TUs, or more.  */
10355
10356   virtual_dwo_name =
10357     xstrprintf ("virtual-dwo/%d-%d-%d-%d",
10358                 get_section_id (&sections.abbrev),
10359                 get_section_id (&sections.line),
10360                 get_section_id (&sections.loc),
10361                 get_section_id (&sections.str_offsets));
10362   make_cleanup (xfree, virtual_dwo_name);
10363   /* Can we use an existing virtual DWO file?  */
10364   dwo_file_slot = lookup_dwo_file_slot (virtual_dwo_name, comp_dir);
10365   /* Create one if necessary.  */
10366   if (*dwo_file_slot == NULL)
10367     {
10368       if (dwarf_read_debug)
10369         {
10370           fprintf_unfiltered (gdb_stdlog, "Creating virtual DWO: %s\n",
10371                               virtual_dwo_name);
10372         }
10373       dwo_file = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_file);
10374       dwo_file->dwo_name
10375         = (const char *) obstack_copy0 (&objfile->objfile_obstack,
10376                                         virtual_dwo_name,
10377                                         strlen (virtual_dwo_name));
10378       dwo_file->comp_dir = comp_dir;
10379       dwo_file->sections.abbrev = sections.abbrev;
10380       dwo_file->sections.line = sections.line;
10381       dwo_file->sections.loc = sections.loc;
10382       dwo_file->sections.macinfo = sections.macinfo;
10383       dwo_file->sections.macro = sections.macro;
10384       dwo_file->sections.str_offsets = sections.str_offsets;
10385       /* The "str" section is global to the entire DWP file.  */
10386       dwo_file->sections.str = dwp_file->sections.str;
10387       /* The info or types section is assigned below to dwo_unit,
10388          there's no need to record it in dwo_file.
10389          Also, we can't simply record type sections in dwo_file because
10390          we record a pointer into the vector in dwo_unit.  As we collect more
10391          types we'll grow the vector and eventually have to reallocate space
10392          for it, invalidating all copies of pointers into the previous
10393          contents.  */
10394       *dwo_file_slot = dwo_file;
10395     }
10396   else
10397     {
10398       if (dwarf_read_debug)
10399         {
10400           fprintf_unfiltered (gdb_stdlog, "Using existing virtual DWO: %s\n",
10401                               virtual_dwo_name);
10402         }
10403       dwo_file = (struct dwo_file *) *dwo_file_slot;
10404     }
10405   do_cleanups (cleanups);
10406
10407   dwo_unit = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_unit);
10408   dwo_unit->dwo_file = dwo_file;
10409   dwo_unit->signature = signature;
10410   dwo_unit->section =
10411     XOBNEW (&objfile->objfile_obstack, struct dwarf2_section_info);
10412   *dwo_unit->section = sections.info_or_types;
10413   /* dwo_unit->{offset,length,type_offset_in_tu} are set later.  */
10414
10415   return dwo_unit;
10416 }
10417
10418 /* Subroutine of create_dwo_unit_in_dwp_v2 to simplify it.
10419    Given a pointer to the containing section SECTION, and OFFSET,SIZE of the
10420    piece within that section used by a TU/CU, return a virtual section
10421    of just that piece.  */
10422
10423 static struct dwarf2_section_info
10424 create_dwp_v2_section (struct dwarf2_section_info *section,
10425                        bfd_size_type offset, bfd_size_type size)
10426 {
10427   struct dwarf2_section_info result;
10428   asection *sectp;
10429
10430   gdb_assert (section != NULL);
10431   gdb_assert (!section->is_virtual);
10432
10433   memset (&result, 0, sizeof (result));
10434   result.s.containing_section = section;
10435   result.is_virtual = 1;
10436
10437   if (size == 0)
10438     return result;
10439
10440   sectp = get_section_bfd_section (section);
10441
10442   /* Flag an error if the piece denoted by OFFSET,SIZE is outside the
10443      bounds of the real section.  This is a pretty-rare event, so just
10444      flag an error (easier) instead of a warning and trying to cope.  */
10445   if (sectp == NULL
10446       || offset + size > bfd_get_section_size (sectp))
10447     {
10448       bfd *abfd = sectp->owner;
10449
10450       error (_("Dwarf Error: Bad DWP V2 section info, doesn't fit"
10451                " in section %s [in module %s]"),
10452              sectp ? bfd_section_name (abfd, sectp) : "<unknown>",
10453              objfile_name (dwarf2_per_objfile->objfile));
10454     }
10455
10456   result.virtual_offset = offset;
10457   result.size = size;
10458   return result;
10459 }
10460
10461 /* Create a dwo_unit object for the DWO unit with signature SIGNATURE.
10462    UNIT_INDEX is the index of the DWO unit in the DWP hash table.
10463    COMP_DIR is the DW_AT_comp_dir attribute of the referencing CU.
10464    This is for DWP version 2 files.  */
10465
10466 static struct dwo_unit *
10467 create_dwo_unit_in_dwp_v2 (struct dwp_file *dwp_file,
10468                            uint32_t unit_index,
10469                            const char *comp_dir,
10470                            ULONGEST signature, int is_debug_types)
10471 {
10472   struct objfile *objfile = dwarf2_per_objfile->objfile;
10473   const struct dwp_hash_table *dwp_htab =
10474     is_debug_types ? dwp_file->tus : dwp_file->cus;
10475   bfd *dbfd = dwp_file->dbfd;
10476   const char *kind = is_debug_types ? "TU" : "CU";
10477   struct dwo_file *dwo_file;
10478   struct dwo_unit *dwo_unit;
10479   struct virtual_v2_dwo_sections sections;
10480   void **dwo_file_slot;
10481   char *virtual_dwo_name;
10482   struct cleanup *cleanups;
10483   int i;
10484
10485   gdb_assert (dwp_file->version == 2);
10486
10487   if (dwarf_read_debug)
10488     {
10489       fprintf_unfiltered (gdb_stdlog, "Reading %s %s/%s in DWP V2 file: %s\n",
10490                           kind,
10491                           pulongest (unit_index), hex_string (signature),
10492                           dwp_file->name);
10493     }
10494
10495   /* Fetch the section offsets of this DWO unit.  */
10496
10497   memset (&sections, 0, sizeof (sections));
10498   cleanups = make_cleanup (null_cleanup, 0);
10499
10500   for (i = 0; i < dwp_htab->nr_columns; ++i)
10501     {
10502       uint32_t offset = read_4_bytes (dbfd,
10503                                       dwp_htab->section_pool.v2.offsets
10504                                       + (((unit_index - 1) * dwp_htab->nr_columns
10505                                           + i)
10506                                          * sizeof (uint32_t)));
10507       uint32_t size = read_4_bytes (dbfd,
10508                                     dwp_htab->section_pool.v2.sizes
10509                                     + (((unit_index - 1) * dwp_htab->nr_columns
10510                                         + i)
10511                                        * sizeof (uint32_t)));
10512
10513       switch (dwp_htab->section_pool.v2.section_ids[i])
10514         {
10515         case DW_SECT_INFO:
10516         case DW_SECT_TYPES:
10517           sections.info_or_types_offset = offset;
10518           sections.info_or_types_size = size;
10519           break;
10520         case DW_SECT_ABBREV:
10521           sections.abbrev_offset = offset;
10522           sections.abbrev_size = size;
10523           break;
10524         case DW_SECT_LINE:
10525           sections.line_offset = offset;
10526           sections.line_size = size;
10527           break;
10528         case DW_SECT_LOC:
10529           sections.loc_offset = offset;
10530           sections.loc_size = size;
10531           break;
10532         case DW_SECT_STR_OFFSETS:
10533           sections.str_offsets_offset = offset;
10534           sections.str_offsets_size = size;
10535           break;
10536         case DW_SECT_MACINFO:
10537           sections.macinfo_offset = offset;
10538           sections.macinfo_size = size;
10539           break;
10540         case DW_SECT_MACRO:
10541           sections.macro_offset = offset;
10542           sections.macro_size = size;
10543           break;
10544         }
10545     }
10546
10547   /* It's easier for the rest of the code if we fake a struct dwo_file and
10548      have dwo_unit "live" in that.  At least for now.
10549
10550      The DWP file can be made up of a random collection of CUs and TUs.
10551      However, for each CU + set of TUs that came from the same original DWO
10552      file, we can combine them back into a virtual DWO file to save space
10553      (fewer struct dwo_file objects to allocate).  Remember that for really
10554      large apps there can be on the order of 8K CUs and 200K TUs, or more.  */
10555
10556   virtual_dwo_name =
10557     xstrprintf ("virtual-dwo/%ld-%ld-%ld-%ld",
10558                 (long) (sections.abbrev_size ? sections.abbrev_offset : 0),
10559                 (long) (sections.line_size ? sections.line_offset : 0),
10560                 (long) (sections.loc_size ? sections.loc_offset : 0),
10561                 (long) (sections.str_offsets_size
10562                         ? sections.str_offsets_offset : 0));
10563   make_cleanup (xfree, virtual_dwo_name);
10564   /* Can we use an existing virtual DWO file?  */
10565   dwo_file_slot = lookup_dwo_file_slot (virtual_dwo_name, comp_dir);
10566   /* Create one if necessary.  */
10567   if (*dwo_file_slot == NULL)
10568     {
10569       if (dwarf_read_debug)
10570         {
10571           fprintf_unfiltered (gdb_stdlog, "Creating virtual DWO: %s\n",
10572                               virtual_dwo_name);
10573         }
10574       dwo_file = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_file);
10575       dwo_file->dwo_name
10576         = (const char *) obstack_copy0 (&objfile->objfile_obstack,
10577                                         virtual_dwo_name,
10578                                         strlen (virtual_dwo_name));
10579       dwo_file->comp_dir = comp_dir;
10580       dwo_file->sections.abbrev =
10581         create_dwp_v2_section (&dwp_file->sections.abbrev,
10582                                sections.abbrev_offset, sections.abbrev_size);
10583       dwo_file->sections.line =
10584         create_dwp_v2_section (&dwp_file->sections.line,
10585                                sections.line_offset, sections.line_size);
10586       dwo_file->sections.loc =
10587         create_dwp_v2_section (&dwp_file->sections.loc,
10588                                sections.loc_offset, sections.loc_size);
10589       dwo_file->sections.macinfo =
10590         create_dwp_v2_section (&dwp_file->sections.macinfo,
10591                                sections.macinfo_offset, sections.macinfo_size);
10592       dwo_file->sections.macro =
10593         create_dwp_v2_section (&dwp_file->sections.macro,
10594                                sections.macro_offset, sections.macro_size);
10595       dwo_file->sections.str_offsets =
10596         create_dwp_v2_section (&dwp_file->sections.str_offsets,
10597                                sections.str_offsets_offset,
10598                                sections.str_offsets_size);
10599       /* The "str" section is global to the entire DWP file.  */
10600       dwo_file->sections.str = dwp_file->sections.str;
10601       /* The info or types section is assigned below to dwo_unit,
10602          there's no need to record it in dwo_file.
10603          Also, we can't simply record type sections in dwo_file because
10604          we record a pointer into the vector in dwo_unit.  As we collect more
10605          types we'll grow the vector and eventually have to reallocate space
10606          for it, invalidating all copies of pointers into the previous
10607          contents.  */
10608       *dwo_file_slot = dwo_file;
10609     }
10610   else
10611     {
10612       if (dwarf_read_debug)
10613         {
10614           fprintf_unfiltered (gdb_stdlog, "Using existing virtual DWO: %s\n",
10615                               virtual_dwo_name);
10616         }
10617       dwo_file = (struct dwo_file *) *dwo_file_slot;
10618     }
10619   do_cleanups (cleanups);
10620
10621   dwo_unit = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_unit);
10622   dwo_unit->dwo_file = dwo_file;
10623   dwo_unit->signature = signature;
10624   dwo_unit->section =
10625     XOBNEW (&objfile->objfile_obstack, struct dwarf2_section_info);
10626   *dwo_unit->section = create_dwp_v2_section (is_debug_types
10627                                               ? &dwp_file->sections.types
10628                                               : &dwp_file->sections.info,
10629                                               sections.info_or_types_offset,
10630                                               sections.info_or_types_size);
10631   /* dwo_unit->{offset,length,type_offset_in_tu} are set later.  */
10632
10633   return dwo_unit;
10634 }
10635
10636 /* Lookup the DWO unit with SIGNATURE in DWP_FILE.
10637    Returns NULL if the signature isn't found.  */
10638
10639 static struct dwo_unit *
10640 lookup_dwo_unit_in_dwp (struct dwp_file *dwp_file, const char *comp_dir,
10641                         ULONGEST signature, int is_debug_types)
10642 {
10643   const struct dwp_hash_table *dwp_htab =
10644     is_debug_types ? dwp_file->tus : dwp_file->cus;
10645   bfd *dbfd = dwp_file->dbfd;
10646   uint32_t mask = dwp_htab->nr_slots - 1;
10647   uint32_t hash = signature & mask;
10648   uint32_t hash2 = ((signature >> 32) & mask) | 1;
10649   unsigned int i;
10650   void **slot;
10651   struct dwo_unit find_dwo_cu;
10652
10653   memset (&find_dwo_cu, 0, sizeof (find_dwo_cu));
10654   find_dwo_cu.signature = signature;
10655   slot = htab_find_slot (is_debug_types
10656                          ? dwp_file->loaded_tus
10657                          : dwp_file->loaded_cus,
10658                          &find_dwo_cu, INSERT);
10659
10660   if (*slot != NULL)
10661     return (struct dwo_unit *) *slot;
10662
10663   /* Use a for loop so that we don't loop forever on bad debug info.  */
10664   for (i = 0; i < dwp_htab->nr_slots; ++i)
10665     {
10666       ULONGEST signature_in_table;
10667
10668       signature_in_table =
10669         read_8_bytes (dbfd, dwp_htab->hash_table + hash * sizeof (uint64_t));
10670       if (signature_in_table == signature)
10671         {
10672           uint32_t unit_index =
10673             read_4_bytes (dbfd,
10674                           dwp_htab->unit_table + hash * sizeof (uint32_t));
10675
10676           if (dwp_file->version == 1)
10677             {
10678               *slot = create_dwo_unit_in_dwp_v1 (dwp_file, unit_index,
10679                                                  comp_dir, signature,
10680                                                  is_debug_types);
10681             }
10682           else
10683             {
10684               *slot = create_dwo_unit_in_dwp_v2 (dwp_file, unit_index,
10685                                                  comp_dir, signature,
10686                                                  is_debug_types);
10687             }
10688           return (struct dwo_unit *) *slot;
10689         }
10690       if (signature_in_table == 0)
10691         return NULL;
10692       hash = (hash + hash2) & mask;
10693     }
10694
10695   error (_("Dwarf Error: bad DWP hash table, lookup didn't terminate"
10696            " [in module %s]"),
10697          dwp_file->name);
10698 }
10699
10700 /* Subroutine of open_dwo_file,open_dwp_file to simplify them.
10701    Open the file specified by FILE_NAME and hand it off to BFD for
10702    preliminary analysis.  Return a newly initialized bfd *, which
10703    includes a canonicalized copy of FILE_NAME.
10704    If IS_DWP is TRUE, we're opening a DWP file, otherwise a DWO file.
10705    SEARCH_CWD is true if the current directory is to be searched.
10706    It will be searched before debug-file-directory.
10707    If successful, the file is added to the bfd include table of the
10708    objfile's bfd (see gdb_bfd_record_inclusion).
10709    If unable to find/open the file, return NULL.
10710    NOTE: This function is derived from symfile_bfd_open.  */
10711
10712 static gdb_bfd_ref_ptr
10713 try_open_dwop_file (const char *file_name, int is_dwp, int search_cwd)
10714 {
10715   int desc, flags;
10716   char *absolute_name;
10717   /* Blech.  OPF_TRY_CWD_FIRST also disables searching the path list if
10718      FILE_NAME contains a '/'.  So we can't use it.  Instead prepend "."
10719      to debug_file_directory.  */
10720   char *search_path;
10721   static const char dirname_separator_string[] = { DIRNAME_SEPARATOR, '\0' };
10722
10723   if (search_cwd)
10724     {
10725       if (*debug_file_directory != '\0')
10726         search_path = concat (".", dirname_separator_string,
10727                               debug_file_directory, (char *) NULL);
10728       else
10729         search_path = xstrdup (".");
10730     }
10731   else
10732     search_path = xstrdup (debug_file_directory);
10733
10734   flags = OPF_RETURN_REALPATH;
10735   if (is_dwp)
10736     flags |= OPF_SEARCH_IN_PATH;
10737   desc = openp (search_path, flags, file_name,
10738                 O_RDONLY | O_BINARY, &absolute_name);
10739   xfree (search_path);
10740   if (desc < 0)
10741     return NULL;
10742
10743   gdb_bfd_ref_ptr sym_bfd (gdb_bfd_open (absolute_name, gnutarget, desc));
10744   xfree (absolute_name);
10745   if (sym_bfd == NULL)
10746     return NULL;
10747   bfd_set_cacheable (sym_bfd.get (), 1);
10748
10749   if (!bfd_check_format (sym_bfd.get (), bfd_object))
10750     return NULL;
10751
10752   /* Success.  Record the bfd as having been included by the objfile's bfd.
10753      This is important because things like demangled_names_hash lives in the
10754      objfile's per_bfd space and may have references to things like symbol
10755      names that live in the DWO/DWP file's per_bfd space.  PR 16426.  */
10756   gdb_bfd_record_inclusion (dwarf2_per_objfile->objfile->obfd, sym_bfd.get ());
10757
10758   return sym_bfd;
10759 }
10760
10761 /* Try to open DWO file FILE_NAME.
10762    COMP_DIR is the DW_AT_comp_dir attribute.
10763    The result is the bfd handle of the file.
10764    If there is a problem finding or opening the file, return NULL.
10765    Upon success, the canonicalized path of the file is stored in the bfd,
10766    same as symfile_bfd_open.  */
10767
10768 static gdb_bfd_ref_ptr
10769 open_dwo_file (const char *file_name, const char *comp_dir)
10770 {
10771   if (IS_ABSOLUTE_PATH (file_name))
10772     return try_open_dwop_file (file_name, 0 /*is_dwp*/, 0 /*search_cwd*/);
10773
10774   /* Before trying the search path, try DWO_NAME in COMP_DIR.  */
10775
10776   if (comp_dir != NULL)
10777     {
10778       char *path_to_try = concat (comp_dir, SLASH_STRING,
10779                                   file_name, (char *) NULL);
10780
10781       /* NOTE: If comp_dir is a relative path, this will also try the
10782          search path, which seems useful.  */
10783       gdb_bfd_ref_ptr abfd (try_open_dwop_file (path_to_try, 0 /*is_dwp*/,
10784                                                 1 /*search_cwd*/));
10785       xfree (path_to_try);
10786       if (abfd != NULL)
10787         return abfd;
10788     }
10789
10790   /* That didn't work, try debug-file-directory, which, despite its name,
10791      is a list of paths.  */
10792
10793   if (*debug_file_directory == '\0')
10794     return NULL;
10795
10796   return try_open_dwop_file (file_name, 0 /*is_dwp*/, 1 /*search_cwd*/);
10797 }
10798
10799 /* This function is mapped across the sections and remembers the offset and
10800    size of each of the DWO debugging sections we are interested in.  */
10801
10802 static void
10803 dwarf2_locate_dwo_sections (bfd *abfd, asection *sectp, void *dwo_sections_ptr)
10804 {
10805   struct dwo_sections *dwo_sections = (struct dwo_sections *) dwo_sections_ptr;
10806   const struct dwop_section_names *names = &dwop_section_names;
10807
10808   if (section_is_p (sectp->name, &names->abbrev_dwo))
10809     {
10810       dwo_sections->abbrev.s.section = sectp;
10811       dwo_sections->abbrev.size = bfd_get_section_size (sectp);
10812     }
10813   else if (section_is_p (sectp->name, &names->info_dwo))
10814     {
10815       dwo_sections->info.s.section = sectp;
10816       dwo_sections->info.size = bfd_get_section_size (sectp);
10817     }
10818   else if (section_is_p (sectp->name, &names->line_dwo))
10819     {
10820       dwo_sections->line.s.section = sectp;
10821       dwo_sections->line.size = bfd_get_section_size (sectp);
10822     }
10823   else if (section_is_p (sectp->name, &names->loc_dwo))
10824     {
10825       dwo_sections->loc.s.section = sectp;
10826       dwo_sections->loc.size = bfd_get_section_size (sectp);
10827     }
10828   else if (section_is_p (sectp->name, &names->macinfo_dwo))
10829     {
10830       dwo_sections->macinfo.s.section = sectp;
10831       dwo_sections->macinfo.size = bfd_get_section_size (sectp);
10832     }
10833   else if (section_is_p (sectp->name, &names->macro_dwo))
10834     {
10835       dwo_sections->macro.s.section = sectp;
10836       dwo_sections->macro.size = bfd_get_section_size (sectp);
10837     }
10838   else if (section_is_p (sectp->name, &names->str_dwo))
10839     {
10840       dwo_sections->str.s.section = sectp;
10841       dwo_sections->str.size = bfd_get_section_size (sectp);
10842     }
10843   else if (section_is_p (sectp->name, &names->str_offsets_dwo))
10844     {
10845       dwo_sections->str_offsets.s.section = sectp;
10846       dwo_sections->str_offsets.size = bfd_get_section_size (sectp);
10847     }
10848   else if (section_is_p (sectp->name, &names->types_dwo))
10849     {
10850       struct dwarf2_section_info type_section;
10851
10852       memset (&type_section, 0, sizeof (type_section));
10853       type_section.s.section = sectp;
10854       type_section.size = bfd_get_section_size (sectp);
10855       VEC_safe_push (dwarf2_section_info_def, dwo_sections->types,
10856                      &type_section);
10857     }
10858 }
10859
10860 /* Initialize the use of the DWO file specified by DWO_NAME and referenced
10861    by PER_CU.  This is for the non-DWP case.
10862    The result is NULL if DWO_NAME can't be found.  */
10863
10864 static struct dwo_file *
10865 open_and_init_dwo_file (struct dwarf2_per_cu_data *per_cu,
10866                         const char *dwo_name, const char *comp_dir)
10867 {
10868   struct objfile *objfile = dwarf2_per_objfile->objfile;
10869   struct dwo_file *dwo_file;
10870   struct cleanup *cleanups;
10871
10872   gdb_bfd_ref_ptr dbfd (open_dwo_file (dwo_name, comp_dir));
10873   if (dbfd == NULL)
10874     {
10875       if (dwarf_read_debug)
10876         fprintf_unfiltered (gdb_stdlog, "DWO file not found: %s\n", dwo_name);
10877       return NULL;
10878     }
10879   dwo_file = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_file);
10880   dwo_file->dwo_name = dwo_name;
10881   dwo_file->comp_dir = comp_dir;
10882   dwo_file->dbfd = dbfd.release ();
10883
10884   cleanups = make_cleanup (free_dwo_file_cleanup, dwo_file);
10885
10886   bfd_map_over_sections (dwo_file->dbfd, dwarf2_locate_dwo_sections,
10887                          &dwo_file->sections);
10888
10889   create_cus_hash_table (*dwo_file, dwo_file->sections.info, dwo_file->cus);
10890
10891   create_debug_types_hash_table (dwo_file, dwo_file->sections.types,
10892                                  dwo_file->tus);
10893
10894   discard_cleanups (cleanups);
10895
10896   if (dwarf_read_debug)
10897     fprintf_unfiltered (gdb_stdlog, "DWO file found: %s\n", dwo_name);
10898
10899   return dwo_file;
10900 }
10901
10902 /* This function is mapped across the sections and remembers the offset and
10903    size of each of the DWP debugging sections common to version 1 and 2 that
10904    we are interested in.  */
10905
10906 static void
10907 dwarf2_locate_common_dwp_sections (bfd *abfd, asection *sectp,
10908                                    void *dwp_file_ptr)
10909 {
10910   struct dwp_file *dwp_file = (struct dwp_file *) dwp_file_ptr;
10911   const struct dwop_section_names *names = &dwop_section_names;
10912   unsigned int elf_section_nr = elf_section_data (sectp)->this_idx;
10913
10914   /* Record the ELF section number for later lookup: this is what the
10915      .debug_cu_index,.debug_tu_index tables use in DWP V1.  */
10916   gdb_assert (elf_section_nr < dwp_file->num_sections);
10917   dwp_file->elf_sections[elf_section_nr] = sectp;
10918
10919   /* Look for specific sections that we need.  */
10920   if (section_is_p (sectp->name, &names->str_dwo))
10921     {
10922       dwp_file->sections.str.s.section = sectp;
10923       dwp_file->sections.str.size = bfd_get_section_size (sectp);
10924     }
10925   else if (section_is_p (sectp->name, &names->cu_index))
10926     {
10927       dwp_file->sections.cu_index.s.section = sectp;
10928       dwp_file->sections.cu_index.size = bfd_get_section_size (sectp);
10929     }
10930   else if (section_is_p (sectp->name, &names->tu_index))
10931     {
10932       dwp_file->sections.tu_index.s.section = sectp;
10933       dwp_file->sections.tu_index.size = bfd_get_section_size (sectp);
10934     }
10935 }
10936
10937 /* This function is mapped across the sections and remembers the offset and
10938    size of each of the DWP version 2 debugging sections that we are interested
10939    in.  This is split into a separate function because we don't know if we
10940    have version 1 or 2 until we parse the cu_index/tu_index sections.  */
10941
10942 static void
10943 dwarf2_locate_v2_dwp_sections (bfd *abfd, asection *sectp, void *dwp_file_ptr)
10944 {
10945   struct dwp_file *dwp_file = (struct dwp_file *) dwp_file_ptr;
10946   const struct dwop_section_names *names = &dwop_section_names;
10947   unsigned int elf_section_nr = elf_section_data (sectp)->this_idx;
10948
10949   /* Record the ELF section number for later lookup: this is what the
10950      .debug_cu_index,.debug_tu_index tables use in DWP V1.  */
10951   gdb_assert (elf_section_nr < dwp_file->num_sections);
10952   dwp_file->elf_sections[elf_section_nr] = sectp;
10953
10954   /* Look for specific sections that we need.  */
10955   if (section_is_p (sectp->name, &names->abbrev_dwo))
10956     {
10957       dwp_file->sections.abbrev.s.section = sectp;
10958       dwp_file->sections.abbrev.size = bfd_get_section_size (sectp);
10959     }
10960   else if (section_is_p (sectp->name, &names->info_dwo))
10961     {
10962       dwp_file->sections.info.s.section = sectp;
10963       dwp_file->sections.info.size = bfd_get_section_size (sectp);
10964     }
10965   else if (section_is_p (sectp->name, &names->line_dwo))
10966     {
10967       dwp_file->sections.line.s.section = sectp;
10968       dwp_file->sections.line.size = bfd_get_section_size (sectp);
10969     }
10970   else if (section_is_p (sectp->name, &names->loc_dwo))
10971     {
10972       dwp_file->sections.loc.s.section = sectp;
10973       dwp_file->sections.loc.size = bfd_get_section_size (sectp);
10974     }
10975   else if (section_is_p (sectp->name, &names->macinfo_dwo))
10976     {
10977       dwp_file->sections.macinfo.s.section = sectp;
10978       dwp_file->sections.macinfo.size = bfd_get_section_size (sectp);
10979     }
10980   else if (section_is_p (sectp->name, &names->macro_dwo))
10981     {
10982       dwp_file->sections.macro.s.section = sectp;
10983       dwp_file->sections.macro.size = bfd_get_section_size (sectp);
10984     }
10985   else if (section_is_p (sectp->name, &names->str_offsets_dwo))
10986     {
10987       dwp_file->sections.str_offsets.s.section = sectp;
10988       dwp_file->sections.str_offsets.size = bfd_get_section_size (sectp);
10989     }
10990   else if (section_is_p (sectp->name, &names->types_dwo))
10991     {
10992       dwp_file->sections.types.s.section = sectp;
10993       dwp_file->sections.types.size = bfd_get_section_size (sectp);
10994     }
10995 }
10996
10997 /* Hash function for dwp_file loaded CUs/TUs.  */
10998
10999 static hashval_t
11000 hash_dwp_loaded_cutus (const void *item)
11001 {
11002   const struct dwo_unit *dwo_unit = (const struct dwo_unit *) item;
11003
11004   /* This drops the top 32 bits of the signature, but is ok for a hash.  */
11005   return dwo_unit->signature;
11006 }
11007
11008 /* Equality function for dwp_file loaded CUs/TUs.  */
11009
11010 static int
11011 eq_dwp_loaded_cutus (const void *a, const void *b)
11012 {
11013   const struct dwo_unit *dua = (const struct dwo_unit *) a;
11014   const struct dwo_unit *dub = (const struct dwo_unit *) b;
11015
11016   return dua->signature == dub->signature;
11017 }
11018
11019 /* Allocate a hash table for dwp_file loaded CUs/TUs.  */
11020
11021 static htab_t
11022 allocate_dwp_loaded_cutus_table (struct objfile *objfile)
11023 {
11024   return htab_create_alloc_ex (3,
11025                                hash_dwp_loaded_cutus,
11026                                eq_dwp_loaded_cutus,
11027                                NULL,
11028                                &objfile->objfile_obstack,
11029                                hashtab_obstack_allocate,
11030                                dummy_obstack_deallocate);
11031 }
11032
11033 /* Try to open DWP file FILE_NAME.
11034    The result is the bfd handle of the file.
11035    If there is a problem finding or opening the file, return NULL.
11036    Upon success, the canonicalized path of the file is stored in the bfd,
11037    same as symfile_bfd_open.  */
11038
11039 static gdb_bfd_ref_ptr
11040 open_dwp_file (const char *file_name)
11041 {
11042   gdb_bfd_ref_ptr abfd (try_open_dwop_file (file_name, 1 /*is_dwp*/,
11043                                             1 /*search_cwd*/));
11044   if (abfd != NULL)
11045     return abfd;
11046
11047   /* Work around upstream bug 15652.
11048      http://sourceware.org/bugzilla/show_bug.cgi?id=15652
11049      [Whether that's a "bug" is debatable, but it is getting in our way.]
11050      We have no real idea where the dwp file is, because gdb's realpath-ing
11051      of the executable's path may have discarded the needed info.
11052      [IWBN if the dwp file name was recorded in the executable, akin to
11053      .gnu_debuglink, but that doesn't exist yet.]
11054      Strip the directory from FILE_NAME and search again.  */
11055   if (*debug_file_directory != '\0')
11056     {
11057       /* Don't implicitly search the current directory here.
11058          If the user wants to search "." to handle this case,
11059          it must be added to debug-file-directory.  */
11060       return try_open_dwop_file (lbasename (file_name), 1 /*is_dwp*/,
11061                                  0 /*search_cwd*/);
11062     }
11063
11064   return NULL;
11065 }
11066
11067 /* Initialize the use of the DWP file for the current objfile.
11068    By convention the name of the DWP file is ${objfile}.dwp.
11069    The result is NULL if it can't be found.  */
11070
11071 static struct dwp_file *
11072 open_and_init_dwp_file (void)
11073 {
11074   struct objfile *objfile = dwarf2_per_objfile->objfile;
11075   struct dwp_file *dwp_file;
11076
11077   /* Try to find first .dwp for the binary file before any symbolic links
11078      resolving.  */
11079
11080   /* If the objfile is a debug file, find the name of the real binary
11081      file and get the name of dwp file from there.  */
11082   std::string dwp_name;
11083   if (objfile->separate_debug_objfile_backlink != NULL)
11084     {
11085       struct objfile *backlink = objfile->separate_debug_objfile_backlink;
11086       const char *backlink_basename = lbasename (backlink->original_name);
11087
11088       dwp_name = ldirname (objfile->original_name) + SLASH_STRING + backlink_basename;
11089     }
11090   else
11091     dwp_name = objfile->original_name;
11092
11093   dwp_name += ".dwp";
11094
11095   gdb_bfd_ref_ptr dbfd (open_dwp_file (dwp_name.c_str ()));
11096   if (dbfd == NULL
11097       && strcmp (objfile->original_name, objfile_name (objfile)) != 0)
11098     {
11099       /* Try to find .dwp for the binary file after gdb_realpath resolving.  */
11100       dwp_name = objfile_name (objfile);
11101       dwp_name += ".dwp";
11102       dbfd = open_dwp_file (dwp_name.c_str ());
11103     }
11104
11105   if (dbfd == NULL)
11106     {
11107       if (dwarf_read_debug)
11108         fprintf_unfiltered (gdb_stdlog, "DWP file not found: %s\n", dwp_name.c_str ());
11109       return NULL;
11110     }
11111   dwp_file = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwp_file);
11112   dwp_file->name = bfd_get_filename (dbfd.get ());
11113   dwp_file->dbfd = dbfd.release ();
11114
11115   /* +1: section 0 is unused */
11116   dwp_file->num_sections = bfd_count_sections (dwp_file->dbfd) + 1;
11117   dwp_file->elf_sections =
11118     OBSTACK_CALLOC (&objfile->objfile_obstack,
11119                     dwp_file->num_sections, asection *);
11120
11121   bfd_map_over_sections (dwp_file->dbfd, dwarf2_locate_common_dwp_sections,
11122                          dwp_file);
11123
11124   dwp_file->cus = create_dwp_hash_table (dwp_file, 0);
11125
11126   dwp_file->tus = create_dwp_hash_table (dwp_file, 1);
11127
11128   /* The DWP file version is stored in the hash table.  Oh well.  */
11129   if (dwp_file->cus->version != dwp_file->tus->version)
11130     {
11131       /* Technically speaking, we should try to limp along, but this is
11132          pretty bizarre.  We use pulongest here because that's the established
11133          portability solution (e.g, we cannot use %u for uint32_t).  */
11134       error (_("Dwarf Error: DWP file CU version %s doesn't match"
11135                " TU version %s [in DWP file %s]"),
11136              pulongest (dwp_file->cus->version),
11137              pulongest (dwp_file->tus->version), dwp_name.c_str ());
11138     }
11139   dwp_file->version = dwp_file->cus->version;
11140
11141   if (dwp_file->version == 2)
11142     bfd_map_over_sections (dwp_file->dbfd, dwarf2_locate_v2_dwp_sections,
11143                            dwp_file);
11144
11145   dwp_file->loaded_cus = allocate_dwp_loaded_cutus_table (objfile);
11146   dwp_file->loaded_tus = allocate_dwp_loaded_cutus_table (objfile);
11147
11148   if (dwarf_read_debug)
11149     {
11150       fprintf_unfiltered (gdb_stdlog, "DWP file found: %s\n", dwp_file->name);
11151       fprintf_unfiltered (gdb_stdlog,
11152                           "    %s CUs, %s TUs\n",
11153                           pulongest (dwp_file->cus ? dwp_file->cus->nr_units : 0),
11154                           pulongest (dwp_file->tus ? dwp_file->tus->nr_units : 0));
11155     }
11156
11157   return dwp_file;
11158 }
11159
11160 /* Wrapper around open_and_init_dwp_file, only open it once.  */
11161
11162 static struct dwp_file *
11163 get_dwp_file (void)
11164 {
11165   if (! dwarf2_per_objfile->dwp_checked)
11166     {
11167       dwarf2_per_objfile->dwp_file = open_and_init_dwp_file ();
11168       dwarf2_per_objfile->dwp_checked = 1;
11169     }
11170   return dwarf2_per_objfile->dwp_file;
11171 }
11172
11173 /* Subroutine of lookup_dwo_comp_unit, lookup_dwo_type_unit.
11174    Look up the CU/TU with signature SIGNATURE, either in DWO file DWO_NAME
11175    or in the DWP file for the objfile, referenced by THIS_UNIT.
11176    If non-NULL, comp_dir is the DW_AT_comp_dir attribute.
11177    IS_DEBUG_TYPES is non-zero if reading a TU, otherwise read a CU.
11178
11179    This is called, for example, when wanting to read a variable with a
11180    complex location.  Therefore we don't want to do file i/o for every call.
11181    Therefore we don't want to look for a DWO file on every call.
11182    Therefore we first see if we've already seen SIGNATURE in a DWP file,
11183    then we check if we've already seen DWO_NAME, and only THEN do we check
11184    for a DWO file.
11185
11186    The result is a pointer to the dwo_unit object or NULL if we didn't find it
11187    (dwo_id mismatch or couldn't find the DWO/DWP file).  */
11188
11189 static struct dwo_unit *
11190 lookup_dwo_cutu (struct dwarf2_per_cu_data *this_unit,
11191                  const char *dwo_name, const char *comp_dir,
11192                  ULONGEST signature, int is_debug_types)
11193 {
11194   struct objfile *objfile = dwarf2_per_objfile->objfile;
11195   const char *kind = is_debug_types ? "TU" : "CU";
11196   void **dwo_file_slot;
11197   struct dwo_file *dwo_file;
11198   struct dwp_file *dwp_file;
11199
11200   /* First see if there's a DWP file.
11201      If we have a DWP file but didn't find the DWO inside it, don't
11202      look for the original DWO file.  It makes gdb behave differently
11203      depending on whether one is debugging in the build tree.  */
11204
11205   dwp_file = get_dwp_file ();
11206   if (dwp_file != NULL)
11207     {
11208       const struct dwp_hash_table *dwp_htab =
11209         is_debug_types ? dwp_file->tus : dwp_file->cus;
11210
11211       if (dwp_htab != NULL)
11212         {
11213           struct dwo_unit *dwo_cutu =
11214             lookup_dwo_unit_in_dwp (dwp_file, comp_dir,
11215                                     signature, is_debug_types);
11216
11217           if (dwo_cutu != NULL)
11218             {
11219               if (dwarf_read_debug)
11220                 {
11221                   fprintf_unfiltered (gdb_stdlog,
11222                                       "Virtual DWO %s %s found: @%s\n",
11223                                       kind, hex_string (signature),
11224                                       host_address_to_string (dwo_cutu));
11225                 }
11226               return dwo_cutu;
11227             }
11228         }
11229     }
11230   else
11231     {
11232       /* No DWP file, look for the DWO file.  */
11233
11234       dwo_file_slot = lookup_dwo_file_slot (dwo_name, comp_dir);
11235       if (*dwo_file_slot == NULL)
11236         {
11237           /* Read in the file and build a table of the CUs/TUs it contains.  */
11238           *dwo_file_slot = open_and_init_dwo_file (this_unit, dwo_name, comp_dir);
11239         }
11240       /* NOTE: This will be NULL if unable to open the file.  */
11241       dwo_file = (struct dwo_file *) *dwo_file_slot;
11242
11243       if (dwo_file != NULL)
11244         {
11245           struct dwo_unit *dwo_cutu = NULL;
11246
11247           if (is_debug_types && dwo_file->tus)
11248             {
11249               struct dwo_unit find_dwo_cutu;
11250
11251               memset (&find_dwo_cutu, 0, sizeof (find_dwo_cutu));
11252               find_dwo_cutu.signature = signature;
11253               dwo_cutu
11254                 = (struct dwo_unit *) htab_find (dwo_file->tus, &find_dwo_cutu);
11255             }
11256           else if (!is_debug_types && dwo_file->cus)
11257             {
11258               struct dwo_unit find_dwo_cutu;
11259
11260               memset (&find_dwo_cutu, 0, sizeof (find_dwo_cutu));
11261               find_dwo_cutu.signature = signature;
11262               dwo_cutu = (struct dwo_unit *)htab_find (dwo_file->cus,
11263                                                        &find_dwo_cutu);
11264             }
11265
11266           if (dwo_cutu != NULL)
11267             {
11268               if (dwarf_read_debug)
11269                 {
11270                   fprintf_unfiltered (gdb_stdlog, "DWO %s %s(%s) found: @%s\n",
11271                                       kind, dwo_name, hex_string (signature),
11272                                       host_address_to_string (dwo_cutu));
11273                 }
11274               return dwo_cutu;
11275             }
11276         }
11277     }
11278
11279   /* We didn't find it.  This could mean a dwo_id mismatch, or
11280      someone deleted the DWO/DWP file, or the search path isn't set up
11281      correctly to find the file.  */
11282
11283   if (dwarf_read_debug)
11284     {
11285       fprintf_unfiltered (gdb_stdlog, "DWO %s %s(%s) not found\n",
11286                           kind, dwo_name, hex_string (signature));
11287     }
11288
11289   /* This is a warning and not a complaint because it can be caused by
11290      pilot error (e.g., user accidentally deleting the DWO).  */
11291   {
11292     /* Print the name of the DWP file if we looked there, helps the user
11293        better diagnose the problem.  */
11294     char *dwp_text = NULL;
11295     struct cleanup *cleanups;
11296
11297     if (dwp_file != NULL)
11298       dwp_text = xstrprintf (" [in DWP file %s]", lbasename (dwp_file->name));
11299     cleanups = make_cleanup (xfree, dwp_text);
11300
11301     warning (_("Could not find DWO %s %s(%s)%s referenced by %s at offset 0x%x"
11302                " [in module %s]"),
11303              kind, dwo_name, hex_string (signature),
11304              dwp_text != NULL ? dwp_text : "",
11305              this_unit->is_debug_types ? "TU" : "CU",
11306              to_underlying (this_unit->sect_off), objfile_name (objfile));
11307
11308     do_cleanups (cleanups);
11309   }
11310   return NULL;
11311 }
11312
11313 /* Lookup the DWO CU DWO_NAME/SIGNATURE referenced from THIS_CU.
11314    See lookup_dwo_cutu_unit for details.  */
11315
11316 static struct dwo_unit *
11317 lookup_dwo_comp_unit (struct dwarf2_per_cu_data *this_cu,
11318                       const char *dwo_name, const char *comp_dir,
11319                       ULONGEST signature)
11320 {
11321   return lookup_dwo_cutu (this_cu, dwo_name, comp_dir, signature, 0);
11322 }
11323
11324 /* Lookup the DWO TU DWO_NAME/SIGNATURE referenced from THIS_TU.
11325    See lookup_dwo_cutu_unit for details.  */
11326
11327 static struct dwo_unit *
11328 lookup_dwo_type_unit (struct signatured_type *this_tu,
11329                       const char *dwo_name, const char *comp_dir)
11330 {
11331   return lookup_dwo_cutu (&this_tu->per_cu, dwo_name, comp_dir, this_tu->signature, 1);
11332 }
11333
11334 /* Traversal function for queue_and_load_all_dwo_tus.  */
11335
11336 static int
11337 queue_and_load_dwo_tu (void **slot, void *info)
11338 {
11339   struct dwo_unit *dwo_unit = (struct dwo_unit *) *slot;
11340   struct dwarf2_per_cu_data *per_cu = (struct dwarf2_per_cu_data *) info;
11341   ULONGEST signature = dwo_unit->signature;
11342   struct signatured_type *sig_type =
11343     lookup_dwo_signatured_type (per_cu->cu, signature);
11344
11345   if (sig_type != NULL)
11346     {
11347       struct dwarf2_per_cu_data *sig_cu = &sig_type->per_cu;
11348
11349       /* We pass NULL for DEPENDENT_CU because we don't yet know if there's
11350          a real dependency of PER_CU on SIG_TYPE.  That is detected later
11351          while processing PER_CU.  */
11352       if (maybe_queue_comp_unit (NULL, sig_cu, per_cu->cu->language))
11353         load_full_type_unit (sig_cu);
11354       VEC_safe_push (dwarf2_per_cu_ptr, per_cu->imported_symtabs, sig_cu);
11355     }
11356
11357   return 1;
11358 }
11359
11360 /* Queue all TUs contained in the DWO of PER_CU to be read in.
11361    The DWO may have the only definition of the type, though it may not be
11362    referenced anywhere in PER_CU.  Thus we have to load *all* its TUs.
11363    http://sourceware.org/bugzilla/show_bug.cgi?id=15021  */
11364
11365 static void
11366 queue_and_load_all_dwo_tus (struct dwarf2_per_cu_data *per_cu)
11367 {
11368   struct dwo_unit *dwo_unit;
11369   struct dwo_file *dwo_file;
11370
11371   gdb_assert (!per_cu->is_debug_types);
11372   gdb_assert (get_dwp_file () == NULL);
11373   gdb_assert (per_cu->cu != NULL);
11374
11375   dwo_unit = per_cu->cu->dwo_unit;
11376   gdb_assert (dwo_unit != NULL);
11377
11378   dwo_file = dwo_unit->dwo_file;
11379   if (dwo_file->tus != NULL)
11380     htab_traverse_noresize (dwo_file->tus, queue_and_load_dwo_tu, per_cu);
11381 }
11382
11383 /* Free all resources associated with DWO_FILE.
11384    Close the DWO file and munmap the sections.
11385    All memory should be on the objfile obstack.  */
11386
11387 static void
11388 free_dwo_file (struct dwo_file *dwo_file, struct objfile *objfile)
11389 {
11390
11391   /* Note: dbfd is NULL for virtual DWO files.  */
11392   gdb_bfd_unref (dwo_file->dbfd);
11393
11394   VEC_free (dwarf2_section_info_def, dwo_file->sections.types);
11395 }
11396
11397 /* Wrapper for free_dwo_file for use in cleanups.  */
11398
11399 static void
11400 free_dwo_file_cleanup (void *arg)
11401 {
11402   struct dwo_file *dwo_file = (struct dwo_file *) arg;
11403   struct objfile *objfile = dwarf2_per_objfile->objfile;
11404
11405   free_dwo_file (dwo_file, objfile);
11406 }
11407
11408 /* Traversal function for free_dwo_files.  */
11409
11410 static int
11411 free_dwo_file_from_slot (void **slot, void *info)
11412 {
11413   struct dwo_file *dwo_file = (struct dwo_file *) *slot;
11414   struct objfile *objfile = (struct objfile *) info;
11415
11416   free_dwo_file (dwo_file, objfile);
11417
11418   return 1;
11419 }
11420
11421 /* Free all resources associated with DWO_FILES.  */
11422
11423 static void
11424 free_dwo_files (htab_t dwo_files, struct objfile *objfile)
11425 {
11426   htab_traverse_noresize (dwo_files, free_dwo_file_from_slot, objfile);
11427 }
11428 \f
11429 /* Read in various DIEs.  */
11430
11431 /* qsort helper for inherit_abstract_dies.  */
11432
11433 static int
11434 unsigned_int_compar (const void *ap, const void *bp)
11435 {
11436   unsigned int a = *(unsigned int *) ap;
11437   unsigned int b = *(unsigned int *) bp;
11438
11439   return (a > b) - (b > a);
11440 }
11441
11442 /* DW_AT_abstract_origin inherits whole DIEs (not just their attributes).
11443    Inherit only the children of the DW_AT_abstract_origin DIE not being
11444    already referenced by DW_AT_abstract_origin from the children of the
11445    current DIE.  */
11446
11447 static void
11448 inherit_abstract_dies (struct die_info *die, struct dwarf2_cu *cu)
11449 {
11450   struct die_info *child_die;
11451   unsigned die_children_count;
11452   /* CU offsets which were referenced by children of the current DIE.  */
11453   sect_offset *offsets;
11454   sect_offset *offsets_end, *offsetp;
11455   /* Parent of DIE - referenced by DW_AT_abstract_origin.  */
11456   struct die_info *origin_die;
11457   /* Iterator of the ORIGIN_DIE children.  */
11458   struct die_info *origin_child_die;
11459   struct cleanup *cleanups;
11460   struct attribute *attr;
11461   struct dwarf2_cu *origin_cu;
11462   struct pending **origin_previous_list_in_scope;
11463
11464   attr = dwarf2_attr (die, DW_AT_abstract_origin, cu);
11465   if (!attr)
11466     return;
11467
11468   /* Note that following die references may follow to a die in a
11469      different cu.  */
11470
11471   origin_cu = cu;
11472   origin_die = follow_die_ref (die, attr, &origin_cu);
11473
11474   /* We're inheriting ORIGIN's children into the scope we'd put DIE's
11475      symbols in.  */
11476   origin_previous_list_in_scope = origin_cu->list_in_scope;
11477   origin_cu->list_in_scope = cu->list_in_scope;
11478
11479   if (die->tag != origin_die->tag
11480       && !(die->tag == DW_TAG_inlined_subroutine
11481            && origin_die->tag == DW_TAG_subprogram))
11482     complaint (&symfile_complaints,
11483                _("DIE 0x%x and its abstract origin 0x%x have different tags"),
11484                to_underlying (die->sect_off),
11485                to_underlying (origin_die->sect_off));
11486
11487   child_die = die->child;
11488   die_children_count = 0;
11489   while (child_die && child_die->tag)
11490     {
11491       child_die = sibling_die (child_die);
11492       die_children_count++;
11493     }
11494   offsets = XNEWVEC (sect_offset, die_children_count);
11495   cleanups = make_cleanup (xfree, offsets);
11496
11497   offsets_end = offsets;
11498   for (child_die = die->child;
11499        child_die && child_die->tag;
11500        child_die = sibling_die (child_die))
11501     {
11502       struct die_info *child_origin_die;
11503       struct dwarf2_cu *child_origin_cu;
11504
11505       /* We are trying to process concrete instance entries:
11506          DW_TAG_call_site DIEs indeed have a DW_AT_abstract_origin tag, but
11507          it's not relevant to our analysis here. i.e. detecting DIEs that are
11508          present in the abstract instance but not referenced in the concrete
11509          one.  */
11510       if (child_die->tag == DW_TAG_call_site
11511           || child_die->tag == DW_TAG_GNU_call_site)
11512         continue;
11513
11514       /* For each CHILD_DIE, find the corresponding child of
11515          ORIGIN_DIE.  If there is more than one layer of
11516          DW_AT_abstract_origin, follow them all; there shouldn't be,
11517          but GCC versions at least through 4.4 generate this (GCC PR
11518          40573).  */
11519       child_origin_die = child_die;
11520       child_origin_cu = cu;
11521       while (1)
11522         {
11523           attr = dwarf2_attr (child_origin_die, DW_AT_abstract_origin,
11524                               child_origin_cu);
11525           if (attr == NULL)
11526             break;
11527           child_origin_die = follow_die_ref (child_origin_die, attr,
11528                                              &child_origin_cu);
11529         }
11530
11531       /* According to DWARF3 3.3.8.2 #3 new entries without their abstract
11532          counterpart may exist.  */
11533       if (child_origin_die != child_die)
11534         {
11535           if (child_die->tag != child_origin_die->tag
11536               && !(child_die->tag == DW_TAG_inlined_subroutine
11537                    && child_origin_die->tag == DW_TAG_subprogram))
11538             complaint (&symfile_complaints,
11539                        _("Child DIE 0x%x and its abstract origin 0x%x have "
11540                          "different tags"),
11541                        to_underlying (child_die->sect_off),
11542                        to_underlying (child_origin_die->sect_off));
11543           if (child_origin_die->parent != origin_die)
11544             complaint (&symfile_complaints,
11545                        _("Child DIE 0x%x and its abstract origin 0x%x have "
11546                          "different parents"),
11547                        to_underlying (child_die->sect_off),
11548                        to_underlying (child_origin_die->sect_off));
11549           else
11550             *offsets_end++ = child_origin_die->sect_off;
11551         }
11552     }
11553   qsort (offsets, offsets_end - offsets, sizeof (*offsets),
11554          unsigned_int_compar);
11555   for (offsetp = offsets + 1; offsetp < offsets_end; offsetp++)
11556     if (offsetp[-1] == *offsetp)
11557       complaint (&symfile_complaints,
11558                  _("Multiple children of DIE 0x%x refer "
11559                    "to DIE 0x%x as their abstract origin"),
11560                  to_underlying (die->sect_off), to_underlying (*offsetp));
11561
11562   offsetp = offsets;
11563   origin_child_die = origin_die->child;
11564   while (origin_child_die && origin_child_die->tag)
11565     {
11566       /* Is ORIGIN_CHILD_DIE referenced by any of the DIE children?  */
11567       while (offsetp < offsets_end
11568              && *offsetp < origin_child_die->sect_off)
11569         offsetp++;
11570       if (offsetp >= offsets_end
11571           || *offsetp > origin_child_die->sect_off)
11572         {
11573           /* Found that ORIGIN_CHILD_DIE is really not referenced.
11574              Check whether we're already processing ORIGIN_CHILD_DIE.
11575              This can happen with mutually referenced abstract_origins.
11576              PR 16581.  */
11577           if (!origin_child_die->in_process)
11578             process_die (origin_child_die, origin_cu);
11579         }
11580       origin_child_die = sibling_die (origin_child_die);
11581     }
11582   origin_cu->list_in_scope = origin_previous_list_in_scope;
11583
11584   do_cleanups (cleanups);
11585 }
11586
11587 static void
11588 read_func_scope (struct die_info *die, struct dwarf2_cu *cu)
11589 {
11590   struct objfile *objfile = cu->objfile;
11591   struct gdbarch *gdbarch = get_objfile_arch (objfile);
11592   struct context_stack *newobj;
11593   CORE_ADDR lowpc;
11594   CORE_ADDR highpc;
11595   struct die_info *child_die;
11596   struct attribute *attr, *call_line, *call_file;
11597   const char *name;
11598   CORE_ADDR baseaddr;
11599   struct block *block;
11600   int inlined_func = (die->tag == DW_TAG_inlined_subroutine);
11601   VEC (symbolp) *template_args = NULL;
11602   struct template_symbol *templ_func = NULL;
11603
11604   if (inlined_func)
11605     {
11606       /* If we do not have call site information, we can't show the
11607          caller of this inlined function.  That's too confusing, so
11608          only use the scope for local variables.  */
11609       call_line = dwarf2_attr (die, DW_AT_call_line, cu);
11610       call_file = dwarf2_attr (die, DW_AT_call_file, cu);
11611       if (call_line == NULL || call_file == NULL)
11612         {
11613           read_lexical_block_scope (die, cu);
11614           return;
11615         }
11616     }
11617
11618   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
11619
11620   name = dwarf2_name (die, cu);
11621
11622   /* Ignore functions with missing or empty names.  These are actually
11623      illegal according to the DWARF standard.  */
11624   if (name == NULL)
11625     {
11626       complaint (&symfile_complaints,
11627                  _("missing name for subprogram DIE at %d"),
11628                  to_underlying (die->sect_off));
11629       return;
11630     }
11631
11632   /* Ignore functions with missing or invalid low and high pc attributes.  */
11633   if (dwarf2_get_pc_bounds (die, &lowpc, &highpc, cu, NULL)
11634       <= PC_BOUNDS_INVALID)
11635     {
11636       attr = dwarf2_attr (die, DW_AT_external, cu);
11637       if (!attr || !DW_UNSND (attr))
11638         complaint (&symfile_complaints,
11639                    _("cannot get low and high bounds "
11640                      "for subprogram DIE at %d"),
11641                    to_underlying (die->sect_off));
11642       return;
11643     }
11644
11645   lowpc = gdbarch_adjust_dwarf2_addr (gdbarch, lowpc + baseaddr);
11646   highpc = gdbarch_adjust_dwarf2_addr (gdbarch, highpc + baseaddr);
11647
11648   /* If we have any template arguments, then we must allocate a
11649      different sort of symbol.  */
11650   for (child_die = die->child; child_die; child_die = sibling_die (child_die))
11651     {
11652       if (child_die->tag == DW_TAG_template_type_param
11653           || child_die->tag == DW_TAG_template_value_param)
11654         {
11655           templ_func = allocate_template_symbol (objfile);
11656           templ_func->base.is_cplus_template_function = 1;
11657           break;
11658         }
11659     }
11660
11661   newobj = push_context (0, lowpc);
11662   newobj->name = new_symbol_full (die, read_type_die (die, cu), cu,
11663                                (struct symbol *) templ_func);
11664
11665   /* If there is a location expression for DW_AT_frame_base, record
11666      it.  */
11667   attr = dwarf2_attr (die, DW_AT_frame_base, cu);
11668   if (attr)
11669     dwarf2_symbol_mark_computed (attr, newobj->name, cu, 1);
11670
11671   /* If there is a location for the static link, record it.  */
11672   newobj->static_link = NULL;
11673   attr = dwarf2_attr (die, DW_AT_static_link, cu);
11674   if (attr)
11675     {
11676       newobj->static_link
11677         = XOBNEW (&objfile->objfile_obstack, struct dynamic_prop);
11678       attr_to_dynamic_prop (attr, die, cu, newobj->static_link);
11679     }
11680
11681   cu->list_in_scope = &local_symbols;
11682
11683   if (die->child != NULL)
11684     {
11685       child_die = die->child;
11686       while (child_die && child_die->tag)
11687         {
11688           if (child_die->tag == DW_TAG_template_type_param
11689               || child_die->tag == DW_TAG_template_value_param)
11690             {
11691               struct symbol *arg = new_symbol (child_die, NULL, cu);
11692
11693               if (arg != NULL)
11694                 VEC_safe_push (symbolp, template_args, arg);
11695             }
11696           else
11697             process_die (child_die, cu);
11698           child_die = sibling_die (child_die);
11699         }
11700     }
11701
11702   inherit_abstract_dies (die, cu);
11703
11704   /* If we have a DW_AT_specification, we might need to import using
11705      directives from the context of the specification DIE.  See the
11706      comment in determine_prefix.  */
11707   if (cu->language == language_cplus
11708       && dwarf2_attr (die, DW_AT_specification, cu))
11709     {
11710       struct dwarf2_cu *spec_cu = cu;
11711       struct die_info *spec_die = die_specification (die, &spec_cu);
11712
11713       while (spec_die)
11714         {
11715           child_die = spec_die->child;
11716           while (child_die && child_die->tag)
11717             {
11718               if (child_die->tag == DW_TAG_imported_module)
11719                 process_die (child_die, spec_cu);
11720               child_die = sibling_die (child_die);
11721             }
11722
11723           /* In some cases, GCC generates specification DIEs that
11724              themselves contain DW_AT_specification attributes.  */
11725           spec_die = die_specification (spec_die, &spec_cu);
11726         }
11727     }
11728
11729   newobj = pop_context ();
11730   /* Make a block for the local symbols within.  */
11731   block = finish_block (newobj->name, &local_symbols, newobj->old_blocks,
11732                         newobj->static_link, lowpc, highpc);
11733
11734   /* For C++, set the block's scope.  */
11735   if ((cu->language == language_cplus
11736        || cu->language == language_fortran
11737        || cu->language == language_d
11738        || cu->language == language_rust)
11739       && cu->processing_has_namespace_info)
11740     block_set_scope (block, determine_prefix (die, cu),
11741                      &objfile->objfile_obstack);
11742
11743   /* If we have address ranges, record them.  */
11744   dwarf2_record_block_ranges (die, block, baseaddr, cu);
11745
11746   gdbarch_make_symbol_special (gdbarch, newobj->name, objfile);
11747
11748   /* Attach template arguments to function.  */
11749   if (! VEC_empty (symbolp, template_args))
11750     {
11751       gdb_assert (templ_func != NULL);
11752
11753       templ_func->n_template_arguments = VEC_length (symbolp, template_args);
11754       templ_func->template_arguments
11755         = XOBNEWVEC (&objfile->objfile_obstack, struct symbol *,
11756                      templ_func->n_template_arguments);
11757       memcpy (templ_func->template_arguments,
11758               VEC_address (symbolp, template_args),
11759               (templ_func->n_template_arguments * sizeof (struct symbol *)));
11760       VEC_free (symbolp, template_args);
11761     }
11762
11763   /* In C++, we can have functions nested inside functions (e.g., when
11764      a function declares a class that has methods).  This means that
11765      when we finish processing a function scope, we may need to go
11766      back to building a containing block's symbol lists.  */
11767   local_symbols = newobj->locals;
11768   local_using_directives = newobj->local_using_directives;
11769
11770   /* If we've finished processing a top-level function, subsequent
11771      symbols go in the file symbol list.  */
11772   if (outermost_context_p ())
11773     cu->list_in_scope = &file_symbols;
11774 }
11775
11776 /* Process all the DIES contained within a lexical block scope.  Start
11777    a new scope, process the dies, and then close the scope.  */
11778
11779 static void
11780 read_lexical_block_scope (struct die_info *die, struct dwarf2_cu *cu)
11781 {
11782   struct objfile *objfile = cu->objfile;
11783   struct gdbarch *gdbarch = get_objfile_arch (objfile);
11784   struct context_stack *newobj;
11785   CORE_ADDR lowpc, highpc;
11786   struct die_info *child_die;
11787   CORE_ADDR baseaddr;
11788
11789   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
11790
11791   /* Ignore blocks with missing or invalid low and high pc attributes.  */
11792   /* ??? Perhaps consider discontiguous blocks defined by DW_AT_ranges
11793      as multiple lexical blocks?  Handling children in a sane way would
11794      be nasty.  Might be easier to properly extend generic blocks to
11795      describe ranges.  */
11796   switch (dwarf2_get_pc_bounds (die, &lowpc, &highpc, cu, NULL))
11797     {
11798     case PC_BOUNDS_NOT_PRESENT:
11799       /* DW_TAG_lexical_block has no attributes, process its children as if
11800          there was no wrapping by that DW_TAG_lexical_block.
11801          GCC does no longer produces such DWARF since GCC r224161.  */
11802       for (child_die = die->child;
11803            child_die != NULL && child_die->tag;
11804            child_die = sibling_die (child_die))
11805         process_die (child_die, cu);
11806       return;
11807     case PC_BOUNDS_INVALID:
11808       return;
11809     }
11810   lowpc = gdbarch_adjust_dwarf2_addr (gdbarch, lowpc + baseaddr);
11811   highpc = gdbarch_adjust_dwarf2_addr (gdbarch, highpc + baseaddr);
11812
11813   push_context (0, lowpc);
11814   if (die->child != NULL)
11815     {
11816       child_die = die->child;
11817       while (child_die && child_die->tag)
11818         {
11819           process_die (child_die, cu);
11820           child_die = sibling_die (child_die);
11821         }
11822     }
11823   inherit_abstract_dies (die, cu);
11824   newobj = pop_context ();
11825
11826   if (local_symbols != NULL || local_using_directives != NULL)
11827     {
11828       struct block *block
11829         = finish_block (0, &local_symbols, newobj->old_blocks, NULL,
11830                         newobj->start_addr, highpc);
11831
11832       /* Note that recording ranges after traversing children, as we
11833          do here, means that recording a parent's ranges entails
11834          walking across all its children's ranges as they appear in
11835          the address map, which is quadratic behavior.
11836
11837          It would be nicer to record the parent's ranges before
11838          traversing its children, simply overriding whatever you find
11839          there.  But since we don't even decide whether to create a
11840          block until after we've traversed its children, that's hard
11841          to do.  */
11842       dwarf2_record_block_ranges (die, block, baseaddr, cu);
11843     }
11844   local_symbols = newobj->locals;
11845   local_using_directives = newobj->local_using_directives;
11846 }
11847
11848 /* Read in DW_TAG_call_site and insert it to CU->call_site_htab.  */
11849
11850 static void
11851 read_call_site_scope (struct die_info *die, struct dwarf2_cu *cu)
11852 {
11853   struct objfile *objfile = cu->objfile;
11854   struct gdbarch *gdbarch = get_objfile_arch (objfile);
11855   CORE_ADDR pc, baseaddr;
11856   struct attribute *attr;
11857   struct call_site *call_site, call_site_local;
11858   void **slot;
11859   int nparams;
11860   struct die_info *child_die;
11861
11862   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
11863
11864   attr = dwarf2_attr (die, DW_AT_call_return_pc, cu);
11865   if (attr == NULL)
11866     {
11867       /* This was a pre-DWARF-5 GNU extension alias
11868          for DW_AT_call_return_pc.  */
11869       attr = dwarf2_attr (die, DW_AT_low_pc, cu);
11870     }
11871   if (!attr)
11872     {
11873       complaint (&symfile_complaints,
11874                  _("missing DW_AT_call_return_pc for DW_TAG_call_site "
11875                    "DIE 0x%x [in module %s]"),
11876                  to_underlying (die->sect_off), objfile_name (objfile));
11877       return;
11878     }
11879   pc = attr_value_as_address (attr) + baseaddr;
11880   pc = gdbarch_adjust_dwarf2_addr (gdbarch, pc);
11881
11882   if (cu->call_site_htab == NULL)
11883     cu->call_site_htab = htab_create_alloc_ex (16, core_addr_hash, core_addr_eq,
11884                                                NULL, &objfile->objfile_obstack,
11885                                                hashtab_obstack_allocate, NULL);
11886   call_site_local.pc = pc;
11887   slot = htab_find_slot (cu->call_site_htab, &call_site_local, INSERT);
11888   if (*slot != NULL)
11889     {
11890       complaint (&symfile_complaints,
11891                  _("Duplicate PC %s for DW_TAG_call_site "
11892                    "DIE 0x%x [in module %s]"),
11893                  paddress (gdbarch, pc), to_underlying (die->sect_off),
11894                  objfile_name (objfile));
11895       return;
11896     }
11897
11898   /* Count parameters at the caller.  */
11899
11900   nparams = 0;
11901   for (child_die = die->child; child_die && child_die->tag;
11902        child_die = sibling_die (child_die))
11903     {
11904       if (child_die->tag != DW_TAG_call_site_parameter
11905           && child_die->tag != DW_TAG_GNU_call_site_parameter)
11906         {
11907           complaint (&symfile_complaints,
11908                      _("Tag %d is not DW_TAG_call_site_parameter in "
11909                        "DW_TAG_call_site child DIE 0x%x [in module %s]"),
11910                      child_die->tag, to_underlying (child_die->sect_off),
11911                      objfile_name (objfile));
11912           continue;
11913         }
11914
11915       nparams++;
11916     }
11917
11918   call_site
11919     = ((struct call_site *)
11920        obstack_alloc (&objfile->objfile_obstack,
11921                       sizeof (*call_site)
11922                       + (sizeof (*call_site->parameter) * (nparams - 1))));
11923   *slot = call_site;
11924   memset (call_site, 0, sizeof (*call_site) - sizeof (*call_site->parameter));
11925   call_site->pc = pc;
11926
11927   if (dwarf2_flag_true_p (die, DW_AT_call_tail_call, cu)
11928       || dwarf2_flag_true_p (die, DW_AT_GNU_tail_call, cu))
11929     {
11930       struct die_info *func_die;
11931
11932       /* Skip also over DW_TAG_inlined_subroutine.  */
11933       for (func_die = die->parent;
11934            func_die && func_die->tag != DW_TAG_subprogram
11935            && func_die->tag != DW_TAG_subroutine_type;
11936            func_die = func_die->parent);
11937
11938       /* DW_AT_call_all_calls is a superset
11939          of DW_AT_call_all_tail_calls.  */
11940       if (func_die
11941           && !dwarf2_flag_true_p (func_die, DW_AT_call_all_calls, cu)
11942           && !dwarf2_flag_true_p (func_die, DW_AT_GNU_all_call_sites, cu)
11943           && !dwarf2_flag_true_p (func_die, DW_AT_call_all_tail_calls, cu)
11944           && !dwarf2_flag_true_p (func_die, DW_AT_GNU_all_tail_call_sites, cu))
11945         {
11946           /* TYPE_TAIL_CALL_LIST is not interesting in functions where it is
11947              not complete.  But keep CALL_SITE for look ups via call_site_htab,
11948              both the initial caller containing the real return address PC and
11949              the final callee containing the current PC of a chain of tail
11950              calls do not need to have the tail call list complete.  But any
11951              function candidate for a virtual tail call frame searched via
11952              TYPE_TAIL_CALL_LIST must have the tail call list complete to be
11953              determined unambiguously.  */
11954         }
11955       else
11956         {
11957           struct type *func_type = NULL;
11958
11959           if (func_die)
11960             func_type = get_die_type (func_die, cu);
11961           if (func_type != NULL)
11962             {
11963               gdb_assert (TYPE_CODE (func_type) == TYPE_CODE_FUNC);
11964
11965               /* Enlist this call site to the function.  */
11966               call_site->tail_call_next = TYPE_TAIL_CALL_LIST (func_type);
11967               TYPE_TAIL_CALL_LIST (func_type) = call_site;
11968             }
11969           else
11970             complaint (&symfile_complaints,
11971                        _("Cannot find function owning DW_TAG_call_site "
11972                          "DIE 0x%x [in module %s]"),
11973                        to_underlying (die->sect_off), objfile_name (objfile));
11974         }
11975     }
11976
11977   attr = dwarf2_attr (die, DW_AT_call_target, cu);
11978   if (attr == NULL)
11979     attr = dwarf2_attr (die, DW_AT_GNU_call_site_target, cu);
11980   if (attr == NULL)
11981     attr = dwarf2_attr (die, DW_AT_call_origin, cu);
11982   if (attr == NULL)
11983     {
11984       /* This was a pre-DWARF-5 GNU extension alias for DW_AT_call_origin.  */
11985       attr = dwarf2_attr (die, DW_AT_abstract_origin, cu);
11986     }
11987   SET_FIELD_DWARF_BLOCK (call_site->target, NULL);
11988   if (!attr || (attr_form_is_block (attr) && DW_BLOCK (attr)->size == 0))
11989     /* Keep NULL DWARF_BLOCK.  */;
11990   else if (attr_form_is_block (attr))
11991     {
11992       struct dwarf2_locexpr_baton *dlbaton;
11993
11994       dlbaton = XOBNEW (&objfile->objfile_obstack, struct dwarf2_locexpr_baton);
11995       dlbaton->data = DW_BLOCK (attr)->data;
11996       dlbaton->size = DW_BLOCK (attr)->size;
11997       dlbaton->per_cu = cu->per_cu;
11998
11999       SET_FIELD_DWARF_BLOCK (call_site->target, dlbaton);
12000     }
12001   else if (attr_form_is_ref (attr))
12002     {
12003       struct dwarf2_cu *target_cu = cu;
12004       struct die_info *target_die;
12005
12006       target_die = follow_die_ref (die, attr, &target_cu);
12007       gdb_assert (target_cu->objfile == objfile);
12008       if (die_is_declaration (target_die, target_cu))
12009         {
12010           const char *target_physname;
12011
12012           /* Prefer the mangled name; otherwise compute the demangled one.  */
12013           target_physname = dwarf2_string_attr (target_die,
12014                                                 DW_AT_linkage_name,
12015                                                 target_cu);
12016           if (target_physname == NULL)
12017             target_physname = dwarf2_string_attr (target_die,
12018                                                  DW_AT_MIPS_linkage_name,
12019                                                  target_cu);
12020           if (target_physname == NULL)
12021             target_physname = dwarf2_physname (NULL, target_die, target_cu);
12022           if (target_physname == NULL)
12023             complaint (&symfile_complaints,
12024                        _("DW_AT_call_target target DIE has invalid "
12025                          "physname, for referencing DIE 0x%x [in module %s]"),
12026                        to_underlying (die->sect_off), objfile_name (objfile));
12027           else
12028             SET_FIELD_PHYSNAME (call_site->target, target_physname);
12029         }
12030       else
12031         {
12032           CORE_ADDR lowpc;
12033
12034           /* DW_AT_entry_pc should be preferred.  */
12035           if (dwarf2_get_pc_bounds (target_die, &lowpc, NULL, target_cu, NULL)
12036               <= PC_BOUNDS_INVALID)
12037             complaint (&symfile_complaints,
12038                        _("DW_AT_call_target target DIE has invalid "
12039                          "low pc, for referencing DIE 0x%x [in module %s]"),
12040                        to_underlying (die->sect_off), objfile_name (objfile));
12041           else
12042             {
12043               lowpc = gdbarch_adjust_dwarf2_addr (gdbarch, lowpc + baseaddr);
12044               SET_FIELD_PHYSADDR (call_site->target, lowpc);
12045             }
12046         }
12047     }
12048   else
12049     complaint (&symfile_complaints,
12050                _("DW_TAG_call_site DW_AT_call_target is neither "
12051                  "block nor reference, for DIE 0x%x [in module %s]"),
12052                to_underlying (die->sect_off), objfile_name (objfile));
12053
12054   call_site->per_cu = cu->per_cu;
12055
12056   for (child_die = die->child;
12057        child_die && child_die->tag;
12058        child_die = sibling_die (child_die))
12059     {
12060       struct call_site_parameter *parameter;
12061       struct attribute *loc, *origin;
12062
12063       if (child_die->tag != DW_TAG_call_site_parameter
12064           && child_die->tag != DW_TAG_GNU_call_site_parameter)
12065         {
12066           /* Already printed the complaint above.  */
12067           continue;
12068         }
12069
12070       gdb_assert (call_site->parameter_count < nparams);
12071       parameter = &call_site->parameter[call_site->parameter_count];
12072
12073       /* DW_AT_location specifies the register number or DW_AT_abstract_origin
12074          specifies DW_TAG_formal_parameter.  Value of the data assumed for the
12075          register is contained in DW_AT_call_value.  */
12076
12077       loc = dwarf2_attr (child_die, DW_AT_location, cu);
12078       origin = dwarf2_attr (child_die, DW_AT_call_parameter, cu);
12079       if (origin == NULL)
12080         {
12081           /* This was a pre-DWARF-5 GNU extension alias
12082              for DW_AT_call_parameter.  */
12083           origin = dwarf2_attr (child_die, DW_AT_abstract_origin, cu);
12084         }
12085       if (loc == NULL && origin != NULL && attr_form_is_ref (origin))
12086         {
12087           parameter->kind = CALL_SITE_PARAMETER_PARAM_OFFSET;
12088
12089           sect_offset sect_off
12090             = (sect_offset) dwarf2_get_ref_die_offset (origin);
12091           if (!offset_in_cu_p (&cu->header, sect_off))
12092             {
12093               /* As DW_OP_GNU_parameter_ref uses CU-relative offset this
12094                  binding can be done only inside one CU.  Such referenced DIE
12095                  therefore cannot be even moved to DW_TAG_partial_unit.  */
12096               complaint (&symfile_complaints,
12097                          _("DW_AT_call_parameter offset is not in CU for "
12098                            "DW_TAG_call_site child DIE 0x%x [in module %s]"),
12099                          to_underlying (child_die->sect_off),
12100                          objfile_name (objfile));
12101               continue;
12102             }
12103           parameter->u.param_cu_off
12104             = (cu_offset) (sect_off - cu->header.sect_off);
12105         }
12106       else if (loc == NULL || origin != NULL || !attr_form_is_block (loc))
12107         {
12108           complaint (&symfile_complaints,
12109                      _("No DW_FORM_block* DW_AT_location for "
12110                        "DW_TAG_call_site child DIE 0x%x [in module %s]"),
12111                      to_underlying (child_die->sect_off), objfile_name (objfile));
12112           continue;
12113         }
12114       else
12115         {
12116           parameter->u.dwarf_reg = dwarf_block_to_dwarf_reg
12117             (DW_BLOCK (loc)->data, &DW_BLOCK (loc)->data[DW_BLOCK (loc)->size]);
12118           if (parameter->u.dwarf_reg != -1)
12119             parameter->kind = CALL_SITE_PARAMETER_DWARF_REG;
12120           else if (dwarf_block_to_sp_offset (gdbarch, DW_BLOCK (loc)->data,
12121                                     &DW_BLOCK (loc)->data[DW_BLOCK (loc)->size],
12122                                              &parameter->u.fb_offset))
12123             parameter->kind = CALL_SITE_PARAMETER_FB_OFFSET;
12124           else
12125             {
12126               complaint (&symfile_complaints,
12127                          _("Only single DW_OP_reg or DW_OP_fbreg is supported "
12128                            "for DW_FORM_block* DW_AT_location is supported for "
12129                            "DW_TAG_call_site child DIE 0x%x "
12130                            "[in module %s]"),
12131                          to_underlying (child_die->sect_off),
12132                          objfile_name (objfile));
12133               continue;
12134             }
12135         }
12136
12137       attr = dwarf2_attr (child_die, DW_AT_call_value, cu);
12138       if (attr == NULL)
12139         attr = dwarf2_attr (child_die, DW_AT_GNU_call_site_value, cu);
12140       if (!attr_form_is_block (attr))
12141         {
12142           complaint (&symfile_complaints,
12143                      _("No DW_FORM_block* DW_AT_call_value for "
12144                        "DW_TAG_call_site child DIE 0x%x [in module %s]"),
12145                      to_underlying (child_die->sect_off),
12146                      objfile_name (objfile));
12147           continue;
12148         }
12149       parameter->value = DW_BLOCK (attr)->data;
12150       parameter->value_size = DW_BLOCK (attr)->size;
12151
12152       /* Parameters are not pre-cleared by memset above.  */
12153       parameter->data_value = NULL;
12154       parameter->data_value_size = 0;
12155       call_site->parameter_count++;
12156
12157       attr = dwarf2_attr (child_die, DW_AT_call_data_value, cu);
12158       if (attr == NULL)
12159         attr = dwarf2_attr (child_die, DW_AT_GNU_call_site_data_value, cu);
12160       if (attr)
12161         {
12162           if (!attr_form_is_block (attr))
12163             complaint (&symfile_complaints,
12164                        _("No DW_FORM_block* DW_AT_call_data_value for "
12165                          "DW_TAG_call_site child DIE 0x%x [in module %s]"),
12166                        to_underlying (child_die->sect_off),
12167                        objfile_name (objfile));
12168           else
12169             {
12170               parameter->data_value = DW_BLOCK (attr)->data;
12171               parameter->data_value_size = DW_BLOCK (attr)->size;
12172             }
12173         }
12174     }
12175 }
12176
12177 /* Call CALLBACK from DW_AT_ranges attribute value OFFSET
12178    reading .debug_rnglists.
12179    Callback's type should be:
12180     void (CORE_ADDR range_beginning, CORE_ADDR range_end)
12181    Return true if the attributes are present and valid, otherwise,
12182    return false.  */
12183
12184 template <typename Callback>
12185 static bool
12186 dwarf2_rnglists_process (unsigned offset, struct dwarf2_cu *cu,
12187                          Callback &&callback)
12188 {
12189   struct objfile *objfile = cu->objfile;
12190   struct gdbarch *gdbarch = get_objfile_arch (objfile);
12191   struct comp_unit_head *cu_header = &cu->header;
12192   bfd *obfd = objfile->obfd;
12193   unsigned int addr_size = cu_header->addr_size;
12194   CORE_ADDR mask = ~(~(CORE_ADDR)1 << (addr_size * 8 - 1));
12195   /* Base address selection entry.  */
12196   CORE_ADDR base;
12197   int found_base;
12198   unsigned int dummy;
12199   const gdb_byte *buffer;
12200   CORE_ADDR low = 0;
12201   CORE_ADDR high = 0;
12202   CORE_ADDR baseaddr;
12203   bool overflow = false;
12204
12205   found_base = cu->base_known;
12206   base = cu->base_address;
12207
12208   dwarf2_read_section (objfile, &dwarf2_per_objfile->rnglists);
12209   if (offset >= dwarf2_per_objfile->rnglists.size)
12210     {
12211       complaint (&symfile_complaints,
12212                  _("Offset %d out of bounds for DW_AT_ranges attribute"),
12213                  offset);
12214       return false;
12215     }
12216   buffer = dwarf2_per_objfile->rnglists.buffer + offset;
12217
12218   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
12219
12220   while (1)
12221     {
12222       /* Initialize it due to a false compiler warning.  */
12223       CORE_ADDR range_beginning = 0, range_end = 0;
12224       const gdb_byte *buf_end = (dwarf2_per_objfile->rnglists.buffer
12225                                  + dwarf2_per_objfile->rnglists.size);
12226       unsigned int bytes_read;
12227
12228       if (buffer == buf_end)
12229         {
12230           overflow = true;
12231           break;
12232         }
12233       const auto rlet = static_cast<enum dwarf_range_list_entry>(*buffer++);
12234       switch (rlet)
12235         {
12236         case DW_RLE_end_of_list:
12237           break;
12238         case DW_RLE_base_address:
12239           if (buffer + cu->header.addr_size > buf_end)
12240             {
12241               overflow = true;
12242               break;
12243             }
12244           base = read_address (obfd, buffer, cu, &bytes_read);
12245           found_base = 1;
12246           buffer += bytes_read;
12247           break;
12248         case DW_RLE_start_length:
12249           if (buffer + cu->header.addr_size > buf_end)
12250             {
12251               overflow = true;
12252               break;
12253             }
12254           range_beginning = read_address (obfd, buffer, cu, &bytes_read);
12255           buffer += bytes_read;
12256           range_end = (range_beginning
12257                        + read_unsigned_leb128 (obfd, buffer, &bytes_read));
12258           buffer += bytes_read;
12259           if (buffer > buf_end)
12260             {
12261               overflow = true;
12262               break;
12263             }
12264           break;
12265         case DW_RLE_offset_pair:
12266           range_beginning = read_unsigned_leb128 (obfd, buffer, &bytes_read);
12267           buffer += bytes_read;
12268           if (buffer > buf_end)
12269             {
12270               overflow = true;
12271               break;
12272             }
12273           range_end = read_unsigned_leb128 (obfd, buffer, &bytes_read);
12274           buffer += bytes_read;
12275           if (buffer > buf_end)
12276             {
12277               overflow = true;
12278               break;
12279             }
12280           break;
12281         case DW_RLE_start_end:
12282           if (buffer + 2 * cu->header.addr_size > buf_end)
12283             {
12284               overflow = true;
12285               break;
12286             }
12287           range_beginning = read_address (obfd, buffer, cu, &bytes_read);
12288           buffer += bytes_read;
12289           range_end = read_address (obfd, buffer, cu, &bytes_read);
12290           buffer += bytes_read;
12291           break;
12292         default:
12293           complaint (&symfile_complaints,
12294                      _("Invalid .debug_rnglists data (no base address)"));
12295           return false;
12296         }
12297       if (rlet == DW_RLE_end_of_list || overflow)
12298         break;
12299       if (rlet == DW_RLE_base_address)
12300         continue;
12301
12302       if (!found_base)
12303         {
12304           /* We have no valid base address for the ranges
12305              data.  */
12306           complaint (&symfile_complaints,
12307                      _("Invalid .debug_rnglists data (no base address)"));
12308           return false;
12309         }
12310
12311       if (range_beginning > range_end)
12312         {
12313           /* Inverted range entries are invalid.  */
12314           complaint (&symfile_complaints,
12315                      _("Invalid .debug_rnglists data (inverted range)"));
12316           return false;
12317         }
12318
12319       /* Empty range entries have no effect.  */
12320       if (range_beginning == range_end)
12321         continue;
12322
12323       range_beginning += base;
12324       range_end += base;
12325
12326       /* A not-uncommon case of bad debug info.
12327          Don't pollute the addrmap with bad data.  */
12328       if (range_beginning + baseaddr == 0
12329           && !dwarf2_per_objfile->has_section_at_zero)
12330         {
12331           complaint (&symfile_complaints,
12332                      _(".debug_rnglists entry has start address of zero"
12333                        " [in module %s]"), objfile_name (objfile));
12334           continue;
12335         }
12336
12337       callback (range_beginning, range_end);
12338     }
12339
12340   if (overflow)
12341     {
12342       complaint (&symfile_complaints,
12343                  _("Offset %d is not terminated "
12344                    "for DW_AT_ranges attribute"),
12345                  offset);
12346       return false;
12347     }
12348
12349   return true;
12350 }
12351
12352 /* Call CALLBACK from DW_AT_ranges attribute value OFFSET reading .debug_ranges.
12353    Callback's type should be:
12354     void (CORE_ADDR range_beginning, CORE_ADDR range_end)
12355    Return 1 if the attributes are present and valid, otherwise, return 0.  */
12356
12357 template <typename Callback>
12358 static int
12359 dwarf2_ranges_process (unsigned offset, struct dwarf2_cu *cu,
12360                        Callback &&callback)
12361 {
12362   struct objfile *objfile = cu->objfile;
12363   struct gdbarch *gdbarch = get_objfile_arch (objfile);
12364   struct comp_unit_head *cu_header = &cu->header;
12365   bfd *obfd = objfile->obfd;
12366   unsigned int addr_size = cu_header->addr_size;
12367   CORE_ADDR mask = ~(~(CORE_ADDR)1 << (addr_size * 8 - 1));
12368   /* Base address selection entry.  */
12369   CORE_ADDR base;
12370   int found_base;
12371   unsigned int dummy;
12372   const gdb_byte *buffer;
12373   CORE_ADDR baseaddr;
12374
12375   if (cu_header->version >= 5)
12376     return dwarf2_rnglists_process (offset, cu, callback);
12377
12378   found_base = cu->base_known;
12379   base = cu->base_address;
12380
12381   dwarf2_read_section (objfile, &dwarf2_per_objfile->ranges);
12382   if (offset >= dwarf2_per_objfile->ranges.size)
12383     {
12384       complaint (&symfile_complaints,
12385                  _("Offset %d out of bounds for DW_AT_ranges attribute"),
12386                  offset);
12387       return 0;
12388     }
12389   buffer = dwarf2_per_objfile->ranges.buffer + offset;
12390
12391   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
12392
12393   while (1)
12394     {
12395       CORE_ADDR range_beginning, range_end;
12396
12397       range_beginning = read_address (obfd, buffer, cu, &dummy);
12398       buffer += addr_size;
12399       range_end = read_address (obfd, buffer, cu, &dummy);
12400       buffer += addr_size;
12401       offset += 2 * addr_size;
12402
12403       /* An end of list marker is a pair of zero addresses.  */
12404       if (range_beginning == 0 && range_end == 0)
12405         /* Found the end of list entry.  */
12406         break;
12407
12408       /* Each base address selection entry is a pair of 2 values.
12409          The first is the largest possible address, the second is
12410          the base address.  Check for a base address here.  */
12411       if ((range_beginning & mask) == mask)
12412         {
12413           /* If we found the largest possible address, then we already
12414              have the base address in range_end.  */
12415           base = range_end;
12416           found_base = 1;
12417           continue;
12418         }
12419
12420       if (!found_base)
12421         {
12422           /* We have no valid base address for the ranges
12423              data.  */
12424           complaint (&symfile_complaints,
12425                      _("Invalid .debug_ranges data (no base address)"));
12426           return 0;
12427         }
12428
12429       if (range_beginning > range_end)
12430         {
12431           /* Inverted range entries are invalid.  */
12432           complaint (&symfile_complaints,
12433                      _("Invalid .debug_ranges data (inverted range)"));
12434           return 0;
12435         }
12436
12437       /* Empty range entries have no effect.  */
12438       if (range_beginning == range_end)
12439         continue;
12440
12441       range_beginning += base;
12442       range_end += base;
12443
12444       /* A not-uncommon case of bad debug info.
12445          Don't pollute the addrmap with bad data.  */
12446       if (range_beginning + baseaddr == 0
12447           && !dwarf2_per_objfile->has_section_at_zero)
12448         {
12449           complaint (&symfile_complaints,
12450                      _(".debug_ranges entry has start address of zero"
12451                        " [in module %s]"), objfile_name (objfile));
12452           continue;
12453         }
12454
12455       callback (range_beginning, range_end);
12456     }
12457
12458   return 1;
12459 }
12460
12461 /* Get low and high pc attributes from DW_AT_ranges attribute value OFFSET.
12462    Return 1 if the attributes are present and valid, otherwise, return 0.
12463    If RANGES_PST is not NULL we should setup `objfile->psymtabs_addrmap'.  */
12464
12465 static int
12466 dwarf2_ranges_read (unsigned offset, CORE_ADDR *low_return,
12467                     CORE_ADDR *high_return, struct dwarf2_cu *cu,
12468                     struct partial_symtab *ranges_pst)
12469 {
12470   struct objfile *objfile = cu->objfile;
12471   struct gdbarch *gdbarch = get_objfile_arch (objfile);
12472   const CORE_ADDR baseaddr = ANOFFSET (objfile->section_offsets,
12473                                        SECT_OFF_TEXT (objfile));
12474   int low_set = 0;
12475   CORE_ADDR low = 0;
12476   CORE_ADDR high = 0;
12477   int retval;
12478
12479   retval = dwarf2_ranges_process (offset, cu,
12480     [&] (CORE_ADDR range_beginning, CORE_ADDR range_end)
12481     {
12482       if (ranges_pst != NULL)
12483         {
12484           CORE_ADDR lowpc;
12485           CORE_ADDR highpc;
12486
12487           lowpc = gdbarch_adjust_dwarf2_addr (gdbarch,
12488                                               range_beginning + baseaddr);
12489           highpc = gdbarch_adjust_dwarf2_addr (gdbarch,
12490                                                range_end + baseaddr);
12491           addrmap_set_empty (objfile->psymtabs_addrmap, lowpc, highpc - 1,
12492                              ranges_pst);
12493         }
12494
12495       /* FIXME: This is recording everything as a low-high
12496          segment of consecutive addresses.  We should have a
12497          data structure for discontiguous block ranges
12498          instead.  */
12499       if (! low_set)
12500         {
12501           low = range_beginning;
12502           high = range_end;
12503           low_set = 1;
12504         }
12505       else
12506         {
12507           if (range_beginning < low)
12508             low = range_beginning;
12509           if (range_end > high)
12510             high = range_end;
12511         }
12512     });
12513   if (!retval)
12514     return 0;
12515
12516   if (! low_set)
12517     /* If the first entry is an end-of-list marker, the range
12518        describes an empty scope, i.e. no instructions.  */
12519     return 0;
12520
12521   if (low_return)
12522     *low_return = low;
12523   if (high_return)
12524     *high_return = high;
12525   return 1;
12526 }
12527
12528 /* Get low and high pc attributes from a die.  See enum pc_bounds_kind
12529    definition for the return value.  *LOWPC and *HIGHPC are set iff
12530    neither PC_BOUNDS_NOT_PRESENT nor PC_BOUNDS_INVALID are returned.  */
12531
12532 static enum pc_bounds_kind
12533 dwarf2_get_pc_bounds (struct die_info *die, CORE_ADDR *lowpc,
12534                       CORE_ADDR *highpc, struct dwarf2_cu *cu,
12535                       struct partial_symtab *pst)
12536 {
12537   struct attribute *attr;
12538   struct attribute *attr_high;
12539   CORE_ADDR low = 0;
12540   CORE_ADDR high = 0;
12541   enum pc_bounds_kind ret;
12542
12543   attr_high = dwarf2_attr (die, DW_AT_high_pc, cu);
12544   if (attr_high)
12545     {
12546       attr = dwarf2_attr (die, DW_AT_low_pc, cu);
12547       if (attr)
12548         {
12549           low = attr_value_as_address (attr);
12550           high = attr_value_as_address (attr_high);
12551           if (cu->header.version >= 4 && attr_form_is_constant (attr_high))
12552             high += low;
12553         }
12554       else
12555         /* Found high w/o low attribute.  */
12556         return PC_BOUNDS_INVALID;
12557
12558       /* Found consecutive range of addresses.  */
12559       ret = PC_BOUNDS_HIGH_LOW;
12560     }
12561   else
12562     {
12563       attr = dwarf2_attr (die, DW_AT_ranges, cu);
12564       if (attr != NULL)
12565         {
12566           /* DW_AT_ranges_base does not apply to DIEs from the DWO skeleton.
12567              We take advantage of the fact that DW_AT_ranges does not appear
12568              in DW_TAG_compile_unit of DWO files.  */
12569           int need_ranges_base = die->tag != DW_TAG_compile_unit;
12570           unsigned int ranges_offset = (DW_UNSND (attr)
12571                                         + (need_ranges_base
12572                                            ? cu->ranges_base
12573                                            : 0));
12574
12575           /* Value of the DW_AT_ranges attribute is the offset in the
12576              .debug_ranges section.  */
12577           if (!dwarf2_ranges_read (ranges_offset, &low, &high, cu, pst))
12578             return PC_BOUNDS_INVALID;
12579           /* Found discontinuous range of addresses.  */
12580           ret = PC_BOUNDS_RANGES;
12581         }
12582       else
12583         return PC_BOUNDS_NOT_PRESENT;
12584     }
12585
12586   /* read_partial_die has also the strict LOW < HIGH requirement.  */
12587   if (high <= low)
12588     return PC_BOUNDS_INVALID;
12589
12590   /* When using the GNU linker, .gnu.linkonce. sections are used to
12591      eliminate duplicate copies of functions and vtables and such.
12592      The linker will arbitrarily choose one and discard the others.
12593      The AT_*_pc values for such functions refer to local labels in
12594      these sections.  If the section from that file was discarded, the
12595      labels are not in the output, so the relocs get a value of 0.
12596      If this is a discarded function, mark the pc bounds as invalid,
12597      so that GDB will ignore it.  */
12598   if (low == 0 && !dwarf2_per_objfile->has_section_at_zero)
12599     return PC_BOUNDS_INVALID;
12600
12601   *lowpc = low;
12602   if (highpc)
12603     *highpc = high;
12604   return ret;
12605 }
12606
12607 /* Assuming that DIE represents a subprogram DIE or a lexical block, get
12608    its low and high PC addresses.  Do nothing if these addresses could not
12609    be determined.  Otherwise, set LOWPC to the low address if it is smaller,
12610    and HIGHPC to the high address if greater than HIGHPC.  */
12611
12612 static void
12613 dwarf2_get_subprogram_pc_bounds (struct die_info *die,
12614                                  CORE_ADDR *lowpc, CORE_ADDR *highpc,
12615                                  struct dwarf2_cu *cu)
12616 {
12617   CORE_ADDR low, high;
12618   struct die_info *child = die->child;
12619
12620   if (dwarf2_get_pc_bounds (die, &low, &high, cu, NULL) >= PC_BOUNDS_RANGES)
12621     {
12622       *lowpc = std::min (*lowpc, low);
12623       *highpc = std::max (*highpc, high);
12624     }
12625
12626   /* If the language does not allow nested subprograms (either inside
12627      subprograms or lexical blocks), we're done.  */
12628   if (cu->language != language_ada)
12629     return;
12630
12631   /* Check all the children of the given DIE.  If it contains nested
12632      subprograms, then check their pc bounds.  Likewise, we need to
12633      check lexical blocks as well, as they may also contain subprogram
12634      definitions.  */
12635   while (child && child->tag)
12636     {
12637       if (child->tag == DW_TAG_subprogram
12638           || child->tag == DW_TAG_lexical_block)
12639         dwarf2_get_subprogram_pc_bounds (child, lowpc, highpc, cu);
12640       child = sibling_die (child);
12641     }
12642 }
12643
12644 /* Get the low and high pc's represented by the scope DIE, and store
12645    them in *LOWPC and *HIGHPC.  If the correct values can't be
12646    determined, set *LOWPC to -1 and *HIGHPC to 0.  */
12647
12648 static void
12649 get_scope_pc_bounds (struct die_info *die,
12650                      CORE_ADDR *lowpc, CORE_ADDR *highpc,
12651                      struct dwarf2_cu *cu)
12652 {
12653   CORE_ADDR best_low = (CORE_ADDR) -1;
12654   CORE_ADDR best_high = (CORE_ADDR) 0;
12655   CORE_ADDR current_low, current_high;
12656
12657   if (dwarf2_get_pc_bounds (die, &current_low, &current_high, cu, NULL)
12658       >= PC_BOUNDS_RANGES)
12659     {
12660       best_low = current_low;
12661       best_high = current_high;
12662     }
12663   else
12664     {
12665       struct die_info *child = die->child;
12666
12667       while (child && child->tag)
12668         {
12669           switch (child->tag) {
12670           case DW_TAG_subprogram:
12671             dwarf2_get_subprogram_pc_bounds (child, &best_low, &best_high, cu);
12672             break;
12673           case DW_TAG_namespace:
12674           case DW_TAG_module:
12675             /* FIXME: carlton/2004-01-16: Should we do this for
12676                DW_TAG_class_type/DW_TAG_structure_type, too?  I think
12677                that current GCC's always emit the DIEs corresponding
12678                to definitions of methods of classes as children of a
12679                DW_TAG_compile_unit or DW_TAG_namespace (as opposed to
12680                the DIEs giving the declarations, which could be
12681                anywhere).  But I don't see any reason why the
12682                standards says that they have to be there.  */
12683             get_scope_pc_bounds (child, &current_low, &current_high, cu);
12684
12685             if (current_low != ((CORE_ADDR) -1))
12686               {
12687                 best_low = std::min (best_low, current_low);
12688                 best_high = std::max (best_high, current_high);
12689               }
12690             break;
12691           default:
12692             /* Ignore.  */
12693             break;
12694           }
12695
12696           child = sibling_die (child);
12697         }
12698     }
12699
12700   *lowpc = best_low;
12701   *highpc = best_high;
12702 }
12703
12704 /* Record the address ranges for BLOCK, offset by BASEADDR, as given
12705    in DIE.  */
12706
12707 static void
12708 dwarf2_record_block_ranges (struct die_info *die, struct block *block,
12709                             CORE_ADDR baseaddr, struct dwarf2_cu *cu)
12710 {
12711   struct objfile *objfile = cu->objfile;
12712   struct gdbarch *gdbarch = get_objfile_arch (objfile);
12713   struct attribute *attr;
12714   struct attribute *attr_high;
12715
12716   attr_high = dwarf2_attr (die, DW_AT_high_pc, cu);
12717   if (attr_high)
12718     {
12719       attr = dwarf2_attr (die, DW_AT_low_pc, cu);
12720       if (attr)
12721         {
12722           CORE_ADDR low = attr_value_as_address (attr);
12723           CORE_ADDR high = attr_value_as_address (attr_high);
12724
12725           if (cu->header.version >= 4 && attr_form_is_constant (attr_high))
12726             high += low;
12727
12728           low = gdbarch_adjust_dwarf2_addr (gdbarch, low + baseaddr);
12729           high = gdbarch_adjust_dwarf2_addr (gdbarch, high + baseaddr);
12730           record_block_range (block, low, high - 1);
12731         }
12732     }
12733
12734   attr = dwarf2_attr (die, DW_AT_ranges, cu);
12735   if (attr)
12736     {
12737       bfd *obfd = objfile->obfd;
12738       /* DW_AT_ranges_base does not apply to DIEs from the DWO skeleton.
12739          We take advantage of the fact that DW_AT_ranges does not appear
12740          in DW_TAG_compile_unit of DWO files.  */
12741       int need_ranges_base = die->tag != DW_TAG_compile_unit;
12742
12743       /* The value of the DW_AT_ranges attribute is the offset of the
12744          address range list in the .debug_ranges section.  */
12745       unsigned long offset = (DW_UNSND (attr)
12746                               + (need_ranges_base ? cu->ranges_base : 0));
12747       const gdb_byte *buffer;
12748
12749       /* For some target architectures, but not others, the
12750          read_address function sign-extends the addresses it returns.
12751          To recognize base address selection entries, we need a
12752          mask.  */
12753       unsigned int addr_size = cu->header.addr_size;
12754       CORE_ADDR base_select_mask = ~(~(CORE_ADDR)1 << (addr_size * 8 - 1));
12755
12756       /* The base address, to which the next pair is relative.  Note
12757          that this 'base' is a DWARF concept: most entries in a range
12758          list are relative, to reduce the number of relocs against the
12759          debugging information.  This is separate from this function's
12760          'baseaddr' argument, which GDB uses to relocate debugging
12761          information from a shared library based on the address at
12762          which the library was loaded.  */
12763       CORE_ADDR base = cu->base_address;
12764       int base_known = cu->base_known;
12765
12766       dwarf2_ranges_process (offset, cu,
12767         [&] (CORE_ADDR start, CORE_ADDR end)
12768         {
12769           start += baseaddr;
12770           end += baseaddr;
12771           start = gdbarch_adjust_dwarf2_addr (gdbarch, start);
12772           end = gdbarch_adjust_dwarf2_addr (gdbarch, end);
12773           record_block_range (block, start, end - 1);
12774         });
12775     }
12776 }
12777
12778 /* Check whether the producer field indicates either of GCC < 4.6, or the
12779    Intel C/C++ compiler, and cache the result in CU.  */
12780
12781 static void
12782 check_producer (struct dwarf2_cu *cu)
12783 {
12784   int major, minor;
12785
12786   if (cu->producer == NULL)
12787     {
12788       /* For unknown compilers expect their behavior is DWARF version
12789          compliant.
12790
12791          GCC started to support .debug_types sections by -gdwarf-4 since
12792          gcc-4.5.x.  As the .debug_types sections are missing DW_AT_producer
12793          for their space efficiency GDB cannot workaround gcc-4.5.x -gdwarf-4
12794          combination.  gcc-4.5.x -gdwarf-4 binaries have DW_AT_accessibility
12795          interpreted incorrectly by GDB now - GCC PR debug/48229.  */
12796     }
12797   else if (producer_is_gcc (cu->producer, &major, &minor))
12798     {
12799       cu->producer_is_gxx_lt_4_6 = major < 4 || (major == 4 && minor < 6);
12800       cu->producer_is_gcc_lt_4_3 = major < 4 || (major == 4 && minor < 3);
12801     }
12802   else if (startswith (cu->producer, "Intel(R) C"))
12803     cu->producer_is_icc = 1;
12804   else
12805     {
12806       /* For other non-GCC compilers, expect their behavior is DWARF version
12807          compliant.  */
12808     }
12809
12810   cu->checked_producer = 1;
12811 }
12812
12813 /* Check for GCC PR debug/45124 fix which is not present in any G++ version up
12814    to 4.5.any while it is present already in G++ 4.6.0 - the PR has been fixed
12815    during 4.6.0 experimental.  */
12816
12817 static int
12818 producer_is_gxx_lt_4_6 (struct dwarf2_cu *cu)
12819 {
12820   if (!cu->checked_producer)
12821     check_producer (cu);
12822
12823   return cu->producer_is_gxx_lt_4_6;
12824 }
12825
12826 /* Return the default accessibility type if it is not overriden by
12827    DW_AT_accessibility.  */
12828
12829 static enum dwarf_access_attribute
12830 dwarf2_default_access_attribute (struct die_info *die, struct dwarf2_cu *cu)
12831 {
12832   if (cu->header.version < 3 || producer_is_gxx_lt_4_6 (cu))
12833     {
12834       /* The default DWARF 2 accessibility for members is public, the default
12835          accessibility for inheritance is private.  */
12836
12837       if (die->tag != DW_TAG_inheritance)
12838         return DW_ACCESS_public;
12839       else
12840         return DW_ACCESS_private;
12841     }
12842   else
12843     {
12844       /* DWARF 3+ defines the default accessibility a different way.  The same
12845          rules apply now for DW_TAG_inheritance as for the members and it only
12846          depends on the container kind.  */
12847
12848       if (die->parent->tag == DW_TAG_class_type)
12849         return DW_ACCESS_private;
12850       else
12851         return DW_ACCESS_public;
12852     }
12853 }
12854
12855 /* Look for DW_AT_data_member_location.  Set *OFFSET to the byte
12856    offset.  If the attribute was not found return 0, otherwise return
12857    1.  If it was found but could not properly be handled, set *OFFSET
12858    to 0.  */
12859
12860 static int
12861 handle_data_member_location (struct die_info *die, struct dwarf2_cu *cu,
12862                              LONGEST *offset)
12863 {
12864   struct attribute *attr;
12865
12866   attr = dwarf2_attr (die, DW_AT_data_member_location, cu);
12867   if (attr != NULL)
12868     {
12869       *offset = 0;
12870
12871       /* Note that we do not check for a section offset first here.
12872          This is because DW_AT_data_member_location is new in DWARF 4,
12873          so if we see it, we can assume that a constant form is really
12874          a constant and not a section offset.  */
12875       if (attr_form_is_constant (attr))
12876         *offset = dwarf2_get_attr_constant_value (attr, 0);
12877       else if (attr_form_is_section_offset (attr))
12878         dwarf2_complex_location_expr_complaint ();
12879       else if (attr_form_is_block (attr))
12880         *offset = decode_locdesc (DW_BLOCK (attr), cu);
12881       else
12882         dwarf2_complex_location_expr_complaint ();
12883
12884       return 1;
12885     }
12886
12887   return 0;
12888 }
12889
12890 /* Add an aggregate field to the field list.  */
12891
12892 static void
12893 dwarf2_add_field (struct field_info *fip, struct die_info *die,
12894                   struct dwarf2_cu *cu)
12895 {
12896   struct objfile *objfile = cu->objfile;
12897   struct gdbarch *gdbarch = get_objfile_arch (objfile);
12898   struct nextfield *new_field;
12899   struct attribute *attr;
12900   struct field *fp;
12901   const char *fieldname = "";
12902
12903   /* Allocate a new field list entry and link it in.  */
12904   new_field = XNEW (struct nextfield);
12905   make_cleanup (xfree, new_field);
12906   memset (new_field, 0, sizeof (struct nextfield));
12907
12908   if (die->tag == DW_TAG_inheritance)
12909     {
12910       new_field->next = fip->baseclasses;
12911       fip->baseclasses = new_field;
12912     }
12913   else
12914     {
12915       new_field->next = fip->fields;
12916       fip->fields = new_field;
12917     }
12918   fip->nfields++;
12919
12920   attr = dwarf2_attr (die, DW_AT_accessibility, cu);
12921   if (attr)
12922     new_field->accessibility = DW_UNSND (attr);
12923   else
12924     new_field->accessibility = dwarf2_default_access_attribute (die, cu);
12925   if (new_field->accessibility != DW_ACCESS_public)
12926     fip->non_public_fields = 1;
12927
12928   attr = dwarf2_attr (die, DW_AT_virtuality, cu);
12929   if (attr)
12930     new_field->virtuality = DW_UNSND (attr);
12931   else
12932     new_field->virtuality = DW_VIRTUALITY_none;
12933
12934   fp = &new_field->field;
12935
12936   if (die->tag == DW_TAG_member && ! die_is_declaration (die, cu))
12937     {
12938       LONGEST offset;
12939
12940       /* Data member other than a C++ static data member.  */
12941
12942       /* Get type of field.  */
12943       fp->type = die_type (die, cu);
12944
12945       SET_FIELD_BITPOS (*fp, 0);
12946
12947       /* Get bit size of field (zero if none).  */
12948       attr = dwarf2_attr (die, DW_AT_bit_size, cu);
12949       if (attr)
12950         {
12951           FIELD_BITSIZE (*fp) = DW_UNSND (attr);
12952         }
12953       else
12954         {
12955           FIELD_BITSIZE (*fp) = 0;
12956         }
12957
12958       /* Get bit offset of field.  */
12959       if (handle_data_member_location (die, cu, &offset))
12960         SET_FIELD_BITPOS (*fp, offset * bits_per_byte);
12961       attr = dwarf2_attr (die, DW_AT_bit_offset, cu);
12962       if (attr)
12963         {
12964           if (gdbarch_bits_big_endian (gdbarch))
12965             {
12966               /* For big endian bits, the DW_AT_bit_offset gives the
12967                  additional bit offset from the MSB of the containing
12968                  anonymous object to the MSB of the field.  We don't
12969                  have to do anything special since we don't need to
12970                  know the size of the anonymous object.  */
12971               SET_FIELD_BITPOS (*fp, FIELD_BITPOS (*fp) + DW_UNSND (attr));
12972             }
12973           else
12974             {
12975               /* For little endian bits, compute the bit offset to the
12976                  MSB of the anonymous object, subtract off the number of
12977                  bits from the MSB of the field to the MSB of the
12978                  object, and then subtract off the number of bits of
12979                  the field itself.  The result is the bit offset of
12980                  the LSB of the field.  */
12981               int anonymous_size;
12982               int bit_offset = DW_UNSND (attr);
12983
12984               attr = dwarf2_attr (die, DW_AT_byte_size, cu);
12985               if (attr)
12986                 {
12987                   /* The size of the anonymous object containing
12988                      the bit field is explicit, so use the
12989                      indicated size (in bytes).  */
12990                   anonymous_size = DW_UNSND (attr);
12991                 }
12992               else
12993                 {
12994                   /* The size of the anonymous object containing
12995                      the bit field must be inferred from the type
12996                      attribute of the data member containing the
12997                      bit field.  */
12998                   anonymous_size = TYPE_LENGTH (fp->type);
12999                 }
13000               SET_FIELD_BITPOS (*fp,
13001                                 (FIELD_BITPOS (*fp)
13002                                  + anonymous_size * bits_per_byte
13003                                  - bit_offset - FIELD_BITSIZE (*fp)));
13004             }
13005         }
13006       attr = dwarf2_attr (die, DW_AT_data_bit_offset, cu);
13007       if (attr != NULL)
13008         SET_FIELD_BITPOS (*fp, (FIELD_BITPOS (*fp)
13009                                 + dwarf2_get_attr_constant_value (attr, 0)));
13010
13011       /* Get name of field.  */
13012       fieldname = dwarf2_name (die, cu);
13013       if (fieldname == NULL)
13014         fieldname = "";
13015
13016       /* The name is already allocated along with this objfile, so we don't
13017          need to duplicate it for the type.  */
13018       fp->name = fieldname;
13019
13020       /* Change accessibility for artificial fields (e.g. virtual table
13021          pointer or virtual base class pointer) to private.  */
13022       if (dwarf2_attr (die, DW_AT_artificial, cu))
13023         {
13024           FIELD_ARTIFICIAL (*fp) = 1;
13025           new_field->accessibility = DW_ACCESS_private;
13026           fip->non_public_fields = 1;
13027         }
13028     }
13029   else if (die->tag == DW_TAG_member || die->tag == DW_TAG_variable)
13030     {
13031       /* C++ static member.  */
13032
13033       /* NOTE: carlton/2002-11-05: It should be a DW_TAG_member that
13034          is a declaration, but all versions of G++ as of this writing
13035          (so through at least 3.2.1) incorrectly generate
13036          DW_TAG_variable tags.  */
13037
13038       const char *physname;
13039
13040       /* Get name of field.  */
13041       fieldname = dwarf2_name (die, cu);
13042       if (fieldname == NULL)
13043         return;
13044
13045       attr = dwarf2_attr (die, DW_AT_const_value, cu);
13046       if (attr
13047           /* Only create a symbol if this is an external value.
13048              new_symbol checks this and puts the value in the global symbol
13049              table, which we want.  If it is not external, new_symbol
13050              will try to put the value in cu->list_in_scope which is wrong.  */
13051           && dwarf2_flag_true_p (die, DW_AT_external, cu))
13052         {
13053           /* A static const member, not much different than an enum as far as
13054              we're concerned, except that we can support more types.  */
13055           new_symbol (die, NULL, cu);
13056         }
13057
13058       /* Get physical name.  */
13059       physname = dwarf2_physname (fieldname, die, cu);
13060
13061       /* The name is already allocated along with this objfile, so we don't
13062          need to duplicate it for the type.  */
13063       SET_FIELD_PHYSNAME (*fp, physname ? physname : "");
13064       FIELD_TYPE (*fp) = die_type (die, cu);
13065       FIELD_NAME (*fp) = fieldname;
13066     }
13067   else if (die->tag == DW_TAG_inheritance)
13068     {
13069       LONGEST offset;
13070
13071       /* C++ base class field.  */
13072       if (handle_data_member_location (die, cu, &offset))
13073         SET_FIELD_BITPOS (*fp, offset * bits_per_byte);
13074       FIELD_BITSIZE (*fp) = 0;
13075       FIELD_TYPE (*fp) = die_type (die, cu);
13076       FIELD_NAME (*fp) = type_name_no_tag (fp->type);
13077       fip->nbaseclasses++;
13078     }
13079 }
13080
13081 /* Add a typedef defined in the scope of the FIP's class.  */
13082
13083 static void
13084 dwarf2_add_typedef (struct field_info *fip, struct die_info *die,
13085                     struct dwarf2_cu *cu)
13086 {
13087   struct typedef_field_list *new_field;
13088   struct typedef_field *fp;
13089
13090   /* Allocate a new field list entry and link it in.  */
13091   new_field = XCNEW (struct typedef_field_list);
13092   make_cleanup (xfree, new_field);
13093
13094   gdb_assert (die->tag == DW_TAG_typedef);
13095
13096   fp = &new_field->field;
13097
13098   /* Get name of field.  */
13099   fp->name = dwarf2_name (die, cu);
13100   if (fp->name == NULL)
13101     return;
13102
13103   fp->type = read_type_die (die, cu);
13104
13105   new_field->next = fip->typedef_field_list;
13106   fip->typedef_field_list = new_field;
13107   fip->typedef_field_list_count++;
13108 }
13109
13110 /* Create the vector of fields, and attach it to the type.  */
13111
13112 static void
13113 dwarf2_attach_fields_to_type (struct field_info *fip, struct type *type,
13114                               struct dwarf2_cu *cu)
13115 {
13116   int nfields = fip->nfields;
13117
13118   /* Record the field count, allocate space for the array of fields,
13119      and create blank accessibility bitfields if necessary.  */
13120   TYPE_NFIELDS (type) = nfields;
13121   TYPE_FIELDS (type) = (struct field *)
13122     TYPE_ALLOC (type, sizeof (struct field) * nfields);
13123   memset (TYPE_FIELDS (type), 0, sizeof (struct field) * nfields);
13124
13125   if (fip->non_public_fields && cu->language != language_ada)
13126     {
13127       ALLOCATE_CPLUS_STRUCT_TYPE (type);
13128
13129       TYPE_FIELD_PRIVATE_BITS (type) =
13130         (B_TYPE *) TYPE_ALLOC (type, B_BYTES (nfields));
13131       B_CLRALL (TYPE_FIELD_PRIVATE_BITS (type), nfields);
13132
13133       TYPE_FIELD_PROTECTED_BITS (type) =
13134         (B_TYPE *) TYPE_ALLOC (type, B_BYTES (nfields));
13135       B_CLRALL (TYPE_FIELD_PROTECTED_BITS (type), nfields);
13136
13137       TYPE_FIELD_IGNORE_BITS (type) =
13138         (B_TYPE *) TYPE_ALLOC (type, B_BYTES (nfields));
13139       B_CLRALL (TYPE_FIELD_IGNORE_BITS (type), nfields);
13140     }
13141
13142   /* If the type has baseclasses, allocate and clear a bit vector for
13143      TYPE_FIELD_VIRTUAL_BITS.  */
13144   if (fip->nbaseclasses && cu->language != language_ada)
13145     {
13146       int num_bytes = B_BYTES (fip->nbaseclasses);
13147       unsigned char *pointer;
13148
13149       ALLOCATE_CPLUS_STRUCT_TYPE (type);
13150       pointer = (unsigned char *) TYPE_ALLOC (type, num_bytes);
13151       TYPE_FIELD_VIRTUAL_BITS (type) = pointer;
13152       B_CLRALL (TYPE_FIELD_VIRTUAL_BITS (type), fip->nbaseclasses);
13153       TYPE_N_BASECLASSES (type) = fip->nbaseclasses;
13154     }
13155
13156   /* Copy the saved-up fields into the field vector.  Start from the head of
13157      the list, adding to the tail of the field array, so that they end up in
13158      the same order in the array in which they were added to the list.  */
13159   while (nfields-- > 0)
13160     {
13161       struct nextfield *fieldp;
13162
13163       if (fip->fields)
13164         {
13165           fieldp = fip->fields;
13166           fip->fields = fieldp->next;
13167         }
13168       else
13169         {
13170           fieldp = fip->baseclasses;
13171           fip->baseclasses = fieldp->next;
13172         }
13173
13174       TYPE_FIELD (type, nfields) = fieldp->field;
13175       switch (fieldp->accessibility)
13176         {
13177         case DW_ACCESS_private:
13178           if (cu->language != language_ada)
13179             SET_TYPE_FIELD_PRIVATE (type, nfields);
13180           break;
13181
13182         case DW_ACCESS_protected:
13183           if (cu->language != language_ada)
13184             SET_TYPE_FIELD_PROTECTED (type, nfields);
13185           break;
13186
13187         case DW_ACCESS_public:
13188           break;
13189
13190         default:
13191           /* Unknown accessibility.  Complain and treat it as public.  */
13192           {
13193             complaint (&symfile_complaints, _("unsupported accessibility %d"),
13194                        fieldp->accessibility);
13195           }
13196           break;
13197         }
13198       if (nfields < fip->nbaseclasses)
13199         {
13200           switch (fieldp->virtuality)
13201             {
13202             case DW_VIRTUALITY_virtual:
13203             case DW_VIRTUALITY_pure_virtual:
13204               if (cu->language == language_ada)
13205                 error (_("unexpected virtuality in component of Ada type"));
13206               SET_TYPE_FIELD_VIRTUAL (type, nfields);
13207               break;
13208             }
13209         }
13210     }
13211 }
13212
13213 /* Return true if this member function is a constructor, false
13214    otherwise.  */
13215
13216 static int
13217 dwarf2_is_constructor (struct die_info *die, struct dwarf2_cu *cu)
13218 {
13219   const char *fieldname;
13220   const char *type_name;
13221   int len;
13222
13223   if (die->parent == NULL)
13224     return 0;
13225
13226   if (die->parent->tag != DW_TAG_structure_type
13227       && die->parent->tag != DW_TAG_union_type
13228       && die->parent->tag != DW_TAG_class_type)
13229     return 0;
13230
13231   fieldname = dwarf2_name (die, cu);
13232   type_name = dwarf2_name (die->parent, cu);
13233   if (fieldname == NULL || type_name == NULL)
13234     return 0;
13235
13236   len = strlen (fieldname);
13237   return (strncmp (fieldname, type_name, len) == 0
13238           && (type_name[len] == '\0' || type_name[len] == '<'));
13239 }
13240
13241 /* Add a member function to the proper fieldlist.  */
13242
13243 static void
13244 dwarf2_add_member_fn (struct field_info *fip, struct die_info *die,
13245                       struct type *type, struct dwarf2_cu *cu)
13246 {
13247   struct objfile *objfile = cu->objfile;
13248   struct attribute *attr;
13249   struct fnfieldlist *flp;
13250   int i;
13251   struct fn_field *fnp;
13252   const char *fieldname;
13253   struct nextfnfield *new_fnfield;
13254   struct type *this_type;
13255   enum dwarf_access_attribute accessibility;
13256
13257   if (cu->language == language_ada)
13258     error (_("unexpected member function in Ada type"));
13259
13260   /* Get name of member function.  */
13261   fieldname = dwarf2_name (die, cu);
13262   if (fieldname == NULL)
13263     return;
13264
13265   /* Look up member function name in fieldlist.  */
13266   for (i = 0; i < fip->nfnfields; i++)
13267     {
13268       if (strcmp (fip->fnfieldlists[i].name, fieldname) == 0)
13269         break;
13270     }
13271
13272   /* Create new list element if necessary.  */
13273   if (i < fip->nfnfields)
13274     flp = &fip->fnfieldlists[i];
13275   else
13276     {
13277       if ((fip->nfnfields % DW_FIELD_ALLOC_CHUNK) == 0)
13278         {
13279           fip->fnfieldlists = (struct fnfieldlist *)
13280             xrealloc (fip->fnfieldlists,
13281                       (fip->nfnfields + DW_FIELD_ALLOC_CHUNK)
13282                       * sizeof (struct fnfieldlist));
13283           if (fip->nfnfields == 0)
13284             make_cleanup (free_current_contents, &fip->fnfieldlists);
13285         }
13286       flp = &fip->fnfieldlists[fip->nfnfields];
13287       flp->name = fieldname;
13288       flp->length = 0;
13289       flp->head = NULL;
13290       i = fip->nfnfields++;
13291     }
13292
13293   /* Create a new member function field and chain it to the field list
13294      entry.  */
13295   new_fnfield = XNEW (struct nextfnfield);
13296   make_cleanup (xfree, new_fnfield);
13297   memset (new_fnfield, 0, sizeof (struct nextfnfield));
13298   new_fnfield->next = flp->head;
13299   flp->head = new_fnfield;
13300   flp->length++;
13301
13302   /* Fill in the member function field info.  */
13303   fnp = &new_fnfield->fnfield;
13304
13305   /* Delay processing of the physname until later.  */
13306   if (cu->language == language_cplus)
13307     {
13308       add_to_method_list (type, i, flp->length - 1, fieldname,
13309                           die, cu);
13310     }
13311   else
13312     {
13313       const char *physname = dwarf2_physname (fieldname, die, cu);
13314       fnp->physname = physname ? physname : "";
13315     }
13316
13317   fnp->type = alloc_type (objfile);
13318   this_type = read_type_die (die, cu);
13319   if (this_type && TYPE_CODE (this_type) == TYPE_CODE_FUNC)
13320     {
13321       int nparams = TYPE_NFIELDS (this_type);
13322
13323       /* TYPE is the domain of this method, and THIS_TYPE is the type
13324            of the method itself (TYPE_CODE_METHOD).  */
13325       smash_to_method_type (fnp->type, type,
13326                             TYPE_TARGET_TYPE (this_type),
13327                             TYPE_FIELDS (this_type),
13328                             TYPE_NFIELDS (this_type),
13329                             TYPE_VARARGS (this_type));
13330
13331       /* Handle static member functions.
13332          Dwarf2 has no clean way to discern C++ static and non-static
13333          member functions.  G++ helps GDB by marking the first
13334          parameter for non-static member functions (which is the this
13335          pointer) as artificial.  We obtain this information from
13336          read_subroutine_type via TYPE_FIELD_ARTIFICIAL.  */
13337       if (nparams == 0 || TYPE_FIELD_ARTIFICIAL (this_type, 0) == 0)
13338         fnp->voffset = VOFFSET_STATIC;
13339     }
13340   else
13341     complaint (&symfile_complaints, _("member function type missing for '%s'"),
13342                dwarf2_full_name (fieldname, die, cu));
13343
13344   /* Get fcontext from DW_AT_containing_type if present.  */
13345   if (dwarf2_attr (die, DW_AT_containing_type, cu) != NULL)
13346     fnp->fcontext = die_containing_type (die, cu);
13347
13348   /* dwarf2 doesn't have stubbed physical names, so the setting of is_const and
13349      is_volatile is irrelevant, as it is needed by gdb_mangle_name only.  */
13350
13351   /* Get accessibility.  */
13352   attr = dwarf2_attr (die, DW_AT_accessibility, cu);
13353   if (attr)
13354     accessibility = (enum dwarf_access_attribute) DW_UNSND (attr);
13355   else
13356     accessibility = dwarf2_default_access_attribute (die, cu);
13357   switch (accessibility)
13358     {
13359     case DW_ACCESS_private:
13360       fnp->is_private = 1;
13361       break;
13362     case DW_ACCESS_protected:
13363       fnp->is_protected = 1;
13364       break;
13365     }
13366
13367   /* Check for artificial methods.  */
13368   attr = dwarf2_attr (die, DW_AT_artificial, cu);
13369   if (attr && DW_UNSND (attr) != 0)
13370     fnp->is_artificial = 1;
13371
13372   fnp->is_constructor = dwarf2_is_constructor (die, cu);
13373
13374   /* Get index in virtual function table if it is a virtual member
13375      function.  For older versions of GCC, this is an offset in the
13376      appropriate virtual table, as specified by DW_AT_containing_type.
13377      For everyone else, it is an expression to be evaluated relative
13378      to the object address.  */
13379
13380   attr = dwarf2_attr (die, DW_AT_vtable_elem_location, cu);
13381   if (attr)
13382     {
13383       if (attr_form_is_block (attr) && DW_BLOCK (attr)->size > 0)
13384         {
13385           if (DW_BLOCK (attr)->data[0] == DW_OP_constu)
13386             {
13387               /* Old-style GCC.  */
13388               fnp->voffset = decode_locdesc (DW_BLOCK (attr), cu) + 2;
13389             }
13390           else if (DW_BLOCK (attr)->data[0] == DW_OP_deref
13391                    || (DW_BLOCK (attr)->size > 1
13392                        && DW_BLOCK (attr)->data[0] == DW_OP_deref_size
13393                        && DW_BLOCK (attr)->data[1] == cu->header.addr_size))
13394             {
13395               fnp->voffset = decode_locdesc (DW_BLOCK (attr), cu);
13396               if ((fnp->voffset % cu->header.addr_size) != 0)
13397                 dwarf2_complex_location_expr_complaint ();
13398               else
13399                 fnp->voffset /= cu->header.addr_size;
13400               fnp->voffset += 2;
13401             }
13402           else
13403             dwarf2_complex_location_expr_complaint ();
13404
13405           if (!fnp->fcontext)
13406             {
13407               /* If there is no `this' field and no DW_AT_containing_type,
13408                  we cannot actually find a base class context for the
13409                  vtable!  */
13410               if (TYPE_NFIELDS (this_type) == 0
13411                   || !TYPE_FIELD_ARTIFICIAL (this_type, 0))
13412                 {
13413                   complaint (&symfile_complaints,
13414                              _("cannot determine context for virtual member "
13415                                "function \"%s\" (offset %d)"),
13416                              fieldname, to_underlying (die->sect_off));
13417                 }
13418               else
13419                 {
13420                   fnp->fcontext
13421                     = TYPE_TARGET_TYPE (TYPE_FIELD_TYPE (this_type, 0));
13422                 }
13423             }
13424         }
13425       else if (attr_form_is_section_offset (attr))
13426         {
13427           dwarf2_complex_location_expr_complaint ();
13428         }
13429       else
13430         {
13431           dwarf2_invalid_attrib_class_complaint ("DW_AT_vtable_elem_location",
13432                                                  fieldname);
13433         }
13434     }
13435   else
13436     {
13437       attr = dwarf2_attr (die, DW_AT_virtuality, cu);
13438       if (attr && DW_UNSND (attr))
13439         {
13440           /* GCC does this, as of 2008-08-25; PR debug/37237.  */
13441           complaint (&symfile_complaints,
13442                      _("Member function \"%s\" (offset %d) is virtual "
13443                        "but the vtable offset is not specified"),
13444                      fieldname, to_underlying (die->sect_off));
13445           ALLOCATE_CPLUS_STRUCT_TYPE (type);
13446           TYPE_CPLUS_DYNAMIC (type) = 1;
13447         }
13448     }
13449 }
13450
13451 /* Create the vector of member function fields, and attach it to the type.  */
13452
13453 static void
13454 dwarf2_attach_fn_fields_to_type (struct field_info *fip, struct type *type,
13455                                  struct dwarf2_cu *cu)
13456 {
13457   struct fnfieldlist *flp;
13458   int i;
13459
13460   if (cu->language == language_ada)
13461     error (_("unexpected member functions in Ada type"));
13462
13463   ALLOCATE_CPLUS_STRUCT_TYPE (type);
13464   TYPE_FN_FIELDLISTS (type) = (struct fn_fieldlist *)
13465     TYPE_ALLOC (type, sizeof (struct fn_fieldlist) * fip->nfnfields);
13466
13467   for (i = 0, flp = fip->fnfieldlists; i < fip->nfnfields; i++, flp++)
13468     {
13469       struct nextfnfield *nfp = flp->head;
13470       struct fn_fieldlist *fn_flp = &TYPE_FN_FIELDLIST (type, i);
13471       int k;
13472
13473       TYPE_FN_FIELDLIST_NAME (type, i) = flp->name;
13474       TYPE_FN_FIELDLIST_LENGTH (type, i) = flp->length;
13475       fn_flp->fn_fields = (struct fn_field *)
13476         TYPE_ALLOC (type, sizeof (struct fn_field) * flp->length);
13477       for (k = flp->length; (k--, nfp); nfp = nfp->next)
13478         fn_flp->fn_fields[k] = nfp->fnfield;
13479     }
13480
13481   TYPE_NFN_FIELDS (type) = fip->nfnfields;
13482 }
13483
13484 /* Returns non-zero if NAME is the name of a vtable member in CU's
13485    language, zero otherwise.  */
13486 static int
13487 is_vtable_name (const char *name, struct dwarf2_cu *cu)
13488 {
13489   static const char vptr[] = "_vptr";
13490   static const char vtable[] = "vtable";
13491
13492   /* Look for the C++ form of the vtable.  */
13493   if (startswith (name, vptr) && is_cplus_marker (name[sizeof (vptr) - 1]))
13494     return 1;
13495
13496   return 0;
13497 }
13498
13499 /* GCC outputs unnamed structures that are really pointers to member
13500    functions, with the ABI-specified layout.  If TYPE describes
13501    such a structure, smash it into a member function type.
13502
13503    GCC shouldn't do this; it should just output pointer to member DIEs.
13504    This is GCC PR debug/28767.  */
13505
13506 static void
13507 quirk_gcc_member_function_pointer (struct type *type, struct objfile *objfile)
13508 {
13509   struct type *pfn_type, *self_type, *new_type;
13510
13511   /* Check for a structure with no name and two children.  */
13512   if (TYPE_CODE (type) != TYPE_CODE_STRUCT || TYPE_NFIELDS (type) != 2)
13513     return;
13514
13515   /* Check for __pfn and __delta members.  */
13516   if (TYPE_FIELD_NAME (type, 0) == NULL
13517       || strcmp (TYPE_FIELD_NAME (type, 0), "__pfn") != 0
13518       || TYPE_FIELD_NAME (type, 1) == NULL
13519       || strcmp (TYPE_FIELD_NAME (type, 1), "__delta") != 0)
13520     return;
13521
13522   /* Find the type of the method.  */
13523   pfn_type = TYPE_FIELD_TYPE (type, 0);
13524   if (pfn_type == NULL
13525       || TYPE_CODE (pfn_type) != TYPE_CODE_PTR
13526       || TYPE_CODE (TYPE_TARGET_TYPE (pfn_type)) != TYPE_CODE_FUNC)
13527     return;
13528
13529   /* Look for the "this" argument.  */
13530   pfn_type = TYPE_TARGET_TYPE (pfn_type);
13531   if (TYPE_NFIELDS (pfn_type) == 0
13532       /* || TYPE_FIELD_TYPE (pfn_type, 0) == NULL */
13533       || TYPE_CODE (TYPE_FIELD_TYPE (pfn_type, 0)) != TYPE_CODE_PTR)
13534     return;
13535
13536   self_type = TYPE_TARGET_TYPE (TYPE_FIELD_TYPE (pfn_type, 0));
13537   new_type = alloc_type (objfile);
13538   smash_to_method_type (new_type, self_type, TYPE_TARGET_TYPE (pfn_type),
13539                         TYPE_FIELDS (pfn_type), TYPE_NFIELDS (pfn_type),
13540                         TYPE_VARARGS (pfn_type));
13541   smash_to_methodptr_type (type, new_type);
13542 }
13543
13544 /* Return non-zero if the CU's PRODUCER string matches the Intel C/C++ compiler
13545    (icc).  */
13546
13547 static int
13548 producer_is_icc (struct dwarf2_cu *cu)
13549 {
13550   if (!cu->checked_producer)
13551     check_producer (cu);
13552
13553   return cu->producer_is_icc;
13554 }
13555
13556 /* Called when we find the DIE that starts a structure or union scope
13557    (definition) to create a type for the structure or union.  Fill in
13558    the type's name and general properties; the members will not be
13559    processed until process_structure_scope.  A symbol table entry for
13560    the type will also not be done until process_structure_scope (assuming
13561    the type has a name).
13562
13563    NOTE: we need to call these functions regardless of whether or not the
13564    DIE has a DW_AT_name attribute, since it might be an anonymous
13565    structure or union.  This gets the type entered into our set of
13566    user defined types.  */
13567
13568 static struct type *
13569 read_structure_type (struct die_info *die, struct dwarf2_cu *cu)
13570 {
13571   struct objfile *objfile = cu->objfile;
13572   struct type *type;
13573   struct attribute *attr;
13574   const char *name;
13575
13576   /* If the definition of this type lives in .debug_types, read that type.
13577      Don't follow DW_AT_specification though, that will take us back up
13578      the chain and we want to go down.  */
13579   attr = dwarf2_attr_no_follow (die, DW_AT_signature);
13580   if (attr)
13581     {
13582       type = get_DW_AT_signature_type (die, attr, cu);
13583
13584       /* The type's CU may not be the same as CU.
13585          Ensure TYPE is recorded with CU in die_type_hash.  */
13586       return set_die_type (die, type, cu);
13587     }
13588
13589   type = alloc_type (objfile);
13590   INIT_CPLUS_SPECIFIC (type);
13591
13592   name = dwarf2_name (die, cu);
13593   if (name != NULL)
13594     {
13595       if (cu->language == language_cplus
13596           || cu->language == language_d
13597           || cu->language == language_rust)
13598         {
13599           const char *full_name = dwarf2_full_name (name, die, cu);
13600
13601           /* dwarf2_full_name might have already finished building the DIE's
13602              type.  If so, there is no need to continue.  */
13603           if (get_die_type (die, cu) != NULL)
13604             return get_die_type (die, cu);
13605
13606           TYPE_TAG_NAME (type) = full_name;
13607           if (die->tag == DW_TAG_structure_type
13608               || die->tag == DW_TAG_class_type)
13609             TYPE_NAME (type) = TYPE_TAG_NAME (type);
13610         }
13611       else
13612         {
13613           /* The name is already allocated along with this objfile, so
13614              we don't need to duplicate it for the type.  */
13615           TYPE_TAG_NAME (type) = name;
13616           if (die->tag == DW_TAG_class_type)
13617             TYPE_NAME (type) = TYPE_TAG_NAME (type);
13618         }
13619     }
13620
13621   if (die->tag == DW_TAG_structure_type)
13622     {
13623       TYPE_CODE (type) = TYPE_CODE_STRUCT;
13624     }
13625   else if (die->tag == DW_TAG_union_type)
13626     {
13627       TYPE_CODE (type) = TYPE_CODE_UNION;
13628     }
13629   else
13630     {
13631       TYPE_CODE (type) = TYPE_CODE_STRUCT;
13632     }
13633
13634   if (cu->language == language_cplus && die->tag == DW_TAG_class_type)
13635     TYPE_DECLARED_CLASS (type) = 1;
13636
13637   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
13638   if (attr)
13639     {
13640       if (attr_form_is_constant (attr))
13641         TYPE_LENGTH (type) = DW_UNSND (attr);
13642       else
13643         {
13644           /* For the moment, dynamic type sizes are not supported
13645              by GDB's struct type.  The actual size is determined
13646              on-demand when resolving the type of a given object,
13647              so set the type's length to zero for now.  Otherwise,
13648              we record an expression as the length, and that expression
13649              could lead to a very large value, which could eventually
13650              lead to us trying to allocate that much memory when creating
13651              a value of that type.  */
13652           TYPE_LENGTH (type) = 0;
13653         }
13654     }
13655   else
13656     {
13657       TYPE_LENGTH (type) = 0;
13658     }
13659
13660   if (producer_is_icc (cu) && (TYPE_LENGTH (type) == 0))
13661     {
13662       /* ICC does not output the required DW_AT_declaration
13663          on incomplete types, but gives them a size of zero.  */
13664       TYPE_STUB (type) = 1;
13665     }
13666   else
13667     TYPE_STUB_SUPPORTED (type) = 1;
13668
13669   if (die_is_declaration (die, cu))
13670     TYPE_STUB (type) = 1;
13671   else if (attr == NULL && die->child == NULL
13672            && producer_is_realview (cu->producer))
13673     /* RealView does not output the required DW_AT_declaration
13674        on incomplete types.  */
13675     TYPE_STUB (type) = 1;
13676
13677   /* We need to add the type field to the die immediately so we don't
13678      infinitely recurse when dealing with pointers to the structure
13679      type within the structure itself.  */
13680   set_die_type (die, type, cu);
13681
13682   /* set_die_type should be already done.  */
13683   set_descriptive_type (type, die, cu);
13684
13685   return type;
13686 }
13687
13688 /* Finish creating a structure or union type, including filling in
13689    its members and creating a symbol for it.  */
13690
13691 static void
13692 process_structure_scope (struct die_info *die, struct dwarf2_cu *cu)
13693 {
13694   struct objfile *objfile = cu->objfile;
13695   struct die_info *child_die;
13696   struct type *type;
13697
13698   type = get_die_type (die, cu);
13699   if (type == NULL)
13700     type = read_structure_type (die, cu);
13701
13702   if (die->child != NULL && ! die_is_declaration (die, cu))
13703     {
13704       struct field_info fi;
13705       VEC (symbolp) *template_args = NULL;
13706       struct cleanup *back_to = make_cleanup (null_cleanup, 0);
13707
13708       memset (&fi, 0, sizeof (struct field_info));
13709
13710       child_die = die->child;
13711
13712       while (child_die && child_die->tag)
13713         {
13714           if (child_die->tag == DW_TAG_member
13715               || child_die->tag == DW_TAG_variable)
13716             {
13717               /* NOTE: carlton/2002-11-05: A C++ static data member
13718                  should be a DW_TAG_member that is a declaration, but
13719                  all versions of G++ as of this writing (so through at
13720                  least 3.2.1) incorrectly generate DW_TAG_variable
13721                  tags for them instead.  */
13722               dwarf2_add_field (&fi, child_die, cu);
13723             }
13724           else if (child_die->tag == DW_TAG_subprogram)
13725             {
13726               /* Rust doesn't have member functions in the C++ sense.
13727                  However, it does emit ordinary functions as children
13728                  of a struct DIE.  */
13729               if (cu->language == language_rust)
13730                 read_func_scope (child_die, cu);
13731               else
13732                 {
13733                   /* C++ member function.  */
13734                   dwarf2_add_member_fn (&fi, child_die, type, cu);
13735                 }
13736             }
13737           else if (child_die->tag == DW_TAG_inheritance)
13738             {
13739               /* C++ base class field.  */
13740               dwarf2_add_field (&fi, child_die, cu);
13741             }
13742           else if (child_die->tag == DW_TAG_typedef)
13743             dwarf2_add_typedef (&fi, child_die, cu);
13744           else if (child_die->tag == DW_TAG_template_type_param
13745                    || child_die->tag == DW_TAG_template_value_param)
13746             {
13747               struct symbol *arg = new_symbol (child_die, NULL, cu);
13748
13749               if (arg != NULL)
13750                 VEC_safe_push (symbolp, template_args, arg);
13751             }
13752
13753           child_die = sibling_die (child_die);
13754         }
13755
13756       /* Attach template arguments to type.  */
13757       if (! VEC_empty (symbolp, template_args))
13758         {
13759           ALLOCATE_CPLUS_STRUCT_TYPE (type);
13760           TYPE_N_TEMPLATE_ARGUMENTS (type)
13761             = VEC_length (symbolp, template_args);
13762           TYPE_TEMPLATE_ARGUMENTS (type)
13763             = XOBNEWVEC (&objfile->objfile_obstack,
13764                          struct symbol *,
13765                          TYPE_N_TEMPLATE_ARGUMENTS (type));
13766           memcpy (TYPE_TEMPLATE_ARGUMENTS (type),
13767                   VEC_address (symbolp, template_args),
13768                   (TYPE_N_TEMPLATE_ARGUMENTS (type)
13769                    * sizeof (struct symbol *)));
13770           VEC_free (symbolp, template_args);
13771         }
13772
13773       /* Attach fields and member functions to the type.  */
13774       if (fi.nfields)
13775         dwarf2_attach_fields_to_type (&fi, type, cu);
13776       if (fi.nfnfields)
13777         {
13778           dwarf2_attach_fn_fields_to_type (&fi, type, cu);
13779
13780           /* Get the type which refers to the base class (possibly this
13781              class itself) which contains the vtable pointer for the current
13782              class from the DW_AT_containing_type attribute.  This use of
13783              DW_AT_containing_type is a GNU extension.  */
13784
13785           if (dwarf2_attr (die, DW_AT_containing_type, cu) != NULL)
13786             {
13787               struct type *t = die_containing_type (die, cu);
13788
13789               set_type_vptr_basetype (type, t);
13790               if (type == t)
13791                 {
13792                   int i;
13793
13794                   /* Our own class provides vtbl ptr.  */
13795                   for (i = TYPE_NFIELDS (t) - 1;
13796                        i >= TYPE_N_BASECLASSES (t);
13797                        --i)
13798                     {
13799                       const char *fieldname = TYPE_FIELD_NAME (t, i);
13800
13801                       if (is_vtable_name (fieldname, cu))
13802                         {
13803                           set_type_vptr_fieldno (type, i);
13804                           break;
13805                         }
13806                     }
13807
13808                   /* Complain if virtual function table field not found.  */
13809                   if (i < TYPE_N_BASECLASSES (t))
13810                     complaint (&symfile_complaints,
13811                                _("virtual function table pointer "
13812                                  "not found when defining class '%s'"),
13813                                TYPE_TAG_NAME (type) ? TYPE_TAG_NAME (type) :
13814                                "");
13815                 }
13816               else
13817                 {
13818                   set_type_vptr_fieldno (type, TYPE_VPTR_FIELDNO (t));
13819                 }
13820             }
13821           else if (cu->producer
13822                    && startswith (cu->producer, "IBM(R) XL C/C++ Advanced Edition"))
13823             {
13824               /* The IBM XLC compiler does not provide direct indication
13825                  of the containing type, but the vtable pointer is
13826                  always named __vfp.  */
13827
13828               int i;
13829
13830               for (i = TYPE_NFIELDS (type) - 1;
13831                    i >= TYPE_N_BASECLASSES (type);
13832                    --i)
13833                 {
13834                   if (strcmp (TYPE_FIELD_NAME (type, i), "__vfp") == 0)
13835                     {
13836                       set_type_vptr_fieldno (type, i);
13837                       set_type_vptr_basetype (type, type);
13838                       break;
13839                     }
13840                 }
13841             }
13842         }
13843
13844       /* Copy fi.typedef_field_list linked list elements content into the
13845          allocated array TYPE_TYPEDEF_FIELD_ARRAY (type).  */
13846       if (fi.typedef_field_list)
13847         {
13848           int i = fi.typedef_field_list_count;
13849
13850           ALLOCATE_CPLUS_STRUCT_TYPE (type);
13851           TYPE_TYPEDEF_FIELD_ARRAY (type)
13852             = ((struct typedef_field *)
13853                TYPE_ALLOC (type, sizeof (TYPE_TYPEDEF_FIELD (type, 0)) * i));
13854           TYPE_TYPEDEF_FIELD_COUNT (type) = i;
13855
13856           /* Reverse the list order to keep the debug info elements order.  */
13857           while (--i >= 0)
13858             {
13859               struct typedef_field *dest, *src;
13860
13861               dest = &TYPE_TYPEDEF_FIELD (type, i);
13862               src = &fi.typedef_field_list->field;
13863               fi.typedef_field_list = fi.typedef_field_list->next;
13864               *dest = *src;
13865             }
13866         }
13867
13868       do_cleanups (back_to);
13869     }
13870
13871   quirk_gcc_member_function_pointer (type, objfile);
13872
13873   /* NOTE: carlton/2004-03-16: GCC 3.4 (or at least one of its
13874      snapshots) has been known to create a die giving a declaration
13875      for a class that has, as a child, a die giving a definition for a
13876      nested class.  So we have to process our children even if the
13877      current die is a declaration.  Normally, of course, a declaration
13878      won't have any children at all.  */
13879
13880   child_die = die->child;
13881
13882   while (child_die != NULL && child_die->tag)
13883     {
13884       if (child_die->tag == DW_TAG_member
13885           || child_die->tag == DW_TAG_variable
13886           || child_die->tag == DW_TAG_inheritance
13887           || child_die->tag == DW_TAG_template_value_param
13888           || child_die->tag == DW_TAG_template_type_param)
13889         {
13890           /* Do nothing.  */
13891         }
13892       else
13893         process_die (child_die, cu);
13894
13895       child_die = sibling_die (child_die);
13896     }
13897
13898   /* Do not consider external references.  According to the DWARF standard,
13899      these DIEs are identified by the fact that they have no byte_size
13900      attribute, and a declaration attribute.  */
13901   if (dwarf2_attr (die, DW_AT_byte_size, cu) != NULL
13902       || !die_is_declaration (die, cu))
13903     new_symbol (die, type, cu);
13904 }
13905
13906 /* Assuming DIE is an enumeration type, and TYPE is its associated type,
13907    update TYPE using some information only available in DIE's children.  */
13908
13909 static void
13910 update_enumeration_type_from_children (struct die_info *die,
13911                                        struct type *type,
13912                                        struct dwarf2_cu *cu)
13913 {
13914   struct die_info *child_die;
13915   int unsigned_enum = 1;
13916   int flag_enum = 1;
13917   ULONGEST mask = 0;
13918
13919   auto_obstack obstack;
13920
13921   for (child_die = die->child;
13922        child_die != NULL && child_die->tag;
13923        child_die = sibling_die (child_die))
13924     {
13925       struct attribute *attr;
13926       LONGEST value;
13927       const gdb_byte *bytes;
13928       struct dwarf2_locexpr_baton *baton;
13929       const char *name;
13930
13931       if (child_die->tag != DW_TAG_enumerator)
13932         continue;
13933
13934       attr = dwarf2_attr (child_die, DW_AT_const_value, cu);
13935       if (attr == NULL)
13936         continue;
13937
13938       name = dwarf2_name (child_die, cu);
13939       if (name == NULL)
13940         name = "<anonymous enumerator>";
13941
13942       dwarf2_const_value_attr (attr, type, name, &obstack, cu,
13943                                &value, &bytes, &baton);
13944       if (value < 0)
13945         {
13946           unsigned_enum = 0;
13947           flag_enum = 0;
13948         }
13949       else if ((mask & value) != 0)
13950         flag_enum = 0;
13951       else
13952         mask |= value;
13953
13954       /* If we already know that the enum type is neither unsigned, nor
13955          a flag type, no need to look at the rest of the enumerates.  */
13956       if (!unsigned_enum && !flag_enum)
13957         break;
13958     }
13959
13960   if (unsigned_enum)
13961     TYPE_UNSIGNED (type) = 1;
13962   if (flag_enum)
13963     TYPE_FLAG_ENUM (type) = 1;
13964 }
13965
13966 /* Given a DW_AT_enumeration_type die, set its type.  We do not
13967    complete the type's fields yet, or create any symbols.  */
13968
13969 static struct type *
13970 read_enumeration_type (struct die_info *die, struct dwarf2_cu *cu)
13971 {
13972   struct objfile *objfile = cu->objfile;
13973   struct type *type;
13974   struct attribute *attr;
13975   const char *name;
13976
13977   /* If the definition of this type lives in .debug_types, read that type.
13978      Don't follow DW_AT_specification though, that will take us back up
13979      the chain and we want to go down.  */
13980   attr = dwarf2_attr_no_follow (die, DW_AT_signature);
13981   if (attr)
13982     {
13983       type = get_DW_AT_signature_type (die, attr, cu);
13984
13985       /* The type's CU may not be the same as CU.
13986          Ensure TYPE is recorded with CU in die_type_hash.  */
13987       return set_die_type (die, type, cu);
13988     }
13989
13990   type = alloc_type (objfile);
13991
13992   TYPE_CODE (type) = TYPE_CODE_ENUM;
13993   name = dwarf2_full_name (NULL, die, cu);
13994   if (name != NULL)
13995     TYPE_TAG_NAME (type) = name;
13996
13997   attr = dwarf2_attr (die, DW_AT_type, cu);
13998   if (attr != NULL)
13999     {
14000       struct type *underlying_type = die_type (die, cu);
14001
14002       TYPE_TARGET_TYPE (type) = underlying_type;
14003     }
14004
14005   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
14006   if (attr)
14007     {
14008       TYPE_LENGTH (type) = DW_UNSND (attr);
14009     }
14010   else
14011     {
14012       TYPE_LENGTH (type) = 0;
14013     }
14014
14015   /* The enumeration DIE can be incomplete.  In Ada, any type can be
14016      declared as private in the package spec, and then defined only
14017      inside the package body.  Such types are known as Taft Amendment
14018      Types.  When another package uses such a type, an incomplete DIE
14019      may be generated by the compiler.  */
14020   if (die_is_declaration (die, cu))
14021     TYPE_STUB (type) = 1;
14022
14023   /* Finish the creation of this type by using the enum's children.
14024      We must call this even when the underlying type has been provided
14025      so that we can determine if we're looking at a "flag" enum.  */
14026   update_enumeration_type_from_children (die, type, cu);
14027
14028   /* If this type has an underlying type that is not a stub, then we
14029      may use its attributes.  We always use the "unsigned" attribute
14030      in this situation, because ordinarily we guess whether the type
14031      is unsigned -- but the guess can be wrong and the underlying type
14032      can tell us the reality.  However, we defer to a local size
14033      attribute if one exists, because this lets the compiler override
14034      the underlying type if needed.  */
14035   if (TYPE_TARGET_TYPE (type) != NULL && !TYPE_STUB (TYPE_TARGET_TYPE (type)))
14036     {
14037       TYPE_UNSIGNED (type) = TYPE_UNSIGNED (TYPE_TARGET_TYPE (type));
14038       if (TYPE_LENGTH (type) == 0)
14039         TYPE_LENGTH (type) = TYPE_LENGTH (TYPE_TARGET_TYPE (type));
14040     }
14041
14042   TYPE_DECLARED_CLASS (type) = dwarf2_flag_true_p (die, DW_AT_enum_class, cu);
14043
14044   return set_die_type (die, type, cu);
14045 }
14046
14047 /* Given a pointer to a die which begins an enumeration, process all
14048    the dies that define the members of the enumeration, and create the
14049    symbol for the enumeration type.
14050
14051    NOTE: We reverse the order of the element list.  */
14052
14053 static void
14054 process_enumeration_scope (struct die_info *die, struct dwarf2_cu *cu)
14055 {
14056   struct type *this_type;
14057
14058   this_type = get_die_type (die, cu);
14059   if (this_type == NULL)
14060     this_type = read_enumeration_type (die, cu);
14061
14062   if (die->child != NULL)
14063     {
14064       struct die_info *child_die;
14065       struct symbol *sym;
14066       struct field *fields = NULL;
14067       int num_fields = 0;
14068       const char *name;
14069
14070       child_die = die->child;
14071       while (child_die && child_die->tag)
14072         {
14073           if (child_die->tag != DW_TAG_enumerator)
14074             {
14075               process_die (child_die, cu);
14076             }
14077           else
14078             {
14079               name = dwarf2_name (child_die, cu);
14080               if (name)
14081                 {
14082                   sym = new_symbol (child_die, this_type, cu);
14083
14084                   if ((num_fields % DW_FIELD_ALLOC_CHUNK) == 0)
14085                     {
14086                       fields = (struct field *)
14087                         xrealloc (fields,
14088                                   (num_fields + DW_FIELD_ALLOC_CHUNK)
14089                                   * sizeof (struct field));
14090                     }
14091
14092                   FIELD_NAME (fields[num_fields]) = SYMBOL_LINKAGE_NAME (sym);
14093                   FIELD_TYPE (fields[num_fields]) = NULL;
14094                   SET_FIELD_ENUMVAL (fields[num_fields], SYMBOL_VALUE (sym));
14095                   FIELD_BITSIZE (fields[num_fields]) = 0;
14096
14097                   num_fields++;
14098                 }
14099             }
14100
14101           child_die = sibling_die (child_die);
14102         }
14103
14104       if (num_fields)
14105         {
14106           TYPE_NFIELDS (this_type) = num_fields;
14107           TYPE_FIELDS (this_type) = (struct field *)
14108             TYPE_ALLOC (this_type, sizeof (struct field) * num_fields);
14109           memcpy (TYPE_FIELDS (this_type), fields,
14110                   sizeof (struct field) * num_fields);
14111           xfree (fields);
14112         }
14113     }
14114
14115   /* If we are reading an enum from a .debug_types unit, and the enum
14116      is a declaration, and the enum is not the signatured type in the
14117      unit, then we do not want to add a symbol for it.  Adding a
14118      symbol would in some cases obscure the true definition of the
14119      enum, giving users an incomplete type when the definition is
14120      actually available.  Note that we do not want to do this for all
14121      enums which are just declarations, because C++0x allows forward
14122      enum declarations.  */
14123   if (cu->per_cu->is_debug_types
14124       && die_is_declaration (die, cu))
14125     {
14126       struct signatured_type *sig_type;
14127
14128       sig_type = (struct signatured_type *) cu->per_cu;
14129       gdb_assert (to_underlying (sig_type->type_offset_in_section) != 0);
14130       if (sig_type->type_offset_in_section != die->sect_off)
14131         return;
14132     }
14133
14134   new_symbol (die, this_type, cu);
14135 }
14136
14137 /* Extract all information from a DW_TAG_array_type DIE and put it in
14138    the DIE's type field.  For now, this only handles one dimensional
14139    arrays.  */
14140
14141 static struct type *
14142 read_array_type (struct die_info *die, struct dwarf2_cu *cu)
14143 {
14144   struct objfile *objfile = cu->objfile;
14145   struct die_info *child_die;
14146   struct type *type;
14147   struct type *element_type, *range_type, *index_type;
14148   struct type **range_types = NULL;
14149   struct attribute *attr;
14150   int ndim = 0;
14151   struct cleanup *back_to;
14152   const char *name;
14153   unsigned int bit_stride = 0;
14154
14155   element_type = die_type (die, cu);
14156
14157   /* The die_type call above may have already set the type for this DIE.  */
14158   type = get_die_type (die, cu);
14159   if (type)
14160     return type;
14161
14162   attr = dwarf2_attr (die, DW_AT_byte_stride, cu);
14163   if (attr != NULL)
14164     bit_stride = DW_UNSND (attr) * 8;
14165
14166   attr = dwarf2_attr (die, DW_AT_bit_stride, cu);
14167   if (attr != NULL)
14168     bit_stride = DW_UNSND (attr);
14169
14170   /* Irix 6.2 native cc creates array types without children for
14171      arrays with unspecified length.  */
14172   if (die->child == NULL)
14173     {
14174       index_type = objfile_type (objfile)->builtin_int;
14175       range_type = create_static_range_type (NULL, index_type, 0, -1);
14176       type = create_array_type_with_stride (NULL, element_type, range_type,
14177                                             bit_stride);
14178       return set_die_type (die, type, cu);
14179     }
14180
14181   back_to = make_cleanup (null_cleanup, NULL);
14182   child_die = die->child;
14183   while (child_die && child_die->tag)
14184     {
14185       if (child_die->tag == DW_TAG_subrange_type)
14186         {
14187           struct type *child_type = read_type_die (child_die, cu);
14188
14189           if (child_type != NULL)
14190             {
14191               /* The range type was succesfully read.  Save it for the
14192                  array type creation.  */
14193               if ((ndim % DW_FIELD_ALLOC_CHUNK) == 0)
14194                 {
14195                   range_types = (struct type **)
14196                     xrealloc (range_types, (ndim + DW_FIELD_ALLOC_CHUNK)
14197                               * sizeof (struct type *));
14198                   if (ndim == 0)
14199                     make_cleanup (free_current_contents, &range_types);
14200                 }
14201               range_types[ndim++] = child_type;
14202             }
14203         }
14204       child_die = sibling_die (child_die);
14205     }
14206
14207   /* Dwarf2 dimensions are output from left to right, create the
14208      necessary array types in backwards order.  */
14209
14210   type = element_type;
14211
14212   if (read_array_order (die, cu) == DW_ORD_col_major)
14213     {
14214       int i = 0;
14215
14216       while (i < ndim)
14217         type = create_array_type_with_stride (NULL, type, range_types[i++],
14218                                               bit_stride);
14219     }
14220   else
14221     {
14222       while (ndim-- > 0)
14223         type = create_array_type_with_stride (NULL, type, range_types[ndim],
14224                                               bit_stride);
14225     }
14226
14227   /* Understand Dwarf2 support for vector types (like they occur on
14228      the PowerPC w/ AltiVec).  Gcc just adds another attribute to the
14229      array type.  This is not part of the Dwarf2/3 standard yet, but a
14230      custom vendor extension.  The main difference between a regular
14231      array and the vector variant is that vectors are passed by value
14232      to functions.  */
14233   attr = dwarf2_attr (die, DW_AT_GNU_vector, cu);
14234   if (attr)
14235     make_vector_type (type);
14236
14237   /* The DIE may have DW_AT_byte_size set.  For example an OpenCL
14238      implementation may choose to implement triple vectors using this
14239      attribute.  */
14240   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
14241   if (attr)
14242     {
14243       if (DW_UNSND (attr) >= TYPE_LENGTH (type))
14244         TYPE_LENGTH (type) = DW_UNSND (attr);
14245       else
14246         complaint (&symfile_complaints,
14247                    _("DW_AT_byte_size for array type smaller "
14248                      "than the total size of elements"));
14249     }
14250
14251   name = dwarf2_name (die, cu);
14252   if (name)
14253     TYPE_NAME (type) = name;
14254
14255   /* Install the type in the die.  */
14256   set_die_type (die, type, cu);
14257
14258   /* set_die_type should be already done.  */
14259   set_descriptive_type (type, die, cu);
14260
14261   do_cleanups (back_to);
14262
14263   return type;
14264 }
14265
14266 static enum dwarf_array_dim_ordering
14267 read_array_order (struct die_info *die, struct dwarf2_cu *cu)
14268 {
14269   struct attribute *attr;
14270
14271   attr = dwarf2_attr (die, DW_AT_ordering, cu);
14272
14273   if (attr)
14274     return (enum dwarf_array_dim_ordering) DW_SND (attr);
14275
14276   /* GNU F77 is a special case, as at 08/2004 array type info is the
14277      opposite order to the dwarf2 specification, but data is still
14278      laid out as per normal fortran.
14279
14280      FIXME: dsl/2004-8-20: If G77 is ever fixed, this will also need
14281      version checking.  */
14282
14283   if (cu->language == language_fortran
14284       && cu->producer && strstr (cu->producer, "GNU F77"))
14285     {
14286       return DW_ORD_row_major;
14287     }
14288
14289   switch (cu->language_defn->la_array_ordering)
14290     {
14291     case array_column_major:
14292       return DW_ORD_col_major;
14293     case array_row_major:
14294     default:
14295       return DW_ORD_row_major;
14296     };
14297 }
14298
14299 /* Extract all information from a DW_TAG_set_type DIE and put it in
14300    the DIE's type field.  */
14301
14302 static struct type *
14303 read_set_type (struct die_info *die, struct dwarf2_cu *cu)
14304 {
14305   struct type *domain_type, *set_type;
14306   struct attribute *attr;
14307
14308   domain_type = die_type (die, cu);
14309
14310   /* The die_type call above may have already set the type for this DIE.  */
14311   set_type = get_die_type (die, cu);
14312   if (set_type)
14313     return set_type;
14314
14315   set_type = create_set_type (NULL, domain_type);
14316
14317   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
14318   if (attr)
14319     TYPE_LENGTH (set_type) = DW_UNSND (attr);
14320
14321   return set_die_type (die, set_type, cu);
14322 }
14323
14324 /* A helper for read_common_block that creates a locexpr baton.
14325    SYM is the symbol which we are marking as computed.
14326    COMMON_DIE is the DIE for the common block.
14327    COMMON_LOC is the location expression attribute for the common
14328    block itself.
14329    MEMBER_LOC is the location expression attribute for the particular
14330    member of the common block that we are processing.
14331    CU is the CU from which the above come.  */
14332
14333 static void
14334 mark_common_block_symbol_computed (struct symbol *sym,
14335                                    struct die_info *common_die,
14336                                    struct attribute *common_loc,
14337                                    struct attribute *member_loc,
14338                                    struct dwarf2_cu *cu)
14339 {
14340   struct objfile *objfile = dwarf2_per_objfile->objfile;
14341   struct dwarf2_locexpr_baton *baton;
14342   gdb_byte *ptr;
14343   unsigned int cu_off;
14344   enum bfd_endian byte_order = gdbarch_byte_order (get_objfile_arch (objfile));
14345   LONGEST offset = 0;
14346
14347   gdb_assert (common_loc && member_loc);
14348   gdb_assert (attr_form_is_block (common_loc));
14349   gdb_assert (attr_form_is_block (member_loc)
14350               || attr_form_is_constant (member_loc));
14351
14352   baton = XOBNEW (&objfile->objfile_obstack, struct dwarf2_locexpr_baton);
14353   baton->per_cu = cu->per_cu;
14354   gdb_assert (baton->per_cu);
14355
14356   baton->size = 5 /* DW_OP_call4 */ + 1 /* DW_OP_plus */;
14357
14358   if (attr_form_is_constant (member_loc))
14359     {
14360       offset = dwarf2_get_attr_constant_value (member_loc, 0);
14361       baton->size += 1 /* DW_OP_addr */ + cu->header.addr_size;
14362     }
14363   else
14364     baton->size += DW_BLOCK (member_loc)->size;
14365
14366   ptr = (gdb_byte *) obstack_alloc (&objfile->objfile_obstack, baton->size);
14367   baton->data = ptr;
14368
14369   *ptr++ = DW_OP_call4;
14370   cu_off = common_die->sect_off - cu->per_cu->sect_off;
14371   store_unsigned_integer (ptr, 4, byte_order, cu_off);
14372   ptr += 4;
14373
14374   if (attr_form_is_constant (member_loc))
14375     {
14376       *ptr++ = DW_OP_addr;
14377       store_unsigned_integer (ptr, cu->header.addr_size, byte_order, offset);
14378       ptr += cu->header.addr_size;
14379     }
14380   else
14381     {
14382       /* We have to copy the data here, because DW_OP_call4 will only
14383          use a DW_AT_location attribute.  */
14384       memcpy (ptr, DW_BLOCK (member_loc)->data, DW_BLOCK (member_loc)->size);
14385       ptr += DW_BLOCK (member_loc)->size;
14386     }
14387
14388   *ptr++ = DW_OP_plus;
14389   gdb_assert (ptr - baton->data == baton->size);
14390
14391   SYMBOL_LOCATION_BATON (sym) = baton;
14392   SYMBOL_ACLASS_INDEX (sym) = dwarf2_locexpr_index;
14393 }
14394
14395 /* Create appropriate locally-scoped variables for all the
14396    DW_TAG_common_block entries.  Also create a struct common_block
14397    listing all such variables for `info common'.  COMMON_BLOCK_DOMAIN
14398    is used to sepate the common blocks name namespace from regular
14399    variable names.  */
14400
14401 static void
14402 read_common_block (struct die_info *die, struct dwarf2_cu *cu)
14403 {
14404   struct attribute *attr;
14405
14406   attr = dwarf2_attr (die, DW_AT_location, cu);
14407   if (attr)
14408     {
14409       /* Support the .debug_loc offsets.  */
14410       if (attr_form_is_block (attr))
14411         {
14412           /* Ok.  */
14413         }
14414       else if (attr_form_is_section_offset (attr))
14415         {
14416           dwarf2_complex_location_expr_complaint ();
14417           attr = NULL;
14418         }
14419       else
14420         {
14421           dwarf2_invalid_attrib_class_complaint ("DW_AT_location",
14422                                                  "common block member");
14423           attr = NULL;
14424         }
14425     }
14426
14427   if (die->child != NULL)
14428     {
14429       struct objfile *objfile = cu->objfile;
14430       struct die_info *child_die;
14431       size_t n_entries = 0, size;
14432       struct common_block *common_block;
14433       struct symbol *sym;
14434
14435       for (child_die = die->child;
14436            child_die && child_die->tag;
14437            child_die = sibling_die (child_die))
14438         ++n_entries;
14439
14440       size = (sizeof (struct common_block)
14441               + (n_entries - 1) * sizeof (struct symbol *));
14442       common_block
14443         = (struct common_block *) obstack_alloc (&objfile->objfile_obstack,
14444                                                  size);
14445       memset (common_block->contents, 0, n_entries * sizeof (struct symbol *));
14446       common_block->n_entries = 0;
14447
14448       for (child_die = die->child;
14449            child_die && child_die->tag;
14450            child_die = sibling_die (child_die))
14451         {
14452           /* Create the symbol in the DW_TAG_common_block block in the current
14453              symbol scope.  */
14454           sym = new_symbol (child_die, NULL, cu);
14455           if (sym != NULL)
14456             {
14457               struct attribute *member_loc;
14458
14459               common_block->contents[common_block->n_entries++] = sym;
14460
14461               member_loc = dwarf2_attr (child_die, DW_AT_data_member_location,
14462                                         cu);
14463               if (member_loc)
14464                 {
14465                   /* GDB has handled this for a long time, but it is
14466                      not specified by DWARF.  It seems to have been
14467                      emitted by gfortran at least as recently as:
14468                      http://gcc.gnu.org/bugzilla/show_bug.cgi?id=23057.  */
14469                   complaint (&symfile_complaints,
14470                              _("Variable in common block has "
14471                                "DW_AT_data_member_location "
14472                                "- DIE at 0x%x [in module %s]"),
14473                              to_underlying (child_die->sect_off),
14474                              objfile_name (cu->objfile));
14475
14476                   if (attr_form_is_section_offset (member_loc))
14477                     dwarf2_complex_location_expr_complaint ();
14478                   else if (attr_form_is_constant (member_loc)
14479                            || attr_form_is_block (member_loc))
14480                     {
14481                       if (attr)
14482                         mark_common_block_symbol_computed (sym, die, attr,
14483                                                            member_loc, cu);
14484                     }
14485                   else
14486                     dwarf2_complex_location_expr_complaint ();
14487                 }
14488             }
14489         }
14490
14491       sym = new_symbol (die, objfile_type (objfile)->builtin_void, cu);
14492       SYMBOL_VALUE_COMMON_BLOCK (sym) = common_block;
14493     }
14494 }
14495
14496 /* Create a type for a C++ namespace.  */
14497
14498 static struct type *
14499 read_namespace_type (struct die_info *die, struct dwarf2_cu *cu)
14500 {
14501   struct objfile *objfile = cu->objfile;
14502   const char *previous_prefix, *name;
14503   int is_anonymous;
14504   struct type *type;
14505
14506   /* For extensions, reuse the type of the original namespace.  */
14507   if (dwarf2_attr (die, DW_AT_extension, cu) != NULL)
14508     {
14509       struct die_info *ext_die;
14510       struct dwarf2_cu *ext_cu = cu;
14511
14512       ext_die = dwarf2_extension (die, &ext_cu);
14513       type = read_type_die (ext_die, ext_cu);
14514
14515       /* EXT_CU may not be the same as CU.
14516          Ensure TYPE is recorded with CU in die_type_hash.  */
14517       return set_die_type (die, type, cu);
14518     }
14519
14520   name = namespace_name (die, &is_anonymous, cu);
14521
14522   /* Now build the name of the current namespace.  */
14523
14524   previous_prefix = determine_prefix (die, cu);
14525   if (previous_prefix[0] != '\0')
14526     name = typename_concat (&objfile->objfile_obstack,
14527                             previous_prefix, name, 0, cu);
14528
14529   /* Create the type.  */
14530   type = init_type (objfile, TYPE_CODE_NAMESPACE, 0, name);
14531   TYPE_TAG_NAME (type) = TYPE_NAME (type);
14532
14533   return set_die_type (die, type, cu);
14534 }
14535
14536 /* Read a namespace scope.  */
14537
14538 static void
14539 read_namespace (struct die_info *die, struct dwarf2_cu *cu)
14540 {
14541   struct objfile *objfile = cu->objfile;
14542   int is_anonymous;
14543
14544   /* Add a symbol associated to this if we haven't seen the namespace
14545      before.  Also, add a using directive if it's an anonymous
14546      namespace.  */
14547
14548   if (dwarf2_attr (die, DW_AT_extension, cu) == NULL)
14549     {
14550       struct type *type;
14551
14552       type = read_type_die (die, cu);
14553       new_symbol (die, type, cu);
14554
14555       namespace_name (die, &is_anonymous, cu);
14556       if (is_anonymous)
14557         {
14558           const char *previous_prefix = determine_prefix (die, cu);
14559
14560           add_using_directive (using_directives (cu->language),
14561                                previous_prefix, TYPE_NAME (type), NULL,
14562                                NULL, NULL, 0, &objfile->objfile_obstack);
14563         }
14564     }
14565
14566   if (die->child != NULL)
14567     {
14568       struct die_info *child_die = die->child;
14569
14570       while (child_die && child_die->tag)
14571         {
14572           process_die (child_die, cu);
14573           child_die = sibling_die (child_die);
14574         }
14575     }
14576 }
14577
14578 /* Read a Fortran module as type.  This DIE can be only a declaration used for
14579    imported module.  Still we need that type as local Fortran "use ... only"
14580    declaration imports depend on the created type in determine_prefix.  */
14581
14582 static struct type *
14583 read_module_type (struct die_info *die, struct dwarf2_cu *cu)
14584 {
14585   struct objfile *objfile = cu->objfile;
14586   const char *module_name;
14587   struct type *type;
14588
14589   module_name = dwarf2_name (die, cu);
14590   if (!module_name)
14591     complaint (&symfile_complaints,
14592                _("DW_TAG_module has no name, offset 0x%x"),
14593                to_underlying (die->sect_off));
14594   type = init_type (objfile, TYPE_CODE_MODULE, 0, module_name);
14595
14596   /* determine_prefix uses TYPE_TAG_NAME.  */
14597   TYPE_TAG_NAME (type) = TYPE_NAME (type);
14598
14599   return set_die_type (die, type, cu);
14600 }
14601
14602 /* Read a Fortran module.  */
14603
14604 static void
14605 read_module (struct die_info *die, struct dwarf2_cu *cu)
14606 {
14607   struct die_info *child_die = die->child;
14608   struct type *type;
14609
14610   type = read_type_die (die, cu);
14611   new_symbol (die, type, cu);
14612
14613   while (child_die && child_die->tag)
14614     {
14615       process_die (child_die, cu);
14616       child_die = sibling_die (child_die);
14617     }
14618 }
14619
14620 /* Return the name of the namespace represented by DIE.  Set
14621    *IS_ANONYMOUS to tell whether or not the namespace is an anonymous
14622    namespace.  */
14623
14624 static const char *
14625 namespace_name (struct die_info *die, int *is_anonymous, struct dwarf2_cu *cu)
14626 {
14627   struct die_info *current_die;
14628   const char *name = NULL;
14629
14630   /* Loop through the extensions until we find a name.  */
14631
14632   for (current_die = die;
14633        current_die != NULL;
14634        current_die = dwarf2_extension (die, &cu))
14635     {
14636       /* We don't use dwarf2_name here so that we can detect the absence
14637          of a name -> anonymous namespace.  */
14638       name = dwarf2_string_attr (die, DW_AT_name, cu);
14639
14640       if (name != NULL)
14641         break;
14642     }
14643
14644   /* Is it an anonymous namespace?  */
14645
14646   *is_anonymous = (name == NULL);
14647   if (*is_anonymous)
14648     name = CP_ANONYMOUS_NAMESPACE_STR;
14649
14650   return name;
14651 }
14652
14653 /* Extract all information from a DW_TAG_pointer_type DIE and add to
14654    the user defined type vector.  */
14655
14656 static struct type *
14657 read_tag_pointer_type (struct die_info *die, struct dwarf2_cu *cu)
14658 {
14659   struct gdbarch *gdbarch = get_objfile_arch (cu->objfile);
14660   struct comp_unit_head *cu_header = &cu->header;
14661   struct type *type;
14662   struct attribute *attr_byte_size;
14663   struct attribute *attr_address_class;
14664   int byte_size, addr_class;
14665   struct type *target_type;
14666
14667   target_type = die_type (die, cu);
14668
14669   /* The die_type call above may have already set the type for this DIE.  */
14670   type = get_die_type (die, cu);
14671   if (type)
14672     return type;
14673
14674   type = lookup_pointer_type (target_type);
14675
14676   attr_byte_size = dwarf2_attr (die, DW_AT_byte_size, cu);
14677   if (attr_byte_size)
14678     byte_size = DW_UNSND (attr_byte_size);
14679   else
14680     byte_size = cu_header->addr_size;
14681
14682   attr_address_class = dwarf2_attr (die, DW_AT_address_class, cu);
14683   if (attr_address_class)
14684     addr_class = DW_UNSND (attr_address_class);
14685   else
14686     addr_class = DW_ADDR_none;
14687
14688   /* If the pointer size or address class is different than the
14689      default, create a type variant marked as such and set the
14690      length accordingly.  */
14691   if (TYPE_LENGTH (type) != byte_size || addr_class != DW_ADDR_none)
14692     {
14693       if (gdbarch_address_class_type_flags_p (gdbarch))
14694         {
14695           int type_flags;
14696
14697           type_flags = gdbarch_address_class_type_flags
14698                          (gdbarch, byte_size, addr_class);
14699           gdb_assert ((type_flags & ~TYPE_INSTANCE_FLAG_ADDRESS_CLASS_ALL)
14700                       == 0);
14701           type = make_type_with_address_space (type, type_flags);
14702         }
14703       else if (TYPE_LENGTH (type) != byte_size)
14704         {
14705           complaint (&symfile_complaints,
14706                      _("invalid pointer size %d"), byte_size);
14707         }
14708       else
14709         {
14710           /* Should we also complain about unhandled address classes?  */
14711         }
14712     }
14713
14714   TYPE_LENGTH (type) = byte_size;
14715   return set_die_type (die, type, cu);
14716 }
14717
14718 /* Extract all information from a DW_TAG_ptr_to_member_type DIE and add to
14719    the user defined type vector.  */
14720
14721 static struct type *
14722 read_tag_ptr_to_member_type (struct die_info *die, struct dwarf2_cu *cu)
14723 {
14724   struct type *type;
14725   struct type *to_type;
14726   struct type *domain;
14727
14728   to_type = die_type (die, cu);
14729   domain = die_containing_type (die, cu);
14730
14731   /* The calls above may have already set the type for this DIE.  */
14732   type = get_die_type (die, cu);
14733   if (type)
14734     return type;
14735
14736   if (TYPE_CODE (check_typedef (to_type)) == TYPE_CODE_METHOD)
14737     type = lookup_methodptr_type (to_type);
14738   else if (TYPE_CODE (check_typedef (to_type)) == TYPE_CODE_FUNC)
14739     {
14740       struct type *new_type = alloc_type (cu->objfile);
14741
14742       smash_to_method_type (new_type, domain, TYPE_TARGET_TYPE (to_type),
14743                             TYPE_FIELDS (to_type), TYPE_NFIELDS (to_type),
14744                             TYPE_VARARGS (to_type));
14745       type = lookup_methodptr_type (new_type);
14746     }
14747   else
14748     type = lookup_memberptr_type (to_type, domain);
14749
14750   return set_die_type (die, type, cu);
14751 }
14752
14753 /* Extract all information from a DW_TAG_{rvalue_,}reference_type DIE and add to
14754    the user defined type vector.  */
14755
14756 static struct type *
14757 read_tag_reference_type (struct die_info *die, struct dwarf2_cu *cu,
14758                           enum type_code refcode)
14759 {
14760   struct comp_unit_head *cu_header = &cu->header;
14761   struct type *type, *target_type;
14762   struct attribute *attr;
14763
14764   gdb_assert (refcode == TYPE_CODE_REF || refcode == TYPE_CODE_RVALUE_REF);
14765
14766   target_type = die_type (die, cu);
14767
14768   /* The die_type call above may have already set the type for this DIE.  */
14769   type = get_die_type (die, cu);
14770   if (type)
14771     return type;
14772
14773   type = lookup_reference_type (target_type, refcode);
14774   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
14775   if (attr)
14776     {
14777       TYPE_LENGTH (type) = DW_UNSND (attr);
14778     }
14779   else
14780     {
14781       TYPE_LENGTH (type) = cu_header->addr_size;
14782     }
14783   return set_die_type (die, type, cu);
14784 }
14785
14786 /* Add the given cv-qualifiers to the element type of the array.  GCC
14787    outputs DWARF type qualifiers that apply to an array, not the
14788    element type.  But GDB relies on the array element type to carry
14789    the cv-qualifiers.  This mimics section 6.7.3 of the C99
14790    specification.  */
14791
14792 static struct type *
14793 add_array_cv_type (struct die_info *die, struct dwarf2_cu *cu,
14794                    struct type *base_type, int cnst, int voltl)
14795 {
14796   struct type *el_type, *inner_array;
14797
14798   base_type = copy_type (base_type);
14799   inner_array = base_type;
14800
14801   while (TYPE_CODE (TYPE_TARGET_TYPE (inner_array)) == TYPE_CODE_ARRAY)
14802     {
14803       TYPE_TARGET_TYPE (inner_array) =
14804         copy_type (TYPE_TARGET_TYPE (inner_array));
14805       inner_array = TYPE_TARGET_TYPE (inner_array);
14806     }
14807
14808   el_type = TYPE_TARGET_TYPE (inner_array);
14809   cnst |= TYPE_CONST (el_type);
14810   voltl |= TYPE_VOLATILE (el_type);
14811   TYPE_TARGET_TYPE (inner_array) = make_cv_type (cnst, voltl, el_type, NULL);
14812
14813   return set_die_type (die, base_type, cu);
14814 }
14815
14816 static struct type *
14817 read_tag_const_type (struct die_info *die, struct dwarf2_cu *cu)
14818 {
14819   struct type *base_type, *cv_type;
14820
14821   base_type = die_type (die, cu);
14822
14823   /* The die_type call above may have already set the type for this DIE.  */
14824   cv_type = get_die_type (die, cu);
14825   if (cv_type)
14826     return cv_type;
14827
14828   /* In case the const qualifier is applied to an array type, the element type
14829      is so qualified, not the array type (section 6.7.3 of C99).  */
14830   if (TYPE_CODE (base_type) == TYPE_CODE_ARRAY)
14831     return add_array_cv_type (die, cu, base_type, 1, 0);
14832
14833   cv_type = make_cv_type (1, TYPE_VOLATILE (base_type), base_type, 0);
14834   return set_die_type (die, cv_type, cu);
14835 }
14836
14837 static struct type *
14838 read_tag_volatile_type (struct die_info *die, struct dwarf2_cu *cu)
14839 {
14840   struct type *base_type, *cv_type;
14841
14842   base_type = die_type (die, cu);
14843
14844   /* The die_type call above may have already set the type for this DIE.  */
14845   cv_type = get_die_type (die, cu);
14846   if (cv_type)
14847     return cv_type;
14848
14849   /* In case the volatile qualifier is applied to an array type, the
14850      element type is so qualified, not the array type (section 6.7.3
14851      of C99).  */
14852   if (TYPE_CODE (base_type) == TYPE_CODE_ARRAY)
14853     return add_array_cv_type (die, cu, base_type, 0, 1);
14854
14855   cv_type = make_cv_type (TYPE_CONST (base_type), 1, base_type, 0);
14856   return set_die_type (die, cv_type, cu);
14857 }
14858
14859 /* Handle DW_TAG_restrict_type.  */
14860
14861 static struct type *
14862 read_tag_restrict_type (struct die_info *die, struct dwarf2_cu *cu)
14863 {
14864   struct type *base_type, *cv_type;
14865
14866   base_type = die_type (die, cu);
14867
14868   /* The die_type call above may have already set the type for this DIE.  */
14869   cv_type = get_die_type (die, cu);
14870   if (cv_type)
14871     return cv_type;
14872
14873   cv_type = make_restrict_type (base_type);
14874   return set_die_type (die, cv_type, cu);
14875 }
14876
14877 /* Handle DW_TAG_atomic_type.  */
14878
14879 static struct type *
14880 read_tag_atomic_type (struct die_info *die, struct dwarf2_cu *cu)
14881 {
14882   struct type *base_type, *cv_type;
14883
14884   base_type = die_type (die, cu);
14885
14886   /* The die_type call above may have already set the type for this DIE.  */
14887   cv_type = get_die_type (die, cu);
14888   if (cv_type)
14889     return cv_type;
14890
14891   cv_type = make_atomic_type (base_type);
14892   return set_die_type (die, cv_type, cu);
14893 }
14894
14895 /* Extract all information from a DW_TAG_string_type DIE and add to
14896    the user defined type vector.  It isn't really a user defined type,
14897    but it behaves like one, with other DIE's using an AT_user_def_type
14898    attribute to reference it.  */
14899
14900 static struct type *
14901 read_tag_string_type (struct die_info *die, struct dwarf2_cu *cu)
14902 {
14903   struct objfile *objfile = cu->objfile;
14904   struct gdbarch *gdbarch = get_objfile_arch (objfile);
14905   struct type *type, *range_type, *index_type, *char_type;
14906   struct attribute *attr;
14907   unsigned int length;
14908
14909   attr = dwarf2_attr (die, DW_AT_string_length, cu);
14910   if (attr)
14911     {
14912       length = DW_UNSND (attr);
14913     }
14914   else
14915     {
14916       /* Check for the DW_AT_byte_size attribute.  */
14917       attr = dwarf2_attr (die, DW_AT_byte_size, cu);
14918       if (attr)
14919         {
14920           length = DW_UNSND (attr);
14921         }
14922       else
14923         {
14924           length = 1;
14925         }
14926     }
14927
14928   index_type = objfile_type (objfile)->builtin_int;
14929   range_type = create_static_range_type (NULL, index_type, 1, length);
14930   char_type = language_string_char_type (cu->language_defn, gdbarch);
14931   type = create_string_type (NULL, char_type, range_type);
14932
14933   return set_die_type (die, type, cu);
14934 }
14935
14936 /* Assuming that DIE corresponds to a function, returns nonzero
14937    if the function is prototyped.  */
14938
14939 static int
14940 prototyped_function_p (struct die_info *die, struct dwarf2_cu *cu)
14941 {
14942   struct attribute *attr;
14943
14944   attr = dwarf2_attr (die, DW_AT_prototyped, cu);
14945   if (attr && (DW_UNSND (attr) != 0))
14946     return 1;
14947
14948   /* The DWARF standard implies that the DW_AT_prototyped attribute
14949      is only meaninful for C, but the concept also extends to other
14950      languages that allow unprototyped functions (Eg: Objective C).
14951      For all other languages, assume that functions are always
14952      prototyped.  */
14953   if (cu->language != language_c
14954       && cu->language != language_objc
14955       && cu->language != language_opencl)
14956     return 1;
14957
14958   /* RealView does not emit DW_AT_prototyped.  We can not distinguish
14959      prototyped and unprototyped functions; default to prototyped,
14960      since that is more common in modern code (and RealView warns
14961      about unprototyped functions).  */
14962   if (producer_is_realview (cu->producer))
14963     return 1;
14964
14965   return 0;
14966 }
14967
14968 /* Handle DIES due to C code like:
14969
14970    struct foo
14971    {
14972    int (*funcp)(int a, long l);
14973    int b;
14974    };
14975
14976    ('funcp' generates a DW_TAG_subroutine_type DIE).  */
14977
14978 static struct type *
14979 read_subroutine_type (struct die_info *die, struct dwarf2_cu *cu)
14980 {
14981   struct objfile *objfile = cu->objfile;
14982   struct type *type;            /* Type that this function returns.  */
14983   struct type *ftype;           /* Function that returns above type.  */
14984   struct attribute *attr;
14985
14986   type = die_type (die, cu);
14987
14988   /* The die_type call above may have already set the type for this DIE.  */
14989   ftype = get_die_type (die, cu);
14990   if (ftype)
14991     return ftype;
14992
14993   ftype = lookup_function_type (type);
14994
14995   if (prototyped_function_p (die, cu))
14996     TYPE_PROTOTYPED (ftype) = 1;
14997
14998   /* Store the calling convention in the type if it's available in
14999      the subroutine die.  Otherwise set the calling convention to
15000      the default value DW_CC_normal.  */
15001   attr = dwarf2_attr (die, DW_AT_calling_convention, cu);
15002   if (attr)
15003     TYPE_CALLING_CONVENTION (ftype) = DW_UNSND (attr);
15004   else if (cu->producer && strstr (cu->producer, "IBM XL C for OpenCL"))
15005     TYPE_CALLING_CONVENTION (ftype) = DW_CC_GDB_IBM_OpenCL;
15006   else
15007     TYPE_CALLING_CONVENTION (ftype) = DW_CC_normal;
15008
15009   /* Record whether the function returns normally to its caller or not
15010      if the DWARF producer set that information.  */
15011   attr = dwarf2_attr (die, DW_AT_noreturn, cu);
15012   if (attr && (DW_UNSND (attr) != 0))
15013     TYPE_NO_RETURN (ftype) = 1;
15014
15015   /* We need to add the subroutine type to the die immediately so
15016      we don't infinitely recurse when dealing with parameters
15017      declared as the same subroutine type.  */
15018   set_die_type (die, ftype, cu);
15019
15020   if (die->child != NULL)
15021     {
15022       struct type *void_type = objfile_type (objfile)->builtin_void;
15023       struct die_info *child_die;
15024       int nparams, iparams;
15025
15026       /* Count the number of parameters.
15027          FIXME: GDB currently ignores vararg functions, but knows about
15028          vararg member functions.  */
15029       nparams = 0;
15030       child_die = die->child;
15031       while (child_die && child_die->tag)
15032         {
15033           if (child_die->tag == DW_TAG_formal_parameter)
15034             nparams++;
15035           else if (child_die->tag == DW_TAG_unspecified_parameters)
15036             TYPE_VARARGS (ftype) = 1;
15037           child_die = sibling_die (child_die);
15038         }
15039
15040       /* Allocate storage for parameters and fill them in.  */
15041       TYPE_NFIELDS (ftype) = nparams;
15042       TYPE_FIELDS (ftype) = (struct field *)
15043         TYPE_ZALLOC (ftype, nparams * sizeof (struct field));
15044
15045       /* TYPE_FIELD_TYPE must never be NULL.  Pre-fill the array to ensure it
15046          even if we error out during the parameters reading below.  */
15047       for (iparams = 0; iparams < nparams; iparams++)
15048         TYPE_FIELD_TYPE (ftype, iparams) = void_type;
15049
15050       iparams = 0;
15051       child_die = die->child;
15052       while (child_die && child_die->tag)
15053         {
15054           if (child_die->tag == DW_TAG_formal_parameter)
15055             {
15056               struct type *arg_type;
15057
15058               /* DWARF version 2 has no clean way to discern C++
15059                  static and non-static member functions.  G++ helps
15060                  GDB by marking the first parameter for non-static
15061                  member functions (which is the this pointer) as
15062                  artificial.  We pass this information to
15063                  dwarf2_add_member_fn via TYPE_FIELD_ARTIFICIAL.
15064
15065                  DWARF version 3 added DW_AT_object_pointer, which GCC
15066                  4.5 does not yet generate.  */
15067               attr = dwarf2_attr (child_die, DW_AT_artificial, cu);
15068               if (attr)
15069                 TYPE_FIELD_ARTIFICIAL (ftype, iparams) = DW_UNSND (attr);
15070               else
15071                 TYPE_FIELD_ARTIFICIAL (ftype, iparams) = 0;
15072               arg_type = die_type (child_die, cu);
15073
15074               /* RealView does not mark THIS as const, which the testsuite
15075                  expects.  GCC marks THIS as const in method definitions,
15076                  but not in the class specifications (GCC PR 43053).  */
15077               if (cu->language == language_cplus && !TYPE_CONST (arg_type)
15078                   && TYPE_FIELD_ARTIFICIAL (ftype, iparams))
15079                 {
15080                   int is_this = 0;
15081                   struct dwarf2_cu *arg_cu = cu;
15082                   const char *name = dwarf2_name (child_die, cu);
15083
15084                   attr = dwarf2_attr (die, DW_AT_object_pointer, cu);
15085                   if (attr)
15086                     {
15087                       /* If the compiler emits this, use it.  */
15088                       if (follow_die_ref (die, attr, &arg_cu) == child_die)
15089                         is_this = 1;
15090                     }
15091                   else if (name && strcmp (name, "this") == 0)
15092                     /* Function definitions will have the argument names.  */
15093                     is_this = 1;
15094                   else if (name == NULL && iparams == 0)
15095                     /* Declarations may not have the names, so like
15096                        elsewhere in GDB, assume an artificial first
15097                        argument is "this".  */
15098                     is_this = 1;
15099
15100                   if (is_this)
15101                     arg_type = make_cv_type (1, TYPE_VOLATILE (arg_type),
15102                                              arg_type, 0);
15103                 }
15104
15105               TYPE_FIELD_TYPE (ftype, iparams) = arg_type;
15106               iparams++;
15107             }
15108           child_die = sibling_die (child_die);
15109         }
15110     }
15111
15112   return ftype;
15113 }
15114
15115 static struct type *
15116 read_typedef (struct die_info *die, struct dwarf2_cu *cu)
15117 {
15118   struct objfile *objfile = cu->objfile;
15119   const char *name = NULL;
15120   struct type *this_type, *target_type;
15121
15122   name = dwarf2_full_name (NULL, die, cu);
15123   this_type = init_type (objfile, TYPE_CODE_TYPEDEF, 0, name);
15124   TYPE_TARGET_STUB (this_type) = 1;
15125   set_die_type (die, this_type, cu);
15126   target_type = die_type (die, cu);
15127   if (target_type != this_type)
15128     TYPE_TARGET_TYPE (this_type) = target_type;
15129   else
15130     {
15131       /* Self-referential typedefs are, it seems, not allowed by the DWARF
15132          spec and cause infinite loops in GDB.  */
15133       complaint (&symfile_complaints,
15134                  _("Self-referential DW_TAG_typedef "
15135                    "- DIE at 0x%x [in module %s]"),
15136                  to_underlying (die->sect_off), objfile_name (objfile));
15137       TYPE_TARGET_TYPE (this_type) = NULL;
15138     }
15139   return this_type;
15140 }
15141
15142 /* Allocate a floating-point type of size BITS and name NAME.  Pass NAME_HINT
15143    (which may be different from NAME) to the architecture back-end to allow
15144    it to guess the correct format if necessary.  */
15145
15146 static struct type *
15147 dwarf2_init_float_type (struct objfile *objfile, int bits, const char *name,
15148                         const char *name_hint)
15149 {
15150   struct gdbarch *gdbarch = get_objfile_arch (objfile);
15151   const struct floatformat **format;
15152   struct type *type;
15153
15154   format = gdbarch_floatformat_for_type (gdbarch, name_hint, bits);
15155   if (format)
15156     type = init_float_type (objfile, bits, name, format);
15157   else
15158     type = init_type (objfile, TYPE_CODE_ERROR, bits / TARGET_CHAR_BIT, name);
15159
15160   return type;
15161 }
15162
15163 /* Find a representation of a given base type and install
15164    it in the TYPE field of the die.  */
15165
15166 static struct type *
15167 read_base_type (struct die_info *die, struct dwarf2_cu *cu)
15168 {
15169   struct objfile *objfile = cu->objfile;
15170   struct type *type;
15171   struct attribute *attr;
15172   int encoding = 0, bits = 0;
15173   const char *name;
15174
15175   attr = dwarf2_attr (die, DW_AT_encoding, cu);
15176   if (attr)
15177     {
15178       encoding = DW_UNSND (attr);
15179     }
15180   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
15181   if (attr)
15182     {
15183       bits = DW_UNSND (attr) * TARGET_CHAR_BIT;
15184     }
15185   name = dwarf2_name (die, cu);
15186   if (!name)
15187     {
15188       complaint (&symfile_complaints,
15189                  _("DW_AT_name missing from DW_TAG_base_type"));
15190     }
15191
15192   switch (encoding)
15193     {
15194       case DW_ATE_address:
15195         /* Turn DW_ATE_address into a void * pointer.  */
15196         type = init_type (objfile, TYPE_CODE_VOID, 1, NULL);
15197         type = init_pointer_type (objfile, bits, name, type);
15198         break;
15199       case DW_ATE_boolean:
15200         type = init_boolean_type (objfile, bits, 1, name);
15201         break;
15202       case DW_ATE_complex_float:
15203         type = dwarf2_init_float_type (objfile, bits / 2, NULL, name);
15204         type = init_complex_type (objfile, name, type);
15205         break;
15206       case DW_ATE_decimal_float:
15207         type = init_decfloat_type (objfile, bits, name);
15208         break;
15209       case DW_ATE_float:
15210         type = dwarf2_init_float_type (objfile, bits, name, name);
15211         break;
15212       case DW_ATE_signed:
15213         type = init_integer_type (objfile, bits, 0, name);
15214         break;
15215       case DW_ATE_unsigned:
15216         if (cu->language == language_fortran
15217             && name
15218             && startswith (name, "character("))
15219           type = init_character_type (objfile, bits, 1, name);
15220         else
15221           type = init_integer_type (objfile, bits, 1, name);
15222         break;
15223       case DW_ATE_signed_char:
15224         if (cu->language == language_ada || cu->language == language_m2
15225             || cu->language == language_pascal
15226             || cu->language == language_fortran)
15227           type = init_character_type (objfile, bits, 0, name);
15228         else
15229           type = init_integer_type (objfile, bits, 0, name);
15230         break;
15231       case DW_ATE_unsigned_char:
15232         if (cu->language == language_ada || cu->language == language_m2
15233             || cu->language == language_pascal
15234             || cu->language == language_fortran
15235             || cu->language == language_rust)
15236           type = init_character_type (objfile, bits, 1, name);
15237         else
15238           type = init_integer_type (objfile, bits, 1, name);
15239         break;
15240       case DW_ATE_UTF:
15241         {
15242           gdbarch *arch = get_objfile_arch (objfile);
15243
15244           if (bits == 16)
15245             type = builtin_type (arch)->builtin_char16;
15246           else if (bits == 32)
15247             type = builtin_type (arch)->builtin_char32;
15248           else
15249             {
15250               complaint (&symfile_complaints,
15251                          _("unsupported DW_ATE_UTF bit size: '%d'"),
15252                          bits);
15253               type = init_integer_type (objfile, bits, 1, name);
15254             }
15255           return set_die_type (die, type, cu);
15256         }
15257         break;
15258
15259       default:
15260         complaint (&symfile_complaints, _("unsupported DW_AT_encoding: '%s'"),
15261                    dwarf_type_encoding_name (encoding));
15262         type = init_type (objfile, TYPE_CODE_ERROR,
15263                           bits / TARGET_CHAR_BIT, name);
15264         break;
15265     }
15266
15267   if (name && strcmp (name, "char") == 0)
15268     TYPE_NOSIGN (type) = 1;
15269
15270   return set_die_type (die, type, cu);
15271 }
15272
15273 /* Parse dwarf attribute if it's a block, reference or constant and put the
15274    resulting value of the attribute into struct bound_prop.
15275    Returns 1 if ATTR could be resolved into PROP, 0 otherwise.  */
15276
15277 static int
15278 attr_to_dynamic_prop (const struct attribute *attr, struct die_info *die,
15279                       struct dwarf2_cu *cu, struct dynamic_prop *prop)
15280 {
15281   struct dwarf2_property_baton *baton;
15282   struct obstack *obstack = &cu->objfile->objfile_obstack;
15283
15284   if (attr == NULL || prop == NULL)
15285     return 0;
15286
15287   if (attr_form_is_block (attr))
15288     {
15289       baton = XOBNEW (obstack, struct dwarf2_property_baton);
15290       baton->referenced_type = NULL;
15291       baton->locexpr.per_cu = cu->per_cu;
15292       baton->locexpr.size = DW_BLOCK (attr)->size;
15293       baton->locexpr.data = DW_BLOCK (attr)->data;
15294       prop->data.baton = baton;
15295       prop->kind = PROP_LOCEXPR;
15296       gdb_assert (prop->data.baton != NULL);
15297     }
15298   else if (attr_form_is_ref (attr))
15299     {
15300       struct dwarf2_cu *target_cu = cu;
15301       struct die_info *target_die;
15302       struct attribute *target_attr;
15303
15304       target_die = follow_die_ref (die, attr, &target_cu);
15305       target_attr = dwarf2_attr (target_die, DW_AT_location, target_cu);
15306       if (target_attr == NULL)
15307         target_attr = dwarf2_attr (target_die, DW_AT_data_member_location,
15308                                    target_cu);
15309       if (target_attr == NULL)
15310         return 0;
15311
15312       switch (target_attr->name)
15313         {
15314           case DW_AT_location:
15315             if (attr_form_is_section_offset (target_attr))
15316               {
15317                 baton = XOBNEW (obstack, struct dwarf2_property_baton);
15318                 baton->referenced_type = die_type (target_die, target_cu);
15319                 fill_in_loclist_baton (cu, &baton->loclist, target_attr);
15320                 prop->data.baton = baton;
15321                 prop->kind = PROP_LOCLIST;
15322                 gdb_assert (prop->data.baton != NULL);
15323               }
15324             else if (attr_form_is_block (target_attr))
15325               {
15326                 baton = XOBNEW (obstack, struct dwarf2_property_baton);
15327                 baton->referenced_type = die_type (target_die, target_cu);
15328                 baton->locexpr.per_cu = cu->per_cu;
15329                 baton->locexpr.size = DW_BLOCK (target_attr)->size;
15330                 baton->locexpr.data = DW_BLOCK (target_attr)->data;
15331                 prop->data.baton = baton;
15332                 prop->kind = PROP_LOCEXPR;
15333                 gdb_assert (prop->data.baton != NULL);
15334               }
15335             else
15336               {
15337                 dwarf2_invalid_attrib_class_complaint ("DW_AT_location",
15338                                                        "dynamic property");
15339                 return 0;
15340               }
15341             break;
15342           case DW_AT_data_member_location:
15343             {
15344               LONGEST offset;
15345
15346               if (!handle_data_member_location (target_die, target_cu,
15347                                                 &offset))
15348                 return 0;
15349
15350               baton = XOBNEW (obstack, struct dwarf2_property_baton);
15351               baton->referenced_type = read_type_die (target_die->parent,
15352                                                       target_cu);
15353               baton->offset_info.offset = offset;
15354               baton->offset_info.type = die_type (target_die, target_cu);
15355               prop->data.baton = baton;
15356               prop->kind = PROP_ADDR_OFFSET;
15357               break;
15358             }
15359         }
15360     }
15361   else if (attr_form_is_constant (attr))
15362     {
15363       prop->data.const_val = dwarf2_get_attr_constant_value (attr, 0);
15364       prop->kind = PROP_CONST;
15365     }
15366   else
15367     {
15368       dwarf2_invalid_attrib_class_complaint (dwarf_form_name (attr->form),
15369                                              dwarf2_name (die, cu));
15370       return 0;
15371     }
15372
15373   return 1;
15374 }
15375
15376 /* Read the given DW_AT_subrange DIE.  */
15377
15378 static struct type *
15379 read_subrange_type (struct die_info *die, struct dwarf2_cu *cu)
15380 {
15381   struct type *base_type, *orig_base_type;
15382   struct type *range_type;
15383   struct attribute *attr;
15384   struct dynamic_prop low, high;
15385   int low_default_is_valid;
15386   int high_bound_is_count = 0;
15387   const char *name;
15388   LONGEST negative_mask;
15389
15390   orig_base_type = die_type (die, cu);
15391   /* If ORIG_BASE_TYPE is a typedef, it will not be TYPE_UNSIGNED,
15392      whereas the real type might be.  So, we use ORIG_BASE_TYPE when
15393      creating the range type, but we use the result of check_typedef
15394      when examining properties of the type.  */
15395   base_type = check_typedef (orig_base_type);
15396
15397   /* The die_type call above may have already set the type for this DIE.  */
15398   range_type = get_die_type (die, cu);
15399   if (range_type)
15400     return range_type;
15401
15402   low.kind = PROP_CONST;
15403   high.kind = PROP_CONST;
15404   high.data.const_val = 0;
15405
15406   /* Set LOW_DEFAULT_IS_VALID if current language and DWARF version allow
15407      omitting DW_AT_lower_bound.  */
15408   switch (cu->language)
15409     {
15410     case language_c:
15411     case language_cplus:
15412       low.data.const_val = 0;
15413       low_default_is_valid = 1;
15414       break;
15415     case language_fortran:
15416       low.data.const_val = 1;
15417       low_default_is_valid = 1;
15418       break;
15419     case language_d:
15420     case language_objc:
15421     case language_rust:
15422       low.data.const_val = 0;
15423       low_default_is_valid = (cu->header.version >= 4);
15424       break;
15425     case language_ada:
15426     case language_m2:
15427     case language_pascal:
15428       low.data.const_val = 1;
15429       low_default_is_valid = (cu->header.version >= 4);
15430       break;
15431     default:
15432       low.data.const_val = 0;
15433       low_default_is_valid = 0;
15434       break;
15435     }
15436
15437   attr = dwarf2_attr (die, DW_AT_lower_bound, cu);
15438   if (attr)
15439     attr_to_dynamic_prop (attr, die, cu, &low);
15440   else if (!low_default_is_valid)
15441     complaint (&symfile_complaints, _("Missing DW_AT_lower_bound "
15442                                       "- DIE at 0x%x [in module %s]"),
15443                to_underlying (die->sect_off), objfile_name (cu->objfile));
15444
15445   attr = dwarf2_attr (die, DW_AT_upper_bound, cu);
15446   if (!attr_to_dynamic_prop (attr, die, cu, &high))
15447     {
15448       attr = dwarf2_attr (die, DW_AT_count, cu);
15449       if (attr_to_dynamic_prop (attr, die, cu, &high))
15450         {
15451           /* If bounds are constant do the final calculation here.  */
15452           if (low.kind == PROP_CONST && high.kind == PROP_CONST)
15453             high.data.const_val = low.data.const_val + high.data.const_val - 1;
15454           else
15455             high_bound_is_count = 1;
15456         }
15457     }
15458
15459   /* Dwarf-2 specifications explicitly allows to create subrange types
15460      without specifying a base type.
15461      In that case, the base type must be set to the type of
15462      the lower bound, upper bound or count, in that order, if any of these
15463      three attributes references an object that has a type.
15464      If no base type is found, the Dwarf-2 specifications say that
15465      a signed integer type of size equal to the size of an address should
15466      be used.
15467      For the following C code: `extern char gdb_int [];'
15468      GCC produces an empty range DIE.
15469      FIXME: muller/2010-05-28: Possible references to object for low bound,
15470      high bound or count are not yet handled by this code.  */
15471   if (TYPE_CODE (base_type) == TYPE_CODE_VOID)
15472     {
15473       struct objfile *objfile = cu->objfile;
15474       struct gdbarch *gdbarch = get_objfile_arch (objfile);
15475       int addr_size = gdbarch_addr_bit (gdbarch) /8;
15476       struct type *int_type = objfile_type (objfile)->builtin_int;
15477
15478       /* Test "int", "long int", and "long long int" objfile types,
15479          and select the first one having a size above or equal to the
15480          architecture address size.  */
15481       if (int_type && TYPE_LENGTH (int_type) >= addr_size)
15482         base_type = int_type;
15483       else
15484         {
15485           int_type = objfile_type (objfile)->builtin_long;
15486           if (int_type && TYPE_LENGTH (int_type) >= addr_size)
15487             base_type = int_type;
15488           else
15489             {
15490               int_type = objfile_type (objfile)->builtin_long_long;
15491               if (int_type && TYPE_LENGTH (int_type) >= addr_size)
15492                 base_type = int_type;
15493             }
15494         }
15495     }
15496
15497   /* Normally, the DWARF producers are expected to use a signed
15498      constant form (Eg. DW_FORM_sdata) to express negative bounds.
15499      But this is unfortunately not always the case, as witnessed
15500      with GCC, for instance, where the ambiguous DW_FORM_dataN form
15501      is used instead.  To work around that ambiguity, we treat
15502      the bounds as signed, and thus sign-extend their values, when
15503      the base type is signed.  */
15504   negative_mask =
15505     -((LONGEST) 1 << (TYPE_LENGTH (base_type) * TARGET_CHAR_BIT - 1));
15506   if (low.kind == PROP_CONST
15507       && !TYPE_UNSIGNED (base_type) && (low.data.const_val & negative_mask))
15508     low.data.const_val |= negative_mask;
15509   if (high.kind == PROP_CONST
15510       && !TYPE_UNSIGNED (base_type) && (high.data.const_val & negative_mask))
15511     high.data.const_val |= negative_mask;
15512
15513   range_type = create_range_type (NULL, orig_base_type, &low, &high);
15514
15515   if (high_bound_is_count)
15516     TYPE_RANGE_DATA (range_type)->flag_upper_bound_is_count = 1;
15517
15518   /* Ada expects an empty array on no boundary attributes.  */
15519   if (attr == NULL && cu->language != language_ada)
15520     TYPE_HIGH_BOUND_KIND (range_type) = PROP_UNDEFINED;
15521
15522   name = dwarf2_name (die, cu);
15523   if (name)
15524     TYPE_NAME (range_type) = name;
15525
15526   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
15527   if (attr)
15528     TYPE_LENGTH (range_type) = DW_UNSND (attr);
15529
15530   set_die_type (die, range_type, cu);
15531
15532   /* set_die_type should be already done.  */
15533   set_descriptive_type (range_type, die, cu);
15534
15535   return range_type;
15536 }
15537
15538 static struct type *
15539 read_unspecified_type (struct die_info *die, struct dwarf2_cu *cu)
15540 {
15541   struct type *type;
15542
15543   /* For now, we only support the C meaning of an unspecified type: void.  */
15544
15545   type = init_type (cu->objfile, TYPE_CODE_VOID, 0, NULL);
15546   TYPE_NAME (type) = dwarf2_name (die, cu);
15547
15548   return set_die_type (die, type, cu);
15549 }
15550
15551 /* Read a single die and all its descendents.  Set the die's sibling
15552    field to NULL; set other fields in the die correctly, and set all
15553    of the descendents' fields correctly.  Set *NEW_INFO_PTR to the
15554    location of the info_ptr after reading all of those dies.  PARENT
15555    is the parent of the die in question.  */
15556
15557 static struct die_info *
15558 read_die_and_children (const struct die_reader_specs *reader,
15559                        const gdb_byte *info_ptr,
15560                        const gdb_byte **new_info_ptr,
15561                        struct die_info *parent)
15562 {
15563   struct die_info *die;
15564   const gdb_byte *cur_ptr;
15565   int has_children;
15566
15567   cur_ptr = read_full_die_1 (reader, &die, info_ptr, &has_children, 0);
15568   if (die == NULL)
15569     {
15570       *new_info_ptr = cur_ptr;
15571       return NULL;
15572     }
15573   store_in_ref_table (die, reader->cu);
15574
15575   if (has_children)
15576     die->child = read_die_and_siblings_1 (reader, cur_ptr, new_info_ptr, die);
15577   else
15578     {
15579       die->child = NULL;
15580       *new_info_ptr = cur_ptr;
15581     }
15582
15583   die->sibling = NULL;
15584   die->parent = parent;
15585   return die;
15586 }
15587
15588 /* Read a die, all of its descendents, and all of its siblings; set
15589    all of the fields of all of the dies correctly.  Arguments are as
15590    in read_die_and_children.  */
15591
15592 static struct die_info *
15593 read_die_and_siblings_1 (const struct die_reader_specs *reader,
15594                          const gdb_byte *info_ptr,
15595                          const gdb_byte **new_info_ptr,
15596                          struct die_info *parent)
15597 {
15598   struct die_info *first_die, *last_sibling;
15599   const gdb_byte *cur_ptr;
15600
15601   cur_ptr = info_ptr;
15602   first_die = last_sibling = NULL;
15603
15604   while (1)
15605     {
15606       struct die_info *die
15607         = read_die_and_children (reader, cur_ptr, &cur_ptr, parent);
15608
15609       if (die == NULL)
15610         {
15611           *new_info_ptr = cur_ptr;
15612           return first_die;
15613         }
15614
15615       if (!first_die)
15616         first_die = die;
15617       else
15618         last_sibling->sibling = die;
15619
15620       last_sibling = die;
15621     }
15622 }
15623
15624 /* Read a die, all of its descendents, and all of its siblings; set
15625    all of the fields of all of the dies correctly.  Arguments are as
15626    in read_die_and_children.
15627    This the main entry point for reading a DIE and all its children.  */
15628
15629 static struct die_info *
15630 read_die_and_siblings (const struct die_reader_specs *reader,
15631                        const gdb_byte *info_ptr,
15632                        const gdb_byte **new_info_ptr,
15633                        struct die_info *parent)
15634 {
15635   struct die_info *die = read_die_and_siblings_1 (reader, info_ptr,
15636                                                   new_info_ptr, parent);
15637
15638   if (dwarf_die_debug)
15639     {
15640       fprintf_unfiltered (gdb_stdlog,
15641                           "Read die from %s@0x%x of %s:\n",
15642                           get_section_name (reader->die_section),
15643                           (unsigned) (info_ptr - reader->die_section->buffer),
15644                           bfd_get_filename (reader->abfd));
15645       dump_die (die, dwarf_die_debug);
15646     }
15647
15648   return die;
15649 }
15650
15651 /* Read a die and all its attributes, leave space for NUM_EXTRA_ATTRS
15652    attributes.
15653    The caller is responsible for filling in the extra attributes
15654    and updating (*DIEP)->num_attrs.
15655    Set DIEP to point to a newly allocated die with its information,
15656    except for its child, sibling, and parent fields.
15657    Set HAS_CHILDREN to tell whether the die has children or not.  */
15658
15659 static const gdb_byte *
15660 read_full_die_1 (const struct die_reader_specs *reader,
15661                  struct die_info **diep, const gdb_byte *info_ptr,
15662                  int *has_children, int num_extra_attrs)
15663 {
15664   unsigned int abbrev_number, bytes_read, i;
15665   struct abbrev_info *abbrev;
15666   struct die_info *die;
15667   struct dwarf2_cu *cu = reader->cu;
15668   bfd *abfd = reader->abfd;
15669
15670   sect_offset sect_off = (sect_offset) (info_ptr - reader->buffer);
15671   abbrev_number = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
15672   info_ptr += bytes_read;
15673   if (!abbrev_number)
15674     {
15675       *diep = NULL;
15676       *has_children = 0;
15677       return info_ptr;
15678     }
15679
15680   abbrev = abbrev_table_lookup_abbrev (cu->abbrev_table, abbrev_number);
15681   if (!abbrev)
15682     error (_("Dwarf Error: could not find abbrev number %d [in module %s]"),
15683            abbrev_number,
15684            bfd_get_filename (abfd));
15685
15686   die = dwarf_alloc_die (cu, abbrev->num_attrs + num_extra_attrs);
15687   die->sect_off = sect_off;
15688   die->tag = abbrev->tag;
15689   die->abbrev = abbrev_number;
15690
15691   /* Make the result usable.
15692      The caller needs to update num_attrs after adding the extra
15693      attributes.  */
15694   die->num_attrs = abbrev->num_attrs;
15695
15696   for (i = 0; i < abbrev->num_attrs; ++i)
15697     info_ptr = read_attribute (reader, &die->attrs[i], &abbrev->attrs[i],
15698                                info_ptr);
15699
15700   *diep = die;
15701   *has_children = abbrev->has_children;
15702   return info_ptr;
15703 }
15704
15705 /* Read a die and all its attributes.
15706    Set DIEP to point to a newly allocated die with its information,
15707    except for its child, sibling, and parent fields.
15708    Set HAS_CHILDREN to tell whether the die has children or not.  */
15709
15710 static const gdb_byte *
15711 read_full_die (const struct die_reader_specs *reader,
15712                struct die_info **diep, const gdb_byte *info_ptr,
15713                int *has_children)
15714 {
15715   const gdb_byte *result;
15716
15717   result = read_full_die_1 (reader, diep, info_ptr, has_children, 0);
15718
15719   if (dwarf_die_debug)
15720     {
15721       fprintf_unfiltered (gdb_stdlog,
15722                           "Read die from %s@0x%x of %s:\n",
15723                           get_section_name (reader->die_section),
15724                           (unsigned) (info_ptr - reader->die_section->buffer),
15725                           bfd_get_filename (reader->abfd));
15726       dump_die (*diep, dwarf_die_debug);
15727     }
15728
15729   return result;
15730 }
15731 \f
15732 /* Abbreviation tables.
15733
15734    In DWARF version 2, the description of the debugging information is
15735    stored in a separate .debug_abbrev section.  Before we read any
15736    dies from a section we read in all abbreviations and install them
15737    in a hash table.  */
15738
15739 /* Allocate space for a struct abbrev_info object in ABBREV_TABLE.  */
15740
15741 static struct abbrev_info *
15742 abbrev_table_alloc_abbrev (struct abbrev_table *abbrev_table)
15743 {
15744   struct abbrev_info *abbrev;
15745
15746   abbrev = XOBNEW (&abbrev_table->abbrev_obstack, struct abbrev_info);
15747   memset (abbrev, 0, sizeof (struct abbrev_info));
15748
15749   return abbrev;
15750 }
15751
15752 /* Add an abbreviation to the table.  */
15753
15754 static void
15755 abbrev_table_add_abbrev (struct abbrev_table *abbrev_table,
15756                          unsigned int abbrev_number,
15757                          struct abbrev_info *abbrev)
15758 {
15759   unsigned int hash_number;
15760
15761   hash_number = abbrev_number % ABBREV_HASH_SIZE;
15762   abbrev->next = abbrev_table->abbrevs[hash_number];
15763   abbrev_table->abbrevs[hash_number] = abbrev;
15764 }
15765
15766 /* Look up an abbrev in the table.
15767    Returns NULL if the abbrev is not found.  */
15768
15769 static struct abbrev_info *
15770 abbrev_table_lookup_abbrev (const struct abbrev_table *abbrev_table,
15771                             unsigned int abbrev_number)
15772 {
15773   unsigned int hash_number;
15774   struct abbrev_info *abbrev;
15775
15776   hash_number = abbrev_number % ABBREV_HASH_SIZE;
15777   abbrev = abbrev_table->abbrevs[hash_number];
15778
15779   while (abbrev)
15780     {
15781       if (abbrev->number == abbrev_number)
15782         return abbrev;
15783       abbrev = abbrev->next;
15784     }
15785   return NULL;
15786 }
15787
15788 /* Read in an abbrev table.  */
15789
15790 static struct abbrev_table *
15791 abbrev_table_read_table (struct dwarf2_section_info *section,
15792                          sect_offset sect_off)
15793 {
15794   struct objfile *objfile = dwarf2_per_objfile->objfile;
15795   bfd *abfd = get_section_bfd_owner (section);
15796   struct abbrev_table *abbrev_table;
15797   const gdb_byte *abbrev_ptr;
15798   struct abbrev_info *cur_abbrev;
15799   unsigned int abbrev_number, bytes_read, abbrev_name;
15800   unsigned int abbrev_form;
15801   struct attr_abbrev *cur_attrs;
15802   unsigned int allocated_attrs;
15803
15804   abbrev_table = XNEW (struct abbrev_table);
15805   abbrev_table->sect_off = sect_off;
15806   obstack_init (&abbrev_table->abbrev_obstack);
15807   abbrev_table->abbrevs =
15808     XOBNEWVEC (&abbrev_table->abbrev_obstack, struct abbrev_info *,
15809                ABBREV_HASH_SIZE);
15810   memset (abbrev_table->abbrevs, 0,
15811           ABBREV_HASH_SIZE * sizeof (struct abbrev_info *));
15812
15813   dwarf2_read_section (objfile, section);
15814   abbrev_ptr = section->buffer + to_underlying (sect_off);
15815   abbrev_number = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
15816   abbrev_ptr += bytes_read;
15817
15818   allocated_attrs = ATTR_ALLOC_CHUNK;
15819   cur_attrs = XNEWVEC (struct attr_abbrev, allocated_attrs);
15820
15821   /* Loop until we reach an abbrev number of 0.  */
15822   while (abbrev_number)
15823     {
15824       cur_abbrev = abbrev_table_alloc_abbrev (abbrev_table);
15825
15826       /* read in abbrev header */
15827       cur_abbrev->number = abbrev_number;
15828       cur_abbrev->tag
15829         = (enum dwarf_tag) read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
15830       abbrev_ptr += bytes_read;
15831       cur_abbrev->has_children = read_1_byte (abfd, abbrev_ptr);
15832       abbrev_ptr += 1;
15833
15834       /* now read in declarations */
15835       for (;;)
15836         {
15837           LONGEST implicit_const;
15838
15839           abbrev_name = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
15840           abbrev_ptr += bytes_read;
15841           abbrev_form = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
15842           abbrev_ptr += bytes_read;
15843           if (abbrev_form == DW_FORM_implicit_const)
15844             {
15845               implicit_const = read_signed_leb128 (abfd, abbrev_ptr,
15846                                                    &bytes_read);
15847               abbrev_ptr += bytes_read;
15848             }
15849           else
15850             {
15851               /* Initialize it due to a false compiler warning.  */
15852               implicit_const = -1;
15853             }
15854
15855           if (abbrev_name == 0)
15856             break;
15857
15858           if (cur_abbrev->num_attrs == allocated_attrs)
15859             {
15860               allocated_attrs += ATTR_ALLOC_CHUNK;
15861               cur_attrs
15862                 = XRESIZEVEC (struct attr_abbrev, cur_attrs, allocated_attrs);
15863             }
15864
15865           cur_attrs[cur_abbrev->num_attrs].name
15866             = (enum dwarf_attribute) abbrev_name;
15867           cur_attrs[cur_abbrev->num_attrs].form
15868             = (enum dwarf_form) abbrev_form;
15869           cur_attrs[cur_abbrev->num_attrs].implicit_const = implicit_const;
15870           ++cur_abbrev->num_attrs;
15871         }
15872
15873       cur_abbrev->attrs =
15874         XOBNEWVEC (&abbrev_table->abbrev_obstack, struct attr_abbrev,
15875                    cur_abbrev->num_attrs);
15876       memcpy (cur_abbrev->attrs, cur_attrs,
15877               cur_abbrev->num_attrs * sizeof (struct attr_abbrev));
15878
15879       abbrev_table_add_abbrev (abbrev_table, abbrev_number, cur_abbrev);
15880
15881       /* Get next abbreviation.
15882          Under Irix6 the abbreviations for a compilation unit are not
15883          always properly terminated with an abbrev number of 0.
15884          Exit loop if we encounter an abbreviation which we have
15885          already read (which means we are about to read the abbreviations
15886          for the next compile unit) or if the end of the abbreviation
15887          table is reached.  */
15888       if ((unsigned int) (abbrev_ptr - section->buffer) >= section->size)
15889         break;
15890       abbrev_number = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
15891       abbrev_ptr += bytes_read;
15892       if (abbrev_table_lookup_abbrev (abbrev_table, abbrev_number) != NULL)
15893         break;
15894     }
15895
15896   xfree (cur_attrs);
15897   return abbrev_table;
15898 }
15899
15900 /* Free the resources held by ABBREV_TABLE.  */
15901
15902 static void
15903 abbrev_table_free (struct abbrev_table *abbrev_table)
15904 {
15905   obstack_free (&abbrev_table->abbrev_obstack, NULL);
15906   xfree (abbrev_table);
15907 }
15908
15909 /* Same as abbrev_table_free but as a cleanup.
15910    We pass in a pointer to the pointer to the table so that we can
15911    set the pointer to NULL when we're done.  It also simplifies
15912    build_type_psymtabs_1.  */
15913
15914 static void
15915 abbrev_table_free_cleanup (void *table_ptr)
15916 {
15917   struct abbrev_table **abbrev_table_ptr = (struct abbrev_table **) table_ptr;
15918
15919   if (*abbrev_table_ptr != NULL)
15920     abbrev_table_free (*abbrev_table_ptr);
15921   *abbrev_table_ptr = NULL;
15922 }
15923
15924 /* Read the abbrev table for CU from ABBREV_SECTION.  */
15925
15926 static void
15927 dwarf2_read_abbrevs (struct dwarf2_cu *cu,
15928                      struct dwarf2_section_info *abbrev_section)
15929 {
15930   cu->abbrev_table =
15931     abbrev_table_read_table (abbrev_section, cu->header.abbrev_sect_off);
15932 }
15933
15934 /* Release the memory used by the abbrev table for a compilation unit.  */
15935
15936 static void
15937 dwarf2_free_abbrev_table (void *ptr_to_cu)
15938 {
15939   struct dwarf2_cu *cu = (struct dwarf2_cu *) ptr_to_cu;
15940
15941   if (cu->abbrev_table != NULL)
15942     abbrev_table_free (cu->abbrev_table);
15943   /* Set this to NULL so that we SEGV if we try to read it later,
15944      and also because free_comp_unit verifies this is NULL.  */
15945   cu->abbrev_table = NULL;
15946 }
15947 \f
15948 /* Returns nonzero if TAG represents a type that we might generate a partial
15949    symbol for.  */
15950
15951 static int
15952 is_type_tag_for_partial (int tag)
15953 {
15954   switch (tag)
15955     {
15956 #if 0
15957     /* Some types that would be reasonable to generate partial symbols for,
15958        that we don't at present.  */
15959     case DW_TAG_array_type:
15960     case DW_TAG_file_type:
15961     case DW_TAG_ptr_to_member_type:
15962     case DW_TAG_set_type:
15963     case DW_TAG_string_type:
15964     case DW_TAG_subroutine_type:
15965 #endif
15966     case DW_TAG_base_type:
15967     case DW_TAG_class_type:
15968     case DW_TAG_interface_type:
15969     case DW_TAG_enumeration_type:
15970     case DW_TAG_structure_type:
15971     case DW_TAG_subrange_type:
15972     case DW_TAG_typedef:
15973     case DW_TAG_union_type:
15974       return 1;
15975     default:
15976       return 0;
15977     }
15978 }
15979
15980 /* Load all DIEs that are interesting for partial symbols into memory.  */
15981
15982 static struct partial_die_info *
15983 load_partial_dies (const struct die_reader_specs *reader,
15984                    const gdb_byte *info_ptr, int building_psymtab)
15985 {
15986   struct dwarf2_cu *cu = reader->cu;
15987   struct objfile *objfile = cu->objfile;
15988   struct partial_die_info *part_die;
15989   struct partial_die_info *parent_die, *last_die, *first_die = NULL;
15990   struct abbrev_info *abbrev;
15991   unsigned int bytes_read;
15992   unsigned int load_all = 0;
15993   int nesting_level = 1;
15994
15995   parent_die = NULL;
15996   last_die = NULL;
15997
15998   gdb_assert (cu->per_cu != NULL);
15999   if (cu->per_cu->load_all_dies)
16000     load_all = 1;
16001
16002   cu->partial_dies
16003     = htab_create_alloc_ex (cu->header.length / 12,
16004                             partial_die_hash,
16005                             partial_die_eq,
16006                             NULL,
16007                             &cu->comp_unit_obstack,
16008                             hashtab_obstack_allocate,
16009                             dummy_obstack_deallocate);
16010
16011   part_die = XOBNEW (&cu->comp_unit_obstack, struct partial_die_info);
16012
16013   while (1)
16014     {
16015       abbrev = peek_die_abbrev (info_ptr, &bytes_read, cu);
16016
16017       /* A NULL abbrev means the end of a series of children.  */
16018       if (abbrev == NULL)
16019         {
16020           if (--nesting_level == 0)
16021             {
16022               /* PART_DIE was probably the last thing allocated on the
16023                  comp_unit_obstack, so we could call obstack_free
16024                  here.  We don't do that because the waste is small,
16025                  and will be cleaned up when we're done with this
16026                  compilation unit.  This way, we're also more robust
16027                  against other users of the comp_unit_obstack.  */
16028               return first_die;
16029             }
16030           info_ptr += bytes_read;
16031           last_die = parent_die;
16032           parent_die = parent_die->die_parent;
16033           continue;
16034         }
16035
16036       /* Check for template arguments.  We never save these; if
16037          they're seen, we just mark the parent, and go on our way.  */
16038       if (parent_die != NULL
16039           && cu->language == language_cplus
16040           && (abbrev->tag == DW_TAG_template_type_param
16041               || abbrev->tag == DW_TAG_template_value_param))
16042         {
16043           parent_die->has_template_arguments = 1;
16044
16045           if (!load_all)
16046             {
16047               /* We don't need a partial DIE for the template argument.  */
16048               info_ptr = skip_one_die (reader, info_ptr + bytes_read, abbrev);
16049               continue;
16050             }
16051         }
16052
16053       /* We only recurse into c++ subprograms looking for template arguments.
16054          Skip their other children.  */
16055       if (!load_all
16056           && cu->language == language_cplus
16057           && parent_die != NULL
16058           && parent_die->tag == DW_TAG_subprogram)
16059         {
16060           info_ptr = skip_one_die (reader, info_ptr + bytes_read, abbrev);
16061           continue;
16062         }
16063
16064       /* Check whether this DIE is interesting enough to save.  Normally
16065          we would not be interested in members here, but there may be
16066          later variables referencing them via DW_AT_specification (for
16067          static members).  */
16068       if (!load_all
16069           && !is_type_tag_for_partial (abbrev->tag)
16070           && abbrev->tag != DW_TAG_constant
16071           && abbrev->tag != DW_TAG_enumerator
16072           && abbrev->tag != DW_TAG_subprogram
16073           && abbrev->tag != DW_TAG_lexical_block
16074           && abbrev->tag != DW_TAG_variable
16075           && abbrev->tag != DW_TAG_namespace
16076           && abbrev->tag != DW_TAG_module
16077           && abbrev->tag != DW_TAG_member
16078           && abbrev->tag != DW_TAG_imported_unit
16079           && abbrev->tag != DW_TAG_imported_declaration)
16080         {
16081           /* Otherwise we skip to the next sibling, if any.  */
16082           info_ptr = skip_one_die (reader, info_ptr + bytes_read, abbrev);
16083           continue;
16084         }
16085
16086       info_ptr = read_partial_die (reader, part_die, abbrev, bytes_read,
16087                                    info_ptr);
16088
16089       /* This two-pass algorithm for processing partial symbols has a
16090          high cost in cache pressure.  Thus, handle some simple cases
16091          here which cover the majority of C partial symbols.  DIEs
16092          which neither have specification tags in them, nor could have
16093          specification tags elsewhere pointing at them, can simply be
16094          processed and discarded.
16095
16096          This segment is also optional; scan_partial_symbols and
16097          add_partial_symbol will handle these DIEs if we chain
16098          them in normally.  When compilers which do not emit large
16099          quantities of duplicate debug information are more common,
16100          this code can probably be removed.  */
16101
16102       /* Any complete simple types at the top level (pretty much all
16103          of them, for a language without namespaces), can be processed
16104          directly.  */
16105       if (parent_die == NULL
16106           && part_die->has_specification == 0
16107           && part_die->is_declaration == 0
16108           && ((part_die->tag == DW_TAG_typedef && !part_die->has_children)
16109               || part_die->tag == DW_TAG_base_type
16110               || part_die->tag == DW_TAG_subrange_type))
16111         {
16112           if (building_psymtab && part_die->name != NULL)
16113             add_psymbol_to_list (part_die->name, strlen (part_die->name), 0,
16114                                  VAR_DOMAIN, LOC_TYPEDEF,
16115                                  &objfile->static_psymbols,
16116                                  0, cu->language, objfile);
16117           info_ptr = locate_pdi_sibling (reader, part_die, info_ptr);
16118           continue;
16119         }
16120
16121       /* The exception for DW_TAG_typedef with has_children above is
16122          a workaround of GCC PR debug/47510.  In the case of this complaint
16123          type_name_no_tag_or_error will error on such types later.
16124
16125          GDB skipped children of DW_TAG_typedef by the shortcut above and then
16126          it could not find the child DIEs referenced later, this is checked
16127          above.  In correct DWARF DW_TAG_typedef should have no children.  */
16128
16129       if (part_die->tag == DW_TAG_typedef && part_die->has_children)
16130         complaint (&symfile_complaints,
16131                    _("DW_TAG_typedef has childen - GCC PR debug/47510 bug "
16132                      "- DIE at 0x%x [in module %s]"),
16133                    to_underlying (part_die->sect_off), objfile_name (objfile));
16134
16135       /* If we're at the second level, and we're an enumerator, and
16136          our parent has no specification (meaning possibly lives in a
16137          namespace elsewhere), then we can add the partial symbol now
16138          instead of queueing it.  */
16139       if (part_die->tag == DW_TAG_enumerator
16140           && parent_die != NULL
16141           && parent_die->die_parent == NULL
16142           && parent_die->tag == DW_TAG_enumeration_type
16143           && parent_die->has_specification == 0)
16144         {
16145           if (part_die->name == NULL)
16146             complaint (&symfile_complaints,
16147                        _("malformed enumerator DIE ignored"));
16148           else if (building_psymtab)
16149             add_psymbol_to_list (part_die->name, strlen (part_die->name), 0,
16150                                  VAR_DOMAIN, LOC_CONST,
16151                                  cu->language == language_cplus
16152                                  ? &objfile->global_psymbols
16153                                  : &objfile->static_psymbols,
16154                                  0, cu->language, objfile);
16155
16156           info_ptr = locate_pdi_sibling (reader, part_die, info_ptr);
16157           continue;
16158         }
16159
16160       /* We'll save this DIE so link it in.  */
16161       part_die->die_parent = parent_die;
16162       part_die->die_sibling = NULL;
16163       part_die->die_child = NULL;
16164
16165       if (last_die && last_die == parent_die)
16166         last_die->die_child = part_die;
16167       else if (last_die)
16168         last_die->die_sibling = part_die;
16169
16170       last_die = part_die;
16171
16172       if (first_die == NULL)
16173         first_die = part_die;
16174
16175       /* Maybe add the DIE to the hash table.  Not all DIEs that we
16176          find interesting need to be in the hash table, because we
16177          also have the parent/sibling/child chains; only those that we
16178          might refer to by offset later during partial symbol reading.
16179
16180          For now this means things that might have be the target of a
16181          DW_AT_specification, DW_AT_abstract_origin, or
16182          DW_AT_extension.  DW_AT_extension will refer only to
16183          namespaces; DW_AT_abstract_origin refers to functions (and
16184          many things under the function DIE, but we do not recurse
16185          into function DIEs during partial symbol reading) and
16186          possibly variables as well; DW_AT_specification refers to
16187          declarations.  Declarations ought to have the DW_AT_declaration
16188          flag.  It happens that GCC forgets to put it in sometimes, but
16189          only for functions, not for types.
16190
16191          Adding more things than necessary to the hash table is harmless
16192          except for the performance cost.  Adding too few will result in
16193          wasted time in find_partial_die, when we reread the compilation
16194          unit with load_all_dies set.  */
16195
16196       if (load_all
16197           || abbrev->tag == DW_TAG_constant
16198           || abbrev->tag == DW_TAG_subprogram
16199           || abbrev->tag == DW_TAG_variable
16200           || abbrev->tag == DW_TAG_namespace
16201           || part_die->is_declaration)
16202         {
16203           void **slot;
16204
16205           slot = htab_find_slot_with_hash (cu->partial_dies, part_die,
16206                                            to_underlying (part_die->sect_off),
16207                                            INSERT);
16208           *slot = part_die;
16209         }
16210
16211       part_die = XOBNEW (&cu->comp_unit_obstack, struct partial_die_info);
16212
16213       /* For some DIEs we want to follow their children (if any).  For C
16214          we have no reason to follow the children of structures; for other
16215          languages we have to, so that we can get at method physnames
16216          to infer fully qualified class names, for DW_AT_specification,
16217          and for C++ template arguments.  For C++, we also look one level
16218          inside functions to find template arguments (if the name of the
16219          function does not already contain the template arguments).
16220
16221          For Ada, we need to scan the children of subprograms and lexical
16222          blocks as well because Ada allows the definition of nested
16223          entities that could be interesting for the debugger, such as
16224          nested subprograms for instance.  */
16225       if (last_die->has_children
16226           && (load_all
16227               || last_die->tag == DW_TAG_namespace
16228               || last_die->tag == DW_TAG_module
16229               || last_die->tag == DW_TAG_enumeration_type
16230               || (cu->language == language_cplus
16231                   && last_die->tag == DW_TAG_subprogram
16232                   && (last_die->name == NULL
16233                       || strchr (last_die->name, '<') == NULL))
16234               || (cu->language != language_c
16235                   && (last_die->tag == DW_TAG_class_type
16236                       || last_die->tag == DW_TAG_interface_type
16237                       || last_die->tag == DW_TAG_structure_type
16238                       || last_die->tag == DW_TAG_union_type))
16239               || (cu->language == language_ada
16240                   && (last_die->tag == DW_TAG_subprogram
16241                       || last_die->tag == DW_TAG_lexical_block))))
16242         {
16243           nesting_level++;
16244           parent_die = last_die;
16245           continue;
16246         }
16247
16248       /* Otherwise we skip to the next sibling, if any.  */
16249       info_ptr = locate_pdi_sibling (reader, last_die, info_ptr);
16250
16251       /* Back to the top, do it again.  */
16252     }
16253 }
16254
16255 /* Read a minimal amount of information into the minimal die structure.  */
16256
16257 static const gdb_byte *
16258 read_partial_die (const struct die_reader_specs *reader,
16259                   struct partial_die_info *part_die,
16260                   struct abbrev_info *abbrev, unsigned int abbrev_len,
16261                   const gdb_byte *info_ptr)
16262 {
16263   struct dwarf2_cu *cu = reader->cu;
16264   struct objfile *objfile = cu->objfile;
16265   const gdb_byte *buffer = reader->buffer;
16266   unsigned int i;
16267   struct attribute attr;
16268   int has_low_pc_attr = 0;
16269   int has_high_pc_attr = 0;
16270   int high_pc_relative = 0;
16271
16272   memset (part_die, 0, sizeof (struct partial_die_info));
16273
16274   part_die->sect_off = (sect_offset) (info_ptr - buffer);
16275
16276   info_ptr += abbrev_len;
16277
16278   if (abbrev == NULL)
16279     return info_ptr;
16280
16281   part_die->tag = abbrev->tag;
16282   part_die->has_children = abbrev->has_children;
16283
16284   for (i = 0; i < abbrev->num_attrs; ++i)
16285     {
16286       info_ptr = read_attribute (reader, &attr, &abbrev->attrs[i], info_ptr);
16287
16288       /* Store the data if it is of an attribute we want to keep in a
16289          partial symbol table.  */
16290       switch (attr.name)
16291         {
16292         case DW_AT_name:
16293           switch (part_die->tag)
16294             {
16295             case DW_TAG_compile_unit:
16296             case DW_TAG_partial_unit:
16297             case DW_TAG_type_unit:
16298               /* Compilation units have a DW_AT_name that is a filename, not
16299                  a source language identifier.  */
16300             case DW_TAG_enumeration_type:
16301             case DW_TAG_enumerator:
16302               /* These tags always have simple identifiers already; no need
16303                  to canonicalize them.  */
16304               part_die->name = DW_STRING (&attr);
16305               break;
16306             default:
16307               part_die->name
16308                 = dwarf2_canonicalize_name (DW_STRING (&attr), cu,
16309                                             &objfile->per_bfd->storage_obstack);
16310               break;
16311             }
16312           break;
16313         case DW_AT_linkage_name:
16314         case DW_AT_MIPS_linkage_name:
16315           /* Note that both forms of linkage name might appear.  We
16316              assume they will be the same, and we only store the last
16317              one we see.  */
16318           if (cu->language == language_ada)
16319             part_die->name = DW_STRING (&attr);
16320           part_die->linkage_name = DW_STRING (&attr);
16321           break;
16322         case DW_AT_low_pc:
16323           has_low_pc_attr = 1;
16324           part_die->lowpc = attr_value_as_address (&attr);
16325           break;
16326         case DW_AT_high_pc:
16327           has_high_pc_attr = 1;
16328           part_die->highpc = attr_value_as_address (&attr);
16329           if (cu->header.version >= 4 && attr_form_is_constant (&attr))
16330                 high_pc_relative = 1;
16331           break;
16332         case DW_AT_location:
16333           /* Support the .debug_loc offsets.  */
16334           if (attr_form_is_block (&attr))
16335             {
16336                part_die->d.locdesc = DW_BLOCK (&attr);
16337             }
16338           else if (attr_form_is_section_offset (&attr))
16339             {
16340               dwarf2_complex_location_expr_complaint ();
16341             }
16342           else
16343             {
16344               dwarf2_invalid_attrib_class_complaint ("DW_AT_location",
16345                                                      "partial symbol information");
16346             }
16347           break;
16348         case DW_AT_external:
16349           part_die->is_external = DW_UNSND (&attr);
16350           break;
16351         case DW_AT_declaration:
16352           part_die->is_declaration = DW_UNSND (&attr);
16353           break;
16354         case DW_AT_type:
16355           part_die->has_type = 1;
16356           break;
16357         case DW_AT_abstract_origin:
16358         case DW_AT_specification:
16359         case DW_AT_extension:
16360           part_die->has_specification = 1;
16361           part_die->spec_offset = dwarf2_get_ref_die_offset (&attr);
16362           part_die->spec_is_dwz = (attr.form == DW_FORM_GNU_ref_alt
16363                                    || cu->per_cu->is_dwz);
16364           break;
16365         case DW_AT_sibling:
16366           /* Ignore absolute siblings, they might point outside of
16367              the current compile unit.  */
16368           if (attr.form == DW_FORM_ref_addr)
16369             complaint (&symfile_complaints,
16370                        _("ignoring absolute DW_AT_sibling"));
16371           else
16372             {
16373               sect_offset off = dwarf2_get_ref_die_offset (&attr);
16374               const gdb_byte *sibling_ptr = buffer + to_underlying (off);
16375
16376               if (sibling_ptr < info_ptr)
16377                 complaint (&symfile_complaints,
16378                            _("DW_AT_sibling points backwards"));
16379               else if (sibling_ptr > reader->buffer_end)
16380                 dwarf2_section_buffer_overflow_complaint (reader->die_section);
16381               else
16382                 part_die->sibling = sibling_ptr;
16383             }
16384           break;
16385         case DW_AT_byte_size:
16386           part_die->has_byte_size = 1;
16387           break;
16388         case DW_AT_const_value:
16389           part_die->has_const_value = 1;
16390           break;
16391         case DW_AT_calling_convention:
16392           /* DWARF doesn't provide a way to identify a program's source-level
16393              entry point.  DW_AT_calling_convention attributes are only meant
16394              to describe functions' calling conventions.
16395
16396              However, because it's a necessary piece of information in
16397              Fortran, and before DWARF 4 DW_CC_program was the only
16398              piece of debugging information whose definition refers to
16399              a 'main program' at all, several compilers marked Fortran
16400              main programs with DW_CC_program --- even when those
16401              functions use the standard calling conventions.
16402
16403              Although DWARF now specifies a way to provide this
16404              information, we support this practice for backward
16405              compatibility.  */
16406           if (DW_UNSND (&attr) == DW_CC_program
16407               && cu->language == language_fortran)
16408             part_die->main_subprogram = 1;
16409           break;
16410         case DW_AT_inline:
16411           if (DW_UNSND (&attr) == DW_INL_inlined
16412               || DW_UNSND (&attr) == DW_INL_declared_inlined)
16413             part_die->may_be_inlined = 1;
16414           break;
16415
16416         case DW_AT_import:
16417           if (part_die->tag == DW_TAG_imported_unit)
16418             {
16419               part_die->d.sect_off = dwarf2_get_ref_die_offset (&attr);
16420               part_die->is_dwz = (attr.form == DW_FORM_GNU_ref_alt
16421                                   || cu->per_cu->is_dwz);
16422             }
16423           break;
16424
16425         case DW_AT_main_subprogram:
16426           part_die->main_subprogram = DW_UNSND (&attr);
16427           break;
16428
16429         default:
16430           break;
16431         }
16432     }
16433
16434   if (high_pc_relative)
16435     part_die->highpc += part_die->lowpc;
16436
16437   if (has_low_pc_attr && has_high_pc_attr)
16438     {
16439       /* When using the GNU linker, .gnu.linkonce. sections are used to
16440          eliminate duplicate copies of functions and vtables and such.
16441          The linker will arbitrarily choose one and discard the others.
16442          The AT_*_pc values for such functions refer to local labels in
16443          these sections.  If the section from that file was discarded, the
16444          labels are not in the output, so the relocs get a value of 0.
16445          If this is a discarded function, mark the pc bounds as invalid,
16446          so that GDB will ignore it.  */
16447       if (part_die->lowpc == 0 && !dwarf2_per_objfile->has_section_at_zero)
16448         {
16449           struct gdbarch *gdbarch = get_objfile_arch (objfile);
16450
16451           complaint (&symfile_complaints,
16452                      _("DW_AT_low_pc %s is zero "
16453                        "for DIE at 0x%x [in module %s]"),
16454                      paddress (gdbarch, part_die->lowpc),
16455                      to_underlying (part_die->sect_off), objfile_name (objfile));
16456         }
16457       /* dwarf2_get_pc_bounds has also the strict low < high requirement.  */
16458       else if (part_die->lowpc >= part_die->highpc)
16459         {
16460           struct gdbarch *gdbarch = get_objfile_arch (objfile);
16461
16462           complaint (&symfile_complaints,
16463                      _("DW_AT_low_pc %s is not < DW_AT_high_pc %s "
16464                        "for DIE at 0x%x [in module %s]"),
16465                      paddress (gdbarch, part_die->lowpc),
16466                      paddress (gdbarch, part_die->highpc),
16467                      to_underlying (part_die->sect_off),
16468                      objfile_name (objfile));
16469         }
16470       else
16471         part_die->has_pc_info = 1;
16472     }
16473
16474   return info_ptr;
16475 }
16476
16477 /* Find a cached partial DIE at OFFSET in CU.  */
16478
16479 static struct partial_die_info *
16480 find_partial_die_in_comp_unit (sect_offset sect_off, struct dwarf2_cu *cu)
16481 {
16482   struct partial_die_info *lookup_die = NULL;
16483   struct partial_die_info part_die;
16484
16485   part_die.sect_off = sect_off;
16486   lookup_die = ((struct partial_die_info *)
16487                 htab_find_with_hash (cu->partial_dies, &part_die,
16488                                      to_underlying (sect_off)));
16489
16490   return lookup_die;
16491 }
16492
16493 /* Find a partial DIE at OFFSET, which may or may not be in CU,
16494    except in the case of .debug_types DIEs which do not reference
16495    outside their CU (they do however referencing other types via
16496    DW_FORM_ref_sig8).  */
16497
16498 static struct partial_die_info *
16499 find_partial_die (sect_offset sect_off, int offset_in_dwz, struct dwarf2_cu *cu)
16500 {
16501   struct objfile *objfile = cu->objfile;
16502   struct dwarf2_per_cu_data *per_cu = NULL;
16503   struct partial_die_info *pd = NULL;
16504
16505   if (offset_in_dwz == cu->per_cu->is_dwz
16506       && offset_in_cu_p (&cu->header, sect_off))
16507     {
16508       pd = find_partial_die_in_comp_unit (sect_off, cu);
16509       if (pd != NULL)
16510         return pd;
16511       /* We missed recording what we needed.
16512          Load all dies and try again.  */
16513       per_cu = cu->per_cu;
16514     }
16515   else
16516     {
16517       /* TUs don't reference other CUs/TUs (except via type signatures).  */
16518       if (cu->per_cu->is_debug_types)
16519         {
16520           error (_("Dwarf Error: Type Unit at offset 0x%x contains"
16521                    " external reference to offset 0x%x [in module %s].\n"),
16522                  to_underlying (cu->header.sect_off), to_underlying (sect_off),
16523                  bfd_get_filename (objfile->obfd));
16524         }
16525       per_cu = dwarf2_find_containing_comp_unit (sect_off, offset_in_dwz,
16526                                                  objfile);
16527
16528       if (per_cu->cu == NULL || per_cu->cu->partial_dies == NULL)
16529         load_partial_comp_unit (per_cu);
16530
16531       per_cu->cu->last_used = 0;
16532       pd = find_partial_die_in_comp_unit (sect_off, per_cu->cu);
16533     }
16534
16535   /* If we didn't find it, and not all dies have been loaded,
16536      load them all and try again.  */
16537
16538   if (pd == NULL && per_cu->load_all_dies == 0)
16539     {
16540       per_cu->load_all_dies = 1;
16541
16542       /* This is nasty.  When we reread the DIEs, somewhere up the call chain
16543          THIS_CU->cu may already be in use.  So we can't just free it and
16544          replace its DIEs with the ones we read in.  Instead, we leave those
16545          DIEs alone (which can still be in use, e.g. in scan_partial_symbols),
16546          and clobber THIS_CU->cu->partial_dies with the hash table for the new
16547          set.  */
16548       load_partial_comp_unit (per_cu);
16549
16550       pd = find_partial_die_in_comp_unit (sect_off, per_cu->cu);
16551     }
16552
16553   if (pd == NULL)
16554     internal_error (__FILE__, __LINE__,
16555                     _("could not find partial DIE 0x%x "
16556                       "in cache [from module %s]\n"),
16557                     to_underlying (sect_off), bfd_get_filename (objfile->obfd));
16558   return pd;
16559 }
16560
16561 /* See if we can figure out if the class lives in a namespace.  We do
16562    this by looking for a member function; its demangled name will
16563    contain namespace info, if there is any.  */
16564
16565 static void
16566 guess_partial_die_structure_name (struct partial_die_info *struct_pdi,
16567                                   struct dwarf2_cu *cu)
16568 {
16569   /* NOTE: carlton/2003-10-07: Getting the info this way changes
16570      what template types look like, because the demangler
16571      frequently doesn't give the same name as the debug info.  We
16572      could fix this by only using the demangled name to get the
16573      prefix (but see comment in read_structure_type).  */
16574
16575   struct partial_die_info *real_pdi;
16576   struct partial_die_info *child_pdi;
16577
16578   /* If this DIE (this DIE's specification, if any) has a parent, then
16579      we should not do this.  We'll prepend the parent's fully qualified
16580      name when we create the partial symbol.  */
16581
16582   real_pdi = struct_pdi;
16583   while (real_pdi->has_specification)
16584     real_pdi = find_partial_die (real_pdi->spec_offset,
16585                                  real_pdi->spec_is_dwz, cu);
16586
16587   if (real_pdi->die_parent != NULL)
16588     return;
16589
16590   for (child_pdi = struct_pdi->die_child;
16591        child_pdi != NULL;
16592        child_pdi = child_pdi->die_sibling)
16593     {
16594       if (child_pdi->tag == DW_TAG_subprogram
16595           && child_pdi->linkage_name != NULL)
16596         {
16597           char *actual_class_name
16598             = language_class_name_from_physname (cu->language_defn,
16599                                                  child_pdi->linkage_name);
16600           if (actual_class_name != NULL)
16601             {
16602               struct_pdi->name
16603                 = ((const char *)
16604                    obstack_copy0 (&cu->objfile->per_bfd->storage_obstack,
16605                                   actual_class_name,
16606                                   strlen (actual_class_name)));
16607               xfree (actual_class_name);
16608             }
16609           break;
16610         }
16611     }
16612 }
16613
16614 /* Adjust PART_DIE before generating a symbol for it.  This function
16615    may set the is_external flag or change the DIE's name.  */
16616
16617 static void
16618 fixup_partial_die (struct partial_die_info *part_die,
16619                    struct dwarf2_cu *cu)
16620 {
16621   /* Once we've fixed up a die, there's no point in doing so again.
16622      This also avoids a memory leak if we were to call
16623      guess_partial_die_structure_name multiple times.  */
16624   if (part_die->fixup_called)
16625     return;
16626
16627   /* If we found a reference attribute and the DIE has no name, try
16628      to find a name in the referred to DIE.  */
16629
16630   if (part_die->name == NULL && part_die->has_specification)
16631     {
16632       struct partial_die_info *spec_die;
16633
16634       spec_die = find_partial_die (part_die->spec_offset,
16635                                    part_die->spec_is_dwz, cu);
16636
16637       fixup_partial_die (spec_die, cu);
16638
16639       if (spec_die->name)
16640         {
16641           part_die->name = spec_die->name;
16642
16643           /* Copy DW_AT_external attribute if it is set.  */
16644           if (spec_die->is_external)
16645             part_die->is_external = spec_die->is_external;
16646         }
16647     }
16648
16649   /* Set default names for some unnamed DIEs.  */
16650
16651   if (part_die->name == NULL && part_die->tag == DW_TAG_namespace)
16652     part_die->name = CP_ANONYMOUS_NAMESPACE_STR;
16653
16654   /* If there is no parent die to provide a namespace, and there are
16655      children, see if we can determine the namespace from their linkage
16656      name.  */
16657   if (cu->language == language_cplus
16658       && !VEC_empty (dwarf2_section_info_def, dwarf2_per_objfile->types)
16659       && part_die->die_parent == NULL
16660       && part_die->has_children
16661       && (part_die->tag == DW_TAG_class_type
16662           || part_die->tag == DW_TAG_structure_type
16663           || part_die->tag == DW_TAG_union_type))
16664     guess_partial_die_structure_name (part_die, cu);
16665
16666   /* GCC might emit a nameless struct or union that has a linkage
16667      name.  See http://gcc.gnu.org/bugzilla/show_bug.cgi?id=47510.  */
16668   if (part_die->name == NULL
16669       && (part_die->tag == DW_TAG_class_type
16670           || part_die->tag == DW_TAG_interface_type
16671           || part_die->tag == DW_TAG_structure_type
16672           || part_die->tag == DW_TAG_union_type)
16673       && part_die->linkage_name != NULL)
16674     {
16675       char *demangled;
16676
16677       demangled = gdb_demangle (part_die->linkage_name, DMGL_TYPES);
16678       if (demangled)
16679         {
16680           const char *base;
16681
16682           /* Strip any leading namespaces/classes, keep only the base name.
16683              DW_AT_name for named DIEs does not contain the prefixes.  */
16684           base = strrchr (demangled, ':');
16685           if (base && base > demangled && base[-1] == ':')
16686             base++;
16687           else
16688             base = demangled;
16689
16690           part_die->name
16691             = ((const char *)
16692                obstack_copy0 (&cu->objfile->per_bfd->storage_obstack,
16693                               base, strlen (base)));
16694           xfree (demangled);
16695         }
16696     }
16697
16698   part_die->fixup_called = 1;
16699 }
16700
16701 /* Read an attribute value described by an attribute form.  */
16702
16703 static const gdb_byte *
16704 read_attribute_value (const struct die_reader_specs *reader,
16705                       struct attribute *attr, unsigned form,
16706                       LONGEST implicit_const, const gdb_byte *info_ptr)
16707 {
16708   struct dwarf2_cu *cu = reader->cu;
16709   struct objfile *objfile = cu->objfile;
16710   struct gdbarch *gdbarch = get_objfile_arch (objfile);
16711   bfd *abfd = reader->abfd;
16712   struct comp_unit_head *cu_header = &cu->header;
16713   unsigned int bytes_read;
16714   struct dwarf_block *blk;
16715
16716   attr->form = (enum dwarf_form) form;
16717   switch (form)
16718     {
16719     case DW_FORM_ref_addr:
16720       if (cu->header.version == 2)
16721         DW_UNSND (attr) = read_address (abfd, info_ptr, cu, &bytes_read);
16722       else
16723         DW_UNSND (attr) = read_offset (abfd, info_ptr,
16724                                        &cu->header, &bytes_read);
16725       info_ptr += bytes_read;
16726       break;
16727     case DW_FORM_GNU_ref_alt:
16728       DW_UNSND (attr) = read_offset (abfd, info_ptr, &cu->header, &bytes_read);
16729       info_ptr += bytes_read;
16730       break;
16731     case DW_FORM_addr:
16732       DW_ADDR (attr) = read_address (abfd, info_ptr, cu, &bytes_read);
16733       DW_ADDR (attr) = gdbarch_adjust_dwarf2_addr (gdbarch, DW_ADDR (attr));
16734       info_ptr += bytes_read;
16735       break;
16736     case DW_FORM_block2:
16737       blk = dwarf_alloc_block (cu);
16738       blk->size = read_2_bytes (abfd, info_ptr);
16739       info_ptr += 2;
16740       blk->data = read_n_bytes (abfd, info_ptr, blk->size);
16741       info_ptr += blk->size;
16742       DW_BLOCK (attr) = blk;
16743       break;
16744     case DW_FORM_block4:
16745       blk = dwarf_alloc_block (cu);
16746       blk->size = read_4_bytes (abfd, info_ptr);
16747       info_ptr += 4;
16748       blk->data = read_n_bytes (abfd, info_ptr, blk->size);
16749       info_ptr += blk->size;
16750       DW_BLOCK (attr) = blk;
16751       break;
16752     case DW_FORM_data2:
16753       DW_UNSND (attr) = read_2_bytes (abfd, info_ptr);
16754       info_ptr += 2;
16755       break;
16756     case DW_FORM_data4:
16757       DW_UNSND (attr) = read_4_bytes (abfd, info_ptr);
16758       info_ptr += 4;
16759       break;
16760     case DW_FORM_data8:
16761       DW_UNSND (attr) = read_8_bytes (abfd, info_ptr);
16762       info_ptr += 8;
16763       break;
16764     case DW_FORM_data16:
16765       blk = dwarf_alloc_block (cu);
16766       blk->size = 16;
16767       blk->data = read_n_bytes (abfd, info_ptr, 16);
16768       info_ptr += 16;
16769       DW_BLOCK (attr) = blk;
16770       break;
16771     case DW_FORM_sec_offset:
16772       DW_UNSND (attr) = read_offset (abfd, info_ptr, &cu->header, &bytes_read);
16773       info_ptr += bytes_read;
16774       break;
16775     case DW_FORM_string:
16776       DW_STRING (attr) = read_direct_string (abfd, info_ptr, &bytes_read);
16777       DW_STRING_IS_CANONICAL (attr) = 0;
16778       info_ptr += bytes_read;
16779       break;
16780     case DW_FORM_strp:
16781       if (!cu->per_cu->is_dwz)
16782         {
16783           DW_STRING (attr) = read_indirect_string (abfd, info_ptr, cu_header,
16784                                                    &bytes_read);
16785           DW_STRING_IS_CANONICAL (attr) = 0;
16786           info_ptr += bytes_read;
16787           break;
16788         }
16789       /* FALLTHROUGH */
16790     case DW_FORM_line_strp:
16791       if (!cu->per_cu->is_dwz)
16792         {
16793           DW_STRING (attr) = read_indirect_line_string (abfd, info_ptr,
16794                                                         cu_header, &bytes_read);
16795           DW_STRING_IS_CANONICAL (attr) = 0;
16796           info_ptr += bytes_read;
16797           break;
16798         }
16799       /* FALLTHROUGH */
16800     case DW_FORM_GNU_strp_alt:
16801       {
16802         struct dwz_file *dwz = dwarf2_get_dwz_file ();
16803         LONGEST str_offset = read_offset (abfd, info_ptr, cu_header,
16804                                           &bytes_read);
16805
16806         DW_STRING (attr) = read_indirect_string_from_dwz (dwz, str_offset);
16807         DW_STRING_IS_CANONICAL (attr) = 0;
16808         info_ptr += bytes_read;
16809       }
16810       break;
16811     case DW_FORM_exprloc:
16812     case DW_FORM_block:
16813       blk = dwarf_alloc_block (cu);
16814       blk->size = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
16815       info_ptr += bytes_read;
16816       blk->data = read_n_bytes (abfd, info_ptr, blk->size);
16817       info_ptr += blk->size;
16818       DW_BLOCK (attr) = blk;
16819       break;
16820     case DW_FORM_block1:
16821       blk = dwarf_alloc_block (cu);
16822       blk->size = read_1_byte (abfd, info_ptr);
16823       info_ptr += 1;
16824       blk->data = read_n_bytes (abfd, info_ptr, blk->size);
16825       info_ptr += blk->size;
16826       DW_BLOCK (attr) = blk;
16827       break;
16828     case DW_FORM_data1:
16829       DW_UNSND (attr) = read_1_byte (abfd, info_ptr);
16830       info_ptr += 1;
16831       break;
16832     case DW_FORM_flag:
16833       DW_UNSND (attr) = read_1_byte (abfd, info_ptr);
16834       info_ptr += 1;
16835       break;
16836     case DW_FORM_flag_present:
16837       DW_UNSND (attr) = 1;
16838       break;
16839     case DW_FORM_sdata:
16840       DW_SND (attr) = read_signed_leb128 (abfd, info_ptr, &bytes_read);
16841       info_ptr += bytes_read;
16842       break;
16843     case DW_FORM_udata:
16844       DW_UNSND (attr) = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
16845       info_ptr += bytes_read;
16846       break;
16847     case DW_FORM_ref1:
16848       DW_UNSND (attr) = (to_underlying (cu->header.sect_off)
16849                          + read_1_byte (abfd, info_ptr));
16850       info_ptr += 1;
16851       break;
16852     case DW_FORM_ref2:
16853       DW_UNSND (attr) = (to_underlying (cu->header.sect_off)
16854                          + read_2_bytes (abfd, info_ptr));
16855       info_ptr += 2;
16856       break;
16857     case DW_FORM_ref4:
16858       DW_UNSND (attr) = (to_underlying (cu->header.sect_off)
16859                          + read_4_bytes (abfd, info_ptr));
16860       info_ptr += 4;
16861       break;
16862     case DW_FORM_ref8:
16863       DW_UNSND (attr) = (to_underlying (cu->header.sect_off)
16864                          + read_8_bytes (abfd, info_ptr));
16865       info_ptr += 8;
16866       break;
16867     case DW_FORM_ref_sig8:
16868       DW_SIGNATURE (attr) = read_8_bytes (abfd, info_ptr);
16869       info_ptr += 8;
16870       break;
16871     case DW_FORM_ref_udata:
16872       DW_UNSND (attr) = (to_underlying (cu->header.sect_off)
16873                          + read_unsigned_leb128 (abfd, info_ptr, &bytes_read));
16874       info_ptr += bytes_read;
16875       break;
16876     case DW_FORM_indirect:
16877       form = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
16878       info_ptr += bytes_read;
16879       if (form == DW_FORM_implicit_const)
16880         {
16881           implicit_const = read_signed_leb128 (abfd, info_ptr, &bytes_read);
16882           info_ptr += bytes_read;
16883         }
16884       info_ptr = read_attribute_value (reader, attr, form, implicit_const,
16885                                        info_ptr);
16886       break;
16887     case DW_FORM_implicit_const:
16888       DW_SND (attr) = implicit_const;
16889       break;
16890     case DW_FORM_GNU_addr_index:
16891       if (reader->dwo_file == NULL)
16892         {
16893           /* For now flag a hard error.
16894              Later we can turn this into a complaint.  */
16895           error (_("Dwarf Error: %s found in non-DWO CU [in module %s]"),
16896                  dwarf_form_name (form),
16897                  bfd_get_filename (abfd));
16898         }
16899       DW_ADDR (attr) = read_addr_index_from_leb128 (cu, info_ptr, &bytes_read);
16900       info_ptr += bytes_read;
16901       break;
16902     case DW_FORM_GNU_str_index:
16903       if (reader->dwo_file == NULL)
16904         {
16905           /* For now flag a hard error.
16906              Later we can turn this into a complaint if warranted.  */
16907           error (_("Dwarf Error: %s found in non-DWO CU [in module %s]"),
16908                  dwarf_form_name (form),
16909                  bfd_get_filename (abfd));
16910         }
16911       {
16912         ULONGEST str_index =
16913           read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
16914
16915         DW_STRING (attr) = read_str_index (reader, str_index);
16916         DW_STRING_IS_CANONICAL (attr) = 0;
16917         info_ptr += bytes_read;
16918       }
16919       break;
16920     default:
16921       error (_("Dwarf Error: Cannot handle %s in DWARF reader [in module %s]"),
16922              dwarf_form_name (form),
16923              bfd_get_filename (abfd));
16924     }
16925
16926   /* Super hack.  */
16927   if (cu->per_cu->is_dwz && attr_form_is_ref (attr))
16928     attr->form = DW_FORM_GNU_ref_alt;
16929
16930   /* We have seen instances where the compiler tried to emit a byte
16931      size attribute of -1 which ended up being encoded as an unsigned
16932      0xffffffff.  Although 0xffffffff is technically a valid size value,
16933      an object of this size seems pretty unlikely so we can relatively
16934      safely treat these cases as if the size attribute was invalid and
16935      treat them as zero by default.  */
16936   if (attr->name == DW_AT_byte_size
16937       && form == DW_FORM_data4
16938       && DW_UNSND (attr) >= 0xffffffff)
16939     {
16940       complaint
16941         (&symfile_complaints,
16942          _("Suspicious DW_AT_byte_size value treated as zero instead of %s"),
16943          hex_string (DW_UNSND (attr)));
16944       DW_UNSND (attr) = 0;
16945     }
16946
16947   return info_ptr;
16948 }
16949
16950 /* Read an attribute described by an abbreviated attribute.  */
16951
16952 static const gdb_byte *
16953 read_attribute (const struct die_reader_specs *reader,
16954                 struct attribute *attr, struct attr_abbrev *abbrev,
16955                 const gdb_byte *info_ptr)
16956 {
16957   attr->name = abbrev->name;
16958   return read_attribute_value (reader, attr, abbrev->form,
16959                                abbrev->implicit_const, info_ptr);
16960 }
16961
16962 /* Read dwarf information from a buffer.  */
16963
16964 static unsigned int
16965 read_1_byte (bfd *abfd, const gdb_byte *buf)
16966 {
16967   return bfd_get_8 (abfd, buf);
16968 }
16969
16970 static int
16971 read_1_signed_byte (bfd *abfd, const gdb_byte *buf)
16972 {
16973   return bfd_get_signed_8 (abfd, buf);
16974 }
16975
16976 static unsigned int
16977 read_2_bytes (bfd *abfd, const gdb_byte *buf)
16978 {
16979   return bfd_get_16 (abfd, buf);
16980 }
16981
16982 static int
16983 read_2_signed_bytes (bfd *abfd, const gdb_byte *buf)
16984 {
16985   return bfd_get_signed_16 (abfd, buf);
16986 }
16987
16988 static unsigned int
16989 read_4_bytes (bfd *abfd, const gdb_byte *buf)
16990 {
16991   return bfd_get_32 (abfd, buf);
16992 }
16993
16994 static int
16995 read_4_signed_bytes (bfd *abfd, const gdb_byte *buf)
16996 {
16997   return bfd_get_signed_32 (abfd, buf);
16998 }
16999
17000 static ULONGEST
17001 read_8_bytes (bfd *abfd, const gdb_byte *buf)
17002 {
17003   return bfd_get_64 (abfd, buf);
17004 }
17005
17006 static CORE_ADDR
17007 read_address (bfd *abfd, const gdb_byte *buf, struct dwarf2_cu *cu,
17008               unsigned int *bytes_read)
17009 {
17010   struct comp_unit_head *cu_header = &cu->header;
17011   CORE_ADDR retval = 0;
17012
17013   if (cu_header->signed_addr_p)
17014     {
17015       switch (cu_header->addr_size)
17016         {
17017         case 2:
17018           retval = bfd_get_signed_16 (abfd, buf);
17019           break;
17020         case 4:
17021           retval = bfd_get_signed_32 (abfd, buf);
17022           break;
17023         case 8:
17024           retval = bfd_get_signed_64 (abfd, buf);
17025           break;
17026         default:
17027           internal_error (__FILE__, __LINE__,
17028                           _("read_address: bad switch, signed [in module %s]"),
17029                           bfd_get_filename (abfd));
17030         }
17031     }
17032   else
17033     {
17034       switch (cu_header->addr_size)
17035         {
17036         case 2:
17037           retval = bfd_get_16 (abfd, buf);
17038           break;
17039         case 4:
17040           retval = bfd_get_32 (abfd, buf);
17041           break;
17042         case 8:
17043           retval = bfd_get_64 (abfd, buf);
17044           break;
17045         default:
17046           internal_error (__FILE__, __LINE__,
17047                           _("read_address: bad switch, "
17048                             "unsigned [in module %s]"),
17049                           bfd_get_filename (abfd));
17050         }
17051     }
17052
17053   *bytes_read = cu_header->addr_size;
17054   return retval;
17055 }
17056
17057 /* Read the initial length from a section.  The (draft) DWARF 3
17058    specification allows the initial length to take up either 4 bytes
17059    or 12 bytes.  If the first 4 bytes are 0xffffffff, then the next 8
17060    bytes describe the length and all offsets will be 8 bytes in length
17061    instead of 4.
17062
17063    An older, non-standard 64-bit format is also handled by this
17064    function.  The older format in question stores the initial length
17065    as an 8-byte quantity without an escape value.  Lengths greater
17066    than 2^32 aren't very common which means that the initial 4 bytes
17067    is almost always zero.  Since a length value of zero doesn't make
17068    sense for the 32-bit format, this initial zero can be considered to
17069    be an escape value which indicates the presence of the older 64-bit
17070    format.  As written, the code can't detect (old format) lengths
17071    greater than 4GB.  If it becomes necessary to handle lengths
17072    somewhat larger than 4GB, we could allow other small values (such
17073    as the non-sensical values of 1, 2, and 3) to also be used as
17074    escape values indicating the presence of the old format.
17075
17076    The value returned via bytes_read should be used to increment the
17077    relevant pointer after calling read_initial_length().
17078
17079    [ Note:  read_initial_length() and read_offset() are based on the
17080      document entitled "DWARF Debugging Information Format", revision
17081      3, draft 8, dated November 19, 2001.  This document was obtained
17082      from:
17083
17084         http://reality.sgiweb.org/davea/dwarf3-draft8-011125.pdf
17085
17086      This document is only a draft and is subject to change.  (So beware.)
17087
17088      Details regarding the older, non-standard 64-bit format were
17089      determined empirically by examining 64-bit ELF files produced by
17090      the SGI toolchain on an IRIX 6.5 machine.
17091
17092      - Kevin, July 16, 2002
17093    ] */
17094
17095 static LONGEST
17096 read_initial_length (bfd *abfd, const gdb_byte *buf, unsigned int *bytes_read)
17097 {
17098   LONGEST length = bfd_get_32 (abfd, buf);
17099
17100   if (length == 0xffffffff)
17101     {
17102       length = bfd_get_64 (abfd, buf + 4);
17103       *bytes_read = 12;
17104     }
17105   else if (length == 0)
17106     {
17107       /* Handle the (non-standard) 64-bit DWARF2 format used by IRIX.  */
17108       length = bfd_get_64 (abfd, buf);
17109       *bytes_read = 8;
17110     }
17111   else
17112     {
17113       *bytes_read = 4;
17114     }
17115
17116   return length;
17117 }
17118
17119 /* Cover function for read_initial_length.
17120    Returns the length of the object at BUF, and stores the size of the
17121    initial length in *BYTES_READ and stores the size that offsets will be in
17122    *OFFSET_SIZE.
17123    If the initial length size is not equivalent to that specified in
17124    CU_HEADER then issue a complaint.
17125    This is useful when reading non-comp-unit headers.  */
17126
17127 static LONGEST
17128 read_checked_initial_length_and_offset (bfd *abfd, const gdb_byte *buf,
17129                                         const struct comp_unit_head *cu_header,
17130                                         unsigned int *bytes_read,
17131                                         unsigned int *offset_size)
17132 {
17133   LONGEST length = read_initial_length (abfd, buf, bytes_read);
17134
17135   gdb_assert (cu_header->initial_length_size == 4
17136               || cu_header->initial_length_size == 8
17137               || cu_header->initial_length_size == 12);
17138
17139   if (cu_header->initial_length_size != *bytes_read)
17140     complaint (&symfile_complaints,
17141                _("intermixed 32-bit and 64-bit DWARF sections"));
17142
17143   *offset_size = (*bytes_read == 4) ? 4 : 8;
17144   return length;
17145 }
17146
17147 /* Read an offset from the data stream.  The size of the offset is
17148    given by cu_header->offset_size.  */
17149
17150 static LONGEST
17151 read_offset (bfd *abfd, const gdb_byte *buf,
17152              const struct comp_unit_head *cu_header,
17153              unsigned int *bytes_read)
17154 {
17155   LONGEST offset = read_offset_1 (abfd, buf, cu_header->offset_size);
17156
17157   *bytes_read = cu_header->offset_size;
17158   return offset;
17159 }
17160
17161 /* Read an offset from the data stream.  */
17162
17163 static LONGEST
17164 read_offset_1 (bfd *abfd, const gdb_byte *buf, unsigned int offset_size)
17165 {
17166   LONGEST retval = 0;
17167
17168   switch (offset_size)
17169     {
17170     case 4:
17171       retval = bfd_get_32 (abfd, buf);
17172       break;
17173     case 8:
17174       retval = bfd_get_64 (abfd, buf);
17175       break;
17176     default:
17177       internal_error (__FILE__, __LINE__,
17178                       _("read_offset_1: bad switch [in module %s]"),
17179                       bfd_get_filename (abfd));
17180     }
17181
17182   return retval;
17183 }
17184
17185 static const gdb_byte *
17186 read_n_bytes (bfd *abfd, const gdb_byte *buf, unsigned int size)
17187 {
17188   /* If the size of a host char is 8 bits, we can return a pointer
17189      to the buffer, otherwise we have to copy the data to a buffer
17190      allocated on the temporary obstack.  */
17191   gdb_assert (HOST_CHAR_BIT == 8);
17192   return buf;
17193 }
17194
17195 static const char *
17196 read_direct_string (bfd *abfd, const gdb_byte *buf,
17197                     unsigned int *bytes_read_ptr)
17198 {
17199   /* If the size of a host char is 8 bits, we can return a pointer
17200      to the string, otherwise we have to copy the string to a buffer
17201      allocated on the temporary obstack.  */
17202   gdb_assert (HOST_CHAR_BIT == 8);
17203   if (*buf == '\0')
17204     {
17205       *bytes_read_ptr = 1;
17206       return NULL;
17207     }
17208   *bytes_read_ptr = strlen ((const char *) buf) + 1;
17209   return (const char *) buf;
17210 }
17211
17212 /* Return pointer to string at section SECT offset STR_OFFSET with error
17213    reporting strings FORM_NAME and SECT_NAME.  */
17214
17215 static const char *
17216 read_indirect_string_at_offset_from (bfd *abfd, LONGEST str_offset,
17217                                      struct dwarf2_section_info *sect,
17218                                      const char *form_name,
17219                                      const char *sect_name)
17220 {
17221   dwarf2_read_section (dwarf2_per_objfile->objfile, sect);
17222   if (sect->buffer == NULL)
17223     error (_("%s used without %s section [in module %s]"),
17224            form_name, sect_name, bfd_get_filename (abfd));
17225   if (str_offset >= sect->size)
17226     error (_("%s pointing outside of %s section [in module %s]"),
17227            form_name, sect_name, bfd_get_filename (abfd));
17228   gdb_assert (HOST_CHAR_BIT == 8);
17229   if (sect->buffer[str_offset] == '\0')
17230     return NULL;
17231   return (const char *) (sect->buffer + str_offset);
17232 }
17233
17234 /* Return pointer to string at .debug_str offset STR_OFFSET.  */
17235
17236 static const char *
17237 read_indirect_string_at_offset (bfd *abfd, LONGEST str_offset)
17238 {
17239   return read_indirect_string_at_offset_from (abfd, str_offset,
17240                                               &dwarf2_per_objfile->str,
17241                                               "DW_FORM_strp", ".debug_str");
17242 }
17243
17244 /* Return pointer to string at .debug_line_str offset STR_OFFSET.  */
17245
17246 static const char *
17247 read_indirect_line_string_at_offset (bfd *abfd, LONGEST str_offset)
17248 {
17249   return read_indirect_string_at_offset_from (abfd, str_offset,
17250                                               &dwarf2_per_objfile->line_str,
17251                                               "DW_FORM_line_strp",
17252                                               ".debug_line_str");
17253 }
17254
17255 /* Read a string at offset STR_OFFSET in the .debug_str section from
17256    the .dwz file DWZ.  Throw an error if the offset is too large.  If
17257    the string consists of a single NUL byte, return NULL; otherwise
17258    return a pointer to the string.  */
17259
17260 static const char *
17261 read_indirect_string_from_dwz (struct dwz_file *dwz, LONGEST str_offset)
17262 {
17263   dwarf2_read_section (dwarf2_per_objfile->objfile, &dwz->str);
17264
17265   if (dwz->str.buffer == NULL)
17266     error (_("DW_FORM_GNU_strp_alt used without .debug_str "
17267              "section [in module %s]"),
17268            bfd_get_filename (dwz->dwz_bfd));
17269   if (str_offset >= dwz->str.size)
17270     error (_("DW_FORM_GNU_strp_alt pointing outside of "
17271              ".debug_str section [in module %s]"),
17272            bfd_get_filename (dwz->dwz_bfd));
17273   gdb_assert (HOST_CHAR_BIT == 8);
17274   if (dwz->str.buffer[str_offset] == '\0')
17275     return NULL;
17276   return (const char *) (dwz->str.buffer + str_offset);
17277 }
17278
17279 /* Return pointer to string at .debug_str offset as read from BUF.
17280    BUF is assumed to be in a compilation unit described by CU_HEADER.
17281    Return *BYTES_READ_PTR count of bytes read from BUF.  */
17282
17283 static const char *
17284 read_indirect_string (bfd *abfd, const gdb_byte *buf,
17285                       const struct comp_unit_head *cu_header,
17286                       unsigned int *bytes_read_ptr)
17287 {
17288   LONGEST str_offset = read_offset (abfd, buf, cu_header, bytes_read_ptr);
17289
17290   return read_indirect_string_at_offset (abfd, str_offset);
17291 }
17292
17293 /* Return pointer to string at .debug_line_str offset as read from BUF.
17294    BUF is assumed to be in a compilation unit described by CU_HEADER.
17295    Return *BYTES_READ_PTR count of bytes read from BUF.  */
17296
17297 static const char *
17298 read_indirect_line_string (bfd *abfd, const gdb_byte *buf,
17299                            const struct comp_unit_head *cu_header,
17300                            unsigned int *bytes_read_ptr)
17301 {
17302   LONGEST str_offset = read_offset (abfd, buf, cu_header, bytes_read_ptr);
17303
17304   return read_indirect_line_string_at_offset (abfd, str_offset);
17305 }
17306
17307 ULONGEST
17308 read_unsigned_leb128 (bfd *abfd, const gdb_byte *buf,
17309                           unsigned int *bytes_read_ptr)
17310 {
17311   ULONGEST result;
17312   unsigned int num_read;
17313   int shift;
17314   unsigned char byte;
17315
17316   result = 0;
17317   shift = 0;
17318   num_read = 0;
17319   while (1)
17320     {
17321       byte = bfd_get_8 (abfd, buf);
17322       buf++;
17323       num_read++;
17324       result |= ((ULONGEST) (byte & 127) << shift);
17325       if ((byte & 128) == 0)
17326         {
17327           break;
17328         }
17329       shift += 7;
17330     }
17331   *bytes_read_ptr = num_read;
17332   return result;
17333 }
17334
17335 static LONGEST
17336 read_signed_leb128 (bfd *abfd, const gdb_byte *buf,
17337                     unsigned int *bytes_read_ptr)
17338 {
17339   LONGEST result;
17340   int shift, num_read;
17341   unsigned char byte;
17342
17343   result = 0;
17344   shift = 0;
17345   num_read = 0;
17346   while (1)
17347     {
17348       byte = bfd_get_8 (abfd, buf);
17349       buf++;
17350       num_read++;
17351       result |= ((LONGEST) (byte & 127) << shift);
17352       shift += 7;
17353       if ((byte & 128) == 0)
17354         {
17355           break;
17356         }
17357     }
17358   if ((shift < 8 * sizeof (result)) && (byte & 0x40))
17359     result |= -(((LONGEST) 1) << shift);
17360   *bytes_read_ptr = num_read;
17361   return result;
17362 }
17363
17364 /* Given index ADDR_INDEX in .debug_addr, fetch the value.
17365    ADDR_BASE is the DW_AT_GNU_addr_base attribute or zero.
17366    ADDR_SIZE is the size of addresses from the CU header.  */
17367
17368 static CORE_ADDR
17369 read_addr_index_1 (unsigned int addr_index, ULONGEST addr_base, int addr_size)
17370 {
17371   struct objfile *objfile = dwarf2_per_objfile->objfile;
17372   bfd *abfd = objfile->obfd;
17373   const gdb_byte *info_ptr;
17374
17375   dwarf2_read_section (objfile, &dwarf2_per_objfile->addr);
17376   if (dwarf2_per_objfile->addr.buffer == NULL)
17377     error (_("DW_FORM_addr_index used without .debug_addr section [in module %s]"),
17378            objfile_name (objfile));
17379   if (addr_base + addr_index * addr_size >= dwarf2_per_objfile->addr.size)
17380     error (_("DW_FORM_addr_index pointing outside of "
17381              ".debug_addr section [in module %s]"),
17382            objfile_name (objfile));
17383   info_ptr = (dwarf2_per_objfile->addr.buffer
17384               + addr_base + addr_index * addr_size);
17385   if (addr_size == 4)
17386     return bfd_get_32 (abfd, info_ptr);
17387   else
17388     return bfd_get_64 (abfd, info_ptr);
17389 }
17390
17391 /* Given index ADDR_INDEX in .debug_addr, fetch the value.  */
17392
17393 static CORE_ADDR
17394 read_addr_index (struct dwarf2_cu *cu, unsigned int addr_index)
17395 {
17396   return read_addr_index_1 (addr_index, cu->addr_base, cu->header.addr_size);
17397 }
17398
17399 /* Given a pointer to an leb128 value, fetch the value from .debug_addr.  */
17400
17401 static CORE_ADDR
17402 read_addr_index_from_leb128 (struct dwarf2_cu *cu, const gdb_byte *info_ptr,
17403                              unsigned int *bytes_read)
17404 {
17405   bfd *abfd = cu->objfile->obfd;
17406   unsigned int addr_index = read_unsigned_leb128 (abfd, info_ptr, bytes_read);
17407
17408   return read_addr_index (cu, addr_index);
17409 }
17410
17411 /* Data structure to pass results from dwarf2_read_addr_index_reader
17412    back to dwarf2_read_addr_index.  */
17413
17414 struct dwarf2_read_addr_index_data
17415 {
17416   ULONGEST addr_base;
17417   int addr_size;
17418 };
17419
17420 /* die_reader_func for dwarf2_read_addr_index.  */
17421
17422 static void
17423 dwarf2_read_addr_index_reader (const struct die_reader_specs *reader,
17424                                const gdb_byte *info_ptr,
17425                                struct die_info *comp_unit_die,
17426                                int has_children,
17427                                void *data)
17428 {
17429   struct dwarf2_cu *cu = reader->cu;
17430   struct dwarf2_read_addr_index_data *aidata =
17431     (struct dwarf2_read_addr_index_data *) data;
17432
17433   aidata->addr_base = cu->addr_base;
17434   aidata->addr_size = cu->header.addr_size;
17435 }
17436
17437 /* Given an index in .debug_addr, fetch the value.
17438    NOTE: This can be called during dwarf expression evaluation,
17439    long after the debug information has been read, and thus per_cu->cu
17440    may no longer exist.  */
17441
17442 CORE_ADDR
17443 dwarf2_read_addr_index (struct dwarf2_per_cu_data *per_cu,
17444                         unsigned int addr_index)
17445 {
17446   struct objfile *objfile = per_cu->objfile;
17447   struct dwarf2_cu *cu = per_cu->cu;
17448   ULONGEST addr_base;
17449   int addr_size;
17450
17451   /* This is intended to be called from outside this file.  */
17452   dw2_setup (objfile);
17453
17454   /* We need addr_base and addr_size.
17455      If we don't have PER_CU->cu, we have to get it.
17456      Nasty, but the alternative is storing the needed info in PER_CU,
17457      which at this point doesn't seem justified: it's not clear how frequently
17458      it would get used and it would increase the size of every PER_CU.
17459      Entry points like dwarf2_per_cu_addr_size do a similar thing
17460      so we're not in uncharted territory here.
17461      Alas we need to be a bit more complicated as addr_base is contained
17462      in the DIE.
17463
17464      We don't need to read the entire CU(/TU).
17465      We just need the header and top level die.
17466
17467      IWBN to use the aging mechanism to let us lazily later discard the CU.
17468      For now we skip this optimization.  */
17469
17470   if (cu != NULL)
17471     {
17472       addr_base = cu->addr_base;
17473       addr_size = cu->header.addr_size;
17474     }
17475   else
17476     {
17477       struct dwarf2_read_addr_index_data aidata;
17478
17479       /* Note: We can't use init_cutu_and_read_dies_simple here,
17480          we need addr_base.  */
17481       init_cutu_and_read_dies (per_cu, NULL, 0, 0,
17482                                dwarf2_read_addr_index_reader, &aidata);
17483       addr_base = aidata.addr_base;
17484       addr_size = aidata.addr_size;
17485     }
17486
17487   return read_addr_index_1 (addr_index, addr_base, addr_size);
17488 }
17489
17490 /* Given a DW_FORM_GNU_str_index, fetch the string.
17491    This is only used by the Fission support.  */
17492
17493 static const char *
17494 read_str_index (const struct die_reader_specs *reader, ULONGEST str_index)
17495 {
17496   struct objfile *objfile = dwarf2_per_objfile->objfile;
17497   const char *objf_name = objfile_name (objfile);
17498   bfd *abfd = objfile->obfd;
17499   struct dwarf2_cu *cu = reader->cu;
17500   struct dwarf2_section_info *str_section = &reader->dwo_file->sections.str;
17501   struct dwarf2_section_info *str_offsets_section =
17502     &reader->dwo_file->sections.str_offsets;
17503   const gdb_byte *info_ptr;
17504   ULONGEST str_offset;
17505   static const char form_name[] = "DW_FORM_GNU_str_index";
17506
17507   dwarf2_read_section (objfile, str_section);
17508   dwarf2_read_section (objfile, str_offsets_section);
17509   if (str_section->buffer == NULL)
17510     error (_("%s used without .debug_str.dwo section"
17511              " in CU at offset 0x%x [in module %s]"),
17512            form_name, to_underlying (cu->header.sect_off), objf_name);
17513   if (str_offsets_section->buffer == NULL)
17514     error (_("%s used without .debug_str_offsets.dwo section"
17515              " in CU at offset 0x%x [in module %s]"),
17516            form_name, to_underlying (cu->header.sect_off), objf_name);
17517   if (str_index * cu->header.offset_size >= str_offsets_section->size)
17518     error (_("%s pointing outside of .debug_str_offsets.dwo"
17519              " section in CU at offset 0x%x [in module %s]"),
17520            form_name, to_underlying (cu->header.sect_off), objf_name);
17521   info_ptr = (str_offsets_section->buffer
17522               + str_index * cu->header.offset_size);
17523   if (cu->header.offset_size == 4)
17524     str_offset = bfd_get_32 (abfd, info_ptr);
17525   else
17526     str_offset = bfd_get_64 (abfd, info_ptr);
17527   if (str_offset >= str_section->size)
17528     error (_("Offset from %s pointing outside of"
17529              " .debug_str.dwo section in CU at offset 0x%x [in module %s]"),
17530            form_name, to_underlying (cu->header.sect_off), objf_name);
17531   return (const char *) (str_section->buffer + str_offset);
17532 }
17533
17534 /* Return the length of an LEB128 number in BUF.  */
17535
17536 static int
17537 leb128_size (const gdb_byte *buf)
17538 {
17539   const gdb_byte *begin = buf;
17540   gdb_byte byte;
17541
17542   while (1)
17543     {
17544       byte = *buf++;
17545       if ((byte & 128) == 0)
17546         return buf - begin;
17547     }
17548 }
17549
17550 static void
17551 set_cu_language (unsigned int lang, struct dwarf2_cu *cu)
17552 {
17553   switch (lang)
17554     {
17555     case DW_LANG_C89:
17556     case DW_LANG_C99:
17557     case DW_LANG_C11:
17558     case DW_LANG_C:
17559     case DW_LANG_UPC:
17560       cu->language = language_c;
17561       break;
17562     case DW_LANG_Java:
17563     case DW_LANG_C_plus_plus:
17564     case DW_LANG_C_plus_plus_11:
17565     case DW_LANG_C_plus_plus_14:
17566       cu->language = language_cplus;
17567       break;
17568     case DW_LANG_D:
17569       cu->language = language_d;
17570       break;
17571     case DW_LANG_Fortran77:
17572     case DW_LANG_Fortran90:
17573     case DW_LANG_Fortran95:
17574     case DW_LANG_Fortran03:
17575     case DW_LANG_Fortran08:
17576       cu->language = language_fortran;
17577       break;
17578     case DW_LANG_Go:
17579       cu->language = language_go;
17580       break;
17581     case DW_LANG_Mips_Assembler:
17582       cu->language = language_asm;
17583       break;
17584     case DW_LANG_Ada83:
17585     case DW_LANG_Ada95:
17586       cu->language = language_ada;
17587       break;
17588     case DW_LANG_Modula2:
17589       cu->language = language_m2;
17590       break;
17591     case DW_LANG_Pascal83:
17592       cu->language = language_pascal;
17593       break;
17594     case DW_LANG_ObjC:
17595       cu->language = language_objc;
17596       break;
17597     case DW_LANG_Rust:
17598     case DW_LANG_Rust_old:
17599       cu->language = language_rust;
17600       break;
17601     case DW_LANG_Cobol74:
17602     case DW_LANG_Cobol85:
17603     default:
17604       cu->language = language_minimal;
17605       break;
17606     }
17607   cu->language_defn = language_def (cu->language);
17608 }
17609
17610 /* Return the named attribute or NULL if not there.  */
17611
17612 static struct attribute *
17613 dwarf2_attr (struct die_info *die, unsigned int name, struct dwarf2_cu *cu)
17614 {
17615   for (;;)
17616     {
17617       unsigned int i;
17618       struct attribute *spec = NULL;
17619
17620       for (i = 0; i < die->num_attrs; ++i)
17621         {
17622           if (die->attrs[i].name == name)
17623             return &die->attrs[i];
17624           if (die->attrs[i].name == DW_AT_specification
17625               || die->attrs[i].name == DW_AT_abstract_origin)
17626             spec = &die->attrs[i];
17627         }
17628
17629       if (!spec)
17630         break;
17631
17632       die = follow_die_ref (die, spec, &cu);
17633     }
17634
17635   return NULL;
17636 }
17637
17638 /* Return the named attribute or NULL if not there,
17639    but do not follow DW_AT_specification, etc.
17640    This is for use in contexts where we're reading .debug_types dies.
17641    Following DW_AT_specification, DW_AT_abstract_origin will take us
17642    back up the chain, and we want to go down.  */
17643
17644 static struct attribute *
17645 dwarf2_attr_no_follow (struct die_info *die, unsigned int name)
17646 {
17647   unsigned int i;
17648
17649   for (i = 0; i < die->num_attrs; ++i)
17650     if (die->attrs[i].name == name)
17651       return &die->attrs[i];
17652
17653   return NULL;
17654 }
17655
17656 /* Return the string associated with a string-typed attribute, or NULL if it
17657    is either not found or is of an incorrect type.  */
17658
17659 static const char *
17660 dwarf2_string_attr (struct die_info *die, unsigned int name, struct dwarf2_cu *cu)
17661 {
17662   struct attribute *attr;
17663   const char *str = NULL;
17664
17665   attr = dwarf2_attr (die, name, cu);
17666
17667   if (attr != NULL)
17668     {
17669       if (attr->form == DW_FORM_strp || attr->form == DW_FORM_line_strp
17670           || attr->form == DW_FORM_string
17671           || attr->form == DW_FORM_GNU_str_index
17672           || attr->form == DW_FORM_GNU_strp_alt)
17673         str = DW_STRING (attr);
17674       else
17675         complaint (&symfile_complaints,
17676                    _("string type expected for attribute %s for "
17677                      "DIE at 0x%x in module %s"),
17678                    dwarf_attr_name (name), to_underlying (die->sect_off),
17679                    objfile_name (cu->objfile));
17680     }
17681
17682   return str;
17683 }
17684
17685 /* Return non-zero iff the attribute NAME is defined for the given DIE,
17686    and holds a non-zero value.  This function should only be used for
17687    DW_FORM_flag or DW_FORM_flag_present attributes.  */
17688
17689 static int
17690 dwarf2_flag_true_p (struct die_info *die, unsigned name, struct dwarf2_cu *cu)
17691 {
17692   struct attribute *attr = dwarf2_attr (die, name, cu);
17693
17694   return (attr && DW_UNSND (attr));
17695 }
17696
17697 static int
17698 die_is_declaration (struct die_info *die, struct dwarf2_cu *cu)
17699 {
17700   /* A DIE is a declaration if it has a DW_AT_declaration attribute
17701      which value is non-zero.  However, we have to be careful with
17702      DIEs having a DW_AT_specification attribute, because dwarf2_attr()
17703      (via dwarf2_flag_true_p) follows this attribute.  So we may
17704      end up accidently finding a declaration attribute that belongs
17705      to a different DIE referenced by the specification attribute,
17706      even though the given DIE does not have a declaration attribute.  */
17707   return (dwarf2_flag_true_p (die, DW_AT_declaration, cu)
17708           && dwarf2_attr (die, DW_AT_specification, cu) == NULL);
17709 }
17710
17711 /* Return the die giving the specification for DIE, if there is
17712    one.  *SPEC_CU is the CU containing DIE on input, and the CU
17713    containing the return value on output.  If there is no
17714    specification, but there is an abstract origin, that is
17715    returned.  */
17716
17717 static struct die_info *
17718 die_specification (struct die_info *die, struct dwarf2_cu **spec_cu)
17719 {
17720   struct attribute *spec_attr = dwarf2_attr (die, DW_AT_specification,
17721                                              *spec_cu);
17722
17723   if (spec_attr == NULL)
17724     spec_attr = dwarf2_attr (die, DW_AT_abstract_origin, *spec_cu);
17725
17726   if (spec_attr == NULL)
17727     return NULL;
17728   else
17729     return follow_die_ref (die, spec_attr, spec_cu);
17730 }
17731
17732 /* Stub for free_line_header to match void * callback types.  */
17733
17734 static void
17735 free_line_header_voidp (void *arg)
17736 {
17737   struct line_header *lh = (struct line_header *) arg;
17738
17739   delete lh;
17740 }
17741
17742 void
17743 line_header::add_include_dir (const char *include_dir)
17744 {
17745   if (dwarf_line_debug >= 2)
17746     fprintf_unfiltered (gdb_stdlog, "Adding dir %zu: %s\n",
17747                         include_dirs.size () + 1, include_dir);
17748
17749   include_dirs.push_back (include_dir);
17750 }
17751
17752 void
17753 line_header::add_file_name (const char *name,
17754                             dir_index d_index,
17755                             unsigned int mod_time,
17756                             unsigned int length)
17757 {
17758   if (dwarf_line_debug >= 2)
17759     fprintf_unfiltered (gdb_stdlog, "Adding file %u: %s\n",
17760                         (unsigned) file_names.size () + 1, name);
17761
17762   file_names.emplace_back (name, d_index, mod_time, length);
17763 }
17764
17765 /* A convenience function to find the proper .debug_line section for a CU.  */
17766
17767 static struct dwarf2_section_info *
17768 get_debug_line_section (struct dwarf2_cu *cu)
17769 {
17770   struct dwarf2_section_info *section;
17771
17772   /* For TUs in DWO files, the DW_AT_stmt_list attribute lives in the
17773      DWO file.  */
17774   if (cu->dwo_unit && cu->per_cu->is_debug_types)
17775     section = &cu->dwo_unit->dwo_file->sections.line;
17776   else if (cu->per_cu->is_dwz)
17777     {
17778       struct dwz_file *dwz = dwarf2_get_dwz_file ();
17779
17780       section = &dwz->line;
17781     }
17782   else
17783     section = &dwarf2_per_objfile->line;
17784
17785   return section;
17786 }
17787
17788 /* Read directory or file name entry format, starting with byte of
17789    format count entries, ULEB128 pairs of entry formats, ULEB128 of
17790    entries count and the entries themselves in the described entry
17791    format.  */
17792
17793 static void
17794 read_formatted_entries (bfd *abfd, const gdb_byte **bufp,
17795                         struct line_header *lh,
17796                         const struct comp_unit_head *cu_header,
17797                         void (*callback) (struct line_header *lh,
17798                                           const char *name,
17799                                           dir_index d_index,
17800                                           unsigned int mod_time,
17801                                           unsigned int length))
17802 {
17803   gdb_byte format_count, formati;
17804   ULONGEST data_count, datai;
17805   const gdb_byte *buf = *bufp;
17806   const gdb_byte *format_header_data;
17807   int i;
17808   unsigned int bytes_read;
17809
17810   format_count = read_1_byte (abfd, buf);
17811   buf += 1;
17812   format_header_data = buf;
17813   for (formati = 0; formati < format_count; formati++)
17814     {
17815       read_unsigned_leb128 (abfd, buf, &bytes_read);
17816       buf += bytes_read;
17817       read_unsigned_leb128 (abfd, buf, &bytes_read);
17818       buf += bytes_read;
17819     }
17820
17821   data_count = read_unsigned_leb128 (abfd, buf, &bytes_read);
17822   buf += bytes_read;
17823   for (datai = 0; datai < data_count; datai++)
17824     {
17825       const gdb_byte *format = format_header_data;
17826       struct file_entry fe;
17827
17828       for (formati = 0; formati < format_count; formati++)
17829         {
17830           ULONGEST content_type = read_unsigned_leb128 (abfd, format, &bytes_read);
17831           format += bytes_read;
17832
17833           ULONGEST form  = read_unsigned_leb128 (abfd, format, &bytes_read);
17834           format += bytes_read;
17835
17836           gdb::optional<const char *> string;
17837           gdb::optional<unsigned int> uint;
17838
17839           switch (form)
17840             {
17841             case DW_FORM_string:
17842               string.emplace (read_direct_string (abfd, buf, &bytes_read));
17843               buf += bytes_read;
17844               break;
17845
17846             case DW_FORM_line_strp:
17847               string.emplace (read_indirect_line_string (abfd, buf,
17848                                                          cu_header,
17849                                                          &bytes_read));
17850               buf += bytes_read;
17851               break;
17852
17853             case DW_FORM_data1:
17854               uint.emplace (read_1_byte (abfd, buf));
17855               buf += 1;
17856               break;
17857
17858             case DW_FORM_data2:
17859               uint.emplace (read_2_bytes (abfd, buf));
17860               buf += 2;
17861               break;
17862
17863             case DW_FORM_data4:
17864               uint.emplace (read_4_bytes (abfd, buf));
17865               buf += 4;
17866               break;
17867
17868             case DW_FORM_data8:
17869               uint.emplace (read_8_bytes (abfd, buf));
17870               buf += 8;
17871               break;
17872
17873             case DW_FORM_udata:
17874               uint.emplace (read_unsigned_leb128 (abfd, buf, &bytes_read));
17875               buf += bytes_read;
17876               break;
17877
17878             case DW_FORM_block:
17879               /* It is valid only for DW_LNCT_timestamp which is ignored by
17880                  current GDB.  */
17881               break;
17882             }
17883
17884           switch (content_type)
17885             {
17886             case DW_LNCT_path:
17887               if (string.has_value ())
17888                 fe.name = *string;
17889               break;
17890             case DW_LNCT_directory_index:
17891               if (uint.has_value ())
17892                 fe.d_index = (dir_index) *uint;
17893               break;
17894             case DW_LNCT_timestamp:
17895               if (uint.has_value ())
17896                 fe.mod_time = *uint;
17897               break;
17898             case DW_LNCT_size:
17899               if (uint.has_value ())
17900                 fe.length = *uint;
17901               break;
17902             case DW_LNCT_MD5:
17903               break;
17904             default:
17905               complaint (&symfile_complaints,
17906                          _("Unknown format content type %s"),
17907                          pulongest (content_type));
17908             }
17909         }
17910
17911       callback (lh, fe.name, fe.d_index, fe.mod_time, fe.length);
17912     }
17913
17914   *bufp = buf;
17915 }
17916
17917 /* Read the statement program header starting at OFFSET in
17918    .debug_line, or .debug_line.dwo.  Return a pointer
17919    to a struct line_header, allocated using xmalloc.
17920    Returns NULL if there is a problem reading the header, e.g., if it
17921    has a version we don't understand.
17922
17923    NOTE: the strings in the include directory and file name tables of
17924    the returned object point into the dwarf line section buffer,
17925    and must not be freed.  */
17926
17927 static line_header_up
17928 dwarf_decode_line_header (sect_offset sect_off, struct dwarf2_cu *cu)
17929 {
17930   const gdb_byte *line_ptr;
17931   unsigned int bytes_read, offset_size;
17932   int i;
17933   const char *cur_dir, *cur_file;
17934   struct dwarf2_section_info *section;
17935   bfd *abfd;
17936
17937   section = get_debug_line_section (cu);
17938   dwarf2_read_section (dwarf2_per_objfile->objfile, section);
17939   if (section->buffer == NULL)
17940     {
17941       if (cu->dwo_unit && cu->per_cu->is_debug_types)
17942         complaint (&symfile_complaints, _("missing .debug_line.dwo section"));
17943       else
17944         complaint (&symfile_complaints, _("missing .debug_line section"));
17945       return 0;
17946     }
17947
17948   /* We can't do this until we know the section is non-empty.
17949      Only then do we know we have such a section.  */
17950   abfd = get_section_bfd_owner (section);
17951
17952   /* Make sure that at least there's room for the total_length field.
17953      That could be 12 bytes long, but we're just going to fudge that.  */
17954   if (to_underlying (sect_off) + 4 >= section->size)
17955     {
17956       dwarf2_statement_list_fits_in_line_number_section_complaint ();
17957       return 0;
17958     }
17959
17960   line_header_up lh (new line_header ());
17961
17962   lh->sect_off = sect_off;
17963   lh->offset_in_dwz = cu->per_cu->is_dwz;
17964
17965   line_ptr = section->buffer + to_underlying (sect_off);
17966
17967   /* Read in the header.  */
17968   lh->total_length =
17969     read_checked_initial_length_and_offset (abfd, line_ptr, &cu->header,
17970                                             &bytes_read, &offset_size);
17971   line_ptr += bytes_read;
17972   if (line_ptr + lh->total_length > (section->buffer + section->size))
17973     {
17974       dwarf2_statement_list_fits_in_line_number_section_complaint ();
17975       return 0;
17976     }
17977   lh->statement_program_end = line_ptr + lh->total_length;
17978   lh->version = read_2_bytes (abfd, line_ptr);
17979   line_ptr += 2;
17980   if (lh->version > 5)
17981     {
17982       /* This is a version we don't understand.  The format could have
17983          changed in ways we don't handle properly so just punt.  */
17984       complaint (&symfile_complaints,
17985                  _("unsupported version in .debug_line section"));
17986       return NULL;
17987     }
17988   if (lh->version >= 5)
17989     {
17990       gdb_byte segment_selector_size;
17991
17992       /* Skip address size.  */
17993       read_1_byte (abfd, line_ptr);
17994       line_ptr += 1;
17995
17996       segment_selector_size = read_1_byte (abfd, line_ptr);
17997       line_ptr += 1;
17998       if (segment_selector_size != 0)
17999         {
18000           complaint (&symfile_complaints,
18001                      _("unsupported segment selector size %u "
18002                        "in .debug_line section"),
18003                      segment_selector_size);
18004           return NULL;
18005         }
18006     }
18007   lh->header_length = read_offset_1 (abfd, line_ptr, offset_size);
18008   line_ptr += offset_size;
18009   lh->minimum_instruction_length = read_1_byte (abfd, line_ptr);
18010   line_ptr += 1;
18011   if (lh->version >= 4)
18012     {
18013       lh->maximum_ops_per_instruction = read_1_byte (abfd, line_ptr);
18014       line_ptr += 1;
18015     }
18016   else
18017     lh->maximum_ops_per_instruction = 1;
18018
18019   if (lh->maximum_ops_per_instruction == 0)
18020     {
18021       lh->maximum_ops_per_instruction = 1;
18022       complaint (&symfile_complaints,
18023                  _("invalid maximum_ops_per_instruction "
18024                    "in `.debug_line' section"));
18025     }
18026
18027   lh->default_is_stmt = read_1_byte (abfd, line_ptr);
18028   line_ptr += 1;
18029   lh->line_base = read_1_signed_byte (abfd, line_ptr);
18030   line_ptr += 1;
18031   lh->line_range = read_1_byte (abfd, line_ptr);
18032   line_ptr += 1;
18033   lh->opcode_base = read_1_byte (abfd, line_ptr);
18034   line_ptr += 1;
18035   lh->standard_opcode_lengths.reset (new unsigned char[lh->opcode_base]);
18036
18037   lh->standard_opcode_lengths[0] = 1;  /* This should never be used anyway.  */
18038   for (i = 1; i < lh->opcode_base; ++i)
18039     {
18040       lh->standard_opcode_lengths[i] = read_1_byte (abfd, line_ptr);
18041       line_ptr += 1;
18042     }
18043
18044   if (lh->version >= 5)
18045     {
18046       /* Read directory table.  */
18047       read_formatted_entries (abfd, &line_ptr, lh.get (), &cu->header,
18048                               [] (struct line_header *lh, const char *name,
18049                                   dir_index d_index, unsigned int mod_time,
18050                                   unsigned int length)
18051         {
18052           lh->add_include_dir (name);
18053         });
18054
18055       /* Read file name table.  */
18056       read_formatted_entries (abfd, &line_ptr, lh.get (), &cu->header,
18057                               [] (struct line_header *lh, const char *name,
18058                                   dir_index d_index, unsigned int mod_time,
18059                                   unsigned int length)
18060         {
18061           lh->add_file_name (name, d_index, mod_time, length);
18062         });
18063     }
18064   else
18065     {
18066       /* Read directory table.  */
18067       while ((cur_dir = read_direct_string (abfd, line_ptr, &bytes_read)) != NULL)
18068         {
18069           line_ptr += bytes_read;
18070           lh->add_include_dir (cur_dir);
18071         }
18072       line_ptr += bytes_read;
18073
18074       /* Read file name table.  */
18075       while ((cur_file = read_direct_string (abfd, line_ptr, &bytes_read)) != NULL)
18076         {
18077           unsigned int mod_time, length;
18078           dir_index d_index;
18079
18080           line_ptr += bytes_read;
18081           d_index = (dir_index) read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
18082           line_ptr += bytes_read;
18083           mod_time = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
18084           line_ptr += bytes_read;
18085           length = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
18086           line_ptr += bytes_read;
18087
18088           lh->add_file_name (cur_file, d_index, mod_time, length);
18089         }
18090       line_ptr += bytes_read;
18091     }
18092   lh->statement_program_start = line_ptr;
18093
18094   if (line_ptr > (section->buffer + section->size))
18095     complaint (&symfile_complaints,
18096                _("line number info header doesn't "
18097                  "fit in `.debug_line' section"));
18098
18099   return lh;
18100 }
18101
18102 /* Subroutine of dwarf_decode_lines to simplify it.
18103    Return the file name of the psymtab for included file FILE_INDEX
18104    in line header LH of PST.
18105    COMP_DIR is the compilation directory (DW_AT_comp_dir) or NULL if unknown.
18106    If space for the result is malloc'd, it will be freed by a cleanup.
18107    Returns NULL if FILE_INDEX should be ignored, i.e., it is pst->filename.
18108
18109    The function creates dangling cleanup registration.  */
18110
18111 static const char *
18112 psymtab_include_file_name (const struct line_header *lh, int file_index,
18113                            const struct partial_symtab *pst,
18114                            const char *comp_dir)
18115 {
18116   const file_entry &fe = lh->file_names[file_index];
18117   const char *include_name = fe.name;
18118   const char *include_name_to_compare = include_name;
18119   const char *pst_filename;
18120   char *copied_name = NULL;
18121   int file_is_pst;
18122
18123   const char *dir_name = fe.include_dir (lh);
18124
18125   if (!IS_ABSOLUTE_PATH (include_name)
18126       && (dir_name != NULL || comp_dir != NULL))
18127     {
18128       /* Avoid creating a duplicate psymtab for PST.
18129          We do this by comparing INCLUDE_NAME and PST_FILENAME.
18130          Before we do the comparison, however, we need to account
18131          for DIR_NAME and COMP_DIR.
18132          First prepend dir_name (if non-NULL).  If we still don't
18133          have an absolute path prepend comp_dir (if non-NULL).
18134          However, the directory we record in the include-file's
18135          psymtab does not contain COMP_DIR (to match the
18136          corresponding symtab(s)).
18137
18138          Example:
18139
18140          bash$ cd /tmp
18141          bash$ gcc -g ./hello.c
18142          include_name = "hello.c"
18143          dir_name = "."
18144          DW_AT_comp_dir = comp_dir = "/tmp"
18145          DW_AT_name = "./hello.c"
18146
18147       */
18148
18149       if (dir_name != NULL)
18150         {
18151           char *tem = concat (dir_name, SLASH_STRING,
18152                               include_name, (char *)NULL);
18153
18154           make_cleanup (xfree, tem);
18155           include_name = tem;
18156           include_name_to_compare = include_name;
18157         }
18158       if (!IS_ABSOLUTE_PATH (include_name) && comp_dir != NULL)
18159         {
18160           char *tem = concat (comp_dir, SLASH_STRING,
18161                               include_name, (char *)NULL);
18162
18163           make_cleanup (xfree, tem);
18164           include_name_to_compare = tem;
18165         }
18166     }
18167
18168   pst_filename = pst->filename;
18169   if (!IS_ABSOLUTE_PATH (pst_filename) && pst->dirname != NULL)
18170     {
18171       copied_name = concat (pst->dirname, SLASH_STRING,
18172                             pst_filename, (char *)NULL);
18173       pst_filename = copied_name;
18174     }
18175
18176   file_is_pst = FILENAME_CMP (include_name_to_compare, pst_filename) == 0;
18177
18178   if (copied_name != NULL)
18179     xfree (copied_name);
18180
18181   if (file_is_pst)
18182     return NULL;
18183   return include_name;
18184 }
18185
18186 /* State machine to track the state of the line number program.  */
18187
18188 class lnp_state_machine
18189 {
18190 public:
18191   /* Initialize a machine state for the start of a line number
18192      program.  */
18193   lnp_state_machine (gdbarch *arch, line_header *lh, bool record_lines_p);
18194
18195   file_entry *current_file ()
18196   {
18197     /* lh->file_names is 0-based, but the file name numbers in the
18198        statement program are 1-based.  */
18199     return m_line_header->file_name_at (m_file);
18200   }
18201
18202   /* Record the line in the state machine.  END_SEQUENCE is true if
18203      we're processing the end of a sequence.  */
18204   void record_line (bool end_sequence);
18205
18206   /* Check address and if invalid nop-out the rest of the lines in this
18207      sequence.  */
18208   void check_line_address (struct dwarf2_cu *cu,
18209                            const gdb_byte *line_ptr,
18210                            CORE_ADDR lowpc, CORE_ADDR address);
18211
18212   void handle_set_discriminator (unsigned int discriminator)
18213   {
18214     m_discriminator = discriminator;
18215     m_line_has_non_zero_discriminator |= discriminator != 0;
18216   }
18217
18218   /* Handle DW_LNE_set_address.  */
18219   void handle_set_address (CORE_ADDR baseaddr, CORE_ADDR address)
18220   {
18221     m_op_index = 0;
18222     address += baseaddr;
18223     m_address = gdbarch_adjust_dwarf2_line (m_gdbarch, address, false);
18224   }
18225
18226   /* Handle DW_LNS_advance_pc.  */
18227   void handle_advance_pc (CORE_ADDR adjust);
18228
18229   /* Handle a special opcode.  */
18230   void handle_special_opcode (unsigned char op_code);
18231
18232   /* Handle DW_LNS_advance_line.  */
18233   void handle_advance_line (int line_delta)
18234   {
18235     advance_line (line_delta);
18236   }
18237
18238   /* Handle DW_LNS_set_file.  */
18239   void handle_set_file (file_name_index file);
18240
18241   /* Handle DW_LNS_negate_stmt.  */
18242   void handle_negate_stmt ()
18243   {
18244     m_is_stmt = !m_is_stmt;
18245   }
18246
18247   /* Handle DW_LNS_const_add_pc.  */
18248   void handle_const_add_pc ();
18249
18250   /* Handle DW_LNS_fixed_advance_pc.  */
18251   void handle_fixed_advance_pc (CORE_ADDR addr_adj)
18252   {
18253     m_address += gdbarch_adjust_dwarf2_line (m_gdbarch, addr_adj, true);
18254     m_op_index = 0;
18255   }
18256
18257   /* Handle DW_LNS_copy.  */
18258   void handle_copy ()
18259   {
18260     record_line (false);
18261     m_discriminator = 0;
18262   }
18263
18264   /* Handle DW_LNE_end_sequence.  */
18265   void handle_end_sequence ()
18266   {
18267     m_record_line_callback = ::record_line;
18268   }
18269
18270 private:
18271   /* Advance the line by LINE_DELTA.  */
18272   void advance_line (int line_delta)
18273   {
18274     m_line += line_delta;
18275
18276     if (line_delta != 0)
18277       m_line_has_non_zero_discriminator = m_discriminator != 0;
18278   }
18279
18280   gdbarch *m_gdbarch;
18281
18282   /* True if we're recording lines.
18283      Otherwise we're building partial symtabs and are just interested in
18284      finding include files mentioned by the line number program.  */
18285   bool m_record_lines_p;
18286
18287   /* The line number header.  */
18288   line_header *m_line_header;
18289
18290   /* These are part of the standard DWARF line number state machine,
18291      and initialized according to the DWARF spec.  */
18292
18293   unsigned char m_op_index = 0;
18294   /* The line table index (1-based) of the current file.  */
18295   file_name_index m_file = (file_name_index) 1;
18296   unsigned int m_line = 1;
18297
18298   /* These are initialized in the constructor.  */
18299
18300   CORE_ADDR m_address;
18301   bool m_is_stmt;
18302   unsigned int m_discriminator;
18303
18304   /* Additional bits of state we need to track.  */
18305
18306   /* The last file that we called dwarf2_start_subfile for.
18307      This is only used for TLLs.  */
18308   unsigned int m_last_file = 0;
18309   /* The last file a line number was recorded for.  */
18310   struct subfile *m_last_subfile = NULL;
18311
18312   /* The function to call to record a line.  */
18313   record_line_ftype *m_record_line_callback = NULL;
18314
18315   /* The last line number that was recorded, used to coalesce
18316      consecutive entries for the same line.  This can happen, for
18317      example, when discriminators are present.  PR 17276.  */
18318   unsigned int m_last_line = 0;
18319   bool m_line_has_non_zero_discriminator = false;
18320 };
18321
18322 void
18323 lnp_state_machine::handle_advance_pc (CORE_ADDR adjust)
18324 {
18325   CORE_ADDR addr_adj = (((m_op_index + adjust)
18326                          / m_line_header->maximum_ops_per_instruction)
18327                         * m_line_header->minimum_instruction_length);
18328   m_address += gdbarch_adjust_dwarf2_line (m_gdbarch, addr_adj, true);
18329   m_op_index = ((m_op_index + adjust)
18330                 % m_line_header->maximum_ops_per_instruction);
18331 }
18332
18333 void
18334 lnp_state_machine::handle_special_opcode (unsigned char op_code)
18335 {
18336   unsigned char adj_opcode = op_code - m_line_header->opcode_base;
18337   CORE_ADDR addr_adj = (((m_op_index
18338                           + (adj_opcode / m_line_header->line_range))
18339                          / m_line_header->maximum_ops_per_instruction)
18340                         * m_line_header->minimum_instruction_length);
18341   m_address += gdbarch_adjust_dwarf2_line (m_gdbarch, addr_adj, true);
18342   m_op_index = ((m_op_index + (adj_opcode / m_line_header->line_range))
18343                 % m_line_header->maximum_ops_per_instruction);
18344
18345   int line_delta = (m_line_header->line_base
18346                     + (adj_opcode % m_line_header->line_range));
18347   advance_line (line_delta);
18348   record_line (false);
18349   m_discriminator = 0;
18350 }
18351
18352 void
18353 lnp_state_machine::handle_set_file (file_name_index file)
18354 {
18355   m_file = file;
18356
18357   const file_entry *fe = current_file ();
18358   if (fe == NULL)
18359     dwarf2_debug_line_missing_file_complaint ();
18360   else if (m_record_lines_p)
18361     {
18362       const char *dir = fe->include_dir (m_line_header);
18363
18364       m_last_subfile = current_subfile;
18365       m_line_has_non_zero_discriminator = m_discriminator != 0;
18366       dwarf2_start_subfile (fe->name, dir);
18367     }
18368 }
18369
18370 void
18371 lnp_state_machine::handle_const_add_pc ()
18372 {
18373   CORE_ADDR adjust
18374     = (255 - m_line_header->opcode_base) / m_line_header->line_range;
18375
18376   CORE_ADDR addr_adj
18377     = (((m_op_index + adjust)
18378         / m_line_header->maximum_ops_per_instruction)
18379        * m_line_header->minimum_instruction_length);
18380
18381   m_address += gdbarch_adjust_dwarf2_line (m_gdbarch, addr_adj, true);
18382   m_op_index = ((m_op_index + adjust)
18383                 % m_line_header->maximum_ops_per_instruction);
18384 }
18385
18386 /* Ignore this record_line request.  */
18387
18388 static void
18389 noop_record_line (struct subfile *subfile, int line, CORE_ADDR pc)
18390 {
18391   return;
18392 }
18393
18394 /* Return non-zero if we should add LINE to the line number table.
18395    LINE is the line to add, LAST_LINE is the last line that was added,
18396    LAST_SUBFILE is the subfile for LAST_LINE.
18397    LINE_HAS_NON_ZERO_DISCRIMINATOR is non-zero if LINE has ever
18398    had a non-zero discriminator.
18399
18400    We have to be careful in the presence of discriminators.
18401    E.g., for this line:
18402
18403      for (i = 0; i < 100000; i++);
18404
18405    clang can emit four line number entries for that one line,
18406    each with a different discriminator.
18407    See gdb.dwarf2/dw2-single-line-discriminators.exp for an example.
18408
18409    However, we want gdb to coalesce all four entries into one.
18410    Otherwise the user could stepi into the middle of the line and
18411    gdb would get confused about whether the pc really was in the
18412    middle of the line.
18413
18414    Things are further complicated by the fact that two consecutive
18415    line number entries for the same line is a heuristic used by gcc
18416    to denote the end of the prologue.  So we can't just discard duplicate
18417    entries, we have to be selective about it.  The heuristic we use is
18418    that we only collapse consecutive entries for the same line if at least
18419    one of those entries has a non-zero discriminator.  PR 17276.
18420
18421    Note: Addresses in the line number state machine can never go backwards
18422    within one sequence, thus this coalescing is ok.  */
18423
18424 static int
18425 dwarf_record_line_p (unsigned int line, unsigned int last_line,
18426                      int line_has_non_zero_discriminator,
18427                      struct subfile *last_subfile)
18428 {
18429   if (current_subfile != last_subfile)
18430     return 1;
18431   if (line != last_line)
18432     return 1;
18433   /* Same line for the same file that we've seen already.
18434      As a last check, for pr 17276, only record the line if the line
18435      has never had a non-zero discriminator.  */
18436   if (!line_has_non_zero_discriminator)
18437     return 1;
18438   return 0;
18439 }
18440
18441 /* Use P_RECORD_LINE to record line number LINE beginning at address ADDRESS
18442    in the line table of subfile SUBFILE.  */
18443
18444 static void
18445 dwarf_record_line_1 (struct gdbarch *gdbarch, struct subfile *subfile,
18446                      unsigned int line, CORE_ADDR address,
18447                      record_line_ftype p_record_line)
18448 {
18449   CORE_ADDR addr = gdbarch_addr_bits_remove (gdbarch, address);
18450
18451   if (dwarf_line_debug)
18452     {
18453       fprintf_unfiltered (gdb_stdlog,
18454                           "Recording line %u, file %s, address %s\n",
18455                           line, lbasename (subfile->name),
18456                           paddress (gdbarch, address));
18457     }
18458
18459   (*p_record_line) (subfile, line, addr);
18460 }
18461
18462 /* Subroutine of dwarf_decode_lines_1 to simplify it.
18463    Mark the end of a set of line number records.
18464    The arguments are the same as for dwarf_record_line_1.
18465    If SUBFILE is NULL the request is ignored.  */
18466
18467 static void
18468 dwarf_finish_line (struct gdbarch *gdbarch, struct subfile *subfile,
18469                    CORE_ADDR address, record_line_ftype p_record_line)
18470 {
18471   if (subfile == NULL)
18472     return;
18473
18474   if (dwarf_line_debug)
18475     {
18476       fprintf_unfiltered (gdb_stdlog,
18477                           "Finishing current line, file %s, address %s\n",
18478                           lbasename (subfile->name),
18479                           paddress (gdbarch, address));
18480     }
18481
18482   dwarf_record_line_1 (gdbarch, subfile, 0, address, p_record_line);
18483 }
18484
18485 void
18486 lnp_state_machine::record_line (bool end_sequence)
18487 {
18488   if (dwarf_line_debug)
18489     {
18490       fprintf_unfiltered (gdb_stdlog,
18491                           "Processing actual line %u: file %u,"
18492                           " address %s, is_stmt %u, discrim %u\n",
18493                           m_line, to_underlying (m_file),
18494                           paddress (m_gdbarch, m_address),
18495                           m_is_stmt, m_discriminator);
18496     }
18497
18498   file_entry *fe = current_file ();
18499
18500   if (fe == NULL)
18501     dwarf2_debug_line_missing_file_complaint ();
18502   /* For now we ignore lines not starting on an instruction boundary.
18503      But not when processing end_sequence for compatibility with the
18504      previous version of the code.  */
18505   else if (m_op_index == 0 || end_sequence)
18506     {
18507       fe->included_p = 1;
18508       if (m_record_lines_p && m_is_stmt)
18509         {
18510           if (m_last_subfile != current_subfile || end_sequence)
18511             {
18512               dwarf_finish_line (m_gdbarch, m_last_subfile,
18513                                  m_address, m_record_line_callback);
18514             }
18515
18516           if (!end_sequence)
18517             {
18518               if (dwarf_record_line_p (m_line, m_last_line,
18519                                        m_line_has_non_zero_discriminator,
18520                                        m_last_subfile))
18521                 {
18522                   dwarf_record_line_1 (m_gdbarch, current_subfile,
18523                                        m_line, m_address,
18524                                        m_record_line_callback);
18525                 }
18526               m_last_subfile = current_subfile;
18527               m_last_line = m_line;
18528             }
18529         }
18530     }
18531 }
18532
18533 lnp_state_machine::lnp_state_machine (gdbarch *arch, line_header *lh,
18534                                       bool record_lines_p)
18535 {
18536   m_gdbarch = arch;
18537   m_record_lines_p = record_lines_p;
18538   m_line_header = lh;
18539
18540   m_record_line_callback = ::record_line;
18541
18542   /* Call `gdbarch_adjust_dwarf2_line' on the initial 0 address as if there
18543      was a line entry for it so that the backend has a chance to adjust it
18544      and also record it in case it needs it.  This is currently used by MIPS
18545      code, cf. `mips_adjust_dwarf2_line'.  */
18546   m_address = gdbarch_adjust_dwarf2_line (arch, 0, 0);
18547   m_is_stmt = lh->default_is_stmt;
18548   m_discriminator = 0;
18549 }
18550
18551 void
18552 lnp_state_machine::check_line_address (struct dwarf2_cu *cu,
18553                                        const gdb_byte *line_ptr,
18554                                        CORE_ADDR lowpc, CORE_ADDR address)
18555 {
18556   /* If address < lowpc then it's not a usable value, it's outside the
18557      pc range of the CU.  However, we restrict the test to only address
18558      values of zero to preserve GDB's previous behaviour which is to
18559      handle the specific case of a function being GC'd by the linker.  */
18560
18561   if (address == 0 && address < lowpc)
18562     {
18563       /* This line table is for a function which has been
18564          GCd by the linker.  Ignore it.  PR gdb/12528 */
18565
18566       struct objfile *objfile = cu->objfile;
18567       long line_offset = line_ptr - get_debug_line_section (cu)->buffer;
18568
18569       complaint (&symfile_complaints,
18570                  _(".debug_line address at offset 0x%lx is 0 [in module %s]"),
18571                  line_offset, objfile_name (objfile));
18572       m_record_line_callback = noop_record_line;
18573       /* Note: record_line_callback is left as noop_record_line until
18574          we see DW_LNE_end_sequence.  */
18575     }
18576 }
18577
18578 /* Subroutine of dwarf_decode_lines to simplify it.
18579    Process the line number information in LH.
18580    If DECODE_FOR_PST_P is non-zero, all we do is process the line number
18581    program in order to set included_p for every referenced header.  */
18582
18583 static void
18584 dwarf_decode_lines_1 (struct line_header *lh, struct dwarf2_cu *cu,
18585                       const int decode_for_pst_p, CORE_ADDR lowpc)
18586 {
18587   const gdb_byte *line_ptr, *extended_end;
18588   const gdb_byte *line_end;
18589   unsigned int bytes_read, extended_len;
18590   unsigned char op_code, extended_op;
18591   CORE_ADDR baseaddr;
18592   struct objfile *objfile = cu->objfile;
18593   bfd *abfd = objfile->obfd;
18594   struct gdbarch *gdbarch = get_objfile_arch (objfile);
18595   /* True if we're recording line info (as opposed to building partial
18596      symtabs and just interested in finding include files mentioned by
18597      the line number program).  */
18598   bool record_lines_p = !decode_for_pst_p;
18599
18600   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
18601
18602   line_ptr = lh->statement_program_start;
18603   line_end = lh->statement_program_end;
18604
18605   /* Read the statement sequences until there's nothing left.  */
18606   while (line_ptr < line_end)
18607     {
18608       /* The DWARF line number program state machine.  Reset the state
18609          machine at the start of each sequence.  */
18610       lnp_state_machine state_machine (gdbarch, lh, record_lines_p);
18611       bool end_sequence = false;
18612
18613       if (record_lines_p)
18614         {
18615           /* Start a subfile for the current file of the state
18616              machine.  */
18617           const file_entry *fe = state_machine.current_file ();
18618
18619           if (fe != NULL)
18620             dwarf2_start_subfile (fe->name, fe->include_dir (lh));
18621         }
18622
18623       /* Decode the table.  */
18624       while (line_ptr < line_end && !end_sequence)
18625         {
18626           op_code = read_1_byte (abfd, line_ptr);
18627           line_ptr += 1;
18628
18629           if (op_code >= lh->opcode_base)
18630             {
18631               /* Special opcode.  */
18632               state_machine.handle_special_opcode (op_code);
18633             }
18634           else switch (op_code)
18635             {
18636             case DW_LNS_extended_op:
18637               extended_len = read_unsigned_leb128 (abfd, line_ptr,
18638                                                    &bytes_read);
18639               line_ptr += bytes_read;
18640               extended_end = line_ptr + extended_len;
18641               extended_op = read_1_byte (abfd, line_ptr);
18642               line_ptr += 1;
18643               switch (extended_op)
18644                 {
18645                 case DW_LNE_end_sequence:
18646                   state_machine.handle_end_sequence ();
18647                   end_sequence = true;
18648                   break;
18649                 case DW_LNE_set_address:
18650                   {
18651                     CORE_ADDR address
18652                       = read_address (abfd, line_ptr, cu, &bytes_read);
18653                     line_ptr += bytes_read;
18654
18655                     state_machine.check_line_address (cu, line_ptr,
18656                                                       lowpc, address);
18657                     state_machine.handle_set_address (baseaddr, address);
18658                   }
18659                   break;
18660                 case DW_LNE_define_file:
18661                   {
18662                     const char *cur_file;
18663                     unsigned int mod_time, length;
18664                     dir_index dindex;
18665
18666                     cur_file = read_direct_string (abfd, line_ptr,
18667                                                    &bytes_read);
18668                     line_ptr += bytes_read;
18669                     dindex = (dir_index)
18670                       read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
18671                     line_ptr += bytes_read;
18672                     mod_time =
18673                       read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
18674                     line_ptr += bytes_read;
18675                     length =
18676                       read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
18677                     line_ptr += bytes_read;
18678                     lh->add_file_name (cur_file, dindex, mod_time, length);
18679                   }
18680                   break;
18681                 case DW_LNE_set_discriminator:
18682                   {
18683                     /* The discriminator is not interesting to the
18684                        debugger; just ignore it.  We still need to
18685                        check its value though:
18686                        if there are consecutive entries for the same
18687                        (non-prologue) line we want to coalesce them.
18688                        PR 17276.  */
18689                     unsigned int discr
18690                       = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
18691                     line_ptr += bytes_read;
18692
18693                     state_machine.handle_set_discriminator (discr);
18694                   }
18695                   break;
18696                 default:
18697                   complaint (&symfile_complaints,
18698                              _("mangled .debug_line section"));
18699                   return;
18700                 }
18701               /* Make sure that we parsed the extended op correctly.  If e.g.
18702                  we expected a different address size than the producer used,
18703                  we may have read the wrong number of bytes.  */
18704               if (line_ptr != extended_end)
18705                 {
18706                   complaint (&symfile_complaints,
18707                              _("mangled .debug_line section"));
18708                   return;
18709                 }
18710               break;
18711             case DW_LNS_copy:
18712               state_machine.handle_copy ();
18713               break;
18714             case DW_LNS_advance_pc:
18715               {
18716                 CORE_ADDR adjust
18717                   = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
18718                 line_ptr += bytes_read;
18719
18720                 state_machine.handle_advance_pc (adjust);
18721               }
18722               break;
18723             case DW_LNS_advance_line:
18724               {
18725                 int line_delta
18726                   = read_signed_leb128 (abfd, line_ptr, &bytes_read);
18727                 line_ptr += bytes_read;
18728
18729                 state_machine.handle_advance_line (line_delta);
18730               }
18731               break;
18732             case DW_LNS_set_file:
18733               {
18734                 file_name_index file
18735                   = (file_name_index) read_unsigned_leb128 (abfd, line_ptr,
18736                                                             &bytes_read);
18737                 line_ptr += bytes_read;
18738
18739                 state_machine.handle_set_file (file);
18740               }
18741               break;
18742             case DW_LNS_set_column:
18743               (void) read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
18744               line_ptr += bytes_read;
18745               break;
18746             case DW_LNS_negate_stmt:
18747               state_machine.handle_negate_stmt ();
18748               break;
18749             case DW_LNS_set_basic_block:
18750               break;
18751             /* Add to the address register of the state machine the
18752                address increment value corresponding to special opcode
18753                255.  I.e., this value is scaled by the minimum
18754                instruction length since special opcode 255 would have
18755                scaled the increment.  */
18756             case DW_LNS_const_add_pc:
18757               state_machine.handle_const_add_pc ();
18758               break;
18759             case DW_LNS_fixed_advance_pc:
18760               {
18761                 CORE_ADDR addr_adj = read_2_bytes (abfd, line_ptr);
18762                 line_ptr += 2;
18763
18764                 state_machine.handle_fixed_advance_pc (addr_adj);
18765               }
18766               break;
18767             default:
18768               {
18769                 /* Unknown standard opcode, ignore it.  */
18770                 int i;
18771
18772                 for (i = 0; i < lh->standard_opcode_lengths[op_code]; i++)
18773                   {
18774                     (void) read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
18775                     line_ptr += bytes_read;
18776                   }
18777               }
18778             }
18779         }
18780
18781       if (!end_sequence)
18782         dwarf2_debug_line_missing_end_sequence_complaint ();
18783
18784       /* We got a DW_LNE_end_sequence (or we ran off the end of the buffer,
18785          in which case we still finish recording the last line).  */
18786       state_machine.record_line (true);
18787     }
18788 }
18789
18790 /* Decode the Line Number Program (LNP) for the given line_header
18791    structure and CU.  The actual information extracted and the type
18792    of structures created from the LNP depends on the value of PST.
18793
18794    1. If PST is NULL, then this procedure uses the data from the program
18795       to create all necessary symbol tables, and their linetables.
18796
18797    2. If PST is not NULL, this procedure reads the program to determine
18798       the list of files included by the unit represented by PST, and
18799       builds all the associated partial symbol tables.
18800
18801    COMP_DIR is the compilation directory (DW_AT_comp_dir) or NULL if unknown.
18802    It is used for relative paths in the line table.
18803    NOTE: When processing partial symtabs (pst != NULL),
18804    comp_dir == pst->dirname.
18805
18806    NOTE: It is important that psymtabs have the same file name (via strcmp)
18807    as the corresponding symtab.  Since COMP_DIR is not used in the name of the
18808    symtab we don't use it in the name of the psymtabs we create.
18809    E.g. expand_line_sal requires this when finding psymtabs to expand.
18810    A good testcase for this is mb-inline.exp.
18811
18812    LOWPC is the lowest address in CU (or 0 if not known).
18813
18814    Boolean DECODE_MAPPING specifies we need to fully decode .debug_line
18815    for its PC<->lines mapping information.  Otherwise only the filename
18816    table is read in.  */
18817
18818 static void
18819 dwarf_decode_lines (struct line_header *lh, const char *comp_dir,
18820                     struct dwarf2_cu *cu, struct partial_symtab *pst,
18821                     CORE_ADDR lowpc, int decode_mapping)
18822 {
18823   struct objfile *objfile = cu->objfile;
18824   const int decode_for_pst_p = (pst != NULL);
18825
18826   if (decode_mapping)
18827     dwarf_decode_lines_1 (lh, cu, decode_for_pst_p, lowpc);
18828
18829   if (decode_for_pst_p)
18830     {
18831       int file_index;
18832
18833       /* Now that we're done scanning the Line Header Program, we can
18834          create the psymtab of each included file.  */
18835       for (file_index = 0; file_index < lh->file_names.size (); file_index++)
18836         if (lh->file_names[file_index].included_p == 1)
18837           {
18838             const char *include_name =
18839               psymtab_include_file_name (lh, file_index, pst, comp_dir);
18840             if (include_name != NULL)
18841               dwarf2_create_include_psymtab (include_name, pst, objfile);
18842           }
18843     }
18844   else
18845     {
18846       /* Make sure a symtab is created for every file, even files
18847          which contain only variables (i.e. no code with associated
18848          line numbers).  */
18849       struct compunit_symtab *cust = buildsym_compunit_symtab ();
18850       int i;
18851
18852       for (i = 0; i < lh->file_names.size (); i++)
18853         {
18854           file_entry &fe = lh->file_names[i];
18855
18856           dwarf2_start_subfile (fe.name, fe.include_dir (lh));
18857
18858           if (current_subfile->symtab == NULL)
18859             {
18860               current_subfile->symtab
18861                 = allocate_symtab (cust, current_subfile->name);
18862             }
18863           fe.symtab = current_subfile->symtab;
18864         }
18865     }
18866 }
18867
18868 /* Start a subfile for DWARF.  FILENAME is the name of the file and
18869    DIRNAME the name of the source directory which contains FILENAME
18870    or NULL if not known.
18871    This routine tries to keep line numbers from identical absolute and
18872    relative file names in a common subfile.
18873
18874    Using the `list' example from the GDB testsuite, which resides in
18875    /srcdir and compiling it with Irix6.2 cc in /compdir using a filename
18876    of /srcdir/list0.c yields the following debugging information for list0.c:
18877
18878    DW_AT_name:          /srcdir/list0.c
18879    DW_AT_comp_dir:      /compdir
18880    files.files[0].name: list0.h
18881    files.files[0].dir:  /srcdir
18882    files.files[1].name: list0.c
18883    files.files[1].dir:  /srcdir
18884
18885    The line number information for list0.c has to end up in a single
18886    subfile, so that `break /srcdir/list0.c:1' works as expected.
18887    start_subfile will ensure that this happens provided that we pass the
18888    concatenation of files.files[1].dir and files.files[1].name as the
18889    subfile's name.  */
18890
18891 static void
18892 dwarf2_start_subfile (const char *filename, const char *dirname)
18893 {
18894   char *copy = NULL;
18895
18896   /* In order not to lose the line information directory,
18897      we concatenate it to the filename when it makes sense.
18898      Note that the Dwarf3 standard says (speaking of filenames in line
18899      information): ``The directory index is ignored for file names
18900      that represent full path names''.  Thus ignoring dirname in the
18901      `else' branch below isn't an issue.  */
18902
18903   if (!IS_ABSOLUTE_PATH (filename) && dirname != NULL)
18904     {
18905       copy = concat (dirname, SLASH_STRING, filename, (char *)NULL);
18906       filename = copy;
18907     }
18908
18909   start_subfile (filename);
18910
18911   if (copy != NULL)
18912     xfree (copy);
18913 }
18914
18915 /* Start a symtab for DWARF.
18916    NAME, COMP_DIR, LOW_PC are passed to start_symtab.  */
18917
18918 static struct compunit_symtab *
18919 dwarf2_start_symtab (struct dwarf2_cu *cu,
18920                      const char *name, const char *comp_dir, CORE_ADDR low_pc)
18921 {
18922   struct compunit_symtab *cust
18923     = start_symtab (cu->objfile, name, comp_dir, low_pc);
18924
18925   record_debugformat ("DWARF 2");
18926   record_producer (cu->producer);
18927
18928   /* We assume that we're processing GCC output.  */
18929   processing_gcc_compilation = 2;
18930
18931   cu->processing_has_namespace_info = 0;
18932
18933   return cust;
18934 }
18935
18936 static void
18937 var_decode_location (struct attribute *attr, struct symbol *sym,
18938                      struct dwarf2_cu *cu)
18939 {
18940   struct objfile *objfile = cu->objfile;
18941   struct comp_unit_head *cu_header = &cu->header;
18942
18943   /* NOTE drow/2003-01-30: There used to be a comment and some special
18944      code here to turn a symbol with DW_AT_external and a
18945      SYMBOL_VALUE_ADDRESS of 0 into a LOC_UNRESOLVED symbol.  This was
18946      necessary for platforms (maybe Alpha, certainly PowerPC GNU/Linux
18947      with some versions of binutils) where shared libraries could have
18948      relocations against symbols in their debug information - the
18949      minimal symbol would have the right address, but the debug info
18950      would not.  It's no longer necessary, because we will explicitly
18951      apply relocations when we read in the debug information now.  */
18952
18953   /* A DW_AT_location attribute with no contents indicates that a
18954      variable has been optimized away.  */
18955   if (attr_form_is_block (attr) && DW_BLOCK (attr)->size == 0)
18956     {
18957       SYMBOL_ACLASS_INDEX (sym) = LOC_OPTIMIZED_OUT;
18958       return;
18959     }
18960
18961   /* Handle one degenerate form of location expression specially, to
18962      preserve GDB's previous behavior when section offsets are
18963      specified.  If this is just a DW_OP_addr or DW_OP_GNU_addr_index
18964      then mark this symbol as LOC_STATIC.  */
18965
18966   if (attr_form_is_block (attr)
18967       && ((DW_BLOCK (attr)->data[0] == DW_OP_addr
18968            && DW_BLOCK (attr)->size == 1 + cu_header->addr_size)
18969           || (DW_BLOCK (attr)->data[0] == DW_OP_GNU_addr_index
18970               && (DW_BLOCK (attr)->size
18971                   == 1 + leb128_size (&DW_BLOCK (attr)->data[1])))))
18972     {
18973       unsigned int dummy;
18974
18975       if (DW_BLOCK (attr)->data[0] == DW_OP_addr)
18976         SYMBOL_VALUE_ADDRESS (sym) =
18977           read_address (objfile->obfd, DW_BLOCK (attr)->data + 1, cu, &dummy);
18978       else
18979         SYMBOL_VALUE_ADDRESS (sym) =
18980           read_addr_index_from_leb128 (cu, DW_BLOCK (attr)->data + 1, &dummy);
18981       SYMBOL_ACLASS_INDEX (sym) = LOC_STATIC;
18982       fixup_symbol_section (sym, objfile);
18983       SYMBOL_VALUE_ADDRESS (sym) += ANOFFSET (objfile->section_offsets,
18984                                               SYMBOL_SECTION (sym));
18985       return;
18986     }
18987
18988   /* NOTE drow/2002-01-30: It might be worthwhile to have a static
18989      expression evaluator, and use LOC_COMPUTED only when necessary
18990      (i.e. when the value of a register or memory location is
18991      referenced, or a thread-local block, etc.).  Then again, it might
18992      not be worthwhile.  I'm assuming that it isn't unless performance
18993      or memory numbers show me otherwise.  */
18994
18995   dwarf2_symbol_mark_computed (attr, sym, cu, 0);
18996
18997   if (SYMBOL_COMPUTED_OPS (sym)->location_has_loclist)
18998     cu->has_loclist = 1;
18999 }
19000
19001 /* Given a pointer to a DWARF information entry, figure out if we need
19002    to make a symbol table entry for it, and if so, create a new entry
19003    and return a pointer to it.
19004    If TYPE is NULL, determine symbol type from the die, otherwise
19005    used the passed type.
19006    If SPACE is not NULL, use it to hold the new symbol.  If it is
19007    NULL, allocate a new symbol on the objfile's obstack.  */
19008
19009 static struct symbol *
19010 new_symbol_full (struct die_info *die, struct type *type, struct dwarf2_cu *cu,
19011                  struct symbol *space)
19012 {
19013   struct objfile *objfile = cu->objfile;
19014   struct gdbarch *gdbarch = get_objfile_arch (objfile);
19015   struct symbol *sym = NULL;
19016   const char *name;
19017   struct attribute *attr = NULL;
19018   struct attribute *attr2 = NULL;
19019   CORE_ADDR baseaddr;
19020   struct pending **list_to_add = NULL;
19021
19022   int inlined_func = (die->tag == DW_TAG_inlined_subroutine);
19023
19024   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
19025
19026   name = dwarf2_name (die, cu);
19027   if (name)
19028     {
19029       const char *linkagename;
19030       int suppress_add = 0;
19031
19032       if (space)
19033         sym = space;
19034       else
19035         sym = allocate_symbol (objfile);
19036       OBJSTAT (objfile, n_syms++);
19037
19038       /* Cache this symbol's name and the name's demangled form (if any).  */
19039       SYMBOL_SET_LANGUAGE (sym, cu->language, &objfile->objfile_obstack);
19040       linkagename = dwarf2_physname (name, die, cu);
19041       SYMBOL_SET_NAMES (sym, linkagename, strlen (linkagename), 0, objfile);
19042
19043       /* Fortran does not have mangling standard and the mangling does differ
19044          between gfortran, iFort etc.  */
19045       if (cu->language == language_fortran
19046           && symbol_get_demangled_name (&(sym->ginfo)) == NULL)
19047         symbol_set_demangled_name (&(sym->ginfo),
19048                                    dwarf2_full_name (name, die, cu),
19049                                    NULL);
19050
19051       /* Default assumptions.
19052          Use the passed type or decode it from the die.  */
19053       SYMBOL_DOMAIN (sym) = VAR_DOMAIN;
19054       SYMBOL_ACLASS_INDEX (sym) = LOC_OPTIMIZED_OUT;
19055       if (type != NULL)
19056         SYMBOL_TYPE (sym) = type;
19057       else
19058         SYMBOL_TYPE (sym) = die_type (die, cu);
19059       attr = dwarf2_attr (die,
19060                           inlined_func ? DW_AT_call_line : DW_AT_decl_line,
19061                           cu);
19062       if (attr)
19063         {
19064           SYMBOL_LINE (sym) = DW_UNSND (attr);
19065         }
19066
19067       attr = dwarf2_attr (die,
19068                           inlined_func ? DW_AT_call_file : DW_AT_decl_file,
19069                           cu);
19070       if (attr)
19071         {
19072           file_name_index file_index = (file_name_index) DW_UNSND (attr);
19073           struct file_entry *fe;
19074
19075           if (cu->line_header != NULL)
19076             fe = cu->line_header->file_name_at (file_index);
19077           else
19078             fe = NULL;
19079
19080           if (fe == NULL)
19081             complaint (&symfile_complaints,
19082                        _("file index out of range"));
19083           else
19084             symbol_set_symtab (sym, fe->symtab);
19085         }
19086
19087       switch (die->tag)
19088         {
19089         case DW_TAG_label:
19090           attr = dwarf2_attr (die, DW_AT_low_pc, cu);
19091           if (attr)
19092             {
19093               CORE_ADDR addr;
19094
19095               addr = attr_value_as_address (attr);
19096               addr = gdbarch_adjust_dwarf2_addr (gdbarch, addr + baseaddr);
19097               SYMBOL_VALUE_ADDRESS (sym) = addr;
19098             }
19099           SYMBOL_TYPE (sym) = objfile_type (objfile)->builtin_core_addr;
19100           SYMBOL_DOMAIN (sym) = LABEL_DOMAIN;
19101           SYMBOL_ACLASS_INDEX (sym) = LOC_LABEL;
19102           add_symbol_to_list (sym, cu->list_in_scope);
19103           break;
19104         case DW_TAG_subprogram:
19105           /* SYMBOL_BLOCK_VALUE (sym) will be filled in later by
19106              finish_block.  */
19107           SYMBOL_ACLASS_INDEX (sym) = LOC_BLOCK;
19108           attr2 = dwarf2_attr (die, DW_AT_external, cu);
19109           if ((attr2 && (DW_UNSND (attr2) != 0))
19110               || cu->language == language_ada)
19111             {
19112               /* Subprograms marked external are stored as a global symbol.
19113                  Ada subprograms, whether marked external or not, are always
19114                  stored as a global symbol, because we want to be able to
19115                  access them globally.  For instance, we want to be able
19116                  to break on a nested subprogram without having to
19117                  specify the context.  */
19118               list_to_add = &global_symbols;
19119             }
19120           else
19121             {
19122               list_to_add = cu->list_in_scope;
19123             }
19124           break;
19125         case DW_TAG_inlined_subroutine:
19126           /* SYMBOL_BLOCK_VALUE (sym) will be filled in later by
19127              finish_block.  */
19128           SYMBOL_ACLASS_INDEX (sym) = LOC_BLOCK;
19129           SYMBOL_INLINED (sym) = 1;
19130           list_to_add = cu->list_in_scope;
19131           break;
19132         case DW_TAG_template_value_param:
19133           suppress_add = 1;
19134           /* Fall through.  */
19135         case DW_TAG_constant:
19136         case DW_TAG_variable:
19137         case DW_TAG_member:
19138           /* Compilation with minimal debug info may result in
19139              variables with missing type entries.  Change the
19140              misleading `void' type to something sensible.  */
19141           if (TYPE_CODE (SYMBOL_TYPE (sym)) == TYPE_CODE_VOID)
19142             SYMBOL_TYPE (sym) = objfile_type (objfile)->builtin_int;
19143
19144           attr = dwarf2_attr (die, DW_AT_const_value, cu);
19145           /* In the case of DW_TAG_member, we should only be called for
19146              static const members.  */
19147           if (die->tag == DW_TAG_member)
19148             {
19149               /* dwarf2_add_field uses die_is_declaration,
19150                  so we do the same.  */
19151               gdb_assert (die_is_declaration (die, cu));
19152               gdb_assert (attr);
19153             }
19154           if (attr)
19155             {
19156               dwarf2_const_value (attr, sym, cu);
19157               attr2 = dwarf2_attr (die, DW_AT_external, cu);
19158               if (!suppress_add)
19159                 {
19160                   if (attr2 && (DW_UNSND (attr2) != 0))
19161                     list_to_add = &global_symbols;
19162                   else
19163                     list_to_add = cu->list_in_scope;
19164                 }
19165               break;
19166             }
19167           attr = dwarf2_attr (die, DW_AT_location, cu);
19168           if (attr)
19169             {
19170               var_decode_location (attr, sym, cu);
19171               attr2 = dwarf2_attr (die, DW_AT_external, cu);
19172
19173               /* Fortran explicitly imports any global symbols to the local
19174                  scope by DW_TAG_common_block.  */
19175               if (cu->language == language_fortran && die->parent
19176                   && die->parent->tag == DW_TAG_common_block)
19177                 attr2 = NULL;
19178
19179               if (SYMBOL_CLASS (sym) == LOC_STATIC
19180                   && SYMBOL_VALUE_ADDRESS (sym) == 0
19181                   && !dwarf2_per_objfile->has_section_at_zero)
19182                 {
19183                   /* When a static variable is eliminated by the linker,
19184                      the corresponding debug information is not stripped
19185                      out, but the variable address is set to null;
19186                      do not add such variables into symbol table.  */
19187                 }
19188               else if (attr2 && (DW_UNSND (attr2) != 0))
19189                 {
19190                   /* Workaround gfortran PR debug/40040 - it uses
19191                      DW_AT_location for variables in -fPIC libraries which may
19192                      get overriden by other libraries/executable and get
19193                      a different address.  Resolve it by the minimal symbol
19194                      which may come from inferior's executable using copy
19195                      relocation.  Make this workaround only for gfortran as for
19196                      other compilers GDB cannot guess the minimal symbol
19197                      Fortran mangling kind.  */
19198                   if (cu->language == language_fortran && die->parent
19199                       && die->parent->tag == DW_TAG_module
19200                       && cu->producer
19201                       && startswith (cu->producer, "GNU Fortran"))
19202                     SYMBOL_ACLASS_INDEX (sym) = LOC_UNRESOLVED;
19203
19204                   /* A variable with DW_AT_external is never static,
19205                      but it may be block-scoped.  */
19206                   list_to_add = (cu->list_in_scope == &file_symbols
19207                                  ? &global_symbols : cu->list_in_scope);
19208                 }
19209               else
19210                 list_to_add = cu->list_in_scope;
19211             }
19212           else
19213             {
19214               /* We do not know the address of this symbol.
19215                  If it is an external symbol and we have type information
19216                  for it, enter the symbol as a LOC_UNRESOLVED symbol.
19217                  The address of the variable will then be determined from
19218                  the minimal symbol table whenever the variable is
19219                  referenced.  */
19220               attr2 = dwarf2_attr (die, DW_AT_external, cu);
19221
19222               /* Fortran explicitly imports any global symbols to the local
19223                  scope by DW_TAG_common_block.  */
19224               if (cu->language == language_fortran && die->parent
19225                   && die->parent->tag == DW_TAG_common_block)
19226                 {
19227                   /* SYMBOL_CLASS doesn't matter here because
19228                      read_common_block is going to reset it.  */
19229                   if (!suppress_add)
19230                     list_to_add = cu->list_in_scope;
19231                 }
19232               else if (attr2 && (DW_UNSND (attr2) != 0)
19233                        && dwarf2_attr (die, DW_AT_type, cu) != NULL)
19234                 {
19235                   /* A variable with DW_AT_external is never static, but it
19236                      may be block-scoped.  */
19237                   list_to_add = (cu->list_in_scope == &file_symbols
19238                                  ? &global_symbols : cu->list_in_scope);
19239
19240                   SYMBOL_ACLASS_INDEX (sym) = LOC_UNRESOLVED;
19241                 }
19242               else if (!die_is_declaration (die, cu))
19243                 {
19244                   /* Use the default LOC_OPTIMIZED_OUT class.  */
19245                   gdb_assert (SYMBOL_CLASS (sym) == LOC_OPTIMIZED_OUT);
19246                   if (!suppress_add)
19247                     list_to_add = cu->list_in_scope;
19248                 }
19249             }
19250           break;
19251         case DW_TAG_formal_parameter:
19252           /* If we are inside a function, mark this as an argument.  If
19253              not, we might be looking at an argument to an inlined function
19254              when we do not have enough information to show inlined frames;
19255              pretend it's a local variable in that case so that the user can
19256              still see it.  */
19257           if (context_stack_depth > 0
19258               && context_stack[context_stack_depth - 1].name != NULL)
19259             SYMBOL_IS_ARGUMENT (sym) = 1;
19260           attr = dwarf2_attr (die, DW_AT_location, cu);
19261           if (attr)
19262             {
19263               var_decode_location (attr, sym, cu);
19264             }
19265           attr = dwarf2_attr (die, DW_AT_const_value, cu);
19266           if (attr)
19267             {
19268               dwarf2_const_value (attr, sym, cu);
19269             }
19270
19271           list_to_add = cu->list_in_scope;
19272           break;
19273         case DW_TAG_unspecified_parameters:
19274           /* From varargs functions; gdb doesn't seem to have any
19275              interest in this information, so just ignore it for now.
19276              (FIXME?) */
19277           break;
19278         case DW_TAG_template_type_param:
19279           suppress_add = 1;
19280           /* Fall through.  */
19281         case DW_TAG_class_type:
19282         case DW_TAG_interface_type:
19283         case DW_TAG_structure_type:
19284         case DW_TAG_union_type:
19285         case DW_TAG_set_type:
19286         case DW_TAG_enumeration_type:
19287           SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
19288           SYMBOL_DOMAIN (sym) = STRUCT_DOMAIN;
19289
19290           {
19291             /* NOTE: carlton/2003-11-10: C++ class symbols shouldn't
19292                really ever be static objects: otherwise, if you try
19293                to, say, break of a class's method and you're in a file
19294                which doesn't mention that class, it won't work unless
19295                the check for all static symbols in lookup_symbol_aux
19296                saves you.  See the OtherFileClass tests in
19297                gdb.c++/namespace.exp.  */
19298
19299             if (!suppress_add)
19300               {
19301                 list_to_add = (cu->list_in_scope == &file_symbols
19302                                && cu->language == language_cplus
19303                                ? &global_symbols : cu->list_in_scope);
19304
19305                 /* The semantics of C++ state that "struct foo {
19306                    ... }" also defines a typedef for "foo".  */
19307                 if (cu->language == language_cplus
19308                     || cu->language == language_ada
19309                     || cu->language == language_d
19310                     || cu->language == language_rust)
19311                   {
19312                     /* The symbol's name is already allocated along
19313                        with this objfile, so we don't need to
19314                        duplicate it for the type.  */
19315                     if (TYPE_NAME (SYMBOL_TYPE (sym)) == 0)
19316                       TYPE_NAME (SYMBOL_TYPE (sym)) = SYMBOL_SEARCH_NAME (sym);
19317                   }
19318               }
19319           }
19320           break;
19321         case DW_TAG_typedef:
19322           SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
19323           SYMBOL_DOMAIN (sym) = VAR_DOMAIN;
19324           list_to_add = cu->list_in_scope;
19325           break;
19326         case DW_TAG_base_type:
19327         case DW_TAG_subrange_type:
19328           SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
19329           SYMBOL_DOMAIN (sym) = VAR_DOMAIN;
19330           list_to_add = cu->list_in_scope;
19331           break;
19332         case DW_TAG_enumerator:
19333           attr = dwarf2_attr (die, DW_AT_const_value, cu);
19334           if (attr)
19335             {
19336               dwarf2_const_value (attr, sym, cu);
19337             }
19338           {
19339             /* NOTE: carlton/2003-11-10: See comment above in the
19340                DW_TAG_class_type, etc. block.  */
19341
19342             list_to_add = (cu->list_in_scope == &file_symbols
19343                            && cu->language == language_cplus
19344                            ? &global_symbols : cu->list_in_scope);
19345           }
19346           break;
19347         case DW_TAG_imported_declaration:
19348         case DW_TAG_namespace:
19349           SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
19350           list_to_add = &global_symbols;
19351           break;
19352         case DW_TAG_module:
19353           SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
19354           SYMBOL_DOMAIN (sym) = MODULE_DOMAIN;
19355           list_to_add = &global_symbols;
19356           break;
19357         case DW_TAG_common_block:
19358           SYMBOL_ACLASS_INDEX (sym) = LOC_COMMON_BLOCK;
19359           SYMBOL_DOMAIN (sym) = COMMON_BLOCK_DOMAIN;
19360           add_symbol_to_list (sym, cu->list_in_scope);
19361           break;
19362         default:
19363           /* Not a tag we recognize.  Hopefully we aren't processing
19364              trash data, but since we must specifically ignore things
19365              we don't recognize, there is nothing else we should do at
19366              this point.  */
19367           complaint (&symfile_complaints, _("unsupported tag: '%s'"),
19368                      dwarf_tag_name (die->tag));
19369           break;
19370         }
19371
19372       if (suppress_add)
19373         {
19374           sym->hash_next = objfile->template_symbols;
19375           objfile->template_symbols = sym;
19376           list_to_add = NULL;
19377         }
19378
19379       if (list_to_add != NULL)
19380         add_symbol_to_list (sym, list_to_add);
19381
19382       /* For the benefit of old versions of GCC, check for anonymous
19383          namespaces based on the demangled name.  */
19384       if (!cu->processing_has_namespace_info
19385           && cu->language == language_cplus)
19386         cp_scan_for_anonymous_namespaces (sym, objfile);
19387     }
19388   return (sym);
19389 }
19390
19391 /* A wrapper for new_symbol_full that always allocates a new symbol.  */
19392
19393 static struct symbol *
19394 new_symbol (struct die_info *die, struct type *type, struct dwarf2_cu *cu)
19395 {
19396   return new_symbol_full (die, type, cu, NULL);
19397 }
19398
19399 /* Given an attr with a DW_FORM_dataN value in host byte order,
19400    zero-extend it as appropriate for the symbol's type.  The DWARF
19401    standard (v4) is not entirely clear about the meaning of using
19402    DW_FORM_dataN for a constant with a signed type, where the type is
19403    wider than the data.  The conclusion of a discussion on the DWARF
19404    list was that this is unspecified.  We choose to always zero-extend
19405    because that is the interpretation long in use by GCC.  */
19406
19407 static gdb_byte *
19408 dwarf2_const_value_data (const struct attribute *attr, struct obstack *obstack,
19409                          struct dwarf2_cu *cu, LONGEST *value, int bits)
19410 {
19411   struct objfile *objfile = cu->objfile;
19412   enum bfd_endian byte_order = bfd_big_endian (objfile->obfd) ?
19413                                 BFD_ENDIAN_BIG : BFD_ENDIAN_LITTLE;
19414   LONGEST l = DW_UNSND (attr);
19415
19416   if (bits < sizeof (*value) * 8)
19417     {
19418       l &= ((LONGEST) 1 << bits) - 1;
19419       *value = l;
19420     }
19421   else if (bits == sizeof (*value) * 8)
19422     *value = l;
19423   else
19424     {
19425       gdb_byte *bytes = (gdb_byte *) obstack_alloc (obstack, bits / 8);
19426       store_unsigned_integer (bytes, bits / 8, byte_order, l);
19427       return bytes;
19428     }
19429
19430   return NULL;
19431 }
19432
19433 /* Read a constant value from an attribute.  Either set *VALUE, or if
19434    the value does not fit in *VALUE, set *BYTES - either already
19435    allocated on the objfile obstack, or newly allocated on OBSTACK,
19436    or, set *BATON, if we translated the constant to a location
19437    expression.  */
19438
19439 static void
19440 dwarf2_const_value_attr (const struct attribute *attr, struct type *type,
19441                          const char *name, struct obstack *obstack,
19442                          struct dwarf2_cu *cu,
19443                          LONGEST *value, const gdb_byte **bytes,
19444                          struct dwarf2_locexpr_baton **baton)
19445 {
19446   struct objfile *objfile = cu->objfile;
19447   struct comp_unit_head *cu_header = &cu->header;
19448   struct dwarf_block *blk;
19449   enum bfd_endian byte_order = (bfd_big_endian (objfile->obfd) ?
19450                                 BFD_ENDIAN_BIG : BFD_ENDIAN_LITTLE);
19451
19452   *value = 0;
19453   *bytes = NULL;
19454   *baton = NULL;
19455
19456   switch (attr->form)
19457     {
19458     case DW_FORM_addr:
19459     case DW_FORM_GNU_addr_index:
19460       {
19461         gdb_byte *data;
19462
19463         if (TYPE_LENGTH (type) != cu_header->addr_size)
19464           dwarf2_const_value_length_mismatch_complaint (name,
19465                                                         cu_header->addr_size,
19466                                                         TYPE_LENGTH (type));
19467         /* Symbols of this form are reasonably rare, so we just
19468            piggyback on the existing location code rather than writing
19469            a new implementation of symbol_computed_ops.  */
19470         *baton = XOBNEW (obstack, struct dwarf2_locexpr_baton);
19471         (*baton)->per_cu = cu->per_cu;
19472         gdb_assert ((*baton)->per_cu);
19473
19474         (*baton)->size = 2 + cu_header->addr_size;
19475         data = (gdb_byte *) obstack_alloc (obstack, (*baton)->size);
19476         (*baton)->data = data;
19477
19478         data[0] = DW_OP_addr;
19479         store_unsigned_integer (&data[1], cu_header->addr_size,
19480                                 byte_order, DW_ADDR (attr));
19481         data[cu_header->addr_size + 1] = DW_OP_stack_value;
19482       }
19483       break;
19484     case DW_FORM_string:
19485     case DW_FORM_strp:
19486     case DW_FORM_GNU_str_index:
19487     case DW_FORM_GNU_strp_alt:
19488       /* DW_STRING is already allocated on the objfile obstack, point
19489          directly to it.  */
19490       *bytes = (const gdb_byte *) DW_STRING (attr);
19491       break;
19492     case DW_FORM_block1:
19493     case DW_FORM_block2:
19494     case DW_FORM_block4:
19495     case DW_FORM_block:
19496     case DW_FORM_exprloc:
19497     case DW_FORM_data16:
19498       blk = DW_BLOCK (attr);
19499       if (TYPE_LENGTH (type) != blk->size)
19500         dwarf2_const_value_length_mismatch_complaint (name, blk->size,
19501                                                       TYPE_LENGTH (type));
19502       *bytes = blk->data;
19503       break;
19504
19505       /* The DW_AT_const_value attributes are supposed to carry the
19506          symbol's value "represented as it would be on the target
19507          architecture."  By the time we get here, it's already been
19508          converted to host endianness, so we just need to sign- or
19509          zero-extend it as appropriate.  */
19510     case DW_FORM_data1:
19511       *bytes = dwarf2_const_value_data (attr, obstack, cu, value, 8);
19512       break;
19513     case DW_FORM_data2:
19514       *bytes = dwarf2_const_value_data (attr, obstack, cu, value, 16);
19515       break;
19516     case DW_FORM_data4:
19517       *bytes = dwarf2_const_value_data (attr, obstack, cu, value, 32);
19518       break;
19519     case DW_FORM_data8:
19520       *bytes = dwarf2_const_value_data (attr, obstack, cu, value, 64);
19521       break;
19522
19523     case DW_FORM_sdata:
19524     case DW_FORM_implicit_const:
19525       *value = DW_SND (attr);
19526       break;
19527
19528     case DW_FORM_udata:
19529       *value = DW_UNSND (attr);
19530       break;
19531
19532     default:
19533       complaint (&symfile_complaints,
19534                  _("unsupported const value attribute form: '%s'"),
19535                  dwarf_form_name (attr->form));
19536       *value = 0;
19537       break;
19538     }
19539 }
19540
19541
19542 /* Copy constant value from an attribute to a symbol.  */
19543
19544 static void
19545 dwarf2_const_value (const struct attribute *attr, struct symbol *sym,
19546                     struct dwarf2_cu *cu)
19547 {
19548   struct objfile *objfile = cu->objfile;
19549   LONGEST value;
19550   const gdb_byte *bytes;
19551   struct dwarf2_locexpr_baton *baton;
19552
19553   dwarf2_const_value_attr (attr, SYMBOL_TYPE (sym),
19554                            SYMBOL_PRINT_NAME (sym),
19555                            &objfile->objfile_obstack, cu,
19556                            &value, &bytes, &baton);
19557
19558   if (baton != NULL)
19559     {
19560       SYMBOL_LOCATION_BATON (sym) = baton;
19561       SYMBOL_ACLASS_INDEX (sym) = dwarf2_locexpr_index;
19562     }
19563   else if (bytes != NULL)
19564      {
19565       SYMBOL_VALUE_BYTES (sym) = bytes;
19566       SYMBOL_ACLASS_INDEX (sym) = LOC_CONST_BYTES;
19567     }
19568   else
19569     {
19570       SYMBOL_VALUE (sym) = value;
19571       SYMBOL_ACLASS_INDEX (sym) = LOC_CONST;
19572     }
19573 }
19574
19575 /* Return the type of the die in question using its DW_AT_type attribute.  */
19576
19577 static struct type *
19578 die_type (struct die_info *die, struct dwarf2_cu *cu)
19579 {
19580   struct attribute *type_attr;
19581
19582   type_attr = dwarf2_attr (die, DW_AT_type, cu);
19583   if (!type_attr)
19584     {
19585       /* A missing DW_AT_type represents a void type.  */
19586       return objfile_type (cu->objfile)->builtin_void;
19587     }
19588
19589   return lookup_die_type (die, type_attr, cu);
19590 }
19591
19592 /* True iff CU's producer generates GNAT Ada auxiliary information
19593    that allows to find parallel types through that information instead
19594    of having to do expensive parallel lookups by type name.  */
19595
19596 static int
19597 need_gnat_info (struct dwarf2_cu *cu)
19598 {
19599   /* FIXME: brobecker/2010-10-12: As of now, only the AdaCore version
19600      of GNAT produces this auxiliary information, without any indication
19601      that it is produced.  Part of enhancing the FSF version of GNAT
19602      to produce that information will be to put in place an indicator
19603      that we can use in order to determine whether the descriptive type
19604      info is available or not.  One suggestion that has been made is
19605      to use a new attribute, attached to the CU die.  For now, assume
19606      that the descriptive type info is not available.  */
19607   return 0;
19608 }
19609
19610 /* Return the auxiliary type of the die in question using its
19611    DW_AT_GNAT_descriptive_type attribute.  Returns NULL if the
19612    attribute is not present.  */
19613
19614 static struct type *
19615 die_descriptive_type (struct die_info *die, struct dwarf2_cu *cu)
19616 {
19617   struct attribute *type_attr;
19618
19619   type_attr = dwarf2_attr (die, DW_AT_GNAT_descriptive_type, cu);
19620   if (!type_attr)
19621     return NULL;
19622
19623   return lookup_die_type (die, type_attr, cu);
19624 }
19625
19626 /* If DIE has a descriptive_type attribute, then set the TYPE's
19627    descriptive type accordingly.  */
19628
19629 static void
19630 set_descriptive_type (struct type *type, struct die_info *die,
19631                       struct dwarf2_cu *cu)
19632 {
19633   struct type *descriptive_type = die_descriptive_type (die, cu);
19634
19635   if (descriptive_type)
19636     {
19637       ALLOCATE_GNAT_AUX_TYPE (type);
19638       TYPE_DESCRIPTIVE_TYPE (type) = descriptive_type;
19639     }
19640 }
19641
19642 /* Return the containing type of the die in question using its
19643    DW_AT_containing_type attribute.  */
19644
19645 static struct type *
19646 die_containing_type (struct die_info *die, struct dwarf2_cu *cu)
19647 {
19648   struct attribute *type_attr;
19649
19650   type_attr = dwarf2_attr (die, DW_AT_containing_type, cu);
19651   if (!type_attr)
19652     error (_("Dwarf Error: Problem turning containing type into gdb type "
19653              "[in module %s]"), objfile_name (cu->objfile));
19654
19655   return lookup_die_type (die, type_attr, cu);
19656 }
19657
19658 /* Return an error marker type to use for the ill formed type in DIE/CU.  */
19659
19660 static struct type *
19661 build_error_marker_type (struct dwarf2_cu *cu, struct die_info *die)
19662 {
19663   struct objfile *objfile = dwarf2_per_objfile->objfile;
19664   char *message, *saved;
19665
19666   message = xstrprintf (_("<unknown type in %s, CU 0x%x, DIE 0x%x>"),
19667                         objfile_name (objfile),
19668                         to_underlying (cu->header.sect_off),
19669                         to_underlying (die->sect_off));
19670   saved = (char *) obstack_copy0 (&objfile->objfile_obstack,
19671                                   message, strlen (message));
19672   xfree (message);
19673
19674   return init_type (objfile, TYPE_CODE_ERROR, 0, saved);
19675 }
19676
19677 /* Look up the type of DIE in CU using its type attribute ATTR.
19678    ATTR must be one of: DW_AT_type, DW_AT_GNAT_descriptive_type,
19679    DW_AT_containing_type.
19680    If there is no type substitute an error marker.  */
19681
19682 static struct type *
19683 lookup_die_type (struct die_info *die, const struct attribute *attr,
19684                  struct dwarf2_cu *cu)
19685 {
19686   struct objfile *objfile = cu->objfile;
19687   struct type *this_type;
19688
19689   gdb_assert (attr->name == DW_AT_type
19690               || attr->name == DW_AT_GNAT_descriptive_type
19691               || attr->name == DW_AT_containing_type);
19692
19693   /* First see if we have it cached.  */
19694
19695   if (attr->form == DW_FORM_GNU_ref_alt)
19696     {
19697       struct dwarf2_per_cu_data *per_cu;
19698       sect_offset sect_off = dwarf2_get_ref_die_offset (attr);
19699
19700       per_cu = dwarf2_find_containing_comp_unit (sect_off, 1, cu->objfile);
19701       this_type = get_die_type_at_offset (sect_off, per_cu);
19702     }
19703   else if (attr_form_is_ref (attr))
19704     {
19705       sect_offset sect_off = dwarf2_get_ref_die_offset (attr);
19706
19707       this_type = get_die_type_at_offset (sect_off, cu->per_cu);
19708     }
19709   else if (attr->form == DW_FORM_ref_sig8)
19710     {
19711       ULONGEST signature = DW_SIGNATURE (attr);
19712
19713       return get_signatured_type (die, signature, cu);
19714     }
19715   else
19716     {
19717       complaint (&symfile_complaints,
19718                  _("Dwarf Error: Bad type attribute %s in DIE"
19719                    " at 0x%x [in module %s]"),
19720                  dwarf_attr_name (attr->name), to_underlying (die->sect_off),
19721                  objfile_name (objfile));
19722       return build_error_marker_type (cu, die);
19723     }
19724
19725   /* If not cached we need to read it in.  */
19726
19727   if (this_type == NULL)
19728     {
19729       struct die_info *type_die = NULL;
19730       struct dwarf2_cu *type_cu = cu;
19731
19732       if (attr_form_is_ref (attr))
19733         type_die = follow_die_ref (die, attr, &type_cu);
19734       if (type_die == NULL)
19735         return build_error_marker_type (cu, die);
19736       /* If we find the type now, it's probably because the type came
19737          from an inter-CU reference and the type's CU got expanded before
19738          ours.  */
19739       this_type = read_type_die (type_die, type_cu);
19740     }
19741
19742   /* If we still don't have a type use an error marker.  */
19743
19744   if (this_type == NULL)
19745     return build_error_marker_type (cu, die);
19746
19747   return this_type;
19748 }
19749
19750 /* Return the type in DIE, CU.
19751    Returns NULL for invalid types.
19752
19753    This first does a lookup in die_type_hash,
19754    and only reads the die in if necessary.
19755
19756    NOTE: This can be called when reading in partial or full symbols.  */
19757
19758 static struct type *
19759 read_type_die (struct die_info *die, struct dwarf2_cu *cu)
19760 {
19761   struct type *this_type;
19762
19763   this_type = get_die_type (die, cu);
19764   if (this_type)
19765     return this_type;
19766
19767   return read_type_die_1 (die, cu);
19768 }
19769
19770 /* Read the type in DIE, CU.
19771    Returns NULL for invalid types.  */
19772
19773 static struct type *
19774 read_type_die_1 (struct die_info *die, struct dwarf2_cu *cu)
19775 {
19776   struct type *this_type = NULL;
19777
19778   switch (die->tag)
19779     {
19780     case DW_TAG_class_type:
19781     case DW_TAG_interface_type:
19782     case DW_TAG_structure_type:
19783     case DW_TAG_union_type:
19784       this_type = read_structure_type (die, cu);
19785       break;
19786     case DW_TAG_enumeration_type:
19787       this_type = read_enumeration_type (die, cu);
19788       break;
19789     case DW_TAG_subprogram:
19790     case DW_TAG_subroutine_type:
19791     case DW_TAG_inlined_subroutine:
19792       this_type = read_subroutine_type (die, cu);
19793       break;
19794     case DW_TAG_array_type:
19795       this_type = read_array_type (die, cu);
19796       break;
19797     case DW_TAG_set_type:
19798       this_type = read_set_type (die, cu);
19799       break;
19800     case DW_TAG_pointer_type:
19801       this_type = read_tag_pointer_type (die, cu);
19802       break;
19803     case DW_TAG_ptr_to_member_type:
19804       this_type = read_tag_ptr_to_member_type (die, cu);
19805       break;
19806     case DW_TAG_reference_type:
19807       this_type = read_tag_reference_type (die, cu, TYPE_CODE_REF);
19808       break;
19809     case DW_TAG_rvalue_reference_type:
19810       this_type = read_tag_reference_type (die, cu, TYPE_CODE_RVALUE_REF);
19811       break;
19812     case DW_TAG_const_type:
19813       this_type = read_tag_const_type (die, cu);
19814       break;
19815     case DW_TAG_volatile_type:
19816       this_type = read_tag_volatile_type (die, cu);
19817       break;
19818     case DW_TAG_restrict_type:
19819       this_type = read_tag_restrict_type (die, cu);
19820       break;
19821     case DW_TAG_string_type:
19822       this_type = read_tag_string_type (die, cu);
19823       break;
19824     case DW_TAG_typedef:
19825       this_type = read_typedef (die, cu);
19826       break;
19827     case DW_TAG_subrange_type:
19828       this_type = read_subrange_type (die, cu);
19829       break;
19830     case DW_TAG_base_type:
19831       this_type = read_base_type (die, cu);
19832       break;
19833     case DW_TAG_unspecified_type:
19834       this_type = read_unspecified_type (die, cu);
19835       break;
19836     case DW_TAG_namespace:
19837       this_type = read_namespace_type (die, cu);
19838       break;
19839     case DW_TAG_module:
19840       this_type = read_module_type (die, cu);
19841       break;
19842     case DW_TAG_atomic_type:
19843       this_type = read_tag_atomic_type (die, cu);
19844       break;
19845     default:
19846       complaint (&symfile_complaints,
19847                  _("unexpected tag in read_type_die: '%s'"),
19848                  dwarf_tag_name (die->tag));
19849       break;
19850     }
19851
19852   return this_type;
19853 }
19854
19855 /* See if we can figure out if the class lives in a namespace.  We do
19856    this by looking for a member function; its demangled name will
19857    contain namespace info, if there is any.
19858    Return the computed name or NULL.
19859    Space for the result is allocated on the objfile's obstack.
19860    This is the full-die version of guess_partial_die_structure_name.
19861    In this case we know DIE has no useful parent.  */
19862
19863 static char *
19864 guess_full_die_structure_name (struct die_info *die, struct dwarf2_cu *cu)
19865 {
19866   struct die_info *spec_die;
19867   struct dwarf2_cu *spec_cu;
19868   struct die_info *child;
19869
19870   spec_cu = cu;
19871   spec_die = die_specification (die, &spec_cu);
19872   if (spec_die != NULL)
19873     {
19874       die = spec_die;
19875       cu = spec_cu;
19876     }
19877
19878   for (child = die->child;
19879        child != NULL;
19880        child = child->sibling)
19881     {
19882       if (child->tag == DW_TAG_subprogram)
19883         {
19884           const char *linkage_name;
19885
19886           linkage_name = dwarf2_string_attr (child, DW_AT_linkage_name, cu);
19887           if (linkage_name == NULL)
19888             linkage_name = dwarf2_string_attr (child, DW_AT_MIPS_linkage_name,
19889                                                cu);
19890           if (linkage_name != NULL)
19891             {
19892               char *actual_name
19893                 = language_class_name_from_physname (cu->language_defn,
19894                                                      linkage_name);
19895               char *name = NULL;
19896
19897               if (actual_name != NULL)
19898                 {
19899                   const char *die_name = dwarf2_name (die, cu);
19900
19901                   if (die_name != NULL
19902                       && strcmp (die_name, actual_name) != 0)
19903                     {
19904                       /* Strip off the class name from the full name.
19905                          We want the prefix.  */
19906                       int die_name_len = strlen (die_name);
19907                       int actual_name_len = strlen (actual_name);
19908
19909                       /* Test for '::' as a sanity check.  */
19910                       if (actual_name_len > die_name_len + 2
19911                           && actual_name[actual_name_len
19912                                          - die_name_len - 1] == ':')
19913                         name = (char *) obstack_copy0 (
19914                           &cu->objfile->per_bfd->storage_obstack,
19915                           actual_name, actual_name_len - die_name_len - 2);
19916                     }
19917                 }
19918               xfree (actual_name);
19919               return name;
19920             }
19921         }
19922     }
19923
19924   return NULL;
19925 }
19926
19927 /* GCC might emit a nameless typedef that has a linkage name.  Determine the
19928    prefix part in such case.  See
19929    http://gcc.gnu.org/bugzilla/show_bug.cgi?id=47510.  */
19930
19931 static const char *
19932 anonymous_struct_prefix (struct die_info *die, struct dwarf2_cu *cu)
19933 {
19934   struct attribute *attr;
19935   const char *base;
19936
19937   if (die->tag != DW_TAG_class_type && die->tag != DW_TAG_interface_type
19938       && die->tag != DW_TAG_structure_type && die->tag != DW_TAG_union_type)
19939     return NULL;
19940
19941   if (dwarf2_string_attr (die, DW_AT_name, cu) != NULL)
19942     return NULL;
19943
19944   attr = dwarf2_attr (die, DW_AT_linkage_name, cu);
19945   if (attr == NULL)
19946     attr = dwarf2_attr (die, DW_AT_MIPS_linkage_name, cu);
19947   if (attr == NULL || DW_STRING (attr) == NULL)
19948     return NULL;
19949
19950   /* dwarf2_name had to be already called.  */
19951   gdb_assert (DW_STRING_IS_CANONICAL (attr));
19952
19953   /* Strip the base name, keep any leading namespaces/classes.  */
19954   base = strrchr (DW_STRING (attr), ':');
19955   if (base == NULL || base == DW_STRING (attr) || base[-1] != ':')
19956     return "";
19957
19958   return (char *) obstack_copy0 (&cu->objfile->per_bfd->storage_obstack,
19959                                  DW_STRING (attr),
19960                                  &base[-1] - DW_STRING (attr));
19961 }
19962
19963 /* Return the name of the namespace/class that DIE is defined within,
19964    or "" if we can't tell.  The caller should not xfree the result.
19965
19966    For example, if we're within the method foo() in the following
19967    code:
19968
19969    namespace N {
19970      class C {
19971        void foo () {
19972        }
19973      };
19974    }
19975
19976    then determine_prefix on foo's die will return "N::C".  */
19977
19978 static const char *
19979 determine_prefix (struct die_info *die, struct dwarf2_cu *cu)
19980 {
19981   struct die_info *parent, *spec_die;
19982   struct dwarf2_cu *spec_cu;
19983   struct type *parent_type;
19984   const char *retval;
19985
19986   if (cu->language != language_cplus
19987       && cu->language != language_fortran && cu->language != language_d
19988       && cu->language != language_rust)
19989     return "";
19990
19991   retval = anonymous_struct_prefix (die, cu);
19992   if (retval)
19993     return retval;
19994
19995   /* We have to be careful in the presence of DW_AT_specification.
19996      For example, with GCC 3.4, given the code
19997
19998      namespace N {
19999        void foo() {
20000          // Definition of N::foo.
20001        }
20002      }
20003
20004      then we'll have a tree of DIEs like this:
20005
20006      1: DW_TAG_compile_unit
20007        2: DW_TAG_namespace        // N
20008          3: DW_TAG_subprogram     // declaration of N::foo
20009        4: DW_TAG_subprogram       // definition of N::foo
20010             DW_AT_specification   // refers to die #3
20011
20012      Thus, when processing die #4, we have to pretend that we're in
20013      the context of its DW_AT_specification, namely the contex of die
20014      #3.  */
20015   spec_cu = cu;
20016   spec_die = die_specification (die, &spec_cu);
20017   if (spec_die == NULL)
20018     parent = die->parent;
20019   else
20020     {
20021       parent = spec_die->parent;
20022       cu = spec_cu;
20023     }
20024
20025   if (parent == NULL)
20026     return "";
20027   else if (parent->building_fullname)
20028     {
20029       const char *name;
20030       const char *parent_name;
20031
20032       /* It has been seen on RealView 2.2 built binaries,
20033          DW_TAG_template_type_param types actually _defined_ as
20034          children of the parent class:
20035
20036          enum E {};
20037          template class <class Enum> Class{};
20038          Class<enum E> class_e;
20039
20040          1: DW_TAG_class_type (Class)
20041            2: DW_TAG_enumeration_type (E)
20042              3: DW_TAG_enumerator (enum1:0)
20043              3: DW_TAG_enumerator (enum2:1)
20044              ...
20045            2: DW_TAG_template_type_param
20046               DW_AT_type  DW_FORM_ref_udata (E)
20047
20048          Besides being broken debug info, it can put GDB into an
20049          infinite loop.  Consider:
20050
20051          When we're building the full name for Class<E>, we'll start
20052          at Class, and go look over its template type parameters,
20053          finding E.  We'll then try to build the full name of E, and
20054          reach here.  We're now trying to build the full name of E,
20055          and look over the parent DIE for containing scope.  In the
20056          broken case, if we followed the parent DIE of E, we'd again
20057          find Class, and once again go look at its template type
20058          arguments, etc., etc.  Simply don't consider such parent die
20059          as source-level parent of this die (it can't be, the language
20060          doesn't allow it), and break the loop here.  */
20061       name = dwarf2_name (die, cu);
20062       parent_name = dwarf2_name (parent, cu);
20063       complaint (&symfile_complaints,
20064                  _("template param type '%s' defined within parent '%s'"),
20065                  name ? name : "<unknown>",
20066                  parent_name ? parent_name : "<unknown>");
20067       return "";
20068     }
20069   else
20070     switch (parent->tag)
20071       {
20072       case DW_TAG_namespace:
20073         parent_type = read_type_die (parent, cu);
20074         /* GCC 4.0 and 4.1 had a bug (PR c++/28460) where they generated bogus
20075            DW_TAG_namespace DIEs with a name of "::" for the global namespace.
20076            Work around this problem here.  */
20077         if (cu->language == language_cplus
20078             && strcmp (TYPE_TAG_NAME (parent_type), "::") == 0)
20079           return "";
20080         /* We give a name to even anonymous namespaces.  */
20081         return TYPE_TAG_NAME (parent_type);
20082       case DW_TAG_class_type:
20083       case DW_TAG_interface_type:
20084       case DW_TAG_structure_type:
20085       case DW_TAG_union_type:
20086       case DW_TAG_module:
20087         parent_type = read_type_die (parent, cu);
20088         if (TYPE_TAG_NAME (parent_type) != NULL)
20089           return TYPE_TAG_NAME (parent_type);
20090         else
20091           /* An anonymous structure is only allowed non-static data
20092              members; no typedefs, no member functions, et cetera.
20093              So it does not need a prefix.  */
20094           return "";
20095       case DW_TAG_compile_unit:
20096       case DW_TAG_partial_unit:
20097         /* gcc-4.5 -gdwarf-4 can drop the enclosing namespace.  Cope.  */
20098         if (cu->language == language_cplus
20099             && !VEC_empty (dwarf2_section_info_def, dwarf2_per_objfile->types)
20100             && die->child != NULL
20101             && (die->tag == DW_TAG_class_type
20102                 || die->tag == DW_TAG_structure_type
20103                 || die->tag == DW_TAG_union_type))
20104           {
20105             char *name = guess_full_die_structure_name (die, cu);
20106             if (name != NULL)
20107               return name;
20108           }
20109         return "";
20110       case DW_TAG_enumeration_type:
20111         parent_type = read_type_die (parent, cu);
20112         if (TYPE_DECLARED_CLASS (parent_type))
20113           {
20114             if (TYPE_TAG_NAME (parent_type) != NULL)
20115               return TYPE_TAG_NAME (parent_type);
20116             return "";
20117           }
20118         /* Fall through.  */
20119       default:
20120         return determine_prefix (parent, cu);
20121       }
20122 }
20123
20124 /* Return a newly-allocated string formed by concatenating PREFIX and SUFFIX
20125    with appropriate separator.  If PREFIX or SUFFIX is NULL or empty, then
20126    simply copy the SUFFIX or PREFIX, respectively.  If OBS is non-null, perform
20127    an obconcat, otherwise allocate storage for the result.  The CU argument is
20128    used to determine the language and hence, the appropriate separator.  */
20129
20130 #define MAX_SEP_LEN 7  /* strlen ("__") + strlen ("_MOD_")  */
20131
20132 static char *
20133 typename_concat (struct obstack *obs, const char *prefix, const char *suffix,
20134                  int physname, struct dwarf2_cu *cu)
20135 {
20136   const char *lead = "";
20137   const char *sep;
20138
20139   if (suffix == NULL || suffix[0] == '\0'
20140       || prefix == NULL || prefix[0] == '\0')
20141     sep = "";
20142   else if (cu->language == language_d)
20143     {
20144       /* For D, the 'main' function could be defined in any module, but it
20145          should never be prefixed.  */
20146       if (strcmp (suffix, "D main") == 0)
20147         {
20148           prefix = "";
20149           sep = "";
20150         }
20151       else
20152         sep = ".";
20153     }
20154   else if (cu->language == language_fortran && physname)
20155     {
20156       /* This is gfortran specific mangling.  Normally DW_AT_linkage_name or
20157          DW_AT_MIPS_linkage_name is preferred and used instead.  */
20158
20159       lead = "__";
20160       sep = "_MOD_";
20161     }
20162   else
20163     sep = "::";
20164
20165   if (prefix == NULL)
20166     prefix = "";
20167   if (suffix == NULL)
20168     suffix = "";
20169
20170   if (obs == NULL)
20171     {
20172       char *retval
20173         = ((char *)
20174            xmalloc (strlen (prefix) + MAX_SEP_LEN + strlen (suffix) + 1));
20175
20176       strcpy (retval, lead);
20177       strcat (retval, prefix);
20178       strcat (retval, sep);
20179       strcat (retval, suffix);
20180       return retval;
20181     }
20182   else
20183     {
20184       /* We have an obstack.  */
20185       return obconcat (obs, lead, prefix, sep, suffix, (char *) NULL);
20186     }
20187 }
20188
20189 /* Return sibling of die, NULL if no sibling.  */
20190
20191 static struct die_info *
20192 sibling_die (struct die_info *die)
20193 {
20194   return die->sibling;
20195 }
20196
20197 /* Get name of a die, return NULL if not found.  */
20198
20199 static const char *
20200 dwarf2_canonicalize_name (const char *name, struct dwarf2_cu *cu,
20201                           struct obstack *obstack)
20202 {
20203   if (name && cu->language == language_cplus)
20204     {
20205       std::string canon_name = cp_canonicalize_string (name);
20206
20207       if (!canon_name.empty ())
20208         {
20209           if (canon_name != name)
20210             name = (const char *) obstack_copy0 (obstack,
20211                                                  canon_name.c_str (),
20212                                                  canon_name.length ());
20213         }
20214     }
20215
20216   return name;
20217 }
20218
20219 /* Get name of a die, return NULL if not found.
20220    Anonymous namespaces are converted to their magic string.  */
20221
20222 static const char *
20223 dwarf2_name (struct die_info *die, struct dwarf2_cu *cu)
20224 {
20225   struct attribute *attr;
20226
20227   attr = dwarf2_attr (die, DW_AT_name, cu);
20228   if ((!attr || !DW_STRING (attr))
20229       && die->tag != DW_TAG_namespace
20230       && die->tag != DW_TAG_class_type
20231       && die->tag != DW_TAG_interface_type
20232       && die->tag != DW_TAG_structure_type
20233       && die->tag != DW_TAG_union_type)
20234     return NULL;
20235
20236   switch (die->tag)
20237     {
20238     case DW_TAG_compile_unit:
20239     case DW_TAG_partial_unit:
20240       /* Compilation units have a DW_AT_name that is a filename, not
20241          a source language identifier.  */
20242     case DW_TAG_enumeration_type:
20243     case DW_TAG_enumerator:
20244       /* These tags always have simple identifiers already; no need
20245          to canonicalize them.  */
20246       return DW_STRING (attr);
20247
20248     case DW_TAG_namespace:
20249       if (attr != NULL && DW_STRING (attr) != NULL)
20250         return DW_STRING (attr);
20251       return CP_ANONYMOUS_NAMESPACE_STR;
20252
20253     case DW_TAG_class_type:
20254     case DW_TAG_interface_type:
20255     case DW_TAG_structure_type:
20256     case DW_TAG_union_type:
20257       /* Some GCC versions emit spurious DW_AT_name attributes for unnamed
20258          structures or unions.  These were of the form "._%d" in GCC 4.1,
20259          or simply "<anonymous struct>" or "<anonymous union>" in GCC 4.3
20260          and GCC 4.4.  We work around this problem by ignoring these.  */
20261       if (attr && DW_STRING (attr)
20262           && (startswith (DW_STRING (attr), "._")
20263               || startswith (DW_STRING (attr), "<anonymous")))
20264         return NULL;
20265
20266       /* GCC might emit a nameless typedef that has a linkage name.  See
20267          http://gcc.gnu.org/bugzilla/show_bug.cgi?id=47510.  */
20268       if (!attr || DW_STRING (attr) == NULL)
20269         {
20270           char *demangled = NULL;
20271
20272           attr = dwarf2_attr (die, DW_AT_linkage_name, cu);
20273           if (attr == NULL)
20274             attr = dwarf2_attr (die, DW_AT_MIPS_linkage_name, cu);
20275
20276           if (attr == NULL || DW_STRING (attr) == NULL)
20277             return NULL;
20278
20279           /* Avoid demangling DW_STRING (attr) the second time on a second
20280              call for the same DIE.  */
20281           if (!DW_STRING_IS_CANONICAL (attr))
20282             demangled = gdb_demangle (DW_STRING (attr), DMGL_TYPES);
20283
20284           if (demangled)
20285             {
20286               const char *base;
20287
20288               /* FIXME: we already did this for the partial symbol... */
20289               DW_STRING (attr)
20290                 = ((const char *)
20291                    obstack_copy0 (&cu->objfile->per_bfd->storage_obstack,
20292                                   demangled, strlen (demangled)));
20293               DW_STRING_IS_CANONICAL (attr) = 1;
20294               xfree (demangled);
20295
20296               /* Strip any leading namespaces/classes, keep only the base name.
20297                  DW_AT_name for named DIEs does not contain the prefixes.  */
20298               base = strrchr (DW_STRING (attr), ':');
20299               if (base && base > DW_STRING (attr) && base[-1] == ':')
20300                 return &base[1];
20301               else
20302                 return DW_STRING (attr);
20303             }
20304         }
20305       break;
20306
20307     default:
20308       break;
20309     }
20310
20311   if (!DW_STRING_IS_CANONICAL (attr))
20312     {
20313       DW_STRING (attr)
20314         = dwarf2_canonicalize_name (DW_STRING (attr), cu,
20315                                     &cu->objfile->per_bfd->storage_obstack);
20316       DW_STRING_IS_CANONICAL (attr) = 1;
20317     }
20318   return DW_STRING (attr);
20319 }
20320
20321 /* Return the die that this die in an extension of, or NULL if there
20322    is none.  *EXT_CU is the CU containing DIE on input, and the CU
20323    containing the return value on output.  */
20324
20325 static struct die_info *
20326 dwarf2_extension (struct die_info *die, struct dwarf2_cu **ext_cu)
20327 {
20328   struct attribute *attr;
20329
20330   attr = dwarf2_attr (die, DW_AT_extension, *ext_cu);
20331   if (attr == NULL)
20332     return NULL;
20333
20334   return follow_die_ref (die, attr, ext_cu);
20335 }
20336
20337 /* Convert a DIE tag into its string name.  */
20338
20339 static const char *
20340 dwarf_tag_name (unsigned tag)
20341 {
20342   const char *name = get_DW_TAG_name (tag);
20343
20344   if (name == NULL)
20345     return "DW_TAG_<unknown>";
20346
20347   return name;
20348 }
20349
20350 /* Convert a DWARF attribute code into its string name.  */
20351
20352 static const char *
20353 dwarf_attr_name (unsigned attr)
20354 {
20355   const char *name;
20356
20357 #ifdef MIPS /* collides with DW_AT_HP_block_index */
20358   if (attr == DW_AT_MIPS_fde)
20359     return "DW_AT_MIPS_fde";
20360 #else
20361   if (attr == DW_AT_HP_block_index)
20362     return "DW_AT_HP_block_index";
20363 #endif
20364
20365   name = get_DW_AT_name (attr);
20366
20367   if (name == NULL)
20368     return "DW_AT_<unknown>";
20369
20370   return name;
20371 }
20372
20373 /* Convert a DWARF value form code into its string name.  */
20374
20375 static const char *
20376 dwarf_form_name (unsigned form)
20377 {
20378   const char *name = get_DW_FORM_name (form);
20379
20380   if (name == NULL)
20381     return "DW_FORM_<unknown>";
20382
20383   return name;
20384 }
20385
20386 static const char *
20387 dwarf_bool_name (unsigned mybool)
20388 {
20389   if (mybool)
20390     return "TRUE";
20391   else
20392     return "FALSE";
20393 }
20394
20395 /* Convert a DWARF type code into its string name.  */
20396
20397 static const char *
20398 dwarf_type_encoding_name (unsigned enc)
20399 {
20400   const char *name = get_DW_ATE_name (enc);
20401
20402   if (name == NULL)
20403     return "DW_ATE_<unknown>";
20404
20405   return name;
20406 }
20407
20408 static void
20409 dump_die_shallow (struct ui_file *f, int indent, struct die_info *die)
20410 {
20411   unsigned int i;
20412
20413   print_spaces (indent, f);
20414   fprintf_unfiltered (f, "Die: %s (abbrev %d, offset 0x%x)\n",
20415                       dwarf_tag_name (die->tag), die->abbrev,
20416                       to_underlying (die->sect_off));
20417
20418   if (die->parent != NULL)
20419     {
20420       print_spaces (indent, f);
20421       fprintf_unfiltered (f, "  parent at offset: 0x%x\n",
20422                           to_underlying (die->parent->sect_off));
20423     }
20424
20425   print_spaces (indent, f);
20426   fprintf_unfiltered (f, "  has children: %s\n",
20427            dwarf_bool_name (die->child != NULL));
20428
20429   print_spaces (indent, f);
20430   fprintf_unfiltered (f, "  attributes:\n");
20431
20432   for (i = 0; i < die->num_attrs; ++i)
20433     {
20434       print_spaces (indent, f);
20435       fprintf_unfiltered (f, "    %s (%s) ",
20436                dwarf_attr_name (die->attrs[i].name),
20437                dwarf_form_name (die->attrs[i].form));
20438
20439       switch (die->attrs[i].form)
20440         {
20441         case DW_FORM_addr:
20442         case DW_FORM_GNU_addr_index:
20443           fprintf_unfiltered (f, "address: ");
20444           fputs_filtered (hex_string (DW_ADDR (&die->attrs[i])), f);
20445           break;
20446         case DW_FORM_block2:
20447         case DW_FORM_block4:
20448         case DW_FORM_block:
20449         case DW_FORM_block1:
20450           fprintf_unfiltered (f, "block: size %s",
20451                               pulongest (DW_BLOCK (&die->attrs[i])->size));
20452           break;
20453         case DW_FORM_exprloc:
20454           fprintf_unfiltered (f, "expression: size %s",
20455                               pulongest (DW_BLOCK (&die->attrs[i])->size));
20456           break;
20457         case DW_FORM_data16:
20458           fprintf_unfiltered (f, "constant of 16 bytes");
20459           break;
20460         case DW_FORM_ref_addr:
20461           fprintf_unfiltered (f, "ref address: ");
20462           fputs_filtered (hex_string (DW_UNSND (&die->attrs[i])), f);
20463           break;
20464         case DW_FORM_GNU_ref_alt:
20465           fprintf_unfiltered (f, "alt ref address: ");
20466           fputs_filtered (hex_string (DW_UNSND (&die->attrs[i])), f);
20467           break;
20468         case DW_FORM_ref1:
20469         case DW_FORM_ref2:
20470         case DW_FORM_ref4:
20471         case DW_FORM_ref8:
20472         case DW_FORM_ref_udata:
20473           fprintf_unfiltered (f, "constant ref: 0x%lx (adjusted)",
20474                               (long) (DW_UNSND (&die->attrs[i])));
20475           break;
20476         case DW_FORM_data1:
20477         case DW_FORM_data2:
20478         case DW_FORM_data4:
20479         case DW_FORM_data8:
20480         case DW_FORM_udata:
20481         case DW_FORM_sdata:
20482           fprintf_unfiltered (f, "constant: %s",
20483                               pulongest (DW_UNSND (&die->attrs[i])));
20484           break;
20485         case DW_FORM_sec_offset:
20486           fprintf_unfiltered (f, "section offset: %s",
20487                               pulongest (DW_UNSND (&die->attrs[i])));
20488           break;
20489         case DW_FORM_ref_sig8:
20490           fprintf_unfiltered (f, "signature: %s",
20491                               hex_string (DW_SIGNATURE (&die->attrs[i])));
20492           break;
20493         case DW_FORM_string:
20494         case DW_FORM_strp:
20495         case DW_FORM_line_strp:
20496         case DW_FORM_GNU_str_index:
20497         case DW_FORM_GNU_strp_alt:
20498           fprintf_unfiltered (f, "string: \"%s\" (%s canonicalized)",
20499                    DW_STRING (&die->attrs[i])
20500                    ? DW_STRING (&die->attrs[i]) : "",
20501                    DW_STRING_IS_CANONICAL (&die->attrs[i]) ? "is" : "not");
20502           break;
20503         case DW_FORM_flag:
20504           if (DW_UNSND (&die->attrs[i]))
20505             fprintf_unfiltered (f, "flag: TRUE");
20506           else
20507             fprintf_unfiltered (f, "flag: FALSE");
20508           break;
20509         case DW_FORM_flag_present:
20510           fprintf_unfiltered (f, "flag: TRUE");
20511           break;
20512         case DW_FORM_indirect:
20513           /* The reader will have reduced the indirect form to
20514              the "base form" so this form should not occur.  */
20515           fprintf_unfiltered (f, 
20516                               "unexpected attribute form: DW_FORM_indirect");
20517           break;
20518         case DW_FORM_implicit_const:
20519           fprintf_unfiltered (f, "constant: %s",
20520                               plongest (DW_SND (&die->attrs[i])));
20521           break;
20522         default:
20523           fprintf_unfiltered (f, "unsupported attribute form: %d.",
20524                    die->attrs[i].form);
20525           break;
20526         }
20527       fprintf_unfiltered (f, "\n");
20528     }
20529 }
20530
20531 static void
20532 dump_die_for_error (struct die_info *die)
20533 {
20534   dump_die_shallow (gdb_stderr, 0, die);
20535 }
20536
20537 static void
20538 dump_die_1 (struct ui_file *f, int level, int max_level, struct die_info *die)
20539 {
20540   int indent = level * 4;
20541
20542   gdb_assert (die != NULL);
20543
20544   if (level >= max_level)
20545     return;
20546
20547   dump_die_shallow (f, indent, die);
20548
20549   if (die->child != NULL)
20550     {
20551       print_spaces (indent, f);
20552       fprintf_unfiltered (f, "  Children:");
20553       if (level + 1 < max_level)
20554         {
20555           fprintf_unfiltered (f, "\n");
20556           dump_die_1 (f, level + 1, max_level, die->child);
20557         }
20558       else
20559         {
20560           fprintf_unfiltered (f,
20561                               " [not printed, max nesting level reached]\n");
20562         }
20563     }
20564
20565   if (die->sibling != NULL && level > 0)
20566     {
20567       dump_die_1 (f, level, max_level, die->sibling);
20568     }
20569 }
20570
20571 /* This is called from the pdie macro in gdbinit.in.
20572    It's not static so gcc will keep a copy callable from gdb.  */
20573
20574 void
20575 dump_die (struct die_info *die, int max_level)
20576 {
20577   dump_die_1 (gdb_stdlog, 0, max_level, die);
20578 }
20579
20580 static void
20581 store_in_ref_table (struct die_info *die, struct dwarf2_cu *cu)
20582 {
20583   void **slot;
20584
20585   slot = htab_find_slot_with_hash (cu->die_hash, die,
20586                                    to_underlying (die->sect_off),
20587                                    INSERT);
20588
20589   *slot = die;
20590 }
20591
20592 /* Return DIE offset of ATTR.  Return 0 with complaint if ATTR is not of the
20593    required kind.  */
20594
20595 static sect_offset
20596 dwarf2_get_ref_die_offset (const struct attribute *attr)
20597 {
20598   if (attr_form_is_ref (attr))
20599     return (sect_offset) DW_UNSND (attr);
20600
20601   complaint (&symfile_complaints,
20602              _("unsupported die ref attribute form: '%s'"),
20603              dwarf_form_name (attr->form));
20604   return {};
20605 }
20606
20607 /* Return the constant value held by ATTR.  Return DEFAULT_VALUE if
20608  * the value held by the attribute is not constant.  */
20609
20610 static LONGEST
20611 dwarf2_get_attr_constant_value (const struct attribute *attr, int default_value)
20612 {
20613   if (attr->form == DW_FORM_sdata || attr->form == DW_FORM_implicit_const)
20614     return DW_SND (attr);
20615   else if (attr->form == DW_FORM_udata
20616            || attr->form == DW_FORM_data1
20617            || attr->form == DW_FORM_data2
20618            || attr->form == DW_FORM_data4
20619            || attr->form == DW_FORM_data8)
20620     return DW_UNSND (attr);
20621   else
20622     {
20623       /* For DW_FORM_data16 see attr_form_is_constant.  */
20624       complaint (&symfile_complaints,
20625                  _("Attribute value is not a constant (%s)"),
20626                  dwarf_form_name (attr->form));
20627       return default_value;
20628     }
20629 }
20630
20631 /* Follow reference or signature attribute ATTR of SRC_DIE.
20632    On entry *REF_CU is the CU of SRC_DIE.
20633    On exit *REF_CU is the CU of the result.  */
20634
20635 static struct die_info *
20636 follow_die_ref_or_sig (struct die_info *src_die, const struct attribute *attr,
20637                        struct dwarf2_cu **ref_cu)
20638 {
20639   struct die_info *die;
20640
20641   if (attr_form_is_ref (attr))
20642     die = follow_die_ref (src_die, attr, ref_cu);
20643   else if (attr->form == DW_FORM_ref_sig8)
20644     die = follow_die_sig (src_die, attr, ref_cu);
20645   else
20646     {
20647       dump_die_for_error (src_die);
20648       error (_("Dwarf Error: Expected reference attribute [in module %s]"),
20649              objfile_name ((*ref_cu)->objfile));
20650     }
20651
20652   return die;
20653 }
20654
20655 /* Follow reference OFFSET.
20656    On entry *REF_CU is the CU of the source die referencing OFFSET.
20657    On exit *REF_CU is the CU of the result.
20658    Returns NULL if OFFSET is invalid.  */
20659
20660 static struct die_info *
20661 follow_die_offset (sect_offset sect_off, int offset_in_dwz,
20662                    struct dwarf2_cu **ref_cu)
20663 {
20664   struct die_info temp_die;
20665   struct dwarf2_cu *target_cu, *cu = *ref_cu;
20666
20667   gdb_assert (cu->per_cu != NULL);
20668
20669   target_cu = cu;
20670
20671   if (cu->per_cu->is_debug_types)
20672     {
20673       /* .debug_types CUs cannot reference anything outside their CU.
20674          If they need to, they have to reference a signatured type via
20675          DW_FORM_ref_sig8.  */
20676       if (!offset_in_cu_p (&cu->header, sect_off))
20677         return NULL;
20678     }
20679   else if (offset_in_dwz != cu->per_cu->is_dwz
20680            || !offset_in_cu_p (&cu->header, sect_off))
20681     {
20682       struct dwarf2_per_cu_data *per_cu;
20683
20684       per_cu = dwarf2_find_containing_comp_unit (sect_off, offset_in_dwz,
20685                                                  cu->objfile);
20686
20687       /* If necessary, add it to the queue and load its DIEs.  */
20688       if (maybe_queue_comp_unit (cu, per_cu, cu->language))
20689         load_full_comp_unit (per_cu, cu->language);
20690
20691       target_cu = per_cu->cu;
20692     }
20693   else if (cu->dies == NULL)
20694     {
20695       /* We're loading full DIEs during partial symbol reading.  */
20696       gdb_assert (dwarf2_per_objfile->reading_partial_symbols);
20697       load_full_comp_unit (cu->per_cu, language_minimal);
20698     }
20699
20700   *ref_cu = target_cu;
20701   temp_die.sect_off = sect_off;
20702   return (struct die_info *) htab_find_with_hash (target_cu->die_hash,
20703                                                   &temp_die,
20704                                                   to_underlying (sect_off));
20705 }
20706
20707 /* Follow reference attribute ATTR of SRC_DIE.
20708    On entry *REF_CU is the CU of SRC_DIE.
20709    On exit *REF_CU is the CU of the result.  */
20710
20711 static struct die_info *
20712 follow_die_ref (struct die_info *src_die, const struct attribute *attr,
20713                 struct dwarf2_cu **ref_cu)
20714 {
20715   sect_offset sect_off = dwarf2_get_ref_die_offset (attr);
20716   struct dwarf2_cu *cu = *ref_cu;
20717   struct die_info *die;
20718
20719   die = follow_die_offset (sect_off,
20720                            (attr->form == DW_FORM_GNU_ref_alt
20721                             || cu->per_cu->is_dwz),
20722                            ref_cu);
20723   if (!die)
20724     error (_("Dwarf Error: Cannot find DIE at 0x%x referenced from DIE "
20725            "at 0x%x [in module %s]"),
20726            to_underlying (sect_off), to_underlying (src_die->sect_off),
20727            objfile_name (cu->objfile));
20728
20729   return die;
20730 }
20731
20732 /* Return DWARF block referenced by DW_AT_location of DIE at SECT_OFF at PER_CU.
20733    Returned value is intended for DW_OP_call*.  Returned
20734    dwarf2_locexpr_baton->data has lifetime of PER_CU->OBJFILE.  */
20735
20736 struct dwarf2_locexpr_baton
20737 dwarf2_fetch_die_loc_sect_off (sect_offset sect_off,
20738                                struct dwarf2_per_cu_data *per_cu,
20739                                CORE_ADDR (*get_frame_pc) (void *baton),
20740                                void *baton)
20741 {
20742   struct dwarf2_cu *cu;
20743   struct die_info *die;
20744   struct attribute *attr;
20745   struct dwarf2_locexpr_baton retval;
20746
20747   dw2_setup (per_cu->objfile);
20748
20749   if (per_cu->cu == NULL)
20750     load_cu (per_cu);
20751   cu = per_cu->cu;
20752   if (cu == NULL)
20753     {
20754       /* We shouldn't get here for a dummy CU, but don't crash on the user.
20755          Instead just throw an error, not much else we can do.  */
20756       error (_("Dwarf Error: Dummy CU at 0x%x referenced in module %s"),
20757              to_underlying (sect_off), objfile_name (per_cu->objfile));
20758     }
20759
20760   die = follow_die_offset (sect_off, per_cu->is_dwz, &cu);
20761   if (!die)
20762     error (_("Dwarf Error: Cannot find DIE at 0x%x referenced in module %s"),
20763            to_underlying (sect_off), objfile_name (per_cu->objfile));
20764
20765   attr = dwarf2_attr (die, DW_AT_location, cu);
20766   if (!attr)
20767     {
20768       /* DWARF: "If there is no such attribute, then there is no effect.".
20769          DATA is ignored if SIZE is 0.  */
20770
20771       retval.data = NULL;
20772       retval.size = 0;
20773     }
20774   else if (attr_form_is_section_offset (attr))
20775     {
20776       struct dwarf2_loclist_baton loclist_baton;
20777       CORE_ADDR pc = (*get_frame_pc) (baton);
20778       size_t size;
20779
20780       fill_in_loclist_baton (cu, &loclist_baton, attr);
20781
20782       retval.data = dwarf2_find_location_expression (&loclist_baton,
20783                                                      &size, pc);
20784       retval.size = size;
20785     }
20786   else
20787     {
20788       if (!attr_form_is_block (attr))
20789         error (_("Dwarf Error: DIE at 0x%x referenced in module %s "
20790                  "is neither DW_FORM_block* nor DW_FORM_exprloc"),
20791                to_underlying (sect_off), objfile_name (per_cu->objfile));
20792
20793       retval.data = DW_BLOCK (attr)->data;
20794       retval.size = DW_BLOCK (attr)->size;
20795     }
20796   retval.per_cu = cu->per_cu;
20797
20798   age_cached_comp_units ();
20799
20800   return retval;
20801 }
20802
20803 /* Like dwarf2_fetch_die_loc_sect_off, but take a CU
20804    offset.  */
20805
20806 struct dwarf2_locexpr_baton
20807 dwarf2_fetch_die_loc_cu_off (cu_offset offset_in_cu,
20808                              struct dwarf2_per_cu_data *per_cu,
20809                              CORE_ADDR (*get_frame_pc) (void *baton),
20810                              void *baton)
20811 {
20812   sect_offset sect_off = per_cu->sect_off + to_underlying (offset_in_cu);
20813
20814   return dwarf2_fetch_die_loc_sect_off (sect_off, per_cu, get_frame_pc, baton);
20815 }
20816
20817 /* Write a constant of a given type as target-ordered bytes into
20818    OBSTACK.  */
20819
20820 static const gdb_byte *
20821 write_constant_as_bytes (struct obstack *obstack,
20822                          enum bfd_endian byte_order,
20823                          struct type *type,
20824                          ULONGEST value,
20825                          LONGEST *len)
20826 {
20827   gdb_byte *result;
20828
20829   *len = TYPE_LENGTH (type);
20830   result = (gdb_byte *) obstack_alloc (obstack, *len);
20831   store_unsigned_integer (result, *len, byte_order, value);
20832
20833   return result;
20834 }
20835
20836 /* If the DIE at OFFSET in PER_CU has a DW_AT_const_value, return a
20837    pointer to the constant bytes and set LEN to the length of the
20838    data.  If memory is needed, allocate it on OBSTACK.  If the DIE
20839    does not have a DW_AT_const_value, return NULL.  */
20840
20841 const gdb_byte *
20842 dwarf2_fetch_constant_bytes (sect_offset sect_off,
20843                              struct dwarf2_per_cu_data *per_cu,
20844                              struct obstack *obstack,
20845                              LONGEST *len)
20846 {
20847   struct dwarf2_cu *cu;
20848   struct die_info *die;
20849   struct attribute *attr;
20850   const gdb_byte *result = NULL;
20851   struct type *type;
20852   LONGEST value;
20853   enum bfd_endian byte_order;
20854
20855   dw2_setup (per_cu->objfile);
20856
20857   if (per_cu->cu == NULL)
20858     load_cu (per_cu);
20859   cu = per_cu->cu;
20860   if (cu == NULL)
20861     {
20862       /* We shouldn't get here for a dummy CU, but don't crash on the user.
20863          Instead just throw an error, not much else we can do.  */
20864       error (_("Dwarf Error: Dummy CU at 0x%x referenced in module %s"),
20865              to_underlying (sect_off), objfile_name (per_cu->objfile));
20866     }
20867
20868   die = follow_die_offset (sect_off, per_cu->is_dwz, &cu);
20869   if (!die)
20870     error (_("Dwarf Error: Cannot find DIE at 0x%x referenced in module %s"),
20871            to_underlying (sect_off), objfile_name (per_cu->objfile));
20872
20873
20874   attr = dwarf2_attr (die, DW_AT_const_value, cu);
20875   if (attr == NULL)
20876     return NULL;
20877
20878   byte_order = (bfd_big_endian (per_cu->objfile->obfd)
20879                 ? BFD_ENDIAN_BIG : BFD_ENDIAN_LITTLE);
20880
20881   switch (attr->form)
20882     {
20883     case DW_FORM_addr:
20884     case DW_FORM_GNU_addr_index:
20885       {
20886         gdb_byte *tem;
20887
20888         *len = cu->header.addr_size;
20889         tem = (gdb_byte *) obstack_alloc (obstack, *len);
20890         store_unsigned_integer (tem, *len, byte_order, DW_ADDR (attr));
20891         result = tem;
20892       }
20893       break;
20894     case DW_FORM_string:
20895     case DW_FORM_strp:
20896     case DW_FORM_GNU_str_index:
20897     case DW_FORM_GNU_strp_alt:
20898       /* DW_STRING is already allocated on the objfile obstack, point
20899          directly to it.  */
20900       result = (const gdb_byte *) DW_STRING (attr);
20901       *len = strlen (DW_STRING (attr));
20902       break;
20903     case DW_FORM_block1:
20904     case DW_FORM_block2:
20905     case DW_FORM_block4:
20906     case DW_FORM_block:
20907     case DW_FORM_exprloc:
20908     case DW_FORM_data16:
20909       result = DW_BLOCK (attr)->data;
20910       *len = DW_BLOCK (attr)->size;
20911       break;
20912
20913       /* The DW_AT_const_value attributes are supposed to carry the
20914          symbol's value "represented as it would be on the target
20915          architecture."  By the time we get here, it's already been
20916          converted to host endianness, so we just need to sign- or
20917          zero-extend it as appropriate.  */
20918     case DW_FORM_data1:
20919       type = die_type (die, cu);
20920       result = dwarf2_const_value_data (attr, obstack, cu, &value, 8);
20921       if (result == NULL)
20922         result = write_constant_as_bytes (obstack, byte_order,
20923                                           type, value, len);
20924       break;
20925     case DW_FORM_data2:
20926       type = die_type (die, cu);
20927       result = dwarf2_const_value_data (attr, obstack, cu, &value, 16);
20928       if (result == NULL)
20929         result = write_constant_as_bytes (obstack, byte_order,
20930                                           type, value, len);
20931       break;
20932     case DW_FORM_data4:
20933       type = die_type (die, cu);
20934       result = dwarf2_const_value_data (attr, obstack, cu, &value, 32);
20935       if (result == NULL)
20936         result = write_constant_as_bytes (obstack, byte_order,
20937                                           type, value, len);
20938       break;
20939     case DW_FORM_data8:
20940       type = die_type (die, cu);
20941       result = dwarf2_const_value_data (attr, obstack, cu, &value, 64);
20942       if (result == NULL)
20943         result = write_constant_as_bytes (obstack, byte_order,
20944                                           type, value, len);
20945       break;
20946
20947     case DW_FORM_sdata:
20948     case DW_FORM_implicit_const:
20949       type = die_type (die, cu);
20950       result = write_constant_as_bytes (obstack, byte_order,
20951                                         type, DW_SND (attr), len);
20952       break;
20953
20954     case DW_FORM_udata:
20955       type = die_type (die, cu);
20956       result = write_constant_as_bytes (obstack, byte_order,
20957                                         type, DW_UNSND (attr), len);
20958       break;
20959
20960     default:
20961       complaint (&symfile_complaints,
20962                  _("unsupported const value attribute form: '%s'"),
20963                  dwarf_form_name (attr->form));
20964       break;
20965     }
20966
20967   return result;
20968 }
20969
20970 /* Return the type of the die at OFFSET in PER_CU.  Return NULL if no
20971    valid type for this die is found.  */
20972
20973 struct type *
20974 dwarf2_fetch_die_type_sect_off (sect_offset sect_off,
20975                                 struct dwarf2_per_cu_data *per_cu)
20976 {
20977   struct dwarf2_cu *cu;
20978   struct die_info *die;
20979
20980   dw2_setup (per_cu->objfile);
20981
20982   if (per_cu->cu == NULL)
20983     load_cu (per_cu);
20984   cu = per_cu->cu;
20985   if (!cu)
20986     return NULL;
20987
20988   die = follow_die_offset (sect_off, per_cu->is_dwz, &cu);
20989   if (!die)
20990     return NULL;
20991
20992   return die_type (die, cu);
20993 }
20994
20995 /* Return the type of the DIE at DIE_OFFSET in the CU named by
20996    PER_CU.  */
20997
20998 struct type *
20999 dwarf2_get_die_type (cu_offset die_offset,
21000                      struct dwarf2_per_cu_data *per_cu)
21001 {
21002   dw2_setup (per_cu->objfile);
21003
21004   sect_offset die_offset_sect = per_cu->sect_off + to_underlying (die_offset);
21005   return get_die_type_at_offset (die_offset_sect, per_cu);
21006 }
21007
21008 /* Follow type unit SIG_TYPE referenced by SRC_DIE.
21009    On entry *REF_CU is the CU of SRC_DIE.
21010    On exit *REF_CU is the CU of the result.
21011    Returns NULL if the referenced DIE isn't found.  */
21012
21013 static struct die_info *
21014 follow_die_sig_1 (struct die_info *src_die, struct signatured_type *sig_type,
21015                   struct dwarf2_cu **ref_cu)
21016 {
21017   struct die_info temp_die;
21018   struct dwarf2_cu *sig_cu;
21019   struct die_info *die;
21020
21021   /* While it might be nice to assert sig_type->type == NULL here,
21022      we can get here for DW_AT_imported_declaration where we need
21023      the DIE not the type.  */
21024
21025   /* If necessary, add it to the queue and load its DIEs.  */
21026
21027   if (maybe_queue_comp_unit (*ref_cu, &sig_type->per_cu, language_minimal))
21028     read_signatured_type (sig_type);
21029
21030   sig_cu = sig_type->per_cu.cu;
21031   gdb_assert (sig_cu != NULL);
21032   gdb_assert (to_underlying (sig_type->type_offset_in_section) != 0);
21033   temp_die.sect_off = sig_type->type_offset_in_section;
21034   die = (struct die_info *) htab_find_with_hash (sig_cu->die_hash, &temp_die,
21035                                                  to_underlying (temp_die.sect_off));
21036   if (die)
21037     {
21038       /* For .gdb_index version 7 keep track of included TUs.
21039          http://sourceware.org/bugzilla/show_bug.cgi?id=15021.  */
21040       if (dwarf2_per_objfile->index_table != NULL
21041           && dwarf2_per_objfile->index_table->version <= 7)
21042         {
21043           VEC_safe_push (dwarf2_per_cu_ptr,
21044                          (*ref_cu)->per_cu->imported_symtabs,
21045                          sig_cu->per_cu);
21046         }
21047
21048       *ref_cu = sig_cu;
21049       return die;
21050     }
21051
21052   return NULL;
21053 }
21054
21055 /* Follow signatured type referenced by ATTR in SRC_DIE.
21056    On entry *REF_CU is the CU of SRC_DIE.
21057    On exit *REF_CU is the CU of the result.
21058    The result is the DIE of the type.
21059    If the referenced type cannot be found an error is thrown.  */
21060
21061 static struct die_info *
21062 follow_die_sig (struct die_info *src_die, const struct attribute *attr,
21063                 struct dwarf2_cu **ref_cu)
21064 {
21065   ULONGEST signature = DW_SIGNATURE (attr);
21066   struct signatured_type *sig_type;
21067   struct die_info *die;
21068
21069   gdb_assert (attr->form == DW_FORM_ref_sig8);
21070
21071   sig_type = lookup_signatured_type (*ref_cu, signature);
21072   /* sig_type will be NULL if the signatured type is missing from
21073      the debug info.  */
21074   if (sig_type == NULL)
21075     {
21076       error (_("Dwarf Error: Cannot find signatured DIE %s referenced"
21077                " from DIE at 0x%x [in module %s]"),
21078              hex_string (signature), to_underlying (src_die->sect_off),
21079              objfile_name ((*ref_cu)->objfile));
21080     }
21081
21082   die = follow_die_sig_1 (src_die, sig_type, ref_cu);
21083   if (die == NULL)
21084     {
21085       dump_die_for_error (src_die);
21086       error (_("Dwarf Error: Problem reading signatured DIE %s referenced"
21087                " from DIE at 0x%x [in module %s]"),
21088              hex_string (signature), to_underlying (src_die->sect_off),
21089              objfile_name ((*ref_cu)->objfile));
21090     }
21091
21092   return die;
21093 }
21094
21095 /* Get the type specified by SIGNATURE referenced in DIE/CU,
21096    reading in and processing the type unit if necessary.  */
21097
21098 static struct type *
21099 get_signatured_type (struct die_info *die, ULONGEST signature,
21100                      struct dwarf2_cu *cu)
21101 {
21102   struct signatured_type *sig_type;
21103   struct dwarf2_cu *type_cu;
21104   struct die_info *type_die;
21105   struct type *type;
21106
21107   sig_type = lookup_signatured_type (cu, signature);
21108   /* sig_type will be NULL if the signatured type is missing from
21109      the debug info.  */
21110   if (sig_type == NULL)
21111     {
21112       complaint (&symfile_complaints,
21113                  _("Dwarf Error: Cannot find signatured DIE %s referenced"
21114                    " from DIE at 0x%x [in module %s]"),
21115                  hex_string (signature), to_underlying (die->sect_off),
21116                  objfile_name (dwarf2_per_objfile->objfile));
21117       return build_error_marker_type (cu, die);
21118     }
21119
21120   /* If we already know the type we're done.  */
21121   if (sig_type->type != NULL)
21122     return sig_type->type;
21123
21124   type_cu = cu;
21125   type_die = follow_die_sig_1 (die, sig_type, &type_cu);
21126   if (type_die != NULL)
21127     {
21128       /* N.B. We need to call get_die_type to ensure only one type for this DIE
21129          is created.  This is important, for example, because for c++ classes
21130          we need TYPE_NAME set which is only done by new_symbol.  Blech.  */
21131       type = read_type_die (type_die, type_cu);
21132       if (type == NULL)
21133         {
21134           complaint (&symfile_complaints,
21135                      _("Dwarf Error: Cannot build signatured type %s"
21136                        " referenced from DIE at 0x%x [in module %s]"),
21137                      hex_string (signature), to_underlying (die->sect_off),
21138                      objfile_name (dwarf2_per_objfile->objfile));
21139           type = build_error_marker_type (cu, die);
21140         }
21141     }
21142   else
21143     {
21144       complaint (&symfile_complaints,
21145                  _("Dwarf Error: Problem reading signatured DIE %s referenced"
21146                    " from DIE at 0x%x [in module %s]"),
21147                  hex_string (signature), to_underlying (die->sect_off),
21148                  objfile_name (dwarf2_per_objfile->objfile));
21149       type = build_error_marker_type (cu, die);
21150     }
21151   sig_type->type = type;
21152
21153   return type;
21154 }
21155
21156 /* Get the type specified by the DW_AT_signature ATTR in DIE/CU,
21157    reading in and processing the type unit if necessary.  */
21158
21159 static struct type *
21160 get_DW_AT_signature_type (struct die_info *die, const struct attribute *attr,
21161                           struct dwarf2_cu *cu) /* ARI: editCase function */
21162 {
21163   /* Yes, DW_AT_signature can use a non-ref_sig8 reference.  */
21164   if (attr_form_is_ref (attr))
21165     {
21166       struct dwarf2_cu *type_cu = cu;
21167       struct die_info *type_die = follow_die_ref (die, attr, &type_cu);
21168
21169       return read_type_die (type_die, type_cu);
21170     }
21171   else if (attr->form == DW_FORM_ref_sig8)
21172     {
21173       return get_signatured_type (die, DW_SIGNATURE (attr), cu);
21174     }
21175   else
21176     {
21177       complaint (&symfile_complaints,
21178                  _("Dwarf Error: DW_AT_signature has bad form %s in DIE"
21179                    " at 0x%x [in module %s]"),
21180                  dwarf_form_name (attr->form), to_underlying (die->sect_off),
21181                  objfile_name (dwarf2_per_objfile->objfile));
21182       return build_error_marker_type (cu, die);
21183     }
21184 }
21185
21186 /* Load the DIEs associated with type unit PER_CU into memory.  */
21187
21188 static void
21189 load_full_type_unit (struct dwarf2_per_cu_data *per_cu)
21190 {
21191   struct signatured_type *sig_type;
21192
21193   /* Caller is responsible for ensuring type_unit_groups don't get here.  */
21194   gdb_assert (! IS_TYPE_UNIT_GROUP (per_cu));
21195
21196   /* We have the per_cu, but we need the signatured_type.
21197      Fortunately this is an easy translation.  */
21198   gdb_assert (per_cu->is_debug_types);
21199   sig_type = (struct signatured_type *) per_cu;
21200
21201   gdb_assert (per_cu->cu == NULL);
21202
21203   read_signatured_type (sig_type);
21204
21205   gdb_assert (per_cu->cu != NULL);
21206 }
21207
21208 /* die_reader_func for read_signatured_type.
21209    This is identical to load_full_comp_unit_reader,
21210    but is kept separate for now.  */
21211
21212 static void
21213 read_signatured_type_reader (const struct die_reader_specs *reader,
21214                              const gdb_byte *info_ptr,
21215                              struct die_info *comp_unit_die,
21216                              int has_children,
21217                              void *data)
21218 {
21219   struct dwarf2_cu *cu = reader->cu;
21220
21221   gdb_assert (cu->die_hash == NULL);
21222   cu->die_hash =
21223     htab_create_alloc_ex (cu->header.length / 12,
21224                           die_hash,
21225                           die_eq,
21226                           NULL,
21227                           &cu->comp_unit_obstack,
21228                           hashtab_obstack_allocate,
21229                           dummy_obstack_deallocate);
21230
21231   if (has_children)
21232     comp_unit_die->child = read_die_and_siblings (reader, info_ptr,
21233                                                   &info_ptr, comp_unit_die);
21234   cu->dies = comp_unit_die;
21235   /* comp_unit_die is not stored in die_hash, no need.  */
21236
21237   /* We try not to read any attributes in this function, because not
21238      all CUs needed for references have been loaded yet, and symbol
21239      table processing isn't initialized.  But we have to set the CU language,
21240      or we won't be able to build types correctly.
21241      Similarly, if we do not read the producer, we can not apply
21242      producer-specific interpretation.  */
21243   prepare_one_comp_unit (cu, cu->dies, language_minimal);
21244 }
21245
21246 /* Read in a signatured type and build its CU and DIEs.
21247    If the type is a stub for the real type in a DWO file,
21248    read in the real type from the DWO file as well.  */
21249
21250 static void
21251 read_signatured_type (struct signatured_type *sig_type)
21252 {
21253   struct dwarf2_per_cu_data *per_cu = &sig_type->per_cu;
21254
21255   gdb_assert (per_cu->is_debug_types);
21256   gdb_assert (per_cu->cu == NULL);
21257
21258   init_cutu_and_read_dies (per_cu, NULL, 0, 1,
21259                            read_signatured_type_reader, NULL);
21260   sig_type->per_cu.tu_read = 1;
21261 }
21262
21263 /* Decode simple location descriptions.
21264    Given a pointer to a dwarf block that defines a location, compute
21265    the location and return the value.
21266
21267    NOTE drow/2003-11-18: This function is called in two situations
21268    now: for the address of static or global variables (partial symbols
21269    only) and for offsets into structures which are expected to be
21270    (more or less) constant.  The partial symbol case should go away,
21271    and only the constant case should remain.  That will let this
21272    function complain more accurately.  A few special modes are allowed
21273    without complaint for global variables (for instance, global
21274    register values and thread-local values).
21275
21276    A location description containing no operations indicates that the
21277    object is optimized out.  The return value is 0 for that case.
21278    FIXME drow/2003-11-16: No callers check for this case any more; soon all
21279    callers will only want a very basic result and this can become a
21280    complaint.
21281
21282    Note that stack[0] is unused except as a default error return.  */
21283
21284 static CORE_ADDR
21285 decode_locdesc (struct dwarf_block *blk, struct dwarf2_cu *cu)
21286 {
21287   struct objfile *objfile = cu->objfile;
21288   size_t i;
21289   size_t size = blk->size;
21290   const gdb_byte *data = blk->data;
21291   CORE_ADDR stack[64];
21292   int stacki;
21293   unsigned int bytes_read, unsnd;
21294   gdb_byte op;
21295
21296   i = 0;
21297   stacki = 0;
21298   stack[stacki] = 0;
21299   stack[++stacki] = 0;
21300
21301   while (i < size)
21302     {
21303       op = data[i++];
21304       switch (op)
21305         {
21306         case DW_OP_lit0:
21307         case DW_OP_lit1:
21308         case DW_OP_lit2:
21309         case DW_OP_lit3:
21310         case DW_OP_lit4:
21311         case DW_OP_lit5:
21312         case DW_OP_lit6:
21313         case DW_OP_lit7:
21314         case DW_OP_lit8:
21315         case DW_OP_lit9:
21316         case DW_OP_lit10:
21317         case DW_OP_lit11:
21318         case DW_OP_lit12:
21319         case DW_OP_lit13:
21320         case DW_OP_lit14:
21321         case DW_OP_lit15:
21322         case DW_OP_lit16:
21323         case DW_OP_lit17:
21324         case DW_OP_lit18:
21325         case DW_OP_lit19:
21326         case DW_OP_lit20:
21327         case DW_OP_lit21:
21328         case DW_OP_lit22:
21329         case DW_OP_lit23:
21330         case DW_OP_lit24:
21331         case DW_OP_lit25:
21332         case DW_OP_lit26:
21333         case DW_OP_lit27:
21334         case DW_OP_lit28:
21335         case DW_OP_lit29:
21336         case DW_OP_lit30:
21337         case DW_OP_lit31:
21338           stack[++stacki] = op - DW_OP_lit0;
21339           break;
21340
21341         case DW_OP_reg0:
21342         case DW_OP_reg1:
21343         case DW_OP_reg2:
21344         case DW_OP_reg3:
21345         case DW_OP_reg4:
21346         case DW_OP_reg5:
21347         case DW_OP_reg6:
21348         case DW_OP_reg7:
21349         case DW_OP_reg8:
21350         case DW_OP_reg9:
21351         case DW_OP_reg10:
21352         case DW_OP_reg11:
21353         case DW_OP_reg12:
21354         case DW_OP_reg13:
21355         case DW_OP_reg14:
21356         case DW_OP_reg15:
21357         case DW_OP_reg16:
21358         case DW_OP_reg17:
21359         case DW_OP_reg18:
21360         case DW_OP_reg19:
21361         case DW_OP_reg20:
21362         case DW_OP_reg21:
21363         case DW_OP_reg22:
21364         case DW_OP_reg23:
21365         case DW_OP_reg24:
21366         case DW_OP_reg25:
21367         case DW_OP_reg26:
21368         case DW_OP_reg27:
21369         case DW_OP_reg28:
21370         case DW_OP_reg29:
21371         case DW_OP_reg30:
21372         case DW_OP_reg31:
21373           stack[++stacki] = op - DW_OP_reg0;
21374           if (i < size)
21375             dwarf2_complex_location_expr_complaint ();
21376           break;
21377
21378         case DW_OP_regx:
21379           unsnd = read_unsigned_leb128 (NULL, (data + i), &bytes_read);
21380           i += bytes_read;
21381           stack[++stacki] = unsnd;
21382           if (i < size)
21383             dwarf2_complex_location_expr_complaint ();
21384           break;
21385
21386         case DW_OP_addr:
21387           stack[++stacki] = read_address (objfile->obfd, &data[i],
21388                                           cu, &bytes_read);
21389           i += bytes_read;
21390           break;
21391
21392         case DW_OP_const1u:
21393           stack[++stacki] = read_1_byte (objfile->obfd, &data[i]);
21394           i += 1;
21395           break;
21396
21397         case DW_OP_const1s:
21398           stack[++stacki] = read_1_signed_byte (objfile->obfd, &data[i]);
21399           i += 1;
21400           break;
21401
21402         case DW_OP_const2u:
21403           stack[++stacki] = read_2_bytes (objfile->obfd, &data[i]);
21404           i += 2;
21405           break;
21406
21407         case DW_OP_const2s:
21408           stack[++stacki] = read_2_signed_bytes (objfile->obfd, &data[i]);
21409           i += 2;
21410           break;
21411
21412         case DW_OP_const4u:
21413           stack[++stacki] = read_4_bytes (objfile->obfd, &data[i]);
21414           i += 4;
21415           break;
21416
21417         case DW_OP_const4s:
21418           stack[++stacki] = read_4_signed_bytes (objfile->obfd, &data[i]);
21419           i += 4;
21420           break;
21421
21422         case DW_OP_const8u:
21423           stack[++stacki] = read_8_bytes (objfile->obfd, &data[i]);
21424           i += 8;
21425           break;
21426
21427         case DW_OP_constu:
21428           stack[++stacki] = read_unsigned_leb128 (NULL, (data + i),
21429                                                   &bytes_read);
21430           i += bytes_read;
21431           break;
21432
21433         case DW_OP_consts:
21434           stack[++stacki] = read_signed_leb128 (NULL, (data + i), &bytes_read);
21435           i += bytes_read;
21436           break;
21437
21438         case DW_OP_dup:
21439           stack[stacki + 1] = stack[stacki];
21440           stacki++;
21441           break;
21442
21443         case DW_OP_plus:
21444           stack[stacki - 1] += stack[stacki];
21445           stacki--;
21446           break;
21447
21448         case DW_OP_plus_uconst:
21449           stack[stacki] += read_unsigned_leb128 (NULL, (data + i),
21450                                                  &bytes_read);
21451           i += bytes_read;
21452           break;
21453
21454         case DW_OP_minus:
21455           stack[stacki - 1] -= stack[stacki];
21456           stacki--;
21457           break;
21458
21459         case DW_OP_deref:
21460           /* If we're not the last op, then we definitely can't encode
21461              this using GDB's address_class enum.  This is valid for partial
21462              global symbols, although the variable's address will be bogus
21463              in the psymtab.  */
21464           if (i < size)
21465             dwarf2_complex_location_expr_complaint ();
21466           break;
21467
21468         case DW_OP_GNU_push_tls_address:
21469         case DW_OP_form_tls_address:
21470           /* The top of the stack has the offset from the beginning
21471              of the thread control block at which the variable is located.  */
21472           /* Nothing should follow this operator, so the top of stack would
21473              be returned.  */
21474           /* This is valid for partial global symbols, but the variable's
21475              address will be bogus in the psymtab.  Make it always at least
21476              non-zero to not look as a variable garbage collected by linker
21477              which have DW_OP_addr 0.  */
21478           if (i < size)
21479             dwarf2_complex_location_expr_complaint ();
21480           stack[stacki]++;
21481           break;
21482
21483         case DW_OP_GNU_uninit:
21484           break;
21485
21486         case DW_OP_GNU_addr_index:
21487         case DW_OP_GNU_const_index:
21488           stack[++stacki] = read_addr_index_from_leb128 (cu, &data[i],
21489                                                          &bytes_read);
21490           i += bytes_read;
21491           break;
21492
21493         default:
21494           {
21495             const char *name = get_DW_OP_name (op);
21496
21497             if (name)
21498               complaint (&symfile_complaints, _("unsupported stack op: '%s'"),
21499                          name);
21500             else
21501               complaint (&symfile_complaints, _("unsupported stack op: '%02x'"),
21502                          op);
21503           }
21504
21505           return (stack[stacki]);
21506         }
21507
21508       /* Enforce maximum stack depth of SIZE-1 to avoid writing
21509          outside of the allocated space.  Also enforce minimum>0.  */
21510       if (stacki >= ARRAY_SIZE (stack) - 1)
21511         {
21512           complaint (&symfile_complaints,
21513                      _("location description stack overflow"));
21514           return 0;
21515         }
21516
21517       if (stacki <= 0)
21518         {
21519           complaint (&symfile_complaints,
21520                      _("location description stack underflow"));
21521           return 0;
21522         }
21523     }
21524   return (stack[stacki]);
21525 }
21526
21527 /* memory allocation interface */
21528
21529 static struct dwarf_block *
21530 dwarf_alloc_block (struct dwarf2_cu *cu)
21531 {
21532   return XOBNEW (&cu->comp_unit_obstack, struct dwarf_block);
21533 }
21534
21535 static struct die_info *
21536 dwarf_alloc_die (struct dwarf2_cu *cu, int num_attrs)
21537 {
21538   struct die_info *die;
21539   size_t size = sizeof (struct die_info);
21540
21541   if (num_attrs > 1)
21542     size += (num_attrs - 1) * sizeof (struct attribute);
21543
21544   die = (struct die_info *) obstack_alloc (&cu->comp_unit_obstack, size);
21545   memset (die, 0, sizeof (struct die_info));
21546   return (die);
21547 }
21548
21549 \f
21550 /* Macro support.  */
21551
21552 /* Return file name relative to the compilation directory of file number I in
21553    *LH's file name table.  The result is allocated using xmalloc; the caller is
21554    responsible for freeing it.  */
21555
21556 static char *
21557 file_file_name (int file, struct line_header *lh)
21558 {
21559   /* Is the file number a valid index into the line header's file name
21560      table?  Remember that file numbers start with one, not zero.  */
21561   if (1 <= file && file <= lh->file_names.size ())
21562     {
21563       const file_entry &fe = lh->file_names[file - 1];
21564
21565       if (!IS_ABSOLUTE_PATH (fe.name))
21566         {
21567           const char *dir = fe.include_dir (lh);
21568           if (dir != NULL)
21569             return concat (dir, SLASH_STRING, fe.name, (char *) NULL);
21570         }
21571       return xstrdup (fe.name);
21572     }
21573   else
21574     {
21575       /* The compiler produced a bogus file number.  We can at least
21576          record the macro definitions made in the file, even if we
21577          won't be able to find the file by name.  */
21578       char fake_name[80];
21579
21580       xsnprintf (fake_name, sizeof (fake_name),
21581                  "<bad macro file number %d>", file);
21582
21583       complaint (&symfile_complaints,
21584                  _("bad file number in macro information (%d)"),
21585                  file);
21586
21587       return xstrdup (fake_name);
21588     }
21589 }
21590
21591 /* Return the full name of file number I in *LH's file name table.
21592    Use COMP_DIR as the name of the current directory of the
21593    compilation.  The result is allocated using xmalloc; the caller is
21594    responsible for freeing it.  */
21595 static char *
21596 file_full_name (int file, struct line_header *lh, const char *comp_dir)
21597 {
21598   /* Is the file number a valid index into the line header's file name
21599      table?  Remember that file numbers start with one, not zero.  */
21600   if (1 <= file && file <= lh->file_names.size ())
21601     {
21602       char *relative = file_file_name (file, lh);
21603
21604       if (IS_ABSOLUTE_PATH (relative) || comp_dir == NULL)
21605         return relative;
21606       return reconcat (relative, comp_dir, SLASH_STRING,
21607                        relative, (char *) NULL);
21608     }
21609   else
21610     return file_file_name (file, lh);
21611 }
21612
21613
21614 static struct macro_source_file *
21615 macro_start_file (int file, int line,
21616                   struct macro_source_file *current_file,
21617                   struct line_header *lh)
21618 {
21619   /* File name relative to the compilation directory of this source file.  */
21620   char *file_name = file_file_name (file, lh);
21621
21622   if (! current_file)
21623     {
21624       /* Note: We don't create a macro table for this compilation unit
21625          at all until we actually get a filename.  */
21626       struct macro_table *macro_table = get_macro_table ();
21627
21628       /* If we have no current file, then this must be the start_file
21629          directive for the compilation unit's main source file.  */
21630       current_file = macro_set_main (macro_table, file_name);
21631       macro_define_special (macro_table);
21632     }
21633   else
21634     current_file = macro_include (current_file, line, file_name);
21635
21636   xfree (file_name);
21637
21638   return current_file;
21639 }
21640
21641
21642 /* Copy the LEN characters at BUF to a xmalloc'ed block of memory,
21643    followed by a null byte.  */
21644 static char *
21645 copy_string (const char *buf, int len)
21646 {
21647   char *s = (char *) xmalloc (len + 1);
21648
21649   memcpy (s, buf, len);
21650   s[len] = '\0';
21651   return s;
21652 }
21653
21654
21655 static const char *
21656 consume_improper_spaces (const char *p, const char *body)
21657 {
21658   if (*p == ' ')
21659     {
21660       complaint (&symfile_complaints,
21661                  _("macro definition contains spaces "
21662                    "in formal argument list:\n`%s'"),
21663                  body);
21664
21665       while (*p == ' ')
21666         p++;
21667     }
21668
21669   return p;
21670 }
21671
21672
21673 static void
21674 parse_macro_definition (struct macro_source_file *file, int line,
21675                         const char *body)
21676 {
21677   const char *p;
21678
21679   /* The body string takes one of two forms.  For object-like macro
21680      definitions, it should be:
21681
21682         <macro name> " " <definition>
21683
21684      For function-like macro definitions, it should be:
21685
21686         <macro name> "() " <definition>
21687      or
21688         <macro name> "(" <arg name> ( "," <arg name> ) * ") " <definition>
21689
21690      Spaces may appear only where explicitly indicated, and in the
21691      <definition>.
21692
21693      The Dwarf 2 spec says that an object-like macro's name is always
21694      followed by a space, but versions of GCC around March 2002 omit
21695      the space when the macro's definition is the empty string.
21696
21697      The Dwarf 2 spec says that there should be no spaces between the
21698      formal arguments in a function-like macro's formal argument list,
21699      but versions of GCC around March 2002 include spaces after the
21700      commas.  */
21701
21702
21703   /* Find the extent of the macro name.  The macro name is terminated
21704      by either a space or null character (for an object-like macro) or
21705      an opening paren (for a function-like macro).  */
21706   for (p = body; *p; p++)
21707     if (*p == ' ' || *p == '(')
21708       break;
21709
21710   if (*p == ' ' || *p == '\0')
21711     {
21712       /* It's an object-like macro.  */
21713       int name_len = p - body;
21714       char *name = copy_string (body, name_len);
21715       const char *replacement;
21716
21717       if (*p == ' ')
21718         replacement = body + name_len + 1;
21719       else
21720         {
21721           dwarf2_macro_malformed_definition_complaint (body);
21722           replacement = body + name_len;
21723         }
21724
21725       macro_define_object (file, line, name, replacement);
21726
21727       xfree (name);
21728     }
21729   else if (*p == '(')
21730     {
21731       /* It's a function-like macro.  */
21732       char *name = copy_string (body, p - body);
21733       int argc = 0;
21734       int argv_size = 1;
21735       char **argv = XNEWVEC (char *, argv_size);
21736
21737       p++;
21738
21739       p = consume_improper_spaces (p, body);
21740
21741       /* Parse the formal argument list.  */
21742       while (*p && *p != ')')
21743         {
21744           /* Find the extent of the current argument name.  */
21745           const char *arg_start = p;
21746
21747           while (*p && *p != ',' && *p != ')' && *p != ' ')
21748             p++;
21749
21750           if (! *p || p == arg_start)
21751             dwarf2_macro_malformed_definition_complaint (body);
21752           else
21753             {
21754               /* Make sure argv has room for the new argument.  */
21755               if (argc >= argv_size)
21756                 {
21757                   argv_size *= 2;
21758                   argv = XRESIZEVEC (char *, argv, argv_size);
21759                 }
21760
21761               argv[argc++] = copy_string (arg_start, p - arg_start);
21762             }
21763
21764           p = consume_improper_spaces (p, body);
21765
21766           /* Consume the comma, if present.  */
21767           if (*p == ',')
21768             {
21769               p++;
21770
21771               p = consume_improper_spaces (p, body);
21772             }
21773         }
21774
21775       if (*p == ')')
21776         {
21777           p++;
21778
21779           if (*p == ' ')
21780             /* Perfectly formed definition, no complaints.  */
21781             macro_define_function (file, line, name,
21782                                    argc, (const char **) argv,
21783                                    p + 1);
21784           else if (*p == '\0')
21785             {
21786               /* Complain, but do define it.  */
21787               dwarf2_macro_malformed_definition_complaint (body);
21788               macro_define_function (file, line, name,
21789                                      argc, (const char **) argv,
21790                                      p);
21791             }
21792           else
21793             /* Just complain.  */
21794             dwarf2_macro_malformed_definition_complaint (body);
21795         }
21796       else
21797         /* Just complain.  */
21798         dwarf2_macro_malformed_definition_complaint (body);
21799
21800       xfree (name);
21801       {
21802         int i;
21803
21804         for (i = 0; i < argc; i++)
21805           xfree (argv[i]);
21806       }
21807       xfree (argv);
21808     }
21809   else
21810     dwarf2_macro_malformed_definition_complaint (body);
21811 }
21812
21813 /* Skip some bytes from BYTES according to the form given in FORM.
21814    Returns the new pointer.  */
21815
21816 static const gdb_byte *
21817 skip_form_bytes (bfd *abfd, const gdb_byte *bytes, const gdb_byte *buffer_end,
21818                  enum dwarf_form form,
21819                  unsigned int offset_size,
21820                  struct dwarf2_section_info *section)
21821 {
21822   unsigned int bytes_read;
21823
21824   switch (form)
21825     {
21826     case DW_FORM_data1:
21827     case DW_FORM_flag:
21828       ++bytes;
21829       break;
21830
21831     case DW_FORM_data2:
21832       bytes += 2;
21833       break;
21834
21835     case DW_FORM_data4:
21836       bytes += 4;
21837       break;
21838
21839     case DW_FORM_data8:
21840       bytes += 8;
21841       break;
21842
21843     case DW_FORM_data16:
21844       bytes += 16;
21845       break;
21846
21847     case DW_FORM_string:
21848       read_direct_string (abfd, bytes, &bytes_read);
21849       bytes += bytes_read;
21850       break;
21851
21852     case DW_FORM_sec_offset:
21853     case DW_FORM_strp:
21854     case DW_FORM_GNU_strp_alt:
21855       bytes += offset_size;
21856       break;
21857
21858     case DW_FORM_block:
21859       bytes += read_unsigned_leb128 (abfd, bytes, &bytes_read);
21860       bytes += bytes_read;
21861       break;
21862
21863     case DW_FORM_block1:
21864       bytes += 1 + read_1_byte (abfd, bytes);
21865       break;
21866     case DW_FORM_block2:
21867       bytes += 2 + read_2_bytes (abfd, bytes);
21868       break;
21869     case DW_FORM_block4:
21870       bytes += 4 + read_4_bytes (abfd, bytes);
21871       break;
21872
21873     case DW_FORM_sdata:
21874     case DW_FORM_udata:
21875     case DW_FORM_GNU_addr_index:
21876     case DW_FORM_GNU_str_index:
21877       bytes = gdb_skip_leb128 (bytes, buffer_end);
21878       if (bytes == NULL)
21879         {
21880           dwarf2_section_buffer_overflow_complaint (section);
21881           return NULL;
21882         }
21883       break;
21884
21885     case DW_FORM_implicit_const:
21886       break;
21887
21888     default:
21889       {
21890       complain:
21891         complaint (&symfile_complaints,
21892                    _("invalid form 0x%x in `%s'"),
21893                    form, get_section_name (section));
21894         return NULL;
21895       }
21896     }
21897
21898   return bytes;
21899 }
21900
21901 /* A helper for dwarf_decode_macros that handles skipping an unknown
21902    opcode.  Returns an updated pointer to the macro data buffer; or,
21903    on error, issues a complaint and returns NULL.  */
21904
21905 static const gdb_byte *
21906 skip_unknown_opcode (unsigned int opcode,
21907                      const gdb_byte **opcode_definitions,
21908                      const gdb_byte *mac_ptr, const gdb_byte *mac_end,
21909                      bfd *abfd,
21910                      unsigned int offset_size,
21911                      struct dwarf2_section_info *section)
21912 {
21913   unsigned int bytes_read, i;
21914   unsigned long arg;
21915   const gdb_byte *defn;
21916
21917   if (opcode_definitions[opcode] == NULL)
21918     {
21919       complaint (&symfile_complaints,
21920                  _("unrecognized DW_MACFINO opcode 0x%x"),
21921                  opcode);
21922       return NULL;
21923     }
21924
21925   defn = opcode_definitions[opcode];
21926   arg = read_unsigned_leb128 (abfd, defn, &bytes_read);
21927   defn += bytes_read;
21928
21929   for (i = 0; i < arg; ++i)
21930     {
21931       mac_ptr = skip_form_bytes (abfd, mac_ptr, mac_end,
21932                                  (enum dwarf_form) defn[i], offset_size,
21933                                  section);
21934       if (mac_ptr == NULL)
21935         {
21936           /* skip_form_bytes already issued the complaint.  */
21937           return NULL;
21938         }
21939     }
21940
21941   return mac_ptr;
21942 }
21943
21944 /* A helper function which parses the header of a macro section.
21945    If the macro section is the extended (for now called "GNU") type,
21946    then this updates *OFFSET_SIZE.  Returns a pointer to just after
21947    the header, or issues a complaint and returns NULL on error.  */
21948
21949 static const gdb_byte *
21950 dwarf_parse_macro_header (const gdb_byte **opcode_definitions,
21951                           bfd *abfd,
21952                           const gdb_byte *mac_ptr,
21953                           unsigned int *offset_size,
21954                           int section_is_gnu)
21955 {
21956   memset (opcode_definitions, 0, 256 * sizeof (gdb_byte *));
21957
21958   if (section_is_gnu)
21959     {
21960       unsigned int version, flags;
21961
21962       version = read_2_bytes (abfd, mac_ptr);
21963       if (version != 4 && version != 5)
21964         {
21965           complaint (&symfile_complaints,
21966                      _("unrecognized version `%d' in .debug_macro section"),
21967                      version);
21968           return NULL;
21969         }
21970       mac_ptr += 2;
21971
21972       flags = read_1_byte (abfd, mac_ptr);
21973       ++mac_ptr;
21974       *offset_size = (flags & 1) ? 8 : 4;
21975
21976       if ((flags & 2) != 0)
21977         /* We don't need the line table offset.  */
21978         mac_ptr += *offset_size;
21979
21980       /* Vendor opcode descriptions.  */
21981       if ((flags & 4) != 0)
21982         {
21983           unsigned int i, count;
21984
21985           count = read_1_byte (abfd, mac_ptr);
21986           ++mac_ptr;
21987           for (i = 0; i < count; ++i)
21988             {
21989               unsigned int opcode, bytes_read;
21990               unsigned long arg;
21991
21992               opcode = read_1_byte (abfd, mac_ptr);
21993               ++mac_ptr;
21994               opcode_definitions[opcode] = mac_ptr;
21995               arg = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
21996               mac_ptr += bytes_read;
21997               mac_ptr += arg;
21998             }
21999         }
22000     }
22001
22002   return mac_ptr;
22003 }
22004
22005 /* A helper for dwarf_decode_macros that handles the GNU extensions,
22006    including DW_MACRO_import.  */
22007
22008 static void
22009 dwarf_decode_macro_bytes (bfd *abfd,
22010                           const gdb_byte *mac_ptr, const gdb_byte *mac_end,
22011                           struct macro_source_file *current_file,
22012                           struct line_header *lh,
22013                           struct dwarf2_section_info *section,
22014                           int section_is_gnu, int section_is_dwz,
22015                           unsigned int offset_size,
22016                           htab_t include_hash)
22017 {
22018   struct objfile *objfile = dwarf2_per_objfile->objfile;
22019   enum dwarf_macro_record_type macinfo_type;
22020   int at_commandline;
22021   const gdb_byte *opcode_definitions[256];
22022
22023   mac_ptr = dwarf_parse_macro_header (opcode_definitions, abfd, mac_ptr,
22024                                       &offset_size, section_is_gnu);
22025   if (mac_ptr == NULL)
22026     {
22027       /* We already issued a complaint.  */
22028       return;
22029     }
22030
22031   /* Determines if GDB is still before first DW_MACINFO_start_file.  If true
22032      GDB is still reading the definitions from command line.  First
22033      DW_MACINFO_start_file will need to be ignored as it was already executed
22034      to create CURRENT_FILE for the main source holding also the command line
22035      definitions.  On first met DW_MACINFO_start_file this flag is reset to
22036      normally execute all the remaining DW_MACINFO_start_file macinfos.  */
22037
22038   at_commandline = 1;
22039
22040   do
22041     {
22042       /* Do we at least have room for a macinfo type byte?  */
22043       if (mac_ptr >= mac_end)
22044         {
22045           dwarf2_section_buffer_overflow_complaint (section);
22046           break;
22047         }
22048
22049       macinfo_type = (enum dwarf_macro_record_type) read_1_byte (abfd, mac_ptr);
22050       mac_ptr++;
22051
22052       /* Note that we rely on the fact that the corresponding GNU and
22053          DWARF constants are the same.  */
22054       switch (macinfo_type)
22055         {
22056           /* A zero macinfo type indicates the end of the macro
22057              information.  */
22058         case 0:
22059           break;
22060
22061         case DW_MACRO_define:
22062         case DW_MACRO_undef:
22063         case DW_MACRO_define_strp:
22064         case DW_MACRO_undef_strp:
22065         case DW_MACRO_define_sup:
22066         case DW_MACRO_undef_sup:
22067           {
22068             unsigned int bytes_read;
22069             int line;
22070             const char *body;
22071             int is_define;
22072
22073             line = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
22074             mac_ptr += bytes_read;
22075
22076             if (macinfo_type == DW_MACRO_define
22077                 || macinfo_type == DW_MACRO_undef)
22078               {
22079                 body = read_direct_string (abfd, mac_ptr, &bytes_read);
22080                 mac_ptr += bytes_read;
22081               }
22082             else
22083               {
22084                 LONGEST str_offset;
22085
22086                 str_offset = read_offset_1 (abfd, mac_ptr, offset_size);
22087                 mac_ptr += offset_size;
22088
22089                 if (macinfo_type == DW_MACRO_define_sup
22090                     || macinfo_type == DW_MACRO_undef_sup
22091                     || section_is_dwz)
22092                   {
22093                     struct dwz_file *dwz = dwarf2_get_dwz_file ();
22094
22095                     body = read_indirect_string_from_dwz (dwz, str_offset);
22096                   }
22097                 else
22098                   body = read_indirect_string_at_offset (abfd, str_offset);
22099               }
22100
22101             is_define = (macinfo_type == DW_MACRO_define
22102                          || macinfo_type == DW_MACRO_define_strp
22103                          || macinfo_type == DW_MACRO_define_sup);
22104             if (! current_file)
22105               {
22106                 /* DWARF violation as no main source is present.  */
22107                 complaint (&symfile_complaints,
22108                            _("debug info with no main source gives macro %s "
22109                              "on line %d: %s"),
22110                            is_define ? _("definition") : _("undefinition"),
22111                            line, body);
22112                 break;
22113               }
22114             if ((line == 0 && !at_commandline)
22115                 || (line != 0 && at_commandline))
22116               complaint (&symfile_complaints,
22117                          _("debug info gives %s macro %s with %s line %d: %s"),
22118                          at_commandline ? _("command-line") : _("in-file"),
22119                          is_define ? _("definition") : _("undefinition"),
22120                          line == 0 ? _("zero") : _("non-zero"), line, body);
22121
22122             if (is_define)
22123               parse_macro_definition (current_file, line, body);
22124             else
22125               {
22126                 gdb_assert (macinfo_type == DW_MACRO_undef
22127                             || macinfo_type == DW_MACRO_undef_strp
22128                             || macinfo_type == DW_MACRO_undef_sup);
22129                 macro_undef (current_file, line, body);
22130               }
22131           }
22132           break;
22133
22134         case DW_MACRO_start_file:
22135           {
22136             unsigned int bytes_read;
22137             int line, file;
22138
22139             line = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
22140             mac_ptr += bytes_read;
22141             file = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
22142             mac_ptr += bytes_read;
22143
22144             if ((line == 0 && !at_commandline)
22145                 || (line != 0 && at_commandline))
22146               complaint (&symfile_complaints,
22147                          _("debug info gives source %d included "
22148                            "from %s at %s line %d"),
22149                          file, at_commandline ? _("command-line") : _("file"),
22150                          line == 0 ? _("zero") : _("non-zero"), line);
22151
22152             if (at_commandline)
22153               {
22154                 /* This DW_MACRO_start_file was executed in the
22155                    pass one.  */
22156                 at_commandline = 0;
22157               }
22158             else
22159               current_file = macro_start_file (file, line, current_file, lh);
22160           }
22161           break;
22162
22163         case DW_MACRO_end_file:
22164           if (! current_file)
22165             complaint (&symfile_complaints,
22166                        _("macro debug info has an unmatched "
22167                          "`close_file' directive"));
22168           else
22169             {
22170               current_file = current_file->included_by;
22171               if (! current_file)
22172                 {
22173                   enum dwarf_macro_record_type next_type;
22174
22175                   /* GCC circa March 2002 doesn't produce the zero
22176                      type byte marking the end of the compilation
22177                      unit.  Complain if it's not there, but exit no
22178                      matter what.  */
22179
22180                   /* Do we at least have room for a macinfo type byte?  */
22181                   if (mac_ptr >= mac_end)
22182                     {
22183                       dwarf2_section_buffer_overflow_complaint (section);
22184                       return;
22185                     }
22186
22187                   /* We don't increment mac_ptr here, so this is just
22188                      a look-ahead.  */
22189                   next_type
22190                     = (enum dwarf_macro_record_type) read_1_byte (abfd,
22191                                                                   mac_ptr);
22192                   if (next_type != 0)
22193                     complaint (&symfile_complaints,
22194                                _("no terminating 0-type entry for "
22195                                  "macros in `.debug_macinfo' section"));
22196
22197                   return;
22198                 }
22199             }
22200           break;
22201
22202         case DW_MACRO_import:
22203         case DW_MACRO_import_sup:
22204           {
22205             LONGEST offset;
22206             void **slot;
22207             bfd *include_bfd = abfd;
22208             struct dwarf2_section_info *include_section = section;
22209             const gdb_byte *include_mac_end = mac_end;
22210             int is_dwz = section_is_dwz;
22211             const gdb_byte *new_mac_ptr;
22212
22213             offset = read_offset_1 (abfd, mac_ptr, offset_size);
22214             mac_ptr += offset_size;
22215
22216             if (macinfo_type == DW_MACRO_import_sup)
22217               {
22218                 struct dwz_file *dwz = dwarf2_get_dwz_file ();
22219
22220                 dwarf2_read_section (objfile, &dwz->macro);
22221
22222                 include_section = &dwz->macro;
22223                 include_bfd = get_section_bfd_owner (include_section);
22224                 include_mac_end = dwz->macro.buffer + dwz->macro.size;
22225                 is_dwz = 1;
22226               }
22227
22228             new_mac_ptr = include_section->buffer + offset;
22229             slot = htab_find_slot (include_hash, new_mac_ptr, INSERT);
22230
22231             if (*slot != NULL)
22232               {
22233                 /* This has actually happened; see
22234                    http://sourceware.org/bugzilla/show_bug.cgi?id=13568.  */
22235                 complaint (&symfile_complaints,
22236                            _("recursive DW_MACRO_import in "
22237                              ".debug_macro section"));
22238               }
22239             else
22240               {
22241                 *slot = (void *) new_mac_ptr;
22242
22243                 dwarf_decode_macro_bytes (include_bfd, new_mac_ptr,
22244                                           include_mac_end, current_file, lh,
22245                                           section, section_is_gnu, is_dwz,
22246                                           offset_size, include_hash);
22247
22248                 htab_remove_elt (include_hash, (void *) new_mac_ptr);
22249               }
22250           }
22251           break;
22252
22253         case DW_MACINFO_vendor_ext:
22254           if (!section_is_gnu)
22255             {
22256               unsigned int bytes_read;
22257
22258               /* This reads the constant, but since we don't recognize
22259                  any vendor extensions, we ignore it.  */
22260               read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
22261               mac_ptr += bytes_read;
22262               read_direct_string (abfd, mac_ptr, &bytes_read);
22263               mac_ptr += bytes_read;
22264
22265               /* We don't recognize any vendor extensions.  */
22266               break;
22267             }
22268           /* FALLTHROUGH */
22269
22270         default:
22271           mac_ptr = skip_unknown_opcode (macinfo_type, opcode_definitions,
22272                                          mac_ptr, mac_end, abfd, offset_size,
22273                                          section);
22274           if (mac_ptr == NULL)
22275             return;
22276           break;
22277         }
22278     } while (macinfo_type != 0);
22279 }
22280
22281 static void
22282 dwarf_decode_macros (struct dwarf2_cu *cu, unsigned int offset,
22283                      int section_is_gnu)
22284 {
22285   struct objfile *objfile = dwarf2_per_objfile->objfile;
22286   struct line_header *lh = cu->line_header;
22287   bfd *abfd;
22288   const gdb_byte *mac_ptr, *mac_end;
22289   struct macro_source_file *current_file = 0;
22290   enum dwarf_macro_record_type macinfo_type;
22291   unsigned int offset_size = cu->header.offset_size;
22292   const gdb_byte *opcode_definitions[256];
22293   struct cleanup *cleanup;
22294   void **slot;
22295   struct dwarf2_section_info *section;
22296   const char *section_name;
22297
22298   if (cu->dwo_unit != NULL)
22299     {
22300       if (section_is_gnu)
22301         {
22302           section = &cu->dwo_unit->dwo_file->sections.macro;
22303           section_name = ".debug_macro.dwo";
22304         }
22305       else
22306         {
22307           section = &cu->dwo_unit->dwo_file->sections.macinfo;
22308           section_name = ".debug_macinfo.dwo";
22309         }
22310     }
22311   else
22312     {
22313       if (section_is_gnu)
22314         {
22315           section = &dwarf2_per_objfile->macro;
22316           section_name = ".debug_macro";
22317         }
22318       else
22319         {
22320           section = &dwarf2_per_objfile->macinfo;
22321           section_name = ".debug_macinfo";
22322         }
22323     }
22324
22325   dwarf2_read_section (objfile, section);
22326   if (section->buffer == NULL)
22327     {
22328       complaint (&symfile_complaints, _("missing %s section"), section_name);
22329       return;
22330     }
22331   abfd = get_section_bfd_owner (section);
22332
22333   /* First pass: Find the name of the base filename.
22334      This filename is needed in order to process all macros whose definition
22335      (or undefinition) comes from the command line.  These macros are defined
22336      before the first DW_MACINFO_start_file entry, and yet still need to be
22337      associated to the base file.
22338
22339      To determine the base file name, we scan the macro definitions until we
22340      reach the first DW_MACINFO_start_file entry.  We then initialize
22341      CURRENT_FILE accordingly so that any macro definition found before the
22342      first DW_MACINFO_start_file can still be associated to the base file.  */
22343
22344   mac_ptr = section->buffer + offset;
22345   mac_end = section->buffer + section->size;
22346
22347   mac_ptr = dwarf_parse_macro_header (opcode_definitions, abfd, mac_ptr,
22348                                       &offset_size, section_is_gnu);
22349   if (mac_ptr == NULL)
22350     {
22351       /* We already issued a complaint.  */
22352       return;
22353     }
22354
22355   do
22356     {
22357       /* Do we at least have room for a macinfo type byte?  */
22358       if (mac_ptr >= mac_end)
22359         {
22360           /* Complaint is printed during the second pass as GDB will probably
22361              stop the first pass earlier upon finding
22362              DW_MACINFO_start_file.  */
22363           break;
22364         }
22365
22366       macinfo_type = (enum dwarf_macro_record_type) read_1_byte (abfd, mac_ptr);
22367       mac_ptr++;
22368
22369       /* Note that we rely on the fact that the corresponding GNU and
22370          DWARF constants are the same.  */
22371       switch (macinfo_type)
22372         {
22373           /* A zero macinfo type indicates the end of the macro
22374              information.  */
22375         case 0:
22376           break;
22377
22378         case DW_MACRO_define:
22379         case DW_MACRO_undef:
22380           /* Only skip the data by MAC_PTR.  */
22381           {
22382             unsigned int bytes_read;
22383
22384             read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
22385             mac_ptr += bytes_read;
22386             read_direct_string (abfd, mac_ptr, &bytes_read);
22387             mac_ptr += bytes_read;
22388           }
22389           break;
22390
22391         case DW_MACRO_start_file:
22392           {
22393             unsigned int bytes_read;
22394             int line, file;
22395
22396             line = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
22397             mac_ptr += bytes_read;
22398             file = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
22399             mac_ptr += bytes_read;
22400
22401             current_file = macro_start_file (file, line, current_file, lh);
22402           }
22403           break;
22404
22405         case DW_MACRO_end_file:
22406           /* No data to skip by MAC_PTR.  */
22407           break;
22408
22409         case DW_MACRO_define_strp:
22410         case DW_MACRO_undef_strp:
22411         case DW_MACRO_define_sup:
22412         case DW_MACRO_undef_sup:
22413           {
22414             unsigned int bytes_read;
22415
22416             read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
22417             mac_ptr += bytes_read;
22418             mac_ptr += offset_size;
22419           }
22420           break;
22421
22422         case DW_MACRO_import:
22423         case DW_MACRO_import_sup:
22424           /* Note that, according to the spec, a transparent include
22425              chain cannot call DW_MACRO_start_file.  So, we can just
22426              skip this opcode.  */
22427           mac_ptr += offset_size;
22428           break;
22429
22430         case DW_MACINFO_vendor_ext:
22431           /* Only skip the data by MAC_PTR.  */
22432           if (!section_is_gnu)
22433             {
22434               unsigned int bytes_read;
22435
22436               read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
22437               mac_ptr += bytes_read;
22438               read_direct_string (abfd, mac_ptr, &bytes_read);
22439               mac_ptr += bytes_read;
22440             }
22441           /* FALLTHROUGH */
22442
22443         default:
22444           mac_ptr = skip_unknown_opcode (macinfo_type, opcode_definitions,
22445                                          mac_ptr, mac_end, abfd, offset_size,
22446                                          section);
22447           if (mac_ptr == NULL)
22448             return;
22449           break;
22450         }
22451     } while (macinfo_type != 0 && current_file == NULL);
22452
22453   /* Second pass: Process all entries.
22454
22455      Use the AT_COMMAND_LINE flag to determine whether we are still processing
22456      command-line macro definitions/undefinitions.  This flag is unset when we
22457      reach the first DW_MACINFO_start_file entry.  */
22458
22459   htab_up include_hash (htab_create_alloc (1, htab_hash_pointer,
22460                                            htab_eq_pointer,
22461                                            NULL, xcalloc, xfree));
22462   mac_ptr = section->buffer + offset;
22463   slot = htab_find_slot (include_hash.get (), mac_ptr, INSERT);
22464   *slot = (void *) mac_ptr;
22465   dwarf_decode_macro_bytes (abfd, mac_ptr, mac_end,
22466                             current_file, lh, section,
22467                             section_is_gnu, 0, offset_size,
22468                             include_hash.get ());
22469 }
22470
22471 /* Check if the attribute's form is a DW_FORM_block*
22472    if so return true else false.  */
22473
22474 static int
22475 attr_form_is_block (const struct attribute *attr)
22476 {
22477   return (attr == NULL ? 0 :
22478       attr->form == DW_FORM_block1
22479       || attr->form == DW_FORM_block2
22480       || attr->form == DW_FORM_block4
22481       || attr->form == DW_FORM_block
22482       || attr->form == DW_FORM_exprloc);
22483 }
22484
22485 /* Return non-zero if ATTR's value is a section offset --- classes
22486    lineptr, loclistptr, macptr or rangelistptr --- or zero, otherwise.
22487    You may use DW_UNSND (attr) to retrieve such offsets.
22488
22489    Section 7.5.4, "Attribute Encodings", explains that no attribute
22490    may have a value that belongs to more than one of these classes; it
22491    would be ambiguous if we did, because we use the same forms for all
22492    of them.  */
22493
22494 static int
22495 attr_form_is_section_offset (const struct attribute *attr)
22496 {
22497   return (attr->form == DW_FORM_data4
22498           || attr->form == DW_FORM_data8
22499           || attr->form == DW_FORM_sec_offset);
22500 }
22501
22502 /* Return non-zero if ATTR's value falls in the 'constant' class, or
22503    zero otherwise.  When this function returns true, you can apply
22504    dwarf2_get_attr_constant_value to it.
22505
22506    However, note that for some attributes you must check
22507    attr_form_is_section_offset before using this test.  DW_FORM_data4
22508    and DW_FORM_data8 are members of both the constant class, and of
22509    the classes that contain offsets into other debug sections
22510    (lineptr, loclistptr, macptr or rangelistptr).  The DWARF spec says
22511    that, if an attribute's can be either a constant or one of the
22512    section offset classes, DW_FORM_data4 and DW_FORM_data8 should be
22513    taken as section offsets, not constants.
22514
22515    DW_FORM_data16 is not considered as dwarf2_get_attr_constant_value
22516    cannot handle that.  */
22517
22518 static int
22519 attr_form_is_constant (const struct attribute *attr)
22520 {
22521   switch (attr->form)
22522     {
22523     case DW_FORM_sdata:
22524     case DW_FORM_udata:
22525     case DW_FORM_data1:
22526     case DW_FORM_data2:
22527     case DW_FORM_data4:
22528     case DW_FORM_data8:
22529     case DW_FORM_implicit_const:
22530       return 1;
22531     default:
22532       return 0;
22533     }
22534 }
22535
22536
22537 /* DW_ADDR is always stored already as sect_offset; despite for the forms
22538    besides DW_FORM_ref_addr it is stored as cu_offset in the DWARF file.  */
22539
22540 static int
22541 attr_form_is_ref (const struct attribute *attr)
22542 {
22543   switch (attr->form)
22544     {
22545     case DW_FORM_ref_addr:
22546     case DW_FORM_ref1:
22547     case DW_FORM_ref2:
22548     case DW_FORM_ref4:
22549     case DW_FORM_ref8:
22550     case DW_FORM_ref_udata:
22551     case DW_FORM_GNU_ref_alt:
22552       return 1;
22553     default:
22554       return 0;
22555     }
22556 }
22557
22558 /* Return the .debug_loc section to use for CU.
22559    For DWO files use .debug_loc.dwo.  */
22560
22561 static struct dwarf2_section_info *
22562 cu_debug_loc_section (struct dwarf2_cu *cu)
22563 {
22564   if (cu->dwo_unit)
22565     {
22566       struct dwo_sections *sections = &cu->dwo_unit->dwo_file->sections;
22567       
22568       return cu->header.version >= 5 ? &sections->loclists : &sections->loc;
22569     }
22570   return (cu->header.version >= 5 ? &dwarf2_per_objfile->loclists
22571                                   : &dwarf2_per_objfile->loc);
22572 }
22573
22574 /* A helper function that fills in a dwarf2_loclist_baton.  */
22575
22576 static void
22577 fill_in_loclist_baton (struct dwarf2_cu *cu,
22578                        struct dwarf2_loclist_baton *baton,
22579                        const struct attribute *attr)
22580 {
22581   struct dwarf2_section_info *section = cu_debug_loc_section (cu);
22582
22583   dwarf2_read_section (dwarf2_per_objfile->objfile, section);
22584
22585   baton->per_cu = cu->per_cu;
22586   gdb_assert (baton->per_cu);
22587   /* We don't know how long the location list is, but make sure we
22588      don't run off the edge of the section.  */
22589   baton->size = section->size - DW_UNSND (attr);
22590   baton->data = section->buffer + DW_UNSND (attr);
22591   baton->base_address = cu->base_address;
22592   baton->from_dwo = cu->dwo_unit != NULL;
22593 }
22594
22595 static void
22596 dwarf2_symbol_mark_computed (const struct attribute *attr, struct symbol *sym,
22597                              struct dwarf2_cu *cu, int is_block)
22598 {
22599   struct objfile *objfile = dwarf2_per_objfile->objfile;
22600   struct dwarf2_section_info *section = cu_debug_loc_section (cu);
22601
22602   if (attr_form_is_section_offset (attr)
22603       /* .debug_loc{,.dwo} may not exist at all, or the offset may be outside
22604          the section.  If so, fall through to the complaint in the
22605          other branch.  */
22606       && DW_UNSND (attr) < dwarf2_section_size (objfile, section))
22607     {
22608       struct dwarf2_loclist_baton *baton;
22609
22610       baton = XOBNEW (&objfile->objfile_obstack, struct dwarf2_loclist_baton);
22611
22612       fill_in_loclist_baton (cu, baton, attr);
22613
22614       if (cu->base_known == 0)
22615         complaint (&symfile_complaints,
22616                    _("Location list used without "
22617                      "specifying the CU base address."));
22618
22619       SYMBOL_ACLASS_INDEX (sym) = (is_block
22620                                    ? dwarf2_loclist_block_index
22621                                    : dwarf2_loclist_index);
22622       SYMBOL_LOCATION_BATON (sym) = baton;
22623     }
22624   else
22625     {
22626       struct dwarf2_locexpr_baton *baton;
22627
22628       baton = XOBNEW (&objfile->objfile_obstack, struct dwarf2_locexpr_baton);
22629       baton->per_cu = cu->per_cu;
22630       gdb_assert (baton->per_cu);
22631
22632       if (attr_form_is_block (attr))
22633         {
22634           /* Note that we're just copying the block's data pointer
22635              here, not the actual data.  We're still pointing into the
22636              info_buffer for SYM's objfile; right now we never release
22637              that buffer, but when we do clean up properly this may
22638              need to change.  */
22639           baton->size = DW_BLOCK (attr)->size;
22640           baton->data = DW_BLOCK (attr)->data;
22641         }
22642       else
22643         {
22644           dwarf2_invalid_attrib_class_complaint ("location description",
22645                                                  SYMBOL_NATURAL_NAME (sym));
22646           baton->size = 0;
22647         }
22648
22649       SYMBOL_ACLASS_INDEX (sym) = (is_block
22650                                    ? dwarf2_locexpr_block_index
22651                                    : dwarf2_locexpr_index);
22652       SYMBOL_LOCATION_BATON (sym) = baton;
22653     }
22654 }
22655
22656 /* Return the OBJFILE associated with the compilation unit CU.  If CU
22657    came from a separate debuginfo file, then the master objfile is
22658    returned.  */
22659
22660 struct objfile *
22661 dwarf2_per_cu_objfile (struct dwarf2_per_cu_data *per_cu)
22662 {
22663   struct objfile *objfile = per_cu->objfile;
22664
22665   /* Return the master objfile, so that we can report and look up the
22666      correct file containing this variable.  */
22667   if (objfile->separate_debug_objfile_backlink)
22668     objfile = objfile->separate_debug_objfile_backlink;
22669
22670   return objfile;
22671 }
22672
22673 /* Return comp_unit_head for PER_CU, either already available in PER_CU->CU
22674    (CU_HEADERP is unused in such case) or prepare a temporary copy at
22675    CU_HEADERP first.  */
22676
22677 static const struct comp_unit_head *
22678 per_cu_header_read_in (struct comp_unit_head *cu_headerp,
22679                        struct dwarf2_per_cu_data *per_cu)
22680 {
22681   const gdb_byte *info_ptr;
22682
22683   if (per_cu->cu)
22684     return &per_cu->cu->header;
22685
22686   info_ptr = per_cu->section->buffer + to_underlying (per_cu->sect_off);
22687
22688   memset (cu_headerp, 0, sizeof (*cu_headerp));
22689   read_comp_unit_head (cu_headerp, info_ptr, per_cu->section,
22690                        rcuh_kind::COMPILE);
22691
22692   return cu_headerp;
22693 }
22694
22695 /* Return the address size given in the compilation unit header for CU.  */
22696
22697 int
22698 dwarf2_per_cu_addr_size (struct dwarf2_per_cu_data *per_cu)
22699 {
22700   struct comp_unit_head cu_header_local;
22701   const struct comp_unit_head *cu_headerp;
22702
22703   cu_headerp = per_cu_header_read_in (&cu_header_local, per_cu);
22704
22705   return cu_headerp->addr_size;
22706 }
22707
22708 /* Return the offset size given in the compilation unit header for CU.  */
22709
22710 int
22711 dwarf2_per_cu_offset_size (struct dwarf2_per_cu_data *per_cu)
22712 {
22713   struct comp_unit_head cu_header_local;
22714   const struct comp_unit_head *cu_headerp;
22715
22716   cu_headerp = per_cu_header_read_in (&cu_header_local, per_cu);
22717
22718   return cu_headerp->offset_size;
22719 }
22720
22721 /* See its dwarf2loc.h declaration.  */
22722
22723 int
22724 dwarf2_per_cu_ref_addr_size (struct dwarf2_per_cu_data *per_cu)
22725 {
22726   struct comp_unit_head cu_header_local;
22727   const struct comp_unit_head *cu_headerp;
22728
22729   cu_headerp = per_cu_header_read_in (&cu_header_local, per_cu);
22730
22731   if (cu_headerp->version == 2)
22732     return cu_headerp->addr_size;
22733   else
22734     return cu_headerp->offset_size;
22735 }
22736
22737 /* Return the text offset of the CU.  The returned offset comes from
22738    this CU's objfile.  If this objfile came from a separate debuginfo
22739    file, then the offset may be different from the corresponding
22740    offset in the parent objfile.  */
22741
22742 CORE_ADDR
22743 dwarf2_per_cu_text_offset (struct dwarf2_per_cu_data *per_cu)
22744 {
22745   struct objfile *objfile = per_cu->objfile;
22746
22747   return ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
22748 }
22749
22750 /* Return DWARF version number of PER_CU.  */
22751
22752 short
22753 dwarf2_version (struct dwarf2_per_cu_data *per_cu)
22754 {
22755   return per_cu->dwarf_version;
22756 }
22757
22758 /* Locate the .debug_info compilation unit from CU's objfile which contains
22759    the DIE at OFFSET.  Raises an error on failure.  */
22760
22761 static struct dwarf2_per_cu_data *
22762 dwarf2_find_containing_comp_unit (sect_offset sect_off,
22763                                   unsigned int offset_in_dwz,
22764                                   struct objfile *objfile)
22765 {
22766   struct dwarf2_per_cu_data *this_cu;
22767   int low, high;
22768   const sect_offset *cu_off;
22769
22770   low = 0;
22771   high = dwarf2_per_objfile->n_comp_units - 1;
22772   while (high > low)
22773     {
22774       struct dwarf2_per_cu_data *mid_cu;
22775       int mid = low + (high - low) / 2;
22776
22777       mid_cu = dwarf2_per_objfile->all_comp_units[mid];
22778       cu_off = &mid_cu->sect_off;
22779       if (mid_cu->is_dwz > offset_in_dwz
22780           || (mid_cu->is_dwz == offset_in_dwz && *cu_off >= sect_off))
22781         high = mid;
22782       else
22783         low = mid + 1;
22784     }
22785   gdb_assert (low == high);
22786   this_cu = dwarf2_per_objfile->all_comp_units[low];
22787   cu_off = &this_cu->sect_off;
22788   if (this_cu->is_dwz != offset_in_dwz || *cu_off > sect_off)
22789     {
22790       if (low == 0 || this_cu->is_dwz != offset_in_dwz)
22791         error (_("Dwarf Error: could not find partial DIE containing "
22792                "offset 0x%x [in module %s]"),
22793                to_underlying (sect_off), bfd_get_filename (objfile->obfd));
22794
22795       gdb_assert (dwarf2_per_objfile->all_comp_units[low-1]->sect_off
22796                   <= sect_off);
22797       return dwarf2_per_objfile->all_comp_units[low-1];
22798     }
22799   else
22800     {
22801       this_cu = dwarf2_per_objfile->all_comp_units[low];
22802       if (low == dwarf2_per_objfile->n_comp_units - 1
22803           && sect_off >= this_cu->sect_off + this_cu->length)
22804         error (_("invalid dwarf2 offset %u"), to_underlying (sect_off));
22805       gdb_assert (sect_off < this_cu->sect_off + this_cu->length);
22806       return this_cu;
22807     }
22808 }
22809
22810 /* Initialize dwarf2_cu CU, owned by PER_CU.  */
22811
22812 static void
22813 init_one_comp_unit (struct dwarf2_cu *cu, struct dwarf2_per_cu_data *per_cu)
22814 {
22815   memset (cu, 0, sizeof (*cu));
22816   per_cu->cu = cu;
22817   cu->per_cu = per_cu;
22818   cu->objfile = per_cu->objfile;
22819   obstack_init (&cu->comp_unit_obstack);
22820 }
22821
22822 /* Initialize basic fields of dwarf_cu CU according to DIE COMP_UNIT_DIE.  */
22823
22824 static void
22825 prepare_one_comp_unit (struct dwarf2_cu *cu, struct die_info *comp_unit_die,
22826                        enum language pretend_language)
22827 {
22828   struct attribute *attr;
22829
22830   /* Set the language we're debugging.  */
22831   attr = dwarf2_attr (comp_unit_die, DW_AT_language, cu);
22832   if (attr)
22833     set_cu_language (DW_UNSND (attr), cu);
22834   else
22835     {
22836       cu->language = pretend_language;
22837       cu->language_defn = language_def (cu->language);
22838     }
22839
22840   cu->producer = dwarf2_string_attr (comp_unit_die, DW_AT_producer, cu);
22841 }
22842
22843 /* Release one cached compilation unit, CU.  We unlink it from the tree
22844    of compilation units, but we don't remove it from the read_in_chain;
22845    the caller is responsible for that.
22846    NOTE: DATA is a void * because this function is also used as a
22847    cleanup routine.  */
22848
22849 static void
22850 free_heap_comp_unit (void *data)
22851 {
22852   struct dwarf2_cu *cu = (struct dwarf2_cu *) data;
22853
22854   gdb_assert (cu->per_cu != NULL);
22855   cu->per_cu->cu = NULL;
22856   cu->per_cu = NULL;
22857
22858   obstack_free (&cu->comp_unit_obstack, NULL);
22859
22860   xfree (cu);
22861 }
22862
22863 /* This cleanup function is passed the address of a dwarf2_cu on the stack
22864    when we're finished with it.  We can't free the pointer itself, but be
22865    sure to unlink it from the cache.  Also release any associated storage.  */
22866
22867 static void
22868 free_stack_comp_unit (void *data)
22869 {
22870   struct dwarf2_cu *cu = (struct dwarf2_cu *) data;
22871
22872   gdb_assert (cu->per_cu != NULL);
22873   cu->per_cu->cu = NULL;
22874   cu->per_cu = NULL;
22875
22876   obstack_free (&cu->comp_unit_obstack, NULL);
22877   cu->partial_dies = NULL;
22878 }
22879
22880 /* Free all cached compilation units.  */
22881
22882 static void
22883 free_cached_comp_units (void *data)
22884 {
22885   dwarf2_per_objfile->free_cached_comp_units ();
22886 }
22887
22888 /* Increase the age counter on each cached compilation unit, and free
22889    any that are too old.  */
22890
22891 static void
22892 age_cached_comp_units (void)
22893 {
22894   struct dwarf2_per_cu_data *per_cu, **last_chain;
22895
22896   dwarf2_clear_marks (dwarf2_per_objfile->read_in_chain);
22897   per_cu = dwarf2_per_objfile->read_in_chain;
22898   while (per_cu != NULL)
22899     {
22900       per_cu->cu->last_used ++;
22901       if (per_cu->cu->last_used <= dwarf_max_cache_age)
22902         dwarf2_mark (per_cu->cu);
22903       per_cu = per_cu->cu->read_in_chain;
22904     }
22905
22906   per_cu = dwarf2_per_objfile->read_in_chain;
22907   last_chain = &dwarf2_per_objfile->read_in_chain;
22908   while (per_cu != NULL)
22909     {
22910       struct dwarf2_per_cu_data *next_cu;
22911
22912       next_cu = per_cu->cu->read_in_chain;
22913
22914       if (!per_cu->cu->mark)
22915         {
22916           free_heap_comp_unit (per_cu->cu);
22917           *last_chain = next_cu;
22918         }
22919       else
22920         last_chain = &per_cu->cu->read_in_chain;
22921
22922       per_cu = next_cu;
22923     }
22924 }
22925
22926 /* Remove a single compilation unit from the cache.  */
22927
22928 static void
22929 free_one_cached_comp_unit (struct dwarf2_per_cu_data *target_per_cu)
22930 {
22931   struct dwarf2_per_cu_data *per_cu, **last_chain;
22932
22933   per_cu = dwarf2_per_objfile->read_in_chain;
22934   last_chain = &dwarf2_per_objfile->read_in_chain;
22935   while (per_cu != NULL)
22936     {
22937       struct dwarf2_per_cu_data *next_cu;
22938
22939       next_cu = per_cu->cu->read_in_chain;
22940
22941       if (per_cu == target_per_cu)
22942         {
22943           free_heap_comp_unit (per_cu->cu);
22944           per_cu->cu = NULL;
22945           *last_chain = next_cu;
22946           break;
22947         }
22948       else
22949         last_chain = &per_cu->cu->read_in_chain;
22950
22951       per_cu = next_cu;
22952     }
22953 }
22954
22955 /* Release all extra memory associated with OBJFILE.  */
22956
22957 void
22958 dwarf2_free_objfile (struct objfile *objfile)
22959 {
22960   dwarf2_per_objfile
22961     = (struct dwarf2_per_objfile *) objfile_data (objfile,
22962                                                   dwarf2_objfile_data_key);
22963
22964   if (dwarf2_per_objfile == NULL)
22965     return;
22966
22967   dwarf2_per_objfile->~dwarf2_per_objfile ();
22968 }
22969
22970 /* A set of CU "per_cu" pointer, DIE offset, and GDB type pointer.
22971    We store these in a hash table separate from the DIEs, and preserve them
22972    when the DIEs are flushed out of cache.
22973
22974    The CU "per_cu" pointer is needed because offset alone is not enough to
22975    uniquely identify the type.  A file may have multiple .debug_types sections,
22976    or the type may come from a DWO file.  Furthermore, while it's more logical
22977    to use per_cu->section+offset, with Fission the section with the data is in
22978    the DWO file but we don't know that section at the point we need it.
22979    We have to use something in dwarf2_per_cu_data (or the pointer to it)
22980    because we can enter the lookup routine, get_die_type_at_offset, from
22981    outside this file, and thus won't necessarily have PER_CU->cu.
22982    Fortunately, PER_CU is stable for the life of the objfile.  */
22983
22984 struct dwarf2_per_cu_offset_and_type
22985 {
22986   const struct dwarf2_per_cu_data *per_cu;
22987   sect_offset sect_off;
22988   struct type *type;
22989 };
22990
22991 /* Hash function for a dwarf2_per_cu_offset_and_type.  */
22992
22993 static hashval_t
22994 per_cu_offset_and_type_hash (const void *item)
22995 {
22996   const struct dwarf2_per_cu_offset_and_type *ofs
22997     = (const struct dwarf2_per_cu_offset_and_type *) item;
22998
22999   return (uintptr_t) ofs->per_cu + to_underlying (ofs->sect_off);
23000 }
23001
23002 /* Equality function for a dwarf2_per_cu_offset_and_type.  */
23003
23004 static int
23005 per_cu_offset_and_type_eq (const void *item_lhs, const void *item_rhs)
23006 {
23007   const struct dwarf2_per_cu_offset_and_type *ofs_lhs
23008     = (const struct dwarf2_per_cu_offset_and_type *) item_lhs;
23009   const struct dwarf2_per_cu_offset_and_type *ofs_rhs
23010     = (const struct dwarf2_per_cu_offset_and_type *) item_rhs;
23011
23012   return (ofs_lhs->per_cu == ofs_rhs->per_cu
23013           && ofs_lhs->sect_off == ofs_rhs->sect_off);
23014 }
23015
23016 /* Set the type associated with DIE to TYPE.  Save it in CU's hash
23017    table if necessary.  For convenience, return TYPE.
23018
23019    The DIEs reading must have careful ordering to:
23020     * Not cause infite loops trying to read in DIEs as a prerequisite for
23021       reading current DIE.
23022     * Not trying to dereference contents of still incompletely read in types
23023       while reading in other DIEs.
23024     * Enable referencing still incompletely read in types just by a pointer to
23025       the type without accessing its fields.
23026
23027    Therefore caller should follow these rules:
23028      * Try to fetch any prerequisite types we may need to build this DIE type
23029        before building the type and calling set_die_type.
23030      * After building type call set_die_type for current DIE as soon as
23031        possible before fetching more types to complete the current type.
23032      * Make the type as complete as possible before fetching more types.  */
23033
23034 static struct type *
23035 set_die_type (struct die_info *die, struct type *type, struct dwarf2_cu *cu)
23036 {
23037   struct dwarf2_per_cu_offset_and_type **slot, ofs;
23038   struct objfile *objfile = cu->objfile;
23039   struct attribute *attr;
23040   struct dynamic_prop prop;
23041
23042   /* For Ada types, make sure that the gnat-specific data is always
23043      initialized (if not already set).  There are a few types where
23044      we should not be doing so, because the type-specific area is
23045      already used to hold some other piece of info (eg: TYPE_CODE_FLT
23046      where the type-specific area is used to store the floatformat).
23047      But this is not a problem, because the gnat-specific information
23048      is actually not needed for these types.  */
23049   if (need_gnat_info (cu)
23050       && TYPE_CODE (type) != TYPE_CODE_FUNC
23051       && TYPE_CODE (type) != TYPE_CODE_FLT
23052       && TYPE_CODE (type) != TYPE_CODE_METHODPTR
23053       && TYPE_CODE (type) != TYPE_CODE_MEMBERPTR
23054       && TYPE_CODE (type) != TYPE_CODE_METHOD
23055       && !HAVE_GNAT_AUX_INFO (type))
23056     INIT_GNAT_SPECIFIC (type);
23057
23058   /* Read DW_AT_allocated and set in type.  */
23059   attr = dwarf2_attr (die, DW_AT_allocated, cu);
23060   if (attr_form_is_block (attr))
23061     {
23062       if (attr_to_dynamic_prop (attr, die, cu, &prop))
23063         add_dyn_prop (DYN_PROP_ALLOCATED, prop, type, objfile);
23064     }
23065   else if (attr != NULL)
23066     {
23067       complaint (&symfile_complaints,
23068                  _("DW_AT_allocated has the wrong form (%s) at DIE 0x%x"),
23069                  (attr != NULL ? dwarf_form_name (attr->form) : "n/a"),
23070                  to_underlying (die->sect_off));
23071     }
23072
23073   /* Read DW_AT_associated and set in type.  */
23074   attr = dwarf2_attr (die, DW_AT_associated, cu);
23075   if (attr_form_is_block (attr))
23076     {
23077       if (attr_to_dynamic_prop (attr, die, cu, &prop))
23078         add_dyn_prop (DYN_PROP_ASSOCIATED, prop, type, objfile);
23079     }
23080   else if (attr != NULL)
23081     {
23082       complaint (&symfile_complaints,
23083                  _("DW_AT_associated has the wrong form (%s) at DIE 0x%x"),
23084                  (attr != NULL ? dwarf_form_name (attr->form) : "n/a"),
23085                  to_underlying (die->sect_off));
23086     }
23087
23088   /* Read DW_AT_data_location and set in type.  */
23089   attr = dwarf2_attr (die, DW_AT_data_location, cu);
23090   if (attr_to_dynamic_prop (attr, die, cu, &prop))
23091     add_dyn_prop (DYN_PROP_DATA_LOCATION, prop, type, objfile);
23092
23093   if (dwarf2_per_objfile->die_type_hash == NULL)
23094     {
23095       dwarf2_per_objfile->die_type_hash =
23096         htab_create_alloc_ex (127,
23097                               per_cu_offset_and_type_hash,
23098                               per_cu_offset_and_type_eq,
23099                               NULL,
23100                               &objfile->objfile_obstack,
23101                               hashtab_obstack_allocate,
23102                               dummy_obstack_deallocate);
23103     }
23104
23105   ofs.per_cu = cu->per_cu;
23106   ofs.sect_off = die->sect_off;
23107   ofs.type = type;
23108   slot = (struct dwarf2_per_cu_offset_and_type **)
23109     htab_find_slot (dwarf2_per_objfile->die_type_hash, &ofs, INSERT);
23110   if (*slot)
23111     complaint (&symfile_complaints,
23112                _("A problem internal to GDB: DIE 0x%x has type already set"),
23113                to_underlying (die->sect_off));
23114   *slot = XOBNEW (&objfile->objfile_obstack,
23115                   struct dwarf2_per_cu_offset_and_type);
23116   **slot = ofs;
23117   return type;
23118 }
23119
23120 /* Look up the type for the die at SECT_OFF in PER_CU in die_type_hash,
23121    or return NULL if the die does not have a saved type.  */
23122
23123 static struct type *
23124 get_die_type_at_offset (sect_offset sect_off,
23125                         struct dwarf2_per_cu_data *per_cu)
23126 {
23127   struct dwarf2_per_cu_offset_and_type *slot, ofs;
23128
23129   if (dwarf2_per_objfile->die_type_hash == NULL)
23130     return NULL;
23131
23132   ofs.per_cu = per_cu;
23133   ofs.sect_off = sect_off;
23134   slot = ((struct dwarf2_per_cu_offset_and_type *)
23135           htab_find (dwarf2_per_objfile->die_type_hash, &ofs));
23136   if (slot)
23137     return slot->type;
23138   else
23139     return NULL;
23140 }
23141
23142 /* Look up the type for DIE in CU in die_type_hash,
23143    or return NULL if DIE does not have a saved type.  */
23144
23145 static struct type *
23146 get_die_type (struct die_info *die, struct dwarf2_cu *cu)
23147 {
23148   return get_die_type_at_offset (die->sect_off, cu->per_cu);
23149 }
23150
23151 /* Add a dependence relationship from CU to REF_PER_CU.  */
23152
23153 static void
23154 dwarf2_add_dependence (struct dwarf2_cu *cu,
23155                        struct dwarf2_per_cu_data *ref_per_cu)
23156 {
23157   void **slot;
23158
23159   if (cu->dependencies == NULL)
23160     cu->dependencies
23161       = htab_create_alloc_ex (5, htab_hash_pointer, htab_eq_pointer,
23162                               NULL, &cu->comp_unit_obstack,
23163                               hashtab_obstack_allocate,
23164                               dummy_obstack_deallocate);
23165
23166   slot = htab_find_slot (cu->dependencies, ref_per_cu, INSERT);
23167   if (*slot == NULL)
23168     *slot = ref_per_cu;
23169 }
23170
23171 /* Subroutine of dwarf2_mark to pass to htab_traverse.
23172    Set the mark field in every compilation unit in the
23173    cache that we must keep because we are keeping CU.  */
23174
23175 static int
23176 dwarf2_mark_helper (void **slot, void *data)
23177 {
23178   struct dwarf2_per_cu_data *per_cu;
23179
23180   per_cu = (struct dwarf2_per_cu_data *) *slot;
23181
23182   /* cu->dependencies references may not yet have been ever read if QUIT aborts
23183      reading of the chain.  As such dependencies remain valid it is not much
23184      useful to track and undo them during QUIT cleanups.  */
23185   if (per_cu->cu == NULL)
23186     return 1;
23187
23188   if (per_cu->cu->mark)
23189     return 1;
23190   per_cu->cu->mark = 1;
23191
23192   if (per_cu->cu->dependencies != NULL)
23193     htab_traverse (per_cu->cu->dependencies, dwarf2_mark_helper, NULL);
23194
23195   return 1;
23196 }
23197
23198 /* Set the mark field in CU and in every other compilation unit in the
23199    cache that we must keep because we are keeping CU.  */
23200
23201 static void
23202 dwarf2_mark (struct dwarf2_cu *cu)
23203 {
23204   if (cu->mark)
23205     return;
23206   cu->mark = 1;
23207   if (cu->dependencies != NULL)
23208     htab_traverse (cu->dependencies, dwarf2_mark_helper, NULL);
23209 }
23210
23211 static void
23212 dwarf2_clear_marks (struct dwarf2_per_cu_data *per_cu)
23213 {
23214   while (per_cu)
23215     {
23216       per_cu->cu->mark = 0;
23217       per_cu = per_cu->cu->read_in_chain;
23218     }
23219 }
23220
23221 /* Trivial hash function for partial_die_info: the hash value of a DIE
23222    is its offset in .debug_info for this objfile.  */
23223
23224 static hashval_t
23225 partial_die_hash (const void *item)
23226 {
23227   const struct partial_die_info *part_die
23228     = (const struct partial_die_info *) item;
23229
23230   return to_underlying (part_die->sect_off);
23231 }
23232
23233 /* Trivial comparison function for partial_die_info structures: two DIEs
23234    are equal if they have the same offset.  */
23235
23236 static int
23237 partial_die_eq (const void *item_lhs, const void *item_rhs)
23238 {
23239   const struct partial_die_info *part_die_lhs
23240     = (const struct partial_die_info *) item_lhs;
23241   const struct partial_die_info *part_die_rhs
23242     = (const struct partial_die_info *) item_rhs;
23243
23244   return part_die_lhs->sect_off == part_die_rhs->sect_off;
23245 }
23246
23247 static struct cmd_list_element *set_dwarf_cmdlist;
23248 static struct cmd_list_element *show_dwarf_cmdlist;
23249
23250 static void
23251 set_dwarf_cmd (char *args, int from_tty)
23252 {
23253   help_list (set_dwarf_cmdlist, "maintenance set dwarf ", all_commands,
23254              gdb_stdout);
23255 }
23256
23257 static void
23258 show_dwarf_cmd (char *args, int from_tty)
23259 {
23260   cmd_show_list (show_dwarf_cmdlist, from_tty, "");
23261 }
23262
23263 /* Free data associated with OBJFILE, if necessary.  */
23264
23265 static void
23266 dwarf2_per_objfile_free (struct objfile *objfile, void *d)
23267 {
23268   struct dwarf2_per_objfile *data = (struct dwarf2_per_objfile *) d;
23269   int ix;
23270
23271   /* Make sure we don't accidentally use dwarf2_per_objfile while
23272      cleaning up.  */
23273   dwarf2_per_objfile = NULL;
23274
23275   for (ix = 0; ix < data->n_comp_units; ++ix)
23276    VEC_free (dwarf2_per_cu_ptr, data->all_comp_units[ix]->imported_symtabs);
23277
23278   for (ix = 0; ix < data->n_type_units; ++ix)
23279     VEC_free (dwarf2_per_cu_ptr,
23280               data->all_type_units[ix]->per_cu.imported_symtabs);
23281   xfree (data->all_type_units);
23282
23283   VEC_free (dwarf2_section_info_def, data->types);
23284
23285   if (data->dwo_files)
23286     free_dwo_files (data->dwo_files, objfile);
23287   if (data->dwp_file)
23288     gdb_bfd_unref (data->dwp_file->dbfd);
23289
23290   if (data->dwz_file && data->dwz_file->dwz_bfd)
23291     gdb_bfd_unref (data->dwz_file->dwz_bfd);
23292 }
23293
23294 \f
23295 /* The "save gdb-index" command.  */
23296
23297 /* In-memory buffer to prepare data to be written later to a file.  */
23298 class data_buf
23299 {
23300 public:
23301   /* Copy DATA to the end of the buffer.  */
23302   template<typename T>
23303   void append_data (const T &data)
23304   {
23305     std::copy (reinterpret_cast<const gdb_byte *> (&data),
23306                reinterpret_cast<const gdb_byte *> (&data + 1),
23307                grow (sizeof (data)));
23308   }
23309
23310   /* Copy CSTR (a zero-terminated string) to the end of buffer.  The
23311      terminating zero is appended too.  */
23312   void append_cstr0 (const char *cstr)
23313   {
23314     const size_t size = strlen (cstr) + 1;
23315     std::copy (cstr, cstr + size, grow (size));
23316   }
23317
23318   /* Accept a host-format integer in VAL and append it to the buffer
23319      as a target-format integer which is LEN bytes long.  */
23320   void append_uint (size_t len, bfd_endian byte_order, ULONGEST val)
23321   {
23322     ::store_unsigned_integer (grow (len), len, byte_order, val);
23323   }
23324
23325   /* Return the size of the buffer.  */
23326   size_t size () const
23327   {
23328     return m_vec.size ();
23329   }
23330
23331   /* Write the buffer to FILE.  */
23332   void file_write (FILE *file) const
23333   {
23334     if (::fwrite (m_vec.data (), 1, m_vec.size (), file) != m_vec.size ())
23335       error (_("couldn't write data to file"));
23336   }
23337
23338 private:
23339   /* Grow SIZE bytes at the end of the buffer.  Returns a pointer to
23340      the start of the new block.  */
23341   gdb_byte *grow (size_t size)
23342   {
23343     m_vec.resize (m_vec.size () + size);
23344     return &*m_vec.end () - size;
23345   }
23346
23347   gdb::byte_vector m_vec;
23348 };
23349
23350 /* An entry in the symbol table.  */
23351 struct symtab_index_entry
23352 {
23353   /* The name of the symbol.  */
23354   const char *name;
23355   /* The offset of the name in the constant pool.  */
23356   offset_type index_offset;
23357   /* A sorted vector of the indices of all the CUs that hold an object
23358      of this name.  */
23359   std::vector<offset_type> cu_indices;
23360 };
23361
23362 /* The symbol table.  This is a power-of-2-sized hash table.  */
23363 struct mapped_symtab
23364 {
23365   mapped_symtab ()
23366   {
23367     data.resize (1024);
23368   }
23369
23370   offset_type n_elements = 0;
23371   std::vector<symtab_index_entry> data;
23372 };
23373
23374 /* Find a slot in SYMTAB for the symbol NAME.  Returns a reference to
23375    the slot.
23376    
23377    Function is used only during write_hash_table so no index format backward
23378    compatibility is needed.  */
23379
23380 static symtab_index_entry &
23381 find_slot (struct mapped_symtab *symtab, const char *name)
23382 {
23383   offset_type index, step, hash = mapped_index_string_hash (INT_MAX, name);
23384
23385   index = hash & (symtab->data.size () - 1);
23386   step = ((hash * 17) & (symtab->data.size () - 1)) | 1;
23387
23388   for (;;)
23389     {
23390       if (symtab->data[index].name == NULL
23391           || strcmp (name, symtab->data[index].name) == 0)
23392         return symtab->data[index];
23393       index = (index + step) & (symtab->data.size () - 1);
23394     }
23395 }
23396
23397 /* Expand SYMTAB's hash table.  */
23398
23399 static void
23400 hash_expand (struct mapped_symtab *symtab)
23401 {
23402   auto old_entries = std::move (symtab->data);
23403
23404   symtab->data.clear ();
23405   symtab->data.resize (old_entries.size () * 2);
23406
23407   for (auto &it : old_entries)
23408     if (it.name != NULL)
23409       {
23410         auto &ref = find_slot (symtab, it.name);
23411         ref = std::move (it);
23412       }
23413 }
23414
23415 /* Add an entry to SYMTAB.  NAME is the name of the symbol.
23416    CU_INDEX is the index of the CU in which the symbol appears.
23417    IS_STATIC is one if the symbol is static, otherwise zero (global).  */
23418
23419 static void
23420 add_index_entry (struct mapped_symtab *symtab, const char *name,
23421                  int is_static, gdb_index_symbol_kind kind,
23422                  offset_type cu_index)
23423 {
23424   offset_type cu_index_and_attrs;
23425
23426   ++symtab->n_elements;
23427   if (4 * symtab->n_elements / 3 >= symtab->data.size ())
23428     hash_expand (symtab);
23429
23430   symtab_index_entry &slot = find_slot (symtab, name);
23431   if (slot.name == NULL)
23432     {
23433       slot.name = name;
23434       /* index_offset is set later.  */
23435     }
23436
23437   cu_index_and_attrs = 0;
23438   DW2_GDB_INDEX_CU_SET_VALUE (cu_index_and_attrs, cu_index);
23439   DW2_GDB_INDEX_SYMBOL_STATIC_SET_VALUE (cu_index_and_attrs, is_static);
23440   DW2_GDB_INDEX_SYMBOL_KIND_SET_VALUE (cu_index_and_attrs, kind);
23441
23442   /* We don't want to record an index value twice as we want to avoid the
23443      duplication.
23444      We process all global symbols and then all static symbols
23445      (which would allow us to avoid the duplication by only having to check
23446      the last entry pushed), but a symbol could have multiple kinds in one CU.
23447      To keep things simple we don't worry about the duplication here and
23448      sort and uniqufy the list after we've processed all symbols.  */
23449   slot.cu_indices.push_back (cu_index_and_attrs);
23450 }
23451
23452 /* Sort and remove duplicates of all symbols' cu_indices lists.  */
23453
23454 static void
23455 uniquify_cu_indices (struct mapped_symtab *symtab)
23456 {
23457   for (auto &entry : symtab->data)
23458     {
23459       if (entry.name != NULL && !entry.cu_indices.empty ())
23460         {
23461           auto &cu_indices = entry.cu_indices;
23462           std::sort (cu_indices.begin (), cu_indices.end ());
23463           auto from = std::unique (cu_indices.begin (), cu_indices.end ());
23464           cu_indices.erase (from, cu_indices.end ());
23465         }
23466     }
23467 }
23468
23469 /* A form of 'const char *' suitable for container keys.  Only the
23470    pointer is stored.  The strings themselves are compared, not the
23471    pointers.  */
23472 class c_str_view
23473 {
23474 public:
23475   c_str_view (const char *cstr)
23476     : m_cstr (cstr)
23477   {}
23478
23479   bool operator== (const c_str_view &other) const
23480   {
23481     return strcmp (m_cstr, other.m_cstr) == 0;
23482   }
23483
23484 private:
23485   friend class c_str_view_hasher;
23486   const char *const m_cstr;
23487 };
23488
23489 /* A std::unordered_map::hasher for c_str_view that uses the right
23490    hash function for strings in a mapped index.  */
23491 class c_str_view_hasher
23492 {
23493 public:
23494   size_t operator () (const c_str_view &x) const
23495   {
23496     return mapped_index_string_hash (INT_MAX, x.m_cstr);
23497   }
23498 };
23499
23500 /* A std::unordered_map::hasher for std::vector<>.  */
23501 template<typename T>
23502 class vector_hasher
23503 {
23504 public:
23505   size_t operator () (const std::vector<T> &key) const
23506   {
23507     return iterative_hash (key.data (),
23508                            sizeof (key.front ()) * key.size (), 0);
23509   }
23510 };
23511
23512 /* Write the mapped hash table SYMTAB to the data buffer OUTPUT, with
23513    constant pool entries going into the data buffer CPOOL.  */
23514
23515 static void
23516 write_hash_table (mapped_symtab *symtab, data_buf &output, data_buf &cpool)
23517 {
23518   {
23519     /* Elements are sorted vectors of the indices of all the CUs that
23520        hold an object of this name.  */
23521     std::unordered_map<std::vector<offset_type>, offset_type,
23522                        vector_hasher<offset_type>>
23523       symbol_hash_table;
23524
23525     /* We add all the index vectors to the constant pool first, to
23526        ensure alignment is ok.  */
23527     for (symtab_index_entry &entry : symtab->data)
23528       {
23529         if (entry.name == NULL)
23530           continue;
23531         gdb_assert (entry.index_offset == 0);
23532
23533         /* Finding before inserting is faster than always trying to
23534            insert, because inserting always allocates a node, does the
23535            lookup, and then destroys the new node if another node
23536            already had the same key.  C++17 try_emplace will avoid
23537            this.  */
23538         const auto found
23539           = symbol_hash_table.find (entry.cu_indices);
23540         if (found != symbol_hash_table.end ())
23541           {
23542             entry.index_offset = found->second;
23543             continue;
23544           }
23545
23546         symbol_hash_table.emplace (entry.cu_indices, cpool.size ());
23547         entry.index_offset = cpool.size ();
23548         cpool.append_data (MAYBE_SWAP (entry.cu_indices.size ()));
23549         for (const auto index : entry.cu_indices)
23550           cpool.append_data (MAYBE_SWAP (index));
23551       }
23552   }
23553
23554   /* Now write out the hash table.  */
23555   std::unordered_map<c_str_view, offset_type, c_str_view_hasher> str_table;
23556   for (const auto &entry : symtab->data)
23557     {
23558       offset_type str_off, vec_off;
23559
23560       if (entry.name != NULL)
23561         {
23562           const auto insertpair = str_table.emplace (entry.name, cpool.size ());
23563           if (insertpair.second)
23564             cpool.append_cstr0 (entry.name);
23565           str_off = insertpair.first->second;
23566           vec_off = entry.index_offset;
23567         }
23568       else
23569         {
23570           /* While 0 is a valid constant pool index, it is not valid
23571              to have 0 for both offsets.  */
23572           str_off = 0;
23573           vec_off = 0;
23574         }
23575
23576       output.append_data (MAYBE_SWAP (str_off));
23577       output.append_data (MAYBE_SWAP (vec_off));
23578     }
23579 }
23580
23581 typedef std::unordered_map<partial_symtab *, unsigned int> psym_index_map;
23582
23583 /* Helper struct for building the address table.  */
23584 struct addrmap_index_data
23585 {
23586   addrmap_index_data (data_buf &addr_vec_, psym_index_map &cu_index_htab_)
23587     : addr_vec (addr_vec_), cu_index_htab (cu_index_htab_)
23588   {}
23589
23590   struct objfile *objfile;
23591   data_buf &addr_vec;
23592   psym_index_map &cu_index_htab;
23593
23594   /* Non-zero if the previous_* fields are valid.
23595      We can't write an entry until we see the next entry (since it is only then
23596      that we know the end of the entry).  */
23597   int previous_valid;
23598   /* Index of the CU in the table of all CUs in the index file.  */
23599   unsigned int previous_cu_index;
23600   /* Start address of the CU.  */
23601   CORE_ADDR previous_cu_start;
23602 };
23603
23604 /* Write an address entry to ADDR_VEC.  */
23605
23606 static void
23607 add_address_entry (struct objfile *objfile, data_buf &addr_vec,
23608                    CORE_ADDR start, CORE_ADDR end, unsigned int cu_index)
23609 {
23610   CORE_ADDR baseaddr;
23611
23612   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
23613
23614   addr_vec.append_uint (8, BFD_ENDIAN_LITTLE, start - baseaddr);
23615   addr_vec.append_uint (8, BFD_ENDIAN_LITTLE, end - baseaddr);
23616   addr_vec.append_data (MAYBE_SWAP (cu_index));
23617 }
23618
23619 /* Worker function for traversing an addrmap to build the address table.  */
23620
23621 static int
23622 add_address_entry_worker (void *datap, CORE_ADDR start_addr, void *obj)
23623 {
23624   struct addrmap_index_data *data = (struct addrmap_index_data *) datap;
23625   struct partial_symtab *pst = (struct partial_symtab *) obj;
23626
23627   if (data->previous_valid)
23628     add_address_entry (data->objfile, data->addr_vec,
23629                        data->previous_cu_start, start_addr,
23630                        data->previous_cu_index);
23631
23632   data->previous_cu_start = start_addr;
23633   if (pst != NULL)
23634     {
23635       const auto it = data->cu_index_htab.find (pst);
23636       gdb_assert (it != data->cu_index_htab.cend ());
23637       data->previous_cu_index = it->second;
23638       data->previous_valid = 1;
23639     }
23640   else
23641     data->previous_valid = 0;
23642
23643   return 0;
23644 }
23645
23646 /* Write OBJFILE's address map to ADDR_VEC.
23647    CU_INDEX_HTAB is used to map addrmap entries to their CU indices
23648    in the index file.  */
23649
23650 static void
23651 write_address_map (struct objfile *objfile, data_buf &addr_vec,
23652                    psym_index_map &cu_index_htab)
23653 {
23654   struct addrmap_index_data addrmap_index_data (addr_vec, cu_index_htab);
23655
23656   /* When writing the address table, we have to cope with the fact that
23657      the addrmap iterator only provides the start of a region; we have to
23658      wait until the next invocation to get the start of the next region.  */
23659
23660   addrmap_index_data.objfile = objfile;
23661   addrmap_index_data.previous_valid = 0;
23662
23663   addrmap_foreach (objfile->psymtabs_addrmap, add_address_entry_worker,
23664                    &addrmap_index_data);
23665
23666   /* It's highly unlikely the last entry (end address = 0xff...ff)
23667      is valid, but we should still handle it.
23668      The end address is recorded as the start of the next region, but that
23669      doesn't work here.  To cope we pass 0xff...ff, this is a rare situation
23670      anyway.  */
23671   if (addrmap_index_data.previous_valid)
23672     add_address_entry (objfile, addr_vec,
23673                        addrmap_index_data.previous_cu_start, (CORE_ADDR) -1,
23674                        addrmap_index_data.previous_cu_index);
23675 }
23676
23677 /* Return the symbol kind of PSYM.  */
23678
23679 static gdb_index_symbol_kind
23680 symbol_kind (struct partial_symbol *psym)
23681 {
23682   domain_enum domain = PSYMBOL_DOMAIN (psym);
23683   enum address_class aclass = PSYMBOL_CLASS (psym);
23684
23685   switch (domain)
23686     {
23687     case VAR_DOMAIN:
23688       switch (aclass)
23689         {
23690         case LOC_BLOCK:
23691           return GDB_INDEX_SYMBOL_KIND_FUNCTION;
23692         case LOC_TYPEDEF:
23693           return GDB_INDEX_SYMBOL_KIND_TYPE;
23694         case LOC_COMPUTED:
23695         case LOC_CONST_BYTES:
23696         case LOC_OPTIMIZED_OUT:
23697         case LOC_STATIC:
23698           return GDB_INDEX_SYMBOL_KIND_VARIABLE;
23699         case LOC_CONST:
23700           /* Note: It's currently impossible to recognize psyms as enum values
23701              short of reading the type info.  For now punt.  */
23702           return GDB_INDEX_SYMBOL_KIND_VARIABLE;
23703         default:
23704           /* There are other LOC_FOO values that one might want to classify
23705              as variables, but dwarf2read.c doesn't currently use them.  */
23706           return GDB_INDEX_SYMBOL_KIND_OTHER;
23707         }
23708     case STRUCT_DOMAIN:
23709       return GDB_INDEX_SYMBOL_KIND_TYPE;
23710     default:
23711       return GDB_INDEX_SYMBOL_KIND_OTHER;
23712     }
23713 }
23714
23715 /* Add a list of partial symbols to SYMTAB.  */
23716
23717 static void
23718 write_psymbols (struct mapped_symtab *symtab,
23719                 std::unordered_set<partial_symbol *> &psyms_seen,
23720                 struct partial_symbol **psymp,
23721                 int count,
23722                 offset_type cu_index,
23723                 int is_static)
23724 {
23725   for (; count-- > 0; ++psymp)
23726     {
23727       struct partial_symbol *psym = *psymp;
23728
23729       if (SYMBOL_LANGUAGE (psym) == language_ada)
23730         error (_("Ada is not currently supported by the index"));
23731
23732       /* Only add a given psymbol once.  */
23733       if (psyms_seen.insert (psym).second)
23734         {
23735           gdb_index_symbol_kind kind = symbol_kind (psym);
23736
23737           add_index_entry (symtab, SYMBOL_SEARCH_NAME (psym),
23738                            is_static, kind, cu_index);
23739         }
23740     }
23741 }
23742
23743 /* A helper struct used when iterating over debug_types.  */
23744 struct signatured_type_index_data
23745 {
23746   signatured_type_index_data (data_buf &types_list_,
23747                               std::unordered_set<partial_symbol *> &psyms_seen_)
23748     : types_list (types_list_), psyms_seen (psyms_seen_)
23749   {}
23750
23751   struct objfile *objfile;
23752   struct mapped_symtab *symtab;
23753   data_buf &types_list;
23754   std::unordered_set<partial_symbol *> &psyms_seen;
23755   int cu_index;
23756 };
23757
23758 /* A helper function that writes a single signatured_type to an
23759    obstack.  */
23760
23761 static int
23762 write_one_signatured_type (void **slot, void *d)
23763 {
23764   struct signatured_type_index_data *info
23765     = (struct signatured_type_index_data *) d;
23766   struct signatured_type *entry = (struct signatured_type *) *slot;
23767   struct partial_symtab *psymtab = entry->per_cu.v.psymtab;
23768
23769   write_psymbols (info->symtab,
23770                   info->psyms_seen,
23771                   info->objfile->global_psymbols.list
23772                   + psymtab->globals_offset,
23773                   psymtab->n_global_syms, info->cu_index,
23774                   0);
23775   write_psymbols (info->symtab,
23776                   info->psyms_seen,
23777                   info->objfile->static_psymbols.list
23778                   + psymtab->statics_offset,
23779                   psymtab->n_static_syms, info->cu_index,
23780                   1);
23781
23782   info->types_list.append_uint (8, BFD_ENDIAN_LITTLE,
23783                                 to_underlying (entry->per_cu.sect_off));
23784   info->types_list.append_uint (8, BFD_ENDIAN_LITTLE,
23785                                 to_underlying (entry->type_offset_in_tu));
23786   info->types_list.append_uint (8, BFD_ENDIAN_LITTLE, entry->signature);
23787
23788   ++info->cu_index;
23789
23790   return 1;
23791 }
23792
23793 /* Recurse into all "included" dependencies and count their symbols as
23794    if they appeared in this psymtab.  */
23795
23796 static void
23797 recursively_count_psymbols (struct partial_symtab *psymtab,
23798                             size_t &psyms_seen)
23799 {
23800   for (int i = 0; i < psymtab->number_of_dependencies; ++i)
23801     if (psymtab->dependencies[i]->user != NULL)
23802       recursively_count_psymbols (psymtab->dependencies[i],
23803                                   psyms_seen);
23804
23805   psyms_seen += psymtab->n_global_syms;
23806   psyms_seen += psymtab->n_static_syms;
23807 }
23808
23809 /* Recurse into all "included" dependencies and write their symbols as
23810    if they appeared in this psymtab.  */
23811
23812 static void
23813 recursively_write_psymbols (struct objfile *objfile,
23814                             struct partial_symtab *psymtab,
23815                             struct mapped_symtab *symtab,
23816                             std::unordered_set<partial_symbol *> &psyms_seen,
23817                             offset_type cu_index)
23818 {
23819   int i;
23820
23821   for (i = 0; i < psymtab->number_of_dependencies; ++i)
23822     if (psymtab->dependencies[i]->user != NULL)
23823       recursively_write_psymbols (objfile, psymtab->dependencies[i],
23824                                   symtab, psyms_seen, cu_index);
23825
23826   write_psymbols (symtab,
23827                   psyms_seen,
23828                   objfile->global_psymbols.list + psymtab->globals_offset,
23829                   psymtab->n_global_syms, cu_index,
23830                   0);
23831   write_psymbols (symtab,
23832                   psyms_seen,
23833                   objfile->static_psymbols.list + psymtab->statics_offset,
23834                   psymtab->n_static_syms, cu_index,
23835                   1);
23836 }
23837
23838 /* Create an index file for OBJFILE in the directory DIR.  */
23839
23840 static void
23841 write_psymtabs_to_index (struct objfile *objfile, const char *dir)
23842 {
23843   if (dwarf2_per_objfile->using_index)
23844     error (_("Cannot use an index to create the index"));
23845
23846   if (VEC_length (dwarf2_section_info_def, dwarf2_per_objfile->types) > 1)
23847     error (_("Cannot make an index when the file has multiple .debug_types sections"));
23848
23849   if (!objfile->psymtabs || !objfile->psymtabs_addrmap)
23850     return;
23851
23852   struct stat st;
23853   if (stat (objfile_name (objfile), &st) < 0)
23854     perror_with_name (objfile_name (objfile));
23855
23856   std::string filename (std::string (dir) + SLASH_STRING
23857                         + lbasename (objfile_name (objfile)) + INDEX_SUFFIX);
23858
23859   FILE *out_file = gdb_fopen_cloexec (filename.c_str (), "wb").release ();
23860   if (!out_file)
23861     error (_("Can't open `%s' for writing"), filename.c_str ());
23862
23863   /* Order matters here; we want FILE to be closed before FILENAME is
23864      unlinked, because on MS-Windows one cannot delete a file that is
23865      still open.  (Don't call anything here that might throw until
23866      file_closer is created.)  */
23867   gdb::unlinker unlink_file (filename.c_str ());
23868   gdb_file_up close_out_file (out_file);
23869
23870   mapped_symtab symtab;
23871   data_buf cu_list;
23872
23873   /* While we're scanning CU's create a table that maps a psymtab pointer
23874      (which is what addrmap records) to its index (which is what is recorded
23875      in the index file).  This will later be needed to write the address
23876      table.  */
23877   psym_index_map cu_index_htab;
23878   cu_index_htab.reserve (dwarf2_per_objfile->n_comp_units);
23879
23880   /* The CU list is already sorted, so we don't need to do additional
23881      work here.  Also, the debug_types entries do not appear in
23882      all_comp_units, but only in their own hash table.  */
23883
23884   /* The psyms_seen set is potentially going to be largish (~40k
23885      elements when indexing a -g3 build of GDB itself).  Estimate the
23886      number of elements in order to avoid too many rehashes, which
23887      require rebuilding buckets and thus many trips to
23888      malloc/free.  */
23889   size_t psyms_count = 0;
23890   for (int i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
23891     {
23892       struct dwarf2_per_cu_data *per_cu
23893         = dwarf2_per_objfile->all_comp_units[i];
23894       struct partial_symtab *psymtab = per_cu->v.psymtab;
23895
23896       if (psymtab != NULL && psymtab->user == NULL)
23897         recursively_count_psymbols (psymtab, psyms_count);
23898     }
23899   /* Generating an index for gdb itself shows a ratio of
23900      TOTAL_SEEN_SYMS/UNIQUE_SYMS or ~5.  4 seems like a good bet.  */
23901   std::unordered_set<partial_symbol *> psyms_seen (psyms_count / 4);
23902   for (int i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
23903     {
23904       struct dwarf2_per_cu_data *per_cu
23905         = dwarf2_per_objfile->all_comp_units[i];
23906       struct partial_symtab *psymtab = per_cu->v.psymtab;
23907
23908       /* CU of a shared file from 'dwz -m' may be unused by this main file.
23909          It may be referenced from a local scope but in such case it does not
23910          need to be present in .gdb_index.  */
23911       if (psymtab == NULL)
23912         continue;
23913
23914       if (psymtab->user == NULL)
23915         recursively_write_psymbols (objfile, psymtab, &symtab,
23916                                     psyms_seen, i);
23917
23918       const auto insertpair = cu_index_htab.emplace (psymtab, i);
23919       gdb_assert (insertpair.second);
23920
23921       cu_list.append_uint (8, BFD_ENDIAN_LITTLE,
23922                            to_underlying (per_cu->sect_off));
23923       cu_list.append_uint (8, BFD_ENDIAN_LITTLE, per_cu->length);
23924     }
23925
23926   /* Dump the address map.  */
23927   data_buf addr_vec;
23928   write_address_map (objfile, addr_vec, cu_index_htab);
23929
23930   /* Write out the .debug_type entries, if any.  */
23931   data_buf types_cu_list;
23932   if (dwarf2_per_objfile->signatured_types)
23933     {
23934       signatured_type_index_data sig_data (types_cu_list,
23935                                            psyms_seen);
23936
23937       sig_data.objfile = objfile;
23938       sig_data.symtab = &symtab;
23939       sig_data.cu_index = dwarf2_per_objfile->n_comp_units;
23940       htab_traverse_noresize (dwarf2_per_objfile->signatured_types,
23941                               write_one_signatured_type, &sig_data);
23942     }
23943
23944   /* Now that we've processed all symbols we can shrink their cu_indices
23945      lists.  */
23946   uniquify_cu_indices (&symtab);
23947
23948   data_buf symtab_vec, constant_pool;
23949   write_hash_table (&symtab, symtab_vec, constant_pool);
23950
23951   data_buf contents;
23952   const offset_type size_of_contents = 6 * sizeof (offset_type);
23953   offset_type total_len = size_of_contents;
23954
23955   /* The version number.  */
23956   contents.append_data (MAYBE_SWAP (8));
23957
23958   /* The offset of the CU list from the start of the file.  */
23959   contents.append_data (MAYBE_SWAP (total_len));
23960   total_len += cu_list.size ();
23961
23962   /* The offset of the types CU list from the start of the file.  */
23963   contents.append_data (MAYBE_SWAP (total_len));
23964   total_len += types_cu_list.size ();
23965
23966   /* The offset of the address table from the start of the file.  */
23967   contents.append_data (MAYBE_SWAP (total_len));
23968   total_len += addr_vec.size ();
23969
23970   /* The offset of the symbol table from the start of the file.  */
23971   contents.append_data (MAYBE_SWAP (total_len));
23972   total_len += symtab_vec.size ();
23973
23974   /* The offset of the constant pool from the start of the file.  */
23975   contents.append_data (MAYBE_SWAP (total_len));
23976   total_len += constant_pool.size ();
23977
23978   gdb_assert (contents.size () == size_of_contents);
23979
23980   contents.file_write (out_file);
23981   cu_list.file_write (out_file);
23982   types_cu_list.file_write (out_file);
23983   addr_vec.file_write (out_file);
23984   symtab_vec.file_write (out_file);
23985   constant_pool.file_write (out_file);
23986
23987   /* We want to keep the file.  */
23988   unlink_file.keep ();
23989 }
23990
23991 /* Implementation of the `save gdb-index' command.
23992    
23993    Note that the file format used by this command is documented in the
23994    GDB manual.  Any changes here must be documented there.  */
23995
23996 static void
23997 save_gdb_index_command (char *arg, int from_tty)
23998 {
23999   struct objfile *objfile;
24000
24001   if (!arg || !*arg)
24002     error (_("usage: save gdb-index DIRECTORY"));
24003
24004   ALL_OBJFILES (objfile)
24005   {
24006     struct stat st;
24007
24008     /* If the objfile does not correspond to an actual file, skip it.  */
24009     if (stat (objfile_name (objfile), &st) < 0)
24010       continue;
24011
24012     dwarf2_per_objfile
24013       = (struct dwarf2_per_objfile *) objfile_data (objfile,
24014                                                     dwarf2_objfile_data_key);
24015     if (dwarf2_per_objfile)
24016       {
24017
24018         TRY
24019           {
24020             write_psymtabs_to_index (objfile, arg);
24021           }
24022         CATCH (except, RETURN_MASK_ERROR)
24023           {
24024             exception_fprintf (gdb_stderr, except,
24025                                _("Error while writing index for `%s': "),
24026                                objfile_name (objfile));
24027           }
24028         END_CATCH
24029       }
24030   }
24031 }
24032
24033 \f
24034
24035 int dwarf_always_disassemble;
24036
24037 static void
24038 show_dwarf_always_disassemble (struct ui_file *file, int from_tty,
24039                                struct cmd_list_element *c, const char *value)
24040 {
24041   fprintf_filtered (file,
24042                     _("Whether to always disassemble "
24043                       "DWARF expressions is %s.\n"),
24044                     value);
24045 }
24046
24047 static void
24048 show_check_physname (struct ui_file *file, int from_tty,
24049                      struct cmd_list_element *c, const char *value)
24050 {
24051   fprintf_filtered (file,
24052                     _("Whether to check \"physname\" is %s.\n"),
24053                     value);
24054 }
24055
24056 void _initialize_dwarf2_read (void);
24057
24058 void
24059 _initialize_dwarf2_read (void)
24060 {
24061   struct cmd_list_element *c;
24062
24063   dwarf2_objfile_data_key
24064     = register_objfile_data_with_cleanup (NULL, dwarf2_per_objfile_free);
24065
24066   add_prefix_cmd ("dwarf", class_maintenance, set_dwarf_cmd, _("\
24067 Set DWARF specific variables.\n\
24068 Configure DWARF variables such as the cache size"),
24069                   &set_dwarf_cmdlist, "maintenance set dwarf ",
24070                   0/*allow-unknown*/, &maintenance_set_cmdlist);
24071
24072   add_prefix_cmd ("dwarf", class_maintenance, show_dwarf_cmd, _("\
24073 Show DWARF specific variables\n\
24074 Show DWARF variables such as the cache size"),
24075                   &show_dwarf_cmdlist, "maintenance show dwarf ",
24076                   0/*allow-unknown*/, &maintenance_show_cmdlist);
24077
24078   add_setshow_zinteger_cmd ("max-cache-age", class_obscure,
24079                             &dwarf_max_cache_age, _("\
24080 Set the upper bound on the age of cached DWARF compilation units."), _("\
24081 Show the upper bound on the age of cached DWARF compilation units."), _("\
24082 A higher limit means that cached compilation units will be stored\n\
24083 in memory longer, and more total memory will be used.  Zero disables\n\
24084 caching, which can slow down startup."),
24085                             NULL,
24086                             show_dwarf_max_cache_age,
24087                             &set_dwarf_cmdlist,
24088                             &show_dwarf_cmdlist);
24089
24090   add_setshow_boolean_cmd ("always-disassemble", class_obscure,
24091                            &dwarf_always_disassemble, _("\
24092 Set whether `info address' always disassembles DWARF expressions."), _("\
24093 Show whether `info address' always disassembles DWARF expressions."), _("\
24094 When enabled, DWARF expressions are always printed in an assembly-like\n\
24095 syntax.  When disabled, expressions will be printed in a more\n\
24096 conversational style, when possible."),
24097                            NULL,
24098                            show_dwarf_always_disassemble,
24099                            &set_dwarf_cmdlist,
24100                            &show_dwarf_cmdlist);
24101
24102   add_setshow_zuinteger_cmd ("dwarf-read", no_class, &dwarf_read_debug, _("\
24103 Set debugging of the DWARF reader."), _("\
24104 Show debugging of the DWARF reader."), _("\
24105 When enabled (non-zero), debugging messages are printed during DWARF\n\
24106 reading and symtab expansion.  A value of 1 (one) provides basic\n\
24107 information.  A value greater than 1 provides more verbose information."),
24108                             NULL,
24109                             NULL,
24110                             &setdebuglist, &showdebuglist);
24111
24112   add_setshow_zuinteger_cmd ("dwarf-die", no_class, &dwarf_die_debug, _("\
24113 Set debugging of the DWARF DIE reader."), _("\
24114 Show debugging of the DWARF DIE reader."), _("\
24115 When enabled (non-zero), DIEs are dumped after they are read in.\n\
24116 The value is the maximum depth to print."),
24117                              NULL,
24118                              NULL,
24119                              &setdebuglist, &showdebuglist);
24120
24121   add_setshow_zuinteger_cmd ("dwarf-line", no_class, &dwarf_line_debug, _("\
24122 Set debugging of the dwarf line reader."), _("\
24123 Show debugging of the dwarf line reader."), _("\
24124 When enabled (non-zero), line number entries are dumped as they are read in.\n\
24125 A value of 1 (one) provides basic information.\n\
24126 A value greater than 1 provides more verbose information."),
24127                              NULL,
24128                              NULL,
24129                              &setdebuglist, &showdebuglist);
24130
24131   add_setshow_boolean_cmd ("check-physname", no_class, &check_physname, _("\
24132 Set cross-checking of \"physname\" code against demangler."), _("\
24133 Show cross-checking of \"physname\" code against demangler."), _("\
24134 When enabled, GDB's internal \"physname\" code is checked against\n\
24135 the demangler."),
24136                            NULL, show_check_physname,
24137                            &setdebuglist, &showdebuglist);
24138
24139   add_setshow_boolean_cmd ("use-deprecated-index-sections",
24140                            no_class, &use_deprecated_index_sections, _("\
24141 Set whether to use deprecated gdb_index sections."), _("\
24142 Show whether to use deprecated gdb_index sections."), _("\
24143 When enabled, deprecated .gdb_index sections are used anyway.\n\
24144 Normally they are ignored either because of a missing feature or\n\
24145 performance issue.\n\
24146 Warning: This option must be enabled before gdb reads the file."),
24147                            NULL,
24148                            NULL,
24149                            &setlist, &showlist);
24150
24151   c = add_cmd ("gdb-index", class_files, save_gdb_index_command,
24152                _("\
24153 Save a gdb-index file.\n\
24154 Usage: save gdb-index DIRECTORY"),
24155                &save_cmdlist);
24156   set_cmd_completer (c, filename_completer);
24157
24158   dwarf2_locexpr_index = register_symbol_computed_impl (LOC_COMPUTED,
24159                                                         &dwarf2_locexpr_funcs);
24160   dwarf2_loclist_index = register_symbol_computed_impl (LOC_COMPUTED,
24161                                                         &dwarf2_loclist_funcs);
24162
24163   dwarf2_locexpr_block_index = register_symbol_block_impl (LOC_BLOCK,
24164                                         &dwarf2_block_frame_base_locexpr_funcs);
24165   dwarf2_loclist_block_index = register_symbol_block_impl (LOC_BLOCK,
24166                                         &dwarf2_block_frame_base_loclist_funcs);
24167 }