Plug line_header leaks
[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 dwarf2_build_psymtabs_hard (struct objfile *);
1546
1547 static void scan_partial_symbols (struct partial_die_info *,
1548                                   CORE_ADDR *, CORE_ADDR *,
1549                                   int, struct dwarf2_cu *);
1550
1551 static void add_partial_symbol (struct partial_die_info *,
1552                                 struct dwarf2_cu *);
1553
1554 static void add_partial_namespace (struct partial_die_info *pdi,
1555                                    CORE_ADDR *lowpc, CORE_ADDR *highpc,
1556                                    int set_addrmap, struct dwarf2_cu *cu);
1557
1558 static void add_partial_module (struct partial_die_info *pdi, CORE_ADDR *lowpc,
1559                                 CORE_ADDR *highpc, int set_addrmap,
1560                                 struct dwarf2_cu *cu);
1561
1562 static void add_partial_enumeration (struct partial_die_info *enum_pdi,
1563                                      struct dwarf2_cu *cu);
1564
1565 static void add_partial_subprogram (struct partial_die_info *pdi,
1566                                     CORE_ADDR *lowpc, CORE_ADDR *highpc,
1567                                     int need_pc, struct dwarf2_cu *cu);
1568
1569 static void dwarf2_read_symtab (struct partial_symtab *,
1570                                 struct objfile *);
1571
1572 static void psymtab_to_symtab_1 (struct partial_symtab *);
1573
1574 static struct abbrev_info *abbrev_table_lookup_abbrev
1575   (const struct abbrev_table *, unsigned int);
1576
1577 static struct abbrev_table *abbrev_table_read_table
1578   (struct dwarf2_section_info *, sect_offset);
1579
1580 static void abbrev_table_free (struct abbrev_table *);
1581
1582 static void abbrev_table_free_cleanup (void *);
1583
1584 static void dwarf2_read_abbrevs (struct dwarf2_cu *,
1585                                  struct dwarf2_section_info *);
1586
1587 static void dwarf2_free_abbrev_table (void *);
1588
1589 static unsigned int peek_abbrev_code (bfd *, const gdb_byte *);
1590
1591 static struct partial_die_info *load_partial_dies
1592   (const struct die_reader_specs *, const gdb_byte *, int);
1593
1594 static const gdb_byte *read_partial_die (const struct die_reader_specs *,
1595                                          struct partial_die_info *,
1596                                          struct abbrev_info *,
1597                                          unsigned int,
1598                                          const gdb_byte *);
1599
1600 static struct partial_die_info *find_partial_die (sect_offset, int,
1601                                                   struct dwarf2_cu *);
1602
1603 static void fixup_partial_die (struct partial_die_info *,
1604                                struct dwarf2_cu *);
1605
1606 static const gdb_byte *read_attribute (const struct die_reader_specs *,
1607                                        struct attribute *, struct attr_abbrev *,
1608                                        const gdb_byte *);
1609
1610 static unsigned int read_1_byte (bfd *, const gdb_byte *);
1611
1612 static int read_1_signed_byte (bfd *, const gdb_byte *);
1613
1614 static unsigned int read_2_bytes (bfd *, const gdb_byte *);
1615
1616 static unsigned int read_4_bytes (bfd *, const gdb_byte *);
1617
1618 static ULONGEST read_8_bytes (bfd *, const gdb_byte *);
1619
1620 static CORE_ADDR read_address (bfd *, const gdb_byte *ptr, struct dwarf2_cu *,
1621                                unsigned int *);
1622
1623 static LONGEST read_initial_length (bfd *, const gdb_byte *, unsigned int *);
1624
1625 static LONGEST read_checked_initial_length_and_offset
1626   (bfd *, const gdb_byte *, const struct comp_unit_head *,
1627    unsigned int *, unsigned int *);
1628
1629 static LONGEST read_offset (bfd *, const gdb_byte *,
1630                             const struct comp_unit_head *,
1631                             unsigned int *);
1632
1633 static LONGEST read_offset_1 (bfd *, const gdb_byte *, unsigned int);
1634
1635 static sect_offset read_abbrev_offset (struct dwarf2_section_info *,
1636                                        sect_offset);
1637
1638 static const gdb_byte *read_n_bytes (bfd *, const gdb_byte *, unsigned int);
1639
1640 static const char *read_direct_string (bfd *, const gdb_byte *, unsigned int *);
1641
1642 static const char *read_indirect_string (bfd *, const gdb_byte *,
1643                                          const struct comp_unit_head *,
1644                                          unsigned int *);
1645
1646 static const char *read_indirect_line_string (bfd *, const gdb_byte *,
1647                                               const struct comp_unit_head *,
1648                                               unsigned int *);
1649
1650 static const char *read_indirect_string_from_dwz (struct dwz_file *, LONGEST);
1651
1652 static LONGEST read_signed_leb128 (bfd *, const gdb_byte *, unsigned int *);
1653
1654 static CORE_ADDR read_addr_index_from_leb128 (struct dwarf2_cu *,
1655                                               const gdb_byte *,
1656                                               unsigned int *);
1657
1658 static const char *read_str_index (const struct die_reader_specs *reader,
1659                                    ULONGEST str_index);
1660
1661 static void set_cu_language (unsigned int, struct dwarf2_cu *);
1662
1663 static struct attribute *dwarf2_attr (struct die_info *, unsigned int,
1664                                       struct dwarf2_cu *);
1665
1666 static struct attribute *dwarf2_attr_no_follow (struct die_info *,
1667                                                 unsigned int);
1668
1669 static const char *dwarf2_string_attr (struct die_info *die, unsigned int name,
1670                                        struct dwarf2_cu *cu);
1671
1672 static int dwarf2_flag_true_p (struct die_info *die, unsigned name,
1673                                struct dwarf2_cu *cu);
1674
1675 static int die_is_declaration (struct die_info *, struct dwarf2_cu *cu);
1676
1677 static struct die_info *die_specification (struct die_info *die,
1678                                            struct dwarf2_cu **);
1679
1680 static line_header_up dwarf_decode_line_header (sect_offset sect_off,
1681                                                 struct dwarf2_cu *cu);
1682
1683 static void dwarf_decode_lines (struct line_header *, const char *,
1684                                 struct dwarf2_cu *, struct partial_symtab *,
1685                                 CORE_ADDR, int decode_mapping);
1686
1687 static void dwarf2_start_subfile (const char *, const char *);
1688
1689 static struct compunit_symtab *dwarf2_start_symtab (struct dwarf2_cu *,
1690                                                     const char *, const char *,
1691                                                     CORE_ADDR);
1692
1693 static struct symbol *new_symbol (struct die_info *, struct type *,
1694                                   struct dwarf2_cu *);
1695
1696 static struct symbol *new_symbol_full (struct die_info *, struct type *,
1697                                        struct dwarf2_cu *, struct symbol *);
1698
1699 static void dwarf2_const_value (const struct attribute *, struct symbol *,
1700                                 struct dwarf2_cu *);
1701
1702 static void dwarf2_const_value_attr (const struct attribute *attr,
1703                                      struct type *type,
1704                                      const char *name,
1705                                      struct obstack *obstack,
1706                                      struct dwarf2_cu *cu, LONGEST *value,
1707                                      const gdb_byte **bytes,
1708                                      struct dwarf2_locexpr_baton **baton);
1709
1710 static struct type *die_type (struct die_info *, struct dwarf2_cu *);
1711
1712 static int need_gnat_info (struct dwarf2_cu *);
1713
1714 static struct type *die_descriptive_type (struct die_info *,
1715                                           struct dwarf2_cu *);
1716
1717 static void set_descriptive_type (struct type *, struct die_info *,
1718                                   struct dwarf2_cu *);
1719
1720 static struct type *die_containing_type (struct die_info *,
1721                                          struct dwarf2_cu *);
1722
1723 static struct type *lookup_die_type (struct die_info *, const struct attribute *,
1724                                      struct dwarf2_cu *);
1725
1726 static struct type *read_type_die (struct die_info *, struct dwarf2_cu *);
1727
1728 static struct type *read_type_die_1 (struct die_info *, struct dwarf2_cu *);
1729
1730 static const char *determine_prefix (struct die_info *die, struct dwarf2_cu *);
1731
1732 static char *typename_concat (struct obstack *obs, const char *prefix,
1733                               const char *suffix, int physname,
1734                               struct dwarf2_cu *cu);
1735
1736 static void read_file_scope (struct die_info *, struct dwarf2_cu *);
1737
1738 static void read_type_unit_scope (struct die_info *, struct dwarf2_cu *);
1739
1740 static void read_func_scope (struct die_info *, struct dwarf2_cu *);
1741
1742 static void read_lexical_block_scope (struct die_info *, struct dwarf2_cu *);
1743
1744 static void read_call_site_scope (struct die_info *die, struct dwarf2_cu *cu);
1745
1746 static int dwarf2_ranges_read (unsigned, CORE_ADDR *, CORE_ADDR *,
1747                                struct dwarf2_cu *, struct partial_symtab *);
1748
1749 /* How dwarf2_get_pc_bounds constructed its *LOWPC and *HIGHPC return
1750    values.  Keep the items ordered with increasing constraints compliance.  */
1751 enum pc_bounds_kind
1752 {
1753   /* No attribute DW_AT_low_pc, DW_AT_high_pc or DW_AT_ranges was found.  */
1754   PC_BOUNDS_NOT_PRESENT,
1755
1756   /* Some of the attributes DW_AT_low_pc, DW_AT_high_pc or DW_AT_ranges
1757      were present but they do not form a valid range of PC addresses.  */
1758   PC_BOUNDS_INVALID,
1759
1760   /* Discontiguous range was found - that is DW_AT_ranges was found.  */
1761   PC_BOUNDS_RANGES,
1762
1763   /* Contiguous range was found - DW_AT_low_pc and DW_AT_high_pc were found.  */
1764   PC_BOUNDS_HIGH_LOW,
1765 };
1766
1767 static enum pc_bounds_kind dwarf2_get_pc_bounds (struct die_info *,
1768                                                  CORE_ADDR *, CORE_ADDR *,
1769                                                  struct dwarf2_cu *,
1770                                                  struct partial_symtab *);
1771
1772 static void get_scope_pc_bounds (struct die_info *,
1773                                  CORE_ADDR *, CORE_ADDR *,
1774                                  struct dwarf2_cu *);
1775
1776 static void dwarf2_record_block_ranges (struct die_info *, struct block *,
1777                                         CORE_ADDR, struct dwarf2_cu *);
1778
1779 static void dwarf2_add_field (struct field_info *, struct die_info *,
1780                               struct dwarf2_cu *);
1781
1782 static void dwarf2_attach_fields_to_type (struct field_info *,
1783                                           struct type *, struct dwarf2_cu *);
1784
1785 static void dwarf2_add_member_fn (struct field_info *,
1786                                   struct die_info *, struct type *,
1787                                   struct dwarf2_cu *);
1788
1789 static void dwarf2_attach_fn_fields_to_type (struct field_info *,
1790                                              struct type *,
1791                                              struct dwarf2_cu *);
1792
1793 static void process_structure_scope (struct die_info *, struct dwarf2_cu *);
1794
1795 static void read_common_block (struct die_info *, struct dwarf2_cu *);
1796
1797 static void read_namespace (struct die_info *die, struct dwarf2_cu *);
1798
1799 static void read_module (struct die_info *die, struct dwarf2_cu *cu);
1800
1801 static struct using_direct **using_directives (enum language);
1802
1803 static void read_import_statement (struct die_info *die, struct dwarf2_cu *);
1804
1805 static int read_namespace_alias (struct die_info *die, struct dwarf2_cu *cu);
1806
1807 static struct type *read_module_type (struct die_info *die,
1808                                       struct dwarf2_cu *cu);
1809
1810 static const char *namespace_name (struct die_info *die,
1811                                    int *is_anonymous, struct dwarf2_cu *);
1812
1813 static void process_enumeration_scope (struct die_info *, struct dwarf2_cu *);
1814
1815 static CORE_ADDR decode_locdesc (struct dwarf_block *, struct dwarf2_cu *);
1816
1817 static enum dwarf_array_dim_ordering read_array_order (struct die_info *,
1818                                                        struct dwarf2_cu *);
1819
1820 static struct die_info *read_die_and_siblings_1
1821   (const struct die_reader_specs *, const gdb_byte *, const gdb_byte **,
1822    struct die_info *);
1823
1824 static struct die_info *read_die_and_siblings (const struct die_reader_specs *,
1825                                                const gdb_byte *info_ptr,
1826                                                const gdb_byte **new_info_ptr,
1827                                                struct die_info *parent);
1828
1829 static const gdb_byte *read_full_die_1 (const struct die_reader_specs *,
1830                                         struct die_info **, const gdb_byte *,
1831                                         int *, int);
1832
1833 static const gdb_byte *read_full_die (const struct die_reader_specs *,
1834                                       struct die_info **, const gdb_byte *,
1835                                       int *);
1836
1837 static void process_die (struct die_info *, struct dwarf2_cu *);
1838
1839 static const char *dwarf2_canonicalize_name (const char *, struct dwarf2_cu *,
1840                                              struct obstack *);
1841
1842 static const char *dwarf2_name (struct die_info *die, struct dwarf2_cu *);
1843
1844 static const char *dwarf2_full_name (const char *name,
1845                                      struct die_info *die,
1846                                      struct dwarf2_cu *cu);
1847
1848 static const char *dwarf2_physname (const char *name, struct die_info *die,
1849                                     struct dwarf2_cu *cu);
1850
1851 static struct die_info *dwarf2_extension (struct die_info *die,
1852                                           struct dwarf2_cu **);
1853
1854 static const char *dwarf_tag_name (unsigned int);
1855
1856 static const char *dwarf_attr_name (unsigned int);
1857
1858 static const char *dwarf_form_name (unsigned int);
1859
1860 static const char *dwarf_bool_name (unsigned int);
1861
1862 static const char *dwarf_type_encoding_name (unsigned int);
1863
1864 static struct die_info *sibling_die (struct die_info *);
1865
1866 static void dump_die_shallow (struct ui_file *, int indent, struct die_info *);
1867
1868 static void dump_die_for_error (struct die_info *);
1869
1870 static void dump_die_1 (struct ui_file *, int level, int max_level,
1871                         struct die_info *);
1872
1873 /*static*/ void dump_die (struct die_info *, int max_level);
1874
1875 static void store_in_ref_table (struct die_info *,
1876                                 struct dwarf2_cu *);
1877
1878 static sect_offset dwarf2_get_ref_die_offset (const struct attribute *);
1879
1880 static LONGEST dwarf2_get_attr_constant_value (const struct attribute *, int);
1881
1882 static struct die_info *follow_die_ref_or_sig (struct die_info *,
1883                                                const struct attribute *,
1884                                                struct dwarf2_cu **);
1885
1886 static struct die_info *follow_die_ref (struct die_info *,
1887                                         const struct attribute *,
1888                                         struct dwarf2_cu **);
1889
1890 static struct die_info *follow_die_sig (struct die_info *,
1891                                         const struct attribute *,
1892                                         struct dwarf2_cu **);
1893
1894 static struct type *get_signatured_type (struct die_info *, ULONGEST,
1895                                          struct dwarf2_cu *);
1896
1897 static struct type *get_DW_AT_signature_type (struct die_info *,
1898                                               const struct attribute *,
1899                                               struct dwarf2_cu *);
1900
1901 static void load_full_type_unit (struct dwarf2_per_cu_data *per_cu);
1902
1903 static void read_signatured_type (struct signatured_type *);
1904
1905 static int attr_to_dynamic_prop (const struct attribute *attr,
1906                                  struct die_info *die, struct dwarf2_cu *cu,
1907                                  struct dynamic_prop *prop);
1908
1909 /* memory allocation interface */
1910
1911 static struct dwarf_block *dwarf_alloc_block (struct dwarf2_cu *);
1912
1913 static struct die_info *dwarf_alloc_die (struct dwarf2_cu *, int);
1914
1915 static void dwarf_decode_macros (struct dwarf2_cu *, unsigned int, int);
1916
1917 static int attr_form_is_block (const struct attribute *);
1918
1919 static int attr_form_is_section_offset (const struct attribute *);
1920
1921 static int attr_form_is_constant (const struct attribute *);
1922
1923 static int attr_form_is_ref (const struct attribute *);
1924
1925 static void fill_in_loclist_baton (struct dwarf2_cu *cu,
1926                                    struct dwarf2_loclist_baton *baton,
1927                                    const struct attribute *attr);
1928
1929 static void dwarf2_symbol_mark_computed (const struct attribute *attr,
1930                                          struct symbol *sym,
1931                                          struct dwarf2_cu *cu,
1932                                          int is_block);
1933
1934 static const gdb_byte *skip_one_die (const struct die_reader_specs *reader,
1935                                      const gdb_byte *info_ptr,
1936                                      struct abbrev_info *abbrev);
1937
1938 static void free_stack_comp_unit (void *);
1939
1940 static hashval_t partial_die_hash (const void *item);
1941
1942 static int partial_die_eq (const void *item_lhs, const void *item_rhs);
1943
1944 static struct dwarf2_per_cu_data *dwarf2_find_containing_comp_unit
1945   (sect_offset sect_off, unsigned int offset_in_dwz, struct objfile *objfile);
1946
1947 static void init_one_comp_unit (struct dwarf2_cu *cu,
1948                                 struct dwarf2_per_cu_data *per_cu);
1949
1950 static void prepare_one_comp_unit (struct dwarf2_cu *cu,
1951                                    struct die_info *comp_unit_die,
1952                                    enum language pretend_language);
1953
1954 static void free_heap_comp_unit (void *);
1955
1956 static void free_cached_comp_units (void *);
1957
1958 static void age_cached_comp_units (void);
1959
1960 static void free_one_cached_comp_unit (struct dwarf2_per_cu_data *);
1961
1962 static struct type *set_die_type (struct die_info *, struct type *,
1963                                   struct dwarf2_cu *);
1964
1965 static void create_all_comp_units (struct objfile *);
1966
1967 static int create_all_type_units (struct objfile *);
1968
1969 static void load_full_comp_unit (struct dwarf2_per_cu_data *,
1970                                  enum language);
1971
1972 static void process_full_comp_unit (struct dwarf2_per_cu_data *,
1973                                     enum language);
1974
1975 static void process_full_type_unit (struct dwarf2_per_cu_data *,
1976                                     enum language);
1977
1978 static void dwarf2_add_dependence (struct dwarf2_cu *,
1979                                    struct dwarf2_per_cu_data *);
1980
1981 static void dwarf2_mark (struct dwarf2_cu *);
1982
1983 static void dwarf2_clear_marks (struct dwarf2_per_cu_data *);
1984
1985 static struct type *get_die_type_at_offset (sect_offset,
1986                                             struct dwarf2_per_cu_data *);
1987
1988 static struct type *get_die_type (struct die_info *die, struct dwarf2_cu *cu);
1989
1990 static void dwarf2_release_queue (void *dummy);
1991
1992 static void queue_comp_unit (struct dwarf2_per_cu_data *per_cu,
1993                              enum language pretend_language);
1994
1995 static void process_queue (void);
1996
1997 /* The return type of find_file_and_directory.  Note, the enclosed
1998    string pointers are only valid while this object is valid.  */
1999
2000 struct file_and_directory
2001 {
2002   /* The filename.  This is never NULL.  */
2003   const char *name;
2004
2005   /* The compilation directory.  NULL if not known.  If we needed to
2006      compute a new string, this points to COMP_DIR_STORAGE, otherwise,
2007      points directly to the DW_AT_comp_dir string attribute owned by
2008      the obstack that owns the DIE.  */
2009   const char *comp_dir;
2010
2011   /* If we needed to build a new string for comp_dir, this is what
2012      owns the storage.  */
2013   std::string comp_dir_storage;
2014 };
2015
2016 static file_and_directory find_file_and_directory (struct die_info *die,
2017                                                    struct dwarf2_cu *cu);
2018
2019 static char *file_full_name (int file, struct line_header *lh,
2020                              const char *comp_dir);
2021
2022 /* Expected enum dwarf_unit_type for read_comp_unit_head.  */
2023 enum class rcuh_kind { COMPILE, TYPE };
2024
2025 static const gdb_byte *read_and_check_comp_unit_head
2026   (struct comp_unit_head *header,
2027    struct dwarf2_section_info *section,
2028    struct dwarf2_section_info *abbrev_section, const gdb_byte *info_ptr,
2029    rcuh_kind section_kind);
2030
2031 static void init_cutu_and_read_dies
2032   (struct dwarf2_per_cu_data *this_cu, struct abbrev_table *abbrev_table,
2033    int use_existing_cu, int keep,
2034    die_reader_func_ftype *die_reader_func, void *data);
2035
2036 static void init_cutu_and_read_dies_simple
2037   (struct dwarf2_per_cu_data *this_cu,
2038    die_reader_func_ftype *die_reader_func, void *data);
2039
2040 static htab_t allocate_signatured_type_table (struct objfile *objfile);
2041
2042 static htab_t allocate_dwo_unit_table (struct objfile *objfile);
2043
2044 static struct dwo_unit *lookup_dwo_unit_in_dwp
2045   (struct dwp_file *dwp_file, const char *comp_dir,
2046    ULONGEST signature, int is_debug_types);
2047
2048 static struct dwp_file *get_dwp_file (void);
2049
2050 static struct dwo_unit *lookup_dwo_comp_unit
2051   (struct dwarf2_per_cu_data *, const char *, const char *, ULONGEST);
2052
2053 static struct dwo_unit *lookup_dwo_type_unit
2054   (struct signatured_type *, const char *, const char *);
2055
2056 static void queue_and_load_all_dwo_tus (struct dwarf2_per_cu_data *);
2057
2058 static void free_dwo_file_cleanup (void *);
2059
2060 static void process_cu_includes (void);
2061
2062 static void check_producer (struct dwarf2_cu *cu);
2063
2064 static void free_line_header_voidp (void *arg);
2065 \f
2066 /* Various complaints about symbol reading that don't abort the process.  */
2067
2068 static void
2069 dwarf2_statement_list_fits_in_line_number_section_complaint (void)
2070 {
2071   complaint (&symfile_complaints,
2072              _("statement list doesn't fit in .debug_line section"));
2073 }
2074
2075 static void
2076 dwarf2_debug_line_missing_file_complaint (void)
2077 {
2078   complaint (&symfile_complaints,
2079              _(".debug_line section has line data without a file"));
2080 }
2081
2082 static void
2083 dwarf2_debug_line_missing_end_sequence_complaint (void)
2084 {
2085   complaint (&symfile_complaints,
2086              _(".debug_line section has line "
2087                "program sequence without an end"));
2088 }
2089
2090 static void
2091 dwarf2_complex_location_expr_complaint (void)
2092 {
2093   complaint (&symfile_complaints, _("location expression too complex"));
2094 }
2095
2096 static void
2097 dwarf2_const_value_length_mismatch_complaint (const char *arg1, int arg2,
2098                                               int arg3)
2099 {
2100   complaint (&symfile_complaints,
2101              _("const value length mismatch for '%s', got %d, expected %d"),
2102              arg1, arg2, arg3);
2103 }
2104
2105 static void
2106 dwarf2_section_buffer_overflow_complaint (struct dwarf2_section_info *section)
2107 {
2108   complaint (&symfile_complaints,
2109              _("debug info runs off end of %s section"
2110                " [in module %s]"),
2111              get_section_name (section),
2112              get_section_file_name (section));
2113 }
2114
2115 static void
2116 dwarf2_macro_malformed_definition_complaint (const char *arg1)
2117 {
2118   complaint (&symfile_complaints,
2119              _("macro debug info contains a "
2120                "malformed macro definition:\n`%s'"),
2121              arg1);
2122 }
2123
2124 static void
2125 dwarf2_invalid_attrib_class_complaint (const char *arg1, const char *arg2)
2126 {
2127   complaint (&symfile_complaints,
2128              _("invalid attribute class or form for '%s' in '%s'"),
2129              arg1, arg2);
2130 }
2131
2132 /* Hash function for line_header_hash.  */
2133
2134 static hashval_t
2135 line_header_hash (const struct line_header *ofs)
2136 {
2137   return to_underlying (ofs->sect_off) ^ ofs->offset_in_dwz;
2138 }
2139
2140 /* Hash function for htab_create_alloc_ex for line_header_hash.  */
2141
2142 static hashval_t
2143 line_header_hash_voidp (const void *item)
2144 {
2145   const struct line_header *ofs = (const struct line_header *) item;
2146
2147   return line_header_hash (ofs);
2148 }
2149
2150 /* Equality function for line_header_hash.  */
2151
2152 static int
2153 line_header_eq_voidp (const void *item_lhs, const void *item_rhs)
2154 {
2155   const struct line_header *ofs_lhs = (const struct line_header *) item_lhs;
2156   const struct line_header *ofs_rhs = (const struct line_header *) item_rhs;
2157
2158   return (ofs_lhs->sect_off == ofs_rhs->sect_off
2159           && ofs_lhs->offset_in_dwz == ofs_rhs->offset_in_dwz);
2160 }
2161
2162 \f
2163 #if WORDS_BIGENDIAN
2164
2165 /* Convert VALUE between big- and little-endian.  */
2166 static offset_type
2167 byte_swap (offset_type value)
2168 {
2169   offset_type result;
2170
2171   result = (value & 0xff) << 24;
2172   result |= (value & 0xff00) << 8;
2173   result |= (value & 0xff0000) >> 8;
2174   result |= (value & 0xff000000) >> 24;
2175   return result;
2176 }
2177
2178 #define MAYBE_SWAP(V)  byte_swap (V)
2179
2180 #else
2181 #define MAYBE_SWAP(V) static_cast<offset_type> (V)
2182 #endif /* WORDS_BIGENDIAN */
2183
2184 /* Read the given attribute value as an address, taking the attribute's
2185    form into account.  */
2186
2187 static CORE_ADDR
2188 attr_value_as_address (struct attribute *attr)
2189 {
2190   CORE_ADDR addr;
2191
2192   if (attr->form != DW_FORM_addr && attr->form != DW_FORM_GNU_addr_index)
2193     {
2194       /* Aside from a few clearly defined exceptions, attributes that
2195          contain an address must always be in DW_FORM_addr form.
2196          Unfortunately, some compilers happen to be violating this
2197          requirement by encoding addresses using other forms, such
2198          as DW_FORM_data4 for example.  For those broken compilers,
2199          we try to do our best, without any guarantee of success,
2200          to interpret the address correctly.  It would also be nice
2201          to generate a complaint, but that would require us to maintain
2202          a list of legitimate cases where a non-address form is allowed,
2203          as well as update callers to pass in at least the CU's DWARF
2204          version.  This is more overhead than what we're willing to
2205          expand for a pretty rare case.  */
2206       addr = DW_UNSND (attr);
2207     }
2208   else
2209     addr = DW_ADDR (attr);
2210
2211   return addr;
2212 }
2213
2214 /* The suffix for an index file.  */
2215 #define INDEX_SUFFIX ".gdb-index"
2216
2217 /* See declaration.  */
2218
2219 dwarf2_per_objfile::dwarf2_per_objfile (struct objfile *objfile_,
2220                                         const dwarf2_debug_sections *names)
2221   : objfile (objfile_)
2222 {
2223   if (names == NULL)
2224     names = &dwarf2_elf_names;
2225
2226   bfd *obfd = objfile->obfd;
2227
2228   for (asection *sec = obfd->sections; sec != NULL; sec = sec->next)
2229     locate_sections (obfd, sec, *names);
2230 }
2231
2232 dwarf2_per_objfile::~dwarf2_per_objfile ()
2233 {
2234   /* Cached DIE trees use xmalloc and the comp_unit_obstack.  */
2235   free_cached_comp_units ();
2236
2237   if (quick_file_names_table)
2238     htab_delete (quick_file_names_table);
2239
2240   if (line_header_hash)
2241     htab_delete (line_header_hash);
2242
2243   /* Everything else should be on the objfile obstack.  */
2244 }
2245
2246 /* See declaration.  */
2247
2248 void
2249 dwarf2_per_objfile::free_cached_comp_units ()
2250 {
2251   dwarf2_per_cu_data *per_cu = read_in_chain;
2252   dwarf2_per_cu_data **last_chain = &read_in_chain;
2253   while (per_cu != NULL)
2254     {
2255       dwarf2_per_cu_data *next_cu = per_cu->cu->read_in_chain;
2256
2257       free_heap_comp_unit (per_cu->cu);
2258       *last_chain = next_cu;
2259       per_cu = next_cu;
2260     }
2261 }
2262
2263 /* Try to locate the sections we need for DWARF 2 debugging
2264    information and return true if we have enough to do something.
2265    NAMES points to the dwarf2 section names, or is NULL if the standard
2266    ELF names are used.  */
2267
2268 int
2269 dwarf2_has_info (struct objfile *objfile,
2270                  const struct dwarf2_debug_sections *names)
2271 {
2272   dwarf2_per_objfile = ((struct dwarf2_per_objfile *)
2273                         objfile_data (objfile, dwarf2_objfile_data_key));
2274   if (!dwarf2_per_objfile)
2275     {
2276       /* Initialize per-objfile state.  */
2277       struct dwarf2_per_objfile *data
2278         = XOBNEW (&objfile->objfile_obstack, struct dwarf2_per_objfile);
2279
2280       dwarf2_per_objfile = new (data) struct dwarf2_per_objfile (objfile, names);
2281       set_objfile_data (objfile, dwarf2_objfile_data_key, dwarf2_per_objfile);
2282     }
2283   return (!dwarf2_per_objfile->info.is_virtual
2284           && dwarf2_per_objfile->info.s.section != NULL
2285           && !dwarf2_per_objfile->abbrev.is_virtual
2286           && dwarf2_per_objfile->abbrev.s.section != NULL);
2287 }
2288
2289 /* Return the containing section of virtual section SECTION.  */
2290
2291 static struct dwarf2_section_info *
2292 get_containing_section (const struct dwarf2_section_info *section)
2293 {
2294   gdb_assert (section->is_virtual);
2295   return section->s.containing_section;
2296 }
2297
2298 /* Return the bfd owner of SECTION.  */
2299
2300 static struct bfd *
2301 get_section_bfd_owner (const struct dwarf2_section_info *section)
2302 {
2303   if (section->is_virtual)
2304     {
2305       section = get_containing_section (section);
2306       gdb_assert (!section->is_virtual);
2307     }
2308   return section->s.section->owner;
2309 }
2310
2311 /* Return the bfd section of SECTION.
2312    Returns NULL if the section is not present.  */
2313
2314 static asection *
2315 get_section_bfd_section (const struct dwarf2_section_info *section)
2316 {
2317   if (section->is_virtual)
2318     {
2319       section = get_containing_section (section);
2320       gdb_assert (!section->is_virtual);
2321     }
2322   return section->s.section;
2323 }
2324
2325 /* Return the name of SECTION.  */
2326
2327 static const char *
2328 get_section_name (const struct dwarf2_section_info *section)
2329 {
2330   asection *sectp = get_section_bfd_section (section);
2331
2332   gdb_assert (sectp != NULL);
2333   return bfd_section_name (get_section_bfd_owner (section), sectp);
2334 }
2335
2336 /* Return the name of the file SECTION is in.  */
2337
2338 static const char *
2339 get_section_file_name (const struct dwarf2_section_info *section)
2340 {
2341   bfd *abfd = get_section_bfd_owner (section);
2342
2343   return bfd_get_filename (abfd);
2344 }
2345
2346 /* Return the id of SECTION.
2347    Returns 0 if SECTION doesn't exist.  */
2348
2349 static int
2350 get_section_id (const struct dwarf2_section_info *section)
2351 {
2352   asection *sectp = get_section_bfd_section (section);
2353
2354   if (sectp == NULL)
2355     return 0;
2356   return sectp->id;
2357 }
2358
2359 /* Return the flags of SECTION.
2360    SECTION (or containing section if this is a virtual section) must exist.  */
2361
2362 static int
2363 get_section_flags (const struct dwarf2_section_info *section)
2364 {
2365   asection *sectp = get_section_bfd_section (section);
2366
2367   gdb_assert (sectp != NULL);
2368   return bfd_get_section_flags (sectp->owner, sectp);
2369 }
2370
2371 /* When loading sections, we look either for uncompressed section or for
2372    compressed section names.  */
2373
2374 static int
2375 section_is_p (const char *section_name,
2376               const struct dwarf2_section_names *names)
2377 {
2378   if (names->normal != NULL
2379       && strcmp (section_name, names->normal) == 0)
2380     return 1;
2381   if (names->compressed != NULL
2382       && strcmp (section_name, names->compressed) == 0)
2383     return 1;
2384   return 0;
2385 }
2386
2387 /* See declaration.  */
2388
2389 void
2390 dwarf2_per_objfile::locate_sections (bfd *abfd, asection *sectp,
2391                                      const dwarf2_debug_sections &names)
2392 {
2393   flagword aflag = bfd_get_section_flags (abfd, sectp);
2394
2395   if ((aflag & SEC_HAS_CONTENTS) == 0)
2396     {
2397     }
2398   else if (section_is_p (sectp->name, &names.info))
2399     {
2400       this->info.s.section = sectp;
2401       this->info.size = bfd_get_section_size (sectp);
2402     }
2403   else if (section_is_p (sectp->name, &names.abbrev))
2404     {
2405       this->abbrev.s.section = sectp;
2406       this->abbrev.size = bfd_get_section_size (sectp);
2407     }
2408   else if (section_is_p (sectp->name, &names.line))
2409     {
2410       this->line.s.section = sectp;
2411       this->line.size = bfd_get_section_size (sectp);
2412     }
2413   else if (section_is_p (sectp->name, &names.loc))
2414     {
2415       this->loc.s.section = sectp;
2416       this->loc.size = bfd_get_section_size (sectp);
2417     }
2418   else if (section_is_p (sectp->name, &names.loclists))
2419     {
2420       this->loclists.s.section = sectp;
2421       this->loclists.size = bfd_get_section_size (sectp);
2422     }
2423   else if (section_is_p (sectp->name, &names.macinfo))
2424     {
2425       this->macinfo.s.section = sectp;
2426       this->macinfo.size = bfd_get_section_size (sectp);
2427     }
2428   else if (section_is_p (sectp->name, &names.macro))
2429     {
2430       this->macro.s.section = sectp;
2431       this->macro.size = bfd_get_section_size (sectp);
2432     }
2433   else if (section_is_p (sectp->name, &names.str))
2434     {
2435       this->str.s.section = sectp;
2436       this->str.size = bfd_get_section_size (sectp);
2437     }
2438   else if (section_is_p (sectp->name, &names.line_str))
2439     {
2440       this->line_str.s.section = sectp;
2441       this->line_str.size = bfd_get_section_size (sectp);
2442     }
2443   else if (section_is_p (sectp->name, &names.addr))
2444     {
2445       this->addr.s.section = sectp;
2446       this->addr.size = bfd_get_section_size (sectp);
2447     }
2448   else if (section_is_p (sectp->name, &names.frame))
2449     {
2450       this->frame.s.section = sectp;
2451       this->frame.size = bfd_get_section_size (sectp);
2452     }
2453   else if (section_is_p (sectp->name, &names.eh_frame))
2454     {
2455       this->eh_frame.s.section = sectp;
2456       this->eh_frame.size = bfd_get_section_size (sectp);
2457     }
2458   else if (section_is_p (sectp->name, &names.ranges))
2459     {
2460       this->ranges.s.section = sectp;
2461       this->ranges.size = bfd_get_section_size (sectp);
2462     }
2463   else if (section_is_p (sectp->name, &names.rnglists))
2464     {
2465       this->rnglists.s.section = sectp;
2466       this->rnglists.size = bfd_get_section_size (sectp);
2467     }
2468   else if (section_is_p (sectp->name, &names.types))
2469     {
2470       struct dwarf2_section_info type_section;
2471
2472       memset (&type_section, 0, sizeof (type_section));
2473       type_section.s.section = sectp;
2474       type_section.size = bfd_get_section_size (sectp);
2475
2476       VEC_safe_push (dwarf2_section_info_def, this->types,
2477                      &type_section);
2478     }
2479   else if (section_is_p (sectp->name, &names.gdb_index))
2480     {
2481       this->gdb_index.s.section = sectp;
2482       this->gdb_index.size = bfd_get_section_size (sectp);
2483     }
2484
2485   if ((bfd_get_section_flags (abfd, sectp) & (SEC_LOAD | SEC_ALLOC))
2486       && bfd_section_vma (abfd, sectp) == 0)
2487     this->has_section_at_zero = true;
2488 }
2489
2490 /* A helper function that decides whether a section is empty,
2491    or not present.  */
2492
2493 static int
2494 dwarf2_section_empty_p (const struct dwarf2_section_info *section)
2495 {
2496   if (section->is_virtual)
2497     return section->size == 0;
2498   return section->s.section == NULL || section->size == 0;
2499 }
2500
2501 /* Read the contents of the section INFO.
2502    OBJFILE is the main object file, but not necessarily the file where
2503    the section comes from.  E.g., for DWO files the bfd of INFO is the bfd
2504    of the DWO file.
2505    If the section is compressed, uncompress it before returning.  */
2506
2507 static void
2508 dwarf2_read_section (struct objfile *objfile, struct dwarf2_section_info *info)
2509 {
2510   asection *sectp;
2511   bfd *abfd;
2512   gdb_byte *buf, *retbuf;
2513
2514   if (info->readin)
2515     return;
2516   info->buffer = NULL;
2517   info->readin = 1;
2518
2519   if (dwarf2_section_empty_p (info))
2520     return;
2521
2522   sectp = get_section_bfd_section (info);
2523
2524   /* If this is a virtual section we need to read in the real one first.  */
2525   if (info->is_virtual)
2526     {
2527       struct dwarf2_section_info *containing_section =
2528         get_containing_section (info);
2529
2530       gdb_assert (sectp != NULL);
2531       if ((sectp->flags & SEC_RELOC) != 0)
2532         {
2533           error (_("Dwarf Error: DWP format V2 with relocations is not"
2534                    " supported in section %s [in module %s]"),
2535                  get_section_name (info), get_section_file_name (info));
2536         }
2537       dwarf2_read_section (objfile, containing_section);
2538       /* Other code should have already caught virtual sections that don't
2539          fit.  */
2540       gdb_assert (info->virtual_offset + info->size
2541                   <= containing_section->size);
2542       /* If the real section is empty or there was a problem reading the
2543          section we shouldn't get here.  */
2544       gdb_assert (containing_section->buffer != NULL);
2545       info->buffer = containing_section->buffer + info->virtual_offset;
2546       return;
2547     }
2548
2549   /* If the section has relocations, we must read it ourselves.
2550      Otherwise we attach it to the BFD.  */
2551   if ((sectp->flags & SEC_RELOC) == 0)
2552     {
2553       info->buffer = gdb_bfd_map_section (sectp, &info->size);
2554       return;
2555     }
2556
2557   buf = (gdb_byte *) obstack_alloc (&objfile->objfile_obstack, info->size);
2558   info->buffer = buf;
2559
2560   /* When debugging .o files, we may need to apply relocations; see
2561      http://sourceware.org/ml/gdb-patches/2002-04/msg00136.html .
2562      We never compress sections in .o files, so we only need to
2563      try this when the section is not compressed.  */
2564   retbuf = symfile_relocate_debug_section (objfile, sectp, buf);
2565   if (retbuf != NULL)
2566     {
2567       info->buffer = retbuf;
2568       return;
2569     }
2570
2571   abfd = get_section_bfd_owner (info);
2572   gdb_assert (abfd != NULL);
2573
2574   if (bfd_seek (abfd, sectp->filepos, SEEK_SET) != 0
2575       || bfd_bread (buf, info->size, abfd) != info->size)
2576     {
2577       error (_("Dwarf Error: Can't read DWARF data"
2578                " in section %s [in module %s]"),
2579              bfd_section_name (abfd, sectp), bfd_get_filename (abfd));
2580     }
2581 }
2582
2583 /* A helper function that returns the size of a section in a safe way.
2584    If you are positive that the section has been read before using the
2585    size, then it is safe to refer to the dwarf2_section_info object's
2586    "size" field directly.  In other cases, you must call this
2587    function, because for compressed sections the size field is not set
2588    correctly until the section has been read.  */
2589
2590 static bfd_size_type
2591 dwarf2_section_size (struct objfile *objfile,
2592                      struct dwarf2_section_info *info)
2593 {
2594   if (!info->readin)
2595     dwarf2_read_section (objfile, info);
2596   return info->size;
2597 }
2598
2599 /* Fill in SECTP, BUFP and SIZEP with section info, given OBJFILE and
2600    SECTION_NAME.  */
2601
2602 void
2603 dwarf2_get_section_info (struct objfile *objfile,
2604                          enum dwarf2_section_enum sect,
2605                          asection **sectp, const gdb_byte **bufp,
2606                          bfd_size_type *sizep)
2607 {
2608   struct dwarf2_per_objfile *data
2609     = (struct dwarf2_per_objfile *) objfile_data (objfile,
2610                                                   dwarf2_objfile_data_key);
2611   struct dwarf2_section_info *info;
2612
2613   /* We may see an objfile without any DWARF, in which case we just
2614      return nothing.  */
2615   if (data == NULL)
2616     {
2617       *sectp = NULL;
2618       *bufp = NULL;
2619       *sizep = 0;
2620       return;
2621     }
2622   switch (sect)
2623     {
2624     case DWARF2_DEBUG_FRAME:
2625       info = &data->frame;
2626       break;
2627     case DWARF2_EH_FRAME:
2628       info = &data->eh_frame;
2629       break;
2630     default:
2631       gdb_assert_not_reached ("unexpected section");
2632     }
2633
2634   dwarf2_read_section (objfile, info);
2635
2636   *sectp = get_section_bfd_section (info);
2637   *bufp = info->buffer;
2638   *sizep = info->size;
2639 }
2640
2641 /* A helper function to find the sections for a .dwz file.  */
2642
2643 static void
2644 locate_dwz_sections (bfd *abfd, asection *sectp, void *arg)
2645 {
2646   struct dwz_file *dwz_file = (struct dwz_file *) arg;
2647
2648   /* Note that we only support the standard ELF names, because .dwz
2649      is ELF-only (at the time of writing).  */
2650   if (section_is_p (sectp->name, &dwarf2_elf_names.abbrev))
2651     {
2652       dwz_file->abbrev.s.section = sectp;
2653       dwz_file->abbrev.size = bfd_get_section_size (sectp);
2654     }
2655   else if (section_is_p (sectp->name, &dwarf2_elf_names.info))
2656     {
2657       dwz_file->info.s.section = sectp;
2658       dwz_file->info.size = bfd_get_section_size (sectp);
2659     }
2660   else if (section_is_p (sectp->name, &dwarf2_elf_names.str))
2661     {
2662       dwz_file->str.s.section = sectp;
2663       dwz_file->str.size = bfd_get_section_size (sectp);
2664     }
2665   else if (section_is_p (sectp->name, &dwarf2_elf_names.line))
2666     {
2667       dwz_file->line.s.section = sectp;
2668       dwz_file->line.size = bfd_get_section_size (sectp);
2669     }
2670   else if (section_is_p (sectp->name, &dwarf2_elf_names.macro))
2671     {
2672       dwz_file->macro.s.section = sectp;
2673       dwz_file->macro.size = bfd_get_section_size (sectp);
2674     }
2675   else if (section_is_p (sectp->name, &dwarf2_elf_names.gdb_index))
2676     {
2677       dwz_file->gdb_index.s.section = sectp;
2678       dwz_file->gdb_index.size = bfd_get_section_size (sectp);
2679     }
2680 }
2681
2682 /* Open the separate '.dwz' debug file, if needed.  Return NULL if
2683    there is no .gnu_debugaltlink section in the file.  Error if there
2684    is such a section but the file cannot be found.  */
2685
2686 static struct dwz_file *
2687 dwarf2_get_dwz_file (void)
2688 {
2689   char *data;
2690   struct cleanup *cleanup;
2691   const char *filename;
2692   struct dwz_file *result;
2693   bfd_size_type buildid_len_arg;
2694   size_t buildid_len;
2695   bfd_byte *buildid;
2696
2697   if (dwarf2_per_objfile->dwz_file != NULL)
2698     return dwarf2_per_objfile->dwz_file;
2699
2700   bfd_set_error (bfd_error_no_error);
2701   data = bfd_get_alt_debug_link_info (dwarf2_per_objfile->objfile->obfd,
2702                                       &buildid_len_arg, &buildid);
2703   if (data == NULL)
2704     {
2705       if (bfd_get_error () == bfd_error_no_error)
2706         return NULL;
2707       error (_("could not read '.gnu_debugaltlink' section: %s"),
2708              bfd_errmsg (bfd_get_error ()));
2709     }
2710   cleanup = make_cleanup (xfree, data);
2711   make_cleanup (xfree, buildid);
2712
2713   buildid_len = (size_t) buildid_len_arg;
2714
2715   filename = (const char *) data;
2716
2717   std::string abs_storage;
2718   if (!IS_ABSOLUTE_PATH (filename))
2719     {
2720       char *abs = gdb_realpath (objfile_name (dwarf2_per_objfile->objfile));
2721
2722       make_cleanup (xfree, abs);
2723       abs_storage = ldirname (abs) + SLASH_STRING + filename;
2724       filename = abs_storage.c_str ();
2725     }
2726
2727   /* First try the file name given in the section.  If that doesn't
2728      work, try to use the build-id instead.  */
2729   gdb_bfd_ref_ptr dwz_bfd (gdb_bfd_open (filename, gnutarget, -1));
2730   if (dwz_bfd != NULL)
2731     {
2732       if (!build_id_verify (dwz_bfd.get (), buildid_len, buildid))
2733         dwz_bfd.release ();
2734     }
2735
2736   if (dwz_bfd == NULL)
2737     dwz_bfd = build_id_to_debug_bfd (buildid_len, buildid);
2738
2739   if (dwz_bfd == NULL)
2740     error (_("could not find '.gnu_debugaltlink' file for %s"),
2741            objfile_name (dwarf2_per_objfile->objfile));
2742
2743   result = OBSTACK_ZALLOC (&dwarf2_per_objfile->objfile->objfile_obstack,
2744                            struct dwz_file);
2745   result->dwz_bfd = dwz_bfd.release ();
2746
2747   bfd_map_over_sections (result->dwz_bfd, locate_dwz_sections, result);
2748
2749   do_cleanups (cleanup);
2750
2751   gdb_bfd_record_inclusion (dwarf2_per_objfile->objfile->obfd, result->dwz_bfd);
2752   dwarf2_per_objfile->dwz_file = result;
2753   return result;
2754 }
2755 \f
2756 /* DWARF quick_symbols_functions support.  */
2757
2758 /* TUs can share .debug_line entries, and there can be a lot more TUs than
2759    unique line tables, so we maintain a separate table of all .debug_line
2760    derived entries to support the sharing.
2761    All the quick functions need is the list of file names.  We discard the
2762    line_header when we're done and don't need to record it here.  */
2763 struct quick_file_names
2764 {
2765   /* The data used to construct the hash key.  */
2766   struct stmt_list_hash hash;
2767
2768   /* The number of entries in file_names, real_names.  */
2769   unsigned int num_file_names;
2770
2771   /* The file names from the line table, after being run through
2772      file_full_name.  */
2773   const char **file_names;
2774
2775   /* The file names from the line table after being run through
2776      gdb_realpath.  These are computed lazily.  */
2777   const char **real_names;
2778 };
2779
2780 /* When using the index (and thus not using psymtabs), each CU has an
2781    object of this type.  This is used to hold information needed by
2782    the various "quick" methods.  */
2783 struct dwarf2_per_cu_quick_data
2784 {
2785   /* The file table.  This can be NULL if there was no file table
2786      or it's currently not read in.
2787      NOTE: This points into dwarf2_per_objfile->quick_file_names_table.  */
2788   struct quick_file_names *file_names;
2789
2790   /* The corresponding symbol table.  This is NULL if symbols for this
2791      CU have not yet been read.  */
2792   struct compunit_symtab *compunit_symtab;
2793
2794   /* A temporary mark bit used when iterating over all CUs in
2795      expand_symtabs_matching.  */
2796   unsigned int mark : 1;
2797
2798   /* True if we've tried to read the file table and found there isn't one.
2799      There will be no point in trying to read it again next time.  */
2800   unsigned int no_file_data : 1;
2801 };
2802
2803 /* Utility hash function for a stmt_list_hash.  */
2804
2805 static hashval_t
2806 hash_stmt_list_entry (const struct stmt_list_hash *stmt_list_hash)
2807 {
2808   hashval_t v = 0;
2809
2810   if (stmt_list_hash->dwo_unit != NULL)
2811     v += (uintptr_t) stmt_list_hash->dwo_unit->dwo_file;
2812   v += to_underlying (stmt_list_hash->line_sect_off);
2813   return v;
2814 }
2815
2816 /* Utility equality function for a stmt_list_hash.  */
2817
2818 static int
2819 eq_stmt_list_entry (const struct stmt_list_hash *lhs,
2820                     const struct stmt_list_hash *rhs)
2821 {
2822   if ((lhs->dwo_unit != NULL) != (rhs->dwo_unit != NULL))
2823     return 0;
2824   if (lhs->dwo_unit != NULL
2825       && lhs->dwo_unit->dwo_file != rhs->dwo_unit->dwo_file)
2826     return 0;
2827
2828   return lhs->line_sect_off == rhs->line_sect_off;
2829 }
2830
2831 /* Hash function for a quick_file_names.  */
2832
2833 static hashval_t
2834 hash_file_name_entry (const void *e)
2835 {
2836   const struct quick_file_names *file_data
2837     = (const struct quick_file_names *) e;
2838
2839   return hash_stmt_list_entry (&file_data->hash);
2840 }
2841
2842 /* Equality function for a quick_file_names.  */
2843
2844 static int
2845 eq_file_name_entry (const void *a, const void *b)
2846 {
2847   const struct quick_file_names *ea = (const struct quick_file_names *) a;
2848   const struct quick_file_names *eb = (const struct quick_file_names *) b;
2849
2850   return eq_stmt_list_entry (&ea->hash, &eb->hash);
2851 }
2852
2853 /* Delete function for a quick_file_names.  */
2854
2855 static void
2856 delete_file_name_entry (void *e)
2857 {
2858   struct quick_file_names *file_data = (struct quick_file_names *) e;
2859   int i;
2860
2861   for (i = 0; i < file_data->num_file_names; ++i)
2862     {
2863       xfree ((void*) file_data->file_names[i]);
2864       if (file_data->real_names)
2865         xfree ((void*) file_data->real_names[i]);
2866     }
2867
2868   /* The space for the struct itself lives on objfile_obstack,
2869      so we don't free it here.  */
2870 }
2871
2872 /* Create a quick_file_names hash table.  */
2873
2874 static htab_t
2875 create_quick_file_names_table (unsigned int nr_initial_entries)
2876 {
2877   return htab_create_alloc (nr_initial_entries,
2878                             hash_file_name_entry, eq_file_name_entry,
2879                             delete_file_name_entry, xcalloc, xfree);
2880 }
2881
2882 /* Read in PER_CU->CU.  This function is unrelated to symtabs, symtab would
2883    have to be created afterwards.  You should call age_cached_comp_units after
2884    processing PER_CU->CU.  dw2_setup must have been already called.  */
2885
2886 static void
2887 load_cu (struct dwarf2_per_cu_data *per_cu)
2888 {
2889   if (per_cu->is_debug_types)
2890     load_full_type_unit (per_cu);
2891   else
2892     load_full_comp_unit (per_cu, language_minimal);
2893
2894   if (per_cu->cu == NULL)
2895     return;  /* Dummy CU.  */
2896
2897   dwarf2_find_base_address (per_cu->cu->dies, per_cu->cu);
2898 }
2899
2900 /* Read in the symbols for PER_CU.  */
2901
2902 static void
2903 dw2_do_instantiate_symtab (struct dwarf2_per_cu_data *per_cu)
2904 {
2905   struct cleanup *back_to;
2906
2907   /* Skip type_unit_groups, reading the type units they contain
2908      is handled elsewhere.  */
2909   if (IS_TYPE_UNIT_GROUP (per_cu))
2910     return;
2911
2912   back_to = make_cleanup (dwarf2_release_queue, NULL);
2913
2914   if (dwarf2_per_objfile->using_index
2915       ? per_cu->v.quick->compunit_symtab == NULL
2916       : (per_cu->v.psymtab == NULL || !per_cu->v.psymtab->readin))
2917     {
2918       queue_comp_unit (per_cu, language_minimal);
2919       load_cu (per_cu);
2920
2921       /* If we just loaded a CU from a DWO, and we're working with an index
2922          that may badly handle TUs, load all the TUs in that DWO as well.
2923          http://sourceware.org/bugzilla/show_bug.cgi?id=15021  */
2924       if (!per_cu->is_debug_types
2925           && per_cu->cu != NULL
2926           && per_cu->cu->dwo_unit != NULL
2927           && dwarf2_per_objfile->index_table != NULL
2928           && dwarf2_per_objfile->index_table->version <= 7
2929           /* DWP files aren't supported yet.  */
2930           && get_dwp_file () == NULL)
2931         queue_and_load_all_dwo_tus (per_cu);
2932     }
2933
2934   process_queue ();
2935
2936   /* Age the cache, releasing compilation units that have not
2937      been used recently.  */
2938   age_cached_comp_units ();
2939
2940   do_cleanups (back_to);
2941 }
2942
2943 /* Ensure that the symbols for PER_CU have been read in.  OBJFILE is
2944    the objfile from which this CU came.  Returns the resulting symbol
2945    table.  */
2946
2947 static struct compunit_symtab *
2948 dw2_instantiate_symtab (struct dwarf2_per_cu_data *per_cu)
2949 {
2950   gdb_assert (dwarf2_per_objfile->using_index);
2951   if (!per_cu->v.quick->compunit_symtab)
2952     {
2953       struct cleanup *back_to = make_cleanup (free_cached_comp_units, NULL);
2954       scoped_restore decrementer = increment_reading_symtab ();
2955       dw2_do_instantiate_symtab (per_cu);
2956       process_cu_includes ();
2957       do_cleanups (back_to);
2958     }
2959
2960   return per_cu->v.quick->compunit_symtab;
2961 }
2962
2963 /* Return the CU/TU given its index.
2964
2965    This is intended for loops like:
2966
2967    for (i = 0; i < (dwarf2_per_objfile->n_comp_units
2968                     + dwarf2_per_objfile->n_type_units); ++i)
2969      {
2970        struct dwarf2_per_cu_data *per_cu = dw2_get_cutu (i);
2971
2972        ...;
2973      }
2974 */
2975
2976 static struct dwarf2_per_cu_data *
2977 dw2_get_cutu (int index)
2978 {
2979   if (index >= dwarf2_per_objfile->n_comp_units)
2980     {
2981       index -= dwarf2_per_objfile->n_comp_units;
2982       gdb_assert (index < dwarf2_per_objfile->n_type_units);
2983       return &dwarf2_per_objfile->all_type_units[index]->per_cu;
2984     }
2985
2986   return dwarf2_per_objfile->all_comp_units[index];
2987 }
2988
2989 /* Return the CU given its index.
2990    This differs from dw2_get_cutu in that it's for when you know INDEX
2991    refers to a CU.  */
2992
2993 static struct dwarf2_per_cu_data *
2994 dw2_get_cu (int index)
2995 {
2996   gdb_assert (index >= 0 && index < dwarf2_per_objfile->n_comp_units);
2997
2998   return dwarf2_per_objfile->all_comp_units[index];
2999 }
3000
3001 /* A helper for create_cus_from_index that handles a given list of
3002    CUs.  */
3003
3004 static void
3005 create_cus_from_index_list (struct objfile *objfile,
3006                             const gdb_byte *cu_list, offset_type n_elements,
3007                             struct dwarf2_section_info *section,
3008                             int is_dwz,
3009                             int base_offset)
3010 {
3011   offset_type i;
3012
3013   for (i = 0; i < n_elements; i += 2)
3014     {
3015       gdb_static_assert (sizeof (ULONGEST) >= 8);
3016
3017       sect_offset sect_off
3018         = (sect_offset) extract_unsigned_integer (cu_list, 8, BFD_ENDIAN_LITTLE);
3019       ULONGEST length = extract_unsigned_integer (cu_list + 8, 8, BFD_ENDIAN_LITTLE);
3020       cu_list += 2 * 8;
3021
3022       dwarf2_per_cu_data *the_cu
3023         = OBSTACK_ZALLOC (&objfile->objfile_obstack,
3024                           struct dwarf2_per_cu_data);
3025       the_cu->sect_off = sect_off;
3026       the_cu->length = length;
3027       the_cu->objfile = objfile;
3028       the_cu->section = section;
3029       the_cu->v.quick = OBSTACK_ZALLOC (&objfile->objfile_obstack,
3030                                         struct dwarf2_per_cu_quick_data);
3031       the_cu->is_dwz = is_dwz;
3032       dwarf2_per_objfile->all_comp_units[base_offset + i / 2] = the_cu;
3033     }
3034 }
3035
3036 /* Read the CU list from the mapped index, and use it to create all
3037    the CU objects for this objfile.  */
3038
3039 static void
3040 create_cus_from_index (struct objfile *objfile,
3041                        const gdb_byte *cu_list, offset_type cu_list_elements,
3042                        const gdb_byte *dwz_list, offset_type dwz_elements)
3043 {
3044   struct dwz_file *dwz;
3045
3046   dwarf2_per_objfile->n_comp_units = (cu_list_elements + dwz_elements) / 2;
3047   dwarf2_per_objfile->all_comp_units =
3048     XOBNEWVEC (&objfile->objfile_obstack, struct dwarf2_per_cu_data *,
3049                dwarf2_per_objfile->n_comp_units);
3050
3051   create_cus_from_index_list (objfile, cu_list, cu_list_elements,
3052                               &dwarf2_per_objfile->info, 0, 0);
3053
3054   if (dwz_elements == 0)
3055     return;
3056
3057   dwz = dwarf2_get_dwz_file ();
3058   create_cus_from_index_list (objfile, dwz_list, dwz_elements, &dwz->info, 1,
3059                               cu_list_elements / 2);
3060 }
3061
3062 /* Create the signatured type hash table from the index.  */
3063
3064 static void
3065 create_signatured_type_table_from_index (struct objfile *objfile,
3066                                          struct dwarf2_section_info *section,
3067                                          const gdb_byte *bytes,
3068                                          offset_type elements)
3069 {
3070   offset_type i;
3071   htab_t sig_types_hash;
3072
3073   dwarf2_per_objfile->n_type_units
3074     = dwarf2_per_objfile->n_allocated_type_units
3075     = elements / 3;
3076   dwarf2_per_objfile->all_type_units =
3077     XNEWVEC (struct signatured_type *, dwarf2_per_objfile->n_type_units);
3078
3079   sig_types_hash = allocate_signatured_type_table (objfile);
3080
3081   for (i = 0; i < elements; i += 3)
3082     {
3083       struct signatured_type *sig_type;
3084       ULONGEST signature;
3085       void **slot;
3086       cu_offset type_offset_in_tu;
3087
3088       gdb_static_assert (sizeof (ULONGEST) >= 8);
3089       sect_offset sect_off
3090         = (sect_offset) extract_unsigned_integer (bytes, 8, BFD_ENDIAN_LITTLE);
3091       type_offset_in_tu
3092         = (cu_offset) extract_unsigned_integer (bytes + 8, 8,
3093                                                 BFD_ENDIAN_LITTLE);
3094       signature = extract_unsigned_integer (bytes + 16, 8, BFD_ENDIAN_LITTLE);
3095       bytes += 3 * 8;
3096
3097       sig_type = OBSTACK_ZALLOC (&objfile->objfile_obstack,
3098                                  struct signatured_type);
3099       sig_type->signature = signature;
3100       sig_type->type_offset_in_tu = type_offset_in_tu;
3101       sig_type->per_cu.is_debug_types = 1;
3102       sig_type->per_cu.section = section;
3103       sig_type->per_cu.sect_off = sect_off;
3104       sig_type->per_cu.objfile = objfile;
3105       sig_type->per_cu.v.quick
3106         = OBSTACK_ZALLOC (&objfile->objfile_obstack,
3107                           struct dwarf2_per_cu_quick_data);
3108
3109       slot = htab_find_slot (sig_types_hash, sig_type, INSERT);
3110       *slot = sig_type;
3111
3112       dwarf2_per_objfile->all_type_units[i / 3] = sig_type;
3113     }
3114
3115   dwarf2_per_objfile->signatured_types = sig_types_hash;
3116 }
3117
3118 /* Read the address map data from the mapped index, and use it to
3119    populate the objfile's psymtabs_addrmap.  */
3120
3121 static void
3122 create_addrmap_from_index (struct objfile *objfile, struct mapped_index *index)
3123 {
3124   struct gdbarch *gdbarch = get_objfile_arch (objfile);
3125   const gdb_byte *iter, *end;
3126   struct addrmap *mutable_map;
3127   CORE_ADDR baseaddr;
3128
3129   auto_obstack temp_obstack;
3130
3131   mutable_map = addrmap_create_mutable (&temp_obstack);
3132
3133   iter = index->address_table;
3134   end = iter + index->address_table_size;
3135
3136   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
3137
3138   while (iter < end)
3139     {
3140       ULONGEST hi, lo, cu_index;
3141       lo = extract_unsigned_integer (iter, 8, BFD_ENDIAN_LITTLE);
3142       iter += 8;
3143       hi = extract_unsigned_integer (iter, 8, BFD_ENDIAN_LITTLE);
3144       iter += 8;
3145       cu_index = extract_unsigned_integer (iter, 4, BFD_ENDIAN_LITTLE);
3146       iter += 4;
3147
3148       if (lo > hi)
3149         {
3150           complaint (&symfile_complaints,
3151                      _(".gdb_index address table has invalid range (%s - %s)"),
3152                      hex_string (lo), hex_string (hi));
3153           continue;
3154         }
3155
3156       if (cu_index >= dwarf2_per_objfile->n_comp_units)
3157         {
3158           complaint (&symfile_complaints,
3159                      _(".gdb_index address table has invalid CU number %u"),
3160                      (unsigned) cu_index);
3161           continue;
3162         }
3163
3164       lo = gdbarch_adjust_dwarf2_addr (gdbarch, lo + baseaddr);
3165       hi = gdbarch_adjust_dwarf2_addr (gdbarch, hi + baseaddr);
3166       addrmap_set_empty (mutable_map, lo, hi - 1, dw2_get_cutu (cu_index));
3167     }
3168
3169   objfile->psymtabs_addrmap = addrmap_create_fixed (mutable_map,
3170                                                     &objfile->objfile_obstack);
3171 }
3172
3173 /* The hash function for strings in the mapped index.  This is the same as
3174    SYMBOL_HASH_NEXT, but we keep a separate copy to maintain control over the
3175    implementation.  This is necessary because the hash function is tied to the
3176    format of the mapped index file.  The hash values do not have to match with
3177    SYMBOL_HASH_NEXT.
3178    
3179    Use INT_MAX for INDEX_VERSION if you generate the current index format.  */
3180
3181 static hashval_t
3182 mapped_index_string_hash (int index_version, const void *p)
3183 {
3184   const unsigned char *str = (const unsigned char *) p;
3185   hashval_t r = 0;
3186   unsigned char c;
3187
3188   while ((c = *str++) != 0)
3189     {
3190       if (index_version >= 5)
3191         c = tolower (c);
3192       r = r * 67 + c - 113;
3193     }
3194
3195   return r;
3196 }
3197
3198 /* Find a slot in the mapped index INDEX for the object named NAME.
3199    If NAME is found, set *VEC_OUT to point to the CU vector in the
3200    constant pool and return 1.  If NAME cannot be found, return 0.  */
3201
3202 static int
3203 find_slot_in_mapped_hash (struct mapped_index *index, const char *name,
3204                           offset_type **vec_out)
3205 {
3206   struct cleanup *back_to = make_cleanup (null_cleanup, 0);
3207   offset_type hash;
3208   offset_type slot, step;
3209   int (*cmp) (const char *, const char *);
3210
3211   if (current_language->la_language == language_cplus
3212       || current_language->la_language == language_fortran
3213       || current_language->la_language == language_d)
3214     {
3215       /* NAME is already canonical.  Drop any qualifiers as .gdb_index does
3216          not contain any.  */
3217
3218       if (strchr (name, '(') != NULL)
3219         {
3220           char *without_params = cp_remove_params (name);
3221
3222           if (without_params != NULL)
3223             {
3224               make_cleanup (xfree, without_params);
3225               name = without_params;
3226             }
3227         }
3228     }
3229
3230   /* Index version 4 did not support case insensitive searches.  But the
3231      indices for case insensitive languages are built in lowercase, therefore
3232      simulate our NAME being searched is also lowercased.  */
3233   hash = mapped_index_string_hash ((index->version == 4
3234                                     && case_sensitivity == case_sensitive_off
3235                                     ? 5 : index->version),
3236                                    name);
3237
3238   slot = hash & (index->symbol_table_slots - 1);
3239   step = ((hash * 17) & (index->symbol_table_slots - 1)) | 1;
3240   cmp = (case_sensitivity == case_sensitive_on ? strcmp : strcasecmp);
3241
3242   for (;;)
3243     {
3244       /* Convert a slot number to an offset into the table.  */
3245       offset_type i = 2 * slot;
3246       const char *str;
3247       if (index->symbol_table[i] == 0 && index->symbol_table[i + 1] == 0)
3248         {
3249           do_cleanups (back_to);
3250           return 0;
3251         }
3252
3253       str = index->constant_pool + MAYBE_SWAP (index->symbol_table[i]);
3254       if (!cmp (name, str))
3255         {
3256           *vec_out = (offset_type *) (index->constant_pool
3257                                       + MAYBE_SWAP (index->symbol_table[i + 1]));
3258           do_cleanups (back_to);
3259           return 1;
3260         }
3261
3262       slot = (slot + step) & (index->symbol_table_slots - 1);
3263     }
3264 }
3265
3266 /* A helper function that reads the .gdb_index from SECTION and fills
3267    in MAP.  FILENAME is the name of the file containing the section;
3268    it is used for error reporting.  DEPRECATED_OK is nonzero if it is
3269    ok to use deprecated sections.
3270
3271    CU_LIST, CU_LIST_ELEMENTS, TYPES_LIST, and TYPES_LIST_ELEMENTS are
3272    out parameters that are filled in with information about the CU and
3273    TU lists in the section.
3274
3275    Returns 1 if all went well, 0 otherwise.  */
3276
3277 static int
3278 read_index_from_section (struct objfile *objfile,
3279                          const char *filename,
3280                          int deprecated_ok,
3281                          struct dwarf2_section_info *section,
3282                          struct mapped_index *map,
3283                          const gdb_byte **cu_list,
3284                          offset_type *cu_list_elements,
3285                          const gdb_byte **types_list,
3286                          offset_type *types_list_elements)
3287 {
3288   const gdb_byte *addr;
3289   offset_type version;
3290   offset_type *metadata;
3291   int i;
3292
3293   if (dwarf2_section_empty_p (section))
3294     return 0;
3295
3296   /* Older elfutils strip versions could keep the section in the main
3297      executable while splitting it for the separate debug info file.  */
3298   if ((get_section_flags (section) & SEC_HAS_CONTENTS) == 0)
3299     return 0;
3300
3301   dwarf2_read_section (objfile, section);
3302
3303   addr = section->buffer;
3304   /* Version check.  */
3305   version = MAYBE_SWAP (*(offset_type *) addr);
3306   /* Versions earlier than 3 emitted every copy of a psymbol.  This
3307      causes the index to behave very poorly for certain requests.  Version 3
3308      contained incomplete addrmap.  So, it seems better to just ignore such
3309      indices.  */
3310   if (version < 4)
3311     {
3312       static int warning_printed = 0;
3313       if (!warning_printed)
3314         {
3315           warning (_("Skipping obsolete .gdb_index section in %s."),
3316                    filename);
3317           warning_printed = 1;
3318         }
3319       return 0;
3320     }
3321   /* Index version 4 uses a different hash function than index version
3322      5 and later.
3323
3324      Versions earlier than 6 did not emit psymbols for inlined
3325      functions.  Using these files will cause GDB not to be able to
3326      set breakpoints on inlined functions by name, so we ignore these
3327      indices unless the user has done
3328      "set use-deprecated-index-sections on".  */
3329   if (version < 6 && !deprecated_ok)
3330     {
3331       static int warning_printed = 0;
3332       if (!warning_printed)
3333         {
3334           warning (_("\
3335 Skipping deprecated .gdb_index section in %s.\n\
3336 Do \"set use-deprecated-index-sections on\" before the file is read\n\
3337 to use the section anyway."),
3338                    filename);
3339           warning_printed = 1;
3340         }
3341       return 0;
3342     }
3343   /* Version 7 indices generated by gold refer to the CU for a symbol instead
3344      of the TU (for symbols coming from TUs),
3345      http://sourceware.org/bugzilla/show_bug.cgi?id=15021.
3346      Plus gold-generated indices can have duplicate entries for global symbols,
3347      http://sourceware.org/bugzilla/show_bug.cgi?id=15646.
3348      These are just performance bugs, and we can't distinguish gdb-generated
3349      indices from gold-generated ones, so issue no warning here.  */
3350
3351   /* Indexes with higher version than the one supported by GDB may be no
3352      longer backward compatible.  */
3353   if (version > 8)
3354     return 0;
3355
3356   map->version = version;
3357   map->total_size = section->size;
3358
3359   metadata = (offset_type *) (addr + sizeof (offset_type));
3360
3361   i = 0;
3362   *cu_list = addr + MAYBE_SWAP (metadata[i]);
3363   *cu_list_elements = ((MAYBE_SWAP (metadata[i + 1]) - MAYBE_SWAP (metadata[i]))
3364                        / 8);
3365   ++i;
3366
3367   *types_list = addr + MAYBE_SWAP (metadata[i]);
3368   *types_list_elements = ((MAYBE_SWAP (metadata[i + 1])
3369                            - MAYBE_SWAP (metadata[i]))
3370                           / 8);
3371   ++i;
3372
3373   map->address_table = addr + MAYBE_SWAP (metadata[i]);
3374   map->address_table_size = (MAYBE_SWAP (metadata[i + 1])
3375                              - MAYBE_SWAP (metadata[i]));
3376   ++i;
3377
3378   map->symbol_table = (offset_type *) (addr + MAYBE_SWAP (metadata[i]));
3379   map->symbol_table_slots = ((MAYBE_SWAP (metadata[i + 1])
3380                               - MAYBE_SWAP (metadata[i]))
3381                              / (2 * sizeof (offset_type)));
3382   ++i;
3383
3384   map->constant_pool = (char *) (addr + MAYBE_SWAP (metadata[i]));
3385
3386   return 1;
3387 }
3388
3389
3390 /* Read the index file.  If everything went ok, initialize the "quick"
3391    elements of all the CUs and return 1.  Otherwise, return 0.  */
3392
3393 static int
3394 dwarf2_read_index (struct objfile *objfile)
3395 {
3396   struct mapped_index local_map, *map;
3397   const gdb_byte *cu_list, *types_list, *dwz_list = NULL;
3398   offset_type cu_list_elements, types_list_elements, dwz_list_elements = 0;
3399   struct dwz_file *dwz;
3400
3401   if (!read_index_from_section (objfile, objfile_name (objfile),
3402                                 use_deprecated_index_sections,
3403                                 &dwarf2_per_objfile->gdb_index, &local_map,
3404                                 &cu_list, &cu_list_elements,
3405                                 &types_list, &types_list_elements))
3406     return 0;
3407
3408   /* Don't use the index if it's empty.  */
3409   if (local_map.symbol_table_slots == 0)
3410     return 0;
3411
3412   /* If there is a .dwz file, read it so we can get its CU list as
3413      well.  */
3414   dwz = dwarf2_get_dwz_file ();
3415   if (dwz != NULL)
3416     {
3417       struct mapped_index dwz_map;
3418       const gdb_byte *dwz_types_ignore;
3419       offset_type dwz_types_elements_ignore;
3420
3421       if (!read_index_from_section (objfile, bfd_get_filename (dwz->dwz_bfd),
3422                                     1,
3423                                     &dwz->gdb_index, &dwz_map,
3424                                     &dwz_list, &dwz_list_elements,
3425                                     &dwz_types_ignore,
3426                                     &dwz_types_elements_ignore))
3427         {
3428           warning (_("could not read '.gdb_index' section from %s; skipping"),
3429                    bfd_get_filename (dwz->dwz_bfd));
3430           return 0;
3431         }
3432     }
3433
3434   create_cus_from_index (objfile, cu_list, cu_list_elements, dwz_list,
3435                          dwz_list_elements);
3436
3437   if (types_list_elements)
3438     {
3439       struct dwarf2_section_info *section;
3440
3441       /* We can only handle a single .debug_types when we have an
3442          index.  */
3443       if (VEC_length (dwarf2_section_info_def, dwarf2_per_objfile->types) != 1)
3444         return 0;
3445
3446       section = VEC_index (dwarf2_section_info_def,
3447                            dwarf2_per_objfile->types, 0);
3448
3449       create_signatured_type_table_from_index (objfile, section, types_list,
3450                                                types_list_elements);
3451     }
3452
3453   create_addrmap_from_index (objfile, &local_map);
3454
3455   map = XOBNEW (&objfile->objfile_obstack, struct mapped_index);
3456   *map = local_map;
3457
3458   dwarf2_per_objfile->index_table = map;
3459   dwarf2_per_objfile->using_index = 1;
3460   dwarf2_per_objfile->quick_file_names_table =
3461     create_quick_file_names_table (dwarf2_per_objfile->n_comp_units);
3462
3463   return 1;
3464 }
3465
3466 /* A helper for the "quick" functions which sets the global
3467    dwarf2_per_objfile according to OBJFILE.  */
3468
3469 static void
3470 dw2_setup (struct objfile *objfile)
3471 {
3472   dwarf2_per_objfile = ((struct dwarf2_per_objfile *)
3473                         objfile_data (objfile, dwarf2_objfile_data_key));
3474   gdb_assert (dwarf2_per_objfile);
3475 }
3476
3477 /* die_reader_func for dw2_get_file_names.  */
3478
3479 static void
3480 dw2_get_file_names_reader (const struct die_reader_specs *reader,
3481                            const gdb_byte *info_ptr,
3482                            struct die_info *comp_unit_die,
3483                            int has_children,
3484                            void *data)
3485 {
3486   struct dwarf2_cu *cu = reader->cu;
3487   struct dwarf2_per_cu_data *this_cu = cu->per_cu;  
3488   struct objfile *objfile = dwarf2_per_objfile->objfile;
3489   struct dwarf2_per_cu_data *lh_cu;
3490   struct attribute *attr;
3491   int i;
3492   void **slot;
3493   struct quick_file_names *qfn;
3494
3495   gdb_assert (! this_cu->is_debug_types);
3496
3497   /* Our callers never want to match partial units -- instead they
3498      will match the enclosing full CU.  */
3499   if (comp_unit_die->tag == DW_TAG_partial_unit)
3500     {
3501       this_cu->v.quick->no_file_data = 1;
3502       return;
3503     }
3504
3505   lh_cu = this_cu;
3506   slot = NULL;
3507
3508   line_header_up lh;
3509   sect_offset line_offset {};
3510
3511   attr = dwarf2_attr (comp_unit_die, DW_AT_stmt_list, cu);
3512   if (attr)
3513     {
3514       struct quick_file_names find_entry;
3515
3516       line_offset = (sect_offset) DW_UNSND (attr);
3517
3518       /* We may have already read in this line header (TU line header sharing).
3519          If we have we're done.  */
3520       find_entry.hash.dwo_unit = cu->dwo_unit;
3521       find_entry.hash.line_sect_off = line_offset;
3522       slot = htab_find_slot (dwarf2_per_objfile->quick_file_names_table,
3523                              &find_entry, INSERT);
3524       if (*slot != NULL)
3525         {
3526           lh_cu->v.quick->file_names = (struct quick_file_names *) *slot;
3527           return;
3528         }
3529
3530       lh = dwarf_decode_line_header (line_offset, cu);
3531     }
3532   if (lh == NULL)
3533     {
3534       lh_cu->v.quick->no_file_data = 1;
3535       return;
3536     }
3537
3538   qfn = XOBNEW (&objfile->objfile_obstack, struct quick_file_names);
3539   qfn->hash.dwo_unit = cu->dwo_unit;
3540   qfn->hash.line_sect_off = line_offset;
3541   gdb_assert (slot != NULL);
3542   *slot = qfn;
3543
3544   file_and_directory fnd = find_file_and_directory (comp_unit_die, cu);
3545
3546   qfn->num_file_names = lh->file_names.size ();
3547   qfn->file_names =
3548     XOBNEWVEC (&objfile->objfile_obstack, const char *, lh->file_names.size ());
3549   for (i = 0; i < lh->file_names.size (); ++i)
3550     qfn->file_names[i] = file_full_name (i + 1, lh.get (), fnd.comp_dir);
3551   qfn->real_names = NULL;
3552
3553   lh_cu->v.quick->file_names = qfn;
3554 }
3555
3556 /* A helper for the "quick" functions which attempts to read the line
3557    table for THIS_CU.  */
3558
3559 static struct quick_file_names *
3560 dw2_get_file_names (struct dwarf2_per_cu_data *this_cu)
3561 {
3562   /* This should never be called for TUs.  */
3563   gdb_assert (! this_cu->is_debug_types);
3564   /* Nor type unit groups.  */
3565   gdb_assert (! IS_TYPE_UNIT_GROUP (this_cu));
3566
3567   if (this_cu->v.quick->file_names != NULL)
3568     return this_cu->v.quick->file_names;
3569   /* If we know there is no line data, no point in looking again.  */
3570   if (this_cu->v.quick->no_file_data)
3571     return NULL;
3572
3573   init_cutu_and_read_dies_simple (this_cu, dw2_get_file_names_reader, NULL);
3574
3575   if (this_cu->v.quick->no_file_data)
3576     return NULL;
3577   return this_cu->v.quick->file_names;
3578 }
3579
3580 /* A helper for the "quick" functions which computes and caches the
3581    real path for a given file name from the line table.  */
3582
3583 static const char *
3584 dw2_get_real_path (struct objfile *objfile,
3585                    struct quick_file_names *qfn, int index)
3586 {
3587   if (qfn->real_names == NULL)
3588     qfn->real_names = OBSTACK_CALLOC (&objfile->objfile_obstack,
3589                                       qfn->num_file_names, const char *);
3590
3591   if (qfn->real_names[index] == NULL)
3592     qfn->real_names[index] = gdb_realpath (qfn->file_names[index]);
3593
3594   return qfn->real_names[index];
3595 }
3596
3597 static struct symtab *
3598 dw2_find_last_source_symtab (struct objfile *objfile)
3599 {
3600   struct compunit_symtab *cust;
3601   int index;
3602
3603   dw2_setup (objfile);
3604   index = dwarf2_per_objfile->n_comp_units - 1;
3605   cust = dw2_instantiate_symtab (dw2_get_cutu (index));
3606   if (cust == NULL)
3607     return NULL;
3608   return compunit_primary_filetab (cust);
3609 }
3610
3611 /* Traversal function for dw2_forget_cached_source_info.  */
3612
3613 static int
3614 dw2_free_cached_file_names (void **slot, void *info)
3615 {
3616   struct quick_file_names *file_data = (struct quick_file_names *) *slot;
3617
3618   if (file_data->real_names)
3619     {
3620       int i;
3621
3622       for (i = 0; i < file_data->num_file_names; ++i)
3623         {
3624           xfree ((void*) file_data->real_names[i]);
3625           file_data->real_names[i] = NULL;
3626         }
3627     }
3628
3629   return 1;
3630 }
3631
3632 static void
3633 dw2_forget_cached_source_info (struct objfile *objfile)
3634 {
3635   dw2_setup (objfile);
3636
3637   htab_traverse_noresize (dwarf2_per_objfile->quick_file_names_table,
3638                           dw2_free_cached_file_names, NULL);
3639 }
3640
3641 /* Helper function for dw2_map_symtabs_matching_filename that expands
3642    the symtabs and calls the iterator.  */
3643
3644 static int
3645 dw2_map_expand_apply (struct objfile *objfile,
3646                       struct dwarf2_per_cu_data *per_cu,
3647                       const char *name, const char *real_path,
3648                       gdb::function_view<bool (symtab *)> callback)
3649 {
3650   struct compunit_symtab *last_made = objfile->compunit_symtabs;
3651
3652   /* Don't visit already-expanded CUs.  */
3653   if (per_cu->v.quick->compunit_symtab)
3654     return 0;
3655
3656   /* This may expand more than one symtab, and we want to iterate over
3657      all of them.  */
3658   dw2_instantiate_symtab (per_cu);
3659
3660   return iterate_over_some_symtabs (name, real_path, objfile->compunit_symtabs,
3661                                     last_made, callback);
3662 }
3663
3664 /* Implementation of the map_symtabs_matching_filename method.  */
3665
3666 static bool
3667 dw2_map_symtabs_matching_filename
3668   (struct objfile *objfile, const char *name, const char *real_path,
3669    gdb::function_view<bool (symtab *)> callback)
3670 {
3671   int i;
3672   const char *name_basename = lbasename (name);
3673
3674   dw2_setup (objfile);
3675
3676   /* The rule is CUs specify all the files, including those used by
3677      any TU, so there's no need to scan TUs here.  */
3678
3679   for (i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
3680     {
3681       int j;
3682       struct dwarf2_per_cu_data *per_cu = dw2_get_cu (i);
3683       struct quick_file_names *file_data;
3684
3685       /* We only need to look at symtabs not already expanded.  */
3686       if (per_cu->v.quick->compunit_symtab)
3687         continue;
3688
3689       file_data = dw2_get_file_names (per_cu);
3690       if (file_data == NULL)
3691         continue;
3692
3693       for (j = 0; j < file_data->num_file_names; ++j)
3694         {
3695           const char *this_name = file_data->file_names[j];
3696           const char *this_real_name;
3697
3698           if (compare_filenames_for_search (this_name, name))
3699             {
3700               if (dw2_map_expand_apply (objfile, per_cu, name, real_path,
3701                                         callback))
3702                 return true;
3703               continue;
3704             }
3705
3706           /* Before we invoke realpath, which can get expensive when many
3707              files are involved, do a quick comparison of the basenames.  */
3708           if (! basenames_may_differ
3709               && FILENAME_CMP (lbasename (this_name), name_basename) != 0)
3710             continue;
3711
3712           this_real_name = dw2_get_real_path (objfile, file_data, j);
3713           if (compare_filenames_for_search (this_real_name, name))
3714             {
3715               if (dw2_map_expand_apply (objfile, per_cu, name, real_path,
3716                                         callback))
3717                 return true;
3718               continue;
3719             }
3720
3721           if (real_path != NULL)
3722             {
3723               gdb_assert (IS_ABSOLUTE_PATH (real_path));
3724               gdb_assert (IS_ABSOLUTE_PATH (name));
3725               if (this_real_name != NULL
3726                   && FILENAME_CMP (real_path, this_real_name) == 0)
3727                 {
3728                   if (dw2_map_expand_apply (objfile, per_cu, name, real_path,
3729                                             callback))
3730                     return true;
3731                   continue;
3732                 }
3733             }
3734         }
3735     }
3736
3737   return false;
3738 }
3739
3740 /* Struct used to manage iterating over all CUs looking for a symbol.  */
3741
3742 struct dw2_symtab_iterator
3743 {
3744   /* The internalized form of .gdb_index.  */
3745   struct mapped_index *index;
3746   /* If non-zero, only look for symbols that match BLOCK_INDEX.  */
3747   int want_specific_block;
3748   /* One of GLOBAL_BLOCK or STATIC_BLOCK.
3749      Unused if !WANT_SPECIFIC_BLOCK.  */
3750   int block_index;
3751   /* The kind of symbol we're looking for.  */
3752   domain_enum domain;
3753   /* The list of CUs from the index entry of the symbol,
3754      or NULL if not found.  */
3755   offset_type *vec;
3756   /* The next element in VEC to look at.  */
3757   int next;
3758   /* The number of elements in VEC, or zero if there is no match.  */
3759   int length;
3760   /* Have we seen a global version of the symbol?
3761      If so we can ignore all further global instances.
3762      This is to work around gold/15646, inefficient gold-generated
3763      indices.  */
3764   int global_seen;
3765 };
3766
3767 /* Initialize the index symtab iterator ITER.
3768    If WANT_SPECIFIC_BLOCK is non-zero, only look for symbols
3769    in block BLOCK_INDEX.  Otherwise BLOCK_INDEX is ignored.  */
3770
3771 static void
3772 dw2_symtab_iter_init (struct dw2_symtab_iterator *iter,
3773                       struct mapped_index *index,
3774                       int want_specific_block,
3775                       int block_index,
3776                       domain_enum domain,
3777                       const char *name)
3778 {
3779   iter->index = index;
3780   iter->want_specific_block = want_specific_block;
3781   iter->block_index = block_index;
3782   iter->domain = domain;
3783   iter->next = 0;
3784   iter->global_seen = 0;
3785
3786   if (find_slot_in_mapped_hash (index, name, &iter->vec))
3787     iter->length = MAYBE_SWAP (*iter->vec);
3788   else
3789     {
3790       iter->vec = NULL;
3791       iter->length = 0;
3792     }
3793 }
3794
3795 /* Return the next matching CU or NULL if there are no more.  */
3796
3797 static struct dwarf2_per_cu_data *
3798 dw2_symtab_iter_next (struct dw2_symtab_iterator *iter)
3799 {
3800   for ( ; iter->next < iter->length; ++iter->next)
3801     {
3802       offset_type cu_index_and_attrs =
3803         MAYBE_SWAP (iter->vec[iter->next + 1]);
3804       offset_type cu_index = GDB_INDEX_CU_VALUE (cu_index_and_attrs);
3805       struct dwarf2_per_cu_data *per_cu;
3806       int want_static = iter->block_index != GLOBAL_BLOCK;
3807       /* This value is only valid for index versions >= 7.  */
3808       int is_static = GDB_INDEX_SYMBOL_STATIC_VALUE (cu_index_and_attrs);
3809       gdb_index_symbol_kind symbol_kind =
3810         GDB_INDEX_SYMBOL_KIND_VALUE (cu_index_and_attrs);
3811       /* Only check the symbol attributes if they're present.
3812          Indices prior to version 7 don't record them,
3813          and indices >= 7 may elide them for certain symbols
3814          (gold does this).  */
3815       int attrs_valid =
3816         (iter->index->version >= 7
3817          && symbol_kind != GDB_INDEX_SYMBOL_KIND_NONE);
3818
3819       /* Don't crash on bad data.  */
3820       if (cu_index >= (dwarf2_per_objfile->n_comp_units
3821                        + dwarf2_per_objfile->n_type_units))
3822         {
3823           complaint (&symfile_complaints,
3824                      _(".gdb_index entry has bad CU index"
3825                        " [in module %s]"),
3826                      objfile_name (dwarf2_per_objfile->objfile));
3827           continue;
3828         }
3829
3830       per_cu = dw2_get_cutu (cu_index);
3831
3832       /* Skip if already read in.  */
3833       if (per_cu->v.quick->compunit_symtab)
3834         continue;
3835
3836       /* Check static vs global.  */
3837       if (attrs_valid)
3838         {
3839           if (iter->want_specific_block
3840               && want_static != is_static)
3841             continue;
3842           /* Work around gold/15646.  */
3843           if (!is_static && iter->global_seen)
3844             continue;
3845           if (!is_static)
3846             iter->global_seen = 1;
3847         }
3848
3849       /* Only check the symbol's kind if it has one.  */
3850       if (attrs_valid)
3851         {
3852           switch (iter->domain)
3853             {
3854             case VAR_DOMAIN:
3855               if (symbol_kind != GDB_INDEX_SYMBOL_KIND_VARIABLE
3856                   && symbol_kind != GDB_INDEX_SYMBOL_KIND_FUNCTION
3857                   /* Some types are also in VAR_DOMAIN.  */
3858                   && symbol_kind != GDB_INDEX_SYMBOL_KIND_TYPE)
3859                 continue;
3860               break;
3861             case STRUCT_DOMAIN:
3862               if (symbol_kind != GDB_INDEX_SYMBOL_KIND_TYPE)
3863                 continue;
3864               break;
3865             case LABEL_DOMAIN:
3866               if (symbol_kind != GDB_INDEX_SYMBOL_KIND_OTHER)
3867                 continue;
3868               break;
3869             default:
3870               break;
3871             }
3872         }
3873
3874       ++iter->next;
3875       return per_cu;
3876     }
3877
3878   return NULL;
3879 }
3880
3881 static struct compunit_symtab *
3882 dw2_lookup_symbol (struct objfile *objfile, int block_index,
3883                    const char *name, domain_enum domain)
3884 {
3885   struct compunit_symtab *stab_best = NULL;
3886   struct mapped_index *index;
3887
3888   dw2_setup (objfile);
3889
3890   index = dwarf2_per_objfile->index_table;
3891
3892   /* index is NULL if OBJF_READNOW.  */
3893   if (index)
3894     {
3895       struct dw2_symtab_iterator iter;
3896       struct dwarf2_per_cu_data *per_cu;
3897
3898       dw2_symtab_iter_init (&iter, index, 1, block_index, domain, name);
3899
3900       while ((per_cu = dw2_symtab_iter_next (&iter)) != NULL)
3901         {
3902           struct symbol *sym, *with_opaque = NULL;
3903           struct compunit_symtab *stab = dw2_instantiate_symtab (per_cu);
3904           const struct blockvector *bv = COMPUNIT_BLOCKVECTOR (stab);
3905           struct block *block = BLOCKVECTOR_BLOCK (bv, block_index);
3906
3907           sym = block_find_symbol (block, name, domain,
3908                                    block_find_non_opaque_type_preferred,
3909                                    &with_opaque);
3910
3911           /* Some caution must be observed with overloaded functions
3912              and methods, since the index will not contain any overload
3913              information (but NAME might contain it).  */
3914
3915           if (sym != NULL
3916               && SYMBOL_MATCHES_SEARCH_NAME (sym, name))
3917             return stab;
3918           if (with_opaque != NULL
3919               && SYMBOL_MATCHES_SEARCH_NAME (with_opaque, name))
3920             stab_best = stab;
3921
3922           /* Keep looking through other CUs.  */
3923         }
3924     }
3925
3926   return stab_best;
3927 }
3928
3929 static void
3930 dw2_print_stats (struct objfile *objfile)
3931 {
3932   int i, total, count;
3933
3934   dw2_setup (objfile);
3935   total = dwarf2_per_objfile->n_comp_units + dwarf2_per_objfile->n_type_units;
3936   count = 0;
3937   for (i = 0; i < total; ++i)
3938     {
3939       struct dwarf2_per_cu_data *per_cu = dw2_get_cutu (i);
3940
3941       if (!per_cu->v.quick->compunit_symtab)
3942         ++count;
3943     }
3944   printf_filtered (_("  Number of read CUs: %d\n"), total - count);
3945   printf_filtered (_("  Number of unread CUs: %d\n"), count);
3946 }
3947
3948 /* This dumps minimal information about the index.
3949    It is called via "mt print objfiles".
3950    One use is to verify .gdb_index has been loaded by the
3951    gdb.dwarf2/gdb-index.exp testcase.  */
3952
3953 static void
3954 dw2_dump (struct objfile *objfile)
3955 {
3956   dw2_setup (objfile);
3957   gdb_assert (dwarf2_per_objfile->using_index);
3958   printf_filtered (".gdb_index:");
3959   if (dwarf2_per_objfile->index_table != NULL)
3960     {
3961       printf_filtered (" version %d\n",
3962                        dwarf2_per_objfile->index_table->version);
3963     }
3964   else
3965     printf_filtered (" faked for \"readnow\"\n");
3966   printf_filtered ("\n");
3967 }
3968
3969 static void
3970 dw2_relocate (struct objfile *objfile,
3971               const struct section_offsets *new_offsets,
3972               const struct section_offsets *delta)
3973 {
3974   /* There's nothing to relocate here.  */
3975 }
3976
3977 static void
3978 dw2_expand_symtabs_for_function (struct objfile *objfile,
3979                                  const char *func_name)
3980 {
3981   struct mapped_index *index;
3982
3983   dw2_setup (objfile);
3984
3985   index = dwarf2_per_objfile->index_table;
3986
3987   /* index is NULL if OBJF_READNOW.  */
3988   if (index)
3989     {
3990       struct dw2_symtab_iterator iter;
3991       struct dwarf2_per_cu_data *per_cu;
3992
3993       /* Note: It doesn't matter what we pass for block_index here.  */
3994       dw2_symtab_iter_init (&iter, index, 0, GLOBAL_BLOCK, VAR_DOMAIN,
3995                             func_name);
3996
3997       while ((per_cu = dw2_symtab_iter_next (&iter)) != NULL)
3998         dw2_instantiate_symtab (per_cu);
3999     }
4000 }
4001
4002 static void
4003 dw2_expand_all_symtabs (struct objfile *objfile)
4004 {
4005   int i;
4006
4007   dw2_setup (objfile);
4008
4009   for (i = 0; i < (dwarf2_per_objfile->n_comp_units
4010                    + dwarf2_per_objfile->n_type_units); ++i)
4011     {
4012       struct dwarf2_per_cu_data *per_cu = dw2_get_cutu (i);
4013
4014       dw2_instantiate_symtab (per_cu);
4015     }
4016 }
4017
4018 static void
4019 dw2_expand_symtabs_with_fullname (struct objfile *objfile,
4020                                   const char *fullname)
4021 {
4022   int i;
4023
4024   dw2_setup (objfile);
4025
4026   /* We don't need to consider type units here.
4027      This is only called for examining code, e.g. expand_line_sal.
4028      There can be an order of magnitude (or more) more type units
4029      than comp units, and we avoid them if we can.  */
4030
4031   for (i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
4032     {
4033       int j;
4034       struct dwarf2_per_cu_data *per_cu = dw2_get_cutu (i);
4035       struct quick_file_names *file_data;
4036
4037       /* We only need to look at symtabs not already expanded.  */
4038       if (per_cu->v.quick->compunit_symtab)
4039         continue;
4040
4041       file_data = dw2_get_file_names (per_cu);
4042       if (file_data == NULL)
4043         continue;
4044
4045       for (j = 0; j < file_data->num_file_names; ++j)
4046         {
4047           const char *this_fullname = file_data->file_names[j];
4048
4049           if (filename_cmp (this_fullname, fullname) == 0)
4050             {
4051               dw2_instantiate_symtab (per_cu);
4052               break;
4053             }
4054         }
4055     }
4056 }
4057
4058 static void
4059 dw2_map_matching_symbols (struct objfile *objfile,
4060                           const char * name, domain_enum domain,
4061                           int global,
4062                           int (*callback) (struct block *,
4063                                            struct symbol *, void *),
4064                           void *data, symbol_compare_ftype *match,
4065                           symbol_compare_ftype *ordered_compare)
4066 {
4067   /* Currently unimplemented; used for Ada.  The function can be called if the
4068      current language is Ada for a non-Ada objfile using GNU index.  As Ada
4069      does not look for non-Ada symbols this function should just return.  */
4070 }
4071
4072 static void
4073 dw2_expand_symtabs_matching
4074   (struct objfile *objfile,
4075    gdb::function_view<expand_symtabs_file_matcher_ftype> file_matcher,
4076    gdb::function_view<expand_symtabs_symbol_matcher_ftype> symbol_matcher,
4077    gdb::function_view<expand_symtabs_exp_notify_ftype> expansion_notify,
4078    enum search_domain kind)
4079 {
4080   int i;
4081   offset_type iter;
4082   struct mapped_index *index;
4083
4084   dw2_setup (objfile);
4085
4086   /* index_table is NULL if OBJF_READNOW.  */
4087   if (!dwarf2_per_objfile->index_table)
4088     return;
4089   index = dwarf2_per_objfile->index_table;
4090
4091   if (file_matcher != NULL)
4092     {
4093       htab_up visited_found (htab_create_alloc (10, htab_hash_pointer,
4094                                                 htab_eq_pointer,
4095                                                 NULL, xcalloc, xfree));
4096       htab_up visited_not_found (htab_create_alloc (10, htab_hash_pointer,
4097                                                     htab_eq_pointer,
4098                                                     NULL, xcalloc, xfree));
4099
4100       /* The rule is CUs specify all the files, including those used by
4101          any TU, so there's no need to scan TUs here.  */
4102
4103       for (i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
4104         {
4105           int j;
4106           struct dwarf2_per_cu_data *per_cu = dw2_get_cu (i);
4107           struct quick_file_names *file_data;
4108           void **slot;
4109
4110           QUIT;
4111
4112           per_cu->v.quick->mark = 0;
4113
4114           /* We only need to look at symtabs not already expanded.  */
4115           if (per_cu->v.quick->compunit_symtab)
4116             continue;
4117
4118           file_data = dw2_get_file_names (per_cu);
4119           if (file_data == NULL)
4120             continue;
4121
4122           if (htab_find (visited_not_found.get (), file_data) != NULL)
4123             continue;
4124           else if (htab_find (visited_found.get (), file_data) != NULL)
4125             {
4126               per_cu->v.quick->mark = 1;
4127               continue;
4128             }
4129
4130           for (j = 0; j < file_data->num_file_names; ++j)
4131             {
4132               const char *this_real_name;
4133
4134               if (file_matcher (file_data->file_names[j], false))
4135                 {
4136                   per_cu->v.quick->mark = 1;
4137                   break;
4138                 }
4139
4140               /* Before we invoke realpath, which can get expensive when many
4141                  files are involved, do a quick comparison of the basenames.  */
4142               if (!basenames_may_differ
4143                   && !file_matcher (lbasename (file_data->file_names[j]),
4144                                     true))
4145                 continue;
4146
4147               this_real_name = dw2_get_real_path (objfile, file_data, j);
4148               if (file_matcher (this_real_name, false))
4149                 {
4150                   per_cu->v.quick->mark = 1;
4151                   break;
4152                 }
4153             }
4154
4155           slot = htab_find_slot (per_cu->v.quick->mark
4156                                  ? visited_found.get ()
4157                                  : visited_not_found.get (),
4158                                  file_data, INSERT);
4159           *slot = file_data;
4160         }
4161     }
4162
4163   for (iter = 0; iter < index->symbol_table_slots; ++iter)
4164     {
4165       offset_type idx = 2 * iter;
4166       const char *name;
4167       offset_type *vec, vec_len, vec_idx;
4168       int global_seen = 0;
4169
4170       QUIT;
4171
4172       if (index->symbol_table[idx] == 0 && index->symbol_table[idx + 1] == 0)
4173         continue;
4174
4175       name = index->constant_pool + MAYBE_SWAP (index->symbol_table[idx]);
4176
4177       if (!symbol_matcher (name))
4178         continue;
4179
4180       /* The name was matched, now expand corresponding CUs that were
4181          marked.  */
4182       vec = (offset_type *) (index->constant_pool
4183                              + MAYBE_SWAP (index->symbol_table[idx + 1]));
4184       vec_len = MAYBE_SWAP (vec[0]);
4185       for (vec_idx = 0; vec_idx < vec_len; ++vec_idx)
4186         {
4187           struct dwarf2_per_cu_data *per_cu;
4188           offset_type cu_index_and_attrs = MAYBE_SWAP (vec[vec_idx + 1]);
4189           /* This value is only valid for index versions >= 7.  */
4190           int is_static = GDB_INDEX_SYMBOL_STATIC_VALUE (cu_index_and_attrs);
4191           gdb_index_symbol_kind symbol_kind =
4192             GDB_INDEX_SYMBOL_KIND_VALUE (cu_index_and_attrs);
4193           int cu_index = GDB_INDEX_CU_VALUE (cu_index_and_attrs);
4194           /* Only check the symbol attributes if they're present.
4195              Indices prior to version 7 don't record them,
4196              and indices >= 7 may elide them for certain symbols
4197              (gold does this).  */
4198           int attrs_valid =
4199             (index->version >= 7
4200              && symbol_kind != GDB_INDEX_SYMBOL_KIND_NONE);
4201
4202           /* Work around gold/15646.  */
4203           if (attrs_valid)
4204             {
4205               if (!is_static && global_seen)
4206                 continue;
4207               if (!is_static)
4208                 global_seen = 1;
4209             }
4210
4211           /* Only check the symbol's kind if it has one.  */
4212           if (attrs_valid)
4213             {
4214               switch (kind)
4215                 {
4216                 case VARIABLES_DOMAIN:
4217                   if (symbol_kind != GDB_INDEX_SYMBOL_KIND_VARIABLE)
4218                     continue;
4219                   break;
4220                 case FUNCTIONS_DOMAIN:
4221                   if (symbol_kind != GDB_INDEX_SYMBOL_KIND_FUNCTION)
4222                     continue;
4223                   break;
4224                 case TYPES_DOMAIN:
4225                   if (symbol_kind != GDB_INDEX_SYMBOL_KIND_TYPE)
4226                     continue;
4227                   break;
4228                 default:
4229                   break;
4230                 }
4231             }
4232
4233           /* Don't crash on bad data.  */
4234           if (cu_index >= (dwarf2_per_objfile->n_comp_units
4235                            + dwarf2_per_objfile->n_type_units))
4236             {
4237               complaint (&symfile_complaints,
4238                          _(".gdb_index entry has bad CU index"
4239                            " [in module %s]"), objfile_name (objfile));
4240               continue;
4241             }
4242
4243           per_cu = dw2_get_cutu (cu_index);
4244           if (file_matcher == NULL || per_cu->v.quick->mark)
4245             {
4246               int symtab_was_null =
4247                 (per_cu->v.quick->compunit_symtab == NULL);
4248
4249               dw2_instantiate_symtab (per_cu);
4250
4251               if (expansion_notify != NULL
4252                   && symtab_was_null
4253                   && per_cu->v.quick->compunit_symtab != NULL)
4254                 {
4255                   expansion_notify (per_cu->v.quick->compunit_symtab);
4256                 }
4257             }
4258         }
4259     }
4260 }
4261
4262 /* A helper for dw2_find_pc_sect_compunit_symtab which finds the most specific
4263    symtab.  */
4264
4265 static struct compunit_symtab *
4266 recursively_find_pc_sect_compunit_symtab (struct compunit_symtab *cust,
4267                                           CORE_ADDR pc)
4268 {
4269   int i;
4270
4271   if (COMPUNIT_BLOCKVECTOR (cust) != NULL
4272       && blockvector_contains_pc (COMPUNIT_BLOCKVECTOR (cust), pc))
4273     return cust;
4274
4275   if (cust->includes == NULL)
4276     return NULL;
4277
4278   for (i = 0; cust->includes[i]; ++i)
4279     {
4280       struct compunit_symtab *s = cust->includes[i];
4281
4282       s = recursively_find_pc_sect_compunit_symtab (s, pc);
4283       if (s != NULL)
4284         return s;
4285     }
4286
4287   return NULL;
4288 }
4289
4290 static struct compunit_symtab *
4291 dw2_find_pc_sect_compunit_symtab (struct objfile *objfile,
4292                                   struct bound_minimal_symbol msymbol,
4293                                   CORE_ADDR pc,
4294                                   struct obj_section *section,
4295                                   int warn_if_readin)
4296 {
4297   struct dwarf2_per_cu_data *data;
4298   struct compunit_symtab *result;
4299
4300   dw2_setup (objfile);
4301
4302   if (!objfile->psymtabs_addrmap)
4303     return NULL;
4304
4305   data = (struct dwarf2_per_cu_data *) addrmap_find (objfile->psymtabs_addrmap,
4306                                                      pc);
4307   if (!data)
4308     return NULL;
4309
4310   if (warn_if_readin && data->v.quick->compunit_symtab)
4311     warning (_("(Internal error: pc %s in read in CU, but not in symtab.)"),
4312              paddress (get_objfile_arch (objfile), pc));
4313
4314   result
4315     = recursively_find_pc_sect_compunit_symtab (dw2_instantiate_symtab (data),
4316                                                 pc);
4317   gdb_assert (result != NULL);
4318   return result;
4319 }
4320
4321 static void
4322 dw2_map_symbol_filenames (struct objfile *objfile, symbol_filename_ftype *fun,
4323                           void *data, int need_fullname)
4324 {
4325   dw2_setup (objfile);
4326
4327   if (!dwarf2_per_objfile->filenames_cache)
4328     {
4329       dwarf2_per_objfile->filenames_cache.emplace ();
4330
4331       htab_up visited (htab_create_alloc (10,
4332                                           htab_hash_pointer, htab_eq_pointer,
4333                                           NULL, xcalloc, xfree));
4334
4335       /* The rule is CUs specify all the files, including those used
4336          by any TU, so there's no need to scan TUs here.  We can
4337          ignore file names coming from already-expanded CUs.  */
4338
4339       for (int i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
4340         {
4341           struct dwarf2_per_cu_data *per_cu = dw2_get_cutu (i);
4342
4343           if (per_cu->v.quick->compunit_symtab)
4344             {
4345               void **slot = htab_find_slot (visited.get (),
4346                                             per_cu->v.quick->file_names,
4347                                             INSERT);
4348
4349               *slot = per_cu->v.quick->file_names;
4350             }
4351         }
4352
4353       for (int i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
4354         {
4355           int j;
4356           struct dwarf2_per_cu_data *per_cu = dw2_get_cu (i);
4357           struct quick_file_names *file_data;
4358           void **slot;
4359
4360           /* We only need to look at symtabs not already expanded.  */
4361           if (per_cu->v.quick->compunit_symtab)
4362             continue;
4363
4364           file_data = dw2_get_file_names (per_cu);
4365           if (file_data == NULL)
4366             continue;
4367
4368           slot = htab_find_slot (visited.get (), file_data, INSERT);
4369           if (*slot)
4370             {
4371               /* Already visited.  */
4372               continue;
4373             }
4374           *slot = file_data;
4375
4376           for (int j = 0; j < file_data->num_file_names; ++j)
4377             {
4378               const char *filename = file_data->file_names[j];
4379               dwarf2_per_objfile->filenames_cache->seen (filename);
4380             }
4381         }
4382     }
4383
4384   dwarf2_per_objfile->filenames_cache->traverse ([&] (const char *filename)
4385     {
4386       const char *this_real_name;
4387
4388       if (need_fullname)
4389         this_real_name = gdb_realpath (filename);
4390       else
4391         this_real_name = NULL;
4392       (*fun) (filename, this_real_name, data);
4393     });
4394 }
4395
4396 static int
4397 dw2_has_symbols (struct objfile *objfile)
4398 {
4399   return 1;
4400 }
4401
4402 const struct quick_symbol_functions dwarf2_gdb_index_functions =
4403 {
4404   dw2_has_symbols,
4405   dw2_find_last_source_symtab,
4406   dw2_forget_cached_source_info,
4407   dw2_map_symtabs_matching_filename,
4408   dw2_lookup_symbol,
4409   dw2_print_stats,
4410   dw2_dump,
4411   dw2_relocate,
4412   dw2_expand_symtabs_for_function,
4413   dw2_expand_all_symtabs,
4414   dw2_expand_symtabs_with_fullname,
4415   dw2_map_matching_symbols,
4416   dw2_expand_symtabs_matching,
4417   dw2_find_pc_sect_compunit_symtab,
4418   dw2_map_symbol_filenames
4419 };
4420
4421 /* Initialize for reading DWARF for this objfile.  Return 0 if this
4422    file will use psymtabs, or 1 if using the GNU index.  */
4423
4424 int
4425 dwarf2_initialize_objfile (struct objfile *objfile)
4426 {
4427   /* If we're about to read full symbols, don't bother with the
4428      indices.  In this case we also don't care if some other debug
4429      format is making psymtabs, because they are all about to be
4430      expanded anyway.  */
4431   if ((objfile->flags & OBJF_READNOW))
4432     {
4433       int i;
4434
4435       dwarf2_per_objfile->using_index = 1;
4436       create_all_comp_units (objfile);
4437       create_all_type_units (objfile);
4438       dwarf2_per_objfile->quick_file_names_table =
4439         create_quick_file_names_table (dwarf2_per_objfile->n_comp_units);
4440
4441       for (i = 0; i < (dwarf2_per_objfile->n_comp_units
4442                        + dwarf2_per_objfile->n_type_units); ++i)
4443         {
4444           struct dwarf2_per_cu_data *per_cu = dw2_get_cutu (i);
4445
4446           per_cu->v.quick = OBSTACK_ZALLOC (&objfile->objfile_obstack,
4447                                             struct dwarf2_per_cu_quick_data);
4448         }
4449
4450       /* Return 1 so that gdb sees the "quick" functions.  However,
4451          these functions will be no-ops because we will have expanded
4452          all symtabs.  */
4453       return 1;
4454     }
4455
4456   if (dwarf2_read_index (objfile))
4457     return 1;
4458
4459   return 0;
4460 }
4461
4462 \f
4463
4464 /* Build a partial symbol table.  */
4465
4466 void
4467 dwarf2_build_psymtabs (struct objfile *objfile)
4468 {
4469
4470   if (objfile->global_psymbols.size == 0 && objfile->static_psymbols.size == 0)
4471     {
4472       init_psymbol_list (objfile, 1024);
4473     }
4474
4475   TRY
4476     {
4477       /* This isn't really ideal: all the data we allocate on the
4478          objfile's obstack is still uselessly kept around.  However,
4479          freeing it seems unsafe.  */
4480       psymtab_discarder psymtabs (objfile);
4481       dwarf2_build_psymtabs_hard (objfile);
4482       psymtabs.keep ();
4483     }
4484   CATCH (except, RETURN_MASK_ERROR)
4485     {
4486       exception_print (gdb_stderr, except);
4487     }
4488   END_CATCH
4489 }
4490
4491 /* Return the total length of the CU described by HEADER.  */
4492
4493 static unsigned int
4494 get_cu_length (const struct comp_unit_head *header)
4495 {
4496   return header->initial_length_size + header->length;
4497 }
4498
4499 /* Return TRUE if SECT_OFF is within CU_HEADER.  */
4500
4501 static inline bool
4502 offset_in_cu_p (const comp_unit_head *cu_header, sect_offset sect_off)
4503 {
4504   sect_offset bottom = cu_header->sect_off;
4505   sect_offset top = cu_header->sect_off + get_cu_length (cu_header);
4506
4507   return sect_off >= bottom && sect_off < top;
4508 }
4509
4510 /* Find the base address of the compilation unit for range lists and
4511    location lists.  It will normally be specified by DW_AT_low_pc.
4512    In DWARF-3 draft 4, the base address could be overridden by
4513    DW_AT_entry_pc.  It's been removed, but GCC still uses this for
4514    compilation units with discontinuous ranges.  */
4515
4516 static void
4517 dwarf2_find_base_address (struct die_info *die, struct dwarf2_cu *cu)
4518 {
4519   struct attribute *attr;
4520
4521   cu->base_known = 0;
4522   cu->base_address = 0;
4523
4524   attr = dwarf2_attr (die, DW_AT_entry_pc, cu);
4525   if (attr)
4526     {
4527       cu->base_address = attr_value_as_address (attr);
4528       cu->base_known = 1;
4529     }
4530   else
4531     {
4532       attr = dwarf2_attr (die, DW_AT_low_pc, cu);
4533       if (attr)
4534         {
4535           cu->base_address = attr_value_as_address (attr);
4536           cu->base_known = 1;
4537         }
4538     }
4539 }
4540
4541 /* Read in the comp unit header information from the debug_info at info_ptr.
4542    Use rcuh_kind::COMPILE as the default type if not known by the caller.
4543    NOTE: This leaves members offset, first_die_offset to be filled in
4544    by the caller.  */
4545
4546 static const gdb_byte *
4547 read_comp_unit_head (struct comp_unit_head *cu_header,
4548                      const gdb_byte *info_ptr,
4549                      struct dwarf2_section_info *section,
4550                      rcuh_kind section_kind)
4551 {
4552   int signed_addr;
4553   unsigned int bytes_read;
4554   const char *filename = get_section_file_name (section);
4555   bfd *abfd = get_section_bfd_owner (section);
4556
4557   cu_header->length = read_initial_length (abfd, info_ptr, &bytes_read);
4558   cu_header->initial_length_size = bytes_read;
4559   cu_header->offset_size = (bytes_read == 4) ? 4 : 8;
4560   info_ptr += bytes_read;
4561   cu_header->version = read_2_bytes (abfd, info_ptr);
4562   info_ptr += 2;
4563   if (cu_header->version < 5)
4564     switch (section_kind)
4565       {
4566       case rcuh_kind::COMPILE:
4567         cu_header->unit_type = DW_UT_compile;
4568         break;
4569       case rcuh_kind::TYPE:
4570         cu_header->unit_type = DW_UT_type;
4571         break;
4572       default:
4573         internal_error (__FILE__, __LINE__,
4574                         _("read_comp_unit_head: invalid section_kind"));
4575       }
4576   else
4577     {
4578       cu_header->unit_type = static_cast<enum dwarf_unit_type>
4579                                                  (read_1_byte (abfd, info_ptr));
4580       info_ptr += 1;
4581       switch (cu_header->unit_type)
4582         {
4583         case DW_UT_compile:
4584           if (section_kind != rcuh_kind::COMPILE)
4585             error (_("Dwarf Error: wrong unit_type in compilation unit header "
4586                    "(is DW_UT_compile, should be DW_UT_type) [in module %s]"),
4587                    filename);
4588           break;
4589         case DW_UT_type:
4590           section_kind = rcuh_kind::TYPE;
4591           break;
4592         default:
4593           error (_("Dwarf Error: wrong unit_type in compilation unit header "
4594                  "(is %d, should be %d or %d) [in module %s]"),
4595                  cu_header->unit_type, DW_UT_compile, DW_UT_type, filename);
4596         }
4597
4598       cu_header->addr_size = read_1_byte (abfd, info_ptr);
4599       info_ptr += 1;
4600     }
4601   cu_header->abbrev_sect_off = (sect_offset) read_offset (abfd, info_ptr,
4602                                                           cu_header,
4603                                                           &bytes_read);
4604   info_ptr += bytes_read;
4605   if (cu_header->version < 5)
4606     {
4607       cu_header->addr_size = read_1_byte (abfd, info_ptr);
4608       info_ptr += 1;
4609     }
4610   signed_addr = bfd_get_sign_extend_vma (abfd);
4611   if (signed_addr < 0)
4612     internal_error (__FILE__, __LINE__,
4613                     _("read_comp_unit_head: dwarf from non elf file"));
4614   cu_header->signed_addr_p = signed_addr;
4615
4616   if (section_kind == rcuh_kind::TYPE)
4617     {
4618       LONGEST type_offset;
4619
4620       cu_header->signature = read_8_bytes (abfd, info_ptr);
4621       info_ptr += 8;
4622
4623       type_offset = read_offset (abfd, info_ptr, cu_header, &bytes_read);
4624       info_ptr += bytes_read;
4625       cu_header->type_cu_offset_in_tu = (cu_offset) type_offset;
4626       if (to_underlying (cu_header->type_cu_offset_in_tu) != type_offset)
4627         error (_("Dwarf Error: Too big type_offset in compilation unit "
4628                "header (is %s) [in module %s]"), plongest (type_offset),
4629                filename);
4630     }
4631
4632   return info_ptr;
4633 }
4634
4635 /* Helper function that returns the proper abbrev section for
4636    THIS_CU.  */
4637
4638 static struct dwarf2_section_info *
4639 get_abbrev_section_for_cu (struct dwarf2_per_cu_data *this_cu)
4640 {
4641   struct dwarf2_section_info *abbrev;
4642
4643   if (this_cu->is_dwz)
4644     abbrev = &dwarf2_get_dwz_file ()->abbrev;
4645   else
4646     abbrev = &dwarf2_per_objfile->abbrev;
4647
4648   return abbrev;
4649 }
4650
4651 /* Subroutine of read_and_check_comp_unit_head and
4652    read_and_check_type_unit_head to simplify them.
4653    Perform various error checking on the header.  */
4654
4655 static void
4656 error_check_comp_unit_head (struct comp_unit_head *header,
4657                             struct dwarf2_section_info *section,
4658                             struct dwarf2_section_info *abbrev_section)
4659 {
4660   const char *filename = get_section_file_name (section);
4661
4662   if (header->version < 2 || header->version > 5)
4663     error (_("Dwarf Error: wrong version in compilation unit header "
4664            "(is %d, should be 2, 3, 4 or 5) [in module %s]"), header->version,
4665            filename);
4666
4667   if (to_underlying (header->abbrev_sect_off)
4668       >= dwarf2_section_size (dwarf2_per_objfile->objfile, abbrev_section))
4669     error (_("Dwarf Error: bad offset (0x%x) in compilation unit header "
4670            "(offset 0x%x + 6) [in module %s]"),
4671            to_underlying (header->abbrev_sect_off),
4672            to_underlying (header->sect_off),
4673            filename);
4674
4675   /* Cast to ULONGEST to use 64-bit arithmetic when possible to
4676      avoid potential 32-bit overflow.  */
4677   if (((ULONGEST) header->sect_off + get_cu_length (header))
4678       > section->size)
4679     error (_("Dwarf Error: bad length (0x%x) in compilation unit header "
4680            "(offset 0x%x + 0) [in module %s]"),
4681            header->length, to_underlying (header->sect_off),
4682            filename);
4683 }
4684
4685 /* Read in a CU/TU header and perform some basic error checking.
4686    The contents of the header are stored in HEADER.
4687    The result is a pointer to the start of the first DIE.  */
4688
4689 static const gdb_byte *
4690 read_and_check_comp_unit_head (struct comp_unit_head *header,
4691                                struct dwarf2_section_info *section,
4692                                struct dwarf2_section_info *abbrev_section,
4693                                const gdb_byte *info_ptr,
4694                                rcuh_kind section_kind)
4695 {
4696   const gdb_byte *beg_of_comp_unit = info_ptr;
4697   bfd *abfd = get_section_bfd_owner (section);
4698
4699   header->sect_off = (sect_offset) (beg_of_comp_unit - section->buffer);
4700
4701   info_ptr = read_comp_unit_head (header, info_ptr, section, section_kind);
4702
4703   header->first_die_cu_offset = (cu_offset) (info_ptr - beg_of_comp_unit);
4704
4705   error_check_comp_unit_head (header, section, abbrev_section);
4706
4707   return info_ptr;
4708 }
4709
4710 /* Fetch the abbreviation table offset from a comp or type unit header.  */
4711
4712 static sect_offset
4713 read_abbrev_offset (struct dwarf2_section_info *section,
4714                     sect_offset sect_off)
4715 {
4716   bfd *abfd = get_section_bfd_owner (section);
4717   const gdb_byte *info_ptr;
4718   unsigned int initial_length_size, offset_size;
4719   uint16_t version;
4720
4721   dwarf2_read_section (dwarf2_per_objfile->objfile, section);
4722   info_ptr = section->buffer + to_underlying (sect_off);
4723   read_initial_length (abfd, info_ptr, &initial_length_size);
4724   offset_size = initial_length_size == 4 ? 4 : 8;
4725   info_ptr += initial_length_size;
4726
4727   version = read_2_bytes (abfd, info_ptr);
4728   info_ptr += 2;
4729   if (version >= 5)
4730     {
4731       /* Skip unit type and address size.  */
4732       info_ptr += 2;
4733     }
4734
4735   return (sect_offset) read_offset_1 (abfd, info_ptr, offset_size);
4736 }
4737
4738 /* Allocate a new partial symtab for file named NAME and mark this new
4739    partial symtab as being an include of PST.  */
4740
4741 static void
4742 dwarf2_create_include_psymtab (const char *name, struct partial_symtab *pst,
4743                                struct objfile *objfile)
4744 {
4745   struct partial_symtab *subpst = allocate_psymtab (name, objfile);
4746
4747   if (!IS_ABSOLUTE_PATH (subpst->filename))
4748     {
4749       /* It shares objfile->objfile_obstack.  */
4750       subpst->dirname = pst->dirname;
4751     }
4752
4753   subpst->textlow = 0;
4754   subpst->texthigh = 0;
4755
4756   subpst->dependencies
4757     = XOBNEW (&objfile->objfile_obstack, struct partial_symtab *);
4758   subpst->dependencies[0] = pst;
4759   subpst->number_of_dependencies = 1;
4760
4761   subpst->globals_offset = 0;
4762   subpst->n_global_syms = 0;
4763   subpst->statics_offset = 0;
4764   subpst->n_static_syms = 0;
4765   subpst->compunit_symtab = NULL;
4766   subpst->read_symtab = pst->read_symtab;
4767   subpst->readin = 0;
4768
4769   /* No private part is necessary for include psymtabs.  This property
4770      can be used to differentiate between such include psymtabs and
4771      the regular ones.  */
4772   subpst->read_symtab_private = NULL;
4773 }
4774
4775 /* Read the Line Number Program data and extract the list of files
4776    included by the source file represented by PST.  Build an include
4777    partial symtab for each of these included files.  */
4778
4779 static void
4780 dwarf2_build_include_psymtabs (struct dwarf2_cu *cu,
4781                                struct die_info *die,
4782                                struct partial_symtab *pst)
4783 {
4784   line_header_up lh;
4785   struct attribute *attr;
4786
4787   attr = dwarf2_attr (die, DW_AT_stmt_list, cu);
4788   if (attr)
4789     lh = dwarf_decode_line_header ((sect_offset) DW_UNSND (attr), cu);
4790   if (lh == NULL)
4791     return;  /* No linetable, so no includes.  */
4792
4793   /* NOTE: pst->dirname is DW_AT_comp_dir (if present).  */
4794   dwarf_decode_lines (lh.get (), pst->dirname, cu, pst, pst->textlow, 1);
4795 }
4796
4797 static hashval_t
4798 hash_signatured_type (const void *item)
4799 {
4800   const struct signatured_type *sig_type
4801     = (const struct signatured_type *) item;
4802
4803   /* This drops the top 32 bits of the signature, but is ok for a hash.  */
4804   return sig_type->signature;
4805 }
4806
4807 static int
4808 eq_signatured_type (const void *item_lhs, const void *item_rhs)
4809 {
4810   const struct signatured_type *lhs = (const struct signatured_type *) item_lhs;
4811   const struct signatured_type *rhs = (const struct signatured_type *) item_rhs;
4812
4813   return lhs->signature == rhs->signature;
4814 }
4815
4816 /* Allocate a hash table for signatured types.  */
4817
4818 static htab_t
4819 allocate_signatured_type_table (struct objfile *objfile)
4820 {
4821   return htab_create_alloc_ex (41,
4822                                hash_signatured_type,
4823                                eq_signatured_type,
4824                                NULL,
4825                                &objfile->objfile_obstack,
4826                                hashtab_obstack_allocate,
4827                                dummy_obstack_deallocate);
4828 }
4829
4830 /* A helper function to add a signatured type CU to a table.  */
4831
4832 static int
4833 add_signatured_type_cu_to_table (void **slot, void *datum)
4834 {
4835   struct signatured_type *sigt = (struct signatured_type *) *slot;
4836   struct signatured_type ***datap = (struct signatured_type ***) datum;
4837
4838   **datap = sigt;
4839   ++*datap;
4840
4841   return 1;
4842 }
4843
4844 /* A helper for create_debug_types_hash_table.  Read types from SECTION
4845    and fill them into TYPES_HTAB.  It will process only type units,
4846    therefore DW_UT_type.  */
4847
4848 static void
4849 create_debug_type_hash_table (struct dwo_file *dwo_file,
4850                               dwarf2_section_info *section, htab_t &types_htab,
4851                               rcuh_kind section_kind)
4852 {
4853   struct objfile *objfile = dwarf2_per_objfile->objfile;
4854   struct dwarf2_section_info *abbrev_section;
4855   bfd *abfd;
4856   const gdb_byte *info_ptr, *end_ptr;
4857
4858   abbrev_section = (dwo_file != NULL
4859                     ? &dwo_file->sections.abbrev
4860                     : &dwarf2_per_objfile->abbrev);
4861
4862   if (dwarf_read_debug)
4863     fprintf_unfiltered (gdb_stdlog, "Reading %s for %s:\n",
4864                         get_section_name (section),
4865                         get_section_file_name (abbrev_section));
4866
4867   dwarf2_read_section (objfile, section);
4868   info_ptr = section->buffer;
4869
4870   if (info_ptr == NULL)
4871     return;
4872
4873   /* We can't set abfd until now because the section may be empty or
4874      not present, in which case the bfd is unknown.  */
4875   abfd = get_section_bfd_owner (section);
4876
4877   /* We don't use init_cutu_and_read_dies_simple, or some such, here
4878      because we don't need to read any dies: the signature is in the
4879      header.  */
4880
4881   end_ptr = info_ptr + section->size;
4882   while (info_ptr < end_ptr)
4883     {
4884       struct signatured_type *sig_type;
4885       struct dwo_unit *dwo_tu;
4886       void **slot;
4887       const gdb_byte *ptr = info_ptr;
4888       struct comp_unit_head header;
4889       unsigned int length;
4890
4891       sect_offset sect_off = (sect_offset) (ptr - section->buffer);
4892
4893       /* Initialize it due to a false compiler warning.  */
4894       header.signature = -1;
4895       header.type_cu_offset_in_tu = (cu_offset) -1;
4896
4897       /* We need to read the type's signature in order to build the hash
4898          table, but we don't need anything else just yet.  */
4899
4900       ptr = read_and_check_comp_unit_head (&header, section,
4901                                            abbrev_section, ptr, section_kind);
4902
4903       length = get_cu_length (&header);
4904
4905       /* Skip dummy type units.  */
4906       if (ptr >= info_ptr + length
4907           || peek_abbrev_code (abfd, ptr) == 0
4908           || header.unit_type != DW_UT_type)
4909         {
4910           info_ptr += length;
4911           continue;
4912         }
4913
4914       if (types_htab == NULL)
4915         {
4916           if (dwo_file)
4917             types_htab = allocate_dwo_unit_table (objfile);
4918           else
4919             types_htab = allocate_signatured_type_table (objfile);
4920         }
4921
4922       if (dwo_file)
4923         {
4924           sig_type = NULL;
4925           dwo_tu = OBSTACK_ZALLOC (&objfile->objfile_obstack,
4926                                    struct dwo_unit);
4927           dwo_tu->dwo_file = dwo_file;
4928           dwo_tu->signature = header.signature;
4929           dwo_tu->type_offset_in_tu = header.type_cu_offset_in_tu;
4930           dwo_tu->section = section;
4931           dwo_tu->sect_off = sect_off;
4932           dwo_tu->length = length;
4933         }
4934       else
4935         {
4936           /* N.B.: type_offset is not usable if this type uses a DWO file.
4937              The real type_offset is in the DWO file.  */
4938           dwo_tu = NULL;
4939           sig_type = OBSTACK_ZALLOC (&objfile->objfile_obstack,
4940                                      struct signatured_type);
4941           sig_type->signature = header.signature;
4942           sig_type->type_offset_in_tu = header.type_cu_offset_in_tu;
4943           sig_type->per_cu.objfile = objfile;
4944           sig_type->per_cu.is_debug_types = 1;
4945           sig_type->per_cu.section = section;
4946           sig_type->per_cu.sect_off = sect_off;
4947           sig_type->per_cu.length = length;
4948         }
4949
4950       slot = htab_find_slot (types_htab,
4951                              dwo_file ? (void*) dwo_tu : (void *) sig_type,
4952                              INSERT);
4953       gdb_assert (slot != NULL);
4954       if (*slot != NULL)
4955         {
4956           sect_offset dup_sect_off;
4957
4958           if (dwo_file)
4959             {
4960               const struct dwo_unit *dup_tu
4961                 = (const struct dwo_unit *) *slot;
4962
4963               dup_sect_off = dup_tu->sect_off;
4964             }
4965           else
4966             {
4967               const struct signatured_type *dup_tu
4968                 = (const struct signatured_type *) *slot;
4969
4970               dup_sect_off = dup_tu->per_cu.sect_off;
4971             }
4972
4973           complaint (&symfile_complaints,
4974                      _("debug type entry at offset 0x%x is duplicate to"
4975                        " the entry at offset 0x%x, signature %s"),
4976                      to_underlying (sect_off), to_underlying (dup_sect_off),
4977                      hex_string (header.signature));
4978         }
4979       *slot = dwo_file ? (void *) dwo_tu : (void *) sig_type;
4980
4981       if (dwarf_read_debug > 1)
4982         fprintf_unfiltered (gdb_stdlog, "  offset 0x%x, signature %s\n",
4983                             to_underlying (sect_off),
4984                             hex_string (header.signature));
4985
4986       info_ptr += length;
4987     }
4988 }
4989
4990 /* Create the hash table of all entries in the .debug_types
4991    (or .debug_types.dwo) section(s).
4992    If reading a DWO file, then DWO_FILE is a pointer to the DWO file object,
4993    otherwise it is NULL.
4994
4995    The result is a pointer to the hash table or NULL if there are no types.
4996
4997    Note: This function processes DWO files only, not DWP files.  */
4998
4999 static void
5000 create_debug_types_hash_table (struct dwo_file *dwo_file,
5001                                VEC (dwarf2_section_info_def) *types,
5002                                htab_t &types_htab)
5003 {
5004   int ix;
5005   struct dwarf2_section_info *section;
5006
5007   if (VEC_empty (dwarf2_section_info_def, types))
5008     return;
5009
5010   for (ix = 0;
5011        VEC_iterate (dwarf2_section_info_def, types, ix, section);
5012        ++ix)
5013     create_debug_type_hash_table (dwo_file, section, types_htab,
5014                                   rcuh_kind::TYPE);
5015 }
5016
5017 /* Create the hash table of all entries in the .debug_types section,
5018    and initialize all_type_units.
5019    The result is zero if there is an error (e.g. missing .debug_types section),
5020    otherwise non-zero.  */
5021
5022 static int
5023 create_all_type_units (struct objfile *objfile)
5024 {
5025   htab_t types_htab = NULL;
5026   struct signatured_type **iter;
5027
5028   create_debug_type_hash_table (NULL, &dwarf2_per_objfile->info, types_htab,
5029                                 rcuh_kind::COMPILE);
5030   create_debug_types_hash_table (NULL, dwarf2_per_objfile->types, types_htab);
5031   if (types_htab == NULL)
5032     {
5033       dwarf2_per_objfile->signatured_types = NULL;
5034       return 0;
5035     }
5036
5037   dwarf2_per_objfile->signatured_types = types_htab;
5038
5039   dwarf2_per_objfile->n_type_units
5040     = dwarf2_per_objfile->n_allocated_type_units
5041     = htab_elements (types_htab);
5042   dwarf2_per_objfile->all_type_units =
5043     XNEWVEC (struct signatured_type *, dwarf2_per_objfile->n_type_units);
5044   iter = &dwarf2_per_objfile->all_type_units[0];
5045   htab_traverse_noresize (types_htab, add_signatured_type_cu_to_table, &iter);
5046   gdb_assert (iter - &dwarf2_per_objfile->all_type_units[0]
5047               == dwarf2_per_objfile->n_type_units);
5048
5049   return 1;
5050 }
5051
5052 /* Add an entry for signature SIG to dwarf2_per_objfile->signatured_types.
5053    If SLOT is non-NULL, it is the entry to use in the hash table.
5054    Otherwise we find one.  */
5055
5056 static struct signatured_type *
5057 add_type_unit (ULONGEST sig, void **slot)
5058 {
5059   struct objfile *objfile = dwarf2_per_objfile->objfile;
5060   int n_type_units = dwarf2_per_objfile->n_type_units;
5061   struct signatured_type *sig_type;
5062
5063   gdb_assert (n_type_units <= dwarf2_per_objfile->n_allocated_type_units);
5064   ++n_type_units;
5065   if (n_type_units > dwarf2_per_objfile->n_allocated_type_units)
5066     {
5067       if (dwarf2_per_objfile->n_allocated_type_units == 0)
5068         dwarf2_per_objfile->n_allocated_type_units = 1;
5069       dwarf2_per_objfile->n_allocated_type_units *= 2;
5070       dwarf2_per_objfile->all_type_units
5071         = XRESIZEVEC (struct signatured_type *,
5072                       dwarf2_per_objfile->all_type_units,
5073                       dwarf2_per_objfile->n_allocated_type_units);
5074       ++dwarf2_per_objfile->tu_stats.nr_all_type_units_reallocs;
5075     }
5076   dwarf2_per_objfile->n_type_units = n_type_units;
5077
5078   sig_type = OBSTACK_ZALLOC (&objfile->objfile_obstack,
5079                              struct signatured_type);
5080   dwarf2_per_objfile->all_type_units[n_type_units - 1] = sig_type;
5081   sig_type->signature = sig;
5082   sig_type->per_cu.is_debug_types = 1;
5083   if (dwarf2_per_objfile->using_index)
5084     {
5085       sig_type->per_cu.v.quick =
5086         OBSTACK_ZALLOC (&objfile->objfile_obstack,
5087                         struct dwarf2_per_cu_quick_data);
5088     }
5089
5090   if (slot == NULL)
5091     {
5092       slot = htab_find_slot (dwarf2_per_objfile->signatured_types,
5093                              sig_type, INSERT);
5094     }
5095   gdb_assert (*slot == NULL);
5096   *slot = sig_type;
5097   /* The rest of sig_type must be filled in by the caller.  */
5098   return sig_type;
5099 }
5100
5101 /* Subroutine of lookup_dwo_signatured_type and lookup_dwp_signatured_type.
5102    Fill in SIG_ENTRY with DWO_ENTRY.  */
5103
5104 static void
5105 fill_in_sig_entry_from_dwo_entry (struct objfile *objfile,
5106                                   struct signatured_type *sig_entry,
5107                                   struct dwo_unit *dwo_entry)
5108 {
5109   /* Make sure we're not clobbering something we don't expect to.  */
5110   gdb_assert (! sig_entry->per_cu.queued);
5111   gdb_assert (sig_entry->per_cu.cu == NULL);
5112   if (dwarf2_per_objfile->using_index)
5113     {
5114       gdb_assert (sig_entry->per_cu.v.quick != NULL);
5115       gdb_assert (sig_entry->per_cu.v.quick->compunit_symtab == NULL);
5116     }
5117   else
5118       gdb_assert (sig_entry->per_cu.v.psymtab == NULL);
5119   gdb_assert (sig_entry->signature == dwo_entry->signature);
5120   gdb_assert (to_underlying (sig_entry->type_offset_in_section) == 0);
5121   gdb_assert (sig_entry->type_unit_group == NULL);
5122   gdb_assert (sig_entry->dwo_unit == NULL);
5123
5124   sig_entry->per_cu.section = dwo_entry->section;
5125   sig_entry->per_cu.sect_off = dwo_entry->sect_off;
5126   sig_entry->per_cu.length = dwo_entry->length;
5127   sig_entry->per_cu.reading_dwo_directly = 1;
5128   sig_entry->per_cu.objfile = objfile;
5129   sig_entry->type_offset_in_tu = dwo_entry->type_offset_in_tu;
5130   sig_entry->dwo_unit = dwo_entry;
5131 }
5132
5133 /* Subroutine of lookup_signatured_type.
5134    If we haven't read the TU yet, create the signatured_type data structure
5135    for a TU to be read in directly from a DWO file, bypassing the stub.
5136    This is the "Stay in DWO Optimization": When there is no DWP file and we're
5137    using .gdb_index, then when reading a CU we want to stay in the DWO file
5138    containing that CU.  Otherwise we could end up reading several other DWO
5139    files (due to comdat folding) to process the transitive closure of all the
5140    mentioned TUs, and that can be slow.  The current DWO file will have every
5141    type signature that it needs.
5142    We only do this for .gdb_index because in the psymtab case we already have
5143    to read all the DWOs to build the type unit groups.  */
5144
5145 static struct signatured_type *
5146 lookup_dwo_signatured_type (struct dwarf2_cu *cu, ULONGEST sig)
5147 {
5148   struct objfile *objfile = dwarf2_per_objfile->objfile;
5149   struct dwo_file *dwo_file;
5150   struct dwo_unit find_dwo_entry, *dwo_entry;
5151   struct signatured_type find_sig_entry, *sig_entry;
5152   void **slot;
5153
5154   gdb_assert (cu->dwo_unit && dwarf2_per_objfile->using_index);
5155
5156   /* If TU skeletons have been removed then we may not have read in any
5157      TUs yet.  */
5158   if (dwarf2_per_objfile->signatured_types == NULL)
5159     {
5160       dwarf2_per_objfile->signatured_types
5161         = allocate_signatured_type_table (objfile);
5162     }
5163
5164   /* We only ever need to read in one copy of a signatured type.
5165      Use the global signatured_types array to do our own comdat-folding
5166      of types.  If this is the first time we're reading this TU, and
5167      the TU has an entry in .gdb_index, replace the recorded data from
5168      .gdb_index with this TU.  */
5169
5170   find_sig_entry.signature = sig;
5171   slot = htab_find_slot (dwarf2_per_objfile->signatured_types,
5172                          &find_sig_entry, INSERT);
5173   sig_entry = (struct signatured_type *) *slot;
5174
5175   /* We can get here with the TU already read, *or* in the process of being
5176      read.  Don't reassign the global entry to point to this DWO if that's
5177      the case.  Also note that if the TU is already being read, it may not
5178      have come from a DWO, the program may be a mix of Fission-compiled
5179      code and non-Fission-compiled code.  */
5180
5181   /* Have we already tried to read this TU?
5182      Note: sig_entry can be NULL if the skeleton TU was removed (thus it
5183      needn't exist in the global table yet).  */
5184   if (sig_entry != NULL && sig_entry->per_cu.tu_read)
5185     return sig_entry;
5186
5187   /* Note: cu->dwo_unit is the dwo_unit that references this TU, not the
5188      dwo_unit of the TU itself.  */
5189   dwo_file = cu->dwo_unit->dwo_file;
5190
5191   /* Ok, this is the first time we're reading this TU.  */
5192   if (dwo_file->tus == NULL)
5193     return NULL;
5194   find_dwo_entry.signature = sig;
5195   dwo_entry = (struct dwo_unit *) htab_find (dwo_file->tus, &find_dwo_entry);
5196   if (dwo_entry == NULL)
5197     return NULL;
5198
5199   /* If the global table doesn't have an entry for this TU, add one.  */
5200   if (sig_entry == NULL)
5201     sig_entry = add_type_unit (sig, slot);
5202
5203   fill_in_sig_entry_from_dwo_entry (objfile, sig_entry, dwo_entry);
5204   sig_entry->per_cu.tu_read = 1;
5205   return sig_entry;
5206 }
5207
5208 /* Subroutine of lookup_signatured_type.
5209    Look up the type for signature SIG, and if we can't find SIG in .gdb_index
5210    then try the DWP file.  If the TU stub (skeleton) has been removed then
5211    it won't be in .gdb_index.  */
5212
5213 static struct signatured_type *
5214 lookup_dwp_signatured_type (struct dwarf2_cu *cu, ULONGEST sig)
5215 {
5216   struct objfile *objfile = dwarf2_per_objfile->objfile;
5217   struct dwp_file *dwp_file = get_dwp_file ();
5218   struct dwo_unit *dwo_entry;
5219   struct signatured_type find_sig_entry, *sig_entry;
5220   void **slot;
5221
5222   gdb_assert (cu->dwo_unit && dwarf2_per_objfile->using_index);
5223   gdb_assert (dwp_file != NULL);
5224
5225   /* If TU skeletons have been removed then we may not have read in any
5226      TUs yet.  */
5227   if (dwarf2_per_objfile->signatured_types == NULL)
5228     {
5229       dwarf2_per_objfile->signatured_types
5230         = allocate_signatured_type_table (objfile);
5231     }
5232
5233   find_sig_entry.signature = sig;
5234   slot = htab_find_slot (dwarf2_per_objfile->signatured_types,
5235                          &find_sig_entry, INSERT);
5236   sig_entry = (struct signatured_type *) *slot;
5237
5238   /* Have we already tried to read this TU?
5239      Note: sig_entry can be NULL if the skeleton TU was removed (thus it
5240      needn't exist in the global table yet).  */
5241   if (sig_entry != NULL)
5242     return sig_entry;
5243
5244   if (dwp_file->tus == NULL)
5245     return NULL;
5246   dwo_entry = lookup_dwo_unit_in_dwp (dwp_file, NULL,
5247                                       sig, 1 /* is_debug_types */);
5248   if (dwo_entry == NULL)
5249     return NULL;
5250
5251   sig_entry = add_type_unit (sig, slot);
5252   fill_in_sig_entry_from_dwo_entry (objfile, sig_entry, dwo_entry);
5253
5254   return sig_entry;
5255 }
5256
5257 /* Lookup a signature based type for DW_FORM_ref_sig8.
5258    Returns NULL if signature SIG is not present in the table.
5259    It is up to the caller to complain about this.  */
5260
5261 static struct signatured_type *
5262 lookup_signatured_type (struct dwarf2_cu *cu, ULONGEST sig)
5263 {
5264   if (cu->dwo_unit
5265       && dwarf2_per_objfile->using_index)
5266     {
5267       /* We're in a DWO/DWP file, and we're using .gdb_index.
5268          These cases require special processing.  */
5269       if (get_dwp_file () == NULL)
5270         return lookup_dwo_signatured_type (cu, sig);
5271       else
5272         return lookup_dwp_signatured_type (cu, sig);
5273     }
5274   else
5275     {
5276       struct signatured_type find_entry, *entry;
5277
5278       if (dwarf2_per_objfile->signatured_types == NULL)
5279         return NULL;
5280       find_entry.signature = sig;
5281       entry = ((struct signatured_type *)
5282                htab_find (dwarf2_per_objfile->signatured_types, &find_entry));
5283       return entry;
5284     }
5285 }
5286 \f
5287 /* Low level DIE reading support.  */
5288
5289 /* Initialize a die_reader_specs struct from a dwarf2_cu struct.  */
5290
5291 static void
5292 init_cu_die_reader (struct die_reader_specs *reader,
5293                     struct dwarf2_cu *cu,
5294                     struct dwarf2_section_info *section,
5295                     struct dwo_file *dwo_file)
5296 {
5297   gdb_assert (section->readin && section->buffer != NULL);
5298   reader->abfd = get_section_bfd_owner (section);
5299   reader->cu = cu;
5300   reader->dwo_file = dwo_file;
5301   reader->die_section = section;
5302   reader->buffer = section->buffer;
5303   reader->buffer_end = section->buffer + section->size;
5304   reader->comp_dir = NULL;
5305 }
5306
5307 /* Subroutine of init_cutu_and_read_dies to simplify it.
5308    Read in the rest of a CU/TU top level DIE from DWO_UNIT.
5309    There's just a lot of work to do, and init_cutu_and_read_dies is big enough
5310    already.
5311
5312    STUB_COMP_UNIT_DIE is for the stub DIE, we copy over certain attributes
5313    from it to the DIE in the DWO.  If NULL we are skipping the stub.
5314    STUB_COMP_DIR is similar to STUB_COMP_UNIT_DIE: When reading a TU directly
5315    from the DWO file, bypassing the stub, it contains the DW_AT_comp_dir
5316    attribute of the referencing CU.  At most one of STUB_COMP_UNIT_DIE and
5317    STUB_COMP_DIR may be non-NULL.
5318    *RESULT_READER,*RESULT_INFO_PTR,*RESULT_COMP_UNIT_DIE,*RESULT_HAS_CHILDREN
5319    are filled in with the info of the DIE from the DWO file.
5320    ABBREV_TABLE_PROVIDED is non-zero if the caller of init_cutu_and_read_dies
5321    provided an abbrev table to use.
5322    The result is non-zero if a valid (non-dummy) DIE was found.  */
5323
5324 static int
5325 read_cutu_die_from_dwo (struct dwarf2_per_cu_data *this_cu,
5326                         struct dwo_unit *dwo_unit,
5327                         int abbrev_table_provided,
5328                         struct die_info *stub_comp_unit_die,
5329                         const char *stub_comp_dir,
5330                         struct die_reader_specs *result_reader,
5331                         const gdb_byte **result_info_ptr,
5332                         struct die_info **result_comp_unit_die,
5333                         int *result_has_children)
5334 {
5335   struct objfile *objfile = dwarf2_per_objfile->objfile;
5336   struct dwarf2_cu *cu = this_cu->cu;
5337   struct dwarf2_section_info *section;
5338   bfd *abfd;
5339   const gdb_byte *begin_info_ptr, *info_ptr;
5340   ULONGEST signature; /* Or dwo_id.  */
5341   struct attribute *comp_dir, *stmt_list, *low_pc, *high_pc, *ranges;
5342   int i,num_extra_attrs;
5343   struct dwarf2_section_info *dwo_abbrev_section;
5344   struct attribute *attr;
5345   struct die_info *comp_unit_die;
5346
5347   /* At most one of these may be provided.  */
5348   gdb_assert ((stub_comp_unit_die != NULL) + (stub_comp_dir != NULL) <= 1);
5349
5350   /* These attributes aren't processed until later:
5351      DW_AT_stmt_list, DW_AT_low_pc, DW_AT_high_pc, DW_AT_ranges.
5352      DW_AT_comp_dir is used now, to find the DWO file, but it is also
5353      referenced later.  However, these attributes are found in the stub
5354      which we won't have later.  In order to not impose this complication
5355      on the rest of the code, we read them here and copy them to the
5356      DWO CU/TU die.  */
5357
5358   stmt_list = NULL;
5359   low_pc = NULL;
5360   high_pc = NULL;
5361   ranges = NULL;
5362   comp_dir = NULL;
5363
5364   if (stub_comp_unit_die != NULL)
5365     {
5366       /* For TUs in DWO files, the DW_AT_stmt_list attribute lives in the
5367          DWO file.  */
5368       if (! this_cu->is_debug_types)
5369         stmt_list = dwarf2_attr (stub_comp_unit_die, DW_AT_stmt_list, cu);
5370       low_pc = dwarf2_attr (stub_comp_unit_die, DW_AT_low_pc, cu);
5371       high_pc = dwarf2_attr (stub_comp_unit_die, DW_AT_high_pc, cu);
5372       ranges = dwarf2_attr (stub_comp_unit_die, DW_AT_ranges, cu);
5373       comp_dir = dwarf2_attr (stub_comp_unit_die, DW_AT_comp_dir, cu);
5374
5375       /* There should be a DW_AT_addr_base attribute here (if needed).
5376          We need the value before we can process DW_FORM_GNU_addr_index.  */
5377       cu->addr_base = 0;
5378       attr = dwarf2_attr (stub_comp_unit_die, DW_AT_GNU_addr_base, cu);
5379       if (attr)
5380         cu->addr_base = DW_UNSND (attr);
5381
5382       /* There should be a DW_AT_ranges_base attribute here (if needed).
5383          We need the value before we can process DW_AT_ranges.  */
5384       cu->ranges_base = 0;
5385       attr = dwarf2_attr (stub_comp_unit_die, DW_AT_GNU_ranges_base, cu);
5386       if (attr)
5387         cu->ranges_base = DW_UNSND (attr);
5388     }
5389   else if (stub_comp_dir != NULL)
5390     {
5391       /* Reconstruct the comp_dir attribute to simplify the code below.  */
5392       comp_dir = XOBNEW (&cu->comp_unit_obstack, struct attribute);
5393       comp_dir->name = DW_AT_comp_dir;
5394       comp_dir->form = DW_FORM_string;
5395       DW_STRING_IS_CANONICAL (comp_dir) = 0;
5396       DW_STRING (comp_dir) = stub_comp_dir;
5397     }
5398
5399   /* Set up for reading the DWO CU/TU.  */
5400   cu->dwo_unit = dwo_unit;
5401   section = dwo_unit->section;
5402   dwarf2_read_section (objfile, section);
5403   abfd = get_section_bfd_owner (section);
5404   begin_info_ptr = info_ptr = (section->buffer
5405                                + to_underlying (dwo_unit->sect_off));
5406   dwo_abbrev_section = &dwo_unit->dwo_file->sections.abbrev;
5407   init_cu_die_reader (result_reader, cu, section, dwo_unit->dwo_file);
5408
5409   if (this_cu->is_debug_types)
5410     {
5411       struct signatured_type *sig_type = (struct signatured_type *) this_cu;
5412
5413       info_ptr = read_and_check_comp_unit_head (&cu->header, section,
5414                                                 dwo_abbrev_section,
5415                                                 info_ptr, rcuh_kind::TYPE);
5416       /* This is not an assert because it can be caused by bad debug info.  */
5417       if (sig_type->signature != cu->header.signature)
5418         {
5419           error (_("Dwarf Error: signature mismatch %s vs %s while reading"
5420                    " TU at offset 0x%x [in module %s]"),
5421                  hex_string (sig_type->signature),
5422                  hex_string (cu->header.signature),
5423                  to_underlying (dwo_unit->sect_off),
5424                  bfd_get_filename (abfd));
5425         }
5426       gdb_assert (dwo_unit->sect_off == cu->header.sect_off);
5427       /* For DWOs coming from DWP files, we don't know the CU length
5428          nor the type's offset in the TU until now.  */
5429       dwo_unit->length = get_cu_length (&cu->header);
5430       dwo_unit->type_offset_in_tu = cu->header.type_cu_offset_in_tu;
5431
5432       /* Establish the type offset that can be used to lookup the type.
5433          For DWO files, we don't know it until now.  */
5434       sig_type->type_offset_in_section
5435         = dwo_unit->sect_off + to_underlying (dwo_unit->type_offset_in_tu);
5436     }
5437   else
5438     {
5439       info_ptr = read_and_check_comp_unit_head (&cu->header, section,
5440                                                 dwo_abbrev_section,
5441                                                 info_ptr, rcuh_kind::COMPILE);
5442       gdb_assert (dwo_unit->sect_off == cu->header.sect_off);
5443       /* For DWOs coming from DWP files, we don't know the CU length
5444          until now.  */
5445       dwo_unit->length = get_cu_length (&cu->header);
5446     }
5447
5448   /* Replace the CU's original abbrev table with the DWO's.
5449      Reminder: We can't read the abbrev table until we've read the header.  */
5450   if (abbrev_table_provided)
5451     {
5452       /* Don't free the provided abbrev table, the caller of
5453          init_cutu_and_read_dies owns it.  */
5454       dwarf2_read_abbrevs (cu, dwo_abbrev_section);
5455       /* Ensure the DWO abbrev table gets freed.  */
5456       make_cleanup (dwarf2_free_abbrev_table, cu);
5457     }
5458   else
5459     {
5460       dwarf2_free_abbrev_table (cu);
5461       dwarf2_read_abbrevs (cu, dwo_abbrev_section);
5462       /* Leave any existing abbrev table cleanup as is.  */
5463     }
5464
5465   /* Read in the die, but leave space to copy over the attributes
5466      from the stub.  This has the benefit of simplifying the rest of
5467      the code - all the work to maintain the illusion of a single
5468      DW_TAG_{compile,type}_unit DIE is done here.  */
5469   num_extra_attrs = ((stmt_list != NULL)
5470                      + (low_pc != NULL)
5471                      + (high_pc != NULL)
5472                      + (ranges != NULL)
5473                      + (comp_dir != NULL));
5474   info_ptr = read_full_die_1 (result_reader, result_comp_unit_die, info_ptr,
5475                               result_has_children, num_extra_attrs);
5476
5477   /* Copy over the attributes from the stub to the DIE we just read in.  */
5478   comp_unit_die = *result_comp_unit_die;
5479   i = comp_unit_die->num_attrs;
5480   if (stmt_list != NULL)
5481     comp_unit_die->attrs[i++] = *stmt_list;
5482   if (low_pc != NULL)
5483     comp_unit_die->attrs[i++] = *low_pc;
5484   if (high_pc != NULL)
5485     comp_unit_die->attrs[i++] = *high_pc;
5486   if (ranges != NULL)
5487     comp_unit_die->attrs[i++] = *ranges;
5488   if (comp_dir != NULL)
5489     comp_unit_die->attrs[i++] = *comp_dir;
5490   comp_unit_die->num_attrs += num_extra_attrs;
5491
5492   if (dwarf_die_debug)
5493     {
5494       fprintf_unfiltered (gdb_stdlog,
5495                           "Read die from %s@0x%x of %s:\n",
5496                           get_section_name (section),
5497                           (unsigned) (begin_info_ptr - section->buffer),
5498                           bfd_get_filename (abfd));
5499       dump_die (comp_unit_die, dwarf_die_debug);
5500     }
5501
5502   /* Save the comp_dir attribute.  If there is no DWP file then we'll read
5503      TUs by skipping the stub and going directly to the entry in the DWO file.
5504      However, skipping the stub means we won't get DW_AT_comp_dir, so we have
5505      to get it via circuitous means.  Blech.  */
5506   if (comp_dir != NULL)
5507     result_reader->comp_dir = DW_STRING (comp_dir);
5508
5509   /* Skip dummy compilation units.  */
5510   if (info_ptr >= begin_info_ptr + dwo_unit->length
5511       || peek_abbrev_code (abfd, info_ptr) == 0)
5512     return 0;
5513
5514   *result_info_ptr = info_ptr;
5515   return 1;
5516 }
5517
5518 /* Subroutine of init_cutu_and_read_dies to simplify it.
5519    Look up the DWO unit specified by COMP_UNIT_DIE of THIS_CU.
5520    Returns NULL if the specified DWO unit cannot be found.  */
5521
5522 static struct dwo_unit *
5523 lookup_dwo_unit (struct dwarf2_per_cu_data *this_cu,
5524                  struct die_info *comp_unit_die)
5525 {
5526   struct dwarf2_cu *cu = this_cu->cu;
5527   struct attribute *attr;
5528   ULONGEST signature;
5529   struct dwo_unit *dwo_unit;
5530   const char *comp_dir, *dwo_name;
5531
5532   gdb_assert (cu != NULL);
5533
5534   /* Yeah, we look dwo_name up again, but it simplifies the code.  */
5535   dwo_name = dwarf2_string_attr (comp_unit_die, DW_AT_GNU_dwo_name, cu);
5536   comp_dir = dwarf2_string_attr (comp_unit_die, DW_AT_comp_dir, cu);
5537
5538   if (this_cu->is_debug_types)
5539     {
5540       struct signatured_type *sig_type;
5541
5542       /* Since this_cu is the first member of struct signatured_type,
5543          we can go from a pointer to one to a pointer to the other.  */
5544       sig_type = (struct signatured_type *) this_cu;
5545       signature = sig_type->signature;
5546       dwo_unit = lookup_dwo_type_unit (sig_type, dwo_name, comp_dir);
5547     }
5548   else
5549     {
5550       struct attribute *attr;
5551
5552       attr = dwarf2_attr (comp_unit_die, DW_AT_GNU_dwo_id, cu);
5553       if (! attr)
5554         error (_("Dwarf Error: missing dwo_id for dwo_name %s"
5555                  " [in module %s]"),
5556                dwo_name, objfile_name (this_cu->objfile));
5557       signature = DW_UNSND (attr);
5558       dwo_unit = lookup_dwo_comp_unit (this_cu, dwo_name, comp_dir,
5559                                        signature);
5560     }
5561
5562   return dwo_unit;
5563 }
5564
5565 /* Subroutine of init_cutu_and_read_dies to simplify it.
5566    See it for a description of the parameters.
5567    Read a TU directly from a DWO file, bypassing the stub.
5568
5569    Note: This function could be a little bit simpler if we shared cleanups
5570    with our caller, init_cutu_and_read_dies.  That's generally a fragile thing
5571    to do, so we keep this function self-contained.  Or we could move this
5572    into our caller, but it's complex enough already.  */
5573
5574 static void
5575 init_tu_and_read_dwo_dies (struct dwarf2_per_cu_data *this_cu,
5576                            int use_existing_cu, int keep,
5577                            die_reader_func_ftype *die_reader_func,
5578                            void *data)
5579 {
5580   struct dwarf2_cu *cu;
5581   struct signatured_type *sig_type;
5582   struct cleanup *cleanups, *free_cu_cleanup = NULL;
5583   struct die_reader_specs reader;
5584   const gdb_byte *info_ptr;
5585   struct die_info *comp_unit_die;
5586   int has_children;
5587
5588   /* Verify we can do the following downcast, and that we have the
5589      data we need.  */
5590   gdb_assert (this_cu->is_debug_types && this_cu->reading_dwo_directly);
5591   sig_type = (struct signatured_type *) this_cu;
5592   gdb_assert (sig_type->dwo_unit != NULL);
5593
5594   cleanups = make_cleanup (null_cleanup, NULL);
5595
5596   if (use_existing_cu && this_cu->cu != NULL)
5597     {
5598       gdb_assert (this_cu->cu->dwo_unit == sig_type->dwo_unit);
5599       cu = this_cu->cu;
5600       /* There's no need to do the rereading_dwo_cu handling that
5601          init_cutu_and_read_dies does since we don't read the stub.  */
5602     }
5603   else
5604     {
5605       /* If !use_existing_cu, this_cu->cu must be NULL.  */
5606       gdb_assert (this_cu->cu == NULL);
5607       cu = XNEW (struct dwarf2_cu);
5608       init_one_comp_unit (cu, this_cu);
5609       /* If an error occurs while loading, release our storage.  */
5610       free_cu_cleanup = make_cleanup (free_heap_comp_unit, cu);
5611     }
5612
5613   /* A future optimization, if needed, would be to use an existing
5614      abbrev table.  When reading DWOs with skeletonless TUs, all the TUs
5615      could share abbrev tables.  */
5616
5617   if (read_cutu_die_from_dwo (this_cu, sig_type->dwo_unit,
5618                               0 /* abbrev_table_provided */,
5619                               NULL /* stub_comp_unit_die */,
5620                               sig_type->dwo_unit->dwo_file->comp_dir,
5621                               &reader, &info_ptr,
5622                               &comp_unit_die, &has_children) == 0)
5623     {
5624       /* Dummy die.  */
5625       do_cleanups (cleanups);
5626       return;
5627     }
5628
5629   /* All the "real" work is done here.  */
5630   die_reader_func (&reader, info_ptr, comp_unit_die, has_children, data);
5631
5632   /* This duplicates the code in init_cutu_and_read_dies,
5633      but the alternative is making the latter more complex.
5634      This function is only for the special case of using DWO files directly:
5635      no point in overly complicating the general case just to handle this.  */
5636   if (free_cu_cleanup != NULL)
5637     {
5638       if (keep)
5639         {
5640           /* We've successfully allocated this compilation unit.  Let our
5641              caller clean it up when finished with it.  */
5642           discard_cleanups (free_cu_cleanup);
5643
5644           /* We can only discard free_cu_cleanup and all subsequent cleanups.
5645              So we have to manually free the abbrev table.  */
5646           dwarf2_free_abbrev_table (cu);
5647
5648           /* Link this CU into read_in_chain.  */
5649           this_cu->cu->read_in_chain = dwarf2_per_objfile->read_in_chain;
5650           dwarf2_per_objfile->read_in_chain = this_cu;
5651         }
5652       else
5653         do_cleanups (free_cu_cleanup);
5654     }
5655
5656   do_cleanups (cleanups);
5657 }
5658
5659 /* Initialize a CU (or TU) and read its DIEs.
5660    If the CU defers to a DWO file, read the DWO file as well.
5661
5662    ABBREV_TABLE, if non-NULL, is the abbreviation table to use.
5663    Otherwise the table specified in the comp unit header is read in and used.
5664    This is an optimization for when we already have the abbrev table.
5665
5666    If USE_EXISTING_CU is non-zero, and THIS_CU->cu is non-NULL, then use it.
5667    Otherwise, a new CU is allocated with xmalloc.
5668
5669    If KEEP is non-zero, then if we allocated a dwarf2_cu we add it to
5670    read_in_chain.  Otherwise the dwarf2_cu data is freed at the end.
5671
5672    WARNING: If THIS_CU is a "dummy CU" (used as filler by the incremental
5673    linker) then DIE_READER_FUNC will not get called.  */
5674
5675 static void
5676 init_cutu_and_read_dies (struct dwarf2_per_cu_data *this_cu,
5677                          struct abbrev_table *abbrev_table,
5678                          int use_existing_cu, int keep,
5679                          die_reader_func_ftype *die_reader_func,
5680                          void *data)
5681 {
5682   struct objfile *objfile = dwarf2_per_objfile->objfile;
5683   struct dwarf2_section_info *section = this_cu->section;
5684   bfd *abfd = get_section_bfd_owner (section);
5685   struct dwarf2_cu *cu;
5686   const gdb_byte *begin_info_ptr, *info_ptr;
5687   struct die_reader_specs reader;
5688   struct die_info *comp_unit_die;
5689   int has_children;
5690   struct attribute *attr;
5691   struct cleanup *cleanups, *free_cu_cleanup = NULL;
5692   struct signatured_type *sig_type = NULL;
5693   struct dwarf2_section_info *abbrev_section;
5694   /* Non-zero if CU currently points to a DWO file and we need to
5695      reread it.  When this happens we need to reread the skeleton die
5696      before we can reread the DWO file (this only applies to CUs, not TUs).  */
5697   int rereading_dwo_cu = 0;
5698
5699   if (dwarf_die_debug)
5700     fprintf_unfiltered (gdb_stdlog, "Reading %s unit at offset 0x%x\n",
5701                         this_cu->is_debug_types ? "type" : "comp",
5702                         to_underlying (this_cu->sect_off));
5703
5704   if (use_existing_cu)
5705     gdb_assert (keep);
5706
5707   /* If we're reading a TU directly from a DWO file, including a virtual DWO
5708      file (instead of going through the stub), short-circuit all of this.  */
5709   if (this_cu->reading_dwo_directly)
5710     {
5711       /* Narrow down the scope of possibilities to have to understand.  */
5712       gdb_assert (this_cu->is_debug_types);
5713       gdb_assert (abbrev_table == NULL);
5714       init_tu_and_read_dwo_dies (this_cu, use_existing_cu, keep,
5715                                  die_reader_func, data);
5716       return;
5717     }
5718
5719   cleanups = make_cleanup (null_cleanup, NULL);
5720
5721   /* This is cheap if the section is already read in.  */
5722   dwarf2_read_section (objfile, section);
5723
5724   begin_info_ptr = info_ptr = section->buffer + to_underlying (this_cu->sect_off);
5725
5726   abbrev_section = get_abbrev_section_for_cu (this_cu);
5727
5728   if (use_existing_cu && this_cu->cu != NULL)
5729     {
5730       cu = this_cu->cu;
5731       /* If this CU is from a DWO file we need to start over, we need to
5732          refetch the attributes from the skeleton CU.
5733          This could be optimized by retrieving those attributes from when we
5734          were here the first time: the previous comp_unit_die was stored in
5735          comp_unit_obstack.  But there's no data yet that we need this
5736          optimization.  */
5737       if (cu->dwo_unit != NULL)
5738         rereading_dwo_cu = 1;
5739     }
5740   else
5741     {
5742       /* If !use_existing_cu, this_cu->cu must be NULL.  */
5743       gdb_assert (this_cu->cu == NULL);
5744       cu = XNEW (struct dwarf2_cu);
5745       init_one_comp_unit (cu, this_cu);
5746       /* If an error occurs while loading, release our storage.  */
5747       free_cu_cleanup = make_cleanup (free_heap_comp_unit, cu);
5748     }
5749
5750   /* Get the header.  */
5751   if (to_underlying (cu->header.first_die_cu_offset) != 0 && !rereading_dwo_cu)
5752     {
5753       /* We already have the header, there's no need to read it in again.  */
5754       info_ptr += to_underlying (cu->header.first_die_cu_offset);
5755     }
5756   else
5757     {
5758       if (this_cu->is_debug_types)
5759         {
5760           info_ptr = read_and_check_comp_unit_head (&cu->header, section,
5761                                                     abbrev_section, info_ptr,
5762                                                     rcuh_kind::TYPE);
5763
5764           /* Since per_cu is the first member of struct signatured_type,
5765              we can go from a pointer to one to a pointer to the other.  */
5766           sig_type = (struct signatured_type *) this_cu;
5767           gdb_assert (sig_type->signature == cu->header.signature);
5768           gdb_assert (sig_type->type_offset_in_tu
5769                       == cu->header.type_cu_offset_in_tu);
5770           gdb_assert (this_cu->sect_off == cu->header.sect_off);
5771
5772           /* LENGTH has not been set yet for type units if we're
5773              using .gdb_index.  */
5774           this_cu->length = get_cu_length (&cu->header);
5775
5776           /* Establish the type offset that can be used to lookup the type.  */
5777           sig_type->type_offset_in_section =
5778             this_cu->sect_off + to_underlying (sig_type->type_offset_in_tu);
5779
5780           this_cu->dwarf_version = cu->header.version;
5781         }
5782       else
5783         {
5784           info_ptr = read_and_check_comp_unit_head (&cu->header, section,
5785                                                     abbrev_section,
5786                                                     info_ptr,
5787                                                     rcuh_kind::COMPILE);
5788
5789           gdb_assert (this_cu->sect_off == cu->header.sect_off);
5790           gdb_assert (this_cu->length == get_cu_length (&cu->header));
5791           this_cu->dwarf_version = cu->header.version;
5792         }
5793     }
5794
5795   /* Skip dummy compilation units.  */
5796   if (info_ptr >= begin_info_ptr + this_cu->length
5797       || peek_abbrev_code (abfd, info_ptr) == 0)
5798     {
5799       do_cleanups (cleanups);
5800       return;
5801     }
5802
5803   /* If we don't have them yet, read the abbrevs for this compilation unit.
5804      And if we need to read them now, make sure they're freed when we're
5805      done.  Note that it's important that if the CU had an abbrev table
5806      on entry we don't free it when we're done: Somewhere up the call stack
5807      it may be in use.  */
5808   if (abbrev_table != NULL)
5809     {
5810       gdb_assert (cu->abbrev_table == NULL);
5811       gdb_assert (cu->header.abbrev_sect_off == abbrev_table->sect_off);
5812       cu->abbrev_table = abbrev_table;
5813     }
5814   else if (cu->abbrev_table == NULL)
5815     {
5816       dwarf2_read_abbrevs (cu, abbrev_section);
5817       make_cleanup (dwarf2_free_abbrev_table, cu);
5818     }
5819   else if (rereading_dwo_cu)
5820     {
5821       dwarf2_free_abbrev_table (cu);
5822       dwarf2_read_abbrevs (cu, abbrev_section);
5823     }
5824
5825   /* Read the top level CU/TU die.  */
5826   init_cu_die_reader (&reader, cu, section, NULL);
5827   info_ptr = read_full_die (&reader, &comp_unit_die, info_ptr, &has_children);
5828
5829   /* If we are in a DWO stub, process it and then read in the "real" CU/TU
5830      from the DWO file.
5831      Note that if USE_EXISTING_OK != 0, and THIS_CU->cu already contains a
5832      DWO CU, that this test will fail (the attribute will not be present).  */
5833   attr = dwarf2_attr (comp_unit_die, DW_AT_GNU_dwo_name, cu);
5834   if (attr)
5835     {
5836       struct dwo_unit *dwo_unit;
5837       struct die_info *dwo_comp_unit_die;
5838
5839       if (has_children)
5840         {
5841           complaint (&symfile_complaints,
5842                      _("compilation unit with DW_AT_GNU_dwo_name"
5843                        " has children (offset 0x%x) [in module %s]"),
5844                      to_underlying (this_cu->sect_off), bfd_get_filename (abfd));
5845         }
5846       dwo_unit = lookup_dwo_unit (this_cu, comp_unit_die);
5847       if (dwo_unit != NULL)
5848         {
5849           if (read_cutu_die_from_dwo (this_cu, dwo_unit,
5850                                       abbrev_table != NULL,
5851                                       comp_unit_die, NULL,
5852                                       &reader, &info_ptr,
5853                                       &dwo_comp_unit_die, &has_children) == 0)
5854             {
5855               /* Dummy die.  */
5856               do_cleanups (cleanups);
5857               return;
5858             }
5859           comp_unit_die = dwo_comp_unit_die;
5860         }
5861       else
5862         {
5863           /* Yikes, we couldn't find the rest of the DIE, we only have
5864              the stub.  A complaint has already been logged.  There's
5865              not much more we can do except pass on the stub DIE to
5866              die_reader_func.  We don't want to throw an error on bad
5867              debug info.  */
5868         }
5869     }
5870
5871   /* All of the above is setup for this call.  Yikes.  */
5872   die_reader_func (&reader, info_ptr, comp_unit_die, has_children, data);
5873
5874   /* Done, clean up.  */
5875   if (free_cu_cleanup != NULL)
5876     {
5877       if (keep)
5878         {
5879           /* We've successfully allocated this compilation unit.  Let our
5880              caller clean it up when finished with it.  */
5881           discard_cleanups (free_cu_cleanup);
5882
5883           /* We can only discard free_cu_cleanup and all subsequent cleanups.
5884              So we have to manually free the abbrev table.  */
5885           dwarf2_free_abbrev_table (cu);
5886
5887           /* Link this CU into read_in_chain.  */
5888           this_cu->cu->read_in_chain = dwarf2_per_objfile->read_in_chain;
5889           dwarf2_per_objfile->read_in_chain = this_cu;
5890         }
5891       else
5892         do_cleanups (free_cu_cleanup);
5893     }
5894
5895   do_cleanups (cleanups);
5896 }
5897
5898 /* Read CU/TU THIS_CU but do not follow DW_AT_GNU_dwo_name if present.
5899    DWO_FILE, if non-NULL, is the DWO file to read (the caller is assumed
5900    to have already done the lookup to find the DWO file).
5901
5902    The caller is required to fill in THIS_CU->section, THIS_CU->offset, and
5903    THIS_CU->is_debug_types, but nothing else.
5904
5905    We fill in THIS_CU->length.
5906
5907    WARNING: If THIS_CU is a "dummy CU" (used as filler by the incremental
5908    linker) then DIE_READER_FUNC will not get called.
5909
5910    THIS_CU->cu is always freed when done.
5911    This is done in order to not leave THIS_CU->cu in a state where we have
5912    to care whether it refers to the "main" CU or the DWO CU.  */
5913
5914 static void
5915 init_cutu_and_read_dies_no_follow (struct dwarf2_per_cu_data *this_cu,
5916                                    struct dwo_file *dwo_file,
5917                                    die_reader_func_ftype *die_reader_func,
5918                                    void *data)
5919 {
5920   struct objfile *objfile = dwarf2_per_objfile->objfile;
5921   struct dwarf2_section_info *section = this_cu->section;
5922   bfd *abfd = get_section_bfd_owner (section);
5923   struct dwarf2_section_info *abbrev_section;
5924   struct dwarf2_cu cu;
5925   const gdb_byte *begin_info_ptr, *info_ptr;
5926   struct die_reader_specs reader;
5927   struct cleanup *cleanups;
5928   struct die_info *comp_unit_die;
5929   int has_children;
5930
5931   if (dwarf_die_debug)
5932     fprintf_unfiltered (gdb_stdlog, "Reading %s unit at offset 0x%x\n",
5933                         this_cu->is_debug_types ? "type" : "comp",
5934                         to_underlying (this_cu->sect_off));
5935
5936   gdb_assert (this_cu->cu == NULL);
5937
5938   abbrev_section = (dwo_file != NULL
5939                     ? &dwo_file->sections.abbrev
5940                     : get_abbrev_section_for_cu (this_cu));
5941
5942   /* This is cheap if the section is already read in.  */
5943   dwarf2_read_section (objfile, section);
5944
5945   init_one_comp_unit (&cu, this_cu);
5946
5947   cleanups = make_cleanup (free_stack_comp_unit, &cu);
5948
5949   begin_info_ptr = info_ptr = section->buffer + to_underlying (this_cu->sect_off);
5950   info_ptr = read_and_check_comp_unit_head (&cu.header, section,
5951                                             abbrev_section, info_ptr,
5952                                             (this_cu->is_debug_types
5953                                              ? rcuh_kind::TYPE
5954                                              : rcuh_kind::COMPILE));
5955
5956   this_cu->length = get_cu_length (&cu.header);
5957
5958   /* Skip dummy compilation units.  */
5959   if (info_ptr >= begin_info_ptr + this_cu->length
5960       || peek_abbrev_code (abfd, info_ptr) == 0)
5961     {
5962       do_cleanups (cleanups);
5963       return;
5964     }
5965
5966   dwarf2_read_abbrevs (&cu, abbrev_section);
5967   make_cleanup (dwarf2_free_abbrev_table, &cu);
5968
5969   init_cu_die_reader (&reader, &cu, section, dwo_file);
5970   info_ptr = read_full_die (&reader, &comp_unit_die, info_ptr, &has_children);
5971
5972   die_reader_func (&reader, info_ptr, comp_unit_die, has_children, data);
5973
5974   do_cleanups (cleanups);
5975 }
5976
5977 /* Read a CU/TU, except that this does not look for DW_AT_GNU_dwo_name and
5978    does not lookup the specified DWO file.
5979    This cannot be used to read DWO files.
5980
5981    THIS_CU->cu is always freed when done.
5982    This is done in order to not leave THIS_CU->cu in a state where we have
5983    to care whether it refers to the "main" CU or the DWO CU.
5984    We can revisit this if the data shows there's a performance issue.  */
5985
5986 static void
5987 init_cutu_and_read_dies_simple (struct dwarf2_per_cu_data *this_cu,
5988                                 die_reader_func_ftype *die_reader_func,
5989                                 void *data)
5990 {
5991   init_cutu_and_read_dies_no_follow (this_cu, NULL, die_reader_func, data);
5992 }
5993 \f
5994 /* Type Unit Groups.
5995
5996    Type Unit Groups are a way to collapse the set of all TUs (type units) into
5997    a more manageable set.  The grouping is done by DW_AT_stmt_list entry
5998    so that all types coming from the same compilation (.o file) are grouped
5999    together.  A future step could be to put the types in the same symtab as
6000    the CU the types ultimately came from.  */
6001
6002 static hashval_t
6003 hash_type_unit_group (const void *item)
6004 {
6005   const struct type_unit_group *tu_group
6006     = (const struct type_unit_group *) item;
6007
6008   return hash_stmt_list_entry (&tu_group->hash);
6009 }
6010
6011 static int
6012 eq_type_unit_group (const void *item_lhs, const void *item_rhs)
6013 {
6014   const struct type_unit_group *lhs = (const struct type_unit_group *) item_lhs;
6015   const struct type_unit_group *rhs = (const struct type_unit_group *) item_rhs;
6016
6017   return eq_stmt_list_entry (&lhs->hash, &rhs->hash);
6018 }
6019
6020 /* Allocate a hash table for type unit groups.  */
6021
6022 static htab_t
6023 allocate_type_unit_groups_table (void)
6024 {
6025   return htab_create_alloc_ex (3,
6026                                hash_type_unit_group,
6027                                eq_type_unit_group,
6028                                NULL,
6029                                &dwarf2_per_objfile->objfile->objfile_obstack,
6030                                hashtab_obstack_allocate,
6031                                dummy_obstack_deallocate);
6032 }
6033
6034 /* Type units that don't have DW_AT_stmt_list are grouped into their own
6035    partial symtabs.  We combine several TUs per psymtab to not let the size
6036    of any one psymtab grow too big.  */
6037 #define NO_STMT_LIST_TYPE_UNIT_PSYMTAB (1 << 31)
6038 #define NO_STMT_LIST_TYPE_UNIT_PSYMTAB_SIZE 10
6039
6040 /* Helper routine for get_type_unit_group.
6041    Create the type_unit_group object used to hold one or more TUs.  */
6042
6043 static struct type_unit_group *
6044 create_type_unit_group (struct dwarf2_cu *cu, sect_offset line_offset_struct)
6045 {
6046   struct objfile *objfile = dwarf2_per_objfile->objfile;
6047   struct dwarf2_per_cu_data *per_cu;
6048   struct type_unit_group *tu_group;
6049
6050   tu_group = OBSTACK_ZALLOC (&objfile->objfile_obstack,
6051                              struct type_unit_group);
6052   per_cu = &tu_group->per_cu;
6053   per_cu->objfile = objfile;
6054
6055   if (dwarf2_per_objfile->using_index)
6056     {
6057       per_cu->v.quick = OBSTACK_ZALLOC (&objfile->objfile_obstack,
6058                                         struct dwarf2_per_cu_quick_data);
6059     }
6060   else
6061     {
6062       unsigned int line_offset = to_underlying (line_offset_struct);
6063       struct partial_symtab *pst;
6064       char *name;
6065
6066       /* Give the symtab a useful name for debug purposes.  */
6067       if ((line_offset & NO_STMT_LIST_TYPE_UNIT_PSYMTAB) != 0)
6068         name = xstrprintf ("<type_units_%d>",
6069                            (line_offset & ~NO_STMT_LIST_TYPE_UNIT_PSYMTAB));
6070       else
6071         name = xstrprintf ("<type_units_at_0x%x>", line_offset);
6072
6073       pst = create_partial_symtab (per_cu, name);
6074       pst->anonymous = 1;
6075
6076       xfree (name);
6077     }
6078
6079   tu_group->hash.dwo_unit = cu->dwo_unit;
6080   tu_group->hash.line_sect_off = line_offset_struct;
6081
6082   return tu_group;
6083 }
6084
6085 /* Look up the type_unit_group for type unit CU, and create it if necessary.
6086    STMT_LIST is a DW_AT_stmt_list attribute.  */
6087
6088 static struct type_unit_group *
6089 get_type_unit_group (struct dwarf2_cu *cu, const struct attribute *stmt_list)
6090 {
6091   struct tu_stats *tu_stats = &dwarf2_per_objfile->tu_stats;
6092   struct type_unit_group *tu_group;
6093   void **slot;
6094   unsigned int line_offset;
6095   struct type_unit_group type_unit_group_for_lookup;
6096
6097   if (dwarf2_per_objfile->type_unit_groups == NULL)
6098     {
6099       dwarf2_per_objfile->type_unit_groups =
6100         allocate_type_unit_groups_table ();
6101     }
6102
6103   /* Do we need to create a new group, or can we use an existing one?  */
6104
6105   if (stmt_list)
6106     {
6107       line_offset = DW_UNSND (stmt_list);
6108       ++tu_stats->nr_symtab_sharers;
6109     }
6110   else
6111     {
6112       /* Ugh, no stmt_list.  Rare, but we have to handle it.
6113          We can do various things here like create one group per TU or
6114          spread them over multiple groups to split up the expansion work.
6115          To avoid worst case scenarios (too many groups or too large groups)
6116          we, umm, group them in bunches.  */
6117       line_offset = (NO_STMT_LIST_TYPE_UNIT_PSYMTAB
6118                      | (tu_stats->nr_stmt_less_type_units
6119                         / NO_STMT_LIST_TYPE_UNIT_PSYMTAB_SIZE));
6120       ++tu_stats->nr_stmt_less_type_units;
6121     }
6122
6123   type_unit_group_for_lookup.hash.dwo_unit = cu->dwo_unit;
6124   type_unit_group_for_lookup.hash.line_sect_off = (sect_offset) line_offset;
6125   slot = htab_find_slot (dwarf2_per_objfile->type_unit_groups,
6126                          &type_unit_group_for_lookup, INSERT);
6127   if (*slot != NULL)
6128     {
6129       tu_group = (struct type_unit_group *) *slot;
6130       gdb_assert (tu_group != NULL);
6131     }
6132   else
6133     {
6134       sect_offset line_offset_struct = (sect_offset) line_offset;
6135       tu_group = create_type_unit_group (cu, line_offset_struct);
6136       *slot = tu_group;
6137       ++tu_stats->nr_symtabs;
6138     }
6139
6140   return tu_group;
6141 }
6142 \f
6143 /* Partial symbol tables.  */
6144
6145 /* Create a psymtab named NAME and assign it to PER_CU.
6146
6147    The caller must fill in the following details:
6148    dirname, textlow, texthigh.  */
6149
6150 static struct partial_symtab *
6151 create_partial_symtab (struct dwarf2_per_cu_data *per_cu, const char *name)
6152 {
6153   struct objfile *objfile = per_cu->objfile;
6154   struct partial_symtab *pst;
6155
6156   pst = start_psymtab_common (objfile, name, 0,
6157                               objfile->global_psymbols.next,
6158                               objfile->static_psymbols.next);
6159
6160   pst->psymtabs_addrmap_supported = 1;
6161
6162   /* This is the glue that links PST into GDB's symbol API.  */
6163   pst->read_symtab_private = per_cu;
6164   pst->read_symtab = dwarf2_read_symtab;
6165   per_cu->v.psymtab = pst;
6166
6167   return pst;
6168 }
6169
6170 /* The DATA object passed to process_psymtab_comp_unit_reader has this
6171    type.  */
6172
6173 struct process_psymtab_comp_unit_data
6174 {
6175   /* True if we are reading a DW_TAG_partial_unit.  */
6176
6177   int want_partial_unit;
6178
6179   /* The "pretend" language that is used if the CU doesn't declare a
6180      language.  */
6181
6182   enum language pretend_language;
6183 };
6184
6185 /* die_reader_func for process_psymtab_comp_unit.  */
6186
6187 static void
6188 process_psymtab_comp_unit_reader (const struct die_reader_specs *reader,
6189                                   const gdb_byte *info_ptr,
6190                                   struct die_info *comp_unit_die,
6191                                   int has_children,
6192                                   void *data)
6193 {
6194   struct dwarf2_cu *cu = reader->cu;
6195   struct objfile *objfile = cu->objfile;
6196   struct gdbarch *gdbarch = get_objfile_arch (objfile);
6197   struct dwarf2_per_cu_data *per_cu = cu->per_cu;
6198   CORE_ADDR baseaddr;
6199   CORE_ADDR best_lowpc = 0, best_highpc = 0;
6200   struct partial_symtab *pst;
6201   enum pc_bounds_kind cu_bounds_kind;
6202   const char *filename;
6203   struct process_psymtab_comp_unit_data *info
6204     = (struct process_psymtab_comp_unit_data *) data;
6205
6206   if (comp_unit_die->tag == DW_TAG_partial_unit && !info->want_partial_unit)
6207     return;
6208
6209   gdb_assert (! per_cu->is_debug_types);
6210
6211   prepare_one_comp_unit (cu, comp_unit_die, info->pretend_language);
6212
6213   cu->list_in_scope = &file_symbols;
6214
6215   /* Allocate a new partial symbol table structure.  */
6216   filename = dwarf2_string_attr (comp_unit_die, DW_AT_name, cu);
6217   if (filename == NULL)
6218     filename = "";
6219
6220   pst = create_partial_symtab (per_cu, filename);
6221
6222   /* This must be done before calling dwarf2_build_include_psymtabs.  */
6223   pst->dirname = dwarf2_string_attr (comp_unit_die, DW_AT_comp_dir, cu);
6224
6225   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
6226
6227   dwarf2_find_base_address (comp_unit_die, cu);
6228
6229   /* Possibly set the default values of LOWPC and HIGHPC from
6230      `DW_AT_ranges'.  */
6231   cu_bounds_kind = dwarf2_get_pc_bounds (comp_unit_die, &best_lowpc,
6232                                          &best_highpc, cu, pst);
6233   if (cu_bounds_kind == PC_BOUNDS_HIGH_LOW && best_lowpc < best_highpc)
6234     /* Store the contiguous range if it is not empty; it can be empty for
6235        CUs with no code.  */
6236     addrmap_set_empty (objfile->psymtabs_addrmap,
6237                        gdbarch_adjust_dwarf2_addr (gdbarch,
6238                                                    best_lowpc + baseaddr),
6239                        gdbarch_adjust_dwarf2_addr (gdbarch,
6240                                                    best_highpc + baseaddr) - 1,
6241                        pst);
6242
6243   /* Check if comp unit has_children.
6244      If so, read the rest of the partial symbols from this comp unit.
6245      If not, there's no more debug_info for this comp unit.  */
6246   if (has_children)
6247     {
6248       struct partial_die_info *first_die;
6249       CORE_ADDR lowpc, highpc;
6250
6251       lowpc = ((CORE_ADDR) -1);
6252       highpc = ((CORE_ADDR) 0);
6253
6254       first_die = load_partial_dies (reader, info_ptr, 1);
6255
6256       scan_partial_symbols (first_die, &lowpc, &highpc,
6257                             cu_bounds_kind <= PC_BOUNDS_INVALID, cu);
6258
6259       /* If we didn't find a lowpc, set it to highpc to avoid
6260          complaints from `maint check'.  */
6261       if (lowpc == ((CORE_ADDR) -1))
6262         lowpc = highpc;
6263
6264       /* If the compilation unit didn't have an explicit address range,
6265          then use the information extracted from its child dies.  */
6266       if (cu_bounds_kind <= PC_BOUNDS_INVALID)
6267         {
6268           best_lowpc = lowpc;
6269           best_highpc = highpc;
6270         }
6271     }
6272   pst->textlow = gdbarch_adjust_dwarf2_addr (gdbarch, best_lowpc + baseaddr);
6273   pst->texthigh = gdbarch_adjust_dwarf2_addr (gdbarch, best_highpc + baseaddr);
6274
6275   end_psymtab_common (objfile, pst);
6276
6277   if (!VEC_empty (dwarf2_per_cu_ptr, cu->per_cu->imported_symtabs))
6278     {
6279       int i;
6280       int len = VEC_length (dwarf2_per_cu_ptr, cu->per_cu->imported_symtabs);
6281       struct dwarf2_per_cu_data *iter;
6282
6283       /* Fill in 'dependencies' here; we fill in 'users' in a
6284          post-pass.  */
6285       pst->number_of_dependencies = len;
6286       pst->dependencies =
6287         XOBNEWVEC (&objfile->objfile_obstack, struct partial_symtab *, len);
6288       for (i = 0;
6289            VEC_iterate (dwarf2_per_cu_ptr, cu->per_cu->imported_symtabs,
6290                         i, iter);
6291            ++i)
6292         pst->dependencies[i] = iter->v.psymtab;
6293
6294       VEC_free (dwarf2_per_cu_ptr, cu->per_cu->imported_symtabs);
6295     }
6296
6297   /* Get the list of files included in the current compilation unit,
6298      and build a psymtab for each of them.  */
6299   dwarf2_build_include_psymtabs (cu, comp_unit_die, pst);
6300
6301   if (dwarf_read_debug)
6302     {
6303       struct gdbarch *gdbarch = get_objfile_arch (objfile);
6304
6305       fprintf_unfiltered (gdb_stdlog,
6306                           "Psymtab for %s unit @0x%x: %s - %s"
6307                           ", %d global, %d static syms\n",
6308                           per_cu->is_debug_types ? "type" : "comp",
6309                           to_underlying (per_cu->sect_off),
6310                           paddress (gdbarch, pst->textlow),
6311                           paddress (gdbarch, pst->texthigh),
6312                           pst->n_global_syms, pst->n_static_syms);
6313     }
6314 }
6315
6316 /* Subroutine of dwarf2_build_psymtabs_hard to simplify it.
6317    Process compilation unit THIS_CU for a psymtab.  */
6318
6319 static void
6320 process_psymtab_comp_unit (struct dwarf2_per_cu_data *this_cu,
6321                            int want_partial_unit,
6322                            enum language pretend_language)
6323 {
6324   struct process_psymtab_comp_unit_data info;
6325
6326   /* If this compilation unit was already read in, free the
6327      cached copy in order to read it in again.  This is
6328      necessary because we skipped some symbols when we first
6329      read in the compilation unit (see load_partial_dies).
6330      This problem could be avoided, but the benefit is unclear.  */
6331   if (this_cu->cu != NULL)
6332     free_one_cached_comp_unit (this_cu);
6333
6334   gdb_assert (! this_cu->is_debug_types);
6335   info.want_partial_unit = want_partial_unit;
6336   info.pretend_language = pretend_language;
6337   init_cutu_and_read_dies (this_cu, NULL, 0, 0,
6338                            process_psymtab_comp_unit_reader,
6339                            &info);
6340
6341   /* Age out any secondary CUs.  */
6342   age_cached_comp_units ();
6343 }
6344
6345 /* Reader function for build_type_psymtabs.  */
6346
6347 static void
6348 build_type_psymtabs_reader (const struct die_reader_specs *reader,
6349                             const gdb_byte *info_ptr,
6350                             struct die_info *type_unit_die,
6351                             int has_children,
6352                             void *data)
6353 {
6354   struct objfile *objfile = dwarf2_per_objfile->objfile;
6355   struct dwarf2_cu *cu = reader->cu;
6356   struct dwarf2_per_cu_data *per_cu = cu->per_cu;
6357   struct signatured_type *sig_type;
6358   struct type_unit_group *tu_group;
6359   struct attribute *attr;
6360   struct partial_die_info *first_die;
6361   CORE_ADDR lowpc, highpc;
6362   struct partial_symtab *pst;
6363
6364   gdb_assert (data == NULL);
6365   gdb_assert (per_cu->is_debug_types);
6366   sig_type = (struct signatured_type *) per_cu;
6367
6368   if (! has_children)
6369     return;
6370
6371   attr = dwarf2_attr_no_follow (type_unit_die, DW_AT_stmt_list);
6372   tu_group = get_type_unit_group (cu, attr);
6373
6374   VEC_safe_push (sig_type_ptr, tu_group->tus, sig_type);
6375
6376   prepare_one_comp_unit (cu, type_unit_die, language_minimal);
6377   cu->list_in_scope = &file_symbols;
6378   pst = create_partial_symtab (per_cu, "");
6379   pst->anonymous = 1;
6380
6381   first_die = load_partial_dies (reader, info_ptr, 1);
6382
6383   lowpc = (CORE_ADDR) -1;
6384   highpc = (CORE_ADDR) 0;
6385   scan_partial_symbols (first_die, &lowpc, &highpc, 0, cu);
6386
6387   end_psymtab_common (objfile, pst);
6388 }
6389
6390 /* Struct used to sort TUs by their abbreviation table offset.  */
6391
6392 struct tu_abbrev_offset
6393 {
6394   struct signatured_type *sig_type;
6395   sect_offset abbrev_offset;
6396 };
6397
6398 /* Helper routine for build_type_psymtabs_1, passed to qsort.  */
6399
6400 static int
6401 sort_tu_by_abbrev_offset (const void *ap, const void *bp)
6402 {
6403   const struct tu_abbrev_offset * const *a
6404     = (const struct tu_abbrev_offset * const*) ap;
6405   const struct tu_abbrev_offset * const *b
6406     = (const struct tu_abbrev_offset * const*) bp;
6407   sect_offset aoff = (*a)->abbrev_offset;
6408   sect_offset boff = (*b)->abbrev_offset;
6409
6410   return (aoff > boff) - (aoff < boff);
6411 }
6412
6413 /* Efficiently read all the type units.
6414    This does the bulk of the work for build_type_psymtabs.
6415
6416    The efficiency is because we sort TUs by the abbrev table they use and
6417    only read each abbrev table once.  In one program there are 200K TUs
6418    sharing 8K abbrev tables.
6419
6420    The main purpose of this function is to support building the
6421    dwarf2_per_objfile->type_unit_groups table.
6422    TUs typically share the DW_AT_stmt_list of the CU they came from, so we
6423    can collapse the search space by grouping them by stmt_list.
6424    The savings can be significant, in the same program from above the 200K TUs
6425    share 8K stmt_list tables.
6426
6427    FUNC is expected to call get_type_unit_group, which will create the
6428    struct type_unit_group if necessary and add it to
6429    dwarf2_per_objfile->type_unit_groups.  */
6430
6431 static void
6432 build_type_psymtabs_1 (void)
6433 {
6434   struct tu_stats *tu_stats = &dwarf2_per_objfile->tu_stats;
6435   struct cleanup *cleanups;
6436   struct abbrev_table *abbrev_table;
6437   sect_offset abbrev_offset;
6438   struct tu_abbrev_offset *sorted_by_abbrev;
6439   int i;
6440
6441   /* It's up to the caller to not call us multiple times.  */
6442   gdb_assert (dwarf2_per_objfile->type_unit_groups == NULL);
6443
6444   if (dwarf2_per_objfile->n_type_units == 0)
6445     return;
6446
6447   /* TUs typically share abbrev tables, and there can be way more TUs than
6448      abbrev tables.  Sort by abbrev table to reduce the number of times we
6449      read each abbrev table in.
6450      Alternatives are to punt or to maintain a cache of abbrev tables.
6451      This is simpler and efficient enough for now.
6452
6453      Later we group TUs by their DW_AT_stmt_list value (as this defines the
6454      symtab to use).  Typically TUs with the same abbrev offset have the same
6455      stmt_list value too so in practice this should work well.
6456
6457      The basic algorithm here is:
6458
6459       sort TUs by abbrev table
6460       for each TU with same abbrev table:
6461         read abbrev table if first user
6462         read TU top level DIE
6463           [IWBN if DWO skeletons had DW_AT_stmt_list]
6464         call FUNC  */
6465
6466   if (dwarf_read_debug)
6467     fprintf_unfiltered (gdb_stdlog, "Building type unit groups ...\n");
6468
6469   /* Sort in a separate table to maintain the order of all_type_units
6470      for .gdb_index: TU indices directly index all_type_units.  */
6471   sorted_by_abbrev = XNEWVEC (struct tu_abbrev_offset,
6472                               dwarf2_per_objfile->n_type_units);
6473   for (i = 0; i < dwarf2_per_objfile->n_type_units; ++i)
6474     {
6475       struct signatured_type *sig_type = dwarf2_per_objfile->all_type_units[i];
6476
6477       sorted_by_abbrev[i].sig_type = sig_type;
6478       sorted_by_abbrev[i].abbrev_offset =
6479         read_abbrev_offset (sig_type->per_cu.section,
6480                             sig_type->per_cu.sect_off);
6481     }
6482   cleanups = make_cleanup (xfree, sorted_by_abbrev);
6483   qsort (sorted_by_abbrev, dwarf2_per_objfile->n_type_units,
6484          sizeof (struct tu_abbrev_offset), sort_tu_by_abbrev_offset);
6485
6486   abbrev_offset = (sect_offset) ~(unsigned) 0;
6487   abbrev_table = NULL;
6488   make_cleanup (abbrev_table_free_cleanup, &abbrev_table);
6489
6490   for (i = 0; i < dwarf2_per_objfile->n_type_units; ++i)
6491     {
6492       const struct tu_abbrev_offset *tu = &sorted_by_abbrev[i];
6493
6494       /* Switch to the next abbrev table if necessary.  */
6495       if (abbrev_table == NULL
6496           || tu->abbrev_offset != abbrev_offset)
6497         {
6498           if (abbrev_table != NULL)
6499             {
6500               abbrev_table_free (abbrev_table);
6501               /* Reset to NULL in case abbrev_table_read_table throws
6502                  an error: abbrev_table_free_cleanup will get called.  */
6503               abbrev_table = NULL;
6504             }
6505           abbrev_offset = tu->abbrev_offset;
6506           abbrev_table =
6507             abbrev_table_read_table (&dwarf2_per_objfile->abbrev,
6508                                      abbrev_offset);
6509           ++tu_stats->nr_uniq_abbrev_tables;
6510         }
6511
6512       init_cutu_and_read_dies (&tu->sig_type->per_cu, abbrev_table, 0, 0,
6513                                build_type_psymtabs_reader, NULL);
6514     }
6515
6516   do_cleanups (cleanups);
6517 }
6518
6519 /* Print collected type unit statistics.  */
6520
6521 static void
6522 print_tu_stats (void)
6523 {
6524   struct tu_stats *tu_stats = &dwarf2_per_objfile->tu_stats;
6525
6526   fprintf_unfiltered (gdb_stdlog, "Type unit statistics:\n");
6527   fprintf_unfiltered (gdb_stdlog, "  %d TUs\n",
6528                       dwarf2_per_objfile->n_type_units);
6529   fprintf_unfiltered (gdb_stdlog, "  %d uniq abbrev tables\n",
6530                       tu_stats->nr_uniq_abbrev_tables);
6531   fprintf_unfiltered (gdb_stdlog, "  %d symtabs from stmt_list entries\n",
6532                       tu_stats->nr_symtabs);
6533   fprintf_unfiltered (gdb_stdlog, "  %d symtab sharers\n",
6534                       tu_stats->nr_symtab_sharers);
6535   fprintf_unfiltered (gdb_stdlog, "  %d type units without a stmt_list\n",
6536                       tu_stats->nr_stmt_less_type_units);
6537   fprintf_unfiltered (gdb_stdlog, "  %d all_type_units reallocs\n",
6538                       tu_stats->nr_all_type_units_reallocs);
6539 }
6540
6541 /* Traversal function for build_type_psymtabs.  */
6542
6543 static int
6544 build_type_psymtab_dependencies (void **slot, void *info)
6545 {
6546   struct objfile *objfile = dwarf2_per_objfile->objfile;
6547   struct type_unit_group *tu_group = (struct type_unit_group *) *slot;
6548   struct dwarf2_per_cu_data *per_cu = &tu_group->per_cu;
6549   struct partial_symtab *pst = per_cu->v.psymtab;
6550   int len = VEC_length (sig_type_ptr, tu_group->tus);
6551   struct signatured_type *iter;
6552   int i;
6553
6554   gdb_assert (len > 0);
6555   gdb_assert (IS_TYPE_UNIT_GROUP (per_cu));
6556
6557   pst->number_of_dependencies = len;
6558   pst->dependencies =
6559     XOBNEWVEC (&objfile->objfile_obstack, struct partial_symtab *, len);
6560   for (i = 0;
6561        VEC_iterate (sig_type_ptr, tu_group->tus, i, iter);
6562        ++i)
6563     {
6564       gdb_assert (iter->per_cu.is_debug_types);
6565       pst->dependencies[i] = iter->per_cu.v.psymtab;
6566       iter->type_unit_group = tu_group;
6567     }
6568
6569   VEC_free (sig_type_ptr, tu_group->tus);
6570
6571   return 1;
6572 }
6573
6574 /* Subroutine of dwarf2_build_psymtabs_hard to simplify it.
6575    Build partial symbol tables for the .debug_types comp-units.  */
6576
6577 static void
6578 build_type_psymtabs (struct objfile *objfile)
6579 {
6580   if (! create_all_type_units (objfile))
6581     return;
6582
6583   build_type_psymtabs_1 ();
6584 }
6585
6586 /* Traversal function for process_skeletonless_type_unit.
6587    Read a TU in a DWO file and build partial symbols for it.  */
6588
6589 static int
6590 process_skeletonless_type_unit (void **slot, void *info)
6591 {
6592   struct dwo_unit *dwo_unit = (struct dwo_unit *) *slot;
6593   struct objfile *objfile = (struct objfile *) info;
6594   struct signatured_type find_entry, *entry;
6595
6596   /* If this TU doesn't exist in the global table, add it and read it in.  */
6597
6598   if (dwarf2_per_objfile->signatured_types == NULL)
6599     {
6600       dwarf2_per_objfile->signatured_types
6601         = allocate_signatured_type_table (objfile);
6602     }
6603
6604   find_entry.signature = dwo_unit->signature;
6605   slot = htab_find_slot (dwarf2_per_objfile->signatured_types, &find_entry,
6606                          INSERT);
6607   /* If we've already seen this type there's nothing to do.  What's happening
6608      is we're doing our own version of comdat-folding here.  */
6609   if (*slot != NULL)
6610     return 1;
6611
6612   /* This does the job that create_all_type_units would have done for
6613      this TU.  */
6614   entry = add_type_unit (dwo_unit->signature, slot);
6615   fill_in_sig_entry_from_dwo_entry (objfile, entry, dwo_unit);
6616   *slot = entry;
6617
6618   /* This does the job that build_type_psymtabs_1 would have done.  */
6619   init_cutu_and_read_dies (&entry->per_cu, NULL, 0, 0,
6620                            build_type_psymtabs_reader, NULL);
6621
6622   return 1;
6623 }
6624
6625 /* Traversal function for process_skeletonless_type_units.  */
6626
6627 static int
6628 process_dwo_file_for_skeletonless_type_units (void **slot, void *info)
6629 {
6630   struct dwo_file *dwo_file = (struct dwo_file *) *slot;
6631
6632   if (dwo_file->tus != NULL)
6633     {
6634       htab_traverse_noresize (dwo_file->tus,
6635                               process_skeletonless_type_unit, info);
6636     }
6637
6638   return 1;
6639 }
6640
6641 /* Scan all TUs of DWO files, verifying we've processed them.
6642    This is needed in case a TU was emitted without its skeleton.
6643    Note: This can't be done until we know what all the DWO files are.  */
6644
6645 static void
6646 process_skeletonless_type_units (struct objfile *objfile)
6647 {
6648   /* Skeletonless TUs in DWP files without .gdb_index is not supported yet.  */
6649   if (get_dwp_file () == NULL
6650       && dwarf2_per_objfile->dwo_files != NULL)
6651     {
6652       htab_traverse_noresize (dwarf2_per_objfile->dwo_files,
6653                               process_dwo_file_for_skeletonless_type_units,
6654                               objfile);
6655     }
6656 }
6657
6658 /* A cleanup function that clears objfile's psymtabs_addrmap field.  */
6659
6660 static void
6661 psymtabs_addrmap_cleanup (void *o)
6662 {
6663   struct objfile *objfile = (struct objfile *) o;
6664
6665   objfile->psymtabs_addrmap = NULL;
6666 }
6667
6668 /* Compute the 'user' field for each psymtab in OBJFILE.  */
6669
6670 static void
6671 set_partial_user (struct objfile *objfile)
6672 {
6673   int i;
6674
6675   for (i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
6676     {
6677       struct dwarf2_per_cu_data *per_cu = dw2_get_cutu (i);
6678       struct partial_symtab *pst = per_cu->v.psymtab;
6679       int j;
6680
6681       if (pst == NULL)
6682         continue;
6683
6684       for (j = 0; j < pst->number_of_dependencies; ++j)
6685         {
6686           /* Set the 'user' field only if it is not already set.  */
6687           if (pst->dependencies[j]->user == NULL)
6688             pst->dependencies[j]->user = pst;
6689         }
6690     }
6691 }
6692
6693 /* Build the partial symbol table by doing a quick pass through the
6694    .debug_info and .debug_abbrev sections.  */
6695
6696 static void
6697 dwarf2_build_psymtabs_hard (struct objfile *objfile)
6698 {
6699   struct cleanup *back_to, *addrmap_cleanup;
6700   int i;
6701
6702   if (dwarf_read_debug)
6703     {
6704       fprintf_unfiltered (gdb_stdlog, "Building psymtabs of objfile %s ...\n",
6705                           objfile_name (objfile));
6706     }
6707
6708   dwarf2_per_objfile->reading_partial_symbols = 1;
6709
6710   dwarf2_read_section (objfile, &dwarf2_per_objfile->info);
6711
6712   /* Any cached compilation units will be linked by the per-objfile
6713      read_in_chain.  Make sure to free them when we're done.  */
6714   back_to = make_cleanup (free_cached_comp_units, NULL);
6715
6716   build_type_psymtabs (objfile);
6717
6718   create_all_comp_units (objfile);
6719
6720   /* Create a temporary address map on a temporary obstack.  We later
6721      copy this to the final obstack.  */
6722   auto_obstack temp_obstack;
6723   objfile->psymtabs_addrmap = addrmap_create_mutable (&temp_obstack);
6724   addrmap_cleanup = make_cleanup (psymtabs_addrmap_cleanup, objfile);
6725
6726   for (i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
6727     {
6728       struct dwarf2_per_cu_data *per_cu = dw2_get_cutu (i);
6729
6730       process_psymtab_comp_unit (per_cu, 0, language_minimal);
6731     }
6732
6733   /* This has to wait until we read the CUs, we need the list of DWOs.  */
6734   process_skeletonless_type_units (objfile);
6735
6736   /* Now that all TUs have been processed we can fill in the dependencies.  */
6737   if (dwarf2_per_objfile->type_unit_groups != NULL)
6738     {
6739       htab_traverse_noresize (dwarf2_per_objfile->type_unit_groups,
6740                               build_type_psymtab_dependencies, NULL);
6741     }
6742
6743   if (dwarf_read_debug)
6744     print_tu_stats ();
6745
6746   set_partial_user (objfile);
6747
6748   objfile->psymtabs_addrmap = addrmap_create_fixed (objfile->psymtabs_addrmap,
6749                                                     &objfile->objfile_obstack);
6750   discard_cleanups (addrmap_cleanup);
6751
6752   do_cleanups (back_to);
6753
6754   if (dwarf_read_debug)
6755     fprintf_unfiltered (gdb_stdlog, "Done building psymtabs of %s\n",
6756                         objfile_name (objfile));
6757 }
6758
6759 /* die_reader_func for load_partial_comp_unit.  */
6760
6761 static void
6762 load_partial_comp_unit_reader (const struct die_reader_specs *reader,
6763                                const gdb_byte *info_ptr,
6764                                struct die_info *comp_unit_die,
6765                                int has_children,
6766                                void *data)
6767 {
6768   struct dwarf2_cu *cu = reader->cu;
6769
6770   prepare_one_comp_unit (cu, comp_unit_die, language_minimal);
6771
6772   /* Check if comp unit has_children.
6773      If so, read the rest of the partial symbols from this comp unit.
6774      If not, there's no more debug_info for this comp unit.  */
6775   if (has_children)
6776     load_partial_dies (reader, info_ptr, 0);
6777 }
6778
6779 /* Load the partial DIEs for a secondary CU into memory.
6780    This is also used when rereading a primary CU with load_all_dies.  */
6781
6782 static void
6783 load_partial_comp_unit (struct dwarf2_per_cu_data *this_cu)
6784 {
6785   init_cutu_and_read_dies (this_cu, NULL, 1, 1,
6786                            load_partial_comp_unit_reader, NULL);
6787 }
6788
6789 static void
6790 read_comp_units_from_section (struct objfile *objfile,
6791                               struct dwarf2_section_info *section,
6792                               unsigned int is_dwz,
6793                               int *n_allocated,
6794                               int *n_comp_units,
6795                               struct dwarf2_per_cu_data ***all_comp_units)
6796 {
6797   const gdb_byte *info_ptr;
6798   bfd *abfd = get_section_bfd_owner (section);
6799
6800   if (dwarf_read_debug)
6801     fprintf_unfiltered (gdb_stdlog, "Reading %s for %s\n",
6802                         get_section_name (section),
6803                         get_section_file_name (section));
6804
6805   dwarf2_read_section (objfile, section);
6806
6807   info_ptr = section->buffer;
6808
6809   while (info_ptr < section->buffer + section->size)
6810     {
6811       unsigned int length, initial_length_size;
6812       struct dwarf2_per_cu_data *this_cu;
6813
6814       sect_offset sect_off = (sect_offset) (info_ptr - section->buffer);
6815
6816       /* Read just enough information to find out where the next
6817          compilation unit is.  */
6818       length = read_initial_length (abfd, info_ptr, &initial_length_size);
6819
6820       /* Save the compilation unit for later lookup.  */
6821       this_cu = XOBNEW (&objfile->objfile_obstack, struct dwarf2_per_cu_data);
6822       memset (this_cu, 0, sizeof (*this_cu));
6823       this_cu->sect_off = sect_off;
6824       this_cu->length = length + initial_length_size;
6825       this_cu->is_dwz = is_dwz;
6826       this_cu->objfile = objfile;
6827       this_cu->section = section;
6828
6829       if (*n_comp_units == *n_allocated)
6830         {
6831           *n_allocated *= 2;
6832           *all_comp_units = XRESIZEVEC (struct dwarf2_per_cu_data *,
6833                                         *all_comp_units, *n_allocated);
6834         }
6835       (*all_comp_units)[*n_comp_units] = this_cu;
6836       ++*n_comp_units;
6837
6838       info_ptr = info_ptr + this_cu->length;
6839     }
6840 }
6841
6842 /* Create a list of all compilation units in OBJFILE.
6843    This is only done for -readnow and building partial symtabs.  */
6844
6845 static void
6846 create_all_comp_units (struct objfile *objfile)
6847 {
6848   int n_allocated;
6849   int n_comp_units;
6850   struct dwarf2_per_cu_data **all_comp_units;
6851   struct dwz_file *dwz;
6852
6853   n_comp_units = 0;
6854   n_allocated = 10;
6855   all_comp_units = XNEWVEC (struct dwarf2_per_cu_data *, n_allocated);
6856
6857   read_comp_units_from_section (objfile, &dwarf2_per_objfile->info, 0,
6858                                 &n_allocated, &n_comp_units, &all_comp_units);
6859
6860   dwz = dwarf2_get_dwz_file ();
6861   if (dwz != NULL)
6862     read_comp_units_from_section (objfile, &dwz->info, 1,
6863                                   &n_allocated, &n_comp_units,
6864                                   &all_comp_units);
6865
6866   dwarf2_per_objfile->all_comp_units = XOBNEWVEC (&objfile->objfile_obstack,
6867                                                   struct dwarf2_per_cu_data *,
6868                                                   n_comp_units);
6869   memcpy (dwarf2_per_objfile->all_comp_units, all_comp_units,
6870           n_comp_units * sizeof (struct dwarf2_per_cu_data *));
6871   xfree (all_comp_units);
6872   dwarf2_per_objfile->n_comp_units = n_comp_units;
6873 }
6874
6875 /* Process all loaded DIEs for compilation unit CU, starting at
6876    FIRST_DIE.  The caller should pass SET_ADDRMAP == 1 if the compilation
6877    unit DIE did not have PC info (DW_AT_low_pc and DW_AT_high_pc, or
6878    DW_AT_ranges).  See the comments of add_partial_subprogram on how
6879    SET_ADDRMAP is used and how *LOWPC and *HIGHPC are updated.  */
6880
6881 static void
6882 scan_partial_symbols (struct partial_die_info *first_die, CORE_ADDR *lowpc,
6883                       CORE_ADDR *highpc, int set_addrmap,
6884                       struct dwarf2_cu *cu)
6885 {
6886   struct partial_die_info *pdi;
6887
6888   /* Now, march along the PDI's, descending into ones which have
6889      interesting children but skipping the children of the other ones,
6890      until we reach the end of the compilation unit.  */
6891
6892   pdi = first_die;
6893
6894   while (pdi != NULL)
6895     {
6896       fixup_partial_die (pdi, cu);
6897
6898       /* Anonymous namespaces or modules have no name but have interesting
6899          children, so we need to look at them.  Ditto for anonymous
6900          enums.  */
6901
6902       if (pdi->name != NULL || pdi->tag == DW_TAG_namespace
6903           || pdi->tag == DW_TAG_module || pdi->tag == DW_TAG_enumeration_type
6904           || pdi->tag == DW_TAG_imported_unit)
6905         {
6906           switch (pdi->tag)
6907             {
6908             case DW_TAG_subprogram:
6909               add_partial_subprogram (pdi, lowpc, highpc, set_addrmap, cu);
6910               break;
6911             case DW_TAG_constant:
6912             case DW_TAG_variable:
6913             case DW_TAG_typedef:
6914             case DW_TAG_union_type:
6915               if (!pdi->is_declaration)
6916                 {
6917                   add_partial_symbol (pdi, cu);
6918                 }
6919               break;
6920             case DW_TAG_class_type:
6921             case DW_TAG_interface_type:
6922             case DW_TAG_structure_type:
6923               if (!pdi->is_declaration)
6924                 {
6925                   add_partial_symbol (pdi, cu);
6926                 }
6927               if (cu->language == language_rust && pdi->has_children)
6928                 scan_partial_symbols (pdi->die_child, lowpc, highpc,
6929                                       set_addrmap, cu);
6930               break;
6931             case DW_TAG_enumeration_type:
6932               if (!pdi->is_declaration)
6933                 add_partial_enumeration (pdi, cu);
6934               break;
6935             case DW_TAG_base_type:
6936             case DW_TAG_subrange_type:
6937               /* File scope base type definitions are added to the partial
6938                  symbol table.  */
6939               add_partial_symbol (pdi, cu);
6940               break;
6941             case DW_TAG_namespace:
6942               add_partial_namespace (pdi, lowpc, highpc, set_addrmap, cu);
6943               break;
6944             case DW_TAG_module:
6945               add_partial_module (pdi, lowpc, highpc, set_addrmap, cu);
6946               break;
6947             case DW_TAG_imported_unit:
6948               {
6949                 struct dwarf2_per_cu_data *per_cu;
6950
6951                 /* For now we don't handle imported units in type units.  */
6952                 if (cu->per_cu->is_debug_types)
6953                   {
6954                     error (_("Dwarf Error: DW_TAG_imported_unit is not"
6955                              " supported in type units [in module %s]"),
6956                            objfile_name (cu->objfile));
6957                   }
6958
6959                 per_cu = dwarf2_find_containing_comp_unit (pdi->d.sect_off,
6960                                                            pdi->is_dwz,
6961                                                            cu->objfile);
6962
6963                 /* Go read the partial unit, if needed.  */
6964                 if (per_cu->v.psymtab == NULL)
6965                   process_psymtab_comp_unit (per_cu, 1, cu->language);
6966
6967                 VEC_safe_push (dwarf2_per_cu_ptr,
6968                                cu->per_cu->imported_symtabs, per_cu);
6969               }
6970               break;
6971             case DW_TAG_imported_declaration:
6972               add_partial_symbol (pdi, cu);
6973               break;
6974             default:
6975               break;
6976             }
6977         }
6978
6979       /* If the die has a sibling, skip to the sibling.  */
6980
6981       pdi = pdi->die_sibling;
6982     }
6983 }
6984
6985 /* Functions used to compute the fully scoped name of a partial DIE.
6986
6987    Normally, this is simple.  For C++, the parent DIE's fully scoped
6988    name is concatenated with "::" and the partial DIE's name.
6989    Enumerators are an exception; they use the scope of their parent
6990    enumeration type, i.e. the name of the enumeration type is not
6991    prepended to the enumerator.
6992
6993    There are two complexities.  One is DW_AT_specification; in this
6994    case "parent" means the parent of the target of the specification,
6995    instead of the direct parent of the DIE.  The other is compilers
6996    which do not emit DW_TAG_namespace; in this case we try to guess
6997    the fully qualified name of structure types from their members'
6998    linkage names.  This must be done using the DIE's children rather
6999    than the children of any DW_AT_specification target.  We only need
7000    to do this for structures at the top level, i.e. if the target of
7001    any DW_AT_specification (if any; otherwise the DIE itself) does not
7002    have a parent.  */
7003
7004 /* Compute the scope prefix associated with PDI's parent, in
7005    compilation unit CU.  The result will be allocated on CU's
7006    comp_unit_obstack, or a copy of the already allocated PDI->NAME
7007    field.  NULL is returned if no prefix is necessary.  */
7008 static const char *
7009 partial_die_parent_scope (struct partial_die_info *pdi,
7010                           struct dwarf2_cu *cu)
7011 {
7012   const char *grandparent_scope;
7013   struct partial_die_info *parent, *real_pdi;
7014
7015   /* We need to look at our parent DIE; if we have a DW_AT_specification,
7016      then this means the parent of the specification DIE.  */
7017
7018   real_pdi = pdi;
7019   while (real_pdi->has_specification)
7020     real_pdi = find_partial_die (real_pdi->spec_offset,
7021                                  real_pdi->spec_is_dwz, cu);
7022
7023   parent = real_pdi->die_parent;
7024   if (parent == NULL)
7025     return NULL;
7026
7027   if (parent->scope_set)
7028     return parent->scope;
7029
7030   fixup_partial_die (parent, cu);
7031
7032   grandparent_scope = partial_die_parent_scope (parent, cu);
7033
7034   /* GCC 4.0 and 4.1 had a bug (PR c++/28460) where they generated bogus
7035      DW_TAG_namespace DIEs with a name of "::" for the global namespace.
7036      Work around this problem here.  */
7037   if (cu->language == language_cplus
7038       && parent->tag == DW_TAG_namespace
7039       && strcmp (parent->name, "::") == 0
7040       && grandparent_scope == NULL)
7041     {
7042       parent->scope = NULL;
7043       parent->scope_set = 1;
7044       return NULL;
7045     }
7046
7047   if (pdi->tag == DW_TAG_enumerator)
7048     /* Enumerators should not get the name of the enumeration as a prefix.  */
7049     parent->scope = grandparent_scope;
7050   else if (parent->tag == DW_TAG_namespace
7051       || parent->tag == DW_TAG_module
7052       || parent->tag == DW_TAG_structure_type
7053       || parent->tag == DW_TAG_class_type
7054       || parent->tag == DW_TAG_interface_type
7055       || parent->tag == DW_TAG_union_type
7056       || parent->tag == DW_TAG_enumeration_type)
7057     {
7058       if (grandparent_scope == NULL)
7059         parent->scope = parent->name;
7060       else
7061         parent->scope = typename_concat (&cu->comp_unit_obstack,
7062                                          grandparent_scope,
7063                                          parent->name, 0, cu);
7064     }
7065   else
7066     {
7067       /* FIXME drow/2004-04-01: What should we be doing with
7068          function-local names?  For partial symbols, we should probably be
7069          ignoring them.  */
7070       complaint (&symfile_complaints,
7071                  _("unhandled containing DIE tag %d for DIE at %d"),
7072                  parent->tag, to_underlying (pdi->sect_off));
7073       parent->scope = grandparent_scope;
7074     }
7075
7076   parent->scope_set = 1;
7077   return parent->scope;
7078 }
7079
7080 /* Return the fully scoped name associated with PDI, from compilation unit
7081    CU.  The result will be allocated with malloc.  */
7082
7083 static char *
7084 partial_die_full_name (struct partial_die_info *pdi,
7085                        struct dwarf2_cu *cu)
7086 {
7087   const char *parent_scope;
7088
7089   /* If this is a template instantiation, we can not work out the
7090      template arguments from partial DIEs.  So, unfortunately, we have
7091      to go through the full DIEs.  At least any work we do building
7092      types here will be reused if full symbols are loaded later.  */
7093   if (pdi->has_template_arguments)
7094     {
7095       fixup_partial_die (pdi, cu);
7096
7097       if (pdi->name != NULL && strchr (pdi->name, '<') == NULL)
7098         {
7099           struct die_info *die;
7100           struct attribute attr;
7101           struct dwarf2_cu *ref_cu = cu;
7102
7103           /* DW_FORM_ref_addr is using section offset.  */
7104           attr.name = (enum dwarf_attribute) 0;
7105           attr.form = DW_FORM_ref_addr;
7106           attr.u.unsnd = to_underlying (pdi->sect_off);
7107           die = follow_die_ref (NULL, &attr, &ref_cu);
7108
7109           return xstrdup (dwarf2_full_name (NULL, die, ref_cu));
7110         }
7111     }
7112
7113   parent_scope = partial_die_parent_scope (pdi, cu);
7114   if (parent_scope == NULL)
7115     return NULL;
7116   else
7117     return typename_concat (NULL, parent_scope, pdi->name, 0, cu);
7118 }
7119
7120 static void
7121 add_partial_symbol (struct partial_die_info *pdi, struct dwarf2_cu *cu)
7122 {
7123   struct objfile *objfile = cu->objfile;
7124   struct gdbarch *gdbarch = get_objfile_arch (objfile);
7125   CORE_ADDR addr = 0;
7126   const char *actual_name = NULL;
7127   CORE_ADDR baseaddr;
7128   char *built_actual_name;
7129
7130   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
7131
7132   built_actual_name = partial_die_full_name (pdi, cu);
7133   if (built_actual_name != NULL)
7134     actual_name = built_actual_name;
7135
7136   if (actual_name == NULL)
7137     actual_name = pdi->name;
7138
7139   switch (pdi->tag)
7140     {
7141     case DW_TAG_subprogram:
7142       addr = gdbarch_adjust_dwarf2_addr (gdbarch, pdi->lowpc + baseaddr);
7143       if (pdi->is_external || cu->language == language_ada)
7144         {
7145           /* brobecker/2007-12-26: Normally, only "external" DIEs are part
7146              of the global scope.  But in Ada, we want to be able to access
7147              nested procedures globally.  So all Ada subprograms are stored
7148              in the global scope.  */
7149           add_psymbol_to_list (actual_name, strlen (actual_name),
7150                                built_actual_name != NULL,
7151                                VAR_DOMAIN, LOC_BLOCK,
7152                                &objfile->global_psymbols,
7153                                addr, cu->language, objfile);
7154         }
7155       else
7156         {
7157           add_psymbol_to_list (actual_name, strlen (actual_name),
7158                                built_actual_name != NULL,
7159                                VAR_DOMAIN, LOC_BLOCK,
7160                                &objfile->static_psymbols,
7161                                addr, cu->language, objfile);
7162         }
7163
7164       if (pdi->main_subprogram && actual_name != NULL)
7165         set_objfile_main_name (objfile, actual_name, cu->language);
7166       break;
7167     case DW_TAG_constant:
7168       {
7169         struct psymbol_allocation_list *list;
7170
7171         if (pdi->is_external)
7172           list = &objfile->global_psymbols;
7173         else
7174           list = &objfile->static_psymbols;
7175         add_psymbol_to_list (actual_name, strlen (actual_name),
7176                              built_actual_name != NULL, VAR_DOMAIN, LOC_STATIC,
7177                              list, 0, cu->language, objfile);
7178       }
7179       break;
7180     case DW_TAG_variable:
7181       if (pdi->d.locdesc)
7182         addr = decode_locdesc (pdi->d.locdesc, cu);
7183
7184       if (pdi->d.locdesc
7185           && addr == 0
7186           && !dwarf2_per_objfile->has_section_at_zero)
7187         {
7188           /* A global or static variable may also have been stripped
7189              out by the linker if unused, in which case its address
7190              will be nullified; do not add such variables into partial
7191              symbol table then.  */
7192         }
7193       else if (pdi->is_external)
7194         {
7195           /* Global Variable.
7196              Don't enter into the minimal symbol tables as there is
7197              a minimal symbol table entry from the ELF symbols already.
7198              Enter into partial symbol table if it has a location
7199              descriptor or a type.
7200              If the location descriptor is missing, new_symbol will create
7201              a LOC_UNRESOLVED symbol, the address of the variable will then
7202              be determined from the minimal symbol table whenever the variable
7203              is referenced.
7204              The address for the partial symbol table entry is not
7205              used by GDB, but it comes in handy for debugging partial symbol
7206              table building.  */
7207
7208           if (pdi->d.locdesc || pdi->has_type)
7209             add_psymbol_to_list (actual_name, strlen (actual_name),
7210                                  built_actual_name != NULL,
7211                                  VAR_DOMAIN, LOC_STATIC,
7212                                  &objfile->global_psymbols,
7213                                  addr + baseaddr,
7214                                  cu->language, objfile);
7215         }
7216       else
7217         {
7218           int has_loc = pdi->d.locdesc != NULL;
7219
7220           /* Static Variable.  Skip symbols whose value we cannot know (those
7221              without location descriptors or constant values).  */
7222           if (!has_loc && !pdi->has_const_value)
7223             {
7224               xfree (built_actual_name);
7225               return;
7226             }
7227
7228           add_psymbol_to_list (actual_name, strlen (actual_name),
7229                                built_actual_name != NULL,
7230                                VAR_DOMAIN, LOC_STATIC,
7231                                &objfile->static_psymbols,
7232                                has_loc ? addr + baseaddr : (CORE_ADDR) 0,
7233                                cu->language, objfile);
7234         }
7235       break;
7236     case DW_TAG_typedef:
7237     case DW_TAG_base_type:
7238     case DW_TAG_subrange_type:
7239       add_psymbol_to_list (actual_name, strlen (actual_name),
7240                            built_actual_name != NULL,
7241                            VAR_DOMAIN, LOC_TYPEDEF,
7242                            &objfile->static_psymbols,
7243                            0, cu->language, objfile);
7244       break;
7245     case DW_TAG_imported_declaration:
7246     case DW_TAG_namespace:
7247       add_psymbol_to_list (actual_name, strlen (actual_name),
7248                            built_actual_name != NULL,
7249                            VAR_DOMAIN, LOC_TYPEDEF,
7250                            &objfile->global_psymbols,
7251                            0, cu->language, objfile);
7252       break;
7253     case DW_TAG_module:
7254       add_psymbol_to_list (actual_name, strlen (actual_name),
7255                            built_actual_name != NULL,
7256                            MODULE_DOMAIN, LOC_TYPEDEF,
7257                            &objfile->global_psymbols,
7258                            0, cu->language, objfile);
7259       break;
7260     case DW_TAG_class_type:
7261     case DW_TAG_interface_type:
7262     case DW_TAG_structure_type:
7263     case DW_TAG_union_type:
7264     case DW_TAG_enumeration_type:
7265       /* Skip external references.  The DWARF standard says in the section
7266          about "Structure, Union, and Class Type Entries": "An incomplete
7267          structure, union or class type is represented by a structure,
7268          union or class entry that does not have a byte size attribute
7269          and that has a DW_AT_declaration attribute."  */
7270       if (!pdi->has_byte_size && pdi->is_declaration)
7271         {
7272           xfree (built_actual_name);
7273           return;
7274         }
7275
7276       /* NOTE: carlton/2003-10-07: See comment in new_symbol about
7277          static vs. global.  */
7278       add_psymbol_to_list (actual_name, strlen (actual_name),
7279                            built_actual_name != NULL,
7280                            STRUCT_DOMAIN, LOC_TYPEDEF,
7281                            cu->language == language_cplus
7282                            ? &objfile->global_psymbols
7283                            : &objfile->static_psymbols,
7284                            0, cu->language, objfile);
7285
7286       break;
7287     case DW_TAG_enumerator:
7288       add_psymbol_to_list (actual_name, strlen (actual_name),
7289                            built_actual_name != NULL,
7290                            VAR_DOMAIN, LOC_CONST,
7291                            cu->language == language_cplus
7292                            ? &objfile->global_psymbols
7293                            : &objfile->static_psymbols,
7294                            0, cu->language, objfile);
7295       break;
7296     default:
7297       break;
7298     }
7299
7300   xfree (built_actual_name);
7301 }
7302
7303 /* Read a partial die corresponding to a namespace; also, add a symbol
7304    corresponding to that namespace to the symbol table.  NAMESPACE is
7305    the name of the enclosing namespace.  */
7306
7307 static void
7308 add_partial_namespace (struct partial_die_info *pdi,
7309                        CORE_ADDR *lowpc, CORE_ADDR *highpc,
7310                        int set_addrmap, struct dwarf2_cu *cu)
7311 {
7312   /* Add a symbol for the namespace.  */
7313
7314   add_partial_symbol (pdi, cu);
7315
7316   /* Now scan partial symbols in that namespace.  */
7317
7318   if (pdi->has_children)
7319     scan_partial_symbols (pdi->die_child, lowpc, highpc, set_addrmap, cu);
7320 }
7321
7322 /* Read a partial die corresponding to a Fortran module.  */
7323
7324 static void
7325 add_partial_module (struct partial_die_info *pdi, CORE_ADDR *lowpc,
7326                     CORE_ADDR *highpc, int set_addrmap, struct dwarf2_cu *cu)
7327 {
7328   /* Add a symbol for the namespace.  */
7329
7330   add_partial_symbol (pdi, cu);
7331
7332   /* Now scan partial symbols in that module.  */
7333
7334   if (pdi->has_children)
7335     scan_partial_symbols (pdi->die_child, lowpc, highpc, set_addrmap, cu);
7336 }
7337
7338 /* Read a partial die corresponding to a subprogram and create a partial
7339    symbol for that subprogram.  When the CU language allows it, this
7340    routine also defines a partial symbol for each nested subprogram
7341    that this subprogram contains.  If SET_ADDRMAP is true, record the
7342    covered ranges in the addrmap.  Set *LOWPC and *HIGHPC to the lowest
7343    and highest PC values found in PDI.
7344
7345    PDI may also be a lexical block, in which case we simply search
7346    recursively for subprograms defined inside that lexical block.
7347    Again, this is only performed when the CU language allows this
7348    type of definitions.  */
7349
7350 static void
7351 add_partial_subprogram (struct partial_die_info *pdi,
7352                         CORE_ADDR *lowpc, CORE_ADDR *highpc,
7353                         int set_addrmap, struct dwarf2_cu *cu)
7354 {
7355   if (pdi->tag == DW_TAG_subprogram)
7356     {
7357       if (pdi->has_pc_info)
7358         {
7359           if (pdi->lowpc < *lowpc)
7360             *lowpc = pdi->lowpc;
7361           if (pdi->highpc > *highpc)
7362             *highpc = pdi->highpc;
7363           if (set_addrmap)
7364             {
7365               struct objfile *objfile = cu->objfile;
7366               struct gdbarch *gdbarch = get_objfile_arch (objfile);
7367               CORE_ADDR baseaddr;
7368               CORE_ADDR highpc;
7369               CORE_ADDR lowpc;
7370
7371               baseaddr = ANOFFSET (objfile->section_offsets,
7372                                    SECT_OFF_TEXT (objfile));
7373               lowpc = gdbarch_adjust_dwarf2_addr (gdbarch,
7374                                                   pdi->lowpc + baseaddr);
7375               highpc = gdbarch_adjust_dwarf2_addr (gdbarch,
7376                                                    pdi->highpc + baseaddr);
7377               addrmap_set_empty (objfile->psymtabs_addrmap, lowpc, highpc - 1,
7378                                  cu->per_cu->v.psymtab);
7379             }
7380         }
7381
7382       if (pdi->has_pc_info || (!pdi->is_external && pdi->may_be_inlined))
7383         {
7384           if (!pdi->is_declaration)
7385             /* Ignore subprogram DIEs that do not have a name, they are
7386                illegal.  Do not emit a complaint at this point, we will
7387                do so when we convert this psymtab into a symtab.  */
7388             if (pdi->name)
7389               add_partial_symbol (pdi, cu);
7390         }
7391     }
7392
7393   if (! pdi->has_children)
7394     return;
7395
7396   if (cu->language == language_ada)
7397     {
7398       pdi = pdi->die_child;
7399       while (pdi != NULL)
7400         {
7401           fixup_partial_die (pdi, cu);
7402           if (pdi->tag == DW_TAG_subprogram
7403               || pdi->tag == DW_TAG_lexical_block)
7404             add_partial_subprogram (pdi, lowpc, highpc, set_addrmap, cu);
7405           pdi = pdi->die_sibling;
7406         }
7407     }
7408 }
7409
7410 /* Read a partial die corresponding to an enumeration type.  */
7411
7412 static void
7413 add_partial_enumeration (struct partial_die_info *enum_pdi,
7414                          struct dwarf2_cu *cu)
7415 {
7416   struct partial_die_info *pdi;
7417
7418   if (enum_pdi->name != NULL)
7419     add_partial_symbol (enum_pdi, cu);
7420
7421   pdi = enum_pdi->die_child;
7422   while (pdi)
7423     {
7424       if (pdi->tag != DW_TAG_enumerator || pdi->name == NULL)
7425         complaint (&symfile_complaints, _("malformed enumerator DIE ignored"));
7426       else
7427         add_partial_symbol (pdi, cu);
7428       pdi = pdi->die_sibling;
7429     }
7430 }
7431
7432 /* Return the initial uleb128 in the die at INFO_PTR.  */
7433
7434 static unsigned int
7435 peek_abbrev_code (bfd *abfd, const gdb_byte *info_ptr)
7436 {
7437   unsigned int bytes_read;
7438
7439   return read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
7440 }
7441
7442 /* Read the initial uleb128 in the die at INFO_PTR in compilation unit CU.
7443    Return the corresponding abbrev, or NULL if the number is zero (indicating
7444    an empty DIE).  In either case *BYTES_READ will be set to the length of
7445    the initial number.  */
7446
7447 static struct abbrev_info *
7448 peek_die_abbrev (const gdb_byte *info_ptr, unsigned int *bytes_read,
7449                  struct dwarf2_cu *cu)
7450 {
7451   bfd *abfd = cu->objfile->obfd;
7452   unsigned int abbrev_number;
7453   struct abbrev_info *abbrev;
7454
7455   abbrev_number = read_unsigned_leb128 (abfd, info_ptr, bytes_read);
7456
7457   if (abbrev_number == 0)
7458     return NULL;
7459
7460   abbrev = abbrev_table_lookup_abbrev (cu->abbrev_table, abbrev_number);
7461   if (!abbrev)
7462     {
7463       error (_("Dwarf Error: Could not find abbrev number %d in %s"
7464                " at offset 0x%x [in module %s]"),
7465              abbrev_number, cu->per_cu->is_debug_types ? "TU" : "CU",
7466              to_underlying (cu->header.sect_off), bfd_get_filename (abfd));
7467     }
7468
7469   return abbrev;
7470 }
7471
7472 /* Scan the debug information for CU starting at INFO_PTR in buffer BUFFER.
7473    Returns a pointer to the end of a series of DIEs, terminated by an empty
7474    DIE.  Any children of the skipped DIEs will also be skipped.  */
7475
7476 static const gdb_byte *
7477 skip_children (const struct die_reader_specs *reader, const gdb_byte *info_ptr)
7478 {
7479   struct dwarf2_cu *cu = reader->cu;
7480   struct abbrev_info *abbrev;
7481   unsigned int bytes_read;
7482
7483   while (1)
7484     {
7485       abbrev = peek_die_abbrev (info_ptr, &bytes_read, cu);
7486       if (abbrev == NULL)
7487         return info_ptr + bytes_read;
7488       else
7489         info_ptr = skip_one_die (reader, info_ptr + bytes_read, abbrev);
7490     }
7491 }
7492
7493 /* Scan the debug information for CU starting at INFO_PTR in buffer BUFFER.
7494    INFO_PTR should point just after the initial uleb128 of a DIE, and the
7495    abbrev corresponding to that skipped uleb128 should be passed in
7496    ABBREV.  Returns a pointer to this DIE's sibling, skipping any
7497    children.  */
7498
7499 static const gdb_byte *
7500 skip_one_die (const struct die_reader_specs *reader, const gdb_byte *info_ptr,
7501               struct abbrev_info *abbrev)
7502 {
7503   unsigned int bytes_read;
7504   struct attribute attr;
7505   bfd *abfd = reader->abfd;
7506   struct dwarf2_cu *cu = reader->cu;
7507   const gdb_byte *buffer = reader->buffer;
7508   const gdb_byte *buffer_end = reader->buffer_end;
7509   unsigned int form, i;
7510
7511   for (i = 0; i < abbrev->num_attrs; i++)
7512     {
7513       /* The only abbrev we care about is DW_AT_sibling.  */
7514       if (abbrev->attrs[i].name == DW_AT_sibling)
7515         {
7516           read_attribute (reader, &attr, &abbrev->attrs[i], info_ptr);
7517           if (attr.form == DW_FORM_ref_addr)
7518             complaint (&symfile_complaints,
7519                        _("ignoring absolute DW_AT_sibling"));
7520           else
7521             {
7522               sect_offset off = dwarf2_get_ref_die_offset (&attr);
7523               const gdb_byte *sibling_ptr = buffer + to_underlying (off);
7524
7525               if (sibling_ptr < info_ptr)
7526                 complaint (&symfile_complaints,
7527                            _("DW_AT_sibling points backwards"));
7528               else if (sibling_ptr > reader->buffer_end)
7529                 dwarf2_section_buffer_overflow_complaint (reader->die_section);
7530               else
7531                 return sibling_ptr;
7532             }
7533         }
7534
7535       /* If it isn't DW_AT_sibling, skip this attribute.  */
7536       form = abbrev->attrs[i].form;
7537     skip_attribute:
7538       switch (form)
7539         {
7540         case DW_FORM_ref_addr:
7541           /* In DWARF 2, DW_FORM_ref_addr is address sized; in DWARF 3
7542              and later it is offset sized.  */
7543           if (cu->header.version == 2)
7544             info_ptr += cu->header.addr_size;
7545           else
7546             info_ptr += cu->header.offset_size;
7547           break;
7548         case DW_FORM_GNU_ref_alt:
7549           info_ptr += cu->header.offset_size;
7550           break;
7551         case DW_FORM_addr:
7552           info_ptr += cu->header.addr_size;
7553           break;
7554         case DW_FORM_data1:
7555         case DW_FORM_ref1:
7556         case DW_FORM_flag:
7557           info_ptr += 1;
7558           break;
7559         case DW_FORM_flag_present:
7560         case DW_FORM_implicit_const:
7561           break;
7562         case DW_FORM_data2:
7563         case DW_FORM_ref2:
7564           info_ptr += 2;
7565           break;
7566         case DW_FORM_data4:
7567         case DW_FORM_ref4:
7568           info_ptr += 4;
7569           break;
7570         case DW_FORM_data8:
7571         case DW_FORM_ref8:
7572         case DW_FORM_ref_sig8:
7573           info_ptr += 8;
7574           break;
7575         case DW_FORM_data16:
7576           info_ptr += 16;
7577           break;
7578         case DW_FORM_string:
7579           read_direct_string (abfd, info_ptr, &bytes_read);
7580           info_ptr += bytes_read;
7581           break;
7582         case DW_FORM_sec_offset:
7583         case DW_FORM_strp:
7584         case DW_FORM_GNU_strp_alt:
7585           info_ptr += cu->header.offset_size;
7586           break;
7587         case DW_FORM_exprloc:
7588         case DW_FORM_block:
7589           info_ptr += read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
7590           info_ptr += bytes_read;
7591           break;
7592         case DW_FORM_block1:
7593           info_ptr += 1 + read_1_byte (abfd, info_ptr);
7594           break;
7595         case DW_FORM_block2:
7596           info_ptr += 2 + read_2_bytes (abfd, info_ptr);
7597           break;
7598         case DW_FORM_block4:
7599           info_ptr += 4 + read_4_bytes (abfd, info_ptr);
7600           break;
7601         case DW_FORM_sdata:
7602         case DW_FORM_udata:
7603         case DW_FORM_ref_udata:
7604         case DW_FORM_GNU_addr_index:
7605         case DW_FORM_GNU_str_index:
7606           info_ptr = safe_skip_leb128 (info_ptr, buffer_end);
7607           break;
7608         case DW_FORM_indirect:
7609           form = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
7610           info_ptr += bytes_read;
7611           /* We need to continue parsing from here, so just go back to
7612              the top.  */
7613           goto skip_attribute;
7614
7615         default:
7616           error (_("Dwarf Error: Cannot handle %s "
7617                    "in DWARF reader [in module %s]"),
7618                  dwarf_form_name (form),
7619                  bfd_get_filename (abfd));
7620         }
7621     }
7622
7623   if (abbrev->has_children)
7624     return skip_children (reader, info_ptr);
7625   else
7626     return info_ptr;
7627 }
7628
7629 /* Locate ORIG_PDI's sibling.
7630    INFO_PTR should point to the start of the next DIE after ORIG_PDI.  */
7631
7632 static const gdb_byte *
7633 locate_pdi_sibling (const struct die_reader_specs *reader,
7634                     struct partial_die_info *orig_pdi,
7635                     const gdb_byte *info_ptr)
7636 {
7637   /* Do we know the sibling already?  */
7638
7639   if (orig_pdi->sibling)
7640     return orig_pdi->sibling;
7641
7642   /* Are there any children to deal with?  */
7643
7644   if (!orig_pdi->has_children)
7645     return info_ptr;
7646
7647   /* Skip the children the long way.  */
7648
7649   return skip_children (reader, info_ptr);
7650 }
7651
7652 /* Expand this partial symbol table into a full symbol table.  SELF is
7653    not NULL.  */
7654
7655 static void
7656 dwarf2_read_symtab (struct partial_symtab *self,
7657                     struct objfile *objfile)
7658 {
7659   if (self->readin)
7660     {
7661       warning (_("bug: psymtab for %s is already read in."),
7662                self->filename);
7663     }
7664   else
7665     {
7666       if (info_verbose)
7667         {
7668           printf_filtered (_("Reading in symbols for %s..."),
7669                            self->filename);
7670           gdb_flush (gdb_stdout);
7671         }
7672
7673       /* Restore our global data.  */
7674       dwarf2_per_objfile
7675         = (struct dwarf2_per_objfile *) objfile_data (objfile,
7676                                                       dwarf2_objfile_data_key);
7677
7678       /* If this psymtab is constructed from a debug-only objfile, the
7679          has_section_at_zero flag will not necessarily be correct.  We
7680          can get the correct value for this flag by looking at the data
7681          associated with the (presumably stripped) associated objfile.  */
7682       if (objfile->separate_debug_objfile_backlink)
7683         {
7684           struct dwarf2_per_objfile *dpo_backlink
7685             = ((struct dwarf2_per_objfile *)
7686                objfile_data (objfile->separate_debug_objfile_backlink,
7687                              dwarf2_objfile_data_key));
7688
7689           dwarf2_per_objfile->has_section_at_zero
7690             = dpo_backlink->has_section_at_zero;
7691         }
7692
7693       dwarf2_per_objfile->reading_partial_symbols = 0;
7694
7695       psymtab_to_symtab_1 (self);
7696
7697       /* Finish up the debug error message.  */
7698       if (info_verbose)
7699         printf_filtered (_("done.\n"));
7700     }
7701
7702   process_cu_includes ();
7703 }
7704 \f
7705 /* Reading in full CUs.  */
7706
7707 /* Add PER_CU to the queue.  */
7708
7709 static void
7710 queue_comp_unit (struct dwarf2_per_cu_data *per_cu,
7711                  enum language pretend_language)
7712 {
7713   struct dwarf2_queue_item *item;
7714
7715   per_cu->queued = 1;
7716   item = XNEW (struct dwarf2_queue_item);
7717   item->per_cu = per_cu;
7718   item->pretend_language = pretend_language;
7719   item->next = NULL;
7720
7721   if (dwarf2_queue == NULL)
7722     dwarf2_queue = item;
7723   else
7724     dwarf2_queue_tail->next = item;
7725
7726   dwarf2_queue_tail = item;
7727 }
7728
7729 /* If PER_CU is not yet queued, add it to the queue.
7730    If DEPENDENT_CU is non-NULL, it has a reference to PER_CU so add a
7731    dependency.
7732    The result is non-zero if PER_CU was queued, otherwise the result is zero
7733    meaning either PER_CU is already queued or it is already loaded.
7734
7735    N.B. There is an invariant here that if a CU is queued then it is loaded.
7736    The caller is required to load PER_CU if we return non-zero.  */
7737
7738 static int
7739 maybe_queue_comp_unit (struct dwarf2_cu *dependent_cu,
7740                        struct dwarf2_per_cu_data *per_cu,
7741                        enum language pretend_language)
7742 {
7743   /* We may arrive here during partial symbol reading, if we need full
7744      DIEs to process an unusual case (e.g. template arguments).  Do
7745      not queue PER_CU, just tell our caller to load its DIEs.  */
7746   if (dwarf2_per_objfile->reading_partial_symbols)
7747     {
7748       if (per_cu->cu == NULL || per_cu->cu->dies == NULL)
7749         return 1;
7750       return 0;
7751     }
7752
7753   /* Mark the dependence relation so that we don't flush PER_CU
7754      too early.  */
7755   if (dependent_cu != NULL)
7756     dwarf2_add_dependence (dependent_cu, per_cu);
7757
7758   /* If it's already on the queue, we have nothing to do.  */
7759   if (per_cu->queued)
7760     return 0;
7761
7762   /* If the compilation unit is already loaded, just mark it as
7763      used.  */
7764   if (per_cu->cu != NULL)
7765     {
7766       per_cu->cu->last_used = 0;
7767       return 0;
7768     }
7769
7770   /* Add it to the queue.  */
7771   queue_comp_unit (per_cu, pretend_language);
7772
7773   return 1;
7774 }
7775
7776 /* Process the queue.  */
7777
7778 static void
7779 process_queue (void)
7780 {
7781   struct dwarf2_queue_item *item, *next_item;
7782
7783   if (dwarf_read_debug)
7784     {
7785       fprintf_unfiltered (gdb_stdlog,
7786                           "Expanding one or more symtabs of objfile %s ...\n",
7787                           objfile_name (dwarf2_per_objfile->objfile));
7788     }
7789
7790   /* The queue starts out with one item, but following a DIE reference
7791      may load a new CU, adding it to the end of the queue.  */
7792   for (item = dwarf2_queue; item != NULL; dwarf2_queue = item = next_item)
7793     {
7794       if ((dwarf2_per_objfile->using_index
7795            ? !item->per_cu->v.quick->compunit_symtab
7796            : (item->per_cu->v.psymtab && !item->per_cu->v.psymtab->readin))
7797           /* Skip dummy CUs.  */
7798           && item->per_cu->cu != NULL)
7799         {
7800           struct dwarf2_per_cu_data *per_cu = item->per_cu;
7801           unsigned int debug_print_threshold;
7802           char buf[100];
7803
7804           if (per_cu->is_debug_types)
7805             {
7806               struct signatured_type *sig_type =
7807                 (struct signatured_type *) per_cu;
7808
7809               sprintf (buf, "TU %s at offset 0x%x",
7810                        hex_string (sig_type->signature),
7811                        to_underlying (per_cu->sect_off));
7812               /* There can be 100s of TUs.
7813                  Only print them in verbose mode.  */
7814               debug_print_threshold = 2;
7815             }
7816           else
7817             {
7818               sprintf (buf, "CU at offset 0x%x",
7819                        to_underlying (per_cu->sect_off));
7820               debug_print_threshold = 1;
7821             }
7822
7823           if (dwarf_read_debug >= debug_print_threshold)
7824             fprintf_unfiltered (gdb_stdlog, "Expanding symtab of %s\n", buf);
7825
7826           if (per_cu->is_debug_types)
7827             process_full_type_unit (per_cu, item->pretend_language);
7828           else
7829             process_full_comp_unit (per_cu, item->pretend_language);
7830
7831           if (dwarf_read_debug >= debug_print_threshold)
7832             fprintf_unfiltered (gdb_stdlog, "Done expanding %s\n", buf);
7833         }
7834
7835       item->per_cu->queued = 0;
7836       next_item = item->next;
7837       xfree (item);
7838     }
7839
7840   dwarf2_queue_tail = NULL;
7841
7842   if (dwarf_read_debug)
7843     {
7844       fprintf_unfiltered (gdb_stdlog, "Done expanding symtabs of %s.\n",
7845                           objfile_name (dwarf2_per_objfile->objfile));
7846     }
7847 }
7848
7849 /* Free all allocated queue entries.  This function only releases anything if
7850    an error was thrown; if the queue was processed then it would have been
7851    freed as we went along.  */
7852
7853 static void
7854 dwarf2_release_queue (void *dummy)
7855 {
7856   struct dwarf2_queue_item *item, *last;
7857
7858   item = dwarf2_queue;
7859   while (item)
7860     {
7861       /* Anything still marked queued is likely to be in an
7862          inconsistent state, so discard it.  */
7863       if (item->per_cu->queued)
7864         {
7865           if (item->per_cu->cu != NULL)
7866             free_one_cached_comp_unit (item->per_cu);
7867           item->per_cu->queued = 0;
7868         }
7869
7870       last = item;
7871       item = item->next;
7872       xfree (last);
7873     }
7874
7875   dwarf2_queue = dwarf2_queue_tail = NULL;
7876 }
7877
7878 /* Read in full symbols for PST, and anything it depends on.  */
7879
7880 static void
7881 psymtab_to_symtab_1 (struct partial_symtab *pst)
7882 {
7883   struct dwarf2_per_cu_data *per_cu;
7884   int i;
7885
7886   if (pst->readin)
7887     return;
7888
7889   for (i = 0; i < pst->number_of_dependencies; i++)
7890     if (!pst->dependencies[i]->readin
7891         && pst->dependencies[i]->user == NULL)
7892       {
7893         /* Inform about additional files that need to be read in.  */
7894         if (info_verbose)
7895           {
7896             /* FIXME: i18n: Need to make this a single string.  */
7897             fputs_filtered (" ", gdb_stdout);
7898             wrap_here ("");
7899             fputs_filtered ("and ", gdb_stdout);
7900             wrap_here ("");
7901             printf_filtered ("%s...", pst->dependencies[i]->filename);
7902             wrap_here ("");     /* Flush output.  */
7903             gdb_flush (gdb_stdout);
7904           }
7905         psymtab_to_symtab_1 (pst->dependencies[i]);
7906       }
7907
7908   per_cu = (struct dwarf2_per_cu_data *) pst->read_symtab_private;
7909
7910   if (per_cu == NULL)
7911     {
7912       /* It's an include file, no symbols to read for it.
7913          Everything is in the parent symtab.  */
7914       pst->readin = 1;
7915       return;
7916     }
7917
7918   dw2_do_instantiate_symtab (per_cu);
7919 }
7920
7921 /* Trivial hash function for die_info: the hash value of a DIE
7922    is its offset in .debug_info for this objfile.  */
7923
7924 static hashval_t
7925 die_hash (const void *item)
7926 {
7927   const struct die_info *die = (const struct die_info *) item;
7928
7929   return to_underlying (die->sect_off);
7930 }
7931
7932 /* Trivial comparison function for die_info structures: two DIEs
7933    are equal if they have the same offset.  */
7934
7935 static int
7936 die_eq (const void *item_lhs, const void *item_rhs)
7937 {
7938   const struct die_info *die_lhs = (const struct die_info *) item_lhs;
7939   const struct die_info *die_rhs = (const struct die_info *) item_rhs;
7940
7941   return die_lhs->sect_off == die_rhs->sect_off;
7942 }
7943
7944 /* die_reader_func for load_full_comp_unit.
7945    This is identical to read_signatured_type_reader,
7946    but is kept separate for now.  */
7947
7948 static void
7949 load_full_comp_unit_reader (const struct die_reader_specs *reader,
7950                             const gdb_byte *info_ptr,
7951                             struct die_info *comp_unit_die,
7952                             int has_children,
7953                             void *data)
7954 {
7955   struct dwarf2_cu *cu = reader->cu;
7956   enum language *language_ptr = (enum language *) data;
7957
7958   gdb_assert (cu->die_hash == NULL);
7959   cu->die_hash =
7960     htab_create_alloc_ex (cu->header.length / 12,
7961                           die_hash,
7962                           die_eq,
7963                           NULL,
7964                           &cu->comp_unit_obstack,
7965                           hashtab_obstack_allocate,
7966                           dummy_obstack_deallocate);
7967
7968   if (has_children)
7969     comp_unit_die->child = read_die_and_siblings (reader, info_ptr,
7970                                                   &info_ptr, comp_unit_die);
7971   cu->dies = comp_unit_die;
7972   /* comp_unit_die is not stored in die_hash, no need.  */
7973
7974   /* We try not to read any attributes in this function, because not
7975      all CUs needed for references have been loaded yet, and symbol
7976      table processing isn't initialized.  But we have to set the CU language,
7977      or we won't be able to build types correctly.
7978      Similarly, if we do not read the producer, we can not apply
7979      producer-specific interpretation.  */
7980   prepare_one_comp_unit (cu, cu->dies, *language_ptr);
7981 }
7982
7983 /* Load the DIEs associated with PER_CU into memory.  */
7984
7985 static void
7986 load_full_comp_unit (struct dwarf2_per_cu_data *this_cu,
7987                      enum language pretend_language)
7988 {
7989   gdb_assert (! this_cu->is_debug_types);
7990
7991   init_cutu_and_read_dies (this_cu, NULL, 1, 1,
7992                            load_full_comp_unit_reader, &pretend_language);
7993 }
7994
7995 /* Add a DIE to the delayed physname list.  */
7996
7997 static void
7998 add_to_method_list (struct type *type, int fnfield_index, int index,
7999                     const char *name, struct die_info *die,
8000                     struct dwarf2_cu *cu)
8001 {
8002   struct delayed_method_info mi;
8003   mi.type = type;
8004   mi.fnfield_index = fnfield_index;
8005   mi.index = index;
8006   mi.name = name;
8007   mi.die = die;
8008   VEC_safe_push (delayed_method_info, cu->method_list, &mi);
8009 }
8010
8011 /* A cleanup for freeing the delayed method list.  */
8012
8013 static void
8014 free_delayed_list (void *ptr)
8015 {
8016   struct dwarf2_cu *cu = (struct dwarf2_cu *) ptr;
8017   if (cu->method_list != NULL)
8018     {
8019       VEC_free (delayed_method_info, cu->method_list);
8020       cu->method_list = NULL;
8021     }
8022 }
8023
8024 /* Compute the physnames of any methods on the CU's method list.
8025
8026    The computation of method physnames is delayed in order to avoid the
8027    (bad) condition that one of the method's formal parameters is of an as yet
8028    incomplete type.  */
8029
8030 static void
8031 compute_delayed_physnames (struct dwarf2_cu *cu)
8032 {
8033   int i;
8034   struct delayed_method_info *mi;
8035   for (i = 0; VEC_iterate (delayed_method_info, cu->method_list, i, mi) ; ++i)
8036     {
8037       const char *physname;
8038       struct fn_fieldlist *fn_flp
8039         = &TYPE_FN_FIELDLIST (mi->type, mi->fnfield_index);
8040       physname = dwarf2_physname (mi->name, mi->die, cu);
8041       TYPE_FN_FIELD_PHYSNAME (fn_flp->fn_fields, mi->index)
8042         = physname ? physname : "";
8043     }
8044 }
8045
8046 /* Go objects should be embedded in a DW_TAG_module DIE,
8047    and it's not clear if/how imported objects will appear.
8048    To keep Go support simple until that's worked out,
8049    go back through what we've read and create something usable.
8050    We could do this while processing each DIE, and feels kinda cleaner,
8051    but that way is more invasive.
8052    This is to, for example, allow the user to type "p var" or "b main"
8053    without having to specify the package name, and allow lookups
8054    of module.object to work in contexts that use the expression
8055    parser.  */
8056
8057 static void
8058 fixup_go_packaging (struct dwarf2_cu *cu)
8059 {
8060   char *package_name = NULL;
8061   struct pending *list;
8062   int i;
8063
8064   for (list = global_symbols; list != NULL; list = list->next)
8065     {
8066       for (i = 0; i < list->nsyms; ++i)
8067         {
8068           struct symbol *sym = list->symbol[i];
8069
8070           if (SYMBOL_LANGUAGE (sym) == language_go
8071               && SYMBOL_CLASS (sym) == LOC_BLOCK)
8072             {
8073               char *this_package_name = go_symbol_package_name (sym);
8074
8075               if (this_package_name == NULL)
8076                 continue;
8077               if (package_name == NULL)
8078                 package_name = this_package_name;
8079               else
8080                 {
8081                   if (strcmp (package_name, this_package_name) != 0)
8082                     complaint (&symfile_complaints,
8083                                _("Symtab %s has objects from two different Go packages: %s and %s"),
8084                                (symbol_symtab (sym) != NULL
8085                                 ? symtab_to_filename_for_display
8086                                     (symbol_symtab (sym))
8087                                 : objfile_name (cu->objfile)),
8088                                this_package_name, package_name);
8089                   xfree (this_package_name);
8090                 }
8091             }
8092         }
8093     }
8094
8095   if (package_name != NULL)
8096     {
8097       struct objfile *objfile = cu->objfile;
8098       const char *saved_package_name
8099         = (const char *) obstack_copy0 (&objfile->per_bfd->storage_obstack,
8100                                         package_name,
8101                                         strlen (package_name));
8102       struct type *type = init_type (objfile, TYPE_CODE_MODULE, 0,
8103                                      saved_package_name);
8104       struct symbol *sym;
8105
8106       TYPE_TAG_NAME (type) = TYPE_NAME (type);
8107
8108       sym = allocate_symbol (objfile);
8109       SYMBOL_SET_LANGUAGE (sym, language_go, &objfile->objfile_obstack);
8110       SYMBOL_SET_NAMES (sym, saved_package_name,
8111                         strlen (saved_package_name), 0, objfile);
8112       /* This is not VAR_DOMAIN because we want a way to ensure a lookup of,
8113          e.g., "main" finds the "main" module and not C's main().  */
8114       SYMBOL_DOMAIN (sym) = STRUCT_DOMAIN;
8115       SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
8116       SYMBOL_TYPE (sym) = type;
8117
8118       add_symbol_to_list (sym, &global_symbols);
8119
8120       xfree (package_name);
8121     }
8122 }
8123
8124 /* Return the symtab for PER_CU.  This works properly regardless of
8125    whether we're using the index or psymtabs.  */
8126
8127 static struct compunit_symtab *
8128 get_compunit_symtab (struct dwarf2_per_cu_data *per_cu)
8129 {
8130   return (dwarf2_per_objfile->using_index
8131           ? per_cu->v.quick->compunit_symtab
8132           : per_cu->v.psymtab->compunit_symtab);
8133 }
8134
8135 /* A helper function for computing the list of all symbol tables
8136    included by PER_CU.  */
8137
8138 static void
8139 recursively_compute_inclusions (VEC (compunit_symtab_ptr) **result,
8140                                 htab_t all_children, htab_t all_type_symtabs,
8141                                 struct dwarf2_per_cu_data *per_cu,
8142                                 struct compunit_symtab *immediate_parent)
8143 {
8144   void **slot;
8145   int ix;
8146   struct compunit_symtab *cust;
8147   struct dwarf2_per_cu_data *iter;
8148
8149   slot = htab_find_slot (all_children, per_cu, INSERT);
8150   if (*slot != NULL)
8151     {
8152       /* This inclusion and its children have been processed.  */
8153       return;
8154     }
8155
8156   *slot = per_cu;
8157   /* Only add a CU if it has a symbol table.  */
8158   cust = get_compunit_symtab (per_cu);
8159   if (cust != NULL)
8160     {
8161       /* If this is a type unit only add its symbol table if we haven't
8162          seen it yet (type unit per_cu's can share symtabs).  */
8163       if (per_cu->is_debug_types)
8164         {
8165           slot = htab_find_slot (all_type_symtabs, cust, INSERT);
8166           if (*slot == NULL)
8167             {
8168               *slot = cust;
8169               VEC_safe_push (compunit_symtab_ptr, *result, cust);
8170               if (cust->user == NULL)
8171                 cust->user = immediate_parent;
8172             }
8173         }
8174       else
8175         {
8176           VEC_safe_push (compunit_symtab_ptr, *result, cust);
8177           if (cust->user == NULL)
8178             cust->user = immediate_parent;
8179         }
8180     }
8181
8182   for (ix = 0;
8183        VEC_iterate (dwarf2_per_cu_ptr, per_cu->imported_symtabs, ix, iter);
8184        ++ix)
8185     {
8186       recursively_compute_inclusions (result, all_children,
8187                                       all_type_symtabs, iter, cust);
8188     }
8189 }
8190
8191 /* Compute the compunit_symtab 'includes' fields for the compunit_symtab of
8192    PER_CU.  */
8193
8194 static void
8195 compute_compunit_symtab_includes (struct dwarf2_per_cu_data *per_cu)
8196 {
8197   gdb_assert (! per_cu->is_debug_types);
8198
8199   if (!VEC_empty (dwarf2_per_cu_ptr, per_cu->imported_symtabs))
8200     {
8201       int ix, len;
8202       struct dwarf2_per_cu_data *per_cu_iter;
8203       struct compunit_symtab *compunit_symtab_iter;
8204       VEC (compunit_symtab_ptr) *result_symtabs = NULL;
8205       htab_t all_children, all_type_symtabs;
8206       struct compunit_symtab *cust = get_compunit_symtab (per_cu);
8207
8208       /* If we don't have a symtab, we can just skip this case.  */
8209       if (cust == NULL)
8210         return;
8211
8212       all_children = htab_create_alloc (1, htab_hash_pointer, htab_eq_pointer,
8213                                         NULL, xcalloc, xfree);
8214       all_type_symtabs = htab_create_alloc (1, htab_hash_pointer, htab_eq_pointer,
8215                                             NULL, xcalloc, xfree);
8216
8217       for (ix = 0;
8218            VEC_iterate (dwarf2_per_cu_ptr, per_cu->imported_symtabs,
8219                         ix, per_cu_iter);
8220            ++ix)
8221         {
8222           recursively_compute_inclusions (&result_symtabs, all_children,
8223                                           all_type_symtabs, per_cu_iter,
8224                                           cust);
8225         }
8226
8227       /* Now we have a transitive closure of all the included symtabs.  */
8228       len = VEC_length (compunit_symtab_ptr, result_symtabs);
8229       cust->includes
8230         = XOBNEWVEC (&dwarf2_per_objfile->objfile->objfile_obstack,
8231                      struct compunit_symtab *, len + 1);
8232       for (ix = 0;
8233            VEC_iterate (compunit_symtab_ptr, result_symtabs, ix,
8234                         compunit_symtab_iter);
8235            ++ix)
8236         cust->includes[ix] = compunit_symtab_iter;
8237       cust->includes[len] = NULL;
8238
8239       VEC_free (compunit_symtab_ptr, result_symtabs);
8240       htab_delete (all_children);
8241       htab_delete (all_type_symtabs);
8242     }
8243 }
8244
8245 /* Compute the 'includes' field for the symtabs of all the CUs we just
8246    read.  */
8247
8248 static void
8249 process_cu_includes (void)
8250 {
8251   int ix;
8252   struct dwarf2_per_cu_data *iter;
8253
8254   for (ix = 0;
8255        VEC_iterate (dwarf2_per_cu_ptr, dwarf2_per_objfile->just_read_cus,
8256                     ix, iter);
8257        ++ix)
8258     {
8259       if (! iter->is_debug_types)
8260         compute_compunit_symtab_includes (iter);
8261     }
8262
8263   VEC_free (dwarf2_per_cu_ptr, dwarf2_per_objfile->just_read_cus);
8264 }
8265
8266 /* Generate full symbol information for PER_CU, whose DIEs have
8267    already been loaded into memory.  */
8268
8269 static void
8270 process_full_comp_unit (struct dwarf2_per_cu_data *per_cu,
8271                         enum language pretend_language)
8272 {
8273   struct dwarf2_cu *cu = per_cu->cu;
8274   struct objfile *objfile = per_cu->objfile;
8275   struct gdbarch *gdbarch = get_objfile_arch (objfile);
8276   CORE_ADDR lowpc, highpc;
8277   struct compunit_symtab *cust;
8278   struct cleanup *back_to, *delayed_list_cleanup;
8279   CORE_ADDR baseaddr;
8280   struct block *static_block;
8281   CORE_ADDR addr;
8282
8283   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
8284
8285   buildsym_init ();
8286   back_to = make_cleanup (really_free_pendings, NULL);
8287   delayed_list_cleanup = make_cleanup (free_delayed_list, cu);
8288
8289   cu->list_in_scope = &file_symbols;
8290
8291   cu->language = pretend_language;
8292   cu->language_defn = language_def (cu->language);
8293
8294   /* Do line number decoding in read_file_scope () */
8295   process_die (cu->dies, cu);
8296
8297   /* For now fudge the Go package.  */
8298   if (cu->language == language_go)
8299     fixup_go_packaging (cu);
8300
8301   /* Now that we have processed all the DIEs in the CU, all the types 
8302      should be complete, and it should now be safe to compute all of the
8303      physnames.  */
8304   compute_delayed_physnames (cu);
8305   do_cleanups (delayed_list_cleanup);
8306
8307   /* Some compilers don't define a DW_AT_high_pc attribute for the
8308      compilation unit.  If the DW_AT_high_pc is missing, synthesize
8309      it, by scanning the DIE's below the compilation unit.  */
8310   get_scope_pc_bounds (cu->dies, &lowpc, &highpc, cu);
8311
8312   addr = gdbarch_adjust_dwarf2_addr (gdbarch, highpc + baseaddr);
8313   static_block = end_symtab_get_static_block (addr, 0, 1);
8314
8315   /* If the comp unit has DW_AT_ranges, it may have discontiguous ranges.
8316      Also, DW_AT_ranges may record ranges not belonging to any child DIEs
8317      (such as virtual method tables).  Record the ranges in STATIC_BLOCK's
8318      addrmap to help ensure it has an accurate map of pc values belonging to
8319      this comp unit.  */
8320   dwarf2_record_block_ranges (cu->dies, static_block, baseaddr, cu);
8321
8322   cust = end_symtab_from_static_block (static_block,
8323                                        SECT_OFF_TEXT (objfile), 0);
8324
8325   if (cust != NULL)
8326     {
8327       int gcc_4_minor = producer_is_gcc_ge_4 (cu->producer);
8328
8329       /* Set symtab language to language from DW_AT_language.  If the
8330          compilation is from a C file generated by language preprocessors, do
8331          not set the language if it was already deduced by start_subfile.  */
8332       if (!(cu->language == language_c
8333             && COMPUNIT_FILETABS (cust)->language != language_unknown))
8334         COMPUNIT_FILETABS (cust)->language = cu->language;
8335
8336       /* GCC-4.0 has started to support -fvar-tracking.  GCC-3.x still can
8337          produce DW_AT_location with location lists but it can be possibly
8338          invalid without -fvar-tracking.  Still up to GCC-4.4.x incl. 4.4.0
8339          there were bugs in prologue debug info, fixed later in GCC-4.5
8340          by "unwind info for epilogues" patch (which is not directly related).
8341
8342          For -gdwarf-4 type units LOCATIONS_VALID indication is fortunately not
8343          needed, it would be wrong due to missing DW_AT_producer there.
8344
8345          Still one can confuse GDB by using non-standard GCC compilation
8346          options - this waits on GCC PR other/32998 (-frecord-gcc-switches).
8347          */ 
8348       if (cu->has_loclist && gcc_4_minor >= 5)
8349         cust->locations_valid = 1;
8350
8351       if (gcc_4_minor >= 5)
8352         cust->epilogue_unwind_valid = 1;
8353
8354       cust->call_site_htab = cu->call_site_htab;
8355     }
8356
8357   if (dwarf2_per_objfile->using_index)
8358     per_cu->v.quick->compunit_symtab = cust;
8359   else
8360     {
8361       struct partial_symtab *pst = per_cu->v.psymtab;
8362       pst->compunit_symtab = cust;
8363       pst->readin = 1;
8364     }
8365
8366   /* Push it for inclusion processing later.  */
8367   VEC_safe_push (dwarf2_per_cu_ptr, dwarf2_per_objfile->just_read_cus, per_cu);
8368
8369   do_cleanups (back_to);
8370 }
8371
8372 /* Generate full symbol information for type unit PER_CU, whose DIEs have
8373    already been loaded into memory.  */
8374
8375 static void
8376 process_full_type_unit (struct dwarf2_per_cu_data *per_cu,
8377                         enum language pretend_language)
8378 {
8379   struct dwarf2_cu *cu = per_cu->cu;
8380   struct objfile *objfile = per_cu->objfile;
8381   struct compunit_symtab *cust;
8382   struct cleanup *back_to, *delayed_list_cleanup;
8383   struct signatured_type *sig_type;
8384
8385   gdb_assert (per_cu->is_debug_types);
8386   sig_type = (struct signatured_type *) per_cu;
8387
8388   buildsym_init ();
8389   back_to = make_cleanup (really_free_pendings, NULL);
8390   delayed_list_cleanup = make_cleanup (free_delayed_list, cu);
8391
8392   cu->list_in_scope = &file_symbols;
8393
8394   cu->language = pretend_language;
8395   cu->language_defn = language_def (cu->language);
8396
8397   /* The symbol tables are set up in read_type_unit_scope.  */
8398   process_die (cu->dies, cu);
8399
8400   /* For now fudge the Go package.  */
8401   if (cu->language == language_go)
8402     fixup_go_packaging (cu);
8403
8404   /* Now that we have processed all the DIEs in the CU, all the types 
8405      should be complete, and it should now be safe to compute all of the
8406      physnames.  */
8407   compute_delayed_physnames (cu);
8408   do_cleanups (delayed_list_cleanup);
8409
8410   /* TUs share symbol tables.
8411      If this is the first TU to use this symtab, complete the construction
8412      of it with end_expandable_symtab.  Otherwise, complete the addition of
8413      this TU's symbols to the existing symtab.  */
8414   if (sig_type->type_unit_group->compunit_symtab == NULL)
8415     {
8416       cust = end_expandable_symtab (0, SECT_OFF_TEXT (objfile));
8417       sig_type->type_unit_group->compunit_symtab = cust;
8418
8419       if (cust != NULL)
8420         {
8421           /* Set symtab language to language from DW_AT_language.  If the
8422              compilation is from a C file generated by language preprocessors,
8423              do not set the language if it was already deduced by
8424              start_subfile.  */
8425           if (!(cu->language == language_c
8426                 && COMPUNIT_FILETABS (cust)->language != language_c))
8427             COMPUNIT_FILETABS (cust)->language = cu->language;
8428         }
8429     }
8430   else
8431     {
8432       augment_type_symtab ();
8433       cust = sig_type->type_unit_group->compunit_symtab;
8434     }
8435
8436   if (dwarf2_per_objfile->using_index)
8437     per_cu->v.quick->compunit_symtab = cust;
8438   else
8439     {
8440       struct partial_symtab *pst = per_cu->v.psymtab;
8441       pst->compunit_symtab = cust;
8442       pst->readin = 1;
8443     }
8444
8445   do_cleanups (back_to);
8446 }
8447
8448 /* Process an imported unit DIE.  */
8449
8450 static void
8451 process_imported_unit_die (struct die_info *die, struct dwarf2_cu *cu)
8452 {
8453   struct attribute *attr;
8454
8455   /* For now we don't handle imported units in type units.  */
8456   if (cu->per_cu->is_debug_types)
8457     {
8458       error (_("Dwarf Error: DW_TAG_imported_unit is not"
8459                " supported in type units [in module %s]"),
8460              objfile_name (cu->objfile));
8461     }
8462
8463   attr = dwarf2_attr (die, DW_AT_import, cu);
8464   if (attr != NULL)
8465     {
8466       sect_offset sect_off = dwarf2_get_ref_die_offset (attr);
8467       bool is_dwz = (attr->form == DW_FORM_GNU_ref_alt || cu->per_cu->is_dwz);
8468       dwarf2_per_cu_data *per_cu
8469         = dwarf2_find_containing_comp_unit (sect_off, is_dwz, cu->objfile);
8470
8471       /* If necessary, add it to the queue and load its DIEs.  */
8472       if (maybe_queue_comp_unit (cu, per_cu, cu->language))
8473         load_full_comp_unit (per_cu, cu->language);
8474
8475       VEC_safe_push (dwarf2_per_cu_ptr, cu->per_cu->imported_symtabs,
8476                      per_cu);
8477     }
8478 }
8479
8480 /* RAII object that represents a process_die scope: i.e.,
8481    starts/finishes processing a DIE.  */
8482 class process_die_scope
8483 {
8484 public:
8485   process_die_scope (die_info *die, dwarf2_cu *cu)
8486     : m_die (die), m_cu (cu)
8487   {
8488     /* We should only be processing DIEs not already in process.  */
8489     gdb_assert (!m_die->in_process);
8490     m_die->in_process = true;
8491   }
8492
8493   ~process_die_scope ()
8494   {
8495     m_die->in_process = false;
8496
8497     /* If we're done processing the DIE for the CU that owns the line
8498        header, we don't need the line header anymore.  */
8499     if (m_cu->line_header_die_owner == m_die)
8500       {
8501         delete m_cu->line_header;
8502         m_cu->line_header = NULL;
8503         m_cu->line_header_die_owner = NULL;
8504       }
8505   }
8506
8507 private:
8508   die_info *m_die;
8509   dwarf2_cu *m_cu;
8510 };
8511
8512 /* Process a die and its children.  */
8513
8514 static void
8515 process_die (struct die_info *die, struct dwarf2_cu *cu)
8516 {
8517   process_die_scope scope (die, cu);
8518
8519   switch (die->tag)
8520     {
8521     case DW_TAG_padding:
8522       break;
8523     case DW_TAG_compile_unit:
8524     case DW_TAG_partial_unit:
8525       read_file_scope (die, cu);
8526       break;
8527     case DW_TAG_type_unit:
8528       read_type_unit_scope (die, cu);
8529       break;
8530     case DW_TAG_subprogram:
8531     case DW_TAG_inlined_subroutine:
8532       read_func_scope (die, cu);
8533       break;
8534     case DW_TAG_lexical_block:
8535     case DW_TAG_try_block:
8536     case DW_TAG_catch_block:
8537       read_lexical_block_scope (die, cu);
8538       break;
8539     case DW_TAG_call_site:
8540     case DW_TAG_GNU_call_site:
8541       read_call_site_scope (die, cu);
8542       break;
8543     case DW_TAG_class_type:
8544     case DW_TAG_interface_type:
8545     case DW_TAG_structure_type:
8546     case DW_TAG_union_type:
8547       process_structure_scope (die, cu);
8548       break;
8549     case DW_TAG_enumeration_type:
8550       process_enumeration_scope (die, cu);
8551       break;
8552
8553     /* These dies have a type, but processing them does not create
8554        a symbol or recurse to process the children.  Therefore we can
8555        read them on-demand through read_type_die.  */
8556     case DW_TAG_subroutine_type:
8557     case DW_TAG_set_type:
8558     case DW_TAG_array_type:
8559     case DW_TAG_pointer_type:
8560     case DW_TAG_ptr_to_member_type:
8561     case DW_TAG_reference_type:
8562     case DW_TAG_rvalue_reference_type:
8563     case DW_TAG_string_type:
8564       break;
8565
8566     case DW_TAG_base_type:
8567     case DW_TAG_subrange_type:
8568     case DW_TAG_typedef:
8569       /* Add a typedef symbol for the type definition, if it has a
8570          DW_AT_name.  */
8571       new_symbol (die, read_type_die (die, cu), cu);
8572       break;
8573     case DW_TAG_common_block:
8574       read_common_block (die, cu);
8575       break;
8576     case DW_TAG_common_inclusion:
8577       break;
8578     case DW_TAG_namespace:
8579       cu->processing_has_namespace_info = 1;
8580       read_namespace (die, cu);
8581       break;
8582     case DW_TAG_module:
8583       cu->processing_has_namespace_info = 1;
8584       read_module (die, cu);
8585       break;
8586     case DW_TAG_imported_declaration:
8587       cu->processing_has_namespace_info = 1;
8588       if (read_namespace_alias (die, cu))
8589         break;
8590       /* The declaration is not a global namespace alias: fall through.  */
8591     case DW_TAG_imported_module:
8592       cu->processing_has_namespace_info = 1;
8593       if (die->child != NULL && (die->tag == DW_TAG_imported_declaration
8594                                  || cu->language != language_fortran))
8595         complaint (&symfile_complaints, _("Tag '%s' has unexpected children"),
8596                    dwarf_tag_name (die->tag));
8597       read_import_statement (die, cu);
8598       break;
8599
8600     case DW_TAG_imported_unit:
8601       process_imported_unit_die (die, cu);
8602       break;
8603
8604     default:
8605       new_symbol (die, NULL, cu);
8606       break;
8607     }
8608 }
8609 \f
8610 /* DWARF name computation.  */
8611
8612 /* A helper function for dwarf2_compute_name which determines whether DIE
8613    needs to have the name of the scope prepended to the name listed in the
8614    die.  */
8615
8616 static int
8617 die_needs_namespace (struct die_info *die, struct dwarf2_cu *cu)
8618 {
8619   struct attribute *attr;
8620
8621   switch (die->tag)
8622     {
8623     case DW_TAG_namespace:
8624     case DW_TAG_typedef:
8625     case DW_TAG_class_type:
8626     case DW_TAG_interface_type:
8627     case DW_TAG_structure_type:
8628     case DW_TAG_union_type:
8629     case DW_TAG_enumeration_type:
8630     case DW_TAG_enumerator:
8631     case DW_TAG_subprogram:
8632     case DW_TAG_inlined_subroutine:
8633     case DW_TAG_member:
8634     case DW_TAG_imported_declaration:
8635       return 1;
8636
8637     case DW_TAG_variable:
8638     case DW_TAG_constant:
8639       /* We only need to prefix "globally" visible variables.  These include
8640          any variable marked with DW_AT_external or any variable that
8641          lives in a namespace.  [Variables in anonymous namespaces
8642          require prefixing, but they are not DW_AT_external.]  */
8643
8644       if (dwarf2_attr (die, DW_AT_specification, cu))
8645         {
8646           struct dwarf2_cu *spec_cu = cu;
8647
8648           return die_needs_namespace (die_specification (die, &spec_cu),
8649                                       spec_cu);
8650         }
8651
8652       attr = dwarf2_attr (die, DW_AT_external, cu);
8653       if (attr == NULL && die->parent->tag != DW_TAG_namespace
8654           && die->parent->tag != DW_TAG_module)
8655         return 0;
8656       /* A variable in a lexical block of some kind does not need a
8657          namespace, even though in C++ such variables may be external
8658          and have a mangled name.  */
8659       if (die->parent->tag ==  DW_TAG_lexical_block
8660           || die->parent->tag ==  DW_TAG_try_block
8661           || die->parent->tag ==  DW_TAG_catch_block
8662           || die->parent->tag == DW_TAG_subprogram)
8663         return 0;
8664       return 1;
8665
8666     default:
8667       return 0;
8668     }
8669 }
8670
8671 /* Compute the fully qualified name of DIE in CU.  If PHYSNAME is nonzero,
8672    compute the physname for the object, which include a method's:
8673    - formal parameters (C++),
8674    - receiver type (Go),
8675
8676    The term "physname" is a bit confusing.
8677    For C++, for example, it is the demangled name.
8678    For Go, for example, it's the mangled name.
8679
8680    For Ada, return the DIE's linkage name rather than the fully qualified
8681    name.  PHYSNAME is ignored..
8682
8683    The result is allocated on the objfile_obstack and canonicalized.  */
8684
8685 static const char *
8686 dwarf2_compute_name (const char *name,
8687                      struct die_info *die, struct dwarf2_cu *cu,
8688                      int physname)
8689 {
8690   struct objfile *objfile = cu->objfile;
8691
8692   if (name == NULL)
8693     name = dwarf2_name (die, cu);
8694
8695   /* For Fortran GDB prefers DW_AT_*linkage_name for the physname if present
8696      but otherwise compute it by typename_concat inside GDB.
8697      FIXME: Actually this is not really true, or at least not always true.
8698      It's all very confusing.  SYMBOL_SET_NAMES doesn't try to demangle
8699      Fortran names because there is no mangling standard.  So new_symbol_full
8700      will set the demangled name to the result of dwarf2_full_name, and it is
8701      the demangled name that GDB uses if it exists.  */
8702   if (cu->language == language_ada
8703       || (cu->language == language_fortran && physname))
8704     {
8705       /* For Ada unit, we prefer the linkage name over the name, as
8706          the former contains the exported name, which the user expects
8707          to be able to reference.  Ideally, we want the user to be able
8708          to reference this entity using either natural or linkage name,
8709          but we haven't started looking at this enhancement yet.  */
8710       const char *linkage_name;
8711
8712       linkage_name = dwarf2_string_attr (die, DW_AT_linkage_name, cu);
8713       if (linkage_name == NULL)
8714         linkage_name = dwarf2_string_attr (die, DW_AT_MIPS_linkage_name, cu);
8715       if (linkage_name != NULL)
8716         return linkage_name;
8717     }
8718
8719   /* These are the only languages we know how to qualify names in.  */
8720   if (name != NULL
8721       && (cu->language == language_cplus
8722           || cu->language == language_fortran || cu->language == language_d
8723           || cu->language == language_rust))
8724     {
8725       if (die_needs_namespace (die, cu))
8726         {
8727           long length;
8728           const char *prefix;
8729           const char *canonical_name = NULL;
8730
8731           string_file buf;
8732
8733           prefix = determine_prefix (die, cu);
8734           if (*prefix != '\0')
8735             {
8736               char *prefixed_name = typename_concat (NULL, prefix, name,
8737                                                      physname, cu);
8738
8739               buf.puts (prefixed_name);
8740               xfree (prefixed_name);
8741             }
8742           else
8743             buf.puts (name);
8744
8745           /* Template parameters may be specified in the DIE's DW_AT_name, or
8746              as children with DW_TAG_template_type_param or
8747              DW_TAG_value_type_param.  If the latter, add them to the name
8748              here.  If the name already has template parameters, then
8749              skip this step; some versions of GCC emit both, and
8750              it is more efficient to use the pre-computed name.
8751
8752              Something to keep in mind about this process: it is very
8753              unlikely, or in some cases downright impossible, to produce
8754              something that will match the mangled name of a function.
8755              If the definition of the function has the same debug info,
8756              we should be able to match up with it anyway.  But fallbacks
8757              using the minimal symbol, for instance to find a method
8758              implemented in a stripped copy of libstdc++, will not work.
8759              If we do not have debug info for the definition, we will have to
8760              match them up some other way.
8761
8762              When we do name matching there is a related problem with function
8763              templates; two instantiated function templates are allowed to
8764              differ only by their return types, which we do not add here.  */
8765
8766           if (cu->language == language_cplus && strchr (name, '<') == NULL)
8767             {
8768               struct attribute *attr;
8769               struct die_info *child;
8770               int first = 1;
8771
8772               die->building_fullname = 1;
8773
8774               for (child = die->child; child != NULL; child = child->sibling)
8775                 {
8776                   struct type *type;
8777                   LONGEST value;
8778                   const gdb_byte *bytes;
8779                   struct dwarf2_locexpr_baton *baton;
8780                   struct value *v;
8781
8782                   if (child->tag != DW_TAG_template_type_param
8783                       && child->tag != DW_TAG_template_value_param)
8784                     continue;
8785
8786                   if (first)
8787                     {
8788                       buf.puts ("<");
8789                       first = 0;
8790                     }
8791                   else
8792                     buf.puts (", ");
8793
8794                   attr = dwarf2_attr (child, DW_AT_type, cu);
8795                   if (attr == NULL)
8796                     {
8797                       complaint (&symfile_complaints,
8798                                  _("template parameter missing DW_AT_type"));
8799                       buf.puts ("UNKNOWN_TYPE");
8800                       continue;
8801                     }
8802                   type = die_type (child, cu);
8803
8804                   if (child->tag == DW_TAG_template_type_param)
8805                     {
8806                       c_print_type (type, "", &buf, -1, 0, &type_print_raw_options);
8807                       continue;
8808                     }
8809
8810                   attr = dwarf2_attr (child, DW_AT_const_value, cu);
8811                   if (attr == NULL)
8812                     {
8813                       complaint (&symfile_complaints,
8814                                  _("template parameter missing "
8815                                    "DW_AT_const_value"));
8816                       buf.puts ("UNKNOWN_VALUE");
8817                       continue;
8818                     }
8819
8820                   dwarf2_const_value_attr (attr, type, name,
8821                                            &cu->comp_unit_obstack, cu,
8822                                            &value, &bytes, &baton);
8823
8824                   if (TYPE_NOSIGN (type))
8825                     /* GDB prints characters as NUMBER 'CHAR'.  If that's
8826                        changed, this can use value_print instead.  */
8827                     c_printchar (value, type, &buf);
8828                   else
8829                     {
8830                       struct value_print_options opts;
8831
8832                       if (baton != NULL)
8833                         v = dwarf2_evaluate_loc_desc (type, NULL,
8834                                                       baton->data,
8835                                                       baton->size,
8836                                                       baton->per_cu);
8837                       else if (bytes != NULL)
8838                         {
8839                           v = allocate_value (type);
8840                           memcpy (value_contents_writeable (v), bytes,
8841                                   TYPE_LENGTH (type));
8842                         }
8843                       else
8844                         v = value_from_longest (type, value);
8845
8846                       /* Specify decimal so that we do not depend on
8847                          the radix.  */
8848                       get_formatted_print_options (&opts, 'd');
8849                       opts.raw = 1;
8850                       value_print (v, &buf, &opts);
8851                       release_value (v);
8852                       value_free (v);
8853                     }
8854                 }
8855
8856               die->building_fullname = 0;
8857
8858               if (!first)
8859                 {
8860                   /* Close the argument list, with a space if necessary
8861                      (nested templates).  */
8862                   if (!buf.empty () && buf.string ().back () == '>')
8863                     buf.puts (" >");
8864                   else
8865                     buf.puts (">");
8866                 }
8867             }
8868
8869           /* For C++ methods, append formal parameter type
8870              information, if PHYSNAME.  */
8871
8872           if (physname && die->tag == DW_TAG_subprogram
8873               && cu->language == language_cplus)
8874             {
8875               struct type *type = read_type_die (die, cu);
8876
8877               c_type_print_args (type, &buf, 1, cu->language,
8878                                  &type_print_raw_options);
8879
8880               if (cu->language == language_cplus)
8881                 {
8882                   /* Assume that an artificial first parameter is
8883                      "this", but do not crash if it is not.  RealView
8884                      marks unnamed (and thus unused) parameters as
8885                      artificial; there is no way to differentiate
8886                      the two cases.  */
8887                   if (TYPE_NFIELDS (type) > 0
8888                       && TYPE_FIELD_ARTIFICIAL (type, 0)
8889                       && TYPE_CODE (TYPE_FIELD_TYPE (type, 0)) == TYPE_CODE_PTR
8890                       && TYPE_CONST (TYPE_TARGET_TYPE (TYPE_FIELD_TYPE (type,
8891                                                                         0))))
8892                     buf.puts (" const");
8893                 }
8894             }
8895
8896           const std::string &intermediate_name = buf.string ();
8897
8898           if (cu->language == language_cplus)
8899             canonical_name
8900               = dwarf2_canonicalize_name (intermediate_name.c_str (), cu,
8901                                           &objfile->per_bfd->storage_obstack);
8902
8903           /* If we only computed INTERMEDIATE_NAME, or if
8904              INTERMEDIATE_NAME is already canonical, then we need to
8905              copy it to the appropriate obstack.  */
8906           if (canonical_name == NULL || canonical_name == intermediate_name.c_str ())
8907             name = ((const char *)
8908                     obstack_copy0 (&objfile->per_bfd->storage_obstack,
8909                                    intermediate_name.c_str (),
8910                                    intermediate_name.length ()));
8911           else
8912             name = canonical_name;
8913         }
8914     }
8915
8916   return name;
8917 }
8918
8919 /* Return the fully qualified name of DIE, based on its DW_AT_name.
8920    If scope qualifiers are appropriate they will be added.  The result
8921    will be allocated on the storage_obstack, or NULL if the DIE does
8922    not have a name.  NAME may either be from a previous call to
8923    dwarf2_name or NULL.
8924
8925    The output string will be canonicalized (if C++).  */
8926
8927 static const char *
8928 dwarf2_full_name (const char *name, struct die_info *die, struct dwarf2_cu *cu)
8929 {
8930   return dwarf2_compute_name (name, die, cu, 0);
8931 }
8932
8933 /* Construct a physname for the given DIE in CU.  NAME may either be
8934    from a previous call to dwarf2_name or NULL.  The result will be
8935    allocated on the objfile_objstack or NULL if the DIE does not have a
8936    name.
8937
8938    The output string will be canonicalized (if C++).  */
8939
8940 static const char *
8941 dwarf2_physname (const char *name, struct die_info *die, struct dwarf2_cu *cu)
8942 {
8943   struct objfile *objfile = cu->objfile;
8944   const char *retval, *mangled = NULL, *canon = NULL;
8945   struct cleanup *back_to;
8946   int need_copy = 1;
8947
8948   /* In this case dwarf2_compute_name is just a shortcut not building anything
8949      on its own.  */
8950   if (!die_needs_namespace (die, cu))
8951     return dwarf2_compute_name (name, die, cu, 1);
8952
8953   back_to = make_cleanup (null_cleanup, NULL);
8954
8955   mangled = dwarf2_string_attr (die, DW_AT_linkage_name, cu);
8956   if (mangled == NULL)
8957     mangled = dwarf2_string_attr (die, DW_AT_MIPS_linkage_name, cu);
8958
8959   /* rustc emits invalid values for DW_AT_linkage_name.  Ignore these.
8960      See https://github.com/rust-lang/rust/issues/32925.  */
8961   if (cu->language == language_rust && mangled != NULL
8962       && strchr (mangled, '{') != NULL)
8963     mangled = NULL;
8964
8965   /* DW_AT_linkage_name is missing in some cases - depend on what GDB
8966      has computed.  */
8967   if (mangled != NULL)
8968     {
8969       char *demangled;
8970
8971       /* Use DMGL_RET_DROP for C++ template functions to suppress their return
8972          type.  It is easier for GDB users to search for such functions as
8973          `name(params)' than `long name(params)'.  In such case the minimal
8974          symbol names do not match the full symbol names but for template
8975          functions there is never a need to look up their definition from their
8976          declaration so the only disadvantage remains the minimal symbol
8977          variant `long name(params)' does not have the proper inferior type.
8978          */
8979
8980       if (cu->language == language_go)
8981         {
8982           /* This is a lie, but we already lie to the caller new_symbol_full.
8983              new_symbol_full assumes we return the mangled name.
8984              This just undoes that lie until things are cleaned up.  */
8985           demangled = NULL;
8986         }
8987       else
8988         {
8989           demangled = gdb_demangle (mangled,
8990                                     (DMGL_PARAMS | DMGL_ANSI | DMGL_RET_DROP));
8991         }
8992       if (demangled)
8993         {
8994           make_cleanup (xfree, demangled);
8995           canon = demangled;
8996         }
8997       else
8998         {
8999           canon = mangled;
9000           need_copy = 0;
9001         }
9002     }
9003
9004   if (canon == NULL || check_physname)
9005     {
9006       const char *physname = dwarf2_compute_name (name, die, cu, 1);
9007
9008       if (canon != NULL && strcmp (physname, canon) != 0)
9009         {
9010           /* It may not mean a bug in GDB.  The compiler could also
9011              compute DW_AT_linkage_name incorrectly.  But in such case
9012              GDB would need to be bug-to-bug compatible.  */
9013
9014           complaint (&symfile_complaints,
9015                      _("Computed physname <%s> does not match demangled <%s> "
9016                        "(from linkage <%s>) - DIE at 0x%x [in module %s]"),
9017                      physname, canon, mangled, to_underlying (die->sect_off),
9018                      objfile_name (objfile));
9019
9020           /* Prefer DW_AT_linkage_name (in the CANON form) - when it
9021              is available here - over computed PHYSNAME.  It is safer
9022              against both buggy GDB and buggy compilers.  */
9023
9024           retval = canon;
9025         }
9026       else
9027         {
9028           retval = physname;
9029           need_copy = 0;
9030         }
9031     }
9032   else
9033     retval = canon;
9034
9035   if (need_copy)
9036     retval = ((const char *)
9037               obstack_copy0 (&objfile->per_bfd->storage_obstack,
9038                              retval, strlen (retval)));
9039
9040   do_cleanups (back_to);
9041   return retval;
9042 }
9043
9044 /* Inspect DIE in CU for a namespace alias.  If one exists, record
9045    a new symbol for it.
9046
9047    Returns 1 if a namespace alias was recorded, 0 otherwise.  */
9048
9049 static int
9050 read_namespace_alias (struct die_info *die, struct dwarf2_cu *cu)
9051 {
9052   struct attribute *attr;
9053
9054   /* If the die does not have a name, this is not a namespace
9055      alias.  */
9056   attr = dwarf2_attr (die, DW_AT_name, cu);
9057   if (attr != NULL)
9058     {
9059       int num;
9060       struct die_info *d = die;
9061       struct dwarf2_cu *imported_cu = cu;
9062
9063       /* If the compiler has nested DW_AT_imported_declaration DIEs,
9064          keep inspecting DIEs until we hit the underlying import.  */
9065 #define MAX_NESTED_IMPORTED_DECLARATIONS 100
9066       for (num = 0; num  < MAX_NESTED_IMPORTED_DECLARATIONS; ++num)
9067         {
9068           attr = dwarf2_attr (d, DW_AT_import, cu);
9069           if (attr == NULL)
9070             break;
9071
9072           d = follow_die_ref (d, attr, &imported_cu);
9073           if (d->tag != DW_TAG_imported_declaration)
9074             break;
9075         }
9076
9077       if (num == MAX_NESTED_IMPORTED_DECLARATIONS)
9078         {
9079           complaint (&symfile_complaints,
9080                      _("DIE at 0x%x has too many recursively imported "
9081                        "declarations"), to_underlying (d->sect_off));
9082           return 0;
9083         }
9084
9085       if (attr != NULL)
9086         {
9087           struct type *type;
9088           sect_offset sect_off = dwarf2_get_ref_die_offset (attr);
9089
9090           type = get_die_type_at_offset (sect_off, cu->per_cu);
9091           if (type != NULL && TYPE_CODE (type) == TYPE_CODE_NAMESPACE)
9092             {
9093               /* This declaration is a global namespace alias.  Add
9094                  a symbol for it whose type is the aliased namespace.  */
9095               new_symbol (die, type, cu);
9096               return 1;
9097             }
9098         }
9099     }
9100
9101   return 0;
9102 }
9103
9104 /* Return the using directives repository (global or local?) to use in the
9105    current context for LANGUAGE.
9106
9107    For Ada, imported declarations can materialize renamings, which *may* be
9108    global.  However it is impossible (for now?) in DWARF to distinguish
9109    "external" imported declarations and "static" ones.  As all imported
9110    declarations seem to be static in all other languages, make them all CU-wide
9111    global only in Ada.  */
9112
9113 static struct using_direct **
9114 using_directives (enum language language)
9115 {
9116   if (language == language_ada && context_stack_depth == 0)
9117     return &global_using_directives;
9118   else
9119     return &local_using_directives;
9120 }
9121
9122 /* Read the import statement specified by the given die and record it.  */
9123
9124 static void
9125 read_import_statement (struct die_info *die, struct dwarf2_cu *cu)
9126 {
9127   struct objfile *objfile = cu->objfile;
9128   struct attribute *import_attr;
9129   struct die_info *imported_die, *child_die;
9130   struct dwarf2_cu *imported_cu;
9131   const char *imported_name;
9132   const char *imported_name_prefix;
9133   const char *canonical_name;
9134   const char *import_alias;
9135   const char *imported_declaration = NULL;
9136   const char *import_prefix;
9137   VEC (const_char_ptr) *excludes = NULL;
9138   struct cleanup *cleanups;
9139
9140   import_attr = dwarf2_attr (die, DW_AT_import, cu);
9141   if (import_attr == NULL)
9142     {
9143       complaint (&symfile_complaints, _("Tag '%s' has no DW_AT_import"),
9144                  dwarf_tag_name (die->tag));
9145       return;
9146     }
9147
9148   imported_cu = cu;
9149   imported_die = follow_die_ref_or_sig (die, import_attr, &imported_cu);
9150   imported_name = dwarf2_name (imported_die, imported_cu);
9151   if (imported_name == NULL)
9152     {
9153       /* GCC bug: https://bugzilla.redhat.com/show_bug.cgi?id=506524
9154
9155         The import in the following code:
9156         namespace A
9157           {
9158             typedef int B;
9159           }
9160
9161         int main ()
9162           {
9163             using A::B;
9164             B b;
9165             return b;
9166           }
9167
9168         ...
9169          <2><51>: Abbrev Number: 3 (DW_TAG_imported_declaration)
9170             <52>   DW_AT_decl_file   : 1
9171             <53>   DW_AT_decl_line   : 6
9172             <54>   DW_AT_import      : <0x75>
9173          <2><58>: Abbrev Number: 4 (DW_TAG_typedef)
9174             <59>   DW_AT_name        : B
9175             <5b>   DW_AT_decl_file   : 1
9176             <5c>   DW_AT_decl_line   : 2
9177             <5d>   DW_AT_type        : <0x6e>
9178         ...
9179          <1><75>: Abbrev Number: 7 (DW_TAG_base_type)
9180             <76>   DW_AT_byte_size   : 4
9181             <77>   DW_AT_encoding    : 5        (signed)
9182
9183         imports the wrong die ( 0x75 instead of 0x58 ).
9184         This case will be ignored until the gcc bug is fixed.  */
9185       return;
9186     }
9187
9188   /* Figure out the local name after import.  */
9189   import_alias = dwarf2_name (die, cu);
9190
9191   /* Figure out where the statement is being imported to.  */
9192   import_prefix = determine_prefix (die, cu);
9193
9194   /* Figure out what the scope of the imported die is and prepend it
9195      to the name of the imported die.  */
9196   imported_name_prefix = determine_prefix (imported_die, imported_cu);
9197
9198   if (imported_die->tag != DW_TAG_namespace
9199       && imported_die->tag != DW_TAG_module)
9200     {
9201       imported_declaration = imported_name;
9202       canonical_name = imported_name_prefix;
9203     }
9204   else if (strlen (imported_name_prefix) > 0)
9205     canonical_name = obconcat (&objfile->objfile_obstack,
9206                                imported_name_prefix,
9207                                (cu->language == language_d ? "." : "::"),
9208                                imported_name, (char *) NULL);
9209   else
9210     canonical_name = imported_name;
9211
9212   cleanups = make_cleanup (VEC_cleanup (const_char_ptr), &excludes);
9213
9214   if (die->tag == DW_TAG_imported_module && cu->language == language_fortran)
9215     for (child_die = die->child; child_die && child_die->tag;
9216          child_die = sibling_die (child_die))
9217       {
9218         /* DWARF-4: A Fortran use statement with a “rename list” may be
9219            represented by an imported module entry with an import attribute
9220            referring to the module and owned entries corresponding to those
9221            entities that are renamed as part of being imported.  */
9222
9223         if (child_die->tag != DW_TAG_imported_declaration)
9224           {
9225             complaint (&symfile_complaints,
9226                        _("child DW_TAG_imported_declaration expected "
9227                          "- DIE at 0x%x [in module %s]"),
9228                        to_underlying (child_die->sect_off), objfile_name (objfile));
9229             continue;
9230           }
9231
9232         import_attr = dwarf2_attr (child_die, DW_AT_import, cu);
9233         if (import_attr == NULL)
9234           {
9235             complaint (&symfile_complaints, _("Tag '%s' has no DW_AT_import"),
9236                        dwarf_tag_name (child_die->tag));
9237             continue;
9238           }
9239
9240         imported_cu = cu;
9241         imported_die = follow_die_ref_or_sig (child_die, import_attr,
9242                                               &imported_cu);
9243         imported_name = dwarf2_name (imported_die, imported_cu);
9244         if (imported_name == NULL)
9245           {
9246             complaint (&symfile_complaints,
9247                        _("child DW_TAG_imported_declaration has unknown "
9248                          "imported name - DIE at 0x%x [in module %s]"),
9249                        to_underlying (child_die->sect_off), objfile_name (objfile));
9250             continue;
9251           }
9252
9253         VEC_safe_push (const_char_ptr, excludes, imported_name);
9254
9255         process_die (child_die, cu);
9256       }
9257
9258   add_using_directive (using_directives (cu->language),
9259                        import_prefix,
9260                        canonical_name,
9261                        import_alias,
9262                        imported_declaration,
9263                        excludes,
9264                        0,
9265                        &objfile->objfile_obstack);
9266
9267   do_cleanups (cleanups);
9268 }
9269
9270 /* Check for possibly missing DW_AT_comp_dir with relative .debug_line
9271    directory paths.  GCC SVN r127613 (new option -fdebug-prefix-map) fixed
9272    this, it was first present in GCC release 4.3.0.  */
9273
9274 static int
9275 producer_is_gcc_lt_4_3 (struct dwarf2_cu *cu)
9276 {
9277   if (!cu->checked_producer)
9278     check_producer (cu);
9279
9280   return cu->producer_is_gcc_lt_4_3;
9281 }
9282
9283 static file_and_directory
9284 find_file_and_directory (struct die_info *die, struct dwarf2_cu *cu)
9285 {
9286   file_and_directory res;
9287
9288   /* Find the filename.  Do not use dwarf2_name here, since the filename
9289      is not a source language identifier.  */
9290   res.name = dwarf2_string_attr (die, DW_AT_name, cu);
9291   res.comp_dir = dwarf2_string_attr (die, DW_AT_comp_dir, cu);
9292
9293   if (res.comp_dir == NULL
9294       && producer_is_gcc_lt_4_3 (cu) && res.name != NULL
9295       && IS_ABSOLUTE_PATH (res.name))
9296     {
9297       res.comp_dir_storage = ldirname (res.name);
9298       if (!res.comp_dir_storage.empty ())
9299         res.comp_dir = res.comp_dir_storage.c_str ();
9300     }
9301   if (res.comp_dir != NULL)
9302     {
9303       /* Irix 6.2 native cc prepends <machine>.: to the compilation
9304          directory, get rid of it.  */
9305       const char *cp = strchr (res.comp_dir, ':');
9306
9307       if (cp && cp != res.comp_dir && cp[-1] == '.' && cp[1] == '/')
9308         res.comp_dir = cp + 1;
9309     }
9310
9311   if (res.name == NULL)
9312     res.name = "<unknown>";
9313
9314   return res;
9315 }
9316
9317 /* Handle DW_AT_stmt_list for a compilation unit.
9318    DIE is the DW_TAG_compile_unit die for CU.
9319    COMP_DIR is the compilation directory.  LOWPC is passed to
9320    dwarf_decode_lines.  See dwarf_decode_lines comments about it.  */
9321
9322 static void
9323 handle_DW_AT_stmt_list (struct die_info *die, struct dwarf2_cu *cu,
9324                         const char *comp_dir, CORE_ADDR lowpc) /* ARI: editCase function */
9325 {
9326   struct objfile *objfile = dwarf2_per_objfile->objfile;
9327   struct attribute *attr;
9328   struct line_header line_header_local;
9329   hashval_t line_header_local_hash;
9330   unsigned u;
9331   void **slot;
9332   int decode_mapping;
9333
9334   gdb_assert (! cu->per_cu->is_debug_types);
9335
9336   attr = dwarf2_attr (die, DW_AT_stmt_list, cu);
9337   if (attr == NULL)
9338     return;
9339
9340   sect_offset line_offset = (sect_offset) DW_UNSND (attr);
9341
9342   /* The line header hash table is only created if needed (it exists to
9343      prevent redundant reading of the line table for partial_units).
9344      If we're given a partial_unit, we'll need it.  If we're given a
9345      compile_unit, then use the line header hash table if it's already
9346      created, but don't create one just yet.  */
9347
9348   if (dwarf2_per_objfile->line_header_hash == NULL
9349       && die->tag == DW_TAG_partial_unit)
9350     {
9351       dwarf2_per_objfile->line_header_hash
9352         = htab_create_alloc_ex (127, line_header_hash_voidp,
9353                                 line_header_eq_voidp,
9354                                 free_line_header_voidp,
9355                                 &objfile->objfile_obstack,
9356                                 hashtab_obstack_allocate,
9357                                 dummy_obstack_deallocate);
9358     }
9359
9360   line_header_local.sect_off = line_offset;
9361   line_header_local.offset_in_dwz = cu->per_cu->is_dwz;
9362   line_header_local_hash = line_header_hash (&line_header_local);
9363   if (dwarf2_per_objfile->line_header_hash != NULL)
9364     {
9365       slot = htab_find_slot_with_hash (dwarf2_per_objfile->line_header_hash,
9366                                        &line_header_local,
9367                                        line_header_local_hash, NO_INSERT);
9368
9369       /* For DW_TAG_compile_unit we need info like symtab::linetable which
9370          is not present in *SLOT (since if there is something in *SLOT then
9371          it will be for a partial_unit).  */
9372       if (die->tag == DW_TAG_partial_unit && slot != NULL)
9373         {
9374           gdb_assert (*slot != NULL);
9375           cu->line_header = (struct line_header *) *slot;
9376           return;
9377         }
9378     }
9379
9380   /* dwarf_decode_line_header does not yet provide sufficient information.
9381      We always have to call also dwarf_decode_lines for it.  */
9382   line_header_up lh = dwarf_decode_line_header (line_offset, cu);
9383   if (lh == NULL)
9384     return;
9385
9386   cu->line_header = lh.release ();
9387   cu->line_header_die_owner = die;
9388
9389   if (dwarf2_per_objfile->line_header_hash == NULL)
9390     slot = NULL;
9391   else
9392     {
9393       slot = htab_find_slot_with_hash (dwarf2_per_objfile->line_header_hash,
9394                                        &line_header_local,
9395                                        line_header_local_hash, INSERT);
9396       gdb_assert (slot != NULL);
9397     }
9398   if (slot != NULL && *slot == NULL)
9399     {
9400       /* This newly decoded line number information unit will be owned
9401          by line_header_hash hash table.  */
9402       *slot = cu->line_header;
9403       cu->line_header_die_owner = NULL;
9404     }
9405   else
9406     {
9407       /* We cannot free any current entry in (*slot) as that struct line_header
9408          may be already used by multiple CUs.  Create only temporary decoded
9409          line_header for this CU - it may happen at most once for each line
9410          number information unit.  And if we're not using line_header_hash
9411          then this is what we want as well.  */
9412       gdb_assert (die->tag != DW_TAG_partial_unit);
9413     }
9414   decode_mapping = (die->tag != DW_TAG_partial_unit);
9415   dwarf_decode_lines (cu->line_header, comp_dir, cu, NULL, lowpc,
9416                       decode_mapping);
9417
9418 }
9419
9420 /* Process DW_TAG_compile_unit or DW_TAG_partial_unit.  */
9421
9422 static void
9423 read_file_scope (struct die_info *die, struct dwarf2_cu *cu)
9424 {
9425   struct objfile *objfile = dwarf2_per_objfile->objfile;
9426   struct gdbarch *gdbarch = get_objfile_arch (objfile);
9427   CORE_ADDR lowpc = ((CORE_ADDR) -1);
9428   CORE_ADDR highpc = ((CORE_ADDR) 0);
9429   struct attribute *attr;
9430   struct die_info *child_die;
9431   CORE_ADDR baseaddr;
9432
9433   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
9434
9435   get_scope_pc_bounds (die, &lowpc, &highpc, cu);
9436
9437   /* If we didn't find a lowpc, set it to highpc to avoid complaints
9438      from finish_block.  */
9439   if (lowpc == ((CORE_ADDR) -1))
9440     lowpc = highpc;
9441   lowpc = gdbarch_adjust_dwarf2_addr (gdbarch, lowpc + baseaddr);
9442
9443   file_and_directory fnd = find_file_and_directory (die, cu);
9444
9445   prepare_one_comp_unit (cu, die, cu->language);
9446
9447   /* The XLCL doesn't generate DW_LANG_OpenCL because this attribute is not
9448      standardised yet.  As a workaround for the language detection we fall
9449      back to the DW_AT_producer string.  */
9450   if (cu->producer && strstr (cu->producer, "IBM XL C for OpenCL") != NULL)
9451     cu->language = language_opencl;
9452
9453   /* Similar hack for Go.  */
9454   if (cu->producer && strstr (cu->producer, "GNU Go ") != NULL)
9455     set_cu_language (DW_LANG_Go, cu);
9456
9457   dwarf2_start_symtab (cu, fnd.name, fnd.comp_dir, lowpc);
9458
9459   /* Decode line number information if present.  We do this before
9460      processing child DIEs, so that the line header table is available
9461      for DW_AT_decl_file.  */
9462   handle_DW_AT_stmt_list (die, cu, fnd.comp_dir, lowpc);
9463
9464   /* Process all dies in compilation unit.  */
9465   if (die->child != NULL)
9466     {
9467       child_die = die->child;
9468       while (child_die && child_die->tag)
9469         {
9470           process_die (child_die, cu);
9471           child_die = sibling_die (child_die);
9472         }
9473     }
9474
9475   /* Decode macro information, if present.  Dwarf 2 macro information
9476      refers to information in the line number info statement program
9477      header, so we can only read it if we've read the header
9478      successfully.  */
9479   attr = dwarf2_attr (die, DW_AT_macros, cu);
9480   if (attr == NULL)
9481     attr = dwarf2_attr (die, DW_AT_GNU_macros, cu);
9482   if (attr && cu->line_header)
9483     {
9484       if (dwarf2_attr (die, DW_AT_macro_info, cu))
9485         complaint (&symfile_complaints,
9486                    _("CU refers to both DW_AT_macros and DW_AT_macro_info"));
9487
9488       dwarf_decode_macros (cu, DW_UNSND (attr), 1);
9489     }
9490   else
9491     {
9492       attr = dwarf2_attr (die, DW_AT_macro_info, cu);
9493       if (attr && cu->line_header)
9494         {
9495           unsigned int macro_offset = DW_UNSND (attr);
9496
9497           dwarf_decode_macros (cu, macro_offset, 0);
9498         }
9499     }
9500 }
9501
9502 /* TU version of handle_DW_AT_stmt_list for read_type_unit_scope.
9503    Create the set of symtabs used by this TU, or if this TU is sharing
9504    symtabs with another TU and the symtabs have already been created
9505    then restore those symtabs in the line header.
9506    We don't need the pc/line-number mapping for type units.  */
9507
9508 static void
9509 setup_type_unit_groups (struct die_info *die, struct dwarf2_cu *cu)
9510 {
9511   struct dwarf2_per_cu_data *per_cu = cu->per_cu;
9512   struct type_unit_group *tu_group;
9513   int first_time;
9514   struct attribute *attr;
9515   unsigned int i;
9516   struct signatured_type *sig_type;
9517
9518   gdb_assert (per_cu->is_debug_types);
9519   sig_type = (struct signatured_type *) per_cu;
9520
9521   attr = dwarf2_attr (die, DW_AT_stmt_list, cu);
9522
9523   /* If we're using .gdb_index (includes -readnow) then
9524      per_cu->type_unit_group may not have been set up yet.  */
9525   if (sig_type->type_unit_group == NULL)
9526     sig_type->type_unit_group = get_type_unit_group (cu, attr);
9527   tu_group = sig_type->type_unit_group;
9528
9529   /* If we've already processed this stmt_list there's no real need to
9530      do it again, we could fake it and just recreate the part we need
9531      (file name,index -> symtab mapping).  If data shows this optimization
9532      is useful we can do it then.  */
9533   first_time = tu_group->compunit_symtab == NULL;
9534
9535   /* We have to handle the case of both a missing DW_AT_stmt_list or bad
9536      debug info.  */
9537   line_header_up lh;
9538   if (attr != NULL)
9539     {
9540       sect_offset line_offset = (sect_offset) DW_UNSND (attr);
9541       lh = dwarf_decode_line_header (line_offset, cu);
9542     }
9543   if (lh == NULL)
9544     {
9545       if (first_time)
9546         dwarf2_start_symtab (cu, "", NULL, 0);
9547       else
9548         {
9549           gdb_assert (tu_group->symtabs == NULL);
9550           restart_symtab (tu_group->compunit_symtab, "", 0);
9551         }
9552       return;
9553     }
9554
9555   cu->line_header = lh.release ();
9556   cu->line_header_die_owner = die;
9557
9558   if (first_time)
9559     {
9560       struct compunit_symtab *cust = dwarf2_start_symtab (cu, "", NULL, 0);
9561
9562       /* Note: We don't assign tu_group->compunit_symtab yet because we're
9563          still initializing it, and our caller (a few levels up)
9564          process_full_type_unit still needs to know if this is the first
9565          time.  */
9566
9567       tu_group->num_symtabs = cu->line_header->file_names.size ();
9568       tu_group->symtabs = XNEWVEC (struct symtab *,
9569                                    cu->line_header->file_names.size ());
9570
9571       for (i = 0; i < cu->line_header->file_names.size (); ++i)
9572         {
9573           file_entry &fe = cu->line_header->file_names[i];
9574
9575           dwarf2_start_subfile (fe.name, fe.include_dir (cu->line_header));
9576
9577           if (current_subfile->symtab == NULL)
9578             {
9579               /* NOTE: start_subfile will recognize when it's been
9580                  passed a file it has already seen.  So we can't
9581                  assume there's a simple mapping from
9582                  cu->line_header->file_names to subfiles, plus
9583                  cu->line_header->file_names may contain dups.  */
9584               current_subfile->symtab
9585                 = allocate_symtab (cust, current_subfile->name);
9586             }
9587
9588           fe.symtab = current_subfile->symtab;
9589           tu_group->symtabs[i] = fe.symtab;
9590         }
9591     }
9592   else
9593     {
9594       restart_symtab (tu_group->compunit_symtab, "", 0);
9595
9596       for (i = 0; i < cu->line_header->file_names.size (); ++i)
9597         {
9598           file_entry &fe = cu->line_header->file_names[i];
9599
9600           fe.symtab = tu_group->symtabs[i];
9601         }
9602     }
9603
9604   /* The main symtab is allocated last.  Type units don't have DW_AT_name
9605      so they don't have a "real" (so to speak) symtab anyway.
9606      There is later code that will assign the main symtab to all symbols
9607      that don't have one.  We need to handle the case of a symbol with a
9608      missing symtab (DW_AT_decl_file) anyway.  */
9609 }
9610
9611 /* Process DW_TAG_type_unit.
9612    For TUs we want to skip the first top level sibling if it's not the
9613    actual type being defined by this TU.  In this case the first top
9614    level sibling is there to provide context only.  */
9615
9616 static void
9617 read_type_unit_scope (struct die_info *die, struct dwarf2_cu *cu)
9618 {
9619   struct die_info *child_die;
9620
9621   prepare_one_comp_unit (cu, die, language_minimal);
9622
9623   /* Initialize (or reinitialize) the machinery for building symtabs.
9624      We do this before processing child DIEs, so that the line header table
9625      is available for DW_AT_decl_file.  */
9626   setup_type_unit_groups (die, cu);
9627
9628   if (die->child != NULL)
9629     {
9630       child_die = die->child;
9631       while (child_die && child_die->tag)
9632         {
9633           process_die (child_die, cu);
9634           child_die = sibling_die (child_die);
9635         }
9636     }
9637 }
9638 \f
9639 /* DWO/DWP files.
9640
9641    http://gcc.gnu.org/wiki/DebugFission
9642    http://gcc.gnu.org/wiki/DebugFissionDWP
9643
9644    To simplify handling of both DWO files ("object" files with the DWARF info)
9645    and DWP files (a file with the DWOs packaged up into one file), we treat
9646    DWP files as having a collection of virtual DWO files.  */
9647
9648 static hashval_t
9649 hash_dwo_file (const void *item)
9650 {
9651   const struct dwo_file *dwo_file = (const struct dwo_file *) item;
9652   hashval_t hash;
9653
9654   hash = htab_hash_string (dwo_file->dwo_name);
9655   if (dwo_file->comp_dir != NULL)
9656     hash += htab_hash_string (dwo_file->comp_dir);
9657   return hash;
9658 }
9659
9660 static int
9661 eq_dwo_file (const void *item_lhs, const void *item_rhs)
9662 {
9663   const struct dwo_file *lhs = (const struct dwo_file *) item_lhs;
9664   const struct dwo_file *rhs = (const struct dwo_file *) item_rhs;
9665
9666   if (strcmp (lhs->dwo_name, rhs->dwo_name) != 0)
9667     return 0;
9668   if (lhs->comp_dir == NULL || rhs->comp_dir == NULL)
9669     return lhs->comp_dir == rhs->comp_dir;
9670   return strcmp (lhs->comp_dir, rhs->comp_dir) == 0;
9671 }
9672
9673 /* Allocate a hash table for DWO files.  */
9674
9675 static htab_t
9676 allocate_dwo_file_hash_table (void)
9677 {
9678   struct objfile *objfile = dwarf2_per_objfile->objfile;
9679
9680   return htab_create_alloc_ex (41,
9681                                hash_dwo_file,
9682                                eq_dwo_file,
9683                                NULL,
9684                                &objfile->objfile_obstack,
9685                                hashtab_obstack_allocate,
9686                                dummy_obstack_deallocate);
9687 }
9688
9689 /* Lookup DWO file DWO_NAME.  */
9690
9691 static void **
9692 lookup_dwo_file_slot (const char *dwo_name, const char *comp_dir)
9693 {
9694   struct dwo_file find_entry;
9695   void **slot;
9696
9697   if (dwarf2_per_objfile->dwo_files == NULL)
9698     dwarf2_per_objfile->dwo_files = allocate_dwo_file_hash_table ();
9699
9700   memset (&find_entry, 0, sizeof (find_entry));
9701   find_entry.dwo_name = dwo_name;
9702   find_entry.comp_dir = comp_dir;
9703   slot = htab_find_slot (dwarf2_per_objfile->dwo_files, &find_entry, INSERT);
9704
9705   return slot;
9706 }
9707
9708 static hashval_t
9709 hash_dwo_unit (const void *item)
9710 {
9711   const struct dwo_unit *dwo_unit = (const struct dwo_unit *) item;
9712
9713   /* This drops the top 32 bits of the id, but is ok for a hash.  */
9714   return dwo_unit->signature;
9715 }
9716
9717 static int
9718 eq_dwo_unit (const void *item_lhs, const void *item_rhs)
9719 {
9720   const struct dwo_unit *lhs = (const struct dwo_unit *) item_lhs;
9721   const struct dwo_unit *rhs = (const struct dwo_unit *) item_rhs;
9722
9723   /* The signature is assumed to be unique within the DWO file.
9724      So while object file CU dwo_id's always have the value zero,
9725      that's OK, assuming each object file DWO file has only one CU,
9726      and that's the rule for now.  */
9727   return lhs->signature == rhs->signature;
9728 }
9729
9730 /* Allocate a hash table for DWO CUs,TUs.
9731    There is one of these tables for each of CUs,TUs for each DWO file.  */
9732
9733 static htab_t
9734 allocate_dwo_unit_table (struct objfile *objfile)
9735 {
9736   /* Start out with a pretty small number.
9737      Generally DWO files contain only one CU and maybe some TUs.  */
9738   return htab_create_alloc_ex (3,
9739                                hash_dwo_unit,
9740                                eq_dwo_unit,
9741                                NULL,
9742                                &objfile->objfile_obstack,
9743                                hashtab_obstack_allocate,
9744                                dummy_obstack_deallocate);
9745 }
9746
9747 /* Structure used to pass data to create_dwo_debug_info_hash_table_reader.  */
9748
9749 struct create_dwo_cu_data
9750 {
9751   struct dwo_file *dwo_file;
9752   struct dwo_unit dwo_unit;
9753 };
9754
9755 /* die_reader_func for create_dwo_cu.  */
9756
9757 static void
9758 create_dwo_cu_reader (const struct die_reader_specs *reader,
9759                       const gdb_byte *info_ptr,
9760                       struct die_info *comp_unit_die,
9761                       int has_children,
9762                       void *datap)
9763 {
9764   struct dwarf2_cu *cu = reader->cu;
9765   sect_offset sect_off = cu->per_cu->sect_off;
9766   struct dwarf2_section_info *section = cu->per_cu->section;
9767   struct create_dwo_cu_data *data = (struct create_dwo_cu_data *) datap;
9768   struct dwo_file *dwo_file = data->dwo_file;
9769   struct dwo_unit *dwo_unit = &data->dwo_unit;
9770   struct attribute *attr;
9771
9772   attr = dwarf2_attr (comp_unit_die, DW_AT_GNU_dwo_id, cu);
9773   if (attr == NULL)
9774     {
9775       complaint (&symfile_complaints,
9776                  _("Dwarf Error: debug entry at offset 0x%x is missing"
9777                    " its dwo_id [in module %s]"),
9778                  to_underlying (sect_off), dwo_file->dwo_name);
9779       return;
9780     }
9781
9782   dwo_unit->dwo_file = dwo_file;
9783   dwo_unit->signature = DW_UNSND (attr);
9784   dwo_unit->section = section;
9785   dwo_unit->sect_off = sect_off;
9786   dwo_unit->length = cu->per_cu->length;
9787
9788   if (dwarf_read_debug)
9789     fprintf_unfiltered (gdb_stdlog, "  offset 0x%x, dwo_id %s\n",
9790                         to_underlying (sect_off),
9791                         hex_string (dwo_unit->signature));
9792 }
9793
9794 /* Create the dwo_units for the CUs in a DWO_FILE.
9795    Note: This function processes DWO files only, not DWP files.  */
9796
9797 static void
9798 create_cus_hash_table (struct dwo_file &dwo_file, dwarf2_section_info &section,
9799                        htab_t &cus_htab)
9800 {
9801   struct objfile *objfile = dwarf2_per_objfile->objfile;
9802   const struct dwarf2_section_info *abbrev_section = &dwo_file.sections.abbrev;
9803   const gdb_byte *info_ptr, *end_ptr;
9804
9805   dwarf2_read_section (objfile, &section);
9806   info_ptr = section.buffer;
9807
9808   if (info_ptr == NULL)
9809     return;
9810
9811   if (dwarf_read_debug)
9812     {
9813       fprintf_unfiltered (gdb_stdlog, "Reading %s for %s:\n",
9814                           get_section_name (&section),
9815                           get_section_file_name (&section));
9816     }
9817
9818   end_ptr = info_ptr + section.size;
9819   while (info_ptr < end_ptr)
9820     {
9821       struct dwarf2_per_cu_data per_cu;
9822       struct create_dwo_cu_data create_dwo_cu_data;
9823       struct dwo_unit *dwo_unit;
9824       void **slot;
9825       sect_offset sect_off = (sect_offset) (info_ptr - section.buffer);
9826
9827       memset (&create_dwo_cu_data.dwo_unit, 0,
9828               sizeof (create_dwo_cu_data.dwo_unit));
9829       memset (&per_cu, 0, sizeof (per_cu));
9830       per_cu.objfile = objfile;
9831       per_cu.is_debug_types = 0;
9832       per_cu.sect_off = sect_offset (info_ptr - section.buffer);
9833       per_cu.section = &section;
9834       create_dwo_cu_data.dwo_file = &dwo_file;
9835
9836       init_cutu_and_read_dies_no_follow (
9837           &per_cu, &dwo_file, create_dwo_cu_reader, &create_dwo_cu_data);
9838       info_ptr += per_cu.length;
9839
9840       // If the unit could not be parsed, skip it.
9841       if (create_dwo_cu_data.dwo_unit.dwo_file == NULL)
9842         continue;
9843
9844       if (cus_htab == NULL)
9845         cus_htab = allocate_dwo_unit_table (objfile);
9846
9847       dwo_unit = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_unit);
9848       *dwo_unit = create_dwo_cu_data.dwo_unit;
9849       slot = htab_find_slot (cus_htab, dwo_unit, INSERT);
9850       gdb_assert (slot != NULL);
9851       if (*slot != NULL)
9852         {
9853           const struct dwo_unit *dup_cu = (const struct dwo_unit *)*slot;
9854           sect_offset dup_sect_off = dup_cu->sect_off;
9855
9856           complaint (&symfile_complaints,
9857                      _("debug cu entry at offset 0x%x is duplicate to"
9858                        " the entry at offset 0x%x, signature %s"),
9859                      to_underlying (sect_off), to_underlying (dup_sect_off),
9860                      hex_string (dwo_unit->signature));
9861         }
9862       *slot = (void *)dwo_unit;
9863     }
9864 }
9865
9866 /* DWP file .debug_{cu,tu}_index section format:
9867    [ref: http://gcc.gnu.org/wiki/DebugFissionDWP]
9868
9869    DWP Version 1:
9870
9871    Both index sections have the same format, and serve to map a 64-bit
9872    signature to a set of section numbers.  Each section begins with a header,
9873    followed by a hash table of 64-bit signatures, a parallel table of 32-bit
9874    indexes, and a pool of 32-bit section numbers.  The index sections will be
9875    aligned at 8-byte boundaries in the file.
9876
9877    The index section header consists of:
9878
9879     V, 32 bit version number
9880     -, 32 bits unused
9881     N, 32 bit number of compilation units or type units in the index
9882     M, 32 bit number of slots in the hash table
9883
9884    Numbers are recorded using the byte order of the application binary.
9885
9886    The hash table begins at offset 16 in the section, and consists of an array
9887    of M 64-bit slots.  Each slot contains a 64-bit signature (using the byte
9888    order of the application binary).  Unused slots in the hash table are 0.
9889    (We rely on the extreme unlikeliness of a signature being exactly 0.)
9890
9891    The parallel table begins immediately after the hash table
9892    (at offset 16 + 8 * M from the beginning of the section), and consists of an
9893    array of 32-bit indexes (using the byte order of the application binary),
9894    corresponding 1-1 with slots in the hash table.  Each entry in the parallel
9895    table contains a 32-bit index into the pool of section numbers.  For unused
9896    hash table slots, the corresponding entry in the parallel table will be 0.
9897
9898    The pool of section numbers begins immediately following the hash table
9899    (at offset 16 + 12 * M from the beginning of the section).  The pool of
9900    section numbers consists of an array of 32-bit words (using the byte order
9901    of the application binary).  Each item in the array is indexed starting
9902    from 0.  The hash table entry provides the index of the first section
9903    number in the set.  Additional section numbers in the set follow, and the
9904    set is terminated by a 0 entry (section number 0 is not used in ELF).
9905
9906    In each set of section numbers, the .debug_info.dwo or .debug_types.dwo
9907    section must be the first entry in the set, and the .debug_abbrev.dwo must
9908    be the second entry. Other members of the set may follow in any order.
9909
9910    ---
9911
9912    DWP Version 2:
9913
9914    DWP Version 2 combines all the .debug_info, etc. sections into one,
9915    and the entries in the index tables are now offsets into these sections.
9916    CU offsets begin at 0.  TU offsets begin at the size of the .debug_info
9917    section.
9918
9919    Index Section Contents:
9920     Header
9921     Hash Table of Signatures   dwp_hash_table.hash_table
9922     Parallel Table of Indices  dwp_hash_table.unit_table
9923     Table of Section Offsets   dwp_hash_table.v2.{section_ids,offsets}
9924     Table of Section Sizes     dwp_hash_table.v2.sizes
9925
9926    The index section header consists of:
9927
9928     V, 32 bit version number
9929     L, 32 bit number of columns in the table of section offsets
9930     N, 32 bit number of compilation units or type units in the index
9931     M, 32 bit number of slots in the hash table
9932
9933    Numbers are recorded using the byte order of the application binary.
9934
9935    The hash table has the same format as version 1.
9936    The parallel table of indices has the same format as version 1,
9937    except that the entries are origin-1 indices into the table of sections
9938    offsets and the table of section sizes.
9939
9940    The table of offsets begins immediately following the parallel table
9941    (at offset 16 + 12 * M from the beginning of the section).  The table is
9942    a two-dimensional array of 32-bit words (using the byte order of the
9943    application binary), with L columns and N+1 rows, in row-major order.
9944    Each row in the array is indexed starting from 0.  The first row provides
9945    a key to the remaining rows: each column in this row provides an identifier
9946    for a debug section, and the offsets in the same column of subsequent rows
9947    refer to that section.  The section identifiers are:
9948
9949     DW_SECT_INFO         1  .debug_info.dwo
9950     DW_SECT_TYPES        2  .debug_types.dwo
9951     DW_SECT_ABBREV       3  .debug_abbrev.dwo
9952     DW_SECT_LINE         4  .debug_line.dwo
9953     DW_SECT_LOC          5  .debug_loc.dwo
9954     DW_SECT_STR_OFFSETS  6  .debug_str_offsets.dwo
9955     DW_SECT_MACINFO      7  .debug_macinfo.dwo
9956     DW_SECT_MACRO        8  .debug_macro.dwo
9957
9958    The offsets provided by the CU and TU index sections are the base offsets
9959    for the contributions made by each CU or TU to the corresponding section
9960    in the package file.  Each CU and TU header contains an abbrev_offset
9961    field, used to find the abbreviations table for that CU or TU within the
9962    contribution to the .debug_abbrev.dwo section for that CU or TU, and should
9963    be interpreted as relative to the base offset given in the index section.
9964    Likewise, offsets into .debug_line.dwo from DW_AT_stmt_list attributes
9965    should be interpreted as relative to the base offset for .debug_line.dwo,
9966    and offsets into other debug sections obtained from DWARF attributes should
9967    also be interpreted as relative to the corresponding base offset.
9968
9969    The table of sizes begins immediately following the table of offsets.
9970    Like the table of offsets, it is a two-dimensional array of 32-bit words,
9971    with L columns and N rows, in row-major order.  Each row in the array is
9972    indexed starting from 1 (row 0 is shared by the two tables).
9973
9974    ---
9975
9976    Hash table lookup is handled the same in version 1 and 2:
9977
9978    We assume that N and M will not exceed 2^32 - 1.
9979    The size of the hash table, M, must be 2^k such that 2^k > 3*N/2.
9980
9981    Given a 64-bit compilation unit signature or a type signature S, an entry
9982    in the hash table is located as follows:
9983
9984    1) Calculate a primary hash H = S & MASK(k), where MASK(k) is a mask with
9985       the low-order k bits all set to 1.
9986
9987    2) Calculate a secondary hash H' = (((S >> 32) & MASK(k)) | 1).
9988
9989    3) If the hash table entry at index H matches the signature, use that
9990       entry.  If the hash table entry at index H is unused (all zeroes),
9991       terminate the search: the signature is not present in the table.
9992
9993    4) Let H = (H + H') modulo M. Repeat at Step 3.
9994
9995    Because M > N and H' and M are relatively prime, the search is guaranteed
9996    to stop at an unused slot or find the match.  */
9997
9998 /* Create a hash table to map DWO IDs to their CU/TU entry in
9999    .debug_{info,types}.dwo in DWP_FILE.
10000    Returns NULL if there isn't one.
10001    Note: This function processes DWP files only, not DWO files.  */
10002
10003 static struct dwp_hash_table *
10004 create_dwp_hash_table (struct dwp_file *dwp_file, int is_debug_types)
10005 {
10006   struct objfile *objfile = dwarf2_per_objfile->objfile;
10007   bfd *dbfd = dwp_file->dbfd;
10008   const gdb_byte *index_ptr, *index_end;
10009   struct dwarf2_section_info *index;
10010   uint32_t version, nr_columns, nr_units, nr_slots;
10011   struct dwp_hash_table *htab;
10012
10013   if (is_debug_types)
10014     index = &dwp_file->sections.tu_index;
10015   else
10016     index = &dwp_file->sections.cu_index;
10017
10018   if (dwarf2_section_empty_p (index))
10019     return NULL;
10020   dwarf2_read_section (objfile, index);
10021
10022   index_ptr = index->buffer;
10023   index_end = index_ptr + index->size;
10024
10025   version = read_4_bytes (dbfd, index_ptr);
10026   index_ptr += 4;
10027   if (version == 2)
10028     nr_columns = read_4_bytes (dbfd, index_ptr);
10029   else
10030     nr_columns = 0;
10031   index_ptr += 4;
10032   nr_units = read_4_bytes (dbfd, index_ptr);
10033   index_ptr += 4;
10034   nr_slots = read_4_bytes (dbfd, index_ptr);
10035   index_ptr += 4;
10036
10037   if (version != 1 && version != 2)
10038     {
10039       error (_("Dwarf Error: unsupported DWP file version (%s)"
10040                " [in module %s]"),
10041              pulongest (version), dwp_file->name);
10042     }
10043   if (nr_slots != (nr_slots & -nr_slots))
10044     {
10045       error (_("Dwarf Error: number of slots in DWP hash table (%s)"
10046                " is not power of 2 [in module %s]"),
10047              pulongest (nr_slots), dwp_file->name);
10048     }
10049
10050   htab = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwp_hash_table);
10051   htab->version = version;
10052   htab->nr_columns = nr_columns;
10053   htab->nr_units = nr_units;
10054   htab->nr_slots = nr_slots;
10055   htab->hash_table = index_ptr;
10056   htab->unit_table = htab->hash_table + sizeof (uint64_t) * nr_slots;
10057
10058   /* Exit early if the table is empty.  */
10059   if (nr_slots == 0 || nr_units == 0
10060       || (version == 2 && nr_columns == 0))
10061     {
10062       /* All must be zero.  */
10063       if (nr_slots != 0 || nr_units != 0
10064           || (version == 2 && nr_columns != 0))
10065         {
10066           complaint (&symfile_complaints,
10067                      _("Empty DWP but nr_slots,nr_units,nr_columns not"
10068                        " all zero [in modules %s]"),
10069                      dwp_file->name);
10070         }
10071       return htab;
10072     }
10073
10074   if (version == 1)
10075     {
10076       htab->section_pool.v1.indices =
10077         htab->unit_table + sizeof (uint32_t) * nr_slots;
10078       /* It's harder to decide whether the section is too small in v1.
10079          V1 is deprecated anyway so we punt.  */
10080     }
10081   else
10082     {
10083       const gdb_byte *ids_ptr = htab->unit_table + sizeof (uint32_t) * nr_slots;
10084       int *ids = htab->section_pool.v2.section_ids;
10085       /* Reverse map for error checking.  */
10086       int ids_seen[DW_SECT_MAX + 1];
10087       int i;
10088
10089       if (nr_columns < 2)
10090         {
10091           error (_("Dwarf Error: bad DWP hash table, too few columns"
10092                    " in section table [in module %s]"),
10093                  dwp_file->name);
10094         }
10095       if (nr_columns > MAX_NR_V2_DWO_SECTIONS)
10096         {
10097           error (_("Dwarf Error: bad DWP hash table, too many columns"
10098                    " in section table [in module %s]"),
10099                  dwp_file->name);
10100         }
10101       memset (ids, 255, (DW_SECT_MAX + 1) * sizeof (int32_t));
10102       memset (ids_seen, 255, (DW_SECT_MAX + 1) * sizeof (int32_t));
10103       for (i = 0; i < nr_columns; ++i)
10104         {
10105           int id = read_4_bytes (dbfd, ids_ptr + i * sizeof (uint32_t));
10106
10107           if (id < DW_SECT_MIN || id > DW_SECT_MAX)
10108             {
10109               error (_("Dwarf Error: bad DWP hash table, bad section id %d"
10110                        " in section table [in module %s]"),
10111                      id, dwp_file->name);
10112             }
10113           if (ids_seen[id] != -1)
10114             {
10115               error (_("Dwarf Error: bad DWP hash table, duplicate section"
10116                        " id %d in section table [in module %s]"),
10117                      id, dwp_file->name);
10118             }
10119           ids_seen[id] = i;
10120           ids[i] = id;
10121         }
10122       /* Must have exactly one info or types section.  */
10123       if (((ids_seen[DW_SECT_INFO] != -1)
10124            + (ids_seen[DW_SECT_TYPES] != -1))
10125           != 1)
10126         {
10127           error (_("Dwarf Error: bad DWP hash table, missing/duplicate"
10128                    " DWO info/types section [in module %s]"),
10129                  dwp_file->name);
10130         }
10131       /* Must have an abbrev section.  */
10132       if (ids_seen[DW_SECT_ABBREV] == -1)
10133         {
10134           error (_("Dwarf Error: bad DWP hash table, missing DWO abbrev"
10135                    " section [in module %s]"),
10136                  dwp_file->name);
10137         }
10138       htab->section_pool.v2.offsets = ids_ptr + sizeof (uint32_t) * nr_columns;
10139       htab->section_pool.v2.sizes =
10140         htab->section_pool.v2.offsets + (sizeof (uint32_t)
10141                                          * nr_units * nr_columns);
10142       if ((htab->section_pool.v2.sizes + (sizeof (uint32_t)
10143                                           * nr_units * nr_columns))
10144           > index_end)
10145         {
10146           error (_("Dwarf Error: DWP index section is corrupt (too small)"
10147                    " [in module %s]"),
10148                  dwp_file->name);
10149         }
10150     }
10151
10152   return htab;
10153 }
10154
10155 /* Update SECTIONS with the data from SECTP.
10156
10157    This function is like the other "locate" section routines that are
10158    passed to bfd_map_over_sections, but in this context the sections to
10159    read comes from the DWP V1 hash table, not the full ELF section table.
10160
10161    The result is non-zero for success, or zero if an error was found.  */
10162
10163 static int
10164 locate_v1_virtual_dwo_sections (asection *sectp,
10165                                 struct virtual_v1_dwo_sections *sections)
10166 {
10167   const struct dwop_section_names *names = &dwop_section_names;
10168
10169   if (section_is_p (sectp->name, &names->abbrev_dwo))
10170     {
10171       /* There can be only one.  */
10172       if (sections->abbrev.s.section != NULL)
10173         return 0;
10174       sections->abbrev.s.section = sectp;
10175       sections->abbrev.size = bfd_get_section_size (sectp);
10176     }
10177   else if (section_is_p (sectp->name, &names->info_dwo)
10178            || section_is_p (sectp->name, &names->types_dwo))
10179     {
10180       /* There can be only one.  */
10181       if (sections->info_or_types.s.section != NULL)
10182         return 0;
10183       sections->info_or_types.s.section = sectp;
10184       sections->info_or_types.size = bfd_get_section_size (sectp);
10185     }
10186   else if (section_is_p (sectp->name, &names->line_dwo))
10187     {
10188       /* There can be only one.  */
10189       if (sections->line.s.section != NULL)
10190         return 0;
10191       sections->line.s.section = sectp;
10192       sections->line.size = bfd_get_section_size (sectp);
10193     }
10194   else if (section_is_p (sectp->name, &names->loc_dwo))
10195     {
10196       /* There can be only one.  */
10197       if (sections->loc.s.section != NULL)
10198         return 0;
10199       sections->loc.s.section = sectp;
10200       sections->loc.size = bfd_get_section_size (sectp);
10201     }
10202   else if (section_is_p (sectp->name, &names->macinfo_dwo))
10203     {
10204       /* There can be only one.  */
10205       if (sections->macinfo.s.section != NULL)
10206         return 0;
10207       sections->macinfo.s.section = sectp;
10208       sections->macinfo.size = bfd_get_section_size (sectp);
10209     }
10210   else if (section_is_p (sectp->name, &names->macro_dwo))
10211     {
10212       /* There can be only one.  */
10213       if (sections->macro.s.section != NULL)
10214         return 0;
10215       sections->macro.s.section = sectp;
10216       sections->macro.size = bfd_get_section_size (sectp);
10217     }
10218   else if (section_is_p (sectp->name, &names->str_offsets_dwo))
10219     {
10220       /* There can be only one.  */
10221       if (sections->str_offsets.s.section != NULL)
10222         return 0;
10223       sections->str_offsets.s.section = sectp;
10224       sections->str_offsets.size = bfd_get_section_size (sectp);
10225     }
10226   else
10227     {
10228       /* No other kind of section is valid.  */
10229       return 0;
10230     }
10231
10232   return 1;
10233 }
10234
10235 /* Create a dwo_unit object for the DWO unit with signature SIGNATURE.
10236    UNIT_INDEX is the index of the DWO unit in the DWP hash table.
10237    COMP_DIR is the DW_AT_comp_dir attribute of the referencing CU.
10238    This is for DWP version 1 files.  */
10239
10240 static struct dwo_unit *
10241 create_dwo_unit_in_dwp_v1 (struct dwp_file *dwp_file,
10242                            uint32_t unit_index,
10243                            const char *comp_dir,
10244                            ULONGEST signature, int is_debug_types)
10245 {
10246   struct objfile *objfile = dwarf2_per_objfile->objfile;
10247   const struct dwp_hash_table *dwp_htab =
10248     is_debug_types ? dwp_file->tus : dwp_file->cus;
10249   bfd *dbfd = dwp_file->dbfd;
10250   const char *kind = is_debug_types ? "TU" : "CU";
10251   struct dwo_file *dwo_file;
10252   struct dwo_unit *dwo_unit;
10253   struct virtual_v1_dwo_sections sections;
10254   void **dwo_file_slot;
10255   char *virtual_dwo_name;
10256   struct cleanup *cleanups;
10257   int i;
10258
10259   gdb_assert (dwp_file->version == 1);
10260
10261   if (dwarf_read_debug)
10262     {
10263       fprintf_unfiltered (gdb_stdlog, "Reading %s %s/%s in DWP V1 file: %s\n",
10264                           kind,
10265                           pulongest (unit_index), hex_string (signature),
10266                           dwp_file->name);
10267     }
10268
10269   /* Fetch the sections of this DWO unit.
10270      Put a limit on the number of sections we look for so that bad data
10271      doesn't cause us to loop forever.  */
10272
10273 #define MAX_NR_V1_DWO_SECTIONS \
10274   (1 /* .debug_info or .debug_types */ \
10275    + 1 /* .debug_abbrev */ \
10276    + 1 /* .debug_line */ \
10277    + 1 /* .debug_loc */ \
10278    + 1 /* .debug_str_offsets */ \
10279    + 1 /* .debug_macro or .debug_macinfo */ \
10280    + 1 /* trailing zero */)
10281
10282   memset (&sections, 0, sizeof (sections));
10283   cleanups = make_cleanup (null_cleanup, 0);
10284
10285   for (i = 0; i < MAX_NR_V1_DWO_SECTIONS; ++i)
10286     {
10287       asection *sectp;
10288       uint32_t section_nr =
10289         read_4_bytes (dbfd,
10290                       dwp_htab->section_pool.v1.indices
10291                       + (unit_index + i) * sizeof (uint32_t));
10292
10293       if (section_nr == 0)
10294         break;
10295       if (section_nr >= dwp_file->num_sections)
10296         {
10297           error (_("Dwarf Error: bad DWP hash table, section number too large"
10298                    " [in module %s]"),
10299                  dwp_file->name);
10300         }
10301
10302       sectp = dwp_file->elf_sections[section_nr];
10303       if (! locate_v1_virtual_dwo_sections (sectp, &sections))
10304         {
10305           error (_("Dwarf Error: bad DWP hash table, invalid section found"
10306                    " [in module %s]"),
10307                  dwp_file->name);
10308         }
10309     }
10310
10311   if (i < 2
10312       || dwarf2_section_empty_p (&sections.info_or_types)
10313       || dwarf2_section_empty_p (&sections.abbrev))
10314     {
10315       error (_("Dwarf Error: bad DWP hash table, missing DWO sections"
10316                " [in module %s]"),
10317              dwp_file->name);
10318     }
10319   if (i == MAX_NR_V1_DWO_SECTIONS)
10320     {
10321       error (_("Dwarf Error: bad DWP hash table, too many DWO sections"
10322                " [in module %s]"),
10323              dwp_file->name);
10324     }
10325
10326   /* It's easier for the rest of the code if we fake a struct dwo_file and
10327      have dwo_unit "live" in that.  At least for now.
10328
10329      The DWP file can be made up of a random collection of CUs and TUs.
10330      However, for each CU + set of TUs that came from the same original DWO
10331      file, we can combine them back into a virtual DWO file to save space
10332      (fewer struct dwo_file objects to allocate).  Remember that for really
10333      large apps there can be on the order of 8K CUs and 200K TUs, or more.  */
10334
10335   virtual_dwo_name =
10336     xstrprintf ("virtual-dwo/%d-%d-%d-%d",
10337                 get_section_id (&sections.abbrev),
10338                 get_section_id (&sections.line),
10339                 get_section_id (&sections.loc),
10340                 get_section_id (&sections.str_offsets));
10341   make_cleanup (xfree, virtual_dwo_name);
10342   /* Can we use an existing virtual DWO file?  */
10343   dwo_file_slot = lookup_dwo_file_slot (virtual_dwo_name, comp_dir);
10344   /* Create one if necessary.  */
10345   if (*dwo_file_slot == NULL)
10346     {
10347       if (dwarf_read_debug)
10348         {
10349           fprintf_unfiltered (gdb_stdlog, "Creating virtual DWO: %s\n",
10350                               virtual_dwo_name);
10351         }
10352       dwo_file = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_file);
10353       dwo_file->dwo_name
10354         = (const char *) obstack_copy0 (&objfile->objfile_obstack,
10355                                         virtual_dwo_name,
10356                                         strlen (virtual_dwo_name));
10357       dwo_file->comp_dir = comp_dir;
10358       dwo_file->sections.abbrev = sections.abbrev;
10359       dwo_file->sections.line = sections.line;
10360       dwo_file->sections.loc = sections.loc;
10361       dwo_file->sections.macinfo = sections.macinfo;
10362       dwo_file->sections.macro = sections.macro;
10363       dwo_file->sections.str_offsets = sections.str_offsets;
10364       /* The "str" section is global to the entire DWP file.  */
10365       dwo_file->sections.str = dwp_file->sections.str;
10366       /* The info or types section is assigned below to dwo_unit,
10367          there's no need to record it in dwo_file.
10368          Also, we can't simply record type sections in dwo_file because
10369          we record a pointer into the vector in dwo_unit.  As we collect more
10370          types we'll grow the vector and eventually have to reallocate space
10371          for it, invalidating all copies of pointers into the previous
10372          contents.  */
10373       *dwo_file_slot = dwo_file;
10374     }
10375   else
10376     {
10377       if (dwarf_read_debug)
10378         {
10379           fprintf_unfiltered (gdb_stdlog, "Using existing virtual DWO: %s\n",
10380                               virtual_dwo_name);
10381         }
10382       dwo_file = (struct dwo_file *) *dwo_file_slot;
10383     }
10384   do_cleanups (cleanups);
10385
10386   dwo_unit = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_unit);
10387   dwo_unit->dwo_file = dwo_file;
10388   dwo_unit->signature = signature;
10389   dwo_unit->section =
10390     XOBNEW (&objfile->objfile_obstack, struct dwarf2_section_info);
10391   *dwo_unit->section = sections.info_or_types;
10392   /* dwo_unit->{offset,length,type_offset_in_tu} are set later.  */
10393
10394   return dwo_unit;
10395 }
10396
10397 /* Subroutine of create_dwo_unit_in_dwp_v2 to simplify it.
10398    Given a pointer to the containing section SECTION, and OFFSET,SIZE of the
10399    piece within that section used by a TU/CU, return a virtual section
10400    of just that piece.  */
10401
10402 static struct dwarf2_section_info
10403 create_dwp_v2_section (struct dwarf2_section_info *section,
10404                        bfd_size_type offset, bfd_size_type size)
10405 {
10406   struct dwarf2_section_info result;
10407   asection *sectp;
10408
10409   gdb_assert (section != NULL);
10410   gdb_assert (!section->is_virtual);
10411
10412   memset (&result, 0, sizeof (result));
10413   result.s.containing_section = section;
10414   result.is_virtual = 1;
10415
10416   if (size == 0)
10417     return result;
10418
10419   sectp = get_section_bfd_section (section);
10420
10421   /* Flag an error if the piece denoted by OFFSET,SIZE is outside the
10422      bounds of the real section.  This is a pretty-rare event, so just
10423      flag an error (easier) instead of a warning and trying to cope.  */
10424   if (sectp == NULL
10425       || offset + size > bfd_get_section_size (sectp))
10426     {
10427       bfd *abfd = sectp->owner;
10428
10429       error (_("Dwarf Error: Bad DWP V2 section info, doesn't fit"
10430                " in section %s [in module %s]"),
10431              sectp ? bfd_section_name (abfd, sectp) : "<unknown>",
10432              objfile_name (dwarf2_per_objfile->objfile));
10433     }
10434
10435   result.virtual_offset = offset;
10436   result.size = size;
10437   return result;
10438 }
10439
10440 /* Create a dwo_unit object for the DWO unit with signature SIGNATURE.
10441    UNIT_INDEX is the index of the DWO unit in the DWP hash table.
10442    COMP_DIR is the DW_AT_comp_dir attribute of the referencing CU.
10443    This is for DWP version 2 files.  */
10444
10445 static struct dwo_unit *
10446 create_dwo_unit_in_dwp_v2 (struct dwp_file *dwp_file,
10447                            uint32_t unit_index,
10448                            const char *comp_dir,
10449                            ULONGEST signature, int is_debug_types)
10450 {
10451   struct objfile *objfile = dwarf2_per_objfile->objfile;
10452   const struct dwp_hash_table *dwp_htab =
10453     is_debug_types ? dwp_file->tus : dwp_file->cus;
10454   bfd *dbfd = dwp_file->dbfd;
10455   const char *kind = is_debug_types ? "TU" : "CU";
10456   struct dwo_file *dwo_file;
10457   struct dwo_unit *dwo_unit;
10458   struct virtual_v2_dwo_sections sections;
10459   void **dwo_file_slot;
10460   char *virtual_dwo_name;
10461   struct cleanup *cleanups;
10462   int i;
10463
10464   gdb_assert (dwp_file->version == 2);
10465
10466   if (dwarf_read_debug)
10467     {
10468       fprintf_unfiltered (gdb_stdlog, "Reading %s %s/%s in DWP V2 file: %s\n",
10469                           kind,
10470                           pulongest (unit_index), hex_string (signature),
10471                           dwp_file->name);
10472     }
10473
10474   /* Fetch the section offsets of this DWO unit.  */
10475
10476   memset (&sections, 0, sizeof (sections));
10477   cleanups = make_cleanup (null_cleanup, 0);
10478
10479   for (i = 0; i < dwp_htab->nr_columns; ++i)
10480     {
10481       uint32_t offset = read_4_bytes (dbfd,
10482                                       dwp_htab->section_pool.v2.offsets
10483                                       + (((unit_index - 1) * dwp_htab->nr_columns
10484                                           + i)
10485                                          * sizeof (uint32_t)));
10486       uint32_t size = read_4_bytes (dbfd,
10487                                     dwp_htab->section_pool.v2.sizes
10488                                     + (((unit_index - 1) * dwp_htab->nr_columns
10489                                         + i)
10490                                        * sizeof (uint32_t)));
10491
10492       switch (dwp_htab->section_pool.v2.section_ids[i])
10493         {
10494         case DW_SECT_INFO:
10495         case DW_SECT_TYPES:
10496           sections.info_or_types_offset = offset;
10497           sections.info_or_types_size = size;
10498           break;
10499         case DW_SECT_ABBREV:
10500           sections.abbrev_offset = offset;
10501           sections.abbrev_size = size;
10502           break;
10503         case DW_SECT_LINE:
10504           sections.line_offset = offset;
10505           sections.line_size = size;
10506           break;
10507         case DW_SECT_LOC:
10508           sections.loc_offset = offset;
10509           sections.loc_size = size;
10510           break;
10511         case DW_SECT_STR_OFFSETS:
10512           sections.str_offsets_offset = offset;
10513           sections.str_offsets_size = size;
10514           break;
10515         case DW_SECT_MACINFO:
10516           sections.macinfo_offset = offset;
10517           sections.macinfo_size = size;
10518           break;
10519         case DW_SECT_MACRO:
10520           sections.macro_offset = offset;
10521           sections.macro_size = size;
10522           break;
10523         }
10524     }
10525
10526   /* It's easier for the rest of the code if we fake a struct dwo_file and
10527      have dwo_unit "live" in that.  At least for now.
10528
10529      The DWP file can be made up of a random collection of CUs and TUs.
10530      However, for each CU + set of TUs that came from the same original DWO
10531      file, we can combine them back into a virtual DWO file to save space
10532      (fewer struct dwo_file objects to allocate).  Remember that for really
10533      large apps there can be on the order of 8K CUs and 200K TUs, or more.  */
10534
10535   virtual_dwo_name =
10536     xstrprintf ("virtual-dwo/%ld-%ld-%ld-%ld",
10537                 (long) (sections.abbrev_size ? sections.abbrev_offset : 0),
10538                 (long) (sections.line_size ? sections.line_offset : 0),
10539                 (long) (sections.loc_size ? sections.loc_offset : 0),
10540                 (long) (sections.str_offsets_size
10541                         ? sections.str_offsets_offset : 0));
10542   make_cleanup (xfree, virtual_dwo_name);
10543   /* Can we use an existing virtual DWO file?  */
10544   dwo_file_slot = lookup_dwo_file_slot (virtual_dwo_name, comp_dir);
10545   /* Create one if necessary.  */
10546   if (*dwo_file_slot == NULL)
10547     {
10548       if (dwarf_read_debug)
10549         {
10550           fprintf_unfiltered (gdb_stdlog, "Creating virtual DWO: %s\n",
10551                               virtual_dwo_name);
10552         }
10553       dwo_file = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_file);
10554       dwo_file->dwo_name
10555         = (const char *) obstack_copy0 (&objfile->objfile_obstack,
10556                                         virtual_dwo_name,
10557                                         strlen (virtual_dwo_name));
10558       dwo_file->comp_dir = comp_dir;
10559       dwo_file->sections.abbrev =
10560         create_dwp_v2_section (&dwp_file->sections.abbrev,
10561                                sections.abbrev_offset, sections.abbrev_size);
10562       dwo_file->sections.line =
10563         create_dwp_v2_section (&dwp_file->sections.line,
10564                                sections.line_offset, sections.line_size);
10565       dwo_file->sections.loc =
10566         create_dwp_v2_section (&dwp_file->sections.loc,
10567                                sections.loc_offset, sections.loc_size);
10568       dwo_file->sections.macinfo =
10569         create_dwp_v2_section (&dwp_file->sections.macinfo,
10570                                sections.macinfo_offset, sections.macinfo_size);
10571       dwo_file->sections.macro =
10572         create_dwp_v2_section (&dwp_file->sections.macro,
10573                                sections.macro_offset, sections.macro_size);
10574       dwo_file->sections.str_offsets =
10575         create_dwp_v2_section (&dwp_file->sections.str_offsets,
10576                                sections.str_offsets_offset,
10577                                sections.str_offsets_size);
10578       /* The "str" section is global to the entire DWP file.  */
10579       dwo_file->sections.str = dwp_file->sections.str;
10580       /* The info or types section is assigned below to dwo_unit,
10581          there's no need to record it in dwo_file.
10582          Also, we can't simply record type sections in dwo_file because
10583          we record a pointer into the vector in dwo_unit.  As we collect more
10584          types we'll grow the vector and eventually have to reallocate space
10585          for it, invalidating all copies of pointers into the previous
10586          contents.  */
10587       *dwo_file_slot = dwo_file;
10588     }
10589   else
10590     {
10591       if (dwarf_read_debug)
10592         {
10593           fprintf_unfiltered (gdb_stdlog, "Using existing virtual DWO: %s\n",
10594                               virtual_dwo_name);
10595         }
10596       dwo_file = (struct dwo_file *) *dwo_file_slot;
10597     }
10598   do_cleanups (cleanups);
10599
10600   dwo_unit = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_unit);
10601   dwo_unit->dwo_file = dwo_file;
10602   dwo_unit->signature = signature;
10603   dwo_unit->section =
10604     XOBNEW (&objfile->objfile_obstack, struct dwarf2_section_info);
10605   *dwo_unit->section = create_dwp_v2_section (is_debug_types
10606                                               ? &dwp_file->sections.types
10607                                               : &dwp_file->sections.info,
10608                                               sections.info_or_types_offset,
10609                                               sections.info_or_types_size);
10610   /* dwo_unit->{offset,length,type_offset_in_tu} are set later.  */
10611
10612   return dwo_unit;
10613 }
10614
10615 /* Lookup the DWO unit with SIGNATURE in DWP_FILE.
10616    Returns NULL if the signature isn't found.  */
10617
10618 static struct dwo_unit *
10619 lookup_dwo_unit_in_dwp (struct dwp_file *dwp_file, const char *comp_dir,
10620                         ULONGEST signature, int is_debug_types)
10621 {
10622   const struct dwp_hash_table *dwp_htab =
10623     is_debug_types ? dwp_file->tus : dwp_file->cus;
10624   bfd *dbfd = dwp_file->dbfd;
10625   uint32_t mask = dwp_htab->nr_slots - 1;
10626   uint32_t hash = signature & mask;
10627   uint32_t hash2 = ((signature >> 32) & mask) | 1;
10628   unsigned int i;
10629   void **slot;
10630   struct dwo_unit find_dwo_cu;
10631
10632   memset (&find_dwo_cu, 0, sizeof (find_dwo_cu));
10633   find_dwo_cu.signature = signature;
10634   slot = htab_find_slot (is_debug_types
10635                          ? dwp_file->loaded_tus
10636                          : dwp_file->loaded_cus,
10637                          &find_dwo_cu, INSERT);
10638
10639   if (*slot != NULL)
10640     return (struct dwo_unit *) *slot;
10641
10642   /* Use a for loop so that we don't loop forever on bad debug info.  */
10643   for (i = 0; i < dwp_htab->nr_slots; ++i)
10644     {
10645       ULONGEST signature_in_table;
10646
10647       signature_in_table =
10648         read_8_bytes (dbfd, dwp_htab->hash_table + hash * sizeof (uint64_t));
10649       if (signature_in_table == signature)
10650         {
10651           uint32_t unit_index =
10652             read_4_bytes (dbfd,
10653                           dwp_htab->unit_table + hash * sizeof (uint32_t));
10654
10655           if (dwp_file->version == 1)
10656             {
10657               *slot = create_dwo_unit_in_dwp_v1 (dwp_file, unit_index,
10658                                                  comp_dir, signature,
10659                                                  is_debug_types);
10660             }
10661           else
10662             {
10663               *slot = create_dwo_unit_in_dwp_v2 (dwp_file, unit_index,
10664                                                  comp_dir, signature,
10665                                                  is_debug_types);
10666             }
10667           return (struct dwo_unit *) *slot;
10668         }
10669       if (signature_in_table == 0)
10670         return NULL;
10671       hash = (hash + hash2) & mask;
10672     }
10673
10674   error (_("Dwarf Error: bad DWP hash table, lookup didn't terminate"
10675            " [in module %s]"),
10676          dwp_file->name);
10677 }
10678
10679 /* Subroutine of open_dwo_file,open_dwp_file to simplify them.
10680    Open the file specified by FILE_NAME and hand it off to BFD for
10681    preliminary analysis.  Return a newly initialized bfd *, which
10682    includes a canonicalized copy of FILE_NAME.
10683    If IS_DWP is TRUE, we're opening a DWP file, otherwise a DWO file.
10684    SEARCH_CWD is true if the current directory is to be searched.
10685    It will be searched before debug-file-directory.
10686    If successful, the file is added to the bfd include table of the
10687    objfile's bfd (see gdb_bfd_record_inclusion).
10688    If unable to find/open the file, return NULL.
10689    NOTE: This function is derived from symfile_bfd_open.  */
10690
10691 static gdb_bfd_ref_ptr
10692 try_open_dwop_file (const char *file_name, int is_dwp, int search_cwd)
10693 {
10694   int desc, flags;
10695   char *absolute_name;
10696   /* Blech.  OPF_TRY_CWD_FIRST also disables searching the path list if
10697      FILE_NAME contains a '/'.  So we can't use it.  Instead prepend "."
10698      to debug_file_directory.  */
10699   char *search_path;
10700   static const char dirname_separator_string[] = { DIRNAME_SEPARATOR, '\0' };
10701
10702   if (search_cwd)
10703     {
10704       if (*debug_file_directory != '\0')
10705         search_path = concat (".", dirname_separator_string,
10706                               debug_file_directory, (char *) NULL);
10707       else
10708         search_path = xstrdup (".");
10709     }
10710   else
10711     search_path = xstrdup (debug_file_directory);
10712
10713   flags = OPF_RETURN_REALPATH;
10714   if (is_dwp)
10715     flags |= OPF_SEARCH_IN_PATH;
10716   desc = openp (search_path, flags, file_name,
10717                 O_RDONLY | O_BINARY, &absolute_name);
10718   xfree (search_path);
10719   if (desc < 0)
10720     return NULL;
10721
10722   gdb_bfd_ref_ptr sym_bfd (gdb_bfd_open (absolute_name, gnutarget, desc));
10723   xfree (absolute_name);
10724   if (sym_bfd == NULL)
10725     return NULL;
10726   bfd_set_cacheable (sym_bfd.get (), 1);
10727
10728   if (!bfd_check_format (sym_bfd.get (), bfd_object))
10729     return NULL;
10730
10731   /* Success.  Record the bfd as having been included by the objfile's bfd.
10732      This is important because things like demangled_names_hash lives in the
10733      objfile's per_bfd space and may have references to things like symbol
10734      names that live in the DWO/DWP file's per_bfd space.  PR 16426.  */
10735   gdb_bfd_record_inclusion (dwarf2_per_objfile->objfile->obfd, sym_bfd.get ());
10736
10737   return sym_bfd;
10738 }
10739
10740 /* Try to open DWO file FILE_NAME.
10741    COMP_DIR is the DW_AT_comp_dir attribute.
10742    The result is the bfd handle of the file.
10743    If there is a problem finding or opening the file, return NULL.
10744    Upon success, the canonicalized path of the file is stored in the bfd,
10745    same as symfile_bfd_open.  */
10746
10747 static gdb_bfd_ref_ptr
10748 open_dwo_file (const char *file_name, const char *comp_dir)
10749 {
10750   if (IS_ABSOLUTE_PATH (file_name))
10751     return try_open_dwop_file (file_name, 0 /*is_dwp*/, 0 /*search_cwd*/);
10752
10753   /* Before trying the search path, try DWO_NAME in COMP_DIR.  */
10754
10755   if (comp_dir != NULL)
10756     {
10757       char *path_to_try = concat (comp_dir, SLASH_STRING,
10758                                   file_name, (char *) NULL);
10759
10760       /* NOTE: If comp_dir is a relative path, this will also try the
10761          search path, which seems useful.  */
10762       gdb_bfd_ref_ptr abfd (try_open_dwop_file (path_to_try, 0 /*is_dwp*/,
10763                                                 1 /*search_cwd*/));
10764       xfree (path_to_try);
10765       if (abfd != NULL)
10766         return abfd;
10767     }
10768
10769   /* That didn't work, try debug-file-directory, which, despite its name,
10770      is a list of paths.  */
10771
10772   if (*debug_file_directory == '\0')
10773     return NULL;
10774
10775   return try_open_dwop_file (file_name, 0 /*is_dwp*/, 1 /*search_cwd*/);
10776 }
10777
10778 /* This function is mapped across the sections and remembers the offset and
10779    size of each of the DWO debugging sections we are interested in.  */
10780
10781 static void
10782 dwarf2_locate_dwo_sections (bfd *abfd, asection *sectp, void *dwo_sections_ptr)
10783 {
10784   struct dwo_sections *dwo_sections = (struct dwo_sections *) dwo_sections_ptr;
10785   const struct dwop_section_names *names = &dwop_section_names;
10786
10787   if (section_is_p (sectp->name, &names->abbrev_dwo))
10788     {
10789       dwo_sections->abbrev.s.section = sectp;
10790       dwo_sections->abbrev.size = bfd_get_section_size (sectp);
10791     }
10792   else if (section_is_p (sectp->name, &names->info_dwo))
10793     {
10794       dwo_sections->info.s.section = sectp;
10795       dwo_sections->info.size = bfd_get_section_size (sectp);
10796     }
10797   else if (section_is_p (sectp->name, &names->line_dwo))
10798     {
10799       dwo_sections->line.s.section = sectp;
10800       dwo_sections->line.size = bfd_get_section_size (sectp);
10801     }
10802   else if (section_is_p (sectp->name, &names->loc_dwo))
10803     {
10804       dwo_sections->loc.s.section = sectp;
10805       dwo_sections->loc.size = bfd_get_section_size (sectp);
10806     }
10807   else if (section_is_p (sectp->name, &names->macinfo_dwo))
10808     {
10809       dwo_sections->macinfo.s.section = sectp;
10810       dwo_sections->macinfo.size = bfd_get_section_size (sectp);
10811     }
10812   else if (section_is_p (sectp->name, &names->macro_dwo))
10813     {
10814       dwo_sections->macro.s.section = sectp;
10815       dwo_sections->macro.size = bfd_get_section_size (sectp);
10816     }
10817   else if (section_is_p (sectp->name, &names->str_dwo))
10818     {
10819       dwo_sections->str.s.section = sectp;
10820       dwo_sections->str.size = bfd_get_section_size (sectp);
10821     }
10822   else if (section_is_p (sectp->name, &names->str_offsets_dwo))
10823     {
10824       dwo_sections->str_offsets.s.section = sectp;
10825       dwo_sections->str_offsets.size = bfd_get_section_size (sectp);
10826     }
10827   else if (section_is_p (sectp->name, &names->types_dwo))
10828     {
10829       struct dwarf2_section_info type_section;
10830
10831       memset (&type_section, 0, sizeof (type_section));
10832       type_section.s.section = sectp;
10833       type_section.size = bfd_get_section_size (sectp);
10834       VEC_safe_push (dwarf2_section_info_def, dwo_sections->types,
10835                      &type_section);
10836     }
10837 }
10838
10839 /* Initialize the use of the DWO file specified by DWO_NAME and referenced
10840    by PER_CU.  This is for the non-DWP case.
10841    The result is NULL if DWO_NAME can't be found.  */
10842
10843 static struct dwo_file *
10844 open_and_init_dwo_file (struct dwarf2_per_cu_data *per_cu,
10845                         const char *dwo_name, const char *comp_dir)
10846 {
10847   struct objfile *objfile = dwarf2_per_objfile->objfile;
10848   struct dwo_file *dwo_file;
10849   struct cleanup *cleanups;
10850
10851   gdb_bfd_ref_ptr dbfd (open_dwo_file (dwo_name, comp_dir));
10852   if (dbfd == NULL)
10853     {
10854       if (dwarf_read_debug)
10855         fprintf_unfiltered (gdb_stdlog, "DWO file not found: %s\n", dwo_name);
10856       return NULL;
10857     }
10858   dwo_file = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_file);
10859   dwo_file->dwo_name = dwo_name;
10860   dwo_file->comp_dir = comp_dir;
10861   dwo_file->dbfd = dbfd.release ();
10862
10863   cleanups = make_cleanup (free_dwo_file_cleanup, dwo_file);
10864
10865   bfd_map_over_sections (dwo_file->dbfd, dwarf2_locate_dwo_sections,
10866                          &dwo_file->sections);
10867
10868   create_cus_hash_table (*dwo_file, dwo_file->sections.info, dwo_file->cus);
10869
10870   create_debug_types_hash_table (dwo_file, dwo_file->sections.types,
10871                                  dwo_file->tus);
10872
10873   discard_cleanups (cleanups);
10874
10875   if (dwarf_read_debug)
10876     fprintf_unfiltered (gdb_stdlog, "DWO file found: %s\n", dwo_name);
10877
10878   return dwo_file;
10879 }
10880
10881 /* This function is mapped across the sections and remembers the offset and
10882    size of each of the DWP debugging sections common to version 1 and 2 that
10883    we are interested in.  */
10884
10885 static void
10886 dwarf2_locate_common_dwp_sections (bfd *abfd, asection *sectp,
10887                                    void *dwp_file_ptr)
10888 {
10889   struct dwp_file *dwp_file = (struct dwp_file *) dwp_file_ptr;
10890   const struct dwop_section_names *names = &dwop_section_names;
10891   unsigned int elf_section_nr = elf_section_data (sectp)->this_idx;
10892
10893   /* Record the ELF section number for later lookup: this is what the
10894      .debug_cu_index,.debug_tu_index tables use in DWP V1.  */
10895   gdb_assert (elf_section_nr < dwp_file->num_sections);
10896   dwp_file->elf_sections[elf_section_nr] = sectp;
10897
10898   /* Look for specific sections that we need.  */
10899   if (section_is_p (sectp->name, &names->str_dwo))
10900     {
10901       dwp_file->sections.str.s.section = sectp;
10902       dwp_file->sections.str.size = bfd_get_section_size (sectp);
10903     }
10904   else if (section_is_p (sectp->name, &names->cu_index))
10905     {
10906       dwp_file->sections.cu_index.s.section = sectp;
10907       dwp_file->sections.cu_index.size = bfd_get_section_size (sectp);
10908     }
10909   else if (section_is_p (sectp->name, &names->tu_index))
10910     {
10911       dwp_file->sections.tu_index.s.section = sectp;
10912       dwp_file->sections.tu_index.size = bfd_get_section_size (sectp);
10913     }
10914 }
10915
10916 /* This function is mapped across the sections and remembers the offset and
10917    size of each of the DWP version 2 debugging sections that we are interested
10918    in.  This is split into a separate function because we don't know if we
10919    have version 1 or 2 until we parse the cu_index/tu_index sections.  */
10920
10921 static void
10922 dwarf2_locate_v2_dwp_sections (bfd *abfd, asection *sectp, void *dwp_file_ptr)
10923 {
10924   struct dwp_file *dwp_file = (struct dwp_file *) dwp_file_ptr;
10925   const struct dwop_section_names *names = &dwop_section_names;
10926   unsigned int elf_section_nr = elf_section_data (sectp)->this_idx;
10927
10928   /* Record the ELF section number for later lookup: this is what the
10929      .debug_cu_index,.debug_tu_index tables use in DWP V1.  */
10930   gdb_assert (elf_section_nr < dwp_file->num_sections);
10931   dwp_file->elf_sections[elf_section_nr] = sectp;
10932
10933   /* Look for specific sections that we need.  */
10934   if (section_is_p (sectp->name, &names->abbrev_dwo))
10935     {
10936       dwp_file->sections.abbrev.s.section = sectp;
10937       dwp_file->sections.abbrev.size = bfd_get_section_size (sectp);
10938     }
10939   else if (section_is_p (sectp->name, &names->info_dwo))
10940     {
10941       dwp_file->sections.info.s.section = sectp;
10942       dwp_file->sections.info.size = bfd_get_section_size (sectp);
10943     }
10944   else if (section_is_p (sectp->name, &names->line_dwo))
10945     {
10946       dwp_file->sections.line.s.section = sectp;
10947       dwp_file->sections.line.size = bfd_get_section_size (sectp);
10948     }
10949   else if (section_is_p (sectp->name, &names->loc_dwo))
10950     {
10951       dwp_file->sections.loc.s.section = sectp;
10952       dwp_file->sections.loc.size = bfd_get_section_size (sectp);
10953     }
10954   else if (section_is_p (sectp->name, &names->macinfo_dwo))
10955     {
10956       dwp_file->sections.macinfo.s.section = sectp;
10957       dwp_file->sections.macinfo.size = bfd_get_section_size (sectp);
10958     }
10959   else if (section_is_p (sectp->name, &names->macro_dwo))
10960     {
10961       dwp_file->sections.macro.s.section = sectp;
10962       dwp_file->sections.macro.size = bfd_get_section_size (sectp);
10963     }
10964   else if (section_is_p (sectp->name, &names->str_offsets_dwo))
10965     {
10966       dwp_file->sections.str_offsets.s.section = sectp;
10967       dwp_file->sections.str_offsets.size = bfd_get_section_size (sectp);
10968     }
10969   else if (section_is_p (sectp->name, &names->types_dwo))
10970     {
10971       dwp_file->sections.types.s.section = sectp;
10972       dwp_file->sections.types.size = bfd_get_section_size (sectp);
10973     }
10974 }
10975
10976 /* Hash function for dwp_file loaded CUs/TUs.  */
10977
10978 static hashval_t
10979 hash_dwp_loaded_cutus (const void *item)
10980 {
10981   const struct dwo_unit *dwo_unit = (const struct dwo_unit *) item;
10982
10983   /* This drops the top 32 bits of the signature, but is ok for a hash.  */
10984   return dwo_unit->signature;
10985 }
10986
10987 /* Equality function for dwp_file loaded CUs/TUs.  */
10988
10989 static int
10990 eq_dwp_loaded_cutus (const void *a, const void *b)
10991 {
10992   const struct dwo_unit *dua = (const struct dwo_unit *) a;
10993   const struct dwo_unit *dub = (const struct dwo_unit *) b;
10994
10995   return dua->signature == dub->signature;
10996 }
10997
10998 /* Allocate a hash table for dwp_file loaded CUs/TUs.  */
10999
11000 static htab_t
11001 allocate_dwp_loaded_cutus_table (struct objfile *objfile)
11002 {
11003   return htab_create_alloc_ex (3,
11004                                hash_dwp_loaded_cutus,
11005                                eq_dwp_loaded_cutus,
11006                                NULL,
11007                                &objfile->objfile_obstack,
11008                                hashtab_obstack_allocate,
11009                                dummy_obstack_deallocate);
11010 }
11011
11012 /* Try to open DWP file FILE_NAME.
11013    The result is the bfd handle of the file.
11014    If there is a problem finding or opening the file, return NULL.
11015    Upon success, the canonicalized path of the file is stored in the bfd,
11016    same as symfile_bfd_open.  */
11017
11018 static gdb_bfd_ref_ptr
11019 open_dwp_file (const char *file_name)
11020 {
11021   gdb_bfd_ref_ptr abfd (try_open_dwop_file (file_name, 1 /*is_dwp*/,
11022                                             1 /*search_cwd*/));
11023   if (abfd != NULL)
11024     return abfd;
11025
11026   /* Work around upstream bug 15652.
11027      http://sourceware.org/bugzilla/show_bug.cgi?id=15652
11028      [Whether that's a "bug" is debatable, but it is getting in our way.]
11029      We have no real idea where the dwp file is, because gdb's realpath-ing
11030      of the executable's path may have discarded the needed info.
11031      [IWBN if the dwp file name was recorded in the executable, akin to
11032      .gnu_debuglink, but that doesn't exist yet.]
11033      Strip the directory from FILE_NAME and search again.  */
11034   if (*debug_file_directory != '\0')
11035     {
11036       /* Don't implicitly search the current directory here.
11037          If the user wants to search "." to handle this case,
11038          it must be added to debug-file-directory.  */
11039       return try_open_dwop_file (lbasename (file_name), 1 /*is_dwp*/,
11040                                  0 /*search_cwd*/);
11041     }
11042
11043   return NULL;
11044 }
11045
11046 /* Initialize the use of the DWP file for the current objfile.
11047    By convention the name of the DWP file is ${objfile}.dwp.
11048    The result is NULL if it can't be found.  */
11049
11050 static struct dwp_file *
11051 open_and_init_dwp_file (void)
11052 {
11053   struct objfile *objfile = dwarf2_per_objfile->objfile;
11054   struct dwp_file *dwp_file;
11055
11056   /* Try to find first .dwp for the binary file before any symbolic links
11057      resolving.  */
11058
11059   /* If the objfile is a debug file, find the name of the real binary
11060      file and get the name of dwp file from there.  */
11061   std::string dwp_name;
11062   if (objfile->separate_debug_objfile_backlink != NULL)
11063     {
11064       struct objfile *backlink = objfile->separate_debug_objfile_backlink;
11065       const char *backlink_basename = lbasename (backlink->original_name);
11066
11067       dwp_name = ldirname (objfile->original_name) + SLASH_STRING + backlink_basename;
11068     }
11069   else
11070     dwp_name = objfile->original_name;
11071
11072   dwp_name += ".dwp";
11073
11074   gdb_bfd_ref_ptr dbfd (open_dwp_file (dwp_name.c_str ()));
11075   if (dbfd == NULL
11076       && strcmp (objfile->original_name, objfile_name (objfile)) != 0)
11077     {
11078       /* Try to find .dwp for the binary file after gdb_realpath resolving.  */
11079       dwp_name = objfile_name (objfile);
11080       dwp_name += ".dwp";
11081       dbfd = open_dwp_file (dwp_name.c_str ());
11082     }
11083
11084   if (dbfd == NULL)
11085     {
11086       if (dwarf_read_debug)
11087         fprintf_unfiltered (gdb_stdlog, "DWP file not found: %s\n", dwp_name.c_str ());
11088       return NULL;
11089     }
11090   dwp_file = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwp_file);
11091   dwp_file->name = bfd_get_filename (dbfd.get ());
11092   dwp_file->dbfd = dbfd.release ();
11093
11094   /* +1: section 0 is unused */
11095   dwp_file->num_sections = bfd_count_sections (dwp_file->dbfd) + 1;
11096   dwp_file->elf_sections =
11097     OBSTACK_CALLOC (&objfile->objfile_obstack,
11098                     dwp_file->num_sections, asection *);
11099
11100   bfd_map_over_sections (dwp_file->dbfd, dwarf2_locate_common_dwp_sections,
11101                          dwp_file);
11102
11103   dwp_file->cus = create_dwp_hash_table (dwp_file, 0);
11104
11105   dwp_file->tus = create_dwp_hash_table (dwp_file, 1);
11106
11107   /* The DWP file version is stored in the hash table.  Oh well.  */
11108   if (dwp_file->cus->version != dwp_file->tus->version)
11109     {
11110       /* Technically speaking, we should try to limp along, but this is
11111          pretty bizarre.  We use pulongest here because that's the established
11112          portability solution (e.g, we cannot use %u for uint32_t).  */
11113       error (_("Dwarf Error: DWP file CU version %s doesn't match"
11114                " TU version %s [in DWP file %s]"),
11115              pulongest (dwp_file->cus->version),
11116              pulongest (dwp_file->tus->version), dwp_name.c_str ());
11117     }
11118   dwp_file->version = dwp_file->cus->version;
11119
11120   if (dwp_file->version == 2)
11121     bfd_map_over_sections (dwp_file->dbfd, dwarf2_locate_v2_dwp_sections,
11122                            dwp_file);
11123
11124   dwp_file->loaded_cus = allocate_dwp_loaded_cutus_table (objfile);
11125   dwp_file->loaded_tus = allocate_dwp_loaded_cutus_table (objfile);
11126
11127   if (dwarf_read_debug)
11128     {
11129       fprintf_unfiltered (gdb_stdlog, "DWP file found: %s\n", dwp_file->name);
11130       fprintf_unfiltered (gdb_stdlog,
11131                           "    %s CUs, %s TUs\n",
11132                           pulongest (dwp_file->cus ? dwp_file->cus->nr_units : 0),
11133                           pulongest (dwp_file->tus ? dwp_file->tus->nr_units : 0));
11134     }
11135
11136   return dwp_file;
11137 }
11138
11139 /* Wrapper around open_and_init_dwp_file, only open it once.  */
11140
11141 static struct dwp_file *
11142 get_dwp_file (void)
11143 {
11144   if (! dwarf2_per_objfile->dwp_checked)
11145     {
11146       dwarf2_per_objfile->dwp_file = open_and_init_dwp_file ();
11147       dwarf2_per_objfile->dwp_checked = 1;
11148     }
11149   return dwarf2_per_objfile->dwp_file;
11150 }
11151
11152 /* Subroutine of lookup_dwo_comp_unit, lookup_dwo_type_unit.
11153    Look up the CU/TU with signature SIGNATURE, either in DWO file DWO_NAME
11154    or in the DWP file for the objfile, referenced by THIS_UNIT.
11155    If non-NULL, comp_dir is the DW_AT_comp_dir attribute.
11156    IS_DEBUG_TYPES is non-zero if reading a TU, otherwise read a CU.
11157
11158    This is called, for example, when wanting to read a variable with a
11159    complex location.  Therefore we don't want to do file i/o for every call.
11160    Therefore we don't want to look for a DWO file on every call.
11161    Therefore we first see if we've already seen SIGNATURE in a DWP file,
11162    then we check if we've already seen DWO_NAME, and only THEN do we check
11163    for a DWO file.
11164
11165    The result is a pointer to the dwo_unit object or NULL if we didn't find it
11166    (dwo_id mismatch or couldn't find the DWO/DWP file).  */
11167
11168 static struct dwo_unit *
11169 lookup_dwo_cutu (struct dwarf2_per_cu_data *this_unit,
11170                  const char *dwo_name, const char *comp_dir,
11171                  ULONGEST signature, int is_debug_types)
11172 {
11173   struct objfile *objfile = dwarf2_per_objfile->objfile;
11174   const char *kind = is_debug_types ? "TU" : "CU";
11175   void **dwo_file_slot;
11176   struct dwo_file *dwo_file;
11177   struct dwp_file *dwp_file;
11178
11179   /* First see if there's a DWP file.
11180      If we have a DWP file but didn't find the DWO inside it, don't
11181      look for the original DWO file.  It makes gdb behave differently
11182      depending on whether one is debugging in the build tree.  */
11183
11184   dwp_file = get_dwp_file ();
11185   if (dwp_file != NULL)
11186     {
11187       const struct dwp_hash_table *dwp_htab =
11188         is_debug_types ? dwp_file->tus : dwp_file->cus;
11189
11190       if (dwp_htab != NULL)
11191         {
11192           struct dwo_unit *dwo_cutu =
11193             lookup_dwo_unit_in_dwp (dwp_file, comp_dir,
11194                                     signature, is_debug_types);
11195
11196           if (dwo_cutu != NULL)
11197             {
11198               if (dwarf_read_debug)
11199                 {
11200                   fprintf_unfiltered (gdb_stdlog,
11201                                       "Virtual DWO %s %s found: @%s\n",
11202                                       kind, hex_string (signature),
11203                                       host_address_to_string (dwo_cutu));
11204                 }
11205               return dwo_cutu;
11206             }
11207         }
11208     }
11209   else
11210     {
11211       /* No DWP file, look for the DWO file.  */
11212
11213       dwo_file_slot = lookup_dwo_file_slot (dwo_name, comp_dir);
11214       if (*dwo_file_slot == NULL)
11215         {
11216           /* Read in the file and build a table of the CUs/TUs it contains.  */
11217           *dwo_file_slot = open_and_init_dwo_file (this_unit, dwo_name, comp_dir);
11218         }
11219       /* NOTE: This will be NULL if unable to open the file.  */
11220       dwo_file = (struct dwo_file *) *dwo_file_slot;
11221
11222       if (dwo_file != NULL)
11223         {
11224           struct dwo_unit *dwo_cutu = NULL;
11225
11226           if (is_debug_types && dwo_file->tus)
11227             {
11228               struct dwo_unit find_dwo_cutu;
11229
11230               memset (&find_dwo_cutu, 0, sizeof (find_dwo_cutu));
11231               find_dwo_cutu.signature = signature;
11232               dwo_cutu
11233                 = (struct dwo_unit *) htab_find (dwo_file->tus, &find_dwo_cutu);
11234             }
11235           else if (!is_debug_types && dwo_file->cus)
11236             {
11237               struct dwo_unit find_dwo_cutu;
11238
11239               memset (&find_dwo_cutu, 0, sizeof (find_dwo_cutu));
11240               find_dwo_cutu.signature = signature;
11241               dwo_cutu = (struct dwo_unit *)htab_find (dwo_file->cus,
11242                                                        &find_dwo_cutu);
11243             }
11244
11245           if (dwo_cutu != NULL)
11246             {
11247               if (dwarf_read_debug)
11248                 {
11249                   fprintf_unfiltered (gdb_stdlog, "DWO %s %s(%s) found: @%s\n",
11250                                       kind, dwo_name, hex_string (signature),
11251                                       host_address_to_string (dwo_cutu));
11252                 }
11253               return dwo_cutu;
11254             }
11255         }
11256     }
11257
11258   /* We didn't find it.  This could mean a dwo_id mismatch, or
11259      someone deleted the DWO/DWP file, or the search path isn't set up
11260      correctly to find the file.  */
11261
11262   if (dwarf_read_debug)
11263     {
11264       fprintf_unfiltered (gdb_stdlog, "DWO %s %s(%s) not found\n",
11265                           kind, dwo_name, hex_string (signature));
11266     }
11267
11268   /* This is a warning and not a complaint because it can be caused by
11269      pilot error (e.g., user accidentally deleting the DWO).  */
11270   {
11271     /* Print the name of the DWP file if we looked there, helps the user
11272        better diagnose the problem.  */
11273     char *dwp_text = NULL;
11274     struct cleanup *cleanups;
11275
11276     if (dwp_file != NULL)
11277       dwp_text = xstrprintf (" [in DWP file %s]", lbasename (dwp_file->name));
11278     cleanups = make_cleanup (xfree, dwp_text);
11279
11280     warning (_("Could not find DWO %s %s(%s)%s referenced by %s at offset 0x%x"
11281                " [in module %s]"),
11282              kind, dwo_name, hex_string (signature),
11283              dwp_text != NULL ? dwp_text : "",
11284              this_unit->is_debug_types ? "TU" : "CU",
11285              to_underlying (this_unit->sect_off), objfile_name (objfile));
11286
11287     do_cleanups (cleanups);
11288   }
11289   return NULL;
11290 }
11291
11292 /* Lookup the DWO CU DWO_NAME/SIGNATURE referenced from THIS_CU.
11293    See lookup_dwo_cutu_unit for details.  */
11294
11295 static struct dwo_unit *
11296 lookup_dwo_comp_unit (struct dwarf2_per_cu_data *this_cu,
11297                       const char *dwo_name, const char *comp_dir,
11298                       ULONGEST signature)
11299 {
11300   return lookup_dwo_cutu (this_cu, dwo_name, comp_dir, signature, 0);
11301 }
11302
11303 /* Lookup the DWO TU DWO_NAME/SIGNATURE referenced from THIS_TU.
11304    See lookup_dwo_cutu_unit for details.  */
11305
11306 static struct dwo_unit *
11307 lookup_dwo_type_unit (struct signatured_type *this_tu,
11308                       const char *dwo_name, const char *comp_dir)
11309 {
11310   return lookup_dwo_cutu (&this_tu->per_cu, dwo_name, comp_dir, this_tu->signature, 1);
11311 }
11312
11313 /* Traversal function for queue_and_load_all_dwo_tus.  */
11314
11315 static int
11316 queue_and_load_dwo_tu (void **slot, void *info)
11317 {
11318   struct dwo_unit *dwo_unit = (struct dwo_unit *) *slot;
11319   struct dwarf2_per_cu_data *per_cu = (struct dwarf2_per_cu_data *) info;
11320   ULONGEST signature = dwo_unit->signature;
11321   struct signatured_type *sig_type =
11322     lookup_dwo_signatured_type (per_cu->cu, signature);
11323
11324   if (sig_type != NULL)
11325     {
11326       struct dwarf2_per_cu_data *sig_cu = &sig_type->per_cu;
11327
11328       /* We pass NULL for DEPENDENT_CU because we don't yet know if there's
11329          a real dependency of PER_CU on SIG_TYPE.  That is detected later
11330          while processing PER_CU.  */
11331       if (maybe_queue_comp_unit (NULL, sig_cu, per_cu->cu->language))
11332         load_full_type_unit (sig_cu);
11333       VEC_safe_push (dwarf2_per_cu_ptr, per_cu->imported_symtabs, sig_cu);
11334     }
11335
11336   return 1;
11337 }
11338
11339 /* Queue all TUs contained in the DWO of PER_CU to be read in.
11340    The DWO may have the only definition of the type, though it may not be
11341    referenced anywhere in PER_CU.  Thus we have to load *all* its TUs.
11342    http://sourceware.org/bugzilla/show_bug.cgi?id=15021  */
11343
11344 static void
11345 queue_and_load_all_dwo_tus (struct dwarf2_per_cu_data *per_cu)
11346 {
11347   struct dwo_unit *dwo_unit;
11348   struct dwo_file *dwo_file;
11349
11350   gdb_assert (!per_cu->is_debug_types);
11351   gdb_assert (get_dwp_file () == NULL);
11352   gdb_assert (per_cu->cu != NULL);
11353
11354   dwo_unit = per_cu->cu->dwo_unit;
11355   gdb_assert (dwo_unit != NULL);
11356
11357   dwo_file = dwo_unit->dwo_file;
11358   if (dwo_file->tus != NULL)
11359     htab_traverse_noresize (dwo_file->tus, queue_and_load_dwo_tu, per_cu);
11360 }
11361
11362 /* Free all resources associated with DWO_FILE.
11363    Close the DWO file and munmap the sections.
11364    All memory should be on the objfile obstack.  */
11365
11366 static void
11367 free_dwo_file (struct dwo_file *dwo_file, struct objfile *objfile)
11368 {
11369
11370   /* Note: dbfd is NULL for virtual DWO files.  */
11371   gdb_bfd_unref (dwo_file->dbfd);
11372
11373   VEC_free (dwarf2_section_info_def, dwo_file->sections.types);
11374 }
11375
11376 /* Wrapper for free_dwo_file for use in cleanups.  */
11377
11378 static void
11379 free_dwo_file_cleanup (void *arg)
11380 {
11381   struct dwo_file *dwo_file = (struct dwo_file *) arg;
11382   struct objfile *objfile = dwarf2_per_objfile->objfile;
11383
11384   free_dwo_file (dwo_file, objfile);
11385 }
11386
11387 /* Traversal function for free_dwo_files.  */
11388
11389 static int
11390 free_dwo_file_from_slot (void **slot, void *info)
11391 {
11392   struct dwo_file *dwo_file = (struct dwo_file *) *slot;
11393   struct objfile *objfile = (struct objfile *) info;
11394
11395   free_dwo_file (dwo_file, objfile);
11396
11397   return 1;
11398 }
11399
11400 /* Free all resources associated with DWO_FILES.  */
11401
11402 static void
11403 free_dwo_files (htab_t dwo_files, struct objfile *objfile)
11404 {
11405   htab_traverse_noresize (dwo_files, free_dwo_file_from_slot, objfile);
11406 }
11407 \f
11408 /* Read in various DIEs.  */
11409
11410 /* qsort helper for inherit_abstract_dies.  */
11411
11412 static int
11413 unsigned_int_compar (const void *ap, const void *bp)
11414 {
11415   unsigned int a = *(unsigned int *) ap;
11416   unsigned int b = *(unsigned int *) bp;
11417
11418   return (a > b) - (b > a);
11419 }
11420
11421 /* DW_AT_abstract_origin inherits whole DIEs (not just their attributes).
11422    Inherit only the children of the DW_AT_abstract_origin DIE not being
11423    already referenced by DW_AT_abstract_origin from the children of the
11424    current DIE.  */
11425
11426 static void
11427 inherit_abstract_dies (struct die_info *die, struct dwarf2_cu *cu)
11428 {
11429   struct die_info *child_die;
11430   unsigned die_children_count;
11431   /* CU offsets which were referenced by children of the current DIE.  */
11432   sect_offset *offsets;
11433   sect_offset *offsets_end, *offsetp;
11434   /* Parent of DIE - referenced by DW_AT_abstract_origin.  */
11435   struct die_info *origin_die;
11436   /* Iterator of the ORIGIN_DIE children.  */
11437   struct die_info *origin_child_die;
11438   struct cleanup *cleanups;
11439   struct attribute *attr;
11440   struct dwarf2_cu *origin_cu;
11441   struct pending **origin_previous_list_in_scope;
11442
11443   attr = dwarf2_attr (die, DW_AT_abstract_origin, cu);
11444   if (!attr)
11445     return;
11446
11447   /* Note that following die references may follow to a die in a
11448      different cu.  */
11449
11450   origin_cu = cu;
11451   origin_die = follow_die_ref (die, attr, &origin_cu);
11452
11453   /* We're inheriting ORIGIN's children into the scope we'd put DIE's
11454      symbols in.  */
11455   origin_previous_list_in_scope = origin_cu->list_in_scope;
11456   origin_cu->list_in_scope = cu->list_in_scope;
11457
11458   if (die->tag != origin_die->tag
11459       && !(die->tag == DW_TAG_inlined_subroutine
11460            && origin_die->tag == DW_TAG_subprogram))
11461     complaint (&symfile_complaints,
11462                _("DIE 0x%x and its abstract origin 0x%x have different tags"),
11463                to_underlying (die->sect_off),
11464                to_underlying (origin_die->sect_off));
11465
11466   child_die = die->child;
11467   die_children_count = 0;
11468   while (child_die && child_die->tag)
11469     {
11470       child_die = sibling_die (child_die);
11471       die_children_count++;
11472     }
11473   offsets = XNEWVEC (sect_offset, die_children_count);
11474   cleanups = make_cleanup (xfree, offsets);
11475
11476   offsets_end = offsets;
11477   for (child_die = die->child;
11478        child_die && child_die->tag;
11479        child_die = sibling_die (child_die))
11480     {
11481       struct die_info *child_origin_die;
11482       struct dwarf2_cu *child_origin_cu;
11483
11484       /* We are trying to process concrete instance entries:
11485          DW_TAG_call_site DIEs indeed have a DW_AT_abstract_origin tag, but
11486          it's not relevant to our analysis here. i.e. detecting DIEs that are
11487          present in the abstract instance but not referenced in the concrete
11488          one.  */
11489       if (child_die->tag == DW_TAG_call_site
11490           || child_die->tag == DW_TAG_GNU_call_site)
11491         continue;
11492
11493       /* For each CHILD_DIE, find the corresponding child of
11494          ORIGIN_DIE.  If there is more than one layer of
11495          DW_AT_abstract_origin, follow them all; there shouldn't be,
11496          but GCC versions at least through 4.4 generate this (GCC PR
11497          40573).  */
11498       child_origin_die = child_die;
11499       child_origin_cu = cu;
11500       while (1)
11501         {
11502           attr = dwarf2_attr (child_origin_die, DW_AT_abstract_origin,
11503                               child_origin_cu);
11504           if (attr == NULL)
11505             break;
11506           child_origin_die = follow_die_ref (child_origin_die, attr,
11507                                              &child_origin_cu);
11508         }
11509
11510       /* According to DWARF3 3.3.8.2 #3 new entries without their abstract
11511          counterpart may exist.  */
11512       if (child_origin_die != child_die)
11513         {
11514           if (child_die->tag != child_origin_die->tag
11515               && !(child_die->tag == DW_TAG_inlined_subroutine
11516                    && child_origin_die->tag == DW_TAG_subprogram))
11517             complaint (&symfile_complaints,
11518                        _("Child DIE 0x%x and its abstract origin 0x%x have "
11519                          "different tags"),
11520                        to_underlying (child_die->sect_off),
11521                        to_underlying (child_origin_die->sect_off));
11522           if (child_origin_die->parent != origin_die)
11523             complaint (&symfile_complaints,
11524                        _("Child DIE 0x%x and its abstract origin 0x%x have "
11525                          "different parents"),
11526                        to_underlying (child_die->sect_off),
11527                        to_underlying (child_origin_die->sect_off));
11528           else
11529             *offsets_end++ = child_origin_die->sect_off;
11530         }
11531     }
11532   qsort (offsets, offsets_end - offsets, sizeof (*offsets),
11533          unsigned_int_compar);
11534   for (offsetp = offsets + 1; offsetp < offsets_end; offsetp++)
11535     if (offsetp[-1] == *offsetp)
11536       complaint (&symfile_complaints,
11537                  _("Multiple children of DIE 0x%x refer "
11538                    "to DIE 0x%x as their abstract origin"),
11539                  to_underlying (die->sect_off), to_underlying (*offsetp));
11540
11541   offsetp = offsets;
11542   origin_child_die = origin_die->child;
11543   while (origin_child_die && origin_child_die->tag)
11544     {
11545       /* Is ORIGIN_CHILD_DIE referenced by any of the DIE children?  */
11546       while (offsetp < offsets_end
11547              && *offsetp < origin_child_die->sect_off)
11548         offsetp++;
11549       if (offsetp >= offsets_end
11550           || *offsetp > origin_child_die->sect_off)
11551         {
11552           /* Found that ORIGIN_CHILD_DIE is really not referenced.
11553              Check whether we're already processing ORIGIN_CHILD_DIE.
11554              This can happen with mutually referenced abstract_origins.
11555              PR 16581.  */
11556           if (!origin_child_die->in_process)
11557             process_die (origin_child_die, origin_cu);
11558         }
11559       origin_child_die = sibling_die (origin_child_die);
11560     }
11561   origin_cu->list_in_scope = origin_previous_list_in_scope;
11562
11563   do_cleanups (cleanups);
11564 }
11565
11566 static void
11567 read_func_scope (struct die_info *die, struct dwarf2_cu *cu)
11568 {
11569   struct objfile *objfile = cu->objfile;
11570   struct gdbarch *gdbarch = get_objfile_arch (objfile);
11571   struct context_stack *newobj;
11572   CORE_ADDR lowpc;
11573   CORE_ADDR highpc;
11574   struct die_info *child_die;
11575   struct attribute *attr, *call_line, *call_file;
11576   const char *name;
11577   CORE_ADDR baseaddr;
11578   struct block *block;
11579   int inlined_func = (die->tag == DW_TAG_inlined_subroutine);
11580   VEC (symbolp) *template_args = NULL;
11581   struct template_symbol *templ_func = NULL;
11582
11583   if (inlined_func)
11584     {
11585       /* If we do not have call site information, we can't show the
11586          caller of this inlined function.  That's too confusing, so
11587          only use the scope for local variables.  */
11588       call_line = dwarf2_attr (die, DW_AT_call_line, cu);
11589       call_file = dwarf2_attr (die, DW_AT_call_file, cu);
11590       if (call_line == NULL || call_file == NULL)
11591         {
11592           read_lexical_block_scope (die, cu);
11593           return;
11594         }
11595     }
11596
11597   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
11598
11599   name = dwarf2_name (die, cu);
11600
11601   /* Ignore functions with missing or empty names.  These are actually
11602      illegal according to the DWARF standard.  */
11603   if (name == NULL)
11604     {
11605       complaint (&symfile_complaints,
11606                  _("missing name for subprogram DIE at %d"),
11607                  to_underlying (die->sect_off));
11608       return;
11609     }
11610
11611   /* Ignore functions with missing or invalid low and high pc attributes.  */
11612   if (dwarf2_get_pc_bounds (die, &lowpc, &highpc, cu, NULL)
11613       <= PC_BOUNDS_INVALID)
11614     {
11615       attr = dwarf2_attr (die, DW_AT_external, cu);
11616       if (!attr || !DW_UNSND (attr))
11617         complaint (&symfile_complaints,
11618                    _("cannot get low and high bounds "
11619                      "for subprogram DIE at %d"),
11620                    to_underlying (die->sect_off));
11621       return;
11622     }
11623
11624   lowpc = gdbarch_adjust_dwarf2_addr (gdbarch, lowpc + baseaddr);
11625   highpc = gdbarch_adjust_dwarf2_addr (gdbarch, highpc + baseaddr);
11626
11627   /* If we have any template arguments, then we must allocate a
11628      different sort of symbol.  */
11629   for (child_die = die->child; child_die; child_die = sibling_die (child_die))
11630     {
11631       if (child_die->tag == DW_TAG_template_type_param
11632           || child_die->tag == DW_TAG_template_value_param)
11633         {
11634           templ_func = allocate_template_symbol (objfile);
11635           templ_func->base.is_cplus_template_function = 1;
11636           break;
11637         }
11638     }
11639
11640   newobj = push_context (0, lowpc);
11641   newobj->name = new_symbol_full (die, read_type_die (die, cu), cu,
11642                                (struct symbol *) templ_func);
11643
11644   /* If there is a location expression for DW_AT_frame_base, record
11645      it.  */
11646   attr = dwarf2_attr (die, DW_AT_frame_base, cu);
11647   if (attr)
11648     dwarf2_symbol_mark_computed (attr, newobj->name, cu, 1);
11649
11650   /* If there is a location for the static link, record it.  */
11651   newobj->static_link = NULL;
11652   attr = dwarf2_attr (die, DW_AT_static_link, cu);
11653   if (attr)
11654     {
11655       newobj->static_link
11656         = XOBNEW (&objfile->objfile_obstack, struct dynamic_prop);
11657       attr_to_dynamic_prop (attr, die, cu, newobj->static_link);
11658     }
11659
11660   cu->list_in_scope = &local_symbols;
11661
11662   if (die->child != NULL)
11663     {
11664       child_die = die->child;
11665       while (child_die && child_die->tag)
11666         {
11667           if (child_die->tag == DW_TAG_template_type_param
11668               || child_die->tag == DW_TAG_template_value_param)
11669             {
11670               struct symbol *arg = new_symbol (child_die, NULL, cu);
11671
11672               if (arg != NULL)
11673                 VEC_safe_push (symbolp, template_args, arg);
11674             }
11675           else
11676             process_die (child_die, cu);
11677           child_die = sibling_die (child_die);
11678         }
11679     }
11680
11681   inherit_abstract_dies (die, cu);
11682
11683   /* If we have a DW_AT_specification, we might need to import using
11684      directives from the context of the specification DIE.  See the
11685      comment in determine_prefix.  */
11686   if (cu->language == language_cplus
11687       && dwarf2_attr (die, DW_AT_specification, cu))
11688     {
11689       struct dwarf2_cu *spec_cu = cu;
11690       struct die_info *spec_die = die_specification (die, &spec_cu);
11691
11692       while (spec_die)
11693         {
11694           child_die = spec_die->child;
11695           while (child_die && child_die->tag)
11696             {
11697               if (child_die->tag == DW_TAG_imported_module)
11698                 process_die (child_die, spec_cu);
11699               child_die = sibling_die (child_die);
11700             }
11701
11702           /* In some cases, GCC generates specification DIEs that
11703              themselves contain DW_AT_specification attributes.  */
11704           spec_die = die_specification (spec_die, &spec_cu);
11705         }
11706     }
11707
11708   newobj = pop_context ();
11709   /* Make a block for the local symbols within.  */
11710   block = finish_block (newobj->name, &local_symbols, newobj->old_blocks,
11711                         newobj->static_link, lowpc, highpc);
11712
11713   /* For C++, set the block's scope.  */
11714   if ((cu->language == language_cplus
11715        || cu->language == language_fortran
11716        || cu->language == language_d
11717        || cu->language == language_rust)
11718       && cu->processing_has_namespace_info)
11719     block_set_scope (block, determine_prefix (die, cu),
11720                      &objfile->objfile_obstack);
11721
11722   /* If we have address ranges, record them.  */
11723   dwarf2_record_block_ranges (die, block, baseaddr, cu);
11724
11725   gdbarch_make_symbol_special (gdbarch, newobj->name, objfile);
11726
11727   /* Attach template arguments to function.  */
11728   if (! VEC_empty (symbolp, template_args))
11729     {
11730       gdb_assert (templ_func != NULL);
11731
11732       templ_func->n_template_arguments = VEC_length (symbolp, template_args);
11733       templ_func->template_arguments
11734         = XOBNEWVEC (&objfile->objfile_obstack, struct symbol *,
11735                      templ_func->n_template_arguments);
11736       memcpy (templ_func->template_arguments,
11737               VEC_address (symbolp, template_args),
11738               (templ_func->n_template_arguments * sizeof (struct symbol *)));
11739       VEC_free (symbolp, template_args);
11740     }
11741
11742   /* In C++, we can have functions nested inside functions (e.g., when
11743      a function declares a class that has methods).  This means that
11744      when we finish processing a function scope, we may need to go
11745      back to building a containing block's symbol lists.  */
11746   local_symbols = newobj->locals;
11747   local_using_directives = newobj->local_using_directives;
11748
11749   /* If we've finished processing a top-level function, subsequent
11750      symbols go in the file symbol list.  */
11751   if (outermost_context_p ())
11752     cu->list_in_scope = &file_symbols;
11753 }
11754
11755 /* Process all the DIES contained within a lexical block scope.  Start
11756    a new scope, process the dies, and then close the scope.  */
11757
11758 static void
11759 read_lexical_block_scope (struct die_info *die, struct dwarf2_cu *cu)
11760 {
11761   struct objfile *objfile = cu->objfile;
11762   struct gdbarch *gdbarch = get_objfile_arch (objfile);
11763   struct context_stack *newobj;
11764   CORE_ADDR lowpc, highpc;
11765   struct die_info *child_die;
11766   CORE_ADDR baseaddr;
11767
11768   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
11769
11770   /* Ignore blocks with missing or invalid low and high pc attributes.  */
11771   /* ??? Perhaps consider discontiguous blocks defined by DW_AT_ranges
11772      as multiple lexical blocks?  Handling children in a sane way would
11773      be nasty.  Might be easier to properly extend generic blocks to
11774      describe ranges.  */
11775   switch (dwarf2_get_pc_bounds (die, &lowpc, &highpc, cu, NULL))
11776     {
11777     case PC_BOUNDS_NOT_PRESENT:
11778       /* DW_TAG_lexical_block has no attributes, process its children as if
11779          there was no wrapping by that DW_TAG_lexical_block.
11780          GCC does no longer produces such DWARF since GCC r224161.  */
11781       for (child_die = die->child;
11782            child_die != NULL && child_die->tag;
11783            child_die = sibling_die (child_die))
11784         process_die (child_die, cu);
11785       return;
11786     case PC_BOUNDS_INVALID:
11787       return;
11788     }
11789   lowpc = gdbarch_adjust_dwarf2_addr (gdbarch, lowpc + baseaddr);
11790   highpc = gdbarch_adjust_dwarf2_addr (gdbarch, highpc + baseaddr);
11791
11792   push_context (0, lowpc);
11793   if (die->child != NULL)
11794     {
11795       child_die = die->child;
11796       while (child_die && child_die->tag)
11797         {
11798           process_die (child_die, cu);
11799           child_die = sibling_die (child_die);
11800         }
11801     }
11802   inherit_abstract_dies (die, cu);
11803   newobj = pop_context ();
11804
11805   if (local_symbols != NULL || local_using_directives != NULL)
11806     {
11807       struct block *block
11808         = finish_block (0, &local_symbols, newobj->old_blocks, NULL,
11809                         newobj->start_addr, highpc);
11810
11811       /* Note that recording ranges after traversing children, as we
11812          do here, means that recording a parent's ranges entails
11813          walking across all its children's ranges as they appear in
11814          the address map, which is quadratic behavior.
11815
11816          It would be nicer to record the parent's ranges before
11817          traversing its children, simply overriding whatever you find
11818          there.  But since we don't even decide whether to create a
11819          block until after we've traversed its children, that's hard
11820          to do.  */
11821       dwarf2_record_block_ranges (die, block, baseaddr, cu);
11822     }
11823   local_symbols = newobj->locals;
11824   local_using_directives = newobj->local_using_directives;
11825 }
11826
11827 /* Read in DW_TAG_call_site and insert it to CU->call_site_htab.  */
11828
11829 static void
11830 read_call_site_scope (struct die_info *die, struct dwarf2_cu *cu)
11831 {
11832   struct objfile *objfile = cu->objfile;
11833   struct gdbarch *gdbarch = get_objfile_arch (objfile);
11834   CORE_ADDR pc, baseaddr;
11835   struct attribute *attr;
11836   struct call_site *call_site, call_site_local;
11837   void **slot;
11838   int nparams;
11839   struct die_info *child_die;
11840
11841   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
11842
11843   attr = dwarf2_attr (die, DW_AT_call_return_pc, cu);
11844   if (attr == NULL)
11845     {
11846       /* This was a pre-DWARF-5 GNU extension alias
11847          for DW_AT_call_return_pc.  */
11848       attr = dwarf2_attr (die, DW_AT_low_pc, cu);
11849     }
11850   if (!attr)
11851     {
11852       complaint (&symfile_complaints,
11853                  _("missing DW_AT_call_return_pc for DW_TAG_call_site "
11854                    "DIE 0x%x [in module %s]"),
11855                  to_underlying (die->sect_off), objfile_name (objfile));
11856       return;
11857     }
11858   pc = attr_value_as_address (attr) + baseaddr;
11859   pc = gdbarch_adjust_dwarf2_addr (gdbarch, pc);
11860
11861   if (cu->call_site_htab == NULL)
11862     cu->call_site_htab = htab_create_alloc_ex (16, core_addr_hash, core_addr_eq,
11863                                                NULL, &objfile->objfile_obstack,
11864                                                hashtab_obstack_allocate, NULL);
11865   call_site_local.pc = pc;
11866   slot = htab_find_slot (cu->call_site_htab, &call_site_local, INSERT);
11867   if (*slot != NULL)
11868     {
11869       complaint (&symfile_complaints,
11870                  _("Duplicate PC %s for DW_TAG_call_site "
11871                    "DIE 0x%x [in module %s]"),
11872                  paddress (gdbarch, pc), to_underlying (die->sect_off),
11873                  objfile_name (objfile));
11874       return;
11875     }
11876
11877   /* Count parameters at the caller.  */
11878
11879   nparams = 0;
11880   for (child_die = die->child; child_die && child_die->tag;
11881        child_die = sibling_die (child_die))
11882     {
11883       if (child_die->tag != DW_TAG_call_site_parameter
11884           && child_die->tag != DW_TAG_GNU_call_site_parameter)
11885         {
11886           complaint (&symfile_complaints,
11887                      _("Tag %d is not DW_TAG_call_site_parameter in "
11888                        "DW_TAG_call_site child DIE 0x%x [in module %s]"),
11889                      child_die->tag, to_underlying (child_die->sect_off),
11890                      objfile_name (objfile));
11891           continue;
11892         }
11893
11894       nparams++;
11895     }
11896
11897   call_site
11898     = ((struct call_site *)
11899        obstack_alloc (&objfile->objfile_obstack,
11900                       sizeof (*call_site)
11901                       + (sizeof (*call_site->parameter) * (nparams - 1))));
11902   *slot = call_site;
11903   memset (call_site, 0, sizeof (*call_site) - sizeof (*call_site->parameter));
11904   call_site->pc = pc;
11905
11906   if (dwarf2_flag_true_p (die, DW_AT_call_tail_call, cu)
11907       || dwarf2_flag_true_p (die, DW_AT_GNU_tail_call, cu))
11908     {
11909       struct die_info *func_die;
11910
11911       /* Skip also over DW_TAG_inlined_subroutine.  */
11912       for (func_die = die->parent;
11913            func_die && func_die->tag != DW_TAG_subprogram
11914            && func_die->tag != DW_TAG_subroutine_type;
11915            func_die = func_die->parent);
11916
11917       /* DW_AT_call_all_calls is a superset
11918          of DW_AT_call_all_tail_calls.  */
11919       if (func_die
11920           && !dwarf2_flag_true_p (func_die, DW_AT_call_all_calls, cu)
11921           && !dwarf2_flag_true_p (func_die, DW_AT_GNU_all_call_sites, cu)
11922           && !dwarf2_flag_true_p (func_die, DW_AT_call_all_tail_calls, cu)
11923           && !dwarf2_flag_true_p (func_die, DW_AT_GNU_all_tail_call_sites, cu))
11924         {
11925           /* TYPE_TAIL_CALL_LIST is not interesting in functions where it is
11926              not complete.  But keep CALL_SITE for look ups via call_site_htab,
11927              both the initial caller containing the real return address PC and
11928              the final callee containing the current PC of a chain of tail
11929              calls do not need to have the tail call list complete.  But any
11930              function candidate for a virtual tail call frame searched via
11931              TYPE_TAIL_CALL_LIST must have the tail call list complete to be
11932              determined unambiguously.  */
11933         }
11934       else
11935         {
11936           struct type *func_type = NULL;
11937
11938           if (func_die)
11939             func_type = get_die_type (func_die, cu);
11940           if (func_type != NULL)
11941             {
11942               gdb_assert (TYPE_CODE (func_type) == TYPE_CODE_FUNC);
11943
11944               /* Enlist this call site to the function.  */
11945               call_site->tail_call_next = TYPE_TAIL_CALL_LIST (func_type);
11946               TYPE_TAIL_CALL_LIST (func_type) = call_site;
11947             }
11948           else
11949             complaint (&symfile_complaints,
11950                        _("Cannot find function owning DW_TAG_call_site "
11951                          "DIE 0x%x [in module %s]"),
11952                        to_underlying (die->sect_off), objfile_name (objfile));
11953         }
11954     }
11955
11956   attr = dwarf2_attr (die, DW_AT_call_target, cu);
11957   if (attr == NULL)
11958     attr = dwarf2_attr (die, DW_AT_GNU_call_site_target, cu);
11959   if (attr == NULL)
11960     attr = dwarf2_attr (die, DW_AT_call_origin, cu);
11961   if (attr == NULL)
11962     {
11963       /* This was a pre-DWARF-5 GNU extension alias for DW_AT_call_origin.  */
11964       attr = dwarf2_attr (die, DW_AT_abstract_origin, cu);
11965     }
11966   SET_FIELD_DWARF_BLOCK (call_site->target, NULL);
11967   if (!attr || (attr_form_is_block (attr) && DW_BLOCK (attr)->size == 0))
11968     /* Keep NULL DWARF_BLOCK.  */;
11969   else if (attr_form_is_block (attr))
11970     {
11971       struct dwarf2_locexpr_baton *dlbaton;
11972
11973       dlbaton = XOBNEW (&objfile->objfile_obstack, struct dwarf2_locexpr_baton);
11974       dlbaton->data = DW_BLOCK (attr)->data;
11975       dlbaton->size = DW_BLOCK (attr)->size;
11976       dlbaton->per_cu = cu->per_cu;
11977
11978       SET_FIELD_DWARF_BLOCK (call_site->target, dlbaton);
11979     }
11980   else if (attr_form_is_ref (attr))
11981     {
11982       struct dwarf2_cu *target_cu = cu;
11983       struct die_info *target_die;
11984
11985       target_die = follow_die_ref (die, attr, &target_cu);
11986       gdb_assert (target_cu->objfile == objfile);
11987       if (die_is_declaration (target_die, target_cu))
11988         {
11989           const char *target_physname;
11990
11991           /* Prefer the mangled name; otherwise compute the demangled one.  */
11992           target_physname = dwarf2_string_attr (target_die,
11993                                                 DW_AT_linkage_name,
11994                                                 target_cu);
11995           if (target_physname == NULL)
11996             target_physname = dwarf2_string_attr (target_die,
11997                                                  DW_AT_MIPS_linkage_name,
11998                                                  target_cu);
11999           if (target_physname == NULL)
12000             target_physname = dwarf2_physname (NULL, target_die, target_cu);
12001           if (target_physname == NULL)
12002             complaint (&symfile_complaints,
12003                        _("DW_AT_call_target target DIE has invalid "
12004                          "physname, for referencing DIE 0x%x [in module %s]"),
12005                        to_underlying (die->sect_off), objfile_name (objfile));
12006           else
12007             SET_FIELD_PHYSNAME (call_site->target, target_physname);
12008         }
12009       else
12010         {
12011           CORE_ADDR lowpc;
12012
12013           /* DW_AT_entry_pc should be preferred.  */
12014           if (dwarf2_get_pc_bounds (target_die, &lowpc, NULL, target_cu, NULL)
12015               <= PC_BOUNDS_INVALID)
12016             complaint (&symfile_complaints,
12017                        _("DW_AT_call_target target DIE has invalid "
12018                          "low pc, for referencing DIE 0x%x [in module %s]"),
12019                        to_underlying (die->sect_off), objfile_name (objfile));
12020           else
12021             {
12022               lowpc = gdbarch_adjust_dwarf2_addr (gdbarch, lowpc + baseaddr);
12023               SET_FIELD_PHYSADDR (call_site->target, lowpc);
12024             }
12025         }
12026     }
12027   else
12028     complaint (&symfile_complaints,
12029                _("DW_TAG_call_site DW_AT_call_target is neither "
12030                  "block nor reference, for DIE 0x%x [in module %s]"),
12031                to_underlying (die->sect_off), objfile_name (objfile));
12032
12033   call_site->per_cu = cu->per_cu;
12034
12035   for (child_die = die->child;
12036        child_die && child_die->tag;
12037        child_die = sibling_die (child_die))
12038     {
12039       struct call_site_parameter *parameter;
12040       struct attribute *loc, *origin;
12041
12042       if (child_die->tag != DW_TAG_call_site_parameter
12043           && child_die->tag != DW_TAG_GNU_call_site_parameter)
12044         {
12045           /* Already printed the complaint above.  */
12046           continue;
12047         }
12048
12049       gdb_assert (call_site->parameter_count < nparams);
12050       parameter = &call_site->parameter[call_site->parameter_count];
12051
12052       /* DW_AT_location specifies the register number or DW_AT_abstract_origin
12053          specifies DW_TAG_formal_parameter.  Value of the data assumed for the
12054          register is contained in DW_AT_call_value.  */
12055
12056       loc = dwarf2_attr (child_die, DW_AT_location, cu);
12057       origin = dwarf2_attr (child_die, DW_AT_call_parameter, cu);
12058       if (origin == NULL)
12059         {
12060           /* This was a pre-DWARF-5 GNU extension alias
12061              for DW_AT_call_parameter.  */
12062           origin = dwarf2_attr (child_die, DW_AT_abstract_origin, cu);
12063         }
12064       if (loc == NULL && origin != NULL && attr_form_is_ref (origin))
12065         {
12066           parameter->kind = CALL_SITE_PARAMETER_PARAM_OFFSET;
12067
12068           sect_offset sect_off
12069             = (sect_offset) dwarf2_get_ref_die_offset (origin);
12070           if (!offset_in_cu_p (&cu->header, sect_off))
12071             {
12072               /* As DW_OP_GNU_parameter_ref uses CU-relative offset this
12073                  binding can be done only inside one CU.  Such referenced DIE
12074                  therefore cannot be even moved to DW_TAG_partial_unit.  */
12075               complaint (&symfile_complaints,
12076                          _("DW_AT_call_parameter offset is not in CU for "
12077                            "DW_TAG_call_site child DIE 0x%x [in module %s]"),
12078                          to_underlying (child_die->sect_off),
12079                          objfile_name (objfile));
12080               continue;
12081             }
12082           parameter->u.param_cu_off
12083             = (cu_offset) (sect_off - cu->header.sect_off);
12084         }
12085       else if (loc == NULL || origin != NULL || !attr_form_is_block (loc))
12086         {
12087           complaint (&symfile_complaints,
12088                      _("No DW_FORM_block* DW_AT_location for "
12089                        "DW_TAG_call_site child DIE 0x%x [in module %s]"),
12090                      to_underlying (child_die->sect_off), objfile_name (objfile));
12091           continue;
12092         }
12093       else
12094         {
12095           parameter->u.dwarf_reg = dwarf_block_to_dwarf_reg
12096             (DW_BLOCK (loc)->data, &DW_BLOCK (loc)->data[DW_BLOCK (loc)->size]);
12097           if (parameter->u.dwarf_reg != -1)
12098             parameter->kind = CALL_SITE_PARAMETER_DWARF_REG;
12099           else if (dwarf_block_to_sp_offset (gdbarch, DW_BLOCK (loc)->data,
12100                                     &DW_BLOCK (loc)->data[DW_BLOCK (loc)->size],
12101                                              &parameter->u.fb_offset))
12102             parameter->kind = CALL_SITE_PARAMETER_FB_OFFSET;
12103           else
12104             {
12105               complaint (&symfile_complaints,
12106                          _("Only single DW_OP_reg or DW_OP_fbreg is supported "
12107                            "for DW_FORM_block* DW_AT_location is supported for "
12108                            "DW_TAG_call_site child DIE 0x%x "
12109                            "[in module %s]"),
12110                          to_underlying (child_die->sect_off),
12111                          objfile_name (objfile));
12112               continue;
12113             }
12114         }
12115
12116       attr = dwarf2_attr (child_die, DW_AT_call_value, cu);
12117       if (attr == NULL)
12118         attr = dwarf2_attr (child_die, DW_AT_GNU_call_site_value, cu);
12119       if (!attr_form_is_block (attr))
12120         {
12121           complaint (&symfile_complaints,
12122                      _("No DW_FORM_block* DW_AT_call_value for "
12123                        "DW_TAG_call_site child DIE 0x%x [in module %s]"),
12124                      to_underlying (child_die->sect_off),
12125                      objfile_name (objfile));
12126           continue;
12127         }
12128       parameter->value = DW_BLOCK (attr)->data;
12129       parameter->value_size = DW_BLOCK (attr)->size;
12130
12131       /* Parameters are not pre-cleared by memset above.  */
12132       parameter->data_value = NULL;
12133       parameter->data_value_size = 0;
12134       call_site->parameter_count++;
12135
12136       attr = dwarf2_attr (child_die, DW_AT_call_data_value, cu);
12137       if (attr == NULL)
12138         attr = dwarf2_attr (child_die, DW_AT_GNU_call_site_data_value, cu);
12139       if (attr)
12140         {
12141           if (!attr_form_is_block (attr))
12142             complaint (&symfile_complaints,
12143                        _("No DW_FORM_block* DW_AT_call_data_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           else
12148             {
12149               parameter->data_value = DW_BLOCK (attr)->data;
12150               parameter->data_value_size = DW_BLOCK (attr)->size;
12151             }
12152         }
12153     }
12154 }
12155
12156 /* Call CALLBACK from DW_AT_ranges attribute value OFFSET
12157    reading .debug_rnglists.
12158    Callback's type should be:
12159     void (CORE_ADDR range_beginning, CORE_ADDR range_end)
12160    Return true if the attributes are present and valid, otherwise,
12161    return false.  */
12162
12163 template <typename Callback>
12164 static bool
12165 dwarf2_rnglists_process (unsigned offset, struct dwarf2_cu *cu,
12166                          Callback &&callback)
12167 {
12168   struct objfile *objfile = cu->objfile;
12169   struct gdbarch *gdbarch = get_objfile_arch (objfile);
12170   struct comp_unit_head *cu_header = &cu->header;
12171   bfd *obfd = objfile->obfd;
12172   unsigned int addr_size = cu_header->addr_size;
12173   CORE_ADDR mask = ~(~(CORE_ADDR)1 << (addr_size * 8 - 1));
12174   /* Base address selection entry.  */
12175   CORE_ADDR base;
12176   int found_base;
12177   unsigned int dummy;
12178   const gdb_byte *buffer;
12179   CORE_ADDR low = 0;
12180   CORE_ADDR high = 0;
12181   CORE_ADDR baseaddr;
12182   bool overflow = false;
12183
12184   found_base = cu->base_known;
12185   base = cu->base_address;
12186
12187   dwarf2_read_section (objfile, &dwarf2_per_objfile->rnglists);
12188   if (offset >= dwarf2_per_objfile->rnglists.size)
12189     {
12190       complaint (&symfile_complaints,
12191                  _("Offset %d out of bounds for DW_AT_ranges attribute"),
12192                  offset);
12193       return false;
12194     }
12195   buffer = dwarf2_per_objfile->rnglists.buffer + offset;
12196
12197   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
12198
12199   while (1)
12200     {
12201       /* Initialize it due to a false compiler warning.  */
12202       CORE_ADDR range_beginning = 0, range_end = 0;
12203       const gdb_byte *buf_end = (dwarf2_per_objfile->rnglists.buffer
12204                                  + dwarf2_per_objfile->rnglists.size);
12205       unsigned int bytes_read;
12206
12207       if (buffer == buf_end)
12208         {
12209           overflow = true;
12210           break;
12211         }
12212       const auto rlet = static_cast<enum dwarf_range_list_entry>(*buffer++);
12213       switch (rlet)
12214         {
12215         case DW_RLE_end_of_list:
12216           break;
12217         case DW_RLE_base_address:
12218           if (buffer + cu->header.addr_size > buf_end)
12219             {
12220               overflow = true;
12221               break;
12222             }
12223           base = read_address (obfd, buffer, cu, &bytes_read);
12224           found_base = 1;
12225           buffer += bytes_read;
12226           break;
12227         case DW_RLE_start_length:
12228           if (buffer + cu->header.addr_size > buf_end)
12229             {
12230               overflow = true;
12231               break;
12232             }
12233           range_beginning = read_address (obfd, buffer, cu, &bytes_read);
12234           buffer += bytes_read;
12235           range_end = (range_beginning
12236                        + read_unsigned_leb128 (obfd, buffer, &bytes_read));
12237           buffer += bytes_read;
12238           if (buffer > buf_end)
12239             {
12240               overflow = true;
12241               break;
12242             }
12243           break;
12244         case DW_RLE_offset_pair:
12245           range_beginning = read_unsigned_leb128 (obfd, buffer, &bytes_read);
12246           buffer += bytes_read;
12247           if (buffer > buf_end)
12248             {
12249               overflow = true;
12250               break;
12251             }
12252           range_end = read_unsigned_leb128 (obfd, buffer, &bytes_read);
12253           buffer += bytes_read;
12254           if (buffer > buf_end)
12255             {
12256               overflow = true;
12257               break;
12258             }
12259           break;
12260         case DW_RLE_start_end:
12261           if (buffer + 2 * cu->header.addr_size > buf_end)
12262             {
12263               overflow = true;
12264               break;
12265             }
12266           range_beginning = read_address (obfd, buffer, cu, &bytes_read);
12267           buffer += bytes_read;
12268           range_end = read_address (obfd, buffer, cu, &bytes_read);
12269           buffer += bytes_read;
12270           break;
12271         default:
12272           complaint (&symfile_complaints,
12273                      _("Invalid .debug_rnglists data (no base address)"));
12274           return false;
12275         }
12276       if (rlet == DW_RLE_end_of_list || overflow)
12277         break;
12278       if (rlet == DW_RLE_base_address)
12279         continue;
12280
12281       if (!found_base)
12282         {
12283           /* We have no valid base address for the ranges
12284              data.  */
12285           complaint (&symfile_complaints,
12286                      _("Invalid .debug_rnglists data (no base address)"));
12287           return false;
12288         }
12289
12290       if (range_beginning > range_end)
12291         {
12292           /* Inverted range entries are invalid.  */
12293           complaint (&symfile_complaints,
12294                      _("Invalid .debug_rnglists data (inverted range)"));
12295           return false;
12296         }
12297
12298       /* Empty range entries have no effect.  */
12299       if (range_beginning == range_end)
12300         continue;
12301
12302       range_beginning += base;
12303       range_end += base;
12304
12305       /* A not-uncommon case of bad debug info.
12306          Don't pollute the addrmap with bad data.  */
12307       if (range_beginning + baseaddr == 0
12308           && !dwarf2_per_objfile->has_section_at_zero)
12309         {
12310           complaint (&symfile_complaints,
12311                      _(".debug_rnglists entry has start address of zero"
12312                        " [in module %s]"), objfile_name (objfile));
12313           continue;
12314         }
12315
12316       callback (range_beginning, range_end);
12317     }
12318
12319   if (overflow)
12320     {
12321       complaint (&symfile_complaints,
12322                  _("Offset %d is not terminated "
12323                    "for DW_AT_ranges attribute"),
12324                  offset);
12325       return false;
12326     }
12327
12328   return true;
12329 }
12330
12331 /* Call CALLBACK from DW_AT_ranges attribute value OFFSET reading .debug_ranges.
12332    Callback's type should be:
12333     void (CORE_ADDR range_beginning, CORE_ADDR range_end)
12334    Return 1 if the attributes are present and valid, otherwise, return 0.  */
12335
12336 template <typename Callback>
12337 static int
12338 dwarf2_ranges_process (unsigned offset, struct dwarf2_cu *cu,
12339                        Callback &&callback)
12340 {
12341   struct objfile *objfile = cu->objfile;
12342   struct gdbarch *gdbarch = get_objfile_arch (objfile);
12343   struct comp_unit_head *cu_header = &cu->header;
12344   bfd *obfd = objfile->obfd;
12345   unsigned int addr_size = cu_header->addr_size;
12346   CORE_ADDR mask = ~(~(CORE_ADDR)1 << (addr_size * 8 - 1));
12347   /* Base address selection entry.  */
12348   CORE_ADDR base;
12349   int found_base;
12350   unsigned int dummy;
12351   const gdb_byte *buffer;
12352   CORE_ADDR baseaddr;
12353
12354   if (cu_header->version >= 5)
12355     return dwarf2_rnglists_process (offset, cu, callback);
12356
12357   found_base = cu->base_known;
12358   base = cu->base_address;
12359
12360   dwarf2_read_section (objfile, &dwarf2_per_objfile->ranges);
12361   if (offset >= dwarf2_per_objfile->ranges.size)
12362     {
12363       complaint (&symfile_complaints,
12364                  _("Offset %d out of bounds for DW_AT_ranges attribute"),
12365                  offset);
12366       return 0;
12367     }
12368   buffer = dwarf2_per_objfile->ranges.buffer + offset;
12369
12370   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
12371
12372   while (1)
12373     {
12374       CORE_ADDR range_beginning, range_end;
12375
12376       range_beginning = read_address (obfd, buffer, cu, &dummy);
12377       buffer += addr_size;
12378       range_end = read_address (obfd, buffer, cu, &dummy);
12379       buffer += addr_size;
12380       offset += 2 * addr_size;
12381
12382       /* An end of list marker is a pair of zero addresses.  */
12383       if (range_beginning == 0 && range_end == 0)
12384         /* Found the end of list entry.  */
12385         break;
12386
12387       /* Each base address selection entry is a pair of 2 values.
12388          The first is the largest possible address, the second is
12389          the base address.  Check for a base address here.  */
12390       if ((range_beginning & mask) == mask)
12391         {
12392           /* If we found the largest possible address, then we already
12393              have the base address in range_end.  */
12394           base = range_end;
12395           found_base = 1;
12396           continue;
12397         }
12398
12399       if (!found_base)
12400         {
12401           /* We have no valid base address for the ranges
12402              data.  */
12403           complaint (&symfile_complaints,
12404                      _("Invalid .debug_ranges data (no base address)"));
12405           return 0;
12406         }
12407
12408       if (range_beginning > range_end)
12409         {
12410           /* Inverted range entries are invalid.  */
12411           complaint (&symfile_complaints,
12412                      _("Invalid .debug_ranges data (inverted range)"));
12413           return 0;
12414         }
12415
12416       /* Empty range entries have no effect.  */
12417       if (range_beginning == range_end)
12418         continue;
12419
12420       range_beginning += base;
12421       range_end += base;
12422
12423       /* A not-uncommon case of bad debug info.
12424          Don't pollute the addrmap with bad data.  */
12425       if (range_beginning + baseaddr == 0
12426           && !dwarf2_per_objfile->has_section_at_zero)
12427         {
12428           complaint (&symfile_complaints,
12429                      _(".debug_ranges entry has start address of zero"
12430                        " [in module %s]"), objfile_name (objfile));
12431           continue;
12432         }
12433
12434       callback (range_beginning, range_end);
12435     }
12436
12437   return 1;
12438 }
12439
12440 /* Get low and high pc attributes from DW_AT_ranges attribute value OFFSET.
12441    Return 1 if the attributes are present and valid, otherwise, return 0.
12442    If RANGES_PST is not NULL we should setup `objfile->psymtabs_addrmap'.  */
12443
12444 static int
12445 dwarf2_ranges_read (unsigned offset, CORE_ADDR *low_return,
12446                     CORE_ADDR *high_return, struct dwarf2_cu *cu,
12447                     struct partial_symtab *ranges_pst)
12448 {
12449   struct objfile *objfile = cu->objfile;
12450   struct gdbarch *gdbarch = get_objfile_arch (objfile);
12451   const CORE_ADDR baseaddr = ANOFFSET (objfile->section_offsets,
12452                                        SECT_OFF_TEXT (objfile));
12453   int low_set = 0;
12454   CORE_ADDR low = 0;
12455   CORE_ADDR high = 0;
12456   int retval;
12457
12458   retval = dwarf2_ranges_process (offset, cu,
12459     [&] (CORE_ADDR range_beginning, CORE_ADDR range_end)
12460     {
12461       if (ranges_pst != NULL)
12462         {
12463           CORE_ADDR lowpc;
12464           CORE_ADDR highpc;
12465
12466           lowpc = gdbarch_adjust_dwarf2_addr (gdbarch,
12467                                               range_beginning + baseaddr);
12468           highpc = gdbarch_adjust_dwarf2_addr (gdbarch,
12469                                                range_end + baseaddr);
12470           addrmap_set_empty (objfile->psymtabs_addrmap, lowpc, highpc - 1,
12471                              ranges_pst);
12472         }
12473
12474       /* FIXME: This is recording everything as a low-high
12475          segment of consecutive addresses.  We should have a
12476          data structure for discontiguous block ranges
12477          instead.  */
12478       if (! low_set)
12479         {
12480           low = range_beginning;
12481           high = range_end;
12482           low_set = 1;
12483         }
12484       else
12485         {
12486           if (range_beginning < low)
12487             low = range_beginning;
12488           if (range_end > high)
12489             high = range_end;
12490         }
12491     });
12492   if (!retval)
12493     return 0;
12494
12495   if (! low_set)
12496     /* If the first entry is an end-of-list marker, the range
12497        describes an empty scope, i.e. no instructions.  */
12498     return 0;
12499
12500   if (low_return)
12501     *low_return = low;
12502   if (high_return)
12503     *high_return = high;
12504   return 1;
12505 }
12506
12507 /* Get low and high pc attributes from a die.  See enum pc_bounds_kind
12508    definition for the return value.  *LOWPC and *HIGHPC are set iff
12509    neither PC_BOUNDS_NOT_PRESENT nor PC_BOUNDS_INVALID are returned.  */
12510
12511 static enum pc_bounds_kind
12512 dwarf2_get_pc_bounds (struct die_info *die, CORE_ADDR *lowpc,
12513                       CORE_ADDR *highpc, struct dwarf2_cu *cu,
12514                       struct partial_symtab *pst)
12515 {
12516   struct attribute *attr;
12517   struct attribute *attr_high;
12518   CORE_ADDR low = 0;
12519   CORE_ADDR high = 0;
12520   enum pc_bounds_kind ret;
12521
12522   attr_high = dwarf2_attr (die, DW_AT_high_pc, cu);
12523   if (attr_high)
12524     {
12525       attr = dwarf2_attr (die, DW_AT_low_pc, cu);
12526       if (attr)
12527         {
12528           low = attr_value_as_address (attr);
12529           high = attr_value_as_address (attr_high);
12530           if (cu->header.version >= 4 && attr_form_is_constant (attr_high))
12531             high += low;
12532         }
12533       else
12534         /* Found high w/o low attribute.  */
12535         return PC_BOUNDS_INVALID;
12536
12537       /* Found consecutive range of addresses.  */
12538       ret = PC_BOUNDS_HIGH_LOW;
12539     }
12540   else
12541     {
12542       attr = dwarf2_attr (die, DW_AT_ranges, cu);
12543       if (attr != NULL)
12544         {
12545           /* DW_AT_ranges_base does not apply to DIEs from the DWO skeleton.
12546              We take advantage of the fact that DW_AT_ranges does not appear
12547              in DW_TAG_compile_unit of DWO files.  */
12548           int need_ranges_base = die->tag != DW_TAG_compile_unit;
12549           unsigned int ranges_offset = (DW_UNSND (attr)
12550                                         + (need_ranges_base
12551                                            ? cu->ranges_base
12552                                            : 0));
12553
12554           /* Value of the DW_AT_ranges attribute is the offset in the
12555              .debug_ranges section.  */
12556           if (!dwarf2_ranges_read (ranges_offset, &low, &high, cu, pst))
12557             return PC_BOUNDS_INVALID;
12558           /* Found discontinuous range of addresses.  */
12559           ret = PC_BOUNDS_RANGES;
12560         }
12561       else
12562         return PC_BOUNDS_NOT_PRESENT;
12563     }
12564
12565   /* read_partial_die has also the strict LOW < HIGH requirement.  */
12566   if (high <= low)
12567     return PC_BOUNDS_INVALID;
12568
12569   /* When using the GNU linker, .gnu.linkonce. sections are used to
12570      eliminate duplicate copies of functions and vtables and such.
12571      The linker will arbitrarily choose one and discard the others.
12572      The AT_*_pc values for such functions refer to local labels in
12573      these sections.  If the section from that file was discarded, the
12574      labels are not in the output, so the relocs get a value of 0.
12575      If this is a discarded function, mark the pc bounds as invalid,
12576      so that GDB will ignore it.  */
12577   if (low == 0 && !dwarf2_per_objfile->has_section_at_zero)
12578     return PC_BOUNDS_INVALID;
12579
12580   *lowpc = low;
12581   if (highpc)
12582     *highpc = high;
12583   return ret;
12584 }
12585
12586 /* Assuming that DIE represents a subprogram DIE or a lexical block, get
12587    its low and high PC addresses.  Do nothing if these addresses could not
12588    be determined.  Otherwise, set LOWPC to the low address if it is smaller,
12589    and HIGHPC to the high address if greater than HIGHPC.  */
12590
12591 static void
12592 dwarf2_get_subprogram_pc_bounds (struct die_info *die,
12593                                  CORE_ADDR *lowpc, CORE_ADDR *highpc,
12594                                  struct dwarf2_cu *cu)
12595 {
12596   CORE_ADDR low, high;
12597   struct die_info *child = die->child;
12598
12599   if (dwarf2_get_pc_bounds (die, &low, &high, cu, NULL) >= PC_BOUNDS_RANGES)
12600     {
12601       *lowpc = std::min (*lowpc, low);
12602       *highpc = std::max (*highpc, high);
12603     }
12604
12605   /* If the language does not allow nested subprograms (either inside
12606      subprograms or lexical blocks), we're done.  */
12607   if (cu->language != language_ada)
12608     return;
12609
12610   /* Check all the children of the given DIE.  If it contains nested
12611      subprograms, then check their pc bounds.  Likewise, we need to
12612      check lexical blocks as well, as they may also contain subprogram
12613      definitions.  */
12614   while (child && child->tag)
12615     {
12616       if (child->tag == DW_TAG_subprogram
12617           || child->tag == DW_TAG_lexical_block)
12618         dwarf2_get_subprogram_pc_bounds (child, lowpc, highpc, cu);
12619       child = sibling_die (child);
12620     }
12621 }
12622
12623 /* Get the low and high pc's represented by the scope DIE, and store
12624    them in *LOWPC and *HIGHPC.  If the correct values can't be
12625    determined, set *LOWPC to -1 and *HIGHPC to 0.  */
12626
12627 static void
12628 get_scope_pc_bounds (struct die_info *die,
12629                      CORE_ADDR *lowpc, CORE_ADDR *highpc,
12630                      struct dwarf2_cu *cu)
12631 {
12632   CORE_ADDR best_low = (CORE_ADDR) -1;
12633   CORE_ADDR best_high = (CORE_ADDR) 0;
12634   CORE_ADDR current_low, current_high;
12635
12636   if (dwarf2_get_pc_bounds (die, &current_low, &current_high, cu, NULL)
12637       >= PC_BOUNDS_RANGES)
12638     {
12639       best_low = current_low;
12640       best_high = current_high;
12641     }
12642   else
12643     {
12644       struct die_info *child = die->child;
12645
12646       while (child && child->tag)
12647         {
12648           switch (child->tag) {
12649           case DW_TAG_subprogram:
12650             dwarf2_get_subprogram_pc_bounds (child, &best_low, &best_high, cu);
12651             break;
12652           case DW_TAG_namespace:
12653           case DW_TAG_module:
12654             /* FIXME: carlton/2004-01-16: Should we do this for
12655                DW_TAG_class_type/DW_TAG_structure_type, too?  I think
12656                that current GCC's always emit the DIEs corresponding
12657                to definitions of methods of classes as children of a
12658                DW_TAG_compile_unit or DW_TAG_namespace (as opposed to
12659                the DIEs giving the declarations, which could be
12660                anywhere).  But I don't see any reason why the
12661                standards says that they have to be there.  */
12662             get_scope_pc_bounds (child, &current_low, &current_high, cu);
12663
12664             if (current_low != ((CORE_ADDR) -1))
12665               {
12666                 best_low = std::min (best_low, current_low);
12667                 best_high = std::max (best_high, current_high);
12668               }
12669             break;
12670           default:
12671             /* Ignore.  */
12672             break;
12673           }
12674
12675           child = sibling_die (child);
12676         }
12677     }
12678
12679   *lowpc = best_low;
12680   *highpc = best_high;
12681 }
12682
12683 /* Record the address ranges for BLOCK, offset by BASEADDR, as given
12684    in DIE.  */
12685
12686 static void
12687 dwarf2_record_block_ranges (struct die_info *die, struct block *block,
12688                             CORE_ADDR baseaddr, struct dwarf2_cu *cu)
12689 {
12690   struct objfile *objfile = cu->objfile;
12691   struct gdbarch *gdbarch = get_objfile_arch (objfile);
12692   struct attribute *attr;
12693   struct attribute *attr_high;
12694
12695   attr_high = dwarf2_attr (die, DW_AT_high_pc, cu);
12696   if (attr_high)
12697     {
12698       attr = dwarf2_attr (die, DW_AT_low_pc, cu);
12699       if (attr)
12700         {
12701           CORE_ADDR low = attr_value_as_address (attr);
12702           CORE_ADDR high = attr_value_as_address (attr_high);
12703
12704           if (cu->header.version >= 4 && attr_form_is_constant (attr_high))
12705             high += low;
12706
12707           low = gdbarch_adjust_dwarf2_addr (gdbarch, low + baseaddr);
12708           high = gdbarch_adjust_dwarf2_addr (gdbarch, high + baseaddr);
12709           record_block_range (block, low, high - 1);
12710         }
12711     }
12712
12713   attr = dwarf2_attr (die, DW_AT_ranges, cu);
12714   if (attr)
12715     {
12716       bfd *obfd = objfile->obfd;
12717       /* DW_AT_ranges_base does not apply to DIEs from the DWO skeleton.
12718          We take advantage of the fact that DW_AT_ranges does not appear
12719          in DW_TAG_compile_unit of DWO files.  */
12720       int need_ranges_base = die->tag != DW_TAG_compile_unit;
12721
12722       /* The value of the DW_AT_ranges attribute is the offset of the
12723          address range list in the .debug_ranges section.  */
12724       unsigned long offset = (DW_UNSND (attr)
12725                               + (need_ranges_base ? cu->ranges_base : 0));
12726       const gdb_byte *buffer;
12727
12728       /* For some target architectures, but not others, the
12729          read_address function sign-extends the addresses it returns.
12730          To recognize base address selection entries, we need a
12731          mask.  */
12732       unsigned int addr_size = cu->header.addr_size;
12733       CORE_ADDR base_select_mask = ~(~(CORE_ADDR)1 << (addr_size * 8 - 1));
12734
12735       /* The base address, to which the next pair is relative.  Note
12736          that this 'base' is a DWARF concept: most entries in a range
12737          list are relative, to reduce the number of relocs against the
12738          debugging information.  This is separate from this function's
12739          'baseaddr' argument, which GDB uses to relocate debugging
12740          information from a shared library based on the address at
12741          which the library was loaded.  */
12742       CORE_ADDR base = cu->base_address;
12743       int base_known = cu->base_known;
12744
12745       dwarf2_ranges_process (offset, cu,
12746         [&] (CORE_ADDR start, CORE_ADDR end)
12747         {
12748           start += baseaddr;
12749           end += baseaddr;
12750           start = gdbarch_adjust_dwarf2_addr (gdbarch, start);
12751           end = gdbarch_adjust_dwarf2_addr (gdbarch, end);
12752           record_block_range (block, start, end - 1);
12753         });
12754     }
12755 }
12756
12757 /* Check whether the producer field indicates either of GCC < 4.6, or the
12758    Intel C/C++ compiler, and cache the result in CU.  */
12759
12760 static void
12761 check_producer (struct dwarf2_cu *cu)
12762 {
12763   int major, minor;
12764
12765   if (cu->producer == NULL)
12766     {
12767       /* For unknown compilers expect their behavior is DWARF version
12768          compliant.
12769
12770          GCC started to support .debug_types sections by -gdwarf-4 since
12771          gcc-4.5.x.  As the .debug_types sections are missing DW_AT_producer
12772          for their space efficiency GDB cannot workaround gcc-4.5.x -gdwarf-4
12773          combination.  gcc-4.5.x -gdwarf-4 binaries have DW_AT_accessibility
12774          interpreted incorrectly by GDB now - GCC PR debug/48229.  */
12775     }
12776   else if (producer_is_gcc (cu->producer, &major, &minor))
12777     {
12778       cu->producer_is_gxx_lt_4_6 = major < 4 || (major == 4 && minor < 6);
12779       cu->producer_is_gcc_lt_4_3 = major < 4 || (major == 4 && minor < 3);
12780     }
12781   else if (startswith (cu->producer, "Intel(R) C"))
12782     cu->producer_is_icc = 1;
12783   else
12784     {
12785       /* For other non-GCC compilers, expect their behavior is DWARF version
12786          compliant.  */
12787     }
12788
12789   cu->checked_producer = 1;
12790 }
12791
12792 /* Check for GCC PR debug/45124 fix which is not present in any G++ version up
12793    to 4.5.any while it is present already in G++ 4.6.0 - the PR has been fixed
12794    during 4.6.0 experimental.  */
12795
12796 static int
12797 producer_is_gxx_lt_4_6 (struct dwarf2_cu *cu)
12798 {
12799   if (!cu->checked_producer)
12800     check_producer (cu);
12801
12802   return cu->producer_is_gxx_lt_4_6;
12803 }
12804
12805 /* Return the default accessibility type if it is not overriden by
12806    DW_AT_accessibility.  */
12807
12808 static enum dwarf_access_attribute
12809 dwarf2_default_access_attribute (struct die_info *die, struct dwarf2_cu *cu)
12810 {
12811   if (cu->header.version < 3 || producer_is_gxx_lt_4_6 (cu))
12812     {
12813       /* The default DWARF 2 accessibility for members is public, the default
12814          accessibility for inheritance is private.  */
12815
12816       if (die->tag != DW_TAG_inheritance)
12817         return DW_ACCESS_public;
12818       else
12819         return DW_ACCESS_private;
12820     }
12821   else
12822     {
12823       /* DWARF 3+ defines the default accessibility a different way.  The same
12824          rules apply now for DW_TAG_inheritance as for the members and it only
12825          depends on the container kind.  */
12826
12827       if (die->parent->tag == DW_TAG_class_type)
12828         return DW_ACCESS_private;
12829       else
12830         return DW_ACCESS_public;
12831     }
12832 }
12833
12834 /* Look for DW_AT_data_member_location.  Set *OFFSET to the byte
12835    offset.  If the attribute was not found return 0, otherwise return
12836    1.  If it was found but could not properly be handled, set *OFFSET
12837    to 0.  */
12838
12839 static int
12840 handle_data_member_location (struct die_info *die, struct dwarf2_cu *cu,
12841                              LONGEST *offset)
12842 {
12843   struct attribute *attr;
12844
12845   attr = dwarf2_attr (die, DW_AT_data_member_location, cu);
12846   if (attr != NULL)
12847     {
12848       *offset = 0;
12849
12850       /* Note that we do not check for a section offset first here.
12851          This is because DW_AT_data_member_location is new in DWARF 4,
12852          so if we see it, we can assume that a constant form is really
12853          a constant and not a section offset.  */
12854       if (attr_form_is_constant (attr))
12855         *offset = dwarf2_get_attr_constant_value (attr, 0);
12856       else if (attr_form_is_section_offset (attr))
12857         dwarf2_complex_location_expr_complaint ();
12858       else if (attr_form_is_block (attr))
12859         *offset = decode_locdesc (DW_BLOCK (attr), cu);
12860       else
12861         dwarf2_complex_location_expr_complaint ();
12862
12863       return 1;
12864     }
12865
12866   return 0;
12867 }
12868
12869 /* Add an aggregate field to the field list.  */
12870
12871 static void
12872 dwarf2_add_field (struct field_info *fip, struct die_info *die,
12873                   struct dwarf2_cu *cu)
12874 {
12875   struct objfile *objfile = cu->objfile;
12876   struct gdbarch *gdbarch = get_objfile_arch (objfile);
12877   struct nextfield *new_field;
12878   struct attribute *attr;
12879   struct field *fp;
12880   const char *fieldname = "";
12881
12882   /* Allocate a new field list entry and link it in.  */
12883   new_field = XNEW (struct nextfield);
12884   make_cleanup (xfree, new_field);
12885   memset (new_field, 0, sizeof (struct nextfield));
12886
12887   if (die->tag == DW_TAG_inheritance)
12888     {
12889       new_field->next = fip->baseclasses;
12890       fip->baseclasses = new_field;
12891     }
12892   else
12893     {
12894       new_field->next = fip->fields;
12895       fip->fields = new_field;
12896     }
12897   fip->nfields++;
12898
12899   attr = dwarf2_attr (die, DW_AT_accessibility, cu);
12900   if (attr)
12901     new_field->accessibility = DW_UNSND (attr);
12902   else
12903     new_field->accessibility = dwarf2_default_access_attribute (die, cu);
12904   if (new_field->accessibility != DW_ACCESS_public)
12905     fip->non_public_fields = 1;
12906
12907   attr = dwarf2_attr (die, DW_AT_virtuality, cu);
12908   if (attr)
12909     new_field->virtuality = DW_UNSND (attr);
12910   else
12911     new_field->virtuality = DW_VIRTUALITY_none;
12912
12913   fp = &new_field->field;
12914
12915   if (die->tag == DW_TAG_member && ! die_is_declaration (die, cu))
12916     {
12917       LONGEST offset;
12918
12919       /* Data member other than a C++ static data member.  */
12920
12921       /* Get type of field.  */
12922       fp->type = die_type (die, cu);
12923
12924       SET_FIELD_BITPOS (*fp, 0);
12925
12926       /* Get bit size of field (zero if none).  */
12927       attr = dwarf2_attr (die, DW_AT_bit_size, cu);
12928       if (attr)
12929         {
12930           FIELD_BITSIZE (*fp) = DW_UNSND (attr);
12931         }
12932       else
12933         {
12934           FIELD_BITSIZE (*fp) = 0;
12935         }
12936
12937       /* Get bit offset of field.  */
12938       if (handle_data_member_location (die, cu, &offset))
12939         SET_FIELD_BITPOS (*fp, offset * bits_per_byte);
12940       attr = dwarf2_attr (die, DW_AT_bit_offset, cu);
12941       if (attr)
12942         {
12943           if (gdbarch_bits_big_endian (gdbarch))
12944             {
12945               /* For big endian bits, the DW_AT_bit_offset gives the
12946                  additional bit offset from the MSB of the containing
12947                  anonymous object to the MSB of the field.  We don't
12948                  have to do anything special since we don't need to
12949                  know the size of the anonymous object.  */
12950               SET_FIELD_BITPOS (*fp, FIELD_BITPOS (*fp) + DW_UNSND (attr));
12951             }
12952           else
12953             {
12954               /* For little endian bits, compute the bit offset to the
12955                  MSB of the anonymous object, subtract off the number of
12956                  bits from the MSB of the field to the MSB of the
12957                  object, and then subtract off the number of bits of
12958                  the field itself.  The result is the bit offset of
12959                  the LSB of the field.  */
12960               int anonymous_size;
12961               int bit_offset = DW_UNSND (attr);
12962
12963               attr = dwarf2_attr (die, DW_AT_byte_size, cu);
12964               if (attr)
12965                 {
12966                   /* The size of the anonymous object containing
12967                      the bit field is explicit, so use the
12968                      indicated size (in bytes).  */
12969                   anonymous_size = DW_UNSND (attr);
12970                 }
12971               else
12972                 {
12973                   /* The size of the anonymous object containing
12974                      the bit field must be inferred from the type
12975                      attribute of the data member containing the
12976                      bit field.  */
12977                   anonymous_size = TYPE_LENGTH (fp->type);
12978                 }
12979               SET_FIELD_BITPOS (*fp,
12980                                 (FIELD_BITPOS (*fp)
12981                                  + anonymous_size * bits_per_byte
12982                                  - bit_offset - FIELD_BITSIZE (*fp)));
12983             }
12984         }
12985       attr = dwarf2_attr (die, DW_AT_data_bit_offset, cu);
12986       if (attr != NULL)
12987         SET_FIELD_BITPOS (*fp, (FIELD_BITPOS (*fp)
12988                                 + dwarf2_get_attr_constant_value (attr, 0)));
12989
12990       /* Get name of field.  */
12991       fieldname = dwarf2_name (die, cu);
12992       if (fieldname == NULL)
12993         fieldname = "";
12994
12995       /* The name is already allocated along with this objfile, so we don't
12996          need to duplicate it for the type.  */
12997       fp->name = fieldname;
12998
12999       /* Change accessibility for artificial fields (e.g. virtual table
13000          pointer or virtual base class pointer) to private.  */
13001       if (dwarf2_attr (die, DW_AT_artificial, cu))
13002         {
13003           FIELD_ARTIFICIAL (*fp) = 1;
13004           new_field->accessibility = DW_ACCESS_private;
13005           fip->non_public_fields = 1;
13006         }
13007     }
13008   else if (die->tag == DW_TAG_member || die->tag == DW_TAG_variable)
13009     {
13010       /* C++ static member.  */
13011
13012       /* NOTE: carlton/2002-11-05: It should be a DW_TAG_member that
13013          is a declaration, but all versions of G++ as of this writing
13014          (so through at least 3.2.1) incorrectly generate
13015          DW_TAG_variable tags.  */
13016
13017       const char *physname;
13018
13019       /* Get name of field.  */
13020       fieldname = dwarf2_name (die, cu);
13021       if (fieldname == NULL)
13022         return;
13023
13024       attr = dwarf2_attr (die, DW_AT_const_value, cu);
13025       if (attr
13026           /* Only create a symbol if this is an external value.
13027              new_symbol checks this and puts the value in the global symbol
13028              table, which we want.  If it is not external, new_symbol
13029              will try to put the value in cu->list_in_scope which is wrong.  */
13030           && dwarf2_flag_true_p (die, DW_AT_external, cu))
13031         {
13032           /* A static const member, not much different than an enum as far as
13033              we're concerned, except that we can support more types.  */
13034           new_symbol (die, NULL, cu);
13035         }
13036
13037       /* Get physical name.  */
13038       physname = dwarf2_physname (fieldname, die, cu);
13039
13040       /* The name is already allocated along with this objfile, so we don't
13041          need to duplicate it for the type.  */
13042       SET_FIELD_PHYSNAME (*fp, physname ? physname : "");
13043       FIELD_TYPE (*fp) = die_type (die, cu);
13044       FIELD_NAME (*fp) = fieldname;
13045     }
13046   else if (die->tag == DW_TAG_inheritance)
13047     {
13048       LONGEST offset;
13049
13050       /* C++ base class field.  */
13051       if (handle_data_member_location (die, cu, &offset))
13052         SET_FIELD_BITPOS (*fp, offset * bits_per_byte);
13053       FIELD_BITSIZE (*fp) = 0;
13054       FIELD_TYPE (*fp) = die_type (die, cu);
13055       FIELD_NAME (*fp) = type_name_no_tag (fp->type);
13056       fip->nbaseclasses++;
13057     }
13058 }
13059
13060 /* Add a typedef defined in the scope of the FIP's class.  */
13061
13062 static void
13063 dwarf2_add_typedef (struct field_info *fip, struct die_info *die,
13064                     struct dwarf2_cu *cu)
13065 {
13066   struct typedef_field_list *new_field;
13067   struct typedef_field *fp;
13068
13069   /* Allocate a new field list entry and link it in.  */
13070   new_field = XCNEW (struct typedef_field_list);
13071   make_cleanup (xfree, new_field);
13072
13073   gdb_assert (die->tag == DW_TAG_typedef);
13074
13075   fp = &new_field->field;
13076
13077   /* Get name of field.  */
13078   fp->name = dwarf2_name (die, cu);
13079   if (fp->name == NULL)
13080     return;
13081
13082   fp->type = read_type_die (die, cu);
13083
13084   new_field->next = fip->typedef_field_list;
13085   fip->typedef_field_list = new_field;
13086   fip->typedef_field_list_count++;
13087 }
13088
13089 /* Create the vector of fields, and attach it to the type.  */
13090
13091 static void
13092 dwarf2_attach_fields_to_type (struct field_info *fip, struct type *type,
13093                               struct dwarf2_cu *cu)
13094 {
13095   int nfields = fip->nfields;
13096
13097   /* Record the field count, allocate space for the array of fields,
13098      and create blank accessibility bitfields if necessary.  */
13099   TYPE_NFIELDS (type) = nfields;
13100   TYPE_FIELDS (type) = (struct field *)
13101     TYPE_ALLOC (type, sizeof (struct field) * nfields);
13102   memset (TYPE_FIELDS (type), 0, sizeof (struct field) * nfields);
13103
13104   if (fip->non_public_fields && cu->language != language_ada)
13105     {
13106       ALLOCATE_CPLUS_STRUCT_TYPE (type);
13107
13108       TYPE_FIELD_PRIVATE_BITS (type) =
13109         (B_TYPE *) TYPE_ALLOC (type, B_BYTES (nfields));
13110       B_CLRALL (TYPE_FIELD_PRIVATE_BITS (type), nfields);
13111
13112       TYPE_FIELD_PROTECTED_BITS (type) =
13113         (B_TYPE *) TYPE_ALLOC (type, B_BYTES (nfields));
13114       B_CLRALL (TYPE_FIELD_PROTECTED_BITS (type), nfields);
13115
13116       TYPE_FIELD_IGNORE_BITS (type) =
13117         (B_TYPE *) TYPE_ALLOC (type, B_BYTES (nfields));
13118       B_CLRALL (TYPE_FIELD_IGNORE_BITS (type), nfields);
13119     }
13120
13121   /* If the type has baseclasses, allocate and clear a bit vector for
13122      TYPE_FIELD_VIRTUAL_BITS.  */
13123   if (fip->nbaseclasses && cu->language != language_ada)
13124     {
13125       int num_bytes = B_BYTES (fip->nbaseclasses);
13126       unsigned char *pointer;
13127
13128       ALLOCATE_CPLUS_STRUCT_TYPE (type);
13129       pointer = (unsigned char *) TYPE_ALLOC (type, num_bytes);
13130       TYPE_FIELD_VIRTUAL_BITS (type) = pointer;
13131       B_CLRALL (TYPE_FIELD_VIRTUAL_BITS (type), fip->nbaseclasses);
13132       TYPE_N_BASECLASSES (type) = fip->nbaseclasses;
13133     }
13134
13135   /* Copy the saved-up fields into the field vector.  Start from the head of
13136      the list, adding to the tail of the field array, so that they end up in
13137      the same order in the array in which they were added to the list.  */
13138   while (nfields-- > 0)
13139     {
13140       struct nextfield *fieldp;
13141
13142       if (fip->fields)
13143         {
13144           fieldp = fip->fields;
13145           fip->fields = fieldp->next;
13146         }
13147       else
13148         {
13149           fieldp = fip->baseclasses;
13150           fip->baseclasses = fieldp->next;
13151         }
13152
13153       TYPE_FIELD (type, nfields) = fieldp->field;
13154       switch (fieldp->accessibility)
13155         {
13156         case DW_ACCESS_private:
13157           if (cu->language != language_ada)
13158             SET_TYPE_FIELD_PRIVATE (type, nfields);
13159           break;
13160
13161         case DW_ACCESS_protected:
13162           if (cu->language != language_ada)
13163             SET_TYPE_FIELD_PROTECTED (type, nfields);
13164           break;
13165
13166         case DW_ACCESS_public:
13167           break;
13168
13169         default:
13170           /* Unknown accessibility.  Complain and treat it as public.  */
13171           {
13172             complaint (&symfile_complaints, _("unsupported accessibility %d"),
13173                        fieldp->accessibility);
13174           }
13175           break;
13176         }
13177       if (nfields < fip->nbaseclasses)
13178         {
13179           switch (fieldp->virtuality)
13180             {
13181             case DW_VIRTUALITY_virtual:
13182             case DW_VIRTUALITY_pure_virtual:
13183               if (cu->language == language_ada)
13184                 error (_("unexpected virtuality in component of Ada type"));
13185               SET_TYPE_FIELD_VIRTUAL (type, nfields);
13186               break;
13187             }
13188         }
13189     }
13190 }
13191
13192 /* Return true if this member function is a constructor, false
13193    otherwise.  */
13194
13195 static int
13196 dwarf2_is_constructor (struct die_info *die, struct dwarf2_cu *cu)
13197 {
13198   const char *fieldname;
13199   const char *type_name;
13200   int len;
13201
13202   if (die->parent == NULL)
13203     return 0;
13204
13205   if (die->parent->tag != DW_TAG_structure_type
13206       && die->parent->tag != DW_TAG_union_type
13207       && die->parent->tag != DW_TAG_class_type)
13208     return 0;
13209
13210   fieldname = dwarf2_name (die, cu);
13211   type_name = dwarf2_name (die->parent, cu);
13212   if (fieldname == NULL || type_name == NULL)
13213     return 0;
13214
13215   len = strlen (fieldname);
13216   return (strncmp (fieldname, type_name, len) == 0
13217           && (type_name[len] == '\0' || type_name[len] == '<'));
13218 }
13219
13220 /* Add a member function to the proper fieldlist.  */
13221
13222 static void
13223 dwarf2_add_member_fn (struct field_info *fip, struct die_info *die,
13224                       struct type *type, struct dwarf2_cu *cu)
13225 {
13226   struct objfile *objfile = cu->objfile;
13227   struct attribute *attr;
13228   struct fnfieldlist *flp;
13229   int i;
13230   struct fn_field *fnp;
13231   const char *fieldname;
13232   struct nextfnfield *new_fnfield;
13233   struct type *this_type;
13234   enum dwarf_access_attribute accessibility;
13235
13236   if (cu->language == language_ada)
13237     error (_("unexpected member function in Ada type"));
13238
13239   /* Get name of member function.  */
13240   fieldname = dwarf2_name (die, cu);
13241   if (fieldname == NULL)
13242     return;
13243
13244   /* Look up member function name in fieldlist.  */
13245   for (i = 0; i < fip->nfnfields; i++)
13246     {
13247       if (strcmp (fip->fnfieldlists[i].name, fieldname) == 0)
13248         break;
13249     }
13250
13251   /* Create new list element if necessary.  */
13252   if (i < fip->nfnfields)
13253     flp = &fip->fnfieldlists[i];
13254   else
13255     {
13256       if ((fip->nfnfields % DW_FIELD_ALLOC_CHUNK) == 0)
13257         {
13258           fip->fnfieldlists = (struct fnfieldlist *)
13259             xrealloc (fip->fnfieldlists,
13260                       (fip->nfnfields + DW_FIELD_ALLOC_CHUNK)
13261                       * sizeof (struct fnfieldlist));
13262           if (fip->nfnfields == 0)
13263             make_cleanup (free_current_contents, &fip->fnfieldlists);
13264         }
13265       flp = &fip->fnfieldlists[fip->nfnfields];
13266       flp->name = fieldname;
13267       flp->length = 0;
13268       flp->head = NULL;
13269       i = fip->nfnfields++;
13270     }
13271
13272   /* Create a new member function field and chain it to the field list
13273      entry.  */
13274   new_fnfield = XNEW (struct nextfnfield);
13275   make_cleanup (xfree, new_fnfield);
13276   memset (new_fnfield, 0, sizeof (struct nextfnfield));
13277   new_fnfield->next = flp->head;
13278   flp->head = new_fnfield;
13279   flp->length++;
13280
13281   /* Fill in the member function field info.  */
13282   fnp = &new_fnfield->fnfield;
13283
13284   /* Delay processing of the physname until later.  */
13285   if (cu->language == language_cplus)
13286     {
13287       add_to_method_list (type, i, flp->length - 1, fieldname,
13288                           die, cu);
13289     }
13290   else
13291     {
13292       const char *physname = dwarf2_physname (fieldname, die, cu);
13293       fnp->physname = physname ? physname : "";
13294     }
13295
13296   fnp->type = alloc_type (objfile);
13297   this_type = read_type_die (die, cu);
13298   if (this_type && TYPE_CODE (this_type) == TYPE_CODE_FUNC)
13299     {
13300       int nparams = TYPE_NFIELDS (this_type);
13301
13302       /* TYPE is the domain of this method, and THIS_TYPE is the type
13303            of the method itself (TYPE_CODE_METHOD).  */
13304       smash_to_method_type (fnp->type, type,
13305                             TYPE_TARGET_TYPE (this_type),
13306                             TYPE_FIELDS (this_type),
13307                             TYPE_NFIELDS (this_type),
13308                             TYPE_VARARGS (this_type));
13309
13310       /* Handle static member functions.
13311          Dwarf2 has no clean way to discern C++ static and non-static
13312          member functions.  G++ helps GDB by marking the first
13313          parameter for non-static member functions (which is the this
13314          pointer) as artificial.  We obtain this information from
13315          read_subroutine_type via TYPE_FIELD_ARTIFICIAL.  */
13316       if (nparams == 0 || TYPE_FIELD_ARTIFICIAL (this_type, 0) == 0)
13317         fnp->voffset = VOFFSET_STATIC;
13318     }
13319   else
13320     complaint (&symfile_complaints, _("member function type missing for '%s'"),
13321                dwarf2_full_name (fieldname, die, cu));
13322
13323   /* Get fcontext from DW_AT_containing_type if present.  */
13324   if (dwarf2_attr (die, DW_AT_containing_type, cu) != NULL)
13325     fnp->fcontext = die_containing_type (die, cu);
13326
13327   /* dwarf2 doesn't have stubbed physical names, so the setting of is_const and
13328      is_volatile is irrelevant, as it is needed by gdb_mangle_name only.  */
13329
13330   /* Get accessibility.  */
13331   attr = dwarf2_attr (die, DW_AT_accessibility, cu);
13332   if (attr)
13333     accessibility = (enum dwarf_access_attribute) DW_UNSND (attr);
13334   else
13335     accessibility = dwarf2_default_access_attribute (die, cu);
13336   switch (accessibility)
13337     {
13338     case DW_ACCESS_private:
13339       fnp->is_private = 1;
13340       break;
13341     case DW_ACCESS_protected:
13342       fnp->is_protected = 1;
13343       break;
13344     }
13345
13346   /* Check for artificial methods.  */
13347   attr = dwarf2_attr (die, DW_AT_artificial, cu);
13348   if (attr && DW_UNSND (attr) != 0)
13349     fnp->is_artificial = 1;
13350
13351   fnp->is_constructor = dwarf2_is_constructor (die, cu);
13352
13353   /* Get index in virtual function table if it is a virtual member
13354      function.  For older versions of GCC, this is an offset in the
13355      appropriate virtual table, as specified by DW_AT_containing_type.
13356      For everyone else, it is an expression to be evaluated relative
13357      to the object address.  */
13358
13359   attr = dwarf2_attr (die, DW_AT_vtable_elem_location, cu);
13360   if (attr)
13361     {
13362       if (attr_form_is_block (attr) && DW_BLOCK (attr)->size > 0)
13363         {
13364           if (DW_BLOCK (attr)->data[0] == DW_OP_constu)
13365             {
13366               /* Old-style GCC.  */
13367               fnp->voffset = decode_locdesc (DW_BLOCK (attr), cu) + 2;
13368             }
13369           else if (DW_BLOCK (attr)->data[0] == DW_OP_deref
13370                    || (DW_BLOCK (attr)->size > 1
13371                        && DW_BLOCK (attr)->data[0] == DW_OP_deref_size
13372                        && DW_BLOCK (attr)->data[1] == cu->header.addr_size))
13373             {
13374               fnp->voffset = decode_locdesc (DW_BLOCK (attr), cu);
13375               if ((fnp->voffset % cu->header.addr_size) != 0)
13376                 dwarf2_complex_location_expr_complaint ();
13377               else
13378                 fnp->voffset /= cu->header.addr_size;
13379               fnp->voffset += 2;
13380             }
13381           else
13382             dwarf2_complex_location_expr_complaint ();
13383
13384           if (!fnp->fcontext)
13385             {
13386               /* If there is no `this' field and no DW_AT_containing_type,
13387                  we cannot actually find a base class context for the
13388                  vtable!  */
13389               if (TYPE_NFIELDS (this_type) == 0
13390                   || !TYPE_FIELD_ARTIFICIAL (this_type, 0))
13391                 {
13392                   complaint (&symfile_complaints,
13393                              _("cannot determine context for virtual member "
13394                                "function \"%s\" (offset %d)"),
13395                              fieldname, to_underlying (die->sect_off));
13396                 }
13397               else
13398                 {
13399                   fnp->fcontext
13400                     = TYPE_TARGET_TYPE (TYPE_FIELD_TYPE (this_type, 0));
13401                 }
13402             }
13403         }
13404       else if (attr_form_is_section_offset (attr))
13405         {
13406           dwarf2_complex_location_expr_complaint ();
13407         }
13408       else
13409         {
13410           dwarf2_invalid_attrib_class_complaint ("DW_AT_vtable_elem_location",
13411                                                  fieldname);
13412         }
13413     }
13414   else
13415     {
13416       attr = dwarf2_attr (die, DW_AT_virtuality, cu);
13417       if (attr && DW_UNSND (attr))
13418         {
13419           /* GCC does this, as of 2008-08-25; PR debug/37237.  */
13420           complaint (&symfile_complaints,
13421                      _("Member function \"%s\" (offset %d) is virtual "
13422                        "but the vtable offset is not specified"),
13423                      fieldname, to_underlying (die->sect_off));
13424           ALLOCATE_CPLUS_STRUCT_TYPE (type);
13425           TYPE_CPLUS_DYNAMIC (type) = 1;
13426         }
13427     }
13428 }
13429
13430 /* Create the vector of member function fields, and attach it to the type.  */
13431
13432 static void
13433 dwarf2_attach_fn_fields_to_type (struct field_info *fip, struct type *type,
13434                                  struct dwarf2_cu *cu)
13435 {
13436   struct fnfieldlist *flp;
13437   int i;
13438
13439   if (cu->language == language_ada)
13440     error (_("unexpected member functions in Ada type"));
13441
13442   ALLOCATE_CPLUS_STRUCT_TYPE (type);
13443   TYPE_FN_FIELDLISTS (type) = (struct fn_fieldlist *)
13444     TYPE_ALLOC (type, sizeof (struct fn_fieldlist) * fip->nfnfields);
13445
13446   for (i = 0, flp = fip->fnfieldlists; i < fip->nfnfields; i++, flp++)
13447     {
13448       struct nextfnfield *nfp = flp->head;
13449       struct fn_fieldlist *fn_flp = &TYPE_FN_FIELDLIST (type, i);
13450       int k;
13451
13452       TYPE_FN_FIELDLIST_NAME (type, i) = flp->name;
13453       TYPE_FN_FIELDLIST_LENGTH (type, i) = flp->length;
13454       fn_flp->fn_fields = (struct fn_field *)
13455         TYPE_ALLOC (type, sizeof (struct fn_field) * flp->length);
13456       for (k = flp->length; (k--, nfp); nfp = nfp->next)
13457         fn_flp->fn_fields[k] = nfp->fnfield;
13458     }
13459
13460   TYPE_NFN_FIELDS (type) = fip->nfnfields;
13461 }
13462
13463 /* Returns non-zero if NAME is the name of a vtable member in CU's
13464    language, zero otherwise.  */
13465 static int
13466 is_vtable_name (const char *name, struct dwarf2_cu *cu)
13467 {
13468   static const char vptr[] = "_vptr";
13469   static const char vtable[] = "vtable";
13470
13471   /* Look for the C++ form of the vtable.  */
13472   if (startswith (name, vptr) && is_cplus_marker (name[sizeof (vptr) - 1]))
13473     return 1;
13474
13475   return 0;
13476 }
13477
13478 /* GCC outputs unnamed structures that are really pointers to member
13479    functions, with the ABI-specified layout.  If TYPE describes
13480    such a structure, smash it into a member function type.
13481
13482    GCC shouldn't do this; it should just output pointer to member DIEs.
13483    This is GCC PR debug/28767.  */
13484
13485 static void
13486 quirk_gcc_member_function_pointer (struct type *type, struct objfile *objfile)
13487 {
13488   struct type *pfn_type, *self_type, *new_type;
13489
13490   /* Check for a structure with no name and two children.  */
13491   if (TYPE_CODE (type) != TYPE_CODE_STRUCT || TYPE_NFIELDS (type) != 2)
13492     return;
13493
13494   /* Check for __pfn and __delta members.  */
13495   if (TYPE_FIELD_NAME (type, 0) == NULL
13496       || strcmp (TYPE_FIELD_NAME (type, 0), "__pfn") != 0
13497       || TYPE_FIELD_NAME (type, 1) == NULL
13498       || strcmp (TYPE_FIELD_NAME (type, 1), "__delta") != 0)
13499     return;
13500
13501   /* Find the type of the method.  */
13502   pfn_type = TYPE_FIELD_TYPE (type, 0);
13503   if (pfn_type == NULL
13504       || TYPE_CODE (pfn_type) != TYPE_CODE_PTR
13505       || TYPE_CODE (TYPE_TARGET_TYPE (pfn_type)) != TYPE_CODE_FUNC)
13506     return;
13507
13508   /* Look for the "this" argument.  */
13509   pfn_type = TYPE_TARGET_TYPE (pfn_type);
13510   if (TYPE_NFIELDS (pfn_type) == 0
13511       /* || TYPE_FIELD_TYPE (pfn_type, 0) == NULL */
13512       || TYPE_CODE (TYPE_FIELD_TYPE (pfn_type, 0)) != TYPE_CODE_PTR)
13513     return;
13514
13515   self_type = TYPE_TARGET_TYPE (TYPE_FIELD_TYPE (pfn_type, 0));
13516   new_type = alloc_type (objfile);
13517   smash_to_method_type (new_type, self_type, TYPE_TARGET_TYPE (pfn_type),
13518                         TYPE_FIELDS (pfn_type), TYPE_NFIELDS (pfn_type),
13519                         TYPE_VARARGS (pfn_type));
13520   smash_to_methodptr_type (type, new_type);
13521 }
13522
13523 /* Return non-zero if the CU's PRODUCER string matches the Intel C/C++ compiler
13524    (icc).  */
13525
13526 static int
13527 producer_is_icc (struct dwarf2_cu *cu)
13528 {
13529   if (!cu->checked_producer)
13530     check_producer (cu);
13531
13532   return cu->producer_is_icc;
13533 }
13534
13535 /* Called when we find the DIE that starts a structure or union scope
13536    (definition) to create a type for the structure or union.  Fill in
13537    the type's name and general properties; the members will not be
13538    processed until process_structure_scope.  A symbol table entry for
13539    the type will also not be done until process_structure_scope (assuming
13540    the type has a name).
13541
13542    NOTE: we need to call these functions regardless of whether or not the
13543    DIE has a DW_AT_name attribute, since it might be an anonymous
13544    structure or union.  This gets the type entered into our set of
13545    user defined types.  */
13546
13547 static struct type *
13548 read_structure_type (struct die_info *die, struct dwarf2_cu *cu)
13549 {
13550   struct objfile *objfile = cu->objfile;
13551   struct type *type;
13552   struct attribute *attr;
13553   const char *name;
13554
13555   /* If the definition of this type lives in .debug_types, read that type.
13556      Don't follow DW_AT_specification though, that will take us back up
13557      the chain and we want to go down.  */
13558   attr = dwarf2_attr_no_follow (die, DW_AT_signature);
13559   if (attr)
13560     {
13561       type = get_DW_AT_signature_type (die, attr, cu);
13562
13563       /* The type's CU may not be the same as CU.
13564          Ensure TYPE is recorded with CU in die_type_hash.  */
13565       return set_die_type (die, type, cu);
13566     }
13567
13568   type = alloc_type (objfile);
13569   INIT_CPLUS_SPECIFIC (type);
13570
13571   name = dwarf2_name (die, cu);
13572   if (name != NULL)
13573     {
13574       if (cu->language == language_cplus
13575           || cu->language == language_d
13576           || cu->language == language_rust)
13577         {
13578           const char *full_name = dwarf2_full_name (name, die, cu);
13579
13580           /* dwarf2_full_name might have already finished building the DIE's
13581              type.  If so, there is no need to continue.  */
13582           if (get_die_type (die, cu) != NULL)
13583             return get_die_type (die, cu);
13584
13585           TYPE_TAG_NAME (type) = full_name;
13586           if (die->tag == DW_TAG_structure_type
13587               || die->tag == DW_TAG_class_type)
13588             TYPE_NAME (type) = TYPE_TAG_NAME (type);
13589         }
13590       else
13591         {
13592           /* The name is already allocated along with this objfile, so
13593              we don't need to duplicate it for the type.  */
13594           TYPE_TAG_NAME (type) = name;
13595           if (die->tag == DW_TAG_class_type)
13596             TYPE_NAME (type) = TYPE_TAG_NAME (type);
13597         }
13598     }
13599
13600   if (die->tag == DW_TAG_structure_type)
13601     {
13602       TYPE_CODE (type) = TYPE_CODE_STRUCT;
13603     }
13604   else if (die->tag == DW_TAG_union_type)
13605     {
13606       TYPE_CODE (type) = TYPE_CODE_UNION;
13607     }
13608   else
13609     {
13610       TYPE_CODE (type) = TYPE_CODE_STRUCT;
13611     }
13612
13613   if (cu->language == language_cplus && die->tag == DW_TAG_class_type)
13614     TYPE_DECLARED_CLASS (type) = 1;
13615
13616   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
13617   if (attr)
13618     {
13619       if (attr_form_is_constant (attr))
13620         TYPE_LENGTH (type) = DW_UNSND (attr);
13621       else
13622         {
13623           /* For the moment, dynamic type sizes are not supported
13624              by GDB's struct type.  The actual size is determined
13625              on-demand when resolving the type of a given object,
13626              so set the type's length to zero for now.  Otherwise,
13627              we record an expression as the length, and that expression
13628              could lead to a very large value, which could eventually
13629              lead to us trying to allocate that much memory when creating
13630              a value of that type.  */
13631           TYPE_LENGTH (type) = 0;
13632         }
13633     }
13634   else
13635     {
13636       TYPE_LENGTH (type) = 0;
13637     }
13638
13639   if (producer_is_icc (cu) && (TYPE_LENGTH (type) == 0))
13640     {
13641       /* ICC does not output the required DW_AT_declaration
13642          on incomplete types, but gives them a size of zero.  */
13643       TYPE_STUB (type) = 1;
13644     }
13645   else
13646     TYPE_STUB_SUPPORTED (type) = 1;
13647
13648   if (die_is_declaration (die, cu))
13649     TYPE_STUB (type) = 1;
13650   else if (attr == NULL && die->child == NULL
13651            && producer_is_realview (cu->producer))
13652     /* RealView does not output the required DW_AT_declaration
13653        on incomplete types.  */
13654     TYPE_STUB (type) = 1;
13655
13656   /* We need to add the type field to the die immediately so we don't
13657      infinitely recurse when dealing with pointers to the structure
13658      type within the structure itself.  */
13659   set_die_type (die, type, cu);
13660
13661   /* set_die_type should be already done.  */
13662   set_descriptive_type (type, die, cu);
13663
13664   return type;
13665 }
13666
13667 /* Finish creating a structure or union type, including filling in
13668    its members and creating a symbol for it.  */
13669
13670 static void
13671 process_structure_scope (struct die_info *die, struct dwarf2_cu *cu)
13672 {
13673   struct objfile *objfile = cu->objfile;
13674   struct die_info *child_die;
13675   struct type *type;
13676
13677   type = get_die_type (die, cu);
13678   if (type == NULL)
13679     type = read_structure_type (die, cu);
13680
13681   if (die->child != NULL && ! die_is_declaration (die, cu))
13682     {
13683       struct field_info fi;
13684       VEC (symbolp) *template_args = NULL;
13685       struct cleanup *back_to = make_cleanup (null_cleanup, 0);
13686
13687       memset (&fi, 0, sizeof (struct field_info));
13688
13689       child_die = die->child;
13690
13691       while (child_die && child_die->tag)
13692         {
13693           if (child_die->tag == DW_TAG_member
13694               || child_die->tag == DW_TAG_variable)
13695             {
13696               /* NOTE: carlton/2002-11-05: A C++ static data member
13697                  should be a DW_TAG_member that is a declaration, but
13698                  all versions of G++ as of this writing (so through at
13699                  least 3.2.1) incorrectly generate DW_TAG_variable
13700                  tags for them instead.  */
13701               dwarf2_add_field (&fi, child_die, cu);
13702             }
13703           else if (child_die->tag == DW_TAG_subprogram)
13704             {
13705               /* Rust doesn't have member functions in the C++ sense.
13706                  However, it does emit ordinary functions as children
13707                  of a struct DIE.  */
13708               if (cu->language == language_rust)
13709                 read_func_scope (child_die, cu);
13710               else
13711                 {
13712                   /* C++ member function.  */
13713                   dwarf2_add_member_fn (&fi, child_die, type, cu);
13714                 }
13715             }
13716           else if (child_die->tag == DW_TAG_inheritance)
13717             {
13718               /* C++ base class field.  */
13719               dwarf2_add_field (&fi, child_die, cu);
13720             }
13721           else if (child_die->tag == DW_TAG_typedef)
13722             dwarf2_add_typedef (&fi, child_die, cu);
13723           else if (child_die->tag == DW_TAG_template_type_param
13724                    || child_die->tag == DW_TAG_template_value_param)
13725             {
13726               struct symbol *arg = new_symbol (child_die, NULL, cu);
13727
13728               if (arg != NULL)
13729                 VEC_safe_push (symbolp, template_args, arg);
13730             }
13731
13732           child_die = sibling_die (child_die);
13733         }
13734
13735       /* Attach template arguments to type.  */
13736       if (! VEC_empty (symbolp, template_args))
13737         {
13738           ALLOCATE_CPLUS_STRUCT_TYPE (type);
13739           TYPE_N_TEMPLATE_ARGUMENTS (type)
13740             = VEC_length (symbolp, template_args);
13741           TYPE_TEMPLATE_ARGUMENTS (type)
13742             = XOBNEWVEC (&objfile->objfile_obstack,
13743                          struct symbol *,
13744                          TYPE_N_TEMPLATE_ARGUMENTS (type));
13745           memcpy (TYPE_TEMPLATE_ARGUMENTS (type),
13746                   VEC_address (symbolp, template_args),
13747                   (TYPE_N_TEMPLATE_ARGUMENTS (type)
13748                    * sizeof (struct symbol *)));
13749           VEC_free (symbolp, template_args);
13750         }
13751
13752       /* Attach fields and member functions to the type.  */
13753       if (fi.nfields)
13754         dwarf2_attach_fields_to_type (&fi, type, cu);
13755       if (fi.nfnfields)
13756         {
13757           dwarf2_attach_fn_fields_to_type (&fi, type, cu);
13758
13759           /* Get the type which refers to the base class (possibly this
13760              class itself) which contains the vtable pointer for the current
13761              class from the DW_AT_containing_type attribute.  This use of
13762              DW_AT_containing_type is a GNU extension.  */
13763
13764           if (dwarf2_attr (die, DW_AT_containing_type, cu) != NULL)
13765             {
13766               struct type *t = die_containing_type (die, cu);
13767
13768               set_type_vptr_basetype (type, t);
13769               if (type == t)
13770                 {
13771                   int i;
13772
13773                   /* Our own class provides vtbl ptr.  */
13774                   for (i = TYPE_NFIELDS (t) - 1;
13775                        i >= TYPE_N_BASECLASSES (t);
13776                        --i)
13777                     {
13778                       const char *fieldname = TYPE_FIELD_NAME (t, i);
13779
13780                       if (is_vtable_name (fieldname, cu))
13781                         {
13782                           set_type_vptr_fieldno (type, i);
13783                           break;
13784                         }
13785                     }
13786
13787                   /* Complain if virtual function table field not found.  */
13788                   if (i < TYPE_N_BASECLASSES (t))
13789                     complaint (&symfile_complaints,
13790                                _("virtual function table pointer "
13791                                  "not found when defining class '%s'"),
13792                                TYPE_TAG_NAME (type) ? TYPE_TAG_NAME (type) :
13793                                "");
13794                 }
13795               else
13796                 {
13797                   set_type_vptr_fieldno (type, TYPE_VPTR_FIELDNO (t));
13798                 }
13799             }
13800           else if (cu->producer
13801                    && startswith (cu->producer, "IBM(R) XL C/C++ Advanced Edition"))
13802             {
13803               /* The IBM XLC compiler does not provide direct indication
13804                  of the containing type, but the vtable pointer is
13805                  always named __vfp.  */
13806
13807               int i;
13808
13809               for (i = TYPE_NFIELDS (type) - 1;
13810                    i >= TYPE_N_BASECLASSES (type);
13811                    --i)
13812                 {
13813                   if (strcmp (TYPE_FIELD_NAME (type, i), "__vfp") == 0)
13814                     {
13815                       set_type_vptr_fieldno (type, i);
13816                       set_type_vptr_basetype (type, type);
13817                       break;
13818                     }
13819                 }
13820             }
13821         }
13822
13823       /* Copy fi.typedef_field_list linked list elements content into the
13824          allocated array TYPE_TYPEDEF_FIELD_ARRAY (type).  */
13825       if (fi.typedef_field_list)
13826         {
13827           int i = fi.typedef_field_list_count;
13828
13829           ALLOCATE_CPLUS_STRUCT_TYPE (type);
13830           TYPE_TYPEDEF_FIELD_ARRAY (type)
13831             = ((struct typedef_field *)
13832                TYPE_ALLOC (type, sizeof (TYPE_TYPEDEF_FIELD (type, 0)) * i));
13833           TYPE_TYPEDEF_FIELD_COUNT (type) = i;
13834
13835           /* Reverse the list order to keep the debug info elements order.  */
13836           while (--i >= 0)
13837             {
13838               struct typedef_field *dest, *src;
13839
13840               dest = &TYPE_TYPEDEF_FIELD (type, i);
13841               src = &fi.typedef_field_list->field;
13842               fi.typedef_field_list = fi.typedef_field_list->next;
13843               *dest = *src;
13844             }
13845         }
13846
13847       do_cleanups (back_to);
13848     }
13849
13850   quirk_gcc_member_function_pointer (type, objfile);
13851
13852   /* NOTE: carlton/2004-03-16: GCC 3.4 (or at least one of its
13853      snapshots) has been known to create a die giving a declaration
13854      for a class that has, as a child, a die giving a definition for a
13855      nested class.  So we have to process our children even if the
13856      current die is a declaration.  Normally, of course, a declaration
13857      won't have any children at all.  */
13858
13859   child_die = die->child;
13860
13861   while (child_die != NULL && child_die->tag)
13862     {
13863       if (child_die->tag == DW_TAG_member
13864           || child_die->tag == DW_TAG_variable
13865           || child_die->tag == DW_TAG_inheritance
13866           || child_die->tag == DW_TAG_template_value_param
13867           || child_die->tag == DW_TAG_template_type_param)
13868         {
13869           /* Do nothing.  */
13870         }
13871       else
13872         process_die (child_die, cu);
13873
13874       child_die = sibling_die (child_die);
13875     }
13876
13877   /* Do not consider external references.  According to the DWARF standard,
13878      these DIEs are identified by the fact that they have no byte_size
13879      attribute, and a declaration attribute.  */
13880   if (dwarf2_attr (die, DW_AT_byte_size, cu) != NULL
13881       || !die_is_declaration (die, cu))
13882     new_symbol (die, type, cu);
13883 }
13884
13885 /* Assuming DIE is an enumeration type, and TYPE is its associated type,
13886    update TYPE using some information only available in DIE's children.  */
13887
13888 static void
13889 update_enumeration_type_from_children (struct die_info *die,
13890                                        struct type *type,
13891                                        struct dwarf2_cu *cu)
13892 {
13893   struct die_info *child_die;
13894   int unsigned_enum = 1;
13895   int flag_enum = 1;
13896   ULONGEST mask = 0;
13897
13898   auto_obstack obstack;
13899
13900   for (child_die = die->child;
13901        child_die != NULL && child_die->tag;
13902        child_die = sibling_die (child_die))
13903     {
13904       struct attribute *attr;
13905       LONGEST value;
13906       const gdb_byte *bytes;
13907       struct dwarf2_locexpr_baton *baton;
13908       const char *name;
13909
13910       if (child_die->tag != DW_TAG_enumerator)
13911         continue;
13912
13913       attr = dwarf2_attr (child_die, DW_AT_const_value, cu);
13914       if (attr == NULL)
13915         continue;
13916
13917       name = dwarf2_name (child_die, cu);
13918       if (name == NULL)
13919         name = "<anonymous enumerator>";
13920
13921       dwarf2_const_value_attr (attr, type, name, &obstack, cu,
13922                                &value, &bytes, &baton);
13923       if (value < 0)
13924         {
13925           unsigned_enum = 0;
13926           flag_enum = 0;
13927         }
13928       else if ((mask & value) != 0)
13929         flag_enum = 0;
13930       else
13931         mask |= value;
13932
13933       /* If we already know that the enum type is neither unsigned, nor
13934          a flag type, no need to look at the rest of the enumerates.  */
13935       if (!unsigned_enum && !flag_enum)
13936         break;
13937     }
13938
13939   if (unsigned_enum)
13940     TYPE_UNSIGNED (type) = 1;
13941   if (flag_enum)
13942     TYPE_FLAG_ENUM (type) = 1;
13943 }
13944
13945 /* Given a DW_AT_enumeration_type die, set its type.  We do not
13946    complete the type's fields yet, or create any symbols.  */
13947
13948 static struct type *
13949 read_enumeration_type (struct die_info *die, struct dwarf2_cu *cu)
13950 {
13951   struct objfile *objfile = cu->objfile;
13952   struct type *type;
13953   struct attribute *attr;
13954   const char *name;
13955
13956   /* If the definition of this type lives in .debug_types, read that type.
13957      Don't follow DW_AT_specification though, that will take us back up
13958      the chain and we want to go down.  */
13959   attr = dwarf2_attr_no_follow (die, DW_AT_signature);
13960   if (attr)
13961     {
13962       type = get_DW_AT_signature_type (die, attr, cu);
13963
13964       /* The type's CU may not be the same as CU.
13965          Ensure TYPE is recorded with CU in die_type_hash.  */
13966       return set_die_type (die, type, cu);
13967     }
13968
13969   type = alloc_type (objfile);
13970
13971   TYPE_CODE (type) = TYPE_CODE_ENUM;
13972   name = dwarf2_full_name (NULL, die, cu);
13973   if (name != NULL)
13974     TYPE_TAG_NAME (type) = name;
13975
13976   attr = dwarf2_attr (die, DW_AT_type, cu);
13977   if (attr != NULL)
13978     {
13979       struct type *underlying_type = die_type (die, cu);
13980
13981       TYPE_TARGET_TYPE (type) = underlying_type;
13982     }
13983
13984   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
13985   if (attr)
13986     {
13987       TYPE_LENGTH (type) = DW_UNSND (attr);
13988     }
13989   else
13990     {
13991       TYPE_LENGTH (type) = 0;
13992     }
13993
13994   /* The enumeration DIE can be incomplete.  In Ada, any type can be
13995      declared as private in the package spec, and then defined only
13996      inside the package body.  Such types are known as Taft Amendment
13997      Types.  When another package uses such a type, an incomplete DIE
13998      may be generated by the compiler.  */
13999   if (die_is_declaration (die, cu))
14000     TYPE_STUB (type) = 1;
14001
14002   /* Finish the creation of this type by using the enum's children.
14003      We must call this even when the underlying type has been provided
14004      so that we can determine if we're looking at a "flag" enum.  */
14005   update_enumeration_type_from_children (die, type, cu);
14006
14007   /* If this type has an underlying type that is not a stub, then we
14008      may use its attributes.  We always use the "unsigned" attribute
14009      in this situation, because ordinarily we guess whether the type
14010      is unsigned -- but the guess can be wrong and the underlying type
14011      can tell us the reality.  However, we defer to a local size
14012      attribute if one exists, because this lets the compiler override
14013      the underlying type if needed.  */
14014   if (TYPE_TARGET_TYPE (type) != NULL && !TYPE_STUB (TYPE_TARGET_TYPE (type)))
14015     {
14016       TYPE_UNSIGNED (type) = TYPE_UNSIGNED (TYPE_TARGET_TYPE (type));
14017       if (TYPE_LENGTH (type) == 0)
14018         TYPE_LENGTH (type) = TYPE_LENGTH (TYPE_TARGET_TYPE (type));
14019     }
14020
14021   TYPE_DECLARED_CLASS (type) = dwarf2_flag_true_p (die, DW_AT_enum_class, cu);
14022
14023   return set_die_type (die, type, cu);
14024 }
14025
14026 /* Given a pointer to a die which begins an enumeration, process all
14027    the dies that define the members of the enumeration, and create the
14028    symbol for the enumeration type.
14029
14030    NOTE: We reverse the order of the element list.  */
14031
14032 static void
14033 process_enumeration_scope (struct die_info *die, struct dwarf2_cu *cu)
14034 {
14035   struct type *this_type;
14036
14037   this_type = get_die_type (die, cu);
14038   if (this_type == NULL)
14039     this_type = read_enumeration_type (die, cu);
14040
14041   if (die->child != NULL)
14042     {
14043       struct die_info *child_die;
14044       struct symbol *sym;
14045       struct field *fields = NULL;
14046       int num_fields = 0;
14047       const char *name;
14048
14049       child_die = die->child;
14050       while (child_die && child_die->tag)
14051         {
14052           if (child_die->tag != DW_TAG_enumerator)
14053             {
14054               process_die (child_die, cu);
14055             }
14056           else
14057             {
14058               name = dwarf2_name (child_die, cu);
14059               if (name)
14060                 {
14061                   sym = new_symbol (child_die, this_type, cu);
14062
14063                   if ((num_fields % DW_FIELD_ALLOC_CHUNK) == 0)
14064                     {
14065                       fields = (struct field *)
14066                         xrealloc (fields,
14067                                   (num_fields + DW_FIELD_ALLOC_CHUNK)
14068                                   * sizeof (struct field));
14069                     }
14070
14071                   FIELD_NAME (fields[num_fields]) = SYMBOL_LINKAGE_NAME (sym);
14072                   FIELD_TYPE (fields[num_fields]) = NULL;
14073                   SET_FIELD_ENUMVAL (fields[num_fields], SYMBOL_VALUE (sym));
14074                   FIELD_BITSIZE (fields[num_fields]) = 0;
14075
14076                   num_fields++;
14077                 }
14078             }
14079
14080           child_die = sibling_die (child_die);
14081         }
14082
14083       if (num_fields)
14084         {
14085           TYPE_NFIELDS (this_type) = num_fields;
14086           TYPE_FIELDS (this_type) = (struct field *)
14087             TYPE_ALLOC (this_type, sizeof (struct field) * num_fields);
14088           memcpy (TYPE_FIELDS (this_type), fields,
14089                   sizeof (struct field) * num_fields);
14090           xfree (fields);
14091         }
14092     }
14093
14094   /* If we are reading an enum from a .debug_types unit, and the enum
14095      is a declaration, and the enum is not the signatured type in the
14096      unit, then we do not want to add a symbol for it.  Adding a
14097      symbol would in some cases obscure the true definition of the
14098      enum, giving users an incomplete type when the definition is
14099      actually available.  Note that we do not want to do this for all
14100      enums which are just declarations, because C++0x allows forward
14101      enum declarations.  */
14102   if (cu->per_cu->is_debug_types
14103       && die_is_declaration (die, cu))
14104     {
14105       struct signatured_type *sig_type;
14106
14107       sig_type = (struct signatured_type *) cu->per_cu;
14108       gdb_assert (to_underlying (sig_type->type_offset_in_section) != 0);
14109       if (sig_type->type_offset_in_section != die->sect_off)
14110         return;
14111     }
14112
14113   new_symbol (die, this_type, cu);
14114 }
14115
14116 /* Extract all information from a DW_TAG_array_type DIE and put it in
14117    the DIE's type field.  For now, this only handles one dimensional
14118    arrays.  */
14119
14120 static struct type *
14121 read_array_type (struct die_info *die, struct dwarf2_cu *cu)
14122 {
14123   struct objfile *objfile = cu->objfile;
14124   struct die_info *child_die;
14125   struct type *type;
14126   struct type *element_type, *range_type, *index_type;
14127   struct type **range_types = NULL;
14128   struct attribute *attr;
14129   int ndim = 0;
14130   struct cleanup *back_to;
14131   const char *name;
14132   unsigned int bit_stride = 0;
14133
14134   element_type = die_type (die, cu);
14135
14136   /* The die_type call above may have already set the type for this DIE.  */
14137   type = get_die_type (die, cu);
14138   if (type)
14139     return type;
14140
14141   attr = dwarf2_attr (die, DW_AT_byte_stride, cu);
14142   if (attr != NULL)
14143     bit_stride = DW_UNSND (attr) * 8;
14144
14145   attr = dwarf2_attr (die, DW_AT_bit_stride, cu);
14146   if (attr != NULL)
14147     bit_stride = DW_UNSND (attr);
14148
14149   /* Irix 6.2 native cc creates array types without children for
14150      arrays with unspecified length.  */
14151   if (die->child == NULL)
14152     {
14153       index_type = objfile_type (objfile)->builtin_int;
14154       range_type = create_static_range_type (NULL, index_type, 0, -1);
14155       type = create_array_type_with_stride (NULL, element_type, range_type,
14156                                             bit_stride);
14157       return set_die_type (die, type, cu);
14158     }
14159
14160   back_to = make_cleanup (null_cleanup, NULL);
14161   child_die = die->child;
14162   while (child_die && child_die->tag)
14163     {
14164       if (child_die->tag == DW_TAG_subrange_type)
14165         {
14166           struct type *child_type = read_type_die (child_die, cu);
14167
14168           if (child_type != NULL)
14169             {
14170               /* The range type was succesfully read.  Save it for the
14171                  array type creation.  */
14172               if ((ndim % DW_FIELD_ALLOC_CHUNK) == 0)
14173                 {
14174                   range_types = (struct type **)
14175                     xrealloc (range_types, (ndim + DW_FIELD_ALLOC_CHUNK)
14176                               * sizeof (struct type *));
14177                   if (ndim == 0)
14178                     make_cleanup (free_current_contents, &range_types);
14179                 }
14180               range_types[ndim++] = child_type;
14181             }
14182         }
14183       child_die = sibling_die (child_die);
14184     }
14185
14186   /* Dwarf2 dimensions are output from left to right, create the
14187      necessary array types in backwards order.  */
14188
14189   type = element_type;
14190
14191   if (read_array_order (die, cu) == DW_ORD_col_major)
14192     {
14193       int i = 0;
14194
14195       while (i < ndim)
14196         type = create_array_type_with_stride (NULL, type, range_types[i++],
14197                                               bit_stride);
14198     }
14199   else
14200     {
14201       while (ndim-- > 0)
14202         type = create_array_type_with_stride (NULL, type, range_types[ndim],
14203                                               bit_stride);
14204     }
14205
14206   /* Understand Dwarf2 support for vector types (like they occur on
14207      the PowerPC w/ AltiVec).  Gcc just adds another attribute to the
14208      array type.  This is not part of the Dwarf2/3 standard yet, but a
14209      custom vendor extension.  The main difference between a regular
14210      array and the vector variant is that vectors are passed by value
14211      to functions.  */
14212   attr = dwarf2_attr (die, DW_AT_GNU_vector, cu);
14213   if (attr)
14214     make_vector_type (type);
14215
14216   /* The DIE may have DW_AT_byte_size set.  For example an OpenCL
14217      implementation may choose to implement triple vectors using this
14218      attribute.  */
14219   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
14220   if (attr)
14221     {
14222       if (DW_UNSND (attr) >= TYPE_LENGTH (type))
14223         TYPE_LENGTH (type) = DW_UNSND (attr);
14224       else
14225         complaint (&symfile_complaints,
14226                    _("DW_AT_byte_size for array type smaller "
14227                      "than the total size of elements"));
14228     }
14229
14230   name = dwarf2_name (die, cu);
14231   if (name)
14232     TYPE_NAME (type) = name;
14233
14234   /* Install the type in the die.  */
14235   set_die_type (die, type, cu);
14236
14237   /* set_die_type should be already done.  */
14238   set_descriptive_type (type, die, cu);
14239
14240   do_cleanups (back_to);
14241
14242   return type;
14243 }
14244
14245 static enum dwarf_array_dim_ordering
14246 read_array_order (struct die_info *die, struct dwarf2_cu *cu)
14247 {
14248   struct attribute *attr;
14249
14250   attr = dwarf2_attr (die, DW_AT_ordering, cu);
14251
14252   if (attr)
14253     return (enum dwarf_array_dim_ordering) DW_SND (attr);
14254
14255   /* GNU F77 is a special case, as at 08/2004 array type info is the
14256      opposite order to the dwarf2 specification, but data is still
14257      laid out as per normal fortran.
14258
14259      FIXME: dsl/2004-8-20: If G77 is ever fixed, this will also need
14260      version checking.  */
14261
14262   if (cu->language == language_fortran
14263       && cu->producer && strstr (cu->producer, "GNU F77"))
14264     {
14265       return DW_ORD_row_major;
14266     }
14267
14268   switch (cu->language_defn->la_array_ordering)
14269     {
14270     case array_column_major:
14271       return DW_ORD_col_major;
14272     case array_row_major:
14273     default:
14274       return DW_ORD_row_major;
14275     };
14276 }
14277
14278 /* Extract all information from a DW_TAG_set_type DIE and put it in
14279    the DIE's type field.  */
14280
14281 static struct type *
14282 read_set_type (struct die_info *die, struct dwarf2_cu *cu)
14283 {
14284   struct type *domain_type, *set_type;
14285   struct attribute *attr;
14286
14287   domain_type = die_type (die, cu);
14288
14289   /* The die_type call above may have already set the type for this DIE.  */
14290   set_type = get_die_type (die, cu);
14291   if (set_type)
14292     return set_type;
14293
14294   set_type = create_set_type (NULL, domain_type);
14295
14296   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
14297   if (attr)
14298     TYPE_LENGTH (set_type) = DW_UNSND (attr);
14299
14300   return set_die_type (die, set_type, cu);
14301 }
14302
14303 /* A helper for read_common_block that creates a locexpr baton.
14304    SYM is the symbol which we are marking as computed.
14305    COMMON_DIE is the DIE for the common block.
14306    COMMON_LOC is the location expression attribute for the common
14307    block itself.
14308    MEMBER_LOC is the location expression attribute for the particular
14309    member of the common block that we are processing.
14310    CU is the CU from which the above come.  */
14311
14312 static void
14313 mark_common_block_symbol_computed (struct symbol *sym,
14314                                    struct die_info *common_die,
14315                                    struct attribute *common_loc,
14316                                    struct attribute *member_loc,
14317                                    struct dwarf2_cu *cu)
14318 {
14319   struct objfile *objfile = dwarf2_per_objfile->objfile;
14320   struct dwarf2_locexpr_baton *baton;
14321   gdb_byte *ptr;
14322   unsigned int cu_off;
14323   enum bfd_endian byte_order = gdbarch_byte_order (get_objfile_arch (objfile));
14324   LONGEST offset = 0;
14325
14326   gdb_assert (common_loc && member_loc);
14327   gdb_assert (attr_form_is_block (common_loc));
14328   gdb_assert (attr_form_is_block (member_loc)
14329               || attr_form_is_constant (member_loc));
14330
14331   baton = XOBNEW (&objfile->objfile_obstack, struct dwarf2_locexpr_baton);
14332   baton->per_cu = cu->per_cu;
14333   gdb_assert (baton->per_cu);
14334
14335   baton->size = 5 /* DW_OP_call4 */ + 1 /* DW_OP_plus */;
14336
14337   if (attr_form_is_constant (member_loc))
14338     {
14339       offset = dwarf2_get_attr_constant_value (member_loc, 0);
14340       baton->size += 1 /* DW_OP_addr */ + cu->header.addr_size;
14341     }
14342   else
14343     baton->size += DW_BLOCK (member_loc)->size;
14344
14345   ptr = (gdb_byte *) obstack_alloc (&objfile->objfile_obstack, baton->size);
14346   baton->data = ptr;
14347
14348   *ptr++ = DW_OP_call4;
14349   cu_off = common_die->sect_off - cu->per_cu->sect_off;
14350   store_unsigned_integer (ptr, 4, byte_order, cu_off);
14351   ptr += 4;
14352
14353   if (attr_form_is_constant (member_loc))
14354     {
14355       *ptr++ = DW_OP_addr;
14356       store_unsigned_integer (ptr, cu->header.addr_size, byte_order, offset);
14357       ptr += cu->header.addr_size;
14358     }
14359   else
14360     {
14361       /* We have to copy the data here, because DW_OP_call4 will only
14362          use a DW_AT_location attribute.  */
14363       memcpy (ptr, DW_BLOCK (member_loc)->data, DW_BLOCK (member_loc)->size);
14364       ptr += DW_BLOCK (member_loc)->size;
14365     }
14366
14367   *ptr++ = DW_OP_plus;
14368   gdb_assert (ptr - baton->data == baton->size);
14369
14370   SYMBOL_LOCATION_BATON (sym) = baton;
14371   SYMBOL_ACLASS_INDEX (sym) = dwarf2_locexpr_index;
14372 }
14373
14374 /* Create appropriate locally-scoped variables for all the
14375    DW_TAG_common_block entries.  Also create a struct common_block
14376    listing all such variables for `info common'.  COMMON_BLOCK_DOMAIN
14377    is used to sepate the common blocks name namespace from regular
14378    variable names.  */
14379
14380 static void
14381 read_common_block (struct die_info *die, struct dwarf2_cu *cu)
14382 {
14383   struct attribute *attr;
14384
14385   attr = dwarf2_attr (die, DW_AT_location, cu);
14386   if (attr)
14387     {
14388       /* Support the .debug_loc offsets.  */
14389       if (attr_form_is_block (attr))
14390         {
14391           /* Ok.  */
14392         }
14393       else if (attr_form_is_section_offset (attr))
14394         {
14395           dwarf2_complex_location_expr_complaint ();
14396           attr = NULL;
14397         }
14398       else
14399         {
14400           dwarf2_invalid_attrib_class_complaint ("DW_AT_location",
14401                                                  "common block member");
14402           attr = NULL;
14403         }
14404     }
14405
14406   if (die->child != NULL)
14407     {
14408       struct objfile *objfile = cu->objfile;
14409       struct die_info *child_die;
14410       size_t n_entries = 0, size;
14411       struct common_block *common_block;
14412       struct symbol *sym;
14413
14414       for (child_die = die->child;
14415            child_die && child_die->tag;
14416            child_die = sibling_die (child_die))
14417         ++n_entries;
14418
14419       size = (sizeof (struct common_block)
14420               + (n_entries - 1) * sizeof (struct symbol *));
14421       common_block
14422         = (struct common_block *) obstack_alloc (&objfile->objfile_obstack,
14423                                                  size);
14424       memset (common_block->contents, 0, n_entries * sizeof (struct symbol *));
14425       common_block->n_entries = 0;
14426
14427       for (child_die = die->child;
14428            child_die && child_die->tag;
14429            child_die = sibling_die (child_die))
14430         {
14431           /* Create the symbol in the DW_TAG_common_block block in the current
14432              symbol scope.  */
14433           sym = new_symbol (child_die, NULL, cu);
14434           if (sym != NULL)
14435             {
14436               struct attribute *member_loc;
14437
14438               common_block->contents[common_block->n_entries++] = sym;
14439
14440               member_loc = dwarf2_attr (child_die, DW_AT_data_member_location,
14441                                         cu);
14442               if (member_loc)
14443                 {
14444                   /* GDB has handled this for a long time, but it is
14445                      not specified by DWARF.  It seems to have been
14446                      emitted by gfortran at least as recently as:
14447                      http://gcc.gnu.org/bugzilla/show_bug.cgi?id=23057.  */
14448                   complaint (&symfile_complaints,
14449                              _("Variable in common block has "
14450                                "DW_AT_data_member_location "
14451                                "- DIE at 0x%x [in module %s]"),
14452                              to_underlying (child_die->sect_off),
14453                              objfile_name (cu->objfile));
14454
14455                   if (attr_form_is_section_offset (member_loc))
14456                     dwarf2_complex_location_expr_complaint ();
14457                   else if (attr_form_is_constant (member_loc)
14458                            || attr_form_is_block (member_loc))
14459                     {
14460                       if (attr)
14461                         mark_common_block_symbol_computed (sym, die, attr,
14462                                                            member_loc, cu);
14463                     }
14464                   else
14465                     dwarf2_complex_location_expr_complaint ();
14466                 }
14467             }
14468         }
14469
14470       sym = new_symbol (die, objfile_type (objfile)->builtin_void, cu);
14471       SYMBOL_VALUE_COMMON_BLOCK (sym) = common_block;
14472     }
14473 }
14474
14475 /* Create a type for a C++ namespace.  */
14476
14477 static struct type *
14478 read_namespace_type (struct die_info *die, struct dwarf2_cu *cu)
14479 {
14480   struct objfile *objfile = cu->objfile;
14481   const char *previous_prefix, *name;
14482   int is_anonymous;
14483   struct type *type;
14484
14485   /* For extensions, reuse the type of the original namespace.  */
14486   if (dwarf2_attr (die, DW_AT_extension, cu) != NULL)
14487     {
14488       struct die_info *ext_die;
14489       struct dwarf2_cu *ext_cu = cu;
14490
14491       ext_die = dwarf2_extension (die, &ext_cu);
14492       type = read_type_die (ext_die, ext_cu);
14493
14494       /* EXT_CU may not be the same as CU.
14495          Ensure TYPE is recorded with CU in die_type_hash.  */
14496       return set_die_type (die, type, cu);
14497     }
14498
14499   name = namespace_name (die, &is_anonymous, cu);
14500
14501   /* Now build the name of the current namespace.  */
14502
14503   previous_prefix = determine_prefix (die, cu);
14504   if (previous_prefix[0] != '\0')
14505     name = typename_concat (&objfile->objfile_obstack,
14506                             previous_prefix, name, 0, cu);
14507
14508   /* Create the type.  */
14509   type = init_type (objfile, TYPE_CODE_NAMESPACE, 0, name);
14510   TYPE_TAG_NAME (type) = TYPE_NAME (type);
14511
14512   return set_die_type (die, type, cu);
14513 }
14514
14515 /* Read a namespace scope.  */
14516
14517 static void
14518 read_namespace (struct die_info *die, struct dwarf2_cu *cu)
14519 {
14520   struct objfile *objfile = cu->objfile;
14521   int is_anonymous;
14522
14523   /* Add a symbol associated to this if we haven't seen the namespace
14524      before.  Also, add a using directive if it's an anonymous
14525      namespace.  */
14526
14527   if (dwarf2_attr (die, DW_AT_extension, cu) == NULL)
14528     {
14529       struct type *type;
14530
14531       type = read_type_die (die, cu);
14532       new_symbol (die, type, cu);
14533
14534       namespace_name (die, &is_anonymous, cu);
14535       if (is_anonymous)
14536         {
14537           const char *previous_prefix = determine_prefix (die, cu);
14538
14539           add_using_directive (using_directives (cu->language),
14540                                previous_prefix, TYPE_NAME (type), NULL,
14541                                NULL, NULL, 0, &objfile->objfile_obstack);
14542         }
14543     }
14544
14545   if (die->child != NULL)
14546     {
14547       struct die_info *child_die = die->child;
14548
14549       while (child_die && child_die->tag)
14550         {
14551           process_die (child_die, cu);
14552           child_die = sibling_die (child_die);
14553         }
14554     }
14555 }
14556
14557 /* Read a Fortran module as type.  This DIE can be only a declaration used for
14558    imported module.  Still we need that type as local Fortran "use ... only"
14559    declaration imports depend on the created type in determine_prefix.  */
14560
14561 static struct type *
14562 read_module_type (struct die_info *die, struct dwarf2_cu *cu)
14563 {
14564   struct objfile *objfile = cu->objfile;
14565   const char *module_name;
14566   struct type *type;
14567
14568   module_name = dwarf2_name (die, cu);
14569   if (!module_name)
14570     complaint (&symfile_complaints,
14571                _("DW_TAG_module has no name, offset 0x%x"),
14572                to_underlying (die->sect_off));
14573   type = init_type (objfile, TYPE_CODE_MODULE, 0, module_name);
14574
14575   /* determine_prefix uses TYPE_TAG_NAME.  */
14576   TYPE_TAG_NAME (type) = TYPE_NAME (type);
14577
14578   return set_die_type (die, type, cu);
14579 }
14580
14581 /* Read a Fortran module.  */
14582
14583 static void
14584 read_module (struct die_info *die, struct dwarf2_cu *cu)
14585 {
14586   struct die_info *child_die = die->child;
14587   struct type *type;
14588
14589   type = read_type_die (die, cu);
14590   new_symbol (die, type, cu);
14591
14592   while (child_die && child_die->tag)
14593     {
14594       process_die (child_die, cu);
14595       child_die = sibling_die (child_die);
14596     }
14597 }
14598
14599 /* Return the name of the namespace represented by DIE.  Set
14600    *IS_ANONYMOUS to tell whether or not the namespace is an anonymous
14601    namespace.  */
14602
14603 static const char *
14604 namespace_name (struct die_info *die, int *is_anonymous, struct dwarf2_cu *cu)
14605 {
14606   struct die_info *current_die;
14607   const char *name = NULL;
14608
14609   /* Loop through the extensions until we find a name.  */
14610
14611   for (current_die = die;
14612        current_die != NULL;
14613        current_die = dwarf2_extension (die, &cu))
14614     {
14615       /* We don't use dwarf2_name here so that we can detect the absence
14616          of a name -> anonymous namespace.  */
14617       name = dwarf2_string_attr (die, DW_AT_name, cu);
14618
14619       if (name != NULL)
14620         break;
14621     }
14622
14623   /* Is it an anonymous namespace?  */
14624
14625   *is_anonymous = (name == NULL);
14626   if (*is_anonymous)
14627     name = CP_ANONYMOUS_NAMESPACE_STR;
14628
14629   return name;
14630 }
14631
14632 /* Extract all information from a DW_TAG_pointer_type DIE and add to
14633    the user defined type vector.  */
14634
14635 static struct type *
14636 read_tag_pointer_type (struct die_info *die, struct dwarf2_cu *cu)
14637 {
14638   struct gdbarch *gdbarch = get_objfile_arch (cu->objfile);
14639   struct comp_unit_head *cu_header = &cu->header;
14640   struct type *type;
14641   struct attribute *attr_byte_size;
14642   struct attribute *attr_address_class;
14643   int byte_size, addr_class;
14644   struct type *target_type;
14645
14646   target_type = die_type (die, cu);
14647
14648   /* The die_type call above may have already set the type for this DIE.  */
14649   type = get_die_type (die, cu);
14650   if (type)
14651     return type;
14652
14653   type = lookup_pointer_type (target_type);
14654
14655   attr_byte_size = dwarf2_attr (die, DW_AT_byte_size, cu);
14656   if (attr_byte_size)
14657     byte_size = DW_UNSND (attr_byte_size);
14658   else
14659     byte_size = cu_header->addr_size;
14660
14661   attr_address_class = dwarf2_attr (die, DW_AT_address_class, cu);
14662   if (attr_address_class)
14663     addr_class = DW_UNSND (attr_address_class);
14664   else
14665     addr_class = DW_ADDR_none;
14666
14667   /* If the pointer size or address class is different than the
14668      default, create a type variant marked as such and set the
14669      length accordingly.  */
14670   if (TYPE_LENGTH (type) != byte_size || addr_class != DW_ADDR_none)
14671     {
14672       if (gdbarch_address_class_type_flags_p (gdbarch))
14673         {
14674           int type_flags;
14675
14676           type_flags = gdbarch_address_class_type_flags
14677                          (gdbarch, byte_size, addr_class);
14678           gdb_assert ((type_flags & ~TYPE_INSTANCE_FLAG_ADDRESS_CLASS_ALL)
14679                       == 0);
14680           type = make_type_with_address_space (type, type_flags);
14681         }
14682       else if (TYPE_LENGTH (type) != byte_size)
14683         {
14684           complaint (&symfile_complaints,
14685                      _("invalid pointer size %d"), byte_size);
14686         }
14687       else
14688         {
14689           /* Should we also complain about unhandled address classes?  */
14690         }
14691     }
14692
14693   TYPE_LENGTH (type) = byte_size;
14694   return set_die_type (die, type, cu);
14695 }
14696
14697 /* Extract all information from a DW_TAG_ptr_to_member_type DIE and add to
14698    the user defined type vector.  */
14699
14700 static struct type *
14701 read_tag_ptr_to_member_type (struct die_info *die, struct dwarf2_cu *cu)
14702 {
14703   struct type *type;
14704   struct type *to_type;
14705   struct type *domain;
14706
14707   to_type = die_type (die, cu);
14708   domain = die_containing_type (die, cu);
14709
14710   /* The calls above may have already set the type for this DIE.  */
14711   type = get_die_type (die, cu);
14712   if (type)
14713     return type;
14714
14715   if (TYPE_CODE (check_typedef (to_type)) == TYPE_CODE_METHOD)
14716     type = lookup_methodptr_type (to_type);
14717   else if (TYPE_CODE (check_typedef (to_type)) == TYPE_CODE_FUNC)
14718     {
14719       struct type *new_type = alloc_type (cu->objfile);
14720
14721       smash_to_method_type (new_type, domain, TYPE_TARGET_TYPE (to_type),
14722                             TYPE_FIELDS (to_type), TYPE_NFIELDS (to_type),
14723                             TYPE_VARARGS (to_type));
14724       type = lookup_methodptr_type (new_type);
14725     }
14726   else
14727     type = lookup_memberptr_type (to_type, domain);
14728
14729   return set_die_type (die, type, cu);
14730 }
14731
14732 /* Extract all information from a DW_TAG_{rvalue_,}reference_type DIE and add to
14733    the user defined type vector.  */
14734
14735 static struct type *
14736 read_tag_reference_type (struct die_info *die, struct dwarf2_cu *cu,
14737                           enum type_code refcode)
14738 {
14739   struct comp_unit_head *cu_header = &cu->header;
14740   struct type *type, *target_type;
14741   struct attribute *attr;
14742
14743   gdb_assert (refcode == TYPE_CODE_REF || refcode == TYPE_CODE_RVALUE_REF);
14744
14745   target_type = die_type (die, cu);
14746
14747   /* The die_type call above may have already set the type for this DIE.  */
14748   type = get_die_type (die, cu);
14749   if (type)
14750     return type;
14751
14752   type = lookup_reference_type (target_type, refcode);
14753   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
14754   if (attr)
14755     {
14756       TYPE_LENGTH (type) = DW_UNSND (attr);
14757     }
14758   else
14759     {
14760       TYPE_LENGTH (type) = cu_header->addr_size;
14761     }
14762   return set_die_type (die, type, cu);
14763 }
14764
14765 /* Add the given cv-qualifiers to the element type of the array.  GCC
14766    outputs DWARF type qualifiers that apply to an array, not the
14767    element type.  But GDB relies on the array element type to carry
14768    the cv-qualifiers.  This mimics section 6.7.3 of the C99
14769    specification.  */
14770
14771 static struct type *
14772 add_array_cv_type (struct die_info *die, struct dwarf2_cu *cu,
14773                    struct type *base_type, int cnst, int voltl)
14774 {
14775   struct type *el_type, *inner_array;
14776
14777   base_type = copy_type (base_type);
14778   inner_array = base_type;
14779
14780   while (TYPE_CODE (TYPE_TARGET_TYPE (inner_array)) == TYPE_CODE_ARRAY)
14781     {
14782       TYPE_TARGET_TYPE (inner_array) =
14783         copy_type (TYPE_TARGET_TYPE (inner_array));
14784       inner_array = TYPE_TARGET_TYPE (inner_array);
14785     }
14786
14787   el_type = TYPE_TARGET_TYPE (inner_array);
14788   cnst |= TYPE_CONST (el_type);
14789   voltl |= TYPE_VOLATILE (el_type);
14790   TYPE_TARGET_TYPE (inner_array) = make_cv_type (cnst, voltl, el_type, NULL);
14791
14792   return set_die_type (die, base_type, cu);
14793 }
14794
14795 static struct type *
14796 read_tag_const_type (struct die_info *die, struct dwarf2_cu *cu)
14797 {
14798   struct type *base_type, *cv_type;
14799
14800   base_type = die_type (die, cu);
14801
14802   /* The die_type call above may have already set the type for this DIE.  */
14803   cv_type = get_die_type (die, cu);
14804   if (cv_type)
14805     return cv_type;
14806
14807   /* In case the const qualifier is applied to an array type, the element type
14808      is so qualified, not the array type (section 6.7.3 of C99).  */
14809   if (TYPE_CODE (base_type) == TYPE_CODE_ARRAY)
14810     return add_array_cv_type (die, cu, base_type, 1, 0);
14811
14812   cv_type = make_cv_type (1, TYPE_VOLATILE (base_type), base_type, 0);
14813   return set_die_type (die, cv_type, cu);
14814 }
14815
14816 static struct type *
14817 read_tag_volatile_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 volatile qualifier is applied to an array type, the
14829      element type is so qualified, not the array type (section 6.7.3
14830      of C99).  */
14831   if (TYPE_CODE (base_type) == TYPE_CODE_ARRAY)
14832     return add_array_cv_type (die, cu, base_type, 0, 1);
14833
14834   cv_type = make_cv_type (TYPE_CONST (base_type), 1, base_type, 0);
14835   return set_die_type (die, cv_type, cu);
14836 }
14837
14838 /* Handle DW_TAG_restrict_type.  */
14839
14840 static struct type *
14841 read_tag_restrict_type (struct die_info *die, struct dwarf2_cu *cu)
14842 {
14843   struct type *base_type, *cv_type;
14844
14845   base_type = die_type (die, cu);
14846
14847   /* The die_type call above may have already set the type for this DIE.  */
14848   cv_type = get_die_type (die, cu);
14849   if (cv_type)
14850     return cv_type;
14851
14852   cv_type = make_restrict_type (base_type);
14853   return set_die_type (die, cv_type, cu);
14854 }
14855
14856 /* Handle DW_TAG_atomic_type.  */
14857
14858 static struct type *
14859 read_tag_atomic_type (struct die_info *die, struct dwarf2_cu *cu)
14860 {
14861   struct type *base_type, *cv_type;
14862
14863   base_type = die_type (die, cu);
14864
14865   /* The die_type call above may have already set the type for this DIE.  */
14866   cv_type = get_die_type (die, cu);
14867   if (cv_type)
14868     return cv_type;
14869
14870   cv_type = make_atomic_type (base_type);
14871   return set_die_type (die, cv_type, cu);
14872 }
14873
14874 /* Extract all information from a DW_TAG_string_type DIE and add to
14875    the user defined type vector.  It isn't really a user defined type,
14876    but it behaves like one, with other DIE's using an AT_user_def_type
14877    attribute to reference it.  */
14878
14879 static struct type *
14880 read_tag_string_type (struct die_info *die, struct dwarf2_cu *cu)
14881 {
14882   struct objfile *objfile = cu->objfile;
14883   struct gdbarch *gdbarch = get_objfile_arch (objfile);
14884   struct type *type, *range_type, *index_type, *char_type;
14885   struct attribute *attr;
14886   unsigned int length;
14887
14888   attr = dwarf2_attr (die, DW_AT_string_length, cu);
14889   if (attr)
14890     {
14891       length = DW_UNSND (attr);
14892     }
14893   else
14894     {
14895       /* Check for the DW_AT_byte_size attribute.  */
14896       attr = dwarf2_attr (die, DW_AT_byte_size, cu);
14897       if (attr)
14898         {
14899           length = DW_UNSND (attr);
14900         }
14901       else
14902         {
14903           length = 1;
14904         }
14905     }
14906
14907   index_type = objfile_type (objfile)->builtin_int;
14908   range_type = create_static_range_type (NULL, index_type, 1, length);
14909   char_type = language_string_char_type (cu->language_defn, gdbarch);
14910   type = create_string_type (NULL, char_type, range_type);
14911
14912   return set_die_type (die, type, cu);
14913 }
14914
14915 /* Assuming that DIE corresponds to a function, returns nonzero
14916    if the function is prototyped.  */
14917
14918 static int
14919 prototyped_function_p (struct die_info *die, struct dwarf2_cu *cu)
14920 {
14921   struct attribute *attr;
14922
14923   attr = dwarf2_attr (die, DW_AT_prototyped, cu);
14924   if (attr && (DW_UNSND (attr) != 0))
14925     return 1;
14926
14927   /* The DWARF standard implies that the DW_AT_prototyped attribute
14928      is only meaninful for C, but the concept also extends to other
14929      languages that allow unprototyped functions (Eg: Objective C).
14930      For all other languages, assume that functions are always
14931      prototyped.  */
14932   if (cu->language != language_c
14933       && cu->language != language_objc
14934       && cu->language != language_opencl)
14935     return 1;
14936
14937   /* RealView does not emit DW_AT_prototyped.  We can not distinguish
14938      prototyped and unprototyped functions; default to prototyped,
14939      since that is more common in modern code (and RealView warns
14940      about unprototyped functions).  */
14941   if (producer_is_realview (cu->producer))
14942     return 1;
14943
14944   return 0;
14945 }
14946
14947 /* Handle DIES due to C code like:
14948
14949    struct foo
14950    {
14951    int (*funcp)(int a, long l);
14952    int b;
14953    };
14954
14955    ('funcp' generates a DW_TAG_subroutine_type DIE).  */
14956
14957 static struct type *
14958 read_subroutine_type (struct die_info *die, struct dwarf2_cu *cu)
14959 {
14960   struct objfile *objfile = cu->objfile;
14961   struct type *type;            /* Type that this function returns.  */
14962   struct type *ftype;           /* Function that returns above type.  */
14963   struct attribute *attr;
14964
14965   type = die_type (die, cu);
14966
14967   /* The die_type call above may have already set the type for this DIE.  */
14968   ftype = get_die_type (die, cu);
14969   if (ftype)
14970     return ftype;
14971
14972   ftype = lookup_function_type (type);
14973
14974   if (prototyped_function_p (die, cu))
14975     TYPE_PROTOTYPED (ftype) = 1;
14976
14977   /* Store the calling convention in the type if it's available in
14978      the subroutine die.  Otherwise set the calling convention to
14979      the default value DW_CC_normal.  */
14980   attr = dwarf2_attr (die, DW_AT_calling_convention, cu);
14981   if (attr)
14982     TYPE_CALLING_CONVENTION (ftype) = DW_UNSND (attr);
14983   else if (cu->producer && strstr (cu->producer, "IBM XL C for OpenCL"))
14984     TYPE_CALLING_CONVENTION (ftype) = DW_CC_GDB_IBM_OpenCL;
14985   else
14986     TYPE_CALLING_CONVENTION (ftype) = DW_CC_normal;
14987
14988   /* Record whether the function returns normally to its caller or not
14989      if the DWARF producer set that information.  */
14990   attr = dwarf2_attr (die, DW_AT_noreturn, cu);
14991   if (attr && (DW_UNSND (attr) != 0))
14992     TYPE_NO_RETURN (ftype) = 1;
14993
14994   /* We need to add the subroutine type to the die immediately so
14995      we don't infinitely recurse when dealing with parameters
14996      declared as the same subroutine type.  */
14997   set_die_type (die, ftype, cu);
14998
14999   if (die->child != NULL)
15000     {
15001       struct type *void_type = objfile_type (objfile)->builtin_void;
15002       struct die_info *child_die;
15003       int nparams, iparams;
15004
15005       /* Count the number of parameters.
15006          FIXME: GDB currently ignores vararg functions, but knows about
15007          vararg member functions.  */
15008       nparams = 0;
15009       child_die = die->child;
15010       while (child_die && child_die->tag)
15011         {
15012           if (child_die->tag == DW_TAG_formal_parameter)
15013             nparams++;
15014           else if (child_die->tag == DW_TAG_unspecified_parameters)
15015             TYPE_VARARGS (ftype) = 1;
15016           child_die = sibling_die (child_die);
15017         }
15018
15019       /* Allocate storage for parameters and fill them in.  */
15020       TYPE_NFIELDS (ftype) = nparams;
15021       TYPE_FIELDS (ftype) = (struct field *)
15022         TYPE_ZALLOC (ftype, nparams * sizeof (struct field));
15023
15024       /* TYPE_FIELD_TYPE must never be NULL.  Pre-fill the array to ensure it
15025          even if we error out during the parameters reading below.  */
15026       for (iparams = 0; iparams < nparams; iparams++)
15027         TYPE_FIELD_TYPE (ftype, iparams) = void_type;
15028
15029       iparams = 0;
15030       child_die = die->child;
15031       while (child_die && child_die->tag)
15032         {
15033           if (child_die->tag == DW_TAG_formal_parameter)
15034             {
15035               struct type *arg_type;
15036
15037               /* DWARF version 2 has no clean way to discern C++
15038                  static and non-static member functions.  G++ helps
15039                  GDB by marking the first parameter for non-static
15040                  member functions (which is the this pointer) as
15041                  artificial.  We pass this information to
15042                  dwarf2_add_member_fn via TYPE_FIELD_ARTIFICIAL.
15043
15044                  DWARF version 3 added DW_AT_object_pointer, which GCC
15045                  4.5 does not yet generate.  */
15046               attr = dwarf2_attr (child_die, DW_AT_artificial, cu);
15047               if (attr)
15048                 TYPE_FIELD_ARTIFICIAL (ftype, iparams) = DW_UNSND (attr);
15049               else
15050                 TYPE_FIELD_ARTIFICIAL (ftype, iparams) = 0;
15051               arg_type = die_type (child_die, cu);
15052
15053               /* RealView does not mark THIS as const, which the testsuite
15054                  expects.  GCC marks THIS as const in method definitions,
15055                  but not in the class specifications (GCC PR 43053).  */
15056               if (cu->language == language_cplus && !TYPE_CONST (arg_type)
15057                   && TYPE_FIELD_ARTIFICIAL (ftype, iparams))
15058                 {
15059                   int is_this = 0;
15060                   struct dwarf2_cu *arg_cu = cu;
15061                   const char *name = dwarf2_name (child_die, cu);
15062
15063                   attr = dwarf2_attr (die, DW_AT_object_pointer, cu);
15064                   if (attr)
15065                     {
15066                       /* If the compiler emits this, use it.  */
15067                       if (follow_die_ref (die, attr, &arg_cu) == child_die)
15068                         is_this = 1;
15069                     }
15070                   else if (name && strcmp (name, "this") == 0)
15071                     /* Function definitions will have the argument names.  */
15072                     is_this = 1;
15073                   else if (name == NULL && iparams == 0)
15074                     /* Declarations may not have the names, so like
15075                        elsewhere in GDB, assume an artificial first
15076                        argument is "this".  */
15077                     is_this = 1;
15078
15079                   if (is_this)
15080                     arg_type = make_cv_type (1, TYPE_VOLATILE (arg_type),
15081                                              arg_type, 0);
15082                 }
15083
15084               TYPE_FIELD_TYPE (ftype, iparams) = arg_type;
15085               iparams++;
15086             }
15087           child_die = sibling_die (child_die);
15088         }
15089     }
15090
15091   return ftype;
15092 }
15093
15094 static struct type *
15095 read_typedef (struct die_info *die, struct dwarf2_cu *cu)
15096 {
15097   struct objfile *objfile = cu->objfile;
15098   const char *name = NULL;
15099   struct type *this_type, *target_type;
15100
15101   name = dwarf2_full_name (NULL, die, cu);
15102   this_type = init_type (objfile, TYPE_CODE_TYPEDEF, 0, name);
15103   TYPE_TARGET_STUB (this_type) = 1;
15104   set_die_type (die, this_type, cu);
15105   target_type = die_type (die, cu);
15106   if (target_type != this_type)
15107     TYPE_TARGET_TYPE (this_type) = target_type;
15108   else
15109     {
15110       /* Self-referential typedefs are, it seems, not allowed by the DWARF
15111          spec and cause infinite loops in GDB.  */
15112       complaint (&symfile_complaints,
15113                  _("Self-referential DW_TAG_typedef "
15114                    "- DIE at 0x%x [in module %s]"),
15115                  to_underlying (die->sect_off), objfile_name (objfile));
15116       TYPE_TARGET_TYPE (this_type) = NULL;
15117     }
15118   return this_type;
15119 }
15120
15121 /* Allocate a floating-point type of size BITS and name NAME.  Pass NAME_HINT
15122    (which may be different from NAME) to the architecture back-end to allow
15123    it to guess the correct format if necessary.  */
15124
15125 static struct type *
15126 dwarf2_init_float_type (struct objfile *objfile, int bits, const char *name,
15127                         const char *name_hint)
15128 {
15129   struct gdbarch *gdbarch = get_objfile_arch (objfile);
15130   const struct floatformat **format;
15131   struct type *type;
15132
15133   format = gdbarch_floatformat_for_type (gdbarch, name_hint, bits);
15134   if (format)
15135     type = init_float_type (objfile, bits, name, format);
15136   else
15137     type = init_type (objfile, TYPE_CODE_ERROR, bits / TARGET_CHAR_BIT, name);
15138
15139   return type;
15140 }
15141
15142 /* Find a representation of a given base type and install
15143    it in the TYPE field of the die.  */
15144
15145 static struct type *
15146 read_base_type (struct die_info *die, struct dwarf2_cu *cu)
15147 {
15148   struct objfile *objfile = cu->objfile;
15149   struct type *type;
15150   struct attribute *attr;
15151   int encoding = 0, bits = 0;
15152   const char *name;
15153
15154   attr = dwarf2_attr (die, DW_AT_encoding, cu);
15155   if (attr)
15156     {
15157       encoding = DW_UNSND (attr);
15158     }
15159   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
15160   if (attr)
15161     {
15162       bits = DW_UNSND (attr) * TARGET_CHAR_BIT;
15163     }
15164   name = dwarf2_name (die, cu);
15165   if (!name)
15166     {
15167       complaint (&symfile_complaints,
15168                  _("DW_AT_name missing from DW_TAG_base_type"));
15169     }
15170
15171   switch (encoding)
15172     {
15173       case DW_ATE_address:
15174         /* Turn DW_ATE_address into a void * pointer.  */
15175         type = init_type (objfile, TYPE_CODE_VOID, 1, NULL);
15176         type = init_pointer_type (objfile, bits, name, type);
15177         break;
15178       case DW_ATE_boolean:
15179         type = init_boolean_type (objfile, bits, 1, name);
15180         break;
15181       case DW_ATE_complex_float:
15182         type = dwarf2_init_float_type (objfile, bits / 2, NULL, name);
15183         type = init_complex_type (objfile, name, type);
15184         break;
15185       case DW_ATE_decimal_float:
15186         type = init_decfloat_type (objfile, bits, name);
15187         break;
15188       case DW_ATE_float:
15189         type = dwarf2_init_float_type (objfile, bits, name, name);
15190         break;
15191       case DW_ATE_signed:
15192         type = init_integer_type (objfile, bits, 0, name);
15193         break;
15194       case DW_ATE_unsigned:
15195         if (cu->language == language_fortran
15196             && name
15197             && startswith (name, "character("))
15198           type = init_character_type (objfile, bits, 1, name);
15199         else
15200           type = init_integer_type (objfile, bits, 1, name);
15201         break;
15202       case DW_ATE_signed_char:
15203         if (cu->language == language_ada || cu->language == language_m2
15204             || cu->language == language_pascal
15205             || cu->language == language_fortran)
15206           type = init_character_type (objfile, bits, 0, name);
15207         else
15208           type = init_integer_type (objfile, bits, 0, name);
15209         break;
15210       case DW_ATE_unsigned_char:
15211         if (cu->language == language_ada || cu->language == language_m2
15212             || cu->language == language_pascal
15213             || cu->language == language_fortran
15214             || cu->language == language_rust)
15215           type = init_character_type (objfile, bits, 1, name);
15216         else
15217           type = init_integer_type (objfile, bits, 1, name);
15218         break;
15219       case DW_ATE_UTF:
15220         {
15221           gdbarch *arch = get_objfile_arch (objfile);
15222
15223           if (bits == 16)
15224             type = builtin_type (arch)->builtin_char16;
15225           else if (bits == 32)
15226             type = builtin_type (arch)->builtin_char32;
15227           else
15228             {
15229               complaint (&symfile_complaints,
15230                          _("unsupported DW_ATE_UTF bit size: '%d'"),
15231                          bits);
15232               type = init_integer_type (objfile, bits, 1, name);
15233             }
15234           return set_die_type (die, type, cu);
15235         }
15236         break;
15237
15238       default:
15239         complaint (&symfile_complaints, _("unsupported DW_AT_encoding: '%s'"),
15240                    dwarf_type_encoding_name (encoding));
15241         type = init_type (objfile, TYPE_CODE_ERROR,
15242                           bits / TARGET_CHAR_BIT, name);
15243         break;
15244     }
15245
15246   if (name && strcmp (name, "char") == 0)
15247     TYPE_NOSIGN (type) = 1;
15248
15249   return set_die_type (die, type, cu);
15250 }
15251
15252 /* Parse dwarf attribute if it's a block, reference or constant and put the
15253    resulting value of the attribute into struct bound_prop.
15254    Returns 1 if ATTR could be resolved into PROP, 0 otherwise.  */
15255
15256 static int
15257 attr_to_dynamic_prop (const struct attribute *attr, struct die_info *die,
15258                       struct dwarf2_cu *cu, struct dynamic_prop *prop)
15259 {
15260   struct dwarf2_property_baton *baton;
15261   struct obstack *obstack = &cu->objfile->objfile_obstack;
15262
15263   if (attr == NULL || prop == NULL)
15264     return 0;
15265
15266   if (attr_form_is_block (attr))
15267     {
15268       baton = XOBNEW (obstack, struct dwarf2_property_baton);
15269       baton->referenced_type = NULL;
15270       baton->locexpr.per_cu = cu->per_cu;
15271       baton->locexpr.size = DW_BLOCK (attr)->size;
15272       baton->locexpr.data = DW_BLOCK (attr)->data;
15273       prop->data.baton = baton;
15274       prop->kind = PROP_LOCEXPR;
15275       gdb_assert (prop->data.baton != NULL);
15276     }
15277   else if (attr_form_is_ref (attr))
15278     {
15279       struct dwarf2_cu *target_cu = cu;
15280       struct die_info *target_die;
15281       struct attribute *target_attr;
15282
15283       target_die = follow_die_ref (die, attr, &target_cu);
15284       target_attr = dwarf2_attr (target_die, DW_AT_location, target_cu);
15285       if (target_attr == NULL)
15286         target_attr = dwarf2_attr (target_die, DW_AT_data_member_location,
15287                                    target_cu);
15288       if (target_attr == NULL)
15289         return 0;
15290
15291       switch (target_attr->name)
15292         {
15293           case DW_AT_location:
15294             if (attr_form_is_section_offset (target_attr))
15295               {
15296                 baton = XOBNEW (obstack, struct dwarf2_property_baton);
15297                 baton->referenced_type = die_type (target_die, target_cu);
15298                 fill_in_loclist_baton (cu, &baton->loclist, target_attr);
15299                 prop->data.baton = baton;
15300                 prop->kind = PROP_LOCLIST;
15301                 gdb_assert (prop->data.baton != NULL);
15302               }
15303             else if (attr_form_is_block (target_attr))
15304               {
15305                 baton = XOBNEW (obstack, struct dwarf2_property_baton);
15306                 baton->referenced_type = die_type (target_die, target_cu);
15307                 baton->locexpr.per_cu = cu->per_cu;
15308                 baton->locexpr.size = DW_BLOCK (target_attr)->size;
15309                 baton->locexpr.data = DW_BLOCK (target_attr)->data;
15310                 prop->data.baton = baton;
15311                 prop->kind = PROP_LOCEXPR;
15312                 gdb_assert (prop->data.baton != NULL);
15313               }
15314             else
15315               {
15316                 dwarf2_invalid_attrib_class_complaint ("DW_AT_location",
15317                                                        "dynamic property");
15318                 return 0;
15319               }
15320             break;
15321           case DW_AT_data_member_location:
15322             {
15323               LONGEST offset;
15324
15325               if (!handle_data_member_location (target_die, target_cu,
15326                                                 &offset))
15327                 return 0;
15328
15329               baton = XOBNEW (obstack, struct dwarf2_property_baton);
15330               baton->referenced_type = read_type_die (target_die->parent,
15331                                                       target_cu);
15332               baton->offset_info.offset = offset;
15333               baton->offset_info.type = die_type (target_die, target_cu);
15334               prop->data.baton = baton;
15335               prop->kind = PROP_ADDR_OFFSET;
15336               break;
15337             }
15338         }
15339     }
15340   else if (attr_form_is_constant (attr))
15341     {
15342       prop->data.const_val = dwarf2_get_attr_constant_value (attr, 0);
15343       prop->kind = PROP_CONST;
15344     }
15345   else
15346     {
15347       dwarf2_invalid_attrib_class_complaint (dwarf_form_name (attr->form),
15348                                              dwarf2_name (die, cu));
15349       return 0;
15350     }
15351
15352   return 1;
15353 }
15354
15355 /* Read the given DW_AT_subrange DIE.  */
15356
15357 static struct type *
15358 read_subrange_type (struct die_info *die, struct dwarf2_cu *cu)
15359 {
15360   struct type *base_type, *orig_base_type;
15361   struct type *range_type;
15362   struct attribute *attr;
15363   struct dynamic_prop low, high;
15364   int low_default_is_valid;
15365   int high_bound_is_count = 0;
15366   const char *name;
15367   LONGEST negative_mask;
15368
15369   orig_base_type = die_type (die, cu);
15370   /* If ORIG_BASE_TYPE is a typedef, it will not be TYPE_UNSIGNED,
15371      whereas the real type might be.  So, we use ORIG_BASE_TYPE when
15372      creating the range type, but we use the result of check_typedef
15373      when examining properties of the type.  */
15374   base_type = check_typedef (orig_base_type);
15375
15376   /* The die_type call above may have already set the type for this DIE.  */
15377   range_type = get_die_type (die, cu);
15378   if (range_type)
15379     return range_type;
15380
15381   low.kind = PROP_CONST;
15382   high.kind = PROP_CONST;
15383   high.data.const_val = 0;
15384
15385   /* Set LOW_DEFAULT_IS_VALID if current language and DWARF version allow
15386      omitting DW_AT_lower_bound.  */
15387   switch (cu->language)
15388     {
15389     case language_c:
15390     case language_cplus:
15391       low.data.const_val = 0;
15392       low_default_is_valid = 1;
15393       break;
15394     case language_fortran:
15395       low.data.const_val = 1;
15396       low_default_is_valid = 1;
15397       break;
15398     case language_d:
15399     case language_objc:
15400     case language_rust:
15401       low.data.const_val = 0;
15402       low_default_is_valid = (cu->header.version >= 4);
15403       break;
15404     case language_ada:
15405     case language_m2:
15406     case language_pascal:
15407       low.data.const_val = 1;
15408       low_default_is_valid = (cu->header.version >= 4);
15409       break;
15410     default:
15411       low.data.const_val = 0;
15412       low_default_is_valid = 0;
15413       break;
15414     }
15415
15416   attr = dwarf2_attr (die, DW_AT_lower_bound, cu);
15417   if (attr)
15418     attr_to_dynamic_prop (attr, die, cu, &low);
15419   else if (!low_default_is_valid)
15420     complaint (&symfile_complaints, _("Missing DW_AT_lower_bound "
15421                                       "- DIE at 0x%x [in module %s]"),
15422                to_underlying (die->sect_off), objfile_name (cu->objfile));
15423
15424   attr = dwarf2_attr (die, DW_AT_upper_bound, cu);
15425   if (!attr_to_dynamic_prop (attr, die, cu, &high))
15426     {
15427       attr = dwarf2_attr (die, DW_AT_count, cu);
15428       if (attr_to_dynamic_prop (attr, die, cu, &high))
15429         {
15430           /* If bounds are constant do the final calculation here.  */
15431           if (low.kind == PROP_CONST && high.kind == PROP_CONST)
15432             high.data.const_val = low.data.const_val + high.data.const_val - 1;
15433           else
15434             high_bound_is_count = 1;
15435         }
15436     }
15437
15438   /* Dwarf-2 specifications explicitly allows to create subrange types
15439      without specifying a base type.
15440      In that case, the base type must be set to the type of
15441      the lower bound, upper bound or count, in that order, if any of these
15442      three attributes references an object that has a type.
15443      If no base type is found, the Dwarf-2 specifications say that
15444      a signed integer type of size equal to the size of an address should
15445      be used.
15446      For the following C code: `extern char gdb_int [];'
15447      GCC produces an empty range DIE.
15448      FIXME: muller/2010-05-28: Possible references to object for low bound,
15449      high bound or count are not yet handled by this code.  */
15450   if (TYPE_CODE (base_type) == TYPE_CODE_VOID)
15451     {
15452       struct objfile *objfile = cu->objfile;
15453       struct gdbarch *gdbarch = get_objfile_arch (objfile);
15454       int addr_size = gdbarch_addr_bit (gdbarch) /8;
15455       struct type *int_type = objfile_type (objfile)->builtin_int;
15456
15457       /* Test "int", "long int", and "long long int" objfile types,
15458          and select the first one having a size above or equal to the
15459          architecture address size.  */
15460       if (int_type && TYPE_LENGTH (int_type) >= addr_size)
15461         base_type = int_type;
15462       else
15463         {
15464           int_type = objfile_type (objfile)->builtin_long;
15465           if (int_type && TYPE_LENGTH (int_type) >= addr_size)
15466             base_type = int_type;
15467           else
15468             {
15469               int_type = objfile_type (objfile)->builtin_long_long;
15470               if (int_type && TYPE_LENGTH (int_type) >= addr_size)
15471                 base_type = int_type;
15472             }
15473         }
15474     }
15475
15476   /* Normally, the DWARF producers are expected to use a signed
15477      constant form (Eg. DW_FORM_sdata) to express negative bounds.
15478      But this is unfortunately not always the case, as witnessed
15479      with GCC, for instance, where the ambiguous DW_FORM_dataN form
15480      is used instead.  To work around that ambiguity, we treat
15481      the bounds as signed, and thus sign-extend their values, when
15482      the base type is signed.  */
15483   negative_mask =
15484     -((LONGEST) 1 << (TYPE_LENGTH (base_type) * TARGET_CHAR_BIT - 1));
15485   if (low.kind == PROP_CONST
15486       && !TYPE_UNSIGNED (base_type) && (low.data.const_val & negative_mask))
15487     low.data.const_val |= negative_mask;
15488   if (high.kind == PROP_CONST
15489       && !TYPE_UNSIGNED (base_type) && (high.data.const_val & negative_mask))
15490     high.data.const_val |= negative_mask;
15491
15492   range_type = create_range_type (NULL, orig_base_type, &low, &high);
15493
15494   if (high_bound_is_count)
15495     TYPE_RANGE_DATA (range_type)->flag_upper_bound_is_count = 1;
15496
15497   /* Ada expects an empty array on no boundary attributes.  */
15498   if (attr == NULL && cu->language != language_ada)
15499     TYPE_HIGH_BOUND_KIND (range_type) = PROP_UNDEFINED;
15500
15501   name = dwarf2_name (die, cu);
15502   if (name)
15503     TYPE_NAME (range_type) = name;
15504
15505   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
15506   if (attr)
15507     TYPE_LENGTH (range_type) = DW_UNSND (attr);
15508
15509   set_die_type (die, range_type, cu);
15510
15511   /* set_die_type should be already done.  */
15512   set_descriptive_type (range_type, die, cu);
15513
15514   return range_type;
15515 }
15516
15517 static struct type *
15518 read_unspecified_type (struct die_info *die, struct dwarf2_cu *cu)
15519 {
15520   struct type *type;
15521
15522   /* For now, we only support the C meaning of an unspecified type: void.  */
15523
15524   type = init_type (cu->objfile, TYPE_CODE_VOID, 0, NULL);
15525   TYPE_NAME (type) = dwarf2_name (die, cu);
15526
15527   return set_die_type (die, type, cu);
15528 }
15529
15530 /* Read a single die and all its descendents.  Set the die's sibling
15531    field to NULL; set other fields in the die correctly, and set all
15532    of the descendents' fields correctly.  Set *NEW_INFO_PTR to the
15533    location of the info_ptr after reading all of those dies.  PARENT
15534    is the parent of the die in question.  */
15535
15536 static struct die_info *
15537 read_die_and_children (const struct die_reader_specs *reader,
15538                        const gdb_byte *info_ptr,
15539                        const gdb_byte **new_info_ptr,
15540                        struct die_info *parent)
15541 {
15542   struct die_info *die;
15543   const gdb_byte *cur_ptr;
15544   int has_children;
15545
15546   cur_ptr = read_full_die_1 (reader, &die, info_ptr, &has_children, 0);
15547   if (die == NULL)
15548     {
15549       *new_info_ptr = cur_ptr;
15550       return NULL;
15551     }
15552   store_in_ref_table (die, reader->cu);
15553
15554   if (has_children)
15555     die->child = read_die_and_siblings_1 (reader, cur_ptr, new_info_ptr, die);
15556   else
15557     {
15558       die->child = NULL;
15559       *new_info_ptr = cur_ptr;
15560     }
15561
15562   die->sibling = NULL;
15563   die->parent = parent;
15564   return die;
15565 }
15566
15567 /* Read a die, all of its descendents, and all of its siblings; set
15568    all of the fields of all of the dies correctly.  Arguments are as
15569    in read_die_and_children.  */
15570
15571 static struct die_info *
15572 read_die_and_siblings_1 (const struct die_reader_specs *reader,
15573                          const gdb_byte *info_ptr,
15574                          const gdb_byte **new_info_ptr,
15575                          struct die_info *parent)
15576 {
15577   struct die_info *first_die, *last_sibling;
15578   const gdb_byte *cur_ptr;
15579
15580   cur_ptr = info_ptr;
15581   first_die = last_sibling = NULL;
15582
15583   while (1)
15584     {
15585       struct die_info *die
15586         = read_die_and_children (reader, cur_ptr, &cur_ptr, parent);
15587
15588       if (die == NULL)
15589         {
15590           *new_info_ptr = cur_ptr;
15591           return first_die;
15592         }
15593
15594       if (!first_die)
15595         first_die = die;
15596       else
15597         last_sibling->sibling = die;
15598
15599       last_sibling = die;
15600     }
15601 }
15602
15603 /* Read a die, all of its descendents, and all of its siblings; set
15604    all of the fields of all of the dies correctly.  Arguments are as
15605    in read_die_and_children.
15606    This the main entry point for reading a DIE and all its children.  */
15607
15608 static struct die_info *
15609 read_die_and_siblings (const struct die_reader_specs *reader,
15610                        const gdb_byte *info_ptr,
15611                        const gdb_byte **new_info_ptr,
15612                        struct die_info *parent)
15613 {
15614   struct die_info *die = read_die_and_siblings_1 (reader, info_ptr,
15615                                                   new_info_ptr, parent);
15616
15617   if (dwarf_die_debug)
15618     {
15619       fprintf_unfiltered (gdb_stdlog,
15620                           "Read die from %s@0x%x of %s:\n",
15621                           get_section_name (reader->die_section),
15622                           (unsigned) (info_ptr - reader->die_section->buffer),
15623                           bfd_get_filename (reader->abfd));
15624       dump_die (die, dwarf_die_debug);
15625     }
15626
15627   return die;
15628 }
15629
15630 /* Read a die and all its attributes, leave space for NUM_EXTRA_ATTRS
15631    attributes.
15632    The caller is responsible for filling in the extra attributes
15633    and updating (*DIEP)->num_attrs.
15634    Set DIEP to point to a newly allocated die with its information,
15635    except for its child, sibling, and parent fields.
15636    Set HAS_CHILDREN to tell whether the die has children or not.  */
15637
15638 static const gdb_byte *
15639 read_full_die_1 (const struct die_reader_specs *reader,
15640                  struct die_info **diep, const gdb_byte *info_ptr,
15641                  int *has_children, int num_extra_attrs)
15642 {
15643   unsigned int abbrev_number, bytes_read, i;
15644   struct abbrev_info *abbrev;
15645   struct die_info *die;
15646   struct dwarf2_cu *cu = reader->cu;
15647   bfd *abfd = reader->abfd;
15648
15649   sect_offset sect_off = (sect_offset) (info_ptr - reader->buffer);
15650   abbrev_number = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
15651   info_ptr += bytes_read;
15652   if (!abbrev_number)
15653     {
15654       *diep = NULL;
15655       *has_children = 0;
15656       return info_ptr;
15657     }
15658
15659   abbrev = abbrev_table_lookup_abbrev (cu->abbrev_table, abbrev_number);
15660   if (!abbrev)
15661     error (_("Dwarf Error: could not find abbrev number %d [in module %s]"),
15662            abbrev_number,
15663            bfd_get_filename (abfd));
15664
15665   die = dwarf_alloc_die (cu, abbrev->num_attrs + num_extra_attrs);
15666   die->sect_off = sect_off;
15667   die->tag = abbrev->tag;
15668   die->abbrev = abbrev_number;
15669
15670   /* Make the result usable.
15671      The caller needs to update num_attrs after adding the extra
15672      attributes.  */
15673   die->num_attrs = abbrev->num_attrs;
15674
15675   for (i = 0; i < abbrev->num_attrs; ++i)
15676     info_ptr = read_attribute (reader, &die->attrs[i], &abbrev->attrs[i],
15677                                info_ptr);
15678
15679   *diep = die;
15680   *has_children = abbrev->has_children;
15681   return info_ptr;
15682 }
15683
15684 /* Read a die and all its attributes.
15685    Set DIEP to point to a newly allocated die with its information,
15686    except for its child, sibling, and parent fields.
15687    Set HAS_CHILDREN to tell whether the die has children or not.  */
15688
15689 static const gdb_byte *
15690 read_full_die (const struct die_reader_specs *reader,
15691                struct die_info **diep, const gdb_byte *info_ptr,
15692                int *has_children)
15693 {
15694   const gdb_byte *result;
15695
15696   result = read_full_die_1 (reader, diep, info_ptr, has_children, 0);
15697
15698   if (dwarf_die_debug)
15699     {
15700       fprintf_unfiltered (gdb_stdlog,
15701                           "Read die from %s@0x%x of %s:\n",
15702                           get_section_name (reader->die_section),
15703                           (unsigned) (info_ptr - reader->die_section->buffer),
15704                           bfd_get_filename (reader->abfd));
15705       dump_die (*diep, dwarf_die_debug);
15706     }
15707
15708   return result;
15709 }
15710 \f
15711 /* Abbreviation tables.
15712
15713    In DWARF version 2, the description of the debugging information is
15714    stored in a separate .debug_abbrev section.  Before we read any
15715    dies from a section we read in all abbreviations and install them
15716    in a hash table.  */
15717
15718 /* Allocate space for a struct abbrev_info object in ABBREV_TABLE.  */
15719
15720 static struct abbrev_info *
15721 abbrev_table_alloc_abbrev (struct abbrev_table *abbrev_table)
15722 {
15723   struct abbrev_info *abbrev;
15724
15725   abbrev = XOBNEW (&abbrev_table->abbrev_obstack, struct abbrev_info);
15726   memset (abbrev, 0, sizeof (struct abbrev_info));
15727
15728   return abbrev;
15729 }
15730
15731 /* Add an abbreviation to the table.  */
15732
15733 static void
15734 abbrev_table_add_abbrev (struct abbrev_table *abbrev_table,
15735                          unsigned int abbrev_number,
15736                          struct abbrev_info *abbrev)
15737 {
15738   unsigned int hash_number;
15739
15740   hash_number = abbrev_number % ABBREV_HASH_SIZE;
15741   abbrev->next = abbrev_table->abbrevs[hash_number];
15742   abbrev_table->abbrevs[hash_number] = abbrev;
15743 }
15744
15745 /* Look up an abbrev in the table.
15746    Returns NULL if the abbrev is not found.  */
15747
15748 static struct abbrev_info *
15749 abbrev_table_lookup_abbrev (const struct abbrev_table *abbrev_table,
15750                             unsigned int abbrev_number)
15751 {
15752   unsigned int hash_number;
15753   struct abbrev_info *abbrev;
15754
15755   hash_number = abbrev_number % ABBREV_HASH_SIZE;
15756   abbrev = abbrev_table->abbrevs[hash_number];
15757
15758   while (abbrev)
15759     {
15760       if (abbrev->number == abbrev_number)
15761         return abbrev;
15762       abbrev = abbrev->next;
15763     }
15764   return NULL;
15765 }
15766
15767 /* Read in an abbrev table.  */
15768
15769 static struct abbrev_table *
15770 abbrev_table_read_table (struct dwarf2_section_info *section,
15771                          sect_offset sect_off)
15772 {
15773   struct objfile *objfile = dwarf2_per_objfile->objfile;
15774   bfd *abfd = get_section_bfd_owner (section);
15775   struct abbrev_table *abbrev_table;
15776   const gdb_byte *abbrev_ptr;
15777   struct abbrev_info *cur_abbrev;
15778   unsigned int abbrev_number, bytes_read, abbrev_name;
15779   unsigned int abbrev_form;
15780   struct attr_abbrev *cur_attrs;
15781   unsigned int allocated_attrs;
15782
15783   abbrev_table = XNEW (struct abbrev_table);
15784   abbrev_table->sect_off = sect_off;
15785   obstack_init (&abbrev_table->abbrev_obstack);
15786   abbrev_table->abbrevs =
15787     XOBNEWVEC (&abbrev_table->abbrev_obstack, struct abbrev_info *,
15788                ABBREV_HASH_SIZE);
15789   memset (abbrev_table->abbrevs, 0,
15790           ABBREV_HASH_SIZE * sizeof (struct abbrev_info *));
15791
15792   dwarf2_read_section (objfile, section);
15793   abbrev_ptr = section->buffer + to_underlying (sect_off);
15794   abbrev_number = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
15795   abbrev_ptr += bytes_read;
15796
15797   allocated_attrs = ATTR_ALLOC_CHUNK;
15798   cur_attrs = XNEWVEC (struct attr_abbrev, allocated_attrs);
15799
15800   /* Loop until we reach an abbrev number of 0.  */
15801   while (abbrev_number)
15802     {
15803       cur_abbrev = abbrev_table_alloc_abbrev (abbrev_table);
15804
15805       /* read in abbrev header */
15806       cur_abbrev->number = abbrev_number;
15807       cur_abbrev->tag
15808         = (enum dwarf_tag) read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
15809       abbrev_ptr += bytes_read;
15810       cur_abbrev->has_children = read_1_byte (abfd, abbrev_ptr);
15811       abbrev_ptr += 1;
15812
15813       /* now read in declarations */
15814       for (;;)
15815         {
15816           LONGEST implicit_const;
15817
15818           abbrev_name = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
15819           abbrev_ptr += bytes_read;
15820           abbrev_form = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
15821           abbrev_ptr += bytes_read;
15822           if (abbrev_form == DW_FORM_implicit_const)
15823             {
15824               implicit_const = read_signed_leb128 (abfd, abbrev_ptr,
15825                                                    &bytes_read);
15826               abbrev_ptr += bytes_read;
15827             }
15828           else
15829             {
15830               /* Initialize it due to a false compiler warning.  */
15831               implicit_const = -1;
15832             }
15833
15834           if (abbrev_name == 0)
15835             break;
15836
15837           if (cur_abbrev->num_attrs == allocated_attrs)
15838             {
15839               allocated_attrs += ATTR_ALLOC_CHUNK;
15840               cur_attrs
15841                 = XRESIZEVEC (struct attr_abbrev, cur_attrs, allocated_attrs);
15842             }
15843
15844           cur_attrs[cur_abbrev->num_attrs].name
15845             = (enum dwarf_attribute) abbrev_name;
15846           cur_attrs[cur_abbrev->num_attrs].form
15847             = (enum dwarf_form) abbrev_form;
15848           cur_attrs[cur_abbrev->num_attrs].implicit_const = implicit_const;
15849           ++cur_abbrev->num_attrs;
15850         }
15851
15852       cur_abbrev->attrs =
15853         XOBNEWVEC (&abbrev_table->abbrev_obstack, struct attr_abbrev,
15854                    cur_abbrev->num_attrs);
15855       memcpy (cur_abbrev->attrs, cur_attrs,
15856               cur_abbrev->num_attrs * sizeof (struct attr_abbrev));
15857
15858       abbrev_table_add_abbrev (abbrev_table, abbrev_number, cur_abbrev);
15859
15860       /* Get next abbreviation.
15861          Under Irix6 the abbreviations for a compilation unit are not
15862          always properly terminated with an abbrev number of 0.
15863          Exit loop if we encounter an abbreviation which we have
15864          already read (which means we are about to read the abbreviations
15865          for the next compile unit) or if the end of the abbreviation
15866          table is reached.  */
15867       if ((unsigned int) (abbrev_ptr - section->buffer) >= section->size)
15868         break;
15869       abbrev_number = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
15870       abbrev_ptr += bytes_read;
15871       if (abbrev_table_lookup_abbrev (abbrev_table, abbrev_number) != NULL)
15872         break;
15873     }
15874
15875   xfree (cur_attrs);
15876   return abbrev_table;
15877 }
15878
15879 /* Free the resources held by ABBREV_TABLE.  */
15880
15881 static void
15882 abbrev_table_free (struct abbrev_table *abbrev_table)
15883 {
15884   obstack_free (&abbrev_table->abbrev_obstack, NULL);
15885   xfree (abbrev_table);
15886 }
15887
15888 /* Same as abbrev_table_free but as a cleanup.
15889    We pass in a pointer to the pointer to the table so that we can
15890    set the pointer to NULL when we're done.  It also simplifies
15891    build_type_psymtabs_1.  */
15892
15893 static void
15894 abbrev_table_free_cleanup (void *table_ptr)
15895 {
15896   struct abbrev_table **abbrev_table_ptr = (struct abbrev_table **) table_ptr;
15897
15898   if (*abbrev_table_ptr != NULL)
15899     abbrev_table_free (*abbrev_table_ptr);
15900   *abbrev_table_ptr = NULL;
15901 }
15902
15903 /* Read the abbrev table for CU from ABBREV_SECTION.  */
15904
15905 static void
15906 dwarf2_read_abbrevs (struct dwarf2_cu *cu,
15907                      struct dwarf2_section_info *abbrev_section)
15908 {
15909   cu->abbrev_table =
15910     abbrev_table_read_table (abbrev_section, cu->header.abbrev_sect_off);
15911 }
15912
15913 /* Release the memory used by the abbrev table for a compilation unit.  */
15914
15915 static void
15916 dwarf2_free_abbrev_table (void *ptr_to_cu)
15917 {
15918   struct dwarf2_cu *cu = (struct dwarf2_cu *) ptr_to_cu;
15919
15920   if (cu->abbrev_table != NULL)
15921     abbrev_table_free (cu->abbrev_table);
15922   /* Set this to NULL so that we SEGV if we try to read it later,
15923      and also because free_comp_unit verifies this is NULL.  */
15924   cu->abbrev_table = NULL;
15925 }
15926 \f
15927 /* Returns nonzero if TAG represents a type that we might generate a partial
15928    symbol for.  */
15929
15930 static int
15931 is_type_tag_for_partial (int tag)
15932 {
15933   switch (tag)
15934     {
15935 #if 0
15936     /* Some types that would be reasonable to generate partial symbols for,
15937        that we don't at present.  */
15938     case DW_TAG_array_type:
15939     case DW_TAG_file_type:
15940     case DW_TAG_ptr_to_member_type:
15941     case DW_TAG_set_type:
15942     case DW_TAG_string_type:
15943     case DW_TAG_subroutine_type:
15944 #endif
15945     case DW_TAG_base_type:
15946     case DW_TAG_class_type:
15947     case DW_TAG_interface_type:
15948     case DW_TAG_enumeration_type:
15949     case DW_TAG_structure_type:
15950     case DW_TAG_subrange_type:
15951     case DW_TAG_typedef:
15952     case DW_TAG_union_type:
15953       return 1;
15954     default:
15955       return 0;
15956     }
15957 }
15958
15959 /* Load all DIEs that are interesting for partial symbols into memory.  */
15960
15961 static struct partial_die_info *
15962 load_partial_dies (const struct die_reader_specs *reader,
15963                    const gdb_byte *info_ptr, int building_psymtab)
15964 {
15965   struct dwarf2_cu *cu = reader->cu;
15966   struct objfile *objfile = cu->objfile;
15967   struct partial_die_info *part_die;
15968   struct partial_die_info *parent_die, *last_die, *first_die = NULL;
15969   struct abbrev_info *abbrev;
15970   unsigned int bytes_read;
15971   unsigned int load_all = 0;
15972   int nesting_level = 1;
15973
15974   parent_die = NULL;
15975   last_die = NULL;
15976
15977   gdb_assert (cu->per_cu != NULL);
15978   if (cu->per_cu->load_all_dies)
15979     load_all = 1;
15980
15981   cu->partial_dies
15982     = htab_create_alloc_ex (cu->header.length / 12,
15983                             partial_die_hash,
15984                             partial_die_eq,
15985                             NULL,
15986                             &cu->comp_unit_obstack,
15987                             hashtab_obstack_allocate,
15988                             dummy_obstack_deallocate);
15989
15990   part_die = XOBNEW (&cu->comp_unit_obstack, struct partial_die_info);
15991
15992   while (1)
15993     {
15994       abbrev = peek_die_abbrev (info_ptr, &bytes_read, cu);
15995
15996       /* A NULL abbrev means the end of a series of children.  */
15997       if (abbrev == NULL)
15998         {
15999           if (--nesting_level == 0)
16000             {
16001               /* PART_DIE was probably the last thing allocated on the
16002                  comp_unit_obstack, so we could call obstack_free
16003                  here.  We don't do that because the waste is small,
16004                  and will be cleaned up when we're done with this
16005                  compilation unit.  This way, we're also more robust
16006                  against other users of the comp_unit_obstack.  */
16007               return first_die;
16008             }
16009           info_ptr += bytes_read;
16010           last_die = parent_die;
16011           parent_die = parent_die->die_parent;
16012           continue;
16013         }
16014
16015       /* Check for template arguments.  We never save these; if
16016          they're seen, we just mark the parent, and go on our way.  */
16017       if (parent_die != NULL
16018           && cu->language == language_cplus
16019           && (abbrev->tag == DW_TAG_template_type_param
16020               || abbrev->tag == DW_TAG_template_value_param))
16021         {
16022           parent_die->has_template_arguments = 1;
16023
16024           if (!load_all)
16025             {
16026               /* We don't need a partial DIE for the template argument.  */
16027               info_ptr = skip_one_die (reader, info_ptr + bytes_read, abbrev);
16028               continue;
16029             }
16030         }
16031
16032       /* We only recurse into c++ subprograms looking for template arguments.
16033          Skip their other children.  */
16034       if (!load_all
16035           && cu->language == language_cplus
16036           && parent_die != NULL
16037           && parent_die->tag == DW_TAG_subprogram)
16038         {
16039           info_ptr = skip_one_die (reader, info_ptr + bytes_read, abbrev);
16040           continue;
16041         }
16042
16043       /* Check whether this DIE is interesting enough to save.  Normally
16044          we would not be interested in members here, but there may be
16045          later variables referencing them via DW_AT_specification (for
16046          static members).  */
16047       if (!load_all
16048           && !is_type_tag_for_partial (abbrev->tag)
16049           && abbrev->tag != DW_TAG_constant
16050           && abbrev->tag != DW_TAG_enumerator
16051           && abbrev->tag != DW_TAG_subprogram
16052           && abbrev->tag != DW_TAG_lexical_block
16053           && abbrev->tag != DW_TAG_variable
16054           && abbrev->tag != DW_TAG_namespace
16055           && abbrev->tag != DW_TAG_module
16056           && abbrev->tag != DW_TAG_member
16057           && abbrev->tag != DW_TAG_imported_unit
16058           && abbrev->tag != DW_TAG_imported_declaration)
16059         {
16060           /* Otherwise we skip to the next sibling, if any.  */
16061           info_ptr = skip_one_die (reader, info_ptr + bytes_read, abbrev);
16062           continue;
16063         }
16064
16065       info_ptr = read_partial_die (reader, part_die, abbrev, bytes_read,
16066                                    info_ptr);
16067
16068       /* This two-pass algorithm for processing partial symbols has a
16069          high cost in cache pressure.  Thus, handle some simple cases
16070          here which cover the majority of C partial symbols.  DIEs
16071          which neither have specification tags in them, nor could have
16072          specification tags elsewhere pointing at them, can simply be
16073          processed and discarded.
16074
16075          This segment is also optional; scan_partial_symbols and
16076          add_partial_symbol will handle these DIEs if we chain
16077          them in normally.  When compilers which do not emit large
16078          quantities of duplicate debug information are more common,
16079          this code can probably be removed.  */
16080
16081       /* Any complete simple types at the top level (pretty much all
16082          of them, for a language without namespaces), can be processed
16083          directly.  */
16084       if (parent_die == NULL
16085           && part_die->has_specification == 0
16086           && part_die->is_declaration == 0
16087           && ((part_die->tag == DW_TAG_typedef && !part_die->has_children)
16088               || part_die->tag == DW_TAG_base_type
16089               || part_die->tag == DW_TAG_subrange_type))
16090         {
16091           if (building_psymtab && part_die->name != NULL)
16092             add_psymbol_to_list (part_die->name, strlen (part_die->name), 0,
16093                                  VAR_DOMAIN, LOC_TYPEDEF,
16094                                  &objfile->static_psymbols,
16095                                  0, cu->language, objfile);
16096           info_ptr = locate_pdi_sibling (reader, part_die, info_ptr);
16097           continue;
16098         }
16099
16100       /* The exception for DW_TAG_typedef with has_children above is
16101          a workaround of GCC PR debug/47510.  In the case of this complaint
16102          type_name_no_tag_or_error will error on such types later.
16103
16104          GDB skipped children of DW_TAG_typedef by the shortcut above and then
16105          it could not find the child DIEs referenced later, this is checked
16106          above.  In correct DWARF DW_TAG_typedef should have no children.  */
16107
16108       if (part_die->tag == DW_TAG_typedef && part_die->has_children)
16109         complaint (&symfile_complaints,
16110                    _("DW_TAG_typedef has childen - GCC PR debug/47510 bug "
16111                      "- DIE at 0x%x [in module %s]"),
16112                    to_underlying (part_die->sect_off), objfile_name (objfile));
16113
16114       /* If we're at the second level, and we're an enumerator, and
16115          our parent has no specification (meaning possibly lives in a
16116          namespace elsewhere), then we can add the partial symbol now
16117          instead of queueing it.  */
16118       if (part_die->tag == DW_TAG_enumerator
16119           && parent_die != NULL
16120           && parent_die->die_parent == NULL
16121           && parent_die->tag == DW_TAG_enumeration_type
16122           && parent_die->has_specification == 0)
16123         {
16124           if (part_die->name == NULL)
16125             complaint (&symfile_complaints,
16126                        _("malformed enumerator DIE ignored"));
16127           else if (building_psymtab)
16128             add_psymbol_to_list (part_die->name, strlen (part_die->name), 0,
16129                                  VAR_DOMAIN, LOC_CONST,
16130                                  cu->language == language_cplus
16131                                  ? &objfile->global_psymbols
16132                                  : &objfile->static_psymbols,
16133                                  0, cu->language, objfile);
16134
16135           info_ptr = locate_pdi_sibling (reader, part_die, info_ptr);
16136           continue;
16137         }
16138
16139       /* We'll save this DIE so link it in.  */
16140       part_die->die_parent = parent_die;
16141       part_die->die_sibling = NULL;
16142       part_die->die_child = NULL;
16143
16144       if (last_die && last_die == parent_die)
16145         last_die->die_child = part_die;
16146       else if (last_die)
16147         last_die->die_sibling = part_die;
16148
16149       last_die = part_die;
16150
16151       if (first_die == NULL)
16152         first_die = part_die;
16153
16154       /* Maybe add the DIE to the hash table.  Not all DIEs that we
16155          find interesting need to be in the hash table, because we
16156          also have the parent/sibling/child chains; only those that we
16157          might refer to by offset later during partial symbol reading.
16158
16159          For now this means things that might have be the target of a
16160          DW_AT_specification, DW_AT_abstract_origin, or
16161          DW_AT_extension.  DW_AT_extension will refer only to
16162          namespaces; DW_AT_abstract_origin refers to functions (and
16163          many things under the function DIE, but we do not recurse
16164          into function DIEs during partial symbol reading) and
16165          possibly variables as well; DW_AT_specification refers to
16166          declarations.  Declarations ought to have the DW_AT_declaration
16167          flag.  It happens that GCC forgets to put it in sometimes, but
16168          only for functions, not for types.
16169
16170          Adding more things than necessary to the hash table is harmless
16171          except for the performance cost.  Adding too few will result in
16172          wasted time in find_partial_die, when we reread the compilation
16173          unit with load_all_dies set.  */
16174
16175       if (load_all
16176           || abbrev->tag == DW_TAG_constant
16177           || abbrev->tag == DW_TAG_subprogram
16178           || abbrev->tag == DW_TAG_variable
16179           || abbrev->tag == DW_TAG_namespace
16180           || part_die->is_declaration)
16181         {
16182           void **slot;
16183
16184           slot = htab_find_slot_with_hash (cu->partial_dies, part_die,
16185                                            to_underlying (part_die->sect_off),
16186                                            INSERT);
16187           *slot = part_die;
16188         }
16189
16190       part_die = XOBNEW (&cu->comp_unit_obstack, struct partial_die_info);
16191
16192       /* For some DIEs we want to follow their children (if any).  For C
16193          we have no reason to follow the children of structures; for other
16194          languages we have to, so that we can get at method physnames
16195          to infer fully qualified class names, for DW_AT_specification,
16196          and for C++ template arguments.  For C++, we also look one level
16197          inside functions to find template arguments (if the name of the
16198          function does not already contain the template arguments).
16199
16200          For Ada, we need to scan the children of subprograms and lexical
16201          blocks as well because Ada allows the definition of nested
16202          entities that could be interesting for the debugger, such as
16203          nested subprograms for instance.  */
16204       if (last_die->has_children
16205           && (load_all
16206               || last_die->tag == DW_TAG_namespace
16207               || last_die->tag == DW_TAG_module
16208               || last_die->tag == DW_TAG_enumeration_type
16209               || (cu->language == language_cplus
16210                   && last_die->tag == DW_TAG_subprogram
16211                   && (last_die->name == NULL
16212                       || strchr (last_die->name, '<') == NULL))
16213               || (cu->language != language_c
16214                   && (last_die->tag == DW_TAG_class_type
16215                       || last_die->tag == DW_TAG_interface_type
16216                       || last_die->tag == DW_TAG_structure_type
16217                       || last_die->tag == DW_TAG_union_type))
16218               || (cu->language == language_ada
16219                   && (last_die->tag == DW_TAG_subprogram
16220                       || last_die->tag == DW_TAG_lexical_block))))
16221         {
16222           nesting_level++;
16223           parent_die = last_die;
16224           continue;
16225         }
16226
16227       /* Otherwise we skip to the next sibling, if any.  */
16228       info_ptr = locate_pdi_sibling (reader, last_die, info_ptr);
16229
16230       /* Back to the top, do it again.  */
16231     }
16232 }
16233
16234 /* Read a minimal amount of information into the minimal die structure.  */
16235
16236 static const gdb_byte *
16237 read_partial_die (const struct die_reader_specs *reader,
16238                   struct partial_die_info *part_die,
16239                   struct abbrev_info *abbrev, unsigned int abbrev_len,
16240                   const gdb_byte *info_ptr)
16241 {
16242   struct dwarf2_cu *cu = reader->cu;
16243   struct objfile *objfile = cu->objfile;
16244   const gdb_byte *buffer = reader->buffer;
16245   unsigned int i;
16246   struct attribute attr;
16247   int has_low_pc_attr = 0;
16248   int has_high_pc_attr = 0;
16249   int high_pc_relative = 0;
16250
16251   memset (part_die, 0, sizeof (struct partial_die_info));
16252
16253   part_die->sect_off = (sect_offset) (info_ptr - buffer);
16254
16255   info_ptr += abbrev_len;
16256
16257   if (abbrev == NULL)
16258     return info_ptr;
16259
16260   part_die->tag = abbrev->tag;
16261   part_die->has_children = abbrev->has_children;
16262
16263   for (i = 0; i < abbrev->num_attrs; ++i)
16264     {
16265       info_ptr = read_attribute (reader, &attr, &abbrev->attrs[i], info_ptr);
16266
16267       /* Store the data if it is of an attribute we want to keep in a
16268          partial symbol table.  */
16269       switch (attr.name)
16270         {
16271         case DW_AT_name:
16272           switch (part_die->tag)
16273             {
16274             case DW_TAG_compile_unit:
16275             case DW_TAG_partial_unit:
16276             case DW_TAG_type_unit:
16277               /* Compilation units have a DW_AT_name that is a filename, not
16278                  a source language identifier.  */
16279             case DW_TAG_enumeration_type:
16280             case DW_TAG_enumerator:
16281               /* These tags always have simple identifiers already; no need
16282                  to canonicalize them.  */
16283               part_die->name = DW_STRING (&attr);
16284               break;
16285             default:
16286               part_die->name
16287                 = dwarf2_canonicalize_name (DW_STRING (&attr), cu,
16288                                             &objfile->per_bfd->storage_obstack);
16289               break;
16290             }
16291           break;
16292         case DW_AT_linkage_name:
16293         case DW_AT_MIPS_linkage_name:
16294           /* Note that both forms of linkage name might appear.  We
16295              assume they will be the same, and we only store the last
16296              one we see.  */
16297           if (cu->language == language_ada)
16298             part_die->name = DW_STRING (&attr);
16299           part_die->linkage_name = DW_STRING (&attr);
16300           break;
16301         case DW_AT_low_pc:
16302           has_low_pc_attr = 1;
16303           part_die->lowpc = attr_value_as_address (&attr);
16304           break;
16305         case DW_AT_high_pc:
16306           has_high_pc_attr = 1;
16307           part_die->highpc = attr_value_as_address (&attr);
16308           if (cu->header.version >= 4 && attr_form_is_constant (&attr))
16309                 high_pc_relative = 1;
16310           break;
16311         case DW_AT_location:
16312           /* Support the .debug_loc offsets.  */
16313           if (attr_form_is_block (&attr))
16314             {
16315                part_die->d.locdesc = DW_BLOCK (&attr);
16316             }
16317           else if (attr_form_is_section_offset (&attr))
16318             {
16319               dwarf2_complex_location_expr_complaint ();
16320             }
16321           else
16322             {
16323               dwarf2_invalid_attrib_class_complaint ("DW_AT_location",
16324                                                      "partial symbol information");
16325             }
16326           break;
16327         case DW_AT_external:
16328           part_die->is_external = DW_UNSND (&attr);
16329           break;
16330         case DW_AT_declaration:
16331           part_die->is_declaration = DW_UNSND (&attr);
16332           break;
16333         case DW_AT_type:
16334           part_die->has_type = 1;
16335           break;
16336         case DW_AT_abstract_origin:
16337         case DW_AT_specification:
16338         case DW_AT_extension:
16339           part_die->has_specification = 1;
16340           part_die->spec_offset = dwarf2_get_ref_die_offset (&attr);
16341           part_die->spec_is_dwz = (attr.form == DW_FORM_GNU_ref_alt
16342                                    || cu->per_cu->is_dwz);
16343           break;
16344         case DW_AT_sibling:
16345           /* Ignore absolute siblings, they might point outside of
16346              the current compile unit.  */
16347           if (attr.form == DW_FORM_ref_addr)
16348             complaint (&symfile_complaints,
16349                        _("ignoring absolute DW_AT_sibling"));
16350           else
16351             {
16352               sect_offset off = dwarf2_get_ref_die_offset (&attr);
16353               const gdb_byte *sibling_ptr = buffer + to_underlying (off);
16354
16355               if (sibling_ptr < info_ptr)
16356                 complaint (&symfile_complaints,
16357                            _("DW_AT_sibling points backwards"));
16358               else if (sibling_ptr > reader->buffer_end)
16359                 dwarf2_section_buffer_overflow_complaint (reader->die_section);
16360               else
16361                 part_die->sibling = sibling_ptr;
16362             }
16363           break;
16364         case DW_AT_byte_size:
16365           part_die->has_byte_size = 1;
16366           break;
16367         case DW_AT_const_value:
16368           part_die->has_const_value = 1;
16369           break;
16370         case DW_AT_calling_convention:
16371           /* DWARF doesn't provide a way to identify a program's source-level
16372              entry point.  DW_AT_calling_convention attributes are only meant
16373              to describe functions' calling conventions.
16374
16375              However, because it's a necessary piece of information in
16376              Fortran, and before DWARF 4 DW_CC_program was the only
16377              piece of debugging information whose definition refers to
16378              a 'main program' at all, several compilers marked Fortran
16379              main programs with DW_CC_program --- even when those
16380              functions use the standard calling conventions.
16381
16382              Although DWARF now specifies a way to provide this
16383              information, we support this practice for backward
16384              compatibility.  */
16385           if (DW_UNSND (&attr) == DW_CC_program
16386               && cu->language == language_fortran)
16387             part_die->main_subprogram = 1;
16388           break;
16389         case DW_AT_inline:
16390           if (DW_UNSND (&attr) == DW_INL_inlined
16391               || DW_UNSND (&attr) == DW_INL_declared_inlined)
16392             part_die->may_be_inlined = 1;
16393           break;
16394
16395         case DW_AT_import:
16396           if (part_die->tag == DW_TAG_imported_unit)
16397             {
16398               part_die->d.sect_off = dwarf2_get_ref_die_offset (&attr);
16399               part_die->is_dwz = (attr.form == DW_FORM_GNU_ref_alt
16400                                   || cu->per_cu->is_dwz);
16401             }
16402           break;
16403
16404         case DW_AT_main_subprogram:
16405           part_die->main_subprogram = DW_UNSND (&attr);
16406           break;
16407
16408         default:
16409           break;
16410         }
16411     }
16412
16413   if (high_pc_relative)
16414     part_die->highpc += part_die->lowpc;
16415
16416   if (has_low_pc_attr && has_high_pc_attr)
16417     {
16418       /* When using the GNU linker, .gnu.linkonce. sections are used to
16419          eliminate duplicate copies of functions and vtables and such.
16420          The linker will arbitrarily choose one and discard the others.
16421          The AT_*_pc values for such functions refer to local labels in
16422          these sections.  If the section from that file was discarded, the
16423          labels are not in the output, so the relocs get a value of 0.
16424          If this is a discarded function, mark the pc bounds as invalid,
16425          so that GDB will ignore it.  */
16426       if (part_die->lowpc == 0 && !dwarf2_per_objfile->has_section_at_zero)
16427         {
16428           struct gdbarch *gdbarch = get_objfile_arch (objfile);
16429
16430           complaint (&symfile_complaints,
16431                      _("DW_AT_low_pc %s is zero "
16432                        "for DIE at 0x%x [in module %s]"),
16433                      paddress (gdbarch, part_die->lowpc),
16434                      to_underlying (part_die->sect_off), objfile_name (objfile));
16435         }
16436       /* dwarf2_get_pc_bounds has also the strict low < high requirement.  */
16437       else if (part_die->lowpc >= part_die->highpc)
16438         {
16439           struct gdbarch *gdbarch = get_objfile_arch (objfile);
16440
16441           complaint (&symfile_complaints,
16442                      _("DW_AT_low_pc %s is not < DW_AT_high_pc %s "
16443                        "for DIE at 0x%x [in module %s]"),
16444                      paddress (gdbarch, part_die->lowpc),
16445                      paddress (gdbarch, part_die->highpc),
16446                      to_underlying (part_die->sect_off),
16447                      objfile_name (objfile));
16448         }
16449       else
16450         part_die->has_pc_info = 1;
16451     }
16452
16453   return info_ptr;
16454 }
16455
16456 /* Find a cached partial DIE at OFFSET in CU.  */
16457
16458 static struct partial_die_info *
16459 find_partial_die_in_comp_unit (sect_offset sect_off, struct dwarf2_cu *cu)
16460 {
16461   struct partial_die_info *lookup_die = NULL;
16462   struct partial_die_info part_die;
16463
16464   part_die.sect_off = sect_off;
16465   lookup_die = ((struct partial_die_info *)
16466                 htab_find_with_hash (cu->partial_dies, &part_die,
16467                                      to_underlying (sect_off)));
16468
16469   return lookup_die;
16470 }
16471
16472 /* Find a partial DIE at OFFSET, which may or may not be in CU,
16473    except in the case of .debug_types DIEs which do not reference
16474    outside their CU (they do however referencing other types via
16475    DW_FORM_ref_sig8).  */
16476
16477 static struct partial_die_info *
16478 find_partial_die (sect_offset sect_off, int offset_in_dwz, struct dwarf2_cu *cu)
16479 {
16480   struct objfile *objfile = cu->objfile;
16481   struct dwarf2_per_cu_data *per_cu = NULL;
16482   struct partial_die_info *pd = NULL;
16483
16484   if (offset_in_dwz == cu->per_cu->is_dwz
16485       && offset_in_cu_p (&cu->header, sect_off))
16486     {
16487       pd = find_partial_die_in_comp_unit (sect_off, cu);
16488       if (pd != NULL)
16489         return pd;
16490       /* We missed recording what we needed.
16491          Load all dies and try again.  */
16492       per_cu = cu->per_cu;
16493     }
16494   else
16495     {
16496       /* TUs don't reference other CUs/TUs (except via type signatures).  */
16497       if (cu->per_cu->is_debug_types)
16498         {
16499           error (_("Dwarf Error: Type Unit at offset 0x%x contains"
16500                    " external reference to offset 0x%x [in module %s].\n"),
16501                  to_underlying (cu->header.sect_off), to_underlying (sect_off),
16502                  bfd_get_filename (objfile->obfd));
16503         }
16504       per_cu = dwarf2_find_containing_comp_unit (sect_off, offset_in_dwz,
16505                                                  objfile);
16506
16507       if (per_cu->cu == NULL || per_cu->cu->partial_dies == NULL)
16508         load_partial_comp_unit (per_cu);
16509
16510       per_cu->cu->last_used = 0;
16511       pd = find_partial_die_in_comp_unit (sect_off, per_cu->cu);
16512     }
16513
16514   /* If we didn't find it, and not all dies have been loaded,
16515      load them all and try again.  */
16516
16517   if (pd == NULL && per_cu->load_all_dies == 0)
16518     {
16519       per_cu->load_all_dies = 1;
16520
16521       /* This is nasty.  When we reread the DIEs, somewhere up the call chain
16522          THIS_CU->cu may already be in use.  So we can't just free it and
16523          replace its DIEs with the ones we read in.  Instead, we leave those
16524          DIEs alone (which can still be in use, e.g. in scan_partial_symbols),
16525          and clobber THIS_CU->cu->partial_dies with the hash table for the new
16526          set.  */
16527       load_partial_comp_unit (per_cu);
16528
16529       pd = find_partial_die_in_comp_unit (sect_off, per_cu->cu);
16530     }
16531
16532   if (pd == NULL)
16533     internal_error (__FILE__, __LINE__,
16534                     _("could not find partial DIE 0x%x "
16535                       "in cache [from module %s]\n"),
16536                     to_underlying (sect_off), bfd_get_filename (objfile->obfd));
16537   return pd;
16538 }
16539
16540 /* See if we can figure out if the class lives in a namespace.  We do
16541    this by looking for a member function; its demangled name will
16542    contain namespace info, if there is any.  */
16543
16544 static void
16545 guess_partial_die_structure_name (struct partial_die_info *struct_pdi,
16546                                   struct dwarf2_cu *cu)
16547 {
16548   /* NOTE: carlton/2003-10-07: Getting the info this way changes
16549      what template types look like, because the demangler
16550      frequently doesn't give the same name as the debug info.  We
16551      could fix this by only using the demangled name to get the
16552      prefix (but see comment in read_structure_type).  */
16553
16554   struct partial_die_info *real_pdi;
16555   struct partial_die_info *child_pdi;
16556
16557   /* If this DIE (this DIE's specification, if any) has a parent, then
16558      we should not do this.  We'll prepend the parent's fully qualified
16559      name when we create the partial symbol.  */
16560
16561   real_pdi = struct_pdi;
16562   while (real_pdi->has_specification)
16563     real_pdi = find_partial_die (real_pdi->spec_offset,
16564                                  real_pdi->spec_is_dwz, cu);
16565
16566   if (real_pdi->die_parent != NULL)
16567     return;
16568
16569   for (child_pdi = struct_pdi->die_child;
16570        child_pdi != NULL;
16571        child_pdi = child_pdi->die_sibling)
16572     {
16573       if (child_pdi->tag == DW_TAG_subprogram
16574           && child_pdi->linkage_name != NULL)
16575         {
16576           char *actual_class_name
16577             = language_class_name_from_physname (cu->language_defn,
16578                                                  child_pdi->linkage_name);
16579           if (actual_class_name != NULL)
16580             {
16581               struct_pdi->name
16582                 = ((const char *)
16583                    obstack_copy0 (&cu->objfile->per_bfd->storage_obstack,
16584                                   actual_class_name,
16585                                   strlen (actual_class_name)));
16586               xfree (actual_class_name);
16587             }
16588           break;
16589         }
16590     }
16591 }
16592
16593 /* Adjust PART_DIE before generating a symbol for it.  This function
16594    may set the is_external flag or change the DIE's name.  */
16595
16596 static void
16597 fixup_partial_die (struct partial_die_info *part_die,
16598                    struct dwarf2_cu *cu)
16599 {
16600   /* Once we've fixed up a die, there's no point in doing so again.
16601      This also avoids a memory leak if we were to call
16602      guess_partial_die_structure_name multiple times.  */
16603   if (part_die->fixup_called)
16604     return;
16605
16606   /* If we found a reference attribute and the DIE has no name, try
16607      to find a name in the referred to DIE.  */
16608
16609   if (part_die->name == NULL && part_die->has_specification)
16610     {
16611       struct partial_die_info *spec_die;
16612
16613       spec_die = find_partial_die (part_die->spec_offset,
16614                                    part_die->spec_is_dwz, cu);
16615
16616       fixup_partial_die (spec_die, cu);
16617
16618       if (spec_die->name)
16619         {
16620           part_die->name = spec_die->name;
16621
16622           /* Copy DW_AT_external attribute if it is set.  */
16623           if (spec_die->is_external)
16624             part_die->is_external = spec_die->is_external;
16625         }
16626     }
16627
16628   /* Set default names for some unnamed DIEs.  */
16629
16630   if (part_die->name == NULL && part_die->tag == DW_TAG_namespace)
16631     part_die->name = CP_ANONYMOUS_NAMESPACE_STR;
16632
16633   /* If there is no parent die to provide a namespace, and there are
16634      children, see if we can determine the namespace from their linkage
16635      name.  */
16636   if (cu->language == language_cplus
16637       && !VEC_empty (dwarf2_section_info_def, dwarf2_per_objfile->types)
16638       && part_die->die_parent == NULL
16639       && part_die->has_children
16640       && (part_die->tag == DW_TAG_class_type
16641           || part_die->tag == DW_TAG_structure_type
16642           || part_die->tag == DW_TAG_union_type))
16643     guess_partial_die_structure_name (part_die, cu);
16644
16645   /* GCC might emit a nameless struct or union that has a linkage
16646      name.  See http://gcc.gnu.org/bugzilla/show_bug.cgi?id=47510.  */
16647   if (part_die->name == NULL
16648       && (part_die->tag == DW_TAG_class_type
16649           || part_die->tag == DW_TAG_interface_type
16650           || part_die->tag == DW_TAG_structure_type
16651           || part_die->tag == DW_TAG_union_type)
16652       && part_die->linkage_name != NULL)
16653     {
16654       char *demangled;
16655
16656       demangled = gdb_demangle (part_die->linkage_name, DMGL_TYPES);
16657       if (demangled)
16658         {
16659           const char *base;
16660
16661           /* Strip any leading namespaces/classes, keep only the base name.
16662              DW_AT_name for named DIEs does not contain the prefixes.  */
16663           base = strrchr (demangled, ':');
16664           if (base && base > demangled && base[-1] == ':')
16665             base++;
16666           else
16667             base = demangled;
16668
16669           part_die->name
16670             = ((const char *)
16671                obstack_copy0 (&cu->objfile->per_bfd->storage_obstack,
16672                               base, strlen (base)));
16673           xfree (demangled);
16674         }
16675     }
16676
16677   part_die->fixup_called = 1;
16678 }
16679
16680 /* Read an attribute value described by an attribute form.  */
16681
16682 static const gdb_byte *
16683 read_attribute_value (const struct die_reader_specs *reader,
16684                       struct attribute *attr, unsigned form,
16685                       LONGEST implicit_const, const gdb_byte *info_ptr)
16686 {
16687   struct dwarf2_cu *cu = reader->cu;
16688   struct objfile *objfile = cu->objfile;
16689   struct gdbarch *gdbarch = get_objfile_arch (objfile);
16690   bfd *abfd = reader->abfd;
16691   struct comp_unit_head *cu_header = &cu->header;
16692   unsigned int bytes_read;
16693   struct dwarf_block *blk;
16694
16695   attr->form = (enum dwarf_form) form;
16696   switch (form)
16697     {
16698     case DW_FORM_ref_addr:
16699       if (cu->header.version == 2)
16700         DW_UNSND (attr) = read_address (abfd, info_ptr, cu, &bytes_read);
16701       else
16702         DW_UNSND (attr) = read_offset (abfd, info_ptr,
16703                                        &cu->header, &bytes_read);
16704       info_ptr += bytes_read;
16705       break;
16706     case DW_FORM_GNU_ref_alt:
16707       DW_UNSND (attr) = read_offset (abfd, info_ptr, &cu->header, &bytes_read);
16708       info_ptr += bytes_read;
16709       break;
16710     case DW_FORM_addr:
16711       DW_ADDR (attr) = read_address (abfd, info_ptr, cu, &bytes_read);
16712       DW_ADDR (attr) = gdbarch_adjust_dwarf2_addr (gdbarch, DW_ADDR (attr));
16713       info_ptr += bytes_read;
16714       break;
16715     case DW_FORM_block2:
16716       blk = dwarf_alloc_block (cu);
16717       blk->size = read_2_bytes (abfd, info_ptr);
16718       info_ptr += 2;
16719       blk->data = read_n_bytes (abfd, info_ptr, blk->size);
16720       info_ptr += blk->size;
16721       DW_BLOCK (attr) = blk;
16722       break;
16723     case DW_FORM_block4:
16724       blk = dwarf_alloc_block (cu);
16725       blk->size = read_4_bytes (abfd, info_ptr);
16726       info_ptr += 4;
16727       blk->data = read_n_bytes (abfd, info_ptr, blk->size);
16728       info_ptr += blk->size;
16729       DW_BLOCK (attr) = blk;
16730       break;
16731     case DW_FORM_data2:
16732       DW_UNSND (attr) = read_2_bytes (abfd, info_ptr);
16733       info_ptr += 2;
16734       break;
16735     case DW_FORM_data4:
16736       DW_UNSND (attr) = read_4_bytes (abfd, info_ptr);
16737       info_ptr += 4;
16738       break;
16739     case DW_FORM_data8:
16740       DW_UNSND (attr) = read_8_bytes (abfd, info_ptr);
16741       info_ptr += 8;
16742       break;
16743     case DW_FORM_data16:
16744       blk = dwarf_alloc_block (cu);
16745       blk->size = 16;
16746       blk->data = read_n_bytes (abfd, info_ptr, 16);
16747       info_ptr += 16;
16748       DW_BLOCK (attr) = blk;
16749       break;
16750     case DW_FORM_sec_offset:
16751       DW_UNSND (attr) = read_offset (abfd, info_ptr, &cu->header, &bytes_read);
16752       info_ptr += bytes_read;
16753       break;
16754     case DW_FORM_string:
16755       DW_STRING (attr) = read_direct_string (abfd, info_ptr, &bytes_read);
16756       DW_STRING_IS_CANONICAL (attr) = 0;
16757       info_ptr += bytes_read;
16758       break;
16759     case DW_FORM_strp:
16760       if (!cu->per_cu->is_dwz)
16761         {
16762           DW_STRING (attr) = read_indirect_string (abfd, info_ptr, cu_header,
16763                                                    &bytes_read);
16764           DW_STRING_IS_CANONICAL (attr) = 0;
16765           info_ptr += bytes_read;
16766           break;
16767         }
16768       /* FALLTHROUGH */
16769     case DW_FORM_line_strp:
16770       if (!cu->per_cu->is_dwz)
16771         {
16772           DW_STRING (attr) = read_indirect_line_string (abfd, info_ptr,
16773                                                         cu_header, &bytes_read);
16774           DW_STRING_IS_CANONICAL (attr) = 0;
16775           info_ptr += bytes_read;
16776           break;
16777         }
16778       /* FALLTHROUGH */
16779     case DW_FORM_GNU_strp_alt:
16780       {
16781         struct dwz_file *dwz = dwarf2_get_dwz_file ();
16782         LONGEST str_offset = read_offset (abfd, info_ptr, cu_header,
16783                                           &bytes_read);
16784
16785         DW_STRING (attr) = read_indirect_string_from_dwz (dwz, str_offset);
16786         DW_STRING_IS_CANONICAL (attr) = 0;
16787         info_ptr += bytes_read;
16788       }
16789       break;
16790     case DW_FORM_exprloc:
16791     case DW_FORM_block:
16792       blk = dwarf_alloc_block (cu);
16793       blk->size = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
16794       info_ptr += bytes_read;
16795       blk->data = read_n_bytes (abfd, info_ptr, blk->size);
16796       info_ptr += blk->size;
16797       DW_BLOCK (attr) = blk;
16798       break;
16799     case DW_FORM_block1:
16800       blk = dwarf_alloc_block (cu);
16801       blk->size = read_1_byte (abfd, info_ptr);
16802       info_ptr += 1;
16803       blk->data = read_n_bytes (abfd, info_ptr, blk->size);
16804       info_ptr += blk->size;
16805       DW_BLOCK (attr) = blk;
16806       break;
16807     case DW_FORM_data1:
16808       DW_UNSND (attr) = read_1_byte (abfd, info_ptr);
16809       info_ptr += 1;
16810       break;
16811     case DW_FORM_flag:
16812       DW_UNSND (attr) = read_1_byte (abfd, info_ptr);
16813       info_ptr += 1;
16814       break;
16815     case DW_FORM_flag_present:
16816       DW_UNSND (attr) = 1;
16817       break;
16818     case DW_FORM_sdata:
16819       DW_SND (attr) = read_signed_leb128 (abfd, info_ptr, &bytes_read);
16820       info_ptr += bytes_read;
16821       break;
16822     case DW_FORM_udata:
16823       DW_UNSND (attr) = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
16824       info_ptr += bytes_read;
16825       break;
16826     case DW_FORM_ref1:
16827       DW_UNSND (attr) = (to_underlying (cu->header.sect_off)
16828                          + read_1_byte (abfd, info_ptr));
16829       info_ptr += 1;
16830       break;
16831     case DW_FORM_ref2:
16832       DW_UNSND (attr) = (to_underlying (cu->header.sect_off)
16833                          + read_2_bytes (abfd, info_ptr));
16834       info_ptr += 2;
16835       break;
16836     case DW_FORM_ref4:
16837       DW_UNSND (attr) = (to_underlying (cu->header.sect_off)
16838                          + read_4_bytes (abfd, info_ptr));
16839       info_ptr += 4;
16840       break;
16841     case DW_FORM_ref8:
16842       DW_UNSND (attr) = (to_underlying (cu->header.sect_off)
16843                          + read_8_bytes (abfd, info_ptr));
16844       info_ptr += 8;
16845       break;
16846     case DW_FORM_ref_sig8:
16847       DW_SIGNATURE (attr) = read_8_bytes (abfd, info_ptr);
16848       info_ptr += 8;
16849       break;
16850     case DW_FORM_ref_udata:
16851       DW_UNSND (attr) = (to_underlying (cu->header.sect_off)
16852                          + read_unsigned_leb128 (abfd, info_ptr, &bytes_read));
16853       info_ptr += bytes_read;
16854       break;
16855     case DW_FORM_indirect:
16856       form = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
16857       info_ptr += bytes_read;
16858       if (form == DW_FORM_implicit_const)
16859         {
16860           implicit_const = read_signed_leb128 (abfd, info_ptr, &bytes_read);
16861           info_ptr += bytes_read;
16862         }
16863       info_ptr = read_attribute_value (reader, attr, form, implicit_const,
16864                                        info_ptr);
16865       break;
16866     case DW_FORM_implicit_const:
16867       DW_SND (attr) = implicit_const;
16868       break;
16869     case DW_FORM_GNU_addr_index:
16870       if (reader->dwo_file == NULL)
16871         {
16872           /* For now flag a hard error.
16873              Later we can turn this into a complaint.  */
16874           error (_("Dwarf Error: %s found in non-DWO CU [in module %s]"),
16875                  dwarf_form_name (form),
16876                  bfd_get_filename (abfd));
16877         }
16878       DW_ADDR (attr) = read_addr_index_from_leb128 (cu, info_ptr, &bytes_read);
16879       info_ptr += bytes_read;
16880       break;
16881     case DW_FORM_GNU_str_index:
16882       if (reader->dwo_file == NULL)
16883         {
16884           /* For now flag a hard error.
16885              Later we can turn this into a complaint if warranted.  */
16886           error (_("Dwarf Error: %s found in non-DWO CU [in module %s]"),
16887                  dwarf_form_name (form),
16888                  bfd_get_filename (abfd));
16889         }
16890       {
16891         ULONGEST str_index =
16892           read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
16893
16894         DW_STRING (attr) = read_str_index (reader, str_index);
16895         DW_STRING_IS_CANONICAL (attr) = 0;
16896         info_ptr += bytes_read;
16897       }
16898       break;
16899     default:
16900       error (_("Dwarf Error: Cannot handle %s in DWARF reader [in module %s]"),
16901              dwarf_form_name (form),
16902              bfd_get_filename (abfd));
16903     }
16904
16905   /* Super hack.  */
16906   if (cu->per_cu->is_dwz && attr_form_is_ref (attr))
16907     attr->form = DW_FORM_GNU_ref_alt;
16908
16909   /* We have seen instances where the compiler tried to emit a byte
16910      size attribute of -1 which ended up being encoded as an unsigned
16911      0xffffffff.  Although 0xffffffff is technically a valid size value,
16912      an object of this size seems pretty unlikely so we can relatively
16913      safely treat these cases as if the size attribute was invalid and
16914      treat them as zero by default.  */
16915   if (attr->name == DW_AT_byte_size
16916       && form == DW_FORM_data4
16917       && DW_UNSND (attr) >= 0xffffffff)
16918     {
16919       complaint
16920         (&symfile_complaints,
16921          _("Suspicious DW_AT_byte_size value treated as zero instead of %s"),
16922          hex_string (DW_UNSND (attr)));
16923       DW_UNSND (attr) = 0;
16924     }
16925
16926   return info_ptr;
16927 }
16928
16929 /* Read an attribute described by an abbreviated attribute.  */
16930
16931 static const gdb_byte *
16932 read_attribute (const struct die_reader_specs *reader,
16933                 struct attribute *attr, struct attr_abbrev *abbrev,
16934                 const gdb_byte *info_ptr)
16935 {
16936   attr->name = abbrev->name;
16937   return read_attribute_value (reader, attr, abbrev->form,
16938                                abbrev->implicit_const, info_ptr);
16939 }
16940
16941 /* Read dwarf information from a buffer.  */
16942
16943 static unsigned int
16944 read_1_byte (bfd *abfd, const gdb_byte *buf)
16945 {
16946   return bfd_get_8 (abfd, buf);
16947 }
16948
16949 static int
16950 read_1_signed_byte (bfd *abfd, const gdb_byte *buf)
16951 {
16952   return bfd_get_signed_8 (abfd, buf);
16953 }
16954
16955 static unsigned int
16956 read_2_bytes (bfd *abfd, const gdb_byte *buf)
16957 {
16958   return bfd_get_16 (abfd, buf);
16959 }
16960
16961 static int
16962 read_2_signed_bytes (bfd *abfd, const gdb_byte *buf)
16963 {
16964   return bfd_get_signed_16 (abfd, buf);
16965 }
16966
16967 static unsigned int
16968 read_4_bytes (bfd *abfd, const gdb_byte *buf)
16969 {
16970   return bfd_get_32 (abfd, buf);
16971 }
16972
16973 static int
16974 read_4_signed_bytes (bfd *abfd, const gdb_byte *buf)
16975 {
16976   return bfd_get_signed_32 (abfd, buf);
16977 }
16978
16979 static ULONGEST
16980 read_8_bytes (bfd *abfd, const gdb_byte *buf)
16981 {
16982   return bfd_get_64 (abfd, buf);
16983 }
16984
16985 static CORE_ADDR
16986 read_address (bfd *abfd, const gdb_byte *buf, struct dwarf2_cu *cu,
16987               unsigned int *bytes_read)
16988 {
16989   struct comp_unit_head *cu_header = &cu->header;
16990   CORE_ADDR retval = 0;
16991
16992   if (cu_header->signed_addr_p)
16993     {
16994       switch (cu_header->addr_size)
16995         {
16996         case 2:
16997           retval = bfd_get_signed_16 (abfd, buf);
16998           break;
16999         case 4:
17000           retval = bfd_get_signed_32 (abfd, buf);
17001           break;
17002         case 8:
17003           retval = bfd_get_signed_64 (abfd, buf);
17004           break;
17005         default:
17006           internal_error (__FILE__, __LINE__,
17007                           _("read_address: bad switch, signed [in module %s]"),
17008                           bfd_get_filename (abfd));
17009         }
17010     }
17011   else
17012     {
17013       switch (cu_header->addr_size)
17014         {
17015         case 2:
17016           retval = bfd_get_16 (abfd, buf);
17017           break;
17018         case 4:
17019           retval = bfd_get_32 (abfd, buf);
17020           break;
17021         case 8:
17022           retval = bfd_get_64 (abfd, buf);
17023           break;
17024         default:
17025           internal_error (__FILE__, __LINE__,
17026                           _("read_address: bad switch, "
17027                             "unsigned [in module %s]"),
17028                           bfd_get_filename (abfd));
17029         }
17030     }
17031
17032   *bytes_read = cu_header->addr_size;
17033   return retval;
17034 }
17035
17036 /* Read the initial length from a section.  The (draft) DWARF 3
17037    specification allows the initial length to take up either 4 bytes
17038    or 12 bytes.  If the first 4 bytes are 0xffffffff, then the next 8
17039    bytes describe the length and all offsets will be 8 bytes in length
17040    instead of 4.
17041
17042    An older, non-standard 64-bit format is also handled by this
17043    function.  The older format in question stores the initial length
17044    as an 8-byte quantity without an escape value.  Lengths greater
17045    than 2^32 aren't very common which means that the initial 4 bytes
17046    is almost always zero.  Since a length value of zero doesn't make
17047    sense for the 32-bit format, this initial zero can be considered to
17048    be an escape value which indicates the presence of the older 64-bit
17049    format.  As written, the code can't detect (old format) lengths
17050    greater than 4GB.  If it becomes necessary to handle lengths
17051    somewhat larger than 4GB, we could allow other small values (such
17052    as the non-sensical values of 1, 2, and 3) to also be used as
17053    escape values indicating the presence of the old format.
17054
17055    The value returned via bytes_read should be used to increment the
17056    relevant pointer after calling read_initial_length().
17057
17058    [ Note:  read_initial_length() and read_offset() are based on the
17059      document entitled "DWARF Debugging Information Format", revision
17060      3, draft 8, dated November 19, 2001.  This document was obtained
17061      from:
17062
17063         http://reality.sgiweb.org/davea/dwarf3-draft8-011125.pdf
17064
17065      This document is only a draft and is subject to change.  (So beware.)
17066
17067      Details regarding the older, non-standard 64-bit format were
17068      determined empirically by examining 64-bit ELF files produced by
17069      the SGI toolchain on an IRIX 6.5 machine.
17070
17071      - Kevin, July 16, 2002
17072    ] */
17073
17074 static LONGEST
17075 read_initial_length (bfd *abfd, const gdb_byte *buf, unsigned int *bytes_read)
17076 {
17077   LONGEST length = bfd_get_32 (abfd, buf);
17078
17079   if (length == 0xffffffff)
17080     {
17081       length = bfd_get_64 (abfd, buf + 4);
17082       *bytes_read = 12;
17083     }
17084   else if (length == 0)
17085     {
17086       /* Handle the (non-standard) 64-bit DWARF2 format used by IRIX.  */
17087       length = bfd_get_64 (abfd, buf);
17088       *bytes_read = 8;
17089     }
17090   else
17091     {
17092       *bytes_read = 4;
17093     }
17094
17095   return length;
17096 }
17097
17098 /* Cover function for read_initial_length.
17099    Returns the length of the object at BUF, and stores the size of the
17100    initial length in *BYTES_READ and stores the size that offsets will be in
17101    *OFFSET_SIZE.
17102    If the initial length size is not equivalent to that specified in
17103    CU_HEADER then issue a complaint.
17104    This is useful when reading non-comp-unit headers.  */
17105
17106 static LONGEST
17107 read_checked_initial_length_and_offset (bfd *abfd, const gdb_byte *buf,
17108                                         const struct comp_unit_head *cu_header,
17109                                         unsigned int *bytes_read,
17110                                         unsigned int *offset_size)
17111 {
17112   LONGEST length = read_initial_length (abfd, buf, bytes_read);
17113
17114   gdb_assert (cu_header->initial_length_size == 4
17115               || cu_header->initial_length_size == 8
17116               || cu_header->initial_length_size == 12);
17117
17118   if (cu_header->initial_length_size != *bytes_read)
17119     complaint (&symfile_complaints,
17120                _("intermixed 32-bit and 64-bit DWARF sections"));
17121
17122   *offset_size = (*bytes_read == 4) ? 4 : 8;
17123   return length;
17124 }
17125
17126 /* Read an offset from the data stream.  The size of the offset is
17127    given by cu_header->offset_size.  */
17128
17129 static LONGEST
17130 read_offset (bfd *abfd, const gdb_byte *buf,
17131              const struct comp_unit_head *cu_header,
17132              unsigned int *bytes_read)
17133 {
17134   LONGEST offset = read_offset_1 (abfd, buf, cu_header->offset_size);
17135
17136   *bytes_read = cu_header->offset_size;
17137   return offset;
17138 }
17139
17140 /* Read an offset from the data stream.  */
17141
17142 static LONGEST
17143 read_offset_1 (bfd *abfd, const gdb_byte *buf, unsigned int offset_size)
17144 {
17145   LONGEST retval = 0;
17146
17147   switch (offset_size)
17148     {
17149     case 4:
17150       retval = bfd_get_32 (abfd, buf);
17151       break;
17152     case 8:
17153       retval = bfd_get_64 (abfd, buf);
17154       break;
17155     default:
17156       internal_error (__FILE__, __LINE__,
17157                       _("read_offset_1: bad switch [in module %s]"),
17158                       bfd_get_filename (abfd));
17159     }
17160
17161   return retval;
17162 }
17163
17164 static const gdb_byte *
17165 read_n_bytes (bfd *abfd, const gdb_byte *buf, unsigned int size)
17166 {
17167   /* If the size of a host char is 8 bits, we can return a pointer
17168      to the buffer, otherwise we have to copy the data to a buffer
17169      allocated on the temporary obstack.  */
17170   gdb_assert (HOST_CHAR_BIT == 8);
17171   return buf;
17172 }
17173
17174 static const char *
17175 read_direct_string (bfd *abfd, const gdb_byte *buf,
17176                     unsigned int *bytes_read_ptr)
17177 {
17178   /* If the size of a host char is 8 bits, we can return a pointer
17179      to the string, otherwise we have to copy the string to a buffer
17180      allocated on the temporary obstack.  */
17181   gdb_assert (HOST_CHAR_BIT == 8);
17182   if (*buf == '\0')
17183     {
17184       *bytes_read_ptr = 1;
17185       return NULL;
17186     }
17187   *bytes_read_ptr = strlen ((const char *) buf) + 1;
17188   return (const char *) buf;
17189 }
17190
17191 /* Return pointer to string at section SECT offset STR_OFFSET with error
17192    reporting strings FORM_NAME and SECT_NAME.  */
17193
17194 static const char *
17195 read_indirect_string_at_offset_from (bfd *abfd, LONGEST str_offset,
17196                                      struct dwarf2_section_info *sect,
17197                                      const char *form_name,
17198                                      const char *sect_name)
17199 {
17200   dwarf2_read_section (dwarf2_per_objfile->objfile, sect);
17201   if (sect->buffer == NULL)
17202     error (_("%s used without %s section [in module %s]"),
17203            form_name, sect_name, bfd_get_filename (abfd));
17204   if (str_offset >= sect->size)
17205     error (_("%s pointing outside of %s section [in module %s]"),
17206            form_name, sect_name, bfd_get_filename (abfd));
17207   gdb_assert (HOST_CHAR_BIT == 8);
17208   if (sect->buffer[str_offset] == '\0')
17209     return NULL;
17210   return (const char *) (sect->buffer + str_offset);
17211 }
17212
17213 /* Return pointer to string at .debug_str offset STR_OFFSET.  */
17214
17215 static const char *
17216 read_indirect_string_at_offset (bfd *abfd, LONGEST str_offset)
17217 {
17218   return read_indirect_string_at_offset_from (abfd, str_offset,
17219                                               &dwarf2_per_objfile->str,
17220                                               "DW_FORM_strp", ".debug_str");
17221 }
17222
17223 /* Return pointer to string at .debug_line_str offset STR_OFFSET.  */
17224
17225 static const char *
17226 read_indirect_line_string_at_offset (bfd *abfd, LONGEST str_offset)
17227 {
17228   return read_indirect_string_at_offset_from (abfd, str_offset,
17229                                               &dwarf2_per_objfile->line_str,
17230                                               "DW_FORM_line_strp",
17231                                               ".debug_line_str");
17232 }
17233
17234 /* Read a string at offset STR_OFFSET in the .debug_str section from
17235    the .dwz file DWZ.  Throw an error if the offset is too large.  If
17236    the string consists of a single NUL byte, return NULL; otherwise
17237    return a pointer to the string.  */
17238
17239 static const char *
17240 read_indirect_string_from_dwz (struct dwz_file *dwz, LONGEST str_offset)
17241 {
17242   dwarf2_read_section (dwarf2_per_objfile->objfile, &dwz->str);
17243
17244   if (dwz->str.buffer == NULL)
17245     error (_("DW_FORM_GNU_strp_alt used without .debug_str "
17246              "section [in module %s]"),
17247            bfd_get_filename (dwz->dwz_bfd));
17248   if (str_offset >= dwz->str.size)
17249     error (_("DW_FORM_GNU_strp_alt pointing outside of "
17250              ".debug_str section [in module %s]"),
17251            bfd_get_filename (dwz->dwz_bfd));
17252   gdb_assert (HOST_CHAR_BIT == 8);
17253   if (dwz->str.buffer[str_offset] == '\0')
17254     return NULL;
17255   return (const char *) (dwz->str.buffer + str_offset);
17256 }
17257
17258 /* Return pointer to string at .debug_str offset as read from BUF.
17259    BUF is assumed to be in a compilation unit described by CU_HEADER.
17260    Return *BYTES_READ_PTR count of bytes read from BUF.  */
17261
17262 static const char *
17263 read_indirect_string (bfd *abfd, const gdb_byte *buf,
17264                       const struct comp_unit_head *cu_header,
17265                       unsigned int *bytes_read_ptr)
17266 {
17267   LONGEST str_offset = read_offset (abfd, buf, cu_header, bytes_read_ptr);
17268
17269   return read_indirect_string_at_offset (abfd, str_offset);
17270 }
17271
17272 /* Return pointer to string at .debug_line_str offset as read from BUF.
17273    BUF is assumed to be in a compilation unit described by CU_HEADER.
17274    Return *BYTES_READ_PTR count of bytes read from BUF.  */
17275
17276 static const char *
17277 read_indirect_line_string (bfd *abfd, const gdb_byte *buf,
17278                            const struct comp_unit_head *cu_header,
17279                            unsigned int *bytes_read_ptr)
17280 {
17281   LONGEST str_offset = read_offset (abfd, buf, cu_header, bytes_read_ptr);
17282
17283   return read_indirect_line_string_at_offset (abfd, str_offset);
17284 }
17285
17286 ULONGEST
17287 read_unsigned_leb128 (bfd *abfd, const gdb_byte *buf,
17288                           unsigned int *bytes_read_ptr)
17289 {
17290   ULONGEST result;
17291   unsigned int num_read;
17292   int shift;
17293   unsigned char byte;
17294
17295   result = 0;
17296   shift = 0;
17297   num_read = 0;
17298   while (1)
17299     {
17300       byte = bfd_get_8 (abfd, buf);
17301       buf++;
17302       num_read++;
17303       result |= ((ULONGEST) (byte & 127) << shift);
17304       if ((byte & 128) == 0)
17305         {
17306           break;
17307         }
17308       shift += 7;
17309     }
17310   *bytes_read_ptr = num_read;
17311   return result;
17312 }
17313
17314 static LONGEST
17315 read_signed_leb128 (bfd *abfd, const gdb_byte *buf,
17316                     unsigned int *bytes_read_ptr)
17317 {
17318   LONGEST result;
17319   int shift, num_read;
17320   unsigned char byte;
17321
17322   result = 0;
17323   shift = 0;
17324   num_read = 0;
17325   while (1)
17326     {
17327       byte = bfd_get_8 (abfd, buf);
17328       buf++;
17329       num_read++;
17330       result |= ((LONGEST) (byte & 127) << shift);
17331       shift += 7;
17332       if ((byte & 128) == 0)
17333         {
17334           break;
17335         }
17336     }
17337   if ((shift < 8 * sizeof (result)) && (byte & 0x40))
17338     result |= -(((LONGEST) 1) << shift);
17339   *bytes_read_ptr = num_read;
17340   return result;
17341 }
17342
17343 /* Given index ADDR_INDEX in .debug_addr, fetch the value.
17344    ADDR_BASE is the DW_AT_GNU_addr_base attribute or zero.
17345    ADDR_SIZE is the size of addresses from the CU header.  */
17346
17347 static CORE_ADDR
17348 read_addr_index_1 (unsigned int addr_index, ULONGEST addr_base, int addr_size)
17349 {
17350   struct objfile *objfile = dwarf2_per_objfile->objfile;
17351   bfd *abfd = objfile->obfd;
17352   const gdb_byte *info_ptr;
17353
17354   dwarf2_read_section (objfile, &dwarf2_per_objfile->addr);
17355   if (dwarf2_per_objfile->addr.buffer == NULL)
17356     error (_("DW_FORM_addr_index used without .debug_addr section [in module %s]"),
17357            objfile_name (objfile));
17358   if (addr_base + addr_index * addr_size >= dwarf2_per_objfile->addr.size)
17359     error (_("DW_FORM_addr_index pointing outside of "
17360              ".debug_addr section [in module %s]"),
17361            objfile_name (objfile));
17362   info_ptr = (dwarf2_per_objfile->addr.buffer
17363               + addr_base + addr_index * addr_size);
17364   if (addr_size == 4)
17365     return bfd_get_32 (abfd, info_ptr);
17366   else
17367     return bfd_get_64 (abfd, info_ptr);
17368 }
17369
17370 /* Given index ADDR_INDEX in .debug_addr, fetch the value.  */
17371
17372 static CORE_ADDR
17373 read_addr_index (struct dwarf2_cu *cu, unsigned int addr_index)
17374 {
17375   return read_addr_index_1 (addr_index, cu->addr_base, cu->header.addr_size);
17376 }
17377
17378 /* Given a pointer to an leb128 value, fetch the value from .debug_addr.  */
17379
17380 static CORE_ADDR
17381 read_addr_index_from_leb128 (struct dwarf2_cu *cu, const gdb_byte *info_ptr,
17382                              unsigned int *bytes_read)
17383 {
17384   bfd *abfd = cu->objfile->obfd;
17385   unsigned int addr_index = read_unsigned_leb128 (abfd, info_ptr, bytes_read);
17386
17387   return read_addr_index (cu, addr_index);
17388 }
17389
17390 /* Data structure to pass results from dwarf2_read_addr_index_reader
17391    back to dwarf2_read_addr_index.  */
17392
17393 struct dwarf2_read_addr_index_data
17394 {
17395   ULONGEST addr_base;
17396   int addr_size;
17397 };
17398
17399 /* die_reader_func for dwarf2_read_addr_index.  */
17400
17401 static void
17402 dwarf2_read_addr_index_reader (const struct die_reader_specs *reader,
17403                                const gdb_byte *info_ptr,
17404                                struct die_info *comp_unit_die,
17405                                int has_children,
17406                                void *data)
17407 {
17408   struct dwarf2_cu *cu = reader->cu;
17409   struct dwarf2_read_addr_index_data *aidata =
17410     (struct dwarf2_read_addr_index_data *) data;
17411
17412   aidata->addr_base = cu->addr_base;
17413   aidata->addr_size = cu->header.addr_size;
17414 }
17415
17416 /* Given an index in .debug_addr, fetch the value.
17417    NOTE: This can be called during dwarf expression evaluation,
17418    long after the debug information has been read, and thus per_cu->cu
17419    may no longer exist.  */
17420
17421 CORE_ADDR
17422 dwarf2_read_addr_index (struct dwarf2_per_cu_data *per_cu,
17423                         unsigned int addr_index)
17424 {
17425   struct objfile *objfile = per_cu->objfile;
17426   struct dwarf2_cu *cu = per_cu->cu;
17427   ULONGEST addr_base;
17428   int addr_size;
17429
17430   /* This is intended to be called from outside this file.  */
17431   dw2_setup (objfile);
17432
17433   /* We need addr_base and addr_size.
17434      If we don't have PER_CU->cu, we have to get it.
17435      Nasty, but the alternative is storing the needed info in PER_CU,
17436      which at this point doesn't seem justified: it's not clear how frequently
17437      it would get used and it would increase the size of every PER_CU.
17438      Entry points like dwarf2_per_cu_addr_size do a similar thing
17439      so we're not in uncharted territory here.
17440      Alas we need to be a bit more complicated as addr_base is contained
17441      in the DIE.
17442
17443      We don't need to read the entire CU(/TU).
17444      We just need the header and top level die.
17445
17446      IWBN to use the aging mechanism to let us lazily later discard the CU.
17447      For now we skip this optimization.  */
17448
17449   if (cu != NULL)
17450     {
17451       addr_base = cu->addr_base;
17452       addr_size = cu->header.addr_size;
17453     }
17454   else
17455     {
17456       struct dwarf2_read_addr_index_data aidata;
17457
17458       /* Note: We can't use init_cutu_and_read_dies_simple here,
17459          we need addr_base.  */
17460       init_cutu_and_read_dies (per_cu, NULL, 0, 0,
17461                                dwarf2_read_addr_index_reader, &aidata);
17462       addr_base = aidata.addr_base;
17463       addr_size = aidata.addr_size;
17464     }
17465
17466   return read_addr_index_1 (addr_index, addr_base, addr_size);
17467 }
17468
17469 /* Given a DW_FORM_GNU_str_index, fetch the string.
17470    This is only used by the Fission support.  */
17471
17472 static const char *
17473 read_str_index (const struct die_reader_specs *reader, ULONGEST str_index)
17474 {
17475   struct objfile *objfile = dwarf2_per_objfile->objfile;
17476   const char *objf_name = objfile_name (objfile);
17477   bfd *abfd = objfile->obfd;
17478   struct dwarf2_cu *cu = reader->cu;
17479   struct dwarf2_section_info *str_section = &reader->dwo_file->sections.str;
17480   struct dwarf2_section_info *str_offsets_section =
17481     &reader->dwo_file->sections.str_offsets;
17482   const gdb_byte *info_ptr;
17483   ULONGEST str_offset;
17484   static const char form_name[] = "DW_FORM_GNU_str_index";
17485
17486   dwarf2_read_section (objfile, str_section);
17487   dwarf2_read_section (objfile, str_offsets_section);
17488   if (str_section->buffer == NULL)
17489     error (_("%s used without .debug_str.dwo section"
17490              " in CU at offset 0x%x [in module %s]"),
17491            form_name, to_underlying (cu->header.sect_off), objf_name);
17492   if (str_offsets_section->buffer == NULL)
17493     error (_("%s used without .debug_str_offsets.dwo section"
17494              " in CU at offset 0x%x [in module %s]"),
17495            form_name, to_underlying (cu->header.sect_off), objf_name);
17496   if (str_index * cu->header.offset_size >= str_offsets_section->size)
17497     error (_("%s pointing outside of .debug_str_offsets.dwo"
17498              " section in CU at offset 0x%x [in module %s]"),
17499            form_name, to_underlying (cu->header.sect_off), objf_name);
17500   info_ptr = (str_offsets_section->buffer
17501               + str_index * cu->header.offset_size);
17502   if (cu->header.offset_size == 4)
17503     str_offset = bfd_get_32 (abfd, info_ptr);
17504   else
17505     str_offset = bfd_get_64 (abfd, info_ptr);
17506   if (str_offset >= str_section->size)
17507     error (_("Offset from %s pointing outside of"
17508              " .debug_str.dwo section in CU at offset 0x%x [in module %s]"),
17509            form_name, to_underlying (cu->header.sect_off), objf_name);
17510   return (const char *) (str_section->buffer + str_offset);
17511 }
17512
17513 /* Return the length of an LEB128 number in BUF.  */
17514
17515 static int
17516 leb128_size (const gdb_byte *buf)
17517 {
17518   const gdb_byte *begin = buf;
17519   gdb_byte byte;
17520
17521   while (1)
17522     {
17523       byte = *buf++;
17524       if ((byte & 128) == 0)
17525         return buf - begin;
17526     }
17527 }
17528
17529 static void
17530 set_cu_language (unsigned int lang, struct dwarf2_cu *cu)
17531 {
17532   switch (lang)
17533     {
17534     case DW_LANG_C89:
17535     case DW_LANG_C99:
17536     case DW_LANG_C11:
17537     case DW_LANG_C:
17538     case DW_LANG_UPC:
17539       cu->language = language_c;
17540       break;
17541     case DW_LANG_Java:
17542     case DW_LANG_C_plus_plus:
17543     case DW_LANG_C_plus_plus_11:
17544     case DW_LANG_C_plus_plus_14:
17545       cu->language = language_cplus;
17546       break;
17547     case DW_LANG_D:
17548       cu->language = language_d;
17549       break;
17550     case DW_LANG_Fortran77:
17551     case DW_LANG_Fortran90:
17552     case DW_LANG_Fortran95:
17553     case DW_LANG_Fortran03:
17554     case DW_LANG_Fortran08:
17555       cu->language = language_fortran;
17556       break;
17557     case DW_LANG_Go:
17558       cu->language = language_go;
17559       break;
17560     case DW_LANG_Mips_Assembler:
17561       cu->language = language_asm;
17562       break;
17563     case DW_LANG_Ada83:
17564     case DW_LANG_Ada95:
17565       cu->language = language_ada;
17566       break;
17567     case DW_LANG_Modula2:
17568       cu->language = language_m2;
17569       break;
17570     case DW_LANG_Pascal83:
17571       cu->language = language_pascal;
17572       break;
17573     case DW_LANG_ObjC:
17574       cu->language = language_objc;
17575       break;
17576     case DW_LANG_Rust:
17577     case DW_LANG_Rust_old:
17578       cu->language = language_rust;
17579       break;
17580     case DW_LANG_Cobol74:
17581     case DW_LANG_Cobol85:
17582     default:
17583       cu->language = language_minimal;
17584       break;
17585     }
17586   cu->language_defn = language_def (cu->language);
17587 }
17588
17589 /* Return the named attribute or NULL if not there.  */
17590
17591 static struct attribute *
17592 dwarf2_attr (struct die_info *die, unsigned int name, struct dwarf2_cu *cu)
17593 {
17594   for (;;)
17595     {
17596       unsigned int i;
17597       struct attribute *spec = NULL;
17598
17599       for (i = 0; i < die->num_attrs; ++i)
17600         {
17601           if (die->attrs[i].name == name)
17602             return &die->attrs[i];
17603           if (die->attrs[i].name == DW_AT_specification
17604               || die->attrs[i].name == DW_AT_abstract_origin)
17605             spec = &die->attrs[i];
17606         }
17607
17608       if (!spec)
17609         break;
17610
17611       die = follow_die_ref (die, spec, &cu);
17612     }
17613
17614   return NULL;
17615 }
17616
17617 /* Return the named attribute or NULL if not there,
17618    but do not follow DW_AT_specification, etc.
17619    This is for use in contexts where we're reading .debug_types dies.
17620    Following DW_AT_specification, DW_AT_abstract_origin will take us
17621    back up the chain, and we want to go down.  */
17622
17623 static struct attribute *
17624 dwarf2_attr_no_follow (struct die_info *die, unsigned int name)
17625 {
17626   unsigned int i;
17627
17628   for (i = 0; i < die->num_attrs; ++i)
17629     if (die->attrs[i].name == name)
17630       return &die->attrs[i];
17631
17632   return NULL;
17633 }
17634
17635 /* Return the string associated with a string-typed attribute, or NULL if it
17636    is either not found or is of an incorrect type.  */
17637
17638 static const char *
17639 dwarf2_string_attr (struct die_info *die, unsigned int name, struct dwarf2_cu *cu)
17640 {
17641   struct attribute *attr;
17642   const char *str = NULL;
17643
17644   attr = dwarf2_attr (die, name, cu);
17645
17646   if (attr != NULL)
17647     {
17648       if (attr->form == DW_FORM_strp || attr->form == DW_FORM_line_strp
17649           || attr->form == DW_FORM_string
17650           || attr->form == DW_FORM_GNU_str_index
17651           || attr->form == DW_FORM_GNU_strp_alt)
17652         str = DW_STRING (attr);
17653       else
17654         complaint (&symfile_complaints,
17655                    _("string type expected for attribute %s for "
17656                      "DIE at 0x%x in module %s"),
17657                    dwarf_attr_name (name), to_underlying (die->sect_off),
17658                    objfile_name (cu->objfile));
17659     }
17660
17661   return str;
17662 }
17663
17664 /* Return non-zero iff the attribute NAME is defined for the given DIE,
17665    and holds a non-zero value.  This function should only be used for
17666    DW_FORM_flag or DW_FORM_flag_present attributes.  */
17667
17668 static int
17669 dwarf2_flag_true_p (struct die_info *die, unsigned name, struct dwarf2_cu *cu)
17670 {
17671   struct attribute *attr = dwarf2_attr (die, name, cu);
17672
17673   return (attr && DW_UNSND (attr));
17674 }
17675
17676 static int
17677 die_is_declaration (struct die_info *die, struct dwarf2_cu *cu)
17678 {
17679   /* A DIE is a declaration if it has a DW_AT_declaration attribute
17680      which value is non-zero.  However, we have to be careful with
17681      DIEs having a DW_AT_specification attribute, because dwarf2_attr()
17682      (via dwarf2_flag_true_p) follows this attribute.  So we may
17683      end up accidently finding a declaration attribute that belongs
17684      to a different DIE referenced by the specification attribute,
17685      even though the given DIE does not have a declaration attribute.  */
17686   return (dwarf2_flag_true_p (die, DW_AT_declaration, cu)
17687           && dwarf2_attr (die, DW_AT_specification, cu) == NULL);
17688 }
17689
17690 /* Return the die giving the specification for DIE, if there is
17691    one.  *SPEC_CU is the CU containing DIE on input, and the CU
17692    containing the return value on output.  If there is no
17693    specification, but there is an abstract origin, that is
17694    returned.  */
17695
17696 static struct die_info *
17697 die_specification (struct die_info *die, struct dwarf2_cu **spec_cu)
17698 {
17699   struct attribute *spec_attr = dwarf2_attr (die, DW_AT_specification,
17700                                              *spec_cu);
17701
17702   if (spec_attr == NULL)
17703     spec_attr = dwarf2_attr (die, DW_AT_abstract_origin, *spec_cu);
17704
17705   if (spec_attr == NULL)
17706     return NULL;
17707   else
17708     return follow_die_ref (die, spec_attr, spec_cu);
17709 }
17710
17711 /* Stub for free_line_header to match void * callback types.  */
17712
17713 static void
17714 free_line_header_voidp (void *arg)
17715 {
17716   struct line_header *lh = (struct line_header *) arg;
17717
17718   delete lh;
17719 }
17720
17721 void
17722 line_header::add_include_dir (const char *include_dir)
17723 {
17724   if (dwarf_line_debug >= 2)
17725     fprintf_unfiltered (gdb_stdlog, "Adding dir %zu: %s\n",
17726                         include_dirs.size () + 1, include_dir);
17727
17728   include_dirs.push_back (include_dir);
17729 }
17730
17731 void
17732 line_header::add_file_name (const char *name,
17733                             dir_index d_index,
17734                             unsigned int mod_time,
17735                             unsigned int length)
17736 {
17737   if (dwarf_line_debug >= 2)
17738     fprintf_unfiltered (gdb_stdlog, "Adding file %u: %s\n",
17739                         (unsigned) file_names.size () + 1, name);
17740
17741   file_names.emplace_back (name, d_index, mod_time, length);
17742 }
17743
17744 /* A convenience function to find the proper .debug_line section for a CU.  */
17745
17746 static struct dwarf2_section_info *
17747 get_debug_line_section (struct dwarf2_cu *cu)
17748 {
17749   struct dwarf2_section_info *section;
17750
17751   /* For TUs in DWO files, the DW_AT_stmt_list attribute lives in the
17752      DWO file.  */
17753   if (cu->dwo_unit && cu->per_cu->is_debug_types)
17754     section = &cu->dwo_unit->dwo_file->sections.line;
17755   else if (cu->per_cu->is_dwz)
17756     {
17757       struct dwz_file *dwz = dwarf2_get_dwz_file ();
17758
17759       section = &dwz->line;
17760     }
17761   else
17762     section = &dwarf2_per_objfile->line;
17763
17764   return section;
17765 }
17766
17767 /* Read directory or file name entry format, starting with byte of
17768    format count entries, ULEB128 pairs of entry formats, ULEB128 of
17769    entries count and the entries themselves in the described entry
17770    format.  */
17771
17772 static void
17773 read_formatted_entries (bfd *abfd, const gdb_byte **bufp,
17774                         struct line_header *lh,
17775                         const struct comp_unit_head *cu_header,
17776                         void (*callback) (struct line_header *lh,
17777                                           const char *name,
17778                                           dir_index d_index,
17779                                           unsigned int mod_time,
17780                                           unsigned int length))
17781 {
17782   gdb_byte format_count, formati;
17783   ULONGEST data_count, datai;
17784   const gdb_byte *buf = *bufp;
17785   const gdb_byte *format_header_data;
17786   int i;
17787   unsigned int bytes_read;
17788
17789   format_count = read_1_byte (abfd, buf);
17790   buf += 1;
17791   format_header_data = buf;
17792   for (formati = 0; formati < format_count; formati++)
17793     {
17794       read_unsigned_leb128 (abfd, buf, &bytes_read);
17795       buf += bytes_read;
17796       read_unsigned_leb128 (abfd, buf, &bytes_read);
17797       buf += bytes_read;
17798     }
17799
17800   data_count = read_unsigned_leb128 (abfd, buf, &bytes_read);
17801   buf += bytes_read;
17802   for (datai = 0; datai < data_count; datai++)
17803     {
17804       const gdb_byte *format = format_header_data;
17805       struct file_entry fe;
17806
17807       for (formati = 0; formati < format_count; formati++)
17808         {
17809           ULONGEST content_type = read_unsigned_leb128 (abfd, format, &bytes_read);
17810           format += bytes_read;
17811
17812           ULONGEST form  = read_unsigned_leb128 (abfd, format, &bytes_read);
17813           format += bytes_read;
17814
17815           gdb::optional<const char *> string;
17816           gdb::optional<unsigned int> uint;
17817
17818           switch (form)
17819             {
17820             case DW_FORM_string:
17821               string.emplace (read_direct_string (abfd, buf, &bytes_read));
17822               buf += bytes_read;
17823               break;
17824
17825             case DW_FORM_line_strp:
17826               string.emplace (read_indirect_line_string (abfd, buf,
17827                                                          cu_header,
17828                                                          &bytes_read));
17829               buf += bytes_read;
17830               break;
17831
17832             case DW_FORM_data1:
17833               uint.emplace (read_1_byte (abfd, buf));
17834               buf += 1;
17835               break;
17836
17837             case DW_FORM_data2:
17838               uint.emplace (read_2_bytes (abfd, buf));
17839               buf += 2;
17840               break;
17841
17842             case DW_FORM_data4:
17843               uint.emplace (read_4_bytes (abfd, buf));
17844               buf += 4;
17845               break;
17846
17847             case DW_FORM_data8:
17848               uint.emplace (read_8_bytes (abfd, buf));
17849               buf += 8;
17850               break;
17851
17852             case DW_FORM_udata:
17853               uint.emplace (read_unsigned_leb128 (abfd, buf, &bytes_read));
17854               buf += bytes_read;
17855               break;
17856
17857             case DW_FORM_block:
17858               /* It is valid only for DW_LNCT_timestamp which is ignored by
17859                  current GDB.  */
17860               break;
17861             }
17862
17863           switch (content_type)
17864             {
17865             case DW_LNCT_path:
17866               if (string.has_value ())
17867                 fe.name = *string;
17868               break;
17869             case DW_LNCT_directory_index:
17870               if (uint.has_value ())
17871                 fe.d_index = (dir_index) *uint;
17872               break;
17873             case DW_LNCT_timestamp:
17874               if (uint.has_value ())
17875                 fe.mod_time = *uint;
17876               break;
17877             case DW_LNCT_size:
17878               if (uint.has_value ())
17879                 fe.length = *uint;
17880               break;
17881             case DW_LNCT_MD5:
17882               break;
17883             default:
17884               complaint (&symfile_complaints,
17885                          _("Unknown format content type %s"),
17886                          pulongest (content_type));
17887             }
17888         }
17889
17890       callback (lh, fe.name, fe.d_index, fe.mod_time, fe.length);
17891     }
17892
17893   *bufp = buf;
17894 }
17895
17896 /* Read the statement program header starting at OFFSET in
17897    .debug_line, or .debug_line.dwo.  Return a pointer
17898    to a struct line_header, allocated using xmalloc.
17899    Returns NULL if there is a problem reading the header, e.g., if it
17900    has a version we don't understand.
17901
17902    NOTE: the strings in the include directory and file name tables of
17903    the returned object point into the dwarf line section buffer,
17904    and must not be freed.  */
17905
17906 static line_header_up
17907 dwarf_decode_line_header (sect_offset sect_off, struct dwarf2_cu *cu)
17908 {
17909   const gdb_byte *line_ptr;
17910   unsigned int bytes_read, offset_size;
17911   int i;
17912   const char *cur_dir, *cur_file;
17913   struct dwarf2_section_info *section;
17914   bfd *abfd;
17915
17916   section = get_debug_line_section (cu);
17917   dwarf2_read_section (dwarf2_per_objfile->objfile, section);
17918   if (section->buffer == NULL)
17919     {
17920       if (cu->dwo_unit && cu->per_cu->is_debug_types)
17921         complaint (&symfile_complaints, _("missing .debug_line.dwo section"));
17922       else
17923         complaint (&symfile_complaints, _("missing .debug_line section"));
17924       return 0;
17925     }
17926
17927   /* We can't do this until we know the section is non-empty.
17928      Only then do we know we have such a section.  */
17929   abfd = get_section_bfd_owner (section);
17930
17931   /* Make sure that at least there's room for the total_length field.
17932      That could be 12 bytes long, but we're just going to fudge that.  */
17933   if (to_underlying (sect_off) + 4 >= section->size)
17934     {
17935       dwarf2_statement_list_fits_in_line_number_section_complaint ();
17936       return 0;
17937     }
17938
17939   line_header_up lh (new line_header ());
17940
17941   lh->sect_off = sect_off;
17942   lh->offset_in_dwz = cu->per_cu->is_dwz;
17943
17944   line_ptr = section->buffer + to_underlying (sect_off);
17945
17946   /* Read in the header.  */
17947   lh->total_length =
17948     read_checked_initial_length_and_offset (abfd, line_ptr, &cu->header,
17949                                             &bytes_read, &offset_size);
17950   line_ptr += bytes_read;
17951   if (line_ptr + lh->total_length > (section->buffer + section->size))
17952     {
17953       dwarf2_statement_list_fits_in_line_number_section_complaint ();
17954       return 0;
17955     }
17956   lh->statement_program_end = line_ptr + lh->total_length;
17957   lh->version = read_2_bytes (abfd, line_ptr);
17958   line_ptr += 2;
17959   if (lh->version > 5)
17960     {
17961       /* This is a version we don't understand.  The format could have
17962          changed in ways we don't handle properly so just punt.  */
17963       complaint (&symfile_complaints,
17964                  _("unsupported version in .debug_line section"));
17965       return NULL;
17966     }
17967   if (lh->version >= 5)
17968     {
17969       gdb_byte segment_selector_size;
17970
17971       /* Skip address size.  */
17972       read_1_byte (abfd, line_ptr);
17973       line_ptr += 1;
17974
17975       segment_selector_size = read_1_byte (abfd, line_ptr);
17976       line_ptr += 1;
17977       if (segment_selector_size != 0)
17978         {
17979           complaint (&symfile_complaints,
17980                      _("unsupported segment selector size %u "
17981                        "in .debug_line section"),
17982                      segment_selector_size);
17983           return NULL;
17984         }
17985     }
17986   lh->header_length = read_offset_1 (abfd, line_ptr, offset_size);
17987   line_ptr += offset_size;
17988   lh->minimum_instruction_length = read_1_byte (abfd, line_ptr);
17989   line_ptr += 1;
17990   if (lh->version >= 4)
17991     {
17992       lh->maximum_ops_per_instruction = read_1_byte (abfd, line_ptr);
17993       line_ptr += 1;
17994     }
17995   else
17996     lh->maximum_ops_per_instruction = 1;
17997
17998   if (lh->maximum_ops_per_instruction == 0)
17999     {
18000       lh->maximum_ops_per_instruction = 1;
18001       complaint (&symfile_complaints,
18002                  _("invalid maximum_ops_per_instruction "
18003                    "in `.debug_line' section"));
18004     }
18005
18006   lh->default_is_stmt = read_1_byte (abfd, line_ptr);
18007   line_ptr += 1;
18008   lh->line_base = read_1_signed_byte (abfd, line_ptr);
18009   line_ptr += 1;
18010   lh->line_range = read_1_byte (abfd, line_ptr);
18011   line_ptr += 1;
18012   lh->opcode_base = read_1_byte (abfd, line_ptr);
18013   line_ptr += 1;
18014   lh->standard_opcode_lengths.reset (new unsigned char[lh->opcode_base]);
18015
18016   lh->standard_opcode_lengths[0] = 1;  /* This should never be used anyway.  */
18017   for (i = 1; i < lh->opcode_base; ++i)
18018     {
18019       lh->standard_opcode_lengths[i] = read_1_byte (abfd, line_ptr);
18020       line_ptr += 1;
18021     }
18022
18023   if (lh->version >= 5)
18024     {
18025       /* Read directory table.  */
18026       read_formatted_entries (abfd, &line_ptr, lh.get (), &cu->header,
18027                               [] (struct line_header *lh, const char *name,
18028                                   dir_index d_index, unsigned int mod_time,
18029                                   unsigned int length)
18030         {
18031           lh->add_include_dir (name);
18032         });
18033
18034       /* Read file name table.  */
18035       read_formatted_entries (abfd, &line_ptr, lh.get (), &cu->header,
18036                               [] (struct line_header *lh, const char *name,
18037                                   dir_index d_index, unsigned int mod_time,
18038                                   unsigned int length)
18039         {
18040           lh->add_file_name (name, d_index, mod_time, length);
18041         });
18042     }
18043   else
18044     {
18045       /* Read directory table.  */
18046       while ((cur_dir = read_direct_string (abfd, line_ptr, &bytes_read)) != NULL)
18047         {
18048           line_ptr += bytes_read;
18049           lh->add_include_dir (cur_dir);
18050         }
18051       line_ptr += bytes_read;
18052
18053       /* Read file name table.  */
18054       while ((cur_file = read_direct_string (abfd, line_ptr, &bytes_read)) != NULL)
18055         {
18056           unsigned int mod_time, length;
18057           dir_index d_index;
18058
18059           line_ptr += bytes_read;
18060           d_index = (dir_index) read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
18061           line_ptr += bytes_read;
18062           mod_time = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
18063           line_ptr += bytes_read;
18064           length = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
18065           line_ptr += bytes_read;
18066
18067           lh->add_file_name (cur_file, d_index, mod_time, length);
18068         }
18069       line_ptr += bytes_read;
18070     }
18071   lh->statement_program_start = line_ptr;
18072
18073   if (line_ptr > (section->buffer + section->size))
18074     complaint (&symfile_complaints,
18075                _("line number info header doesn't "
18076                  "fit in `.debug_line' section"));
18077
18078   return lh;
18079 }
18080
18081 /* Subroutine of dwarf_decode_lines to simplify it.
18082    Return the file name of the psymtab for included file FILE_INDEX
18083    in line header LH of PST.
18084    COMP_DIR is the compilation directory (DW_AT_comp_dir) or NULL if unknown.
18085    If space for the result is malloc'd, it will be freed by a cleanup.
18086    Returns NULL if FILE_INDEX should be ignored, i.e., it is pst->filename.
18087
18088    The function creates dangling cleanup registration.  */
18089
18090 static const char *
18091 psymtab_include_file_name (const struct line_header *lh, int file_index,
18092                            const struct partial_symtab *pst,
18093                            const char *comp_dir)
18094 {
18095   const file_entry &fe = lh->file_names[file_index];
18096   const char *include_name = fe.name;
18097   const char *include_name_to_compare = include_name;
18098   const char *pst_filename;
18099   char *copied_name = NULL;
18100   int file_is_pst;
18101
18102   const char *dir_name = fe.include_dir (lh);
18103
18104   if (!IS_ABSOLUTE_PATH (include_name)
18105       && (dir_name != NULL || comp_dir != NULL))
18106     {
18107       /* Avoid creating a duplicate psymtab for PST.
18108          We do this by comparing INCLUDE_NAME and PST_FILENAME.
18109          Before we do the comparison, however, we need to account
18110          for DIR_NAME and COMP_DIR.
18111          First prepend dir_name (if non-NULL).  If we still don't
18112          have an absolute path prepend comp_dir (if non-NULL).
18113          However, the directory we record in the include-file's
18114          psymtab does not contain COMP_DIR (to match the
18115          corresponding symtab(s)).
18116
18117          Example:
18118
18119          bash$ cd /tmp
18120          bash$ gcc -g ./hello.c
18121          include_name = "hello.c"
18122          dir_name = "."
18123          DW_AT_comp_dir = comp_dir = "/tmp"
18124          DW_AT_name = "./hello.c"
18125
18126       */
18127
18128       if (dir_name != NULL)
18129         {
18130           char *tem = concat (dir_name, SLASH_STRING,
18131                               include_name, (char *)NULL);
18132
18133           make_cleanup (xfree, tem);
18134           include_name = tem;
18135           include_name_to_compare = include_name;
18136         }
18137       if (!IS_ABSOLUTE_PATH (include_name) && comp_dir != NULL)
18138         {
18139           char *tem = concat (comp_dir, SLASH_STRING,
18140                               include_name, (char *)NULL);
18141
18142           make_cleanup (xfree, tem);
18143           include_name_to_compare = tem;
18144         }
18145     }
18146
18147   pst_filename = pst->filename;
18148   if (!IS_ABSOLUTE_PATH (pst_filename) && pst->dirname != NULL)
18149     {
18150       copied_name = concat (pst->dirname, SLASH_STRING,
18151                             pst_filename, (char *)NULL);
18152       pst_filename = copied_name;
18153     }
18154
18155   file_is_pst = FILENAME_CMP (include_name_to_compare, pst_filename) == 0;
18156
18157   if (copied_name != NULL)
18158     xfree (copied_name);
18159
18160   if (file_is_pst)
18161     return NULL;
18162   return include_name;
18163 }
18164
18165 /* State machine to track the state of the line number program.  */
18166
18167 class lnp_state_machine
18168 {
18169 public:
18170   /* Initialize a machine state for the start of a line number
18171      program.  */
18172   lnp_state_machine (gdbarch *arch, line_header *lh, bool record_lines_p);
18173
18174   file_entry *current_file ()
18175   {
18176     /* lh->file_names is 0-based, but the file name numbers in the
18177        statement program are 1-based.  */
18178     return m_line_header->file_name_at (m_file);
18179   }
18180
18181   /* Record the line in the state machine.  END_SEQUENCE is true if
18182      we're processing the end of a sequence.  */
18183   void record_line (bool end_sequence);
18184
18185   /* Check address and if invalid nop-out the rest of the lines in this
18186      sequence.  */
18187   void check_line_address (struct dwarf2_cu *cu,
18188                            const gdb_byte *line_ptr,
18189                            CORE_ADDR lowpc, CORE_ADDR address);
18190
18191   void handle_set_discriminator (unsigned int discriminator)
18192   {
18193     m_discriminator = discriminator;
18194     m_line_has_non_zero_discriminator |= discriminator != 0;
18195   }
18196
18197   /* Handle DW_LNE_set_address.  */
18198   void handle_set_address (CORE_ADDR baseaddr, CORE_ADDR address)
18199   {
18200     m_op_index = 0;
18201     address += baseaddr;
18202     m_address = gdbarch_adjust_dwarf2_line (m_gdbarch, address, false);
18203   }
18204
18205   /* Handle DW_LNS_advance_pc.  */
18206   void handle_advance_pc (CORE_ADDR adjust);
18207
18208   /* Handle a special opcode.  */
18209   void handle_special_opcode (unsigned char op_code);
18210
18211   /* Handle DW_LNS_advance_line.  */
18212   void handle_advance_line (int line_delta)
18213   {
18214     advance_line (line_delta);
18215   }
18216
18217   /* Handle DW_LNS_set_file.  */
18218   void handle_set_file (file_name_index file);
18219
18220   /* Handle DW_LNS_negate_stmt.  */
18221   void handle_negate_stmt ()
18222   {
18223     m_is_stmt = !m_is_stmt;
18224   }
18225
18226   /* Handle DW_LNS_const_add_pc.  */
18227   void handle_const_add_pc ();
18228
18229   /* Handle DW_LNS_fixed_advance_pc.  */
18230   void handle_fixed_advance_pc (CORE_ADDR addr_adj)
18231   {
18232     m_address += gdbarch_adjust_dwarf2_line (m_gdbarch, addr_adj, true);
18233     m_op_index = 0;
18234   }
18235
18236   /* Handle DW_LNS_copy.  */
18237   void handle_copy ()
18238   {
18239     record_line (false);
18240     m_discriminator = 0;
18241   }
18242
18243   /* Handle DW_LNE_end_sequence.  */
18244   void handle_end_sequence ()
18245   {
18246     m_record_line_callback = ::record_line;
18247   }
18248
18249 private:
18250   /* Advance the line by LINE_DELTA.  */
18251   void advance_line (int line_delta)
18252   {
18253     m_line += line_delta;
18254
18255     if (line_delta != 0)
18256       m_line_has_non_zero_discriminator = m_discriminator != 0;
18257   }
18258
18259   gdbarch *m_gdbarch;
18260
18261   /* True if we're recording lines.
18262      Otherwise we're building partial symtabs and are just interested in
18263      finding include files mentioned by the line number program.  */
18264   bool m_record_lines_p;
18265
18266   /* The line number header.  */
18267   line_header *m_line_header;
18268
18269   /* These are part of the standard DWARF line number state machine,
18270      and initialized according to the DWARF spec.  */
18271
18272   unsigned char m_op_index = 0;
18273   /* The line table index (1-based) of the current file.  */
18274   file_name_index m_file = (file_name_index) 1;
18275   unsigned int m_line = 1;
18276
18277   /* These are initialized in the constructor.  */
18278
18279   CORE_ADDR m_address;
18280   bool m_is_stmt;
18281   unsigned int m_discriminator;
18282
18283   /* Additional bits of state we need to track.  */
18284
18285   /* The last file that we called dwarf2_start_subfile for.
18286      This is only used for TLLs.  */
18287   unsigned int m_last_file = 0;
18288   /* The last file a line number was recorded for.  */
18289   struct subfile *m_last_subfile = NULL;
18290
18291   /* The function to call to record a line.  */
18292   record_line_ftype *m_record_line_callback = NULL;
18293
18294   /* The last line number that was recorded, used to coalesce
18295      consecutive entries for the same line.  This can happen, for
18296      example, when discriminators are present.  PR 17276.  */
18297   unsigned int m_last_line = 0;
18298   bool m_line_has_non_zero_discriminator = false;
18299 };
18300
18301 void
18302 lnp_state_machine::handle_advance_pc (CORE_ADDR adjust)
18303 {
18304   CORE_ADDR addr_adj = (((m_op_index + adjust)
18305                          / m_line_header->maximum_ops_per_instruction)
18306                         * m_line_header->minimum_instruction_length);
18307   m_address += gdbarch_adjust_dwarf2_line (m_gdbarch, addr_adj, true);
18308   m_op_index = ((m_op_index + adjust)
18309                 % m_line_header->maximum_ops_per_instruction);
18310 }
18311
18312 void
18313 lnp_state_machine::handle_special_opcode (unsigned char op_code)
18314 {
18315   unsigned char adj_opcode = op_code - m_line_header->opcode_base;
18316   CORE_ADDR addr_adj = (((m_op_index
18317                           + (adj_opcode / m_line_header->line_range))
18318                          / m_line_header->maximum_ops_per_instruction)
18319                         * m_line_header->minimum_instruction_length);
18320   m_address += gdbarch_adjust_dwarf2_line (m_gdbarch, addr_adj, true);
18321   m_op_index = ((m_op_index + (adj_opcode / m_line_header->line_range))
18322                 % m_line_header->maximum_ops_per_instruction);
18323
18324   int line_delta = (m_line_header->line_base
18325                     + (adj_opcode % m_line_header->line_range));
18326   advance_line (line_delta);
18327   record_line (false);
18328   m_discriminator = 0;
18329 }
18330
18331 void
18332 lnp_state_machine::handle_set_file (file_name_index file)
18333 {
18334   m_file = file;
18335
18336   const file_entry *fe = current_file ();
18337   if (fe == NULL)
18338     dwarf2_debug_line_missing_file_complaint ();
18339   else if (m_record_lines_p)
18340     {
18341       const char *dir = fe->include_dir (m_line_header);
18342
18343       m_last_subfile = current_subfile;
18344       m_line_has_non_zero_discriminator = m_discriminator != 0;
18345       dwarf2_start_subfile (fe->name, dir);
18346     }
18347 }
18348
18349 void
18350 lnp_state_machine::handle_const_add_pc ()
18351 {
18352   CORE_ADDR adjust
18353     = (255 - m_line_header->opcode_base) / m_line_header->line_range;
18354
18355   CORE_ADDR addr_adj
18356     = (((m_op_index + adjust)
18357         / m_line_header->maximum_ops_per_instruction)
18358        * m_line_header->minimum_instruction_length);
18359
18360   m_address += gdbarch_adjust_dwarf2_line (m_gdbarch, addr_adj, true);
18361   m_op_index = ((m_op_index + adjust)
18362                 % m_line_header->maximum_ops_per_instruction);
18363 }
18364
18365 /* Ignore this record_line request.  */
18366
18367 static void
18368 noop_record_line (struct subfile *subfile, int line, CORE_ADDR pc)
18369 {
18370   return;
18371 }
18372
18373 /* Return non-zero if we should add LINE to the line number table.
18374    LINE is the line to add, LAST_LINE is the last line that was added,
18375    LAST_SUBFILE is the subfile for LAST_LINE.
18376    LINE_HAS_NON_ZERO_DISCRIMINATOR is non-zero if LINE has ever
18377    had a non-zero discriminator.
18378
18379    We have to be careful in the presence of discriminators.
18380    E.g., for this line:
18381
18382      for (i = 0; i < 100000; i++);
18383
18384    clang can emit four line number entries for that one line,
18385    each with a different discriminator.
18386    See gdb.dwarf2/dw2-single-line-discriminators.exp for an example.
18387
18388    However, we want gdb to coalesce all four entries into one.
18389    Otherwise the user could stepi into the middle of the line and
18390    gdb would get confused about whether the pc really was in the
18391    middle of the line.
18392
18393    Things are further complicated by the fact that two consecutive
18394    line number entries for the same line is a heuristic used by gcc
18395    to denote the end of the prologue.  So we can't just discard duplicate
18396    entries, we have to be selective about it.  The heuristic we use is
18397    that we only collapse consecutive entries for the same line if at least
18398    one of those entries has a non-zero discriminator.  PR 17276.
18399
18400    Note: Addresses in the line number state machine can never go backwards
18401    within one sequence, thus this coalescing is ok.  */
18402
18403 static int
18404 dwarf_record_line_p (unsigned int line, unsigned int last_line,
18405                      int line_has_non_zero_discriminator,
18406                      struct subfile *last_subfile)
18407 {
18408   if (current_subfile != last_subfile)
18409     return 1;
18410   if (line != last_line)
18411     return 1;
18412   /* Same line for the same file that we've seen already.
18413      As a last check, for pr 17276, only record the line if the line
18414      has never had a non-zero discriminator.  */
18415   if (!line_has_non_zero_discriminator)
18416     return 1;
18417   return 0;
18418 }
18419
18420 /* Use P_RECORD_LINE to record line number LINE beginning at address ADDRESS
18421    in the line table of subfile SUBFILE.  */
18422
18423 static void
18424 dwarf_record_line_1 (struct gdbarch *gdbarch, struct subfile *subfile,
18425                      unsigned int line, CORE_ADDR address,
18426                      record_line_ftype p_record_line)
18427 {
18428   CORE_ADDR addr = gdbarch_addr_bits_remove (gdbarch, address);
18429
18430   if (dwarf_line_debug)
18431     {
18432       fprintf_unfiltered (gdb_stdlog,
18433                           "Recording line %u, file %s, address %s\n",
18434                           line, lbasename (subfile->name),
18435                           paddress (gdbarch, address));
18436     }
18437
18438   (*p_record_line) (subfile, line, addr);
18439 }
18440
18441 /* Subroutine of dwarf_decode_lines_1 to simplify it.
18442    Mark the end of a set of line number records.
18443    The arguments are the same as for dwarf_record_line_1.
18444    If SUBFILE is NULL the request is ignored.  */
18445
18446 static void
18447 dwarf_finish_line (struct gdbarch *gdbarch, struct subfile *subfile,
18448                    CORE_ADDR address, record_line_ftype p_record_line)
18449 {
18450   if (subfile == NULL)
18451     return;
18452
18453   if (dwarf_line_debug)
18454     {
18455       fprintf_unfiltered (gdb_stdlog,
18456                           "Finishing current line, file %s, address %s\n",
18457                           lbasename (subfile->name),
18458                           paddress (gdbarch, address));
18459     }
18460
18461   dwarf_record_line_1 (gdbarch, subfile, 0, address, p_record_line);
18462 }
18463
18464 void
18465 lnp_state_machine::record_line (bool end_sequence)
18466 {
18467   if (dwarf_line_debug)
18468     {
18469       fprintf_unfiltered (gdb_stdlog,
18470                           "Processing actual line %u: file %u,"
18471                           " address %s, is_stmt %u, discrim %u\n",
18472                           m_line, to_underlying (m_file),
18473                           paddress (m_gdbarch, m_address),
18474                           m_is_stmt, m_discriminator);
18475     }
18476
18477   file_entry *fe = current_file ();
18478
18479   if (fe == NULL)
18480     dwarf2_debug_line_missing_file_complaint ();
18481   /* For now we ignore lines not starting on an instruction boundary.
18482      But not when processing end_sequence for compatibility with the
18483      previous version of the code.  */
18484   else if (m_op_index == 0 || end_sequence)
18485     {
18486       fe->included_p = 1;
18487       if (m_record_lines_p && m_is_stmt)
18488         {
18489           if (m_last_subfile != current_subfile || end_sequence)
18490             {
18491               dwarf_finish_line (m_gdbarch, m_last_subfile,
18492                                  m_address, m_record_line_callback);
18493             }
18494
18495           if (!end_sequence)
18496             {
18497               if (dwarf_record_line_p (m_line, m_last_line,
18498                                        m_line_has_non_zero_discriminator,
18499                                        m_last_subfile))
18500                 {
18501                   dwarf_record_line_1 (m_gdbarch, current_subfile,
18502                                        m_line, m_address,
18503                                        m_record_line_callback);
18504                 }
18505               m_last_subfile = current_subfile;
18506               m_last_line = m_line;
18507             }
18508         }
18509     }
18510 }
18511
18512 lnp_state_machine::lnp_state_machine (gdbarch *arch, line_header *lh,
18513                                       bool record_lines_p)
18514 {
18515   m_gdbarch = arch;
18516   m_record_lines_p = record_lines_p;
18517   m_line_header = lh;
18518
18519   m_record_line_callback = ::record_line;
18520
18521   /* Call `gdbarch_adjust_dwarf2_line' on the initial 0 address as if there
18522      was a line entry for it so that the backend has a chance to adjust it
18523      and also record it in case it needs it.  This is currently used by MIPS
18524      code, cf. `mips_adjust_dwarf2_line'.  */
18525   m_address = gdbarch_adjust_dwarf2_line (arch, 0, 0);
18526   m_is_stmt = lh->default_is_stmt;
18527   m_discriminator = 0;
18528 }
18529
18530 void
18531 lnp_state_machine::check_line_address (struct dwarf2_cu *cu,
18532                                        const gdb_byte *line_ptr,
18533                                        CORE_ADDR lowpc, CORE_ADDR address)
18534 {
18535   /* If address < lowpc then it's not a usable value, it's outside the
18536      pc range of the CU.  However, we restrict the test to only address
18537      values of zero to preserve GDB's previous behaviour which is to
18538      handle the specific case of a function being GC'd by the linker.  */
18539
18540   if (address == 0 && address < lowpc)
18541     {
18542       /* This line table is for a function which has been
18543          GCd by the linker.  Ignore it.  PR gdb/12528 */
18544
18545       struct objfile *objfile = cu->objfile;
18546       long line_offset = line_ptr - get_debug_line_section (cu)->buffer;
18547
18548       complaint (&symfile_complaints,
18549                  _(".debug_line address at offset 0x%lx is 0 [in module %s]"),
18550                  line_offset, objfile_name (objfile));
18551       m_record_line_callback = noop_record_line;
18552       /* Note: record_line_callback is left as noop_record_line until
18553          we see DW_LNE_end_sequence.  */
18554     }
18555 }
18556
18557 /* Subroutine of dwarf_decode_lines to simplify it.
18558    Process the line number information in LH.
18559    If DECODE_FOR_PST_P is non-zero, all we do is process the line number
18560    program in order to set included_p for every referenced header.  */
18561
18562 static void
18563 dwarf_decode_lines_1 (struct line_header *lh, struct dwarf2_cu *cu,
18564                       const int decode_for_pst_p, CORE_ADDR lowpc)
18565 {
18566   const gdb_byte *line_ptr, *extended_end;
18567   const gdb_byte *line_end;
18568   unsigned int bytes_read, extended_len;
18569   unsigned char op_code, extended_op;
18570   CORE_ADDR baseaddr;
18571   struct objfile *objfile = cu->objfile;
18572   bfd *abfd = objfile->obfd;
18573   struct gdbarch *gdbarch = get_objfile_arch (objfile);
18574   /* True if we're recording line info (as opposed to building partial
18575      symtabs and just interested in finding include files mentioned by
18576      the line number program).  */
18577   bool record_lines_p = !decode_for_pst_p;
18578
18579   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
18580
18581   line_ptr = lh->statement_program_start;
18582   line_end = lh->statement_program_end;
18583
18584   /* Read the statement sequences until there's nothing left.  */
18585   while (line_ptr < line_end)
18586     {
18587       /* The DWARF line number program state machine.  Reset the state
18588          machine at the start of each sequence.  */
18589       lnp_state_machine state_machine (gdbarch, lh, record_lines_p);
18590       bool end_sequence = false;
18591
18592       if (record_lines_p)
18593         {
18594           /* Start a subfile for the current file of the state
18595              machine.  */
18596           const file_entry *fe = state_machine.current_file ();
18597
18598           if (fe != NULL)
18599             dwarf2_start_subfile (fe->name, fe->include_dir (lh));
18600         }
18601
18602       /* Decode the table.  */
18603       while (line_ptr < line_end && !end_sequence)
18604         {
18605           op_code = read_1_byte (abfd, line_ptr);
18606           line_ptr += 1;
18607
18608           if (op_code >= lh->opcode_base)
18609             {
18610               /* Special opcode.  */
18611               state_machine.handle_special_opcode (op_code);
18612             }
18613           else switch (op_code)
18614             {
18615             case DW_LNS_extended_op:
18616               extended_len = read_unsigned_leb128 (abfd, line_ptr,
18617                                                    &bytes_read);
18618               line_ptr += bytes_read;
18619               extended_end = line_ptr + extended_len;
18620               extended_op = read_1_byte (abfd, line_ptr);
18621               line_ptr += 1;
18622               switch (extended_op)
18623                 {
18624                 case DW_LNE_end_sequence:
18625                   state_machine.handle_end_sequence ();
18626                   end_sequence = true;
18627                   break;
18628                 case DW_LNE_set_address:
18629                   {
18630                     CORE_ADDR address
18631                       = read_address (abfd, line_ptr, cu, &bytes_read);
18632                     line_ptr += bytes_read;
18633
18634                     state_machine.check_line_address (cu, line_ptr,
18635                                                       lowpc, address);
18636                     state_machine.handle_set_address (baseaddr, address);
18637                   }
18638                   break;
18639                 case DW_LNE_define_file:
18640                   {
18641                     const char *cur_file;
18642                     unsigned int mod_time, length;
18643                     dir_index dindex;
18644
18645                     cur_file = read_direct_string (abfd, line_ptr,
18646                                                    &bytes_read);
18647                     line_ptr += bytes_read;
18648                     dindex = (dir_index)
18649                       read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
18650                     line_ptr += bytes_read;
18651                     mod_time =
18652                       read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
18653                     line_ptr += bytes_read;
18654                     length =
18655                       read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
18656                     line_ptr += bytes_read;
18657                     lh->add_file_name (cur_file, dindex, mod_time, length);
18658                   }
18659                   break;
18660                 case DW_LNE_set_discriminator:
18661                   {
18662                     /* The discriminator is not interesting to the
18663                        debugger; just ignore it.  We still need to
18664                        check its value though:
18665                        if there are consecutive entries for the same
18666                        (non-prologue) line we want to coalesce them.
18667                        PR 17276.  */
18668                     unsigned int discr
18669                       = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
18670                     line_ptr += bytes_read;
18671
18672                     state_machine.handle_set_discriminator (discr);
18673                   }
18674                   break;
18675                 default:
18676                   complaint (&symfile_complaints,
18677                              _("mangled .debug_line section"));
18678                   return;
18679                 }
18680               /* Make sure that we parsed the extended op correctly.  If e.g.
18681                  we expected a different address size than the producer used,
18682                  we may have read the wrong number of bytes.  */
18683               if (line_ptr != extended_end)
18684                 {
18685                   complaint (&symfile_complaints,
18686                              _("mangled .debug_line section"));
18687                   return;
18688                 }
18689               break;
18690             case DW_LNS_copy:
18691               state_machine.handle_copy ();
18692               break;
18693             case DW_LNS_advance_pc:
18694               {
18695                 CORE_ADDR adjust
18696                   = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
18697                 line_ptr += bytes_read;
18698
18699                 state_machine.handle_advance_pc (adjust);
18700               }
18701               break;
18702             case DW_LNS_advance_line:
18703               {
18704                 int line_delta
18705                   = read_signed_leb128 (abfd, line_ptr, &bytes_read);
18706                 line_ptr += bytes_read;
18707
18708                 state_machine.handle_advance_line (line_delta);
18709               }
18710               break;
18711             case DW_LNS_set_file:
18712               {
18713                 file_name_index file
18714                   = (file_name_index) read_unsigned_leb128 (abfd, line_ptr,
18715                                                             &bytes_read);
18716                 line_ptr += bytes_read;
18717
18718                 state_machine.handle_set_file (file);
18719               }
18720               break;
18721             case DW_LNS_set_column:
18722               (void) read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
18723               line_ptr += bytes_read;
18724               break;
18725             case DW_LNS_negate_stmt:
18726               state_machine.handle_negate_stmt ();
18727               break;
18728             case DW_LNS_set_basic_block:
18729               break;
18730             /* Add to the address register of the state machine the
18731                address increment value corresponding to special opcode
18732                255.  I.e., this value is scaled by the minimum
18733                instruction length since special opcode 255 would have
18734                scaled the increment.  */
18735             case DW_LNS_const_add_pc:
18736               state_machine.handle_const_add_pc ();
18737               break;
18738             case DW_LNS_fixed_advance_pc:
18739               {
18740                 CORE_ADDR addr_adj = read_2_bytes (abfd, line_ptr);
18741                 line_ptr += 2;
18742
18743                 state_machine.handle_fixed_advance_pc (addr_adj);
18744               }
18745               break;
18746             default:
18747               {
18748                 /* Unknown standard opcode, ignore it.  */
18749                 int i;
18750
18751                 for (i = 0; i < lh->standard_opcode_lengths[op_code]; i++)
18752                   {
18753                     (void) read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
18754                     line_ptr += bytes_read;
18755                   }
18756               }
18757             }
18758         }
18759
18760       if (!end_sequence)
18761         dwarf2_debug_line_missing_end_sequence_complaint ();
18762
18763       /* We got a DW_LNE_end_sequence (or we ran off the end of the buffer,
18764          in which case we still finish recording the last line).  */
18765       state_machine.record_line (true);
18766     }
18767 }
18768
18769 /* Decode the Line Number Program (LNP) for the given line_header
18770    structure and CU.  The actual information extracted and the type
18771    of structures created from the LNP depends on the value of PST.
18772
18773    1. If PST is NULL, then this procedure uses the data from the program
18774       to create all necessary symbol tables, and their linetables.
18775
18776    2. If PST is not NULL, this procedure reads the program to determine
18777       the list of files included by the unit represented by PST, and
18778       builds all the associated partial symbol tables.
18779
18780    COMP_DIR is the compilation directory (DW_AT_comp_dir) or NULL if unknown.
18781    It is used for relative paths in the line table.
18782    NOTE: When processing partial symtabs (pst != NULL),
18783    comp_dir == pst->dirname.
18784
18785    NOTE: It is important that psymtabs have the same file name (via strcmp)
18786    as the corresponding symtab.  Since COMP_DIR is not used in the name of the
18787    symtab we don't use it in the name of the psymtabs we create.
18788    E.g. expand_line_sal requires this when finding psymtabs to expand.
18789    A good testcase for this is mb-inline.exp.
18790
18791    LOWPC is the lowest address in CU (or 0 if not known).
18792
18793    Boolean DECODE_MAPPING specifies we need to fully decode .debug_line
18794    for its PC<->lines mapping information.  Otherwise only the filename
18795    table is read in.  */
18796
18797 static void
18798 dwarf_decode_lines (struct line_header *lh, const char *comp_dir,
18799                     struct dwarf2_cu *cu, struct partial_symtab *pst,
18800                     CORE_ADDR lowpc, int decode_mapping)
18801 {
18802   struct objfile *objfile = cu->objfile;
18803   const int decode_for_pst_p = (pst != NULL);
18804
18805   if (decode_mapping)
18806     dwarf_decode_lines_1 (lh, cu, decode_for_pst_p, lowpc);
18807
18808   if (decode_for_pst_p)
18809     {
18810       int file_index;
18811
18812       /* Now that we're done scanning the Line Header Program, we can
18813          create the psymtab of each included file.  */
18814       for (file_index = 0; file_index < lh->file_names.size (); file_index++)
18815         if (lh->file_names[file_index].included_p == 1)
18816           {
18817             const char *include_name =
18818               psymtab_include_file_name (lh, file_index, pst, comp_dir);
18819             if (include_name != NULL)
18820               dwarf2_create_include_psymtab (include_name, pst, objfile);
18821           }
18822     }
18823   else
18824     {
18825       /* Make sure a symtab is created for every file, even files
18826          which contain only variables (i.e. no code with associated
18827          line numbers).  */
18828       struct compunit_symtab *cust = buildsym_compunit_symtab ();
18829       int i;
18830
18831       for (i = 0; i < lh->file_names.size (); i++)
18832         {
18833           file_entry &fe = lh->file_names[i];
18834
18835           dwarf2_start_subfile (fe.name, fe.include_dir (lh));
18836
18837           if (current_subfile->symtab == NULL)
18838             {
18839               current_subfile->symtab
18840                 = allocate_symtab (cust, current_subfile->name);
18841             }
18842           fe.symtab = current_subfile->symtab;
18843         }
18844     }
18845 }
18846
18847 /* Start a subfile for DWARF.  FILENAME is the name of the file and
18848    DIRNAME the name of the source directory which contains FILENAME
18849    or NULL if not known.
18850    This routine tries to keep line numbers from identical absolute and
18851    relative file names in a common subfile.
18852
18853    Using the `list' example from the GDB testsuite, which resides in
18854    /srcdir and compiling it with Irix6.2 cc in /compdir using a filename
18855    of /srcdir/list0.c yields the following debugging information for list0.c:
18856
18857    DW_AT_name:          /srcdir/list0.c
18858    DW_AT_comp_dir:      /compdir
18859    files.files[0].name: list0.h
18860    files.files[0].dir:  /srcdir
18861    files.files[1].name: list0.c
18862    files.files[1].dir:  /srcdir
18863
18864    The line number information for list0.c has to end up in a single
18865    subfile, so that `break /srcdir/list0.c:1' works as expected.
18866    start_subfile will ensure that this happens provided that we pass the
18867    concatenation of files.files[1].dir and files.files[1].name as the
18868    subfile's name.  */
18869
18870 static void
18871 dwarf2_start_subfile (const char *filename, const char *dirname)
18872 {
18873   char *copy = NULL;
18874
18875   /* In order not to lose the line information directory,
18876      we concatenate it to the filename when it makes sense.
18877      Note that the Dwarf3 standard says (speaking of filenames in line
18878      information): ``The directory index is ignored for file names
18879      that represent full path names''.  Thus ignoring dirname in the
18880      `else' branch below isn't an issue.  */
18881
18882   if (!IS_ABSOLUTE_PATH (filename) && dirname != NULL)
18883     {
18884       copy = concat (dirname, SLASH_STRING, filename, (char *)NULL);
18885       filename = copy;
18886     }
18887
18888   start_subfile (filename);
18889
18890   if (copy != NULL)
18891     xfree (copy);
18892 }
18893
18894 /* Start a symtab for DWARF.
18895    NAME, COMP_DIR, LOW_PC are passed to start_symtab.  */
18896
18897 static struct compunit_symtab *
18898 dwarf2_start_symtab (struct dwarf2_cu *cu,
18899                      const char *name, const char *comp_dir, CORE_ADDR low_pc)
18900 {
18901   struct compunit_symtab *cust
18902     = start_symtab (cu->objfile, name, comp_dir, low_pc);
18903
18904   record_debugformat ("DWARF 2");
18905   record_producer (cu->producer);
18906
18907   /* We assume that we're processing GCC output.  */
18908   processing_gcc_compilation = 2;
18909
18910   cu->processing_has_namespace_info = 0;
18911
18912   return cust;
18913 }
18914
18915 static void
18916 var_decode_location (struct attribute *attr, struct symbol *sym,
18917                      struct dwarf2_cu *cu)
18918 {
18919   struct objfile *objfile = cu->objfile;
18920   struct comp_unit_head *cu_header = &cu->header;
18921
18922   /* NOTE drow/2003-01-30: There used to be a comment and some special
18923      code here to turn a symbol with DW_AT_external and a
18924      SYMBOL_VALUE_ADDRESS of 0 into a LOC_UNRESOLVED symbol.  This was
18925      necessary for platforms (maybe Alpha, certainly PowerPC GNU/Linux
18926      with some versions of binutils) where shared libraries could have
18927      relocations against symbols in their debug information - the
18928      minimal symbol would have the right address, but the debug info
18929      would not.  It's no longer necessary, because we will explicitly
18930      apply relocations when we read in the debug information now.  */
18931
18932   /* A DW_AT_location attribute with no contents indicates that a
18933      variable has been optimized away.  */
18934   if (attr_form_is_block (attr) && DW_BLOCK (attr)->size == 0)
18935     {
18936       SYMBOL_ACLASS_INDEX (sym) = LOC_OPTIMIZED_OUT;
18937       return;
18938     }
18939
18940   /* Handle one degenerate form of location expression specially, to
18941      preserve GDB's previous behavior when section offsets are
18942      specified.  If this is just a DW_OP_addr or DW_OP_GNU_addr_index
18943      then mark this symbol as LOC_STATIC.  */
18944
18945   if (attr_form_is_block (attr)
18946       && ((DW_BLOCK (attr)->data[0] == DW_OP_addr
18947            && DW_BLOCK (attr)->size == 1 + cu_header->addr_size)
18948           || (DW_BLOCK (attr)->data[0] == DW_OP_GNU_addr_index
18949               && (DW_BLOCK (attr)->size
18950                   == 1 + leb128_size (&DW_BLOCK (attr)->data[1])))))
18951     {
18952       unsigned int dummy;
18953
18954       if (DW_BLOCK (attr)->data[0] == DW_OP_addr)
18955         SYMBOL_VALUE_ADDRESS (sym) =
18956           read_address (objfile->obfd, DW_BLOCK (attr)->data + 1, cu, &dummy);
18957       else
18958         SYMBOL_VALUE_ADDRESS (sym) =
18959           read_addr_index_from_leb128 (cu, DW_BLOCK (attr)->data + 1, &dummy);
18960       SYMBOL_ACLASS_INDEX (sym) = LOC_STATIC;
18961       fixup_symbol_section (sym, objfile);
18962       SYMBOL_VALUE_ADDRESS (sym) += ANOFFSET (objfile->section_offsets,
18963                                               SYMBOL_SECTION (sym));
18964       return;
18965     }
18966
18967   /* NOTE drow/2002-01-30: It might be worthwhile to have a static
18968      expression evaluator, and use LOC_COMPUTED only when necessary
18969      (i.e. when the value of a register or memory location is
18970      referenced, or a thread-local block, etc.).  Then again, it might
18971      not be worthwhile.  I'm assuming that it isn't unless performance
18972      or memory numbers show me otherwise.  */
18973
18974   dwarf2_symbol_mark_computed (attr, sym, cu, 0);
18975
18976   if (SYMBOL_COMPUTED_OPS (sym)->location_has_loclist)
18977     cu->has_loclist = 1;
18978 }
18979
18980 /* Given a pointer to a DWARF information entry, figure out if we need
18981    to make a symbol table entry for it, and if so, create a new entry
18982    and return a pointer to it.
18983    If TYPE is NULL, determine symbol type from the die, otherwise
18984    used the passed type.
18985    If SPACE is not NULL, use it to hold the new symbol.  If it is
18986    NULL, allocate a new symbol on the objfile's obstack.  */
18987
18988 static struct symbol *
18989 new_symbol_full (struct die_info *die, struct type *type, struct dwarf2_cu *cu,
18990                  struct symbol *space)
18991 {
18992   struct objfile *objfile = cu->objfile;
18993   struct gdbarch *gdbarch = get_objfile_arch (objfile);
18994   struct symbol *sym = NULL;
18995   const char *name;
18996   struct attribute *attr = NULL;
18997   struct attribute *attr2 = NULL;
18998   CORE_ADDR baseaddr;
18999   struct pending **list_to_add = NULL;
19000
19001   int inlined_func = (die->tag == DW_TAG_inlined_subroutine);
19002
19003   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
19004
19005   name = dwarf2_name (die, cu);
19006   if (name)
19007     {
19008       const char *linkagename;
19009       int suppress_add = 0;
19010
19011       if (space)
19012         sym = space;
19013       else
19014         sym = allocate_symbol (objfile);
19015       OBJSTAT (objfile, n_syms++);
19016
19017       /* Cache this symbol's name and the name's demangled form (if any).  */
19018       SYMBOL_SET_LANGUAGE (sym, cu->language, &objfile->objfile_obstack);
19019       linkagename = dwarf2_physname (name, die, cu);
19020       SYMBOL_SET_NAMES (sym, linkagename, strlen (linkagename), 0, objfile);
19021
19022       /* Fortran does not have mangling standard and the mangling does differ
19023          between gfortran, iFort etc.  */
19024       if (cu->language == language_fortran
19025           && symbol_get_demangled_name (&(sym->ginfo)) == NULL)
19026         symbol_set_demangled_name (&(sym->ginfo),
19027                                    dwarf2_full_name (name, die, cu),
19028                                    NULL);
19029
19030       /* Default assumptions.
19031          Use the passed type or decode it from the die.  */
19032       SYMBOL_DOMAIN (sym) = VAR_DOMAIN;
19033       SYMBOL_ACLASS_INDEX (sym) = LOC_OPTIMIZED_OUT;
19034       if (type != NULL)
19035         SYMBOL_TYPE (sym) = type;
19036       else
19037         SYMBOL_TYPE (sym) = die_type (die, cu);
19038       attr = dwarf2_attr (die,
19039                           inlined_func ? DW_AT_call_line : DW_AT_decl_line,
19040                           cu);
19041       if (attr)
19042         {
19043           SYMBOL_LINE (sym) = DW_UNSND (attr);
19044         }
19045
19046       attr = dwarf2_attr (die,
19047                           inlined_func ? DW_AT_call_file : DW_AT_decl_file,
19048                           cu);
19049       if (attr)
19050         {
19051           file_name_index file_index = (file_name_index) DW_UNSND (attr);
19052           struct file_entry *fe;
19053
19054           if (cu->line_header != NULL)
19055             fe = cu->line_header->file_name_at (file_index);
19056           else
19057             fe = NULL;
19058
19059           if (fe == NULL)
19060             complaint (&symfile_complaints,
19061                        _("file index out of range"));
19062           else
19063             symbol_set_symtab (sym, fe->symtab);
19064         }
19065
19066       switch (die->tag)
19067         {
19068         case DW_TAG_label:
19069           attr = dwarf2_attr (die, DW_AT_low_pc, cu);
19070           if (attr)
19071             {
19072               CORE_ADDR addr;
19073
19074               addr = attr_value_as_address (attr);
19075               addr = gdbarch_adjust_dwarf2_addr (gdbarch, addr + baseaddr);
19076               SYMBOL_VALUE_ADDRESS (sym) = addr;
19077             }
19078           SYMBOL_TYPE (sym) = objfile_type (objfile)->builtin_core_addr;
19079           SYMBOL_DOMAIN (sym) = LABEL_DOMAIN;
19080           SYMBOL_ACLASS_INDEX (sym) = LOC_LABEL;
19081           add_symbol_to_list (sym, cu->list_in_scope);
19082           break;
19083         case DW_TAG_subprogram:
19084           /* SYMBOL_BLOCK_VALUE (sym) will be filled in later by
19085              finish_block.  */
19086           SYMBOL_ACLASS_INDEX (sym) = LOC_BLOCK;
19087           attr2 = dwarf2_attr (die, DW_AT_external, cu);
19088           if ((attr2 && (DW_UNSND (attr2) != 0))
19089               || cu->language == language_ada)
19090             {
19091               /* Subprograms marked external are stored as a global symbol.
19092                  Ada subprograms, whether marked external or not, are always
19093                  stored as a global symbol, because we want to be able to
19094                  access them globally.  For instance, we want to be able
19095                  to break on a nested subprogram without having to
19096                  specify the context.  */
19097               list_to_add = &global_symbols;
19098             }
19099           else
19100             {
19101               list_to_add = cu->list_in_scope;
19102             }
19103           break;
19104         case DW_TAG_inlined_subroutine:
19105           /* SYMBOL_BLOCK_VALUE (sym) will be filled in later by
19106              finish_block.  */
19107           SYMBOL_ACLASS_INDEX (sym) = LOC_BLOCK;
19108           SYMBOL_INLINED (sym) = 1;
19109           list_to_add = cu->list_in_scope;
19110           break;
19111         case DW_TAG_template_value_param:
19112           suppress_add = 1;
19113           /* Fall through.  */
19114         case DW_TAG_constant:
19115         case DW_TAG_variable:
19116         case DW_TAG_member:
19117           /* Compilation with minimal debug info may result in
19118              variables with missing type entries.  Change the
19119              misleading `void' type to something sensible.  */
19120           if (TYPE_CODE (SYMBOL_TYPE (sym)) == TYPE_CODE_VOID)
19121             SYMBOL_TYPE (sym)
19122               = objfile_type (objfile)->nodebug_data_symbol;
19123
19124           attr = dwarf2_attr (die, DW_AT_const_value, cu);
19125           /* In the case of DW_TAG_member, we should only be called for
19126              static const members.  */
19127           if (die->tag == DW_TAG_member)
19128             {
19129               /* dwarf2_add_field uses die_is_declaration,
19130                  so we do the same.  */
19131               gdb_assert (die_is_declaration (die, cu));
19132               gdb_assert (attr);
19133             }
19134           if (attr)
19135             {
19136               dwarf2_const_value (attr, sym, cu);
19137               attr2 = dwarf2_attr (die, DW_AT_external, cu);
19138               if (!suppress_add)
19139                 {
19140                   if (attr2 && (DW_UNSND (attr2) != 0))
19141                     list_to_add = &global_symbols;
19142                   else
19143                     list_to_add = cu->list_in_scope;
19144                 }
19145               break;
19146             }
19147           attr = dwarf2_attr (die, DW_AT_location, cu);
19148           if (attr)
19149             {
19150               var_decode_location (attr, sym, cu);
19151               attr2 = dwarf2_attr (die, DW_AT_external, cu);
19152
19153               /* Fortran explicitly imports any global symbols to the local
19154                  scope by DW_TAG_common_block.  */
19155               if (cu->language == language_fortran && die->parent
19156                   && die->parent->tag == DW_TAG_common_block)
19157                 attr2 = NULL;
19158
19159               if (SYMBOL_CLASS (sym) == LOC_STATIC
19160                   && SYMBOL_VALUE_ADDRESS (sym) == 0
19161                   && !dwarf2_per_objfile->has_section_at_zero)
19162                 {
19163                   /* When a static variable is eliminated by the linker,
19164                      the corresponding debug information is not stripped
19165                      out, but the variable address is set to null;
19166                      do not add such variables into symbol table.  */
19167                 }
19168               else if (attr2 && (DW_UNSND (attr2) != 0))
19169                 {
19170                   /* Workaround gfortran PR debug/40040 - it uses
19171                      DW_AT_location for variables in -fPIC libraries which may
19172                      get overriden by other libraries/executable and get
19173                      a different address.  Resolve it by the minimal symbol
19174                      which may come from inferior's executable using copy
19175                      relocation.  Make this workaround only for gfortran as for
19176                      other compilers GDB cannot guess the minimal symbol
19177                      Fortran mangling kind.  */
19178                   if (cu->language == language_fortran && die->parent
19179                       && die->parent->tag == DW_TAG_module
19180                       && cu->producer
19181                       && startswith (cu->producer, "GNU Fortran"))
19182                     SYMBOL_ACLASS_INDEX (sym) = LOC_UNRESOLVED;
19183
19184                   /* A variable with DW_AT_external is never static,
19185                      but it may be block-scoped.  */
19186                   list_to_add = (cu->list_in_scope == &file_symbols
19187                                  ? &global_symbols : cu->list_in_scope);
19188                 }
19189               else
19190                 list_to_add = cu->list_in_scope;
19191             }
19192           else
19193             {
19194               /* We do not know the address of this symbol.
19195                  If it is an external symbol and we have type information
19196                  for it, enter the symbol as a LOC_UNRESOLVED symbol.
19197                  The address of the variable will then be determined from
19198                  the minimal symbol table whenever the variable is
19199                  referenced.  */
19200               attr2 = dwarf2_attr (die, DW_AT_external, cu);
19201
19202               /* Fortran explicitly imports any global symbols to the local
19203                  scope by DW_TAG_common_block.  */
19204               if (cu->language == language_fortran && die->parent
19205                   && die->parent->tag == DW_TAG_common_block)
19206                 {
19207                   /* SYMBOL_CLASS doesn't matter here because
19208                      read_common_block is going to reset it.  */
19209                   if (!suppress_add)
19210                     list_to_add = cu->list_in_scope;
19211                 }
19212               else if (attr2 && (DW_UNSND (attr2) != 0)
19213                        && dwarf2_attr (die, DW_AT_type, cu) != NULL)
19214                 {
19215                   /* A variable with DW_AT_external is never static, but it
19216                      may be block-scoped.  */
19217                   list_to_add = (cu->list_in_scope == &file_symbols
19218                                  ? &global_symbols : cu->list_in_scope);
19219
19220                   SYMBOL_ACLASS_INDEX (sym) = LOC_UNRESOLVED;
19221                 }
19222               else if (!die_is_declaration (die, cu))
19223                 {
19224                   /* Use the default LOC_OPTIMIZED_OUT class.  */
19225                   gdb_assert (SYMBOL_CLASS (sym) == LOC_OPTIMIZED_OUT);
19226                   if (!suppress_add)
19227                     list_to_add = cu->list_in_scope;
19228                 }
19229             }
19230           break;
19231         case DW_TAG_formal_parameter:
19232           /* If we are inside a function, mark this as an argument.  If
19233              not, we might be looking at an argument to an inlined function
19234              when we do not have enough information to show inlined frames;
19235              pretend it's a local variable in that case so that the user can
19236              still see it.  */
19237           if (context_stack_depth > 0
19238               && context_stack[context_stack_depth - 1].name != NULL)
19239             SYMBOL_IS_ARGUMENT (sym) = 1;
19240           attr = dwarf2_attr (die, DW_AT_location, cu);
19241           if (attr)
19242             {
19243               var_decode_location (attr, sym, cu);
19244             }
19245           attr = dwarf2_attr (die, DW_AT_const_value, cu);
19246           if (attr)
19247             {
19248               dwarf2_const_value (attr, sym, cu);
19249             }
19250
19251           list_to_add = cu->list_in_scope;
19252           break;
19253         case DW_TAG_unspecified_parameters:
19254           /* From varargs functions; gdb doesn't seem to have any
19255              interest in this information, so just ignore it for now.
19256              (FIXME?) */
19257           break;
19258         case DW_TAG_template_type_param:
19259           suppress_add = 1;
19260           /* Fall through.  */
19261         case DW_TAG_class_type:
19262         case DW_TAG_interface_type:
19263         case DW_TAG_structure_type:
19264         case DW_TAG_union_type:
19265         case DW_TAG_set_type:
19266         case DW_TAG_enumeration_type:
19267           SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
19268           SYMBOL_DOMAIN (sym) = STRUCT_DOMAIN;
19269
19270           {
19271             /* NOTE: carlton/2003-11-10: C++ class symbols shouldn't
19272                really ever be static objects: otherwise, if you try
19273                to, say, break of a class's method and you're in a file
19274                which doesn't mention that class, it won't work unless
19275                the check for all static symbols in lookup_symbol_aux
19276                saves you.  See the OtherFileClass tests in
19277                gdb.c++/namespace.exp.  */
19278
19279             if (!suppress_add)
19280               {
19281                 list_to_add = (cu->list_in_scope == &file_symbols
19282                                && cu->language == language_cplus
19283                                ? &global_symbols : cu->list_in_scope);
19284
19285                 /* The semantics of C++ state that "struct foo {
19286                    ... }" also defines a typedef for "foo".  */
19287                 if (cu->language == language_cplus
19288                     || cu->language == language_ada
19289                     || cu->language == language_d
19290                     || cu->language == language_rust)
19291                   {
19292                     /* The symbol's name is already allocated along
19293                        with this objfile, so we don't need to
19294                        duplicate it for the type.  */
19295                     if (TYPE_NAME (SYMBOL_TYPE (sym)) == 0)
19296                       TYPE_NAME (SYMBOL_TYPE (sym)) = SYMBOL_SEARCH_NAME (sym);
19297                   }
19298               }
19299           }
19300           break;
19301         case DW_TAG_typedef:
19302           SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
19303           SYMBOL_DOMAIN (sym) = VAR_DOMAIN;
19304           list_to_add = cu->list_in_scope;
19305           break;
19306         case DW_TAG_base_type:
19307         case DW_TAG_subrange_type:
19308           SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
19309           SYMBOL_DOMAIN (sym) = VAR_DOMAIN;
19310           list_to_add = cu->list_in_scope;
19311           break;
19312         case DW_TAG_enumerator:
19313           attr = dwarf2_attr (die, DW_AT_const_value, cu);
19314           if (attr)
19315             {
19316               dwarf2_const_value (attr, sym, cu);
19317             }
19318           {
19319             /* NOTE: carlton/2003-11-10: See comment above in the
19320                DW_TAG_class_type, etc. block.  */
19321
19322             list_to_add = (cu->list_in_scope == &file_symbols
19323                            && cu->language == language_cplus
19324                            ? &global_symbols : cu->list_in_scope);
19325           }
19326           break;
19327         case DW_TAG_imported_declaration:
19328         case DW_TAG_namespace:
19329           SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
19330           list_to_add = &global_symbols;
19331           break;
19332         case DW_TAG_module:
19333           SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
19334           SYMBOL_DOMAIN (sym) = MODULE_DOMAIN;
19335           list_to_add = &global_symbols;
19336           break;
19337         case DW_TAG_common_block:
19338           SYMBOL_ACLASS_INDEX (sym) = LOC_COMMON_BLOCK;
19339           SYMBOL_DOMAIN (sym) = COMMON_BLOCK_DOMAIN;
19340           add_symbol_to_list (sym, cu->list_in_scope);
19341           break;
19342         default:
19343           /* Not a tag we recognize.  Hopefully we aren't processing
19344              trash data, but since we must specifically ignore things
19345              we don't recognize, there is nothing else we should do at
19346              this point.  */
19347           complaint (&symfile_complaints, _("unsupported tag: '%s'"),
19348                      dwarf_tag_name (die->tag));
19349           break;
19350         }
19351
19352       if (suppress_add)
19353         {
19354           sym->hash_next = objfile->template_symbols;
19355           objfile->template_symbols = sym;
19356           list_to_add = NULL;
19357         }
19358
19359       if (list_to_add != NULL)
19360         add_symbol_to_list (sym, list_to_add);
19361
19362       /* For the benefit of old versions of GCC, check for anonymous
19363          namespaces based on the demangled name.  */
19364       if (!cu->processing_has_namespace_info
19365           && cu->language == language_cplus)
19366         cp_scan_for_anonymous_namespaces (sym, objfile);
19367     }
19368   return (sym);
19369 }
19370
19371 /* A wrapper for new_symbol_full that always allocates a new symbol.  */
19372
19373 static struct symbol *
19374 new_symbol (struct die_info *die, struct type *type, struct dwarf2_cu *cu)
19375 {
19376   return new_symbol_full (die, type, cu, NULL);
19377 }
19378
19379 /* Given an attr with a DW_FORM_dataN value in host byte order,
19380    zero-extend it as appropriate for the symbol's type.  The DWARF
19381    standard (v4) is not entirely clear about the meaning of using
19382    DW_FORM_dataN for a constant with a signed type, where the type is
19383    wider than the data.  The conclusion of a discussion on the DWARF
19384    list was that this is unspecified.  We choose to always zero-extend
19385    because that is the interpretation long in use by GCC.  */
19386
19387 static gdb_byte *
19388 dwarf2_const_value_data (const struct attribute *attr, struct obstack *obstack,
19389                          struct dwarf2_cu *cu, LONGEST *value, int bits)
19390 {
19391   struct objfile *objfile = cu->objfile;
19392   enum bfd_endian byte_order = bfd_big_endian (objfile->obfd) ?
19393                                 BFD_ENDIAN_BIG : BFD_ENDIAN_LITTLE;
19394   LONGEST l = DW_UNSND (attr);
19395
19396   if (bits < sizeof (*value) * 8)
19397     {
19398       l &= ((LONGEST) 1 << bits) - 1;
19399       *value = l;
19400     }
19401   else if (bits == sizeof (*value) * 8)
19402     *value = l;
19403   else
19404     {
19405       gdb_byte *bytes = (gdb_byte *) obstack_alloc (obstack, bits / 8);
19406       store_unsigned_integer (bytes, bits / 8, byte_order, l);
19407       return bytes;
19408     }
19409
19410   return NULL;
19411 }
19412
19413 /* Read a constant value from an attribute.  Either set *VALUE, or if
19414    the value does not fit in *VALUE, set *BYTES - either already
19415    allocated on the objfile obstack, or newly allocated on OBSTACK,
19416    or, set *BATON, if we translated the constant to a location
19417    expression.  */
19418
19419 static void
19420 dwarf2_const_value_attr (const struct attribute *attr, struct type *type,
19421                          const char *name, struct obstack *obstack,
19422                          struct dwarf2_cu *cu,
19423                          LONGEST *value, const gdb_byte **bytes,
19424                          struct dwarf2_locexpr_baton **baton)
19425 {
19426   struct objfile *objfile = cu->objfile;
19427   struct comp_unit_head *cu_header = &cu->header;
19428   struct dwarf_block *blk;
19429   enum bfd_endian byte_order = (bfd_big_endian (objfile->obfd) ?
19430                                 BFD_ENDIAN_BIG : BFD_ENDIAN_LITTLE);
19431
19432   *value = 0;
19433   *bytes = NULL;
19434   *baton = NULL;
19435
19436   switch (attr->form)
19437     {
19438     case DW_FORM_addr:
19439     case DW_FORM_GNU_addr_index:
19440       {
19441         gdb_byte *data;
19442
19443         if (TYPE_LENGTH (type) != cu_header->addr_size)
19444           dwarf2_const_value_length_mismatch_complaint (name,
19445                                                         cu_header->addr_size,
19446                                                         TYPE_LENGTH (type));
19447         /* Symbols of this form are reasonably rare, so we just
19448            piggyback on the existing location code rather than writing
19449            a new implementation of symbol_computed_ops.  */
19450         *baton = XOBNEW (obstack, struct dwarf2_locexpr_baton);
19451         (*baton)->per_cu = cu->per_cu;
19452         gdb_assert ((*baton)->per_cu);
19453
19454         (*baton)->size = 2 + cu_header->addr_size;
19455         data = (gdb_byte *) obstack_alloc (obstack, (*baton)->size);
19456         (*baton)->data = data;
19457
19458         data[0] = DW_OP_addr;
19459         store_unsigned_integer (&data[1], cu_header->addr_size,
19460                                 byte_order, DW_ADDR (attr));
19461         data[cu_header->addr_size + 1] = DW_OP_stack_value;
19462       }
19463       break;
19464     case DW_FORM_string:
19465     case DW_FORM_strp:
19466     case DW_FORM_GNU_str_index:
19467     case DW_FORM_GNU_strp_alt:
19468       /* DW_STRING is already allocated on the objfile obstack, point
19469          directly to it.  */
19470       *bytes = (const gdb_byte *) DW_STRING (attr);
19471       break;
19472     case DW_FORM_block1:
19473     case DW_FORM_block2:
19474     case DW_FORM_block4:
19475     case DW_FORM_block:
19476     case DW_FORM_exprloc:
19477     case DW_FORM_data16:
19478       blk = DW_BLOCK (attr);
19479       if (TYPE_LENGTH (type) != blk->size)
19480         dwarf2_const_value_length_mismatch_complaint (name, blk->size,
19481                                                       TYPE_LENGTH (type));
19482       *bytes = blk->data;
19483       break;
19484
19485       /* The DW_AT_const_value attributes are supposed to carry the
19486          symbol's value "represented as it would be on the target
19487          architecture."  By the time we get here, it's already been
19488          converted to host endianness, so we just need to sign- or
19489          zero-extend it as appropriate.  */
19490     case DW_FORM_data1:
19491       *bytes = dwarf2_const_value_data (attr, obstack, cu, value, 8);
19492       break;
19493     case DW_FORM_data2:
19494       *bytes = dwarf2_const_value_data (attr, obstack, cu, value, 16);
19495       break;
19496     case DW_FORM_data4:
19497       *bytes = dwarf2_const_value_data (attr, obstack, cu, value, 32);
19498       break;
19499     case DW_FORM_data8:
19500       *bytes = dwarf2_const_value_data (attr, obstack, cu, value, 64);
19501       break;
19502
19503     case DW_FORM_sdata:
19504       *value = DW_SND (attr);
19505       break;
19506
19507     case DW_FORM_udata:
19508       *value = DW_UNSND (attr);
19509       break;
19510
19511     default:
19512       complaint (&symfile_complaints,
19513                  _("unsupported const value attribute form: '%s'"),
19514                  dwarf_form_name (attr->form));
19515       *value = 0;
19516       break;
19517     }
19518 }
19519
19520
19521 /* Copy constant value from an attribute to a symbol.  */
19522
19523 static void
19524 dwarf2_const_value (const struct attribute *attr, struct symbol *sym,
19525                     struct dwarf2_cu *cu)
19526 {
19527   struct objfile *objfile = cu->objfile;
19528   LONGEST value;
19529   const gdb_byte *bytes;
19530   struct dwarf2_locexpr_baton *baton;
19531
19532   dwarf2_const_value_attr (attr, SYMBOL_TYPE (sym),
19533                            SYMBOL_PRINT_NAME (sym),
19534                            &objfile->objfile_obstack, cu,
19535                            &value, &bytes, &baton);
19536
19537   if (baton != NULL)
19538     {
19539       SYMBOL_LOCATION_BATON (sym) = baton;
19540       SYMBOL_ACLASS_INDEX (sym) = dwarf2_locexpr_index;
19541     }
19542   else if (bytes != NULL)
19543      {
19544       SYMBOL_VALUE_BYTES (sym) = bytes;
19545       SYMBOL_ACLASS_INDEX (sym) = LOC_CONST_BYTES;
19546     }
19547   else
19548     {
19549       SYMBOL_VALUE (sym) = value;
19550       SYMBOL_ACLASS_INDEX (sym) = LOC_CONST;
19551     }
19552 }
19553
19554 /* Return the type of the die in question using its DW_AT_type attribute.  */
19555
19556 static struct type *
19557 die_type (struct die_info *die, struct dwarf2_cu *cu)
19558 {
19559   struct attribute *type_attr;
19560
19561   type_attr = dwarf2_attr (die, DW_AT_type, cu);
19562   if (!type_attr)
19563     {
19564       /* A missing DW_AT_type represents a void type.  */
19565       return objfile_type (cu->objfile)->builtin_void;
19566     }
19567
19568   return lookup_die_type (die, type_attr, cu);
19569 }
19570
19571 /* True iff CU's producer generates GNAT Ada auxiliary information
19572    that allows to find parallel types through that information instead
19573    of having to do expensive parallel lookups by type name.  */
19574
19575 static int
19576 need_gnat_info (struct dwarf2_cu *cu)
19577 {
19578   /* FIXME: brobecker/2010-10-12: As of now, only the AdaCore version
19579      of GNAT produces this auxiliary information, without any indication
19580      that it is produced.  Part of enhancing the FSF version of GNAT
19581      to produce that information will be to put in place an indicator
19582      that we can use in order to determine whether the descriptive type
19583      info is available or not.  One suggestion that has been made is
19584      to use a new attribute, attached to the CU die.  For now, assume
19585      that the descriptive type info is not available.  */
19586   return 0;
19587 }
19588
19589 /* Return the auxiliary type of the die in question using its
19590    DW_AT_GNAT_descriptive_type attribute.  Returns NULL if the
19591    attribute is not present.  */
19592
19593 static struct type *
19594 die_descriptive_type (struct die_info *die, struct dwarf2_cu *cu)
19595 {
19596   struct attribute *type_attr;
19597
19598   type_attr = dwarf2_attr (die, DW_AT_GNAT_descriptive_type, cu);
19599   if (!type_attr)
19600     return NULL;
19601
19602   return lookup_die_type (die, type_attr, cu);
19603 }
19604
19605 /* If DIE has a descriptive_type attribute, then set the TYPE's
19606    descriptive type accordingly.  */
19607
19608 static void
19609 set_descriptive_type (struct type *type, struct die_info *die,
19610                       struct dwarf2_cu *cu)
19611 {
19612   struct type *descriptive_type = die_descriptive_type (die, cu);
19613
19614   if (descriptive_type)
19615     {
19616       ALLOCATE_GNAT_AUX_TYPE (type);
19617       TYPE_DESCRIPTIVE_TYPE (type) = descriptive_type;
19618     }
19619 }
19620
19621 /* Return the containing type of the die in question using its
19622    DW_AT_containing_type attribute.  */
19623
19624 static struct type *
19625 die_containing_type (struct die_info *die, struct dwarf2_cu *cu)
19626 {
19627   struct attribute *type_attr;
19628
19629   type_attr = dwarf2_attr (die, DW_AT_containing_type, cu);
19630   if (!type_attr)
19631     error (_("Dwarf Error: Problem turning containing type into gdb type "
19632              "[in module %s]"), objfile_name (cu->objfile));
19633
19634   return lookup_die_type (die, type_attr, cu);
19635 }
19636
19637 /* Return an error marker type to use for the ill formed type in DIE/CU.  */
19638
19639 static struct type *
19640 build_error_marker_type (struct dwarf2_cu *cu, struct die_info *die)
19641 {
19642   struct objfile *objfile = dwarf2_per_objfile->objfile;
19643   char *message, *saved;
19644
19645   message = xstrprintf (_("<unknown type in %s, CU 0x%x, DIE 0x%x>"),
19646                         objfile_name (objfile),
19647                         to_underlying (cu->header.sect_off),
19648                         to_underlying (die->sect_off));
19649   saved = (char *) obstack_copy0 (&objfile->objfile_obstack,
19650                                   message, strlen (message));
19651   xfree (message);
19652
19653   return init_type (objfile, TYPE_CODE_ERROR, 0, saved);
19654 }
19655
19656 /* Look up the type of DIE in CU using its type attribute ATTR.
19657    ATTR must be one of: DW_AT_type, DW_AT_GNAT_descriptive_type,
19658    DW_AT_containing_type.
19659    If there is no type substitute an error marker.  */
19660
19661 static struct type *
19662 lookup_die_type (struct die_info *die, const struct attribute *attr,
19663                  struct dwarf2_cu *cu)
19664 {
19665   struct objfile *objfile = cu->objfile;
19666   struct type *this_type;
19667
19668   gdb_assert (attr->name == DW_AT_type
19669               || attr->name == DW_AT_GNAT_descriptive_type
19670               || attr->name == DW_AT_containing_type);
19671
19672   /* First see if we have it cached.  */
19673
19674   if (attr->form == DW_FORM_GNU_ref_alt)
19675     {
19676       struct dwarf2_per_cu_data *per_cu;
19677       sect_offset sect_off = dwarf2_get_ref_die_offset (attr);
19678
19679       per_cu = dwarf2_find_containing_comp_unit (sect_off, 1, cu->objfile);
19680       this_type = get_die_type_at_offset (sect_off, per_cu);
19681     }
19682   else if (attr_form_is_ref (attr))
19683     {
19684       sect_offset sect_off = dwarf2_get_ref_die_offset (attr);
19685
19686       this_type = get_die_type_at_offset (sect_off, cu->per_cu);
19687     }
19688   else if (attr->form == DW_FORM_ref_sig8)
19689     {
19690       ULONGEST signature = DW_SIGNATURE (attr);
19691
19692       return get_signatured_type (die, signature, cu);
19693     }
19694   else
19695     {
19696       complaint (&symfile_complaints,
19697                  _("Dwarf Error: Bad type attribute %s in DIE"
19698                    " at 0x%x [in module %s]"),
19699                  dwarf_attr_name (attr->name), to_underlying (die->sect_off),
19700                  objfile_name (objfile));
19701       return build_error_marker_type (cu, die);
19702     }
19703
19704   /* If not cached we need to read it in.  */
19705
19706   if (this_type == NULL)
19707     {
19708       struct die_info *type_die = NULL;
19709       struct dwarf2_cu *type_cu = cu;
19710
19711       if (attr_form_is_ref (attr))
19712         type_die = follow_die_ref (die, attr, &type_cu);
19713       if (type_die == NULL)
19714         return build_error_marker_type (cu, die);
19715       /* If we find the type now, it's probably because the type came
19716          from an inter-CU reference and the type's CU got expanded before
19717          ours.  */
19718       this_type = read_type_die (type_die, type_cu);
19719     }
19720
19721   /* If we still don't have a type use an error marker.  */
19722
19723   if (this_type == NULL)
19724     return build_error_marker_type (cu, die);
19725
19726   return this_type;
19727 }
19728
19729 /* Return the type in DIE, CU.
19730    Returns NULL for invalid types.
19731
19732    This first does a lookup in die_type_hash,
19733    and only reads the die in if necessary.
19734
19735    NOTE: This can be called when reading in partial or full symbols.  */
19736
19737 static struct type *
19738 read_type_die (struct die_info *die, struct dwarf2_cu *cu)
19739 {
19740   struct type *this_type;
19741
19742   this_type = get_die_type (die, cu);
19743   if (this_type)
19744     return this_type;
19745
19746   return read_type_die_1 (die, cu);
19747 }
19748
19749 /* Read the type in DIE, CU.
19750    Returns NULL for invalid types.  */
19751
19752 static struct type *
19753 read_type_die_1 (struct die_info *die, struct dwarf2_cu *cu)
19754 {
19755   struct type *this_type = NULL;
19756
19757   switch (die->tag)
19758     {
19759     case DW_TAG_class_type:
19760     case DW_TAG_interface_type:
19761     case DW_TAG_structure_type:
19762     case DW_TAG_union_type:
19763       this_type = read_structure_type (die, cu);
19764       break;
19765     case DW_TAG_enumeration_type:
19766       this_type = read_enumeration_type (die, cu);
19767       break;
19768     case DW_TAG_subprogram:
19769     case DW_TAG_subroutine_type:
19770     case DW_TAG_inlined_subroutine:
19771       this_type = read_subroutine_type (die, cu);
19772       break;
19773     case DW_TAG_array_type:
19774       this_type = read_array_type (die, cu);
19775       break;
19776     case DW_TAG_set_type:
19777       this_type = read_set_type (die, cu);
19778       break;
19779     case DW_TAG_pointer_type:
19780       this_type = read_tag_pointer_type (die, cu);
19781       break;
19782     case DW_TAG_ptr_to_member_type:
19783       this_type = read_tag_ptr_to_member_type (die, cu);
19784       break;
19785     case DW_TAG_reference_type:
19786       this_type = read_tag_reference_type (die, cu, TYPE_CODE_REF);
19787       break;
19788     case DW_TAG_rvalue_reference_type:
19789       this_type = read_tag_reference_type (die, cu, TYPE_CODE_RVALUE_REF);
19790       break;
19791     case DW_TAG_const_type:
19792       this_type = read_tag_const_type (die, cu);
19793       break;
19794     case DW_TAG_volatile_type:
19795       this_type = read_tag_volatile_type (die, cu);
19796       break;
19797     case DW_TAG_restrict_type:
19798       this_type = read_tag_restrict_type (die, cu);
19799       break;
19800     case DW_TAG_string_type:
19801       this_type = read_tag_string_type (die, cu);
19802       break;
19803     case DW_TAG_typedef:
19804       this_type = read_typedef (die, cu);
19805       break;
19806     case DW_TAG_subrange_type:
19807       this_type = read_subrange_type (die, cu);
19808       break;
19809     case DW_TAG_base_type:
19810       this_type = read_base_type (die, cu);
19811       break;
19812     case DW_TAG_unspecified_type:
19813       this_type = read_unspecified_type (die, cu);
19814       break;
19815     case DW_TAG_namespace:
19816       this_type = read_namespace_type (die, cu);
19817       break;
19818     case DW_TAG_module:
19819       this_type = read_module_type (die, cu);
19820       break;
19821     case DW_TAG_atomic_type:
19822       this_type = read_tag_atomic_type (die, cu);
19823       break;
19824     default:
19825       complaint (&symfile_complaints,
19826                  _("unexpected tag in read_type_die: '%s'"),
19827                  dwarf_tag_name (die->tag));
19828       break;
19829     }
19830
19831   return this_type;
19832 }
19833
19834 /* See if we can figure out if the class lives in a namespace.  We do
19835    this by looking for a member function; its demangled name will
19836    contain namespace info, if there is any.
19837    Return the computed name or NULL.
19838    Space for the result is allocated on the objfile's obstack.
19839    This is the full-die version of guess_partial_die_structure_name.
19840    In this case we know DIE has no useful parent.  */
19841
19842 static char *
19843 guess_full_die_structure_name (struct die_info *die, struct dwarf2_cu *cu)
19844 {
19845   struct die_info *spec_die;
19846   struct dwarf2_cu *spec_cu;
19847   struct die_info *child;
19848
19849   spec_cu = cu;
19850   spec_die = die_specification (die, &spec_cu);
19851   if (spec_die != NULL)
19852     {
19853       die = spec_die;
19854       cu = spec_cu;
19855     }
19856
19857   for (child = die->child;
19858        child != NULL;
19859        child = child->sibling)
19860     {
19861       if (child->tag == DW_TAG_subprogram)
19862         {
19863           const char *linkage_name;
19864
19865           linkage_name = dwarf2_string_attr (child, DW_AT_linkage_name, cu);
19866           if (linkage_name == NULL)
19867             linkage_name = dwarf2_string_attr (child, DW_AT_MIPS_linkage_name,
19868                                                cu);
19869           if (linkage_name != NULL)
19870             {
19871               char *actual_name
19872                 = language_class_name_from_physname (cu->language_defn,
19873                                                      linkage_name);
19874               char *name = NULL;
19875
19876               if (actual_name != NULL)
19877                 {
19878                   const char *die_name = dwarf2_name (die, cu);
19879
19880                   if (die_name != NULL
19881                       && strcmp (die_name, actual_name) != 0)
19882                     {
19883                       /* Strip off the class name from the full name.
19884                          We want the prefix.  */
19885                       int die_name_len = strlen (die_name);
19886                       int actual_name_len = strlen (actual_name);
19887
19888                       /* Test for '::' as a sanity check.  */
19889                       if (actual_name_len > die_name_len + 2
19890                           && actual_name[actual_name_len
19891                                          - die_name_len - 1] == ':')
19892                         name = (char *) obstack_copy0 (
19893                           &cu->objfile->per_bfd->storage_obstack,
19894                           actual_name, actual_name_len - die_name_len - 2);
19895                     }
19896                 }
19897               xfree (actual_name);
19898               return name;
19899             }
19900         }
19901     }
19902
19903   return NULL;
19904 }
19905
19906 /* GCC might emit a nameless typedef that has a linkage name.  Determine the
19907    prefix part in such case.  See
19908    http://gcc.gnu.org/bugzilla/show_bug.cgi?id=47510.  */
19909
19910 static const char *
19911 anonymous_struct_prefix (struct die_info *die, struct dwarf2_cu *cu)
19912 {
19913   struct attribute *attr;
19914   const char *base;
19915
19916   if (die->tag != DW_TAG_class_type && die->tag != DW_TAG_interface_type
19917       && die->tag != DW_TAG_structure_type && die->tag != DW_TAG_union_type)
19918     return NULL;
19919
19920   if (dwarf2_string_attr (die, DW_AT_name, cu) != NULL)
19921     return NULL;
19922
19923   attr = dwarf2_attr (die, DW_AT_linkage_name, cu);
19924   if (attr == NULL)
19925     attr = dwarf2_attr (die, DW_AT_MIPS_linkage_name, cu);
19926   if (attr == NULL || DW_STRING (attr) == NULL)
19927     return NULL;
19928
19929   /* dwarf2_name had to be already called.  */
19930   gdb_assert (DW_STRING_IS_CANONICAL (attr));
19931
19932   /* Strip the base name, keep any leading namespaces/classes.  */
19933   base = strrchr (DW_STRING (attr), ':');
19934   if (base == NULL || base == DW_STRING (attr) || base[-1] != ':')
19935     return "";
19936
19937   return (char *) obstack_copy0 (&cu->objfile->per_bfd->storage_obstack,
19938                                  DW_STRING (attr),
19939                                  &base[-1] - DW_STRING (attr));
19940 }
19941
19942 /* Return the name of the namespace/class that DIE is defined within,
19943    or "" if we can't tell.  The caller should not xfree the result.
19944
19945    For example, if we're within the method foo() in the following
19946    code:
19947
19948    namespace N {
19949      class C {
19950        void foo () {
19951        }
19952      };
19953    }
19954
19955    then determine_prefix on foo's die will return "N::C".  */
19956
19957 static const char *
19958 determine_prefix (struct die_info *die, struct dwarf2_cu *cu)
19959 {
19960   struct die_info *parent, *spec_die;
19961   struct dwarf2_cu *spec_cu;
19962   struct type *parent_type;
19963   const char *retval;
19964
19965   if (cu->language != language_cplus
19966       && cu->language != language_fortran && cu->language != language_d
19967       && cu->language != language_rust)
19968     return "";
19969
19970   retval = anonymous_struct_prefix (die, cu);
19971   if (retval)
19972     return retval;
19973
19974   /* We have to be careful in the presence of DW_AT_specification.
19975      For example, with GCC 3.4, given the code
19976
19977      namespace N {
19978        void foo() {
19979          // Definition of N::foo.
19980        }
19981      }
19982
19983      then we'll have a tree of DIEs like this:
19984
19985      1: DW_TAG_compile_unit
19986        2: DW_TAG_namespace        // N
19987          3: DW_TAG_subprogram     // declaration of N::foo
19988        4: DW_TAG_subprogram       // definition of N::foo
19989             DW_AT_specification   // refers to die #3
19990
19991      Thus, when processing die #4, we have to pretend that we're in
19992      the context of its DW_AT_specification, namely the contex of die
19993      #3.  */
19994   spec_cu = cu;
19995   spec_die = die_specification (die, &spec_cu);
19996   if (spec_die == NULL)
19997     parent = die->parent;
19998   else
19999     {
20000       parent = spec_die->parent;
20001       cu = spec_cu;
20002     }
20003
20004   if (parent == NULL)
20005     return "";
20006   else if (parent->building_fullname)
20007     {
20008       const char *name;
20009       const char *parent_name;
20010
20011       /* It has been seen on RealView 2.2 built binaries,
20012          DW_TAG_template_type_param types actually _defined_ as
20013          children of the parent class:
20014
20015          enum E {};
20016          template class <class Enum> Class{};
20017          Class<enum E> class_e;
20018
20019          1: DW_TAG_class_type (Class)
20020            2: DW_TAG_enumeration_type (E)
20021              3: DW_TAG_enumerator (enum1:0)
20022              3: DW_TAG_enumerator (enum2:1)
20023              ...
20024            2: DW_TAG_template_type_param
20025               DW_AT_type  DW_FORM_ref_udata (E)
20026
20027          Besides being broken debug info, it can put GDB into an
20028          infinite loop.  Consider:
20029
20030          When we're building the full name for Class<E>, we'll start
20031          at Class, and go look over its template type parameters,
20032          finding E.  We'll then try to build the full name of E, and
20033          reach here.  We're now trying to build the full name of E,
20034          and look over the parent DIE for containing scope.  In the
20035          broken case, if we followed the parent DIE of E, we'd again
20036          find Class, and once again go look at its template type
20037          arguments, etc., etc.  Simply don't consider such parent die
20038          as source-level parent of this die (it can't be, the language
20039          doesn't allow it), and break the loop here.  */
20040       name = dwarf2_name (die, cu);
20041       parent_name = dwarf2_name (parent, cu);
20042       complaint (&symfile_complaints,
20043                  _("template param type '%s' defined within parent '%s'"),
20044                  name ? name : "<unknown>",
20045                  parent_name ? parent_name : "<unknown>");
20046       return "";
20047     }
20048   else
20049     switch (parent->tag)
20050       {
20051       case DW_TAG_namespace:
20052         parent_type = read_type_die (parent, cu);
20053         /* GCC 4.0 and 4.1 had a bug (PR c++/28460) where they generated bogus
20054            DW_TAG_namespace DIEs with a name of "::" for the global namespace.
20055            Work around this problem here.  */
20056         if (cu->language == language_cplus
20057             && strcmp (TYPE_TAG_NAME (parent_type), "::") == 0)
20058           return "";
20059         /* We give a name to even anonymous namespaces.  */
20060         return TYPE_TAG_NAME (parent_type);
20061       case DW_TAG_class_type:
20062       case DW_TAG_interface_type:
20063       case DW_TAG_structure_type:
20064       case DW_TAG_union_type:
20065       case DW_TAG_module:
20066         parent_type = read_type_die (parent, cu);
20067         if (TYPE_TAG_NAME (parent_type) != NULL)
20068           return TYPE_TAG_NAME (parent_type);
20069         else
20070           /* An anonymous structure is only allowed non-static data
20071              members; no typedefs, no member functions, et cetera.
20072              So it does not need a prefix.  */
20073           return "";
20074       case DW_TAG_compile_unit:
20075       case DW_TAG_partial_unit:
20076         /* gcc-4.5 -gdwarf-4 can drop the enclosing namespace.  Cope.  */
20077         if (cu->language == language_cplus
20078             && !VEC_empty (dwarf2_section_info_def, dwarf2_per_objfile->types)
20079             && die->child != NULL
20080             && (die->tag == DW_TAG_class_type
20081                 || die->tag == DW_TAG_structure_type
20082                 || die->tag == DW_TAG_union_type))
20083           {
20084             char *name = guess_full_die_structure_name (die, cu);
20085             if (name != NULL)
20086               return name;
20087           }
20088         return "";
20089       case DW_TAG_enumeration_type:
20090         parent_type = read_type_die (parent, cu);
20091         if (TYPE_DECLARED_CLASS (parent_type))
20092           {
20093             if (TYPE_TAG_NAME (parent_type) != NULL)
20094               return TYPE_TAG_NAME (parent_type);
20095             return "";
20096           }
20097         /* Fall through.  */
20098       default:
20099         return determine_prefix (parent, cu);
20100       }
20101 }
20102
20103 /* Return a newly-allocated string formed by concatenating PREFIX and SUFFIX
20104    with appropriate separator.  If PREFIX or SUFFIX is NULL or empty, then
20105    simply copy the SUFFIX or PREFIX, respectively.  If OBS is non-null, perform
20106    an obconcat, otherwise allocate storage for the result.  The CU argument is
20107    used to determine the language and hence, the appropriate separator.  */
20108
20109 #define MAX_SEP_LEN 7  /* strlen ("__") + strlen ("_MOD_")  */
20110
20111 static char *
20112 typename_concat (struct obstack *obs, const char *prefix, const char *suffix,
20113                  int physname, struct dwarf2_cu *cu)
20114 {
20115   const char *lead = "";
20116   const char *sep;
20117
20118   if (suffix == NULL || suffix[0] == '\0'
20119       || prefix == NULL || prefix[0] == '\0')
20120     sep = "";
20121   else if (cu->language == language_d)
20122     {
20123       /* For D, the 'main' function could be defined in any module, but it
20124          should never be prefixed.  */
20125       if (strcmp (suffix, "D main") == 0)
20126         {
20127           prefix = "";
20128           sep = "";
20129         }
20130       else
20131         sep = ".";
20132     }
20133   else if (cu->language == language_fortran && physname)
20134     {
20135       /* This is gfortran specific mangling.  Normally DW_AT_linkage_name or
20136          DW_AT_MIPS_linkage_name is preferred and used instead.  */
20137
20138       lead = "__";
20139       sep = "_MOD_";
20140     }
20141   else
20142     sep = "::";
20143
20144   if (prefix == NULL)
20145     prefix = "";
20146   if (suffix == NULL)
20147     suffix = "";
20148
20149   if (obs == NULL)
20150     {
20151       char *retval
20152         = ((char *)
20153            xmalloc (strlen (prefix) + MAX_SEP_LEN + strlen (suffix) + 1));
20154
20155       strcpy (retval, lead);
20156       strcat (retval, prefix);
20157       strcat (retval, sep);
20158       strcat (retval, suffix);
20159       return retval;
20160     }
20161   else
20162     {
20163       /* We have an obstack.  */
20164       return obconcat (obs, lead, prefix, sep, suffix, (char *) NULL);
20165     }
20166 }
20167
20168 /* Return sibling of die, NULL if no sibling.  */
20169
20170 static struct die_info *
20171 sibling_die (struct die_info *die)
20172 {
20173   return die->sibling;
20174 }
20175
20176 /* Get name of a die, return NULL if not found.  */
20177
20178 static const char *
20179 dwarf2_canonicalize_name (const char *name, struct dwarf2_cu *cu,
20180                           struct obstack *obstack)
20181 {
20182   if (name && cu->language == language_cplus)
20183     {
20184       std::string canon_name = cp_canonicalize_string (name);
20185
20186       if (!canon_name.empty ())
20187         {
20188           if (canon_name != name)
20189             name = (const char *) obstack_copy0 (obstack,
20190                                                  canon_name.c_str (),
20191                                                  canon_name.length ());
20192         }
20193     }
20194
20195   return name;
20196 }
20197
20198 /* Get name of a die, return NULL if not found.
20199    Anonymous namespaces are converted to their magic string.  */
20200
20201 static const char *
20202 dwarf2_name (struct die_info *die, struct dwarf2_cu *cu)
20203 {
20204   struct attribute *attr;
20205
20206   attr = dwarf2_attr (die, DW_AT_name, cu);
20207   if ((!attr || !DW_STRING (attr))
20208       && die->tag != DW_TAG_namespace
20209       && die->tag != DW_TAG_class_type
20210       && die->tag != DW_TAG_interface_type
20211       && die->tag != DW_TAG_structure_type
20212       && die->tag != DW_TAG_union_type)
20213     return NULL;
20214
20215   switch (die->tag)
20216     {
20217     case DW_TAG_compile_unit:
20218     case DW_TAG_partial_unit:
20219       /* Compilation units have a DW_AT_name that is a filename, not
20220          a source language identifier.  */
20221     case DW_TAG_enumeration_type:
20222     case DW_TAG_enumerator:
20223       /* These tags always have simple identifiers already; no need
20224          to canonicalize them.  */
20225       return DW_STRING (attr);
20226
20227     case DW_TAG_namespace:
20228       if (attr != NULL && DW_STRING (attr) != NULL)
20229         return DW_STRING (attr);
20230       return CP_ANONYMOUS_NAMESPACE_STR;
20231
20232     case DW_TAG_class_type:
20233     case DW_TAG_interface_type:
20234     case DW_TAG_structure_type:
20235     case DW_TAG_union_type:
20236       /* Some GCC versions emit spurious DW_AT_name attributes for unnamed
20237          structures or unions.  These were of the form "._%d" in GCC 4.1,
20238          or simply "<anonymous struct>" or "<anonymous union>" in GCC 4.3
20239          and GCC 4.4.  We work around this problem by ignoring these.  */
20240       if (attr && DW_STRING (attr)
20241           && (startswith (DW_STRING (attr), "._")
20242               || startswith (DW_STRING (attr), "<anonymous")))
20243         return NULL;
20244
20245       /* GCC might emit a nameless typedef that has a linkage name.  See
20246          http://gcc.gnu.org/bugzilla/show_bug.cgi?id=47510.  */
20247       if (!attr || DW_STRING (attr) == NULL)
20248         {
20249           char *demangled = NULL;
20250
20251           attr = dwarf2_attr (die, DW_AT_linkage_name, cu);
20252           if (attr == NULL)
20253             attr = dwarf2_attr (die, DW_AT_MIPS_linkage_name, cu);
20254
20255           if (attr == NULL || DW_STRING (attr) == NULL)
20256             return NULL;
20257
20258           /* Avoid demangling DW_STRING (attr) the second time on a second
20259              call for the same DIE.  */
20260           if (!DW_STRING_IS_CANONICAL (attr))
20261             demangled = gdb_demangle (DW_STRING (attr), DMGL_TYPES);
20262
20263           if (demangled)
20264             {
20265               const char *base;
20266
20267               /* FIXME: we already did this for the partial symbol... */
20268               DW_STRING (attr)
20269                 = ((const char *)
20270                    obstack_copy0 (&cu->objfile->per_bfd->storage_obstack,
20271                                   demangled, strlen (demangled)));
20272               DW_STRING_IS_CANONICAL (attr) = 1;
20273               xfree (demangled);
20274
20275               /* Strip any leading namespaces/classes, keep only the base name.
20276                  DW_AT_name for named DIEs does not contain the prefixes.  */
20277               base = strrchr (DW_STRING (attr), ':');
20278               if (base && base > DW_STRING (attr) && base[-1] == ':')
20279                 return &base[1];
20280               else
20281                 return DW_STRING (attr);
20282             }
20283         }
20284       break;
20285
20286     default:
20287       break;
20288     }
20289
20290   if (!DW_STRING_IS_CANONICAL (attr))
20291     {
20292       DW_STRING (attr)
20293         = dwarf2_canonicalize_name (DW_STRING (attr), cu,
20294                                     &cu->objfile->per_bfd->storage_obstack);
20295       DW_STRING_IS_CANONICAL (attr) = 1;
20296     }
20297   return DW_STRING (attr);
20298 }
20299
20300 /* Return the die that this die in an extension of, or NULL if there
20301    is none.  *EXT_CU is the CU containing DIE on input, and the CU
20302    containing the return value on output.  */
20303
20304 static struct die_info *
20305 dwarf2_extension (struct die_info *die, struct dwarf2_cu **ext_cu)
20306 {
20307   struct attribute *attr;
20308
20309   attr = dwarf2_attr (die, DW_AT_extension, *ext_cu);
20310   if (attr == NULL)
20311     return NULL;
20312
20313   return follow_die_ref (die, attr, ext_cu);
20314 }
20315
20316 /* Convert a DIE tag into its string name.  */
20317
20318 static const char *
20319 dwarf_tag_name (unsigned tag)
20320 {
20321   const char *name = get_DW_TAG_name (tag);
20322
20323   if (name == NULL)
20324     return "DW_TAG_<unknown>";
20325
20326   return name;
20327 }
20328
20329 /* Convert a DWARF attribute code into its string name.  */
20330
20331 static const char *
20332 dwarf_attr_name (unsigned attr)
20333 {
20334   const char *name;
20335
20336 #ifdef MIPS /* collides with DW_AT_HP_block_index */
20337   if (attr == DW_AT_MIPS_fde)
20338     return "DW_AT_MIPS_fde";
20339 #else
20340   if (attr == DW_AT_HP_block_index)
20341     return "DW_AT_HP_block_index";
20342 #endif
20343
20344   name = get_DW_AT_name (attr);
20345
20346   if (name == NULL)
20347     return "DW_AT_<unknown>";
20348
20349   return name;
20350 }
20351
20352 /* Convert a DWARF value form code into its string name.  */
20353
20354 static const char *
20355 dwarf_form_name (unsigned form)
20356 {
20357   const char *name = get_DW_FORM_name (form);
20358
20359   if (name == NULL)
20360     return "DW_FORM_<unknown>";
20361
20362   return name;
20363 }
20364
20365 static const char *
20366 dwarf_bool_name (unsigned mybool)
20367 {
20368   if (mybool)
20369     return "TRUE";
20370   else
20371     return "FALSE";
20372 }
20373
20374 /* Convert a DWARF type code into its string name.  */
20375
20376 static const char *
20377 dwarf_type_encoding_name (unsigned enc)
20378 {
20379   const char *name = get_DW_ATE_name (enc);
20380
20381   if (name == NULL)
20382     return "DW_ATE_<unknown>";
20383
20384   return name;
20385 }
20386
20387 static void
20388 dump_die_shallow (struct ui_file *f, int indent, struct die_info *die)
20389 {
20390   unsigned int i;
20391
20392   print_spaces (indent, f);
20393   fprintf_unfiltered (f, "Die: %s (abbrev %d, offset 0x%x)\n",
20394                       dwarf_tag_name (die->tag), die->abbrev,
20395                       to_underlying (die->sect_off));
20396
20397   if (die->parent != NULL)
20398     {
20399       print_spaces (indent, f);
20400       fprintf_unfiltered (f, "  parent at offset: 0x%x\n",
20401                           to_underlying (die->parent->sect_off));
20402     }
20403
20404   print_spaces (indent, f);
20405   fprintf_unfiltered (f, "  has children: %s\n",
20406            dwarf_bool_name (die->child != NULL));
20407
20408   print_spaces (indent, f);
20409   fprintf_unfiltered (f, "  attributes:\n");
20410
20411   for (i = 0; i < die->num_attrs; ++i)
20412     {
20413       print_spaces (indent, f);
20414       fprintf_unfiltered (f, "    %s (%s) ",
20415                dwarf_attr_name (die->attrs[i].name),
20416                dwarf_form_name (die->attrs[i].form));
20417
20418       switch (die->attrs[i].form)
20419         {
20420         case DW_FORM_addr:
20421         case DW_FORM_GNU_addr_index:
20422           fprintf_unfiltered (f, "address: ");
20423           fputs_filtered (hex_string (DW_ADDR (&die->attrs[i])), f);
20424           break;
20425         case DW_FORM_block2:
20426         case DW_FORM_block4:
20427         case DW_FORM_block:
20428         case DW_FORM_block1:
20429           fprintf_unfiltered (f, "block: size %s",
20430                               pulongest (DW_BLOCK (&die->attrs[i])->size));
20431           break;
20432         case DW_FORM_exprloc:
20433           fprintf_unfiltered (f, "expression: size %s",
20434                               pulongest (DW_BLOCK (&die->attrs[i])->size));
20435           break;
20436         case DW_FORM_data16:
20437           fprintf_unfiltered (f, "constant of 16 bytes");
20438           break;
20439         case DW_FORM_ref_addr:
20440           fprintf_unfiltered (f, "ref address: ");
20441           fputs_filtered (hex_string (DW_UNSND (&die->attrs[i])), f);
20442           break;
20443         case DW_FORM_GNU_ref_alt:
20444           fprintf_unfiltered (f, "alt ref address: ");
20445           fputs_filtered (hex_string (DW_UNSND (&die->attrs[i])), f);
20446           break;
20447         case DW_FORM_ref1:
20448         case DW_FORM_ref2:
20449         case DW_FORM_ref4:
20450         case DW_FORM_ref8:
20451         case DW_FORM_ref_udata:
20452           fprintf_unfiltered (f, "constant ref: 0x%lx (adjusted)",
20453                               (long) (DW_UNSND (&die->attrs[i])));
20454           break;
20455         case DW_FORM_data1:
20456         case DW_FORM_data2:
20457         case DW_FORM_data4:
20458         case DW_FORM_data8:
20459         case DW_FORM_udata:
20460         case DW_FORM_sdata:
20461           fprintf_unfiltered (f, "constant: %s",
20462                               pulongest (DW_UNSND (&die->attrs[i])));
20463           break;
20464         case DW_FORM_sec_offset:
20465           fprintf_unfiltered (f, "section offset: %s",
20466                               pulongest (DW_UNSND (&die->attrs[i])));
20467           break;
20468         case DW_FORM_ref_sig8:
20469           fprintf_unfiltered (f, "signature: %s",
20470                               hex_string (DW_SIGNATURE (&die->attrs[i])));
20471           break;
20472         case DW_FORM_string:
20473         case DW_FORM_strp:
20474         case DW_FORM_line_strp:
20475         case DW_FORM_GNU_str_index:
20476         case DW_FORM_GNU_strp_alt:
20477           fprintf_unfiltered (f, "string: \"%s\" (%s canonicalized)",
20478                    DW_STRING (&die->attrs[i])
20479                    ? DW_STRING (&die->attrs[i]) : "",
20480                    DW_STRING_IS_CANONICAL (&die->attrs[i]) ? "is" : "not");
20481           break;
20482         case DW_FORM_flag:
20483           if (DW_UNSND (&die->attrs[i]))
20484             fprintf_unfiltered (f, "flag: TRUE");
20485           else
20486             fprintf_unfiltered (f, "flag: FALSE");
20487           break;
20488         case DW_FORM_flag_present:
20489           fprintf_unfiltered (f, "flag: TRUE");
20490           break;
20491         case DW_FORM_indirect:
20492           /* The reader will have reduced the indirect form to
20493              the "base form" so this form should not occur.  */
20494           fprintf_unfiltered (f, 
20495                               "unexpected attribute form: DW_FORM_indirect");
20496           break;
20497         default:
20498           fprintf_unfiltered (f, "unsupported attribute form: %d.",
20499                    die->attrs[i].form);
20500           break;
20501         }
20502       fprintf_unfiltered (f, "\n");
20503     }
20504 }
20505
20506 static void
20507 dump_die_for_error (struct die_info *die)
20508 {
20509   dump_die_shallow (gdb_stderr, 0, die);
20510 }
20511
20512 static void
20513 dump_die_1 (struct ui_file *f, int level, int max_level, struct die_info *die)
20514 {
20515   int indent = level * 4;
20516
20517   gdb_assert (die != NULL);
20518
20519   if (level >= max_level)
20520     return;
20521
20522   dump_die_shallow (f, indent, die);
20523
20524   if (die->child != NULL)
20525     {
20526       print_spaces (indent, f);
20527       fprintf_unfiltered (f, "  Children:");
20528       if (level + 1 < max_level)
20529         {
20530           fprintf_unfiltered (f, "\n");
20531           dump_die_1 (f, level + 1, max_level, die->child);
20532         }
20533       else
20534         {
20535           fprintf_unfiltered (f,
20536                               " [not printed, max nesting level reached]\n");
20537         }
20538     }
20539
20540   if (die->sibling != NULL && level > 0)
20541     {
20542       dump_die_1 (f, level, max_level, die->sibling);
20543     }
20544 }
20545
20546 /* This is called from the pdie macro in gdbinit.in.
20547    It's not static so gcc will keep a copy callable from gdb.  */
20548
20549 void
20550 dump_die (struct die_info *die, int max_level)
20551 {
20552   dump_die_1 (gdb_stdlog, 0, max_level, die);
20553 }
20554
20555 static void
20556 store_in_ref_table (struct die_info *die, struct dwarf2_cu *cu)
20557 {
20558   void **slot;
20559
20560   slot = htab_find_slot_with_hash (cu->die_hash, die,
20561                                    to_underlying (die->sect_off),
20562                                    INSERT);
20563
20564   *slot = die;
20565 }
20566
20567 /* Return DIE offset of ATTR.  Return 0 with complaint if ATTR is not of the
20568    required kind.  */
20569
20570 static sect_offset
20571 dwarf2_get_ref_die_offset (const struct attribute *attr)
20572 {
20573   if (attr_form_is_ref (attr))
20574     return (sect_offset) DW_UNSND (attr);
20575
20576   complaint (&symfile_complaints,
20577              _("unsupported die ref attribute form: '%s'"),
20578              dwarf_form_name (attr->form));
20579   return {};
20580 }
20581
20582 /* Return the constant value held by ATTR.  Return DEFAULT_VALUE if
20583  * the value held by the attribute is not constant.  */
20584
20585 static LONGEST
20586 dwarf2_get_attr_constant_value (const struct attribute *attr, int default_value)
20587 {
20588   if (attr->form == DW_FORM_sdata)
20589     return DW_SND (attr);
20590   else if (attr->form == DW_FORM_udata
20591            || attr->form == DW_FORM_data1
20592            || attr->form == DW_FORM_data2
20593            || attr->form == DW_FORM_data4
20594            || attr->form == DW_FORM_data8)
20595     return DW_UNSND (attr);
20596   else
20597     {
20598       /* For DW_FORM_data16 see attr_form_is_constant.  */
20599       complaint (&symfile_complaints,
20600                  _("Attribute value is not a constant (%s)"),
20601                  dwarf_form_name (attr->form));
20602       return default_value;
20603     }
20604 }
20605
20606 /* Follow reference or signature attribute ATTR of SRC_DIE.
20607    On entry *REF_CU is the CU of SRC_DIE.
20608    On exit *REF_CU is the CU of the result.  */
20609
20610 static struct die_info *
20611 follow_die_ref_or_sig (struct die_info *src_die, const struct attribute *attr,
20612                        struct dwarf2_cu **ref_cu)
20613 {
20614   struct die_info *die;
20615
20616   if (attr_form_is_ref (attr))
20617     die = follow_die_ref (src_die, attr, ref_cu);
20618   else if (attr->form == DW_FORM_ref_sig8)
20619     die = follow_die_sig (src_die, attr, ref_cu);
20620   else
20621     {
20622       dump_die_for_error (src_die);
20623       error (_("Dwarf Error: Expected reference attribute [in module %s]"),
20624              objfile_name ((*ref_cu)->objfile));
20625     }
20626
20627   return die;
20628 }
20629
20630 /* Follow reference OFFSET.
20631    On entry *REF_CU is the CU of the source die referencing OFFSET.
20632    On exit *REF_CU is the CU of the result.
20633    Returns NULL if OFFSET is invalid.  */
20634
20635 static struct die_info *
20636 follow_die_offset (sect_offset sect_off, int offset_in_dwz,
20637                    struct dwarf2_cu **ref_cu)
20638 {
20639   struct die_info temp_die;
20640   struct dwarf2_cu *target_cu, *cu = *ref_cu;
20641
20642   gdb_assert (cu->per_cu != NULL);
20643
20644   target_cu = cu;
20645
20646   if (cu->per_cu->is_debug_types)
20647     {
20648       /* .debug_types CUs cannot reference anything outside their CU.
20649          If they need to, they have to reference a signatured type via
20650          DW_FORM_ref_sig8.  */
20651       if (!offset_in_cu_p (&cu->header, sect_off))
20652         return NULL;
20653     }
20654   else if (offset_in_dwz != cu->per_cu->is_dwz
20655            || !offset_in_cu_p (&cu->header, sect_off))
20656     {
20657       struct dwarf2_per_cu_data *per_cu;
20658
20659       per_cu = dwarf2_find_containing_comp_unit (sect_off, offset_in_dwz,
20660                                                  cu->objfile);
20661
20662       /* If necessary, add it to the queue and load its DIEs.  */
20663       if (maybe_queue_comp_unit (cu, per_cu, cu->language))
20664         load_full_comp_unit (per_cu, cu->language);
20665
20666       target_cu = per_cu->cu;
20667     }
20668   else if (cu->dies == NULL)
20669     {
20670       /* We're loading full DIEs during partial symbol reading.  */
20671       gdb_assert (dwarf2_per_objfile->reading_partial_symbols);
20672       load_full_comp_unit (cu->per_cu, language_minimal);
20673     }
20674
20675   *ref_cu = target_cu;
20676   temp_die.sect_off = sect_off;
20677   return (struct die_info *) htab_find_with_hash (target_cu->die_hash,
20678                                                   &temp_die,
20679                                                   to_underlying (sect_off));
20680 }
20681
20682 /* Follow reference attribute ATTR of SRC_DIE.
20683    On entry *REF_CU is the CU of SRC_DIE.
20684    On exit *REF_CU is the CU of the result.  */
20685
20686 static struct die_info *
20687 follow_die_ref (struct die_info *src_die, const struct attribute *attr,
20688                 struct dwarf2_cu **ref_cu)
20689 {
20690   sect_offset sect_off = dwarf2_get_ref_die_offset (attr);
20691   struct dwarf2_cu *cu = *ref_cu;
20692   struct die_info *die;
20693
20694   die = follow_die_offset (sect_off,
20695                            (attr->form == DW_FORM_GNU_ref_alt
20696                             || cu->per_cu->is_dwz),
20697                            ref_cu);
20698   if (!die)
20699     error (_("Dwarf Error: Cannot find DIE at 0x%x referenced from DIE "
20700            "at 0x%x [in module %s]"),
20701            to_underlying (sect_off), to_underlying (src_die->sect_off),
20702            objfile_name (cu->objfile));
20703
20704   return die;
20705 }
20706
20707 /* Return DWARF block referenced by DW_AT_location of DIE at SECT_OFF at PER_CU.
20708    Returned value is intended for DW_OP_call*.  Returned
20709    dwarf2_locexpr_baton->data has lifetime of PER_CU->OBJFILE.  */
20710
20711 struct dwarf2_locexpr_baton
20712 dwarf2_fetch_die_loc_sect_off (sect_offset sect_off,
20713                                struct dwarf2_per_cu_data *per_cu,
20714                                CORE_ADDR (*get_frame_pc) (void *baton),
20715                                void *baton)
20716 {
20717   struct dwarf2_cu *cu;
20718   struct die_info *die;
20719   struct attribute *attr;
20720   struct dwarf2_locexpr_baton retval;
20721
20722   dw2_setup (per_cu->objfile);
20723
20724   if (per_cu->cu == NULL)
20725     load_cu (per_cu);
20726   cu = per_cu->cu;
20727   if (cu == NULL)
20728     {
20729       /* We shouldn't get here for a dummy CU, but don't crash on the user.
20730          Instead just throw an error, not much else we can do.  */
20731       error (_("Dwarf Error: Dummy CU at 0x%x referenced in module %s"),
20732              to_underlying (sect_off), objfile_name (per_cu->objfile));
20733     }
20734
20735   die = follow_die_offset (sect_off, per_cu->is_dwz, &cu);
20736   if (!die)
20737     error (_("Dwarf Error: Cannot find DIE at 0x%x referenced in module %s"),
20738            to_underlying (sect_off), objfile_name (per_cu->objfile));
20739
20740   attr = dwarf2_attr (die, DW_AT_location, cu);
20741   if (!attr)
20742     {
20743       /* DWARF: "If there is no such attribute, then there is no effect.".
20744          DATA is ignored if SIZE is 0.  */
20745
20746       retval.data = NULL;
20747       retval.size = 0;
20748     }
20749   else if (attr_form_is_section_offset (attr))
20750     {
20751       struct dwarf2_loclist_baton loclist_baton;
20752       CORE_ADDR pc = (*get_frame_pc) (baton);
20753       size_t size;
20754
20755       fill_in_loclist_baton (cu, &loclist_baton, attr);
20756
20757       retval.data = dwarf2_find_location_expression (&loclist_baton,
20758                                                      &size, pc);
20759       retval.size = size;
20760     }
20761   else
20762     {
20763       if (!attr_form_is_block (attr))
20764         error (_("Dwarf Error: DIE at 0x%x referenced in module %s "
20765                  "is neither DW_FORM_block* nor DW_FORM_exprloc"),
20766                to_underlying (sect_off), objfile_name (per_cu->objfile));
20767
20768       retval.data = DW_BLOCK (attr)->data;
20769       retval.size = DW_BLOCK (attr)->size;
20770     }
20771   retval.per_cu = cu->per_cu;
20772
20773   age_cached_comp_units ();
20774
20775   return retval;
20776 }
20777
20778 /* Like dwarf2_fetch_die_loc_sect_off, but take a CU
20779    offset.  */
20780
20781 struct dwarf2_locexpr_baton
20782 dwarf2_fetch_die_loc_cu_off (cu_offset offset_in_cu,
20783                              struct dwarf2_per_cu_data *per_cu,
20784                              CORE_ADDR (*get_frame_pc) (void *baton),
20785                              void *baton)
20786 {
20787   sect_offset sect_off = per_cu->sect_off + to_underlying (offset_in_cu);
20788
20789   return dwarf2_fetch_die_loc_sect_off (sect_off, per_cu, get_frame_pc, baton);
20790 }
20791
20792 /* Write a constant of a given type as target-ordered bytes into
20793    OBSTACK.  */
20794
20795 static const gdb_byte *
20796 write_constant_as_bytes (struct obstack *obstack,
20797                          enum bfd_endian byte_order,
20798                          struct type *type,
20799                          ULONGEST value,
20800                          LONGEST *len)
20801 {
20802   gdb_byte *result;
20803
20804   *len = TYPE_LENGTH (type);
20805   result = (gdb_byte *) obstack_alloc (obstack, *len);
20806   store_unsigned_integer (result, *len, byte_order, value);
20807
20808   return result;
20809 }
20810
20811 /* If the DIE at OFFSET in PER_CU has a DW_AT_const_value, return a
20812    pointer to the constant bytes and set LEN to the length of the
20813    data.  If memory is needed, allocate it on OBSTACK.  If the DIE
20814    does not have a DW_AT_const_value, return NULL.  */
20815
20816 const gdb_byte *
20817 dwarf2_fetch_constant_bytes (sect_offset sect_off,
20818                              struct dwarf2_per_cu_data *per_cu,
20819                              struct obstack *obstack,
20820                              LONGEST *len)
20821 {
20822   struct dwarf2_cu *cu;
20823   struct die_info *die;
20824   struct attribute *attr;
20825   const gdb_byte *result = NULL;
20826   struct type *type;
20827   LONGEST value;
20828   enum bfd_endian byte_order;
20829
20830   dw2_setup (per_cu->objfile);
20831
20832   if (per_cu->cu == NULL)
20833     load_cu (per_cu);
20834   cu = per_cu->cu;
20835   if (cu == NULL)
20836     {
20837       /* We shouldn't get here for a dummy CU, but don't crash on the user.
20838          Instead just throw an error, not much else we can do.  */
20839       error (_("Dwarf Error: Dummy CU at 0x%x referenced in module %s"),
20840              to_underlying (sect_off), objfile_name (per_cu->objfile));
20841     }
20842
20843   die = follow_die_offset (sect_off, per_cu->is_dwz, &cu);
20844   if (!die)
20845     error (_("Dwarf Error: Cannot find DIE at 0x%x referenced in module %s"),
20846            to_underlying (sect_off), objfile_name (per_cu->objfile));
20847
20848
20849   attr = dwarf2_attr (die, DW_AT_const_value, cu);
20850   if (attr == NULL)
20851     return NULL;
20852
20853   byte_order = (bfd_big_endian (per_cu->objfile->obfd)
20854                 ? BFD_ENDIAN_BIG : BFD_ENDIAN_LITTLE);
20855
20856   switch (attr->form)
20857     {
20858     case DW_FORM_addr:
20859     case DW_FORM_GNU_addr_index:
20860       {
20861         gdb_byte *tem;
20862
20863         *len = cu->header.addr_size;
20864         tem = (gdb_byte *) obstack_alloc (obstack, *len);
20865         store_unsigned_integer (tem, *len, byte_order, DW_ADDR (attr));
20866         result = tem;
20867       }
20868       break;
20869     case DW_FORM_string:
20870     case DW_FORM_strp:
20871     case DW_FORM_GNU_str_index:
20872     case DW_FORM_GNU_strp_alt:
20873       /* DW_STRING is already allocated on the objfile obstack, point
20874          directly to it.  */
20875       result = (const gdb_byte *) DW_STRING (attr);
20876       *len = strlen (DW_STRING (attr));
20877       break;
20878     case DW_FORM_block1:
20879     case DW_FORM_block2:
20880     case DW_FORM_block4:
20881     case DW_FORM_block:
20882     case DW_FORM_exprloc:
20883     case DW_FORM_data16:
20884       result = DW_BLOCK (attr)->data;
20885       *len = DW_BLOCK (attr)->size;
20886       break;
20887
20888       /* The DW_AT_const_value attributes are supposed to carry the
20889          symbol's value "represented as it would be on the target
20890          architecture."  By the time we get here, it's already been
20891          converted to host endianness, so we just need to sign- or
20892          zero-extend it as appropriate.  */
20893     case DW_FORM_data1:
20894       type = die_type (die, cu);
20895       result = dwarf2_const_value_data (attr, obstack, cu, &value, 8);
20896       if (result == NULL)
20897         result = write_constant_as_bytes (obstack, byte_order,
20898                                           type, value, len);
20899       break;
20900     case DW_FORM_data2:
20901       type = die_type (die, cu);
20902       result = dwarf2_const_value_data (attr, obstack, cu, &value, 16);
20903       if (result == NULL)
20904         result = write_constant_as_bytes (obstack, byte_order,
20905                                           type, value, len);
20906       break;
20907     case DW_FORM_data4:
20908       type = die_type (die, cu);
20909       result = dwarf2_const_value_data (attr, obstack, cu, &value, 32);
20910       if (result == NULL)
20911         result = write_constant_as_bytes (obstack, byte_order,
20912                                           type, value, len);
20913       break;
20914     case DW_FORM_data8:
20915       type = die_type (die, cu);
20916       result = dwarf2_const_value_data (attr, obstack, cu, &value, 64);
20917       if (result == NULL)
20918         result = write_constant_as_bytes (obstack, byte_order,
20919                                           type, value, len);
20920       break;
20921
20922     case DW_FORM_sdata:
20923       type = die_type (die, cu);
20924       result = write_constant_as_bytes (obstack, byte_order,
20925                                         type, DW_SND (attr), len);
20926       break;
20927
20928     case DW_FORM_udata:
20929       type = die_type (die, cu);
20930       result = write_constant_as_bytes (obstack, byte_order,
20931                                         type, DW_UNSND (attr), len);
20932       break;
20933
20934     default:
20935       complaint (&symfile_complaints,
20936                  _("unsupported const value attribute form: '%s'"),
20937                  dwarf_form_name (attr->form));
20938       break;
20939     }
20940
20941   return result;
20942 }
20943
20944 /* Return the type of the die at OFFSET in PER_CU.  Return NULL if no
20945    valid type for this die is found.  */
20946
20947 struct type *
20948 dwarf2_fetch_die_type_sect_off (sect_offset sect_off,
20949                                 struct dwarf2_per_cu_data *per_cu)
20950 {
20951   struct dwarf2_cu *cu;
20952   struct die_info *die;
20953
20954   dw2_setup (per_cu->objfile);
20955
20956   if (per_cu->cu == NULL)
20957     load_cu (per_cu);
20958   cu = per_cu->cu;
20959   if (!cu)
20960     return NULL;
20961
20962   die = follow_die_offset (sect_off, per_cu->is_dwz, &cu);
20963   if (!die)
20964     return NULL;
20965
20966   return die_type (die, cu);
20967 }
20968
20969 /* Return the type of the DIE at DIE_OFFSET in the CU named by
20970    PER_CU.  */
20971
20972 struct type *
20973 dwarf2_get_die_type (cu_offset die_offset,
20974                      struct dwarf2_per_cu_data *per_cu)
20975 {
20976   dw2_setup (per_cu->objfile);
20977
20978   sect_offset die_offset_sect = per_cu->sect_off + to_underlying (die_offset);
20979   return get_die_type_at_offset (die_offset_sect, per_cu);
20980 }
20981
20982 /* Follow type unit SIG_TYPE referenced by SRC_DIE.
20983    On entry *REF_CU is the CU of SRC_DIE.
20984    On exit *REF_CU is the CU of the result.
20985    Returns NULL if the referenced DIE isn't found.  */
20986
20987 static struct die_info *
20988 follow_die_sig_1 (struct die_info *src_die, struct signatured_type *sig_type,
20989                   struct dwarf2_cu **ref_cu)
20990 {
20991   struct die_info temp_die;
20992   struct dwarf2_cu *sig_cu;
20993   struct die_info *die;
20994
20995   /* While it might be nice to assert sig_type->type == NULL here,
20996      we can get here for DW_AT_imported_declaration where we need
20997      the DIE not the type.  */
20998
20999   /* If necessary, add it to the queue and load its DIEs.  */
21000
21001   if (maybe_queue_comp_unit (*ref_cu, &sig_type->per_cu, language_minimal))
21002     read_signatured_type (sig_type);
21003
21004   sig_cu = sig_type->per_cu.cu;
21005   gdb_assert (sig_cu != NULL);
21006   gdb_assert (to_underlying (sig_type->type_offset_in_section) != 0);
21007   temp_die.sect_off = sig_type->type_offset_in_section;
21008   die = (struct die_info *) htab_find_with_hash (sig_cu->die_hash, &temp_die,
21009                                                  to_underlying (temp_die.sect_off));
21010   if (die)
21011     {
21012       /* For .gdb_index version 7 keep track of included TUs.
21013          http://sourceware.org/bugzilla/show_bug.cgi?id=15021.  */
21014       if (dwarf2_per_objfile->index_table != NULL
21015           && dwarf2_per_objfile->index_table->version <= 7)
21016         {
21017           VEC_safe_push (dwarf2_per_cu_ptr,
21018                          (*ref_cu)->per_cu->imported_symtabs,
21019                          sig_cu->per_cu);
21020         }
21021
21022       *ref_cu = sig_cu;
21023       return die;
21024     }
21025
21026   return NULL;
21027 }
21028
21029 /* Follow signatured type referenced by ATTR in SRC_DIE.
21030    On entry *REF_CU is the CU of SRC_DIE.
21031    On exit *REF_CU is the CU of the result.
21032    The result is the DIE of the type.
21033    If the referenced type cannot be found an error is thrown.  */
21034
21035 static struct die_info *
21036 follow_die_sig (struct die_info *src_die, const struct attribute *attr,
21037                 struct dwarf2_cu **ref_cu)
21038 {
21039   ULONGEST signature = DW_SIGNATURE (attr);
21040   struct signatured_type *sig_type;
21041   struct die_info *die;
21042
21043   gdb_assert (attr->form == DW_FORM_ref_sig8);
21044
21045   sig_type = lookup_signatured_type (*ref_cu, signature);
21046   /* sig_type will be NULL if the signatured type is missing from
21047      the debug info.  */
21048   if (sig_type == NULL)
21049     {
21050       error (_("Dwarf Error: Cannot find signatured DIE %s referenced"
21051                " from DIE at 0x%x [in module %s]"),
21052              hex_string (signature), to_underlying (src_die->sect_off),
21053              objfile_name ((*ref_cu)->objfile));
21054     }
21055
21056   die = follow_die_sig_1 (src_die, sig_type, ref_cu);
21057   if (die == NULL)
21058     {
21059       dump_die_for_error (src_die);
21060       error (_("Dwarf Error: Problem reading signatured DIE %s referenced"
21061                " from DIE at 0x%x [in module %s]"),
21062              hex_string (signature), to_underlying (src_die->sect_off),
21063              objfile_name ((*ref_cu)->objfile));
21064     }
21065
21066   return die;
21067 }
21068
21069 /* Get the type specified by SIGNATURE referenced in DIE/CU,
21070    reading in and processing the type unit if necessary.  */
21071
21072 static struct type *
21073 get_signatured_type (struct die_info *die, ULONGEST signature,
21074                      struct dwarf2_cu *cu)
21075 {
21076   struct signatured_type *sig_type;
21077   struct dwarf2_cu *type_cu;
21078   struct die_info *type_die;
21079   struct type *type;
21080
21081   sig_type = lookup_signatured_type (cu, signature);
21082   /* sig_type will be NULL if the signatured type is missing from
21083      the debug info.  */
21084   if (sig_type == NULL)
21085     {
21086       complaint (&symfile_complaints,
21087                  _("Dwarf Error: Cannot find signatured DIE %s referenced"
21088                    " from DIE at 0x%x [in module %s]"),
21089                  hex_string (signature), to_underlying (die->sect_off),
21090                  objfile_name (dwarf2_per_objfile->objfile));
21091       return build_error_marker_type (cu, die);
21092     }
21093
21094   /* If we already know the type we're done.  */
21095   if (sig_type->type != NULL)
21096     return sig_type->type;
21097
21098   type_cu = cu;
21099   type_die = follow_die_sig_1 (die, sig_type, &type_cu);
21100   if (type_die != NULL)
21101     {
21102       /* N.B. We need to call get_die_type to ensure only one type for this DIE
21103          is created.  This is important, for example, because for c++ classes
21104          we need TYPE_NAME set which is only done by new_symbol.  Blech.  */
21105       type = read_type_die (type_die, type_cu);
21106       if (type == NULL)
21107         {
21108           complaint (&symfile_complaints,
21109                      _("Dwarf Error: Cannot build signatured type %s"
21110                        " referenced from DIE at 0x%x [in module %s]"),
21111                      hex_string (signature), to_underlying (die->sect_off),
21112                      objfile_name (dwarf2_per_objfile->objfile));
21113           type = build_error_marker_type (cu, die);
21114         }
21115     }
21116   else
21117     {
21118       complaint (&symfile_complaints,
21119                  _("Dwarf Error: Problem reading signatured DIE %s referenced"
21120                    " from DIE at 0x%x [in module %s]"),
21121                  hex_string (signature), to_underlying (die->sect_off),
21122                  objfile_name (dwarf2_per_objfile->objfile));
21123       type = build_error_marker_type (cu, die);
21124     }
21125   sig_type->type = type;
21126
21127   return type;
21128 }
21129
21130 /* Get the type specified by the DW_AT_signature ATTR in DIE/CU,
21131    reading in and processing the type unit if necessary.  */
21132
21133 static struct type *
21134 get_DW_AT_signature_type (struct die_info *die, const struct attribute *attr,
21135                           struct dwarf2_cu *cu) /* ARI: editCase function */
21136 {
21137   /* Yes, DW_AT_signature can use a non-ref_sig8 reference.  */
21138   if (attr_form_is_ref (attr))
21139     {
21140       struct dwarf2_cu *type_cu = cu;
21141       struct die_info *type_die = follow_die_ref (die, attr, &type_cu);
21142
21143       return read_type_die (type_die, type_cu);
21144     }
21145   else if (attr->form == DW_FORM_ref_sig8)
21146     {
21147       return get_signatured_type (die, DW_SIGNATURE (attr), cu);
21148     }
21149   else
21150     {
21151       complaint (&symfile_complaints,
21152                  _("Dwarf Error: DW_AT_signature has bad form %s in DIE"
21153                    " at 0x%x [in module %s]"),
21154                  dwarf_form_name (attr->form), to_underlying (die->sect_off),
21155                  objfile_name (dwarf2_per_objfile->objfile));
21156       return build_error_marker_type (cu, die);
21157     }
21158 }
21159
21160 /* Load the DIEs associated with type unit PER_CU into memory.  */
21161
21162 static void
21163 load_full_type_unit (struct dwarf2_per_cu_data *per_cu)
21164 {
21165   struct signatured_type *sig_type;
21166
21167   /* Caller is responsible for ensuring type_unit_groups don't get here.  */
21168   gdb_assert (! IS_TYPE_UNIT_GROUP (per_cu));
21169
21170   /* We have the per_cu, but we need the signatured_type.
21171      Fortunately this is an easy translation.  */
21172   gdb_assert (per_cu->is_debug_types);
21173   sig_type = (struct signatured_type *) per_cu;
21174
21175   gdb_assert (per_cu->cu == NULL);
21176
21177   read_signatured_type (sig_type);
21178
21179   gdb_assert (per_cu->cu != NULL);
21180 }
21181
21182 /* die_reader_func for read_signatured_type.
21183    This is identical to load_full_comp_unit_reader,
21184    but is kept separate for now.  */
21185
21186 static void
21187 read_signatured_type_reader (const struct die_reader_specs *reader,
21188                              const gdb_byte *info_ptr,
21189                              struct die_info *comp_unit_die,
21190                              int has_children,
21191                              void *data)
21192 {
21193   struct dwarf2_cu *cu = reader->cu;
21194
21195   gdb_assert (cu->die_hash == NULL);
21196   cu->die_hash =
21197     htab_create_alloc_ex (cu->header.length / 12,
21198                           die_hash,
21199                           die_eq,
21200                           NULL,
21201                           &cu->comp_unit_obstack,
21202                           hashtab_obstack_allocate,
21203                           dummy_obstack_deallocate);
21204
21205   if (has_children)
21206     comp_unit_die->child = read_die_and_siblings (reader, info_ptr,
21207                                                   &info_ptr, comp_unit_die);
21208   cu->dies = comp_unit_die;
21209   /* comp_unit_die is not stored in die_hash, no need.  */
21210
21211   /* We try not to read any attributes in this function, because not
21212      all CUs needed for references have been loaded yet, and symbol
21213      table processing isn't initialized.  But we have to set the CU language,
21214      or we won't be able to build types correctly.
21215      Similarly, if we do not read the producer, we can not apply
21216      producer-specific interpretation.  */
21217   prepare_one_comp_unit (cu, cu->dies, language_minimal);
21218 }
21219
21220 /* Read in a signatured type and build its CU and DIEs.
21221    If the type is a stub for the real type in a DWO file,
21222    read in the real type from the DWO file as well.  */
21223
21224 static void
21225 read_signatured_type (struct signatured_type *sig_type)
21226 {
21227   struct dwarf2_per_cu_data *per_cu = &sig_type->per_cu;
21228
21229   gdb_assert (per_cu->is_debug_types);
21230   gdb_assert (per_cu->cu == NULL);
21231
21232   init_cutu_and_read_dies (per_cu, NULL, 0, 1,
21233                            read_signatured_type_reader, NULL);
21234   sig_type->per_cu.tu_read = 1;
21235 }
21236
21237 /* Decode simple location descriptions.
21238    Given a pointer to a dwarf block that defines a location, compute
21239    the location and return the value.
21240
21241    NOTE drow/2003-11-18: This function is called in two situations
21242    now: for the address of static or global variables (partial symbols
21243    only) and for offsets into structures which are expected to be
21244    (more or less) constant.  The partial symbol case should go away,
21245    and only the constant case should remain.  That will let this
21246    function complain more accurately.  A few special modes are allowed
21247    without complaint for global variables (for instance, global
21248    register values and thread-local values).
21249
21250    A location description containing no operations indicates that the
21251    object is optimized out.  The return value is 0 for that case.
21252    FIXME drow/2003-11-16: No callers check for this case any more; soon all
21253    callers will only want a very basic result and this can become a
21254    complaint.
21255
21256    Note that stack[0] is unused except as a default error return.  */
21257
21258 static CORE_ADDR
21259 decode_locdesc (struct dwarf_block *blk, struct dwarf2_cu *cu)
21260 {
21261   struct objfile *objfile = cu->objfile;
21262   size_t i;
21263   size_t size = blk->size;
21264   const gdb_byte *data = blk->data;
21265   CORE_ADDR stack[64];
21266   int stacki;
21267   unsigned int bytes_read, unsnd;
21268   gdb_byte op;
21269
21270   i = 0;
21271   stacki = 0;
21272   stack[stacki] = 0;
21273   stack[++stacki] = 0;
21274
21275   while (i < size)
21276     {
21277       op = data[i++];
21278       switch (op)
21279         {
21280         case DW_OP_lit0:
21281         case DW_OP_lit1:
21282         case DW_OP_lit2:
21283         case DW_OP_lit3:
21284         case DW_OP_lit4:
21285         case DW_OP_lit5:
21286         case DW_OP_lit6:
21287         case DW_OP_lit7:
21288         case DW_OP_lit8:
21289         case DW_OP_lit9:
21290         case DW_OP_lit10:
21291         case DW_OP_lit11:
21292         case DW_OP_lit12:
21293         case DW_OP_lit13:
21294         case DW_OP_lit14:
21295         case DW_OP_lit15:
21296         case DW_OP_lit16:
21297         case DW_OP_lit17:
21298         case DW_OP_lit18:
21299         case DW_OP_lit19:
21300         case DW_OP_lit20:
21301         case DW_OP_lit21:
21302         case DW_OP_lit22:
21303         case DW_OP_lit23:
21304         case DW_OP_lit24:
21305         case DW_OP_lit25:
21306         case DW_OP_lit26:
21307         case DW_OP_lit27:
21308         case DW_OP_lit28:
21309         case DW_OP_lit29:
21310         case DW_OP_lit30:
21311         case DW_OP_lit31:
21312           stack[++stacki] = op - DW_OP_lit0;
21313           break;
21314
21315         case DW_OP_reg0:
21316         case DW_OP_reg1:
21317         case DW_OP_reg2:
21318         case DW_OP_reg3:
21319         case DW_OP_reg4:
21320         case DW_OP_reg5:
21321         case DW_OP_reg6:
21322         case DW_OP_reg7:
21323         case DW_OP_reg8:
21324         case DW_OP_reg9:
21325         case DW_OP_reg10:
21326         case DW_OP_reg11:
21327         case DW_OP_reg12:
21328         case DW_OP_reg13:
21329         case DW_OP_reg14:
21330         case DW_OP_reg15:
21331         case DW_OP_reg16:
21332         case DW_OP_reg17:
21333         case DW_OP_reg18:
21334         case DW_OP_reg19:
21335         case DW_OP_reg20:
21336         case DW_OP_reg21:
21337         case DW_OP_reg22:
21338         case DW_OP_reg23:
21339         case DW_OP_reg24:
21340         case DW_OP_reg25:
21341         case DW_OP_reg26:
21342         case DW_OP_reg27:
21343         case DW_OP_reg28:
21344         case DW_OP_reg29:
21345         case DW_OP_reg30:
21346         case DW_OP_reg31:
21347           stack[++stacki] = op - DW_OP_reg0;
21348           if (i < size)
21349             dwarf2_complex_location_expr_complaint ();
21350           break;
21351
21352         case DW_OP_regx:
21353           unsnd = read_unsigned_leb128 (NULL, (data + i), &bytes_read);
21354           i += bytes_read;
21355           stack[++stacki] = unsnd;
21356           if (i < size)
21357             dwarf2_complex_location_expr_complaint ();
21358           break;
21359
21360         case DW_OP_addr:
21361           stack[++stacki] = read_address (objfile->obfd, &data[i],
21362                                           cu, &bytes_read);
21363           i += bytes_read;
21364           break;
21365
21366         case DW_OP_const1u:
21367           stack[++stacki] = read_1_byte (objfile->obfd, &data[i]);
21368           i += 1;
21369           break;
21370
21371         case DW_OP_const1s:
21372           stack[++stacki] = read_1_signed_byte (objfile->obfd, &data[i]);
21373           i += 1;
21374           break;
21375
21376         case DW_OP_const2u:
21377           stack[++stacki] = read_2_bytes (objfile->obfd, &data[i]);
21378           i += 2;
21379           break;
21380
21381         case DW_OP_const2s:
21382           stack[++stacki] = read_2_signed_bytes (objfile->obfd, &data[i]);
21383           i += 2;
21384           break;
21385
21386         case DW_OP_const4u:
21387           stack[++stacki] = read_4_bytes (objfile->obfd, &data[i]);
21388           i += 4;
21389           break;
21390
21391         case DW_OP_const4s:
21392           stack[++stacki] = read_4_signed_bytes (objfile->obfd, &data[i]);
21393           i += 4;
21394           break;
21395
21396         case DW_OP_const8u:
21397           stack[++stacki] = read_8_bytes (objfile->obfd, &data[i]);
21398           i += 8;
21399           break;
21400
21401         case DW_OP_constu:
21402           stack[++stacki] = read_unsigned_leb128 (NULL, (data + i),
21403                                                   &bytes_read);
21404           i += bytes_read;
21405           break;
21406
21407         case DW_OP_consts:
21408           stack[++stacki] = read_signed_leb128 (NULL, (data + i), &bytes_read);
21409           i += bytes_read;
21410           break;
21411
21412         case DW_OP_dup:
21413           stack[stacki + 1] = stack[stacki];
21414           stacki++;
21415           break;
21416
21417         case DW_OP_plus:
21418           stack[stacki - 1] += stack[stacki];
21419           stacki--;
21420           break;
21421
21422         case DW_OP_plus_uconst:
21423           stack[stacki] += read_unsigned_leb128 (NULL, (data + i),
21424                                                  &bytes_read);
21425           i += bytes_read;
21426           break;
21427
21428         case DW_OP_minus:
21429           stack[stacki - 1] -= stack[stacki];
21430           stacki--;
21431           break;
21432
21433         case DW_OP_deref:
21434           /* If we're not the last op, then we definitely can't encode
21435              this using GDB's address_class enum.  This is valid for partial
21436              global symbols, although the variable's address will be bogus
21437              in the psymtab.  */
21438           if (i < size)
21439             dwarf2_complex_location_expr_complaint ();
21440           break;
21441
21442         case DW_OP_GNU_push_tls_address:
21443         case DW_OP_form_tls_address:
21444           /* The top of the stack has the offset from the beginning
21445              of the thread control block at which the variable is located.  */
21446           /* Nothing should follow this operator, so the top of stack would
21447              be returned.  */
21448           /* This is valid for partial global symbols, but the variable's
21449              address will be bogus in the psymtab.  Make it always at least
21450              non-zero to not look as a variable garbage collected by linker
21451              which have DW_OP_addr 0.  */
21452           if (i < size)
21453             dwarf2_complex_location_expr_complaint ();
21454           stack[stacki]++;
21455           break;
21456
21457         case DW_OP_GNU_uninit:
21458           break;
21459
21460         case DW_OP_GNU_addr_index:
21461         case DW_OP_GNU_const_index:
21462           stack[++stacki] = read_addr_index_from_leb128 (cu, &data[i],
21463                                                          &bytes_read);
21464           i += bytes_read;
21465           break;
21466
21467         default:
21468           {
21469             const char *name = get_DW_OP_name (op);
21470
21471             if (name)
21472               complaint (&symfile_complaints, _("unsupported stack op: '%s'"),
21473                          name);
21474             else
21475               complaint (&symfile_complaints, _("unsupported stack op: '%02x'"),
21476                          op);
21477           }
21478
21479           return (stack[stacki]);
21480         }
21481
21482       /* Enforce maximum stack depth of SIZE-1 to avoid writing
21483          outside of the allocated space.  Also enforce minimum>0.  */
21484       if (stacki >= ARRAY_SIZE (stack) - 1)
21485         {
21486           complaint (&symfile_complaints,
21487                      _("location description stack overflow"));
21488           return 0;
21489         }
21490
21491       if (stacki <= 0)
21492         {
21493           complaint (&symfile_complaints,
21494                      _("location description stack underflow"));
21495           return 0;
21496         }
21497     }
21498   return (stack[stacki]);
21499 }
21500
21501 /* memory allocation interface */
21502
21503 static struct dwarf_block *
21504 dwarf_alloc_block (struct dwarf2_cu *cu)
21505 {
21506   return XOBNEW (&cu->comp_unit_obstack, struct dwarf_block);
21507 }
21508
21509 static struct die_info *
21510 dwarf_alloc_die (struct dwarf2_cu *cu, int num_attrs)
21511 {
21512   struct die_info *die;
21513   size_t size = sizeof (struct die_info);
21514
21515   if (num_attrs > 1)
21516     size += (num_attrs - 1) * sizeof (struct attribute);
21517
21518   die = (struct die_info *) obstack_alloc (&cu->comp_unit_obstack, size);
21519   memset (die, 0, sizeof (struct die_info));
21520   return (die);
21521 }
21522
21523 \f
21524 /* Macro support.  */
21525
21526 /* Return file name relative to the compilation directory of file number I in
21527    *LH's file name table.  The result is allocated using xmalloc; the caller is
21528    responsible for freeing it.  */
21529
21530 static char *
21531 file_file_name (int file, struct line_header *lh)
21532 {
21533   /* Is the file number a valid index into the line header's file name
21534      table?  Remember that file numbers start with one, not zero.  */
21535   if (1 <= file && file <= lh->file_names.size ())
21536     {
21537       const file_entry &fe = lh->file_names[file - 1];
21538
21539       if (!IS_ABSOLUTE_PATH (fe.name))
21540         {
21541           const char *dir = fe.include_dir (lh);
21542           if (dir != NULL)
21543             return concat (dir, SLASH_STRING, fe.name, (char *) NULL);
21544         }
21545       return xstrdup (fe.name);
21546     }
21547   else
21548     {
21549       /* The compiler produced a bogus file number.  We can at least
21550          record the macro definitions made in the file, even if we
21551          won't be able to find the file by name.  */
21552       char fake_name[80];
21553
21554       xsnprintf (fake_name, sizeof (fake_name),
21555                  "<bad macro file number %d>", file);
21556
21557       complaint (&symfile_complaints,
21558                  _("bad file number in macro information (%d)"),
21559                  file);
21560
21561       return xstrdup (fake_name);
21562     }
21563 }
21564
21565 /* Return the full name of file number I in *LH's file name table.
21566    Use COMP_DIR as the name of the current directory of the
21567    compilation.  The result is allocated using xmalloc; the caller is
21568    responsible for freeing it.  */
21569 static char *
21570 file_full_name (int file, struct line_header *lh, const char *comp_dir)
21571 {
21572   /* Is the file number a valid index into the line header's file name
21573      table?  Remember that file numbers start with one, not zero.  */
21574   if (1 <= file && file <= lh->file_names.size ())
21575     {
21576       char *relative = file_file_name (file, lh);
21577
21578       if (IS_ABSOLUTE_PATH (relative) || comp_dir == NULL)
21579         return relative;
21580       return reconcat (relative, comp_dir, SLASH_STRING,
21581                        relative, (char *) NULL);
21582     }
21583   else
21584     return file_file_name (file, lh);
21585 }
21586
21587
21588 static struct macro_source_file *
21589 macro_start_file (int file, int line,
21590                   struct macro_source_file *current_file,
21591                   struct line_header *lh)
21592 {
21593   /* File name relative to the compilation directory of this source file.  */
21594   char *file_name = file_file_name (file, lh);
21595
21596   if (! current_file)
21597     {
21598       /* Note: We don't create a macro table for this compilation unit
21599          at all until we actually get a filename.  */
21600       struct macro_table *macro_table = get_macro_table ();
21601
21602       /* If we have no current file, then this must be the start_file
21603          directive for the compilation unit's main source file.  */
21604       current_file = macro_set_main (macro_table, file_name);
21605       macro_define_special (macro_table);
21606     }
21607   else
21608     current_file = macro_include (current_file, line, file_name);
21609
21610   xfree (file_name);
21611
21612   return current_file;
21613 }
21614
21615
21616 /* Copy the LEN characters at BUF to a xmalloc'ed block of memory,
21617    followed by a null byte.  */
21618 static char *
21619 copy_string (const char *buf, int len)
21620 {
21621   char *s = (char *) xmalloc (len + 1);
21622
21623   memcpy (s, buf, len);
21624   s[len] = '\0';
21625   return s;
21626 }
21627
21628
21629 static const char *
21630 consume_improper_spaces (const char *p, const char *body)
21631 {
21632   if (*p == ' ')
21633     {
21634       complaint (&symfile_complaints,
21635                  _("macro definition contains spaces "
21636                    "in formal argument list:\n`%s'"),
21637                  body);
21638
21639       while (*p == ' ')
21640         p++;
21641     }
21642
21643   return p;
21644 }
21645
21646
21647 static void
21648 parse_macro_definition (struct macro_source_file *file, int line,
21649                         const char *body)
21650 {
21651   const char *p;
21652
21653   /* The body string takes one of two forms.  For object-like macro
21654      definitions, it should be:
21655
21656         <macro name> " " <definition>
21657
21658      For function-like macro definitions, it should be:
21659
21660         <macro name> "() " <definition>
21661      or
21662         <macro name> "(" <arg name> ( "," <arg name> ) * ") " <definition>
21663
21664      Spaces may appear only where explicitly indicated, and in the
21665      <definition>.
21666
21667      The Dwarf 2 spec says that an object-like macro's name is always
21668      followed by a space, but versions of GCC around March 2002 omit
21669      the space when the macro's definition is the empty string.
21670
21671      The Dwarf 2 spec says that there should be no spaces between the
21672      formal arguments in a function-like macro's formal argument list,
21673      but versions of GCC around March 2002 include spaces after the
21674      commas.  */
21675
21676
21677   /* Find the extent of the macro name.  The macro name is terminated
21678      by either a space or null character (for an object-like macro) or
21679      an opening paren (for a function-like macro).  */
21680   for (p = body; *p; p++)
21681     if (*p == ' ' || *p == '(')
21682       break;
21683
21684   if (*p == ' ' || *p == '\0')
21685     {
21686       /* It's an object-like macro.  */
21687       int name_len = p - body;
21688       char *name = copy_string (body, name_len);
21689       const char *replacement;
21690
21691       if (*p == ' ')
21692         replacement = body + name_len + 1;
21693       else
21694         {
21695           dwarf2_macro_malformed_definition_complaint (body);
21696           replacement = body + name_len;
21697         }
21698
21699       macro_define_object (file, line, name, replacement);
21700
21701       xfree (name);
21702     }
21703   else if (*p == '(')
21704     {
21705       /* It's a function-like macro.  */
21706       char *name = copy_string (body, p - body);
21707       int argc = 0;
21708       int argv_size = 1;
21709       char **argv = XNEWVEC (char *, argv_size);
21710
21711       p++;
21712
21713       p = consume_improper_spaces (p, body);
21714
21715       /* Parse the formal argument list.  */
21716       while (*p && *p != ')')
21717         {
21718           /* Find the extent of the current argument name.  */
21719           const char *arg_start = p;
21720
21721           while (*p && *p != ',' && *p != ')' && *p != ' ')
21722             p++;
21723
21724           if (! *p || p == arg_start)
21725             dwarf2_macro_malformed_definition_complaint (body);
21726           else
21727             {
21728               /* Make sure argv has room for the new argument.  */
21729               if (argc >= argv_size)
21730                 {
21731                   argv_size *= 2;
21732                   argv = XRESIZEVEC (char *, argv, argv_size);
21733                 }
21734
21735               argv[argc++] = copy_string (arg_start, p - arg_start);
21736             }
21737
21738           p = consume_improper_spaces (p, body);
21739
21740           /* Consume the comma, if present.  */
21741           if (*p == ',')
21742             {
21743               p++;
21744
21745               p = consume_improper_spaces (p, body);
21746             }
21747         }
21748
21749       if (*p == ')')
21750         {
21751           p++;
21752
21753           if (*p == ' ')
21754             /* Perfectly formed definition, no complaints.  */
21755             macro_define_function (file, line, name,
21756                                    argc, (const char **) argv,
21757                                    p + 1);
21758           else if (*p == '\0')
21759             {
21760               /* Complain, but do define it.  */
21761               dwarf2_macro_malformed_definition_complaint (body);
21762               macro_define_function (file, line, name,
21763                                      argc, (const char **) argv,
21764                                      p);
21765             }
21766           else
21767             /* Just complain.  */
21768             dwarf2_macro_malformed_definition_complaint (body);
21769         }
21770       else
21771         /* Just complain.  */
21772         dwarf2_macro_malformed_definition_complaint (body);
21773
21774       xfree (name);
21775       {
21776         int i;
21777
21778         for (i = 0; i < argc; i++)
21779           xfree (argv[i]);
21780       }
21781       xfree (argv);
21782     }
21783   else
21784     dwarf2_macro_malformed_definition_complaint (body);
21785 }
21786
21787 /* Skip some bytes from BYTES according to the form given in FORM.
21788    Returns the new pointer.  */
21789
21790 static const gdb_byte *
21791 skip_form_bytes (bfd *abfd, const gdb_byte *bytes, const gdb_byte *buffer_end,
21792                  enum dwarf_form form,
21793                  unsigned int offset_size,
21794                  struct dwarf2_section_info *section)
21795 {
21796   unsigned int bytes_read;
21797
21798   switch (form)
21799     {
21800     case DW_FORM_data1:
21801     case DW_FORM_flag:
21802       ++bytes;
21803       break;
21804
21805     case DW_FORM_data2:
21806       bytes += 2;
21807       break;
21808
21809     case DW_FORM_data4:
21810       bytes += 4;
21811       break;
21812
21813     case DW_FORM_data8:
21814       bytes += 8;
21815       break;
21816
21817     case DW_FORM_data16:
21818       bytes += 16;
21819       break;
21820
21821     case DW_FORM_string:
21822       read_direct_string (abfd, bytes, &bytes_read);
21823       bytes += bytes_read;
21824       break;
21825
21826     case DW_FORM_sec_offset:
21827     case DW_FORM_strp:
21828     case DW_FORM_GNU_strp_alt:
21829       bytes += offset_size;
21830       break;
21831
21832     case DW_FORM_block:
21833       bytes += read_unsigned_leb128 (abfd, bytes, &bytes_read);
21834       bytes += bytes_read;
21835       break;
21836
21837     case DW_FORM_block1:
21838       bytes += 1 + read_1_byte (abfd, bytes);
21839       break;
21840     case DW_FORM_block2:
21841       bytes += 2 + read_2_bytes (abfd, bytes);
21842       break;
21843     case DW_FORM_block4:
21844       bytes += 4 + read_4_bytes (abfd, bytes);
21845       break;
21846
21847     case DW_FORM_sdata:
21848     case DW_FORM_udata:
21849     case DW_FORM_GNU_addr_index:
21850     case DW_FORM_GNU_str_index:
21851       bytes = gdb_skip_leb128 (bytes, buffer_end);
21852       if (bytes == NULL)
21853         {
21854           dwarf2_section_buffer_overflow_complaint (section);
21855           return NULL;
21856         }
21857       break;
21858
21859     default:
21860       {
21861       complain:
21862         complaint (&symfile_complaints,
21863                    _("invalid form 0x%x in `%s'"),
21864                    form, get_section_name (section));
21865         return NULL;
21866       }
21867     }
21868
21869   return bytes;
21870 }
21871
21872 /* A helper for dwarf_decode_macros that handles skipping an unknown
21873    opcode.  Returns an updated pointer to the macro data buffer; or,
21874    on error, issues a complaint and returns NULL.  */
21875
21876 static const gdb_byte *
21877 skip_unknown_opcode (unsigned int opcode,
21878                      const gdb_byte **opcode_definitions,
21879                      const gdb_byte *mac_ptr, const gdb_byte *mac_end,
21880                      bfd *abfd,
21881                      unsigned int offset_size,
21882                      struct dwarf2_section_info *section)
21883 {
21884   unsigned int bytes_read, i;
21885   unsigned long arg;
21886   const gdb_byte *defn;
21887
21888   if (opcode_definitions[opcode] == NULL)
21889     {
21890       complaint (&symfile_complaints,
21891                  _("unrecognized DW_MACFINO opcode 0x%x"),
21892                  opcode);
21893       return NULL;
21894     }
21895
21896   defn = opcode_definitions[opcode];
21897   arg = read_unsigned_leb128 (abfd, defn, &bytes_read);
21898   defn += bytes_read;
21899
21900   for (i = 0; i < arg; ++i)
21901     {
21902       mac_ptr = skip_form_bytes (abfd, mac_ptr, mac_end,
21903                                  (enum dwarf_form) defn[i], offset_size,
21904                                  section);
21905       if (mac_ptr == NULL)
21906         {
21907           /* skip_form_bytes already issued the complaint.  */
21908           return NULL;
21909         }
21910     }
21911
21912   return mac_ptr;
21913 }
21914
21915 /* A helper function which parses the header of a macro section.
21916    If the macro section is the extended (for now called "GNU") type,
21917    then this updates *OFFSET_SIZE.  Returns a pointer to just after
21918    the header, or issues a complaint and returns NULL on error.  */
21919
21920 static const gdb_byte *
21921 dwarf_parse_macro_header (const gdb_byte **opcode_definitions,
21922                           bfd *abfd,
21923                           const gdb_byte *mac_ptr,
21924                           unsigned int *offset_size,
21925                           int section_is_gnu)
21926 {
21927   memset (opcode_definitions, 0, 256 * sizeof (gdb_byte *));
21928
21929   if (section_is_gnu)
21930     {
21931       unsigned int version, flags;
21932
21933       version = read_2_bytes (abfd, mac_ptr);
21934       if (version != 4 && version != 5)
21935         {
21936           complaint (&symfile_complaints,
21937                      _("unrecognized version `%d' in .debug_macro section"),
21938                      version);
21939           return NULL;
21940         }
21941       mac_ptr += 2;
21942
21943       flags = read_1_byte (abfd, mac_ptr);
21944       ++mac_ptr;
21945       *offset_size = (flags & 1) ? 8 : 4;
21946
21947       if ((flags & 2) != 0)
21948         /* We don't need the line table offset.  */
21949         mac_ptr += *offset_size;
21950
21951       /* Vendor opcode descriptions.  */
21952       if ((flags & 4) != 0)
21953         {
21954           unsigned int i, count;
21955
21956           count = read_1_byte (abfd, mac_ptr);
21957           ++mac_ptr;
21958           for (i = 0; i < count; ++i)
21959             {
21960               unsigned int opcode, bytes_read;
21961               unsigned long arg;
21962
21963               opcode = read_1_byte (abfd, mac_ptr);
21964               ++mac_ptr;
21965               opcode_definitions[opcode] = mac_ptr;
21966               arg = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
21967               mac_ptr += bytes_read;
21968               mac_ptr += arg;
21969             }
21970         }
21971     }
21972
21973   return mac_ptr;
21974 }
21975
21976 /* A helper for dwarf_decode_macros that handles the GNU extensions,
21977    including DW_MACRO_import.  */
21978
21979 static void
21980 dwarf_decode_macro_bytes (bfd *abfd,
21981                           const gdb_byte *mac_ptr, const gdb_byte *mac_end,
21982                           struct macro_source_file *current_file,
21983                           struct line_header *lh,
21984                           struct dwarf2_section_info *section,
21985                           int section_is_gnu, int section_is_dwz,
21986                           unsigned int offset_size,
21987                           htab_t include_hash)
21988 {
21989   struct objfile *objfile = dwarf2_per_objfile->objfile;
21990   enum dwarf_macro_record_type macinfo_type;
21991   int at_commandline;
21992   const gdb_byte *opcode_definitions[256];
21993
21994   mac_ptr = dwarf_parse_macro_header (opcode_definitions, abfd, mac_ptr,
21995                                       &offset_size, section_is_gnu);
21996   if (mac_ptr == NULL)
21997     {
21998       /* We already issued a complaint.  */
21999       return;
22000     }
22001
22002   /* Determines if GDB is still before first DW_MACINFO_start_file.  If true
22003      GDB is still reading the definitions from command line.  First
22004      DW_MACINFO_start_file will need to be ignored as it was already executed
22005      to create CURRENT_FILE for the main source holding also the command line
22006      definitions.  On first met DW_MACINFO_start_file this flag is reset to
22007      normally execute all the remaining DW_MACINFO_start_file macinfos.  */
22008
22009   at_commandline = 1;
22010
22011   do
22012     {
22013       /* Do we at least have room for a macinfo type byte?  */
22014       if (mac_ptr >= mac_end)
22015         {
22016           dwarf2_section_buffer_overflow_complaint (section);
22017           break;
22018         }
22019
22020       macinfo_type = (enum dwarf_macro_record_type) read_1_byte (abfd, mac_ptr);
22021       mac_ptr++;
22022
22023       /* Note that we rely on the fact that the corresponding GNU and
22024          DWARF constants are the same.  */
22025       switch (macinfo_type)
22026         {
22027           /* A zero macinfo type indicates the end of the macro
22028              information.  */
22029         case 0:
22030           break;
22031
22032         case DW_MACRO_define:
22033         case DW_MACRO_undef:
22034         case DW_MACRO_define_strp:
22035         case DW_MACRO_undef_strp:
22036         case DW_MACRO_define_sup:
22037         case DW_MACRO_undef_sup:
22038           {
22039             unsigned int bytes_read;
22040             int line;
22041             const char *body;
22042             int is_define;
22043
22044             line = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
22045             mac_ptr += bytes_read;
22046
22047             if (macinfo_type == DW_MACRO_define
22048                 || macinfo_type == DW_MACRO_undef)
22049               {
22050                 body = read_direct_string (abfd, mac_ptr, &bytes_read);
22051                 mac_ptr += bytes_read;
22052               }
22053             else
22054               {
22055                 LONGEST str_offset;
22056
22057                 str_offset = read_offset_1 (abfd, mac_ptr, offset_size);
22058                 mac_ptr += offset_size;
22059
22060                 if (macinfo_type == DW_MACRO_define_sup
22061                     || macinfo_type == DW_MACRO_undef_sup
22062                     || section_is_dwz)
22063                   {
22064                     struct dwz_file *dwz = dwarf2_get_dwz_file ();
22065
22066                     body = read_indirect_string_from_dwz (dwz, str_offset);
22067                   }
22068                 else
22069                   body = read_indirect_string_at_offset (abfd, str_offset);
22070               }
22071
22072             is_define = (macinfo_type == DW_MACRO_define
22073                          || macinfo_type == DW_MACRO_define_strp
22074                          || macinfo_type == DW_MACRO_define_sup);
22075             if (! current_file)
22076               {
22077                 /* DWARF violation as no main source is present.  */
22078                 complaint (&symfile_complaints,
22079                            _("debug info with no main source gives macro %s "
22080                              "on line %d: %s"),
22081                            is_define ? _("definition") : _("undefinition"),
22082                            line, body);
22083                 break;
22084               }
22085             if ((line == 0 && !at_commandline)
22086                 || (line != 0 && at_commandline))
22087               complaint (&symfile_complaints,
22088                          _("debug info gives %s macro %s with %s line %d: %s"),
22089                          at_commandline ? _("command-line") : _("in-file"),
22090                          is_define ? _("definition") : _("undefinition"),
22091                          line == 0 ? _("zero") : _("non-zero"), line, body);
22092
22093             if (is_define)
22094               parse_macro_definition (current_file, line, body);
22095             else
22096               {
22097                 gdb_assert (macinfo_type == DW_MACRO_undef
22098                             || macinfo_type == DW_MACRO_undef_strp
22099                             || macinfo_type == DW_MACRO_undef_sup);
22100                 macro_undef (current_file, line, body);
22101               }
22102           }
22103           break;
22104
22105         case DW_MACRO_start_file:
22106           {
22107             unsigned int bytes_read;
22108             int line, file;
22109
22110             line = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
22111             mac_ptr += bytes_read;
22112             file = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
22113             mac_ptr += bytes_read;
22114
22115             if ((line == 0 && !at_commandline)
22116                 || (line != 0 && at_commandline))
22117               complaint (&symfile_complaints,
22118                          _("debug info gives source %d included "
22119                            "from %s at %s line %d"),
22120                          file, at_commandline ? _("command-line") : _("file"),
22121                          line == 0 ? _("zero") : _("non-zero"), line);
22122
22123             if (at_commandline)
22124               {
22125                 /* This DW_MACRO_start_file was executed in the
22126                    pass one.  */
22127                 at_commandline = 0;
22128               }
22129             else
22130               current_file = macro_start_file (file, line, current_file, lh);
22131           }
22132           break;
22133
22134         case DW_MACRO_end_file:
22135           if (! current_file)
22136             complaint (&symfile_complaints,
22137                        _("macro debug info has an unmatched "
22138                          "`close_file' directive"));
22139           else
22140             {
22141               current_file = current_file->included_by;
22142               if (! current_file)
22143                 {
22144                   enum dwarf_macro_record_type next_type;
22145
22146                   /* GCC circa March 2002 doesn't produce the zero
22147                      type byte marking the end of the compilation
22148                      unit.  Complain if it's not there, but exit no
22149                      matter what.  */
22150
22151                   /* Do we at least have room for a macinfo type byte?  */
22152                   if (mac_ptr >= mac_end)
22153                     {
22154                       dwarf2_section_buffer_overflow_complaint (section);
22155                       return;
22156                     }
22157
22158                   /* We don't increment mac_ptr here, so this is just
22159                      a look-ahead.  */
22160                   next_type
22161                     = (enum dwarf_macro_record_type) read_1_byte (abfd,
22162                                                                   mac_ptr);
22163                   if (next_type != 0)
22164                     complaint (&symfile_complaints,
22165                                _("no terminating 0-type entry for "
22166                                  "macros in `.debug_macinfo' section"));
22167
22168                   return;
22169                 }
22170             }
22171           break;
22172
22173         case DW_MACRO_import:
22174         case DW_MACRO_import_sup:
22175           {
22176             LONGEST offset;
22177             void **slot;
22178             bfd *include_bfd = abfd;
22179             struct dwarf2_section_info *include_section = section;
22180             const gdb_byte *include_mac_end = mac_end;
22181             int is_dwz = section_is_dwz;
22182             const gdb_byte *new_mac_ptr;
22183
22184             offset = read_offset_1 (abfd, mac_ptr, offset_size);
22185             mac_ptr += offset_size;
22186
22187             if (macinfo_type == DW_MACRO_import_sup)
22188               {
22189                 struct dwz_file *dwz = dwarf2_get_dwz_file ();
22190
22191                 dwarf2_read_section (objfile, &dwz->macro);
22192
22193                 include_section = &dwz->macro;
22194                 include_bfd = get_section_bfd_owner (include_section);
22195                 include_mac_end = dwz->macro.buffer + dwz->macro.size;
22196                 is_dwz = 1;
22197               }
22198
22199             new_mac_ptr = include_section->buffer + offset;
22200             slot = htab_find_slot (include_hash, new_mac_ptr, INSERT);
22201
22202             if (*slot != NULL)
22203               {
22204                 /* This has actually happened; see
22205                    http://sourceware.org/bugzilla/show_bug.cgi?id=13568.  */
22206                 complaint (&symfile_complaints,
22207                            _("recursive DW_MACRO_import in "
22208                              ".debug_macro section"));
22209               }
22210             else
22211               {
22212                 *slot = (void *) new_mac_ptr;
22213
22214                 dwarf_decode_macro_bytes (include_bfd, new_mac_ptr,
22215                                           include_mac_end, current_file, lh,
22216                                           section, section_is_gnu, is_dwz,
22217                                           offset_size, include_hash);
22218
22219                 htab_remove_elt (include_hash, (void *) new_mac_ptr);
22220               }
22221           }
22222           break;
22223
22224         case DW_MACINFO_vendor_ext:
22225           if (!section_is_gnu)
22226             {
22227               unsigned int bytes_read;
22228
22229               /* This reads the constant, but since we don't recognize
22230                  any vendor extensions, we ignore it.  */
22231               read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
22232               mac_ptr += bytes_read;
22233               read_direct_string (abfd, mac_ptr, &bytes_read);
22234               mac_ptr += bytes_read;
22235
22236               /* We don't recognize any vendor extensions.  */
22237               break;
22238             }
22239           /* FALLTHROUGH */
22240
22241         default:
22242           mac_ptr = skip_unknown_opcode (macinfo_type, opcode_definitions,
22243                                          mac_ptr, mac_end, abfd, offset_size,
22244                                          section);
22245           if (mac_ptr == NULL)
22246             return;
22247           break;
22248         }
22249     } while (macinfo_type != 0);
22250 }
22251
22252 static void
22253 dwarf_decode_macros (struct dwarf2_cu *cu, unsigned int offset,
22254                      int section_is_gnu)
22255 {
22256   struct objfile *objfile = dwarf2_per_objfile->objfile;
22257   struct line_header *lh = cu->line_header;
22258   bfd *abfd;
22259   const gdb_byte *mac_ptr, *mac_end;
22260   struct macro_source_file *current_file = 0;
22261   enum dwarf_macro_record_type macinfo_type;
22262   unsigned int offset_size = cu->header.offset_size;
22263   const gdb_byte *opcode_definitions[256];
22264   struct cleanup *cleanup;
22265   void **slot;
22266   struct dwarf2_section_info *section;
22267   const char *section_name;
22268
22269   if (cu->dwo_unit != NULL)
22270     {
22271       if (section_is_gnu)
22272         {
22273           section = &cu->dwo_unit->dwo_file->sections.macro;
22274           section_name = ".debug_macro.dwo";
22275         }
22276       else
22277         {
22278           section = &cu->dwo_unit->dwo_file->sections.macinfo;
22279           section_name = ".debug_macinfo.dwo";
22280         }
22281     }
22282   else
22283     {
22284       if (section_is_gnu)
22285         {
22286           section = &dwarf2_per_objfile->macro;
22287           section_name = ".debug_macro";
22288         }
22289       else
22290         {
22291           section = &dwarf2_per_objfile->macinfo;
22292           section_name = ".debug_macinfo";
22293         }
22294     }
22295
22296   dwarf2_read_section (objfile, section);
22297   if (section->buffer == NULL)
22298     {
22299       complaint (&symfile_complaints, _("missing %s section"), section_name);
22300       return;
22301     }
22302   abfd = get_section_bfd_owner (section);
22303
22304   /* First pass: Find the name of the base filename.
22305      This filename is needed in order to process all macros whose definition
22306      (or undefinition) comes from the command line.  These macros are defined
22307      before the first DW_MACINFO_start_file entry, and yet still need to be
22308      associated to the base file.
22309
22310      To determine the base file name, we scan the macro definitions until we
22311      reach the first DW_MACINFO_start_file entry.  We then initialize
22312      CURRENT_FILE accordingly so that any macro definition found before the
22313      first DW_MACINFO_start_file can still be associated to the base file.  */
22314
22315   mac_ptr = section->buffer + offset;
22316   mac_end = section->buffer + section->size;
22317
22318   mac_ptr = dwarf_parse_macro_header (opcode_definitions, abfd, mac_ptr,
22319                                       &offset_size, section_is_gnu);
22320   if (mac_ptr == NULL)
22321     {
22322       /* We already issued a complaint.  */
22323       return;
22324     }
22325
22326   do
22327     {
22328       /* Do we at least have room for a macinfo type byte?  */
22329       if (mac_ptr >= mac_end)
22330         {
22331           /* Complaint is printed during the second pass as GDB will probably
22332              stop the first pass earlier upon finding
22333              DW_MACINFO_start_file.  */
22334           break;
22335         }
22336
22337       macinfo_type = (enum dwarf_macro_record_type) read_1_byte (abfd, mac_ptr);
22338       mac_ptr++;
22339
22340       /* Note that we rely on the fact that the corresponding GNU and
22341          DWARF constants are the same.  */
22342       switch (macinfo_type)
22343         {
22344           /* A zero macinfo type indicates the end of the macro
22345              information.  */
22346         case 0:
22347           break;
22348
22349         case DW_MACRO_define:
22350         case DW_MACRO_undef:
22351           /* Only skip the data by MAC_PTR.  */
22352           {
22353             unsigned int bytes_read;
22354
22355             read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
22356             mac_ptr += bytes_read;
22357             read_direct_string (abfd, mac_ptr, &bytes_read);
22358             mac_ptr += bytes_read;
22359           }
22360           break;
22361
22362         case DW_MACRO_start_file:
22363           {
22364             unsigned int bytes_read;
22365             int line, file;
22366
22367             line = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
22368             mac_ptr += bytes_read;
22369             file = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
22370             mac_ptr += bytes_read;
22371
22372             current_file = macro_start_file (file, line, current_file, lh);
22373           }
22374           break;
22375
22376         case DW_MACRO_end_file:
22377           /* No data to skip by MAC_PTR.  */
22378           break;
22379
22380         case DW_MACRO_define_strp:
22381         case DW_MACRO_undef_strp:
22382         case DW_MACRO_define_sup:
22383         case DW_MACRO_undef_sup:
22384           {
22385             unsigned int bytes_read;
22386
22387             read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
22388             mac_ptr += bytes_read;
22389             mac_ptr += offset_size;
22390           }
22391           break;
22392
22393         case DW_MACRO_import:
22394         case DW_MACRO_import_sup:
22395           /* Note that, according to the spec, a transparent include
22396              chain cannot call DW_MACRO_start_file.  So, we can just
22397              skip this opcode.  */
22398           mac_ptr += offset_size;
22399           break;
22400
22401         case DW_MACINFO_vendor_ext:
22402           /* Only skip the data by MAC_PTR.  */
22403           if (!section_is_gnu)
22404             {
22405               unsigned int bytes_read;
22406
22407               read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
22408               mac_ptr += bytes_read;
22409               read_direct_string (abfd, mac_ptr, &bytes_read);
22410               mac_ptr += bytes_read;
22411             }
22412           /* FALLTHROUGH */
22413
22414         default:
22415           mac_ptr = skip_unknown_opcode (macinfo_type, opcode_definitions,
22416                                          mac_ptr, mac_end, abfd, offset_size,
22417                                          section);
22418           if (mac_ptr == NULL)
22419             return;
22420           break;
22421         }
22422     } while (macinfo_type != 0 && current_file == NULL);
22423
22424   /* Second pass: Process all entries.
22425
22426      Use the AT_COMMAND_LINE flag to determine whether we are still processing
22427      command-line macro definitions/undefinitions.  This flag is unset when we
22428      reach the first DW_MACINFO_start_file entry.  */
22429
22430   htab_up include_hash (htab_create_alloc (1, htab_hash_pointer,
22431                                            htab_eq_pointer,
22432                                            NULL, xcalloc, xfree));
22433   mac_ptr = section->buffer + offset;
22434   slot = htab_find_slot (include_hash.get (), mac_ptr, INSERT);
22435   *slot = (void *) mac_ptr;
22436   dwarf_decode_macro_bytes (abfd, mac_ptr, mac_end,
22437                             current_file, lh, section,
22438                             section_is_gnu, 0, offset_size,
22439                             include_hash.get ());
22440 }
22441
22442 /* Check if the attribute's form is a DW_FORM_block*
22443    if so return true else false.  */
22444
22445 static int
22446 attr_form_is_block (const struct attribute *attr)
22447 {
22448   return (attr == NULL ? 0 :
22449       attr->form == DW_FORM_block1
22450       || attr->form == DW_FORM_block2
22451       || attr->form == DW_FORM_block4
22452       || attr->form == DW_FORM_block
22453       || attr->form == DW_FORM_exprloc);
22454 }
22455
22456 /* Return non-zero if ATTR's value is a section offset --- classes
22457    lineptr, loclistptr, macptr or rangelistptr --- or zero, otherwise.
22458    You may use DW_UNSND (attr) to retrieve such offsets.
22459
22460    Section 7.5.4, "Attribute Encodings", explains that no attribute
22461    may have a value that belongs to more than one of these classes; it
22462    would be ambiguous if we did, because we use the same forms for all
22463    of them.  */
22464
22465 static int
22466 attr_form_is_section_offset (const struct attribute *attr)
22467 {
22468   return (attr->form == DW_FORM_data4
22469           || attr->form == DW_FORM_data8
22470           || attr->form == DW_FORM_sec_offset);
22471 }
22472
22473 /* Return non-zero if ATTR's value falls in the 'constant' class, or
22474    zero otherwise.  When this function returns true, you can apply
22475    dwarf2_get_attr_constant_value to it.
22476
22477    However, note that for some attributes you must check
22478    attr_form_is_section_offset before using this test.  DW_FORM_data4
22479    and DW_FORM_data8 are members of both the constant class, and of
22480    the classes that contain offsets into other debug sections
22481    (lineptr, loclistptr, macptr or rangelistptr).  The DWARF spec says
22482    that, if an attribute's can be either a constant or one of the
22483    section offset classes, DW_FORM_data4 and DW_FORM_data8 should be
22484    taken as section offsets, not constants.
22485
22486    DW_FORM_data16 is not considered as dwarf2_get_attr_constant_value
22487    cannot handle that.  */
22488
22489 static int
22490 attr_form_is_constant (const struct attribute *attr)
22491 {
22492   switch (attr->form)
22493     {
22494     case DW_FORM_sdata:
22495     case DW_FORM_udata:
22496     case DW_FORM_data1:
22497     case DW_FORM_data2:
22498     case DW_FORM_data4:
22499     case DW_FORM_data8:
22500       return 1;
22501     default:
22502       return 0;
22503     }
22504 }
22505
22506
22507 /* DW_ADDR is always stored already as sect_offset; despite for the forms
22508    besides DW_FORM_ref_addr it is stored as cu_offset in the DWARF file.  */
22509
22510 static int
22511 attr_form_is_ref (const struct attribute *attr)
22512 {
22513   switch (attr->form)
22514     {
22515     case DW_FORM_ref_addr:
22516     case DW_FORM_ref1:
22517     case DW_FORM_ref2:
22518     case DW_FORM_ref4:
22519     case DW_FORM_ref8:
22520     case DW_FORM_ref_udata:
22521     case DW_FORM_GNU_ref_alt:
22522       return 1;
22523     default:
22524       return 0;
22525     }
22526 }
22527
22528 /* Return the .debug_loc section to use for CU.
22529    For DWO files use .debug_loc.dwo.  */
22530
22531 static struct dwarf2_section_info *
22532 cu_debug_loc_section (struct dwarf2_cu *cu)
22533 {
22534   if (cu->dwo_unit)
22535     {
22536       struct dwo_sections *sections = &cu->dwo_unit->dwo_file->sections;
22537       
22538       return cu->header.version >= 5 ? &sections->loclists : &sections->loc;
22539     }
22540   return (cu->header.version >= 5 ? &dwarf2_per_objfile->loclists
22541                                   : &dwarf2_per_objfile->loc);
22542 }
22543
22544 /* A helper function that fills in a dwarf2_loclist_baton.  */
22545
22546 static void
22547 fill_in_loclist_baton (struct dwarf2_cu *cu,
22548                        struct dwarf2_loclist_baton *baton,
22549                        const struct attribute *attr)
22550 {
22551   struct dwarf2_section_info *section = cu_debug_loc_section (cu);
22552
22553   dwarf2_read_section (dwarf2_per_objfile->objfile, section);
22554
22555   baton->per_cu = cu->per_cu;
22556   gdb_assert (baton->per_cu);
22557   /* We don't know how long the location list is, but make sure we
22558      don't run off the edge of the section.  */
22559   baton->size = section->size - DW_UNSND (attr);
22560   baton->data = section->buffer + DW_UNSND (attr);
22561   baton->base_address = cu->base_address;
22562   baton->from_dwo = cu->dwo_unit != NULL;
22563 }
22564
22565 static void
22566 dwarf2_symbol_mark_computed (const struct attribute *attr, struct symbol *sym,
22567                              struct dwarf2_cu *cu, int is_block)
22568 {
22569   struct objfile *objfile = dwarf2_per_objfile->objfile;
22570   struct dwarf2_section_info *section = cu_debug_loc_section (cu);
22571
22572   if (attr_form_is_section_offset (attr)
22573       /* .debug_loc{,.dwo} may not exist at all, or the offset may be outside
22574          the section.  If so, fall through to the complaint in the
22575          other branch.  */
22576       && DW_UNSND (attr) < dwarf2_section_size (objfile, section))
22577     {
22578       struct dwarf2_loclist_baton *baton;
22579
22580       baton = XOBNEW (&objfile->objfile_obstack, struct dwarf2_loclist_baton);
22581
22582       fill_in_loclist_baton (cu, baton, attr);
22583
22584       if (cu->base_known == 0)
22585         complaint (&symfile_complaints,
22586                    _("Location list used without "
22587                      "specifying the CU base address."));
22588
22589       SYMBOL_ACLASS_INDEX (sym) = (is_block
22590                                    ? dwarf2_loclist_block_index
22591                                    : dwarf2_loclist_index);
22592       SYMBOL_LOCATION_BATON (sym) = baton;
22593     }
22594   else
22595     {
22596       struct dwarf2_locexpr_baton *baton;
22597
22598       baton = XOBNEW (&objfile->objfile_obstack, struct dwarf2_locexpr_baton);
22599       baton->per_cu = cu->per_cu;
22600       gdb_assert (baton->per_cu);
22601
22602       if (attr_form_is_block (attr))
22603         {
22604           /* Note that we're just copying the block's data pointer
22605              here, not the actual data.  We're still pointing into the
22606              info_buffer for SYM's objfile; right now we never release
22607              that buffer, but when we do clean up properly this may
22608              need to change.  */
22609           baton->size = DW_BLOCK (attr)->size;
22610           baton->data = DW_BLOCK (attr)->data;
22611         }
22612       else
22613         {
22614           dwarf2_invalid_attrib_class_complaint ("location description",
22615                                                  SYMBOL_NATURAL_NAME (sym));
22616           baton->size = 0;
22617         }
22618
22619       SYMBOL_ACLASS_INDEX (sym) = (is_block
22620                                    ? dwarf2_locexpr_block_index
22621                                    : dwarf2_locexpr_index);
22622       SYMBOL_LOCATION_BATON (sym) = baton;
22623     }
22624 }
22625
22626 /* Return the OBJFILE associated with the compilation unit CU.  If CU
22627    came from a separate debuginfo file, then the master objfile is
22628    returned.  */
22629
22630 struct objfile *
22631 dwarf2_per_cu_objfile (struct dwarf2_per_cu_data *per_cu)
22632 {
22633   struct objfile *objfile = per_cu->objfile;
22634
22635   /* Return the master objfile, so that we can report and look up the
22636      correct file containing this variable.  */
22637   if (objfile->separate_debug_objfile_backlink)
22638     objfile = objfile->separate_debug_objfile_backlink;
22639
22640   return objfile;
22641 }
22642
22643 /* Return comp_unit_head for PER_CU, either already available in PER_CU->CU
22644    (CU_HEADERP is unused in such case) or prepare a temporary copy at
22645    CU_HEADERP first.  */
22646
22647 static const struct comp_unit_head *
22648 per_cu_header_read_in (struct comp_unit_head *cu_headerp,
22649                        struct dwarf2_per_cu_data *per_cu)
22650 {
22651   const gdb_byte *info_ptr;
22652
22653   if (per_cu->cu)
22654     return &per_cu->cu->header;
22655
22656   info_ptr = per_cu->section->buffer + to_underlying (per_cu->sect_off);
22657
22658   memset (cu_headerp, 0, sizeof (*cu_headerp));
22659   read_comp_unit_head (cu_headerp, info_ptr, per_cu->section,
22660                        rcuh_kind::COMPILE);
22661
22662   return cu_headerp;
22663 }
22664
22665 /* Return the address size given in the compilation unit header for CU.  */
22666
22667 int
22668 dwarf2_per_cu_addr_size (struct dwarf2_per_cu_data *per_cu)
22669 {
22670   struct comp_unit_head cu_header_local;
22671   const struct comp_unit_head *cu_headerp;
22672
22673   cu_headerp = per_cu_header_read_in (&cu_header_local, per_cu);
22674
22675   return cu_headerp->addr_size;
22676 }
22677
22678 /* Return the offset size given in the compilation unit header for CU.  */
22679
22680 int
22681 dwarf2_per_cu_offset_size (struct dwarf2_per_cu_data *per_cu)
22682 {
22683   struct comp_unit_head cu_header_local;
22684   const struct comp_unit_head *cu_headerp;
22685
22686   cu_headerp = per_cu_header_read_in (&cu_header_local, per_cu);
22687
22688   return cu_headerp->offset_size;
22689 }
22690
22691 /* See its dwarf2loc.h declaration.  */
22692
22693 int
22694 dwarf2_per_cu_ref_addr_size (struct dwarf2_per_cu_data *per_cu)
22695 {
22696   struct comp_unit_head cu_header_local;
22697   const struct comp_unit_head *cu_headerp;
22698
22699   cu_headerp = per_cu_header_read_in (&cu_header_local, per_cu);
22700
22701   if (cu_headerp->version == 2)
22702     return cu_headerp->addr_size;
22703   else
22704     return cu_headerp->offset_size;
22705 }
22706
22707 /* Return the text offset of the CU.  The returned offset comes from
22708    this CU's objfile.  If this objfile came from a separate debuginfo
22709    file, then the offset may be different from the corresponding
22710    offset in the parent objfile.  */
22711
22712 CORE_ADDR
22713 dwarf2_per_cu_text_offset (struct dwarf2_per_cu_data *per_cu)
22714 {
22715   struct objfile *objfile = per_cu->objfile;
22716
22717   return ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
22718 }
22719
22720 /* Return DWARF version number of PER_CU.  */
22721
22722 short
22723 dwarf2_version (struct dwarf2_per_cu_data *per_cu)
22724 {
22725   return per_cu->dwarf_version;
22726 }
22727
22728 /* Locate the .debug_info compilation unit from CU's objfile which contains
22729    the DIE at OFFSET.  Raises an error on failure.  */
22730
22731 static struct dwarf2_per_cu_data *
22732 dwarf2_find_containing_comp_unit (sect_offset sect_off,
22733                                   unsigned int offset_in_dwz,
22734                                   struct objfile *objfile)
22735 {
22736   struct dwarf2_per_cu_data *this_cu;
22737   int low, high;
22738   const sect_offset *cu_off;
22739
22740   low = 0;
22741   high = dwarf2_per_objfile->n_comp_units - 1;
22742   while (high > low)
22743     {
22744       struct dwarf2_per_cu_data *mid_cu;
22745       int mid = low + (high - low) / 2;
22746
22747       mid_cu = dwarf2_per_objfile->all_comp_units[mid];
22748       cu_off = &mid_cu->sect_off;
22749       if (mid_cu->is_dwz > offset_in_dwz
22750           || (mid_cu->is_dwz == offset_in_dwz && *cu_off >= sect_off))
22751         high = mid;
22752       else
22753         low = mid + 1;
22754     }
22755   gdb_assert (low == high);
22756   this_cu = dwarf2_per_objfile->all_comp_units[low];
22757   cu_off = &this_cu->sect_off;
22758   if (this_cu->is_dwz != offset_in_dwz || *cu_off > sect_off)
22759     {
22760       if (low == 0 || this_cu->is_dwz != offset_in_dwz)
22761         error (_("Dwarf Error: could not find partial DIE containing "
22762                "offset 0x%x [in module %s]"),
22763                to_underlying (sect_off), bfd_get_filename (objfile->obfd));
22764
22765       gdb_assert (dwarf2_per_objfile->all_comp_units[low-1]->sect_off
22766                   <= sect_off);
22767       return dwarf2_per_objfile->all_comp_units[low-1];
22768     }
22769   else
22770     {
22771       this_cu = dwarf2_per_objfile->all_comp_units[low];
22772       if (low == dwarf2_per_objfile->n_comp_units - 1
22773           && sect_off >= this_cu->sect_off + this_cu->length)
22774         error (_("invalid dwarf2 offset %u"), to_underlying (sect_off));
22775       gdb_assert (sect_off < this_cu->sect_off + this_cu->length);
22776       return this_cu;
22777     }
22778 }
22779
22780 /* Initialize dwarf2_cu CU, owned by PER_CU.  */
22781
22782 static void
22783 init_one_comp_unit (struct dwarf2_cu *cu, struct dwarf2_per_cu_data *per_cu)
22784 {
22785   memset (cu, 0, sizeof (*cu));
22786   per_cu->cu = cu;
22787   cu->per_cu = per_cu;
22788   cu->objfile = per_cu->objfile;
22789   obstack_init (&cu->comp_unit_obstack);
22790 }
22791
22792 /* Initialize basic fields of dwarf_cu CU according to DIE COMP_UNIT_DIE.  */
22793
22794 static void
22795 prepare_one_comp_unit (struct dwarf2_cu *cu, struct die_info *comp_unit_die,
22796                        enum language pretend_language)
22797 {
22798   struct attribute *attr;
22799
22800   /* Set the language we're debugging.  */
22801   attr = dwarf2_attr (comp_unit_die, DW_AT_language, cu);
22802   if (attr)
22803     set_cu_language (DW_UNSND (attr), cu);
22804   else
22805     {
22806       cu->language = pretend_language;
22807       cu->language_defn = language_def (cu->language);
22808     }
22809
22810   cu->producer = dwarf2_string_attr (comp_unit_die, DW_AT_producer, cu);
22811 }
22812
22813 /* Release one cached compilation unit, CU.  We unlink it from the tree
22814    of compilation units, but we don't remove it from the read_in_chain;
22815    the caller is responsible for that.
22816    NOTE: DATA is a void * because this function is also used as a
22817    cleanup routine.  */
22818
22819 static void
22820 free_heap_comp_unit (void *data)
22821 {
22822   struct dwarf2_cu *cu = (struct dwarf2_cu *) data;
22823
22824   gdb_assert (cu->per_cu != NULL);
22825   cu->per_cu->cu = NULL;
22826   cu->per_cu = NULL;
22827
22828   obstack_free (&cu->comp_unit_obstack, NULL);
22829
22830   xfree (cu);
22831 }
22832
22833 /* This cleanup function is passed the address of a dwarf2_cu on the stack
22834    when we're finished with it.  We can't free the pointer itself, but be
22835    sure to unlink it from the cache.  Also release any associated storage.  */
22836
22837 static void
22838 free_stack_comp_unit (void *data)
22839 {
22840   struct dwarf2_cu *cu = (struct dwarf2_cu *) data;
22841
22842   gdb_assert (cu->per_cu != NULL);
22843   cu->per_cu->cu = NULL;
22844   cu->per_cu = NULL;
22845
22846   obstack_free (&cu->comp_unit_obstack, NULL);
22847   cu->partial_dies = NULL;
22848 }
22849
22850 /* Free all cached compilation units.  */
22851
22852 static void
22853 free_cached_comp_units (void *data)
22854 {
22855   dwarf2_per_objfile->free_cached_comp_units ();
22856 }
22857
22858 /* Increase the age counter on each cached compilation unit, and free
22859    any that are too old.  */
22860
22861 static void
22862 age_cached_comp_units (void)
22863 {
22864   struct dwarf2_per_cu_data *per_cu, **last_chain;
22865
22866   dwarf2_clear_marks (dwarf2_per_objfile->read_in_chain);
22867   per_cu = dwarf2_per_objfile->read_in_chain;
22868   while (per_cu != NULL)
22869     {
22870       per_cu->cu->last_used ++;
22871       if (per_cu->cu->last_used <= dwarf_max_cache_age)
22872         dwarf2_mark (per_cu->cu);
22873       per_cu = per_cu->cu->read_in_chain;
22874     }
22875
22876   per_cu = dwarf2_per_objfile->read_in_chain;
22877   last_chain = &dwarf2_per_objfile->read_in_chain;
22878   while (per_cu != NULL)
22879     {
22880       struct dwarf2_per_cu_data *next_cu;
22881
22882       next_cu = per_cu->cu->read_in_chain;
22883
22884       if (!per_cu->cu->mark)
22885         {
22886           free_heap_comp_unit (per_cu->cu);
22887           *last_chain = next_cu;
22888         }
22889       else
22890         last_chain = &per_cu->cu->read_in_chain;
22891
22892       per_cu = next_cu;
22893     }
22894 }
22895
22896 /* Remove a single compilation unit from the cache.  */
22897
22898 static void
22899 free_one_cached_comp_unit (struct dwarf2_per_cu_data *target_per_cu)
22900 {
22901   struct dwarf2_per_cu_data *per_cu, **last_chain;
22902
22903   per_cu = dwarf2_per_objfile->read_in_chain;
22904   last_chain = &dwarf2_per_objfile->read_in_chain;
22905   while (per_cu != NULL)
22906     {
22907       struct dwarf2_per_cu_data *next_cu;
22908
22909       next_cu = per_cu->cu->read_in_chain;
22910
22911       if (per_cu == target_per_cu)
22912         {
22913           free_heap_comp_unit (per_cu->cu);
22914           per_cu->cu = NULL;
22915           *last_chain = next_cu;
22916           break;
22917         }
22918       else
22919         last_chain = &per_cu->cu->read_in_chain;
22920
22921       per_cu = next_cu;
22922     }
22923 }
22924
22925 /* Release all extra memory associated with OBJFILE.  */
22926
22927 void
22928 dwarf2_free_objfile (struct objfile *objfile)
22929 {
22930   dwarf2_per_objfile
22931     = (struct dwarf2_per_objfile *) objfile_data (objfile,
22932                                                   dwarf2_objfile_data_key);
22933
22934   if (dwarf2_per_objfile == NULL)
22935     return;
22936
22937   dwarf2_per_objfile->~dwarf2_per_objfile ();
22938 }
22939
22940 /* A set of CU "per_cu" pointer, DIE offset, and GDB type pointer.
22941    We store these in a hash table separate from the DIEs, and preserve them
22942    when the DIEs are flushed out of cache.
22943
22944    The CU "per_cu" pointer is needed because offset alone is not enough to
22945    uniquely identify the type.  A file may have multiple .debug_types sections,
22946    or the type may come from a DWO file.  Furthermore, while it's more logical
22947    to use per_cu->section+offset, with Fission the section with the data is in
22948    the DWO file but we don't know that section at the point we need it.
22949    We have to use something in dwarf2_per_cu_data (or the pointer to it)
22950    because we can enter the lookup routine, get_die_type_at_offset, from
22951    outside this file, and thus won't necessarily have PER_CU->cu.
22952    Fortunately, PER_CU is stable for the life of the objfile.  */
22953
22954 struct dwarf2_per_cu_offset_and_type
22955 {
22956   const struct dwarf2_per_cu_data *per_cu;
22957   sect_offset sect_off;
22958   struct type *type;
22959 };
22960
22961 /* Hash function for a dwarf2_per_cu_offset_and_type.  */
22962
22963 static hashval_t
22964 per_cu_offset_and_type_hash (const void *item)
22965 {
22966   const struct dwarf2_per_cu_offset_and_type *ofs
22967     = (const struct dwarf2_per_cu_offset_and_type *) item;
22968
22969   return (uintptr_t) ofs->per_cu + to_underlying (ofs->sect_off);
22970 }
22971
22972 /* Equality function for a dwarf2_per_cu_offset_and_type.  */
22973
22974 static int
22975 per_cu_offset_and_type_eq (const void *item_lhs, const void *item_rhs)
22976 {
22977   const struct dwarf2_per_cu_offset_and_type *ofs_lhs
22978     = (const struct dwarf2_per_cu_offset_and_type *) item_lhs;
22979   const struct dwarf2_per_cu_offset_and_type *ofs_rhs
22980     = (const struct dwarf2_per_cu_offset_and_type *) item_rhs;
22981
22982   return (ofs_lhs->per_cu == ofs_rhs->per_cu
22983           && ofs_lhs->sect_off == ofs_rhs->sect_off);
22984 }
22985
22986 /* Set the type associated with DIE to TYPE.  Save it in CU's hash
22987    table if necessary.  For convenience, return TYPE.
22988
22989    The DIEs reading must have careful ordering to:
22990     * Not cause infite loops trying to read in DIEs as a prerequisite for
22991       reading current DIE.
22992     * Not trying to dereference contents of still incompletely read in types
22993       while reading in other DIEs.
22994     * Enable referencing still incompletely read in types just by a pointer to
22995       the type without accessing its fields.
22996
22997    Therefore caller should follow these rules:
22998      * Try to fetch any prerequisite types we may need to build this DIE type
22999        before building the type and calling set_die_type.
23000      * After building type call set_die_type for current DIE as soon as
23001        possible before fetching more types to complete the current type.
23002      * Make the type as complete as possible before fetching more types.  */
23003
23004 static struct type *
23005 set_die_type (struct die_info *die, struct type *type, struct dwarf2_cu *cu)
23006 {
23007   struct dwarf2_per_cu_offset_and_type **slot, ofs;
23008   struct objfile *objfile = cu->objfile;
23009   struct attribute *attr;
23010   struct dynamic_prop prop;
23011
23012   /* For Ada types, make sure that the gnat-specific data is always
23013      initialized (if not already set).  There are a few types where
23014      we should not be doing so, because the type-specific area is
23015      already used to hold some other piece of info (eg: TYPE_CODE_FLT
23016      where the type-specific area is used to store the floatformat).
23017      But this is not a problem, because the gnat-specific information
23018      is actually not needed for these types.  */
23019   if (need_gnat_info (cu)
23020       && TYPE_CODE (type) != TYPE_CODE_FUNC
23021       && TYPE_CODE (type) != TYPE_CODE_FLT
23022       && TYPE_CODE (type) != TYPE_CODE_METHODPTR
23023       && TYPE_CODE (type) != TYPE_CODE_MEMBERPTR
23024       && TYPE_CODE (type) != TYPE_CODE_METHOD
23025       && !HAVE_GNAT_AUX_INFO (type))
23026     INIT_GNAT_SPECIFIC (type);
23027
23028   /* Read DW_AT_allocated and set in type.  */
23029   attr = dwarf2_attr (die, DW_AT_allocated, cu);
23030   if (attr_form_is_block (attr))
23031     {
23032       if (attr_to_dynamic_prop (attr, die, cu, &prop))
23033         add_dyn_prop (DYN_PROP_ALLOCATED, prop, type, objfile);
23034     }
23035   else if (attr != NULL)
23036     {
23037       complaint (&symfile_complaints,
23038                  _("DW_AT_allocated has the wrong form (%s) at DIE 0x%x"),
23039                  (attr != NULL ? dwarf_form_name (attr->form) : "n/a"),
23040                  to_underlying (die->sect_off));
23041     }
23042
23043   /* Read DW_AT_associated and set in type.  */
23044   attr = dwarf2_attr (die, DW_AT_associated, cu);
23045   if (attr_form_is_block (attr))
23046     {
23047       if (attr_to_dynamic_prop (attr, die, cu, &prop))
23048         add_dyn_prop (DYN_PROP_ASSOCIATED, prop, type, objfile);
23049     }
23050   else if (attr != NULL)
23051     {
23052       complaint (&symfile_complaints,
23053                  _("DW_AT_associated has the wrong form (%s) at DIE 0x%x"),
23054                  (attr != NULL ? dwarf_form_name (attr->form) : "n/a"),
23055                  to_underlying (die->sect_off));
23056     }
23057
23058   /* Read DW_AT_data_location and set in type.  */
23059   attr = dwarf2_attr (die, DW_AT_data_location, cu);
23060   if (attr_to_dynamic_prop (attr, die, cu, &prop))
23061     add_dyn_prop (DYN_PROP_DATA_LOCATION, prop, type, objfile);
23062
23063   if (dwarf2_per_objfile->die_type_hash == NULL)
23064     {
23065       dwarf2_per_objfile->die_type_hash =
23066         htab_create_alloc_ex (127,
23067                               per_cu_offset_and_type_hash,
23068                               per_cu_offset_and_type_eq,
23069                               NULL,
23070                               &objfile->objfile_obstack,
23071                               hashtab_obstack_allocate,
23072                               dummy_obstack_deallocate);
23073     }
23074
23075   ofs.per_cu = cu->per_cu;
23076   ofs.sect_off = die->sect_off;
23077   ofs.type = type;
23078   slot = (struct dwarf2_per_cu_offset_and_type **)
23079     htab_find_slot (dwarf2_per_objfile->die_type_hash, &ofs, INSERT);
23080   if (*slot)
23081     complaint (&symfile_complaints,
23082                _("A problem internal to GDB: DIE 0x%x has type already set"),
23083                to_underlying (die->sect_off));
23084   *slot = XOBNEW (&objfile->objfile_obstack,
23085                   struct dwarf2_per_cu_offset_and_type);
23086   **slot = ofs;
23087   return type;
23088 }
23089
23090 /* Look up the type for the die at SECT_OFF in PER_CU in die_type_hash,
23091    or return NULL if the die does not have a saved type.  */
23092
23093 static struct type *
23094 get_die_type_at_offset (sect_offset sect_off,
23095                         struct dwarf2_per_cu_data *per_cu)
23096 {
23097   struct dwarf2_per_cu_offset_and_type *slot, ofs;
23098
23099   if (dwarf2_per_objfile->die_type_hash == NULL)
23100     return NULL;
23101
23102   ofs.per_cu = per_cu;
23103   ofs.sect_off = sect_off;
23104   slot = ((struct dwarf2_per_cu_offset_and_type *)
23105           htab_find (dwarf2_per_objfile->die_type_hash, &ofs));
23106   if (slot)
23107     return slot->type;
23108   else
23109     return NULL;
23110 }
23111
23112 /* Look up the type for DIE in CU in die_type_hash,
23113    or return NULL if DIE does not have a saved type.  */
23114
23115 static struct type *
23116 get_die_type (struct die_info *die, struct dwarf2_cu *cu)
23117 {
23118   return get_die_type_at_offset (die->sect_off, cu->per_cu);
23119 }
23120
23121 /* Add a dependence relationship from CU to REF_PER_CU.  */
23122
23123 static void
23124 dwarf2_add_dependence (struct dwarf2_cu *cu,
23125                        struct dwarf2_per_cu_data *ref_per_cu)
23126 {
23127   void **slot;
23128
23129   if (cu->dependencies == NULL)
23130     cu->dependencies
23131       = htab_create_alloc_ex (5, htab_hash_pointer, htab_eq_pointer,
23132                               NULL, &cu->comp_unit_obstack,
23133                               hashtab_obstack_allocate,
23134                               dummy_obstack_deallocate);
23135
23136   slot = htab_find_slot (cu->dependencies, ref_per_cu, INSERT);
23137   if (*slot == NULL)
23138     *slot = ref_per_cu;
23139 }
23140
23141 /* Subroutine of dwarf2_mark to pass to htab_traverse.
23142    Set the mark field in every compilation unit in the
23143    cache that we must keep because we are keeping CU.  */
23144
23145 static int
23146 dwarf2_mark_helper (void **slot, void *data)
23147 {
23148   struct dwarf2_per_cu_data *per_cu;
23149
23150   per_cu = (struct dwarf2_per_cu_data *) *slot;
23151
23152   /* cu->dependencies references may not yet have been ever read if QUIT aborts
23153      reading of the chain.  As such dependencies remain valid it is not much
23154      useful to track and undo them during QUIT cleanups.  */
23155   if (per_cu->cu == NULL)
23156     return 1;
23157
23158   if (per_cu->cu->mark)
23159     return 1;
23160   per_cu->cu->mark = 1;
23161
23162   if (per_cu->cu->dependencies != NULL)
23163     htab_traverse (per_cu->cu->dependencies, dwarf2_mark_helper, NULL);
23164
23165   return 1;
23166 }
23167
23168 /* Set the mark field in CU and in every other compilation unit in the
23169    cache that we must keep because we are keeping CU.  */
23170
23171 static void
23172 dwarf2_mark (struct dwarf2_cu *cu)
23173 {
23174   if (cu->mark)
23175     return;
23176   cu->mark = 1;
23177   if (cu->dependencies != NULL)
23178     htab_traverse (cu->dependencies, dwarf2_mark_helper, NULL);
23179 }
23180
23181 static void
23182 dwarf2_clear_marks (struct dwarf2_per_cu_data *per_cu)
23183 {
23184   while (per_cu)
23185     {
23186       per_cu->cu->mark = 0;
23187       per_cu = per_cu->cu->read_in_chain;
23188     }
23189 }
23190
23191 /* Trivial hash function for partial_die_info: the hash value of a DIE
23192    is its offset in .debug_info for this objfile.  */
23193
23194 static hashval_t
23195 partial_die_hash (const void *item)
23196 {
23197   const struct partial_die_info *part_die
23198     = (const struct partial_die_info *) item;
23199
23200   return to_underlying (part_die->sect_off);
23201 }
23202
23203 /* Trivial comparison function for partial_die_info structures: two DIEs
23204    are equal if they have the same offset.  */
23205
23206 static int
23207 partial_die_eq (const void *item_lhs, const void *item_rhs)
23208 {
23209   const struct partial_die_info *part_die_lhs
23210     = (const struct partial_die_info *) item_lhs;
23211   const struct partial_die_info *part_die_rhs
23212     = (const struct partial_die_info *) item_rhs;
23213
23214   return part_die_lhs->sect_off == part_die_rhs->sect_off;
23215 }
23216
23217 static struct cmd_list_element *set_dwarf_cmdlist;
23218 static struct cmd_list_element *show_dwarf_cmdlist;
23219
23220 static void
23221 set_dwarf_cmd (char *args, int from_tty)
23222 {
23223   help_list (set_dwarf_cmdlist, "maintenance set dwarf ", all_commands,
23224              gdb_stdout);
23225 }
23226
23227 static void
23228 show_dwarf_cmd (char *args, int from_tty)
23229 {
23230   cmd_show_list (show_dwarf_cmdlist, from_tty, "");
23231 }
23232
23233 /* Free data associated with OBJFILE, if necessary.  */
23234
23235 static void
23236 dwarf2_per_objfile_free (struct objfile *objfile, void *d)
23237 {
23238   struct dwarf2_per_objfile *data = (struct dwarf2_per_objfile *) d;
23239   int ix;
23240
23241   /* Make sure we don't accidentally use dwarf2_per_objfile while
23242      cleaning up.  */
23243   dwarf2_per_objfile = NULL;
23244
23245   for (ix = 0; ix < data->n_comp_units; ++ix)
23246    VEC_free (dwarf2_per_cu_ptr, data->all_comp_units[ix]->imported_symtabs);
23247
23248   for (ix = 0; ix < data->n_type_units; ++ix)
23249     VEC_free (dwarf2_per_cu_ptr,
23250               data->all_type_units[ix]->per_cu.imported_symtabs);
23251   xfree (data->all_type_units);
23252
23253   VEC_free (dwarf2_section_info_def, data->types);
23254
23255   if (data->dwo_files)
23256     free_dwo_files (data->dwo_files, objfile);
23257   if (data->dwp_file)
23258     gdb_bfd_unref (data->dwp_file->dbfd);
23259
23260   if (data->dwz_file && data->dwz_file->dwz_bfd)
23261     gdb_bfd_unref (data->dwz_file->dwz_bfd);
23262 }
23263
23264 \f
23265 /* The "save gdb-index" command.  */
23266
23267 /* In-memory buffer to prepare data to be written later to a file.  */
23268 class data_buf
23269 {
23270 public:
23271   /* Copy DATA to the end of the buffer.  */
23272   template<typename T>
23273   void append_data (const T &data)
23274   {
23275     std::copy (reinterpret_cast<const gdb_byte *> (&data),
23276                reinterpret_cast<const gdb_byte *> (&data + 1),
23277                grow (sizeof (data)));
23278   }
23279
23280   /* Copy CSTR (a zero-terminated string) to the end of buffer.  The
23281      terminating zero is appended too.  */
23282   void append_cstr0 (const char *cstr)
23283   {
23284     const size_t size = strlen (cstr) + 1;
23285     std::copy (cstr, cstr + size, grow (size));
23286   }
23287
23288   /* Accept a host-format integer in VAL and append it to the buffer
23289      as a target-format integer which is LEN bytes long.  */
23290   void append_uint (size_t len, bfd_endian byte_order, ULONGEST val)
23291   {
23292     ::store_unsigned_integer (grow (len), len, byte_order, val);
23293   }
23294
23295   /* Return the size of the buffer.  */
23296   size_t size () const
23297   {
23298     return m_vec.size ();
23299   }
23300
23301   /* Write the buffer to FILE.  */
23302   void file_write (FILE *file) const
23303   {
23304     if (::fwrite (m_vec.data (), 1, m_vec.size (), file) != m_vec.size ())
23305       error (_("couldn't write data to file"));
23306   }
23307
23308 private:
23309   /* Grow SIZE bytes at the end of the buffer.  Returns a pointer to
23310      the start of the new block.  */
23311   gdb_byte *grow (size_t size)
23312   {
23313     m_vec.resize (m_vec.size () + size);
23314     return &*m_vec.end () - size;
23315   }
23316
23317   gdb::byte_vector m_vec;
23318 };
23319
23320 /* An entry in the symbol table.  */
23321 struct symtab_index_entry
23322 {
23323   /* The name of the symbol.  */
23324   const char *name;
23325   /* The offset of the name in the constant pool.  */
23326   offset_type index_offset;
23327   /* A sorted vector of the indices of all the CUs that hold an object
23328      of this name.  */
23329   std::vector<offset_type> cu_indices;
23330 };
23331
23332 /* The symbol table.  This is a power-of-2-sized hash table.  */
23333 struct mapped_symtab
23334 {
23335   mapped_symtab ()
23336   {
23337     data.resize (1024);
23338   }
23339
23340   offset_type n_elements = 0;
23341   std::vector<symtab_index_entry> data;
23342 };
23343
23344 /* Find a slot in SYMTAB for the symbol NAME.  Returns a reference to
23345    the slot.
23346    
23347    Function is used only during write_hash_table so no index format backward
23348    compatibility is needed.  */
23349
23350 static symtab_index_entry &
23351 find_slot (struct mapped_symtab *symtab, const char *name)
23352 {
23353   offset_type index, step, hash = mapped_index_string_hash (INT_MAX, name);
23354
23355   index = hash & (symtab->data.size () - 1);
23356   step = ((hash * 17) & (symtab->data.size () - 1)) | 1;
23357
23358   for (;;)
23359     {
23360       if (symtab->data[index].name == NULL
23361           || strcmp (name, symtab->data[index].name) == 0)
23362         return symtab->data[index];
23363       index = (index + step) & (symtab->data.size () - 1);
23364     }
23365 }
23366
23367 /* Expand SYMTAB's hash table.  */
23368
23369 static void
23370 hash_expand (struct mapped_symtab *symtab)
23371 {
23372   auto old_entries = std::move (symtab->data);
23373
23374   symtab->data.clear ();
23375   symtab->data.resize (old_entries.size () * 2);
23376
23377   for (auto &it : old_entries)
23378     if (it.name != NULL)
23379       {
23380         auto &ref = find_slot (symtab, it.name);
23381         ref = std::move (it);
23382       }
23383 }
23384
23385 /* Add an entry to SYMTAB.  NAME is the name of the symbol.
23386    CU_INDEX is the index of the CU in which the symbol appears.
23387    IS_STATIC is one if the symbol is static, otherwise zero (global).  */
23388
23389 static void
23390 add_index_entry (struct mapped_symtab *symtab, const char *name,
23391                  int is_static, gdb_index_symbol_kind kind,
23392                  offset_type cu_index)
23393 {
23394   offset_type cu_index_and_attrs;
23395
23396   ++symtab->n_elements;
23397   if (4 * symtab->n_elements / 3 >= symtab->data.size ())
23398     hash_expand (symtab);
23399
23400   symtab_index_entry &slot = find_slot (symtab, name);
23401   if (slot.name == NULL)
23402     {
23403       slot.name = name;
23404       /* index_offset is set later.  */
23405     }
23406
23407   cu_index_and_attrs = 0;
23408   DW2_GDB_INDEX_CU_SET_VALUE (cu_index_and_attrs, cu_index);
23409   DW2_GDB_INDEX_SYMBOL_STATIC_SET_VALUE (cu_index_and_attrs, is_static);
23410   DW2_GDB_INDEX_SYMBOL_KIND_SET_VALUE (cu_index_and_attrs, kind);
23411
23412   /* We don't want to record an index value twice as we want to avoid the
23413      duplication.
23414      We process all global symbols and then all static symbols
23415      (which would allow us to avoid the duplication by only having to check
23416      the last entry pushed), but a symbol could have multiple kinds in one CU.
23417      To keep things simple we don't worry about the duplication here and
23418      sort and uniqufy the list after we've processed all symbols.  */
23419   slot.cu_indices.push_back (cu_index_and_attrs);
23420 }
23421
23422 /* Sort and remove duplicates of all symbols' cu_indices lists.  */
23423
23424 static void
23425 uniquify_cu_indices (struct mapped_symtab *symtab)
23426 {
23427   for (auto &entry : symtab->data)
23428     {
23429       if (entry.name != NULL && !entry.cu_indices.empty ())
23430         {
23431           auto &cu_indices = entry.cu_indices;
23432           std::sort (cu_indices.begin (), cu_indices.end ());
23433           auto from = std::unique (cu_indices.begin (), cu_indices.end ());
23434           cu_indices.erase (from, cu_indices.end ());
23435         }
23436     }
23437 }
23438
23439 /* A form of 'const char *' suitable for container keys.  Only the
23440    pointer is stored.  The strings themselves are compared, not the
23441    pointers.  */
23442 class c_str_view
23443 {
23444 public:
23445   c_str_view (const char *cstr)
23446     : m_cstr (cstr)
23447   {}
23448
23449   bool operator== (const c_str_view &other) const
23450   {
23451     return strcmp (m_cstr, other.m_cstr) == 0;
23452   }
23453
23454 private:
23455   friend class c_str_view_hasher;
23456   const char *const m_cstr;
23457 };
23458
23459 /* A std::unordered_map::hasher for c_str_view that uses the right
23460    hash function for strings in a mapped index.  */
23461 class c_str_view_hasher
23462 {
23463 public:
23464   size_t operator () (const c_str_view &x) const
23465   {
23466     return mapped_index_string_hash (INT_MAX, x.m_cstr);
23467   }
23468 };
23469
23470 /* A std::unordered_map::hasher for std::vector<>.  */
23471 template<typename T>
23472 class vector_hasher
23473 {
23474 public:
23475   size_t operator () (const std::vector<T> &key) const
23476   {
23477     return iterative_hash (key.data (),
23478                            sizeof (key.front ()) * key.size (), 0);
23479   }
23480 };
23481
23482 /* Write the mapped hash table SYMTAB to the data buffer OUTPUT, with
23483    constant pool entries going into the data buffer CPOOL.  */
23484
23485 static void
23486 write_hash_table (mapped_symtab *symtab, data_buf &output, data_buf &cpool)
23487 {
23488   {
23489     /* Elements are sorted vectors of the indices of all the CUs that
23490        hold an object of this name.  */
23491     std::unordered_map<std::vector<offset_type>, offset_type,
23492                        vector_hasher<offset_type>>
23493       symbol_hash_table;
23494
23495     /* We add all the index vectors to the constant pool first, to
23496        ensure alignment is ok.  */
23497     for (symtab_index_entry &entry : symtab->data)
23498       {
23499         if (entry.name == NULL)
23500           continue;
23501         gdb_assert (entry.index_offset == 0);
23502
23503         /* Finding before inserting is faster than always trying to
23504            insert, because inserting always allocates a node, does the
23505            lookup, and then destroys the new node if another node
23506            already had the same key.  C++17 try_emplace will avoid
23507            this.  */
23508         const auto found
23509           = symbol_hash_table.find (entry.cu_indices);
23510         if (found != symbol_hash_table.end ())
23511           {
23512             entry.index_offset = found->second;
23513             continue;
23514           }
23515
23516         symbol_hash_table.emplace (entry.cu_indices, cpool.size ());
23517         entry.index_offset = cpool.size ();
23518         cpool.append_data (MAYBE_SWAP (entry.cu_indices.size ()));
23519         for (const auto index : entry.cu_indices)
23520           cpool.append_data (MAYBE_SWAP (index));
23521       }
23522   }
23523
23524   /* Now write out the hash table.  */
23525   std::unordered_map<c_str_view, offset_type, c_str_view_hasher> str_table;
23526   for (const auto &entry : symtab->data)
23527     {
23528       offset_type str_off, vec_off;
23529
23530       if (entry.name != NULL)
23531         {
23532           const auto insertpair = str_table.emplace (entry.name, cpool.size ());
23533           if (insertpair.second)
23534             cpool.append_cstr0 (entry.name);
23535           str_off = insertpair.first->second;
23536           vec_off = entry.index_offset;
23537         }
23538       else
23539         {
23540           /* While 0 is a valid constant pool index, it is not valid
23541              to have 0 for both offsets.  */
23542           str_off = 0;
23543           vec_off = 0;
23544         }
23545
23546       output.append_data (MAYBE_SWAP (str_off));
23547       output.append_data (MAYBE_SWAP (vec_off));
23548     }
23549 }
23550
23551 typedef std::unordered_map<partial_symtab *, unsigned int> psym_index_map;
23552
23553 /* Helper struct for building the address table.  */
23554 struct addrmap_index_data
23555 {
23556   addrmap_index_data (data_buf &addr_vec_, psym_index_map &cu_index_htab_)
23557     : addr_vec (addr_vec_), cu_index_htab (cu_index_htab_)
23558   {}
23559
23560   struct objfile *objfile;
23561   data_buf &addr_vec;
23562   psym_index_map &cu_index_htab;
23563
23564   /* Non-zero if the previous_* fields are valid.
23565      We can't write an entry until we see the next entry (since it is only then
23566      that we know the end of the entry).  */
23567   int previous_valid;
23568   /* Index of the CU in the table of all CUs in the index file.  */
23569   unsigned int previous_cu_index;
23570   /* Start address of the CU.  */
23571   CORE_ADDR previous_cu_start;
23572 };
23573
23574 /* Write an address entry to ADDR_VEC.  */
23575
23576 static void
23577 add_address_entry (struct objfile *objfile, data_buf &addr_vec,
23578                    CORE_ADDR start, CORE_ADDR end, unsigned int cu_index)
23579 {
23580   CORE_ADDR baseaddr;
23581
23582   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
23583
23584   addr_vec.append_uint (8, BFD_ENDIAN_LITTLE, start - baseaddr);
23585   addr_vec.append_uint (8, BFD_ENDIAN_LITTLE, end - baseaddr);
23586   addr_vec.append_data (MAYBE_SWAP (cu_index));
23587 }
23588
23589 /* Worker function for traversing an addrmap to build the address table.  */
23590
23591 static int
23592 add_address_entry_worker (void *datap, CORE_ADDR start_addr, void *obj)
23593 {
23594   struct addrmap_index_data *data = (struct addrmap_index_data *) datap;
23595   struct partial_symtab *pst = (struct partial_symtab *) obj;
23596
23597   if (data->previous_valid)
23598     add_address_entry (data->objfile, data->addr_vec,
23599                        data->previous_cu_start, start_addr,
23600                        data->previous_cu_index);
23601
23602   data->previous_cu_start = start_addr;
23603   if (pst != NULL)
23604     {
23605       const auto it = data->cu_index_htab.find (pst);
23606       gdb_assert (it != data->cu_index_htab.cend ());
23607       data->previous_cu_index = it->second;
23608       data->previous_valid = 1;
23609     }
23610   else
23611     data->previous_valid = 0;
23612
23613   return 0;
23614 }
23615
23616 /* Write OBJFILE's address map to ADDR_VEC.
23617    CU_INDEX_HTAB is used to map addrmap entries to their CU indices
23618    in the index file.  */
23619
23620 static void
23621 write_address_map (struct objfile *objfile, data_buf &addr_vec,
23622                    psym_index_map &cu_index_htab)
23623 {
23624   struct addrmap_index_data addrmap_index_data (addr_vec, cu_index_htab);
23625
23626   /* When writing the address table, we have to cope with the fact that
23627      the addrmap iterator only provides the start of a region; we have to
23628      wait until the next invocation to get the start of the next region.  */
23629
23630   addrmap_index_data.objfile = objfile;
23631   addrmap_index_data.previous_valid = 0;
23632
23633   addrmap_foreach (objfile->psymtabs_addrmap, add_address_entry_worker,
23634                    &addrmap_index_data);
23635
23636   /* It's highly unlikely the last entry (end address = 0xff...ff)
23637      is valid, but we should still handle it.
23638      The end address is recorded as the start of the next region, but that
23639      doesn't work here.  To cope we pass 0xff...ff, this is a rare situation
23640      anyway.  */
23641   if (addrmap_index_data.previous_valid)
23642     add_address_entry (objfile, addr_vec,
23643                        addrmap_index_data.previous_cu_start, (CORE_ADDR) -1,
23644                        addrmap_index_data.previous_cu_index);
23645 }
23646
23647 /* Return the symbol kind of PSYM.  */
23648
23649 static gdb_index_symbol_kind
23650 symbol_kind (struct partial_symbol *psym)
23651 {
23652   domain_enum domain = PSYMBOL_DOMAIN (psym);
23653   enum address_class aclass = PSYMBOL_CLASS (psym);
23654
23655   switch (domain)
23656     {
23657     case VAR_DOMAIN:
23658       switch (aclass)
23659         {
23660         case LOC_BLOCK:
23661           return GDB_INDEX_SYMBOL_KIND_FUNCTION;
23662         case LOC_TYPEDEF:
23663           return GDB_INDEX_SYMBOL_KIND_TYPE;
23664         case LOC_COMPUTED:
23665         case LOC_CONST_BYTES:
23666         case LOC_OPTIMIZED_OUT:
23667         case LOC_STATIC:
23668           return GDB_INDEX_SYMBOL_KIND_VARIABLE;
23669         case LOC_CONST:
23670           /* Note: It's currently impossible to recognize psyms as enum values
23671              short of reading the type info.  For now punt.  */
23672           return GDB_INDEX_SYMBOL_KIND_VARIABLE;
23673         default:
23674           /* There are other LOC_FOO values that one might want to classify
23675              as variables, but dwarf2read.c doesn't currently use them.  */
23676           return GDB_INDEX_SYMBOL_KIND_OTHER;
23677         }
23678     case STRUCT_DOMAIN:
23679       return GDB_INDEX_SYMBOL_KIND_TYPE;
23680     default:
23681       return GDB_INDEX_SYMBOL_KIND_OTHER;
23682     }
23683 }
23684
23685 /* Add a list of partial symbols to SYMTAB.  */
23686
23687 static void
23688 write_psymbols (struct mapped_symtab *symtab,
23689                 std::unordered_set<partial_symbol *> &psyms_seen,
23690                 struct partial_symbol **psymp,
23691                 int count,
23692                 offset_type cu_index,
23693                 int is_static)
23694 {
23695   for (; count-- > 0; ++psymp)
23696     {
23697       struct partial_symbol *psym = *psymp;
23698
23699       if (SYMBOL_LANGUAGE (psym) == language_ada)
23700         error (_("Ada is not currently supported by the index"));
23701
23702       /* Only add a given psymbol once.  */
23703       if (psyms_seen.insert (psym).second)
23704         {
23705           gdb_index_symbol_kind kind = symbol_kind (psym);
23706
23707           add_index_entry (symtab, SYMBOL_SEARCH_NAME (psym),
23708                            is_static, kind, cu_index);
23709         }
23710     }
23711 }
23712
23713 /* A helper struct used when iterating over debug_types.  */
23714 struct signatured_type_index_data
23715 {
23716   signatured_type_index_data (data_buf &types_list_,
23717                               std::unordered_set<partial_symbol *> &psyms_seen_)
23718     : types_list (types_list_), psyms_seen (psyms_seen_)
23719   {}
23720
23721   struct objfile *objfile;
23722   struct mapped_symtab *symtab;
23723   data_buf &types_list;
23724   std::unordered_set<partial_symbol *> &psyms_seen;
23725   int cu_index;
23726 };
23727
23728 /* A helper function that writes a single signatured_type to an
23729    obstack.  */
23730
23731 static int
23732 write_one_signatured_type (void **slot, void *d)
23733 {
23734   struct signatured_type_index_data *info
23735     = (struct signatured_type_index_data *) d;
23736   struct signatured_type *entry = (struct signatured_type *) *slot;
23737   struct partial_symtab *psymtab = entry->per_cu.v.psymtab;
23738
23739   write_psymbols (info->symtab,
23740                   info->psyms_seen,
23741                   info->objfile->global_psymbols.list
23742                   + psymtab->globals_offset,
23743                   psymtab->n_global_syms, info->cu_index,
23744                   0);
23745   write_psymbols (info->symtab,
23746                   info->psyms_seen,
23747                   info->objfile->static_psymbols.list
23748                   + psymtab->statics_offset,
23749                   psymtab->n_static_syms, info->cu_index,
23750                   1);
23751
23752   info->types_list.append_uint (8, BFD_ENDIAN_LITTLE,
23753                                 to_underlying (entry->per_cu.sect_off));
23754   info->types_list.append_uint (8, BFD_ENDIAN_LITTLE,
23755                                 to_underlying (entry->type_offset_in_tu));
23756   info->types_list.append_uint (8, BFD_ENDIAN_LITTLE, entry->signature);
23757
23758   ++info->cu_index;
23759
23760   return 1;
23761 }
23762
23763 /* Recurse into all "included" dependencies and count their symbols as
23764    if they appeared in this psymtab.  */
23765
23766 static void
23767 recursively_count_psymbols (struct partial_symtab *psymtab,
23768                             size_t &psyms_seen)
23769 {
23770   for (int i = 0; i < psymtab->number_of_dependencies; ++i)
23771     if (psymtab->dependencies[i]->user != NULL)
23772       recursively_count_psymbols (psymtab->dependencies[i],
23773                                   psyms_seen);
23774
23775   psyms_seen += psymtab->n_global_syms;
23776   psyms_seen += psymtab->n_static_syms;
23777 }
23778
23779 /* Recurse into all "included" dependencies and write their symbols as
23780    if they appeared in this psymtab.  */
23781
23782 static void
23783 recursively_write_psymbols (struct objfile *objfile,
23784                             struct partial_symtab *psymtab,
23785                             struct mapped_symtab *symtab,
23786                             std::unordered_set<partial_symbol *> &psyms_seen,
23787                             offset_type cu_index)
23788 {
23789   int i;
23790
23791   for (i = 0; i < psymtab->number_of_dependencies; ++i)
23792     if (psymtab->dependencies[i]->user != NULL)
23793       recursively_write_psymbols (objfile, psymtab->dependencies[i],
23794                                   symtab, psyms_seen, cu_index);
23795
23796   write_psymbols (symtab,
23797                   psyms_seen,
23798                   objfile->global_psymbols.list + psymtab->globals_offset,
23799                   psymtab->n_global_syms, cu_index,
23800                   0);
23801   write_psymbols (symtab,
23802                   psyms_seen,
23803                   objfile->static_psymbols.list + psymtab->statics_offset,
23804                   psymtab->n_static_syms, cu_index,
23805                   1);
23806 }
23807
23808 /* Create an index file for OBJFILE in the directory DIR.  */
23809
23810 static void
23811 write_psymtabs_to_index (struct objfile *objfile, const char *dir)
23812 {
23813   if (dwarf2_per_objfile->using_index)
23814     error (_("Cannot use an index to create the index"));
23815
23816   if (VEC_length (dwarf2_section_info_def, dwarf2_per_objfile->types) > 1)
23817     error (_("Cannot make an index when the file has multiple .debug_types sections"));
23818
23819   if (!objfile->psymtabs || !objfile->psymtabs_addrmap)
23820     return;
23821
23822   struct stat st;
23823   if (stat (objfile_name (objfile), &st) < 0)
23824     perror_with_name (objfile_name (objfile));
23825
23826   std::string filename (std::string (dir) + SLASH_STRING
23827                         + lbasename (objfile_name (objfile)) + INDEX_SUFFIX);
23828
23829   FILE *out_file = gdb_fopen_cloexec (filename.c_str (), "wb").release ();
23830   if (!out_file)
23831     error (_("Can't open `%s' for writing"), filename.c_str ());
23832
23833   /* Order matters here; we want FILE to be closed before FILENAME is
23834      unlinked, because on MS-Windows one cannot delete a file that is
23835      still open.  (Don't call anything here that might throw until
23836      file_closer is created.)  */
23837   gdb::unlinker unlink_file (filename.c_str ());
23838   gdb_file_up close_out_file (out_file);
23839
23840   mapped_symtab symtab;
23841   data_buf cu_list;
23842
23843   /* While we're scanning CU's create a table that maps a psymtab pointer
23844      (which is what addrmap records) to its index (which is what is recorded
23845      in the index file).  This will later be needed to write the address
23846      table.  */
23847   psym_index_map cu_index_htab;
23848   cu_index_htab.reserve (dwarf2_per_objfile->n_comp_units);
23849
23850   /* The CU list is already sorted, so we don't need to do additional
23851      work here.  Also, the debug_types entries do not appear in
23852      all_comp_units, but only in their own hash table.  */
23853
23854   /* The psyms_seen set is potentially going to be largish (~40k
23855      elements when indexing a -g3 build of GDB itself).  Estimate the
23856      number of elements in order to avoid too many rehashes, which
23857      require rebuilding buckets and thus many trips to
23858      malloc/free.  */
23859   size_t psyms_count = 0;
23860   for (int i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
23861     {
23862       struct dwarf2_per_cu_data *per_cu
23863         = dwarf2_per_objfile->all_comp_units[i];
23864       struct partial_symtab *psymtab = per_cu->v.psymtab;
23865
23866       if (psymtab != NULL && psymtab->user == NULL)
23867         recursively_count_psymbols (psymtab, psyms_count);
23868     }
23869   /* Generating an index for gdb itself shows a ratio of
23870      TOTAL_SEEN_SYMS/UNIQUE_SYMS or ~5.  4 seems like a good bet.  */
23871   std::unordered_set<partial_symbol *> psyms_seen (psyms_count / 4);
23872   for (int i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
23873     {
23874       struct dwarf2_per_cu_data *per_cu
23875         = dwarf2_per_objfile->all_comp_units[i];
23876       struct partial_symtab *psymtab = per_cu->v.psymtab;
23877
23878       /* CU of a shared file from 'dwz -m' may be unused by this main file.
23879          It may be referenced from a local scope but in such case it does not
23880          need to be present in .gdb_index.  */
23881       if (psymtab == NULL)
23882         continue;
23883
23884       if (psymtab->user == NULL)
23885         recursively_write_psymbols (objfile, psymtab, &symtab,
23886                                     psyms_seen, i);
23887
23888       const auto insertpair = cu_index_htab.emplace (psymtab, i);
23889       gdb_assert (insertpair.second);
23890
23891       cu_list.append_uint (8, BFD_ENDIAN_LITTLE,
23892                            to_underlying (per_cu->sect_off));
23893       cu_list.append_uint (8, BFD_ENDIAN_LITTLE, per_cu->length);
23894     }
23895
23896   /* Dump the address map.  */
23897   data_buf addr_vec;
23898   write_address_map (objfile, addr_vec, cu_index_htab);
23899
23900   /* Write out the .debug_type entries, if any.  */
23901   data_buf types_cu_list;
23902   if (dwarf2_per_objfile->signatured_types)
23903     {
23904       signatured_type_index_data sig_data (types_cu_list,
23905                                            psyms_seen);
23906
23907       sig_data.objfile = objfile;
23908       sig_data.symtab = &symtab;
23909       sig_data.cu_index = dwarf2_per_objfile->n_comp_units;
23910       htab_traverse_noresize (dwarf2_per_objfile->signatured_types,
23911                               write_one_signatured_type, &sig_data);
23912     }
23913
23914   /* Now that we've processed all symbols we can shrink their cu_indices
23915      lists.  */
23916   uniquify_cu_indices (&symtab);
23917
23918   data_buf symtab_vec, constant_pool;
23919   write_hash_table (&symtab, symtab_vec, constant_pool);
23920
23921   data_buf contents;
23922   const offset_type size_of_contents = 6 * sizeof (offset_type);
23923   offset_type total_len = size_of_contents;
23924
23925   /* The version number.  */
23926   contents.append_data (MAYBE_SWAP (8));
23927
23928   /* The offset of the CU list from the start of the file.  */
23929   contents.append_data (MAYBE_SWAP (total_len));
23930   total_len += cu_list.size ();
23931
23932   /* The offset of the types CU list from the start of the file.  */
23933   contents.append_data (MAYBE_SWAP (total_len));
23934   total_len += types_cu_list.size ();
23935
23936   /* The offset of the address table from the start of the file.  */
23937   contents.append_data (MAYBE_SWAP (total_len));
23938   total_len += addr_vec.size ();
23939
23940   /* The offset of the symbol table from the start of the file.  */
23941   contents.append_data (MAYBE_SWAP (total_len));
23942   total_len += symtab_vec.size ();
23943
23944   /* The offset of the constant pool from the start of the file.  */
23945   contents.append_data (MAYBE_SWAP (total_len));
23946   total_len += constant_pool.size ();
23947
23948   gdb_assert (contents.size () == size_of_contents);
23949
23950   contents.file_write (out_file);
23951   cu_list.file_write (out_file);
23952   types_cu_list.file_write (out_file);
23953   addr_vec.file_write (out_file);
23954   symtab_vec.file_write (out_file);
23955   constant_pool.file_write (out_file);
23956
23957   /* We want to keep the file.  */
23958   unlink_file.keep ();
23959 }
23960
23961 /* Implementation of the `save gdb-index' command.
23962    
23963    Note that the file format used by this command is documented in the
23964    GDB manual.  Any changes here must be documented there.  */
23965
23966 static void
23967 save_gdb_index_command (char *arg, int from_tty)
23968 {
23969   struct objfile *objfile;
23970
23971   if (!arg || !*arg)
23972     error (_("usage: save gdb-index DIRECTORY"));
23973
23974   ALL_OBJFILES (objfile)
23975   {
23976     struct stat st;
23977
23978     /* If the objfile does not correspond to an actual file, skip it.  */
23979     if (stat (objfile_name (objfile), &st) < 0)
23980       continue;
23981
23982     dwarf2_per_objfile
23983       = (struct dwarf2_per_objfile *) objfile_data (objfile,
23984                                                     dwarf2_objfile_data_key);
23985     if (dwarf2_per_objfile)
23986       {
23987
23988         TRY
23989           {
23990             write_psymtabs_to_index (objfile, arg);
23991           }
23992         CATCH (except, RETURN_MASK_ERROR)
23993           {
23994             exception_fprintf (gdb_stderr, except,
23995                                _("Error while writing index for `%s': "),
23996                                objfile_name (objfile));
23997           }
23998         END_CATCH
23999       }
24000   }
24001 }
24002
24003 \f
24004
24005 int dwarf_always_disassemble;
24006
24007 static void
24008 show_dwarf_always_disassemble (struct ui_file *file, int from_tty,
24009                                struct cmd_list_element *c, const char *value)
24010 {
24011   fprintf_filtered (file,
24012                     _("Whether to always disassemble "
24013                       "DWARF expressions is %s.\n"),
24014                     value);
24015 }
24016
24017 static void
24018 show_check_physname (struct ui_file *file, int from_tty,
24019                      struct cmd_list_element *c, const char *value)
24020 {
24021   fprintf_filtered (file,
24022                     _("Whether to check \"physname\" is %s.\n"),
24023                     value);
24024 }
24025
24026 void _initialize_dwarf2_read (void);
24027
24028 void
24029 _initialize_dwarf2_read (void)
24030 {
24031   struct cmd_list_element *c;
24032
24033   dwarf2_objfile_data_key
24034     = register_objfile_data_with_cleanup (NULL, dwarf2_per_objfile_free);
24035
24036   add_prefix_cmd ("dwarf", class_maintenance, set_dwarf_cmd, _("\
24037 Set DWARF specific variables.\n\
24038 Configure DWARF variables such as the cache size"),
24039                   &set_dwarf_cmdlist, "maintenance set dwarf ",
24040                   0/*allow-unknown*/, &maintenance_set_cmdlist);
24041
24042   add_prefix_cmd ("dwarf", class_maintenance, show_dwarf_cmd, _("\
24043 Show DWARF specific variables\n\
24044 Show DWARF variables such as the cache size"),
24045                   &show_dwarf_cmdlist, "maintenance show dwarf ",
24046                   0/*allow-unknown*/, &maintenance_show_cmdlist);
24047
24048   add_setshow_zinteger_cmd ("max-cache-age", class_obscure,
24049                             &dwarf_max_cache_age, _("\
24050 Set the upper bound on the age of cached DWARF compilation units."), _("\
24051 Show the upper bound on the age of cached DWARF compilation units."), _("\
24052 A higher limit means that cached compilation units will be stored\n\
24053 in memory longer, and more total memory will be used.  Zero disables\n\
24054 caching, which can slow down startup."),
24055                             NULL,
24056                             show_dwarf_max_cache_age,
24057                             &set_dwarf_cmdlist,
24058                             &show_dwarf_cmdlist);
24059
24060   add_setshow_boolean_cmd ("always-disassemble", class_obscure,
24061                            &dwarf_always_disassemble, _("\
24062 Set whether `info address' always disassembles DWARF expressions."), _("\
24063 Show whether `info address' always disassembles DWARF expressions."), _("\
24064 When enabled, DWARF expressions are always printed in an assembly-like\n\
24065 syntax.  When disabled, expressions will be printed in a more\n\
24066 conversational style, when possible."),
24067                            NULL,
24068                            show_dwarf_always_disassemble,
24069                            &set_dwarf_cmdlist,
24070                            &show_dwarf_cmdlist);
24071
24072   add_setshow_zuinteger_cmd ("dwarf-read", no_class, &dwarf_read_debug, _("\
24073 Set debugging of the DWARF reader."), _("\
24074 Show debugging of the DWARF reader."), _("\
24075 When enabled (non-zero), debugging messages are printed during DWARF\n\
24076 reading and symtab expansion.  A value of 1 (one) provides basic\n\
24077 information.  A value greater than 1 provides more verbose information."),
24078                             NULL,
24079                             NULL,
24080                             &setdebuglist, &showdebuglist);
24081
24082   add_setshow_zuinteger_cmd ("dwarf-die", no_class, &dwarf_die_debug, _("\
24083 Set debugging of the DWARF DIE reader."), _("\
24084 Show debugging of the DWARF DIE reader."), _("\
24085 When enabled (non-zero), DIEs are dumped after they are read in.\n\
24086 The value is the maximum depth to print."),
24087                              NULL,
24088                              NULL,
24089                              &setdebuglist, &showdebuglist);
24090
24091   add_setshow_zuinteger_cmd ("dwarf-line", no_class, &dwarf_line_debug, _("\
24092 Set debugging of the dwarf line reader."), _("\
24093 Show debugging of the dwarf line reader."), _("\
24094 When enabled (non-zero), line number entries are dumped as they are read in.\n\
24095 A value of 1 (one) provides basic information.\n\
24096 A value greater than 1 provides more verbose information."),
24097                              NULL,
24098                              NULL,
24099                              &setdebuglist, &showdebuglist);
24100
24101   add_setshow_boolean_cmd ("check-physname", no_class, &check_physname, _("\
24102 Set cross-checking of \"physname\" code against demangler."), _("\
24103 Show cross-checking of \"physname\" code against demangler."), _("\
24104 When enabled, GDB's internal \"physname\" code is checked against\n\
24105 the demangler."),
24106                            NULL, show_check_physname,
24107                            &setdebuglist, &showdebuglist);
24108
24109   add_setshow_boolean_cmd ("use-deprecated-index-sections",
24110                            no_class, &use_deprecated_index_sections, _("\
24111 Set whether to use deprecated gdb_index sections."), _("\
24112 Show whether to use deprecated gdb_index sections."), _("\
24113 When enabled, deprecated .gdb_index sections are used anyway.\n\
24114 Normally they are ignored either because of a missing feature or\n\
24115 performance issue.\n\
24116 Warning: This option must be enabled before gdb reads the file."),
24117                            NULL,
24118                            NULL,
24119                            &setlist, &showlist);
24120
24121   c = add_cmd ("gdb-index", class_files, save_gdb_index_command,
24122                _("\
24123 Save a gdb-index file.\n\
24124 Usage: save gdb-index DIRECTORY"),
24125                &save_cmdlist);
24126   set_cmd_completer (c, filename_completer);
24127
24128   dwarf2_locexpr_index = register_symbol_computed_impl (LOC_COMPUTED,
24129                                                         &dwarf2_locexpr_funcs);
24130   dwarf2_loclist_index = register_symbol_computed_impl (LOC_COMPUTED,
24131                                                         &dwarf2_loclist_funcs);
24132
24133   dwarf2_locexpr_block_index = register_symbol_block_impl (LOC_BLOCK,
24134                                         &dwarf2_block_frame_base_locexpr_funcs);
24135   dwarf2_loclist_block_index = register_symbol_block_impl (LOC_BLOCK,
24136                                         &dwarf2_block_frame_base_loclist_funcs);
24137 }