Introduce dw2_linkage_name and dw2_linkage_name_attr.
[external/binutils.git] / gdb / dwarf2read.c
1 /* DWARF 2 debugging format support for GDB.
2
3    Copyright (C) 1994-2017 Free Software Foundation, Inc.
4
5    Adapted by Gary Funck (gary@intrepid.com), Intrepid Technology,
6    Inc.  with support from Florida State University (under contract
7    with the Ada Joint Program Office), and Silicon Graphics, Inc.
8    Initial contribution by Brent Benson, Harris Computer Systems, Inc.,
9    based on Fred Fish's (Cygnus Support) implementation of DWARF 1
10    support.
11
12    This file is part of GDB.
13
14    This program is free software; you can redistribute it and/or modify
15    it under the terms of the GNU General Public License as published by
16    the Free Software Foundation; either version 3 of the License, or
17    (at your option) any later version.
18
19    This program is distributed in the hope that it will be useful,
20    but WITHOUT ANY WARRANTY; without even the implied warranty of
21    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
22    GNU General Public License for more details.
23
24    You should have received a copy of the GNU General Public License
25    along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
26
27 /* FIXME: Various die-reading functions need to be more careful with
28    reading off the end of the section.
29    E.g., load_partial_dies, read_partial_die.  */
30
31 #include "defs.h"
32 #include "bfd.h"
33 #include "elf-bfd.h"
34 #include "symtab.h"
35 #include "gdbtypes.h"
36 #include "objfiles.h"
37 #include "dwarf2.h"
38 #include "buildsym.h"
39 #include "demangle.h"
40 #include "gdb-demangle.h"
41 #include "expression.h"
42 #include "filenames.h"  /* for DOSish file names */
43 #include "macrotab.h"
44 #include "language.h"
45 #include "complaints.h"
46 #include "bcache.h"
47 #include "dwarf2expr.h"
48 #include "dwarf2loc.h"
49 #include "cp-support.h"
50 #include "hashtab.h"
51 #include "command.h"
52 #include "gdbcmd.h"
53 #include "block.h"
54 #include "addrmap.h"
55 #include "typeprint.h"
56 #include "psympriv.h"
57 #include <sys/stat.h>
58 #include "completer.h"
59 #include "vec.h"
60 #include "c-lang.h"
61 #include "go-lang.h"
62 #include "valprint.h"
63 #include "gdbcore.h" /* for gnutarget */
64 #include "gdb/gdb-index.h"
65 #include <ctype.h>
66 #include "gdb_bfd.h"
67 #include "f-lang.h"
68 #include "source.h"
69 #include "filestuff.h"
70 #include "build-id.h"
71 #include "namespace.h"
72 #include "common/gdb_unlinker.h"
73 #include "common/function-view.h"
74 #include "common/gdb_optional.h"
75 #include "common/underlying.h"
76 #include "common/byte-vector.h"
77 #include "filename-seen-cache.h"
78 #include <fcntl.h>
79 #include <sys/types.h>
80 #include <algorithm>
81 #include <unordered_set>
82 #include <unordered_map>
83
84 typedef struct symbol *symbolp;
85 DEF_VEC_P (symbolp);
86
87 /* When == 1, print basic high level tracing messages.
88    When > 1, be more verbose.
89    This is in contrast to the low level DIE reading of dwarf_die_debug.  */
90 static unsigned int dwarf_read_debug = 0;
91
92 /* When non-zero, dump DIEs after they are read in.  */
93 static unsigned int dwarf_die_debug = 0;
94
95 /* When non-zero, dump line number entries as they are read in.  */
96 static unsigned int dwarf_line_debug = 0;
97
98 /* When non-zero, cross-check physname against demangler.  */
99 static int check_physname = 0;
100
101 /* When non-zero, do not reject deprecated .gdb_index sections.  */
102 static int use_deprecated_index_sections = 0;
103
104 static const struct objfile_data *dwarf2_objfile_data_key;
105
106 /* The "aclass" indices for various kinds of computed DWARF symbols.  */
107
108 static int dwarf2_locexpr_index;
109 static int dwarf2_loclist_index;
110 static int dwarf2_locexpr_block_index;
111 static int dwarf2_loclist_block_index;
112
113 /* A descriptor for dwarf sections.
114
115    S.ASECTION, SIZE are typically initialized when the objfile is first
116    scanned.  BUFFER, READIN are filled in later when the section is read.
117    If the section contained compressed data then SIZE is updated to record
118    the uncompressed size of the section.
119
120    DWP file format V2 introduces a wrinkle that is easiest to handle by
121    creating the concept of virtual sections contained within a real section.
122    In DWP V2 the sections of the input DWO files are concatenated together
123    into one section, but section offsets are kept relative to the original
124    input section.
125    If this is a virtual dwp-v2 section, S.CONTAINING_SECTION is a backlink to
126    the real section this "virtual" section is contained in, and BUFFER,SIZE
127    describe the virtual section.  */
128
129 struct dwarf2_section_info
130 {
131   union
132   {
133     /* If this is a real section, the bfd section.  */
134     asection *section;
135     /* If this is a virtual section, pointer to the containing ("real")
136        section.  */
137     struct dwarf2_section_info *containing_section;
138   } s;
139   /* Pointer to section data, only valid if readin.  */
140   const gdb_byte *buffer;
141   /* The size of the section, real or virtual.  */
142   bfd_size_type size;
143   /* If this is a virtual section, the offset in the real section.
144      Only valid if is_virtual.  */
145   bfd_size_type virtual_offset;
146   /* True if we have tried to read this section.  */
147   char readin;
148   /* True if this is a virtual section, False otherwise.
149      This specifies which of s.section and s.containing_section to use.  */
150   char is_virtual;
151 };
152
153 typedef struct dwarf2_section_info dwarf2_section_info_def;
154 DEF_VEC_O (dwarf2_section_info_def);
155
156 /* All offsets in the index are of this type.  It must be
157    architecture-independent.  */
158 typedef uint32_t offset_type;
159
160 DEF_VEC_I (offset_type);
161
162 /* Ensure only legit values are used.  */
163 #define DW2_GDB_INDEX_SYMBOL_STATIC_SET_VALUE(cu_index, value) \
164   do { \
165     gdb_assert ((unsigned int) (value) <= 1); \
166     GDB_INDEX_SYMBOL_STATIC_SET_VALUE((cu_index), (value)); \
167   } while (0)
168
169 /* Ensure only legit values are used.  */
170 #define DW2_GDB_INDEX_SYMBOL_KIND_SET_VALUE(cu_index, value) \
171   do { \
172     gdb_assert ((value) >= GDB_INDEX_SYMBOL_KIND_TYPE \
173                 && (value) <= GDB_INDEX_SYMBOL_KIND_OTHER); \
174     GDB_INDEX_SYMBOL_KIND_SET_VALUE((cu_index), (value)); \
175   } while (0)
176
177 /* Ensure we don't use more than the alloted nuber of bits for the CU.  */
178 #define DW2_GDB_INDEX_CU_SET_VALUE(cu_index, value) \
179   do { \
180     gdb_assert (((value) & ~GDB_INDEX_CU_MASK) == 0); \
181     GDB_INDEX_CU_SET_VALUE((cu_index), (value)); \
182   } while (0)
183
184 /* A description of the mapped index.  The file format is described in
185    a comment by the code that writes the index.  */
186 struct mapped_index
187 {
188   /* Index data format version.  */
189   int version;
190
191   /* The total length of the buffer.  */
192   off_t total_size;
193
194   /* A pointer to the address table data.  */
195   const gdb_byte *address_table;
196
197   /* Size of the address table data in bytes.  */
198   offset_type address_table_size;
199
200   /* The symbol table, implemented as a hash table.  */
201   const offset_type *symbol_table;
202
203   /* Size in slots, each slot is 2 offset_types.  */
204   offset_type symbol_table_slots;
205
206   /* A pointer to the constant pool.  */
207   const char *constant_pool;
208 };
209
210 typedef struct dwarf2_per_cu_data *dwarf2_per_cu_ptr;
211 DEF_VEC_P (dwarf2_per_cu_ptr);
212
213 struct tu_stats
214 {
215   int nr_uniq_abbrev_tables;
216   int nr_symtabs;
217   int nr_symtab_sharers;
218   int nr_stmt_less_type_units;
219   int nr_all_type_units_reallocs;
220 };
221
222 /* Collection of data recorded per objfile.
223    This hangs off of dwarf2_objfile_data_key.  */
224
225 struct dwarf2_per_objfile
226 {
227   /* Construct a dwarf2_per_objfile for OBJFILE.  NAMES points to the
228      dwarf2 section names, or is NULL if the standard ELF names are
229      used.  */
230   dwarf2_per_objfile (struct objfile *objfile,
231                       const dwarf2_debug_sections *names);
232
233   ~dwarf2_per_objfile ();
234
235   /* Disable copy.  */
236   dwarf2_per_objfile (const dwarf2_per_objfile &) = delete;
237   void operator= (const dwarf2_per_objfile &) = delete;
238
239   /* Free all cached compilation units.  */
240   void free_cached_comp_units ();
241 private:
242   /* This function is mapped across the sections and remembers the
243      offset and size of each of the debugging sections we are
244      interested in.  */
245   void locate_sections (bfd *abfd, asection *sectp,
246                         const dwarf2_debug_sections &names);
247
248 public:
249   dwarf2_section_info info {};
250   dwarf2_section_info abbrev {};
251   dwarf2_section_info line {};
252   dwarf2_section_info loc {};
253   dwarf2_section_info loclists {};
254   dwarf2_section_info macinfo {};
255   dwarf2_section_info macro {};
256   dwarf2_section_info str {};
257   dwarf2_section_info line_str {};
258   dwarf2_section_info ranges {};
259   dwarf2_section_info rnglists {};
260   dwarf2_section_info addr {};
261   dwarf2_section_info frame {};
262   dwarf2_section_info eh_frame {};
263   dwarf2_section_info gdb_index {};
264
265   VEC (dwarf2_section_info_def) *types = NULL;
266
267   /* Back link.  */
268   struct objfile *objfile = NULL;
269
270   /* Table of all the compilation units.  This is used to locate
271      the target compilation unit of a particular reference.  */
272   struct dwarf2_per_cu_data **all_comp_units = NULL;
273
274   /* The number of compilation units in ALL_COMP_UNITS.  */
275   int n_comp_units = 0;
276
277   /* The number of .debug_types-related CUs.  */
278   int n_type_units = 0;
279
280   /* The number of elements allocated in all_type_units.
281      If there are skeleton-less TUs, we add them to all_type_units lazily.  */
282   int n_allocated_type_units = 0;
283
284   /* The .debug_types-related CUs (TUs).
285      This is stored in malloc space because we may realloc it.  */
286   struct signatured_type **all_type_units = NULL;
287
288   /* Table of struct type_unit_group objects.
289      The hash key is the DW_AT_stmt_list value.  */
290   htab_t type_unit_groups {};
291
292   /* A table mapping .debug_types signatures to its signatured_type entry.
293      This is NULL if the .debug_types section hasn't been read in yet.  */
294   htab_t signatured_types {};
295
296   /* Type unit statistics, to see how well the scaling improvements
297      are doing.  */
298   struct tu_stats tu_stats {};
299
300   /* A chain of compilation units that are currently read in, so that
301      they can be freed later.  */
302   dwarf2_per_cu_data *read_in_chain = NULL;
303
304   /* A table mapping DW_AT_dwo_name values to struct dwo_file objects.
305      This is NULL if the table hasn't been allocated yet.  */
306   htab_t dwo_files {};
307
308   /* True if we've checked for whether there is a DWP file.  */
309   bool dwp_checked = false;
310
311   /* The DWP file if there is one, or NULL.  */
312   struct dwp_file *dwp_file = NULL;
313
314   /* The shared '.dwz' file, if one exists.  This is used when the
315      original data was compressed using 'dwz -m'.  */
316   struct dwz_file *dwz_file = NULL;
317
318   /* A flag indicating whether this objfile has a section loaded at a
319      VMA of 0.  */
320   bool has_section_at_zero = false;
321
322   /* True if we are using the mapped index,
323      or we are faking it for OBJF_READNOW's sake.  */
324   bool using_index = false;
325
326   /* The mapped index, or NULL if .gdb_index is missing or not being used.  */
327   mapped_index *index_table = NULL;
328
329   /* When using index_table, this keeps track of all quick_file_names entries.
330      TUs typically share line table entries with a CU, so we maintain a
331      separate table of all line table entries to support the sharing.
332      Note that while there can be way more TUs than CUs, we've already
333      sorted all the TUs into "type unit groups", grouped by their
334      DW_AT_stmt_list value.  Therefore the only sharing done here is with a
335      CU and its associated TU group if there is one.  */
336   htab_t quick_file_names_table {};
337
338   /* Set during partial symbol reading, to prevent queueing of full
339      symbols.  */
340   bool reading_partial_symbols = false;
341
342   /* Table mapping type DIEs to their struct type *.
343      This is NULL if not allocated yet.
344      The mapping is done via (CU/TU + DIE offset) -> type.  */
345   htab_t die_type_hash {};
346
347   /* The CUs we recently read.  */
348   VEC (dwarf2_per_cu_ptr) *just_read_cus = NULL;
349
350   /* Table containing line_header indexed by offset and offset_in_dwz.  */
351   htab_t line_header_hash {};
352
353   /* Table containing all filenames.  This is an optional because the
354      table is lazily constructed on first access.  */
355   gdb::optional<filename_seen_cache> filenames_cache;
356 };
357
358 static struct dwarf2_per_objfile *dwarf2_per_objfile;
359
360 /* Default names of the debugging sections.  */
361
362 /* Note that if the debugging section has been compressed, it might
363    have a name like .zdebug_info.  */
364
365 static const struct dwarf2_debug_sections dwarf2_elf_names =
366 {
367   { ".debug_info", ".zdebug_info" },
368   { ".debug_abbrev", ".zdebug_abbrev" },
369   { ".debug_line", ".zdebug_line" },
370   { ".debug_loc", ".zdebug_loc" },
371   { ".debug_loclists", ".zdebug_loclists" },
372   { ".debug_macinfo", ".zdebug_macinfo" },
373   { ".debug_macro", ".zdebug_macro" },
374   { ".debug_str", ".zdebug_str" },
375   { ".debug_line_str", ".zdebug_line_str" },
376   { ".debug_ranges", ".zdebug_ranges" },
377   { ".debug_rnglists", ".zdebug_rnglists" },
378   { ".debug_types", ".zdebug_types" },
379   { ".debug_addr", ".zdebug_addr" },
380   { ".debug_frame", ".zdebug_frame" },
381   { ".eh_frame", NULL },
382   { ".gdb_index", ".zgdb_index" },
383   23
384 };
385
386 /* List of DWO/DWP sections.  */
387
388 static const struct dwop_section_names
389 {
390   struct dwarf2_section_names abbrev_dwo;
391   struct dwarf2_section_names info_dwo;
392   struct dwarf2_section_names line_dwo;
393   struct dwarf2_section_names loc_dwo;
394   struct dwarf2_section_names loclists_dwo;
395   struct dwarf2_section_names macinfo_dwo;
396   struct dwarf2_section_names macro_dwo;
397   struct dwarf2_section_names str_dwo;
398   struct dwarf2_section_names str_offsets_dwo;
399   struct dwarf2_section_names types_dwo;
400   struct dwarf2_section_names cu_index;
401   struct dwarf2_section_names tu_index;
402 }
403 dwop_section_names =
404 {
405   { ".debug_abbrev.dwo", ".zdebug_abbrev.dwo" },
406   { ".debug_info.dwo", ".zdebug_info.dwo" },
407   { ".debug_line.dwo", ".zdebug_line.dwo" },
408   { ".debug_loc.dwo", ".zdebug_loc.dwo" },
409   { ".debug_loclists.dwo", ".zdebug_loclists.dwo" },
410   { ".debug_macinfo.dwo", ".zdebug_macinfo.dwo" },
411   { ".debug_macro.dwo", ".zdebug_macro.dwo" },
412   { ".debug_str.dwo", ".zdebug_str.dwo" },
413   { ".debug_str_offsets.dwo", ".zdebug_str_offsets.dwo" },
414   { ".debug_types.dwo", ".zdebug_types.dwo" },
415   { ".debug_cu_index", ".zdebug_cu_index" },
416   { ".debug_tu_index", ".zdebug_tu_index" },
417 };
418
419 /* local data types */
420
421 /* The data in a compilation unit header, after target2host
422    translation, looks like this.  */
423 struct comp_unit_head
424 {
425   unsigned int length;
426   short version;
427   unsigned char addr_size;
428   unsigned char signed_addr_p;
429   sect_offset abbrev_sect_off;
430
431   /* Size of file offsets; either 4 or 8.  */
432   unsigned int offset_size;
433
434   /* Size of the length field; either 4 or 12.  */
435   unsigned int initial_length_size;
436
437   enum dwarf_unit_type unit_type;
438
439   /* Offset to the first byte of this compilation unit header in the
440      .debug_info section, for resolving relative reference dies.  */
441   sect_offset sect_off;
442
443   /* Offset to first die in this cu from the start of the cu.
444      This will be the first byte following the compilation unit header.  */
445   cu_offset first_die_cu_offset;
446
447   /* 64-bit signature of this type unit - it is valid only for
448      UNIT_TYPE DW_UT_type.  */
449   ULONGEST signature;
450
451   /* For types, offset in the type's DIE of the type defined by this TU.  */
452   cu_offset type_cu_offset_in_tu;
453 };
454
455 /* Type used for delaying computation of method physnames.
456    See comments for compute_delayed_physnames.  */
457 struct delayed_method_info
458 {
459   /* The type to which the method is attached, i.e., its parent class.  */
460   struct type *type;
461
462   /* The index of the method in the type's function fieldlists.  */
463   int fnfield_index;
464
465   /* The index of the method in the fieldlist.  */
466   int index;
467
468   /* The name of the DIE.  */
469   const char *name;
470
471   /*  The DIE associated with this method.  */
472   struct die_info *die;
473 };
474
475 typedef struct delayed_method_info delayed_method_info;
476 DEF_VEC_O (delayed_method_info);
477
478 /* Internal state when decoding a particular compilation unit.  */
479 struct dwarf2_cu
480 {
481   /* The objfile containing this compilation unit.  */
482   struct objfile *objfile;
483
484   /* The header of the compilation unit.  */
485   struct comp_unit_head header;
486
487   /* Base address of this compilation unit.  */
488   CORE_ADDR base_address;
489
490   /* Non-zero if base_address has been set.  */
491   int base_known;
492
493   /* The language we are debugging.  */
494   enum language language;
495   const struct language_defn *language_defn;
496
497   const char *producer;
498
499   /* The generic symbol table building routines have separate lists for
500      file scope symbols and all all other scopes (local scopes).  So
501      we need to select the right one to pass to add_symbol_to_list().
502      We do it by keeping a pointer to the correct list in list_in_scope.
503
504      FIXME: The original dwarf code just treated the file scope as the
505      first local scope, and all other local scopes as nested local
506      scopes, and worked fine.  Check to see if we really need to
507      distinguish these in buildsym.c.  */
508   struct pending **list_in_scope;
509
510   /* The abbrev table for this CU.
511      Normally this points to the abbrev table in the objfile.
512      But if DWO_UNIT is non-NULL this is the abbrev table in the DWO file.  */
513   struct abbrev_table *abbrev_table;
514
515   /* Hash table holding all the loaded partial DIEs
516      with partial_die->offset.SECT_OFF as hash.  */
517   htab_t partial_dies;
518
519   /* Storage for things with the same lifetime as this read-in compilation
520      unit, including partial DIEs.  */
521   struct obstack comp_unit_obstack;
522
523   /* When multiple dwarf2_cu structures are living in memory, this field
524      chains them all together, so that they can be released efficiently.
525      We will probably also want a generation counter so that most-recently-used
526      compilation units are cached...  */
527   struct dwarf2_per_cu_data *read_in_chain;
528
529   /* Backlink to our per_cu entry.  */
530   struct dwarf2_per_cu_data *per_cu;
531
532   /* How many compilation units ago was this CU last referenced?  */
533   int last_used;
534
535   /* A hash table of DIE cu_offset for following references with
536      die_info->offset.sect_off as hash.  */
537   htab_t die_hash;
538
539   /* Full DIEs if read in.  */
540   struct die_info *dies;
541
542   /* A set of pointers to dwarf2_per_cu_data objects for compilation
543      units referenced by this one.  Only set during full symbol processing;
544      partial symbol tables do not have dependencies.  */
545   htab_t dependencies;
546
547   /* Header data from the line table, during full symbol processing.  */
548   struct line_header *line_header;
549   /* Non-NULL if LINE_HEADER is owned by this DWARF_CU.  Otherwise,
550      it's owned by dwarf2_per_objfile::line_header_hash.  If non-NULL,
551      this is the DW_TAG_compile_unit die for this CU.  We'll hold on
552      to the line header as long as this DIE is being processed.  See
553      process_die_scope.  */
554   die_info *line_header_die_owner;
555
556   /* A list of methods which need to have physnames computed
557      after all type information has been read.  */
558   VEC (delayed_method_info) *method_list;
559
560   /* To be copied to symtab->call_site_htab.  */
561   htab_t call_site_htab;
562
563   /* Non-NULL if this CU came from a DWO file.
564      There is an invariant here that is important to remember:
565      Except for attributes copied from the top level DIE in the "main"
566      (or "stub") file in preparation for reading the DWO file
567      (e.g., DW_AT_GNU_addr_base), we KISS: there is only *one* CU.
568      Either there isn't a DWO file (in which case this is NULL and the point
569      is moot), or there is and either we're not going to read it (in which
570      case this is NULL) or there is and we are reading it (in which case this
571      is non-NULL).  */
572   struct dwo_unit *dwo_unit;
573
574   /* The DW_AT_addr_base attribute if present, zero otherwise
575      (zero is a valid value though).
576      Note this value comes from the Fission stub CU/TU's DIE.  */
577   ULONGEST addr_base;
578
579   /* The DW_AT_ranges_base attribute if present, zero otherwise
580      (zero is a valid value though).
581      Note this value comes from the Fission stub CU/TU's DIE.
582      Also note that the value is zero in the non-DWO case so this value can
583      be used without needing to know whether DWO files are in use or not.
584      N.B. This does not apply to DW_AT_ranges appearing in
585      DW_TAG_compile_unit dies.  This is a bit of a wart, consider if ever
586      DW_AT_ranges appeared in the DW_TAG_compile_unit of DWO DIEs: then
587      DW_AT_ranges_base *would* have to be applied, and we'd have to care
588      whether the DW_AT_ranges attribute came from the skeleton or DWO.  */
589   ULONGEST ranges_base;
590
591   /* Mark used when releasing cached dies.  */
592   unsigned int mark : 1;
593
594   /* This CU references .debug_loc.  See the symtab->locations_valid field.
595      This test is imperfect as there may exist optimized debug code not using
596      any location list and still facing inlining issues if handled as
597      unoptimized code.  For a future better test see GCC PR other/32998.  */
598   unsigned int has_loclist : 1;
599
600   /* These cache the results for producer_is_* fields.  CHECKED_PRODUCER is set
601      if all the producer_is_* fields are valid.  This information is cached
602      because profiling CU expansion showed excessive time spent in
603      producer_is_gxx_lt_4_6.  */
604   unsigned int checked_producer : 1;
605   unsigned int producer_is_gxx_lt_4_6 : 1;
606   unsigned int producer_is_gcc_lt_4_3 : 1;
607   unsigned int producer_is_icc : 1;
608
609   /* When set, the file that we're processing is known to have
610      debugging info for C++ namespaces.  GCC 3.3.x did not produce
611      this information, but later versions do.  */
612
613   unsigned int processing_has_namespace_info : 1;
614 };
615
616 /* Persistent data held for a compilation unit, even when not
617    processing it.  We put a pointer to this structure in the
618    read_symtab_private field of the psymtab.  */
619
620 struct dwarf2_per_cu_data
621 {
622   /* The start offset and length of this compilation unit.
623      NOTE: Unlike comp_unit_head.length, this length includes
624      initial_length_size.
625      If the DIE refers to a DWO file, this is always of the original die,
626      not the DWO file.  */
627   sect_offset sect_off;
628   unsigned int length;
629
630   /* DWARF standard version this data has been read from (such as 4 or 5).  */
631   short dwarf_version;
632
633   /* Flag indicating this compilation unit will be read in before
634      any of the current compilation units are processed.  */
635   unsigned int queued : 1;
636
637   /* This flag will be set when reading partial DIEs if we need to load
638      absolutely all DIEs for this compilation unit, instead of just the ones
639      we think are interesting.  It gets set if we look for a DIE in the
640      hash table and don't find it.  */
641   unsigned int load_all_dies : 1;
642
643   /* Non-zero if this CU is from .debug_types.
644      Struct dwarf2_per_cu_data is contained in struct signatured_type iff
645      this is non-zero.  */
646   unsigned int is_debug_types : 1;
647
648   /* Non-zero if this CU is from the .dwz file.  */
649   unsigned int is_dwz : 1;
650
651   /* Non-zero if reading a TU directly from a DWO file, bypassing the stub.
652      This flag is only valid if is_debug_types is true.
653      We can't read a CU directly from a DWO file: There are required
654      attributes in the stub.  */
655   unsigned int reading_dwo_directly : 1;
656
657   /* Non-zero if the TU has been read.
658      This is used to assist the "Stay in DWO Optimization" for Fission:
659      When reading a DWO, it's faster to read TUs from the DWO instead of
660      fetching them from random other DWOs (due to comdat folding).
661      If the TU has already been read, the optimization is unnecessary
662      (and unwise - we don't want to change where gdb thinks the TU lives
663      "midflight").
664      This flag is only valid if is_debug_types is true.  */
665   unsigned int tu_read : 1;
666
667   /* The section this CU/TU lives in.
668      If the DIE refers to a DWO file, this is always the original die,
669      not the DWO file.  */
670   struct dwarf2_section_info *section;
671
672   /* Set to non-NULL iff this CU is currently loaded.  When it gets freed out
673      of the CU cache it gets reset to NULL again.  This is left as NULL for
674      dummy CUs (a CU header, but nothing else).  */
675   struct dwarf2_cu *cu;
676
677   /* The corresponding objfile.
678      Normally we can get the objfile from dwarf2_per_objfile.
679      However we can enter this file with just a "per_cu" handle.  */
680   struct objfile *objfile;
681
682   /* When dwarf2_per_objfile->using_index is true, the 'quick' field
683      is active.  Otherwise, the 'psymtab' field is active.  */
684   union
685   {
686     /* The partial symbol table associated with this compilation unit,
687        or NULL for unread partial units.  */
688     struct partial_symtab *psymtab;
689
690     /* Data needed by the "quick" functions.  */
691     struct dwarf2_per_cu_quick_data *quick;
692   } v;
693
694   /* The CUs we import using DW_TAG_imported_unit.  This is filled in
695      while reading psymtabs, used to compute the psymtab dependencies,
696      and then cleared.  Then it is filled in again while reading full
697      symbols, and only deleted when the objfile is destroyed.
698
699      This is also used to work around a difference between the way gold
700      generates .gdb_index version <=7 and the way gdb does.  Arguably this
701      is a gold bug.  For symbols coming from TUs, gold records in the index
702      the CU that includes the TU instead of the TU itself.  This breaks
703      dw2_lookup_symbol: It assumes that if the index says symbol X lives
704      in CU/TU Y, then one need only expand Y and a subsequent lookup in Y
705      will find X.  Alas TUs live in their own symtab, so after expanding CU Y
706      we need to look in TU Z to find X.  Fortunately, this is akin to
707      DW_TAG_imported_unit, so we just use the same mechanism: For
708      .gdb_index version <=7 this also records the TUs that the CU referred
709      to.  Concurrently with this change gdb was modified to emit version 8
710      indices so we only pay a price for gold generated indices.
711      http://sourceware.org/bugzilla/show_bug.cgi?id=15021.  */
712   VEC (dwarf2_per_cu_ptr) *imported_symtabs;
713 };
714
715 /* Entry in the signatured_types hash table.  */
716
717 struct signatured_type
718 {
719   /* The "per_cu" object of this type.
720      This struct is used iff per_cu.is_debug_types.
721      N.B.: This is the first member so that it's easy to convert pointers
722      between them.  */
723   struct dwarf2_per_cu_data per_cu;
724
725   /* The type's signature.  */
726   ULONGEST signature;
727
728   /* Offset in the TU of the type's DIE, as read from the TU header.
729      If this TU is a DWO stub and the definition lives in a DWO file
730      (specified by DW_AT_GNU_dwo_name), this value is unusable.  */
731   cu_offset type_offset_in_tu;
732
733   /* Offset in the section of the type's DIE.
734      If the definition lives in a DWO file, this is the offset in the
735      .debug_types.dwo section.
736      The value is zero until the actual value is known.
737      Zero is otherwise not a valid section offset.  */
738   sect_offset type_offset_in_section;
739
740   /* Type units are grouped by their DW_AT_stmt_list entry so that they
741      can share them.  This points to the containing symtab.  */
742   struct type_unit_group *type_unit_group;
743
744   /* The type.
745      The first time we encounter this type we fully read it in and install it
746      in the symbol tables.  Subsequent times we only need the type.  */
747   struct type *type;
748
749   /* Containing DWO unit.
750      This field is valid iff per_cu.reading_dwo_directly.  */
751   struct dwo_unit *dwo_unit;
752 };
753
754 typedef struct signatured_type *sig_type_ptr;
755 DEF_VEC_P (sig_type_ptr);
756
757 /* A struct that can be used as a hash key for tables based on DW_AT_stmt_list.
758    This includes type_unit_group and quick_file_names.  */
759
760 struct stmt_list_hash
761 {
762   /* The DWO unit this table is from or NULL if there is none.  */
763   struct dwo_unit *dwo_unit;
764
765   /* Offset in .debug_line or .debug_line.dwo.  */
766   sect_offset line_sect_off;
767 };
768
769 /* Each element of dwarf2_per_objfile->type_unit_groups is a pointer to
770    an object of this type.  */
771
772 struct type_unit_group
773 {
774   /* dwarf2read.c's main "handle" on a TU symtab.
775      To simplify things we create an artificial CU that "includes" all the
776      type units using this stmt_list so that the rest of the code still has
777      a "per_cu" handle on the symtab.
778      This PER_CU is recognized by having no section.  */
779 #define IS_TYPE_UNIT_GROUP(per_cu) ((per_cu)->section == NULL)
780   struct dwarf2_per_cu_data per_cu;
781
782   /* The TUs that share this DW_AT_stmt_list entry.
783      This is added to while parsing type units to build partial symtabs,
784      and is deleted afterwards and not used again.  */
785   VEC (sig_type_ptr) *tus;
786
787   /* The compunit symtab.
788      Type units in a group needn't all be defined in the same source file,
789      so we create an essentially anonymous symtab as the compunit symtab.  */
790   struct compunit_symtab *compunit_symtab;
791
792   /* The data used to construct the hash key.  */
793   struct stmt_list_hash hash;
794
795   /* The number of symtabs from the line header.
796      The value here must match line_header.num_file_names.  */
797   unsigned int num_symtabs;
798
799   /* The symbol tables for this TU (obtained from the files listed in
800      DW_AT_stmt_list).
801      WARNING: The order of entries here must match the order of entries
802      in the line header.  After the first TU using this type_unit_group, the
803      line header for the subsequent TUs is recreated from this.  This is done
804      because we need to use the same symtabs for each TU using the same
805      DW_AT_stmt_list value.  Also note that symtabs may be repeated here,
806      there's no guarantee the line header doesn't have duplicate entries.  */
807   struct symtab **symtabs;
808 };
809
810 /* These sections are what may appear in a (real or virtual) DWO file.  */
811
812 struct dwo_sections
813 {
814   struct dwarf2_section_info abbrev;
815   struct dwarf2_section_info line;
816   struct dwarf2_section_info loc;
817   struct dwarf2_section_info loclists;
818   struct dwarf2_section_info macinfo;
819   struct dwarf2_section_info macro;
820   struct dwarf2_section_info str;
821   struct dwarf2_section_info str_offsets;
822   /* In the case of a virtual DWO file, these two are unused.  */
823   struct dwarf2_section_info info;
824   VEC (dwarf2_section_info_def) *types;
825 };
826
827 /* CUs/TUs in DWP/DWO files.  */
828
829 struct dwo_unit
830 {
831   /* Backlink to the containing struct dwo_file.  */
832   struct dwo_file *dwo_file;
833
834   /* The "id" that distinguishes this CU/TU.
835      .debug_info calls this "dwo_id", .debug_types calls this "signature".
836      Since signatures came first, we stick with it for consistency.  */
837   ULONGEST signature;
838
839   /* The section this CU/TU lives in, in the DWO file.  */
840   struct dwarf2_section_info *section;
841
842   /* Same as dwarf2_per_cu_data:{sect_off,length} but in the DWO section.  */
843   sect_offset sect_off;
844   unsigned int length;
845
846   /* For types, offset in the type's DIE of the type defined by this TU.  */
847   cu_offset type_offset_in_tu;
848 };
849
850 /* include/dwarf2.h defines the DWP section codes.
851    It defines a max value but it doesn't define a min value, which we
852    use for error checking, so provide one.  */
853
854 enum dwp_v2_section_ids
855 {
856   DW_SECT_MIN = 1
857 };
858
859 /* Data for one DWO file.
860
861    This includes virtual DWO files (a virtual DWO file is a DWO file as it
862    appears in a DWP file).  DWP files don't really have DWO files per se -
863    comdat folding of types "loses" the DWO file they came from, and from
864    a high level view DWP files appear to contain a mass of random types.
865    However, to maintain consistency with the non-DWP case we pretend DWP
866    files contain virtual DWO files, and we assign each TU with one virtual
867    DWO file (generally based on the line and abbrev section offsets -
868    a heuristic that seems to work in practice).  */
869
870 struct dwo_file
871 {
872   /* The DW_AT_GNU_dwo_name attribute.
873      For virtual DWO files the name is constructed from the section offsets
874      of abbrev,line,loc,str_offsets so that we combine virtual DWO files
875      from related CU+TUs.  */
876   const char *dwo_name;
877
878   /* The DW_AT_comp_dir attribute.  */
879   const char *comp_dir;
880
881   /* The bfd, when the file is open.  Otherwise this is NULL.
882      This is unused(NULL) for virtual DWO files where we use dwp_file.dbfd.  */
883   bfd *dbfd;
884
885   /* The sections that make up this DWO file.
886      Remember that for virtual DWO files in DWP V2, these are virtual
887      sections (for lack of a better name).  */
888   struct dwo_sections sections;
889
890   /* The CUs in the file.
891      Each element is a struct dwo_unit. Multiple CUs per DWO are supported as
892      an extension to handle LLVM's Link Time Optimization output (where
893      multiple source files may be compiled into a single object/dwo pair). */
894   htab_t cus;
895
896   /* Table of TUs in the file.
897      Each element is a struct dwo_unit.  */
898   htab_t tus;
899 };
900
901 /* These sections are what may appear in a DWP file.  */
902
903 struct dwp_sections
904 {
905   /* These are used by both DWP version 1 and 2.  */
906   struct dwarf2_section_info str;
907   struct dwarf2_section_info cu_index;
908   struct dwarf2_section_info tu_index;
909
910   /* These are only used by DWP version 2 files.
911      In DWP version 1 the .debug_info.dwo, .debug_types.dwo, and other
912      sections are referenced by section number, and are not recorded here.
913      In DWP version 2 there is at most one copy of all these sections, each
914      section being (effectively) comprised of the concatenation of all of the
915      individual sections that exist in the version 1 format.
916      To keep the code simple we treat each of these concatenated pieces as a
917      section itself (a virtual section?).  */
918   struct dwarf2_section_info abbrev;
919   struct dwarf2_section_info info;
920   struct dwarf2_section_info line;
921   struct dwarf2_section_info loc;
922   struct dwarf2_section_info macinfo;
923   struct dwarf2_section_info macro;
924   struct dwarf2_section_info str_offsets;
925   struct dwarf2_section_info types;
926 };
927
928 /* These sections are what may appear in a virtual DWO file in DWP version 1.
929    A virtual DWO file is a DWO file as it appears in a DWP file.  */
930
931 struct virtual_v1_dwo_sections
932 {
933   struct dwarf2_section_info abbrev;
934   struct dwarf2_section_info line;
935   struct dwarf2_section_info loc;
936   struct dwarf2_section_info macinfo;
937   struct dwarf2_section_info macro;
938   struct dwarf2_section_info str_offsets;
939   /* Each DWP hash table entry records one CU or one TU.
940      That is recorded here, and copied to dwo_unit.section.  */
941   struct dwarf2_section_info info_or_types;
942 };
943
944 /* Similar to virtual_v1_dwo_sections, but for DWP version 2.
945    In version 2, the sections of the DWO files are concatenated together
946    and stored in one section of that name.  Thus each ELF section contains
947    several "virtual" sections.  */
948
949 struct virtual_v2_dwo_sections
950 {
951   bfd_size_type abbrev_offset;
952   bfd_size_type abbrev_size;
953
954   bfd_size_type line_offset;
955   bfd_size_type line_size;
956
957   bfd_size_type loc_offset;
958   bfd_size_type loc_size;
959
960   bfd_size_type macinfo_offset;
961   bfd_size_type macinfo_size;
962
963   bfd_size_type macro_offset;
964   bfd_size_type macro_size;
965
966   bfd_size_type str_offsets_offset;
967   bfd_size_type str_offsets_size;
968
969   /* Each DWP hash table entry records one CU or one TU.
970      That is recorded here, and copied to dwo_unit.section.  */
971   bfd_size_type info_or_types_offset;
972   bfd_size_type info_or_types_size;
973 };
974
975 /* Contents of DWP hash tables.  */
976
977 struct dwp_hash_table
978 {
979   uint32_t version, nr_columns;
980   uint32_t nr_units, nr_slots;
981   const gdb_byte *hash_table, *unit_table;
982   union
983   {
984     struct
985     {
986       const gdb_byte *indices;
987     } v1;
988     struct
989     {
990       /* This is indexed by column number and gives the id of the section
991          in that column.  */
992 #define MAX_NR_V2_DWO_SECTIONS \
993   (1 /* .debug_info or .debug_types */ \
994    + 1 /* .debug_abbrev */ \
995    + 1 /* .debug_line */ \
996    + 1 /* .debug_loc */ \
997    + 1 /* .debug_str_offsets */ \
998    + 1 /* .debug_macro or .debug_macinfo */)
999       int section_ids[MAX_NR_V2_DWO_SECTIONS];
1000       const gdb_byte *offsets;
1001       const gdb_byte *sizes;
1002     } v2;
1003   } section_pool;
1004 };
1005
1006 /* Data for one DWP file.  */
1007
1008 struct dwp_file
1009 {
1010   /* Name of the file.  */
1011   const char *name;
1012
1013   /* File format version.  */
1014   int version;
1015
1016   /* The bfd.  */
1017   bfd *dbfd;
1018
1019   /* Section info for this file.  */
1020   struct dwp_sections sections;
1021
1022   /* Table of CUs in the file.  */
1023   const struct dwp_hash_table *cus;
1024
1025   /* Table of TUs in the file.  */
1026   const struct dwp_hash_table *tus;
1027
1028   /* Tables of loaded CUs/TUs.  Each entry is a struct dwo_unit *.  */
1029   htab_t loaded_cus;
1030   htab_t loaded_tus;
1031
1032   /* Table to map ELF section numbers to their sections.
1033      This is only needed for the DWP V1 file format.  */
1034   unsigned int num_sections;
1035   asection **elf_sections;
1036 };
1037
1038 /* This represents a '.dwz' file.  */
1039
1040 struct dwz_file
1041 {
1042   /* A dwz file can only contain a few sections.  */
1043   struct dwarf2_section_info abbrev;
1044   struct dwarf2_section_info info;
1045   struct dwarf2_section_info str;
1046   struct dwarf2_section_info line;
1047   struct dwarf2_section_info macro;
1048   struct dwarf2_section_info gdb_index;
1049
1050   /* The dwz's BFD.  */
1051   bfd *dwz_bfd;
1052 };
1053
1054 /* Struct used to pass misc. parameters to read_die_and_children, et
1055    al.  which are used for both .debug_info and .debug_types dies.
1056    All parameters here are unchanging for the life of the call.  This
1057    struct exists to abstract away the constant parameters of die reading.  */
1058
1059 struct die_reader_specs
1060 {
1061   /* The bfd of die_section.  */
1062   bfd* abfd;
1063
1064   /* The CU of the DIE we are parsing.  */
1065   struct dwarf2_cu *cu;
1066
1067   /* Non-NULL if reading a DWO file (including one packaged into a DWP).  */
1068   struct dwo_file *dwo_file;
1069
1070   /* The section the die comes from.
1071      This is either .debug_info or .debug_types, or the .dwo variants.  */
1072   struct dwarf2_section_info *die_section;
1073
1074   /* die_section->buffer.  */
1075   const gdb_byte *buffer;
1076
1077   /* The end of the buffer.  */
1078   const gdb_byte *buffer_end;
1079
1080   /* The value of the DW_AT_comp_dir attribute.  */
1081   const char *comp_dir;
1082 };
1083
1084 /* Type of function passed to init_cutu_and_read_dies, et.al.  */
1085 typedef void (die_reader_func_ftype) (const struct die_reader_specs *reader,
1086                                       const gdb_byte *info_ptr,
1087                                       struct die_info *comp_unit_die,
1088                                       int has_children,
1089                                       void *data);
1090
1091 /* A 1-based directory index.  This is a strong typedef to prevent
1092    accidentally using a directory index as a 0-based index into an
1093    array/vector.  */
1094 enum class dir_index : unsigned int {};
1095
1096 /* Likewise, a 1-based file name index.  */
1097 enum class file_name_index : unsigned int {};
1098
1099 struct file_entry
1100 {
1101   file_entry () = default;
1102
1103   file_entry (const char *name_, dir_index d_index_,
1104               unsigned int mod_time_, unsigned int length_)
1105     : name (name_),
1106       d_index (d_index_),
1107       mod_time (mod_time_),
1108       length (length_)
1109   {}
1110
1111   /* Return the include directory at D_INDEX stored in LH.  Returns
1112      NULL if D_INDEX is out of bounds.  */
1113   const char *include_dir (const line_header *lh) const;
1114
1115   /* The file name.  Note this is an observing pointer.  The memory is
1116      owned by debug_line_buffer.  */
1117   const char *name {};
1118
1119   /* The directory index (1-based).  */
1120   dir_index d_index {};
1121
1122   unsigned int mod_time {};
1123
1124   unsigned int length {};
1125
1126   /* True if referenced by the Line Number Program.  */
1127   bool included_p {};
1128
1129   /* The associated symbol table, if any.  */
1130   struct symtab *symtab {};
1131 };
1132
1133 /* The line number information for a compilation unit (found in the
1134    .debug_line section) begins with a "statement program header",
1135    which contains the following information.  */
1136 struct line_header
1137 {
1138   line_header ()
1139     : offset_in_dwz {}
1140   {}
1141
1142   /* Add an entry to the include directory table.  */
1143   void add_include_dir (const char *include_dir);
1144
1145   /* Add an entry to the file name table.  */
1146   void add_file_name (const char *name, dir_index d_index,
1147                       unsigned int mod_time, unsigned int length);
1148
1149   /* Return the include dir at INDEX (1-based).  Returns NULL if INDEX
1150      is out of bounds.  */
1151   const char *include_dir_at (dir_index index) const
1152   {
1153     /* Convert directory index number (1-based) to vector index
1154        (0-based).  */
1155     size_t vec_index = to_underlying (index) - 1;
1156
1157     if (vec_index >= include_dirs.size ())
1158       return NULL;
1159     return include_dirs[vec_index];
1160   }
1161
1162   /* Return the file name at INDEX (1-based).  Returns NULL if INDEX
1163      is out of bounds.  */
1164   file_entry *file_name_at (file_name_index index)
1165   {
1166     /* Convert file name index number (1-based) to vector index
1167        (0-based).  */
1168     size_t vec_index = to_underlying (index) - 1;
1169
1170     if (vec_index >= file_names.size ())
1171       return NULL;
1172     return &file_names[vec_index];
1173   }
1174
1175   /* Const version of the above.  */
1176   const file_entry *file_name_at (unsigned int index) const
1177   {
1178     if (index >= file_names.size ())
1179       return NULL;
1180     return &file_names[index];
1181   }
1182
1183   /* Offset of line number information in .debug_line section.  */
1184   sect_offset sect_off {};
1185
1186   /* OFFSET is for struct dwz_file associated with dwarf2_per_objfile.  */
1187   unsigned offset_in_dwz : 1; /* Can't initialize bitfields in-class.  */
1188
1189   unsigned int total_length {};
1190   unsigned short version {};
1191   unsigned int header_length {};
1192   unsigned char minimum_instruction_length {};
1193   unsigned char maximum_ops_per_instruction {};
1194   unsigned char default_is_stmt {};
1195   int line_base {};
1196   unsigned char line_range {};
1197   unsigned char opcode_base {};
1198
1199   /* standard_opcode_lengths[i] is the number of operands for the
1200      standard opcode whose value is i.  This means that
1201      standard_opcode_lengths[0] is unused, and the last meaningful
1202      element is standard_opcode_lengths[opcode_base - 1].  */
1203   std::unique_ptr<unsigned char[]> standard_opcode_lengths;
1204
1205   /* The include_directories table.  Note these are observing
1206      pointers.  The memory is owned by debug_line_buffer.  */
1207   std::vector<const char *> include_dirs;
1208
1209   /* The file_names table.  */
1210   std::vector<file_entry> file_names;
1211
1212   /* The start and end of the statement program following this
1213      header.  These point into dwarf2_per_objfile->line_buffer.  */
1214   const gdb_byte *statement_program_start {}, *statement_program_end {};
1215 };
1216
1217 typedef std::unique_ptr<line_header> line_header_up;
1218
1219 const char *
1220 file_entry::include_dir (const line_header *lh) const
1221 {
1222   return lh->include_dir_at (d_index);
1223 }
1224
1225 /* When we construct a partial symbol table entry we only
1226    need this much information.  */
1227 struct partial_die_info
1228   {
1229     /* Offset of this DIE.  */
1230     sect_offset sect_off;
1231
1232     /* DWARF-2 tag for this DIE.  */
1233     ENUM_BITFIELD(dwarf_tag) tag : 16;
1234
1235     /* Assorted flags describing the data found in this DIE.  */
1236     unsigned int has_children : 1;
1237     unsigned int is_external : 1;
1238     unsigned int is_declaration : 1;
1239     unsigned int has_type : 1;
1240     unsigned int has_specification : 1;
1241     unsigned int has_pc_info : 1;
1242     unsigned int may_be_inlined : 1;
1243
1244     /* This DIE has been marked DW_AT_main_subprogram.  */
1245     unsigned int main_subprogram : 1;
1246
1247     /* Flag set if the SCOPE field of this structure has been
1248        computed.  */
1249     unsigned int scope_set : 1;
1250
1251     /* Flag set if the DIE has a byte_size attribute.  */
1252     unsigned int has_byte_size : 1;
1253
1254     /* Flag set if the DIE has a DW_AT_const_value attribute.  */
1255     unsigned int has_const_value : 1;
1256
1257     /* Flag set if any of the DIE's children are template arguments.  */
1258     unsigned int has_template_arguments : 1;
1259
1260     /* Flag set if fixup_partial_die has been called on this die.  */
1261     unsigned int fixup_called : 1;
1262
1263     /* Flag set if DW_TAG_imported_unit uses DW_FORM_GNU_ref_alt.  */
1264     unsigned int is_dwz : 1;
1265
1266     /* Flag set if spec_offset uses DW_FORM_GNU_ref_alt.  */
1267     unsigned int spec_is_dwz : 1;
1268
1269     /* The name of this DIE.  Normally the value of DW_AT_name, but
1270        sometimes a default name for unnamed DIEs.  */
1271     const char *name;
1272
1273     /* The linkage name, if present.  */
1274     const char *linkage_name;
1275
1276     /* The scope to prepend to our children.  This is generally
1277        allocated on the comp_unit_obstack, so will disappear
1278        when this compilation unit leaves the cache.  */
1279     const char *scope;
1280
1281     /* Some data associated with the partial DIE.  The tag determines
1282        which field is live.  */
1283     union
1284     {
1285       /* The location description associated with this DIE, if any.  */
1286       struct dwarf_block *locdesc;
1287       /* The offset of an import, for DW_TAG_imported_unit.  */
1288       sect_offset sect_off;
1289     } d;
1290
1291     /* If HAS_PC_INFO, the PC range associated with this DIE.  */
1292     CORE_ADDR lowpc;
1293     CORE_ADDR highpc;
1294
1295     /* Pointer into the info_buffer (or types_buffer) pointing at the target of
1296        DW_AT_sibling, if any.  */
1297     /* NOTE: This member isn't strictly necessary, read_partial_die could
1298        return DW_AT_sibling values to its caller load_partial_dies.  */
1299     const gdb_byte *sibling;
1300
1301     /* If HAS_SPECIFICATION, the offset of the DIE referred to by
1302        DW_AT_specification (or DW_AT_abstract_origin or
1303        DW_AT_extension).  */
1304     sect_offset spec_offset;
1305
1306     /* Pointers to this DIE's parent, first child, and next sibling,
1307        if any.  */
1308     struct partial_die_info *die_parent, *die_child, *die_sibling;
1309   };
1310
1311 /* This data structure holds the information of an abbrev.  */
1312 struct abbrev_info
1313   {
1314     unsigned int number;        /* number identifying abbrev */
1315     enum dwarf_tag tag;         /* dwarf tag */
1316     unsigned short has_children;                /* boolean */
1317     unsigned short num_attrs;   /* number of attributes */
1318     struct attr_abbrev *attrs;  /* an array of attribute descriptions */
1319     struct abbrev_info *next;   /* next in chain */
1320   };
1321
1322 struct attr_abbrev
1323   {
1324     ENUM_BITFIELD(dwarf_attribute) name : 16;
1325     ENUM_BITFIELD(dwarf_form) form : 16;
1326
1327     /* It is valid only if FORM is DW_FORM_implicit_const.  */
1328     LONGEST implicit_const;
1329   };
1330
1331 /* Size of abbrev_table.abbrev_hash_table.  */
1332 #define ABBREV_HASH_SIZE 121
1333
1334 /* Top level data structure to contain an abbreviation table.  */
1335
1336 struct abbrev_table
1337 {
1338   /* Where the abbrev table came from.
1339      This is used as a sanity check when the table is used.  */
1340   sect_offset sect_off;
1341
1342   /* Storage for the abbrev table.  */
1343   struct obstack abbrev_obstack;
1344
1345   /* Hash table of abbrevs.
1346      This is an array of size ABBREV_HASH_SIZE allocated in abbrev_obstack.
1347      It could be statically allocated, but the previous code didn't so we
1348      don't either.  */
1349   struct abbrev_info **abbrevs;
1350 };
1351
1352 /* Attributes have a name and a value.  */
1353 struct attribute
1354   {
1355     ENUM_BITFIELD(dwarf_attribute) name : 16;
1356     ENUM_BITFIELD(dwarf_form) form : 15;
1357
1358     /* Has DW_STRING already been updated by dwarf2_canonicalize_name?  This
1359        field should be in u.str (existing only for DW_STRING) but it is kept
1360        here for better struct attribute alignment.  */
1361     unsigned int string_is_canonical : 1;
1362
1363     union
1364       {
1365         const char *str;
1366         struct dwarf_block *blk;
1367         ULONGEST unsnd;
1368         LONGEST snd;
1369         CORE_ADDR addr;
1370         ULONGEST signature;
1371       }
1372     u;
1373   };
1374
1375 /* This data structure holds a complete die structure.  */
1376 struct die_info
1377   {
1378     /* DWARF-2 tag for this DIE.  */
1379     ENUM_BITFIELD(dwarf_tag) tag : 16;
1380
1381     /* Number of attributes */
1382     unsigned char num_attrs;
1383
1384     /* True if we're presently building the full type name for the
1385        type derived from this DIE.  */
1386     unsigned char building_fullname : 1;
1387
1388     /* True if this die is in process.  PR 16581.  */
1389     unsigned char in_process : 1;
1390
1391     /* Abbrev number */
1392     unsigned int abbrev;
1393
1394     /* Offset in .debug_info or .debug_types section.  */
1395     sect_offset sect_off;
1396
1397     /* The dies in a compilation unit form an n-ary tree.  PARENT
1398        points to this die's parent; CHILD points to the first child of
1399        this node; and all the children of a given node are chained
1400        together via their SIBLING fields.  */
1401     struct die_info *child;     /* Its first child, if any.  */
1402     struct die_info *sibling;   /* Its next sibling, if any.  */
1403     struct die_info *parent;    /* Its parent, if any.  */
1404
1405     /* An array of attributes, with NUM_ATTRS elements.  There may be
1406        zero, but it's not common and zero-sized arrays are not
1407        sufficiently portable C.  */
1408     struct attribute attrs[1];
1409   };
1410
1411 /* Get at parts of an attribute structure.  */
1412
1413 #define DW_STRING(attr)    ((attr)->u.str)
1414 #define DW_STRING_IS_CANONICAL(attr) ((attr)->string_is_canonical)
1415 #define DW_UNSND(attr)     ((attr)->u.unsnd)
1416 #define DW_BLOCK(attr)     ((attr)->u.blk)
1417 #define DW_SND(attr)       ((attr)->u.snd)
1418 #define DW_ADDR(attr)      ((attr)->u.addr)
1419 #define DW_SIGNATURE(attr) ((attr)->u.signature)
1420
1421 /* Blocks are a bunch of untyped bytes.  */
1422 struct dwarf_block
1423   {
1424     size_t size;
1425
1426     /* Valid only if SIZE is not zero.  */
1427     const gdb_byte *data;
1428   };
1429
1430 #ifndef ATTR_ALLOC_CHUNK
1431 #define ATTR_ALLOC_CHUNK 4
1432 #endif
1433
1434 /* Allocate fields for structs, unions and enums in this size.  */
1435 #ifndef DW_FIELD_ALLOC_CHUNK
1436 #define DW_FIELD_ALLOC_CHUNK 4
1437 #endif
1438
1439 /* FIXME: We might want to set this from BFD via bfd_arch_bits_per_byte,
1440    but this would require a corresponding change in unpack_field_as_long
1441    and friends.  */
1442 static int bits_per_byte = 8;
1443
1444 struct nextfield
1445 {
1446   struct nextfield *next;
1447   int accessibility;
1448   int virtuality;
1449   struct field field;
1450 };
1451
1452 struct nextfnfield
1453 {
1454   struct nextfnfield *next;
1455   struct fn_field fnfield;
1456 };
1457
1458 struct fnfieldlist
1459 {
1460   const char *name;
1461   int length;
1462   struct nextfnfield *head;
1463 };
1464
1465 struct typedef_field_list
1466 {
1467   struct typedef_field field;
1468   struct typedef_field_list *next;
1469 };
1470
1471 /* The routines that read and process dies for a C struct or C++ class
1472    pass lists of data member fields and lists of member function fields
1473    in an instance of a field_info structure, as defined below.  */
1474 struct field_info
1475   {
1476     /* List of data member and baseclasses fields.  */
1477     struct nextfield *fields, *baseclasses;
1478
1479     /* Number of fields (including baseclasses).  */
1480     int nfields;
1481
1482     /* Number of baseclasses.  */
1483     int nbaseclasses;
1484
1485     /* Set if the accesibility of one of the fields is not public.  */
1486     int non_public_fields;
1487
1488     /* Member function fields array, entries are allocated in the order they
1489        are encountered in the object file.  */
1490     struct nextfnfield *fnfields;
1491
1492     /* Member function fieldlist array, contains name of possibly overloaded
1493        member function, number of overloaded member functions and a pointer
1494        to the head of the member function field chain.  */
1495     struct fnfieldlist *fnfieldlists;
1496
1497     /* Number of entries in the fnfieldlists array.  */
1498     int nfnfields;
1499
1500     /* typedefs defined inside this class.  TYPEDEF_FIELD_LIST contains head of
1501        a NULL terminated list of TYPEDEF_FIELD_LIST_COUNT elements.  */
1502     struct typedef_field_list *typedef_field_list;
1503     unsigned typedef_field_list_count;
1504   };
1505
1506 /* One item on the queue of compilation units to read in full symbols
1507    for.  */
1508 struct dwarf2_queue_item
1509 {
1510   struct dwarf2_per_cu_data *per_cu;
1511   enum language pretend_language;
1512   struct dwarf2_queue_item *next;
1513 };
1514
1515 /* The current queue.  */
1516 static struct dwarf2_queue_item *dwarf2_queue, *dwarf2_queue_tail;
1517
1518 /* Loaded secondary compilation units are kept in memory until they
1519    have not been referenced for the processing of this many
1520    compilation units.  Set this to zero to disable caching.  Cache
1521    sizes of up to at least twenty will improve startup time for
1522    typical inter-CU-reference binaries, at an obvious memory cost.  */
1523 static int dwarf_max_cache_age = 5;
1524 static void
1525 show_dwarf_max_cache_age (struct ui_file *file, int from_tty,
1526                           struct cmd_list_element *c, const char *value)
1527 {
1528   fprintf_filtered (file, _("The upper bound on the age of cached "
1529                             "DWARF compilation units is %s.\n"),
1530                     value);
1531 }
1532 \f
1533 /* local function prototypes */
1534
1535 static const char *get_section_name (const struct dwarf2_section_info *);
1536
1537 static const char *get_section_file_name (const struct dwarf2_section_info *);
1538
1539 static void dwarf2_find_base_address (struct die_info *die,
1540                                       struct dwarf2_cu *cu);
1541
1542 static struct partial_symtab *create_partial_symtab
1543   (struct dwarf2_per_cu_data *per_cu, const char *name);
1544
1545 static void build_type_psymtabs_reader (const struct die_reader_specs *reader,
1546                                         const gdb_byte *info_ptr,
1547                                         struct die_info *type_unit_die,
1548                                         int has_children, void *data);
1549
1550 static void dwarf2_build_psymtabs_hard (struct objfile *);
1551
1552 static void scan_partial_symbols (struct partial_die_info *,
1553                                   CORE_ADDR *, CORE_ADDR *,
1554                                   int, struct dwarf2_cu *);
1555
1556 static void add_partial_symbol (struct partial_die_info *,
1557                                 struct dwarf2_cu *);
1558
1559 static void add_partial_namespace (struct partial_die_info *pdi,
1560                                    CORE_ADDR *lowpc, CORE_ADDR *highpc,
1561                                    int set_addrmap, struct dwarf2_cu *cu);
1562
1563 static void add_partial_module (struct partial_die_info *pdi, CORE_ADDR *lowpc,
1564                                 CORE_ADDR *highpc, int set_addrmap,
1565                                 struct dwarf2_cu *cu);
1566
1567 static void add_partial_enumeration (struct partial_die_info *enum_pdi,
1568                                      struct dwarf2_cu *cu);
1569
1570 static void add_partial_subprogram (struct partial_die_info *pdi,
1571                                     CORE_ADDR *lowpc, CORE_ADDR *highpc,
1572                                     int need_pc, struct dwarf2_cu *cu);
1573
1574 static void dwarf2_read_symtab (struct partial_symtab *,
1575                                 struct objfile *);
1576
1577 static void psymtab_to_symtab_1 (struct partial_symtab *);
1578
1579 static struct abbrev_info *abbrev_table_lookup_abbrev
1580   (const struct abbrev_table *, unsigned int);
1581
1582 static struct abbrev_table *abbrev_table_read_table
1583   (struct dwarf2_section_info *, sect_offset);
1584
1585 static void abbrev_table_free (struct abbrev_table *);
1586
1587 static void abbrev_table_free_cleanup (void *);
1588
1589 static void dwarf2_read_abbrevs (struct dwarf2_cu *,
1590                                  struct dwarf2_section_info *);
1591
1592 static void dwarf2_free_abbrev_table (void *);
1593
1594 static unsigned int peek_abbrev_code (bfd *, const gdb_byte *);
1595
1596 static struct partial_die_info *load_partial_dies
1597   (const struct die_reader_specs *, const gdb_byte *, int);
1598
1599 static const gdb_byte *read_partial_die (const struct die_reader_specs *,
1600                                          struct partial_die_info *,
1601                                          struct abbrev_info *,
1602                                          unsigned int,
1603                                          const gdb_byte *);
1604
1605 static struct partial_die_info *find_partial_die (sect_offset, int,
1606                                                   struct dwarf2_cu *);
1607
1608 static void fixup_partial_die (struct partial_die_info *,
1609                                struct dwarf2_cu *);
1610
1611 static const gdb_byte *read_attribute (const struct die_reader_specs *,
1612                                        struct attribute *, struct attr_abbrev *,
1613                                        const gdb_byte *);
1614
1615 static unsigned int read_1_byte (bfd *, const gdb_byte *);
1616
1617 static int read_1_signed_byte (bfd *, const gdb_byte *);
1618
1619 static unsigned int read_2_bytes (bfd *, const gdb_byte *);
1620
1621 static unsigned int read_4_bytes (bfd *, const gdb_byte *);
1622
1623 static ULONGEST read_8_bytes (bfd *, const gdb_byte *);
1624
1625 static CORE_ADDR read_address (bfd *, const gdb_byte *ptr, struct dwarf2_cu *,
1626                                unsigned int *);
1627
1628 static LONGEST read_initial_length (bfd *, const gdb_byte *, unsigned int *);
1629
1630 static LONGEST read_checked_initial_length_and_offset
1631   (bfd *, const gdb_byte *, const struct comp_unit_head *,
1632    unsigned int *, unsigned int *);
1633
1634 static LONGEST read_offset (bfd *, const gdb_byte *,
1635                             const struct comp_unit_head *,
1636                             unsigned int *);
1637
1638 static LONGEST read_offset_1 (bfd *, const gdb_byte *, unsigned int);
1639
1640 static sect_offset read_abbrev_offset (struct dwarf2_section_info *,
1641                                        sect_offset);
1642
1643 static const gdb_byte *read_n_bytes (bfd *, const gdb_byte *, unsigned int);
1644
1645 static const char *read_direct_string (bfd *, const gdb_byte *, unsigned int *);
1646
1647 static const char *read_indirect_string (bfd *, const gdb_byte *,
1648                                          const struct comp_unit_head *,
1649                                          unsigned int *);
1650
1651 static const char *read_indirect_line_string (bfd *, const gdb_byte *,
1652                                               const struct comp_unit_head *,
1653                                               unsigned int *);
1654
1655 static const char *read_indirect_string_from_dwz (struct dwz_file *, LONGEST);
1656
1657 static LONGEST read_signed_leb128 (bfd *, const gdb_byte *, unsigned int *);
1658
1659 static CORE_ADDR read_addr_index_from_leb128 (struct dwarf2_cu *,
1660                                               const gdb_byte *,
1661                                               unsigned int *);
1662
1663 static const char *read_str_index (const struct die_reader_specs *reader,
1664                                    ULONGEST str_index);
1665
1666 static void set_cu_language (unsigned int, struct dwarf2_cu *);
1667
1668 static struct attribute *dwarf2_attr (struct die_info *, unsigned int,
1669                                       struct dwarf2_cu *);
1670
1671 static struct attribute *dwarf2_attr_no_follow (struct die_info *,
1672                                                 unsigned int);
1673
1674 static const char *dwarf2_string_attr (struct die_info *die, unsigned int name,
1675                                        struct dwarf2_cu *cu);
1676
1677 static int dwarf2_flag_true_p (struct die_info *die, unsigned name,
1678                                struct dwarf2_cu *cu);
1679
1680 static int die_is_declaration (struct die_info *, struct dwarf2_cu *cu);
1681
1682 static struct die_info *die_specification (struct die_info *die,
1683                                            struct dwarf2_cu **);
1684
1685 static line_header_up dwarf_decode_line_header (sect_offset sect_off,
1686                                                 struct dwarf2_cu *cu);
1687
1688 static void dwarf_decode_lines (struct line_header *, const char *,
1689                                 struct dwarf2_cu *, struct partial_symtab *,
1690                                 CORE_ADDR, int decode_mapping);
1691
1692 static void dwarf2_start_subfile (const char *, const char *);
1693
1694 static struct compunit_symtab *dwarf2_start_symtab (struct dwarf2_cu *,
1695                                                     const char *, const char *,
1696                                                     CORE_ADDR);
1697
1698 static struct symbol *new_symbol (struct die_info *, struct type *,
1699                                   struct dwarf2_cu *);
1700
1701 static struct symbol *new_symbol_full (struct die_info *, struct type *,
1702                                        struct dwarf2_cu *, struct symbol *);
1703
1704 static void dwarf2_const_value (const struct attribute *, struct symbol *,
1705                                 struct dwarf2_cu *);
1706
1707 static void dwarf2_const_value_attr (const struct attribute *attr,
1708                                      struct type *type,
1709                                      const char *name,
1710                                      struct obstack *obstack,
1711                                      struct dwarf2_cu *cu, LONGEST *value,
1712                                      const gdb_byte **bytes,
1713                                      struct dwarf2_locexpr_baton **baton);
1714
1715 static struct type *die_type (struct die_info *, struct dwarf2_cu *);
1716
1717 static int need_gnat_info (struct dwarf2_cu *);
1718
1719 static struct type *die_descriptive_type (struct die_info *,
1720                                           struct dwarf2_cu *);
1721
1722 static void set_descriptive_type (struct type *, struct die_info *,
1723                                   struct dwarf2_cu *);
1724
1725 static struct type *die_containing_type (struct die_info *,
1726                                          struct dwarf2_cu *);
1727
1728 static struct type *lookup_die_type (struct die_info *, const struct attribute *,
1729                                      struct dwarf2_cu *);
1730
1731 static struct type *read_type_die (struct die_info *, struct dwarf2_cu *);
1732
1733 static struct type *read_type_die_1 (struct die_info *, struct dwarf2_cu *);
1734
1735 static const char *determine_prefix (struct die_info *die, struct dwarf2_cu *);
1736
1737 static char *typename_concat (struct obstack *obs, const char *prefix,
1738                               const char *suffix, int physname,
1739                               struct dwarf2_cu *cu);
1740
1741 static void read_file_scope (struct die_info *, struct dwarf2_cu *);
1742
1743 static void read_type_unit_scope (struct die_info *, struct dwarf2_cu *);
1744
1745 static void read_func_scope (struct die_info *, struct dwarf2_cu *);
1746
1747 static void read_lexical_block_scope (struct die_info *, struct dwarf2_cu *);
1748
1749 static void read_call_site_scope (struct die_info *die, struct dwarf2_cu *cu);
1750
1751 static int dwarf2_ranges_read (unsigned, CORE_ADDR *, CORE_ADDR *,
1752                                struct dwarf2_cu *, struct partial_symtab *);
1753
1754 /* How dwarf2_get_pc_bounds constructed its *LOWPC and *HIGHPC return
1755    values.  Keep the items ordered with increasing constraints compliance.  */
1756 enum pc_bounds_kind
1757 {
1758   /* No attribute DW_AT_low_pc, DW_AT_high_pc or DW_AT_ranges was found.  */
1759   PC_BOUNDS_NOT_PRESENT,
1760
1761   /* Some of the attributes DW_AT_low_pc, DW_AT_high_pc or DW_AT_ranges
1762      were present but they do not form a valid range of PC addresses.  */
1763   PC_BOUNDS_INVALID,
1764
1765   /* Discontiguous range was found - that is DW_AT_ranges was found.  */
1766   PC_BOUNDS_RANGES,
1767
1768   /* Contiguous range was found - DW_AT_low_pc and DW_AT_high_pc were found.  */
1769   PC_BOUNDS_HIGH_LOW,
1770 };
1771
1772 static enum pc_bounds_kind dwarf2_get_pc_bounds (struct die_info *,
1773                                                  CORE_ADDR *, CORE_ADDR *,
1774                                                  struct dwarf2_cu *,
1775                                                  struct partial_symtab *);
1776
1777 static void get_scope_pc_bounds (struct die_info *,
1778                                  CORE_ADDR *, CORE_ADDR *,
1779                                  struct dwarf2_cu *);
1780
1781 static void dwarf2_record_block_ranges (struct die_info *, struct block *,
1782                                         CORE_ADDR, struct dwarf2_cu *);
1783
1784 static void dwarf2_add_field (struct field_info *, struct die_info *,
1785                               struct dwarf2_cu *);
1786
1787 static void dwarf2_attach_fields_to_type (struct field_info *,
1788                                           struct type *, struct dwarf2_cu *);
1789
1790 static void dwarf2_add_member_fn (struct field_info *,
1791                                   struct die_info *, struct type *,
1792                                   struct dwarf2_cu *);
1793
1794 static void dwarf2_attach_fn_fields_to_type (struct field_info *,
1795                                              struct type *,
1796                                              struct dwarf2_cu *);
1797
1798 static void process_structure_scope (struct die_info *, struct dwarf2_cu *);
1799
1800 static void read_common_block (struct die_info *, struct dwarf2_cu *);
1801
1802 static void read_namespace (struct die_info *die, struct dwarf2_cu *);
1803
1804 static void read_module (struct die_info *die, struct dwarf2_cu *cu);
1805
1806 static struct using_direct **using_directives (enum language);
1807
1808 static void read_import_statement (struct die_info *die, struct dwarf2_cu *);
1809
1810 static int read_namespace_alias (struct die_info *die, struct dwarf2_cu *cu);
1811
1812 static struct type *read_module_type (struct die_info *die,
1813                                       struct dwarf2_cu *cu);
1814
1815 static const char *namespace_name (struct die_info *die,
1816                                    int *is_anonymous, struct dwarf2_cu *);
1817
1818 static void process_enumeration_scope (struct die_info *, struct dwarf2_cu *);
1819
1820 static CORE_ADDR decode_locdesc (struct dwarf_block *, struct dwarf2_cu *);
1821
1822 static enum dwarf_array_dim_ordering read_array_order (struct die_info *,
1823                                                        struct dwarf2_cu *);
1824
1825 static struct die_info *read_die_and_siblings_1
1826   (const struct die_reader_specs *, const gdb_byte *, const gdb_byte **,
1827    struct die_info *);
1828
1829 static struct die_info *read_die_and_siblings (const struct die_reader_specs *,
1830                                                const gdb_byte *info_ptr,
1831                                                const gdb_byte **new_info_ptr,
1832                                                struct die_info *parent);
1833
1834 static const gdb_byte *read_full_die_1 (const struct die_reader_specs *,
1835                                         struct die_info **, const gdb_byte *,
1836                                         int *, int);
1837
1838 static const gdb_byte *read_full_die (const struct die_reader_specs *,
1839                                       struct die_info **, const gdb_byte *,
1840                                       int *);
1841
1842 static void process_die (struct die_info *, struct dwarf2_cu *);
1843
1844 static const char *dwarf2_canonicalize_name (const char *, struct dwarf2_cu *,
1845                                              struct obstack *);
1846
1847 static const char *dwarf2_name (struct die_info *die, struct dwarf2_cu *);
1848
1849 static const char *dwarf2_full_name (const char *name,
1850                                      struct die_info *die,
1851                                      struct dwarf2_cu *cu);
1852
1853 static const char *dwarf2_physname (const char *name, struct die_info *die,
1854                                     struct dwarf2_cu *cu);
1855
1856 static struct die_info *dwarf2_extension (struct die_info *die,
1857                                           struct dwarf2_cu **);
1858
1859 static const char *dwarf_tag_name (unsigned int);
1860
1861 static const char *dwarf_attr_name (unsigned int);
1862
1863 static const char *dwarf_form_name (unsigned int);
1864
1865 static const char *dwarf_bool_name (unsigned int);
1866
1867 static const char *dwarf_type_encoding_name (unsigned int);
1868
1869 static struct die_info *sibling_die (struct die_info *);
1870
1871 static void dump_die_shallow (struct ui_file *, int indent, struct die_info *);
1872
1873 static void dump_die_for_error (struct die_info *);
1874
1875 static void dump_die_1 (struct ui_file *, int level, int max_level,
1876                         struct die_info *);
1877
1878 /*static*/ void dump_die (struct die_info *, int max_level);
1879
1880 static void store_in_ref_table (struct die_info *,
1881                                 struct dwarf2_cu *);
1882
1883 static sect_offset dwarf2_get_ref_die_offset (const struct attribute *);
1884
1885 static LONGEST dwarf2_get_attr_constant_value (const struct attribute *, int);
1886
1887 static struct die_info *follow_die_ref_or_sig (struct die_info *,
1888                                                const struct attribute *,
1889                                                struct dwarf2_cu **);
1890
1891 static struct die_info *follow_die_ref (struct die_info *,
1892                                         const struct attribute *,
1893                                         struct dwarf2_cu **);
1894
1895 static struct die_info *follow_die_sig (struct die_info *,
1896                                         const struct attribute *,
1897                                         struct dwarf2_cu **);
1898
1899 static struct type *get_signatured_type (struct die_info *, ULONGEST,
1900                                          struct dwarf2_cu *);
1901
1902 static struct type *get_DW_AT_signature_type (struct die_info *,
1903                                               const struct attribute *,
1904                                               struct dwarf2_cu *);
1905
1906 static void load_full_type_unit (struct dwarf2_per_cu_data *per_cu);
1907
1908 static void read_signatured_type (struct signatured_type *);
1909
1910 static int attr_to_dynamic_prop (const struct attribute *attr,
1911                                  struct die_info *die, struct dwarf2_cu *cu,
1912                                  struct dynamic_prop *prop);
1913
1914 /* memory allocation interface */
1915
1916 static struct dwarf_block *dwarf_alloc_block (struct dwarf2_cu *);
1917
1918 static struct die_info *dwarf_alloc_die (struct dwarf2_cu *, int);
1919
1920 static void dwarf_decode_macros (struct dwarf2_cu *, unsigned int, int);
1921
1922 static int attr_form_is_block (const struct attribute *);
1923
1924 static int attr_form_is_section_offset (const struct attribute *);
1925
1926 static int attr_form_is_constant (const struct attribute *);
1927
1928 static int attr_form_is_ref (const struct attribute *);
1929
1930 static void fill_in_loclist_baton (struct dwarf2_cu *cu,
1931                                    struct dwarf2_loclist_baton *baton,
1932                                    const struct attribute *attr);
1933
1934 static void dwarf2_symbol_mark_computed (const struct attribute *attr,
1935                                          struct symbol *sym,
1936                                          struct dwarf2_cu *cu,
1937                                          int is_block);
1938
1939 static const gdb_byte *skip_one_die (const struct die_reader_specs *reader,
1940                                      const gdb_byte *info_ptr,
1941                                      struct abbrev_info *abbrev);
1942
1943 static void free_stack_comp_unit (void *);
1944
1945 static hashval_t partial_die_hash (const void *item);
1946
1947 static int partial_die_eq (const void *item_lhs, const void *item_rhs);
1948
1949 static struct dwarf2_per_cu_data *dwarf2_find_containing_comp_unit
1950   (sect_offset sect_off, unsigned int offset_in_dwz, struct objfile *objfile);
1951
1952 static void init_one_comp_unit (struct dwarf2_cu *cu,
1953                                 struct dwarf2_per_cu_data *per_cu);
1954
1955 static void prepare_one_comp_unit (struct dwarf2_cu *cu,
1956                                    struct die_info *comp_unit_die,
1957                                    enum language pretend_language);
1958
1959 static void free_heap_comp_unit (void *);
1960
1961 static void free_cached_comp_units (void *);
1962
1963 static void age_cached_comp_units (void);
1964
1965 static void free_one_cached_comp_unit (struct dwarf2_per_cu_data *);
1966
1967 static struct type *set_die_type (struct die_info *, struct type *,
1968                                   struct dwarf2_cu *);
1969
1970 static void create_all_comp_units (struct objfile *);
1971
1972 static int create_all_type_units (struct objfile *);
1973
1974 static void load_full_comp_unit (struct dwarf2_per_cu_data *,
1975                                  enum language);
1976
1977 static void process_full_comp_unit (struct dwarf2_per_cu_data *,
1978                                     enum language);
1979
1980 static void process_full_type_unit (struct dwarf2_per_cu_data *,
1981                                     enum language);
1982
1983 static void dwarf2_add_dependence (struct dwarf2_cu *,
1984                                    struct dwarf2_per_cu_data *);
1985
1986 static void dwarf2_mark (struct dwarf2_cu *);
1987
1988 static void dwarf2_clear_marks (struct dwarf2_per_cu_data *);
1989
1990 static struct type *get_die_type_at_offset (sect_offset,
1991                                             struct dwarf2_per_cu_data *);
1992
1993 static struct type *get_die_type (struct die_info *die, struct dwarf2_cu *cu);
1994
1995 static void dwarf2_release_queue (void *dummy);
1996
1997 static void queue_comp_unit (struct dwarf2_per_cu_data *per_cu,
1998                              enum language pretend_language);
1999
2000 static void process_queue (void);
2001
2002 /* The return type of find_file_and_directory.  Note, the enclosed
2003    string pointers are only valid while this object is valid.  */
2004
2005 struct file_and_directory
2006 {
2007   /* The filename.  This is never NULL.  */
2008   const char *name;
2009
2010   /* The compilation directory.  NULL if not known.  If we needed to
2011      compute a new string, this points to COMP_DIR_STORAGE, otherwise,
2012      points directly to the DW_AT_comp_dir string attribute owned by
2013      the obstack that owns the DIE.  */
2014   const char *comp_dir;
2015
2016   /* If we needed to build a new string for comp_dir, this is what
2017      owns the storage.  */
2018   std::string comp_dir_storage;
2019 };
2020
2021 static file_and_directory find_file_and_directory (struct die_info *die,
2022                                                    struct dwarf2_cu *cu);
2023
2024 static char *file_full_name (int file, struct line_header *lh,
2025                              const char *comp_dir);
2026
2027 /* Expected enum dwarf_unit_type for read_comp_unit_head.  */
2028 enum class rcuh_kind { COMPILE, TYPE };
2029
2030 static const gdb_byte *read_and_check_comp_unit_head
2031   (struct comp_unit_head *header,
2032    struct dwarf2_section_info *section,
2033    struct dwarf2_section_info *abbrev_section, const gdb_byte *info_ptr,
2034    rcuh_kind section_kind);
2035
2036 static void init_cutu_and_read_dies
2037   (struct dwarf2_per_cu_data *this_cu, struct abbrev_table *abbrev_table,
2038    int use_existing_cu, int keep,
2039    die_reader_func_ftype *die_reader_func, void *data);
2040
2041 static void init_cutu_and_read_dies_simple
2042   (struct dwarf2_per_cu_data *this_cu,
2043    die_reader_func_ftype *die_reader_func, void *data);
2044
2045 static htab_t allocate_signatured_type_table (struct objfile *objfile);
2046
2047 static htab_t allocate_dwo_unit_table (struct objfile *objfile);
2048
2049 static struct dwo_unit *lookup_dwo_unit_in_dwp
2050   (struct dwp_file *dwp_file, const char *comp_dir,
2051    ULONGEST signature, int is_debug_types);
2052
2053 static struct dwp_file *get_dwp_file (void);
2054
2055 static struct dwo_unit *lookup_dwo_comp_unit
2056   (struct dwarf2_per_cu_data *, const char *, const char *, ULONGEST);
2057
2058 static struct dwo_unit *lookup_dwo_type_unit
2059   (struct signatured_type *, const char *, const char *);
2060
2061 static void queue_and_load_all_dwo_tus (struct dwarf2_per_cu_data *);
2062
2063 static void free_dwo_file_cleanup (void *);
2064
2065 static void process_cu_includes (void);
2066
2067 static void check_producer (struct dwarf2_cu *cu);
2068
2069 static void free_line_header_voidp (void *arg);
2070 \f
2071 /* Various complaints about symbol reading that don't abort the process.  */
2072
2073 static void
2074 dwarf2_statement_list_fits_in_line_number_section_complaint (void)
2075 {
2076   complaint (&symfile_complaints,
2077              _("statement list doesn't fit in .debug_line section"));
2078 }
2079
2080 static void
2081 dwarf2_debug_line_missing_file_complaint (void)
2082 {
2083   complaint (&symfile_complaints,
2084              _(".debug_line section has line data without a file"));
2085 }
2086
2087 static void
2088 dwarf2_debug_line_missing_end_sequence_complaint (void)
2089 {
2090   complaint (&symfile_complaints,
2091              _(".debug_line section has line "
2092                "program sequence without an end"));
2093 }
2094
2095 static void
2096 dwarf2_complex_location_expr_complaint (void)
2097 {
2098   complaint (&symfile_complaints, _("location expression too complex"));
2099 }
2100
2101 static void
2102 dwarf2_const_value_length_mismatch_complaint (const char *arg1, int arg2,
2103                                               int arg3)
2104 {
2105   complaint (&symfile_complaints,
2106              _("const value length mismatch for '%s', got %d, expected %d"),
2107              arg1, arg2, arg3);
2108 }
2109
2110 static void
2111 dwarf2_section_buffer_overflow_complaint (struct dwarf2_section_info *section)
2112 {
2113   complaint (&symfile_complaints,
2114              _("debug info runs off end of %s section"
2115                " [in module %s]"),
2116              get_section_name (section),
2117              get_section_file_name (section));
2118 }
2119
2120 static void
2121 dwarf2_macro_malformed_definition_complaint (const char *arg1)
2122 {
2123   complaint (&symfile_complaints,
2124              _("macro debug info contains a "
2125                "malformed macro definition:\n`%s'"),
2126              arg1);
2127 }
2128
2129 static void
2130 dwarf2_invalid_attrib_class_complaint (const char *arg1, const char *arg2)
2131 {
2132   complaint (&symfile_complaints,
2133              _("invalid attribute class or form for '%s' in '%s'"),
2134              arg1, arg2);
2135 }
2136
2137 /* Hash function for line_header_hash.  */
2138
2139 static hashval_t
2140 line_header_hash (const struct line_header *ofs)
2141 {
2142   return to_underlying (ofs->sect_off) ^ ofs->offset_in_dwz;
2143 }
2144
2145 /* Hash function for htab_create_alloc_ex for line_header_hash.  */
2146
2147 static hashval_t
2148 line_header_hash_voidp (const void *item)
2149 {
2150   const struct line_header *ofs = (const struct line_header *) item;
2151
2152   return line_header_hash (ofs);
2153 }
2154
2155 /* Equality function for line_header_hash.  */
2156
2157 static int
2158 line_header_eq_voidp (const void *item_lhs, const void *item_rhs)
2159 {
2160   const struct line_header *ofs_lhs = (const struct line_header *) item_lhs;
2161   const struct line_header *ofs_rhs = (const struct line_header *) item_rhs;
2162
2163   return (ofs_lhs->sect_off == ofs_rhs->sect_off
2164           && ofs_lhs->offset_in_dwz == ofs_rhs->offset_in_dwz);
2165 }
2166
2167 \f
2168 #if WORDS_BIGENDIAN
2169
2170 /* Convert VALUE between big- and little-endian.  */
2171 static offset_type
2172 byte_swap (offset_type value)
2173 {
2174   offset_type result;
2175
2176   result = (value & 0xff) << 24;
2177   result |= (value & 0xff00) << 8;
2178   result |= (value & 0xff0000) >> 8;
2179   result |= (value & 0xff000000) >> 24;
2180   return result;
2181 }
2182
2183 #define MAYBE_SWAP(V)  byte_swap (V)
2184
2185 #else
2186 #define MAYBE_SWAP(V) static_cast<offset_type> (V)
2187 #endif /* WORDS_BIGENDIAN */
2188
2189 /* Read the given attribute value as an address, taking the attribute's
2190    form into account.  */
2191
2192 static CORE_ADDR
2193 attr_value_as_address (struct attribute *attr)
2194 {
2195   CORE_ADDR addr;
2196
2197   if (attr->form != DW_FORM_addr && attr->form != DW_FORM_GNU_addr_index)
2198     {
2199       /* Aside from a few clearly defined exceptions, attributes that
2200          contain an address must always be in DW_FORM_addr form.
2201          Unfortunately, some compilers happen to be violating this
2202          requirement by encoding addresses using other forms, such
2203          as DW_FORM_data4 for example.  For those broken compilers,
2204          we try to do our best, without any guarantee of success,
2205          to interpret the address correctly.  It would also be nice
2206          to generate a complaint, but that would require us to maintain
2207          a list of legitimate cases where a non-address form is allowed,
2208          as well as update callers to pass in at least the CU's DWARF
2209          version.  This is more overhead than what we're willing to
2210          expand for a pretty rare case.  */
2211       addr = DW_UNSND (attr);
2212     }
2213   else
2214     addr = DW_ADDR (attr);
2215
2216   return addr;
2217 }
2218
2219 /* The suffix for an index file.  */
2220 #define INDEX_SUFFIX ".gdb-index"
2221
2222 /* See declaration.  */
2223
2224 dwarf2_per_objfile::dwarf2_per_objfile (struct objfile *objfile_,
2225                                         const dwarf2_debug_sections *names)
2226   : objfile (objfile_)
2227 {
2228   if (names == NULL)
2229     names = &dwarf2_elf_names;
2230
2231   bfd *obfd = objfile->obfd;
2232
2233   for (asection *sec = obfd->sections; sec != NULL; sec = sec->next)
2234     locate_sections (obfd, sec, *names);
2235 }
2236
2237 dwarf2_per_objfile::~dwarf2_per_objfile ()
2238 {
2239   /* Cached DIE trees use xmalloc and the comp_unit_obstack.  */
2240   free_cached_comp_units ();
2241
2242   if (quick_file_names_table)
2243     htab_delete (quick_file_names_table);
2244
2245   if (line_header_hash)
2246     htab_delete (line_header_hash);
2247
2248   /* Everything else should be on the objfile obstack.  */
2249 }
2250
2251 /* See declaration.  */
2252
2253 void
2254 dwarf2_per_objfile::free_cached_comp_units ()
2255 {
2256   dwarf2_per_cu_data *per_cu = read_in_chain;
2257   dwarf2_per_cu_data **last_chain = &read_in_chain;
2258   while (per_cu != NULL)
2259     {
2260       dwarf2_per_cu_data *next_cu = per_cu->cu->read_in_chain;
2261
2262       free_heap_comp_unit (per_cu->cu);
2263       *last_chain = next_cu;
2264       per_cu = next_cu;
2265     }
2266 }
2267
2268 /* Try to locate the sections we need for DWARF 2 debugging
2269    information and return true if we have enough to do something.
2270    NAMES points to the dwarf2 section names, or is NULL if the standard
2271    ELF names are used.  */
2272
2273 int
2274 dwarf2_has_info (struct objfile *objfile,
2275                  const struct dwarf2_debug_sections *names)
2276 {
2277   dwarf2_per_objfile = ((struct dwarf2_per_objfile *)
2278                         objfile_data (objfile, dwarf2_objfile_data_key));
2279   if (!dwarf2_per_objfile)
2280     {
2281       /* Initialize per-objfile state.  */
2282       struct dwarf2_per_objfile *data
2283         = XOBNEW (&objfile->objfile_obstack, struct dwarf2_per_objfile);
2284
2285       dwarf2_per_objfile = new (data) struct dwarf2_per_objfile (objfile, names);
2286       set_objfile_data (objfile, dwarf2_objfile_data_key, dwarf2_per_objfile);
2287     }
2288   return (!dwarf2_per_objfile->info.is_virtual
2289           && dwarf2_per_objfile->info.s.section != NULL
2290           && !dwarf2_per_objfile->abbrev.is_virtual
2291           && dwarf2_per_objfile->abbrev.s.section != NULL);
2292 }
2293
2294 /* Return the containing section of virtual section SECTION.  */
2295
2296 static struct dwarf2_section_info *
2297 get_containing_section (const struct dwarf2_section_info *section)
2298 {
2299   gdb_assert (section->is_virtual);
2300   return section->s.containing_section;
2301 }
2302
2303 /* Return the bfd owner of SECTION.  */
2304
2305 static struct bfd *
2306 get_section_bfd_owner (const struct dwarf2_section_info *section)
2307 {
2308   if (section->is_virtual)
2309     {
2310       section = get_containing_section (section);
2311       gdb_assert (!section->is_virtual);
2312     }
2313   return section->s.section->owner;
2314 }
2315
2316 /* Return the bfd section of SECTION.
2317    Returns NULL if the section is not present.  */
2318
2319 static asection *
2320 get_section_bfd_section (const struct dwarf2_section_info *section)
2321 {
2322   if (section->is_virtual)
2323     {
2324       section = get_containing_section (section);
2325       gdb_assert (!section->is_virtual);
2326     }
2327   return section->s.section;
2328 }
2329
2330 /* Return the name of SECTION.  */
2331
2332 static const char *
2333 get_section_name (const struct dwarf2_section_info *section)
2334 {
2335   asection *sectp = get_section_bfd_section (section);
2336
2337   gdb_assert (sectp != NULL);
2338   return bfd_section_name (get_section_bfd_owner (section), sectp);
2339 }
2340
2341 /* Return the name of the file SECTION is in.  */
2342
2343 static const char *
2344 get_section_file_name (const struct dwarf2_section_info *section)
2345 {
2346   bfd *abfd = get_section_bfd_owner (section);
2347
2348   return bfd_get_filename (abfd);
2349 }
2350
2351 /* Return the id of SECTION.
2352    Returns 0 if SECTION doesn't exist.  */
2353
2354 static int
2355 get_section_id (const struct dwarf2_section_info *section)
2356 {
2357   asection *sectp = get_section_bfd_section (section);
2358
2359   if (sectp == NULL)
2360     return 0;
2361   return sectp->id;
2362 }
2363
2364 /* Return the flags of SECTION.
2365    SECTION (or containing section if this is a virtual section) must exist.  */
2366
2367 static int
2368 get_section_flags (const struct dwarf2_section_info *section)
2369 {
2370   asection *sectp = get_section_bfd_section (section);
2371
2372   gdb_assert (sectp != NULL);
2373   return bfd_get_section_flags (sectp->owner, sectp);
2374 }
2375
2376 /* When loading sections, we look either for uncompressed section or for
2377    compressed section names.  */
2378
2379 static int
2380 section_is_p (const char *section_name,
2381               const struct dwarf2_section_names *names)
2382 {
2383   if (names->normal != NULL
2384       && strcmp (section_name, names->normal) == 0)
2385     return 1;
2386   if (names->compressed != NULL
2387       && strcmp (section_name, names->compressed) == 0)
2388     return 1;
2389   return 0;
2390 }
2391
2392 /* See declaration.  */
2393
2394 void
2395 dwarf2_per_objfile::locate_sections (bfd *abfd, asection *sectp,
2396                                      const dwarf2_debug_sections &names)
2397 {
2398   flagword aflag = bfd_get_section_flags (abfd, sectp);
2399
2400   if ((aflag & SEC_HAS_CONTENTS) == 0)
2401     {
2402     }
2403   else if (section_is_p (sectp->name, &names.info))
2404     {
2405       this->info.s.section = sectp;
2406       this->info.size = bfd_get_section_size (sectp);
2407     }
2408   else if (section_is_p (sectp->name, &names.abbrev))
2409     {
2410       this->abbrev.s.section = sectp;
2411       this->abbrev.size = bfd_get_section_size (sectp);
2412     }
2413   else if (section_is_p (sectp->name, &names.line))
2414     {
2415       this->line.s.section = sectp;
2416       this->line.size = bfd_get_section_size (sectp);
2417     }
2418   else if (section_is_p (sectp->name, &names.loc))
2419     {
2420       this->loc.s.section = sectp;
2421       this->loc.size = bfd_get_section_size (sectp);
2422     }
2423   else if (section_is_p (sectp->name, &names.loclists))
2424     {
2425       this->loclists.s.section = sectp;
2426       this->loclists.size = bfd_get_section_size (sectp);
2427     }
2428   else if (section_is_p (sectp->name, &names.macinfo))
2429     {
2430       this->macinfo.s.section = sectp;
2431       this->macinfo.size = bfd_get_section_size (sectp);
2432     }
2433   else if (section_is_p (sectp->name, &names.macro))
2434     {
2435       this->macro.s.section = sectp;
2436       this->macro.size = bfd_get_section_size (sectp);
2437     }
2438   else if (section_is_p (sectp->name, &names.str))
2439     {
2440       this->str.s.section = sectp;
2441       this->str.size = bfd_get_section_size (sectp);
2442     }
2443   else if (section_is_p (sectp->name, &names.line_str))
2444     {
2445       this->line_str.s.section = sectp;
2446       this->line_str.size = bfd_get_section_size (sectp);
2447     }
2448   else if (section_is_p (sectp->name, &names.addr))
2449     {
2450       this->addr.s.section = sectp;
2451       this->addr.size = bfd_get_section_size (sectp);
2452     }
2453   else if (section_is_p (sectp->name, &names.frame))
2454     {
2455       this->frame.s.section = sectp;
2456       this->frame.size = bfd_get_section_size (sectp);
2457     }
2458   else if (section_is_p (sectp->name, &names.eh_frame))
2459     {
2460       this->eh_frame.s.section = sectp;
2461       this->eh_frame.size = bfd_get_section_size (sectp);
2462     }
2463   else if (section_is_p (sectp->name, &names.ranges))
2464     {
2465       this->ranges.s.section = sectp;
2466       this->ranges.size = bfd_get_section_size (sectp);
2467     }
2468   else if (section_is_p (sectp->name, &names.rnglists))
2469     {
2470       this->rnglists.s.section = sectp;
2471       this->rnglists.size = bfd_get_section_size (sectp);
2472     }
2473   else if (section_is_p (sectp->name, &names.types))
2474     {
2475       struct dwarf2_section_info type_section;
2476
2477       memset (&type_section, 0, sizeof (type_section));
2478       type_section.s.section = sectp;
2479       type_section.size = bfd_get_section_size (sectp);
2480
2481       VEC_safe_push (dwarf2_section_info_def, this->types,
2482                      &type_section);
2483     }
2484   else if (section_is_p (sectp->name, &names.gdb_index))
2485     {
2486       this->gdb_index.s.section = sectp;
2487       this->gdb_index.size = bfd_get_section_size (sectp);
2488     }
2489
2490   if ((bfd_get_section_flags (abfd, sectp) & (SEC_LOAD | SEC_ALLOC))
2491       && bfd_section_vma (abfd, sectp) == 0)
2492     this->has_section_at_zero = true;
2493 }
2494
2495 /* A helper function that decides whether a section is empty,
2496    or not present.  */
2497
2498 static int
2499 dwarf2_section_empty_p (const struct dwarf2_section_info *section)
2500 {
2501   if (section->is_virtual)
2502     return section->size == 0;
2503   return section->s.section == NULL || section->size == 0;
2504 }
2505
2506 /* Read the contents of the section INFO.
2507    OBJFILE is the main object file, but not necessarily the file where
2508    the section comes from.  E.g., for DWO files the bfd of INFO is the bfd
2509    of the DWO file.
2510    If the section is compressed, uncompress it before returning.  */
2511
2512 static void
2513 dwarf2_read_section (struct objfile *objfile, struct dwarf2_section_info *info)
2514 {
2515   asection *sectp;
2516   bfd *abfd;
2517   gdb_byte *buf, *retbuf;
2518
2519   if (info->readin)
2520     return;
2521   info->buffer = NULL;
2522   info->readin = 1;
2523
2524   if (dwarf2_section_empty_p (info))
2525     return;
2526
2527   sectp = get_section_bfd_section (info);
2528
2529   /* If this is a virtual section we need to read in the real one first.  */
2530   if (info->is_virtual)
2531     {
2532       struct dwarf2_section_info *containing_section =
2533         get_containing_section (info);
2534
2535       gdb_assert (sectp != NULL);
2536       if ((sectp->flags & SEC_RELOC) != 0)
2537         {
2538           error (_("Dwarf Error: DWP format V2 with relocations is not"
2539                    " supported in section %s [in module %s]"),
2540                  get_section_name (info), get_section_file_name (info));
2541         }
2542       dwarf2_read_section (objfile, containing_section);
2543       /* Other code should have already caught virtual sections that don't
2544          fit.  */
2545       gdb_assert (info->virtual_offset + info->size
2546                   <= containing_section->size);
2547       /* If the real section is empty or there was a problem reading the
2548          section we shouldn't get here.  */
2549       gdb_assert (containing_section->buffer != NULL);
2550       info->buffer = containing_section->buffer + info->virtual_offset;
2551       return;
2552     }
2553
2554   /* If the section has relocations, we must read it ourselves.
2555      Otherwise we attach it to the BFD.  */
2556   if ((sectp->flags & SEC_RELOC) == 0)
2557     {
2558       info->buffer = gdb_bfd_map_section (sectp, &info->size);
2559       return;
2560     }
2561
2562   buf = (gdb_byte *) obstack_alloc (&objfile->objfile_obstack, info->size);
2563   info->buffer = buf;
2564
2565   /* When debugging .o files, we may need to apply relocations; see
2566      http://sourceware.org/ml/gdb-patches/2002-04/msg00136.html .
2567      We never compress sections in .o files, so we only need to
2568      try this when the section is not compressed.  */
2569   retbuf = symfile_relocate_debug_section (objfile, sectp, buf);
2570   if (retbuf != NULL)
2571     {
2572       info->buffer = retbuf;
2573       return;
2574     }
2575
2576   abfd = get_section_bfd_owner (info);
2577   gdb_assert (abfd != NULL);
2578
2579   if (bfd_seek (abfd, sectp->filepos, SEEK_SET) != 0
2580       || bfd_bread (buf, info->size, abfd) != info->size)
2581     {
2582       error (_("Dwarf Error: Can't read DWARF data"
2583                " in section %s [in module %s]"),
2584              bfd_section_name (abfd, sectp), bfd_get_filename (abfd));
2585     }
2586 }
2587
2588 /* A helper function that returns the size of a section in a safe way.
2589    If you are positive that the section has been read before using the
2590    size, then it is safe to refer to the dwarf2_section_info object's
2591    "size" field directly.  In other cases, you must call this
2592    function, because for compressed sections the size field is not set
2593    correctly until the section has been read.  */
2594
2595 static bfd_size_type
2596 dwarf2_section_size (struct objfile *objfile,
2597                      struct dwarf2_section_info *info)
2598 {
2599   if (!info->readin)
2600     dwarf2_read_section (objfile, info);
2601   return info->size;
2602 }
2603
2604 /* Fill in SECTP, BUFP and SIZEP with section info, given OBJFILE and
2605    SECTION_NAME.  */
2606
2607 void
2608 dwarf2_get_section_info (struct objfile *objfile,
2609                          enum dwarf2_section_enum sect,
2610                          asection **sectp, const gdb_byte **bufp,
2611                          bfd_size_type *sizep)
2612 {
2613   struct dwarf2_per_objfile *data
2614     = (struct dwarf2_per_objfile *) objfile_data (objfile,
2615                                                   dwarf2_objfile_data_key);
2616   struct dwarf2_section_info *info;
2617
2618   /* We may see an objfile without any DWARF, in which case we just
2619      return nothing.  */
2620   if (data == NULL)
2621     {
2622       *sectp = NULL;
2623       *bufp = NULL;
2624       *sizep = 0;
2625       return;
2626     }
2627   switch (sect)
2628     {
2629     case DWARF2_DEBUG_FRAME:
2630       info = &data->frame;
2631       break;
2632     case DWARF2_EH_FRAME:
2633       info = &data->eh_frame;
2634       break;
2635     default:
2636       gdb_assert_not_reached ("unexpected section");
2637     }
2638
2639   dwarf2_read_section (objfile, info);
2640
2641   *sectp = get_section_bfd_section (info);
2642   *bufp = info->buffer;
2643   *sizep = info->size;
2644 }
2645
2646 /* A helper function to find the sections for a .dwz file.  */
2647
2648 static void
2649 locate_dwz_sections (bfd *abfd, asection *sectp, void *arg)
2650 {
2651   struct dwz_file *dwz_file = (struct dwz_file *) arg;
2652
2653   /* Note that we only support the standard ELF names, because .dwz
2654      is ELF-only (at the time of writing).  */
2655   if (section_is_p (sectp->name, &dwarf2_elf_names.abbrev))
2656     {
2657       dwz_file->abbrev.s.section = sectp;
2658       dwz_file->abbrev.size = bfd_get_section_size (sectp);
2659     }
2660   else if (section_is_p (sectp->name, &dwarf2_elf_names.info))
2661     {
2662       dwz_file->info.s.section = sectp;
2663       dwz_file->info.size = bfd_get_section_size (sectp);
2664     }
2665   else if (section_is_p (sectp->name, &dwarf2_elf_names.str))
2666     {
2667       dwz_file->str.s.section = sectp;
2668       dwz_file->str.size = bfd_get_section_size (sectp);
2669     }
2670   else if (section_is_p (sectp->name, &dwarf2_elf_names.line))
2671     {
2672       dwz_file->line.s.section = sectp;
2673       dwz_file->line.size = bfd_get_section_size (sectp);
2674     }
2675   else if (section_is_p (sectp->name, &dwarf2_elf_names.macro))
2676     {
2677       dwz_file->macro.s.section = sectp;
2678       dwz_file->macro.size = bfd_get_section_size (sectp);
2679     }
2680   else if (section_is_p (sectp->name, &dwarf2_elf_names.gdb_index))
2681     {
2682       dwz_file->gdb_index.s.section = sectp;
2683       dwz_file->gdb_index.size = bfd_get_section_size (sectp);
2684     }
2685 }
2686
2687 /* Open the separate '.dwz' debug file, if needed.  Return NULL if
2688    there is no .gnu_debugaltlink section in the file.  Error if there
2689    is such a section but the file cannot be found.  */
2690
2691 static struct dwz_file *
2692 dwarf2_get_dwz_file (void)
2693 {
2694   char *data;
2695   struct cleanup *cleanup;
2696   const char *filename;
2697   struct dwz_file *result;
2698   bfd_size_type buildid_len_arg;
2699   size_t buildid_len;
2700   bfd_byte *buildid;
2701
2702   if (dwarf2_per_objfile->dwz_file != NULL)
2703     return dwarf2_per_objfile->dwz_file;
2704
2705   bfd_set_error (bfd_error_no_error);
2706   data = bfd_get_alt_debug_link_info (dwarf2_per_objfile->objfile->obfd,
2707                                       &buildid_len_arg, &buildid);
2708   if (data == NULL)
2709     {
2710       if (bfd_get_error () == bfd_error_no_error)
2711         return NULL;
2712       error (_("could not read '.gnu_debugaltlink' section: %s"),
2713              bfd_errmsg (bfd_get_error ()));
2714     }
2715   cleanup = make_cleanup (xfree, data);
2716   make_cleanup (xfree, buildid);
2717
2718   buildid_len = (size_t) buildid_len_arg;
2719
2720   filename = (const char *) data;
2721
2722   std::string abs_storage;
2723   if (!IS_ABSOLUTE_PATH (filename))
2724     {
2725       gdb::unique_xmalloc_ptr<char> abs
2726         = gdb_realpath (objfile_name (dwarf2_per_objfile->objfile));
2727
2728       abs_storage = ldirname (abs.get ()) + SLASH_STRING + filename;
2729       filename = abs_storage.c_str ();
2730     }
2731
2732   /* First try the file name given in the section.  If that doesn't
2733      work, try to use the build-id instead.  */
2734   gdb_bfd_ref_ptr dwz_bfd (gdb_bfd_open (filename, gnutarget, -1));
2735   if (dwz_bfd != NULL)
2736     {
2737       if (!build_id_verify (dwz_bfd.get (), buildid_len, buildid))
2738         dwz_bfd.release ();
2739     }
2740
2741   if (dwz_bfd == NULL)
2742     dwz_bfd = build_id_to_debug_bfd (buildid_len, buildid);
2743
2744   if (dwz_bfd == NULL)
2745     error (_("could not find '.gnu_debugaltlink' file for %s"),
2746            objfile_name (dwarf2_per_objfile->objfile));
2747
2748   result = OBSTACK_ZALLOC (&dwarf2_per_objfile->objfile->objfile_obstack,
2749                            struct dwz_file);
2750   result->dwz_bfd = dwz_bfd.release ();
2751
2752   bfd_map_over_sections (result->dwz_bfd, locate_dwz_sections, result);
2753
2754   do_cleanups (cleanup);
2755
2756   gdb_bfd_record_inclusion (dwarf2_per_objfile->objfile->obfd, result->dwz_bfd);
2757   dwarf2_per_objfile->dwz_file = result;
2758   return result;
2759 }
2760 \f
2761 /* DWARF quick_symbols_functions support.  */
2762
2763 /* TUs can share .debug_line entries, and there can be a lot more TUs than
2764    unique line tables, so we maintain a separate table of all .debug_line
2765    derived entries to support the sharing.
2766    All the quick functions need is the list of file names.  We discard the
2767    line_header when we're done and don't need to record it here.  */
2768 struct quick_file_names
2769 {
2770   /* The data used to construct the hash key.  */
2771   struct stmt_list_hash hash;
2772
2773   /* The number of entries in file_names, real_names.  */
2774   unsigned int num_file_names;
2775
2776   /* The file names from the line table, after being run through
2777      file_full_name.  */
2778   const char **file_names;
2779
2780   /* The file names from the line table after being run through
2781      gdb_realpath.  These are computed lazily.  */
2782   const char **real_names;
2783 };
2784
2785 /* When using the index (and thus not using psymtabs), each CU has an
2786    object of this type.  This is used to hold information needed by
2787    the various "quick" methods.  */
2788 struct dwarf2_per_cu_quick_data
2789 {
2790   /* The file table.  This can be NULL if there was no file table
2791      or it's currently not read in.
2792      NOTE: This points into dwarf2_per_objfile->quick_file_names_table.  */
2793   struct quick_file_names *file_names;
2794
2795   /* The corresponding symbol table.  This is NULL if symbols for this
2796      CU have not yet been read.  */
2797   struct compunit_symtab *compunit_symtab;
2798
2799   /* A temporary mark bit used when iterating over all CUs in
2800      expand_symtabs_matching.  */
2801   unsigned int mark : 1;
2802
2803   /* True if we've tried to read the file table and found there isn't one.
2804      There will be no point in trying to read it again next time.  */
2805   unsigned int no_file_data : 1;
2806 };
2807
2808 /* Utility hash function for a stmt_list_hash.  */
2809
2810 static hashval_t
2811 hash_stmt_list_entry (const struct stmt_list_hash *stmt_list_hash)
2812 {
2813   hashval_t v = 0;
2814
2815   if (stmt_list_hash->dwo_unit != NULL)
2816     v += (uintptr_t) stmt_list_hash->dwo_unit->dwo_file;
2817   v += to_underlying (stmt_list_hash->line_sect_off);
2818   return v;
2819 }
2820
2821 /* Utility equality function for a stmt_list_hash.  */
2822
2823 static int
2824 eq_stmt_list_entry (const struct stmt_list_hash *lhs,
2825                     const struct stmt_list_hash *rhs)
2826 {
2827   if ((lhs->dwo_unit != NULL) != (rhs->dwo_unit != NULL))
2828     return 0;
2829   if (lhs->dwo_unit != NULL
2830       && lhs->dwo_unit->dwo_file != rhs->dwo_unit->dwo_file)
2831     return 0;
2832
2833   return lhs->line_sect_off == rhs->line_sect_off;
2834 }
2835
2836 /* Hash function for a quick_file_names.  */
2837
2838 static hashval_t
2839 hash_file_name_entry (const void *e)
2840 {
2841   const struct quick_file_names *file_data
2842     = (const struct quick_file_names *) e;
2843
2844   return hash_stmt_list_entry (&file_data->hash);
2845 }
2846
2847 /* Equality function for a quick_file_names.  */
2848
2849 static int
2850 eq_file_name_entry (const void *a, const void *b)
2851 {
2852   const struct quick_file_names *ea = (const struct quick_file_names *) a;
2853   const struct quick_file_names *eb = (const struct quick_file_names *) b;
2854
2855   return eq_stmt_list_entry (&ea->hash, &eb->hash);
2856 }
2857
2858 /* Delete function for a quick_file_names.  */
2859
2860 static void
2861 delete_file_name_entry (void *e)
2862 {
2863   struct quick_file_names *file_data = (struct quick_file_names *) e;
2864   int i;
2865
2866   for (i = 0; i < file_data->num_file_names; ++i)
2867     {
2868       xfree ((void*) file_data->file_names[i]);
2869       if (file_data->real_names)
2870         xfree ((void*) file_data->real_names[i]);
2871     }
2872
2873   /* The space for the struct itself lives on objfile_obstack,
2874      so we don't free it here.  */
2875 }
2876
2877 /* Create a quick_file_names hash table.  */
2878
2879 static htab_t
2880 create_quick_file_names_table (unsigned int nr_initial_entries)
2881 {
2882   return htab_create_alloc (nr_initial_entries,
2883                             hash_file_name_entry, eq_file_name_entry,
2884                             delete_file_name_entry, xcalloc, xfree);
2885 }
2886
2887 /* Read in PER_CU->CU.  This function is unrelated to symtabs, symtab would
2888    have to be created afterwards.  You should call age_cached_comp_units after
2889    processing PER_CU->CU.  dw2_setup must have been already called.  */
2890
2891 static void
2892 load_cu (struct dwarf2_per_cu_data *per_cu)
2893 {
2894   if (per_cu->is_debug_types)
2895     load_full_type_unit (per_cu);
2896   else
2897     load_full_comp_unit (per_cu, language_minimal);
2898
2899   if (per_cu->cu == NULL)
2900     return;  /* Dummy CU.  */
2901
2902   dwarf2_find_base_address (per_cu->cu->dies, per_cu->cu);
2903 }
2904
2905 /* Read in the symbols for PER_CU.  */
2906
2907 static void
2908 dw2_do_instantiate_symtab (struct dwarf2_per_cu_data *per_cu)
2909 {
2910   struct cleanup *back_to;
2911
2912   /* Skip type_unit_groups, reading the type units they contain
2913      is handled elsewhere.  */
2914   if (IS_TYPE_UNIT_GROUP (per_cu))
2915     return;
2916
2917   back_to = make_cleanup (dwarf2_release_queue, NULL);
2918
2919   if (dwarf2_per_objfile->using_index
2920       ? per_cu->v.quick->compunit_symtab == NULL
2921       : (per_cu->v.psymtab == NULL || !per_cu->v.psymtab->readin))
2922     {
2923       queue_comp_unit (per_cu, language_minimal);
2924       load_cu (per_cu);
2925
2926       /* If we just loaded a CU from a DWO, and we're working with an index
2927          that may badly handle TUs, load all the TUs in that DWO as well.
2928          http://sourceware.org/bugzilla/show_bug.cgi?id=15021  */
2929       if (!per_cu->is_debug_types
2930           && per_cu->cu != NULL
2931           && per_cu->cu->dwo_unit != NULL
2932           && dwarf2_per_objfile->index_table != NULL
2933           && dwarf2_per_objfile->index_table->version <= 7
2934           /* DWP files aren't supported yet.  */
2935           && get_dwp_file () == NULL)
2936         queue_and_load_all_dwo_tus (per_cu);
2937     }
2938
2939   process_queue ();
2940
2941   /* Age the cache, releasing compilation units that have not
2942      been used recently.  */
2943   age_cached_comp_units ();
2944
2945   do_cleanups (back_to);
2946 }
2947
2948 /* Ensure that the symbols for PER_CU have been read in.  OBJFILE is
2949    the objfile from which this CU came.  Returns the resulting symbol
2950    table.  */
2951
2952 static struct compunit_symtab *
2953 dw2_instantiate_symtab (struct dwarf2_per_cu_data *per_cu)
2954 {
2955   gdb_assert (dwarf2_per_objfile->using_index);
2956   if (!per_cu->v.quick->compunit_symtab)
2957     {
2958       struct cleanup *back_to = make_cleanup (free_cached_comp_units, NULL);
2959       scoped_restore decrementer = increment_reading_symtab ();
2960       dw2_do_instantiate_symtab (per_cu);
2961       process_cu_includes ();
2962       do_cleanups (back_to);
2963     }
2964
2965   return per_cu->v.quick->compunit_symtab;
2966 }
2967
2968 /* Return the CU/TU given its index.
2969
2970    This is intended for loops like:
2971
2972    for (i = 0; i < (dwarf2_per_objfile->n_comp_units
2973                     + dwarf2_per_objfile->n_type_units); ++i)
2974      {
2975        struct dwarf2_per_cu_data *per_cu = dw2_get_cutu (i);
2976
2977        ...;
2978      }
2979 */
2980
2981 static struct dwarf2_per_cu_data *
2982 dw2_get_cutu (int index)
2983 {
2984   if (index >= dwarf2_per_objfile->n_comp_units)
2985     {
2986       index -= dwarf2_per_objfile->n_comp_units;
2987       gdb_assert (index < dwarf2_per_objfile->n_type_units);
2988       return &dwarf2_per_objfile->all_type_units[index]->per_cu;
2989     }
2990
2991   return dwarf2_per_objfile->all_comp_units[index];
2992 }
2993
2994 /* Return the CU given its index.
2995    This differs from dw2_get_cutu in that it's for when you know INDEX
2996    refers to a CU.  */
2997
2998 static struct dwarf2_per_cu_data *
2999 dw2_get_cu (int index)
3000 {
3001   gdb_assert (index >= 0 && index < dwarf2_per_objfile->n_comp_units);
3002
3003   return dwarf2_per_objfile->all_comp_units[index];
3004 }
3005
3006 /* A helper for create_cus_from_index that handles a given list of
3007    CUs.  */
3008
3009 static void
3010 create_cus_from_index_list (struct objfile *objfile,
3011                             const gdb_byte *cu_list, offset_type n_elements,
3012                             struct dwarf2_section_info *section,
3013                             int is_dwz,
3014                             int base_offset)
3015 {
3016   offset_type i;
3017
3018   for (i = 0; i < n_elements; i += 2)
3019     {
3020       gdb_static_assert (sizeof (ULONGEST) >= 8);
3021
3022       sect_offset sect_off
3023         = (sect_offset) extract_unsigned_integer (cu_list, 8, BFD_ENDIAN_LITTLE);
3024       ULONGEST length = extract_unsigned_integer (cu_list + 8, 8, BFD_ENDIAN_LITTLE);
3025       cu_list += 2 * 8;
3026
3027       dwarf2_per_cu_data *the_cu
3028         = OBSTACK_ZALLOC (&objfile->objfile_obstack,
3029                           struct dwarf2_per_cu_data);
3030       the_cu->sect_off = sect_off;
3031       the_cu->length = length;
3032       the_cu->objfile = objfile;
3033       the_cu->section = section;
3034       the_cu->v.quick = OBSTACK_ZALLOC (&objfile->objfile_obstack,
3035                                         struct dwarf2_per_cu_quick_data);
3036       the_cu->is_dwz = is_dwz;
3037       dwarf2_per_objfile->all_comp_units[base_offset + i / 2] = the_cu;
3038     }
3039 }
3040
3041 /* Read the CU list from the mapped index, and use it to create all
3042    the CU objects for this objfile.  */
3043
3044 static void
3045 create_cus_from_index (struct objfile *objfile,
3046                        const gdb_byte *cu_list, offset_type cu_list_elements,
3047                        const gdb_byte *dwz_list, offset_type dwz_elements)
3048 {
3049   struct dwz_file *dwz;
3050
3051   dwarf2_per_objfile->n_comp_units = (cu_list_elements + dwz_elements) / 2;
3052   dwarf2_per_objfile->all_comp_units =
3053     XOBNEWVEC (&objfile->objfile_obstack, struct dwarf2_per_cu_data *,
3054                dwarf2_per_objfile->n_comp_units);
3055
3056   create_cus_from_index_list (objfile, cu_list, cu_list_elements,
3057                               &dwarf2_per_objfile->info, 0, 0);
3058
3059   if (dwz_elements == 0)
3060     return;
3061
3062   dwz = dwarf2_get_dwz_file ();
3063   create_cus_from_index_list (objfile, dwz_list, dwz_elements, &dwz->info, 1,
3064                               cu_list_elements / 2);
3065 }
3066
3067 /* Create the signatured type hash table from the index.  */
3068
3069 static void
3070 create_signatured_type_table_from_index (struct objfile *objfile,
3071                                          struct dwarf2_section_info *section,
3072                                          const gdb_byte *bytes,
3073                                          offset_type elements)
3074 {
3075   offset_type i;
3076   htab_t sig_types_hash;
3077
3078   dwarf2_per_objfile->n_type_units
3079     = dwarf2_per_objfile->n_allocated_type_units
3080     = elements / 3;
3081   dwarf2_per_objfile->all_type_units =
3082     XNEWVEC (struct signatured_type *, dwarf2_per_objfile->n_type_units);
3083
3084   sig_types_hash = allocate_signatured_type_table (objfile);
3085
3086   for (i = 0; i < elements; i += 3)
3087     {
3088       struct signatured_type *sig_type;
3089       ULONGEST signature;
3090       void **slot;
3091       cu_offset type_offset_in_tu;
3092
3093       gdb_static_assert (sizeof (ULONGEST) >= 8);
3094       sect_offset sect_off
3095         = (sect_offset) extract_unsigned_integer (bytes, 8, BFD_ENDIAN_LITTLE);
3096       type_offset_in_tu
3097         = (cu_offset) extract_unsigned_integer (bytes + 8, 8,
3098                                                 BFD_ENDIAN_LITTLE);
3099       signature = extract_unsigned_integer (bytes + 16, 8, BFD_ENDIAN_LITTLE);
3100       bytes += 3 * 8;
3101
3102       sig_type = OBSTACK_ZALLOC (&objfile->objfile_obstack,
3103                                  struct signatured_type);
3104       sig_type->signature = signature;
3105       sig_type->type_offset_in_tu = type_offset_in_tu;
3106       sig_type->per_cu.is_debug_types = 1;
3107       sig_type->per_cu.section = section;
3108       sig_type->per_cu.sect_off = sect_off;
3109       sig_type->per_cu.objfile = objfile;
3110       sig_type->per_cu.v.quick
3111         = OBSTACK_ZALLOC (&objfile->objfile_obstack,
3112                           struct dwarf2_per_cu_quick_data);
3113
3114       slot = htab_find_slot (sig_types_hash, sig_type, INSERT);
3115       *slot = sig_type;
3116
3117       dwarf2_per_objfile->all_type_units[i / 3] = sig_type;
3118     }
3119
3120   dwarf2_per_objfile->signatured_types = sig_types_hash;
3121 }
3122
3123 /* Read the address map data from the mapped index, and use it to
3124    populate the objfile's psymtabs_addrmap.  */
3125
3126 static void
3127 create_addrmap_from_index (struct objfile *objfile, struct mapped_index *index)
3128 {
3129   struct gdbarch *gdbarch = get_objfile_arch (objfile);
3130   const gdb_byte *iter, *end;
3131   struct addrmap *mutable_map;
3132   CORE_ADDR baseaddr;
3133
3134   auto_obstack temp_obstack;
3135
3136   mutable_map = addrmap_create_mutable (&temp_obstack);
3137
3138   iter = index->address_table;
3139   end = iter + index->address_table_size;
3140
3141   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
3142
3143   while (iter < end)
3144     {
3145       ULONGEST hi, lo, cu_index;
3146       lo = extract_unsigned_integer (iter, 8, BFD_ENDIAN_LITTLE);
3147       iter += 8;
3148       hi = extract_unsigned_integer (iter, 8, BFD_ENDIAN_LITTLE);
3149       iter += 8;
3150       cu_index = extract_unsigned_integer (iter, 4, BFD_ENDIAN_LITTLE);
3151       iter += 4;
3152
3153       if (lo > hi)
3154         {
3155           complaint (&symfile_complaints,
3156                      _(".gdb_index address table has invalid range (%s - %s)"),
3157                      hex_string (lo), hex_string (hi));
3158           continue;
3159         }
3160
3161       if (cu_index >= dwarf2_per_objfile->n_comp_units)
3162         {
3163           complaint (&symfile_complaints,
3164                      _(".gdb_index address table has invalid CU number %u"),
3165                      (unsigned) cu_index);
3166           continue;
3167         }
3168
3169       lo = gdbarch_adjust_dwarf2_addr (gdbarch, lo + baseaddr);
3170       hi = gdbarch_adjust_dwarf2_addr (gdbarch, hi + baseaddr);
3171       addrmap_set_empty (mutable_map, lo, hi - 1, dw2_get_cutu (cu_index));
3172     }
3173
3174   objfile->psymtabs_addrmap = addrmap_create_fixed (mutable_map,
3175                                                     &objfile->objfile_obstack);
3176 }
3177
3178 /* The hash function for strings in the mapped index.  This is the same as
3179    SYMBOL_HASH_NEXT, but we keep a separate copy to maintain control over the
3180    implementation.  This is necessary because the hash function is tied to the
3181    format of the mapped index file.  The hash values do not have to match with
3182    SYMBOL_HASH_NEXT.
3183    
3184    Use INT_MAX for INDEX_VERSION if you generate the current index format.  */
3185
3186 static hashval_t
3187 mapped_index_string_hash (int index_version, const void *p)
3188 {
3189   const unsigned char *str = (const unsigned char *) p;
3190   hashval_t r = 0;
3191   unsigned char c;
3192
3193   while ((c = *str++) != 0)
3194     {
3195       if (index_version >= 5)
3196         c = tolower (c);
3197       r = r * 67 + c - 113;
3198     }
3199
3200   return r;
3201 }
3202
3203 /* Find a slot in the mapped index INDEX for the object named NAME.
3204    If NAME is found, set *VEC_OUT to point to the CU vector in the
3205    constant pool and return 1.  If NAME cannot be found, return 0.  */
3206
3207 static int
3208 find_slot_in_mapped_hash (struct mapped_index *index, const char *name,
3209                           offset_type **vec_out)
3210 {
3211   struct cleanup *back_to = make_cleanup (null_cleanup, 0);
3212   offset_type hash;
3213   offset_type slot, step;
3214   int (*cmp) (const char *, const char *);
3215
3216   if (current_language->la_language == language_cplus
3217       || current_language->la_language == language_fortran
3218       || current_language->la_language == language_d)
3219     {
3220       /* NAME is already canonical.  Drop any qualifiers as .gdb_index does
3221          not contain any.  */
3222
3223       if (strchr (name, '(') != NULL)
3224         {
3225           char *without_params = cp_remove_params (name);
3226
3227           if (without_params != NULL)
3228             {
3229               make_cleanup (xfree, without_params);
3230               name = without_params;
3231             }
3232         }
3233     }
3234
3235   /* Index version 4 did not support case insensitive searches.  But the
3236      indices for case insensitive languages are built in lowercase, therefore
3237      simulate our NAME being searched is also lowercased.  */
3238   hash = mapped_index_string_hash ((index->version == 4
3239                                     && case_sensitivity == case_sensitive_off
3240                                     ? 5 : index->version),
3241                                    name);
3242
3243   slot = hash & (index->symbol_table_slots - 1);
3244   step = ((hash * 17) & (index->symbol_table_slots - 1)) | 1;
3245   cmp = (case_sensitivity == case_sensitive_on ? strcmp : strcasecmp);
3246
3247   for (;;)
3248     {
3249       /* Convert a slot number to an offset into the table.  */
3250       offset_type i = 2 * slot;
3251       const char *str;
3252       if (index->symbol_table[i] == 0 && index->symbol_table[i + 1] == 0)
3253         {
3254           do_cleanups (back_to);
3255           return 0;
3256         }
3257
3258       str = index->constant_pool + MAYBE_SWAP (index->symbol_table[i]);
3259       if (!cmp (name, str))
3260         {
3261           *vec_out = (offset_type *) (index->constant_pool
3262                                       + MAYBE_SWAP (index->symbol_table[i + 1]));
3263           do_cleanups (back_to);
3264           return 1;
3265         }
3266
3267       slot = (slot + step) & (index->symbol_table_slots - 1);
3268     }
3269 }
3270
3271 /* A helper function that reads the .gdb_index from SECTION and fills
3272    in MAP.  FILENAME is the name of the file containing the section;
3273    it is used for error reporting.  DEPRECATED_OK is nonzero if it is
3274    ok to use deprecated sections.
3275
3276    CU_LIST, CU_LIST_ELEMENTS, TYPES_LIST, and TYPES_LIST_ELEMENTS are
3277    out parameters that are filled in with information about the CU and
3278    TU lists in the section.
3279
3280    Returns 1 if all went well, 0 otherwise.  */
3281
3282 static int
3283 read_index_from_section (struct objfile *objfile,
3284                          const char *filename,
3285                          int deprecated_ok,
3286                          struct dwarf2_section_info *section,
3287                          struct mapped_index *map,
3288                          const gdb_byte **cu_list,
3289                          offset_type *cu_list_elements,
3290                          const gdb_byte **types_list,
3291                          offset_type *types_list_elements)
3292 {
3293   const gdb_byte *addr;
3294   offset_type version;
3295   offset_type *metadata;
3296   int i;
3297
3298   if (dwarf2_section_empty_p (section))
3299     return 0;
3300
3301   /* Older elfutils strip versions could keep the section in the main
3302      executable while splitting it for the separate debug info file.  */
3303   if ((get_section_flags (section) & SEC_HAS_CONTENTS) == 0)
3304     return 0;
3305
3306   dwarf2_read_section (objfile, section);
3307
3308   addr = section->buffer;
3309   /* Version check.  */
3310   version = MAYBE_SWAP (*(offset_type *) addr);
3311   /* Versions earlier than 3 emitted every copy of a psymbol.  This
3312      causes the index to behave very poorly for certain requests.  Version 3
3313      contained incomplete addrmap.  So, it seems better to just ignore such
3314      indices.  */
3315   if (version < 4)
3316     {
3317       static int warning_printed = 0;
3318       if (!warning_printed)
3319         {
3320           warning (_("Skipping obsolete .gdb_index section in %s."),
3321                    filename);
3322           warning_printed = 1;
3323         }
3324       return 0;
3325     }
3326   /* Index version 4 uses a different hash function than index version
3327      5 and later.
3328
3329      Versions earlier than 6 did not emit psymbols for inlined
3330      functions.  Using these files will cause GDB not to be able to
3331      set breakpoints on inlined functions by name, so we ignore these
3332      indices unless the user has done
3333      "set use-deprecated-index-sections on".  */
3334   if (version < 6 && !deprecated_ok)
3335     {
3336       static int warning_printed = 0;
3337       if (!warning_printed)
3338         {
3339           warning (_("\
3340 Skipping deprecated .gdb_index section in %s.\n\
3341 Do \"set use-deprecated-index-sections on\" before the file is read\n\
3342 to use the section anyway."),
3343                    filename);
3344           warning_printed = 1;
3345         }
3346       return 0;
3347     }
3348   /* Version 7 indices generated by gold refer to the CU for a symbol instead
3349      of the TU (for symbols coming from TUs),
3350      http://sourceware.org/bugzilla/show_bug.cgi?id=15021.
3351      Plus gold-generated indices can have duplicate entries for global symbols,
3352      http://sourceware.org/bugzilla/show_bug.cgi?id=15646.
3353      These are just performance bugs, and we can't distinguish gdb-generated
3354      indices from gold-generated ones, so issue no warning here.  */
3355
3356   /* Indexes with higher version than the one supported by GDB may be no
3357      longer backward compatible.  */
3358   if (version > 8)
3359     return 0;
3360
3361   map->version = version;
3362   map->total_size = section->size;
3363
3364   metadata = (offset_type *) (addr + sizeof (offset_type));
3365
3366   i = 0;
3367   *cu_list = addr + MAYBE_SWAP (metadata[i]);
3368   *cu_list_elements = ((MAYBE_SWAP (metadata[i + 1]) - MAYBE_SWAP (metadata[i]))
3369                        / 8);
3370   ++i;
3371
3372   *types_list = addr + MAYBE_SWAP (metadata[i]);
3373   *types_list_elements = ((MAYBE_SWAP (metadata[i + 1])
3374                            - MAYBE_SWAP (metadata[i]))
3375                           / 8);
3376   ++i;
3377
3378   map->address_table = addr + MAYBE_SWAP (metadata[i]);
3379   map->address_table_size = (MAYBE_SWAP (metadata[i + 1])
3380                              - MAYBE_SWAP (metadata[i]));
3381   ++i;
3382
3383   map->symbol_table = (offset_type *) (addr + MAYBE_SWAP (metadata[i]));
3384   map->symbol_table_slots = ((MAYBE_SWAP (metadata[i + 1])
3385                               - MAYBE_SWAP (metadata[i]))
3386                              / (2 * sizeof (offset_type)));
3387   ++i;
3388
3389   map->constant_pool = (char *) (addr + MAYBE_SWAP (metadata[i]));
3390
3391   return 1;
3392 }
3393
3394
3395 /* Read the index file.  If everything went ok, initialize the "quick"
3396    elements of all the CUs and return 1.  Otherwise, return 0.  */
3397
3398 static int
3399 dwarf2_read_index (struct objfile *objfile)
3400 {
3401   struct mapped_index local_map, *map;
3402   const gdb_byte *cu_list, *types_list, *dwz_list = NULL;
3403   offset_type cu_list_elements, types_list_elements, dwz_list_elements = 0;
3404   struct dwz_file *dwz;
3405
3406   if (!read_index_from_section (objfile, objfile_name (objfile),
3407                                 use_deprecated_index_sections,
3408                                 &dwarf2_per_objfile->gdb_index, &local_map,
3409                                 &cu_list, &cu_list_elements,
3410                                 &types_list, &types_list_elements))
3411     return 0;
3412
3413   /* Don't use the index if it's empty.  */
3414   if (local_map.symbol_table_slots == 0)
3415     return 0;
3416
3417   /* If there is a .dwz file, read it so we can get its CU list as
3418      well.  */
3419   dwz = dwarf2_get_dwz_file ();
3420   if (dwz != NULL)
3421     {
3422       struct mapped_index dwz_map;
3423       const gdb_byte *dwz_types_ignore;
3424       offset_type dwz_types_elements_ignore;
3425
3426       if (!read_index_from_section (objfile, bfd_get_filename (dwz->dwz_bfd),
3427                                     1,
3428                                     &dwz->gdb_index, &dwz_map,
3429                                     &dwz_list, &dwz_list_elements,
3430                                     &dwz_types_ignore,
3431                                     &dwz_types_elements_ignore))
3432         {
3433           warning (_("could not read '.gdb_index' section from %s; skipping"),
3434                    bfd_get_filename (dwz->dwz_bfd));
3435           return 0;
3436         }
3437     }
3438
3439   create_cus_from_index (objfile, cu_list, cu_list_elements, dwz_list,
3440                          dwz_list_elements);
3441
3442   if (types_list_elements)
3443     {
3444       struct dwarf2_section_info *section;
3445
3446       /* We can only handle a single .debug_types when we have an
3447          index.  */
3448       if (VEC_length (dwarf2_section_info_def, dwarf2_per_objfile->types) != 1)
3449         return 0;
3450
3451       section = VEC_index (dwarf2_section_info_def,
3452                            dwarf2_per_objfile->types, 0);
3453
3454       create_signatured_type_table_from_index (objfile, section, types_list,
3455                                                types_list_elements);
3456     }
3457
3458   create_addrmap_from_index (objfile, &local_map);
3459
3460   map = XOBNEW (&objfile->objfile_obstack, struct mapped_index);
3461   *map = local_map;
3462
3463   dwarf2_per_objfile->index_table = map;
3464   dwarf2_per_objfile->using_index = 1;
3465   dwarf2_per_objfile->quick_file_names_table =
3466     create_quick_file_names_table (dwarf2_per_objfile->n_comp_units);
3467
3468   return 1;
3469 }
3470
3471 /* A helper for the "quick" functions which sets the global
3472    dwarf2_per_objfile according to OBJFILE.  */
3473
3474 static void
3475 dw2_setup (struct objfile *objfile)
3476 {
3477   dwarf2_per_objfile = ((struct dwarf2_per_objfile *)
3478                         objfile_data (objfile, dwarf2_objfile_data_key));
3479   gdb_assert (dwarf2_per_objfile);
3480 }
3481
3482 /* die_reader_func for dw2_get_file_names.  */
3483
3484 static void
3485 dw2_get_file_names_reader (const struct die_reader_specs *reader,
3486                            const gdb_byte *info_ptr,
3487                            struct die_info *comp_unit_die,
3488                            int has_children,
3489                            void *data)
3490 {
3491   struct dwarf2_cu *cu = reader->cu;
3492   struct dwarf2_per_cu_data *this_cu = cu->per_cu;  
3493   struct objfile *objfile = dwarf2_per_objfile->objfile;
3494   struct dwarf2_per_cu_data *lh_cu;
3495   struct attribute *attr;
3496   int i;
3497   void **slot;
3498   struct quick_file_names *qfn;
3499
3500   gdb_assert (! this_cu->is_debug_types);
3501
3502   /* Our callers never want to match partial units -- instead they
3503      will match the enclosing full CU.  */
3504   if (comp_unit_die->tag == DW_TAG_partial_unit)
3505     {
3506       this_cu->v.quick->no_file_data = 1;
3507       return;
3508     }
3509
3510   lh_cu = this_cu;
3511   slot = NULL;
3512
3513   line_header_up lh;
3514   sect_offset line_offset {};
3515
3516   attr = dwarf2_attr (comp_unit_die, DW_AT_stmt_list, cu);
3517   if (attr)
3518     {
3519       struct quick_file_names find_entry;
3520
3521       line_offset = (sect_offset) DW_UNSND (attr);
3522
3523       /* We may have already read in this line header (TU line header sharing).
3524          If we have we're done.  */
3525       find_entry.hash.dwo_unit = cu->dwo_unit;
3526       find_entry.hash.line_sect_off = line_offset;
3527       slot = htab_find_slot (dwarf2_per_objfile->quick_file_names_table,
3528                              &find_entry, INSERT);
3529       if (*slot != NULL)
3530         {
3531           lh_cu->v.quick->file_names = (struct quick_file_names *) *slot;
3532           return;
3533         }
3534
3535       lh = dwarf_decode_line_header (line_offset, cu);
3536     }
3537   if (lh == NULL)
3538     {
3539       lh_cu->v.quick->no_file_data = 1;
3540       return;
3541     }
3542
3543   qfn = XOBNEW (&objfile->objfile_obstack, struct quick_file_names);
3544   qfn->hash.dwo_unit = cu->dwo_unit;
3545   qfn->hash.line_sect_off = line_offset;
3546   gdb_assert (slot != NULL);
3547   *slot = qfn;
3548
3549   file_and_directory fnd = find_file_and_directory (comp_unit_die, cu);
3550
3551   qfn->num_file_names = lh->file_names.size ();
3552   qfn->file_names =
3553     XOBNEWVEC (&objfile->objfile_obstack, const char *, lh->file_names.size ());
3554   for (i = 0; i < lh->file_names.size (); ++i)
3555     qfn->file_names[i] = file_full_name (i + 1, lh.get (), fnd.comp_dir);
3556   qfn->real_names = NULL;
3557
3558   lh_cu->v.quick->file_names = qfn;
3559 }
3560
3561 /* A helper for the "quick" functions which attempts to read the line
3562    table for THIS_CU.  */
3563
3564 static struct quick_file_names *
3565 dw2_get_file_names (struct dwarf2_per_cu_data *this_cu)
3566 {
3567   /* This should never be called for TUs.  */
3568   gdb_assert (! this_cu->is_debug_types);
3569   /* Nor type unit groups.  */
3570   gdb_assert (! IS_TYPE_UNIT_GROUP (this_cu));
3571
3572   if (this_cu->v.quick->file_names != NULL)
3573     return this_cu->v.quick->file_names;
3574   /* If we know there is no line data, no point in looking again.  */
3575   if (this_cu->v.quick->no_file_data)
3576     return NULL;
3577
3578   init_cutu_and_read_dies_simple (this_cu, dw2_get_file_names_reader, NULL);
3579
3580   if (this_cu->v.quick->no_file_data)
3581     return NULL;
3582   return this_cu->v.quick->file_names;
3583 }
3584
3585 /* A helper for the "quick" functions which computes and caches the
3586    real path for a given file name from the line table.  */
3587
3588 static const char *
3589 dw2_get_real_path (struct objfile *objfile,
3590                    struct quick_file_names *qfn, int index)
3591 {
3592   if (qfn->real_names == NULL)
3593     qfn->real_names = OBSTACK_CALLOC (&objfile->objfile_obstack,
3594                                       qfn->num_file_names, const char *);
3595
3596   if (qfn->real_names[index] == NULL)
3597     qfn->real_names[index] = gdb_realpath (qfn->file_names[index]).release ();
3598
3599   return qfn->real_names[index];
3600 }
3601
3602 static struct symtab *
3603 dw2_find_last_source_symtab (struct objfile *objfile)
3604 {
3605   struct compunit_symtab *cust;
3606   int index;
3607
3608   dw2_setup (objfile);
3609   index = dwarf2_per_objfile->n_comp_units - 1;
3610   cust = dw2_instantiate_symtab (dw2_get_cutu (index));
3611   if (cust == NULL)
3612     return NULL;
3613   return compunit_primary_filetab (cust);
3614 }
3615
3616 /* Traversal function for dw2_forget_cached_source_info.  */
3617
3618 static int
3619 dw2_free_cached_file_names (void **slot, void *info)
3620 {
3621   struct quick_file_names *file_data = (struct quick_file_names *) *slot;
3622
3623   if (file_data->real_names)
3624     {
3625       int i;
3626
3627       for (i = 0; i < file_data->num_file_names; ++i)
3628         {
3629           xfree ((void*) file_data->real_names[i]);
3630           file_data->real_names[i] = NULL;
3631         }
3632     }
3633
3634   return 1;
3635 }
3636
3637 static void
3638 dw2_forget_cached_source_info (struct objfile *objfile)
3639 {
3640   dw2_setup (objfile);
3641
3642   htab_traverse_noresize (dwarf2_per_objfile->quick_file_names_table,
3643                           dw2_free_cached_file_names, NULL);
3644 }
3645
3646 /* Helper function for dw2_map_symtabs_matching_filename that expands
3647    the symtabs and calls the iterator.  */
3648
3649 static int
3650 dw2_map_expand_apply (struct objfile *objfile,
3651                       struct dwarf2_per_cu_data *per_cu,
3652                       const char *name, const char *real_path,
3653                       gdb::function_view<bool (symtab *)> callback)
3654 {
3655   struct compunit_symtab *last_made = objfile->compunit_symtabs;
3656
3657   /* Don't visit already-expanded CUs.  */
3658   if (per_cu->v.quick->compunit_symtab)
3659     return 0;
3660
3661   /* This may expand more than one symtab, and we want to iterate over
3662      all of them.  */
3663   dw2_instantiate_symtab (per_cu);
3664
3665   return iterate_over_some_symtabs (name, real_path, objfile->compunit_symtabs,
3666                                     last_made, callback);
3667 }
3668
3669 /* Implementation of the map_symtabs_matching_filename method.  */
3670
3671 static bool
3672 dw2_map_symtabs_matching_filename
3673   (struct objfile *objfile, const char *name, const char *real_path,
3674    gdb::function_view<bool (symtab *)> callback)
3675 {
3676   int i;
3677   const char *name_basename = lbasename (name);
3678
3679   dw2_setup (objfile);
3680
3681   /* The rule is CUs specify all the files, including those used by
3682      any TU, so there's no need to scan TUs here.  */
3683
3684   for (i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
3685     {
3686       int j;
3687       struct dwarf2_per_cu_data *per_cu = dw2_get_cu (i);
3688       struct quick_file_names *file_data;
3689
3690       /* We only need to look at symtabs not already expanded.  */
3691       if (per_cu->v.quick->compunit_symtab)
3692         continue;
3693
3694       file_data = dw2_get_file_names (per_cu);
3695       if (file_data == NULL)
3696         continue;
3697
3698       for (j = 0; j < file_data->num_file_names; ++j)
3699         {
3700           const char *this_name = file_data->file_names[j];
3701           const char *this_real_name;
3702
3703           if (compare_filenames_for_search (this_name, name))
3704             {
3705               if (dw2_map_expand_apply (objfile, per_cu, name, real_path,
3706                                         callback))
3707                 return true;
3708               continue;
3709             }
3710
3711           /* Before we invoke realpath, which can get expensive when many
3712              files are involved, do a quick comparison of the basenames.  */
3713           if (! basenames_may_differ
3714               && FILENAME_CMP (lbasename (this_name), name_basename) != 0)
3715             continue;
3716
3717           this_real_name = dw2_get_real_path (objfile, file_data, j);
3718           if (compare_filenames_for_search (this_real_name, name))
3719             {
3720               if (dw2_map_expand_apply (objfile, per_cu, name, real_path,
3721                                         callback))
3722                 return true;
3723               continue;
3724             }
3725
3726           if (real_path != NULL)
3727             {
3728               gdb_assert (IS_ABSOLUTE_PATH (real_path));
3729               gdb_assert (IS_ABSOLUTE_PATH (name));
3730               if (this_real_name != NULL
3731                   && FILENAME_CMP (real_path, this_real_name) == 0)
3732                 {
3733                   if (dw2_map_expand_apply (objfile, per_cu, name, real_path,
3734                                             callback))
3735                     return true;
3736                   continue;
3737                 }
3738             }
3739         }
3740     }
3741
3742   return false;
3743 }
3744
3745 /* Struct used to manage iterating over all CUs looking for a symbol.  */
3746
3747 struct dw2_symtab_iterator
3748 {
3749   /* The internalized form of .gdb_index.  */
3750   struct mapped_index *index;
3751   /* If non-zero, only look for symbols that match BLOCK_INDEX.  */
3752   int want_specific_block;
3753   /* One of GLOBAL_BLOCK or STATIC_BLOCK.
3754      Unused if !WANT_SPECIFIC_BLOCK.  */
3755   int block_index;
3756   /* The kind of symbol we're looking for.  */
3757   domain_enum domain;
3758   /* The list of CUs from the index entry of the symbol,
3759      or NULL if not found.  */
3760   offset_type *vec;
3761   /* The next element in VEC to look at.  */
3762   int next;
3763   /* The number of elements in VEC, or zero if there is no match.  */
3764   int length;
3765   /* Have we seen a global version of the symbol?
3766      If so we can ignore all further global instances.
3767      This is to work around gold/15646, inefficient gold-generated
3768      indices.  */
3769   int global_seen;
3770 };
3771
3772 /* Initialize the index symtab iterator ITER.
3773    If WANT_SPECIFIC_BLOCK is non-zero, only look for symbols
3774    in block BLOCK_INDEX.  Otherwise BLOCK_INDEX is ignored.  */
3775
3776 static void
3777 dw2_symtab_iter_init (struct dw2_symtab_iterator *iter,
3778                       struct mapped_index *index,
3779                       int want_specific_block,
3780                       int block_index,
3781                       domain_enum domain,
3782                       const char *name)
3783 {
3784   iter->index = index;
3785   iter->want_specific_block = want_specific_block;
3786   iter->block_index = block_index;
3787   iter->domain = domain;
3788   iter->next = 0;
3789   iter->global_seen = 0;
3790
3791   if (find_slot_in_mapped_hash (index, name, &iter->vec))
3792     iter->length = MAYBE_SWAP (*iter->vec);
3793   else
3794     {
3795       iter->vec = NULL;
3796       iter->length = 0;
3797     }
3798 }
3799
3800 /* Return the next matching CU or NULL if there are no more.  */
3801
3802 static struct dwarf2_per_cu_data *
3803 dw2_symtab_iter_next (struct dw2_symtab_iterator *iter)
3804 {
3805   for ( ; iter->next < iter->length; ++iter->next)
3806     {
3807       offset_type cu_index_and_attrs =
3808         MAYBE_SWAP (iter->vec[iter->next + 1]);
3809       offset_type cu_index = GDB_INDEX_CU_VALUE (cu_index_and_attrs);
3810       struct dwarf2_per_cu_data *per_cu;
3811       int want_static = iter->block_index != GLOBAL_BLOCK;
3812       /* This value is only valid for index versions >= 7.  */
3813       int is_static = GDB_INDEX_SYMBOL_STATIC_VALUE (cu_index_and_attrs);
3814       gdb_index_symbol_kind symbol_kind =
3815         GDB_INDEX_SYMBOL_KIND_VALUE (cu_index_and_attrs);
3816       /* Only check the symbol attributes if they're present.
3817          Indices prior to version 7 don't record them,
3818          and indices >= 7 may elide them for certain symbols
3819          (gold does this).  */
3820       int attrs_valid =
3821         (iter->index->version >= 7
3822          && symbol_kind != GDB_INDEX_SYMBOL_KIND_NONE);
3823
3824       /* Don't crash on bad data.  */
3825       if (cu_index >= (dwarf2_per_objfile->n_comp_units
3826                        + dwarf2_per_objfile->n_type_units))
3827         {
3828           complaint (&symfile_complaints,
3829                      _(".gdb_index entry has bad CU index"
3830                        " [in module %s]"),
3831                      objfile_name (dwarf2_per_objfile->objfile));
3832           continue;
3833         }
3834
3835       per_cu = dw2_get_cutu (cu_index);
3836
3837       /* Skip if already read in.  */
3838       if (per_cu->v.quick->compunit_symtab)
3839         continue;
3840
3841       /* Check static vs global.  */
3842       if (attrs_valid)
3843         {
3844           if (iter->want_specific_block
3845               && want_static != is_static)
3846             continue;
3847           /* Work around gold/15646.  */
3848           if (!is_static && iter->global_seen)
3849             continue;
3850           if (!is_static)
3851             iter->global_seen = 1;
3852         }
3853
3854       /* Only check the symbol's kind if it has one.  */
3855       if (attrs_valid)
3856         {
3857           switch (iter->domain)
3858             {
3859             case VAR_DOMAIN:
3860               if (symbol_kind != GDB_INDEX_SYMBOL_KIND_VARIABLE
3861                   && symbol_kind != GDB_INDEX_SYMBOL_KIND_FUNCTION
3862                   /* Some types are also in VAR_DOMAIN.  */
3863                   && symbol_kind != GDB_INDEX_SYMBOL_KIND_TYPE)
3864                 continue;
3865               break;
3866             case STRUCT_DOMAIN:
3867               if (symbol_kind != GDB_INDEX_SYMBOL_KIND_TYPE)
3868                 continue;
3869               break;
3870             case LABEL_DOMAIN:
3871               if (symbol_kind != GDB_INDEX_SYMBOL_KIND_OTHER)
3872                 continue;
3873               break;
3874             default:
3875               break;
3876             }
3877         }
3878
3879       ++iter->next;
3880       return per_cu;
3881     }
3882
3883   return NULL;
3884 }
3885
3886 static struct compunit_symtab *
3887 dw2_lookup_symbol (struct objfile *objfile, int block_index,
3888                    const char *name, domain_enum domain)
3889 {
3890   struct compunit_symtab *stab_best = NULL;
3891   struct mapped_index *index;
3892
3893   dw2_setup (objfile);
3894
3895   index = dwarf2_per_objfile->index_table;
3896
3897   /* index is NULL if OBJF_READNOW.  */
3898   if (index)
3899     {
3900       struct dw2_symtab_iterator iter;
3901       struct dwarf2_per_cu_data *per_cu;
3902
3903       dw2_symtab_iter_init (&iter, index, 1, block_index, domain, name);
3904
3905       while ((per_cu = dw2_symtab_iter_next (&iter)) != NULL)
3906         {
3907           struct symbol *sym, *with_opaque = NULL;
3908           struct compunit_symtab *stab = dw2_instantiate_symtab (per_cu);
3909           const struct blockvector *bv = COMPUNIT_BLOCKVECTOR (stab);
3910           struct block *block = BLOCKVECTOR_BLOCK (bv, block_index);
3911
3912           sym = block_find_symbol (block, name, domain,
3913                                    block_find_non_opaque_type_preferred,
3914                                    &with_opaque);
3915
3916           /* Some caution must be observed with overloaded functions
3917              and methods, since the index will not contain any overload
3918              information (but NAME might contain it).  */
3919
3920           if (sym != NULL
3921               && SYMBOL_MATCHES_SEARCH_NAME (sym, name))
3922             return stab;
3923           if (with_opaque != NULL
3924               && SYMBOL_MATCHES_SEARCH_NAME (with_opaque, name))
3925             stab_best = stab;
3926
3927           /* Keep looking through other CUs.  */
3928         }
3929     }
3930
3931   return stab_best;
3932 }
3933
3934 static void
3935 dw2_print_stats (struct objfile *objfile)
3936 {
3937   int i, total, count;
3938
3939   dw2_setup (objfile);
3940   total = dwarf2_per_objfile->n_comp_units + dwarf2_per_objfile->n_type_units;
3941   count = 0;
3942   for (i = 0; i < total; ++i)
3943     {
3944       struct dwarf2_per_cu_data *per_cu = dw2_get_cutu (i);
3945
3946       if (!per_cu->v.quick->compunit_symtab)
3947         ++count;
3948     }
3949   printf_filtered (_("  Number of read CUs: %d\n"), total - count);
3950   printf_filtered (_("  Number of unread CUs: %d\n"), count);
3951 }
3952
3953 /* This dumps minimal information about the index.
3954    It is called via "mt print objfiles".
3955    One use is to verify .gdb_index has been loaded by the
3956    gdb.dwarf2/gdb-index.exp testcase.  */
3957
3958 static void
3959 dw2_dump (struct objfile *objfile)
3960 {
3961   dw2_setup (objfile);
3962   gdb_assert (dwarf2_per_objfile->using_index);
3963   printf_filtered (".gdb_index:");
3964   if (dwarf2_per_objfile->index_table != NULL)
3965     {
3966       printf_filtered (" version %d\n",
3967                        dwarf2_per_objfile->index_table->version);
3968     }
3969   else
3970     printf_filtered (" faked for \"readnow\"\n");
3971   printf_filtered ("\n");
3972 }
3973
3974 static void
3975 dw2_relocate (struct objfile *objfile,
3976               const struct section_offsets *new_offsets,
3977               const struct section_offsets *delta)
3978 {
3979   /* There's nothing to relocate here.  */
3980 }
3981
3982 static void
3983 dw2_expand_symtabs_for_function (struct objfile *objfile,
3984                                  const char *func_name)
3985 {
3986   struct mapped_index *index;
3987
3988   dw2_setup (objfile);
3989
3990   index = dwarf2_per_objfile->index_table;
3991
3992   /* index is NULL if OBJF_READNOW.  */
3993   if (index)
3994     {
3995       struct dw2_symtab_iterator iter;
3996       struct dwarf2_per_cu_data *per_cu;
3997
3998       /* Note: It doesn't matter what we pass for block_index here.  */
3999       dw2_symtab_iter_init (&iter, index, 0, GLOBAL_BLOCK, VAR_DOMAIN,
4000                             func_name);
4001
4002       while ((per_cu = dw2_symtab_iter_next (&iter)) != NULL)
4003         dw2_instantiate_symtab (per_cu);
4004     }
4005 }
4006
4007 static void
4008 dw2_expand_all_symtabs (struct objfile *objfile)
4009 {
4010   int i;
4011
4012   dw2_setup (objfile);
4013
4014   for (i = 0; i < (dwarf2_per_objfile->n_comp_units
4015                    + dwarf2_per_objfile->n_type_units); ++i)
4016     {
4017       struct dwarf2_per_cu_data *per_cu = dw2_get_cutu (i);
4018
4019       dw2_instantiate_symtab (per_cu);
4020     }
4021 }
4022
4023 static void
4024 dw2_expand_symtabs_with_fullname (struct objfile *objfile,
4025                                   const char *fullname)
4026 {
4027   int i;
4028
4029   dw2_setup (objfile);
4030
4031   /* We don't need to consider type units here.
4032      This is only called for examining code, e.g. expand_line_sal.
4033      There can be an order of magnitude (or more) more type units
4034      than comp units, and we avoid them if we can.  */
4035
4036   for (i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
4037     {
4038       int j;
4039       struct dwarf2_per_cu_data *per_cu = dw2_get_cutu (i);
4040       struct quick_file_names *file_data;
4041
4042       /* We only need to look at symtabs not already expanded.  */
4043       if (per_cu->v.quick->compunit_symtab)
4044         continue;
4045
4046       file_data = dw2_get_file_names (per_cu);
4047       if (file_data == NULL)
4048         continue;
4049
4050       for (j = 0; j < file_data->num_file_names; ++j)
4051         {
4052           const char *this_fullname = file_data->file_names[j];
4053
4054           if (filename_cmp (this_fullname, fullname) == 0)
4055             {
4056               dw2_instantiate_symtab (per_cu);
4057               break;
4058             }
4059         }
4060     }
4061 }
4062
4063 static void
4064 dw2_map_matching_symbols (struct objfile *objfile,
4065                           const char * name, domain_enum domain,
4066                           int global,
4067                           int (*callback) (struct block *,
4068                                            struct symbol *, void *),
4069                           void *data, symbol_compare_ftype *match,
4070                           symbol_compare_ftype *ordered_compare)
4071 {
4072   /* Currently unimplemented; used for Ada.  The function can be called if the
4073      current language is Ada for a non-Ada objfile using GNU index.  As Ada
4074      does not look for non-Ada symbols this function should just return.  */
4075 }
4076
4077 static void
4078 dw2_expand_symtabs_matching
4079   (struct objfile *objfile,
4080    gdb::function_view<expand_symtabs_file_matcher_ftype> file_matcher,
4081    gdb::function_view<expand_symtabs_symbol_matcher_ftype> symbol_matcher,
4082    gdb::function_view<expand_symtabs_exp_notify_ftype> expansion_notify,
4083    enum search_domain kind)
4084 {
4085   int i;
4086   offset_type iter;
4087   struct mapped_index *index;
4088
4089   dw2_setup (objfile);
4090
4091   /* index_table is NULL if OBJF_READNOW.  */
4092   if (!dwarf2_per_objfile->index_table)
4093     return;
4094   index = dwarf2_per_objfile->index_table;
4095
4096   if (file_matcher != NULL)
4097     {
4098       htab_up visited_found (htab_create_alloc (10, htab_hash_pointer,
4099                                                 htab_eq_pointer,
4100                                                 NULL, xcalloc, xfree));
4101       htab_up visited_not_found (htab_create_alloc (10, htab_hash_pointer,
4102                                                     htab_eq_pointer,
4103                                                     NULL, xcalloc, xfree));
4104
4105       /* The rule is CUs specify all the files, including those used by
4106          any TU, so there's no need to scan TUs here.  */
4107
4108       for (i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
4109         {
4110           int j;
4111           struct dwarf2_per_cu_data *per_cu = dw2_get_cu (i);
4112           struct quick_file_names *file_data;
4113           void **slot;
4114
4115           QUIT;
4116
4117           per_cu->v.quick->mark = 0;
4118
4119           /* We only need to look at symtabs not already expanded.  */
4120           if (per_cu->v.quick->compunit_symtab)
4121             continue;
4122
4123           file_data = dw2_get_file_names (per_cu);
4124           if (file_data == NULL)
4125             continue;
4126
4127           if (htab_find (visited_not_found.get (), file_data) != NULL)
4128             continue;
4129           else if (htab_find (visited_found.get (), file_data) != NULL)
4130             {
4131               per_cu->v.quick->mark = 1;
4132               continue;
4133             }
4134
4135           for (j = 0; j < file_data->num_file_names; ++j)
4136             {
4137               const char *this_real_name;
4138
4139               if (file_matcher (file_data->file_names[j], false))
4140                 {
4141                   per_cu->v.quick->mark = 1;
4142                   break;
4143                 }
4144
4145               /* Before we invoke realpath, which can get expensive when many
4146                  files are involved, do a quick comparison of the basenames.  */
4147               if (!basenames_may_differ
4148                   && !file_matcher (lbasename (file_data->file_names[j]),
4149                                     true))
4150                 continue;
4151
4152               this_real_name = dw2_get_real_path (objfile, file_data, j);
4153               if (file_matcher (this_real_name, false))
4154                 {
4155                   per_cu->v.quick->mark = 1;
4156                   break;
4157                 }
4158             }
4159
4160           slot = htab_find_slot (per_cu->v.quick->mark
4161                                  ? visited_found.get ()
4162                                  : visited_not_found.get (),
4163                                  file_data, INSERT);
4164           *slot = file_data;
4165         }
4166     }
4167
4168   for (iter = 0; iter < index->symbol_table_slots; ++iter)
4169     {
4170       offset_type idx = 2 * iter;
4171       const char *name;
4172       offset_type *vec, vec_len, vec_idx;
4173       int global_seen = 0;
4174
4175       QUIT;
4176
4177       if (index->symbol_table[idx] == 0 && index->symbol_table[idx + 1] == 0)
4178         continue;
4179
4180       name = index->constant_pool + MAYBE_SWAP (index->symbol_table[idx]);
4181
4182       if (!symbol_matcher (name))
4183         continue;
4184
4185       /* The name was matched, now expand corresponding CUs that were
4186          marked.  */
4187       vec = (offset_type *) (index->constant_pool
4188                              + MAYBE_SWAP (index->symbol_table[idx + 1]));
4189       vec_len = MAYBE_SWAP (vec[0]);
4190       for (vec_idx = 0; vec_idx < vec_len; ++vec_idx)
4191         {
4192           struct dwarf2_per_cu_data *per_cu;
4193           offset_type cu_index_and_attrs = MAYBE_SWAP (vec[vec_idx + 1]);
4194           /* This value is only valid for index versions >= 7.  */
4195           int is_static = GDB_INDEX_SYMBOL_STATIC_VALUE (cu_index_and_attrs);
4196           gdb_index_symbol_kind symbol_kind =
4197             GDB_INDEX_SYMBOL_KIND_VALUE (cu_index_and_attrs);
4198           int cu_index = GDB_INDEX_CU_VALUE (cu_index_and_attrs);
4199           /* Only check the symbol attributes if they're present.
4200              Indices prior to version 7 don't record them,
4201              and indices >= 7 may elide them for certain symbols
4202              (gold does this).  */
4203           int attrs_valid =
4204             (index->version >= 7
4205              && symbol_kind != GDB_INDEX_SYMBOL_KIND_NONE);
4206
4207           /* Work around gold/15646.  */
4208           if (attrs_valid)
4209             {
4210               if (!is_static && global_seen)
4211                 continue;
4212               if (!is_static)
4213                 global_seen = 1;
4214             }
4215
4216           /* Only check the symbol's kind if it has one.  */
4217           if (attrs_valid)
4218             {
4219               switch (kind)
4220                 {
4221                 case VARIABLES_DOMAIN:
4222                   if (symbol_kind != GDB_INDEX_SYMBOL_KIND_VARIABLE)
4223                     continue;
4224                   break;
4225                 case FUNCTIONS_DOMAIN:
4226                   if (symbol_kind != GDB_INDEX_SYMBOL_KIND_FUNCTION)
4227                     continue;
4228                   break;
4229                 case TYPES_DOMAIN:
4230                   if (symbol_kind != GDB_INDEX_SYMBOL_KIND_TYPE)
4231                     continue;
4232                   break;
4233                 default:
4234                   break;
4235                 }
4236             }
4237
4238           /* Don't crash on bad data.  */
4239           if (cu_index >= (dwarf2_per_objfile->n_comp_units
4240                            + dwarf2_per_objfile->n_type_units))
4241             {
4242               complaint (&symfile_complaints,
4243                          _(".gdb_index entry has bad CU index"
4244                            " [in module %s]"), objfile_name (objfile));
4245               continue;
4246             }
4247
4248           per_cu = dw2_get_cutu (cu_index);
4249           if (file_matcher == NULL || per_cu->v.quick->mark)
4250             {
4251               int symtab_was_null =
4252                 (per_cu->v.quick->compunit_symtab == NULL);
4253
4254               dw2_instantiate_symtab (per_cu);
4255
4256               if (expansion_notify != NULL
4257                   && symtab_was_null
4258                   && per_cu->v.quick->compunit_symtab != NULL)
4259                 {
4260                   expansion_notify (per_cu->v.quick->compunit_symtab);
4261                 }
4262             }
4263         }
4264     }
4265 }
4266
4267 /* A helper for dw2_find_pc_sect_compunit_symtab which finds the most specific
4268    symtab.  */
4269
4270 static struct compunit_symtab *
4271 recursively_find_pc_sect_compunit_symtab (struct compunit_symtab *cust,
4272                                           CORE_ADDR pc)
4273 {
4274   int i;
4275
4276   if (COMPUNIT_BLOCKVECTOR (cust) != NULL
4277       && blockvector_contains_pc (COMPUNIT_BLOCKVECTOR (cust), pc))
4278     return cust;
4279
4280   if (cust->includes == NULL)
4281     return NULL;
4282
4283   for (i = 0; cust->includes[i]; ++i)
4284     {
4285       struct compunit_symtab *s = cust->includes[i];
4286
4287       s = recursively_find_pc_sect_compunit_symtab (s, pc);
4288       if (s != NULL)
4289         return s;
4290     }
4291
4292   return NULL;
4293 }
4294
4295 static struct compunit_symtab *
4296 dw2_find_pc_sect_compunit_symtab (struct objfile *objfile,
4297                                   struct bound_minimal_symbol msymbol,
4298                                   CORE_ADDR pc,
4299                                   struct obj_section *section,
4300                                   int warn_if_readin)
4301 {
4302   struct dwarf2_per_cu_data *data;
4303   struct compunit_symtab *result;
4304
4305   dw2_setup (objfile);
4306
4307   if (!objfile->psymtabs_addrmap)
4308     return NULL;
4309
4310   data = (struct dwarf2_per_cu_data *) addrmap_find (objfile->psymtabs_addrmap,
4311                                                      pc);
4312   if (!data)
4313     return NULL;
4314
4315   if (warn_if_readin && data->v.quick->compunit_symtab)
4316     warning (_("(Internal error: pc %s in read in CU, but not in symtab.)"),
4317              paddress (get_objfile_arch (objfile), pc));
4318
4319   result
4320     = recursively_find_pc_sect_compunit_symtab (dw2_instantiate_symtab (data),
4321                                                 pc);
4322   gdb_assert (result != NULL);
4323   return result;
4324 }
4325
4326 static void
4327 dw2_map_symbol_filenames (struct objfile *objfile, symbol_filename_ftype *fun,
4328                           void *data, int need_fullname)
4329 {
4330   dw2_setup (objfile);
4331
4332   if (!dwarf2_per_objfile->filenames_cache)
4333     {
4334       dwarf2_per_objfile->filenames_cache.emplace ();
4335
4336       htab_up visited (htab_create_alloc (10,
4337                                           htab_hash_pointer, htab_eq_pointer,
4338                                           NULL, xcalloc, xfree));
4339
4340       /* The rule is CUs specify all the files, including those used
4341          by any TU, so there's no need to scan TUs here.  We can
4342          ignore file names coming from already-expanded CUs.  */
4343
4344       for (int i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
4345         {
4346           struct dwarf2_per_cu_data *per_cu = dw2_get_cutu (i);
4347
4348           if (per_cu->v.quick->compunit_symtab)
4349             {
4350               void **slot = htab_find_slot (visited.get (),
4351                                             per_cu->v.quick->file_names,
4352                                             INSERT);
4353
4354               *slot = per_cu->v.quick->file_names;
4355             }
4356         }
4357
4358       for (int i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
4359         {
4360           int j;
4361           struct dwarf2_per_cu_data *per_cu = dw2_get_cu (i);
4362           struct quick_file_names *file_data;
4363           void **slot;
4364
4365           /* We only need to look at symtabs not already expanded.  */
4366           if (per_cu->v.quick->compunit_symtab)
4367             continue;
4368
4369           file_data = dw2_get_file_names (per_cu);
4370           if (file_data == NULL)
4371             continue;
4372
4373           slot = htab_find_slot (visited.get (), file_data, INSERT);
4374           if (*slot)
4375             {
4376               /* Already visited.  */
4377               continue;
4378             }
4379           *slot = file_data;
4380
4381           for (int j = 0; j < file_data->num_file_names; ++j)
4382             {
4383               const char *filename = file_data->file_names[j];
4384               dwarf2_per_objfile->filenames_cache->seen (filename);
4385             }
4386         }
4387     }
4388
4389   dwarf2_per_objfile->filenames_cache->traverse ([&] (const char *filename)
4390     {
4391       gdb::unique_xmalloc_ptr<char> this_real_name;
4392
4393       if (need_fullname)
4394         this_real_name = gdb_realpath (filename);
4395       (*fun) (filename, this_real_name.get (), data);
4396     });
4397 }
4398
4399 static int
4400 dw2_has_symbols (struct objfile *objfile)
4401 {
4402   return 1;
4403 }
4404
4405 const struct quick_symbol_functions dwarf2_gdb_index_functions =
4406 {
4407   dw2_has_symbols,
4408   dw2_find_last_source_symtab,
4409   dw2_forget_cached_source_info,
4410   dw2_map_symtabs_matching_filename,
4411   dw2_lookup_symbol,
4412   dw2_print_stats,
4413   dw2_dump,
4414   dw2_relocate,
4415   dw2_expand_symtabs_for_function,
4416   dw2_expand_all_symtabs,
4417   dw2_expand_symtabs_with_fullname,
4418   dw2_map_matching_symbols,
4419   dw2_expand_symtabs_matching,
4420   dw2_find_pc_sect_compunit_symtab,
4421   dw2_map_symbol_filenames
4422 };
4423
4424 /* Initialize for reading DWARF for this objfile.  Return 0 if this
4425    file will use psymtabs, or 1 if using the GNU index.  */
4426
4427 int
4428 dwarf2_initialize_objfile (struct objfile *objfile)
4429 {
4430   /* If we're about to read full symbols, don't bother with the
4431      indices.  In this case we also don't care if some other debug
4432      format is making psymtabs, because they are all about to be
4433      expanded anyway.  */
4434   if ((objfile->flags & OBJF_READNOW))
4435     {
4436       int i;
4437
4438       dwarf2_per_objfile->using_index = 1;
4439       create_all_comp_units (objfile);
4440       create_all_type_units (objfile);
4441       dwarf2_per_objfile->quick_file_names_table =
4442         create_quick_file_names_table (dwarf2_per_objfile->n_comp_units);
4443
4444       for (i = 0; i < (dwarf2_per_objfile->n_comp_units
4445                        + dwarf2_per_objfile->n_type_units); ++i)
4446         {
4447           struct dwarf2_per_cu_data *per_cu = dw2_get_cutu (i);
4448
4449           per_cu->v.quick = OBSTACK_ZALLOC (&objfile->objfile_obstack,
4450                                             struct dwarf2_per_cu_quick_data);
4451         }
4452
4453       /* Return 1 so that gdb sees the "quick" functions.  However,
4454          these functions will be no-ops because we will have expanded
4455          all symtabs.  */
4456       return 1;
4457     }
4458
4459   if (dwarf2_read_index (objfile))
4460     return 1;
4461
4462   return 0;
4463 }
4464
4465 \f
4466
4467 /* Build a partial symbol table.  */
4468
4469 void
4470 dwarf2_build_psymtabs (struct objfile *objfile)
4471 {
4472
4473   if (objfile->global_psymbols.size == 0 && objfile->static_psymbols.size == 0)
4474     {
4475       init_psymbol_list (objfile, 1024);
4476     }
4477
4478   TRY
4479     {
4480       /* This isn't really ideal: all the data we allocate on the
4481          objfile's obstack is still uselessly kept around.  However,
4482          freeing it seems unsafe.  */
4483       psymtab_discarder psymtabs (objfile);
4484       dwarf2_build_psymtabs_hard (objfile);
4485       psymtabs.keep ();
4486     }
4487   CATCH (except, RETURN_MASK_ERROR)
4488     {
4489       exception_print (gdb_stderr, except);
4490     }
4491   END_CATCH
4492 }
4493
4494 /* Return the total length of the CU described by HEADER.  */
4495
4496 static unsigned int
4497 get_cu_length (const struct comp_unit_head *header)
4498 {
4499   return header->initial_length_size + header->length;
4500 }
4501
4502 /* Return TRUE if SECT_OFF is within CU_HEADER.  */
4503
4504 static inline bool
4505 offset_in_cu_p (const comp_unit_head *cu_header, sect_offset sect_off)
4506 {
4507   sect_offset bottom = cu_header->sect_off;
4508   sect_offset top = cu_header->sect_off + get_cu_length (cu_header);
4509
4510   return sect_off >= bottom && sect_off < top;
4511 }
4512
4513 /* Find the base address of the compilation unit for range lists and
4514    location lists.  It will normally be specified by DW_AT_low_pc.
4515    In DWARF-3 draft 4, the base address could be overridden by
4516    DW_AT_entry_pc.  It's been removed, but GCC still uses this for
4517    compilation units with discontinuous ranges.  */
4518
4519 static void
4520 dwarf2_find_base_address (struct die_info *die, struct dwarf2_cu *cu)
4521 {
4522   struct attribute *attr;
4523
4524   cu->base_known = 0;
4525   cu->base_address = 0;
4526
4527   attr = dwarf2_attr (die, DW_AT_entry_pc, cu);
4528   if (attr)
4529     {
4530       cu->base_address = attr_value_as_address (attr);
4531       cu->base_known = 1;
4532     }
4533   else
4534     {
4535       attr = dwarf2_attr (die, DW_AT_low_pc, cu);
4536       if (attr)
4537         {
4538           cu->base_address = attr_value_as_address (attr);
4539           cu->base_known = 1;
4540         }
4541     }
4542 }
4543
4544 /* Read in the comp unit header information from the debug_info at info_ptr.
4545    Use rcuh_kind::COMPILE as the default type if not known by the caller.
4546    NOTE: This leaves members offset, first_die_offset to be filled in
4547    by the caller.  */
4548
4549 static const gdb_byte *
4550 read_comp_unit_head (struct comp_unit_head *cu_header,
4551                      const gdb_byte *info_ptr,
4552                      struct dwarf2_section_info *section,
4553                      rcuh_kind section_kind)
4554 {
4555   int signed_addr;
4556   unsigned int bytes_read;
4557   const char *filename = get_section_file_name (section);
4558   bfd *abfd = get_section_bfd_owner (section);
4559
4560   cu_header->length = read_initial_length (abfd, info_ptr, &bytes_read);
4561   cu_header->initial_length_size = bytes_read;
4562   cu_header->offset_size = (bytes_read == 4) ? 4 : 8;
4563   info_ptr += bytes_read;
4564   cu_header->version = read_2_bytes (abfd, info_ptr);
4565   info_ptr += 2;
4566   if (cu_header->version < 5)
4567     switch (section_kind)
4568       {
4569       case rcuh_kind::COMPILE:
4570         cu_header->unit_type = DW_UT_compile;
4571         break;
4572       case rcuh_kind::TYPE:
4573         cu_header->unit_type = DW_UT_type;
4574         break;
4575       default:
4576         internal_error (__FILE__, __LINE__,
4577                         _("read_comp_unit_head: invalid section_kind"));
4578       }
4579   else
4580     {
4581       cu_header->unit_type = static_cast<enum dwarf_unit_type>
4582                                                  (read_1_byte (abfd, info_ptr));
4583       info_ptr += 1;
4584       switch (cu_header->unit_type)
4585         {
4586         case DW_UT_compile:
4587           if (section_kind != rcuh_kind::COMPILE)
4588             error (_("Dwarf Error: wrong unit_type in compilation unit header "
4589                    "(is DW_UT_compile, should be DW_UT_type) [in module %s]"),
4590                    filename);
4591           break;
4592         case DW_UT_type:
4593           section_kind = rcuh_kind::TYPE;
4594           break;
4595         default:
4596           error (_("Dwarf Error: wrong unit_type in compilation unit header "
4597                  "(is %d, should be %d or %d) [in module %s]"),
4598                  cu_header->unit_type, DW_UT_compile, DW_UT_type, filename);
4599         }
4600
4601       cu_header->addr_size = read_1_byte (abfd, info_ptr);
4602       info_ptr += 1;
4603     }
4604   cu_header->abbrev_sect_off = (sect_offset) read_offset (abfd, info_ptr,
4605                                                           cu_header,
4606                                                           &bytes_read);
4607   info_ptr += bytes_read;
4608   if (cu_header->version < 5)
4609     {
4610       cu_header->addr_size = read_1_byte (abfd, info_ptr);
4611       info_ptr += 1;
4612     }
4613   signed_addr = bfd_get_sign_extend_vma (abfd);
4614   if (signed_addr < 0)
4615     internal_error (__FILE__, __LINE__,
4616                     _("read_comp_unit_head: dwarf from non elf file"));
4617   cu_header->signed_addr_p = signed_addr;
4618
4619   if (section_kind == rcuh_kind::TYPE)
4620     {
4621       LONGEST type_offset;
4622
4623       cu_header->signature = read_8_bytes (abfd, info_ptr);
4624       info_ptr += 8;
4625
4626       type_offset = read_offset (abfd, info_ptr, cu_header, &bytes_read);
4627       info_ptr += bytes_read;
4628       cu_header->type_cu_offset_in_tu = (cu_offset) type_offset;
4629       if (to_underlying (cu_header->type_cu_offset_in_tu) != type_offset)
4630         error (_("Dwarf Error: Too big type_offset in compilation unit "
4631                "header (is %s) [in module %s]"), plongest (type_offset),
4632                filename);
4633     }
4634
4635   return info_ptr;
4636 }
4637
4638 /* Helper function that returns the proper abbrev section for
4639    THIS_CU.  */
4640
4641 static struct dwarf2_section_info *
4642 get_abbrev_section_for_cu (struct dwarf2_per_cu_data *this_cu)
4643 {
4644   struct dwarf2_section_info *abbrev;
4645
4646   if (this_cu->is_dwz)
4647     abbrev = &dwarf2_get_dwz_file ()->abbrev;
4648   else
4649     abbrev = &dwarf2_per_objfile->abbrev;
4650
4651   return abbrev;
4652 }
4653
4654 /* Subroutine of read_and_check_comp_unit_head and
4655    read_and_check_type_unit_head to simplify them.
4656    Perform various error checking on the header.  */
4657
4658 static void
4659 error_check_comp_unit_head (struct comp_unit_head *header,
4660                             struct dwarf2_section_info *section,
4661                             struct dwarf2_section_info *abbrev_section)
4662 {
4663   const char *filename = get_section_file_name (section);
4664
4665   if (header->version < 2 || header->version > 5)
4666     error (_("Dwarf Error: wrong version in compilation unit header "
4667            "(is %d, should be 2, 3, 4 or 5) [in module %s]"), header->version,
4668            filename);
4669
4670   if (to_underlying (header->abbrev_sect_off)
4671       >= dwarf2_section_size (dwarf2_per_objfile->objfile, abbrev_section))
4672     error (_("Dwarf Error: bad offset (0x%x) in compilation unit header "
4673            "(offset 0x%x + 6) [in module %s]"),
4674            to_underlying (header->abbrev_sect_off),
4675            to_underlying (header->sect_off),
4676            filename);
4677
4678   /* Cast to ULONGEST to use 64-bit arithmetic when possible to
4679      avoid potential 32-bit overflow.  */
4680   if (((ULONGEST) header->sect_off + get_cu_length (header))
4681       > section->size)
4682     error (_("Dwarf Error: bad length (0x%x) in compilation unit header "
4683            "(offset 0x%x + 0) [in module %s]"),
4684            header->length, to_underlying (header->sect_off),
4685            filename);
4686 }
4687
4688 /* Read in a CU/TU header and perform some basic error checking.
4689    The contents of the header are stored in HEADER.
4690    The result is a pointer to the start of the first DIE.  */
4691
4692 static const gdb_byte *
4693 read_and_check_comp_unit_head (struct comp_unit_head *header,
4694                                struct dwarf2_section_info *section,
4695                                struct dwarf2_section_info *abbrev_section,
4696                                const gdb_byte *info_ptr,
4697                                rcuh_kind section_kind)
4698 {
4699   const gdb_byte *beg_of_comp_unit = info_ptr;
4700   bfd *abfd = get_section_bfd_owner (section);
4701
4702   header->sect_off = (sect_offset) (beg_of_comp_unit - section->buffer);
4703
4704   info_ptr = read_comp_unit_head (header, info_ptr, section, section_kind);
4705
4706   header->first_die_cu_offset = (cu_offset) (info_ptr - beg_of_comp_unit);
4707
4708   error_check_comp_unit_head (header, section, abbrev_section);
4709
4710   return info_ptr;
4711 }
4712
4713 /* Fetch the abbreviation table offset from a comp or type unit header.  */
4714
4715 static sect_offset
4716 read_abbrev_offset (struct dwarf2_section_info *section,
4717                     sect_offset sect_off)
4718 {
4719   bfd *abfd = get_section_bfd_owner (section);
4720   const gdb_byte *info_ptr;
4721   unsigned int initial_length_size, offset_size;
4722   uint16_t version;
4723
4724   dwarf2_read_section (dwarf2_per_objfile->objfile, section);
4725   info_ptr = section->buffer + to_underlying (sect_off);
4726   read_initial_length (abfd, info_ptr, &initial_length_size);
4727   offset_size = initial_length_size == 4 ? 4 : 8;
4728   info_ptr += initial_length_size;
4729
4730   version = read_2_bytes (abfd, info_ptr);
4731   info_ptr += 2;
4732   if (version >= 5)
4733     {
4734       /* Skip unit type and address size.  */
4735       info_ptr += 2;
4736     }
4737
4738   return (sect_offset) read_offset_1 (abfd, info_ptr, offset_size);
4739 }
4740
4741 /* Allocate a new partial symtab for file named NAME and mark this new
4742    partial symtab as being an include of PST.  */
4743
4744 static void
4745 dwarf2_create_include_psymtab (const char *name, struct partial_symtab *pst,
4746                                struct objfile *objfile)
4747 {
4748   struct partial_symtab *subpst = allocate_psymtab (name, objfile);
4749
4750   if (!IS_ABSOLUTE_PATH (subpst->filename))
4751     {
4752       /* It shares objfile->objfile_obstack.  */
4753       subpst->dirname = pst->dirname;
4754     }
4755
4756   subpst->textlow = 0;
4757   subpst->texthigh = 0;
4758
4759   subpst->dependencies
4760     = XOBNEW (&objfile->objfile_obstack, struct partial_symtab *);
4761   subpst->dependencies[0] = pst;
4762   subpst->number_of_dependencies = 1;
4763
4764   subpst->globals_offset = 0;
4765   subpst->n_global_syms = 0;
4766   subpst->statics_offset = 0;
4767   subpst->n_static_syms = 0;
4768   subpst->compunit_symtab = NULL;
4769   subpst->read_symtab = pst->read_symtab;
4770   subpst->readin = 0;
4771
4772   /* No private part is necessary for include psymtabs.  This property
4773      can be used to differentiate between such include psymtabs and
4774      the regular ones.  */
4775   subpst->read_symtab_private = NULL;
4776 }
4777
4778 /* Read the Line Number Program data and extract the list of files
4779    included by the source file represented by PST.  Build an include
4780    partial symtab for each of these included files.  */
4781
4782 static void
4783 dwarf2_build_include_psymtabs (struct dwarf2_cu *cu,
4784                                struct die_info *die,
4785                                struct partial_symtab *pst)
4786 {
4787   line_header_up lh;
4788   struct attribute *attr;
4789
4790   attr = dwarf2_attr (die, DW_AT_stmt_list, cu);
4791   if (attr)
4792     lh = dwarf_decode_line_header ((sect_offset) DW_UNSND (attr), cu);
4793   if (lh == NULL)
4794     return;  /* No linetable, so no includes.  */
4795
4796   /* NOTE: pst->dirname is DW_AT_comp_dir (if present).  */
4797   dwarf_decode_lines (lh.get (), pst->dirname, cu, pst, pst->textlow, 1);
4798 }
4799
4800 static hashval_t
4801 hash_signatured_type (const void *item)
4802 {
4803   const struct signatured_type *sig_type
4804     = (const struct signatured_type *) item;
4805
4806   /* This drops the top 32 bits of the signature, but is ok for a hash.  */
4807   return sig_type->signature;
4808 }
4809
4810 static int
4811 eq_signatured_type (const void *item_lhs, const void *item_rhs)
4812 {
4813   const struct signatured_type *lhs = (const struct signatured_type *) item_lhs;
4814   const struct signatured_type *rhs = (const struct signatured_type *) item_rhs;
4815
4816   return lhs->signature == rhs->signature;
4817 }
4818
4819 /* Allocate a hash table for signatured types.  */
4820
4821 static htab_t
4822 allocate_signatured_type_table (struct objfile *objfile)
4823 {
4824   return htab_create_alloc_ex (41,
4825                                hash_signatured_type,
4826                                eq_signatured_type,
4827                                NULL,
4828                                &objfile->objfile_obstack,
4829                                hashtab_obstack_allocate,
4830                                dummy_obstack_deallocate);
4831 }
4832
4833 /* A helper function to add a signatured type CU to a table.  */
4834
4835 static int
4836 add_signatured_type_cu_to_table (void **slot, void *datum)
4837 {
4838   struct signatured_type *sigt = (struct signatured_type *) *slot;
4839   struct signatured_type ***datap = (struct signatured_type ***) datum;
4840
4841   **datap = sigt;
4842   ++*datap;
4843
4844   return 1;
4845 }
4846
4847 /* A helper for create_debug_types_hash_table.  Read types from SECTION
4848    and fill them into TYPES_HTAB.  It will process only type units,
4849    therefore DW_UT_type.  */
4850
4851 static void
4852 create_debug_type_hash_table (struct dwo_file *dwo_file,
4853                               dwarf2_section_info *section, htab_t &types_htab,
4854                               rcuh_kind section_kind)
4855 {
4856   struct objfile *objfile = dwarf2_per_objfile->objfile;
4857   struct dwarf2_section_info *abbrev_section;
4858   bfd *abfd;
4859   const gdb_byte *info_ptr, *end_ptr;
4860
4861   abbrev_section = (dwo_file != NULL
4862                     ? &dwo_file->sections.abbrev
4863                     : &dwarf2_per_objfile->abbrev);
4864
4865   if (dwarf_read_debug)
4866     fprintf_unfiltered (gdb_stdlog, "Reading %s for %s:\n",
4867                         get_section_name (section),
4868                         get_section_file_name (abbrev_section));
4869
4870   dwarf2_read_section (objfile, section);
4871   info_ptr = section->buffer;
4872
4873   if (info_ptr == NULL)
4874     return;
4875
4876   /* We can't set abfd until now because the section may be empty or
4877      not present, in which case the bfd is unknown.  */
4878   abfd = get_section_bfd_owner (section);
4879
4880   /* We don't use init_cutu_and_read_dies_simple, or some such, here
4881      because we don't need to read any dies: the signature is in the
4882      header.  */
4883
4884   end_ptr = info_ptr + section->size;
4885   while (info_ptr < end_ptr)
4886     {
4887       struct signatured_type *sig_type;
4888       struct dwo_unit *dwo_tu;
4889       void **slot;
4890       const gdb_byte *ptr = info_ptr;
4891       struct comp_unit_head header;
4892       unsigned int length;
4893
4894       sect_offset sect_off = (sect_offset) (ptr - section->buffer);
4895
4896       /* Initialize it due to a false compiler warning.  */
4897       header.signature = -1;
4898       header.type_cu_offset_in_tu = (cu_offset) -1;
4899
4900       /* We need to read the type's signature in order to build the hash
4901          table, but we don't need anything else just yet.  */
4902
4903       ptr = read_and_check_comp_unit_head (&header, section,
4904                                            abbrev_section, ptr, section_kind);
4905
4906       length = get_cu_length (&header);
4907
4908       /* Skip dummy type units.  */
4909       if (ptr >= info_ptr + length
4910           || peek_abbrev_code (abfd, ptr) == 0
4911           || header.unit_type != DW_UT_type)
4912         {
4913           info_ptr += length;
4914           continue;
4915         }
4916
4917       if (types_htab == NULL)
4918         {
4919           if (dwo_file)
4920             types_htab = allocate_dwo_unit_table (objfile);
4921           else
4922             types_htab = allocate_signatured_type_table (objfile);
4923         }
4924
4925       if (dwo_file)
4926         {
4927           sig_type = NULL;
4928           dwo_tu = OBSTACK_ZALLOC (&objfile->objfile_obstack,
4929                                    struct dwo_unit);
4930           dwo_tu->dwo_file = dwo_file;
4931           dwo_tu->signature = header.signature;
4932           dwo_tu->type_offset_in_tu = header.type_cu_offset_in_tu;
4933           dwo_tu->section = section;
4934           dwo_tu->sect_off = sect_off;
4935           dwo_tu->length = length;
4936         }
4937       else
4938         {
4939           /* N.B.: type_offset is not usable if this type uses a DWO file.
4940              The real type_offset is in the DWO file.  */
4941           dwo_tu = NULL;
4942           sig_type = OBSTACK_ZALLOC (&objfile->objfile_obstack,
4943                                      struct signatured_type);
4944           sig_type->signature = header.signature;
4945           sig_type->type_offset_in_tu = header.type_cu_offset_in_tu;
4946           sig_type->per_cu.objfile = objfile;
4947           sig_type->per_cu.is_debug_types = 1;
4948           sig_type->per_cu.section = section;
4949           sig_type->per_cu.sect_off = sect_off;
4950           sig_type->per_cu.length = length;
4951         }
4952
4953       slot = htab_find_slot (types_htab,
4954                              dwo_file ? (void*) dwo_tu : (void *) sig_type,
4955                              INSERT);
4956       gdb_assert (slot != NULL);
4957       if (*slot != NULL)
4958         {
4959           sect_offset dup_sect_off;
4960
4961           if (dwo_file)
4962             {
4963               const struct dwo_unit *dup_tu
4964                 = (const struct dwo_unit *) *slot;
4965
4966               dup_sect_off = dup_tu->sect_off;
4967             }
4968           else
4969             {
4970               const struct signatured_type *dup_tu
4971                 = (const struct signatured_type *) *slot;
4972
4973               dup_sect_off = dup_tu->per_cu.sect_off;
4974             }
4975
4976           complaint (&symfile_complaints,
4977                      _("debug type entry at offset 0x%x is duplicate to"
4978                        " the entry at offset 0x%x, signature %s"),
4979                      to_underlying (sect_off), to_underlying (dup_sect_off),
4980                      hex_string (header.signature));
4981         }
4982       *slot = dwo_file ? (void *) dwo_tu : (void *) sig_type;
4983
4984       if (dwarf_read_debug > 1)
4985         fprintf_unfiltered (gdb_stdlog, "  offset 0x%x, signature %s\n",
4986                             to_underlying (sect_off),
4987                             hex_string (header.signature));
4988
4989       info_ptr += length;
4990     }
4991 }
4992
4993 /* Create the hash table of all entries in the .debug_types
4994    (or .debug_types.dwo) section(s).
4995    If reading a DWO file, then DWO_FILE is a pointer to the DWO file object,
4996    otherwise it is NULL.
4997
4998    The result is a pointer to the hash table or NULL if there are no types.
4999
5000    Note: This function processes DWO files only, not DWP files.  */
5001
5002 static void
5003 create_debug_types_hash_table (struct dwo_file *dwo_file,
5004                                VEC (dwarf2_section_info_def) *types,
5005                                htab_t &types_htab)
5006 {
5007   int ix;
5008   struct dwarf2_section_info *section;
5009
5010   if (VEC_empty (dwarf2_section_info_def, types))
5011     return;
5012
5013   for (ix = 0;
5014        VEC_iterate (dwarf2_section_info_def, types, ix, section);
5015        ++ix)
5016     create_debug_type_hash_table (dwo_file, section, types_htab,
5017                                   rcuh_kind::TYPE);
5018 }
5019
5020 /* Create the hash table of all entries in the .debug_types section,
5021    and initialize all_type_units.
5022    The result is zero if there is an error (e.g. missing .debug_types section),
5023    otherwise non-zero.  */
5024
5025 static int
5026 create_all_type_units (struct objfile *objfile)
5027 {
5028   htab_t types_htab = NULL;
5029   struct signatured_type **iter;
5030
5031   create_debug_type_hash_table (NULL, &dwarf2_per_objfile->info, types_htab,
5032                                 rcuh_kind::COMPILE);
5033   create_debug_types_hash_table (NULL, dwarf2_per_objfile->types, types_htab);
5034   if (types_htab == NULL)
5035     {
5036       dwarf2_per_objfile->signatured_types = NULL;
5037       return 0;
5038     }
5039
5040   dwarf2_per_objfile->signatured_types = types_htab;
5041
5042   dwarf2_per_objfile->n_type_units
5043     = dwarf2_per_objfile->n_allocated_type_units
5044     = htab_elements (types_htab);
5045   dwarf2_per_objfile->all_type_units =
5046     XNEWVEC (struct signatured_type *, dwarf2_per_objfile->n_type_units);
5047   iter = &dwarf2_per_objfile->all_type_units[0];
5048   htab_traverse_noresize (types_htab, add_signatured_type_cu_to_table, &iter);
5049   gdb_assert (iter - &dwarf2_per_objfile->all_type_units[0]
5050               == dwarf2_per_objfile->n_type_units);
5051
5052   return 1;
5053 }
5054
5055 /* Add an entry for signature SIG to dwarf2_per_objfile->signatured_types.
5056    If SLOT is non-NULL, it is the entry to use in the hash table.
5057    Otherwise we find one.  */
5058
5059 static struct signatured_type *
5060 add_type_unit (ULONGEST sig, void **slot)
5061 {
5062   struct objfile *objfile = dwarf2_per_objfile->objfile;
5063   int n_type_units = dwarf2_per_objfile->n_type_units;
5064   struct signatured_type *sig_type;
5065
5066   gdb_assert (n_type_units <= dwarf2_per_objfile->n_allocated_type_units);
5067   ++n_type_units;
5068   if (n_type_units > dwarf2_per_objfile->n_allocated_type_units)
5069     {
5070       if (dwarf2_per_objfile->n_allocated_type_units == 0)
5071         dwarf2_per_objfile->n_allocated_type_units = 1;
5072       dwarf2_per_objfile->n_allocated_type_units *= 2;
5073       dwarf2_per_objfile->all_type_units
5074         = XRESIZEVEC (struct signatured_type *,
5075                       dwarf2_per_objfile->all_type_units,
5076                       dwarf2_per_objfile->n_allocated_type_units);
5077       ++dwarf2_per_objfile->tu_stats.nr_all_type_units_reallocs;
5078     }
5079   dwarf2_per_objfile->n_type_units = n_type_units;
5080
5081   sig_type = OBSTACK_ZALLOC (&objfile->objfile_obstack,
5082                              struct signatured_type);
5083   dwarf2_per_objfile->all_type_units[n_type_units - 1] = sig_type;
5084   sig_type->signature = sig;
5085   sig_type->per_cu.is_debug_types = 1;
5086   if (dwarf2_per_objfile->using_index)
5087     {
5088       sig_type->per_cu.v.quick =
5089         OBSTACK_ZALLOC (&objfile->objfile_obstack,
5090                         struct dwarf2_per_cu_quick_data);
5091     }
5092
5093   if (slot == NULL)
5094     {
5095       slot = htab_find_slot (dwarf2_per_objfile->signatured_types,
5096                              sig_type, INSERT);
5097     }
5098   gdb_assert (*slot == NULL);
5099   *slot = sig_type;
5100   /* The rest of sig_type must be filled in by the caller.  */
5101   return sig_type;
5102 }
5103
5104 /* Subroutine of lookup_dwo_signatured_type and lookup_dwp_signatured_type.
5105    Fill in SIG_ENTRY with DWO_ENTRY.  */
5106
5107 static void
5108 fill_in_sig_entry_from_dwo_entry (struct objfile *objfile,
5109                                   struct signatured_type *sig_entry,
5110                                   struct dwo_unit *dwo_entry)
5111 {
5112   /* Make sure we're not clobbering something we don't expect to.  */
5113   gdb_assert (! sig_entry->per_cu.queued);
5114   gdb_assert (sig_entry->per_cu.cu == NULL);
5115   if (dwarf2_per_objfile->using_index)
5116     {
5117       gdb_assert (sig_entry->per_cu.v.quick != NULL);
5118       gdb_assert (sig_entry->per_cu.v.quick->compunit_symtab == NULL);
5119     }
5120   else
5121       gdb_assert (sig_entry->per_cu.v.psymtab == NULL);
5122   gdb_assert (sig_entry->signature == dwo_entry->signature);
5123   gdb_assert (to_underlying (sig_entry->type_offset_in_section) == 0);
5124   gdb_assert (sig_entry->type_unit_group == NULL);
5125   gdb_assert (sig_entry->dwo_unit == NULL);
5126
5127   sig_entry->per_cu.section = dwo_entry->section;
5128   sig_entry->per_cu.sect_off = dwo_entry->sect_off;
5129   sig_entry->per_cu.length = dwo_entry->length;
5130   sig_entry->per_cu.reading_dwo_directly = 1;
5131   sig_entry->per_cu.objfile = objfile;
5132   sig_entry->type_offset_in_tu = dwo_entry->type_offset_in_tu;
5133   sig_entry->dwo_unit = dwo_entry;
5134 }
5135
5136 /* Subroutine of lookup_signatured_type.
5137    If we haven't read the TU yet, create the signatured_type data structure
5138    for a TU to be read in directly from a DWO file, bypassing the stub.
5139    This is the "Stay in DWO Optimization": When there is no DWP file and we're
5140    using .gdb_index, then when reading a CU we want to stay in the DWO file
5141    containing that CU.  Otherwise we could end up reading several other DWO
5142    files (due to comdat folding) to process the transitive closure of all the
5143    mentioned TUs, and that can be slow.  The current DWO file will have every
5144    type signature that it needs.
5145    We only do this for .gdb_index because in the psymtab case we already have
5146    to read all the DWOs to build the type unit groups.  */
5147
5148 static struct signatured_type *
5149 lookup_dwo_signatured_type (struct dwarf2_cu *cu, ULONGEST sig)
5150 {
5151   struct objfile *objfile = dwarf2_per_objfile->objfile;
5152   struct dwo_file *dwo_file;
5153   struct dwo_unit find_dwo_entry, *dwo_entry;
5154   struct signatured_type find_sig_entry, *sig_entry;
5155   void **slot;
5156
5157   gdb_assert (cu->dwo_unit && dwarf2_per_objfile->using_index);
5158
5159   /* If TU skeletons have been removed then we may not have read in any
5160      TUs yet.  */
5161   if (dwarf2_per_objfile->signatured_types == NULL)
5162     {
5163       dwarf2_per_objfile->signatured_types
5164         = allocate_signatured_type_table (objfile);
5165     }
5166
5167   /* We only ever need to read in one copy of a signatured type.
5168      Use the global signatured_types array to do our own comdat-folding
5169      of types.  If this is the first time we're reading this TU, and
5170      the TU has an entry in .gdb_index, replace the recorded data from
5171      .gdb_index with this TU.  */
5172
5173   find_sig_entry.signature = sig;
5174   slot = htab_find_slot (dwarf2_per_objfile->signatured_types,
5175                          &find_sig_entry, INSERT);
5176   sig_entry = (struct signatured_type *) *slot;
5177
5178   /* We can get here with the TU already read, *or* in the process of being
5179      read.  Don't reassign the global entry to point to this DWO if that's
5180      the case.  Also note that if the TU is already being read, it may not
5181      have come from a DWO, the program may be a mix of Fission-compiled
5182      code and non-Fission-compiled code.  */
5183
5184   /* Have we already tried to read this TU?
5185      Note: sig_entry can be NULL if the skeleton TU was removed (thus it
5186      needn't exist in the global table yet).  */
5187   if (sig_entry != NULL && sig_entry->per_cu.tu_read)
5188     return sig_entry;
5189
5190   /* Note: cu->dwo_unit is the dwo_unit that references this TU, not the
5191      dwo_unit of the TU itself.  */
5192   dwo_file = cu->dwo_unit->dwo_file;
5193
5194   /* Ok, this is the first time we're reading this TU.  */
5195   if (dwo_file->tus == NULL)
5196     return NULL;
5197   find_dwo_entry.signature = sig;
5198   dwo_entry = (struct dwo_unit *) htab_find (dwo_file->tus, &find_dwo_entry);
5199   if (dwo_entry == NULL)
5200     return NULL;
5201
5202   /* If the global table doesn't have an entry for this TU, add one.  */
5203   if (sig_entry == NULL)
5204     sig_entry = add_type_unit (sig, slot);
5205
5206   fill_in_sig_entry_from_dwo_entry (objfile, sig_entry, dwo_entry);
5207   sig_entry->per_cu.tu_read = 1;
5208   return sig_entry;
5209 }
5210
5211 /* Subroutine of lookup_signatured_type.
5212    Look up the type for signature SIG, and if we can't find SIG in .gdb_index
5213    then try the DWP file.  If the TU stub (skeleton) has been removed then
5214    it won't be in .gdb_index.  */
5215
5216 static struct signatured_type *
5217 lookup_dwp_signatured_type (struct dwarf2_cu *cu, ULONGEST sig)
5218 {
5219   struct objfile *objfile = dwarf2_per_objfile->objfile;
5220   struct dwp_file *dwp_file = get_dwp_file ();
5221   struct dwo_unit *dwo_entry;
5222   struct signatured_type find_sig_entry, *sig_entry;
5223   void **slot;
5224
5225   gdb_assert (cu->dwo_unit && dwarf2_per_objfile->using_index);
5226   gdb_assert (dwp_file != NULL);
5227
5228   /* If TU skeletons have been removed then we may not have read in any
5229      TUs yet.  */
5230   if (dwarf2_per_objfile->signatured_types == NULL)
5231     {
5232       dwarf2_per_objfile->signatured_types
5233         = allocate_signatured_type_table (objfile);
5234     }
5235
5236   find_sig_entry.signature = sig;
5237   slot = htab_find_slot (dwarf2_per_objfile->signatured_types,
5238                          &find_sig_entry, INSERT);
5239   sig_entry = (struct signatured_type *) *slot;
5240
5241   /* Have we already tried to read this TU?
5242      Note: sig_entry can be NULL if the skeleton TU was removed (thus it
5243      needn't exist in the global table yet).  */
5244   if (sig_entry != NULL)
5245     return sig_entry;
5246
5247   if (dwp_file->tus == NULL)
5248     return NULL;
5249   dwo_entry = lookup_dwo_unit_in_dwp (dwp_file, NULL,
5250                                       sig, 1 /* is_debug_types */);
5251   if (dwo_entry == NULL)
5252     return NULL;
5253
5254   sig_entry = add_type_unit (sig, slot);
5255   fill_in_sig_entry_from_dwo_entry (objfile, sig_entry, dwo_entry);
5256
5257   return sig_entry;
5258 }
5259
5260 /* Lookup a signature based type for DW_FORM_ref_sig8.
5261    Returns NULL if signature SIG is not present in the table.
5262    It is up to the caller to complain about this.  */
5263
5264 static struct signatured_type *
5265 lookup_signatured_type (struct dwarf2_cu *cu, ULONGEST sig)
5266 {
5267   if (cu->dwo_unit
5268       && dwarf2_per_objfile->using_index)
5269     {
5270       /* We're in a DWO/DWP file, and we're using .gdb_index.
5271          These cases require special processing.  */
5272       if (get_dwp_file () == NULL)
5273         return lookup_dwo_signatured_type (cu, sig);
5274       else
5275         return lookup_dwp_signatured_type (cu, sig);
5276     }
5277   else
5278     {
5279       struct signatured_type find_entry, *entry;
5280
5281       if (dwarf2_per_objfile->signatured_types == NULL)
5282         return NULL;
5283       find_entry.signature = sig;
5284       entry = ((struct signatured_type *)
5285                htab_find (dwarf2_per_objfile->signatured_types, &find_entry));
5286       return entry;
5287     }
5288 }
5289 \f
5290 /* Low level DIE reading support.  */
5291
5292 /* Initialize a die_reader_specs struct from a dwarf2_cu struct.  */
5293
5294 static void
5295 init_cu_die_reader (struct die_reader_specs *reader,
5296                     struct dwarf2_cu *cu,
5297                     struct dwarf2_section_info *section,
5298                     struct dwo_file *dwo_file)
5299 {
5300   gdb_assert (section->readin && section->buffer != NULL);
5301   reader->abfd = get_section_bfd_owner (section);
5302   reader->cu = cu;
5303   reader->dwo_file = dwo_file;
5304   reader->die_section = section;
5305   reader->buffer = section->buffer;
5306   reader->buffer_end = section->buffer + section->size;
5307   reader->comp_dir = NULL;
5308 }
5309
5310 /* Subroutine of init_cutu_and_read_dies to simplify it.
5311    Read in the rest of a CU/TU top level DIE from DWO_UNIT.
5312    There's just a lot of work to do, and init_cutu_and_read_dies is big enough
5313    already.
5314
5315    STUB_COMP_UNIT_DIE is for the stub DIE, we copy over certain attributes
5316    from it to the DIE in the DWO.  If NULL we are skipping the stub.
5317    STUB_COMP_DIR is similar to STUB_COMP_UNIT_DIE: When reading a TU directly
5318    from the DWO file, bypassing the stub, it contains the DW_AT_comp_dir
5319    attribute of the referencing CU.  At most one of STUB_COMP_UNIT_DIE and
5320    STUB_COMP_DIR may be non-NULL.
5321    *RESULT_READER,*RESULT_INFO_PTR,*RESULT_COMP_UNIT_DIE,*RESULT_HAS_CHILDREN
5322    are filled in with the info of the DIE from the DWO file.
5323    ABBREV_TABLE_PROVIDED is non-zero if the caller of init_cutu_and_read_dies
5324    provided an abbrev table to use.
5325    The result is non-zero if a valid (non-dummy) DIE was found.  */
5326
5327 static int
5328 read_cutu_die_from_dwo (struct dwarf2_per_cu_data *this_cu,
5329                         struct dwo_unit *dwo_unit,
5330                         int abbrev_table_provided,
5331                         struct die_info *stub_comp_unit_die,
5332                         const char *stub_comp_dir,
5333                         struct die_reader_specs *result_reader,
5334                         const gdb_byte **result_info_ptr,
5335                         struct die_info **result_comp_unit_die,
5336                         int *result_has_children)
5337 {
5338   struct objfile *objfile = dwarf2_per_objfile->objfile;
5339   struct dwarf2_cu *cu = this_cu->cu;
5340   struct dwarf2_section_info *section;
5341   bfd *abfd;
5342   const gdb_byte *begin_info_ptr, *info_ptr;
5343   ULONGEST signature; /* Or dwo_id.  */
5344   struct attribute *comp_dir, *stmt_list, *low_pc, *high_pc, *ranges;
5345   int i,num_extra_attrs;
5346   struct dwarf2_section_info *dwo_abbrev_section;
5347   struct attribute *attr;
5348   struct die_info *comp_unit_die;
5349
5350   /* At most one of these may be provided.  */
5351   gdb_assert ((stub_comp_unit_die != NULL) + (stub_comp_dir != NULL) <= 1);
5352
5353   /* These attributes aren't processed until later:
5354      DW_AT_stmt_list, DW_AT_low_pc, DW_AT_high_pc, DW_AT_ranges.
5355      DW_AT_comp_dir is used now, to find the DWO file, but it is also
5356      referenced later.  However, these attributes are found in the stub
5357      which we won't have later.  In order to not impose this complication
5358      on the rest of the code, we read them here and copy them to the
5359      DWO CU/TU die.  */
5360
5361   stmt_list = NULL;
5362   low_pc = NULL;
5363   high_pc = NULL;
5364   ranges = NULL;
5365   comp_dir = NULL;
5366
5367   if (stub_comp_unit_die != NULL)
5368     {
5369       /* For TUs in DWO files, the DW_AT_stmt_list attribute lives in the
5370          DWO file.  */
5371       if (! this_cu->is_debug_types)
5372         stmt_list = dwarf2_attr (stub_comp_unit_die, DW_AT_stmt_list, cu);
5373       low_pc = dwarf2_attr (stub_comp_unit_die, DW_AT_low_pc, cu);
5374       high_pc = dwarf2_attr (stub_comp_unit_die, DW_AT_high_pc, cu);
5375       ranges = dwarf2_attr (stub_comp_unit_die, DW_AT_ranges, cu);
5376       comp_dir = dwarf2_attr (stub_comp_unit_die, DW_AT_comp_dir, cu);
5377
5378       /* There should be a DW_AT_addr_base attribute here (if needed).
5379          We need the value before we can process DW_FORM_GNU_addr_index.  */
5380       cu->addr_base = 0;
5381       attr = dwarf2_attr (stub_comp_unit_die, DW_AT_GNU_addr_base, cu);
5382       if (attr)
5383         cu->addr_base = DW_UNSND (attr);
5384
5385       /* There should be a DW_AT_ranges_base attribute here (if needed).
5386          We need the value before we can process DW_AT_ranges.  */
5387       cu->ranges_base = 0;
5388       attr = dwarf2_attr (stub_comp_unit_die, DW_AT_GNU_ranges_base, cu);
5389       if (attr)
5390         cu->ranges_base = DW_UNSND (attr);
5391     }
5392   else if (stub_comp_dir != NULL)
5393     {
5394       /* Reconstruct the comp_dir attribute to simplify the code below.  */
5395       comp_dir = XOBNEW (&cu->comp_unit_obstack, struct attribute);
5396       comp_dir->name = DW_AT_comp_dir;
5397       comp_dir->form = DW_FORM_string;
5398       DW_STRING_IS_CANONICAL (comp_dir) = 0;
5399       DW_STRING (comp_dir) = stub_comp_dir;
5400     }
5401
5402   /* Set up for reading the DWO CU/TU.  */
5403   cu->dwo_unit = dwo_unit;
5404   section = dwo_unit->section;
5405   dwarf2_read_section (objfile, section);
5406   abfd = get_section_bfd_owner (section);
5407   begin_info_ptr = info_ptr = (section->buffer
5408                                + to_underlying (dwo_unit->sect_off));
5409   dwo_abbrev_section = &dwo_unit->dwo_file->sections.abbrev;
5410   init_cu_die_reader (result_reader, cu, section, dwo_unit->dwo_file);
5411
5412   if (this_cu->is_debug_types)
5413     {
5414       struct signatured_type *sig_type = (struct signatured_type *) this_cu;
5415
5416       info_ptr = read_and_check_comp_unit_head (&cu->header, section,
5417                                                 dwo_abbrev_section,
5418                                                 info_ptr, rcuh_kind::TYPE);
5419       /* This is not an assert because it can be caused by bad debug info.  */
5420       if (sig_type->signature != cu->header.signature)
5421         {
5422           error (_("Dwarf Error: signature mismatch %s vs %s while reading"
5423                    " TU at offset 0x%x [in module %s]"),
5424                  hex_string (sig_type->signature),
5425                  hex_string (cu->header.signature),
5426                  to_underlying (dwo_unit->sect_off),
5427                  bfd_get_filename (abfd));
5428         }
5429       gdb_assert (dwo_unit->sect_off == cu->header.sect_off);
5430       /* For DWOs coming from DWP files, we don't know the CU length
5431          nor the type's offset in the TU until now.  */
5432       dwo_unit->length = get_cu_length (&cu->header);
5433       dwo_unit->type_offset_in_tu = cu->header.type_cu_offset_in_tu;
5434
5435       /* Establish the type offset that can be used to lookup the type.
5436          For DWO files, we don't know it until now.  */
5437       sig_type->type_offset_in_section
5438         = dwo_unit->sect_off + to_underlying (dwo_unit->type_offset_in_tu);
5439     }
5440   else
5441     {
5442       info_ptr = read_and_check_comp_unit_head (&cu->header, section,
5443                                                 dwo_abbrev_section,
5444                                                 info_ptr, rcuh_kind::COMPILE);
5445       gdb_assert (dwo_unit->sect_off == cu->header.sect_off);
5446       /* For DWOs coming from DWP files, we don't know the CU length
5447          until now.  */
5448       dwo_unit->length = get_cu_length (&cu->header);
5449     }
5450
5451   /* Replace the CU's original abbrev table with the DWO's.
5452      Reminder: We can't read the abbrev table until we've read the header.  */
5453   if (abbrev_table_provided)
5454     {
5455       /* Don't free the provided abbrev table, the caller of
5456          init_cutu_and_read_dies owns it.  */
5457       dwarf2_read_abbrevs (cu, dwo_abbrev_section);
5458       /* Ensure the DWO abbrev table gets freed.  */
5459       make_cleanup (dwarf2_free_abbrev_table, cu);
5460     }
5461   else
5462     {
5463       dwarf2_free_abbrev_table (cu);
5464       dwarf2_read_abbrevs (cu, dwo_abbrev_section);
5465       /* Leave any existing abbrev table cleanup as is.  */
5466     }
5467
5468   /* Read in the die, but leave space to copy over the attributes
5469      from the stub.  This has the benefit of simplifying the rest of
5470      the code - all the work to maintain the illusion of a single
5471      DW_TAG_{compile,type}_unit DIE is done here.  */
5472   num_extra_attrs = ((stmt_list != NULL)
5473                      + (low_pc != NULL)
5474                      + (high_pc != NULL)
5475                      + (ranges != NULL)
5476                      + (comp_dir != NULL));
5477   info_ptr = read_full_die_1 (result_reader, result_comp_unit_die, info_ptr,
5478                               result_has_children, num_extra_attrs);
5479
5480   /* Copy over the attributes from the stub to the DIE we just read in.  */
5481   comp_unit_die = *result_comp_unit_die;
5482   i = comp_unit_die->num_attrs;
5483   if (stmt_list != NULL)
5484     comp_unit_die->attrs[i++] = *stmt_list;
5485   if (low_pc != NULL)
5486     comp_unit_die->attrs[i++] = *low_pc;
5487   if (high_pc != NULL)
5488     comp_unit_die->attrs[i++] = *high_pc;
5489   if (ranges != NULL)
5490     comp_unit_die->attrs[i++] = *ranges;
5491   if (comp_dir != NULL)
5492     comp_unit_die->attrs[i++] = *comp_dir;
5493   comp_unit_die->num_attrs += num_extra_attrs;
5494
5495   if (dwarf_die_debug)
5496     {
5497       fprintf_unfiltered (gdb_stdlog,
5498                           "Read die from %s@0x%x of %s:\n",
5499                           get_section_name (section),
5500                           (unsigned) (begin_info_ptr - section->buffer),
5501                           bfd_get_filename (abfd));
5502       dump_die (comp_unit_die, dwarf_die_debug);
5503     }
5504
5505   /* Save the comp_dir attribute.  If there is no DWP file then we'll read
5506      TUs by skipping the stub and going directly to the entry in the DWO file.
5507      However, skipping the stub means we won't get DW_AT_comp_dir, so we have
5508      to get it via circuitous means.  Blech.  */
5509   if (comp_dir != NULL)
5510     result_reader->comp_dir = DW_STRING (comp_dir);
5511
5512   /* Skip dummy compilation units.  */
5513   if (info_ptr >= begin_info_ptr + dwo_unit->length
5514       || peek_abbrev_code (abfd, info_ptr) == 0)
5515     return 0;
5516
5517   *result_info_ptr = info_ptr;
5518   return 1;
5519 }
5520
5521 /* Subroutine of init_cutu_and_read_dies to simplify it.
5522    Look up the DWO unit specified by COMP_UNIT_DIE of THIS_CU.
5523    Returns NULL if the specified DWO unit cannot be found.  */
5524
5525 static struct dwo_unit *
5526 lookup_dwo_unit (struct dwarf2_per_cu_data *this_cu,
5527                  struct die_info *comp_unit_die)
5528 {
5529   struct dwarf2_cu *cu = this_cu->cu;
5530   struct attribute *attr;
5531   ULONGEST signature;
5532   struct dwo_unit *dwo_unit;
5533   const char *comp_dir, *dwo_name;
5534
5535   gdb_assert (cu != NULL);
5536
5537   /* Yeah, we look dwo_name up again, but it simplifies the code.  */
5538   dwo_name = dwarf2_string_attr (comp_unit_die, DW_AT_GNU_dwo_name, cu);
5539   comp_dir = dwarf2_string_attr (comp_unit_die, DW_AT_comp_dir, cu);
5540
5541   if (this_cu->is_debug_types)
5542     {
5543       struct signatured_type *sig_type;
5544
5545       /* Since this_cu is the first member of struct signatured_type,
5546          we can go from a pointer to one to a pointer to the other.  */
5547       sig_type = (struct signatured_type *) this_cu;
5548       signature = sig_type->signature;
5549       dwo_unit = lookup_dwo_type_unit (sig_type, dwo_name, comp_dir);
5550     }
5551   else
5552     {
5553       struct attribute *attr;
5554
5555       attr = dwarf2_attr (comp_unit_die, DW_AT_GNU_dwo_id, cu);
5556       if (! attr)
5557         error (_("Dwarf Error: missing dwo_id for dwo_name %s"
5558                  " [in module %s]"),
5559                dwo_name, objfile_name (this_cu->objfile));
5560       signature = DW_UNSND (attr);
5561       dwo_unit = lookup_dwo_comp_unit (this_cu, dwo_name, comp_dir,
5562                                        signature);
5563     }
5564
5565   return dwo_unit;
5566 }
5567
5568 /* Subroutine of init_cutu_and_read_dies to simplify it.
5569    See it for a description of the parameters.
5570    Read a TU directly from a DWO file, bypassing the stub.
5571
5572    Note: This function could be a little bit simpler if we shared cleanups
5573    with our caller, init_cutu_and_read_dies.  That's generally a fragile thing
5574    to do, so we keep this function self-contained.  Or we could move this
5575    into our caller, but it's complex enough already.  */
5576
5577 static void
5578 init_tu_and_read_dwo_dies (struct dwarf2_per_cu_data *this_cu,
5579                            int use_existing_cu, int keep,
5580                            die_reader_func_ftype *die_reader_func,
5581                            void *data)
5582 {
5583   struct dwarf2_cu *cu;
5584   struct signatured_type *sig_type;
5585   struct cleanup *cleanups, *free_cu_cleanup = NULL;
5586   struct die_reader_specs reader;
5587   const gdb_byte *info_ptr;
5588   struct die_info *comp_unit_die;
5589   int has_children;
5590
5591   /* Verify we can do the following downcast, and that we have the
5592      data we need.  */
5593   gdb_assert (this_cu->is_debug_types && this_cu->reading_dwo_directly);
5594   sig_type = (struct signatured_type *) this_cu;
5595   gdb_assert (sig_type->dwo_unit != NULL);
5596
5597   cleanups = make_cleanup (null_cleanup, NULL);
5598
5599   if (use_existing_cu && this_cu->cu != NULL)
5600     {
5601       gdb_assert (this_cu->cu->dwo_unit == sig_type->dwo_unit);
5602       cu = this_cu->cu;
5603       /* There's no need to do the rereading_dwo_cu handling that
5604          init_cutu_and_read_dies does since we don't read the stub.  */
5605     }
5606   else
5607     {
5608       /* If !use_existing_cu, this_cu->cu must be NULL.  */
5609       gdb_assert (this_cu->cu == NULL);
5610       cu = XNEW (struct dwarf2_cu);
5611       init_one_comp_unit (cu, this_cu);
5612       /* If an error occurs while loading, release our storage.  */
5613       free_cu_cleanup = make_cleanup (free_heap_comp_unit, cu);
5614     }
5615
5616   /* A future optimization, if needed, would be to use an existing
5617      abbrev table.  When reading DWOs with skeletonless TUs, all the TUs
5618      could share abbrev tables.  */
5619
5620   if (read_cutu_die_from_dwo (this_cu, sig_type->dwo_unit,
5621                               0 /* abbrev_table_provided */,
5622                               NULL /* stub_comp_unit_die */,
5623                               sig_type->dwo_unit->dwo_file->comp_dir,
5624                               &reader, &info_ptr,
5625                               &comp_unit_die, &has_children) == 0)
5626     {
5627       /* Dummy die.  */
5628       do_cleanups (cleanups);
5629       return;
5630     }
5631
5632   /* All the "real" work is done here.  */
5633   die_reader_func (&reader, info_ptr, comp_unit_die, has_children, data);
5634
5635   /* This duplicates the code in init_cutu_and_read_dies,
5636      but the alternative is making the latter more complex.
5637      This function is only for the special case of using DWO files directly:
5638      no point in overly complicating the general case just to handle this.  */
5639   if (free_cu_cleanup != NULL)
5640     {
5641       if (keep)
5642         {
5643           /* We've successfully allocated this compilation unit.  Let our
5644              caller clean it up when finished with it.  */
5645           discard_cleanups (free_cu_cleanup);
5646
5647           /* We can only discard free_cu_cleanup and all subsequent cleanups.
5648              So we have to manually free the abbrev table.  */
5649           dwarf2_free_abbrev_table (cu);
5650
5651           /* Link this CU into read_in_chain.  */
5652           this_cu->cu->read_in_chain = dwarf2_per_objfile->read_in_chain;
5653           dwarf2_per_objfile->read_in_chain = this_cu;
5654         }
5655       else
5656         do_cleanups (free_cu_cleanup);
5657     }
5658
5659   do_cleanups (cleanups);
5660 }
5661
5662 /* Initialize a CU (or TU) and read its DIEs.
5663    If the CU defers to a DWO file, read the DWO file as well.
5664
5665    ABBREV_TABLE, if non-NULL, is the abbreviation table to use.
5666    Otherwise the table specified in the comp unit header is read in and used.
5667    This is an optimization for when we already have the abbrev table.
5668
5669    If USE_EXISTING_CU is non-zero, and THIS_CU->cu is non-NULL, then use it.
5670    Otherwise, a new CU is allocated with xmalloc.
5671
5672    If KEEP is non-zero, then if we allocated a dwarf2_cu we add it to
5673    read_in_chain.  Otherwise the dwarf2_cu data is freed at the end.
5674
5675    WARNING: If THIS_CU is a "dummy CU" (used as filler by the incremental
5676    linker) then DIE_READER_FUNC will not get called.  */
5677
5678 static void
5679 init_cutu_and_read_dies (struct dwarf2_per_cu_data *this_cu,
5680                          struct abbrev_table *abbrev_table,
5681                          int use_existing_cu, int keep,
5682                          die_reader_func_ftype *die_reader_func,
5683                          void *data)
5684 {
5685   struct objfile *objfile = dwarf2_per_objfile->objfile;
5686   struct dwarf2_section_info *section = this_cu->section;
5687   bfd *abfd = get_section_bfd_owner (section);
5688   struct dwarf2_cu *cu;
5689   const gdb_byte *begin_info_ptr, *info_ptr;
5690   struct die_reader_specs reader;
5691   struct die_info *comp_unit_die;
5692   int has_children;
5693   struct attribute *attr;
5694   struct cleanup *cleanups, *free_cu_cleanup = NULL;
5695   struct signatured_type *sig_type = NULL;
5696   struct dwarf2_section_info *abbrev_section;
5697   /* Non-zero if CU currently points to a DWO file and we need to
5698      reread it.  When this happens we need to reread the skeleton die
5699      before we can reread the DWO file (this only applies to CUs, not TUs).  */
5700   int rereading_dwo_cu = 0;
5701
5702   if (dwarf_die_debug)
5703     fprintf_unfiltered (gdb_stdlog, "Reading %s unit at offset 0x%x\n",
5704                         this_cu->is_debug_types ? "type" : "comp",
5705                         to_underlying (this_cu->sect_off));
5706
5707   if (use_existing_cu)
5708     gdb_assert (keep);
5709
5710   /* If we're reading a TU directly from a DWO file, including a virtual DWO
5711      file (instead of going through the stub), short-circuit all of this.  */
5712   if (this_cu->reading_dwo_directly)
5713     {
5714       /* Narrow down the scope of possibilities to have to understand.  */
5715       gdb_assert (this_cu->is_debug_types);
5716       gdb_assert (abbrev_table == NULL);
5717       init_tu_and_read_dwo_dies (this_cu, use_existing_cu, keep,
5718                                  die_reader_func, data);
5719       return;
5720     }
5721
5722   cleanups = make_cleanup (null_cleanup, NULL);
5723
5724   /* This is cheap if the section is already read in.  */
5725   dwarf2_read_section (objfile, section);
5726
5727   begin_info_ptr = info_ptr = section->buffer + to_underlying (this_cu->sect_off);
5728
5729   abbrev_section = get_abbrev_section_for_cu (this_cu);
5730
5731   if (use_existing_cu && this_cu->cu != NULL)
5732     {
5733       cu = this_cu->cu;
5734       /* If this CU is from a DWO file we need to start over, we need to
5735          refetch the attributes from the skeleton CU.
5736          This could be optimized by retrieving those attributes from when we
5737          were here the first time: the previous comp_unit_die was stored in
5738          comp_unit_obstack.  But there's no data yet that we need this
5739          optimization.  */
5740       if (cu->dwo_unit != NULL)
5741         rereading_dwo_cu = 1;
5742     }
5743   else
5744     {
5745       /* If !use_existing_cu, this_cu->cu must be NULL.  */
5746       gdb_assert (this_cu->cu == NULL);
5747       cu = XNEW (struct dwarf2_cu);
5748       init_one_comp_unit (cu, this_cu);
5749       /* If an error occurs while loading, release our storage.  */
5750       free_cu_cleanup = make_cleanup (free_heap_comp_unit, cu);
5751     }
5752
5753   /* Get the header.  */
5754   if (to_underlying (cu->header.first_die_cu_offset) != 0 && !rereading_dwo_cu)
5755     {
5756       /* We already have the header, there's no need to read it in again.  */
5757       info_ptr += to_underlying (cu->header.first_die_cu_offset);
5758     }
5759   else
5760     {
5761       if (this_cu->is_debug_types)
5762         {
5763           info_ptr = read_and_check_comp_unit_head (&cu->header, section,
5764                                                     abbrev_section, info_ptr,
5765                                                     rcuh_kind::TYPE);
5766
5767           /* Since per_cu is the first member of struct signatured_type,
5768              we can go from a pointer to one to a pointer to the other.  */
5769           sig_type = (struct signatured_type *) this_cu;
5770           gdb_assert (sig_type->signature == cu->header.signature);
5771           gdb_assert (sig_type->type_offset_in_tu
5772                       == cu->header.type_cu_offset_in_tu);
5773           gdb_assert (this_cu->sect_off == cu->header.sect_off);
5774
5775           /* LENGTH has not been set yet for type units if we're
5776              using .gdb_index.  */
5777           this_cu->length = get_cu_length (&cu->header);
5778
5779           /* Establish the type offset that can be used to lookup the type.  */
5780           sig_type->type_offset_in_section =
5781             this_cu->sect_off + to_underlying (sig_type->type_offset_in_tu);
5782
5783           this_cu->dwarf_version = cu->header.version;
5784         }
5785       else
5786         {
5787           info_ptr = read_and_check_comp_unit_head (&cu->header, section,
5788                                                     abbrev_section,
5789                                                     info_ptr,
5790                                                     rcuh_kind::COMPILE);
5791
5792           gdb_assert (this_cu->sect_off == cu->header.sect_off);
5793           gdb_assert (this_cu->length == get_cu_length (&cu->header));
5794           this_cu->dwarf_version = cu->header.version;
5795         }
5796     }
5797
5798   /* Skip dummy compilation units.  */
5799   if (info_ptr >= begin_info_ptr + this_cu->length
5800       || peek_abbrev_code (abfd, info_ptr) == 0)
5801     {
5802       do_cleanups (cleanups);
5803       return;
5804     }
5805
5806   /* If we don't have them yet, read the abbrevs for this compilation unit.
5807      And if we need to read them now, make sure they're freed when we're
5808      done.  Note that it's important that if the CU had an abbrev table
5809      on entry we don't free it when we're done: Somewhere up the call stack
5810      it may be in use.  */
5811   if (abbrev_table != NULL)
5812     {
5813       gdb_assert (cu->abbrev_table == NULL);
5814       gdb_assert (cu->header.abbrev_sect_off == abbrev_table->sect_off);
5815       cu->abbrev_table = abbrev_table;
5816     }
5817   else if (cu->abbrev_table == NULL)
5818     {
5819       dwarf2_read_abbrevs (cu, abbrev_section);
5820       make_cleanup (dwarf2_free_abbrev_table, cu);
5821     }
5822   else if (rereading_dwo_cu)
5823     {
5824       dwarf2_free_abbrev_table (cu);
5825       dwarf2_read_abbrevs (cu, abbrev_section);
5826     }
5827
5828   /* Read the top level CU/TU die.  */
5829   init_cu_die_reader (&reader, cu, section, NULL);
5830   info_ptr = read_full_die (&reader, &comp_unit_die, info_ptr, &has_children);
5831
5832   /* If we are in a DWO stub, process it and then read in the "real" CU/TU
5833      from the DWO file.
5834      Note that if USE_EXISTING_OK != 0, and THIS_CU->cu already contains a
5835      DWO CU, that this test will fail (the attribute will not be present).  */
5836   attr = dwarf2_attr (comp_unit_die, DW_AT_GNU_dwo_name, cu);
5837   if (attr)
5838     {
5839       struct dwo_unit *dwo_unit;
5840       struct die_info *dwo_comp_unit_die;
5841
5842       if (has_children)
5843         {
5844           complaint (&symfile_complaints,
5845                      _("compilation unit with DW_AT_GNU_dwo_name"
5846                        " has children (offset 0x%x) [in module %s]"),
5847                      to_underlying (this_cu->sect_off), bfd_get_filename (abfd));
5848         }
5849       dwo_unit = lookup_dwo_unit (this_cu, comp_unit_die);
5850       if (dwo_unit != NULL)
5851         {
5852           if (read_cutu_die_from_dwo (this_cu, dwo_unit,
5853                                       abbrev_table != NULL,
5854                                       comp_unit_die, NULL,
5855                                       &reader, &info_ptr,
5856                                       &dwo_comp_unit_die, &has_children) == 0)
5857             {
5858               /* Dummy die.  */
5859               do_cleanups (cleanups);
5860               return;
5861             }
5862           comp_unit_die = dwo_comp_unit_die;
5863         }
5864       else
5865         {
5866           /* Yikes, we couldn't find the rest of the DIE, we only have
5867              the stub.  A complaint has already been logged.  There's
5868              not much more we can do except pass on the stub DIE to
5869              die_reader_func.  We don't want to throw an error on bad
5870              debug info.  */
5871         }
5872     }
5873
5874   /* All of the above is setup for this call.  Yikes.  */
5875   die_reader_func (&reader, info_ptr, comp_unit_die, has_children, data);
5876
5877   /* Done, clean up.  */
5878   if (free_cu_cleanup != NULL)
5879     {
5880       if (keep)
5881         {
5882           /* We've successfully allocated this compilation unit.  Let our
5883              caller clean it up when finished with it.  */
5884           discard_cleanups (free_cu_cleanup);
5885
5886           /* We can only discard free_cu_cleanup and all subsequent cleanups.
5887              So we have to manually free the abbrev table.  */
5888           dwarf2_free_abbrev_table (cu);
5889
5890           /* Link this CU into read_in_chain.  */
5891           this_cu->cu->read_in_chain = dwarf2_per_objfile->read_in_chain;
5892           dwarf2_per_objfile->read_in_chain = this_cu;
5893         }
5894       else
5895         do_cleanups (free_cu_cleanup);
5896     }
5897
5898   do_cleanups (cleanups);
5899 }
5900
5901 /* Read CU/TU THIS_CU but do not follow DW_AT_GNU_dwo_name if present.
5902    DWO_FILE, if non-NULL, is the DWO file to read (the caller is assumed
5903    to have already done the lookup to find the DWO file).
5904
5905    The caller is required to fill in THIS_CU->section, THIS_CU->offset, and
5906    THIS_CU->is_debug_types, but nothing else.
5907
5908    We fill in THIS_CU->length.
5909
5910    WARNING: If THIS_CU is a "dummy CU" (used as filler by the incremental
5911    linker) then DIE_READER_FUNC will not get called.
5912
5913    THIS_CU->cu is always freed when done.
5914    This is done in order to not leave THIS_CU->cu in a state where we have
5915    to care whether it refers to the "main" CU or the DWO CU.  */
5916
5917 static void
5918 init_cutu_and_read_dies_no_follow (struct dwarf2_per_cu_data *this_cu,
5919                                    struct dwo_file *dwo_file,
5920                                    die_reader_func_ftype *die_reader_func,
5921                                    void *data)
5922 {
5923   struct objfile *objfile = dwarf2_per_objfile->objfile;
5924   struct dwarf2_section_info *section = this_cu->section;
5925   bfd *abfd = get_section_bfd_owner (section);
5926   struct dwarf2_section_info *abbrev_section;
5927   struct dwarf2_cu cu;
5928   const gdb_byte *begin_info_ptr, *info_ptr;
5929   struct die_reader_specs reader;
5930   struct cleanup *cleanups;
5931   struct die_info *comp_unit_die;
5932   int has_children;
5933
5934   if (dwarf_die_debug)
5935     fprintf_unfiltered (gdb_stdlog, "Reading %s unit at offset 0x%x\n",
5936                         this_cu->is_debug_types ? "type" : "comp",
5937                         to_underlying (this_cu->sect_off));
5938
5939   gdb_assert (this_cu->cu == NULL);
5940
5941   abbrev_section = (dwo_file != NULL
5942                     ? &dwo_file->sections.abbrev
5943                     : get_abbrev_section_for_cu (this_cu));
5944
5945   /* This is cheap if the section is already read in.  */
5946   dwarf2_read_section (objfile, section);
5947
5948   init_one_comp_unit (&cu, this_cu);
5949
5950   cleanups = make_cleanup (free_stack_comp_unit, &cu);
5951
5952   begin_info_ptr = info_ptr = section->buffer + to_underlying (this_cu->sect_off);
5953   info_ptr = read_and_check_comp_unit_head (&cu.header, section,
5954                                             abbrev_section, info_ptr,
5955                                             (this_cu->is_debug_types
5956                                              ? rcuh_kind::TYPE
5957                                              : rcuh_kind::COMPILE));
5958
5959   this_cu->length = get_cu_length (&cu.header);
5960
5961   /* Skip dummy compilation units.  */
5962   if (info_ptr >= begin_info_ptr + this_cu->length
5963       || peek_abbrev_code (abfd, info_ptr) == 0)
5964     {
5965       do_cleanups (cleanups);
5966       return;
5967     }
5968
5969   dwarf2_read_abbrevs (&cu, abbrev_section);
5970   make_cleanup (dwarf2_free_abbrev_table, &cu);
5971
5972   init_cu_die_reader (&reader, &cu, section, dwo_file);
5973   info_ptr = read_full_die (&reader, &comp_unit_die, info_ptr, &has_children);
5974
5975   die_reader_func (&reader, info_ptr, comp_unit_die, has_children, data);
5976
5977   do_cleanups (cleanups);
5978 }
5979
5980 /* Read a CU/TU, except that this does not look for DW_AT_GNU_dwo_name and
5981    does not lookup the specified DWO file.
5982    This cannot be used to read DWO files.
5983
5984    THIS_CU->cu is always freed when done.
5985    This is done in order to not leave THIS_CU->cu in a state where we have
5986    to care whether it refers to the "main" CU or the DWO CU.
5987    We can revisit this if the data shows there's a performance issue.  */
5988
5989 static void
5990 init_cutu_and_read_dies_simple (struct dwarf2_per_cu_data *this_cu,
5991                                 die_reader_func_ftype *die_reader_func,
5992                                 void *data)
5993 {
5994   init_cutu_and_read_dies_no_follow (this_cu, NULL, die_reader_func, data);
5995 }
5996 \f
5997 /* Type Unit Groups.
5998
5999    Type Unit Groups are a way to collapse the set of all TUs (type units) into
6000    a more manageable set.  The grouping is done by DW_AT_stmt_list entry
6001    so that all types coming from the same compilation (.o file) are grouped
6002    together.  A future step could be to put the types in the same symtab as
6003    the CU the types ultimately came from.  */
6004
6005 static hashval_t
6006 hash_type_unit_group (const void *item)
6007 {
6008   const struct type_unit_group *tu_group
6009     = (const struct type_unit_group *) item;
6010
6011   return hash_stmt_list_entry (&tu_group->hash);
6012 }
6013
6014 static int
6015 eq_type_unit_group (const void *item_lhs, const void *item_rhs)
6016 {
6017   const struct type_unit_group *lhs = (const struct type_unit_group *) item_lhs;
6018   const struct type_unit_group *rhs = (const struct type_unit_group *) item_rhs;
6019
6020   return eq_stmt_list_entry (&lhs->hash, &rhs->hash);
6021 }
6022
6023 /* Allocate a hash table for type unit groups.  */
6024
6025 static htab_t
6026 allocate_type_unit_groups_table (void)
6027 {
6028   return htab_create_alloc_ex (3,
6029                                hash_type_unit_group,
6030                                eq_type_unit_group,
6031                                NULL,
6032                                &dwarf2_per_objfile->objfile->objfile_obstack,
6033                                hashtab_obstack_allocate,
6034                                dummy_obstack_deallocate);
6035 }
6036
6037 /* Type units that don't have DW_AT_stmt_list are grouped into their own
6038    partial symtabs.  We combine several TUs per psymtab to not let the size
6039    of any one psymtab grow too big.  */
6040 #define NO_STMT_LIST_TYPE_UNIT_PSYMTAB (1 << 31)
6041 #define NO_STMT_LIST_TYPE_UNIT_PSYMTAB_SIZE 10
6042
6043 /* Helper routine for get_type_unit_group.
6044    Create the type_unit_group object used to hold one or more TUs.  */
6045
6046 static struct type_unit_group *
6047 create_type_unit_group (struct dwarf2_cu *cu, sect_offset line_offset_struct)
6048 {
6049   struct objfile *objfile = dwarf2_per_objfile->objfile;
6050   struct dwarf2_per_cu_data *per_cu;
6051   struct type_unit_group *tu_group;
6052
6053   tu_group = OBSTACK_ZALLOC (&objfile->objfile_obstack,
6054                              struct type_unit_group);
6055   per_cu = &tu_group->per_cu;
6056   per_cu->objfile = objfile;
6057
6058   if (dwarf2_per_objfile->using_index)
6059     {
6060       per_cu->v.quick = OBSTACK_ZALLOC (&objfile->objfile_obstack,
6061                                         struct dwarf2_per_cu_quick_data);
6062     }
6063   else
6064     {
6065       unsigned int line_offset = to_underlying (line_offset_struct);
6066       struct partial_symtab *pst;
6067       char *name;
6068
6069       /* Give the symtab a useful name for debug purposes.  */
6070       if ((line_offset & NO_STMT_LIST_TYPE_UNIT_PSYMTAB) != 0)
6071         name = xstrprintf ("<type_units_%d>",
6072                            (line_offset & ~NO_STMT_LIST_TYPE_UNIT_PSYMTAB));
6073       else
6074         name = xstrprintf ("<type_units_at_0x%x>", line_offset);
6075
6076       pst = create_partial_symtab (per_cu, name);
6077       pst->anonymous = 1;
6078
6079       xfree (name);
6080     }
6081
6082   tu_group->hash.dwo_unit = cu->dwo_unit;
6083   tu_group->hash.line_sect_off = line_offset_struct;
6084
6085   return tu_group;
6086 }
6087
6088 /* Look up the type_unit_group for type unit CU, and create it if necessary.
6089    STMT_LIST is a DW_AT_stmt_list attribute.  */
6090
6091 static struct type_unit_group *
6092 get_type_unit_group (struct dwarf2_cu *cu, const struct attribute *stmt_list)
6093 {
6094   struct tu_stats *tu_stats = &dwarf2_per_objfile->tu_stats;
6095   struct type_unit_group *tu_group;
6096   void **slot;
6097   unsigned int line_offset;
6098   struct type_unit_group type_unit_group_for_lookup;
6099
6100   if (dwarf2_per_objfile->type_unit_groups == NULL)
6101     {
6102       dwarf2_per_objfile->type_unit_groups =
6103         allocate_type_unit_groups_table ();
6104     }
6105
6106   /* Do we need to create a new group, or can we use an existing one?  */
6107
6108   if (stmt_list)
6109     {
6110       line_offset = DW_UNSND (stmt_list);
6111       ++tu_stats->nr_symtab_sharers;
6112     }
6113   else
6114     {
6115       /* Ugh, no stmt_list.  Rare, but we have to handle it.
6116          We can do various things here like create one group per TU or
6117          spread them over multiple groups to split up the expansion work.
6118          To avoid worst case scenarios (too many groups or too large groups)
6119          we, umm, group them in bunches.  */
6120       line_offset = (NO_STMT_LIST_TYPE_UNIT_PSYMTAB
6121                      | (tu_stats->nr_stmt_less_type_units
6122                         / NO_STMT_LIST_TYPE_UNIT_PSYMTAB_SIZE));
6123       ++tu_stats->nr_stmt_less_type_units;
6124     }
6125
6126   type_unit_group_for_lookup.hash.dwo_unit = cu->dwo_unit;
6127   type_unit_group_for_lookup.hash.line_sect_off = (sect_offset) line_offset;
6128   slot = htab_find_slot (dwarf2_per_objfile->type_unit_groups,
6129                          &type_unit_group_for_lookup, INSERT);
6130   if (*slot != NULL)
6131     {
6132       tu_group = (struct type_unit_group *) *slot;
6133       gdb_assert (tu_group != NULL);
6134     }
6135   else
6136     {
6137       sect_offset line_offset_struct = (sect_offset) line_offset;
6138       tu_group = create_type_unit_group (cu, line_offset_struct);
6139       *slot = tu_group;
6140       ++tu_stats->nr_symtabs;
6141     }
6142
6143   return tu_group;
6144 }
6145 \f
6146 /* Partial symbol tables.  */
6147
6148 /* Create a psymtab named NAME and assign it to PER_CU.
6149
6150    The caller must fill in the following details:
6151    dirname, textlow, texthigh.  */
6152
6153 static struct partial_symtab *
6154 create_partial_symtab (struct dwarf2_per_cu_data *per_cu, const char *name)
6155 {
6156   struct objfile *objfile = per_cu->objfile;
6157   struct partial_symtab *pst;
6158
6159   pst = start_psymtab_common (objfile, name, 0,
6160                               objfile->global_psymbols.next,
6161                               objfile->static_psymbols.next);
6162
6163   pst->psymtabs_addrmap_supported = 1;
6164
6165   /* This is the glue that links PST into GDB's symbol API.  */
6166   pst->read_symtab_private = per_cu;
6167   pst->read_symtab = dwarf2_read_symtab;
6168   per_cu->v.psymtab = pst;
6169
6170   return pst;
6171 }
6172
6173 /* The DATA object passed to process_psymtab_comp_unit_reader has this
6174    type.  */
6175
6176 struct process_psymtab_comp_unit_data
6177 {
6178   /* True if we are reading a DW_TAG_partial_unit.  */
6179
6180   int want_partial_unit;
6181
6182   /* The "pretend" language that is used if the CU doesn't declare a
6183      language.  */
6184
6185   enum language pretend_language;
6186 };
6187
6188 /* die_reader_func for process_psymtab_comp_unit.  */
6189
6190 static void
6191 process_psymtab_comp_unit_reader (const struct die_reader_specs *reader,
6192                                   const gdb_byte *info_ptr,
6193                                   struct die_info *comp_unit_die,
6194                                   int has_children,
6195                                   void *data)
6196 {
6197   struct dwarf2_cu *cu = reader->cu;
6198   struct objfile *objfile = cu->objfile;
6199   struct gdbarch *gdbarch = get_objfile_arch (objfile);
6200   struct dwarf2_per_cu_data *per_cu = cu->per_cu;
6201   CORE_ADDR baseaddr;
6202   CORE_ADDR best_lowpc = 0, best_highpc = 0;
6203   struct partial_symtab *pst;
6204   enum pc_bounds_kind cu_bounds_kind;
6205   const char *filename;
6206   struct process_psymtab_comp_unit_data *info
6207     = (struct process_psymtab_comp_unit_data *) data;
6208
6209   if (comp_unit_die->tag == DW_TAG_partial_unit && !info->want_partial_unit)
6210     return;
6211
6212   gdb_assert (! per_cu->is_debug_types);
6213
6214   prepare_one_comp_unit (cu, comp_unit_die, info->pretend_language);
6215
6216   cu->list_in_scope = &file_symbols;
6217
6218   /* Allocate a new partial symbol table structure.  */
6219   filename = dwarf2_string_attr (comp_unit_die, DW_AT_name, cu);
6220   if (filename == NULL)
6221     filename = "";
6222
6223   pst = create_partial_symtab (per_cu, filename);
6224
6225   /* This must be done before calling dwarf2_build_include_psymtabs.  */
6226   pst->dirname = dwarf2_string_attr (comp_unit_die, DW_AT_comp_dir, cu);
6227
6228   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
6229
6230   dwarf2_find_base_address (comp_unit_die, cu);
6231
6232   /* Possibly set the default values of LOWPC and HIGHPC from
6233      `DW_AT_ranges'.  */
6234   cu_bounds_kind = dwarf2_get_pc_bounds (comp_unit_die, &best_lowpc,
6235                                          &best_highpc, cu, pst);
6236   if (cu_bounds_kind == PC_BOUNDS_HIGH_LOW && best_lowpc < best_highpc)
6237     /* Store the contiguous range if it is not empty; it can be empty for
6238        CUs with no code.  */
6239     addrmap_set_empty (objfile->psymtabs_addrmap,
6240                        gdbarch_adjust_dwarf2_addr (gdbarch,
6241                                                    best_lowpc + baseaddr),
6242                        gdbarch_adjust_dwarf2_addr (gdbarch,
6243                                                    best_highpc + baseaddr) - 1,
6244                        pst);
6245
6246   /* Check if comp unit has_children.
6247      If so, read the rest of the partial symbols from this comp unit.
6248      If not, there's no more debug_info for this comp unit.  */
6249   if (has_children)
6250     {
6251       struct partial_die_info *first_die;
6252       CORE_ADDR lowpc, highpc;
6253
6254       lowpc = ((CORE_ADDR) -1);
6255       highpc = ((CORE_ADDR) 0);
6256
6257       first_die = load_partial_dies (reader, info_ptr, 1);
6258
6259       scan_partial_symbols (first_die, &lowpc, &highpc,
6260                             cu_bounds_kind <= PC_BOUNDS_INVALID, cu);
6261
6262       /* If we didn't find a lowpc, set it to highpc to avoid
6263          complaints from `maint check'.  */
6264       if (lowpc == ((CORE_ADDR) -1))
6265         lowpc = highpc;
6266
6267       /* If the compilation unit didn't have an explicit address range,
6268          then use the information extracted from its child dies.  */
6269       if (cu_bounds_kind <= PC_BOUNDS_INVALID)
6270         {
6271           best_lowpc = lowpc;
6272           best_highpc = highpc;
6273         }
6274     }
6275   pst->textlow = gdbarch_adjust_dwarf2_addr (gdbarch, best_lowpc + baseaddr);
6276   pst->texthigh = gdbarch_adjust_dwarf2_addr (gdbarch, best_highpc + baseaddr);
6277
6278   end_psymtab_common (objfile, pst);
6279
6280   if (!VEC_empty (dwarf2_per_cu_ptr, cu->per_cu->imported_symtabs))
6281     {
6282       int i;
6283       int len = VEC_length (dwarf2_per_cu_ptr, cu->per_cu->imported_symtabs);
6284       struct dwarf2_per_cu_data *iter;
6285
6286       /* Fill in 'dependencies' here; we fill in 'users' in a
6287          post-pass.  */
6288       pst->number_of_dependencies = len;
6289       pst->dependencies =
6290         XOBNEWVEC (&objfile->objfile_obstack, struct partial_symtab *, len);
6291       for (i = 0;
6292            VEC_iterate (dwarf2_per_cu_ptr, cu->per_cu->imported_symtabs,
6293                         i, iter);
6294            ++i)
6295         pst->dependencies[i] = iter->v.psymtab;
6296
6297       VEC_free (dwarf2_per_cu_ptr, cu->per_cu->imported_symtabs);
6298     }
6299
6300   /* Get the list of files included in the current compilation unit,
6301      and build a psymtab for each of them.  */
6302   dwarf2_build_include_psymtabs (cu, comp_unit_die, pst);
6303
6304   if (dwarf_read_debug)
6305     {
6306       struct gdbarch *gdbarch = get_objfile_arch (objfile);
6307
6308       fprintf_unfiltered (gdb_stdlog,
6309                           "Psymtab for %s unit @0x%x: %s - %s"
6310                           ", %d global, %d static syms\n",
6311                           per_cu->is_debug_types ? "type" : "comp",
6312                           to_underlying (per_cu->sect_off),
6313                           paddress (gdbarch, pst->textlow),
6314                           paddress (gdbarch, pst->texthigh),
6315                           pst->n_global_syms, pst->n_static_syms);
6316     }
6317 }
6318
6319 /* Subroutine of dwarf2_build_psymtabs_hard to simplify it.
6320    Process compilation unit THIS_CU for a psymtab.  */
6321
6322 static void
6323 process_psymtab_comp_unit (struct dwarf2_per_cu_data *this_cu,
6324                            int want_partial_unit,
6325                            enum language pretend_language)
6326 {
6327   /* If this compilation unit was already read in, free the
6328      cached copy in order to read it in again.  This is
6329      necessary because we skipped some symbols when we first
6330      read in the compilation unit (see load_partial_dies).
6331      This problem could be avoided, but the benefit is unclear.  */
6332   if (this_cu->cu != NULL)
6333     free_one_cached_comp_unit (this_cu);
6334
6335   if (this_cu->is_debug_types)
6336     init_cutu_and_read_dies (this_cu, NULL, 0, 0, build_type_psymtabs_reader,
6337                              NULL);
6338   else
6339     {
6340       process_psymtab_comp_unit_data info;
6341       info.want_partial_unit = want_partial_unit;
6342       info.pretend_language = pretend_language;
6343       init_cutu_and_read_dies (this_cu, NULL, 0, 0,
6344                                process_psymtab_comp_unit_reader, &info);
6345     }
6346
6347   /* Age out any secondary CUs.  */
6348   age_cached_comp_units ();
6349 }
6350
6351 /* Reader function for build_type_psymtabs.  */
6352
6353 static void
6354 build_type_psymtabs_reader (const struct die_reader_specs *reader,
6355                             const gdb_byte *info_ptr,
6356                             struct die_info *type_unit_die,
6357                             int has_children,
6358                             void *data)
6359 {
6360   struct objfile *objfile = dwarf2_per_objfile->objfile;
6361   struct dwarf2_cu *cu = reader->cu;
6362   struct dwarf2_per_cu_data *per_cu = cu->per_cu;
6363   struct signatured_type *sig_type;
6364   struct type_unit_group *tu_group;
6365   struct attribute *attr;
6366   struct partial_die_info *first_die;
6367   CORE_ADDR lowpc, highpc;
6368   struct partial_symtab *pst;
6369
6370   gdb_assert (data == NULL);
6371   gdb_assert (per_cu->is_debug_types);
6372   sig_type = (struct signatured_type *) per_cu;
6373
6374   if (! has_children)
6375     return;
6376
6377   attr = dwarf2_attr_no_follow (type_unit_die, DW_AT_stmt_list);
6378   tu_group = get_type_unit_group (cu, attr);
6379
6380   VEC_safe_push (sig_type_ptr, tu_group->tus, sig_type);
6381
6382   prepare_one_comp_unit (cu, type_unit_die, language_minimal);
6383   cu->list_in_scope = &file_symbols;
6384   pst = create_partial_symtab (per_cu, "");
6385   pst->anonymous = 1;
6386
6387   first_die = load_partial_dies (reader, info_ptr, 1);
6388
6389   lowpc = (CORE_ADDR) -1;
6390   highpc = (CORE_ADDR) 0;
6391   scan_partial_symbols (first_die, &lowpc, &highpc, 0, cu);
6392
6393   end_psymtab_common (objfile, pst);
6394 }
6395
6396 /* Struct used to sort TUs by their abbreviation table offset.  */
6397
6398 struct tu_abbrev_offset
6399 {
6400   struct signatured_type *sig_type;
6401   sect_offset abbrev_offset;
6402 };
6403
6404 /* Helper routine for build_type_psymtabs_1, passed to qsort.  */
6405
6406 static int
6407 sort_tu_by_abbrev_offset (const void *ap, const void *bp)
6408 {
6409   const struct tu_abbrev_offset * const *a
6410     = (const struct tu_abbrev_offset * const*) ap;
6411   const struct tu_abbrev_offset * const *b
6412     = (const struct tu_abbrev_offset * const*) bp;
6413   sect_offset aoff = (*a)->abbrev_offset;
6414   sect_offset boff = (*b)->abbrev_offset;
6415
6416   return (aoff > boff) - (aoff < boff);
6417 }
6418
6419 /* Efficiently read all the type units.
6420    This does the bulk of the work for build_type_psymtabs.
6421
6422    The efficiency is because we sort TUs by the abbrev table they use and
6423    only read each abbrev table once.  In one program there are 200K TUs
6424    sharing 8K abbrev tables.
6425
6426    The main purpose of this function is to support building the
6427    dwarf2_per_objfile->type_unit_groups table.
6428    TUs typically share the DW_AT_stmt_list of the CU they came from, so we
6429    can collapse the search space by grouping them by stmt_list.
6430    The savings can be significant, in the same program from above the 200K TUs
6431    share 8K stmt_list tables.
6432
6433    FUNC is expected to call get_type_unit_group, which will create the
6434    struct type_unit_group if necessary and add it to
6435    dwarf2_per_objfile->type_unit_groups.  */
6436
6437 static void
6438 build_type_psymtabs_1 (void)
6439 {
6440   struct tu_stats *tu_stats = &dwarf2_per_objfile->tu_stats;
6441   struct cleanup *cleanups;
6442   struct abbrev_table *abbrev_table;
6443   sect_offset abbrev_offset;
6444   struct tu_abbrev_offset *sorted_by_abbrev;
6445   int i;
6446
6447   /* It's up to the caller to not call us multiple times.  */
6448   gdb_assert (dwarf2_per_objfile->type_unit_groups == NULL);
6449
6450   if (dwarf2_per_objfile->n_type_units == 0)
6451     return;
6452
6453   /* TUs typically share abbrev tables, and there can be way more TUs than
6454      abbrev tables.  Sort by abbrev table to reduce the number of times we
6455      read each abbrev table in.
6456      Alternatives are to punt or to maintain a cache of abbrev tables.
6457      This is simpler and efficient enough for now.
6458
6459      Later we group TUs by their DW_AT_stmt_list value (as this defines the
6460      symtab to use).  Typically TUs with the same abbrev offset have the same
6461      stmt_list value too so in practice this should work well.
6462
6463      The basic algorithm here is:
6464
6465       sort TUs by abbrev table
6466       for each TU with same abbrev table:
6467         read abbrev table if first user
6468         read TU top level DIE
6469           [IWBN if DWO skeletons had DW_AT_stmt_list]
6470         call FUNC  */
6471
6472   if (dwarf_read_debug)
6473     fprintf_unfiltered (gdb_stdlog, "Building type unit groups ...\n");
6474
6475   /* Sort in a separate table to maintain the order of all_type_units
6476      for .gdb_index: TU indices directly index all_type_units.  */
6477   sorted_by_abbrev = XNEWVEC (struct tu_abbrev_offset,
6478                               dwarf2_per_objfile->n_type_units);
6479   for (i = 0; i < dwarf2_per_objfile->n_type_units; ++i)
6480     {
6481       struct signatured_type *sig_type = dwarf2_per_objfile->all_type_units[i];
6482
6483       sorted_by_abbrev[i].sig_type = sig_type;
6484       sorted_by_abbrev[i].abbrev_offset =
6485         read_abbrev_offset (sig_type->per_cu.section,
6486                             sig_type->per_cu.sect_off);
6487     }
6488   cleanups = make_cleanup (xfree, sorted_by_abbrev);
6489   qsort (sorted_by_abbrev, dwarf2_per_objfile->n_type_units,
6490          sizeof (struct tu_abbrev_offset), sort_tu_by_abbrev_offset);
6491
6492   abbrev_offset = (sect_offset) ~(unsigned) 0;
6493   abbrev_table = NULL;
6494   make_cleanup (abbrev_table_free_cleanup, &abbrev_table);
6495
6496   for (i = 0; i < dwarf2_per_objfile->n_type_units; ++i)
6497     {
6498       const struct tu_abbrev_offset *tu = &sorted_by_abbrev[i];
6499
6500       /* Switch to the next abbrev table if necessary.  */
6501       if (abbrev_table == NULL
6502           || tu->abbrev_offset != abbrev_offset)
6503         {
6504           if (abbrev_table != NULL)
6505             {
6506               abbrev_table_free (abbrev_table);
6507               /* Reset to NULL in case abbrev_table_read_table throws
6508                  an error: abbrev_table_free_cleanup will get called.  */
6509               abbrev_table = NULL;
6510             }
6511           abbrev_offset = tu->abbrev_offset;
6512           abbrev_table =
6513             abbrev_table_read_table (&dwarf2_per_objfile->abbrev,
6514                                      abbrev_offset);
6515           ++tu_stats->nr_uniq_abbrev_tables;
6516         }
6517
6518       init_cutu_and_read_dies (&tu->sig_type->per_cu, abbrev_table, 0, 0,
6519                                build_type_psymtabs_reader, NULL);
6520     }
6521
6522   do_cleanups (cleanups);
6523 }
6524
6525 /* Print collected type unit statistics.  */
6526
6527 static void
6528 print_tu_stats (void)
6529 {
6530   struct tu_stats *tu_stats = &dwarf2_per_objfile->tu_stats;
6531
6532   fprintf_unfiltered (gdb_stdlog, "Type unit statistics:\n");
6533   fprintf_unfiltered (gdb_stdlog, "  %d TUs\n",
6534                       dwarf2_per_objfile->n_type_units);
6535   fprintf_unfiltered (gdb_stdlog, "  %d uniq abbrev tables\n",
6536                       tu_stats->nr_uniq_abbrev_tables);
6537   fprintf_unfiltered (gdb_stdlog, "  %d symtabs from stmt_list entries\n",
6538                       tu_stats->nr_symtabs);
6539   fprintf_unfiltered (gdb_stdlog, "  %d symtab sharers\n",
6540                       tu_stats->nr_symtab_sharers);
6541   fprintf_unfiltered (gdb_stdlog, "  %d type units without a stmt_list\n",
6542                       tu_stats->nr_stmt_less_type_units);
6543   fprintf_unfiltered (gdb_stdlog, "  %d all_type_units reallocs\n",
6544                       tu_stats->nr_all_type_units_reallocs);
6545 }
6546
6547 /* Traversal function for build_type_psymtabs.  */
6548
6549 static int
6550 build_type_psymtab_dependencies (void **slot, void *info)
6551 {
6552   struct objfile *objfile = dwarf2_per_objfile->objfile;
6553   struct type_unit_group *tu_group = (struct type_unit_group *) *slot;
6554   struct dwarf2_per_cu_data *per_cu = &tu_group->per_cu;
6555   struct partial_symtab *pst = per_cu->v.psymtab;
6556   int len = VEC_length (sig_type_ptr, tu_group->tus);
6557   struct signatured_type *iter;
6558   int i;
6559
6560   gdb_assert (len > 0);
6561   gdb_assert (IS_TYPE_UNIT_GROUP (per_cu));
6562
6563   pst->number_of_dependencies = len;
6564   pst->dependencies =
6565     XOBNEWVEC (&objfile->objfile_obstack, struct partial_symtab *, len);
6566   for (i = 0;
6567        VEC_iterate (sig_type_ptr, tu_group->tus, i, iter);
6568        ++i)
6569     {
6570       gdb_assert (iter->per_cu.is_debug_types);
6571       pst->dependencies[i] = iter->per_cu.v.psymtab;
6572       iter->type_unit_group = tu_group;
6573     }
6574
6575   VEC_free (sig_type_ptr, tu_group->tus);
6576
6577   return 1;
6578 }
6579
6580 /* Subroutine of dwarf2_build_psymtabs_hard to simplify it.
6581    Build partial symbol tables for the .debug_types comp-units.  */
6582
6583 static void
6584 build_type_psymtabs (struct objfile *objfile)
6585 {
6586   if (! create_all_type_units (objfile))
6587     return;
6588
6589   build_type_psymtabs_1 ();
6590 }
6591
6592 /* Traversal function for process_skeletonless_type_unit.
6593    Read a TU in a DWO file and build partial symbols for it.  */
6594
6595 static int
6596 process_skeletonless_type_unit (void **slot, void *info)
6597 {
6598   struct dwo_unit *dwo_unit = (struct dwo_unit *) *slot;
6599   struct objfile *objfile = (struct objfile *) info;
6600   struct signatured_type find_entry, *entry;
6601
6602   /* If this TU doesn't exist in the global table, add it and read it in.  */
6603
6604   if (dwarf2_per_objfile->signatured_types == NULL)
6605     {
6606       dwarf2_per_objfile->signatured_types
6607         = allocate_signatured_type_table (objfile);
6608     }
6609
6610   find_entry.signature = dwo_unit->signature;
6611   slot = htab_find_slot (dwarf2_per_objfile->signatured_types, &find_entry,
6612                          INSERT);
6613   /* If we've already seen this type there's nothing to do.  What's happening
6614      is we're doing our own version of comdat-folding here.  */
6615   if (*slot != NULL)
6616     return 1;
6617
6618   /* This does the job that create_all_type_units would have done for
6619      this TU.  */
6620   entry = add_type_unit (dwo_unit->signature, slot);
6621   fill_in_sig_entry_from_dwo_entry (objfile, entry, dwo_unit);
6622   *slot = entry;
6623
6624   /* This does the job that build_type_psymtabs_1 would have done.  */
6625   init_cutu_and_read_dies (&entry->per_cu, NULL, 0, 0,
6626                            build_type_psymtabs_reader, NULL);
6627
6628   return 1;
6629 }
6630
6631 /* Traversal function for process_skeletonless_type_units.  */
6632
6633 static int
6634 process_dwo_file_for_skeletonless_type_units (void **slot, void *info)
6635 {
6636   struct dwo_file *dwo_file = (struct dwo_file *) *slot;
6637
6638   if (dwo_file->tus != NULL)
6639     {
6640       htab_traverse_noresize (dwo_file->tus,
6641                               process_skeletonless_type_unit, info);
6642     }
6643
6644   return 1;
6645 }
6646
6647 /* Scan all TUs of DWO files, verifying we've processed them.
6648    This is needed in case a TU was emitted without its skeleton.
6649    Note: This can't be done until we know what all the DWO files are.  */
6650
6651 static void
6652 process_skeletonless_type_units (struct objfile *objfile)
6653 {
6654   /* Skeletonless TUs in DWP files without .gdb_index is not supported yet.  */
6655   if (get_dwp_file () == NULL
6656       && dwarf2_per_objfile->dwo_files != NULL)
6657     {
6658       htab_traverse_noresize (dwarf2_per_objfile->dwo_files,
6659                               process_dwo_file_for_skeletonless_type_units,
6660                               objfile);
6661     }
6662 }
6663
6664 /* A cleanup function that clears objfile's psymtabs_addrmap field.  */
6665
6666 static void
6667 psymtabs_addrmap_cleanup (void *o)
6668 {
6669   struct objfile *objfile = (struct objfile *) o;
6670
6671   objfile->psymtabs_addrmap = NULL;
6672 }
6673
6674 /* Compute the 'user' field for each psymtab in OBJFILE.  */
6675
6676 static void
6677 set_partial_user (struct objfile *objfile)
6678 {
6679   int i;
6680
6681   for (i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
6682     {
6683       struct dwarf2_per_cu_data *per_cu = dw2_get_cutu (i);
6684       struct partial_symtab *pst = per_cu->v.psymtab;
6685       int j;
6686
6687       if (pst == NULL)
6688         continue;
6689
6690       for (j = 0; j < pst->number_of_dependencies; ++j)
6691         {
6692           /* Set the 'user' field only if it is not already set.  */
6693           if (pst->dependencies[j]->user == NULL)
6694             pst->dependencies[j]->user = pst;
6695         }
6696     }
6697 }
6698
6699 /* Build the partial symbol table by doing a quick pass through the
6700    .debug_info and .debug_abbrev sections.  */
6701
6702 static void
6703 dwarf2_build_psymtabs_hard (struct objfile *objfile)
6704 {
6705   struct cleanup *back_to, *addrmap_cleanup;
6706   int i;
6707
6708   if (dwarf_read_debug)
6709     {
6710       fprintf_unfiltered (gdb_stdlog, "Building psymtabs of objfile %s ...\n",
6711                           objfile_name (objfile));
6712     }
6713
6714   dwarf2_per_objfile->reading_partial_symbols = 1;
6715
6716   dwarf2_read_section (objfile, &dwarf2_per_objfile->info);
6717
6718   /* Any cached compilation units will be linked by the per-objfile
6719      read_in_chain.  Make sure to free them when we're done.  */
6720   back_to = make_cleanup (free_cached_comp_units, NULL);
6721
6722   build_type_psymtabs (objfile);
6723
6724   create_all_comp_units (objfile);
6725
6726   /* Create a temporary address map on a temporary obstack.  We later
6727      copy this to the final obstack.  */
6728   auto_obstack temp_obstack;
6729   objfile->psymtabs_addrmap = addrmap_create_mutable (&temp_obstack);
6730   addrmap_cleanup = make_cleanup (psymtabs_addrmap_cleanup, objfile);
6731
6732   for (i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
6733     {
6734       struct dwarf2_per_cu_data *per_cu = dw2_get_cutu (i);
6735
6736       process_psymtab_comp_unit (per_cu, 0, language_minimal);
6737     }
6738
6739   /* This has to wait until we read the CUs, we need the list of DWOs.  */
6740   process_skeletonless_type_units (objfile);
6741
6742   /* Now that all TUs have been processed we can fill in the dependencies.  */
6743   if (dwarf2_per_objfile->type_unit_groups != NULL)
6744     {
6745       htab_traverse_noresize (dwarf2_per_objfile->type_unit_groups,
6746                               build_type_psymtab_dependencies, NULL);
6747     }
6748
6749   if (dwarf_read_debug)
6750     print_tu_stats ();
6751
6752   set_partial_user (objfile);
6753
6754   objfile->psymtabs_addrmap = addrmap_create_fixed (objfile->psymtabs_addrmap,
6755                                                     &objfile->objfile_obstack);
6756   discard_cleanups (addrmap_cleanup);
6757
6758   do_cleanups (back_to);
6759
6760   if (dwarf_read_debug)
6761     fprintf_unfiltered (gdb_stdlog, "Done building psymtabs of %s\n",
6762                         objfile_name (objfile));
6763 }
6764
6765 /* die_reader_func for load_partial_comp_unit.  */
6766
6767 static void
6768 load_partial_comp_unit_reader (const struct die_reader_specs *reader,
6769                                const gdb_byte *info_ptr,
6770                                struct die_info *comp_unit_die,
6771                                int has_children,
6772                                void *data)
6773 {
6774   struct dwarf2_cu *cu = reader->cu;
6775
6776   prepare_one_comp_unit (cu, comp_unit_die, language_minimal);
6777
6778   /* Check if comp unit has_children.
6779      If so, read the rest of the partial symbols from this comp unit.
6780      If not, there's no more debug_info for this comp unit.  */
6781   if (has_children)
6782     load_partial_dies (reader, info_ptr, 0);
6783 }
6784
6785 /* Load the partial DIEs for a secondary CU into memory.
6786    This is also used when rereading a primary CU with load_all_dies.  */
6787
6788 static void
6789 load_partial_comp_unit (struct dwarf2_per_cu_data *this_cu)
6790 {
6791   init_cutu_and_read_dies (this_cu, NULL, 1, 1,
6792                            load_partial_comp_unit_reader, NULL);
6793 }
6794
6795 static void
6796 read_comp_units_from_section (struct objfile *objfile,
6797                               struct dwarf2_section_info *section,
6798                               struct dwarf2_section_info *abbrev_section,
6799                               unsigned int is_dwz,
6800                               int *n_allocated,
6801                               int *n_comp_units,
6802                               struct dwarf2_per_cu_data ***all_comp_units)
6803 {
6804   const gdb_byte *info_ptr;
6805   bfd *abfd = get_section_bfd_owner (section);
6806
6807   if (dwarf_read_debug)
6808     fprintf_unfiltered (gdb_stdlog, "Reading %s for %s\n",
6809                         get_section_name (section),
6810                         get_section_file_name (section));
6811
6812   dwarf2_read_section (objfile, section);
6813
6814   info_ptr = section->buffer;
6815
6816   while (info_ptr < section->buffer + section->size)
6817     {
6818       struct dwarf2_per_cu_data *this_cu;
6819
6820       sect_offset sect_off = (sect_offset) (info_ptr - section->buffer);
6821
6822       comp_unit_head cu_header;
6823       read_and_check_comp_unit_head (&cu_header, section, abbrev_section,
6824                                      info_ptr, rcuh_kind::COMPILE);
6825
6826       /* Save the compilation unit for later lookup.  */
6827       if (cu_header.unit_type != DW_UT_type)
6828         {
6829           this_cu = XOBNEW (&objfile->objfile_obstack,
6830                             struct dwarf2_per_cu_data);
6831           memset (this_cu, 0, sizeof (*this_cu));
6832         }
6833       else
6834         {
6835           auto sig_type = XOBNEW (&objfile->objfile_obstack,
6836                                   struct signatured_type);
6837           memset (sig_type, 0, sizeof (*sig_type));
6838           sig_type->signature = cu_header.signature;
6839           sig_type->type_offset_in_tu = cu_header.type_cu_offset_in_tu;
6840           this_cu = &sig_type->per_cu;
6841         }
6842       this_cu->is_debug_types = (cu_header.unit_type == DW_UT_type);
6843       this_cu->sect_off = sect_off;
6844       this_cu->length = cu_header.length + cu_header.initial_length_size;
6845       this_cu->is_dwz = is_dwz;
6846       this_cu->objfile = objfile;
6847       this_cu->section = section;
6848
6849       if (*n_comp_units == *n_allocated)
6850         {
6851           *n_allocated *= 2;
6852           *all_comp_units = XRESIZEVEC (struct dwarf2_per_cu_data *,
6853                                         *all_comp_units, *n_allocated);
6854         }
6855       (*all_comp_units)[*n_comp_units] = this_cu;
6856       ++*n_comp_units;
6857
6858       info_ptr = info_ptr + this_cu->length;
6859     }
6860 }
6861
6862 /* Create a list of all compilation units in OBJFILE.
6863    This is only done for -readnow and building partial symtabs.  */
6864
6865 static void
6866 create_all_comp_units (struct objfile *objfile)
6867 {
6868   int n_allocated;
6869   int n_comp_units;
6870   struct dwarf2_per_cu_data **all_comp_units;
6871   struct dwz_file *dwz;
6872
6873   n_comp_units = 0;
6874   n_allocated = 10;
6875   all_comp_units = XNEWVEC (struct dwarf2_per_cu_data *, n_allocated);
6876
6877   read_comp_units_from_section (objfile, &dwarf2_per_objfile->info,
6878                                 &dwarf2_per_objfile->abbrev, 0,
6879                                 &n_allocated, &n_comp_units, &all_comp_units);
6880
6881   dwz = dwarf2_get_dwz_file ();
6882   if (dwz != NULL)
6883     read_comp_units_from_section (objfile, &dwz->info, &dwz->abbrev, 1,
6884                                   &n_allocated, &n_comp_units,
6885                                   &all_comp_units);
6886
6887   dwarf2_per_objfile->all_comp_units = XOBNEWVEC (&objfile->objfile_obstack,
6888                                                   struct dwarf2_per_cu_data *,
6889                                                   n_comp_units);
6890   memcpy (dwarf2_per_objfile->all_comp_units, all_comp_units,
6891           n_comp_units * sizeof (struct dwarf2_per_cu_data *));
6892   xfree (all_comp_units);
6893   dwarf2_per_objfile->n_comp_units = n_comp_units;
6894 }
6895
6896 /* Process all loaded DIEs for compilation unit CU, starting at
6897    FIRST_DIE.  The caller should pass SET_ADDRMAP == 1 if the compilation
6898    unit DIE did not have PC info (DW_AT_low_pc and DW_AT_high_pc, or
6899    DW_AT_ranges).  See the comments of add_partial_subprogram on how
6900    SET_ADDRMAP is used and how *LOWPC and *HIGHPC are updated.  */
6901
6902 static void
6903 scan_partial_symbols (struct partial_die_info *first_die, CORE_ADDR *lowpc,
6904                       CORE_ADDR *highpc, int set_addrmap,
6905                       struct dwarf2_cu *cu)
6906 {
6907   struct partial_die_info *pdi;
6908
6909   /* Now, march along the PDI's, descending into ones which have
6910      interesting children but skipping the children of the other ones,
6911      until we reach the end of the compilation unit.  */
6912
6913   pdi = first_die;
6914
6915   while (pdi != NULL)
6916     {
6917       fixup_partial_die (pdi, cu);
6918
6919       /* Anonymous namespaces or modules have no name but have interesting
6920          children, so we need to look at them.  Ditto for anonymous
6921          enums.  */
6922
6923       if (pdi->name != NULL || pdi->tag == DW_TAG_namespace
6924           || pdi->tag == DW_TAG_module || pdi->tag == DW_TAG_enumeration_type
6925           || pdi->tag == DW_TAG_imported_unit)
6926         {
6927           switch (pdi->tag)
6928             {
6929             case DW_TAG_subprogram:
6930               add_partial_subprogram (pdi, lowpc, highpc, set_addrmap, cu);
6931               break;
6932             case DW_TAG_constant:
6933             case DW_TAG_variable:
6934             case DW_TAG_typedef:
6935             case DW_TAG_union_type:
6936               if (!pdi->is_declaration)
6937                 {
6938                   add_partial_symbol (pdi, cu);
6939                 }
6940               break;
6941             case DW_TAG_class_type:
6942             case DW_TAG_interface_type:
6943             case DW_TAG_structure_type:
6944               if (!pdi->is_declaration)
6945                 {
6946                   add_partial_symbol (pdi, cu);
6947                 }
6948               if (cu->language == language_rust && pdi->has_children)
6949                 scan_partial_symbols (pdi->die_child, lowpc, highpc,
6950                                       set_addrmap, cu);
6951               break;
6952             case DW_TAG_enumeration_type:
6953               if (!pdi->is_declaration)
6954                 add_partial_enumeration (pdi, cu);
6955               break;
6956             case DW_TAG_base_type:
6957             case DW_TAG_subrange_type:
6958               /* File scope base type definitions are added to the partial
6959                  symbol table.  */
6960               add_partial_symbol (pdi, cu);
6961               break;
6962             case DW_TAG_namespace:
6963               add_partial_namespace (pdi, lowpc, highpc, set_addrmap, cu);
6964               break;
6965             case DW_TAG_module:
6966               add_partial_module (pdi, lowpc, highpc, set_addrmap, cu);
6967               break;
6968             case DW_TAG_imported_unit:
6969               {
6970                 struct dwarf2_per_cu_data *per_cu;
6971
6972                 /* For now we don't handle imported units in type units.  */
6973                 if (cu->per_cu->is_debug_types)
6974                   {
6975                     error (_("Dwarf Error: DW_TAG_imported_unit is not"
6976                              " supported in type units [in module %s]"),
6977                            objfile_name (cu->objfile));
6978                   }
6979
6980                 per_cu = dwarf2_find_containing_comp_unit (pdi->d.sect_off,
6981                                                            pdi->is_dwz,
6982                                                            cu->objfile);
6983
6984                 /* Go read the partial unit, if needed.  */
6985                 if (per_cu->v.psymtab == NULL)
6986                   process_psymtab_comp_unit (per_cu, 1, cu->language);
6987
6988                 VEC_safe_push (dwarf2_per_cu_ptr,
6989                                cu->per_cu->imported_symtabs, per_cu);
6990               }
6991               break;
6992             case DW_TAG_imported_declaration:
6993               add_partial_symbol (pdi, cu);
6994               break;
6995             default:
6996               break;
6997             }
6998         }
6999
7000       /* If the die has a sibling, skip to the sibling.  */
7001
7002       pdi = pdi->die_sibling;
7003     }
7004 }
7005
7006 /* Functions used to compute the fully scoped name of a partial DIE.
7007
7008    Normally, this is simple.  For C++, the parent DIE's fully scoped
7009    name is concatenated with "::" and the partial DIE's name.
7010    Enumerators are an exception; they use the scope of their parent
7011    enumeration type, i.e. the name of the enumeration type is not
7012    prepended to the enumerator.
7013
7014    There are two complexities.  One is DW_AT_specification; in this
7015    case "parent" means the parent of the target of the specification,
7016    instead of the direct parent of the DIE.  The other is compilers
7017    which do not emit DW_TAG_namespace; in this case we try to guess
7018    the fully qualified name of structure types from their members'
7019    linkage names.  This must be done using the DIE's children rather
7020    than the children of any DW_AT_specification target.  We only need
7021    to do this for structures at the top level, i.e. if the target of
7022    any DW_AT_specification (if any; otherwise the DIE itself) does not
7023    have a parent.  */
7024
7025 /* Compute the scope prefix associated with PDI's parent, in
7026    compilation unit CU.  The result will be allocated on CU's
7027    comp_unit_obstack, or a copy of the already allocated PDI->NAME
7028    field.  NULL is returned if no prefix is necessary.  */
7029 static const char *
7030 partial_die_parent_scope (struct partial_die_info *pdi,
7031                           struct dwarf2_cu *cu)
7032 {
7033   const char *grandparent_scope;
7034   struct partial_die_info *parent, *real_pdi;
7035
7036   /* We need to look at our parent DIE; if we have a DW_AT_specification,
7037      then this means the parent of the specification DIE.  */
7038
7039   real_pdi = pdi;
7040   while (real_pdi->has_specification)
7041     real_pdi = find_partial_die (real_pdi->spec_offset,
7042                                  real_pdi->spec_is_dwz, cu);
7043
7044   parent = real_pdi->die_parent;
7045   if (parent == NULL)
7046     return NULL;
7047
7048   if (parent->scope_set)
7049     return parent->scope;
7050
7051   fixup_partial_die (parent, cu);
7052
7053   grandparent_scope = partial_die_parent_scope (parent, cu);
7054
7055   /* GCC 4.0 and 4.1 had a bug (PR c++/28460) where they generated bogus
7056      DW_TAG_namespace DIEs with a name of "::" for the global namespace.
7057      Work around this problem here.  */
7058   if (cu->language == language_cplus
7059       && parent->tag == DW_TAG_namespace
7060       && strcmp (parent->name, "::") == 0
7061       && grandparent_scope == NULL)
7062     {
7063       parent->scope = NULL;
7064       parent->scope_set = 1;
7065       return NULL;
7066     }
7067
7068   if (pdi->tag == DW_TAG_enumerator)
7069     /* Enumerators should not get the name of the enumeration as a prefix.  */
7070     parent->scope = grandparent_scope;
7071   else if (parent->tag == DW_TAG_namespace
7072       || parent->tag == DW_TAG_module
7073       || parent->tag == DW_TAG_structure_type
7074       || parent->tag == DW_TAG_class_type
7075       || parent->tag == DW_TAG_interface_type
7076       || parent->tag == DW_TAG_union_type
7077       || parent->tag == DW_TAG_enumeration_type)
7078     {
7079       if (grandparent_scope == NULL)
7080         parent->scope = parent->name;
7081       else
7082         parent->scope = typename_concat (&cu->comp_unit_obstack,
7083                                          grandparent_scope,
7084                                          parent->name, 0, cu);
7085     }
7086   else
7087     {
7088       /* FIXME drow/2004-04-01: What should we be doing with
7089          function-local names?  For partial symbols, we should probably be
7090          ignoring them.  */
7091       complaint (&symfile_complaints,
7092                  _("unhandled containing DIE tag %d for DIE at %d"),
7093                  parent->tag, to_underlying (pdi->sect_off));
7094       parent->scope = grandparent_scope;
7095     }
7096
7097   parent->scope_set = 1;
7098   return parent->scope;
7099 }
7100
7101 /* Return the fully scoped name associated with PDI, from compilation unit
7102    CU.  The result will be allocated with malloc.  */
7103
7104 static char *
7105 partial_die_full_name (struct partial_die_info *pdi,
7106                        struct dwarf2_cu *cu)
7107 {
7108   const char *parent_scope;
7109
7110   /* If this is a template instantiation, we can not work out the
7111      template arguments from partial DIEs.  So, unfortunately, we have
7112      to go through the full DIEs.  At least any work we do building
7113      types here will be reused if full symbols are loaded later.  */
7114   if (pdi->has_template_arguments)
7115     {
7116       fixup_partial_die (pdi, cu);
7117
7118       if (pdi->name != NULL && strchr (pdi->name, '<') == NULL)
7119         {
7120           struct die_info *die;
7121           struct attribute attr;
7122           struct dwarf2_cu *ref_cu = cu;
7123
7124           /* DW_FORM_ref_addr is using section offset.  */
7125           attr.name = (enum dwarf_attribute) 0;
7126           attr.form = DW_FORM_ref_addr;
7127           attr.u.unsnd = to_underlying (pdi->sect_off);
7128           die = follow_die_ref (NULL, &attr, &ref_cu);
7129
7130           return xstrdup (dwarf2_full_name (NULL, die, ref_cu));
7131         }
7132     }
7133
7134   parent_scope = partial_die_parent_scope (pdi, cu);
7135   if (parent_scope == NULL)
7136     return NULL;
7137   else
7138     return typename_concat (NULL, parent_scope, pdi->name, 0, cu);
7139 }
7140
7141 static void
7142 add_partial_symbol (struct partial_die_info *pdi, struct dwarf2_cu *cu)
7143 {
7144   struct objfile *objfile = cu->objfile;
7145   struct gdbarch *gdbarch = get_objfile_arch (objfile);
7146   CORE_ADDR addr = 0;
7147   const char *actual_name = NULL;
7148   CORE_ADDR baseaddr;
7149   char *built_actual_name;
7150
7151   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
7152
7153   built_actual_name = partial_die_full_name (pdi, cu);
7154   if (built_actual_name != NULL)
7155     actual_name = built_actual_name;
7156
7157   if (actual_name == NULL)
7158     actual_name = pdi->name;
7159
7160   switch (pdi->tag)
7161     {
7162     case DW_TAG_subprogram:
7163       addr = gdbarch_adjust_dwarf2_addr (gdbarch, pdi->lowpc + baseaddr);
7164       if (pdi->is_external || cu->language == language_ada)
7165         {
7166           /* brobecker/2007-12-26: Normally, only "external" DIEs are part
7167              of the global scope.  But in Ada, we want to be able to access
7168              nested procedures globally.  So all Ada subprograms are stored
7169              in the global scope.  */
7170           add_psymbol_to_list (actual_name, strlen (actual_name),
7171                                built_actual_name != NULL,
7172                                VAR_DOMAIN, LOC_BLOCK,
7173                                &objfile->global_psymbols,
7174                                addr, cu->language, objfile);
7175         }
7176       else
7177         {
7178           add_psymbol_to_list (actual_name, strlen (actual_name),
7179                                built_actual_name != NULL,
7180                                VAR_DOMAIN, LOC_BLOCK,
7181                                &objfile->static_psymbols,
7182                                addr, cu->language, objfile);
7183         }
7184
7185       if (pdi->main_subprogram && actual_name != NULL)
7186         set_objfile_main_name (objfile, actual_name, cu->language);
7187       break;
7188     case DW_TAG_constant:
7189       {
7190         struct psymbol_allocation_list *list;
7191
7192         if (pdi->is_external)
7193           list = &objfile->global_psymbols;
7194         else
7195           list = &objfile->static_psymbols;
7196         add_psymbol_to_list (actual_name, strlen (actual_name),
7197                              built_actual_name != NULL, VAR_DOMAIN, LOC_STATIC,
7198                              list, 0, cu->language, objfile);
7199       }
7200       break;
7201     case DW_TAG_variable:
7202       if (pdi->d.locdesc)
7203         addr = decode_locdesc (pdi->d.locdesc, cu);
7204
7205       if (pdi->d.locdesc
7206           && addr == 0
7207           && !dwarf2_per_objfile->has_section_at_zero)
7208         {
7209           /* A global or static variable may also have been stripped
7210              out by the linker if unused, in which case its address
7211              will be nullified; do not add such variables into partial
7212              symbol table then.  */
7213         }
7214       else if (pdi->is_external)
7215         {
7216           /* Global Variable.
7217              Don't enter into the minimal symbol tables as there is
7218              a minimal symbol table entry from the ELF symbols already.
7219              Enter into partial symbol table if it has a location
7220              descriptor or a type.
7221              If the location descriptor is missing, new_symbol will create
7222              a LOC_UNRESOLVED symbol, the address of the variable will then
7223              be determined from the minimal symbol table whenever the variable
7224              is referenced.
7225              The address for the partial symbol table entry is not
7226              used by GDB, but it comes in handy for debugging partial symbol
7227              table building.  */
7228
7229           if (pdi->d.locdesc || pdi->has_type)
7230             add_psymbol_to_list (actual_name, strlen (actual_name),
7231                                  built_actual_name != NULL,
7232                                  VAR_DOMAIN, LOC_STATIC,
7233                                  &objfile->global_psymbols,
7234                                  addr + baseaddr,
7235                                  cu->language, objfile);
7236         }
7237       else
7238         {
7239           int has_loc = pdi->d.locdesc != NULL;
7240
7241           /* Static Variable.  Skip symbols whose value we cannot know (those
7242              without location descriptors or constant values).  */
7243           if (!has_loc && !pdi->has_const_value)
7244             {
7245               xfree (built_actual_name);
7246               return;
7247             }
7248
7249           add_psymbol_to_list (actual_name, strlen (actual_name),
7250                                built_actual_name != NULL,
7251                                VAR_DOMAIN, LOC_STATIC,
7252                                &objfile->static_psymbols,
7253                                has_loc ? addr + baseaddr : (CORE_ADDR) 0,
7254                                cu->language, objfile);
7255         }
7256       break;
7257     case DW_TAG_typedef:
7258     case DW_TAG_base_type:
7259     case DW_TAG_subrange_type:
7260       add_psymbol_to_list (actual_name, strlen (actual_name),
7261                            built_actual_name != NULL,
7262                            VAR_DOMAIN, LOC_TYPEDEF,
7263                            &objfile->static_psymbols,
7264                            0, cu->language, objfile);
7265       break;
7266     case DW_TAG_imported_declaration:
7267     case DW_TAG_namespace:
7268       add_psymbol_to_list (actual_name, strlen (actual_name),
7269                            built_actual_name != NULL,
7270                            VAR_DOMAIN, LOC_TYPEDEF,
7271                            &objfile->global_psymbols,
7272                            0, cu->language, objfile);
7273       break;
7274     case DW_TAG_module:
7275       add_psymbol_to_list (actual_name, strlen (actual_name),
7276                            built_actual_name != NULL,
7277                            MODULE_DOMAIN, LOC_TYPEDEF,
7278                            &objfile->global_psymbols,
7279                            0, cu->language, objfile);
7280       break;
7281     case DW_TAG_class_type:
7282     case DW_TAG_interface_type:
7283     case DW_TAG_structure_type:
7284     case DW_TAG_union_type:
7285     case DW_TAG_enumeration_type:
7286       /* Skip external references.  The DWARF standard says in the section
7287          about "Structure, Union, and Class Type Entries": "An incomplete
7288          structure, union or class type is represented by a structure,
7289          union or class entry that does not have a byte size attribute
7290          and that has a DW_AT_declaration attribute."  */
7291       if (!pdi->has_byte_size && pdi->is_declaration)
7292         {
7293           xfree (built_actual_name);
7294           return;
7295         }
7296
7297       /* NOTE: carlton/2003-10-07: See comment in new_symbol about
7298          static vs. global.  */
7299       add_psymbol_to_list (actual_name, strlen (actual_name),
7300                            built_actual_name != NULL,
7301                            STRUCT_DOMAIN, LOC_TYPEDEF,
7302                            cu->language == language_cplus
7303                            ? &objfile->global_psymbols
7304                            : &objfile->static_psymbols,
7305                            0, cu->language, objfile);
7306
7307       break;
7308     case DW_TAG_enumerator:
7309       add_psymbol_to_list (actual_name, strlen (actual_name),
7310                            built_actual_name != NULL,
7311                            VAR_DOMAIN, LOC_CONST,
7312                            cu->language == language_cplus
7313                            ? &objfile->global_psymbols
7314                            : &objfile->static_psymbols,
7315                            0, cu->language, objfile);
7316       break;
7317     default:
7318       break;
7319     }
7320
7321   xfree (built_actual_name);
7322 }
7323
7324 /* Read a partial die corresponding to a namespace; also, add a symbol
7325    corresponding to that namespace to the symbol table.  NAMESPACE is
7326    the name of the enclosing namespace.  */
7327
7328 static void
7329 add_partial_namespace (struct partial_die_info *pdi,
7330                        CORE_ADDR *lowpc, CORE_ADDR *highpc,
7331                        int set_addrmap, struct dwarf2_cu *cu)
7332 {
7333   /* Add a symbol for the namespace.  */
7334
7335   add_partial_symbol (pdi, cu);
7336
7337   /* Now scan partial symbols in that namespace.  */
7338
7339   if (pdi->has_children)
7340     scan_partial_symbols (pdi->die_child, lowpc, highpc, set_addrmap, cu);
7341 }
7342
7343 /* Read a partial die corresponding to a Fortran module.  */
7344
7345 static void
7346 add_partial_module (struct partial_die_info *pdi, CORE_ADDR *lowpc,
7347                     CORE_ADDR *highpc, int set_addrmap, struct dwarf2_cu *cu)
7348 {
7349   /* Add a symbol for the namespace.  */
7350
7351   add_partial_symbol (pdi, cu);
7352
7353   /* Now scan partial symbols in that module.  */
7354
7355   if (pdi->has_children)
7356     scan_partial_symbols (pdi->die_child, lowpc, highpc, set_addrmap, cu);
7357 }
7358
7359 /* Read a partial die corresponding to a subprogram and create a partial
7360    symbol for that subprogram.  When the CU language allows it, this
7361    routine also defines a partial symbol for each nested subprogram
7362    that this subprogram contains.  If SET_ADDRMAP is true, record the
7363    covered ranges in the addrmap.  Set *LOWPC and *HIGHPC to the lowest
7364    and highest PC values found in PDI.
7365
7366    PDI may also be a lexical block, in which case we simply search
7367    recursively for subprograms defined inside that lexical block.
7368    Again, this is only performed when the CU language allows this
7369    type of definitions.  */
7370
7371 static void
7372 add_partial_subprogram (struct partial_die_info *pdi,
7373                         CORE_ADDR *lowpc, CORE_ADDR *highpc,
7374                         int set_addrmap, struct dwarf2_cu *cu)
7375 {
7376   if (pdi->tag == DW_TAG_subprogram)
7377     {
7378       if (pdi->has_pc_info)
7379         {
7380           if (pdi->lowpc < *lowpc)
7381             *lowpc = pdi->lowpc;
7382           if (pdi->highpc > *highpc)
7383             *highpc = pdi->highpc;
7384           if (set_addrmap)
7385             {
7386               struct objfile *objfile = cu->objfile;
7387               struct gdbarch *gdbarch = get_objfile_arch (objfile);
7388               CORE_ADDR baseaddr;
7389               CORE_ADDR highpc;
7390               CORE_ADDR lowpc;
7391
7392               baseaddr = ANOFFSET (objfile->section_offsets,
7393                                    SECT_OFF_TEXT (objfile));
7394               lowpc = gdbarch_adjust_dwarf2_addr (gdbarch,
7395                                                   pdi->lowpc + baseaddr);
7396               highpc = gdbarch_adjust_dwarf2_addr (gdbarch,
7397                                                    pdi->highpc + baseaddr);
7398               addrmap_set_empty (objfile->psymtabs_addrmap, lowpc, highpc - 1,
7399                                  cu->per_cu->v.psymtab);
7400             }
7401         }
7402
7403       if (pdi->has_pc_info || (!pdi->is_external && pdi->may_be_inlined))
7404         {
7405           if (!pdi->is_declaration)
7406             /* Ignore subprogram DIEs that do not have a name, they are
7407                illegal.  Do not emit a complaint at this point, we will
7408                do so when we convert this psymtab into a symtab.  */
7409             if (pdi->name)
7410               add_partial_symbol (pdi, cu);
7411         }
7412     }
7413
7414   if (! pdi->has_children)
7415     return;
7416
7417   if (cu->language == language_ada)
7418     {
7419       pdi = pdi->die_child;
7420       while (pdi != NULL)
7421         {
7422           fixup_partial_die (pdi, cu);
7423           if (pdi->tag == DW_TAG_subprogram
7424               || pdi->tag == DW_TAG_lexical_block)
7425             add_partial_subprogram (pdi, lowpc, highpc, set_addrmap, cu);
7426           pdi = pdi->die_sibling;
7427         }
7428     }
7429 }
7430
7431 /* Read a partial die corresponding to an enumeration type.  */
7432
7433 static void
7434 add_partial_enumeration (struct partial_die_info *enum_pdi,
7435                          struct dwarf2_cu *cu)
7436 {
7437   struct partial_die_info *pdi;
7438
7439   if (enum_pdi->name != NULL)
7440     add_partial_symbol (enum_pdi, cu);
7441
7442   pdi = enum_pdi->die_child;
7443   while (pdi)
7444     {
7445       if (pdi->tag != DW_TAG_enumerator || pdi->name == NULL)
7446         complaint (&symfile_complaints, _("malformed enumerator DIE ignored"));
7447       else
7448         add_partial_symbol (pdi, cu);
7449       pdi = pdi->die_sibling;
7450     }
7451 }
7452
7453 /* Return the initial uleb128 in the die at INFO_PTR.  */
7454
7455 static unsigned int
7456 peek_abbrev_code (bfd *abfd, const gdb_byte *info_ptr)
7457 {
7458   unsigned int bytes_read;
7459
7460   return read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
7461 }
7462
7463 /* Read the initial uleb128 in the die at INFO_PTR in compilation unit CU.
7464    Return the corresponding abbrev, or NULL if the number is zero (indicating
7465    an empty DIE).  In either case *BYTES_READ will be set to the length of
7466    the initial number.  */
7467
7468 static struct abbrev_info *
7469 peek_die_abbrev (const gdb_byte *info_ptr, unsigned int *bytes_read,
7470                  struct dwarf2_cu *cu)
7471 {
7472   bfd *abfd = cu->objfile->obfd;
7473   unsigned int abbrev_number;
7474   struct abbrev_info *abbrev;
7475
7476   abbrev_number = read_unsigned_leb128 (abfd, info_ptr, bytes_read);
7477
7478   if (abbrev_number == 0)
7479     return NULL;
7480
7481   abbrev = abbrev_table_lookup_abbrev (cu->abbrev_table, abbrev_number);
7482   if (!abbrev)
7483     {
7484       error (_("Dwarf Error: Could not find abbrev number %d in %s"
7485                " at offset 0x%x [in module %s]"),
7486              abbrev_number, cu->per_cu->is_debug_types ? "TU" : "CU",
7487              to_underlying (cu->header.sect_off), bfd_get_filename (abfd));
7488     }
7489
7490   return abbrev;
7491 }
7492
7493 /* Scan the debug information for CU starting at INFO_PTR in buffer BUFFER.
7494    Returns a pointer to the end of a series of DIEs, terminated by an empty
7495    DIE.  Any children of the skipped DIEs will also be skipped.  */
7496
7497 static const gdb_byte *
7498 skip_children (const struct die_reader_specs *reader, const gdb_byte *info_ptr)
7499 {
7500   struct dwarf2_cu *cu = reader->cu;
7501   struct abbrev_info *abbrev;
7502   unsigned int bytes_read;
7503
7504   while (1)
7505     {
7506       abbrev = peek_die_abbrev (info_ptr, &bytes_read, cu);
7507       if (abbrev == NULL)
7508         return info_ptr + bytes_read;
7509       else
7510         info_ptr = skip_one_die (reader, info_ptr + bytes_read, abbrev);
7511     }
7512 }
7513
7514 /* Scan the debug information for CU starting at INFO_PTR in buffer BUFFER.
7515    INFO_PTR should point just after the initial uleb128 of a DIE, and the
7516    abbrev corresponding to that skipped uleb128 should be passed in
7517    ABBREV.  Returns a pointer to this DIE's sibling, skipping any
7518    children.  */
7519
7520 static const gdb_byte *
7521 skip_one_die (const struct die_reader_specs *reader, const gdb_byte *info_ptr,
7522               struct abbrev_info *abbrev)
7523 {
7524   unsigned int bytes_read;
7525   struct attribute attr;
7526   bfd *abfd = reader->abfd;
7527   struct dwarf2_cu *cu = reader->cu;
7528   const gdb_byte *buffer = reader->buffer;
7529   const gdb_byte *buffer_end = reader->buffer_end;
7530   unsigned int form, i;
7531
7532   for (i = 0; i < abbrev->num_attrs; i++)
7533     {
7534       /* The only abbrev we care about is DW_AT_sibling.  */
7535       if (abbrev->attrs[i].name == DW_AT_sibling)
7536         {
7537           read_attribute (reader, &attr, &abbrev->attrs[i], info_ptr);
7538           if (attr.form == DW_FORM_ref_addr)
7539             complaint (&symfile_complaints,
7540                        _("ignoring absolute DW_AT_sibling"));
7541           else
7542             {
7543               sect_offset off = dwarf2_get_ref_die_offset (&attr);
7544               const gdb_byte *sibling_ptr = buffer + to_underlying (off);
7545
7546               if (sibling_ptr < info_ptr)
7547                 complaint (&symfile_complaints,
7548                            _("DW_AT_sibling points backwards"));
7549               else if (sibling_ptr > reader->buffer_end)
7550                 dwarf2_section_buffer_overflow_complaint (reader->die_section);
7551               else
7552                 return sibling_ptr;
7553             }
7554         }
7555
7556       /* If it isn't DW_AT_sibling, skip this attribute.  */
7557       form = abbrev->attrs[i].form;
7558     skip_attribute:
7559       switch (form)
7560         {
7561         case DW_FORM_ref_addr:
7562           /* In DWARF 2, DW_FORM_ref_addr is address sized; in DWARF 3
7563              and later it is offset sized.  */
7564           if (cu->header.version == 2)
7565             info_ptr += cu->header.addr_size;
7566           else
7567             info_ptr += cu->header.offset_size;
7568           break;
7569         case DW_FORM_GNU_ref_alt:
7570           info_ptr += cu->header.offset_size;
7571           break;
7572         case DW_FORM_addr:
7573           info_ptr += cu->header.addr_size;
7574           break;
7575         case DW_FORM_data1:
7576         case DW_FORM_ref1:
7577         case DW_FORM_flag:
7578           info_ptr += 1;
7579           break;
7580         case DW_FORM_flag_present:
7581         case DW_FORM_implicit_const:
7582           break;
7583         case DW_FORM_data2:
7584         case DW_FORM_ref2:
7585           info_ptr += 2;
7586           break;
7587         case DW_FORM_data4:
7588         case DW_FORM_ref4:
7589           info_ptr += 4;
7590           break;
7591         case DW_FORM_data8:
7592         case DW_FORM_ref8:
7593         case DW_FORM_ref_sig8:
7594           info_ptr += 8;
7595           break;
7596         case DW_FORM_data16:
7597           info_ptr += 16;
7598           break;
7599         case DW_FORM_string:
7600           read_direct_string (abfd, info_ptr, &bytes_read);
7601           info_ptr += bytes_read;
7602           break;
7603         case DW_FORM_sec_offset:
7604         case DW_FORM_strp:
7605         case DW_FORM_GNU_strp_alt:
7606           info_ptr += cu->header.offset_size;
7607           break;
7608         case DW_FORM_exprloc:
7609         case DW_FORM_block:
7610           info_ptr += read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
7611           info_ptr += bytes_read;
7612           break;
7613         case DW_FORM_block1:
7614           info_ptr += 1 + read_1_byte (abfd, info_ptr);
7615           break;
7616         case DW_FORM_block2:
7617           info_ptr += 2 + read_2_bytes (abfd, info_ptr);
7618           break;
7619         case DW_FORM_block4:
7620           info_ptr += 4 + read_4_bytes (abfd, info_ptr);
7621           break;
7622         case DW_FORM_sdata:
7623         case DW_FORM_udata:
7624         case DW_FORM_ref_udata:
7625         case DW_FORM_GNU_addr_index:
7626         case DW_FORM_GNU_str_index:
7627           info_ptr = safe_skip_leb128 (info_ptr, buffer_end);
7628           break;
7629         case DW_FORM_indirect:
7630           form = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
7631           info_ptr += bytes_read;
7632           /* We need to continue parsing from here, so just go back to
7633              the top.  */
7634           goto skip_attribute;
7635
7636         default:
7637           error (_("Dwarf Error: Cannot handle %s "
7638                    "in DWARF reader [in module %s]"),
7639                  dwarf_form_name (form),
7640                  bfd_get_filename (abfd));
7641         }
7642     }
7643
7644   if (abbrev->has_children)
7645     return skip_children (reader, info_ptr);
7646   else
7647     return info_ptr;
7648 }
7649
7650 /* Locate ORIG_PDI's sibling.
7651    INFO_PTR should point to the start of the next DIE after ORIG_PDI.  */
7652
7653 static const gdb_byte *
7654 locate_pdi_sibling (const struct die_reader_specs *reader,
7655                     struct partial_die_info *orig_pdi,
7656                     const gdb_byte *info_ptr)
7657 {
7658   /* Do we know the sibling already?  */
7659
7660   if (orig_pdi->sibling)
7661     return orig_pdi->sibling;
7662
7663   /* Are there any children to deal with?  */
7664
7665   if (!orig_pdi->has_children)
7666     return info_ptr;
7667
7668   /* Skip the children the long way.  */
7669
7670   return skip_children (reader, info_ptr);
7671 }
7672
7673 /* Expand this partial symbol table into a full symbol table.  SELF is
7674    not NULL.  */
7675
7676 static void
7677 dwarf2_read_symtab (struct partial_symtab *self,
7678                     struct objfile *objfile)
7679 {
7680   if (self->readin)
7681     {
7682       warning (_("bug: psymtab for %s is already read in."),
7683                self->filename);
7684     }
7685   else
7686     {
7687       if (info_verbose)
7688         {
7689           printf_filtered (_("Reading in symbols for %s..."),
7690                            self->filename);
7691           gdb_flush (gdb_stdout);
7692         }
7693
7694       /* Restore our global data.  */
7695       dwarf2_per_objfile
7696         = (struct dwarf2_per_objfile *) objfile_data (objfile,
7697                                                       dwarf2_objfile_data_key);
7698
7699       /* If this psymtab is constructed from a debug-only objfile, the
7700          has_section_at_zero flag will not necessarily be correct.  We
7701          can get the correct value for this flag by looking at the data
7702          associated with the (presumably stripped) associated objfile.  */
7703       if (objfile->separate_debug_objfile_backlink)
7704         {
7705           struct dwarf2_per_objfile *dpo_backlink
7706             = ((struct dwarf2_per_objfile *)
7707                objfile_data (objfile->separate_debug_objfile_backlink,
7708                              dwarf2_objfile_data_key));
7709
7710           dwarf2_per_objfile->has_section_at_zero
7711             = dpo_backlink->has_section_at_zero;
7712         }
7713
7714       dwarf2_per_objfile->reading_partial_symbols = 0;
7715
7716       psymtab_to_symtab_1 (self);
7717
7718       /* Finish up the debug error message.  */
7719       if (info_verbose)
7720         printf_filtered (_("done.\n"));
7721     }
7722
7723   process_cu_includes ();
7724 }
7725 \f
7726 /* Reading in full CUs.  */
7727
7728 /* Add PER_CU to the queue.  */
7729
7730 static void
7731 queue_comp_unit (struct dwarf2_per_cu_data *per_cu,
7732                  enum language pretend_language)
7733 {
7734   struct dwarf2_queue_item *item;
7735
7736   per_cu->queued = 1;
7737   item = XNEW (struct dwarf2_queue_item);
7738   item->per_cu = per_cu;
7739   item->pretend_language = pretend_language;
7740   item->next = NULL;
7741
7742   if (dwarf2_queue == NULL)
7743     dwarf2_queue = item;
7744   else
7745     dwarf2_queue_tail->next = item;
7746
7747   dwarf2_queue_tail = item;
7748 }
7749
7750 /* If PER_CU is not yet queued, add it to the queue.
7751    If DEPENDENT_CU is non-NULL, it has a reference to PER_CU so add a
7752    dependency.
7753    The result is non-zero if PER_CU was queued, otherwise the result is zero
7754    meaning either PER_CU is already queued or it is already loaded.
7755
7756    N.B. There is an invariant here that if a CU is queued then it is loaded.
7757    The caller is required to load PER_CU if we return non-zero.  */
7758
7759 static int
7760 maybe_queue_comp_unit (struct dwarf2_cu *dependent_cu,
7761                        struct dwarf2_per_cu_data *per_cu,
7762                        enum language pretend_language)
7763 {
7764   /* We may arrive here during partial symbol reading, if we need full
7765      DIEs to process an unusual case (e.g. template arguments).  Do
7766      not queue PER_CU, just tell our caller to load its DIEs.  */
7767   if (dwarf2_per_objfile->reading_partial_symbols)
7768     {
7769       if (per_cu->cu == NULL || per_cu->cu->dies == NULL)
7770         return 1;
7771       return 0;
7772     }
7773
7774   /* Mark the dependence relation so that we don't flush PER_CU
7775      too early.  */
7776   if (dependent_cu != NULL)
7777     dwarf2_add_dependence (dependent_cu, per_cu);
7778
7779   /* If it's already on the queue, we have nothing to do.  */
7780   if (per_cu->queued)
7781     return 0;
7782
7783   /* If the compilation unit is already loaded, just mark it as
7784      used.  */
7785   if (per_cu->cu != NULL)
7786     {
7787       per_cu->cu->last_used = 0;
7788       return 0;
7789     }
7790
7791   /* Add it to the queue.  */
7792   queue_comp_unit (per_cu, pretend_language);
7793
7794   return 1;
7795 }
7796
7797 /* Process the queue.  */
7798
7799 static void
7800 process_queue (void)
7801 {
7802   struct dwarf2_queue_item *item, *next_item;
7803
7804   if (dwarf_read_debug)
7805     {
7806       fprintf_unfiltered (gdb_stdlog,
7807                           "Expanding one or more symtabs of objfile %s ...\n",
7808                           objfile_name (dwarf2_per_objfile->objfile));
7809     }
7810
7811   /* The queue starts out with one item, but following a DIE reference
7812      may load a new CU, adding it to the end of the queue.  */
7813   for (item = dwarf2_queue; item != NULL; dwarf2_queue = item = next_item)
7814     {
7815       if ((dwarf2_per_objfile->using_index
7816            ? !item->per_cu->v.quick->compunit_symtab
7817            : (item->per_cu->v.psymtab && !item->per_cu->v.psymtab->readin))
7818           /* Skip dummy CUs.  */
7819           && item->per_cu->cu != NULL)
7820         {
7821           struct dwarf2_per_cu_data *per_cu = item->per_cu;
7822           unsigned int debug_print_threshold;
7823           char buf[100];
7824
7825           if (per_cu->is_debug_types)
7826             {
7827               struct signatured_type *sig_type =
7828                 (struct signatured_type *) per_cu;
7829
7830               sprintf (buf, "TU %s at offset 0x%x",
7831                        hex_string (sig_type->signature),
7832                        to_underlying (per_cu->sect_off));
7833               /* There can be 100s of TUs.
7834                  Only print them in verbose mode.  */
7835               debug_print_threshold = 2;
7836             }
7837           else
7838             {
7839               sprintf (buf, "CU at offset 0x%x",
7840                        to_underlying (per_cu->sect_off));
7841               debug_print_threshold = 1;
7842             }
7843
7844           if (dwarf_read_debug >= debug_print_threshold)
7845             fprintf_unfiltered (gdb_stdlog, "Expanding symtab of %s\n", buf);
7846
7847           if (per_cu->is_debug_types)
7848             process_full_type_unit (per_cu, item->pretend_language);
7849           else
7850             process_full_comp_unit (per_cu, item->pretend_language);
7851
7852           if (dwarf_read_debug >= debug_print_threshold)
7853             fprintf_unfiltered (gdb_stdlog, "Done expanding %s\n", buf);
7854         }
7855
7856       item->per_cu->queued = 0;
7857       next_item = item->next;
7858       xfree (item);
7859     }
7860
7861   dwarf2_queue_tail = NULL;
7862
7863   if (dwarf_read_debug)
7864     {
7865       fprintf_unfiltered (gdb_stdlog, "Done expanding symtabs of %s.\n",
7866                           objfile_name (dwarf2_per_objfile->objfile));
7867     }
7868 }
7869
7870 /* Free all allocated queue entries.  This function only releases anything if
7871    an error was thrown; if the queue was processed then it would have been
7872    freed as we went along.  */
7873
7874 static void
7875 dwarf2_release_queue (void *dummy)
7876 {
7877   struct dwarf2_queue_item *item, *last;
7878
7879   item = dwarf2_queue;
7880   while (item)
7881     {
7882       /* Anything still marked queued is likely to be in an
7883          inconsistent state, so discard it.  */
7884       if (item->per_cu->queued)
7885         {
7886           if (item->per_cu->cu != NULL)
7887             free_one_cached_comp_unit (item->per_cu);
7888           item->per_cu->queued = 0;
7889         }
7890
7891       last = item;
7892       item = item->next;
7893       xfree (last);
7894     }
7895
7896   dwarf2_queue = dwarf2_queue_tail = NULL;
7897 }
7898
7899 /* Read in full symbols for PST, and anything it depends on.  */
7900
7901 static void
7902 psymtab_to_symtab_1 (struct partial_symtab *pst)
7903 {
7904   struct dwarf2_per_cu_data *per_cu;
7905   int i;
7906
7907   if (pst->readin)
7908     return;
7909
7910   for (i = 0; i < pst->number_of_dependencies; i++)
7911     if (!pst->dependencies[i]->readin
7912         && pst->dependencies[i]->user == NULL)
7913       {
7914         /* Inform about additional files that need to be read in.  */
7915         if (info_verbose)
7916           {
7917             /* FIXME: i18n: Need to make this a single string.  */
7918             fputs_filtered (" ", gdb_stdout);
7919             wrap_here ("");
7920             fputs_filtered ("and ", gdb_stdout);
7921             wrap_here ("");
7922             printf_filtered ("%s...", pst->dependencies[i]->filename);
7923             wrap_here ("");     /* Flush output.  */
7924             gdb_flush (gdb_stdout);
7925           }
7926         psymtab_to_symtab_1 (pst->dependencies[i]);
7927       }
7928
7929   per_cu = (struct dwarf2_per_cu_data *) pst->read_symtab_private;
7930
7931   if (per_cu == NULL)
7932     {
7933       /* It's an include file, no symbols to read for it.
7934          Everything is in the parent symtab.  */
7935       pst->readin = 1;
7936       return;
7937     }
7938
7939   dw2_do_instantiate_symtab (per_cu);
7940 }
7941
7942 /* Trivial hash function for die_info: the hash value of a DIE
7943    is its offset in .debug_info for this objfile.  */
7944
7945 static hashval_t
7946 die_hash (const void *item)
7947 {
7948   const struct die_info *die = (const struct die_info *) item;
7949
7950   return to_underlying (die->sect_off);
7951 }
7952
7953 /* Trivial comparison function for die_info structures: two DIEs
7954    are equal if they have the same offset.  */
7955
7956 static int
7957 die_eq (const void *item_lhs, const void *item_rhs)
7958 {
7959   const struct die_info *die_lhs = (const struct die_info *) item_lhs;
7960   const struct die_info *die_rhs = (const struct die_info *) item_rhs;
7961
7962   return die_lhs->sect_off == die_rhs->sect_off;
7963 }
7964
7965 /* die_reader_func for load_full_comp_unit.
7966    This is identical to read_signatured_type_reader,
7967    but is kept separate for now.  */
7968
7969 static void
7970 load_full_comp_unit_reader (const struct die_reader_specs *reader,
7971                             const gdb_byte *info_ptr,
7972                             struct die_info *comp_unit_die,
7973                             int has_children,
7974                             void *data)
7975 {
7976   struct dwarf2_cu *cu = reader->cu;
7977   enum language *language_ptr = (enum language *) data;
7978
7979   gdb_assert (cu->die_hash == NULL);
7980   cu->die_hash =
7981     htab_create_alloc_ex (cu->header.length / 12,
7982                           die_hash,
7983                           die_eq,
7984                           NULL,
7985                           &cu->comp_unit_obstack,
7986                           hashtab_obstack_allocate,
7987                           dummy_obstack_deallocate);
7988
7989   if (has_children)
7990     comp_unit_die->child = read_die_and_siblings (reader, info_ptr,
7991                                                   &info_ptr, comp_unit_die);
7992   cu->dies = comp_unit_die;
7993   /* comp_unit_die is not stored in die_hash, no need.  */
7994
7995   /* We try not to read any attributes in this function, because not
7996      all CUs needed for references have been loaded yet, and symbol
7997      table processing isn't initialized.  But we have to set the CU language,
7998      or we won't be able to build types correctly.
7999      Similarly, if we do not read the producer, we can not apply
8000      producer-specific interpretation.  */
8001   prepare_one_comp_unit (cu, cu->dies, *language_ptr);
8002 }
8003
8004 /* Load the DIEs associated with PER_CU into memory.  */
8005
8006 static void
8007 load_full_comp_unit (struct dwarf2_per_cu_data *this_cu,
8008                      enum language pretend_language)
8009 {
8010   gdb_assert (! this_cu->is_debug_types);
8011
8012   init_cutu_and_read_dies (this_cu, NULL, 1, 1,
8013                            load_full_comp_unit_reader, &pretend_language);
8014 }
8015
8016 /* Add a DIE to the delayed physname list.  */
8017
8018 static void
8019 add_to_method_list (struct type *type, int fnfield_index, int index,
8020                     const char *name, struct die_info *die,
8021                     struct dwarf2_cu *cu)
8022 {
8023   struct delayed_method_info mi;
8024   mi.type = type;
8025   mi.fnfield_index = fnfield_index;
8026   mi.index = index;
8027   mi.name = name;
8028   mi.die = die;
8029   VEC_safe_push (delayed_method_info, cu->method_list, &mi);
8030 }
8031
8032 /* A cleanup for freeing the delayed method list.  */
8033
8034 static void
8035 free_delayed_list (void *ptr)
8036 {
8037   struct dwarf2_cu *cu = (struct dwarf2_cu *) ptr;
8038   if (cu->method_list != NULL)
8039     {
8040       VEC_free (delayed_method_info, cu->method_list);
8041       cu->method_list = NULL;
8042     }
8043 }
8044
8045 /* Check whether [PHYSNAME, PHYSNAME+LEN) ends with a modifier like
8046    "const" / "volatile".  If so, decrements LEN by the length of the
8047    modifier and return true.  Otherwise return false.  */
8048
8049 template<size_t N>
8050 static bool
8051 check_modifier (const char *physname, size_t &len, const char (&mod)[N])
8052 {
8053   size_t mod_len = sizeof (mod) - 1;
8054   if (len > mod_len && startswith (physname + (len - mod_len), mod))
8055     {
8056       len -= mod_len;
8057       return true;
8058     }
8059   return false;
8060 }
8061
8062 /* Compute the physnames of any methods on the CU's method list.
8063
8064    The computation of method physnames is delayed in order to avoid the
8065    (bad) condition that one of the method's formal parameters is of an as yet
8066    incomplete type.  */
8067
8068 static void
8069 compute_delayed_physnames (struct dwarf2_cu *cu)
8070 {
8071   int i;
8072   struct delayed_method_info *mi;
8073
8074   /* Only C++ delays computing physnames.  */
8075   if (VEC_empty (delayed_method_info, cu->method_list))
8076     return;
8077   gdb_assert (cu->language == language_cplus);
8078
8079   for (i = 0; VEC_iterate (delayed_method_info, cu->method_list, i, mi) ; ++i)
8080     {
8081       const char *physname;
8082       struct fn_fieldlist *fn_flp
8083         = &TYPE_FN_FIELDLIST (mi->type, mi->fnfield_index);
8084       physname = dwarf2_physname (mi->name, mi->die, cu);
8085       TYPE_FN_FIELD_PHYSNAME (fn_flp->fn_fields, mi->index)
8086         = physname ? physname : "";
8087
8088       /* Since there's no tag to indicate whether a method is a
8089          const/volatile overload, extract that information out of the
8090          demangled name.  */
8091       if (physname != NULL)
8092         {
8093           size_t len = strlen (physname);
8094
8095           while (1)
8096             {
8097               if (physname[len] == ')') /* shortcut */
8098                 break;
8099               else if (check_modifier (physname, len, " const"))
8100                 TYPE_FN_FIELD_CONST (fn_flp->fn_fields, mi->index) = 1;
8101               else if (check_modifier (physname, len, " volatile"))
8102                 TYPE_FN_FIELD_VOLATILE (fn_flp->fn_fields, mi->index) = 1;
8103               else
8104                 break;
8105             }
8106         }
8107     }
8108 }
8109
8110 /* Go objects should be embedded in a DW_TAG_module DIE,
8111    and it's not clear if/how imported objects will appear.
8112    To keep Go support simple until that's worked out,
8113    go back through what we've read and create something usable.
8114    We could do this while processing each DIE, and feels kinda cleaner,
8115    but that way is more invasive.
8116    This is to, for example, allow the user to type "p var" or "b main"
8117    without having to specify the package name, and allow lookups
8118    of module.object to work in contexts that use the expression
8119    parser.  */
8120
8121 static void
8122 fixup_go_packaging (struct dwarf2_cu *cu)
8123 {
8124   char *package_name = NULL;
8125   struct pending *list;
8126   int i;
8127
8128   for (list = global_symbols; list != NULL; list = list->next)
8129     {
8130       for (i = 0; i < list->nsyms; ++i)
8131         {
8132           struct symbol *sym = list->symbol[i];
8133
8134           if (SYMBOL_LANGUAGE (sym) == language_go
8135               && SYMBOL_CLASS (sym) == LOC_BLOCK)
8136             {
8137               char *this_package_name = go_symbol_package_name (sym);
8138
8139               if (this_package_name == NULL)
8140                 continue;
8141               if (package_name == NULL)
8142                 package_name = this_package_name;
8143               else
8144                 {
8145                   if (strcmp (package_name, this_package_name) != 0)
8146                     complaint (&symfile_complaints,
8147                                _("Symtab %s has objects from two different Go packages: %s and %s"),
8148                                (symbol_symtab (sym) != NULL
8149                                 ? symtab_to_filename_for_display
8150                                     (symbol_symtab (sym))
8151                                 : objfile_name (cu->objfile)),
8152                                this_package_name, package_name);
8153                   xfree (this_package_name);
8154                 }
8155             }
8156         }
8157     }
8158
8159   if (package_name != NULL)
8160     {
8161       struct objfile *objfile = cu->objfile;
8162       const char *saved_package_name
8163         = (const char *) obstack_copy0 (&objfile->per_bfd->storage_obstack,
8164                                         package_name,
8165                                         strlen (package_name));
8166       struct type *type = init_type (objfile, TYPE_CODE_MODULE, 0,
8167                                      saved_package_name);
8168       struct symbol *sym;
8169
8170       TYPE_TAG_NAME (type) = TYPE_NAME (type);
8171
8172       sym = allocate_symbol (objfile);
8173       SYMBOL_SET_LANGUAGE (sym, language_go, &objfile->objfile_obstack);
8174       SYMBOL_SET_NAMES (sym, saved_package_name,
8175                         strlen (saved_package_name), 0, objfile);
8176       /* This is not VAR_DOMAIN because we want a way to ensure a lookup of,
8177          e.g., "main" finds the "main" module and not C's main().  */
8178       SYMBOL_DOMAIN (sym) = STRUCT_DOMAIN;
8179       SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
8180       SYMBOL_TYPE (sym) = type;
8181
8182       add_symbol_to_list (sym, &global_symbols);
8183
8184       xfree (package_name);
8185     }
8186 }
8187
8188 /* Return the symtab for PER_CU.  This works properly regardless of
8189    whether we're using the index or psymtabs.  */
8190
8191 static struct compunit_symtab *
8192 get_compunit_symtab (struct dwarf2_per_cu_data *per_cu)
8193 {
8194   return (dwarf2_per_objfile->using_index
8195           ? per_cu->v.quick->compunit_symtab
8196           : per_cu->v.psymtab->compunit_symtab);
8197 }
8198
8199 /* A helper function for computing the list of all symbol tables
8200    included by PER_CU.  */
8201
8202 static void
8203 recursively_compute_inclusions (VEC (compunit_symtab_ptr) **result,
8204                                 htab_t all_children, htab_t all_type_symtabs,
8205                                 struct dwarf2_per_cu_data *per_cu,
8206                                 struct compunit_symtab *immediate_parent)
8207 {
8208   void **slot;
8209   int ix;
8210   struct compunit_symtab *cust;
8211   struct dwarf2_per_cu_data *iter;
8212
8213   slot = htab_find_slot (all_children, per_cu, INSERT);
8214   if (*slot != NULL)
8215     {
8216       /* This inclusion and its children have been processed.  */
8217       return;
8218     }
8219
8220   *slot = per_cu;
8221   /* Only add a CU if it has a symbol table.  */
8222   cust = get_compunit_symtab (per_cu);
8223   if (cust != NULL)
8224     {
8225       /* If this is a type unit only add its symbol table if we haven't
8226          seen it yet (type unit per_cu's can share symtabs).  */
8227       if (per_cu->is_debug_types)
8228         {
8229           slot = htab_find_slot (all_type_symtabs, cust, INSERT);
8230           if (*slot == NULL)
8231             {
8232               *slot = cust;
8233               VEC_safe_push (compunit_symtab_ptr, *result, cust);
8234               if (cust->user == NULL)
8235                 cust->user = immediate_parent;
8236             }
8237         }
8238       else
8239         {
8240           VEC_safe_push (compunit_symtab_ptr, *result, cust);
8241           if (cust->user == NULL)
8242             cust->user = immediate_parent;
8243         }
8244     }
8245
8246   for (ix = 0;
8247        VEC_iterate (dwarf2_per_cu_ptr, per_cu->imported_symtabs, ix, iter);
8248        ++ix)
8249     {
8250       recursively_compute_inclusions (result, all_children,
8251                                       all_type_symtabs, iter, cust);
8252     }
8253 }
8254
8255 /* Compute the compunit_symtab 'includes' fields for the compunit_symtab of
8256    PER_CU.  */
8257
8258 static void
8259 compute_compunit_symtab_includes (struct dwarf2_per_cu_data *per_cu)
8260 {
8261   gdb_assert (! per_cu->is_debug_types);
8262
8263   if (!VEC_empty (dwarf2_per_cu_ptr, per_cu->imported_symtabs))
8264     {
8265       int ix, len;
8266       struct dwarf2_per_cu_data *per_cu_iter;
8267       struct compunit_symtab *compunit_symtab_iter;
8268       VEC (compunit_symtab_ptr) *result_symtabs = NULL;
8269       htab_t all_children, all_type_symtabs;
8270       struct compunit_symtab *cust = get_compunit_symtab (per_cu);
8271
8272       /* If we don't have a symtab, we can just skip this case.  */
8273       if (cust == NULL)
8274         return;
8275
8276       all_children = htab_create_alloc (1, htab_hash_pointer, htab_eq_pointer,
8277                                         NULL, xcalloc, xfree);
8278       all_type_symtabs = htab_create_alloc (1, htab_hash_pointer, htab_eq_pointer,
8279                                             NULL, xcalloc, xfree);
8280
8281       for (ix = 0;
8282            VEC_iterate (dwarf2_per_cu_ptr, per_cu->imported_symtabs,
8283                         ix, per_cu_iter);
8284            ++ix)
8285         {
8286           recursively_compute_inclusions (&result_symtabs, all_children,
8287                                           all_type_symtabs, per_cu_iter,
8288                                           cust);
8289         }
8290
8291       /* Now we have a transitive closure of all the included symtabs.  */
8292       len = VEC_length (compunit_symtab_ptr, result_symtabs);
8293       cust->includes
8294         = XOBNEWVEC (&dwarf2_per_objfile->objfile->objfile_obstack,
8295                      struct compunit_symtab *, len + 1);
8296       for (ix = 0;
8297            VEC_iterate (compunit_symtab_ptr, result_symtabs, ix,
8298                         compunit_symtab_iter);
8299            ++ix)
8300         cust->includes[ix] = compunit_symtab_iter;
8301       cust->includes[len] = NULL;
8302
8303       VEC_free (compunit_symtab_ptr, result_symtabs);
8304       htab_delete (all_children);
8305       htab_delete (all_type_symtabs);
8306     }
8307 }
8308
8309 /* Compute the 'includes' field for the symtabs of all the CUs we just
8310    read.  */
8311
8312 static void
8313 process_cu_includes (void)
8314 {
8315   int ix;
8316   struct dwarf2_per_cu_data *iter;
8317
8318   for (ix = 0;
8319        VEC_iterate (dwarf2_per_cu_ptr, dwarf2_per_objfile->just_read_cus,
8320                     ix, iter);
8321        ++ix)
8322     {
8323       if (! iter->is_debug_types)
8324         compute_compunit_symtab_includes (iter);
8325     }
8326
8327   VEC_free (dwarf2_per_cu_ptr, dwarf2_per_objfile->just_read_cus);
8328 }
8329
8330 /* Generate full symbol information for PER_CU, whose DIEs have
8331    already been loaded into memory.  */
8332
8333 static void
8334 process_full_comp_unit (struct dwarf2_per_cu_data *per_cu,
8335                         enum language pretend_language)
8336 {
8337   struct dwarf2_cu *cu = per_cu->cu;
8338   struct objfile *objfile = per_cu->objfile;
8339   struct gdbarch *gdbarch = get_objfile_arch (objfile);
8340   CORE_ADDR lowpc, highpc;
8341   struct compunit_symtab *cust;
8342   struct cleanup *back_to, *delayed_list_cleanup;
8343   CORE_ADDR baseaddr;
8344   struct block *static_block;
8345   CORE_ADDR addr;
8346
8347   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
8348
8349   buildsym_init ();
8350   back_to = make_cleanup (really_free_pendings, NULL);
8351   delayed_list_cleanup = make_cleanup (free_delayed_list, cu);
8352
8353   cu->list_in_scope = &file_symbols;
8354
8355   cu->language = pretend_language;
8356   cu->language_defn = language_def (cu->language);
8357
8358   /* Do line number decoding in read_file_scope () */
8359   process_die (cu->dies, cu);
8360
8361   /* For now fudge the Go package.  */
8362   if (cu->language == language_go)
8363     fixup_go_packaging (cu);
8364
8365   /* Now that we have processed all the DIEs in the CU, all the types 
8366      should be complete, and it should now be safe to compute all of the
8367      physnames.  */
8368   compute_delayed_physnames (cu);
8369   do_cleanups (delayed_list_cleanup);
8370
8371   /* Some compilers don't define a DW_AT_high_pc attribute for the
8372      compilation unit.  If the DW_AT_high_pc is missing, synthesize
8373      it, by scanning the DIE's below the compilation unit.  */
8374   get_scope_pc_bounds (cu->dies, &lowpc, &highpc, cu);
8375
8376   addr = gdbarch_adjust_dwarf2_addr (gdbarch, highpc + baseaddr);
8377   static_block = end_symtab_get_static_block (addr, 0, 1);
8378
8379   /* If the comp unit has DW_AT_ranges, it may have discontiguous ranges.
8380      Also, DW_AT_ranges may record ranges not belonging to any child DIEs
8381      (such as virtual method tables).  Record the ranges in STATIC_BLOCK's
8382      addrmap to help ensure it has an accurate map of pc values belonging to
8383      this comp unit.  */
8384   dwarf2_record_block_ranges (cu->dies, static_block, baseaddr, cu);
8385
8386   cust = end_symtab_from_static_block (static_block,
8387                                        SECT_OFF_TEXT (objfile), 0);
8388
8389   if (cust != NULL)
8390     {
8391       int gcc_4_minor = producer_is_gcc_ge_4 (cu->producer);
8392
8393       /* Set symtab language to language from DW_AT_language.  If the
8394          compilation is from a C file generated by language preprocessors, do
8395          not set the language if it was already deduced by start_subfile.  */
8396       if (!(cu->language == language_c
8397             && COMPUNIT_FILETABS (cust)->language != language_unknown))
8398         COMPUNIT_FILETABS (cust)->language = cu->language;
8399
8400       /* GCC-4.0 has started to support -fvar-tracking.  GCC-3.x still can
8401          produce DW_AT_location with location lists but it can be possibly
8402          invalid without -fvar-tracking.  Still up to GCC-4.4.x incl. 4.4.0
8403          there were bugs in prologue debug info, fixed later in GCC-4.5
8404          by "unwind info for epilogues" patch (which is not directly related).
8405
8406          For -gdwarf-4 type units LOCATIONS_VALID indication is fortunately not
8407          needed, it would be wrong due to missing DW_AT_producer there.
8408
8409          Still one can confuse GDB by using non-standard GCC compilation
8410          options - this waits on GCC PR other/32998 (-frecord-gcc-switches).
8411          */ 
8412       if (cu->has_loclist && gcc_4_minor >= 5)
8413         cust->locations_valid = 1;
8414
8415       if (gcc_4_minor >= 5)
8416         cust->epilogue_unwind_valid = 1;
8417
8418       cust->call_site_htab = cu->call_site_htab;
8419     }
8420
8421   if (dwarf2_per_objfile->using_index)
8422     per_cu->v.quick->compunit_symtab = cust;
8423   else
8424     {
8425       struct partial_symtab *pst = per_cu->v.psymtab;
8426       pst->compunit_symtab = cust;
8427       pst->readin = 1;
8428     }
8429
8430   /* Push it for inclusion processing later.  */
8431   VEC_safe_push (dwarf2_per_cu_ptr, dwarf2_per_objfile->just_read_cus, per_cu);
8432
8433   do_cleanups (back_to);
8434 }
8435
8436 /* Generate full symbol information for type unit PER_CU, whose DIEs have
8437    already been loaded into memory.  */
8438
8439 static void
8440 process_full_type_unit (struct dwarf2_per_cu_data *per_cu,
8441                         enum language pretend_language)
8442 {
8443   struct dwarf2_cu *cu = per_cu->cu;
8444   struct objfile *objfile = per_cu->objfile;
8445   struct compunit_symtab *cust;
8446   struct cleanup *back_to, *delayed_list_cleanup;
8447   struct signatured_type *sig_type;
8448
8449   gdb_assert (per_cu->is_debug_types);
8450   sig_type = (struct signatured_type *) per_cu;
8451
8452   buildsym_init ();
8453   back_to = make_cleanup (really_free_pendings, NULL);
8454   delayed_list_cleanup = make_cleanup (free_delayed_list, cu);
8455
8456   cu->list_in_scope = &file_symbols;
8457
8458   cu->language = pretend_language;
8459   cu->language_defn = language_def (cu->language);
8460
8461   /* The symbol tables are set up in read_type_unit_scope.  */
8462   process_die (cu->dies, cu);
8463
8464   /* For now fudge the Go package.  */
8465   if (cu->language == language_go)
8466     fixup_go_packaging (cu);
8467
8468   /* Now that we have processed all the DIEs in the CU, all the types 
8469      should be complete, and it should now be safe to compute all of the
8470      physnames.  */
8471   compute_delayed_physnames (cu);
8472   do_cleanups (delayed_list_cleanup);
8473
8474   /* TUs share symbol tables.
8475      If this is the first TU to use this symtab, complete the construction
8476      of it with end_expandable_symtab.  Otherwise, complete the addition of
8477      this TU's symbols to the existing symtab.  */
8478   if (sig_type->type_unit_group->compunit_symtab == NULL)
8479     {
8480       cust = end_expandable_symtab (0, SECT_OFF_TEXT (objfile));
8481       sig_type->type_unit_group->compunit_symtab = cust;
8482
8483       if (cust != NULL)
8484         {
8485           /* Set symtab language to language from DW_AT_language.  If the
8486              compilation is from a C file generated by language preprocessors,
8487              do not set the language if it was already deduced by
8488              start_subfile.  */
8489           if (!(cu->language == language_c
8490                 && COMPUNIT_FILETABS (cust)->language != language_c))
8491             COMPUNIT_FILETABS (cust)->language = cu->language;
8492         }
8493     }
8494   else
8495     {
8496       augment_type_symtab ();
8497       cust = sig_type->type_unit_group->compunit_symtab;
8498     }
8499
8500   if (dwarf2_per_objfile->using_index)
8501     per_cu->v.quick->compunit_symtab = cust;
8502   else
8503     {
8504       struct partial_symtab *pst = per_cu->v.psymtab;
8505       pst->compunit_symtab = cust;
8506       pst->readin = 1;
8507     }
8508
8509   do_cleanups (back_to);
8510 }
8511
8512 /* Process an imported unit DIE.  */
8513
8514 static void
8515 process_imported_unit_die (struct die_info *die, struct dwarf2_cu *cu)
8516 {
8517   struct attribute *attr;
8518
8519   /* For now we don't handle imported units in type units.  */
8520   if (cu->per_cu->is_debug_types)
8521     {
8522       error (_("Dwarf Error: DW_TAG_imported_unit is not"
8523                " supported in type units [in module %s]"),
8524              objfile_name (cu->objfile));
8525     }
8526
8527   attr = dwarf2_attr (die, DW_AT_import, cu);
8528   if (attr != NULL)
8529     {
8530       sect_offset sect_off = dwarf2_get_ref_die_offset (attr);
8531       bool is_dwz = (attr->form == DW_FORM_GNU_ref_alt || cu->per_cu->is_dwz);
8532       dwarf2_per_cu_data *per_cu
8533         = dwarf2_find_containing_comp_unit (sect_off, is_dwz, cu->objfile);
8534
8535       /* If necessary, add it to the queue and load its DIEs.  */
8536       if (maybe_queue_comp_unit (cu, per_cu, cu->language))
8537         load_full_comp_unit (per_cu, cu->language);
8538
8539       VEC_safe_push (dwarf2_per_cu_ptr, cu->per_cu->imported_symtabs,
8540                      per_cu);
8541     }
8542 }
8543
8544 /* RAII object that represents a process_die scope: i.e.,
8545    starts/finishes processing a DIE.  */
8546 class process_die_scope
8547 {
8548 public:
8549   process_die_scope (die_info *die, dwarf2_cu *cu)
8550     : m_die (die), m_cu (cu)
8551   {
8552     /* We should only be processing DIEs not already in process.  */
8553     gdb_assert (!m_die->in_process);
8554     m_die->in_process = true;
8555   }
8556
8557   ~process_die_scope ()
8558   {
8559     m_die->in_process = false;
8560
8561     /* If we're done processing the DIE for the CU that owns the line
8562        header, we don't need the line header anymore.  */
8563     if (m_cu->line_header_die_owner == m_die)
8564       {
8565         delete m_cu->line_header;
8566         m_cu->line_header = NULL;
8567         m_cu->line_header_die_owner = NULL;
8568       }
8569   }
8570
8571 private:
8572   die_info *m_die;
8573   dwarf2_cu *m_cu;
8574 };
8575
8576 /* Process a die and its children.  */
8577
8578 static void
8579 process_die (struct die_info *die, struct dwarf2_cu *cu)
8580 {
8581   process_die_scope scope (die, cu);
8582
8583   switch (die->tag)
8584     {
8585     case DW_TAG_padding:
8586       break;
8587     case DW_TAG_compile_unit:
8588     case DW_TAG_partial_unit:
8589       read_file_scope (die, cu);
8590       break;
8591     case DW_TAG_type_unit:
8592       read_type_unit_scope (die, cu);
8593       break;
8594     case DW_TAG_subprogram:
8595     case DW_TAG_inlined_subroutine:
8596       read_func_scope (die, cu);
8597       break;
8598     case DW_TAG_lexical_block:
8599     case DW_TAG_try_block:
8600     case DW_TAG_catch_block:
8601       read_lexical_block_scope (die, cu);
8602       break;
8603     case DW_TAG_call_site:
8604     case DW_TAG_GNU_call_site:
8605       read_call_site_scope (die, cu);
8606       break;
8607     case DW_TAG_class_type:
8608     case DW_TAG_interface_type:
8609     case DW_TAG_structure_type:
8610     case DW_TAG_union_type:
8611       process_structure_scope (die, cu);
8612       break;
8613     case DW_TAG_enumeration_type:
8614       process_enumeration_scope (die, cu);
8615       break;
8616
8617     /* These dies have a type, but processing them does not create
8618        a symbol or recurse to process the children.  Therefore we can
8619        read them on-demand through read_type_die.  */
8620     case DW_TAG_subroutine_type:
8621     case DW_TAG_set_type:
8622     case DW_TAG_array_type:
8623     case DW_TAG_pointer_type:
8624     case DW_TAG_ptr_to_member_type:
8625     case DW_TAG_reference_type:
8626     case DW_TAG_rvalue_reference_type:
8627     case DW_TAG_string_type:
8628       break;
8629
8630     case DW_TAG_base_type:
8631     case DW_TAG_subrange_type:
8632     case DW_TAG_typedef:
8633       /* Add a typedef symbol for the type definition, if it has a
8634          DW_AT_name.  */
8635       new_symbol (die, read_type_die (die, cu), cu);
8636       break;
8637     case DW_TAG_common_block:
8638       read_common_block (die, cu);
8639       break;
8640     case DW_TAG_common_inclusion:
8641       break;
8642     case DW_TAG_namespace:
8643       cu->processing_has_namespace_info = 1;
8644       read_namespace (die, cu);
8645       break;
8646     case DW_TAG_module:
8647       cu->processing_has_namespace_info = 1;
8648       read_module (die, cu);
8649       break;
8650     case DW_TAG_imported_declaration:
8651       cu->processing_has_namespace_info = 1;
8652       if (read_namespace_alias (die, cu))
8653         break;
8654       /* The declaration is not a global namespace alias: fall through.  */
8655     case DW_TAG_imported_module:
8656       cu->processing_has_namespace_info = 1;
8657       if (die->child != NULL && (die->tag == DW_TAG_imported_declaration
8658                                  || cu->language != language_fortran))
8659         complaint (&symfile_complaints, _("Tag '%s' has unexpected children"),
8660                    dwarf_tag_name (die->tag));
8661       read_import_statement (die, cu);
8662       break;
8663
8664     case DW_TAG_imported_unit:
8665       process_imported_unit_die (die, cu);
8666       break;
8667
8668     default:
8669       new_symbol (die, NULL, cu);
8670       break;
8671     }
8672 }
8673 \f
8674 /* DWARF name computation.  */
8675
8676 /* A helper function for dwarf2_compute_name which determines whether DIE
8677    needs to have the name of the scope prepended to the name listed in the
8678    die.  */
8679
8680 static int
8681 die_needs_namespace (struct die_info *die, struct dwarf2_cu *cu)
8682 {
8683   struct attribute *attr;
8684
8685   switch (die->tag)
8686     {
8687     case DW_TAG_namespace:
8688     case DW_TAG_typedef:
8689     case DW_TAG_class_type:
8690     case DW_TAG_interface_type:
8691     case DW_TAG_structure_type:
8692     case DW_TAG_union_type:
8693     case DW_TAG_enumeration_type:
8694     case DW_TAG_enumerator:
8695     case DW_TAG_subprogram:
8696     case DW_TAG_inlined_subroutine:
8697     case DW_TAG_member:
8698     case DW_TAG_imported_declaration:
8699       return 1;
8700
8701     case DW_TAG_variable:
8702     case DW_TAG_constant:
8703       /* We only need to prefix "globally" visible variables.  These include
8704          any variable marked with DW_AT_external or any variable that
8705          lives in a namespace.  [Variables in anonymous namespaces
8706          require prefixing, but they are not DW_AT_external.]  */
8707
8708       if (dwarf2_attr (die, DW_AT_specification, cu))
8709         {
8710           struct dwarf2_cu *spec_cu = cu;
8711
8712           return die_needs_namespace (die_specification (die, &spec_cu),
8713                                       spec_cu);
8714         }
8715
8716       attr = dwarf2_attr (die, DW_AT_external, cu);
8717       if (attr == NULL && die->parent->tag != DW_TAG_namespace
8718           && die->parent->tag != DW_TAG_module)
8719         return 0;
8720       /* A variable in a lexical block of some kind does not need a
8721          namespace, even though in C++ such variables may be external
8722          and have a mangled name.  */
8723       if (die->parent->tag ==  DW_TAG_lexical_block
8724           || die->parent->tag ==  DW_TAG_try_block
8725           || die->parent->tag ==  DW_TAG_catch_block
8726           || die->parent->tag == DW_TAG_subprogram)
8727         return 0;
8728       return 1;
8729
8730     default:
8731       return 0;
8732     }
8733 }
8734
8735 /* Return the DIE's linkage name attribute, either DW_AT_linkage_name
8736    or DW_AT_MIPS_linkage_name.  Returns NULL if the attribute is not
8737    defined for the given DIE.  */
8738
8739 static struct attribute *
8740 dw2_linkage_name_attr (struct die_info *die, struct dwarf2_cu *cu)
8741 {
8742   struct attribute *attr;
8743
8744   attr = dwarf2_attr (die, DW_AT_linkage_name, cu);
8745   if (attr == NULL)
8746     attr = dwarf2_attr (die, DW_AT_MIPS_linkage_name, cu);
8747
8748   return attr;
8749 }
8750
8751 /* Return the DIE's linkage name as a string, either DW_AT_linkage_name
8752    or DW_AT_MIPS_linkage_name.  Returns NULL if the attribute is not
8753    defined for the given DIE.  */
8754
8755 static const char *
8756 dw2_linkage_name (struct die_info *die, struct dwarf2_cu *cu)
8757 {
8758   const char *linkage_name;
8759
8760   linkage_name = dwarf2_string_attr (die, DW_AT_linkage_name, cu);
8761   if (linkage_name == NULL)
8762     linkage_name = dwarf2_string_attr (die, DW_AT_MIPS_linkage_name, cu);
8763
8764   return linkage_name;
8765 }
8766
8767 /* Compute the fully qualified name of DIE in CU.  If PHYSNAME is nonzero,
8768    compute the physname for the object, which include a method's:
8769    - formal parameters (C++),
8770    - receiver type (Go),
8771
8772    The term "physname" is a bit confusing.
8773    For C++, for example, it is the demangled name.
8774    For Go, for example, it's the mangled name.
8775
8776    For Ada, return the DIE's linkage name rather than the fully qualified
8777    name.  PHYSNAME is ignored..
8778
8779    The result is allocated on the objfile_obstack and canonicalized.  */
8780
8781 static const char *
8782 dwarf2_compute_name (const char *name,
8783                      struct die_info *die, struct dwarf2_cu *cu,
8784                      int physname)
8785 {
8786   struct objfile *objfile = cu->objfile;
8787
8788   if (name == NULL)
8789     name = dwarf2_name (die, cu);
8790
8791   /* For Fortran GDB prefers DW_AT_*linkage_name for the physname if present
8792      but otherwise compute it by typename_concat inside GDB.
8793      FIXME: Actually this is not really true, or at least not always true.
8794      It's all very confusing.  SYMBOL_SET_NAMES doesn't try to demangle
8795      Fortran names because there is no mangling standard.  So new_symbol_full
8796      will set the demangled name to the result of dwarf2_full_name, and it is
8797      the demangled name that GDB uses if it exists.  */
8798   if (cu->language == language_ada
8799       || (cu->language == language_fortran && physname))
8800     {
8801       /* For Ada unit, we prefer the linkage name over the name, as
8802          the former contains the exported name, which the user expects
8803          to be able to reference.  Ideally, we want the user to be able
8804          to reference this entity using either natural or linkage name,
8805          but we haven't started looking at this enhancement yet.  */
8806       const char *linkage_name = dw2_linkage_name (die, cu);
8807
8808       if (linkage_name != NULL)
8809         return linkage_name;
8810     }
8811
8812   /* These are the only languages we know how to qualify names in.  */
8813   if (name != NULL
8814       && (cu->language == language_cplus
8815           || cu->language == language_fortran || cu->language == language_d
8816           || cu->language == language_rust))
8817     {
8818       if (die_needs_namespace (die, cu))
8819         {
8820           long length;
8821           const char *prefix;
8822           const char *canonical_name = NULL;
8823
8824           string_file buf;
8825
8826           prefix = determine_prefix (die, cu);
8827           if (*prefix != '\0')
8828             {
8829               char *prefixed_name = typename_concat (NULL, prefix, name,
8830                                                      physname, cu);
8831
8832               buf.puts (prefixed_name);
8833               xfree (prefixed_name);
8834             }
8835           else
8836             buf.puts (name);
8837
8838           /* Template parameters may be specified in the DIE's DW_AT_name, or
8839              as children with DW_TAG_template_type_param or
8840              DW_TAG_value_type_param.  If the latter, add them to the name
8841              here.  If the name already has template parameters, then
8842              skip this step; some versions of GCC emit both, and
8843              it is more efficient to use the pre-computed name.
8844
8845              Something to keep in mind about this process: it is very
8846              unlikely, or in some cases downright impossible, to produce
8847              something that will match the mangled name of a function.
8848              If the definition of the function has the same debug info,
8849              we should be able to match up with it anyway.  But fallbacks
8850              using the minimal symbol, for instance to find a method
8851              implemented in a stripped copy of libstdc++, will not work.
8852              If we do not have debug info for the definition, we will have to
8853              match them up some other way.
8854
8855              When we do name matching there is a related problem with function
8856              templates; two instantiated function templates are allowed to
8857              differ only by their return types, which we do not add here.  */
8858
8859           if (cu->language == language_cplus && strchr (name, '<') == NULL)
8860             {
8861               struct attribute *attr;
8862               struct die_info *child;
8863               int first = 1;
8864
8865               die->building_fullname = 1;
8866
8867               for (child = die->child; child != NULL; child = child->sibling)
8868                 {
8869                   struct type *type;
8870                   LONGEST value;
8871                   const gdb_byte *bytes;
8872                   struct dwarf2_locexpr_baton *baton;
8873                   struct value *v;
8874
8875                   if (child->tag != DW_TAG_template_type_param
8876                       && child->tag != DW_TAG_template_value_param)
8877                     continue;
8878
8879                   if (first)
8880                     {
8881                       buf.puts ("<");
8882                       first = 0;
8883                     }
8884                   else
8885                     buf.puts (", ");
8886
8887                   attr = dwarf2_attr (child, DW_AT_type, cu);
8888                   if (attr == NULL)
8889                     {
8890                       complaint (&symfile_complaints,
8891                                  _("template parameter missing DW_AT_type"));
8892                       buf.puts ("UNKNOWN_TYPE");
8893                       continue;
8894                     }
8895                   type = die_type (child, cu);
8896
8897                   if (child->tag == DW_TAG_template_type_param)
8898                     {
8899                       c_print_type (type, "", &buf, -1, 0, &type_print_raw_options);
8900                       continue;
8901                     }
8902
8903                   attr = dwarf2_attr (child, DW_AT_const_value, cu);
8904                   if (attr == NULL)
8905                     {
8906                       complaint (&symfile_complaints,
8907                                  _("template parameter missing "
8908                                    "DW_AT_const_value"));
8909                       buf.puts ("UNKNOWN_VALUE");
8910                       continue;
8911                     }
8912
8913                   dwarf2_const_value_attr (attr, type, name,
8914                                            &cu->comp_unit_obstack, cu,
8915                                            &value, &bytes, &baton);
8916
8917                   if (TYPE_NOSIGN (type))
8918                     /* GDB prints characters as NUMBER 'CHAR'.  If that's
8919                        changed, this can use value_print instead.  */
8920                     c_printchar (value, type, &buf);
8921                   else
8922                     {
8923                       struct value_print_options opts;
8924
8925                       if (baton != NULL)
8926                         v = dwarf2_evaluate_loc_desc (type, NULL,
8927                                                       baton->data,
8928                                                       baton->size,
8929                                                       baton->per_cu);
8930                       else if (bytes != NULL)
8931                         {
8932                           v = allocate_value (type);
8933                           memcpy (value_contents_writeable (v), bytes,
8934                                   TYPE_LENGTH (type));
8935                         }
8936                       else
8937                         v = value_from_longest (type, value);
8938
8939                       /* Specify decimal so that we do not depend on
8940                          the radix.  */
8941                       get_formatted_print_options (&opts, 'd');
8942                       opts.raw = 1;
8943                       value_print (v, &buf, &opts);
8944                       release_value (v);
8945                       value_free (v);
8946                     }
8947                 }
8948
8949               die->building_fullname = 0;
8950
8951               if (!first)
8952                 {
8953                   /* Close the argument list, with a space if necessary
8954                      (nested templates).  */
8955                   if (!buf.empty () && buf.string ().back () == '>')
8956                     buf.puts (" >");
8957                   else
8958                     buf.puts (">");
8959                 }
8960             }
8961
8962           /* For C++ methods, append formal parameter type
8963              information, if PHYSNAME.  */
8964
8965           if (physname && die->tag == DW_TAG_subprogram
8966               && cu->language == language_cplus)
8967             {
8968               struct type *type = read_type_die (die, cu);
8969
8970               c_type_print_args (type, &buf, 1, cu->language,
8971                                  &type_print_raw_options);
8972
8973               if (cu->language == language_cplus)
8974                 {
8975                   /* Assume that an artificial first parameter is
8976                      "this", but do not crash if it is not.  RealView
8977                      marks unnamed (and thus unused) parameters as
8978                      artificial; there is no way to differentiate
8979                      the two cases.  */
8980                   if (TYPE_NFIELDS (type) > 0
8981                       && TYPE_FIELD_ARTIFICIAL (type, 0)
8982                       && TYPE_CODE (TYPE_FIELD_TYPE (type, 0)) == TYPE_CODE_PTR
8983                       && TYPE_CONST (TYPE_TARGET_TYPE (TYPE_FIELD_TYPE (type,
8984                                                                         0))))
8985                     buf.puts (" const");
8986                 }
8987             }
8988
8989           const std::string &intermediate_name = buf.string ();
8990
8991           if (cu->language == language_cplus)
8992             canonical_name
8993               = dwarf2_canonicalize_name (intermediate_name.c_str (), cu,
8994                                           &objfile->per_bfd->storage_obstack);
8995
8996           /* If we only computed INTERMEDIATE_NAME, or if
8997              INTERMEDIATE_NAME is already canonical, then we need to
8998              copy it to the appropriate obstack.  */
8999           if (canonical_name == NULL || canonical_name == intermediate_name.c_str ())
9000             name = ((const char *)
9001                     obstack_copy0 (&objfile->per_bfd->storage_obstack,
9002                                    intermediate_name.c_str (),
9003                                    intermediate_name.length ()));
9004           else
9005             name = canonical_name;
9006         }
9007     }
9008
9009   return name;
9010 }
9011
9012 /* Return the fully qualified name of DIE, based on its DW_AT_name.
9013    If scope qualifiers are appropriate they will be added.  The result
9014    will be allocated on the storage_obstack, or NULL if the DIE does
9015    not have a name.  NAME may either be from a previous call to
9016    dwarf2_name or NULL.
9017
9018    The output string will be canonicalized (if C++).  */
9019
9020 static const char *
9021 dwarf2_full_name (const char *name, struct die_info *die, struct dwarf2_cu *cu)
9022 {
9023   return dwarf2_compute_name (name, die, cu, 0);
9024 }
9025
9026 /* Construct a physname for the given DIE in CU.  NAME may either be
9027    from a previous call to dwarf2_name or NULL.  The result will be
9028    allocated on the objfile_objstack or NULL if the DIE does not have a
9029    name.
9030
9031    The output string will be canonicalized (if C++).  */
9032
9033 static const char *
9034 dwarf2_physname (const char *name, struct die_info *die, struct dwarf2_cu *cu)
9035 {
9036   struct objfile *objfile = cu->objfile;
9037   const char *retval, *mangled = NULL, *canon = NULL;
9038   struct cleanup *back_to;
9039   int need_copy = 1;
9040
9041   /* In this case dwarf2_compute_name is just a shortcut not building anything
9042      on its own.  */
9043   if (!die_needs_namespace (die, cu))
9044     return dwarf2_compute_name (name, die, cu, 1);
9045
9046   back_to = make_cleanup (null_cleanup, NULL);
9047
9048   mangled = dw2_linkage_name (die, cu);
9049
9050   /* rustc emits invalid values for DW_AT_linkage_name.  Ignore these.
9051      See https://github.com/rust-lang/rust/issues/32925.  */
9052   if (cu->language == language_rust && mangled != NULL
9053       && strchr (mangled, '{') != NULL)
9054     mangled = NULL;
9055
9056   /* DW_AT_linkage_name is missing in some cases - depend on what GDB
9057      has computed.  */
9058   if (mangled != NULL)
9059     {
9060       char *demangled;
9061
9062       /* Use DMGL_RET_DROP for C++ template functions to suppress their return
9063          type.  It is easier for GDB users to search for such functions as
9064          `name(params)' than `long name(params)'.  In such case the minimal
9065          symbol names do not match the full symbol names but for template
9066          functions there is never a need to look up their definition from their
9067          declaration so the only disadvantage remains the minimal symbol
9068          variant `long name(params)' does not have the proper inferior type.
9069          */
9070
9071       if (cu->language == language_go)
9072         {
9073           /* This is a lie, but we already lie to the caller new_symbol_full.
9074              new_symbol_full assumes we return the mangled name.
9075              This just undoes that lie until things are cleaned up.  */
9076           demangled = NULL;
9077         }
9078       else
9079         {
9080           demangled = gdb_demangle (mangled,
9081                                     (DMGL_PARAMS | DMGL_ANSI | DMGL_RET_DROP));
9082         }
9083       if (demangled)
9084         {
9085           make_cleanup (xfree, demangled);
9086           canon = demangled;
9087         }
9088       else
9089         {
9090           canon = mangled;
9091           need_copy = 0;
9092         }
9093     }
9094
9095   if (canon == NULL || check_physname)
9096     {
9097       const char *physname = dwarf2_compute_name (name, die, cu, 1);
9098
9099       if (canon != NULL && strcmp (physname, canon) != 0)
9100         {
9101           /* It may not mean a bug in GDB.  The compiler could also
9102              compute DW_AT_linkage_name incorrectly.  But in such case
9103              GDB would need to be bug-to-bug compatible.  */
9104
9105           complaint (&symfile_complaints,
9106                      _("Computed physname <%s> does not match demangled <%s> "
9107                        "(from linkage <%s>) - DIE at 0x%x [in module %s]"),
9108                      physname, canon, mangled, to_underlying (die->sect_off),
9109                      objfile_name (objfile));
9110
9111           /* Prefer DW_AT_linkage_name (in the CANON form) - when it
9112              is available here - over computed PHYSNAME.  It is safer
9113              against both buggy GDB and buggy compilers.  */
9114
9115           retval = canon;
9116         }
9117       else
9118         {
9119           retval = physname;
9120           need_copy = 0;
9121         }
9122     }
9123   else
9124     retval = canon;
9125
9126   if (need_copy)
9127     retval = ((const char *)
9128               obstack_copy0 (&objfile->per_bfd->storage_obstack,
9129                              retval, strlen (retval)));
9130
9131   do_cleanups (back_to);
9132   return retval;
9133 }
9134
9135 /* Inspect DIE in CU for a namespace alias.  If one exists, record
9136    a new symbol for it.
9137
9138    Returns 1 if a namespace alias was recorded, 0 otherwise.  */
9139
9140 static int
9141 read_namespace_alias (struct die_info *die, struct dwarf2_cu *cu)
9142 {
9143   struct attribute *attr;
9144
9145   /* If the die does not have a name, this is not a namespace
9146      alias.  */
9147   attr = dwarf2_attr (die, DW_AT_name, cu);
9148   if (attr != NULL)
9149     {
9150       int num;
9151       struct die_info *d = die;
9152       struct dwarf2_cu *imported_cu = cu;
9153
9154       /* If the compiler has nested DW_AT_imported_declaration DIEs,
9155          keep inspecting DIEs until we hit the underlying import.  */
9156 #define MAX_NESTED_IMPORTED_DECLARATIONS 100
9157       for (num = 0; num  < MAX_NESTED_IMPORTED_DECLARATIONS; ++num)
9158         {
9159           attr = dwarf2_attr (d, DW_AT_import, cu);
9160           if (attr == NULL)
9161             break;
9162
9163           d = follow_die_ref (d, attr, &imported_cu);
9164           if (d->tag != DW_TAG_imported_declaration)
9165             break;
9166         }
9167
9168       if (num == MAX_NESTED_IMPORTED_DECLARATIONS)
9169         {
9170           complaint (&symfile_complaints,
9171                      _("DIE at 0x%x has too many recursively imported "
9172                        "declarations"), to_underlying (d->sect_off));
9173           return 0;
9174         }
9175
9176       if (attr != NULL)
9177         {
9178           struct type *type;
9179           sect_offset sect_off = dwarf2_get_ref_die_offset (attr);
9180
9181           type = get_die_type_at_offset (sect_off, cu->per_cu);
9182           if (type != NULL && TYPE_CODE (type) == TYPE_CODE_NAMESPACE)
9183             {
9184               /* This declaration is a global namespace alias.  Add
9185                  a symbol for it whose type is the aliased namespace.  */
9186               new_symbol (die, type, cu);
9187               return 1;
9188             }
9189         }
9190     }
9191
9192   return 0;
9193 }
9194
9195 /* Return the using directives repository (global or local?) to use in the
9196    current context for LANGUAGE.
9197
9198    For Ada, imported declarations can materialize renamings, which *may* be
9199    global.  However it is impossible (for now?) in DWARF to distinguish
9200    "external" imported declarations and "static" ones.  As all imported
9201    declarations seem to be static in all other languages, make them all CU-wide
9202    global only in Ada.  */
9203
9204 static struct using_direct **
9205 using_directives (enum language language)
9206 {
9207   if (language == language_ada && context_stack_depth == 0)
9208     return &global_using_directives;
9209   else
9210     return &local_using_directives;
9211 }
9212
9213 /* Read the import statement specified by the given die and record it.  */
9214
9215 static void
9216 read_import_statement (struct die_info *die, struct dwarf2_cu *cu)
9217 {
9218   struct objfile *objfile = cu->objfile;
9219   struct attribute *import_attr;
9220   struct die_info *imported_die, *child_die;
9221   struct dwarf2_cu *imported_cu;
9222   const char *imported_name;
9223   const char *imported_name_prefix;
9224   const char *canonical_name;
9225   const char *import_alias;
9226   const char *imported_declaration = NULL;
9227   const char *import_prefix;
9228   VEC (const_char_ptr) *excludes = NULL;
9229   struct cleanup *cleanups;
9230
9231   import_attr = dwarf2_attr (die, DW_AT_import, cu);
9232   if (import_attr == NULL)
9233     {
9234       complaint (&symfile_complaints, _("Tag '%s' has no DW_AT_import"),
9235                  dwarf_tag_name (die->tag));
9236       return;
9237     }
9238
9239   imported_cu = cu;
9240   imported_die = follow_die_ref_or_sig (die, import_attr, &imported_cu);
9241   imported_name = dwarf2_name (imported_die, imported_cu);
9242   if (imported_name == NULL)
9243     {
9244       /* GCC bug: https://bugzilla.redhat.com/show_bug.cgi?id=506524
9245
9246         The import in the following code:
9247         namespace A
9248           {
9249             typedef int B;
9250           }
9251
9252         int main ()
9253           {
9254             using A::B;
9255             B b;
9256             return b;
9257           }
9258
9259         ...
9260          <2><51>: Abbrev Number: 3 (DW_TAG_imported_declaration)
9261             <52>   DW_AT_decl_file   : 1
9262             <53>   DW_AT_decl_line   : 6
9263             <54>   DW_AT_import      : <0x75>
9264          <2><58>: Abbrev Number: 4 (DW_TAG_typedef)
9265             <59>   DW_AT_name        : B
9266             <5b>   DW_AT_decl_file   : 1
9267             <5c>   DW_AT_decl_line   : 2
9268             <5d>   DW_AT_type        : <0x6e>
9269         ...
9270          <1><75>: Abbrev Number: 7 (DW_TAG_base_type)
9271             <76>   DW_AT_byte_size   : 4
9272             <77>   DW_AT_encoding    : 5        (signed)
9273
9274         imports the wrong die ( 0x75 instead of 0x58 ).
9275         This case will be ignored until the gcc bug is fixed.  */
9276       return;
9277     }
9278
9279   /* Figure out the local name after import.  */
9280   import_alias = dwarf2_name (die, cu);
9281
9282   /* Figure out where the statement is being imported to.  */
9283   import_prefix = determine_prefix (die, cu);
9284
9285   /* Figure out what the scope of the imported die is and prepend it
9286      to the name of the imported die.  */
9287   imported_name_prefix = determine_prefix (imported_die, imported_cu);
9288
9289   if (imported_die->tag != DW_TAG_namespace
9290       && imported_die->tag != DW_TAG_module)
9291     {
9292       imported_declaration = imported_name;
9293       canonical_name = imported_name_prefix;
9294     }
9295   else if (strlen (imported_name_prefix) > 0)
9296     canonical_name = obconcat (&objfile->objfile_obstack,
9297                                imported_name_prefix,
9298                                (cu->language == language_d ? "." : "::"),
9299                                imported_name, (char *) NULL);
9300   else
9301     canonical_name = imported_name;
9302
9303   cleanups = make_cleanup (VEC_cleanup (const_char_ptr), &excludes);
9304
9305   if (die->tag == DW_TAG_imported_module && cu->language == language_fortran)
9306     for (child_die = die->child; child_die && child_die->tag;
9307          child_die = sibling_die (child_die))
9308       {
9309         /* DWARF-4: A Fortran use statement with a “rename list” may be
9310            represented by an imported module entry with an import attribute
9311            referring to the module and owned entries corresponding to those
9312            entities that are renamed as part of being imported.  */
9313
9314         if (child_die->tag != DW_TAG_imported_declaration)
9315           {
9316             complaint (&symfile_complaints,
9317                        _("child DW_TAG_imported_declaration expected "
9318                          "- DIE at 0x%x [in module %s]"),
9319                        to_underlying (child_die->sect_off), objfile_name (objfile));
9320             continue;
9321           }
9322
9323         import_attr = dwarf2_attr (child_die, DW_AT_import, cu);
9324         if (import_attr == NULL)
9325           {
9326             complaint (&symfile_complaints, _("Tag '%s' has no DW_AT_import"),
9327                        dwarf_tag_name (child_die->tag));
9328             continue;
9329           }
9330
9331         imported_cu = cu;
9332         imported_die = follow_die_ref_or_sig (child_die, import_attr,
9333                                               &imported_cu);
9334         imported_name = dwarf2_name (imported_die, imported_cu);
9335         if (imported_name == NULL)
9336           {
9337             complaint (&symfile_complaints,
9338                        _("child DW_TAG_imported_declaration has unknown "
9339                          "imported name - DIE at 0x%x [in module %s]"),
9340                        to_underlying (child_die->sect_off), objfile_name (objfile));
9341             continue;
9342           }
9343
9344         VEC_safe_push (const_char_ptr, excludes, imported_name);
9345
9346         process_die (child_die, cu);
9347       }
9348
9349   add_using_directive (using_directives (cu->language),
9350                        import_prefix,
9351                        canonical_name,
9352                        import_alias,
9353                        imported_declaration,
9354                        excludes,
9355                        0,
9356                        &objfile->objfile_obstack);
9357
9358   do_cleanups (cleanups);
9359 }
9360
9361 /* Check for possibly missing DW_AT_comp_dir with relative .debug_line
9362    directory paths.  GCC SVN r127613 (new option -fdebug-prefix-map) fixed
9363    this, it was first present in GCC release 4.3.0.  */
9364
9365 static int
9366 producer_is_gcc_lt_4_3 (struct dwarf2_cu *cu)
9367 {
9368   if (!cu->checked_producer)
9369     check_producer (cu);
9370
9371   return cu->producer_is_gcc_lt_4_3;
9372 }
9373
9374 static file_and_directory
9375 find_file_and_directory (struct die_info *die, struct dwarf2_cu *cu)
9376 {
9377   file_and_directory res;
9378
9379   /* Find the filename.  Do not use dwarf2_name here, since the filename
9380      is not a source language identifier.  */
9381   res.name = dwarf2_string_attr (die, DW_AT_name, cu);
9382   res.comp_dir = dwarf2_string_attr (die, DW_AT_comp_dir, cu);
9383
9384   if (res.comp_dir == NULL
9385       && producer_is_gcc_lt_4_3 (cu) && res.name != NULL
9386       && IS_ABSOLUTE_PATH (res.name))
9387     {
9388       res.comp_dir_storage = ldirname (res.name);
9389       if (!res.comp_dir_storage.empty ())
9390         res.comp_dir = res.comp_dir_storage.c_str ();
9391     }
9392   if (res.comp_dir != NULL)
9393     {
9394       /* Irix 6.2 native cc prepends <machine>.: to the compilation
9395          directory, get rid of it.  */
9396       const char *cp = strchr (res.comp_dir, ':');
9397
9398       if (cp && cp != res.comp_dir && cp[-1] == '.' && cp[1] == '/')
9399         res.comp_dir = cp + 1;
9400     }
9401
9402   if (res.name == NULL)
9403     res.name = "<unknown>";
9404
9405   return res;
9406 }
9407
9408 /* Handle DW_AT_stmt_list for a compilation unit.
9409    DIE is the DW_TAG_compile_unit die for CU.
9410    COMP_DIR is the compilation directory.  LOWPC is passed to
9411    dwarf_decode_lines.  See dwarf_decode_lines comments about it.  */
9412
9413 static void
9414 handle_DW_AT_stmt_list (struct die_info *die, struct dwarf2_cu *cu,
9415                         const char *comp_dir, CORE_ADDR lowpc) /* ARI: editCase function */
9416 {
9417   struct objfile *objfile = dwarf2_per_objfile->objfile;
9418   struct attribute *attr;
9419   struct line_header line_header_local;
9420   hashval_t line_header_local_hash;
9421   unsigned u;
9422   void **slot;
9423   int decode_mapping;
9424
9425   gdb_assert (! cu->per_cu->is_debug_types);
9426
9427   attr = dwarf2_attr (die, DW_AT_stmt_list, cu);
9428   if (attr == NULL)
9429     return;
9430
9431   sect_offset line_offset = (sect_offset) DW_UNSND (attr);
9432
9433   /* The line header hash table is only created if needed (it exists to
9434      prevent redundant reading of the line table for partial_units).
9435      If we're given a partial_unit, we'll need it.  If we're given a
9436      compile_unit, then use the line header hash table if it's already
9437      created, but don't create one just yet.  */
9438
9439   if (dwarf2_per_objfile->line_header_hash == NULL
9440       && die->tag == DW_TAG_partial_unit)
9441     {
9442       dwarf2_per_objfile->line_header_hash
9443         = htab_create_alloc_ex (127, line_header_hash_voidp,
9444                                 line_header_eq_voidp,
9445                                 free_line_header_voidp,
9446                                 &objfile->objfile_obstack,
9447                                 hashtab_obstack_allocate,
9448                                 dummy_obstack_deallocate);
9449     }
9450
9451   line_header_local.sect_off = line_offset;
9452   line_header_local.offset_in_dwz = cu->per_cu->is_dwz;
9453   line_header_local_hash = line_header_hash (&line_header_local);
9454   if (dwarf2_per_objfile->line_header_hash != NULL)
9455     {
9456       slot = htab_find_slot_with_hash (dwarf2_per_objfile->line_header_hash,
9457                                        &line_header_local,
9458                                        line_header_local_hash, NO_INSERT);
9459
9460       /* For DW_TAG_compile_unit we need info like symtab::linetable which
9461          is not present in *SLOT (since if there is something in *SLOT then
9462          it will be for a partial_unit).  */
9463       if (die->tag == DW_TAG_partial_unit && slot != NULL)
9464         {
9465           gdb_assert (*slot != NULL);
9466           cu->line_header = (struct line_header *) *slot;
9467           return;
9468         }
9469     }
9470
9471   /* dwarf_decode_line_header does not yet provide sufficient information.
9472      We always have to call also dwarf_decode_lines for it.  */
9473   line_header_up lh = dwarf_decode_line_header (line_offset, cu);
9474   if (lh == NULL)
9475     return;
9476
9477   cu->line_header = lh.release ();
9478   cu->line_header_die_owner = die;
9479
9480   if (dwarf2_per_objfile->line_header_hash == NULL)
9481     slot = NULL;
9482   else
9483     {
9484       slot = htab_find_slot_with_hash (dwarf2_per_objfile->line_header_hash,
9485                                        &line_header_local,
9486                                        line_header_local_hash, INSERT);
9487       gdb_assert (slot != NULL);
9488     }
9489   if (slot != NULL && *slot == NULL)
9490     {
9491       /* This newly decoded line number information unit will be owned
9492          by line_header_hash hash table.  */
9493       *slot = cu->line_header;
9494       cu->line_header_die_owner = NULL;
9495     }
9496   else
9497     {
9498       /* We cannot free any current entry in (*slot) as that struct line_header
9499          may be already used by multiple CUs.  Create only temporary decoded
9500          line_header for this CU - it may happen at most once for each line
9501          number information unit.  And if we're not using line_header_hash
9502          then this is what we want as well.  */
9503       gdb_assert (die->tag != DW_TAG_partial_unit);
9504     }
9505   decode_mapping = (die->tag != DW_TAG_partial_unit);
9506   dwarf_decode_lines (cu->line_header, comp_dir, cu, NULL, lowpc,
9507                       decode_mapping);
9508
9509 }
9510
9511 /* Process DW_TAG_compile_unit or DW_TAG_partial_unit.  */
9512
9513 static void
9514 read_file_scope (struct die_info *die, struct dwarf2_cu *cu)
9515 {
9516   struct objfile *objfile = dwarf2_per_objfile->objfile;
9517   struct gdbarch *gdbarch = get_objfile_arch (objfile);
9518   CORE_ADDR lowpc = ((CORE_ADDR) -1);
9519   CORE_ADDR highpc = ((CORE_ADDR) 0);
9520   struct attribute *attr;
9521   struct die_info *child_die;
9522   CORE_ADDR baseaddr;
9523
9524   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
9525
9526   get_scope_pc_bounds (die, &lowpc, &highpc, cu);
9527
9528   /* If we didn't find a lowpc, set it to highpc to avoid complaints
9529      from finish_block.  */
9530   if (lowpc == ((CORE_ADDR) -1))
9531     lowpc = highpc;
9532   lowpc = gdbarch_adjust_dwarf2_addr (gdbarch, lowpc + baseaddr);
9533
9534   file_and_directory fnd = find_file_and_directory (die, cu);
9535
9536   prepare_one_comp_unit (cu, die, cu->language);
9537
9538   /* The XLCL doesn't generate DW_LANG_OpenCL because this attribute is not
9539      standardised yet.  As a workaround for the language detection we fall
9540      back to the DW_AT_producer string.  */
9541   if (cu->producer && strstr (cu->producer, "IBM XL C for OpenCL") != NULL)
9542     cu->language = language_opencl;
9543
9544   /* Similar hack for Go.  */
9545   if (cu->producer && strstr (cu->producer, "GNU Go ") != NULL)
9546     set_cu_language (DW_LANG_Go, cu);
9547
9548   dwarf2_start_symtab (cu, fnd.name, fnd.comp_dir, lowpc);
9549
9550   /* Decode line number information if present.  We do this before
9551      processing child DIEs, so that the line header table is available
9552      for DW_AT_decl_file.  */
9553   handle_DW_AT_stmt_list (die, cu, fnd.comp_dir, lowpc);
9554
9555   /* Process all dies in compilation unit.  */
9556   if (die->child != NULL)
9557     {
9558       child_die = die->child;
9559       while (child_die && child_die->tag)
9560         {
9561           process_die (child_die, cu);
9562           child_die = sibling_die (child_die);
9563         }
9564     }
9565
9566   /* Decode macro information, if present.  Dwarf 2 macro information
9567      refers to information in the line number info statement program
9568      header, so we can only read it if we've read the header
9569      successfully.  */
9570   attr = dwarf2_attr (die, DW_AT_macros, cu);
9571   if (attr == NULL)
9572     attr = dwarf2_attr (die, DW_AT_GNU_macros, cu);
9573   if (attr && cu->line_header)
9574     {
9575       if (dwarf2_attr (die, DW_AT_macro_info, cu))
9576         complaint (&symfile_complaints,
9577                    _("CU refers to both DW_AT_macros and DW_AT_macro_info"));
9578
9579       dwarf_decode_macros (cu, DW_UNSND (attr), 1);
9580     }
9581   else
9582     {
9583       attr = dwarf2_attr (die, DW_AT_macro_info, cu);
9584       if (attr && cu->line_header)
9585         {
9586           unsigned int macro_offset = DW_UNSND (attr);
9587
9588           dwarf_decode_macros (cu, macro_offset, 0);
9589         }
9590     }
9591 }
9592
9593 /* TU version of handle_DW_AT_stmt_list for read_type_unit_scope.
9594    Create the set of symtabs used by this TU, or if this TU is sharing
9595    symtabs with another TU and the symtabs have already been created
9596    then restore those symtabs in the line header.
9597    We don't need the pc/line-number mapping for type units.  */
9598
9599 static void
9600 setup_type_unit_groups (struct die_info *die, struct dwarf2_cu *cu)
9601 {
9602   struct dwarf2_per_cu_data *per_cu = cu->per_cu;
9603   struct type_unit_group *tu_group;
9604   int first_time;
9605   struct attribute *attr;
9606   unsigned int i;
9607   struct signatured_type *sig_type;
9608
9609   gdb_assert (per_cu->is_debug_types);
9610   sig_type = (struct signatured_type *) per_cu;
9611
9612   attr = dwarf2_attr (die, DW_AT_stmt_list, cu);
9613
9614   /* If we're using .gdb_index (includes -readnow) then
9615      per_cu->type_unit_group may not have been set up yet.  */
9616   if (sig_type->type_unit_group == NULL)
9617     sig_type->type_unit_group = get_type_unit_group (cu, attr);
9618   tu_group = sig_type->type_unit_group;
9619
9620   /* If we've already processed this stmt_list there's no real need to
9621      do it again, we could fake it and just recreate the part we need
9622      (file name,index -> symtab mapping).  If data shows this optimization
9623      is useful we can do it then.  */
9624   first_time = tu_group->compunit_symtab == NULL;
9625
9626   /* We have to handle the case of both a missing DW_AT_stmt_list or bad
9627      debug info.  */
9628   line_header_up lh;
9629   if (attr != NULL)
9630     {
9631       sect_offset line_offset = (sect_offset) DW_UNSND (attr);
9632       lh = dwarf_decode_line_header (line_offset, cu);
9633     }
9634   if (lh == NULL)
9635     {
9636       if (first_time)
9637         dwarf2_start_symtab (cu, "", NULL, 0);
9638       else
9639         {
9640           gdb_assert (tu_group->symtabs == NULL);
9641           restart_symtab (tu_group->compunit_symtab, "", 0);
9642         }
9643       return;
9644     }
9645
9646   cu->line_header = lh.release ();
9647   cu->line_header_die_owner = die;
9648
9649   if (first_time)
9650     {
9651       struct compunit_symtab *cust = dwarf2_start_symtab (cu, "", NULL, 0);
9652
9653       /* Note: We don't assign tu_group->compunit_symtab yet because we're
9654          still initializing it, and our caller (a few levels up)
9655          process_full_type_unit still needs to know if this is the first
9656          time.  */
9657
9658       tu_group->num_symtabs = cu->line_header->file_names.size ();
9659       tu_group->symtabs = XNEWVEC (struct symtab *,
9660                                    cu->line_header->file_names.size ());
9661
9662       for (i = 0; i < cu->line_header->file_names.size (); ++i)
9663         {
9664           file_entry &fe = cu->line_header->file_names[i];
9665
9666           dwarf2_start_subfile (fe.name, fe.include_dir (cu->line_header));
9667
9668           if (current_subfile->symtab == NULL)
9669             {
9670               /* NOTE: start_subfile will recognize when it's been
9671                  passed a file it has already seen.  So we can't
9672                  assume there's a simple mapping from
9673                  cu->line_header->file_names to subfiles, plus
9674                  cu->line_header->file_names may contain dups.  */
9675               current_subfile->symtab
9676                 = allocate_symtab (cust, current_subfile->name);
9677             }
9678
9679           fe.symtab = current_subfile->symtab;
9680           tu_group->symtabs[i] = fe.symtab;
9681         }
9682     }
9683   else
9684     {
9685       restart_symtab (tu_group->compunit_symtab, "", 0);
9686
9687       for (i = 0; i < cu->line_header->file_names.size (); ++i)
9688         {
9689           file_entry &fe = cu->line_header->file_names[i];
9690
9691           fe.symtab = tu_group->symtabs[i];
9692         }
9693     }
9694
9695   /* The main symtab is allocated last.  Type units don't have DW_AT_name
9696      so they don't have a "real" (so to speak) symtab anyway.
9697      There is later code that will assign the main symtab to all symbols
9698      that don't have one.  We need to handle the case of a symbol with a
9699      missing symtab (DW_AT_decl_file) anyway.  */
9700 }
9701
9702 /* Process DW_TAG_type_unit.
9703    For TUs we want to skip the first top level sibling if it's not the
9704    actual type being defined by this TU.  In this case the first top
9705    level sibling is there to provide context only.  */
9706
9707 static void
9708 read_type_unit_scope (struct die_info *die, struct dwarf2_cu *cu)
9709 {
9710   struct die_info *child_die;
9711
9712   prepare_one_comp_unit (cu, die, language_minimal);
9713
9714   /* Initialize (or reinitialize) the machinery for building symtabs.
9715      We do this before processing child DIEs, so that the line header table
9716      is available for DW_AT_decl_file.  */
9717   setup_type_unit_groups (die, cu);
9718
9719   if (die->child != NULL)
9720     {
9721       child_die = die->child;
9722       while (child_die && child_die->tag)
9723         {
9724           process_die (child_die, cu);
9725           child_die = sibling_die (child_die);
9726         }
9727     }
9728 }
9729 \f
9730 /* DWO/DWP files.
9731
9732    http://gcc.gnu.org/wiki/DebugFission
9733    http://gcc.gnu.org/wiki/DebugFissionDWP
9734
9735    To simplify handling of both DWO files ("object" files with the DWARF info)
9736    and DWP files (a file with the DWOs packaged up into one file), we treat
9737    DWP files as having a collection of virtual DWO files.  */
9738
9739 static hashval_t
9740 hash_dwo_file (const void *item)
9741 {
9742   const struct dwo_file *dwo_file = (const struct dwo_file *) item;
9743   hashval_t hash;
9744
9745   hash = htab_hash_string (dwo_file->dwo_name);
9746   if (dwo_file->comp_dir != NULL)
9747     hash += htab_hash_string (dwo_file->comp_dir);
9748   return hash;
9749 }
9750
9751 static int
9752 eq_dwo_file (const void *item_lhs, const void *item_rhs)
9753 {
9754   const struct dwo_file *lhs = (const struct dwo_file *) item_lhs;
9755   const struct dwo_file *rhs = (const struct dwo_file *) item_rhs;
9756
9757   if (strcmp (lhs->dwo_name, rhs->dwo_name) != 0)
9758     return 0;
9759   if (lhs->comp_dir == NULL || rhs->comp_dir == NULL)
9760     return lhs->comp_dir == rhs->comp_dir;
9761   return strcmp (lhs->comp_dir, rhs->comp_dir) == 0;
9762 }
9763
9764 /* Allocate a hash table for DWO files.  */
9765
9766 static htab_t
9767 allocate_dwo_file_hash_table (void)
9768 {
9769   struct objfile *objfile = dwarf2_per_objfile->objfile;
9770
9771   return htab_create_alloc_ex (41,
9772                                hash_dwo_file,
9773                                eq_dwo_file,
9774                                NULL,
9775                                &objfile->objfile_obstack,
9776                                hashtab_obstack_allocate,
9777                                dummy_obstack_deallocate);
9778 }
9779
9780 /* Lookup DWO file DWO_NAME.  */
9781
9782 static void **
9783 lookup_dwo_file_slot (const char *dwo_name, const char *comp_dir)
9784 {
9785   struct dwo_file find_entry;
9786   void **slot;
9787
9788   if (dwarf2_per_objfile->dwo_files == NULL)
9789     dwarf2_per_objfile->dwo_files = allocate_dwo_file_hash_table ();
9790
9791   memset (&find_entry, 0, sizeof (find_entry));
9792   find_entry.dwo_name = dwo_name;
9793   find_entry.comp_dir = comp_dir;
9794   slot = htab_find_slot (dwarf2_per_objfile->dwo_files, &find_entry, INSERT);
9795
9796   return slot;
9797 }
9798
9799 static hashval_t
9800 hash_dwo_unit (const void *item)
9801 {
9802   const struct dwo_unit *dwo_unit = (const struct dwo_unit *) item;
9803
9804   /* This drops the top 32 bits of the id, but is ok for a hash.  */
9805   return dwo_unit->signature;
9806 }
9807
9808 static int
9809 eq_dwo_unit (const void *item_lhs, const void *item_rhs)
9810 {
9811   const struct dwo_unit *lhs = (const struct dwo_unit *) item_lhs;
9812   const struct dwo_unit *rhs = (const struct dwo_unit *) item_rhs;
9813
9814   /* The signature is assumed to be unique within the DWO file.
9815      So while object file CU dwo_id's always have the value zero,
9816      that's OK, assuming each object file DWO file has only one CU,
9817      and that's the rule for now.  */
9818   return lhs->signature == rhs->signature;
9819 }
9820
9821 /* Allocate a hash table for DWO CUs,TUs.
9822    There is one of these tables for each of CUs,TUs for each DWO file.  */
9823
9824 static htab_t
9825 allocate_dwo_unit_table (struct objfile *objfile)
9826 {
9827   /* Start out with a pretty small number.
9828      Generally DWO files contain only one CU and maybe some TUs.  */
9829   return htab_create_alloc_ex (3,
9830                                hash_dwo_unit,
9831                                eq_dwo_unit,
9832                                NULL,
9833                                &objfile->objfile_obstack,
9834                                hashtab_obstack_allocate,
9835                                dummy_obstack_deallocate);
9836 }
9837
9838 /* Structure used to pass data to create_dwo_debug_info_hash_table_reader.  */
9839
9840 struct create_dwo_cu_data
9841 {
9842   struct dwo_file *dwo_file;
9843   struct dwo_unit dwo_unit;
9844 };
9845
9846 /* die_reader_func for create_dwo_cu.  */
9847
9848 static void
9849 create_dwo_cu_reader (const struct die_reader_specs *reader,
9850                       const gdb_byte *info_ptr,
9851                       struct die_info *comp_unit_die,
9852                       int has_children,
9853                       void *datap)
9854 {
9855   struct dwarf2_cu *cu = reader->cu;
9856   sect_offset sect_off = cu->per_cu->sect_off;
9857   struct dwarf2_section_info *section = cu->per_cu->section;
9858   struct create_dwo_cu_data *data = (struct create_dwo_cu_data *) datap;
9859   struct dwo_file *dwo_file = data->dwo_file;
9860   struct dwo_unit *dwo_unit = &data->dwo_unit;
9861   struct attribute *attr;
9862
9863   attr = dwarf2_attr (comp_unit_die, DW_AT_GNU_dwo_id, cu);
9864   if (attr == NULL)
9865     {
9866       complaint (&symfile_complaints,
9867                  _("Dwarf Error: debug entry at offset 0x%x is missing"
9868                    " its dwo_id [in module %s]"),
9869                  to_underlying (sect_off), dwo_file->dwo_name);
9870       return;
9871     }
9872
9873   dwo_unit->dwo_file = dwo_file;
9874   dwo_unit->signature = DW_UNSND (attr);
9875   dwo_unit->section = section;
9876   dwo_unit->sect_off = sect_off;
9877   dwo_unit->length = cu->per_cu->length;
9878
9879   if (dwarf_read_debug)
9880     fprintf_unfiltered (gdb_stdlog, "  offset 0x%x, dwo_id %s\n",
9881                         to_underlying (sect_off),
9882                         hex_string (dwo_unit->signature));
9883 }
9884
9885 /* Create the dwo_units for the CUs in a DWO_FILE.
9886    Note: This function processes DWO files only, not DWP files.  */
9887
9888 static void
9889 create_cus_hash_table (struct dwo_file &dwo_file, dwarf2_section_info &section,
9890                        htab_t &cus_htab)
9891 {
9892   struct objfile *objfile = dwarf2_per_objfile->objfile;
9893   const struct dwarf2_section_info *abbrev_section = &dwo_file.sections.abbrev;
9894   const gdb_byte *info_ptr, *end_ptr;
9895
9896   dwarf2_read_section (objfile, &section);
9897   info_ptr = section.buffer;
9898
9899   if (info_ptr == NULL)
9900     return;
9901
9902   if (dwarf_read_debug)
9903     {
9904       fprintf_unfiltered (gdb_stdlog, "Reading %s for %s:\n",
9905                           get_section_name (&section),
9906                           get_section_file_name (&section));
9907     }
9908
9909   end_ptr = info_ptr + section.size;
9910   while (info_ptr < end_ptr)
9911     {
9912       struct dwarf2_per_cu_data per_cu;
9913       struct create_dwo_cu_data create_dwo_cu_data;
9914       struct dwo_unit *dwo_unit;
9915       void **slot;
9916       sect_offset sect_off = (sect_offset) (info_ptr - section.buffer);
9917
9918       memset (&create_dwo_cu_data.dwo_unit, 0,
9919               sizeof (create_dwo_cu_data.dwo_unit));
9920       memset (&per_cu, 0, sizeof (per_cu));
9921       per_cu.objfile = objfile;
9922       per_cu.is_debug_types = 0;
9923       per_cu.sect_off = sect_offset (info_ptr - section.buffer);
9924       per_cu.section = &section;
9925       create_dwo_cu_data.dwo_file = &dwo_file;
9926
9927       init_cutu_and_read_dies_no_follow (
9928           &per_cu, &dwo_file, create_dwo_cu_reader, &create_dwo_cu_data);
9929       info_ptr += per_cu.length;
9930
9931       // If the unit could not be parsed, skip it.
9932       if (create_dwo_cu_data.dwo_unit.dwo_file == NULL)
9933         continue;
9934
9935       if (cus_htab == NULL)
9936         cus_htab = allocate_dwo_unit_table (objfile);
9937
9938       dwo_unit = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_unit);
9939       *dwo_unit = create_dwo_cu_data.dwo_unit;
9940       slot = htab_find_slot (cus_htab, dwo_unit, INSERT);
9941       gdb_assert (slot != NULL);
9942       if (*slot != NULL)
9943         {
9944           const struct dwo_unit *dup_cu = (const struct dwo_unit *)*slot;
9945           sect_offset dup_sect_off = dup_cu->sect_off;
9946
9947           complaint (&symfile_complaints,
9948                      _("debug cu entry at offset 0x%x is duplicate to"
9949                        " the entry at offset 0x%x, signature %s"),
9950                      to_underlying (sect_off), to_underlying (dup_sect_off),
9951                      hex_string (dwo_unit->signature));
9952         }
9953       *slot = (void *)dwo_unit;
9954     }
9955 }
9956
9957 /* DWP file .debug_{cu,tu}_index section format:
9958    [ref: http://gcc.gnu.org/wiki/DebugFissionDWP]
9959
9960    DWP Version 1:
9961
9962    Both index sections have the same format, and serve to map a 64-bit
9963    signature to a set of section numbers.  Each section begins with a header,
9964    followed by a hash table of 64-bit signatures, a parallel table of 32-bit
9965    indexes, and a pool of 32-bit section numbers.  The index sections will be
9966    aligned at 8-byte boundaries in the file.
9967
9968    The index section header consists of:
9969
9970     V, 32 bit version number
9971     -, 32 bits unused
9972     N, 32 bit number of compilation units or type units in the index
9973     M, 32 bit number of slots in the hash table
9974
9975    Numbers are recorded using the byte order of the application binary.
9976
9977    The hash table begins at offset 16 in the section, and consists of an array
9978    of M 64-bit slots.  Each slot contains a 64-bit signature (using the byte
9979    order of the application binary).  Unused slots in the hash table are 0.
9980    (We rely on the extreme unlikeliness of a signature being exactly 0.)
9981
9982    The parallel table begins immediately after the hash table
9983    (at offset 16 + 8 * M from the beginning of the section), and consists of an
9984    array of 32-bit indexes (using the byte order of the application binary),
9985    corresponding 1-1 with slots in the hash table.  Each entry in the parallel
9986    table contains a 32-bit index into the pool of section numbers.  For unused
9987    hash table slots, the corresponding entry in the parallel table will be 0.
9988
9989    The pool of section numbers begins immediately following the hash table
9990    (at offset 16 + 12 * M from the beginning of the section).  The pool of
9991    section numbers consists of an array of 32-bit words (using the byte order
9992    of the application binary).  Each item in the array is indexed starting
9993    from 0.  The hash table entry provides the index of the first section
9994    number in the set.  Additional section numbers in the set follow, and the
9995    set is terminated by a 0 entry (section number 0 is not used in ELF).
9996
9997    In each set of section numbers, the .debug_info.dwo or .debug_types.dwo
9998    section must be the first entry in the set, and the .debug_abbrev.dwo must
9999    be the second entry. Other members of the set may follow in any order.
10000
10001    ---
10002
10003    DWP Version 2:
10004
10005    DWP Version 2 combines all the .debug_info, etc. sections into one,
10006    and the entries in the index tables are now offsets into these sections.
10007    CU offsets begin at 0.  TU offsets begin at the size of the .debug_info
10008    section.
10009
10010    Index Section Contents:
10011     Header
10012     Hash Table of Signatures   dwp_hash_table.hash_table
10013     Parallel Table of Indices  dwp_hash_table.unit_table
10014     Table of Section Offsets   dwp_hash_table.v2.{section_ids,offsets}
10015     Table of Section Sizes     dwp_hash_table.v2.sizes
10016
10017    The index section header consists of:
10018
10019     V, 32 bit version number
10020     L, 32 bit number of columns in the table of section offsets
10021     N, 32 bit number of compilation units or type units in the index
10022     M, 32 bit number of slots in the hash table
10023
10024    Numbers are recorded using the byte order of the application binary.
10025
10026    The hash table has the same format as version 1.
10027    The parallel table of indices has the same format as version 1,
10028    except that the entries are origin-1 indices into the table of sections
10029    offsets and the table of section sizes.
10030
10031    The table of offsets begins immediately following the parallel table
10032    (at offset 16 + 12 * M from the beginning of the section).  The table is
10033    a two-dimensional array of 32-bit words (using the byte order of the
10034    application binary), with L columns and N+1 rows, in row-major order.
10035    Each row in the array is indexed starting from 0.  The first row provides
10036    a key to the remaining rows: each column in this row provides an identifier
10037    for a debug section, and the offsets in the same column of subsequent rows
10038    refer to that section.  The section identifiers are:
10039
10040     DW_SECT_INFO         1  .debug_info.dwo
10041     DW_SECT_TYPES        2  .debug_types.dwo
10042     DW_SECT_ABBREV       3  .debug_abbrev.dwo
10043     DW_SECT_LINE         4  .debug_line.dwo
10044     DW_SECT_LOC          5  .debug_loc.dwo
10045     DW_SECT_STR_OFFSETS  6  .debug_str_offsets.dwo
10046     DW_SECT_MACINFO      7  .debug_macinfo.dwo
10047     DW_SECT_MACRO        8  .debug_macro.dwo
10048
10049    The offsets provided by the CU and TU index sections are the base offsets
10050    for the contributions made by each CU or TU to the corresponding section
10051    in the package file.  Each CU and TU header contains an abbrev_offset
10052    field, used to find the abbreviations table for that CU or TU within the
10053    contribution to the .debug_abbrev.dwo section for that CU or TU, and should
10054    be interpreted as relative to the base offset given in the index section.
10055    Likewise, offsets into .debug_line.dwo from DW_AT_stmt_list attributes
10056    should be interpreted as relative to the base offset for .debug_line.dwo,
10057    and offsets into other debug sections obtained from DWARF attributes should
10058    also be interpreted as relative to the corresponding base offset.
10059
10060    The table of sizes begins immediately following the table of offsets.
10061    Like the table of offsets, it is a two-dimensional array of 32-bit words,
10062    with L columns and N rows, in row-major order.  Each row in the array is
10063    indexed starting from 1 (row 0 is shared by the two tables).
10064
10065    ---
10066
10067    Hash table lookup is handled the same in version 1 and 2:
10068
10069    We assume that N and M will not exceed 2^32 - 1.
10070    The size of the hash table, M, must be 2^k such that 2^k > 3*N/2.
10071
10072    Given a 64-bit compilation unit signature or a type signature S, an entry
10073    in the hash table is located as follows:
10074
10075    1) Calculate a primary hash H = S & MASK(k), where MASK(k) is a mask with
10076       the low-order k bits all set to 1.
10077
10078    2) Calculate a secondary hash H' = (((S >> 32) & MASK(k)) | 1).
10079
10080    3) If the hash table entry at index H matches the signature, use that
10081       entry.  If the hash table entry at index H is unused (all zeroes),
10082       terminate the search: the signature is not present in the table.
10083
10084    4) Let H = (H + H') modulo M. Repeat at Step 3.
10085
10086    Because M > N and H' and M are relatively prime, the search is guaranteed
10087    to stop at an unused slot or find the match.  */
10088
10089 /* Create a hash table to map DWO IDs to their CU/TU entry in
10090    .debug_{info,types}.dwo in DWP_FILE.
10091    Returns NULL if there isn't one.
10092    Note: This function processes DWP files only, not DWO files.  */
10093
10094 static struct dwp_hash_table *
10095 create_dwp_hash_table (struct dwp_file *dwp_file, int is_debug_types)
10096 {
10097   struct objfile *objfile = dwarf2_per_objfile->objfile;
10098   bfd *dbfd = dwp_file->dbfd;
10099   const gdb_byte *index_ptr, *index_end;
10100   struct dwarf2_section_info *index;
10101   uint32_t version, nr_columns, nr_units, nr_slots;
10102   struct dwp_hash_table *htab;
10103
10104   if (is_debug_types)
10105     index = &dwp_file->sections.tu_index;
10106   else
10107     index = &dwp_file->sections.cu_index;
10108
10109   if (dwarf2_section_empty_p (index))
10110     return NULL;
10111   dwarf2_read_section (objfile, index);
10112
10113   index_ptr = index->buffer;
10114   index_end = index_ptr + index->size;
10115
10116   version = read_4_bytes (dbfd, index_ptr);
10117   index_ptr += 4;
10118   if (version == 2)
10119     nr_columns = read_4_bytes (dbfd, index_ptr);
10120   else
10121     nr_columns = 0;
10122   index_ptr += 4;
10123   nr_units = read_4_bytes (dbfd, index_ptr);
10124   index_ptr += 4;
10125   nr_slots = read_4_bytes (dbfd, index_ptr);
10126   index_ptr += 4;
10127
10128   if (version != 1 && version != 2)
10129     {
10130       error (_("Dwarf Error: unsupported DWP file version (%s)"
10131                " [in module %s]"),
10132              pulongest (version), dwp_file->name);
10133     }
10134   if (nr_slots != (nr_slots & -nr_slots))
10135     {
10136       error (_("Dwarf Error: number of slots in DWP hash table (%s)"
10137                " is not power of 2 [in module %s]"),
10138              pulongest (nr_slots), dwp_file->name);
10139     }
10140
10141   htab = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwp_hash_table);
10142   htab->version = version;
10143   htab->nr_columns = nr_columns;
10144   htab->nr_units = nr_units;
10145   htab->nr_slots = nr_slots;
10146   htab->hash_table = index_ptr;
10147   htab->unit_table = htab->hash_table + sizeof (uint64_t) * nr_slots;
10148
10149   /* Exit early if the table is empty.  */
10150   if (nr_slots == 0 || nr_units == 0
10151       || (version == 2 && nr_columns == 0))
10152     {
10153       /* All must be zero.  */
10154       if (nr_slots != 0 || nr_units != 0
10155           || (version == 2 && nr_columns != 0))
10156         {
10157           complaint (&symfile_complaints,
10158                      _("Empty DWP but nr_slots,nr_units,nr_columns not"
10159                        " all zero [in modules %s]"),
10160                      dwp_file->name);
10161         }
10162       return htab;
10163     }
10164
10165   if (version == 1)
10166     {
10167       htab->section_pool.v1.indices =
10168         htab->unit_table + sizeof (uint32_t) * nr_slots;
10169       /* It's harder to decide whether the section is too small in v1.
10170          V1 is deprecated anyway so we punt.  */
10171     }
10172   else
10173     {
10174       const gdb_byte *ids_ptr = htab->unit_table + sizeof (uint32_t) * nr_slots;
10175       int *ids = htab->section_pool.v2.section_ids;
10176       /* Reverse map for error checking.  */
10177       int ids_seen[DW_SECT_MAX + 1];
10178       int i;
10179
10180       if (nr_columns < 2)
10181         {
10182           error (_("Dwarf Error: bad DWP hash table, too few columns"
10183                    " in section table [in module %s]"),
10184                  dwp_file->name);
10185         }
10186       if (nr_columns > MAX_NR_V2_DWO_SECTIONS)
10187         {
10188           error (_("Dwarf Error: bad DWP hash table, too many columns"
10189                    " in section table [in module %s]"),
10190                  dwp_file->name);
10191         }
10192       memset (ids, 255, (DW_SECT_MAX + 1) * sizeof (int32_t));
10193       memset (ids_seen, 255, (DW_SECT_MAX + 1) * sizeof (int32_t));
10194       for (i = 0; i < nr_columns; ++i)
10195         {
10196           int id = read_4_bytes (dbfd, ids_ptr + i * sizeof (uint32_t));
10197
10198           if (id < DW_SECT_MIN || id > DW_SECT_MAX)
10199             {
10200               error (_("Dwarf Error: bad DWP hash table, bad section id %d"
10201                        " in section table [in module %s]"),
10202                      id, dwp_file->name);
10203             }
10204           if (ids_seen[id] != -1)
10205             {
10206               error (_("Dwarf Error: bad DWP hash table, duplicate section"
10207                        " id %d in section table [in module %s]"),
10208                      id, dwp_file->name);
10209             }
10210           ids_seen[id] = i;
10211           ids[i] = id;
10212         }
10213       /* Must have exactly one info or types section.  */
10214       if (((ids_seen[DW_SECT_INFO] != -1)
10215            + (ids_seen[DW_SECT_TYPES] != -1))
10216           != 1)
10217         {
10218           error (_("Dwarf Error: bad DWP hash table, missing/duplicate"
10219                    " DWO info/types section [in module %s]"),
10220                  dwp_file->name);
10221         }
10222       /* Must have an abbrev section.  */
10223       if (ids_seen[DW_SECT_ABBREV] == -1)
10224         {
10225           error (_("Dwarf Error: bad DWP hash table, missing DWO abbrev"
10226                    " section [in module %s]"),
10227                  dwp_file->name);
10228         }
10229       htab->section_pool.v2.offsets = ids_ptr + sizeof (uint32_t) * nr_columns;
10230       htab->section_pool.v2.sizes =
10231         htab->section_pool.v2.offsets + (sizeof (uint32_t)
10232                                          * nr_units * nr_columns);
10233       if ((htab->section_pool.v2.sizes + (sizeof (uint32_t)
10234                                           * nr_units * nr_columns))
10235           > index_end)
10236         {
10237           error (_("Dwarf Error: DWP index section is corrupt (too small)"
10238                    " [in module %s]"),
10239                  dwp_file->name);
10240         }
10241     }
10242
10243   return htab;
10244 }
10245
10246 /* Update SECTIONS with the data from SECTP.
10247
10248    This function is like the other "locate" section routines that are
10249    passed to bfd_map_over_sections, but in this context the sections to
10250    read comes from the DWP V1 hash table, not the full ELF section table.
10251
10252    The result is non-zero for success, or zero if an error was found.  */
10253
10254 static int
10255 locate_v1_virtual_dwo_sections (asection *sectp,
10256                                 struct virtual_v1_dwo_sections *sections)
10257 {
10258   const struct dwop_section_names *names = &dwop_section_names;
10259
10260   if (section_is_p (sectp->name, &names->abbrev_dwo))
10261     {
10262       /* There can be only one.  */
10263       if (sections->abbrev.s.section != NULL)
10264         return 0;
10265       sections->abbrev.s.section = sectp;
10266       sections->abbrev.size = bfd_get_section_size (sectp);
10267     }
10268   else if (section_is_p (sectp->name, &names->info_dwo)
10269            || section_is_p (sectp->name, &names->types_dwo))
10270     {
10271       /* There can be only one.  */
10272       if (sections->info_or_types.s.section != NULL)
10273         return 0;
10274       sections->info_or_types.s.section = sectp;
10275       sections->info_or_types.size = bfd_get_section_size (sectp);
10276     }
10277   else if (section_is_p (sectp->name, &names->line_dwo))
10278     {
10279       /* There can be only one.  */
10280       if (sections->line.s.section != NULL)
10281         return 0;
10282       sections->line.s.section = sectp;
10283       sections->line.size = bfd_get_section_size (sectp);
10284     }
10285   else if (section_is_p (sectp->name, &names->loc_dwo))
10286     {
10287       /* There can be only one.  */
10288       if (sections->loc.s.section != NULL)
10289         return 0;
10290       sections->loc.s.section = sectp;
10291       sections->loc.size = bfd_get_section_size (sectp);
10292     }
10293   else if (section_is_p (sectp->name, &names->macinfo_dwo))
10294     {
10295       /* There can be only one.  */
10296       if (sections->macinfo.s.section != NULL)
10297         return 0;
10298       sections->macinfo.s.section = sectp;
10299       sections->macinfo.size = bfd_get_section_size (sectp);
10300     }
10301   else if (section_is_p (sectp->name, &names->macro_dwo))
10302     {
10303       /* There can be only one.  */
10304       if (sections->macro.s.section != NULL)
10305         return 0;
10306       sections->macro.s.section = sectp;
10307       sections->macro.size = bfd_get_section_size (sectp);
10308     }
10309   else if (section_is_p (sectp->name, &names->str_offsets_dwo))
10310     {
10311       /* There can be only one.  */
10312       if (sections->str_offsets.s.section != NULL)
10313         return 0;
10314       sections->str_offsets.s.section = sectp;
10315       sections->str_offsets.size = bfd_get_section_size (sectp);
10316     }
10317   else
10318     {
10319       /* No other kind of section is valid.  */
10320       return 0;
10321     }
10322
10323   return 1;
10324 }
10325
10326 /* Create a dwo_unit object for the DWO unit with signature SIGNATURE.
10327    UNIT_INDEX is the index of the DWO unit in the DWP hash table.
10328    COMP_DIR is the DW_AT_comp_dir attribute of the referencing CU.
10329    This is for DWP version 1 files.  */
10330
10331 static struct dwo_unit *
10332 create_dwo_unit_in_dwp_v1 (struct dwp_file *dwp_file,
10333                            uint32_t unit_index,
10334                            const char *comp_dir,
10335                            ULONGEST signature, int is_debug_types)
10336 {
10337   struct objfile *objfile = dwarf2_per_objfile->objfile;
10338   const struct dwp_hash_table *dwp_htab =
10339     is_debug_types ? dwp_file->tus : dwp_file->cus;
10340   bfd *dbfd = dwp_file->dbfd;
10341   const char *kind = is_debug_types ? "TU" : "CU";
10342   struct dwo_file *dwo_file;
10343   struct dwo_unit *dwo_unit;
10344   struct virtual_v1_dwo_sections sections;
10345   void **dwo_file_slot;
10346   char *virtual_dwo_name;
10347   struct cleanup *cleanups;
10348   int i;
10349
10350   gdb_assert (dwp_file->version == 1);
10351
10352   if (dwarf_read_debug)
10353     {
10354       fprintf_unfiltered (gdb_stdlog, "Reading %s %s/%s in DWP V1 file: %s\n",
10355                           kind,
10356                           pulongest (unit_index), hex_string (signature),
10357                           dwp_file->name);
10358     }
10359
10360   /* Fetch the sections of this DWO unit.
10361      Put a limit on the number of sections we look for so that bad data
10362      doesn't cause us to loop forever.  */
10363
10364 #define MAX_NR_V1_DWO_SECTIONS \
10365   (1 /* .debug_info or .debug_types */ \
10366    + 1 /* .debug_abbrev */ \
10367    + 1 /* .debug_line */ \
10368    + 1 /* .debug_loc */ \
10369    + 1 /* .debug_str_offsets */ \
10370    + 1 /* .debug_macro or .debug_macinfo */ \
10371    + 1 /* trailing zero */)
10372
10373   memset (&sections, 0, sizeof (sections));
10374   cleanups = make_cleanup (null_cleanup, 0);
10375
10376   for (i = 0; i < MAX_NR_V1_DWO_SECTIONS; ++i)
10377     {
10378       asection *sectp;
10379       uint32_t section_nr =
10380         read_4_bytes (dbfd,
10381                       dwp_htab->section_pool.v1.indices
10382                       + (unit_index + i) * sizeof (uint32_t));
10383
10384       if (section_nr == 0)
10385         break;
10386       if (section_nr >= dwp_file->num_sections)
10387         {
10388           error (_("Dwarf Error: bad DWP hash table, section number too large"
10389                    " [in module %s]"),
10390                  dwp_file->name);
10391         }
10392
10393       sectp = dwp_file->elf_sections[section_nr];
10394       if (! locate_v1_virtual_dwo_sections (sectp, &sections))
10395         {
10396           error (_("Dwarf Error: bad DWP hash table, invalid section found"
10397                    " [in module %s]"),
10398                  dwp_file->name);
10399         }
10400     }
10401
10402   if (i < 2
10403       || dwarf2_section_empty_p (&sections.info_or_types)
10404       || dwarf2_section_empty_p (&sections.abbrev))
10405     {
10406       error (_("Dwarf Error: bad DWP hash table, missing DWO sections"
10407                " [in module %s]"),
10408              dwp_file->name);
10409     }
10410   if (i == MAX_NR_V1_DWO_SECTIONS)
10411     {
10412       error (_("Dwarf Error: bad DWP hash table, too many DWO sections"
10413                " [in module %s]"),
10414              dwp_file->name);
10415     }
10416
10417   /* It's easier for the rest of the code if we fake a struct dwo_file and
10418      have dwo_unit "live" in that.  At least for now.
10419
10420      The DWP file can be made up of a random collection of CUs and TUs.
10421      However, for each CU + set of TUs that came from the same original DWO
10422      file, we can combine them back into a virtual DWO file to save space
10423      (fewer struct dwo_file objects to allocate).  Remember that for really
10424      large apps there can be on the order of 8K CUs and 200K TUs, or more.  */
10425
10426   virtual_dwo_name =
10427     xstrprintf ("virtual-dwo/%d-%d-%d-%d",
10428                 get_section_id (&sections.abbrev),
10429                 get_section_id (&sections.line),
10430                 get_section_id (&sections.loc),
10431                 get_section_id (&sections.str_offsets));
10432   make_cleanup (xfree, virtual_dwo_name);
10433   /* Can we use an existing virtual DWO file?  */
10434   dwo_file_slot = lookup_dwo_file_slot (virtual_dwo_name, comp_dir);
10435   /* Create one if necessary.  */
10436   if (*dwo_file_slot == NULL)
10437     {
10438       if (dwarf_read_debug)
10439         {
10440           fprintf_unfiltered (gdb_stdlog, "Creating virtual DWO: %s\n",
10441                               virtual_dwo_name);
10442         }
10443       dwo_file = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_file);
10444       dwo_file->dwo_name
10445         = (const char *) obstack_copy0 (&objfile->objfile_obstack,
10446                                         virtual_dwo_name,
10447                                         strlen (virtual_dwo_name));
10448       dwo_file->comp_dir = comp_dir;
10449       dwo_file->sections.abbrev = sections.abbrev;
10450       dwo_file->sections.line = sections.line;
10451       dwo_file->sections.loc = sections.loc;
10452       dwo_file->sections.macinfo = sections.macinfo;
10453       dwo_file->sections.macro = sections.macro;
10454       dwo_file->sections.str_offsets = sections.str_offsets;
10455       /* The "str" section is global to the entire DWP file.  */
10456       dwo_file->sections.str = dwp_file->sections.str;
10457       /* The info or types section is assigned below to dwo_unit,
10458          there's no need to record it in dwo_file.
10459          Also, we can't simply record type sections in dwo_file because
10460          we record a pointer into the vector in dwo_unit.  As we collect more
10461          types we'll grow the vector and eventually have to reallocate space
10462          for it, invalidating all copies of pointers into the previous
10463          contents.  */
10464       *dwo_file_slot = dwo_file;
10465     }
10466   else
10467     {
10468       if (dwarf_read_debug)
10469         {
10470           fprintf_unfiltered (gdb_stdlog, "Using existing virtual DWO: %s\n",
10471                               virtual_dwo_name);
10472         }
10473       dwo_file = (struct dwo_file *) *dwo_file_slot;
10474     }
10475   do_cleanups (cleanups);
10476
10477   dwo_unit = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_unit);
10478   dwo_unit->dwo_file = dwo_file;
10479   dwo_unit->signature = signature;
10480   dwo_unit->section =
10481     XOBNEW (&objfile->objfile_obstack, struct dwarf2_section_info);
10482   *dwo_unit->section = sections.info_or_types;
10483   /* dwo_unit->{offset,length,type_offset_in_tu} are set later.  */
10484
10485   return dwo_unit;
10486 }
10487
10488 /* Subroutine of create_dwo_unit_in_dwp_v2 to simplify it.
10489    Given a pointer to the containing section SECTION, and OFFSET,SIZE of the
10490    piece within that section used by a TU/CU, return a virtual section
10491    of just that piece.  */
10492
10493 static struct dwarf2_section_info
10494 create_dwp_v2_section (struct dwarf2_section_info *section,
10495                        bfd_size_type offset, bfd_size_type size)
10496 {
10497   struct dwarf2_section_info result;
10498   asection *sectp;
10499
10500   gdb_assert (section != NULL);
10501   gdb_assert (!section->is_virtual);
10502
10503   memset (&result, 0, sizeof (result));
10504   result.s.containing_section = section;
10505   result.is_virtual = 1;
10506
10507   if (size == 0)
10508     return result;
10509
10510   sectp = get_section_bfd_section (section);
10511
10512   /* Flag an error if the piece denoted by OFFSET,SIZE is outside the
10513      bounds of the real section.  This is a pretty-rare event, so just
10514      flag an error (easier) instead of a warning and trying to cope.  */
10515   if (sectp == NULL
10516       || offset + size > bfd_get_section_size (sectp))
10517     {
10518       bfd *abfd = sectp->owner;
10519
10520       error (_("Dwarf Error: Bad DWP V2 section info, doesn't fit"
10521                " in section %s [in module %s]"),
10522              sectp ? bfd_section_name (abfd, sectp) : "<unknown>",
10523              objfile_name (dwarf2_per_objfile->objfile));
10524     }
10525
10526   result.virtual_offset = offset;
10527   result.size = size;
10528   return result;
10529 }
10530
10531 /* Create a dwo_unit object for the DWO unit with signature SIGNATURE.
10532    UNIT_INDEX is the index of the DWO unit in the DWP hash table.
10533    COMP_DIR is the DW_AT_comp_dir attribute of the referencing CU.
10534    This is for DWP version 2 files.  */
10535
10536 static struct dwo_unit *
10537 create_dwo_unit_in_dwp_v2 (struct dwp_file *dwp_file,
10538                            uint32_t unit_index,
10539                            const char *comp_dir,
10540                            ULONGEST signature, int is_debug_types)
10541 {
10542   struct objfile *objfile = dwarf2_per_objfile->objfile;
10543   const struct dwp_hash_table *dwp_htab =
10544     is_debug_types ? dwp_file->tus : dwp_file->cus;
10545   bfd *dbfd = dwp_file->dbfd;
10546   const char *kind = is_debug_types ? "TU" : "CU";
10547   struct dwo_file *dwo_file;
10548   struct dwo_unit *dwo_unit;
10549   struct virtual_v2_dwo_sections sections;
10550   void **dwo_file_slot;
10551   char *virtual_dwo_name;
10552   struct cleanup *cleanups;
10553   int i;
10554
10555   gdb_assert (dwp_file->version == 2);
10556
10557   if (dwarf_read_debug)
10558     {
10559       fprintf_unfiltered (gdb_stdlog, "Reading %s %s/%s in DWP V2 file: %s\n",
10560                           kind,
10561                           pulongest (unit_index), hex_string (signature),
10562                           dwp_file->name);
10563     }
10564
10565   /* Fetch the section offsets of this DWO unit.  */
10566
10567   memset (&sections, 0, sizeof (sections));
10568   cleanups = make_cleanup (null_cleanup, 0);
10569
10570   for (i = 0; i < dwp_htab->nr_columns; ++i)
10571     {
10572       uint32_t offset = read_4_bytes (dbfd,
10573                                       dwp_htab->section_pool.v2.offsets
10574                                       + (((unit_index - 1) * dwp_htab->nr_columns
10575                                           + i)
10576                                          * sizeof (uint32_t)));
10577       uint32_t size = read_4_bytes (dbfd,
10578                                     dwp_htab->section_pool.v2.sizes
10579                                     + (((unit_index - 1) * dwp_htab->nr_columns
10580                                         + i)
10581                                        * sizeof (uint32_t)));
10582
10583       switch (dwp_htab->section_pool.v2.section_ids[i])
10584         {
10585         case DW_SECT_INFO:
10586         case DW_SECT_TYPES:
10587           sections.info_or_types_offset = offset;
10588           sections.info_or_types_size = size;
10589           break;
10590         case DW_SECT_ABBREV:
10591           sections.abbrev_offset = offset;
10592           sections.abbrev_size = size;
10593           break;
10594         case DW_SECT_LINE:
10595           sections.line_offset = offset;
10596           sections.line_size = size;
10597           break;
10598         case DW_SECT_LOC:
10599           sections.loc_offset = offset;
10600           sections.loc_size = size;
10601           break;
10602         case DW_SECT_STR_OFFSETS:
10603           sections.str_offsets_offset = offset;
10604           sections.str_offsets_size = size;
10605           break;
10606         case DW_SECT_MACINFO:
10607           sections.macinfo_offset = offset;
10608           sections.macinfo_size = size;
10609           break;
10610         case DW_SECT_MACRO:
10611           sections.macro_offset = offset;
10612           sections.macro_size = size;
10613           break;
10614         }
10615     }
10616
10617   /* It's easier for the rest of the code if we fake a struct dwo_file and
10618      have dwo_unit "live" in that.  At least for now.
10619
10620      The DWP file can be made up of a random collection of CUs and TUs.
10621      However, for each CU + set of TUs that came from the same original DWO
10622      file, we can combine them back into a virtual DWO file to save space
10623      (fewer struct dwo_file objects to allocate).  Remember that for really
10624      large apps there can be on the order of 8K CUs and 200K TUs, or more.  */
10625
10626   virtual_dwo_name =
10627     xstrprintf ("virtual-dwo/%ld-%ld-%ld-%ld",
10628                 (long) (sections.abbrev_size ? sections.abbrev_offset : 0),
10629                 (long) (sections.line_size ? sections.line_offset : 0),
10630                 (long) (sections.loc_size ? sections.loc_offset : 0),
10631                 (long) (sections.str_offsets_size
10632                         ? sections.str_offsets_offset : 0));
10633   make_cleanup (xfree, virtual_dwo_name);
10634   /* Can we use an existing virtual DWO file?  */
10635   dwo_file_slot = lookup_dwo_file_slot (virtual_dwo_name, comp_dir);
10636   /* Create one if necessary.  */
10637   if (*dwo_file_slot == NULL)
10638     {
10639       if (dwarf_read_debug)
10640         {
10641           fprintf_unfiltered (gdb_stdlog, "Creating virtual DWO: %s\n",
10642                               virtual_dwo_name);
10643         }
10644       dwo_file = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_file);
10645       dwo_file->dwo_name
10646         = (const char *) obstack_copy0 (&objfile->objfile_obstack,
10647                                         virtual_dwo_name,
10648                                         strlen (virtual_dwo_name));
10649       dwo_file->comp_dir = comp_dir;
10650       dwo_file->sections.abbrev =
10651         create_dwp_v2_section (&dwp_file->sections.abbrev,
10652                                sections.abbrev_offset, sections.abbrev_size);
10653       dwo_file->sections.line =
10654         create_dwp_v2_section (&dwp_file->sections.line,
10655                                sections.line_offset, sections.line_size);
10656       dwo_file->sections.loc =
10657         create_dwp_v2_section (&dwp_file->sections.loc,
10658                                sections.loc_offset, sections.loc_size);
10659       dwo_file->sections.macinfo =
10660         create_dwp_v2_section (&dwp_file->sections.macinfo,
10661                                sections.macinfo_offset, sections.macinfo_size);
10662       dwo_file->sections.macro =
10663         create_dwp_v2_section (&dwp_file->sections.macro,
10664                                sections.macro_offset, sections.macro_size);
10665       dwo_file->sections.str_offsets =
10666         create_dwp_v2_section (&dwp_file->sections.str_offsets,
10667                                sections.str_offsets_offset,
10668                                sections.str_offsets_size);
10669       /* The "str" section is global to the entire DWP file.  */
10670       dwo_file->sections.str = dwp_file->sections.str;
10671       /* The info or types section is assigned below to dwo_unit,
10672          there's no need to record it in dwo_file.
10673          Also, we can't simply record type sections in dwo_file because
10674          we record a pointer into the vector in dwo_unit.  As we collect more
10675          types we'll grow the vector and eventually have to reallocate space
10676          for it, invalidating all copies of pointers into the previous
10677          contents.  */
10678       *dwo_file_slot = dwo_file;
10679     }
10680   else
10681     {
10682       if (dwarf_read_debug)
10683         {
10684           fprintf_unfiltered (gdb_stdlog, "Using existing virtual DWO: %s\n",
10685                               virtual_dwo_name);
10686         }
10687       dwo_file = (struct dwo_file *) *dwo_file_slot;
10688     }
10689   do_cleanups (cleanups);
10690
10691   dwo_unit = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_unit);
10692   dwo_unit->dwo_file = dwo_file;
10693   dwo_unit->signature = signature;
10694   dwo_unit->section =
10695     XOBNEW (&objfile->objfile_obstack, struct dwarf2_section_info);
10696   *dwo_unit->section = create_dwp_v2_section (is_debug_types
10697                                               ? &dwp_file->sections.types
10698                                               : &dwp_file->sections.info,
10699                                               sections.info_or_types_offset,
10700                                               sections.info_or_types_size);
10701   /* dwo_unit->{offset,length,type_offset_in_tu} are set later.  */
10702
10703   return dwo_unit;
10704 }
10705
10706 /* Lookup the DWO unit with SIGNATURE in DWP_FILE.
10707    Returns NULL if the signature isn't found.  */
10708
10709 static struct dwo_unit *
10710 lookup_dwo_unit_in_dwp (struct dwp_file *dwp_file, const char *comp_dir,
10711                         ULONGEST signature, int is_debug_types)
10712 {
10713   const struct dwp_hash_table *dwp_htab =
10714     is_debug_types ? dwp_file->tus : dwp_file->cus;
10715   bfd *dbfd = dwp_file->dbfd;
10716   uint32_t mask = dwp_htab->nr_slots - 1;
10717   uint32_t hash = signature & mask;
10718   uint32_t hash2 = ((signature >> 32) & mask) | 1;
10719   unsigned int i;
10720   void **slot;
10721   struct dwo_unit find_dwo_cu;
10722
10723   memset (&find_dwo_cu, 0, sizeof (find_dwo_cu));
10724   find_dwo_cu.signature = signature;
10725   slot = htab_find_slot (is_debug_types
10726                          ? dwp_file->loaded_tus
10727                          : dwp_file->loaded_cus,
10728                          &find_dwo_cu, INSERT);
10729
10730   if (*slot != NULL)
10731     return (struct dwo_unit *) *slot;
10732
10733   /* Use a for loop so that we don't loop forever on bad debug info.  */
10734   for (i = 0; i < dwp_htab->nr_slots; ++i)
10735     {
10736       ULONGEST signature_in_table;
10737
10738       signature_in_table =
10739         read_8_bytes (dbfd, dwp_htab->hash_table + hash * sizeof (uint64_t));
10740       if (signature_in_table == signature)
10741         {
10742           uint32_t unit_index =
10743             read_4_bytes (dbfd,
10744                           dwp_htab->unit_table + hash * sizeof (uint32_t));
10745
10746           if (dwp_file->version == 1)
10747             {
10748               *slot = create_dwo_unit_in_dwp_v1 (dwp_file, unit_index,
10749                                                  comp_dir, signature,
10750                                                  is_debug_types);
10751             }
10752           else
10753             {
10754               *slot = create_dwo_unit_in_dwp_v2 (dwp_file, unit_index,
10755                                                  comp_dir, signature,
10756                                                  is_debug_types);
10757             }
10758           return (struct dwo_unit *) *slot;
10759         }
10760       if (signature_in_table == 0)
10761         return NULL;
10762       hash = (hash + hash2) & mask;
10763     }
10764
10765   error (_("Dwarf Error: bad DWP hash table, lookup didn't terminate"
10766            " [in module %s]"),
10767          dwp_file->name);
10768 }
10769
10770 /* Subroutine of open_dwo_file,open_dwp_file to simplify them.
10771    Open the file specified by FILE_NAME and hand it off to BFD for
10772    preliminary analysis.  Return a newly initialized bfd *, which
10773    includes a canonicalized copy of FILE_NAME.
10774    If IS_DWP is TRUE, we're opening a DWP file, otherwise a DWO file.
10775    SEARCH_CWD is true if the current directory is to be searched.
10776    It will be searched before debug-file-directory.
10777    If successful, the file is added to the bfd include table of the
10778    objfile's bfd (see gdb_bfd_record_inclusion).
10779    If unable to find/open the file, return NULL.
10780    NOTE: This function is derived from symfile_bfd_open.  */
10781
10782 static gdb_bfd_ref_ptr
10783 try_open_dwop_file (const char *file_name, int is_dwp, int search_cwd)
10784 {
10785   int desc, flags;
10786   char *absolute_name;
10787   /* Blech.  OPF_TRY_CWD_FIRST also disables searching the path list if
10788      FILE_NAME contains a '/'.  So we can't use it.  Instead prepend "."
10789      to debug_file_directory.  */
10790   char *search_path;
10791   static const char dirname_separator_string[] = { DIRNAME_SEPARATOR, '\0' };
10792
10793   if (search_cwd)
10794     {
10795       if (*debug_file_directory != '\0')
10796         search_path = concat (".", dirname_separator_string,
10797                               debug_file_directory, (char *) NULL);
10798       else
10799         search_path = xstrdup (".");
10800     }
10801   else
10802     search_path = xstrdup (debug_file_directory);
10803
10804   flags = OPF_RETURN_REALPATH;
10805   if (is_dwp)
10806     flags |= OPF_SEARCH_IN_PATH;
10807   desc = openp (search_path, flags, file_name,
10808                 O_RDONLY | O_BINARY, &absolute_name);
10809   xfree (search_path);
10810   if (desc < 0)
10811     return NULL;
10812
10813   gdb_bfd_ref_ptr sym_bfd (gdb_bfd_open (absolute_name, gnutarget, desc));
10814   xfree (absolute_name);
10815   if (sym_bfd == NULL)
10816     return NULL;
10817   bfd_set_cacheable (sym_bfd.get (), 1);
10818
10819   if (!bfd_check_format (sym_bfd.get (), bfd_object))
10820     return NULL;
10821
10822   /* Success.  Record the bfd as having been included by the objfile's bfd.
10823      This is important because things like demangled_names_hash lives in the
10824      objfile's per_bfd space and may have references to things like symbol
10825      names that live in the DWO/DWP file's per_bfd space.  PR 16426.  */
10826   gdb_bfd_record_inclusion (dwarf2_per_objfile->objfile->obfd, sym_bfd.get ());
10827
10828   return sym_bfd;
10829 }
10830
10831 /* Try to open DWO file FILE_NAME.
10832    COMP_DIR is the DW_AT_comp_dir attribute.
10833    The result is the bfd handle of the file.
10834    If there is a problem finding or opening the file, return NULL.
10835    Upon success, the canonicalized path of the file is stored in the bfd,
10836    same as symfile_bfd_open.  */
10837
10838 static gdb_bfd_ref_ptr
10839 open_dwo_file (const char *file_name, const char *comp_dir)
10840 {
10841   if (IS_ABSOLUTE_PATH (file_name))
10842     return try_open_dwop_file (file_name, 0 /*is_dwp*/, 0 /*search_cwd*/);
10843
10844   /* Before trying the search path, try DWO_NAME in COMP_DIR.  */
10845
10846   if (comp_dir != NULL)
10847     {
10848       char *path_to_try = concat (comp_dir, SLASH_STRING,
10849                                   file_name, (char *) NULL);
10850
10851       /* NOTE: If comp_dir is a relative path, this will also try the
10852          search path, which seems useful.  */
10853       gdb_bfd_ref_ptr abfd (try_open_dwop_file (path_to_try, 0 /*is_dwp*/,
10854                                                 1 /*search_cwd*/));
10855       xfree (path_to_try);
10856       if (abfd != NULL)
10857         return abfd;
10858     }
10859
10860   /* That didn't work, try debug-file-directory, which, despite its name,
10861      is a list of paths.  */
10862
10863   if (*debug_file_directory == '\0')
10864     return NULL;
10865
10866   return try_open_dwop_file (file_name, 0 /*is_dwp*/, 1 /*search_cwd*/);
10867 }
10868
10869 /* This function is mapped across the sections and remembers the offset and
10870    size of each of the DWO debugging sections we are interested in.  */
10871
10872 static void
10873 dwarf2_locate_dwo_sections (bfd *abfd, asection *sectp, void *dwo_sections_ptr)
10874 {
10875   struct dwo_sections *dwo_sections = (struct dwo_sections *) dwo_sections_ptr;
10876   const struct dwop_section_names *names = &dwop_section_names;
10877
10878   if (section_is_p (sectp->name, &names->abbrev_dwo))
10879     {
10880       dwo_sections->abbrev.s.section = sectp;
10881       dwo_sections->abbrev.size = bfd_get_section_size (sectp);
10882     }
10883   else if (section_is_p (sectp->name, &names->info_dwo))
10884     {
10885       dwo_sections->info.s.section = sectp;
10886       dwo_sections->info.size = bfd_get_section_size (sectp);
10887     }
10888   else if (section_is_p (sectp->name, &names->line_dwo))
10889     {
10890       dwo_sections->line.s.section = sectp;
10891       dwo_sections->line.size = bfd_get_section_size (sectp);
10892     }
10893   else if (section_is_p (sectp->name, &names->loc_dwo))
10894     {
10895       dwo_sections->loc.s.section = sectp;
10896       dwo_sections->loc.size = bfd_get_section_size (sectp);
10897     }
10898   else if (section_is_p (sectp->name, &names->macinfo_dwo))
10899     {
10900       dwo_sections->macinfo.s.section = sectp;
10901       dwo_sections->macinfo.size = bfd_get_section_size (sectp);
10902     }
10903   else if (section_is_p (sectp->name, &names->macro_dwo))
10904     {
10905       dwo_sections->macro.s.section = sectp;
10906       dwo_sections->macro.size = bfd_get_section_size (sectp);
10907     }
10908   else if (section_is_p (sectp->name, &names->str_dwo))
10909     {
10910       dwo_sections->str.s.section = sectp;
10911       dwo_sections->str.size = bfd_get_section_size (sectp);
10912     }
10913   else if (section_is_p (sectp->name, &names->str_offsets_dwo))
10914     {
10915       dwo_sections->str_offsets.s.section = sectp;
10916       dwo_sections->str_offsets.size = bfd_get_section_size (sectp);
10917     }
10918   else if (section_is_p (sectp->name, &names->types_dwo))
10919     {
10920       struct dwarf2_section_info type_section;
10921
10922       memset (&type_section, 0, sizeof (type_section));
10923       type_section.s.section = sectp;
10924       type_section.size = bfd_get_section_size (sectp);
10925       VEC_safe_push (dwarf2_section_info_def, dwo_sections->types,
10926                      &type_section);
10927     }
10928 }
10929
10930 /* Initialize the use of the DWO file specified by DWO_NAME and referenced
10931    by PER_CU.  This is for the non-DWP case.
10932    The result is NULL if DWO_NAME can't be found.  */
10933
10934 static struct dwo_file *
10935 open_and_init_dwo_file (struct dwarf2_per_cu_data *per_cu,
10936                         const char *dwo_name, const char *comp_dir)
10937 {
10938   struct objfile *objfile = dwarf2_per_objfile->objfile;
10939   struct dwo_file *dwo_file;
10940   struct cleanup *cleanups;
10941
10942   gdb_bfd_ref_ptr dbfd (open_dwo_file (dwo_name, comp_dir));
10943   if (dbfd == NULL)
10944     {
10945       if (dwarf_read_debug)
10946         fprintf_unfiltered (gdb_stdlog, "DWO file not found: %s\n", dwo_name);
10947       return NULL;
10948     }
10949   dwo_file = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_file);
10950   dwo_file->dwo_name = dwo_name;
10951   dwo_file->comp_dir = comp_dir;
10952   dwo_file->dbfd = dbfd.release ();
10953
10954   cleanups = make_cleanup (free_dwo_file_cleanup, dwo_file);
10955
10956   bfd_map_over_sections (dwo_file->dbfd, dwarf2_locate_dwo_sections,
10957                          &dwo_file->sections);
10958
10959   create_cus_hash_table (*dwo_file, dwo_file->sections.info, dwo_file->cus);
10960
10961   create_debug_types_hash_table (dwo_file, dwo_file->sections.types,
10962                                  dwo_file->tus);
10963
10964   discard_cleanups (cleanups);
10965
10966   if (dwarf_read_debug)
10967     fprintf_unfiltered (gdb_stdlog, "DWO file found: %s\n", dwo_name);
10968
10969   return dwo_file;
10970 }
10971
10972 /* This function is mapped across the sections and remembers the offset and
10973    size of each of the DWP debugging sections common to version 1 and 2 that
10974    we are interested in.  */
10975
10976 static void
10977 dwarf2_locate_common_dwp_sections (bfd *abfd, asection *sectp,
10978                                    void *dwp_file_ptr)
10979 {
10980   struct dwp_file *dwp_file = (struct dwp_file *) dwp_file_ptr;
10981   const struct dwop_section_names *names = &dwop_section_names;
10982   unsigned int elf_section_nr = elf_section_data (sectp)->this_idx;
10983
10984   /* Record the ELF section number for later lookup: this is what the
10985      .debug_cu_index,.debug_tu_index tables use in DWP V1.  */
10986   gdb_assert (elf_section_nr < dwp_file->num_sections);
10987   dwp_file->elf_sections[elf_section_nr] = sectp;
10988
10989   /* Look for specific sections that we need.  */
10990   if (section_is_p (sectp->name, &names->str_dwo))
10991     {
10992       dwp_file->sections.str.s.section = sectp;
10993       dwp_file->sections.str.size = bfd_get_section_size (sectp);
10994     }
10995   else if (section_is_p (sectp->name, &names->cu_index))
10996     {
10997       dwp_file->sections.cu_index.s.section = sectp;
10998       dwp_file->sections.cu_index.size = bfd_get_section_size (sectp);
10999     }
11000   else if (section_is_p (sectp->name, &names->tu_index))
11001     {
11002       dwp_file->sections.tu_index.s.section = sectp;
11003       dwp_file->sections.tu_index.size = bfd_get_section_size (sectp);
11004     }
11005 }
11006
11007 /* This function is mapped across the sections and remembers the offset and
11008    size of each of the DWP version 2 debugging sections that we are interested
11009    in.  This is split into a separate function because we don't know if we
11010    have version 1 or 2 until we parse the cu_index/tu_index sections.  */
11011
11012 static void
11013 dwarf2_locate_v2_dwp_sections (bfd *abfd, asection *sectp, void *dwp_file_ptr)
11014 {
11015   struct dwp_file *dwp_file = (struct dwp_file *) dwp_file_ptr;
11016   const struct dwop_section_names *names = &dwop_section_names;
11017   unsigned int elf_section_nr = elf_section_data (sectp)->this_idx;
11018
11019   /* Record the ELF section number for later lookup: this is what the
11020      .debug_cu_index,.debug_tu_index tables use in DWP V1.  */
11021   gdb_assert (elf_section_nr < dwp_file->num_sections);
11022   dwp_file->elf_sections[elf_section_nr] = sectp;
11023
11024   /* Look for specific sections that we need.  */
11025   if (section_is_p (sectp->name, &names->abbrev_dwo))
11026     {
11027       dwp_file->sections.abbrev.s.section = sectp;
11028       dwp_file->sections.abbrev.size = bfd_get_section_size (sectp);
11029     }
11030   else if (section_is_p (sectp->name, &names->info_dwo))
11031     {
11032       dwp_file->sections.info.s.section = sectp;
11033       dwp_file->sections.info.size = bfd_get_section_size (sectp);
11034     }
11035   else if (section_is_p (sectp->name, &names->line_dwo))
11036     {
11037       dwp_file->sections.line.s.section = sectp;
11038       dwp_file->sections.line.size = bfd_get_section_size (sectp);
11039     }
11040   else if (section_is_p (sectp->name, &names->loc_dwo))
11041     {
11042       dwp_file->sections.loc.s.section = sectp;
11043       dwp_file->sections.loc.size = bfd_get_section_size (sectp);
11044     }
11045   else if (section_is_p (sectp->name, &names->macinfo_dwo))
11046     {
11047       dwp_file->sections.macinfo.s.section = sectp;
11048       dwp_file->sections.macinfo.size = bfd_get_section_size (sectp);
11049     }
11050   else if (section_is_p (sectp->name, &names->macro_dwo))
11051     {
11052       dwp_file->sections.macro.s.section = sectp;
11053       dwp_file->sections.macro.size = bfd_get_section_size (sectp);
11054     }
11055   else if (section_is_p (sectp->name, &names->str_offsets_dwo))
11056     {
11057       dwp_file->sections.str_offsets.s.section = sectp;
11058       dwp_file->sections.str_offsets.size = bfd_get_section_size (sectp);
11059     }
11060   else if (section_is_p (sectp->name, &names->types_dwo))
11061     {
11062       dwp_file->sections.types.s.section = sectp;
11063       dwp_file->sections.types.size = bfd_get_section_size (sectp);
11064     }
11065 }
11066
11067 /* Hash function for dwp_file loaded CUs/TUs.  */
11068
11069 static hashval_t
11070 hash_dwp_loaded_cutus (const void *item)
11071 {
11072   const struct dwo_unit *dwo_unit = (const struct dwo_unit *) item;
11073
11074   /* This drops the top 32 bits of the signature, but is ok for a hash.  */
11075   return dwo_unit->signature;
11076 }
11077
11078 /* Equality function for dwp_file loaded CUs/TUs.  */
11079
11080 static int
11081 eq_dwp_loaded_cutus (const void *a, const void *b)
11082 {
11083   const struct dwo_unit *dua = (const struct dwo_unit *) a;
11084   const struct dwo_unit *dub = (const struct dwo_unit *) b;
11085
11086   return dua->signature == dub->signature;
11087 }
11088
11089 /* Allocate a hash table for dwp_file loaded CUs/TUs.  */
11090
11091 static htab_t
11092 allocate_dwp_loaded_cutus_table (struct objfile *objfile)
11093 {
11094   return htab_create_alloc_ex (3,
11095                                hash_dwp_loaded_cutus,
11096                                eq_dwp_loaded_cutus,
11097                                NULL,
11098                                &objfile->objfile_obstack,
11099                                hashtab_obstack_allocate,
11100                                dummy_obstack_deallocate);
11101 }
11102
11103 /* Try to open DWP file FILE_NAME.
11104    The result is the bfd handle of the file.
11105    If there is a problem finding or opening the file, return NULL.
11106    Upon success, the canonicalized path of the file is stored in the bfd,
11107    same as symfile_bfd_open.  */
11108
11109 static gdb_bfd_ref_ptr
11110 open_dwp_file (const char *file_name)
11111 {
11112   gdb_bfd_ref_ptr abfd (try_open_dwop_file (file_name, 1 /*is_dwp*/,
11113                                             1 /*search_cwd*/));
11114   if (abfd != NULL)
11115     return abfd;
11116
11117   /* Work around upstream bug 15652.
11118      http://sourceware.org/bugzilla/show_bug.cgi?id=15652
11119      [Whether that's a "bug" is debatable, but it is getting in our way.]
11120      We have no real idea where the dwp file is, because gdb's realpath-ing
11121      of the executable's path may have discarded the needed info.
11122      [IWBN if the dwp file name was recorded in the executable, akin to
11123      .gnu_debuglink, but that doesn't exist yet.]
11124      Strip the directory from FILE_NAME and search again.  */
11125   if (*debug_file_directory != '\0')
11126     {
11127       /* Don't implicitly search the current directory here.
11128          If the user wants to search "." to handle this case,
11129          it must be added to debug-file-directory.  */
11130       return try_open_dwop_file (lbasename (file_name), 1 /*is_dwp*/,
11131                                  0 /*search_cwd*/);
11132     }
11133
11134   return NULL;
11135 }
11136
11137 /* Initialize the use of the DWP file for the current objfile.
11138    By convention the name of the DWP file is ${objfile}.dwp.
11139    The result is NULL if it can't be found.  */
11140
11141 static struct dwp_file *
11142 open_and_init_dwp_file (void)
11143 {
11144   struct objfile *objfile = dwarf2_per_objfile->objfile;
11145   struct dwp_file *dwp_file;
11146
11147   /* Try to find first .dwp for the binary file before any symbolic links
11148      resolving.  */
11149
11150   /* If the objfile is a debug file, find the name of the real binary
11151      file and get the name of dwp file from there.  */
11152   std::string dwp_name;
11153   if (objfile->separate_debug_objfile_backlink != NULL)
11154     {
11155       struct objfile *backlink = objfile->separate_debug_objfile_backlink;
11156       const char *backlink_basename = lbasename (backlink->original_name);
11157
11158       dwp_name = ldirname (objfile->original_name) + SLASH_STRING + backlink_basename;
11159     }
11160   else
11161     dwp_name = objfile->original_name;
11162
11163   dwp_name += ".dwp";
11164
11165   gdb_bfd_ref_ptr dbfd (open_dwp_file (dwp_name.c_str ()));
11166   if (dbfd == NULL
11167       && strcmp (objfile->original_name, objfile_name (objfile)) != 0)
11168     {
11169       /* Try to find .dwp for the binary file after gdb_realpath resolving.  */
11170       dwp_name = objfile_name (objfile);
11171       dwp_name += ".dwp";
11172       dbfd = open_dwp_file (dwp_name.c_str ());
11173     }
11174
11175   if (dbfd == NULL)
11176     {
11177       if (dwarf_read_debug)
11178         fprintf_unfiltered (gdb_stdlog, "DWP file not found: %s\n", dwp_name.c_str ());
11179       return NULL;
11180     }
11181   dwp_file = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwp_file);
11182   dwp_file->name = bfd_get_filename (dbfd.get ());
11183   dwp_file->dbfd = dbfd.release ();
11184
11185   /* +1: section 0 is unused */
11186   dwp_file->num_sections = bfd_count_sections (dwp_file->dbfd) + 1;
11187   dwp_file->elf_sections =
11188     OBSTACK_CALLOC (&objfile->objfile_obstack,
11189                     dwp_file->num_sections, asection *);
11190
11191   bfd_map_over_sections (dwp_file->dbfd, dwarf2_locate_common_dwp_sections,
11192                          dwp_file);
11193
11194   dwp_file->cus = create_dwp_hash_table (dwp_file, 0);
11195
11196   dwp_file->tus = create_dwp_hash_table (dwp_file, 1);
11197
11198   /* The DWP file version is stored in the hash table.  Oh well.  */
11199   if (dwp_file->cus->version != dwp_file->tus->version)
11200     {
11201       /* Technically speaking, we should try to limp along, but this is
11202          pretty bizarre.  We use pulongest here because that's the established
11203          portability solution (e.g, we cannot use %u for uint32_t).  */
11204       error (_("Dwarf Error: DWP file CU version %s doesn't match"
11205                " TU version %s [in DWP file %s]"),
11206              pulongest (dwp_file->cus->version),
11207              pulongest (dwp_file->tus->version), dwp_name.c_str ());
11208     }
11209   dwp_file->version = dwp_file->cus->version;
11210
11211   if (dwp_file->version == 2)
11212     bfd_map_over_sections (dwp_file->dbfd, dwarf2_locate_v2_dwp_sections,
11213                            dwp_file);
11214
11215   dwp_file->loaded_cus = allocate_dwp_loaded_cutus_table (objfile);
11216   dwp_file->loaded_tus = allocate_dwp_loaded_cutus_table (objfile);
11217
11218   if (dwarf_read_debug)
11219     {
11220       fprintf_unfiltered (gdb_stdlog, "DWP file found: %s\n", dwp_file->name);
11221       fprintf_unfiltered (gdb_stdlog,
11222                           "    %s CUs, %s TUs\n",
11223                           pulongest (dwp_file->cus ? dwp_file->cus->nr_units : 0),
11224                           pulongest (dwp_file->tus ? dwp_file->tus->nr_units : 0));
11225     }
11226
11227   return dwp_file;
11228 }
11229
11230 /* Wrapper around open_and_init_dwp_file, only open it once.  */
11231
11232 static struct dwp_file *
11233 get_dwp_file (void)
11234 {
11235   if (! dwarf2_per_objfile->dwp_checked)
11236     {
11237       dwarf2_per_objfile->dwp_file = open_and_init_dwp_file ();
11238       dwarf2_per_objfile->dwp_checked = 1;
11239     }
11240   return dwarf2_per_objfile->dwp_file;
11241 }
11242
11243 /* Subroutine of lookup_dwo_comp_unit, lookup_dwo_type_unit.
11244    Look up the CU/TU with signature SIGNATURE, either in DWO file DWO_NAME
11245    or in the DWP file for the objfile, referenced by THIS_UNIT.
11246    If non-NULL, comp_dir is the DW_AT_comp_dir attribute.
11247    IS_DEBUG_TYPES is non-zero if reading a TU, otherwise read a CU.
11248
11249    This is called, for example, when wanting to read a variable with a
11250    complex location.  Therefore we don't want to do file i/o for every call.
11251    Therefore we don't want to look for a DWO file on every call.
11252    Therefore we first see if we've already seen SIGNATURE in a DWP file,
11253    then we check if we've already seen DWO_NAME, and only THEN do we check
11254    for a DWO file.
11255
11256    The result is a pointer to the dwo_unit object or NULL if we didn't find it
11257    (dwo_id mismatch or couldn't find the DWO/DWP file).  */
11258
11259 static struct dwo_unit *
11260 lookup_dwo_cutu (struct dwarf2_per_cu_data *this_unit,
11261                  const char *dwo_name, const char *comp_dir,
11262                  ULONGEST signature, int is_debug_types)
11263 {
11264   struct objfile *objfile = dwarf2_per_objfile->objfile;
11265   const char *kind = is_debug_types ? "TU" : "CU";
11266   void **dwo_file_slot;
11267   struct dwo_file *dwo_file;
11268   struct dwp_file *dwp_file;
11269
11270   /* First see if there's a DWP file.
11271      If we have a DWP file but didn't find the DWO inside it, don't
11272      look for the original DWO file.  It makes gdb behave differently
11273      depending on whether one is debugging in the build tree.  */
11274
11275   dwp_file = get_dwp_file ();
11276   if (dwp_file != NULL)
11277     {
11278       const struct dwp_hash_table *dwp_htab =
11279         is_debug_types ? dwp_file->tus : dwp_file->cus;
11280
11281       if (dwp_htab != NULL)
11282         {
11283           struct dwo_unit *dwo_cutu =
11284             lookup_dwo_unit_in_dwp (dwp_file, comp_dir,
11285                                     signature, is_debug_types);
11286
11287           if (dwo_cutu != NULL)
11288             {
11289               if (dwarf_read_debug)
11290                 {
11291                   fprintf_unfiltered (gdb_stdlog,
11292                                       "Virtual DWO %s %s found: @%s\n",
11293                                       kind, hex_string (signature),
11294                                       host_address_to_string (dwo_cutu));
11295                 }
11296               return dwo_cutu;
11297             }
11298         }
11299     }
11300   else
11301     {
11302       /* No DWP file, look for the DWO file.  */
11303
11304       dwo_file_slot = lookup_dwo_file_slot (dwo_name, comp_dir);
11305       if (*dwo_file_slot == NULL)
11306         {
11307           /* Read in the file and build a table of the CUs/TUs it contains.  */
11308           *dwo_file_slot = open_and_init_dwo_file (this_unit, dwo_name, comp_dir);
11309         }
11310       /* NOTE: This will be NULL if unable to open the file.  */
11311       dwo_file = (struct dwo_file *) *dwo_file_slot;
11312
11313       if (dwo_file != NULL)
11314         {
11315           struct dwo_unit *dwo_cutu = NULL;
11316
11317           if (is_debug_types && dwo_file->tus)
11318             {
11319               struct dwo_unit find_dwo_cutu;
11320
11321               memset (&find_dwo_cutu, 0, sizeof (find_dwo_cutu));
11322               find_dwo_cutu.signature = signature;
11323               dwo_cutu
11324                 = (struct dwo_unit *) htab_find (dwo_file->tus, &find_dwo_cutu);
11325             }
11326           else if (!is_debug_types && dwo_file->cus)
11327             {
11328               struct dwo_unit find_dwo_cutu;
11329
11330               memset (&find_dwo_cutu, 0, sizeof (find_dwo_cutu));
11331               find_dwo_cutu.signature = signature;
11332               dwo_cutu = (struct dwo_unit *)htab_find (dwo_file->cus,
11333                                                        &find_dwo_cutu);
11334             }
11335
11336           if (dwo_cutu != NULL)
11337             {
11338               if (dwarf_read_debug)
11339                 {
11340                   fprintf_unfiltered (gdb_stdlog, "DWO %s %s(%s) found: @%s\n",
11341                                       kind, dwo_name, hex_string (signature),
11342                                       host_address_to_string (dwo_cutu));
11343                 }
11344               return dwo_cutu;
11345             }
11346         }
11347     }
11348
11349   /* We didn't find it.  This could mean a dwo_id mismatch, or
11350      someone deleted the DWO/DWP file, or the search path isn't set up
11351      correctly to find the file.  */
11352
11353   if (dwarf_read_debug)
11354     {
11355       fprintf_unfiltered (gdb_stdlog, "DWO %s %s(%s) not found\n",
11356                           kind, dwo_name, hex_string (signature));
11357     }
11358
11359   /* This is a warning and not a complaint because it can be caused by
11360      pilot error (e.g., user accidentally deleting the DWO).  */
11361   {
11362     /* Print the name of the DWP file if we looked there, helps the user
11363        better diagnose the problem.  */
11364     char *dwp_text = NULL;
11365     struct cleanup *cleanups;
11366
11367     if (dwp_file != NULL)
11368       dwp_text = xstrprintf (" [in DWP file %s]", lbasename (dwp_file->name));
11369     cleanups = make_cleanup (xfree, dwp_text);
11370
11371     warning (_("Could not find DWO %s %s(%s)%s referenced by %s at offset 0x%x"
11372                " [in module %s]"),
11373              kind, dwo_name, hex_string (signature),
11374              dwp_text != NULL ? dwp_text : "",
11375              this_unit->is_debug_types ? "TU" : "CU",
11376              to_underlying (this_unit->sect_off), objfile_name (objfile));
11377
11378     do_cleanups (cleanups);
11379   }
11380   return NULL;
11381 }
11382
11383 /* Lookup the DWO CU DWO_NAME/SIGNATURE referenced from THIS_CU.
11384    See lookup_dwo_cutu_unit for details.  */
11385
11386 static struct dwo_unit *
11387 lookup_dwo_comp_unit (struct dwarf2_per_cu_data *this_cu,
11388                       const char *dwo_name, const char *comp_dir,
11389                       ULONGEST signature)
11390 {
11391   return lookup_dwo_cutu (this_cu, dwo_name, comp_dir, signature, 0);
11392 }
11393
11394 /* Lookup the DWO TU DWO_NAME/SIGNATURE referenced from THIS_TU.
11395    See lookup_dwo_cutu_unit for details.  */
11396
11397 static struct dwo_unit *
11398 lookup_dwo_type_unit (struct signatured_type *this_tu,
11399                       const char *dwo_name, const char *comp_dir)
11400 {
11401   return lookup_dwo_cutu (&this_tu->per_cu, dwo_name, comp_dir, this_tu->signature, 1);
11402 }
11403
11404 /* Traversal function for queue_and_load_all_dwo_tus.  */
11405
11406 static int
11407 queue_and_load_dwo_tu (void **slot, void *info)
11408 {
11409   struct dwo_unit *dwo_unit = (struct dwo_unit *) *slot;
11410   struct dwarf2_per_cu_data *per_cu = (struct dwarf2_per_cu_data *) info;
11411   ULONGEST signature = dwo_unit->signature;
11412   struct signatured_type *sig_type =
11413     lookup_dwo_signatured_type (per_cu->cu, signature);
11414
11415   if (sig_type != NULL)
11416     {
11417       struct dwarf2_per_cu_data *sig_cu = &sig_type->per_cu;
11418
11419       /* We pass NULL for DEPENDENT_CU because we don't yet know if there's
11420          a real dependency of PER_CU on SIG_TYPE.  That is detected later
11421          while processing PER_CU.  */
11422       if (maybe_queue_comp_unit (NULL, sig_cu, per_cu->cu->language))
11423         load_full_type_unit (sig_cu);
11424       VEC_safe_push (dwarf2_per_cu_ptr, per_cu->imported_symtabs, sig_cu);
11425     }
11426
11427   return 1;
11428 }
11429
11430 /* Queue all TUs contained in the DWO of PER_CU to be read in.
11431    The DWO may have the only definition of the type, though it may not be
11432    referenced anywhere in PER_CU.  Thus we have to load *all* its TUs.
11433    http://sourceware.org/bugzilla/show_bug.cgi?id=15021  */
11434
11435 static void
11436 queue_and_load_all_dwo_tus (struct dwarf2_per_cu_data *per_cu)
11437 {
11438   struct dwo_unit *dwo_unit;
11439   struct dwo_file *dwo_file;
11440
11441   gdb_assert (!per_cu->is_debug_types);
11442   gdb_assert (get_dwp_file () == NULL);
11443   gdb_assert (per_cu->cu != NULL);
11444
11445   dwo_unit = per_cu->cu->dwo_unit;
11446   gdb_assert (dwo_unit != NULL);
11447
11448   dwo_file = dwo_unit->dwo_file;
11449   if (dwo_file->tus != NULL)
11450     htab_traverse_noresize (dwo_file->tus, queue_and_load_dwo_tu, per_cu);
11451 }
11452
11453 /* Free all resources associated with DWO_FILE.
11454    Close the DWO file and munmap the sections.
11455    All memory should be on the objfile obstack.  */
11456
11457 static void
11458 free_dwo_file (struct dwo_file *dwo_file, struct objfile *objfile)
11459 {
11460
11461   /* Note: dbfd is NULL for virtual DWO files.  */
11462   gdb_bfd_unref (dwo_file->dbfd);
11463
11464   VEC_free (dwarf2_section_info_def, dwo_file->sections.types);
11465 }
11466
11467 /* Wrapper for free_dwo_file for use in cleanups.  */
11468
11469 static void
11470 free_dwo_file_cleanup (void *arg)
11471 {
11472   struct dwo_file *dwo_file = (struct dwo_file *) arg;
11473   struct objfile *objfile = dwarf2_per_objfile->objfile;
11474
11475   free_dwo_file (dwo_file, objfile);
11476 }
11477
11478 /* Traversal function for free_dwo_files.  */
11479
11480 static int
11481 free_dwo_file_from_slot (void **slot, void *info)
11482 {
11483   struct dwo_file *dwo_file = (struct dwo_file *) *slot;
11484   struct objfile *objfile = (struct objfile *) info;
11485
11486   free_dwo_file (dwo_file, objfile);
11487
11488   return 1;
11489 }
11490
11491 /* Free all resources associated with DWO_FILES.  */
11492
11493 static void
11494 free_dwo_files (htab_t dwo_files, struct objfile *objfile)
11495 {
11496   htab_traverse_noresize (dwo_files, free_dwo_file_from_slot, objfile);
11497 }
11498 \f
11499 /* Read in various DIEs.  */
11500
11501 /* qsort helper for inherit_abstract_dies.  */
11502
11503 static int
11504 unsigned_int_compar (const void *ap, const void *bp)
11505 {
11506   unsigned int a = *(unsigned int *) ap;
11507   unsigned int b = *(unsigned int *) bp;
11508
11509   return (a > b) - (b > a);
11510 }
11511
11512 /* DW_AT_abstract_origin inherits whole DIEs (not just their attributes).
11513    Inherit only the children of the DW_AT_abstract_origin DIE not being
11514    already referenced by DW_AT_abstract_origin from the children of the
11515    current DIE.  */
11516
11517 static void
11518 inherit_abstract_dies (struct die_info *die, struct dwarf2_cu *cu)
11519 {
11520   struct die_info *child_die;
11521   unsigned die_children_count;
11522   /* CU offsets which were referenced by children of the current DIE.  */
11523   sect_offset *offsets;
11524   sect_offset *offsets_end, *offsetp;
11525   /* Parent of DIE - referenced by DW_AT_abstract_origin.  */
11526   struct die_info *origin_die;
11527   /* Iterator of the ORIGIN_DIE children.  */
11528   struct die_info *origin_child_die;
11529   struct cleanup *cleanups;
11530   struct attribute *attr;
11531   struct dwarf2_cu *origin_cu;
11532   struct pending **origin_previous_list_in_scope;
11533
11534   attr = dwarf2_attr (die, DW_AT_abstract_origin, cu);
11535   if (!attr)
11536     return;
11537
11538   /* Note that following die references may follow to a die in a
11539      different cu.  */
11540
11541   origin_cu = cu;
11542   origin_die = follow_die_ref (die, attr, &origin_cu);
11543
11544   /* We're inheriting ORIGIN's children into the scope we'd put DIE's
11545      symbols in.  */
11546   origin_previous_list_in_scope = origin_cu->list_in_scope;
11547   origin_cu->list_in_scope = cu->list_in_scope;
11548
11549   if (die->tag != origin_die->tag
11550       && !(die->tag == DW_TAG_inlined_subroutine
11551            && origin_die->tag == DW_TAG_subprogram))
11552     complaint (&symfile_complaints,
11553                _("DIE 0x%x and its abstract origin 0x%x have different tags"),
11554                to_underlying (die->sect_off),
11555                to_underlying (origin_die->sect_off));
11556
11557   child_die = die->child;
11558   die_children_count = 0;
11559   while (child_die && child_die->tag)
11560     {
11561       child_die = sibling_die (child_die);
11562       die_children_count++;
11563     }
11564   offsets = XNEWVEC (sect_offset, die_children_count);
11565   cleanups = make_cleanup (xfree, offsets);
11566
11567   offsets_end = offsets;
11568   for (child_die = die->child;
11569        child_die && child_die->tag;
11570        child_die = sibling_die (child_die))
11571     {
11572       struct die_info *child_origin_die;
11573       struct dwarf2_cu *child_origin_cu;
11574
11575       /* We are trying to process concrete instance entries:
11576          DW_TAG_call_site DIEs indeed have a DW_AT_abstract_origin tag, but
11577          it's not relevant to our analysis here. i.e. detecting DIEs that are
11578          present in the abstract instance but not referenced in the concrete
11579          one.  */
11580       if (child_die->tag == DW_TAG_call_site
11581           || child_die->tag == DW_TAG_GNU_call_site)
11582         continue;
11583
11584       /* For each CHILD_DIE, find the corresponding child of
11585          ORIGIN_DIE.  If there is more than one layer of
11586          DW_AT_abstract_origin, follow them all; there shouldn't be,
11587          but GCC versions at least through 4.4 generate this (GCC PR
11588          40573).  */
11589       child_origin_die = child_die;
11590       child_origin_cu = cu;
11591       while (1)
11592         {
11593           attr = dwarf2_attr (child_origin_die, DW_AT_abstract_origin,
11594                               child_origin_cu);
11595           if (attr == NULL)
11596             break;
11597           child_origin_die = follow_die_ref (child_origin_die, attr,
11598                                              &child_origin_cu);
11599         }
11600
11601       /* According to DWARF3 3.3.8.2 #3 new entries without their abstract
11602          counterpart may exist.  */
11603       if (child_origin_die != child_die)
11604         {
11605           if (child_die->tag != child_origin_die->tag
11606               && !(child_die->tag == DW_TAG_inlined_subroutine
11607                    && child_origin_die->tag == DW_TAG_subprogram))
11608             complaint (&symfile_complaints,
11609                        _("Child DIE 0x%x and its abstract origin 0x%x have "
11610                          "different tags"),
11611                        to_underlying (child_die->sect_off),
11612                        to_underlying (child_origin_die->sect_off));
11613           if (child_origin_die->parent != origin_die)
11614             complaint (&symfile_complaints,
11615                        _("Child DIE 0x%x and its abstract origin 0x%x have "
11616                          "different parents"),
11617                        to_underlying (child_die->sect_off),
11618                        to_underlying (child_origin_die->sect_off));
11619           else
11620             *offsets_end++ = child_origin_die->sect_off;
11621         }
11622     }
11623   qsort (offsets, offsets_end - offsets, sizeof (*offsets),
11624          unsigned_int_compar);
11625   for (offsetp = offsets + 1; offsetp < offsets_end; offsetp++)
11626     if (offsetp[-1] == *offsetp)
11627       complaint (&symfile_complaints,
11628                  _("Multiple children of DIE 0x%x refer "
11629                    "to DIE 0x%x as their abstract origin"),
11630                  to_underlying (die->sect_off), to_underlying (*offsetp));
11631
11632   offsetp = offsets;
11633   origin_child_die = origin_die->child;
11634   while (origin_child_die && origin_child_die->tag)
11635     {
11636       /* Is ORIGIN_CHILD_DIE referenced by any of the DIE children?  */
11637       while (offsetp < offsets_end
11638              && *offsetp < origin_child_die->sect_off)
11639         offsetp++;
11640       if (offsetp >= offsets_end
11641           || *offsetp > origin_child_die->sect_off)
11642         {
11643           /* Found that ORIGIN_CHILD_DIE is really not referenced.
11644              Check whether we're already processing ORIGIN_CHILD_DIE.
11645              This can happen with mutually referenced abstract_origins.
11646              PR 16581.  */
11647           if (!origin_child_die->in_process)
11648             process_die (origin_child_die, origin_cu);
11649         }
11650       origin_child_die = sibling_die (origin_child_die);
11651     }
11652   origin_cu->list_in_scope = origin_previous_list_in_scope;
11653
11654   do_cleanups (cleanups);
11655 }
11656
11657 static void
11658 read_func_scope (struct die_info *die, struct dwarf2_cu *cu)
11659 {
11660   struct objfile *objfile = cu->objfile;
11661   struct gdbarch *gdbarch = get_objfile_arch (objfile);
11662   struct context_stack *newobj;
11663   CORE_ADDR lowpc;
11664   CORE_ADDR highpc;
11665   struct die_info *child_die;
11666   struct attribute *attr, *call_line, *call_file;
11667   const char *name;
11668   CORE_ADDR baseaddr;
11669   struct block *block;
11670   int inlined_func = (die->tag == DW_TAG_inlined_subroutine);
11671   VEC (symbolp) *template_args = NULL;
11672   struct template_symbol *templ_func = NULL;
11673
11674   if (inlined_func)
11675     {
11676       /* If we do not have call site information, we can't show the
11677          caller of this inlined function.  That's too confusing, so
11678          only use the scope for local variables.  */
11679       call_line = dwarf2_attr (die, DW_AT_call_line, cu);
11680       call_file = dwarf2_attr (die, DW_AT_call_file, cu);
11681       if (call_line == NULL || call_file == NULL)
11682         {
11683           read_lexical_block_scope (die, cu);
11684           return;
11685         }
11686     }
11687
11688   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
11689
11690   name = dwarf2_name (die, cu);
11691
11692   /* Ignore functions with missing or empty names.  These are actually
11693      illegal according to the DWARF standard.  */
11694   if (name == NULL)
11695     {
11696       complaint (&symfile_complaints,
11697                  _("missing name for subprogram DIE at %d"),
11698                  to_underlying (die->sect_off));
11699       return;
11700     }
11701
11702   /* Ignore functions with missing or invalid low and high pc attributes.  */
11703   if (dwarf2_get_pc_bounds (die, &lowpc, &highpc, cu, NULL)
11704       <= PC_BOUNDS_INVALID)
11705     {
11706       attr = dwarf2_attr (die, DW_AT_external, cu);
11707       if (!attr || !DW_UNSND (attr))
11708         complaint (&symfile_complaints,
11709                    _("cannot get low and high bounds "
11710                      "for subprogram DIE at %d"),
11711                    to_underlying (die->sect_off));
11712       return;
11713     }
11714
11715   lowpc = gdbarch_adjust_dwarf2_addr (gdbarch, lowpc + baseaddr);
11716   highpc = gdbarch_adjust_dwarf2_addr (gdbarch, highpc + baseaddr);
11717
11718   /* If we have any template arguments, then we must allocate a
11719      different sort of symbol.  */
11720   for (child_die = die->child; child_die; child_die = sibling_die (child_die))
11721     {
11722       if (child_die->tag == DW_TAG_template_type_param
11723           || child_die->tag == DW_TAG_template_value_param)
11724         {
11725           templ_func = allocate_template_symbol (objfile);
11726           templ_func->base.is_cplus_template_function = 1;
11727           break;
11728         }
11729     }
11730
11731   newobj = push_context (0, lowpc);
11732   newobj->name = new_symbol_full (die, read_type_die (die, cu), cu,
11733                                (struct symbol *) templ_func);
11734
11735   /* If there is a location expression for DW_AT_frame_base, record
11736      it.  */
11737   attr = dwarf2_attr (die, DW_AT_frame_base, cu);
11738   if (attr)
11739     dwarf2_symbol_mark_computed (attr, newobj->name, cu, 1);
11740
11741   /* If there is a location for the static link, record it.  */
11742   newobj->static_link = NULL;
11743   attr = dwarf2_attr (die, DW_AT_static_link, cu);
11744   if (attr)
11745     {
11746       newobj->static_link
11747         = XOBNEW (&objfile->objfile_obstack, struct dynamic_prop);
11748       attr_to_dynamic_prop (attr, die, cu, newobj->static_link);
11749     }
11750
11751   cu->list_in_scope = &local_symbols;
11752
11753   if (die->child != NULL)
11754     {
11755       child_die = die->child;
11756       while (child_die && child_die->tag)
11757         {
11758           if (child_die->tag == DW_TAG_template_type_param
11759               || child_die->tag == DW_TAG_template_value_param)
11760             {
11761               struct symbol *arg = new_symbol (child_die, NULL, cu);
11762
11763               if (arg != NULL)
11764                 VEC_safe_push (symbolp, template_args, arg);
11765             }
11766           else
11767             process_die (child_die, cu);
11768           child_die = sibling_die (child_die);
11769         }
11770     }
11771
11772   inherit_abstract_dies (die, cu);
11773
11774   /* If we have a DW_AT_specification, we might need to import using
11775      directives from the context of the specification DIE.  See the
11776      comment in determine_prefix.  */
11777   if (cu->language == language_cplus
11778       && dwarf2_attr (die, DW_AT_specification, cu))
11779     {
11780       struct dwarf2_cu *spec_cu = cu;
11781       struct die_info *spec_die = die_specification (die, &spec_cu);
11782
11783       while (spec_die)
11784         {
11785           child_die = spec_die->child;
11786           while (child_die && child_die->tag)
11787             {
11788               if (child_die->tag == DW_TAG_imported_module)
11789                 process_die (child_die, spec_cu);
11790               child_die = sibling_die (child_die);
11791             }
11792
11793           /* In some cases, GCC generates specification DIEs that
11794              themselves contain DW_AT_specification attributes.  */
11795           spec_die = die_specification (spec_die, &spec_cu);
11796         }
11797     }
11798
11799   newobj = pop_context ();
11800   /* Make a block for the local symbols within.  */
11801   block = finish_block (newobj->name, &local_symbols, newobj->old_blocks,
11802                         newobj->static_link, lowpc, highpc);
11803
11804   /* For C++, set the block's scope.  */
11805   if ((cu->language == language_cplus
11806        || cu->language == language_fortran
11807        || cu->language == language_d
11808        || cu->language == language_rust)
11809       && cu->processing_has_namespace_info)
11810     block_set_scope (block, determine_prefix (die, cu),
11811                      &objfile->objfile_obstack);
11812
11813   /* If we have address ranges, record them.  */
11814   dwarf2_record_block_ranges (die, block, baseaddr, cu);
11815
11816   gdbarch_make_symbol_special (gdbarch, newobj->name, objfile);
11817
11818   /* Attach template arguments to function.  */
11819   if (! VEC_empty (symbolp, template_args))
11820     {
11821       gdb_assert (templ_func != NULL);
11822
11823       templ_func->n_template_arguments = VEC_length (symbolp, template_args);
11824       templ_func->template_arguments
11825         = XOBNEWVEC (&objfile->objfile_obstack, struct symbol *,
11826                      templ_func->n_template_arguments);
11827       memcpy (templ_func->template_arguments,
11828               VEC_address (symbolp, template_args),
11829               (templ_func->n_template_arguments * sizeof (struct symbol *)));
11830       VEC_free (symbolp, template_args);
11831     }
11832
11833   /* In C++, we can have functions nested inside functions (e.g., when
11834      a function declares a class that has methods).  This means that
11835      when we finish processing a function scope, we may need to go
11836      back to building a containing block's symbol lists.  */
11837   local_symbols = newobj->locals;
11838   local_using_directives = newobj->local_using_directives;
11839
11840   /* If we've finished processing a top-level function, subsequent
11841      symbols go in the file symbol list.  */
11842   if (outermost_context_p ())
11843     cu->list_in_scope = &file_symbols;
11844 }
11845
11846 /* Process all the DIES contained within a lexical block scope.  Start
11847    a new scope, process the dies, and then close the scope.  */
11848
11849 static void
11850 read_lexical_block_scope (struct die_info *die, struct dwarf2_cu *cu)
11851 {
11852   struct objfile *objfile = cu->objfile;
11853   struct gdbarch *gdbarch = get_objfile_arch (objfile);
11854   struct context_stack *newobj;
11855   CORE_ADDR lowpc, highpc;
11856   struct die_info *child_die;
11857   CORE_ADDR baseaddr;
11858
11859   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
11860
11861   /* Ignore blocks with missing or invalid low and high pc attributes.  */
11862   /* ??? Perhaps consider discontiguous blocks defined by DW_AT_ranges
11863      as multiple lexical blocks?  Handling children in a sane way would
11864      be nasty.  Might be easier to properly extend generic blocks to
11865      describe ranges.  */
11866   switch (dwarf2_get_pc_bounds (die, &lowpc, &highpc, cu, NULL))
11867     {
11868     case PC_BOUNDS_NOT_PRESENT:
11869       /* DW_TAG_lexical_block has no attributes, process its children as if
11870          there was no wrapping by that DW_TAG_lexical_block.
11871          GCC does no longer produces such DWARF since GCC r224161.  */
11872       for (child_die = die->child;
11873            child_die != NULL && child_die->tag;
11874            child_die = sibling_die (child_die))
11875         process_die (child_die, cu);
11876       return;
11877     case PC_BOUNDS_INVALID:
11878       return;
11879     }
11880   lowpc = gdbarch_adjust_dwarf2_addr (gdbarch, lowpc + baseaddr);
11881   highpc = gdbarch_adjust_dwarf2_addr (gdbarch, highpc + baseaddr);
11882
11883   push_context (0, lowpc);
11884   if (die->child != NULL)
11885     {
11886       child_die = die->child;
11887       while (child_die && child_die->tag)
11888         {
11889           process_die (child_die, cu);
11890           child_die = sibling_die (child_die);
11891         }
11892     }
11893   inherit_abstract_dies (die, cu);
11894   newobj = pop_context ();
11895
11896   if (local_symbols != NULL || local_using_directives != NULL)
11897     {
11898       struct block *block
11899         = finish_block (0, &local_symbols, newobj->old_blocks, NULL,
11900                         newobj->start_addr, highpc);
11901
11902       /* Note that recording ranges after traversing children, as we
11903          do here, means that recording a parent's ranges entails
11904          walking across all its children's ranges as they appear in
11905          the address map, which is quadratic behavior.
11906
11907          It would be nicer to record the parent's ranges before
11908          traversing its children, simply overriding whatever you find
11909          there.  But since we don't even decide whether to create a
11910          block until after we've traversed its children, that's hard
11911          to do.  */
11912       dwarf2_record_block_ranges (die, block, baseaddr, cu);
11913     }
11914   local_symbols = newobj->locals;
11915   local_using_directives = newobj->local_using_directives;
11916 }
11917
11918 /* Read in DW_TAG_call_site and insert it to CU->call_site_htab.  */
11919
11920 static void
11921 read_call_site_scope (struct die_info *die, struct dwarf2_cu *cu)
11922 {
11923   struct objfile *objfile = cu->objfile;
11924   struct gdbarch *gdbarch = get_objfile_arch (objfile);
11925   CORE_ADDR pc, baseaddr;
11926   struct attribute *attr;
11927   struct call_site *call_site, call_site_local;
11928   void **slot;
11929   int nparams;
11930   struct die_info *child_die;
11931
11932   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
11933
11934   attr = dwarf2_attr (die, DW_AT_call_return_pc, cu);
11935   if (attr == NULL)
11936     {
11937       /* This was a pre-DWARF-5 GNU extension alias
11938          for DW_AT_call_return_pc.  */
11939       attr = dwarf2_attr (die, DW_AT_low_pc, cu);
11940     }
11941   if (!attr)
11942     {
11943       complaint (&symfile_complaints,
11944                  _("missing DW_AT_call_return_pc for DW_TAG_call_site "
11945                    "DIE 0x%x [in module %s]"),
11946                  to_underlying (die->sect_off), objfile_name (objfile));
11947       return;
11948     }
11949   pc = attr_value_as_address (attr) + baseaddr;
11950   pc = gdbarch_adjust_dwarf2_addr (gdbarch, pc);
11951
11952   if (cu->call_site_htab == NULL)
11953     cu->call_site_htab = htab_create_alloc_ex (16, core_addr_hash, core_addr_eq,
11954                                                NULL, &objfile->objfile_obstack,
11955                                                hashtab_obstack_allocate, NULL);
11956   call_site_local.pc = pc;
11957   slot = htab_find_slot (cu->call_site_htab, &call_site_local, INSERT);
11958   if (*slot != NULL)
11959     {
11960       complaint (&symfile_complaints,
11961                  _("Duplicate PC %s for DW_TAG_call_site "
11962                    "DIE 0x%x [in module %s]"),
11963                  paddress (gdbarch, pc), to_underlying (die->sect_off),
11964                  objfile_name (objfile));
11965       return;
11966     }
11967
11968   /* Count parameters at the caller.  */
11969
11970   nparams = 0;
11971   for (child_die = die->child; child_die && child_die->tag;
11972        child_die = sibling_die (child_die))
11973     {
11974       if (child_die->tag != DW_TAG_call_site_parameter
11975           && child_die->tag != DW_TAG_GNU_call_site_parameter)
11976         {
11977           complaint (&symfile_complaints,
11978                      _("Tag %d is not DW_TAG_call_site_parameter in "
11979                        "DW_TAG_call_site child DIE 0x%x [in module %s]"),
11980                      child_die->tag, to_underlying (child_die->sect_off),
11981                      objfile_name (objfile));
11982           continue;
11983         }
11984
11985       nparams++;
11986     }
11987
11988   call_site
11989     = ((struct call_site *)
11990        obstack_alloc (&objfile->objfile_obstack,
11991                       sizeof (*call_site)
11992                       + (sizeof (*call_site->parameter) * (nparams - 1))));
11993   *slot = call_site;
11994   memset (call_site, 0, sizeof (*call_site) - sizeof (*call_site->parameter));
11995   call_site->pc = pc;
11996
11997   if (dwarf2_flag_true_p (die, DW_AT_call_tail_call, cu)
11998       || dwarf2_flag_true_p (die, DW_AT_GNU_tail_call, cu))
11999     {
12000       struct die_info *func_die;
12001
12002       /* Skip also over DW_TAG_inlined_subroutine.  */
12003       for (func_die = die->parent;
12004            func_die && func_die->tag != DW_TAG_subprogram
12005            && func_die->tag != DW_TAG_subroutine_type;
12006            func_die = func_die->parent);
12007
12008       /* DW_AT_call_all_calls is a superset
12009          of DW_AT_call_all_tail_calls.  */
12010       if (func_die
12011           && !dwarf2_flag_true_p (func_die, DW_AT_call_all_calls, cu)
12012           && !dwarf2_flag_true_p (func_die, DW_AT_GNU_all_call_sites, cu)
12013           && !dwarf2_flag_true_p (func_die, DW_AT_call_all_tail_calls, cu)
12014           && !dwarf2_flag_true_p (func_die, DW_AT_GNU_all_tail_call_sites, cu))
12015         {
12016           /* TYPE_TAIL_CALL_LIST is not interesting in functions where it is
12017              not complete.  But keep CALL_SITE for look ups via call_site_htab,
12018              both the initial caller containing the real return address PC and
12019              the final callee containing the current PC of a chain of tail
12020              calls do not need to have the tail call list complete.  But any
12021              function candidate for a virtual tail call frame searched via
12022              TYPE_TAIL_CALL_LIST must have the tail call list complete to be
12023              determined unambiguously.  */
12024         }
12025       else
12026         {
12027           struct type *func_type = NULL;
12028
12029           if (func_die)
12030             func_type = get_die_type (func_die, cu);
12031           if (func_type != NULL)
12032             {
12033               gdb_assert (TYPE_CODE (func_type) == TYPE_CODE_FUNC);
12034
12035               /* Enlist this call site to the function.  */
12036               call_site->tail_call_next = TYPE_TAIL_CALL_LIST (func_type);
12037               TYPE_TAIL_CALL_LIST (func_type) = call_site;
12038             }
12039           else
12040             complaint (&symfile_complaints,
12041                        _("Cannot find function owning DW_TAG_call_site "
12042                          "DIE 0x%x [in module %s]"),
12043                        to_underlying (die->sect_off), objfile_name (objfile));
12044         }
12045     }
12046
12047   attr = dwarf2_attr (die, DW_AT_call_target, cu);
12048   if (attr == NULL)
12049     attr = dwarf2_attr (die, DW_AT_GNU_call_site_target, cu);
12050   if (attr == NULL)
12051     attr = dwarf2_attr (die, DW_AT_call_origin, cu);
12052   if (attr == NULL)
12053     {
12054       /* This was a pre-DWARF-5 GNU extension alias for DW_AT_call_origin.  */
12055       attr = dwarf2_attr (die, DW_AT_abstract_origin, cu);
12056     }
12057   SET_FIELD_DWARF_BLOCK (call_site->target, NULL);
12058   if (!attr || (attr_form_is_block (attr) && DW_BLOCK (attr)->size == 0))
12059     /* Keep NULL DWARF_BLOCK.  */;
12060   else if (attr_form_is_block (attr))
12061     {
12062       struct dwarf2_locexpr_baton *dlbaton;
12063
12064       dlbaton = XOBNEW (&objfile->objfile_obstack, struct dwarf2_locexpr_baton);
12065       dlbaton->data = DW_BLOCK (attr)->data;
12066       dlbaton->size = DW_BLOCK (attr)->size;
12067       dlbaton->per_cu = cu->per_cu;
12068
12069       SET_FIELD_DWARF_BLOCK (call_site->target, dlbaton);
12070     }
12071   else if (attr_form_is_ref (attr))
12072     {
12073       struct dwarf2_cu *target_cu = cu;
12074       struct die_info *target_die;
12075
12076       target_die = follow_die_ref (die, attr, &target_cu);
12077       gdb_assert (target_cu->objfile == objfile);
12078       if (die_is_declaration (target_die, target_cu))
12079         {
12080           const char *target_physname;
12081
12082           /* Prefer the mangled name; otherwise compute the demangled one.  */
12083           target_physname = dw2_linkage_name (target_die, target_cu);
12084           if (target_physname == NULL)
12085             target_physname = dwarf2_physname (NULL, target_die, target_cu);
12086           if (target_physname == NULL)
12087             complaint (&symfile_complaints,
12088                        _("DW_AT_call_target target DIE has invalid "
12089                          "physname, for referencing DIE 0x%x [in module %s]"),
12090                        to_underlying (die->sect_off), objfile_name (objfile));
12091           else
12092             SET_FIELD_PHYSNAME (call_site->target, target_physname);
12093         }
12094       else
12095         {
12096           CORE_ADDR lowpc;
12097
12098           /* DW_AT_entry_pc should be preferred.  */
12099           if (dwarf2_get_pc_bounds (target_die, &lowpc, NULL, target_cu, NULL)
12100               <= PC_BOUNDS_INVALID)
12101             complaint (&symfile_complaints,
12102                        _("DW_AT_call_target target DIE has invalid "
12103                          "low pc, for referencing DIE 0x%x [in module %s]"),
12104                        to_underlying (die->sect_off), objfile_name (objfile));
12105           else
12106             {
12107               lowpc = gdbarch_adjust_dwarf2_addr (gdbarch, lowpc + baseaddr);
12108               SET_FIELD_PHYSADDR (call_site->target, lowpc);
12109             }
12110         }
12111     }
12112   else
12113     complaint (&symfile_complaints,
12114                _("DW_TAG_call_site DW_AT_call_target is neither "
12115                  "block nor reference, for DIE 0x%x [in module %s]"),
12116                to_underlying (die->sect_off), objfile_name (objfile));
12117
12118   call_site->per_cu = cu->per_cu;
12119
12120   for (child_die = die->child;
12121        child_die && child_die->tag;
12122        child_die = sibling_die (child_die))
12123     {
12124       struct call_site_parameter *parameter;
12125       struct attribute *loc, *origin;
12126
12127       if (child_die->tag != DW_TAG_call_site_parameter
12128           && child_die->tag != DW_TAG_GNU_call_site_parameter)
12129         {
12130           /* Already printed the complaint above.  */
12131           continue;
12132         }
12133
12134       gdb_assert (call_site->parameter_count < nparams);
12135       parameter = &call_site->parameter[call_site->parameter_count];
12136
12137       /* DW_AT_location specifies the register number or DW_AT_abstract_origin
12138          specifies DW_TAG_formal_parameter.  Value of the data assumed for the
12139          register is contained in DW_AT_call_value.  */
12140
12141       loc = dwarf2_attr (child_die, DW_AT_location, cu);
12142       origin = dwarf2_attr (child_die, DW_AT_call_parameter, cu);
12143       if (origin == NULL)
12144         {
12145           /* This was a pre-DWARF-5 GNU extension alias
12146              for DW_AT_call_parameter.  */
12147           origin = dwarf2_attr (child_die, DW_AT_abstract_origin, cu);
12148         }
12149       if (loc == NULL && origin != NULL && attr_form_is_ref (origin))
12150         {
12151           parameter->kind = CALL_SITE_PARAMETER_PARAM_OFFSET;
12152
12153           sect_offset sect_off
12154             = (sect_offset) dwarf2_get_ref_die_offset (origin);
12155           if (!offset_in_cu_p (&cu->header, sect_off))
12156             {
12157               /* As DW_OP_GNU_parameter_ref uses CU-relative offset this
12158                  binding can be done only inside one CU.  Such referenced DIE
12159                  therefore cannot be even moved to DW_TAG_partial_unit.  */
12160               complaint (&symfile_complaints,
12161                          _("DW_AT_call_parameter offset is not in CU for "
12162                            "DW_TAG_call_site child DIE 0x%x [in module %s]"),
12163                          to_underlying (child_die->sect_off),
12164                          objfile_name (objfile));
12165               continue;
12166             }
12167           parameter->u.param_cu_off
12168             = (cu_offset) (sect_off - cu->header.sect_off);
12169         }
12170       else if (loc == NULL || origin != NULL || !attr_form_is_block (loc))
12171         {
12172           complaint (&symfile_complaints,
12173                      _("No DW_FORM_block* DW_AT_location for "
12174                        "DW_TAG_call_site child DIE 0x%x [in module %s]"),
12175                      to_underlying (child_die->sect_off), objfile_name (objfile));
12176           continue;
12177         }
12178       else
12179         {
12180           parameter->u.dwarf_reg = dwarf_block_to_dwarf_reg
12181             (DW_BLOCK (loc)->data, &DW_BLOCK (loc)->data[DW_BLOCK (loc)->size]);
12182           if (parameter->u.dwarf_reg != -1)
12183             parameter->kind = CALL_SITE_PARAMETER_DWARF_REG;
12184           else if (dwarf_block_to_sp_offset (gdbarch, DW_BLOCK (loc)->data,
12185                                     &DW_BLOCK (loc)->data[DW_BLOCK (loc)->size],
12186                                              &parameter->u.fb_offset))
12187             parameter->kind = CALL_SITE_PARAMETER_FB_OFFSET;
12188           else
12189             {
12190               complaint (&symfile_complaints,
12191                          _("Only single DW_OP_reg or DW_OP_fbreg is supported "
12192                            "for DW_FORM_block* DW_AT_location is supported for "
12193                            "DW_TAG_call_site child DIE 0x%x "
12194                            "[in module %s]"),
12195                          to_underlying (child_die->sect_off),
12196                          objfile_name (objfile));
12197               continue;
12198             }
12199         }
12200
12201       attr = dwarf2_attr (child_die, DW_AT_call_value, cu);
12202       if (attr == NULL)
12203         attr = dwarf2_attr (child_die, DW_AT_GNU_call_site_value, cu);
12204       if (!attr_form_is_block (attr))
12205         {
12206           complaint (&symfile_complaints,
12207                      _("No DW_FORM_block* DW_AT_call_value for "
12208                        "DW_TAG_call_site child DIE 0x%x [in module %s]"),
12209                      to_underlying (child_die->sect_off),
12210                      objfile_name (objfile));
12211           continue;
12212         }
12213       parameter->value = DW_BLOCK (attr)->data;
12214       parameter->value_size = DW_BLOCK (attr)->size;
12215
12216       /* Parameters are not pre-cleared by memset above.  */
12217       parameter->data_value = NULL;
12218       parameter->data_value_size = 0;
12219       call_site->parameter_count++;
12220
12221       attr = dwarf2_attr (child_die, DW_AT_call_data_value, cu);
12222       if (attr == NULL)
12223         attr = dwarf2_attr (child_die, DW_AT_GNU_call_site_data_value, cu);
12224       if (attr)
12225         {
12226           if (!attr_form_is_block (attr))
12227             complaint (&symfile_complaints,
12228                        _("No DW_FORM_block* DW_AT_call_data_value for "
12229                          "DW_TAG_call_site child DIE 0x%x [in module %s]"),
12230                        to_underlying (child_die->sect_off),
12231                        objfile_name (objfile));
12232           else
12233             {
12234               parameter->data_value = DW_BLOCK (attr)->data;
12235               parameter->data_value_size = DW_BLOCK (attr)->size;
12236             }
12237         }
12238     }
12239 }
12240
12241 /* Call CALLBACK from DW_AT_ranges attribute value OFFSET
12242    reading .debug_rnglists.
12243    Callback's type should be:
12244     void (CORE_ADDR range_beginning, CORE_ADDR range_end)
12245    Return true if the attributes are present and valid, otherwise,
12246    return false.  */
12247
12248 template <typename Callback>
12249 static bool
12250 dwarf2_rnglists_process (unsigned offset, struct dwarf2_cu *cu,
12251                          Callback &&callback)
12252 {
12253   struct objfile *objfile = cu->objfile;
12254   struct gdbarch *gdbarch = get_objfile_arch (objfile);
12255   struct comp_unit_head *cu_header = &cu->header;
12256   bfd *obfd = objfile->obfd;
12257   unsigned int addr_size = cu_header->addr_size;
12258   CORE_ADDR mask = ~(~(CORE_ADDR)1 << (addr_size * 8 - 1));
12259   /* Base address selection entry.  */
12260   CORE_ADDR base;
12261   int found_base;
12262   unsigned int dummy;
12263   const gdb_byte *buffer;
12264   CORE_ADDR low = 0;
12265   CORE_ADDR high = 0;
12266   CORE_ADDR baseaddr;
12267   bool overflow = false;
12268
12269   found_base = cu->base_known;
12270   base = cu->base_address;
12271
12272   dwarf2_read_section (objfile, &dwarf2_per_objfile->rnglists);
12273   if (offset >= dwarf2_per_objfile->rnglists.size)
12274     {
12275       complaint (&symfile_complaints,
12276                  _("Offset %d out of bounds for DW_AT_ranges attribute"),
12277                  offset);
12278       return false;
12279     }
12280   buffer = dwarf2_per_objfile->rnglists.buffer + offset;
12281
12282   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
12283
12284   while (1)
12285     {
12286       /* Initialize it due to a false compiler warning.  */
12287       CORE_ADDR range_beginning = 0, range_end = 0;
12288       const gdb_byte *buf_end = (dwarf2_per_objfile->rnglists.buffer
12289                                  + dwarf2_per_objfile->rnglists.size);
12290       unsigned int bytes_read;
12291
12292       if (buffer == buf_end)
12293         {
12294           overflow = true;
12295           break;
12296         }
12297       const auto rlet = static_cast<enum dwarf_range_list_entry>(*buffer++);
12298       switch (rlet)
12299         {
12300         case DW_RLE_end_of_list:
12301           break;
12302         case DW_RLE_base_address:
12303           if (buffer + cu->header.addr_size > buf_end)
12304             {
12305               overflow = true;
12306               break;
12307             }
12308           base = read_address (obfd, buffer, cu, &bytes_read);
12309           found_base = 1;
12310           buffer += bytes_read;
12311           break;
12312         case DW_RLE_start_length:
12313           if (buffer + cu->header.addr_size > buf_end)
12314             {
12315               overflow = true;
12316               break;
12317             }
12318           range_beginning = read_address (obfd, buffer, cu, &bytes_read);
12319           buffer += bytes_read;
12320           range_end = (range_beginning
12321                        + read_unsigned_leb128 (obfd, buffer, &bytes_read));
12322           buffer += bytes_read;
12323           if (buffer > buf_end)
12324             {
12325               overflow = true;
12326               break;
12327             }
12328           break;
12329         case DW_RLE_offset_pair:
12330           range_beginning = read_unsigned_leb128 (obfd, buffer, &bytes_read);
12331           buffer += bytes_read;
12332           if (buffer > buf_end)
12333             {
12334               overflow = true;
12335               break;
12336             }
12337           range_end = read_unsigned_leb128 (obfd, buffer, &bytes_read);
12338           buffer += bytes_read;
12339           if (buffer > buf_end)
12340             {
12341               overflow = true;
12342               break;
12343             }
12344           break;
12345         case DW_RLE_start_end:
12346           if (buffer + 2 * cu->header.addr_size > buf_end)
12347             {
12348               overflow = true;
12349               break;
12350             }
12351           range_beginning = read_address (obfd, buffer, cu, &bytes_read);
12352           buffer += bytes_read;
12353           range_end = read_address (obfd, buffer, cu, &bytes_read);
12354           buffer += bytes_read;
12355           break;
12356         default:
12357           complaint (&symfile_complaints,
12358                      _("Invalid .debug_rnglists data (no base address)"));
12359           return false;
12360         }
12361       if (rlet == DW_RLE_end_of_list || overflow)
12362         break;
12363       if (rlet == DW_RLE_base_address)
12364         continue;
12365
12366       if (!found_base)
12367         {
12368           /* We have no valid base address for the ranges
12369              data.  */
12370           complaint (&symfile_complaints,
12371                      _("Invalid .debug_rnglists data (no base address)"));
12372           return false;
12373         }
12374
12375       if (range_beginning > range_end)
12376         {
12377           /* Inverted range entries are invalid.  */
12378           complaint (&symfile_complaints,
12379                      _("Invalid .debug_rnglists data (inverted range)"));
12380           return false;
12381         }
12382
12383       /* Empty range entries have no effect.  */
12384       if (range_beginning == range_end)
12385         continue;
12386
12387       range_beginning += base;
12388       range_end += base;
12389
12390       /* A not-uncommon case of bad debug info.
12391          Don't pollute the addrmap with bad data.  */
12392       if (range_beginning + baseaddr == 0
12393           && !dwarf2_per_objfile->has_section_at_zero)
12394         {
12395           complaint (&symfile_complaints,
12396                      _(".debug_rnglists entry has start address of zero"
12397                        " [in module %s]"), objfile_name (objfile));
12398           continue;
12399         }
12400
12401       callback (range_beginning, range_end);
12402     }
12403
12404   if (overflow)
12405     {
12406       complaint (&symfile_complaints,
12407                  _("Offset %d is not terminated "
12408                    "for DW_AT_ranges attribute"),
12409                  offset);
12410       return false;
12411     }
12412
12413   return true;
12414 }
12415
12416 /* Call CALLBACK from DW_AT_ranges attribute value OFFSET reading .debug_ranges.
12417    Callback's type should be:
12418     void (CORE_ADDR range_beginning, CORE_ADDR range_end)
12419    Return 1 if the attributes are present and valid, otherwise, return 0.  */
12420
12421 template <typename Callback>
12422 static int
12423 dwarf2_ranges_process (unsigned offset, struct dwarf2_cu *cu,
12424                        Callback &&callback)
12425 {
12426   struct objfile *objfile = cu->objfile;
12427   struct gdbarch *gdbarch = get_objfile_arch (objfile);
12428   struct comp_unit_head *cu_header = &cu->header;
12429   bfd *obfd = objfile->obfd;
12430   unsigned int addr_size = cu_header->addr_size;
12431   CORE_ADDR mask = ~(~(CORE_ADDR)1 << (addr_size * 8 - 1));
12432   /* Base address selection entry.  */
12433   CORE_ADDR base;
12434   int found_base;
12435   unsigned int dummy;
12436   const gdb_byte *buffer;
12437   CORE_ADDR baseaddr;
12438
12439   if (cu_header->version >= 5)
12440     return dwarf2_rnglists_process (offset, cu, callback);
12441
12442   found_base = cu->base_known;
12443   base = cu->base_address;
12444
12445   dwarf2_read_section (objfile, &dwarf2_per_objfile->ranges);
12446   if (offset >= dwarf2_per_objfile->ranges.size)
12447     {
12448       complaint (&symfile_complaints,
12449                  _("Offset %d out of bounds for DW_AT_ranges attribute"),
12450                  offset);
12451       return 0;
12452     }
12453   buffer = dwarf2_per_objfile->ranges.buffer + offset;
12454
12455   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
12456
12457   while (1)
12458     {
12459       CORE_ADDR range_beginning, range_end;
12460
12461       range_beginning = read_address (obfd, buffer, cu, &dummy);
12462       buffer += addr_size;
12463       range_end = read_address (obfd, buffer, cu, &dummy);
12464       buffer += addr_size;
12465       offset += 2 * addr_size;
12466
12467       /* An end of list marker is a pair of zero addresses.  */
12468       if (range_beginning == 0 && range_end == 0)
12469         /* Found the end of list entry.  */
12470         break;
12471
12472       /* Each base address selection entry is a pair of 2 values.
12473          The first is the largest possible address, the second is
12474          the base address.  Check for a base address here.  */
12475       if ((range_beginning & mask) == mask)
12476         {
12477           /* If we found the largest possible address, then we already
12478              have the base address in range_end.  */
12479           base = range_end;
12480           found_base = 1;
12481           continue;
12482         }
12483
12484       if (!found_base)
12485         {
12486           /* We have no valid base address for the ranges
12487              data.  */
12488           complaint (&symfile_complaints,
12489                      _("Invalid .debug_ranges data (no base address)"));
12490           return 0;
12491         }
12492
12493       if (range_beginning > range_end)
12494         {
12495           /* Inverted range entries are invalid.  */
12496           complaint (&symfile_complaints,
12497                      _("Invalid .debug_ranges data (inverted range)"));
12498           return 0;
12499         }
12500
12501       /* Empty range entries have no effect.  */
12502       if (range_beginning == range_end)
12503         continue;
12504
12505       range_beginning += base;
12506       range_end += base;
12507
12508       /* A not-uncommon case of bad debug info.
12509          Don't pollute the addrmap with bad data.  */
12510       if (range_beginning + baseaddr == 0
12511           && !dwarf2_per_objfile->has_section_at_zero)
12512         {
12513           complaint (&symfile_complaints,
12514                      _(".debug_ranges entry has start address of zero"
12515                        " [in module %s]"), objfile_name (objfile));
12516           continue;
12517         }
12518
12519       callback (range_beginning, range_end);
12520     }
12521
12522   return 1;
12523 }
12524
12525 /* Get low and high pc attributes from DW_AT_ranges attribute value OFFSET.
12526    Return 1 if the attributes are present and valid, otherwise, return 0.
12527    If RANGES_PST is not NULL we should setup `objfile->psymtabs_addrmap'.  */
12528
12529 static int
12530 dwarf2_ranges_read (unsigned offset, CORE_ADDR *low_return,
12531                     CORE_ADDR *high_return, struct dwarf2_cu *cu,
12532                     struct partial_symtab *ranges_pst)
12533 {
12534   struct objfile *objfile = cu->objfile;
12535   struct gdbarch *gdbarch = get_objfile_arch (objfile);
12536   const CORE_ADDR baseaddr = ANOFFSET (objfile->section_offsets,
12537                                        SECT_OFF_TEXT (objfile));
12538   int low_set = 0;
12539   CORE_ADDR low = 0;
12540   CORE_ADDR high = 0;
12541   int retval;
12542
12543   retval = dwarf2_ranges_process (offset, cu,
12544     [&] (CORE_ADDR range_beginning, CORE_ADDR range_end)
12545     {
12546       if (ranges_pst != NULL)
12547         {
12548           CORE_ADDR lowpc;
12549           CORE_ADDR highpc;
12550
12551           lowpc = gdbarch_adjust_dwarf2_addr (gdbarch,
12552                                               range_beginning + baseaddr);
12553           highpc = gdbarch_adjust_dwarf2_addr (gdbarch,
12554                                                range_end + baseaddr);
12555           addrmap_set_empty (objfile->psymtabs_addrmap, lowpc, highpc - 1,
12556                              ranges_pst);
12557         }
12558
12559       /* FIXME: This is recording everything as a low-high
12560          segment of consecutive addresses.  We should have a
12561          data structure for discontiguous block ranges
12562          instead.  */
12563       if (! low_set)
12564         {
12565           low = range_beginning;
12566           high = range_end;
12567           low_set = 1;
12568         }
12569       else
12570         {
12571           if (range_beginning < low)
12572             low = range_beginning;
12573           if (range_end > high)
12574             high = range_end;
12575         }
12576     });
12577   if (!retval)
12578     return 0;
12579
12580   if (! low_set)
12581     /* If the first entry is an end-of-list marker, the range
12582        describes an empty scope, i.e. no instructions.  */
12583     return 0;
12584
12585   if (low_return)
12586     *low_return = low;
12587   if (high_return)
12588     *high_return = high;
12589   return 1;
12590 }
12591
12592 /* Get low and high pc attributes from a die.  See enum pc_bounds_kind
12593    definition for the return value.  *LOWPC and *HIGHPC are set iff
12594    neither PC_BOUNDS_NOT_PRESENT nor PC_BOUNDS_INVALID are returned.  */
12595
12596 static enum pc_bounds_kind
12597 dwarf2_get_pc_bounds (struct die_info *die, CORE_ADDR *lowpc,
12598                       CORE_ADDR *highpc, struct dwarf2_cu *cu,
12599                       struct partial_symtab *pst)
12600 {
12601   struct attribute *attr;
12602   struct attribute *attr_high;
12603   CORE_ADDR low = 0;
12604   CORE_ADDR high = 0;
12605   enum pc_bounds_kind ret;
12606
12607   attr_high = dwarf2_attr (die, DW_AT_high_pc, cu);
12608   if (attr_high)
12609     {
12610       attr = dwarf2_attr (die, DW_AT_low_pc, cu);
12611       if (attr)
12612         {
12613           low = attr_value_as_address (attr);
12614           high = attr_value_as_address (attr_high);
12615           if (cu->header.version >= 4 && attr_form_is_constant (attr_high))
12616             high += low;
12617         }
12618       else
12619         /* Found high w/o low attribute.  */
12620         return PC_BOUNDS_INVALID;
12621
12622       /* Found consecutive range of addresses.  */
12623       ret = PC_BOUNDS_HIGH_LOW;
12624     }
12625   else
12626     {
12627       attr = dwarf2_attr (die, DW_AT_ranges, cu);
12628       if (attr != NULL)
12629         {
12630           /* DW_AT_ranges_base does not apply to DIEs from the DWO skeleton.
12631              We take advantage of the fact that DW_AT_ranges does not appear
12632              in DW_TAG_compile_unit of DWO files.  */
12633           int need_ranges_base = die->tag != DW_TAG_compile_unit;
12634           unsigned int ranges_offset = (DW_UNSND (attr)
12635                                         + (need_ranges_base
12636                                            ? cu->ranges_base
12637                                            : 0));
12638
12639           /* Value of the DW_AT_ranges attribute is the offset in the
12640              .debug_ranges section.  */
12641           if (!dwarf2_ranges_read (ranges_offset, &low, &high, cu, pst))
12642             return PC_BOUNDS_INVALID;
12643           /* Found discontinuous range of addresses.  */
12644           ret = PC_BOUNDS_RANGES;
12645         }
12646       else
12647         return PC_BOUNDS_NOT_PRESENT;
12648     }
12649
12650   /* read_partial_die has also the strict LOW < HIGH requirement.  */
12651   if (high <= low)
12652     return PC_BOUNDS_INVALID;
12653
12654   /* When using the GNU linker, .gnu.linkonce. sections are used to
12655      eliminate duplicate copies of functions and vtables and such.
12656      The linker will arbitrarily choose one and discard the others.
12657      The AT_*_pc values for such functions refer to local labels in
12658      these sections.  If the section from that file was discarded, the
12659      labels are not in the output, so the relocs get a value of 0.
12660      If this is a discarded function, mark the pc bounds as invalid,
12661      so that GDB will ignore it.  */
12662   if (low == 0 && !dwarf2_per_objfile->has_section_at_zero)
12663     return PC_BOUNDS_INVALID;
12664
12665   *lowpc = low;
12666   if (highpc)
12667     *highpc = high;
12668   return ret;
12669 }
12670
12671 /* Assuming that DIE represents a subprogram DIE or a lexical block, get
12672    its low and high PC addresses.  Do nothing if these addresses could not
12673    be determined.  Otherwise, set LOWPC to the low address if it is smaller,
12674    and HIGHPC to the high address if greater than HIGHPC.  */
12675
12676 static void
12677 dwarf2_get_subprogram_pc_bounds (struct die_info *die,
12678                                  CORE_ADDR *lowpc, CORE_ADDR *highpc,
12679                                  struct dwarf2_cu *cu)
12680 {
12681   CORE_ADDR low, high;
12682   struct die_info *child = die->child;
12683
12684   if (dwarf2_get_pc_bounds (die, &low, &high, cu, NULL) >= PC_BOUNDS_RANGES)
12685     {
12686       *lowpc = std::min (*lowpc, low);
12687       *highpc = std::max (*highpc, high);
12688     }
12689
12690   /* If the language does not allow nested subprograms (either inside
12691      subprograms or lexical blocks), we're done.  */
12692   if (cu->language != language_ada)
12693     return;
12694
12695   /* Check all the children of the given DIE.  If it contains nested
12696      subprograms, then check their pc bounds.  Likewise, we need to
12697      check lexical blocks as well, as they may also contain subprogram
12698      definitions.  */
12699   while (child && child->tag)
12700     {
12701       if (child->tag == DW_TAG_subprogram
12702           || child->tag == DW_TAG_lexical_block)
12703         dwarf2_get_subprogram_pc_bounds (child, lowpc, highpc, cu);
12704       child = sibling_die (child);
12705     }
12706 }
12707
12708 /* Get the low and high pc's represented by the scope DIE, and store
12709    them in *LOWPC and *HIGHPC.  If the correct values can't be
12710    determined, set *LOWPC to -1 and *HIGHPC to 0.  */
12711
12712 static void
12713 get_scope_pc_bounds (struct die_info *die,
12714                      CORE_ADDR *lowpc, CORE_ADDR *highpc,
12715                      struct dwarf2_cu *cu)
12716 {
12717   CORE_ADDR best_low = (CORE_ADDR) -1;
12718   CORE_ADDR best_high = (CORE_ADDR) 0;
12719   CORE_ADDR current_low, current_high;
12720
12721   if (dwarf2_get_pc_bounds (die, &current_low, &current_high, cu, NULL)
12722       >= PC_BOUNDS_RANGES)
12723     {
12724       best_low = current_low;
12725       best_high = current_high;
12726     }
12727   else
12728     {
12729       struct die_info *child = die->child;
12730
12731       while (child && child->tag)
12732         {
12733           switch (child->tag) {
12734           case DW_TAG_subprogram:
12735             dwarf2_get_subprogram_pc_bounds (child, &best_low, &best_high, cu);
12736             break;
12737           case DW_TAG_namespace:
12738           case DW_TAG_module:
12739             /* FIXME: carlton/2004-01-16: Should we do this for
12740                DW_TAG_class_type/DW_TAG_structure_type, too?  I think
12741                that current GCC's always emit the DIEs corresponding
12742                to definitions of methods of classes as children of a
12743                DW_TAG_compile_unit or DW_TAG_namespace (as opposed to
12744                the DIEs giving the declarations, which could be
12745                anywhere).  But I don't see any reason why the
12746                standards says that they have to be there.  */
12747             get_scope_pc_bounds (child, &current_low, &current_high, cu);
12748
12749             if (current_low != ((CORE_ADDR) -1))
12750               {
12751                 best_low = std::min (best_low, current_low);
12752                 best_high = std::max (best_high, current_high);
12753               }
12754             break;
12755           default:
12756             /* Ignore.  */
12757             break;
12758           }
12759
12760           child = sibling_die (child);
12761         }
12762     }
12763
12764   *lowpc = best_low;
12765   *highpc = best_high;
12766 }
12767
12768 /* Record the address ranges for BLOCK, offset by BASEADDR, as given
12769    in DIE.  */
12770
12771 static void
12772 dwarf2_record_block_ranges (struct die_info *die, struct block *block,
12773                             CORE_ADDR baseaddr, struct dwarf2_cu *cu)
12774 {
12775   struct objfile *objfile = cu->objfile;
12776   struct gdbarch *gdbarch = get_objfile_arch (objfile);
12777   struct attribute *attr;
12778   struct attribute *attr_high;
12779
12780   attr_high = dwarf2_attr (die, DW_AT_high_pc, cu);
12781   if (attr_high)
12782     {
12783       attr = dwarf2_attr (die, DW_AT_low_pc, cu);
12784       if (attr)
12785         {
12786           CORE_ADDR low = attr_value_as_address (attr);
12787           CORE_ADDR high = attr_value_as_address (attr_high);
12788
12789           if (cu->header.version >= 4 && attr_form_is_constant (attr_high))
12790             high += low;
12791
12792           low = gdbarch_adjust_dwarf2_addr (gdbarch, low + baseaddr);
12793           high = gdbarch_adjust_dwarf2_addr (gdbarch, high + baseaddr);
12794           record_block_range (block, low, high - 1);
12795         }
12796     }
12797
12798   attr = dwarf2_attr (die, DW_AT_ranges, cu);
12799   if (attr)
12800     {
12801       bfd *obfd = objfile->obfd;
12802       /* DW_AT_ranges_base does not apply to DIEs from the DWO skeleton.
12803          We take advantage of the fact that DW_AT_ranges does not appear
12804          in DW_TAG_compile_unit of DWO files.  */
12805       int need_ranges_base = die->tag != DW_TAG_compile_unit;
12806
12807       /* The value of the DW_AT_ranges attribute is the offset of the
12808          address range list in the .debug_ranges section.  */
12809       unsigned long offset = (DW_UNSND (attr)
12810                               + (need_ranges_base ? cu->ranges_base : 0));
12811       const gdb_byte *buffer;
12812
12813       /* For some target architectures, but not others, the
12814          read_address function sign-extends the addresses it returns.
12815          To recognize base address selection entries, we need a
12816          mask.  */
12817       unsigned int addr_size = cu->header.addr_size;
12818       CORE_ADDR base_select_mask = ~(~(CORE_ADDR)1 << (addr_size * 8 - 1));
12819
12820       /* The base address, to which the next pair is relative.  Note
12821          that this 'base' is a DWARF concept: most entries in a range
12822          list are relative, to reduce the number of relocs against the
12823          debugging information.  This is separate from this function's
12824          'baseaddr' argument, which GDB uses to relocate debugging
12825          information from a shared library based on the address at
12826          which the library was loaded.  */
12827       CORE_ADDR base = cu->base_address;
12828       int base_known = cu->base_known;
12829
12830       dwarf2_ranges_process (offset, cu,
12831         [&] (CORE_ADDR start, CORE_ADDR end)
12832         {
12833           start += baseaddr;
12834           end += baseaddr;
12835           start = gdbarch_adjust_dwarf2_addr (gdbarch, start);
12836           end = gdbarch_adjust_dwarf2_addr (gdbarch, end);
12837           record_block_range (block, start, end - 1);
12838         });
12839     }
12840 }
12841
12842 /* Check whether the producer field indicates either of GCC < 4.6, or the
12843    Intel C/C++ compiler, and cache the result in CU.  */
12844
12845 static void
12846 check_producer (struct dwarf2_cu *cu)
12847 {
12848   int major, minor;
12849
12850   if (cu->producer == NULL)
12851     {
12852       /* For unknown compilers expect their behavior is DWARF version
12853          compliant.
12854
12855          GCC started to support .debug_types sections by -gdwarf-4 since
12856          gcc-4.5.x.  As the .debug_types sections are missing DW_AT_producer
12857          for their space efficiency GDB cannot workaround gcc-4.5.x -gdwarf-4
12858          combination.  gcc-4.5.x -gdwarf-4 binaries have DW_AT_accessibility
12859          interpreted incorrectly by GDB now - GCC PR debug/48229.  */
12860     }
12861   else if (producer_is_gcc (cu->producer, &major, &minor))
12862     {
12863       cu->producer_is_gxx_lt_4_6 = major < 4 || (major == 4 && minor < 6);
12864       cu->producer_is_gcc_lt_4_3 = major < 4 || (major == 4 && minor < 3);
12865     }
12866   else if (startswith (cu->producer, "Intel(R) C"))
12867     cu->producer_is_icc = 1;
12868   else
12869     {
12870       /* For other non-GCC compilers, expect their behavior is DWARF version
12871          compliant.  */
12872     }
12873
12874   cu->checked_producer = 1;
12875 }
12876
12877 /* Check for GCC PR debug/45124 fix which is not present in any G++ version up
12878    to 4.5.any while it is present already in G++ 4.6.0 - the PR has been fixed
12879    during 4.6.0 experimental.  */
12880
12881 static int
12882 producer_is_gxx_lt_4_6 (struct dwarf2_cu *cu)
12883 {
12884   if (!cu->checked_producer)
12885     check_producer (cu);
12886
12887   return cu->producer_is_gxx_lt_4_6;
12888 }
12889
12890 /* Return the default accessibility type if it is not overriden by
12891    DW_AT_accessibility.  */
12892
12893 static enum dwarf_access_attribute
12894 dwarf2_default_access_attribute (struct die_info *die, struct dwarf2_cu *cu)
12895 {
12896   if (cu->header.version < 3 || producer_is_gxx_lt_4_6 (cu))
12897     {
12898       /* The default DWARF 2 accessibility for members is public, the default
12899          accessibility for inheritance is private.  */
12900
12901       if (die->tag != DW_TAG_inheritance)
12902         return DW_ACCESS_public;
12903       else
12904         return DW_ACCESS_private;
12905     }
12906   else
12907     {
12908       /* DWARF 3+ defines the default accessibility a different way.  The same
12909          rules apply now for DW_TAG_inheritance as for the members and it only
12910          depends on the container kind.  */
12911
12912       if (die->parent->tag == DW_TAG_class_type)
12913         return DW_ACCESS_private;
12914       else
12915         return DW_ACCESS_public;
12916     }
12917 }
12918
12919 /* Look for DW_AT_data_member_location.  Set *OFFSET to the byte
12920    offset.  If the attribute was not found return 0, otherwise return
12921    1.  If it was found but could not properly be handled, set *OFFSET
12922    to 0.  */
12923
12924 static int
12925 handle_data_member_location (struct die_info *die, struct dwarf2_cu *cu,
12926                              LONGEST *offset)
12927 {
12928   struct attribute *attr;
12929
12930   attr = dwarf2_attr (die, DW_AT_data_member_location, cu);
12931   if (attr != NULL)
12932     {
12933       *offset = 0;
12934
12935       /* Note that we do not check for a section offset first here.
12936          This is because DW_AT_data_member_location is new in DWARF 4,
12937          so if we see it, we can assume that a constant form is really
12938          a constant and not a section offset.  */
12939       if (attr_form_is_constant (attr))
12940         *offset = dwarf2_get_attr_constant_value (attr, 0);
12941       else if (attr_form_is_section_offset (attr))
12942         dwarf2_complex_location_expr_complaint ();
12943       else if (attr_form_is_block (attr))
12944         *offset = decode_locdesc (DW_BLOCK (attr), cu);
12945       else
12946         dwarf2_complex_location_expr_complaint ();
12947
12948       return 1;
12949     }
12950
12951   return 0;
12952 }
12953
12954 /* Add an aggregate field to the field list.  */
12955
12956 static void
12957 dwarf2_add_field (struct field_info *fip, struct die_info *die,
12958                   struct dwarf2_cu *cu)
12959 {
12960   struct objfile *objfile = cu->objfile;
12961   struct gdbarch *gdbarch = get_objfile_arch (objfile);
12962   struct nextfield *new_field;
12963   struct attribute *attr;
12964   struct field *fp;
12965   const char *fieldname = "";
12966
12967   /* Allocate a new field list entry and link it in.  */
12968   new_field = XNEW (struct nextfield);
12969   make_cleanup (xfree, new_field);
12970   memset (new_field, 0, sizeof (struct nextfield));
12971
12972   if (die->tag == DW_TAG_inheritance)
12973     {
12974       new_field->next = fip->baseclasses;
12975       fip->baseclasses = new_field;
12976     }
12977   else
12978     {
12979       new_field->next = fip->fields;
12980       fip->fields = new_field;
12981     }
12982   fip->nfields++;
12983
12984   attr = dwarf2_attr (die, DW_AT_accessibility, cu);
12985   if (attr)
12986     new_field->accessibility = DW_UNSND (attr);
12987   else
12988     new_field->accessibility = dwarf2_default_access_attribute (die, cu);
12989   if (new_field->accessibility != DW_ACCESS_public)
12990     fip->non_public_fields = 1;
12991
12992   attr = dwarf2_attr (die, DW_AT_virtuality, cu);
12993   if (attr)
12994     new_field->virtuality = DW_UNSND (attr);
12995   else
12996     new_field->virtuality = DW_VIRTUALITY_none;
12997
12998   fp = &new_field->field;
12999
13000   if (die->tag == DW_TAG_member && ! die_is_declaration (die, cu))
13001     {
13002       LONGEST offset;
13003
13004       /* Data member other than a C++ static data member.  */
13005
13006       /* Get type of field.  */
13007       fp->type = die_type (die, cu);
13008
13009       SET_FIELD_BITPOS (*fp, 0);
13010
13011       /* Get bit size of field (zero if none).  */
13012       attr = dwarf2_attr (die, DW_AT_bit_size, cu);
13013       if (attr)
13014         {
13015           FIELD_BITSIZE (*fp) = DW_UNSND (attr);
13016         }
13017       else
13018         {
13019           FIELD_BITSIZE (*fp) = 0;
13020         }
13021
13022       /* Get bit offset of field.  */
13023       if (handle_data_member_location (die, cu, &offset))
13024         SET_FIELD_BITPOS (*fp, offset * bits_per_byte);
13025       attr = dwarf2_attr (die, DW_AT_bit_offset, cu);
13026       if (attr)
13027         {
13028           if (gdbarch_bits_big_endian (gdbarch))
13029             {
13030               /* For big endian bits, the DW_AT_bit_offset gives the
13031                  additional bit offset from the MSB of the containing
13032                  anonymous object to the MSB of the field.  We don't
13033                  have to do anything special since we don't need to
13034                  know the size of the anonymous object.  */
13035               SET_FIELD_BITPOS (*fp, FIELD_BITPOS (*fp) + DW_UNSND (attr));
13036             }
13037           else
13038             {
13039               /* For little endian bits, compute the bit offset to the
13040                  MSB of the anonymous object, subtract off the number of
13041                  bits from the MSB of the field to the MSB of the
13042                  object, and then subtract off the number of bits of
13043                  the field itself.  The result is the bit offset of
13044                  the LSB of the field.  */
13045               int anonymous_size;
13046               int bit_offset = DW_UNSND (attr);
13047
13048               attr = dwarf2_attr (die, DW_AT_byte_size, cu);
13049               if (attr)
13050                 {
13051                   /* The size of the anonymous object containing
13052                      the bit field is explicit, so use the
13053                      indicated size (in bytes).  */
13054                   anonymous_size = DW_UNSND (attr);
13055                 }
13056               else
13057                 {
13058                   /* The size of the anonymous object containing
13059                      the bit field must be inferred from the type
13060                      attribute of the data member containing the
13061                      bit field.  */
13062                   anonymous_size = TYPE_LENGTH (fp->type);
13063                 }
13064               SET_FIELD_BITPOS (*fp,
13065                                 (FIELD_BITPOS (*fp)
13066                                  + anonymous_size * bits_per_byte
13067                                  - bit_offset - FIELD_BITSIZE (*fp)));
13068             }
13069         }
13070       attr = dwarf2_attr (die, DW_AT_data_bit_offset, cu);
13071       if (attr != NULL)
13072         SET_FIELD_BITPOS (*fp, (FIELD_BITPOS (*fp)
13073                                 + dwarf2_get_attr_constant_value (attr, 0)));
13074
13075       /* Get name of field.  */
13076       fieldname = dwarf2_name (die, cu);
13077       if (fieldname == NULL)
13078         fieldname = "";
13079
13080       /* The name is already allocated along with this objfile, so we don't
13081          need to duplicate it for the type.  */
13082       fp->name = fieldname;
13083
13084       /* Change accessibility for artificial fields (e.g. virtual table
13085          pointer or virtual base class pointer) to private.  */
13086       if (dwarf2_attr (die, DW_AT_artificial, cu))
13087         {
13088           FIELD_ARTIFICIAL (*fp) = 1;
13089           new_field->accessibility = DW_ACCESS_private;
13090           fip->non_public_fields = 1;
13091         }
13092     }
13093   else if (die->tag == DW_TAG_member || die->tag == DW_TAG_variable)
13094     {
13095       /* C++ static member.  */
13096
13097       /* NOTE: carlton/2002-11-05: It should be a DW_TAG_member that
13098          is a declaration, but all versions of G++ as of this writing
13099          (so through at least 3.2.1) incorrectly generate
13100          DW_TAG_variable tags.  */
13101
13102       const char *physname;
13103
13104       /* Get name of field.  */
13105       fieldname = dwarf2_name (die, cu);
13106       if (fieldname == NULL)
13107         return;
13108
13109       attr = dwarf2_attr (die, DW_AT_const_value, cu);
13110       if (attr
13111           /* Only create a symbol if this is an external value.
13112              new_symbol checks this and puts the value in the global symbol
13113              table, which we want.  If it is not external, new_symbol
13114              will try to put the value in cu->list_in_scope which is wrong.  */
13115           && dwarf2_flag_true_p (die, DW_AT_external, cu))
13116         {
13117           /* A static const member, not much different than an enum as far as
13118              we're concerned, except that we can support more types.  */
13119           new_symbol (die, NULL, cu);
13120         }
13121
13122       /* Get physical name.  */
13123       physname = dwarf2_physname (fieldname, die, cu);
13124
13125       /* The name is already allocated along with this objfile, so we don't
13126          need to duplicate it for the type.  */
13127       SET_FIELD_PHYSNAME (*fp, physname ? physname : "");
13128       FIELD_TYPE (*fp) = die_type (die, cu);
13129       FIELD_NAME (*fp) = fieldname;
13130     }
13131   else if (die->tag == DW_TAG_inheritance)
13132     {
13133       LONGEST offset;
13134
13135       /* C++ base class field.  */
13136       if (handle_data_member_location (die, cu, &offset))
13137         SET_FIELD_BITPOS (*fp, offset * bits_per_byte);
13138       FIELD_BITSIZE (*fp) = 0;
13139       FIELD_TYPE (*fp) = die_type (die, cu);
13140       FIELD_NAME (*fp) = type_name_no_tag (fp->type);
13141       fip->nbaseclasses++;
13142     }
13143 }
13144
13145 /* Add a typedef defined in the scope of the FIP's class.  */
13146
13147 static void
13148 dwarf2_add_typedef (struct field_info *fip, struct die_info *die,
13149                     struct dwarf2_cu *cu)
13150 {
13151   struct typedef_field_list *new_field;
13152   struct typedef_field *fp;
13153
13154   /* Allocate a new field list entry and link it in.  */
13155   new_field = XCNEW (struct typedef_field_list);
13156   make_cleanup (xfree, new_field);
13157
13158   gdb_assert (die->tag == DW_TAG_typedef);
13159
13160   fp = &new_field->field;
13161
13162   /* Get name of field.  */
13163   fp->name = dwarf2_name (die, cu);
13164   if (fp->name == NULL)
13165     return;
13166
13167   fp->type = read_type_die (die, cu);
13168
13169   new_field->next = fip->typedef_field_list;
13170   fip->typedef_field_list = new_field;
13171   fip->typedef_field_list_count++;
13172 }
13173
13174 /* Create the vector of fields, and attach it to the type.  */
13175
13176 static void
13177 dwarf2_attach_fields_to_type (struct field_info *fip, struct type *type,
13178                               struct dwarf2_cu *cu)
13179 {
13180   int nfields = fip->nfields;
13181
13182   /* Record the field count, allocate space for the array of fields,
13183      and create blank accessibility bitfields if necessary.  */
13184   TYPE_NFIELDS (type) = nfields;
13185   TYPE_FIELDS (type) = (struct field *)
13186     TYPE_ALLOC (type, sizeof (struct field) * nfields);
13187   memset (TYPE_FIELDS (type), 0, sizeof (struct field) * nfields);
13188
13189   if (fip->non_public_fields && cu->language != language_ada)
13190     {
13191       ALLOCATE_CPLUS_STRUCT_TYPE (type);
13192
13193       TYPE_FIELD_PRIVATE_BITS (type) =
13194         (B_TYPE *) TYPE_ALLOC (type, B_BYTES (nfields));
13195       B_CLRALL (TYPE_FIELD_PRIVATE_BITS (type), nfields);
13196
13197       TYPE_FIELD_PROTECTED_BITS (type) =
13198         (B_TYPE *) TYPE_ALLOC (type, B_BYTES (nfields));
13199       B_CLRALL (TYPE_FIELD_PROTECTED_BITS (type), nfields);
13200
13201       TYPE_FIELD_IGNORE_BITS (type) =
13202         (B_TYPE *) TYPE_ALLOC (type, B_BYTES (nfields));
13203       B_CLRALL (TYPE_FIELD_IGNORE_BITS (type), nfields);
13204     }
13205
13206   /* If the type has baseclasses, allocate and clear a bit vector for
13207      TYPE_FIELD_VIRTUAL_BITS.  */
13208   if (fip->nbaseclasses && cu->language != language_ada)
13209     {
13210       int num_bytes = B_BYTES (fip->nbaseclasses);
13211       unsigned char *pointer;
13212
13213       ALLOCATE_CPLUS_STRUCT_TYPE (type);
13214       pointer = (unsigned char *) TYPE_ALLOC (type, num_bytes);
13215       TYPE_FIELD_VIRTUAL_BITS (type) = pointer;
13216       B_CLRALL (TYPE_FIELD_VIRTUAL_BITS (type), fip->nbaseclasses);
13217       TYPE_N_BASECLASSES (type) = fip->nbaseclasses;
13218     }
13219
13220   /* Copy the saved-up fields into the field vector.  Start from the head of
13221      the list, adding to the tail of the field array, so that they end up in
13222      the same order in the array in which they were added to the list.  */
13223   while (nfields-- > 0)
13224     {
13225       struct nextfield *fieldp;
13226
13227       if (fip->fields)
13228         {
13229           fieldp = fip->fields;
13230           fip->fields = fieldp->next;
13231         }
13232       else
13233         {
13234           fieldp = fip->baseclasses;
13235           fip->baseclasses = fieldp->next;
13236         }
13237
13238       TYPE_FIELD (type, nfields) = fieldp->field;
13239       switch (fieldp->accessibility)
13240         {
13241         case DW_ACCESS_private:
13242           if (cu->language != language_ada)
13243             SET_TYPE_FIELD_PRIVATE (type, nfields);
13244           break;
13245
13246         case DW_ACCESS_protected:
13247           if (cu->language != language_ada)
13248             SET_TYPE_FIELD_PROTECTED (type, nfields);
13249           break;
13250
13251         case DW_ACCESS_public:
13252           break;
13253
13254         default:
13255           /* Unknown accessibility.  Complain and treat it as public.  */
13256           {
13257             complaint (&symfile_complaints, _("unsupported accessibility %d"),
13258                        fieldp->accessibility);
13259           }
13260           break;
13261         }
13262       if (nfields < fip->nbaseclasses)
13263         {
13264           switch (fieldp->virtuality)
13265             {
13266             case DW_VIRTUALITY_virtual:
13267             case DW_VIRTUALITY_pure_virtual:
13268               if (cu->language == language_ada)
13269                 error (_("unexpected virtuality in component of Ada type"));
13270               SET_TYPE_FIELD_VIRTUAL (type, nfields);
13271               break;
13272             }
13273         }
13274     }
13275 }
13276
13277 /* Return true if this member function is a constructor, false
13278    otherwise.  */
13279
13280 static int
13281 dwarf2_is_constructor (struct die_info *die, struct dwarf2_cu *cu)
13282 {
13283   const char *fieldname;
13284   const char *type_name;
13285   int len;
13286
13287   if (die->parent == NULL)
13288     return 0;
13289
13290   if (die->parent->tag != DW_TAG_structure_type
13291       && die->parent->tag != DW_TAG_union_type
13292       && die->parent->tag != DW_TAG_class_type)
13293     return 0;
13294
13295   fieldname = dwarf2_name (die, cu);
13296   type_name = dwarf2_name (die->parent, cu);
13297   if (fieldname == NULL || type_name == NULL)
13298     return 0;
13299
13300   len = strlen (fieldname);
13301   return (strncmp (fieldname, type_name, len) == 0
13302           && (type_name[len] == '\0' || type_name[len] == '<'));
13303 }
13304
13305 /* Add a member function to the proper fieldlist.  */
13306
13307 static void
13308 dwarf2_add_member_fn (struct field_info *fip, struct die_info *die,
13309                       struct type *type, struct dwarf2_cu *cu)
13310 {
13311   struct objfile *objfile = cu->objfile;
13312   struct attribute *attr;
13313   struct fnfieldlist *flp;
13314   int i;
13315   struct fn_field *fnp;
13316   const char *fieldname;
13317   struct nextfnfield *new_fnfield;
13318   struct type *this_type;
13319   enum dwarf_access_attribute accessibility;
13320
13321   if (cu->language == language_ada)
13322     error (_("unexpected member function in Ada type"));
13323
13324   /* Get name of member function.  */
13325   fieldname = dwarf2_name (die, cu);
13326   if (fieldname == NULL)
13327     return;
13328
13329   /* Look up member function name in fieldlist.  */
13330   for (i = 0; i < fip->nfnfields; i++)
13331     {
13332       if (strcmp (fip->fnfieldlists[i].name, fieldname) == 0)
13333         break;
13334     }
13335
13336   /* Create new list element if necessary.  */
13337   if (i < fip->nfnfields)
13338     flp = &fip->fnfieldlists[i];
13339   else
13340     {
13341       if ((fip->nfnfields % DW_FIELD_ALLOC_CHUNK) == 0)
13342         {
13343           fip->fnfieldlists = (struct fnfieldlist *)
13344             xrealloc (fip->fnfieldlists,
13345                       (fip->nfnfields + DW_FIELD_ALLOC_CHUNK)
13346                       * sizeof (struct fnfieldlist));
13347           if (fip->nfnfields == 0)
13348             make_cleanup (free_current_contents, &fip->fnfieldlists);
13349         }
13350       flp = &fip->fnfieldlists[fip->nfnfields];
13351       flp->name = fieldname;
13352       flp->length = 0;
13353       flp->head = NULL;
13354       i = fip->nfnfields++;
13355     }
13356
13357   /* Create a new member function field and chain it to the field list
13358      entry.  */
13359   new_fnfield = XNEW (struct nextfnfield);
13360   make_cleanup (xfree, new_fnfield);
13361   memset (new_fnfield, 0, sizeof (struct nextfnfield));
13362   new_fnfield->next = flp->head;
13363   flp->head = new_fnfield;
13364   flp->length++;
13365
13366   /* Fill in the member function field info.  */
13367   fnp = &new_fnfield->fnfield;
13368
13369   /* Delay processing of the physname until later.  */
13370   if (cu->language == language_cplus)
13371     {
13372       add_to_method_list (type, i, flp->length - 1, fieldname,
13373                           die, cu);
13374     }
13375   else
13376     {
13377       const char *physname = dwarf2_physname (fieldname, die, cu);
13378       fnp->physname = physname ? physname : "";
13379     }
13380
13381   fnp->type = alloc_type (objfile);
13382   this_type = read_type_die (die, cu);
13383   if (this_type && TYPE_CODE (this_type) == TYPE_CODE_FUNC)
13384     {
13385       int nparams = TYPE_NFIELDS (this_type);
13386
13387       /* TYPE is the domain of this method, and THIS_TYPE is the type
13388            of the method itself (TYPE_CODE_METHOD).  */
13389       smash_to_method_type (fnp->type, type,
13390                             TYPE_TARGET_TYPE (this_type),
13391                             TYPE_FIELDS (this_type),
13392                             TYPE_NFIELDS (this_type),
13393                             TYPE_VARARGS (this_type));
13394
13395       /* Handle static member functions.
13396          Dwarf2 has no clean way to discern C++ static and non-static
13397          member functions.  G++ helps GDB by marking the first
13398          parameter for non-static member functions (which is the this
13399          pointer) as artificial.  We obtain this information from
13400          read_subroutine_type via TYPE_FIELD_ARTIFICIAL.  */
13401       if (nparams == 0 || TYPE_FIELD_ARTIFICIAL (this_type, 0) == 0)
13402         fnp->voffset = VOFFSET_STATIC;
13403     }
13404   else
13405     complaint (&symfile_complaints, _("member function type missing for '%s'"),
13406                dwarf2_full_name (fieldname, die, cu));
13407
13408   /* Get fcontext from DW_AT_containing_type if present.  */
13409   if (dwarf2_attr (die, DW_AT_containing_type, cu) != NULL)
13410     fnp->fcontext = die_containing_type (die, cu);
13411
13412   /* dwarf2 doesn't have stubbed physical names, so the setting of is_const and
13413      is_volatile is irrelevant, as it is needed by gdb_mangle_name only.  */
13414
13415   /* Get accessibility.  */
13416   attr = dwarf2_attr (die, DW_AT_accessibility, cu);
13417   if (attr)
13418     accessibility = (enum dwarf_access_attribute) DW_UNSND (attr);
13419   else
13420     accessibility = dwarf2_default_access_attribute (die, cu);
13421   switch (accessibility)
13422     {
13423     case DW_ACCESS_private:
13424       fnp->is_private = 1;
13425       break;
13426     case DW_ACCESS_protected:
13427       fnp->is_protected = 1;
13428       break;
13429     }
13430
13431   /* Check for artificial methods.  */
13432   attr = dwarf2_attr (die, DW_AT_artificial, cu);
13433   if (attr && DW_UNSND (attr) != 0)
13434     fnp->is_artificial = 1;
13435
13436   fnp->is_constructor = dwarf2_is_constructor (die, cu);
13437
13438   /* Get index in virtual function table if it is a virtual member
13439      function.  For older versions of GCC, this is an offset in the
13440      appropriate virtual table, as specified by DW_AT_containing_type.
13441      For everyone else, it is an expression to be evaluated relative
13442      to the object address.  */
13443
13444   attr = dwarf2_attr (die, DW_AT_vtable_elem_location, cu);
13445   if (attr)
13446     {
13447       if (attr_form_is_block (attr) && DW_BLOCK (attr)->size > 0)
13448         {
13449           if (DW_BLOCK (attr)->data[0] == DW_OP_constu)
13450             {
13451               /* Old-style GCC.  */
13452               fnp->voffset = decode_locdesc (DW_BLOCK (attr), cu) + 2;
13453             }
13454           else if (DW_BLOCK (attr)->data[0] == DW_OP_deref
13455                    || (DW_BLOCK (attr)->size > 1
13456                        && DW_BLOCK (attr)->data[0] == DW_OP_deref_size
13457                        && DW_BLOCK (attr)->data[1] == cu->header.addr_size))
13458             {
13459               fnp->voffset = decode_locdesc (DW_BLOCK (attr), cu);
13460               if ((fnp->voffset % cu->header.addr_size) != 0)
13461                 dwarf2_complex_location_expr_complaint ();
13462               else
13463                 fnp->voffset /= cu->header.addr_size;
13464               fnp->voffset += 2;
13465             }
13466           else
13467             dwarf2_complex_location_expr_complaint ();
13468
13469           if (!fnp->fcontext)
13470             {
13471               /* If there is no `this' field and no DW_AT_containing_type,
13472                  we cannot actually find a base class context for the
13473                  vtable!  */
13474               if (TYPE_NFIELDS (this_type) == 0
13475                   || !TYPE_FIELD_ARTIFICIAL (this_type, 0))
13476                 {
13477                   complaint (&symfile_complaints,
13478                              _("cannot determine context for virtual member "
13479                                "function \"%s\" (offset %d)"),
13480                              fieldname, to_underlying (die->sect_off));
13481                 }
13482               else
13483                 {
13484                   fnp->fcontext
13485                     = TYPE_TARGET_TYPE (TYPE_FIELD_TYPE (this_type, 0));
13486                 }
13487             }
13488         }
13489       else if (attr_form_is_section_offset (attr))
13490         {
13491           dwarf2_complex_location_expr_complaint ();
13492         }
13493       else
13494         {
13495           dwarf2_invalid_attrib_class_complaint ("DW_AT_vtable_elem_location",
13496                                                  fieldname);
13497         }
13498     }
13499   else
13500     {
13501       attr = dwarf2_attr (die, DW_AT_virtuality, cu);
13502       if (attr && DW_UNSND (attr))
13503         {
13504           /* GCC does this, as of 2008-08-25; PR debug/37237.  */
13505           complaint (&symfile_complaints,
13506                      _("Member function \"%s\" (offset %d) is virtual "
13507                        "but the vtable offset is not specified"),
13508                      fieldname, to_underlying (die->sect_off));
13509           ALLOCATE_CPLUS_STRUCT_TYPE (type);
13510           TYPE_CPLUS_DYNAMIC (type) = 1;
13511         }
13512     }
13513 }
13514
13515 /* Create the vector of member function fields, and attach it to the type.  */
13516
13517 static void
13518 dwarf2_attach_fn_fields_to_type (struct field_info *fip, struct type *type,
13519                                  struct dwarf2_cu *cu)
13520 {
13521   struct fnfieldlist *flp;
13522   int i;
13523
13524   if (cu->language == language_ada)
13525     error (_("unexpected member functions in Ada type"));
13526
13527   ALLOCATE_CPLUS_STRUCT_TYPE (type);
13528   TYPE_FN_FIELDLISTS (type) = (struct fn_fieldlist *)
13529     TYPE_ALLOC (type, sizeof (struct fn_fieldlist) * fip->nfnfields);
13530
13531   for (i = 0, flp = fip->fnfieldlists; i < fip->nfnfields; i++, flp++)
13532     {
13533       struct nextfnfield *nfp = flp->head;
13534       struct fn_fieldlist *fn_flp = &TYPE_FN_FIELDLIST (type, i);
13535       int k;
13536
13537       TYPE_FN_FIELDLIST_NAME (type, i) = flp->name;
13538       TYPE_FN_FIELDLIST_LENGTH (type, i) = flp->length;
13539       fn_flp->fn_fields = (struct fn_field *)
13540         TYPE_ALLOC (type, sizeof (struct fn_field) * flp->length);
13541       for (k = flp->length; (k--, nfp); nfp = nfp->next)
13542         fn_flp->fn_fields[k] = nfp->fnfield;
13543     }
13544
13545   TYPE_NFN_FIELDS (type) = fip->nfnfields;
13546 }
13547
13548 /* Returns non-zero if NAME is the name of a vtable member in CU's
13549    language, zero otherwise.  */
13550 static int
13551 is_vtable_name (const char *name, struct dwarf2_cu *cu)
13552 {
13553   static const char vptr[] = "_vptr";
13554   static const char vtable[] = "vtable";
13555
13556   /* Look for the C++ form of the vtable.  */
13557   if (startswith (name, vptr) && is_cplus_marker (name[sizeof (vptr) - 1]))
13558     return 1;
13559
13560   return 0;
13561 }
13562
13563 /* GCC outputs unnamed structures that are really pointers to member
13564    functions, with the ABI-specified layout.  If TYPE describes
13565    such a structure, smash it into a member function type.
13566
13567    GCC shouldn't do this; it should just output pointer to member DIEs.
13568    This is GCC PR debug/28767.  */
13569
13570 static void
13571 quirk_gcc_member_function_pointer (struct type *type, struct objfile *objfile)
13572 {
13573   struct type *pfn_type, *self_type, *new_type;
13574
13575   /* Check for a structure with no name and two children.  */
13576   if (TYPE_CODE (type) != TYPE_CODE_STRUCT || TYPE_NFIELDS (type) != 2)
13577     return;
13578
13579   /* Check for __pfn and __delta members.  */
13580   if (TYPE_FIELD_NAME (type, 0) == NULL
13581       || strcmp (TYPE_FIELD_NAME (type, 0), "__pfn") != 0
13582       || TYPE_FIELD_NAME (type, 1) == NULL
13583       || strcmp (TYPE_FIELD_NAME (type, 1), "__delta") != 0)
13584     return;
13585
13586   /* Find the type of the method.  */
13587   pfn_type = TYPE_FIELD_TYPE (type, 0);
13588   if (pfn_type == NULL
13589       || TYPE_CODE (pfn_type) != TYPE_CODE_PTR
13590       || TYPE_CODE (TYPE_TARGET_TYPE (pfn_type)) != TYPE_CODE_FUNC)
13591     return;
13592
13593   /* Look for the "this" argument.  */
13594   pfn_type = TYPE_TARGET_TYPE (pfn_type);
13595   if (TYPE_NFIELDS (pfn_type) == 0
13596       /* || TYPE_FIELD_TYPE (pfn_type, 0) == NULL */
13597       || TYPE_CODE (TYPE_FIELD_TYPE (pfn_type, 0)) != TYPE_CODE_PTR)
13598     return;
13599
13600   self_type = TYPE_TARGET_TYPE (TYPE_FIELD_TYPE (pfn_type, 0));
13601   new_type = alloc_type (objfile);
13602   smash_to_method_type (new_type, self_type, TYPE_TARGET_TYPE (pfn_type),
13603                         TYPE_FIELDS (pfn_type), TYPE_NFIELDS (pfn_type),
13604                         TYPE_VARARGS (pfn_type));
13605   smash_to_methodptr_type (type, new_type);
13606 }
13607
13608 /* Return non-zero if the CU's PRODUCER string matches the Intel C/C++ compiler
13609    (icc).  */
13610
13611 static int
13612 producer_is_icc (struct dwarf2_cu *cu)
13613 {
13614   if (!cu->checked_producer)
13615     check_producer (cu);
13616
13617   return cu->producer_is_icc;
13618 }
13619
13620 /* Called when we find the DIE that starts a structure or union scope
13621    (definition) to create a type for the structure or union.  Fill in
13622    the type's name and general properties; the members will not be
13623    processed until process_structure_scope.  A symbol table entry for
13624    the type will also not be done until process_structure_scope (assuming
13625    the type has a name).
13626
13627    NOTE: we need to call these functions regardless of whether or not the
13628    DIE has a DW_AT_name attribute, since it might be an anonymous
13629    structure or union.  This gets the type entered into our set of
13630    user defined types.  */
13631
13632 static struct type *
13633 read_structure_type (struct die_info *die, struct dwarf2_cu *cu)
13634 {
13635   struct objfile *objfile = cu->objfile;
13636   struct type *type;
13637   struct attribute *attr;
13638   const char *name;
13639
13640   /* If the definition of this type lives in .debug_types, read that type.
13641      Don't follow DW_AT_specification though, that will take us back up
13642      the chain and we want to go down.  */
13643   attr = dwarf2_attr_no_follow (die, DW_AT_signature);
13644   if (attr)
13645     {
13646       type = get_DW_AT_signature_type (die, attr, cu);
13647
13648       /* The type's CU may not be the same as CU.
13649          Ensure TYPE is recorded with CU in die_type_hash.  */
13650       return set_die_type (die, type, cu);
13651     }
13652
13653   type = alloc_type (objfile);
13654   INIT_CPLUS_SPECIFIC (type);
13655
13656   name = dwarf2_name (die, cu);
13657   if (name != NULL)
13658     {
13659       if (cu->language == language_cplus
13660           || cu->language == language_d
13661           || cu->language == language_rust)
13662         {
13663           const char *full_name = dwarf2_full_name (name, die, cu);
13664
13665           /* dwarf2_full_name might have already finished building the DIE's
13666              type.  If so, there is no need to continue.  */
13667           if (get_die_type (die, cu) != NULL)
13668             return get_die_type (die, cu);
13669
13670           TYPE_TAG_NAME (type) = full_name;
13671           if (die->tag == DW_TAG_structure_type
13672               || die->tag == DW_TAG_class_type)
13673             TYPE_NAME (type) = TYPE_TAG_NAME (type);
13674         }
13675       else
13676         {
13677           /* The name is already allocated along with this objfile, so
13678              we don't need to duplicate it for the type.  */
13679           TYPE_TAG_NAME (type) = name;
13680           if (die->tag == DW_TAG_class_type)
13681             TYPE_NAME (type) = TYPE_TAG_NAME (type);
13682         }
13683     }
13684
13685   if (die->tag == DW_TAG_structure_type)
13686     {
13687       TYPE_CODE (type) = TYPE_CODE_STRUCT;
13688     }
13689   else if (die->tag == DW_TAG_union_type)
13690     {
13691       TYPE_CODE (type) = TYPE_CODE_UNION;
13692     }
13693   else
13694     {
13695       TYPE_CODE (type) = TYPE_CODE_STRUCT;
13696     }
13697
13698   if (cu->language == language_cplus && die->tag == DW_TAG_class_type)
13699     TYPE_DECLARED_CLASS (type) = 1;
13700
13701   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
13702   if (attr)
13703     {
13704       if (attr_form_is_constant (attr))
13705         TYPE_LENGTH (type) = DW_UNSND (attr);
13706       else
13707         {
13708           /* For the moment, dynamic type sizes are not supported
13709              by GDB's struct type.  The actual size is determined
13710              on-demand when resolving the type of a given object,
13711              so set the type's length to zero for now.  Otherwise,
13712              we record an expression as the length, and that expression
13713              could lead to a very large value, which could eventually
13714              lead to us trying to allocate that much memory when creating
13715              a value of that type.  */
13716           TYPE_LENGTH (type) = 0;
13717         }
13718     }
13719   else
13720     {
13721       TYPE_LENGTH (type) = 0;
13722     }
13723
13724   if (producer_is_icc (cu) && (TYPE_LENGTH (type) == 0))
13725     {
13726       /* ICC does not output the required DW_AT_declaration
13727          on incomplete types, but gives them a size of zero.  */
13728       TYPE_STUB (type) = 1;
13729     }
13730   else
13731     TYPE_STUB_SUPPORTED (type) = 1;
13732
13733   if (die_is_declaration (die, cu))
13734     TYPE_STUB (type) = 1;
13735   else if (attr == NULL && die->child == NULL
13736            && producer_is_realview (cu->producer))
13737     /* RealView does not output the required DW_AT_declaration
13738        on incomplete types.  */
13739     TYPE_STUB (type) = 1;
13740
13741   /* We need to add the type field to the die immediately so we don't
13742      infinitely recurse when dealing with pointers to the structure
13743      type within the structure itself.  */
13744   set_die_type (die, type, cu);
13745
13746   /* set_die_type should be already done.  */
13747   set_descriptive_type (type, die, cu);
13748
13749   return type;
13750 }
13751
13752 /* Finish creating a structure or union type, including filling in
13753    its members and creating a symbol for it.  */
13754
13755 static void
13756 process_structure_scope (struct die_info *die, struct dwarf2_cu *cu)
13757 {
13758   struct objfile *objfile = cu->objfile;
13759   struct die_info *child_die;
13760   struct type *type;
13761
13762   type = get_die_type (die, cu);
13763   if (type == NULL)
13764     type = read_structure_type (die, cu);
13765
13766   if (die->child != NULL && ! die_is_declaration (die, cu))
13767     {
13768       struct field_info fi;
13769       VEC (symbolp) *template_args = NULL;
13770       struct cleanup *back_to = make_cleanup (null_cleanup, 0);
13771
13772       memset (&fi, 0, sizeof (struct field_info));
13773
13774       child_die = die->child;
13775
13776       while (child_die && child_die->tag)
13777         {
13778           if (child_die->tag == DW_TAG_member
13779               || child_die->tag == DW_TAG_variable)
13780             {
13781               /* NOTE: carlton/2002-11-05: A C++ static data member
13782                  should be a DW_TAG_member that is a declaration, but
13783                  all versions of G++ as of this writing (so through at
13784                  least 3.2.1) incorrectly generate DW_TAG_variable
13785                  tags for them instead.  */
13786               dwarf2_add_field (&fi, child_die, cu);
13787             }
13788           else if (child_die->tag == DW_TAG_subprogram)
13789             {
13790               /* Rust doesn't have member functions in the C++ sense.
13791                  However, it does emit ordinary functions as children
13792                  of a struct DIE.  */
13793               if (cu->language == language_rust)
13794                 read_func_scope (child_die, cu);
13795               else
13796                 {
13797                   /* C++ member function.  */
13798                   dwarf2_add_member_fn (&fi, child_die, type, cu);
13799                 }
13800             }
13801           else if (child_die->tag == DW_TAG_inheritance)
13802             {
13803               /* C++ base class field.  */
13804               dwarf2_add_field (&fi, child_die, cu);
13805             }
13806           else if (child_die->tag == DW_TAG_typedef)
13807             dwarf2_add_typedef (&fi, child_die, cu);
13808           else if (child_die->tag == DW_TAG_template_type_param
13809                    || child_die->tag == DW_TAG_template_value_param)
13810             {
13811               struct symbol *arg = new_symbol (child_die, NULL, cu);
13812
13813               if (arg != NULL)
13814                 VEC_safe_push (symbolp, template_args, arg);
13815             }
13816
13817           child_die = sibling_die (child_die);
13818         }
13819
13820       /* Attach template arguments to type.  */
13821       if (! VEC_empty (symbolp, template_args))
13822         {
13823           ALLOCATE_CPLUS_STRUCT_TYPE (type);
13824           TYPE_N_TEMPLATE_ARGUMENTS (type)
13825             = VEC_length (symbolp, template_args);
13826           TYPE_TEMPLATE_ARGUMENTS (type)
13827             = XOBNEWVEC (&objfile->objfile_obstack,
13828                          struct symbol *,
13829                          TYPE_N_TEMPLATE_ARGUMENTS (type));
13830           memcpy (TYPE_TEMPLATE_ARGUMENTS (type),
13831                   VEC_address (symbolp, template_args),
13832                   (TYPE_N_TEMPLATE_ARGUMENTS (type)
13833                    * sizeof (struct symbol *)));
13834           VEC_free (symbolp, template_args);
13835         }
13836
13837       /* Attach fields and member functions to the type.  */
13838       if (fi.nfields)
13839         dwarf2_attach_fields_to_type (&fi, type, cu);
13840       if (fi.nfnfields)
13841         {
13842           dwarf2_attach_fn_fields_to_type (&fi, type, cu);
13843
13844           /* Get the type which refers to the base class (possibly this
13845              class itself) which contains the vtable pointer for the current
13846              class from the DW_AT_containing_type attribute.  This use of
13847              DW_AT_containing_type is a GNU extension.  */
13848
13849           if (dwarf2_attr (die, DW_AT_containing_type, cu) != NULL)
13850             {
13851               struct type *t = die_containing_type (die, cu);
13852
13853               set_type_vptr_basetype (type, t);
13854               if (type == t)
13855                 {
13856                   int i;
13857
13858                   /* Our own class provides vtbl ptr.  */
13859                   for (i = TYPE_NFIELDS (t) - 1;
13860                        i >= TYPE_N_BASECLASSES (t);
13861                        --i)
13862                     {
13863                       const char *fieldname = TYPE_FIELD_NAME (t, i);
13864
13865                       if (is_vtable_name (fieldname, cu))
13866                         {
13867                           set_type_vptr_fieldno (type, i);
13868                           break;
13869                         }
13870                     }
13871
13872                   /* Complain if virtual function table field not found.  */
13873                   if (i < TYPE_N_BASECLASSES (t))
13874                     complaint (&symfile_complaints,
13875                                _("virtual function table pointer "
13876                                  "not found when defining class '%s'"),
13877                                TYPE_TAG_NAME (type) ? TYPE_TAG_NAME (type) :
13878                                "");
13879                 }
13880               else
13881                 {
13882                   set_type_vptr_fieldno (type, TYPE_VPTR_FIELDNO (t));
13883                 }
13884             }
13885           else if (cu->producer
13886                    && startswith (cu->producer, "IBM(R) XL C/C++ Advanced Edition"))
13887             {
13888               /* The IBM XLC compiler does not provide direct indication
13889                  of the containing type, but the vtable pointer is
13890                  always named __vfp.  */
13891
13892               int i;
13893
13894               for (i = TYPE_NFIELDS (type) - 1;
13895                    i >= TYPE_N_BASECLASSES (type);
13896                    --i)
13897                 {
13898                   if (strcmp (TYPE_FIELD_NAME (type, i), "__vfp") == 0)
13899                     {
13900                       set_type_vptr_fieldno (type, i);
13901                       set_type_vptr_basetype (type, type);
13902                       break;
13903                     }
13904                 }
13905             }
13906         }
13907
13908       /* Copy fi.typedef_field_list linked list elements content into the
13909          allocated array TYPE_TYPEDEF_FIELD_ARRAY (type).  */
13910       if (fi.typedef_field_list)
13911         {
13912           int i = fi.typedef_field_list_count;
13913
13914           ALLOCATE_CPLUS_STRUCT_TYPE (type);
13915           TYPE_TYPEDEF_FIELD_ARRAY (type)
13916             = ((struct typedef_field *)
13917                TYPE_ALLOC (type, sizeof (TYPE_TYPEDEF_FIELD (type, 0)) * i));
13918           TYPE_TYPEDEF_FIELD_COUNT (type) = i;
13919
13920           /* Reverse the list order to keep the debug info elements order.  */
13921           while (--i >= 0)
13922             {
13923               struct typedef_field *dest, *src;
13924
13925               dest = &TYPE_TYPEDEF_FIELD (type, i);
13926               src = &fi.typedef_field_list->field;
13927               fi.typedef_field_list = fi.typedef_field_list->next;
13928               *dest = *src;
13929             }
13930         }
13931
13932       do_cleanups (back_to);
13933     }
13934
13935   quirk_gcc_member_function_pointer (type, objfile);
13936
13937   /* NOTE: carlton/2004-03-16: GCC 3.4 (or at least one of its
13938      snapshots) has been known to create a die giving a declaration
13939      for a class that has, as a child, a die giving a definition for a
13940      nested class.  So we have to process our children even if the
13941      current die is a declaration.  Normally, of course, a declaration
13942      won't have any children at all.  */
13943
13944   child_die = die->child;
13945
13946   while (child_die != NULL && child_die->tag)
13947     {
13948       if (child_die->tag == DW_TAG_member
13949           || child_die->tag == DW_TAG_variable
13950           || child_die->tag == DW_TAG_inheritance
13951           || child_die->tag == DW_TAG_template_value_param
13952           || child_die->tag == DW_TAG_template_type_param)
13953         {
13954           /* Do nothing.  */
13955         }
13956       else
13957         process_die (child_die, cu);
13958
13959       child_die = sibling_die (child_die);
13960     }
13961
13962   /* Do not consider external references.  According to the DWARF standard,
13963      these DIEs are identified by the fact that they have no byte_size
13964      attribute, and a declaration attribute.  */
13965   if (dwarf2_attr (die, DW_AT_byte_size, cu) != NULL
13966       || !die_is_declaration (die, cu))
13967     new_symbol (die, type, cu);
13968 }
13969
13970 /* Assuming DIE is an enumeration type, and TYPE is its associated type,
13971    update TYPE using some information only available in DIE's children.  */
13972
13973 static void
13974 update_enumeration_type_from_children (struct die_info *die,
13975                                        struct type *type,
13976                                        struct dwarf2_cu *cu)
13977 {
13978   struct die_info *child_die;
13979   int unsigned_enum = 1;
13980   int flag_enum = 1;
13981   ULONGEST mask = 0;
13982
13983   auto_obstack obstack;
13984
13985   for (child_die = die->child;
13986        child_die != NULL && child_die->tag;
13987        child_die = sibling_die (child_die))
13988     {
13989       struct attribute *attr;
13990       LONGEST value;
13991       const gdb_byte *bytes;
13992       struct dwarf2_locexpr_baton *baton;
13993       const char *name;
13994
13995       if (child_die->tag != DW_TAG_enumerator)
13996         continue;
13997
13998       attr = dwarf2_attr (child_die, DW_AT_const_value, cu);
13999       if (attr == NULL)
14000         continue;
14001
14002       name = dwarf2_name (child_die, cu);
14003       if (name == NULL)
14004         name = "<anonymous enumerator>";
14005
14006       dwarf2_const_value_attr (attr, type, name, &obstack, cu,
14007                                &value, &bytes, &baton);
14008       if (value < 0)
14009         {
14010           unsigned_enum = 0;
14011           flag_enum = 0;
14012         }
14013       else if ((mask & value) != 0)
14014         flag_enum = 0;
14015       else
14016         mask |= value;
14017
14018       /* If we already know that the enum type is neither unsigned, nor
14019          a flag type, no need to look at the rest of the enumerates.  */
14020       if (!unsigned_enum && !flag_enum)
14021         break;
14022     }
14023
14024   if (unsigned_enum)
14025     TYPE_UNSIGNED (type) = 1;
14026   if (flag_enum)
14027     TYPE_FLAG_ENUM (type) = 1;
14028 }
14029
14030 /* Given a DW_AT_enumeration_type die, set its type.  We do not
14031    complete the type's fields yet, or create any symbols.  */
14032
14033 static struct type *
14034 read_enumeration_type (struct die_info *die, struct dwarf2_cu *cu)
14035 {
14036   struct objfile *objfile = cu->objfile;
14037   struct type *type;
14038   struct attribute *attr;
14039   const char *name;
14040
14041   /* If the definition of this type lives in .debug_types, read that type.
14042      Don't follow DW_AT_specification though, that will take us back up
14043      the chain and we want to go down.  */
14044   attr = dwarf2_attr_no_follow (die, DW_AT_signature);
14045   if (attr)
14046     {
14047       type = get_DW_AT_signature_type (die, attr, cu);
14048
14049       /* The type's CU may not be the same as CU.
14050          Ensure TYPE is recorded with CU in die_type_hash.  */
14051       return set_die_type (die, type, cu);
14052     }
14053
14054   type = alloc_type (objfile);
14055
14056   TYPE_CODE (type) = TYPE_CODE_ENUM;
14057   name = dwarf2_full_name (NULL, die, cu);
14058   if (name != NULL)
14059     TYPE_TAG_NAME (type) = name;
14060
14061   attr = dwarf2_attr (die, DW_AT_type, cu);
14062   if (attr != NULL)
14063     {
14064       struct type *underlying_type = die_type (die, cu);
14065
14066       TYPE_TARGET_TYPE (type) = underlying_type;
14067     }
14068
14069   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
14070   if (attr)
14071     {
14072       TYPE_LENGTH (type) = DW_UNSND (attr);
14073     }
14074   else
14075     {
14076       TYPE_LENGTH (type) = 0;
14077     }
14078
14079   /* The enumeration DIE can be incomplete.  In Ada, any type can be
14080      declared as private in the package spec, and then defined only
14081      inside the package body.  Such types are known as Taft Amendment
14082      Types.  When another package uses such a type, an incomplete DIE
14083      may be generated by the compiler.  */
14084   if (die_is_declaration (die, cu))
14085     TYPE_STUB (type) = 1;
14086
14087   /* Finish the creation of this type by using the enum's children.
14088      We must call this even when the underlying type has been provided
14089      so that we can determine if we're looking at a "flag" enum.  */
14090   update_enumeration_type_from_children (die, type, cu);
14091
14092   /* If this type has an underlying type that is not a stub, then we
14093      may use its attributes.  We always use the "unsigned" attribute
14094      in this situation, because ordinarily we guess whether the type
14095      is unsigned -- but the guess can be wrong and the underlying type
14096      can tell us the reality.  However, we defer to a local size
14097      attribute if one exists, because this lets the compiler override
14098      the underlying type if needed.  */
14099   if (TYPE_TARGET_TYPE (type) != NULL && !TYPE_STUB (TYPE_TARGET_TYPE (type)))
14100     {
14101       TYPE_UNSIGNED (type) = TYPE_UNSIGNED (TYPE_TARGET_TYPE (type));
14102       if (TYPE_LENGTH (type) == 0)
14103         TYPE_LENGTH (type) = TYPE_LENGTH (TYPE_TARGET_TYPE (type));
14104     }
14105
14106   TYPE_DECLARED_CLASS (type) = dwarf2_flag_true_p (die, DW_AT_enum_class, cu);
14107
14108   return set_die_type (die, type, cu);
14109 }
14110
14111 /* Given a pointer to a die which begins an enumeration, process all
14112    the dies that define the members of the enumeration, and create the
14113    symbol for the enumeration type.
14114
14115    NOTE: We reverse the order of the element list.  */
14116
14117 static void
14118 process_enumeration_scope (struct die_info *die, struct dwarf2_cu *cu)
14119 {
14120   struct type *this_type;
14121
14122   this_type = get_die_type (die, cu);
14123   if (this_type == NULL)
14124     this_type = read_enumeration_type (die, cu);
14125
14126   if (die->child != NULL)
14127     {
14128       struct die_info *child_die;
14129       struct symbol *sym;
14130       struct field *fields = NULL;
14131       int num_fields = 0;
14132       const char *name;
14133
14134       child_die = die->child;
14135       while (child_die && child_die->tag)
14136         {
14137           if (child_die->tag != DW_TAG_enumerator)
14138             {
14139               process_die (child_die, cu);
14140             }
14141           else
14142             {
14143               name = dwarf2_name (child_die, cu);
14144               if (name)
14145                 {
14146                   sym = new_symbol (child_die, this_type, cu);
14147
14148                   if ((num_fields % DW_FIELD_ALLOC_CHUNK) == 0)
14149                     {
14150                       fields = (struct field *)
14151                         xrealloc (fields,
14152                                   (num_fields + DW_FIELD_ALLOC_CHUNK)
14153                                   * sizeof (struct field));
14154                     }
14155
14156                   FIELD_NAME (fields[num_fields]) = SYMBOL_LINKAGE_NAME (sym);
14157                   FIELD_TYPE (fields[num_fields]) = NULL;
14158                   SET_FIELD_ENUMVAL (fields[num_fields], SYMBOL_VALUE (sym));
14159                   FIELD_BITSIZE (fields[num_fields]) = 0;
14160
14161                   num_fields++;
14162                 }
14163             }
14164
14165           child_die = sibling_die (child_die);
14166         }
14167
14168       if (num_fields)
14169         {
14170           TYPE_NFIELDS (this_type) = num_fields;
14171           TYPE_FIELDS (this_type) = (struct field *)
14172             TYPE_ALLOC (this_type, sizeof (struct field) * num_fields);
14173           memcpy (TYPE_FIELDS (this_type), fields,
14174                   sizeof (struct field) * num_fields);
14175           xfree (fields);
14176         }
14177     }
14178
14179   /* If we are reading an enum from a .debug_types unit, and the enum
14180      is a declaration, and the enum is not the signatured type in the
14181      unit, then we do not want to add a symbol for it.  Adding a
14182      symbol would in some cases obscure the true definition of the
14183      enum, giving users an incomplete type when the definition is
14184      actually available.  Note that we do not want to do this for all
14185      enums which are just declarations, because C++0x allows forward
14186      enum declarations.  */
14187   if (cu->per_cu->is_debug_types
14188       && die_is_declaration (die, cu))
14189     {
14190       struct signatured_type *sig_type;
14191
14192       sig_type = (struct signatured_type *) cu->per_cu;
14193       gdb_assert (to_underlying (sig_type->type_offset_in_section) != 0);
14194       if (sig_type->type_offset_in_section != die->sect_off)
14195         return;
14196     }
14197
14198   new_symbol (die, this_type, cu);
14199 }
14200
14201 /* Extract all information from a DW_TAG_array_type DIE and put it in
14202    the DIE's type field.  For now, this only handles one dimensional
14203    arrays.  */
14204
14205 static struct type *
14206 read_array_type (struct die_info *die, struct dwarf2_cu *cu)
14207 {
14208   struct objfile *objfile = cu->objfile;
14209   struct die_info *child_die;
14210   struct type *type;
14211   struct type *element_type, *range_type, *index_type;
14212   struct type **range_types = NULL;
14213   struct attribute *attr;
14214   int ndim = 0;
14215   struct cleanup *back_to;
14216   const char *name;
14217   unsigned int bit_stride = 0;
14218
14219   element_type = die_type (die, cu);
14220
14221   /* The die_type call above may have already set the type for this DIE.  */
14222   type = get_die_type (die, cu);
14223   if (type)
14224     return type;
14225
14226   attr = dwarf2_attr (die, DW_AT_byte_stride, cu);
14227   if (attr != NULL)
14228     bit_stride = DW_UNSND (attr) * 8;
14229
14230   attr = dwarf2_attr (die, DW_AT_bit_stride, cu);
14231   if (attr != NULL)
14232     bit_stride = DW_UNSND (attr);
14233
14234   /* Irix 6.2 native cc creates array types without children for
14235      arrays with unspecified length.  */
14236   if (die->child == NULL)
14237     {
14238       index_type = objfile_type (objfile)->builtin_int;
14239       range_type = create_static_range_type (NULL, index_type, 0, -1);
14240       type = create_array_type_with_stride (NULL, element_type, range_type,
14241                                             bit_stride);
14242       return set_die_type (die, type, cu);
14243     }
14244
14245   back_to = make_cleanup (null_cleanup, NULL);
14246   child_die = die->child;
14247   while (child_die && child_die->tag)
14248     {
14249       if (child_die->tag == DW_TAG_subrange_type)
14250         {
14251           struct type *child_type = read_type_die (child_die, cu);
14252
14253           if (child_type != NULL)
14254             {
14255               /* The range type was succesfully read.  Save it for the
14256                  array type creation.  */
14257               if ((ndim % DW_FIELD_ALLOC_CHUNK) == 0)
14258                 {
14259                   range_types = (struct type **)
14260                     xrealloc (range_types, (ndim + DW_FIELD_ALLOC_CHUNK)
14261                               * sizeof (struct type *));
14262                   if (ndim == 0)
14263                     make_cleanup (free_current_contents, &range_types);
14264                 }
14265               range_types[ndim++] = child_type;
14266             }
14267         }
14268       child_die = sibling_die (child_die);
14269     }
14270
14271   /* Dwarf2 dimensions are output from left to right, create the
14272      necessary array types in backwards order.  */
14273
14274   type = element_type;
14275
14276   if (read_array_order (die, cu) == DW_ORD_col_major)
14277     {
14278       int i = 0;
14279
14280       while (i < ndim)
14281         type = create_array_type_with_stride (NULL, type, range_types[i++],
14282                                               bit_stride);
14283     }
14284   else
14285     {
14286       while (ndim-- > 0)
14287         type = create_array_type_with_stride (NULL, type, range_types[ndim],
14288                                               bit_stride);
14289     }
14290
14291   /* Understand Dwarf2 support for vector types (like they occur on
14292      the PowerPC w/ AltiVec).  Gcc just adds another attribute to the
14293      array type.  This is not part of the Dwarf2/3 standard yet, but a
14294      custom vendor extension.  The main difference between a regular
14295      array and the vector variant is that vectors are passed by value
14296      to functions.  */
14297   attr = dwarf2_attr (die, DW_AT_GNU_vector, cu);
14298   if (attr)
14299     make_vector_type (type);
14300
14301   /* The DIE may have DW_AT_byte_size set.  For example an OpenCL
14302      implementation may choose to implement triple vectors using this
14303      attribute.  */
14304   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
14305   if (attr)
14306     {
14307       if (DW_UNSND (attr) >= TYPE_LENGTH (type))
14308         TYPE_LENGTH (type) = DW_UNSND (attr);
14309       else
14310         complaint (&symfile_complaints,
14311                    _("DW_AT_byte_size for array type smaller "
14312                      "than the total size of elements"));
14313     }
14314
14315   name = dwarf2_name (die, cu);
14316   if (name)
14317     TYPE_NAME (type) = name;
14318
14319   /* Install the type in the die.  */
14320   set_die_type (die, type, cu);
14321
14322   /* set_die_type should be already done.  */
14323   set_descriptive_type (type, die, cu);
14324
14325   do_cleanups (back_to);
14326
14327   return type;
14328 }
14329
14330 static enum dwarf_array_dim_ordering
14331 read_array_order (struct die_info *die, struct dwarf2_cu *cu)
14332 {
14333   struct attribute *attr;
14334
14335   attr = dwarf2_attr (die, DW_AT_ordering, cu);
14336
14337   if (attr)
14338     return (enum dwarf_array_dim_ordering) DW_SND (attr);
14339
14340   /* GNU F77 is a special case, as at 08/2004 array type info is the
14341      opposite order to the dwarf2 specification, but data is still
14342      laid out as per normal fortran.
14343
14344      FIXME: dsl/2004-8-20: If G77 is ever fixed, this will also need
14345      version checking.  */
14346
14347   if (cu->language == language_fortran
14348       && cu->producer && strstr (cu->producer, "GNU F77"))
14349     {
14350       return DW_ORD_row_major;
14351     }
14352
14353   switch (cu->language_defn->la_array_ordering)
14354     {
14355     case array_column_major:
14356       return DW_ORD_col_major;
14357     case array_row_major:
14358     default:
14359       return DW_ORD_row_major;
14360     };
14361 }
14362
14363 /* Extract all information from a DW_TAG_set_type DIE and put it in
14364    the DIE's type field.  */
14365
14366 static struct type *
14367 read_set_type (struct die_info *die, struct dwarf2_cu *cu)
14368 {
14369   struct type *domain_type, *set_type;
14370   struct attribute *attr;
14371
14372   domain_type = die_type (die, cu);
14373
14374   /* The die_type call above may have already set the type for this DIE.  */
14375   set_type = get_die_type (die, cu);
14376   if (set_type)
14377     return set_type;
14378
14379   set_type = create_set_type (NULL, domain_type);
14380
14381   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
14382   if (attr)
14383     TYPE_LENGTH (set_type) = DW_UNSND (attr);
14384
14385   return set_die_type (die, set_type, cu);
14386 }
14387
14388 /* A helper for read_common_block that creates a locexpr baton.
14389    SYM is the symbol which we are marking as computed.
14390    COMMON_DIE is the DIE for the common block.
14391    COMMON_LOC is the location expression attribute for the common
14392    block itself.
14393    MEMBER_LOC is the location expression attribute for the particular
14394    member of the common block that we are processing.
14395    CU is the CU from which the above come.  */
14396
14397 static void
14398 mark_common_block_symbol_computed (struct symbol *sym,
14399                                    struct die_info *common_die,
14400                                    struct attribute *common_loc,
14401                                    struct attribute *member_loc,
14402                                    struct dwarf2_cu *cu)
14403 {
14404   struct objfile *objfile = dwarf2_per_objfile->objfile;
14405   struct dwarf2_locexpr_baton *baton;
14406   gdb_byte *ptr;
14407   unsigned int cu_off;
14408   enum bfd_endian byte_order = gdbarch_byte_order (get_objfile_arch (objfile));
14409   LONGEST offset = 0;
14410
14411   gdb_assert (common_loc && member_loc);
14412   gdb_assert (attr_form_is_block (common_loc));
14413   gdb_assert (attr_form_is_block (member_loc)
14414               || attr_form_is_constant (member_loc));
14415
14416   baton = XOBNEW (&objfile->objfile_obstack, struct dwarf2_locexpr_baton);
14417   baton->per_cu = cu->per_cu;
14418   gdb_assert (baton->per_cu);
14419
14420   baton->size = 5 /* DW_OP_call4 */ + 1 /* DW_OP_plus */;
14421
14422   if (attr_form_is_constant (member_loc))
14423     {
14424       offset = dwarf2_get_attr_constant_value (member_loc, 0);
14425       baton->size += 1 /* DW_OP_addr */ + cu->header.addr_size;
14426     }
14427   else
14428     baton->size += DW_BLOCK (member_loc)->size;
14429
14430   ptr = (gdb_byte *) obstack_alloc (&objfile->objfile_obstack, baton->size);
14431   baton->data = ptr;
14432
14433   *ptr++ = DW_OP_call4;
14434   cu_off = common_die->sect_off - cu->per_cu->sect_off;
14435   store_unsigned_integer (ptr, 4, byte_order, cu_off);
14436   ptr += 4;
14437
14438   if (attr_form_is_constant (member_loc))
14439     {
14440       *ptr++ = DW_OP_addr;
14441       store_unsigned_integer (ptr, cu->header.addr_size, byte_order, offset);
14442       ptr += cu->header.addr_size;
14443     }
14444   else
14445     {
14446       /* We have to copy the data here, because DW_OP_call4 will only
14447          use a DW_AT_location attribute.  */
14448       memcpy (ptr, DW_BLOCK (member_loc)->data, DW_BLOCK (member_loc)->size);
14449       ptr += DW_BLOCK (member_loc)->size;
14450     }
14451
14452   *ptr++ = DW_OP_plus;
14453   gdb_assert (ptr - baton->data == baton->size);
14454
14455   SYMBOL_LOCATION_BATON (sym) = baton;
14456   SYMBOL_ACLASS_INDEX (sym) = dwarf2_locexpr_index;
14457 }
14458
14459 /* Create appropriate locally-scoped variables for all the
14460    DW_TAG_common_block entries.  Also create a struct common_block
14461    listing all such variables for `info common'.  COMMON_BLOCK_DOMAIN
14462    is used to sepate the common blocks name namespace from regular
14463    variable names.  */
14464
14465 static void
14466 read_common_block (struct die_info *die, struct dwarf2_cu *cu)
14467 {
14468   struct attribute *attr;
14469
14470   attr = dwarf2_attr (die, DW_AT_location, cu);
14471   if (attr)
14472     {
14473       /* Support the .debug_loc offsets.  */
14474       if (attr_form_is_block (attr))
14475         {
14476           /* Ok.  */
14477         }
14478       else if (attr_form_is_section_offset (attr))
14479         {
14480           dwarf2_complex_location_expr_complaint ();
14481           attr = NULL;
14482         }
14483       else
14484         {
14485           dwarf2_invalid_attrib_class_complaint ("DW_AT_location",
14486                                                  "common block member");
14487           attr = NULL;
14488         }
14489     }
14490
14491   if (die->child != NULL)
14492     {
14493       struct objfile *objfile = cu->objfile;
14494       struct die_info *child_die;
14495       size_t n_entries = 0, size;
14496       struct common_block *common_block;
14497       struct symbol *sym;
14498
14499       for (child_die = die->child;
14500            child_die && child_die->tag;
14501            child_die = sibling_die (child_die))
14502         ++n_entries;
14503
14504       size = (sizeof (struct common_block)
14505               + (n_entries - 1) * sizeof (struct symbol *));
14506       common_block
14507         = (struct common_block *) obstack_alloc (&objfile->objfile_obstack,
14508                                                  size);
14509       memset (common_block->contents, 0, n_entries * sizeof (struct symbol *));
14510       common_block->n_entries = 0;
14511
14512       for (child_die = die->child;
14513            child_die && child_die->tag;
14514            child_die = sibling_die (child_die))
14515         {
14516           /* Create the symbol in the DW_TAG_common_block block in the current
14517              symbol scope.  */
14518           sym = new_symbol (child_die, NULL, cu);
14519           if (sym != NULL)
14520             {
14521               struct attribute *member_loc;
14522
14523               common_block->contents[common_block->n_entries++] = sym;
14524
14525               member_loc = dwarf2_attr (child_die, DW_AT_data_member_location,
14526                                         cu);
14527               if (member_loc)
14528                 {
14529                   /* GDB has handled this for a long time, but it is
14530                      not specified by DWARF.  It seems to have been
14531                      emitted by gfortran at least as recently as:
14532                      http://gcc.gnu.org/bugzilla/show_bug.cgi?id=23057.  */
14533                   complaint (&symfile_complaints,
14534                              _("Variable in common block has "
14535                                "DW_AT_data_member_location "
14536                                "- DIE at 0x%x [in module %s]"),
14537                              to_underlying (child_die->sect_off),
14538                              objfile_name (cu->objfile));
14539
14540                   if (attr_form_is_section_offset (member_loc))
14541                     dwarf2_complex_location_expr_complaint ();
14542                   else if (attr_form_is_constant (member_loc)
14543                            || attr_form_is_block (member_loc))
14544                     {
14545                       if (attr)
14546                         mark_common_block_symbol_computed (sym, die, attr,
14547                                                            member_loc, cu);
14548                     }
14549                   else
14550                     dwarf2_complex_location_expr_complaint ();
14551                 }
14552             }
14553         }
14554
14555       sym = new_symbol (die, objfile_type (objfile)->builtin_void, cu);
14556       SYMBOL_VALUE_COMMON_BLOCK (sym) = common_block;
14557     }
14558 }
14559
14560 /* Create a type for a C++ namespace.  */
14561
14562 static struct type *
14563 read_namespace_type (struct die_info *die, struct dwarf2_cu *cu)
14564 {
14565   struct objfile *objfile = cu->objfile;
14566   const char *previous_prefix, *name;
14567   int is_anonymous;
14568   struct type *type;
14569
14570   /* For extensions, reuse the type of the original namespace.  */
14571   if (dwarf2_attr (die, DW_AT_extension, cu) != NULL)
14572     {
14573       struct die_info *ext_die;
14574       struct dwarf2_cu *ext_cu = cu;
14575
14576       ext_die = dwarf2_extension (die, &ext_cu);
14577       type = read_type_die (ext_die, ext_cu);
14578
14579       /* EXT_CU may not be the same as CU.
14580          Ensure TYPE is recorded with CU in die_type_hash.  */
14581       return set_die_type (die, type, cu);
14582     }
14583
14584   name = namespace_name (die, &is_anonymous, cu);
14585
14586   /* Now build the name of the current namespace.  */
14587
14588   previous_prefix = determine_prefix (die, cu);
14589   if (previous_prefix[0] != '\0')
14590     name = typename_concat (&objfile->objfile_obstack,
14591                             previous_prefix, name, 0, cu);
14592
14593   /* Create the type.  */
14594   type = init_type (objfile, TYPE_CODE_NAMESPACE, 0, name);
14595   TYPE_TAG_NAME (type) = TYPE_NAME (type);
14596
14597   return set_die_type (die, type, cu);
14598 }
14599
14600 /* Read a namespace scope.  */
14601
14602 static void
14603 read_namespace (struct die_info *die, struct dwarf2_cu *cu)
14604 {
14605   struct objfile *objfile = cu->objfile;
14606   int is_anonymous;
14607
14608   /* Add a symbol associated to this if we haven't seen the namespace
14609      before.  Also, add a using directive if it's an anonymous
14610      namespace.  */
14611
14612   if (dwarf2_attr (die, DW_AT_extension, cu) == NULL)
14613     {
14614       struct type *type;
14615
14616       type = read_type_die (die, cu);
14617       new_symbol (die, type, cu);
14618
14619       namespace_name (die, &is_anonymous, cu);
14620       if (is_anonymous)
14621         {
14622           const char *previous_prefix = determine_prefix (die, cu);
14623
14624           add_using_directive (using_directives (cu->language),
14625                                previous_prefix, TYPE_NAME (type), NULL,
14626                                NULL, NULL, 0, &objfile->objfile_obstack);
14627         }
14628     }
14629
14630   if (die->child != NULL)
14631     {
14632       struct die_info *child_die = die->child;
14633
14634       while (child_die && child_die->tag)
14635         {
14636           process_die (child_die, cu);
14637           child_die = sibling_die (child_die);
14638         }
14639     }
14640 }
14641
14642 /* Read a Fortran module as type.  This DIE can be only a declaration used for
14643    imported module.  Still we need that type as local Fortran "use ... only"
14644    declaration imports depend on the created type in determine_prefix.  */
14645
14646 static struct type *
14647 read_module_type (struct die_info *die, struct dwarf2_cu *cu)
14648 {
14649   struct objfile *objfile = cu->objfile;
14650   const char *module_name;
14651   struct type *type;
14652
14653   module_name = dwarf2_name (die, cu);
14654   if (!module_name)
14655     complaint (&symfile_complaints,
14656                _("DW_TAG_module has no name, offset 0x%x"),
14657                to_underlying (die->sect_off));
14658   type = init_type (objfile, TYPE_CODE_MODULE, 0, module_name);
14659
14660   /* determine_prefix uses TYPE_TAG_NAME.  */
14661   TYPE_TAG_NAME (type) = TYPE_NAME (type);
14662
14663   return set_die_type (die, type, cu);
14664 }
14665
14666 /* Read a Fortran module.  */
14667
14668 static void
14669 read_module (struct die_info *die, struct dwarf2_cu *cu)
14670 {
14671   struct die_info *child_die = die->child;
14672   struct type *type;
14673
14674   type = read_type_die (die, cu);
14675   new_symbol (die, type, cu);
14676
14677   while (child_die && child_die->tag)
14678     {
14679       process_die (child_die, cu);
14680       child_die = sibling_die (child_die);
14681     }
14682 }
14683
14684 /* Return the name of the namespace represented by DIE.  Set
14685    *IS_ANONYMOUS to tell whether or not the namespace is an anonymous
14686    namespace.  */
14687
14688 static const char *
14689 namespace_name (struct die_info *die, int *is_anonymous, struct dwarf2_cu *cu)
14690 {
14691   struct die_info *current_die;
14692   const char *name = NULL;
14693
14694   /* Loop through the extensions until we find a name.  */
14695
14696   for (current_die = die;
14697        current_die != NULL;
14698        current_die = dwarf2_extension (die, &cu))
14699     {
14700       /* We don't use dwarf2_name here so that we can detect the absence
14701          of a name -> anonymous namespace.  */
14702       name = dwarf2_string_attr (die, DW_AT_name, cu);
14703
14704       if (name != NULL)
14705         break;
14706     }
14707
14708   /* Is it an anonymous namespace?  */
14709
14710   *is_anonymous = (name == NULL);
14711   if (*is_anonymous)
14712     name = CP_ANONYMOUS_NAMESPACE_STR;
14713
14714   return name;
14715 }
14716
14717 /* Extract all information from a DW_TAG_pointer_type DIE and add to
14718    the user defined type vector.  */
14719
14720 static struct type *
14721 read_tag_pointer_type (struct die_info *die, struct dwarf2_cu *cu)
14722 {
14723   struct gdbarch *gdbarch = get_objfile_arch (cu->objfile);
14724   struct comp_unit_head *cu_header = &cu->header;
14725   struct type *type;
14726   struct attribute *attr_byte_size;
14727   struct attribute *attr_address_class;
14728   int byte_size, addr_class;
14729   struct type *target_type;
14730
14731   target_type = die_type (die, cu);
14732
14733   /* The die_type call above may have already set the type for this DIE.  */
14734   type = get_die_type (die, cu);
14735   if (type)
14736     return type;
14737
14738   type = lookup_pointer_type (target_type);
14739
14740   attr_byte_size = dwarf2_attr (die, DW_AT_byte_size, cu);
14741   if (attr_byte_size)
14742     byte_size = DW_UNSND (attr_byte_size);
14743   else
14744     byte_size = cu_header->addr_size;
14745
14746   attr_address_class = dwarf2_attr (die, DW_AT_address_class, cu);
14747   if (attr_address_class)
14748     addr_class = DW_UNSND (attr_address_class);
14749   else
14750     addr_class = DW_ADDR_none;
14751
14752   /* If the pointer size or address class is different than the
14753      default, create a type variant marked as such and set the
14754      length accordingly.  */
14755   if (TYPE_LENGTH (type) != byte_size || addr_class != DW_ADDR_none)
14756     {
14757       if (gdbarch_address_class_type_flags_p (gdbarch))
14758         {
14759           int type_flags;
14760
14761           type_flags = gdbarch_address_class_type_flags
14762                          (gdbarch, byte_size, addr_class);
14763           gdb_assert ((type_flags & ~TYPE_INSTANCE_FLAG_ADDRESS_CLASS_ALL)
14764                       == 0);
14765           type = make_type_with_address_space (type, type_flags);
14766         }
14767       else if (TYPE_LENGTH (type) != byte_size)
14768         {
14769           complaint (&symfile_complaints,
14770                      _("invalid pointer size %d"), byte_size);
14771         }
14772       else
14773         {
14774           /* Should we also complain about unhandled address classes?  */
14775         }
14776     }
14777
14778   TYPE_LENGTH (type) = byte_size;
14779   return set_die_type (die, type, cu);
14780 }
14781
14782 /* Extract all information from a DW_TAG_ptr_to_member_type DIE and add to
14783    the user defined type vector.  */
14784
14785 static struct type *
14786 read_tag_ptr_to_member_type (struct die_info *die, struct dwarf2_cu *cu)
14787 {
14788   struct type *type;
14789   struct type *to_type;
14790   struct type *domain;
14791
14792   to_type = die_type (die, cu);
14793   domain = die_containing_type (die, cu);
14794
14795   /* The calls above may have already set the type for this DIE.  */
14796   type = get_die_type (die, cu);
14797   if (type)
14798     return type;
14799
14800   if (TYPE_CODE (check_typedef (to_type)) == TYPE_CODE_METHOD)
14801     type = lookup_methodptr_type (to_type);
14802   else if (TYPE_CODE (check_typedef (to_type)) == TYPE_CODE_FUNC)
14803     {
14804       struct type *new_type = alloc_type (cu->objfile);
14805
14806       smash_to_method_type (new_type, domain, TYPE_TARGET_TYPE (to_type),
14807                             TYPE_FIELDS (to_type), TYPE_NFIELDS (to_type),
14808                             TYPE_VARARGS (to_type));
14809       type = lookup_methodptr_type (new_type);
14810     }
14811   else
14812     type = lookup_memberptr_type (to_type, domain);
14813
14814   return set_die_type (die, type, cu);
14815 }
14816
14817 /* Extract all information from a DW_TAG_{rvalue_,}reference_type DIE and add to
14818    the user defined type vector.  */
14819
14820 static struct type *
14821 read_tag_reference_type (struct die_info *die, struct dwarf2_cu *cu,
14822                           enum type_code refcode)
14823 {
14824   struct comp_unit_head *cu_header = &cu->header;
14825   struct type *type, *target_type;
14826   struct attribute *attr;
14827
14828   gdb_assert (refcode == TYPE_CODE_REF || refcode == TYPE_CODE_RVALUE_REF);
14829
14830   target_type = die_type (die, cu);
14831
14832   /* The die_type call above may have already set the type for this DIE.  */
14833   type = get_die_type (die, cu);
14834   if (type)
14835     return type;
14836
14837   type = lookup_reference_type (target_type, refcode);
14838   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
14839   if (attr)
14840     {
14841       TYPE_LENGTH (type) = DW_UNSND (attr);
14842     }
14843   else
14844     {
14845       TYPE_LENGTH (type) = cu_header->addr_size;
14846     }
14847   return set_die_type (die, type, cu);
14848 }
14849
14850 /* Add the given cv-qualifiers to the element type of the array.  GCC
14851    outputs DWARF type qualifiers that apply to an array, not the
14852    element type.  But GDB relies on the array element type to carry
14853    the cv-qualifiers.  This mimics section 6.7.3 of the C99
14854    specification.  */
14855
14856 static struct type *
14857 add_array_cv_type (struct die_info *die, struct dwarf2_cu *cu,
14858                    struct type *base_type, int cnst, int voltl)
14859 {
14860   struct type *el_type, *inner_array;
14861
14862   base_type = copy_type (base_type);
14863   inner_array = base_type;
14864
14865   while (TYPE_CODE (TYPE_TARGET_TYPE (inner_array)) == TYPE_CODE_ARRAY)
14866     {
14867       TYPE_TARGET_TYPE (inner_array) =
14868         copy_type (TYPE_TARGET_TYPE (inner_array));
14869       inner_array = TYPE_TARGET_TYPE (inner_array);
14870     }
14871
14872   el_type = TYPE_TARGET_TYPE (inner_array);
14873   cnst |= TYPE_CONST (el_type);
14874   voltl |= TYPE_VOLATILE (el_type);
14875   TYPE_TARGET_TYPE (inner_array) = make_cv_type (cnst, voltl, el_type, NULL);
14876
14877   return set_die_type (die, base_type, cu);
14878 }
14879
14880 static struct type *
14881 read_tag_const_type (struct die_info *die, struct dwarf2_cu *cu)
14882 {
14883   struct type *base_type, *cv_type;
14884
14885   base_type = die_type (die, cu);
14886
14887   /* The die_type call above may have already set the type for this DIE.  */
14888   cv_type = get_die_type (die, cu);
14889   if (cv_type)
14890     return cv_type;
14891
14892   /* In case the const qualifier is applied to an array type, the element type
14893      is so qualified, not the array type (section 6.7.3 of C99).  */
14894   if (TYPE_CODE (base_type) == TYPE_CODE_ARRAY)
14895     return add_array_cv_type (die, cu, base_type, 1, 0);
14896
14897   cv_type = make_cv_type (1, TYPE_VOLATILE (base_type), base_type, 0);
14898   return set_die_type (die, cv_type, cu);
14899 }
14900
14901 static struct type *
14902 read_tag_volatile_type (struct die_info *die, struct dwarf2_cu *cu)
14903 {
14904   struct type *base_type, *cv_type;
14905
14906   base_type = die_type (die, cu);
14907
14908   /* The die_type call above may have already set the type for this DIE.  */
14909   cv_type = get_die_type (die, cu);
14910   if (cv_type)
14911     return cv_type;
14912
14913   /* In case the volatile qualifier is applied to an array type, the
14914      element type is so qualified, not the array type (section 6.7.3
14915      of C99).  */
14916   if (TYPE_CODE (base_type) == TYPE_CODE_ARRAY)
14917     return add_array_cv_type (die, cu, base_type, 0, 1);
14918
14919   cv_type = make_cv_type (TYPE_CONST (base_type), 1, base_type, 0);
14920   return set_die_type (die, cv_type, cu);
14921 }
14922
14923 /* Handle DW_TAG_restrict_type.  */
14924
14925 static struct type *
14926 read_tag_restrict_type (struct die_info *die, struct dwarf2_cu *cu)
14927 {
14928   struct type *base_type, *cv_type;
14929
14930   base_type = die_type (die, cu);
14931
14932   /* The die_type call above may have already set the type for this DIE.  */
14933   cv_type = get_die_type (die, cu);
14934   if (cv_type)
14935     return cv_type;
14936
14937   cv_type = make_restrict_type (base_type);
14938   return set_die_type (die, cv_type, cu);
14939 }
14940
14941 /* Handle DW_TAG_atomic_type.  */
14942
14943 static struct type *
14944 read_tag_atomic_type (struct die_info *die, struct dwarf2_cu *cu)
14945 {
14946   struct type *base_type, *cv_type;
14947
14948   base_type = die_type (die, cu);
14949
14950   /* The die_type call above may have already set the type for this DIE.  */
14951   cv_type = get_die_type (die, cu);
14952   if (cv_type)
14953     return cv_type;
14954
14955   cv_type = make_atomic_type (base_type);
14956   return set_die_type (die, cv_type, cu);
14957 }
14958
14959 /* Extract all information from a DW_TAG_string_type DIE and add to
14960    the user defined type vector.  It isn't really a user defined type,
14961    but it behaves like one, with other DIE's using an AT_user_def_type
14962    attribute to reference it.  */
14963
14964 static struct type *
14965 read_tag_string_type (struct die_info *die, struct dwarf2_cu *cu)
14966 {
14967   struct objfile *objfile = cu->objfile;
14968   struct gdbarch *gdbarch = get_objfile_arch (objfile);
14969   struct type *type, *range_type, *index_type, *char_type;
14970   struct attribute *attr;
14971   unsigned int length;
14972
14973   attr = dwarf2_attr (die, DW_AT_string_length, cu);
14974   if (attr)
14975     {
14976       length = DW_UNSND (attr);
14977     }
14978   else
14979     {
14980       /* Check for the DW_AT_byte_size attribute.  */
14981       attr = dwarf2_attr (die, DW_AT_byte_size, cu);
14982       if (attr)
14983         {
14984           length = DW_UNSND (attr);
14985         }
14986       else
14987         {
14988           length = 1;
14989         }
14990     }
14991
14992   index_type = objfile_type (objfile)->builtin_int;
14993   range_type = create_static_range_type (NULL, index_type, 1, length);
14994   char_type = language_string_char_type (cu->language_defn, gdbarch);
14995   type = create_string_type (NULL, char_type, range_type);
14996
14997   return set_die_type (die, type, cu);
14998 }
14999
15000 /* Assuming that DIE corresponds to a function, returns nonzero
15001    if the function is prototyped.  */
15002
15003 static int
15004 prototyped_function_p (struct die_info *die, struct dwarf2_cu *cu)
15005 {
15006   struct attribute *attr;
15007
15008   attr = dwarf2_attr (die, DW_AT_prototyped, cu);
15009   if (attr && (DW_UNSND (attr) != 0))
15010     return 1;
15011
15012   /* The DWARF standard implies that the DW_AT_prototyped attribute
15013      is only meaninful for C, but the concept also extends to other
15014      languages that allow unprototyped functions (Eg: Objective C).
15015      For all other languages, assume that functions are always
15016      prototyped.  */
15017   if (cu->language != language_c
15018       && cu->language != language_objc
15019       && cu->language != language_opencl)
15020     return 1;
15021
15022   /* RealView does not emit DW_AT_prototyped.  We can not distinguish
15023      prototyped and unprototyped functions; default to prototyped,
15024      since that is more common in modern code (and RealView warns
15025      about unprototyped functions).  */
15026   if (producer_is_realview (cu->producer))
15027     return 1;
15028
15029   return 0;
15030 }
15031
15032 /* Handle DIES due to C code like:
15033
15034    struct foo
15035    {
15036    int (*funcp)(int a, long l);
15037    int b;
15038    };
15039
15040    ('funcp' generates a DW_TAG_subroutine_type DIE).  */
15041
15042 static struct type *
15043 read_subroutine_type (struct die_info *die, struct dwarf2_cu *cu)
15044 {
15045   struct objfile *objfile = cu->objfile;
15046   struct type *type;            /* Type that this function returns.  */
15047   struct type *ftype;           /* Function that returns above type.  */
15048   struct attribute *attr;
15049
15050   type = die_type (die, cu);
15051
15052   /* The die_type call above may have already set the type for this DIE.  */
15053   ftype = get_die_type (die, cu);
15054   if (ftype)
15055     return ftype;
15056
15057   ftype = lookup_function_type (type);
15058
15059   if (prototyped_function_p (die, cu))
15060     TYPE_PROTOTYPED (ftype) = 1;
15061
15062   /* Store the calling convention in the type if it's available in
15063      the subroutine die.  Otherwise set the calling convention to
15064      the default value DW_CC_normal.  */
15065   attr = dwarf2_attr (die, DW_AT_calling_convention, cu);
15066   if (attr)
15067     TYPE_CALLING_CONVENTION (ftype) = DW_UNSND (attr);
15068   else if (cu->producer && strstr (cu->producer, "IBM XL C for OpenCL"))
15069     TYPE_CALLING_CONVENTION (ftype) = DW_CC_GDB_IBM_OpenCL;
15070   else
15071     TYPE_CALLING_CONVENTION (ftype) = DW_CC_normal;
15072
15073   /* Record whether the function returns normally to its caller or not
15074      if the DWARF producer set that information.  */
15075   attr = dwarf2_attr (die, DW_AT_noreturn, cu);
15076   if (attr && (DW_UNSND (attr) != 0))
15077     TYPE_NO_RETURN (ftype) = 1;
15078
15079   /* We need to add the subroutine type to the die immediately so
15080      we don't infinitely recurse when dealing with parameters
15081      declared as the same subroutine type.  */
15082   set_die_type (die, ftype, cu);
15083
15084   if (die->child != NULL)
15085     {
15086       struct type *void_type = objfile_type (objfile)->builtin_void;
15087       struct die_info *child_die;
15088       int nparams, iparams;
15089
15090       /* Count the number of parameters.
15091          FIXME: GDB currently ignores vararg functions, but knows about
15092          vararg member functions.  */
15093       nparams = 0;
15094       child_die = die->child;
15095       while (child_die && child_die->tag)
15096         {
15097           if (child_die->tag == DW_TAG_formal_parameter)
15098             nparams++;
15099           else if (child_die->tag == DW_TAG_unspecified_parameters)
15100             TYPE_VARARGS (ftype) = 1;
15101           child_die = sibling_die (child_die);
15102         }
15103
15104       /* Allocate storage for parameters and fill them in.  */
15105       TYPE_NFIELDS (ftype) = nparams;
15106       TYPE_FIELDS (ftype) = (struct field *)
15107         TYPE_ZALLOC (ftype, nparams * sizeof (struct field));
15108
15109       /* TYPE_FIELD_TYPE must never be NULL.  Pre-fill the array to ensure it
15110          even if we error out during the parameters reading below.  */
15111       for (iparams = 0; iparams < nparams; iparams++)
15112         TYPE_FIELD_TYPE (ftype, iparams) = void_type;
15113
15114       iparams = 0;
15115       child_die = die->child;
15116       while (child_die && child_die->tag)
15117         {
15118           if (child_die->tag == DW_TAG_formal_parameter)
15119             {
15120               struct type *arg_type;
15121
15122               /* DWARF version 2 has no clean way to discern C++
15123                  static and non-static member functions.  G++ helps
15124                  GDB by marking the first parameter for non-static
15125                  member functions (which is the this pointer) as
15126                  artificial.  We pass this information to
15127                  dwarf2_add_member_fn via TYPE_FIELD_ARTIFICIAL.
15128
15129                  DWARF version 3 added DW_AT_object_pointer, which GCC
15130                  4.5 does not yet generate.  */
15131               attr = dwarf2_attr (child_die, DW_AT_artificial, cu);
15132               if (attr)
15133                 TYPE_FIELD_ARTIFICIAL (ftype, iparams) = DW_UNSND (attr);
15134               else
15135                 TYPE_FIELD_ARTIFICIAL (ftype, iparams) = 0;
15136               arg_type = die_type (child_die, cu);
15137
15138               /* RealView does not mark THIS as const, which the testsuite
15139                  expects.  GCC marks THIS as const in method definitions,
15140                  but not in the class specifications (GCC PR 43053).  */
15141               if (cu->language == language_cplus && !TYPE_CONST (arg_type)
15142                   && TYPE_FIELD_ARTIFICIAL (ftype, iparams))
15143                 {
15144                   int is_this = 0;
15145                   struct dwarf2_cu *arg_cu = cu;
15146                   const char *name = dwarf2_name (child_die, cu);
15147
15148                   attr = dwarf2_attr (die, DW_AT_object_pointer, cu);
15149                   if (attr)
15150                     {
15151                       /* If the compiler emits this, use it.  */
15152                       if (follow_die_ref (die, attr, &arg_cu) == child_die)
15153                         is_this = 1;
15154                     }
15155                   else if (name && strcmp (name, "this") == 0)
15156                     /* Function definitions will have the argument names.  */
15157                     is_this = 1;
15158                   else if (name == NULL && iparams == 0)
15159                     /* Declarations may not have the names, so like
15160                        elsewhere in GDB, assume an artificial first
15161                        argument is "this".  */
15162                     is_this = 1;
15163
15164                   if (is_this)
15165                     arg_type = make_cv_type (1, TYPE_VOLATILE (arg_type),
15166                                              arg_type, 0);
15167                 }
15168
15169               TYPE_FIELD_TYPE (ftype, iparams) = arg_type;
15170               iparams++;
15171             }
15172           child_die = sibling_die (child_die);
15173         }
15174     }
15175
15176   return ftype;
15177 }
15178
15179 static struct type *
15180 read_typedef (struct die_info *die, struct dwarf2_cu *cu)
15181 {
15182   struct objfile *objfile = cu->objfile;
15183   const char *name = NULL;
15184   struct type *this_type, *target_type;
15185
15186   name = dwarf2_full_name (NULL, die, cu);
15187   this_type = init_type (objfile, TYPE_CODE_TYPEDEF, 0, name);
15188   TYPE_TARGET_STUB (this_type) = 1;
15189   set_die_type (die, this_type, cu);
15190   target_type = die_type (die, cu);
15191   if (target_type != this_type)
15192     TYPE_TARGET_TYPE (this_type) = target_type;
15193   else
15194     {
15195       /* Self-referential typedefs are, it seems, not allowed by the DWARF
15196          spec and cause infinite loops in GDB.  */
15197       complaint (&symfile_complaints,
15198                  _("Self-referential DW_TAG_typedef "
15199                    "- DIE at 0x%x [in module %s]"),
15200                  to_underlying (die->sect_off), objfile_name (objfile));
15201       TYPE_TARGET_TYPE (this_type) = NULL;
15202     }
15203   return this_type;
15204 }
15205
15206 /* Allocate a floating-point type of size BITS and name NAME.  Pass NAME_HINT
15207    (which may be different from NAME) to the architecture back-end to allow
15208    it to guess the correct format if necessary.  */
15209
15210 static struct type *
15211 dwarf2_init_float_type (struct objfile *objfile, int bits, const char *name,
15212                         const char *name_hint)
15213 {
15214   struct gdbarch *gdbarch = get_objfile_arch (objfile);
15215   const struct floatformat **format;
15216   struct type *type;
15217
15218   format = gdbarch_floatformat_for_type (gdbarch, name_hint, bits);
15219   if (format)
15220     type = init_float_type (objfile, bits, name, format);
15221   else
15222     type = init_type (objfile, TYPE_CODE_ERROR, bits / TARGET_CHAR_BIT, name);
15223
15224   return type;
15225 }
15226
15227 /* Find a representation of a given base type and install
15228    it in the TYPE field of the die.  */
15229
15230 static struct type *
15231 read_base_type (struct die_info *die, struct dwarf2_cu *cu)
15232 {
15233   struct objfile *objfile = cu->objfile;
15234   struct type *type;
15235   struct attribute *attr;
15236   int encoding = 0, bits = 0;
15237   const char *name;
15238
15239   attr = dwarf2_attr (die, DW_AT_encoding, cu);
15240   if (attr)
15241     {
15242       encoding = DW_UNSND (attr);
15243     }
15244   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
15245   if (attr)
15246     {
15247       bits = DW_UNSND (attr) * TARGET_CHAR_BIT;
15248     }
15249   name = dwarf2_name (die, cu);
15250   if (!name)
15251     {
15252       complaint (&symfile_complaints,
15253                  _("DW_AT_name missing from DW_TAG_base_type"));
15254     }
15255
15256   switch (encoding)
15257     {
15258       case DW_ATE_address:
15259         /* Turn DW_ATE_address into a void * pointer.  */
15260         type = init_type (objfile, TYPE_CODE_VOID, 1, NULL);
15261         type = init_pointer_type (objfile, bits, name, type);
15262         break;
15263       case DW_ATE_boolean:
15264         type = init_boolean_type (objfile, bits, 1, name);
15265         break;
15266       case DW_ATE_complex_float:
15267         type = dwarf2_init_float_type (objfile, bits / 2, NULL, name);
15268         type = init_complex_type (objfile, name, type);
15269         break;
15270       case DW_ATE_decimal_float:
15271         type = init_decfloat_type (objfile, bits, name);
15272         break;
15273       case DW_ATE_float:
15274         type = dwarf2_init_float_type (objfile, bits, name, name);
15275         break;
15276       case DW_ATE_signed:
15277         type = init_integer_type (objfile, bits, 0, name);
15278         break;
15279       case DW_ATE_unsigned:
15280         if (cu->language == language_fortran
15281             && name
15282             && startswith (name, "character("))
15283           type = init_character_type (objfile, bits, 1, name);
15284         else
15285           type = init_integer_type (objfile, bits, 1, name);
15286         break;
15287       case DW_ATE_signed_char:
15288         if (cu->language == language_ada || cu->language == language_m2
15289             || cu->language == language_pascal
15290             || cu->language == language_fortran)
15291           type = init_character_type (objfile, bits, 0, name);
15292         else
15293           type = init_integer_type (objfile, bits, 0, name);
15294         break;
15295       case DW_ATE_unsigned_char:
15296         if (cu->language == language_ada || cu->language == language_m2
15297             || cu->language == language_pascal
15298             || cu->language == language_fortran
15299             || cu->language == language_rust)
15300           type = init_character_type (objfile, bits, 1, name);
15301         else
15302           type = init_integer_type (objfile, bits, 1, name);
15303         break;
15304       case DW_ATE_UTF:
15305         {
15306           gdbarch *arch = get_objfile_arch (objfile);
15307
15308           if (bits == 16)
15309             type = builtin_type (arch)->builtin_char16;
15310           else if (bits == 32)
15311             type = builtin_type (arch)->builtin_char32;
15312           else
15313             {
15314               complaint (&symfile_complaints,
15315                          _("unsupported DW_ATE_UTF bit size: '%d'"),
15316                          bits);
15317               type = init_integer_type (objfile, bits, 1, name);
15318             }
15319           return set_die_type (die, type, cu);
15320         }
15321         break;
15322
15323       default:
15324         complaint (&symfile_complaints, _("unsupported DW_AT_encoding: '%s'"),
15325                    dwarf_type_encoding_name (encoding));
15326         type = init_type (objfile, TYPE_CODE_ERROR,
15327                           bits / TARGET_CHAR_BIT, name);
15328         break;
15329     }
15330
15331   if (name && strcmp (name, "char") == 0)
15332     TYPE_NOSIGN (type) = 1;
15333
15334   return set_die_type (die, type, cu);
15335 }
15336
15337 /* Parse dwarf attribute if it's a block, reference or constant and put the
15338    resulting value of the attribute into struct bound_prop.
15339    Returns 1 if ATTR could be resolved into PROP, 0 otherwise.  */
15340
15341 static int
15342 attr_to_dynamic_prop (const struct attribute *attr, struct die_info *die,
15343                       struct dwarf2_cu *cu, struct dynamic_prop *prop)
15344 {
15345   struct dwarf2_property_baton *baton;
15346   struct obstack *obstack = &cu->objfile->objfile_obstack;
15347
15348   if (attr == NULL || prop == NULL)
15349     return 0;
15350
15351   if (attr_form_is_block (attr))
15352     {
15353       baton = XOBNEW (obstack, struct dwarf2_property_baton);
15354       baton->referenced_type = NULL;
15355       baton->locexpr.per_cu = cu->per_cu;
15356       baton->locexpr.size = DW_BLOCK (attr)->size;
15357       baton->locexpr.data = DW_BLOCK (attr)->data;
15358       prop->data.baton = baton;
15359       prop->kind = PROP_LOCEXPR;
15360       gdb_assert (prop->data.baton != NULL);
15361     }
15362   else if (attr_form_is_ref (attr))
15363     {
15364       struct dwarf2_cu *target_cu = cu;
15365       struct die_info *target_die;
15366       struct attribute *target_attr;
15367
15368       target_die = follow_die_ref (die, attr, &target_cu);
15369       target_attr = dwarf2_attr (target_die, DW_AT_location, target_cu);
15370       if (target_attr == NULL)
15371         target_attr = dwarf2_attr (target_die, DW_AT_data_member_location,
15372                                    target_cu);
15373       if (target_attr == NULL)
15374         return 0;
15375
15376       switch (target_attr->name)
15377         {
15378           case DW_AT_location:
15379             if (attr_form_is_section_offset (target_attr))
15380               {
15381                 baton = XOBNEW (obstack, struct dwarf2_property_baton);
15382                 baton->referenced_type = die_type (target_die, target_cu);
15383                 fill_in_loclist_baton (cu, &baton->loclist, target_attr);
15384                 prop->data.baton = baton;
15385                 prop->kind = PROP_LOCLIST;
15386                 gdb_assert (prop->data.baton != NULL);
15387               }
15388             else if (attr_form_is_block (target_attr))
15389               {
15390                 baton = XOBNEW (obstack, struct dwarf2_property_baton);
15391                 baton->referenced_type = die_type (target_die, target_cu);
15392                 baton->locexpr.per_cu = cu->per_cu;
15393                 baton->locexpr.size = DW_BLOCK (target_attr)->size;
15394                 baton->locexpr.data = DW_BLOCK (target_attr)->data;
15395                 prop->data.baton = baton;
15396                 prop->kind = PROP_LOCEXPR;
15397                 gdb_assert (prop->data.baton != NULL);
15398               }
15399             else
15400               {
15401                 dwarf2_invalid_attrib_class_complaint ("DW_AT_location",
15402                                                        "dynamic property");
15403                 return 0;
15404               }
15405             break;
15406           case DW_AT_data_member_location:
15407             {
15408               LONGEST offset;
15409
15410               if (!handle_data_member_location (target_die, target_cu,
15411                                                 &offset))
15412                 return 0;
15413
15414               baton = XOBNEW (obstack, struct dwarf2_property_baton);
15415               baton->referenced_type = read_type_die (target_die->parent,
15416                                                       target_cu);
15417               baton->offset_info.offset = offset;
15418               baton->offset_info.type = die_type (target_die, target_cu);
15419               prop->data.baton = baton;
15420               prop->kind = PROP_ADDR_OFFSET;
15421               break;
15422             }
15423         }
15424     }
15425   else if (attr_form_is_constant (attr))
15426     {
15427       prop->data.const_val = dwarf2_get_attr_constant_value (attr, 0);
15428       prop->kind = PROP_CONST;
15429     }
15430   else
15431     {
15432       dwarf2_invalid_attrib_class_complaint (dwarf_form_name (attr->form),
15433                                              dwarf2_name (die, cu));
15434       return 0;
15435     }
15436
15437   return 1;
15438 }
15439
15440 /* Read the given DW_AT_subrange DIE.  */
15441
15442 static struct type *
15443 read_subrange_type (struct die_info *die, struct dwarf2_cu *cu)
15444 {
15445   struct type *base_type, *orig_base_type;
15446   struct type *range_type;
15447   struct attribute *attr;
15448   struct dynamic_prop low, high;
15449   int low_default_is_valid;
15450   int high_bound_is_count = 0;
15451   const char *name;
15452   LONGEST negative_mask;
15453
15454   orig_base_type = die_type (die, cu);
15455   /* If ORIG_BASE_TYPE is a typedef, it will not be TYPE_UNSIGNED,
15456      whereas the real type might be.  So, we use ORIG_BASE_TYPE when
15457      creating the range type, but we use the result of check_typedef
15458      when examining properties of the type.  */
15459   base_type = check_typedef (orig_base_type);
15460
15461   /* The die_type call above may have already set the type for this DIE.  */
15462   range_type = get_die_type (die, cu);
15463   if (range_type)
15464     return range_type;
15465
15466   low.kind = PROP_CONST;
15467   high.kind = PROP_CONST;
15468   high.data.const_val = 0;
15469
15470   /* Set LOW_DEFAULT_IS_VALID if current language and DWARF version allow
15471      omitting DW_AT_lower_bound.  */
15472   switch (cu->language)
15473     {
15474     case language_c:
15475     case language_cplus:
15476       low.data.const_val = 0;
15477       low_default_is_valid = 1;
15478       break;
15479     case language_fortran:
15480       low.data.const_val = 1;
15481       low_default_is_valid = 1;
15482       break;
15483     case language_d:
15484     case language_objc:
15485     case language_rust:
15486       low.data.const_val = 0;
15487       low_default_is_valid = (cu->header.version >= 4);
15488       break;
15489     case language_ada:
15490     case language_m2:
15491     case language_pascal:
15492       low.data.const_val = 1;
15493       low_default_is_valid = (cu->header.version >= 4);
15494       break;
15495     default:
15496       low.data.const_val = 0;
15497       low_default_is_valid = 0;
15498       break;
15499     }
15500
15501   attr = dwarf2_attr (die, DW_AT_lower_bound, cu);
15502   if (attr)
15503     attr_to_dynamic_prop (attr, die, cu, &low);
15504   else if (!low_default_is_valid)
15505     complaint (&symfile_complaints, _("Missing DW_AT_lower_bound "
15506                                       "- DIE at 0x%x [in module %s]"),
15507                to_underlying (die->sect_off), objfile_name (cu->objfile));
15508
15509   attr = dwarf2_attr (die, DW_AT_upper_bound, cu);
15510   if (!attr_to_dynamic_prop (attr, die, cu, &high))
15511     {
15512       attr = dwarf2_attr (die, DW_AT_count, cu);
15513       if (attr_to_dynamic_prop (attr, die, cu, &high))
15514         {
15515           /* If bounds are constant do the final calculation here.  */
15516           if (low.kind == PROP_CONST && high.kind == PROP_CONST)
15517             high.data.const_val = low.data.const_val + high.data.const_val - 1;
15518           else
15519             high_bound_is_count = 1;
15520         }
15521     }
15522
15523   /* Dwarf-2 specifications explicitly allows to create subrange types
15524      without specifying a base type.
15525      In that case, the base type must be set to the type of
15526      the lower bound, upper bound or count, in that order, if any of these
15527      three attributes references an object that has a type.
15528      If no base type is found, the Dwarf-2 specifications say that
15529      a signed integer type of size equal to the size of an address should
15530      be used.
15531      For the following C code: `extern char gdb_int [];'
15532      GCC produces an empty range DIE.
15533      FIXME: muller/2010-05-28: Possible references to object for low bound,
15534      high bound or count are not yet handled by this code.  */
15535   if (TYPE_CODE (base_type) == TYPE_CODE_VOID)
15536     {
15537       struct objfile *objfile = cu->objfile;
15538       struct gdbarch *gdbarch = get_objfile_arch (objfile);
15539       int addr_size = gdbarch_addr_bit (gdbarch) /8;
15540       struct type *int_type = objfile_type (objfile)->builtin_int;
15541
15542       /* Test "int", "long int", and "long long int" objfile types,
15543          and select the first one having a size above or equal to the
15544          architecture address size.  */
15545       if (int_type && TYPE_LENGTH (int_type) >= addr_size)
15546         base_type = int_type;
15547       else
15548         {
15549           int_type = objfile_type (objfile)->builtin_long;
15550           if (int_type && TYPE_LENGTH (int_type) >= addr_size)
15551             base_type = int_type;
15552           else
15553             {
15554               int_type = objfile_type (objfile)->builtin_long_long;
15555               if (int_type && TYPE_LENGTH (int_type) >= addr_size)
15556                 base_type = int_type;
15557             }
15558         }
15559     }
15560
15561   /* Normally, the DWARF producers are expected to use a signed
15562      constant form (Eg. DW_FORM_sdata) to express negative bounds.
15563      But this is unfortunately not always the case, as witnessed
15564      with GCC, for instance, where the ambiguous DW_FORM_dataN form
15565      is used instead.  To work around that ambiguity, we treat
15566      the bounds as signed, and thus sign-extend their values, when
15567      the base type is signed.  */
15568   negative_mask =
15569     -((LONGEST) 1 << (TYPE_LENGTH (base_type) * TARGET_CHAR_BIT - 1));
15570   if (low.kind == PROP_CONST
15571       && !TYPE_UNSIGNED (base_type) && (low.data.const_val & negative_mask))
15572     low.data.const_val |= negative_mask;
15573   if (high.kind == PROP_CONST
15574       && !TYPE_UNSIGNED (base_type) && (high.data.const_val & negative_mask))
15575     high.data.const_val |= negative_mask;
15576
15577   range_type = create_range_type (NULL, orig_base_type, &low, &high);
15578
15579   if (high_bound_is_count)
15580     TYPE_RANGE_DATA (range_type)->flag_upper_bound_is_count = 1;
15581
15582   /* Ada expects an empty array on no boundary attributes.  */
15583   if (attr == NULL && cu->language != language_ada)
15584     TYPE_HIGH_BOUND_KIND (range_type) = PROP_UNDEFINED;
15585
15586   name = dwarf2_name (die, cu);
15587   if (name)
15588     TYPE_NAME (range_type) = name;
15589
15590   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
15591   if (attr)
15592     TYPE_LENGTH (range_type) = DW_UNSND (attr);
15593
15594   set_die_type (die, range_type, cu);
15595
15596   /* set_die_type should be already done.  */
15597   set_descriptive_type (range_type, die, cu);
15598
15599   return range_type;
15600 }
15601
15602 static struct type *
15603 read_unspecified_type (struct die_info *die, struct dwarf2_cu *cu)
15604 {
15605   struct type *type;
15606
15607   /* For now, we only support the C meaning of an unspecified type: void.  */
15608
15609   type = init_type (cu->objfile, TYPE_CODE_VOID, 0, NULL);
15610   TYPE_NAME (type) = dwarf2_name (die, cu);
15611
15612   return set_die_type (die, type, cu);
15613 }
15614
15615 /* Read a single die and all its descendents.  Set the die's sibling
15616    field to NULL; set other fields in the die correctly, and set all
15617    of the descendents' fields correctly.  Set *NEW_INFO_PTR to the
15618    location of the info_ptr after reading all of those dies.  PARENT
15619    is the parent of the die in question.  */
15620
15621 static struct die_info *
15622 read_die_and_children (const struct die_reader_specs *reader,
15623                        const gdb_byte *info_ptr,
15624                        const gdb_byte **new_info_ptr,
15625                        struct die_info *parent)
15626 {
15627   struct die_info *die;
15628   const gdb_byte *cur_ptr;
15629   int has_children;
15630
15631   cur_ptr = read_full_die_1 (reader, &die, info_ptr, &has_children, 0);
15632   if (die == NULL)
15633     {
15634       *new_info_ptr = cur_ptr;
15635       return NULL;
15636     }
15637   store_in_ref_table (die, reader->cu);
15638
15639   if (has_children)
15640     die->child = read_die_and_siblings_1 (reader, cur_ptr, new_info_ptr, die);
15641   else
15642     {
15643       die->child = NULL;
15644       *new_info_ptr = cur_ptr;
15645     }
15646
15647   die->sibling = NULL;
15648   die->parent = parent;
15649   return die;
15650 }
15651
15652 /* Read a die, all of its descendents, and all of its siblings; set
15653    all of the fields of all of the dies correctly.  Arguments are as
15654    in read_die_and_children.  */
15655
15656 static struct die_info *
15657 read_die_and_siblings_1 (const struct die_reader_specs *reader,
15658                          const gdb_byte *info_ptr,
15659                          const gdb_byte **new_info_ptr,
15660                          struct die_info *parent)
15661 {
15662   struct die_info *first_die, *last_sibling;
15663   const gdb_byte *cur_ptr;
15664
15665   cur_ptr = info_ptr;
15666   first_die = last_sibling = NULL;
15667
15668   while (1)
15669     {
15670       struct die_info *die
15671         = read_die_and_children (reader, cur_ptr, &cur_ptr, parent);
15672
15673       if (die == NULL)
15674         {
15675           *new_info_ptr = cur_ptr;
15676           return first_die;
15677         }
15678
15679       if (!first_die)
15680         first_die = die;
15681       else
15682         last_sibling->sibling = die;
15683
15684       last_sibling = die;
15685     }
15686 }
15687
15688 /* Read a die, all of its descendents, and all of its siblings; set
15689    all of the fields of all of the dies correctly.  Arguments are as
15690    in read_die_and_children.
15691    This the main entry point for reading a DIE and all its children.  */
15692
15693 static struct die_info *
15694 read_die_and_siblings (const struct die_reader_specs *reader,
15695                        const gdb_byte *info_ptr,
15696                        const gdb_byte **new_info_ptr,
15697                        struct die_info *parent)
15698 {
15699   struct die_info *die = read_die_and_siblings_1 (reader, info_ptr,
15700                                                   new_info_ptr, parent);
15701
15702   if (dwarf_die_debug)
15703     {
15704       fprintf_unfiltered (gdb_stdlog,
15705                           "Read die from %s@0x%x of %s:\n",
15706                           get_section_name (reader->die_section),
15707                           (unsigned) (info_ptr - reader->die_section->buffer),
15708                           bfd_get_filename (reader->abfd));
15709       dump_die (die, dwarf_die_debug);
15710     }
15711
15712   return die;
15713 }
15714
15715 /* Read a die and all its attributes, leave space for NUM_EXTRA_ATTRS
15716    attributes.
15717    The caller is responsible for filling in the extra attributes
15718    and updating (*DIEP)->num_attrs.
15719    Set DIEP to point to a newly allocated die with its information,
15720    except for its child, sibling, and parent fields.
15721    Set HAS_CHILDREN to tell whether the die has children or not.  */
15722
15723 static const gdb_byte *
15724 read_full_die_1 (const struct die_reader_specs *reader,
15725                  struct die_info **diep, const gdb_byte *info_ptr,
15726                  int *has_children, int num_extra_attrs)
15727 {
15728   unsigned int abbrev_number, bytes_read, i;
15729   struct abbrev_info *abbrev;
15730   struct die_info *die;
15731   struct dwarf2_cu *cu = reader->cu;
15732   bfd *abfd = reader->abfd;
15733
15734   sect_offset sect_off = (sect_offset) (info_ptr - reader->buffer);
15735   abbrev_number = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
15736   info_ptr += bytes_read;
15737   if (!abbrev_number)
15738     {
15739       *diep = NULL;
15740       *has_children = 0;
15741       return info_ptr;
15742     }
15743
15744   abbrev = abbrev_table_lookup_abbrev (cu->abbrev_table, abbrev_number);
15745   if (!abbrev)
15746     error (_("Dwarf Error: could not find abbrev number %d [in module %s]"),
15747            abbrev_number,
15748            bfd_get_filename (abfd));
15749
15750   die = dwarf_alloc_die (cu, abbrev->num_attrs + num_extra_attrs);
15751   die->sect_off = sect_off;
15752   die->tag = abbrev->tag;
15753   die->abbrev = abbrev_number;
15754
15755   /* Make the result usable.
15756      The caller needs to update num_attrs after adding the extra
15757      attributes.  */
15758   die->num_attrs = abbrev->num_attrs;
15759
15760   for (i = 0; i < abbrev->num_attrs; ++i)
15761     info_ptr = read_attribute (reader, &die->attrs[i], &abbrev->attrs[i],
15762                                info_ptr);
15763
15764   *diep = die;
15765   *has_children = abbrev->has_children;
15766   return info_ptr;
15767 }
15768
15769 /* Read a die and all its attributes.
15770    Set DIEP to point to a newly allocated die with its information,
15771    except for its child, sibling, and parent fields.
15772    Set HAS_CHILDREN to tell whether the die has children or not.  */
15773
15774 static const gdb_byte *
15775 read_full_die (const struct die_reader_specs *reader,
15776                struct die_info **diep, const gdb_byte *info_ptr,
15777                int *has_children)
15778 {
15779   const gdb_byte *result;
15780
15781   result = read_full_die_1 (reader, diep, info_ptr, has_children, 0);
15782
15783   if (dwarf_die_debug)
15784     {
15785       fprintf_unfiltered (gdb_stdlog,
15786                           "Read die from %s@0x%x of %s:\n",
15787                           get_section_name (reader->die_section),
15788                           (unsigned) (info_ptr - reader->die_section->buffer),
15789                           bfd_get_filename (reader->abfd));
15790       dump_die (*diep, dwarf_die_debug);
15791     }
15792
15793   return result;
15794 }
15795 \f
15796 /* Abbreviation tables.
15797
15798    In DWARF version 2, the description of the debugging information is
15799    stored in a separate .debug_abbrev section.  Before we read any
15800    dies from a section we read in all abbreviations and install them
15801    in a hash table.  */
15802
15803 /* Allocate space for a struct abbrev_info object in ABBREV_TABLE.  */
15804
15805 static struct abbrev_info *
15806 abbrev_table_alloc_abbrev (struct abbrev_table *abbrev_table)
15807 {
15808   struct abbrev_info *abbrev;
15809
15810   abbrev = XOBNEW (&abbrev_table->abbrev_obstack, struct abbrev_info);
15811   memset (abbrev, 0, sizeof (struct abbrev_info));
15812
15813   return abbrev;
15814 }
15815
15816 /* Add an abbreviation to the table.  */
15817
15818 static void
15819 abbrev_table_add_abbrev (struct abbrev_table *abbrev_table,
15820                          unsigned int abbrev_number,
15821                          struct abbrev_info *abbrev)
15822 {
15823   unsigned int hash_number;
15824
15825   hash_number = abbrev_number % ABBREV_HASH_SIZE;
15826   abbrev->next = abbrev_table->abbrevs[hash_number];
15827   abbrev_table->abbrevs[hash_number] = abbrev;
15828 }
15829
15830 /* Look up an abbrev in the table.
15831    Returns NULL if the abbrev is not found.  */
15832
15833 static struct abbrev_info *
15834 abbrev_table_lookup_abbrev (const struct abbrev_table *abbrev_table,
15835                             unsigned int abbrev_number)
15836 {
15837   unsigned int hash_number;
15838   struct abbrev_info *abbrev;
15839
15840   hash_number = abbrev_number % ABBREV_HASH_SIZE;
15841   abbrev = abbrev_table->abbrevs[hash_number];
15842
15843   while (abbrev)
15844     {
15845       if (abbrev->number == abbrev_number)
15846         return abbrev;
15847       abbrev = abbrev->next;
15848     }
15849   return NULL;
15850 }
15851
15852 /* Read in an abbrev table.  */
15853
15854 static struct abbrev_table *
15855 abbrev_table_read_table (struct dwarf2_section_info *section,
15856                          sect_offset sect_off)
15857 {
15858   struct objfile *objfile = dwarf2_per_objfile->objfile;
15859   bfd *abfd = get_section_bfd_owner (section);
15860   struct abbrev_table *abbrev_table;
15861   const gdb_byte *abbrev_ptr;
15862   struct abbrev_info *cur_abbrev;
15863   unsigned int abbrev_number, bytes_read, abbrev_name;
15864   unsigned int abbrev_form;
15865   struct attr_abbrev *cur_attrs;
15866   unsigned int allocated_attrs;
15867
15868   abbrev_table = XNEW (struct abbrev_table);
15869   abbrev_table->sect_off = sect_off;
15870   obstack_init (&abbrev_table->abbrev_obstack);
15871   abbrev_table->abbrevs =
15872     XOBNEWVEC (&abbrev_table->abbrev_obstack, struct abbrev_info *,
15873                ABBREV_HASH_SIZE);
15874   memset (abbrev_table->abbrevs, 0,
15875           ABBREV_HASH_SIZE * sizeof (struct abbrev_info *));
15876
15877   dwarf2_read_section (objfile, section);
15878   abbrev_ptr = section->buffer + to_underlying (sect_off);
15879   abbrev_number = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
15880   abbrev_ptr += bytes_read;
15881
15882   allocated_attrs = ATTR_ALLOC_CHUNK;
15883   cur_attrs = XNEWVEC (struct attr_abbrev, allocated_attrs);
15884
15885   /* Loop until we reach an abbrev number of 0.  */
15886   while (abbrev_number)
15887     {
15888       cur_abbrev = abbrev_table_alloc_abbrev (abbrev_table);
15889
15890       /* read in abbrev header */
15891       cur_abbrev->number = abbrev_number;
15892       cur_abbrev->tag
15893         = (enum dwarf_tag) read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
15894       abbrev_ptr += bytes_read;
15895       cur_abbrev->has_children = read_1_byte (abfd, abbrev_ptr);
15896       abbrev_ptr += 1;
15897
15898       /* now read in declarations */
15899       for (;;)
15900         {
15901           LONGEST implicit_const;
15902
15903           abbrev_name = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
15904           abbrev_ptr += bytes_read;
15905           abbrev_form = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
15906           abbrev_ptr += bytes_read;
15907           if (abbrev_form == DW_FORM_implicit_const)
15908             {
15909               implicit_const = read_signed_leb128 (abfd, abbrev_ptr,
15910                                                    &bytes_read);
15911               abbrev_ptr += bytes_read;
15912             }
15913           else
15914             {
15915               /* Initialize it due to a false compiler warning.  */
15916               implicit_const = -1;
15917             }
15918
15919           if (abbrev_name == 0)
15920             break;
15921
15922           if (cur_abbrev->num_attrs == allocated_attrs)
15923             {
15924               allocated_attrs += ATTR_ALLOC_CHUNK;
15925               cur_attrs
15926                 = XRESIZEVEC (struct attr_abbrev, cur_attrs, allocated_attrs);
15927             }
15928
15929           cur_attrs[cur_abbrev->num_attrs].name
15930             = (enum dwarf_attribute) abbrev_name;
15931           cur_attrs[cur_abbrev->num_attrs].form
15932             = (enum dwarf_form) abbrev_form;
15933           cur_attrs[cur_abbrev->num_attrs].implicit_const = implicit_const;
15934           ++cur_abbrev->num_attrs;
15935         }
15936
15937       cur_abbrev->attrs =
15938         XOBNEWVEC (&abbrev_table->abbrev_obstack, struct attr_abbrev,
15939                    cur_abbrev->num_attrs);
15940       memcpy (cur_abbrev->attrs, cur_attrs,
15941               cur_abbrev->num_attrs * sizeof (struct attr_abbrev));
15942
15943       abbrev_table_add_abbrev (abbrev_table, abbrev_number, cur_abbrev);
15944
15945       /* Get next abbreviation.
15946          Under Irix6 the abbreviations for a compilation unit are not
15947          always properly terminated with an abbrev number of 0.
15948          Exit loop if we encounter an abbreviation which we have
15949          already read (which means we are about to read the abbreviations
15950          for the next compile unit) or if the end of the abbreviation
15951          table is reached.  */
15952       if ((unsigned int) (abbrev_ptr - section->buffer) >= section->size)
15953         break;
15954       abbrev_number = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
15955       abbrev_ptr += bytes_read;
15956       if (abbrev_table_lookup_abbrev (abbrev_table, abbrev_number) != NULL)
15957         break;
15958     }
15959
15960   xfree (cur_attrs);
15961   return abbrev_table;
15962 }
15963
15964 /* Free the resources held by ABBREV_TABLE.  */
15965
15966 static void
15967 abbrev_table_free (struct abbrev_table *abbrev_table)
15968 {
15969   obstack_free (&abbrev_table->abbrev_obstack, NULL);
15970   xfree (abbrev_table);
15971 }
15972
15973 /* Same as abbrev_table_free but as a cleanup.
15974    We pass in a pointer to the pointer to the table so that we can
15975    set the pointer to NULL when we're done.  It also simplifies
15976    build_type_psymtabs_1.  */
15977
15978 static void
15979 abbrev_table_free_cleanup (void *table_ptr)
15980 {
15981   struct abbrev_table **abbrev_table_ptr = (struct abbrev_table **) table_ptr;
15982
15983   if (*abbrev_table_ptr != NULL)
15984     abbrev_table_free (*abbrev_table_ptr);
15985   *abbrev_table_ptr = NULL;
15986 }
15987
15988 /* Read the abbrev table for CU from ABBREV_SECTION.  */
15989
15990 static void
15991 dwarf2_read_abbrevs (struct dwarf2_cu *cu,
15992                      struct dwarf2_section_info *abbrev_section)
15993 {
15994   cu->abbrev_table =
15995     abbrev_table_read_table (abbrev_section, cu->header.abbrev_sect_off);
15996 }
15997
15998 /* Release the memory used by the abbrev table for a compilation unit.  */
15999
16000 static void
16001 dwarf2_free_abbrev_table (void *ptr_to_cu)
16002 {
16003   struct dwarf2_cu *cu = (struct dwarf2_cu *) ptr_to_cu;
16004
16005   if (cu->abbrev_table != NULL)
16006     abbrev_table_free (cu->abbrev_table);
16007   /* Set this to NULL so that we SEGV if we try to read it later,
16008      and also because free_comp_unit verifies this is NULL.  */
16009   cu->abbrev_table = NULL;
16010 }
16011 \f
16012 /* Returns nonzero if TAG represents a type that we might generate a partial
16013    symbol for.  */
16014
16015 static int
16016 is_type_tag_for_partial (int tag)
16017 {
16018   switch (tag)
16019     {
16020 #if 0
16021     /* Some types that would be reasonable to generate partial symbols for,
16022        that we don't at present.  */
16023     case DW_TAG_array_type:
16024     case DW_TAG_file_type:
16025     case DW_TAG_ptr_to_member_type:
16026     case DW_TAG_set_type:
16027     case DW_TAG_string_type:
16028     case DW_TAG_subroutine_type:
16029 #endif
16030     case DW_TAG_base_type:
16031     case DW_TAG_class_type:
16032     case DW_TAG_interface_type:
16033     case DW_TAG_enumeration_type:
16034     case DW_TAG_structure_type:
16035     case DW_TAG_subrange_type:
16036     case DW_TAG_typedef:
16037     case DW_TAG_union_type:
16038       return 1;
16039     default:
16040       return 0;
16041     }
16042 }
16043
16044 /* Load all DIEs that are interesting for partial symbols into memory.  */
16045
16046 static struct partial_die_info *
16047 load_partial_dies (const struct die_reader_specs *reader,
16048                    const gdb_byte *info_ptr, int building_psymtab)
16049 {
16050   struct dwarf2_cu *cu = reader->cu;
16051   struct objfile *objfile = cu->objfile;
16052   struct partial_die_info *part_die;
16053   struct partial_die_info *parent_die, *last_die, *first_die = NULL;
16054   struct abbrev_info *abbrev;
16055   unsigned int bytes_read;
16056   unsigned int load_all = 0;
16057   int nesting_level = 1;
16058
16059   parent_die = NULL;
16060   last_die = NULL;
16061
16062   gdb_assert (cu->per_cu != NULL);
16063   if (cu->per_cu->load_all_dies)
16064     load_all = 1;
16065
16066   cu->partial_dies
16067     = htab_create_alloc_ex (cu->header.length / 12,
16068                             partial_die_hash,
16069                             partial_die_eq,
16070                             NULL,
16071                             &cu->comp_unit_obstack,
16072                             hashtab_obstack_allocate,
16073                             dummy_obstack_deallocate);
16074
16075   part_die = XOBNEW (&cu->comp_unit_obstack, struct partial_die_info);
16076
16077   while (1)
16078     {
16079       abbrev = peek_die_abbrev (info_ptr, &bytes_read, cu);
16080
16081       /* A NULL abbrev means the end of a series of children.  */
16082       if (abbrev == NULL)
16083         {
16084           if (--nesting_level == 0)
16085             {
16086               /* PART_DIE was probably the last thing allocated on the
16087                  comp_unit_obstack, so we could call obstack_free
16088                  here.  We don't do that because the waste is small,
16089                  and will be cleaned up when we're done with this
16090                  compilation unit.  This way, we're also more robust
16091                  against other users of the comp_unit_obstack.  */
16092               return first_die;
16093             }
16094           info_ptr += bytes_read;
16095           last_die = parent_die;
16096           parent_die = parent_die->die_parent;
16097           continue;
16098         }
16099
16100       /* Check for template arguments.  We never save these; if
16101          they're seen, we just mark the parent, and go on our way.  */
16102       if (parent_die != NULL
16103           && cu->language == language_cplus
16104           && (abbrev->tag == DW_TAG_template_type_param
16105               || abbrev->tag == DW_TAG_template_value_param))
16106         {
16107           parent_die->has_template_arguments = 1;
16108
16109           if (!load_all)
16110             {
16111               /* We don't need a partial DIE for the template argument.  */
16112               info_ptr = skip_one_die (reader, info_ptr + bytes_read, abbrev);
16113               continue;
16114             }
16115         }
16116
16117       /* We only recurse into c++ subprograms looking for template arguments.
16118          Skip their other children.  */
16119       if (!load_all
16120           && cu->language == language_cplus
16121           && parent_die != NULL
16122           && parent_die->tag == DW_TAG_subprogram)
16123         {
16124           info_ptr = skip_one_die (reader, info_ptr + bytes_read, abbrev);
16125           continue;
16126         }
16127
16128       /* Check whether this DIE is interesting enough to save.  Normally
16129          we would not be interested in members here, but there may be
16130          later variables referencing them via DW_AT_specification (for
16131          static members).  */
16132       if (!load_all
16133           && !is_type_tag_for_partial (abbrev->tag)
16134           && abbrev->tag != DW_TAG_constant
16135           && abbrev->tag != DW_TAG_enumerator
16136           && abbrev->tag != DW_TAG_subprogram
16137           && abbrev->tag != DW_TAG_lexical_block
16138           && abbrev->tag != DW_TAG_variable
16139           && abbrev->tag != DW_TAG_namespace
16140           && abbrev->tag != DW_TAG_module
16141           && abbrev->tag != DW_TAG_member
16142           && abbrev->tag != DW_TAG_imported_unit
16143           && abbrev->tag != DW_TAG_imported_declaration)
16144         {
16145           /* Otherwise we skip to the next sibling, if any.  */
16146           info_ptr = skip_one_die (reader, info_ptr + bytes_read, abbrev);
16147           continue;
16148         }
16149
16150       info_ptr = read_partial_die (reader, part_die, abbrev, bytes_read,
16151                                    info_ptr);
16152
16153       /* This two-pass algorithm for processing partial symbols has a
16154          high cost in cache pressure.  Thus, handle some simple cases
16155          here which cover the majority of C partial symbols.  DIEs
16156          which neither have specification tags in them, nor could have
16157          specification tags elsewhere pointing at them, can simply be
16158          processed and discarded.
16159
16160          This segment is also optional; scan_partial_symbols and
16161          add_partial_symbol will handle these DIEs if we chain
16162          them in normally.  When compilers which do not emit large
16163          quantities of duplicate debug information are more common,
16164          this code can probably be removed.  */
16165
16166       /* Any complete simple types at the top level (pretty much all
16167          of them, for a language without namespaces), can be processed
16168          directly.  */
16169       if (parent_die == NULL
16170           && part_die->has_specification == 0
16171           && part_die->is_declaration == 0
16172           && ((part_die->tag == DW_TAG_typedef && !part_die->has_children)
16173               || part_die->tag == DW_TAG_base_type
16174               || part_die->tag == DW_TAG_subrange_type))
16175         {
16176           if (building_psymtab && part_die->name != NULL)
16177             add_psymbol_to_list (part_die->name, strlen (part_die->name), 0,
16178                                  VAR_DOMAIN, LOC_TYPEDEF,
16179                                  &objfile->static_psymbols,
16180                                  0, cu->language, objfile);
16181           info_ptr = locate_pdi_sibling (reader, part_die, info_ptr);
16182           continue;
16183         }
16184
16185       /* The exception for DW_TAG_typedef with has_children above is
16186          a workaround of GCC PR debug/47510.  In the case of this complaint
16187          type_name_no_tag_or_error will error on such types later.
16188
16189          GDB skipped children of DW_TAG_typedef by the shortcut above and then
16190          it could not find the child DIEs referenced later, this is checked
16191          above.  In correct DWARF DW_TAG_typedef should have no children.  */
16192
16193       if (part_die->tag == DW_TAG_typedef && part_die->has_children)
16194         complaint (&symfile_complaints,
16195                    _("DW_TAG_typedef has childen - GCC PR debug/47510 bug "
16196                      "- DIE at 0x%x [in module %s]"),
16197                    to_underlying (part_die->sect_off), objfile_name (objfile));
16198
16199       /* If we're at the second level, and we're an enumerator, and
16200          our parent has no specification (meaning possibly lives in a
16201          namespace elsewhere), then we can add the partial symbol now
16202          instead of queueing it.  */
16203       if (part_die->tag == DW_TAG_enumerator
16204           && parent_die != NULL
16205           && parent_die->die_parent == NULL
16206           && parent_die->tag == DW_TAG_enumeration_type
16207           && parent_die->has_specification == 0)
16208         {
16209           if (part_die->name == NULL)
16210             complaint (&symfile_complaints,
16211                        _("malformed enumerator DIE ignored"));
16212           else if (building_psymtab)
16213             add_psymbol_to_list (part_die->name, strlen (part_die->name), 0,
16214                                  VAR_DOMAIN, LOC_CONST,
16215                                  cu->language == language_cplus
16216                                  ? &objfile->global_psymbols
16217                                  : &objfile->static_psymbols,
16218                                  0, cu->language, objfile);
16219
16220           info_ptr = locate_pdi_sibling (reader, part_die, info_ptr);
16221           continue;
16222         }
16223
16224       /* We'll save this DIE so link it in.  */
16225       part_die->die_parent = parent_die;
16226       part_die->die_sibling = NULL;
16227       part_die->die_child = NULL;
16228
16229       if (last_die && last_die == parent_die)
16230         last_die->die_child = part_die;
16231       else if (last_die)
16232         last_die->die_sibling = part_die;
16233
16234       last_die = part_die;
16235
16236       if (first_die == NULL)
16237         first_die = part_die;
16238
16239       /* Maybe add the DIE to the hash table.  Not all DIEs that we
16240          find interesting need to be in the hash table, because we
16241          also have the parent/sibling/child chains; only those that we
16242          might refer to by offset later during partial symbol reading.
16243
16244          For now this means things that might have be the target of a
16245          DW_AT_specification, DW_AT_abstract_origin, or
16246          DW_AT_extension.  DW_AT_extension will refer only to
16247          namespaces; DW_AT_abstract_origin refers to functions (and
16248          many things under the function DIE, but we do not recurse
16249          into function DIEs during partial symbol reading) and
16250          possibly variables as well; DW_AT_specification refers to
16251          declarations.  Declarations ought to have the DW_AT_declaration
16252          flag.  It happens that GCC forgets to put it in sometimes, but
16253          only for functions, not for types.
16254
16255          Adding more things than necessary to the hash table is harmless
16256          except for the performance cost.  Adding too few will result in
16257          wasted time in find_partial_die, when we reread the compilation
16258          unit with load_all_dies set.  */
16259
16260       if (load_all
16261           || abbrev->tag == DW_TAG_constant
16262           || abbrev->tag == DW_TAG_subprogram
16263           || abbrev->tag == DW_TAG_variable
16264           || abbrev->tag == DW_TAG_namespace
16265           || part_die->is_declaration)
16266         {
16267           void **slot;
16268
16269           slot = htab_find_slot_with_hash (cu->partial_dies, part_die,
16270                                            to_underlying (part_die->sect_off),
16271                                            INSERT);
16272           *slot = part_die;
16273         }
16274
16275       part_die = XOBNEW (&cu->comp_unit_obstack, struct partial_die_info);
16276
16277       /* For some DIEs we want to follow their children (if any).  For C
16278          we have no reason to follow the children of structures; for other
16279          languages we have to, so that we can get at method physnames
16280          to infer fully qualified class names, for DW_AT_specification,
16281          and for C++ template arguments.  For C++, we also look one level
16282          inside functions to find template arguments (if the name of the
16283          function does not already contain the template arguments).
16284
16285          For Ada, we need to scan the children of subprograms and lexical
16286          blocks as well because Ada allows the definition of nested
16287          entities that could be interesting for the debugger, such as
16288          nested subprograms for instance.  */
16289       if (last_die->has_children
16290           && (load_all
16291               || last_die->tag == DW_TAG_namespace
16292               || last_die->tag == DW_TAG_module
16293               || last_die->tag == DW_TAG_enumeration_type
16294               || (cu->language == language_cplus
16295                   && last_die->tag == DW_TAG_subprogram
16296                   && (last_die->name == NULL
16297                       || strchr (last_die->name, '<') == NULL))
16298               || (cu->language != language_c
16299                   && (last_die->tag == DW_TAG_class_type
16300                       || last_die->tag == DW_TAG_interface_type
16301                       || last_die->tag == DW_TAG_structure_type
16302                       || last_die->tag == DW_TAG_union_type))
16303               || (cu->language == language_ada
16304                   && (last_die->tag == DW_TAG_subprogram
16305                       || last_die->tag == DW_TAG_lexical_block))))
16306         {
16307           nesting_level++;
16308           parent_die = last_die;
16309           continue;
16310         }
16311
16312       /* Otherwise we skip to the next sibling, if any.  */
16313       info_ptr = locate_pdi_sibling (reader, last_die, info_ptr);
16314
16315       /* Back to the top, do it again.  */
16316     }
16317 }
16318
16319 /* Read a minimal amount of information into the minimal die structure.  */
16320
16321 static const gdb_byte *
16322 read_partial_die (const struct die_reader_specs *reader,
16323                   struct partial_die_info *part_die,
16324                   struct abbrev_info *abbrev, unsigned int abbrev_len,
16325                   const gdb_byte *info_ptr)
16326 {
16327   struct dwarf2_cu *cu = reader->cu;
16328   struct objfile *objfile = cu->objfile;
16329   const gdb_byte *buffer = reader->buffer;
16330   unsigned int i;
16331   struct attribute attr;
16332   int has_low_pc_attr = 0;
16333   int has_high_pc_attr = 0;
16334   int high_pc_relative = 0;
16335
16336   memset (part_die, 0, sizeof (struct partial_die_info));
16337
16338   part_die->sect_off = (sect_offset) (info_ptr - buffer);
16339
16340   info_ptr += abbrev_len;
16341
16342   if (abbrev == NULL)
16343     return info_ptr;
16344
16345   part_die->tag = abbrev->tag;
16346   part_die->has_children = abbrev->has_children;
16347
16348   for (i = 0; i < abbrev->num_attrs; ++i)
16349     {
16350       info_ptr = read_attribute (reader, &attr, &abbrev->attrs[i], info_ptr);
16351
16352       /* Store the data if it is of an attribute we want to keep in a
16353          partial symbol table.  */
16354       switch (attr.name)
16355         {
16356         case DW_AT_name:
16357           switch (part_die->tag)
16358             {
16359             case DW_TAG_compile_unit:
16360             case DW_TAG_partial_unit:
16361             case DW_TAG_type_unit:
16362               /* Compilation units have a DW_AT_name that is a filename, not
16363                  a source language identifier.  */
16364             case DW_TAG_enumeration_type:
16365             case DW_TAG_enumerator:
16366               /* These tags always have simple identifiers already; no need
16367                  to canonicalize them.  */
16368               part_die->name = DW_STRING (&attr);
16369               break;
16370             default:
16371               part_die->name
16372                 = dwarf2_canonicalize_name (DW_STRING (&attr), cu,
16373                                             &objfile->per_bfd->storage_obstack);
16374               break;
16375             }
16376           break;
16377         case DW_AT_linkage_name:
16378         case DW_AT_MIPS_linkage_name:
16379           /* Note that both forms of linkage name might appear.  We
16380              assume they will be the same, and we only store the last
16381              one we see.  */
16382           if (cu->language == language_ada)
16383             part_die->name = DW_STRING (&attr);
16384           part_die->linkage_name = DW_STRING (&attr);
16385           break;
16386         case DW_AT_low_pc:
16387           has_low_pc_attr = 1;
16388           part_die->lowpc = attr_value_as_address (&attr);
16389           break;
16390         case DW_AT_high_pc:
16391           has_high_pc_attr = 1;
16392           part_die->highpc = attr_value_as_address (&attr);
16393           if (cu->header.version >= 4 && attr_form_is_constant (&attr))
16394                 high_pc_relative = 1;
16395           break;
16396         case DW_AT_location:
16397           /* Support the .debug_loc offsets.  */
16398           if (attr_form_is_block (&attr))
16399             {
16400                part_die->d.locdesc = DW_BLOCK (&attr);
16401             }
16402           else if (attr_form_is_section_offset (&attr))
16403             {
16404               dwarf2_complex_location_expr_complaint ();
16405             }
16406           else
16407             {
16408               dwarf2_invalid_attrib_class_complaint ("DW_AT_location",
16409                                                      "partial symbol information");
16410             }
16411           break;
16412         case DW_AT_external:
16413           part_die->is_external = DW_UNSND (&attr);
16414           break;
16415         case DW_AT_declaration:
16416           part_die->is_declaration = DW_UNSND (&attr);
16417           break;
16418         case DW_AT_type:
16419           part_die->has_type = 1;
16420           break;
16421         case DW_AT_abstract_origin:
16422         case DW_AT_specification:
16423         case DW_AT_extension:
16424           part_die->has_specification = 1;
16425           part_die->spec_offset = dwarf2_get_ref_die_offset (&attr);
16426           part_die->spec_is_dwz = (attr.form == DW_FORM_GNU_ref_alt
16427                                    || cu->per_cu->is_dwz);
16428           break;
16429         case DW_AT_sibling:
16430           /* Ignore absolute siblings, they might point outside of
16431              the current compile unit.  */
16432           if (attr.form == DW_FORM_ref_addr)
16433             complaint (&symfile_complaints,
16434                        _("ignoring absolute DW_AT_sibling"));
16435           else
16436             {
16437               sect_offset off = dwarf2_get_ref_die_offset (&attr);
16438               const gdb_byte *sibling_ptr = buffer + to_underlying (off);
16439
16440               if (sibling_ptr < info_ptr)
16441                 complaint (&symfile_complaints,
16442                            _("DW_AT_sibling points backwards"));
16443               else if (sibling_ptr > reader->buffer_end)
16444                 dwarf2_section_buffer_overflow_complaint (reader->die_section);
16445               else
16446                 part_die->sibling = sibling_ptr;
16447             }
16448           break;
16449         case DW_AT_byte_size:
16450           part_die->has_byte_size = 1;
16451           break;
16452         case DW_AT_const_value:
16453           part_die->has_const_value = 1;
16454           break;
16455         case DW_AT_calling_convention:
16456           /* DWARF doesn't provide a way to identify a program's source-level
16457              entry point.  DW_AT_calling_convention attributes are only meant
16458              to describe functions' calling conventions.
16459
16460              However, because it's a necessary piece of information in
16461              Fortran, and before DWARF 4 DW_CC_program was the only
16462              piece of debugging information whose definition refers to
16463              a 'main program' at all, several compilers marked Fortran
16464              main programs with DW_CC_program --- even when those
16465              functions use the standard calling conventions.
16466
16467              Although DWARF now specifies a way to provide this
16468              information, we support this practice for backward
16469              compatibility.  */
16470           if (DW_UNSND (&attr) == DW_CC_program
16471               && cu->language == language_fortran)
16472             part_die->main_subprogram = 1;
16473           break;
16474         case DW_AT_inline:
16475           if (DW_UNSND (&attr) == DW_INL_inlined
16476               || DW_UNSND (&attr) == DW_INL_declared_inlined)
16477             part_die->may_be_inlined = 1;
16478           break;
16479
16480         case DW_AT_import:
16481           if (part_die->tag == DW_TAG_imported_unit)
16482             {
16483               part_die->d.sect_off = dwarf2_get_ref_die_offset (&attr);
16484               part_die->is_dwz = (attr.form == DW_FORM_GNU_ref_alt
16485                                   || cu->per_cu->is_dwz);
16486             }
16487           break;
16488
16489         case DW_AT_main_subprogram:
16490           part_die->main_subprogram = DW_UNSND (&attr);
16491           break;
16492
16493         default:
16494           break;
16495         }
16496     }
16497
16498   if (high_pc_relative)
16499     part_die->highpc += part_die->lowpc;
16500
16501   if (has_low_pc_attr && has_high_pc_attr)
16502     {
16503       /* When using the GNU linker, .gnu.linkonce. sections are used to
16504          eliminate duplicate copies of functions and vtables and such.
16505          The linker will arbitrarily choose one and discard the others.
16506          The AT_*_pc values for such functions refer to local labels in
16507          these sections.  If the section from that file was discarded, the
16508          labels are not in the output, so the relocs get a value of 0.
16509          If this is a discarded function, mark the pc bounds as invalid,
16510          so that GDB will ignore it.  */
16511       if (part_die->lowpc == 0 && !dwarf2_per_objfile->has_section_at_zero)
16512         {
16513           struct gdbarch *gdbarch = get_objfile_arch (objfile);
16514
16515           complaint (&symfile_complaints,
16516                      _("DW_AT_low_pc %s is zero "
16517                        "for DIE at 0x%x [in module %s]"),
16518                      paddress (gdbarch, part_die->lowpc),
16519                      to_underlying (part_die->sect_off), objfile_name (objfile));
16520         }
16521       /* dwarf2_get_pc_bounds has also the strict low < high requirement.  */
16522       else if (part_die->lowpc >= part_die->highpc)
16523         {
16524           struct gdbarch *gdbarch = get_objfile_arch (objfile);
16525
16526           complaint (&symfile_complaints,
16527                      _("DW_AT_low_pc %s is not < DW_AT_high_pc %s "
16528                        "for DIE at 0x%x [in module %s]"),
16529                      paddress (gdbarch, part_die->lowpc),
16530                      paddress (gdbarch, part_die->highpc),
16531                      to_underlying (part_die->sect_off),
16532                      objfile_name (objfile));
16533         }
16534       else
16535         part_die->has_pc_info = 1;
16536     }
16537
16538   return info_ptr;
16539 }
16540
16541 /* Find a cached partial DIE at OFFSET in CU.  */
16542
16543 static struct partial_die_info *
16544 find_partial_die_in_comp_unit (sect_offset sect_off, struct dwarf2_cu *cu)
16545 {
16546   struct partial_die_info *lookup_die = NULL;
16547   struct partial_die_info part_die;
16548
16549   part_die.sect_off = sect_off;
16550   lookup_die = ((struct partial_die_info *)
16551                 htab_find_with_hash (cu->partial_dies, &part_die,
16552                                      to_underlying (sect_off)));
16553
16554   return lookup_die;
16555 }
16556
16557 /* Find a partial DIE at OFFSET, which may or may not be in CU,
16558    except in the case of .debug_types DIEs which do not reference
16559    outside their CU (they do however referencing other types via
16560    DW_FORM_ref_sig8).  */
16561
16562 static struct partial_die_info *
16563 find_partial_die (sect_offset sect_off, int offset_in_dwz, struct dwarf2_cu *cu)
16564 {
16565   struct objfile *objfile = cu->objfile;
16566   struct dwarf2_per_cu_data *per_cu = NULL;
16567   struct partial_die_info *pd = NULL;
16568
16569   if (offset_in_dwz == cu->per_cu->is_dwz
16570       && offset_in_cu_p (&cu->header, sect_off))
16571     {
16572       pd = find_partial_die_in_comp_unit (sect_off, cu);
16573       if (pd != NULL)
16574         return pd;
16575       /* We missed recording what we needed.
16576          Load all dies and try again.  */
16577       per_cu = cu->per_cu;
16578     }
16579   else
16580     {
16581       /* TUs don't reference other CUs/TUs (except via type signatures).  */
16582       if (cu->per_cu->is_debug_types)
16583         {
16584           error (_("Dwarf Error: Type Unit at offset 0x%x contains"
16585                    " external reference to offset 0x%x [in module %s].\n"),
16586                  to_underlying (cu->header.sect_off), to_underlying (sect_off),
16587                  bfd_get_filename (objfile->obfd));
16588         }
16589       per_cu = dwarf2_find_containing_comp_unit (sect_off, offset_in_dwz,
16590                                                  objfile);
16591
16592       if (per_cu->cu == NULL || per_cu->cu->partial_dies == NULL)
16593         load_partial_comp_unit (per_cu);
16594
16595       per_cu->cu->last_used = 0;
16596       pd = find_partial_die_in_comp_unit (sect_off, per_cu->cu);
16597     }
16598
16599   /* If we didn't find it, and not all dies have been loaded,
16600      load them all and try again.  */
16601
16602   if (pd == NULL && per_cu->load_all_dies == 0)
16603     {
16604       per_cu->load_all_dies = 1;
16605
16606       /* This is nasty.  When we reread the DIEs, somewhere up the call chain
16607          THIS_CU->cu may already be in use.  So we can't just free it and
16608          replace its DIEs with the ones we read in.  Instead, we leave those
16609          DIEs alone (which can still be in use, e.g. in scan_partial_symbols),
16610          and clobber THIS_CU->cu->partial_dies with the hash table for the new
16611          set.  */
16612       load_partial_comp_unit (per_cu);
16613
16614       pd = find_partial_die_in_comp_unit (sect_off, per_cu->cu);
16615     }
16616
16617   if (pd == NULL)
16618     internal_error (__FILE__, __LINE__,
16619                     _("could not find partial DIE 0x%x "
16620                       "in cache [from module %s]\n"),
16621                     to_underlying (sect_off), bfd_get_filename (objfile->obfd));
16622   return pd;
16623 }
16624
16625 /* See if we can figure out if the class lives in a namespace.  We do
16626    this by looking for a member function; its demangled name will
16627    contain namespace info, if there is any.  */
16628
16629 static void
16630 guess_partial_die_structure_name (struct partial_die_info *struct_pdi,
16631                                   struct dwarf2_cu *cu)
16632 {
16633   /* NOTE: carlton/2003-10-07: Getting the info this way changes
16634      what template types look like, because the demangler
16635      frequently doesn't give the same name as the debug info.  We
16636      could fix this by only using the demangled name to get the
16637      prefix (but see comment in read_structure_type).  */
16638
16639   struct partial_die_info *real_pdi;
16640   struct partial_die_info *child_pdi;
16641
16642   /* If this DIE (this DIE's specification, if any) has a parent, then
16643      we should not do this.  We'll prepend the parent's fully qualified
16644      name when we create the partial symbol.  */
16645
16646   real_pdi = struct_pdi;
16647   while (real_pdi->has_specification)
16648     real_pdi = find_partial_die (real_pdi->spec_offset,
16649                                  real_pdi->spec_is_dwz, cu);
16650
16651   if (real_pdi->die_parent != NULL)
16652     return;
16653
16654   for (child_pdi = struct_pdi->die_child;
16655        child_pdi != NULL;
16656        child_pdi = child_pdi->die_sibling)
16657     {
16658       if (child_pdi->tag == DW_TAG_subprogram
16659           && child_pdi->linkage_name != NULL)
16660         {
16661           char *actual_class_name
16662             = language_class_name_from_physname (cu->language_defn,
16663                                                  child_pdi->linkage_name);
16664           if (actual_class_name != NULL)
16665             {
16666               struct_pdi->name
16667                 = ((const char *)
16668                    obstack_copy0 (&cu->objfile->per_bfd->storage_obstack,
16669                                   actual_class_name,
16670                                   strlen (actual_class_name)));
16671               xfree (actual_class_name);
16672             }
16673           break;
16674         }
16675     }
16676 }
16677
16678 /* Adjust PART_DIE before generating a symbol for it.  This function
16679    may set the is_external flag or change the DIE's name.  */
16680
16681 static void
16682 fixup_partial_die (struct partial_die_info *part_die,
16683                    struct dwarf2_cu *cu)
16684 {
16685   /* Once we've fixed up a die, there's no point in doing so again.
16686      This also avoids a memory leak if we were to call
16687      guess_partial_die_structure_name multiple times.  */
16688   if (part_die->fixup_called)
16689     return;
16690
16691   /* If we found a reference attribute and the DIE has no name, try
16692      to find a name in the referred to DIE.  */
16693
16694   if (part_die->name == NULL && part_die->has_specification)
16695     {
16696       struct partial_die_info *spec_die;
16697
16698       spec_die = find_partial_die (part_die->spec_offset,
16699                                    part_die->spec_is_dwz, cu);
16700
16701       fixup_partial_die (spec_die, cu);
16702
16703       if (spec_die->name)
16704         {
16705           part_die->name = spec_die->name;
16706
16707           /* Copy DW_AT_external attribute if it is set.  */
16708           if (spec_die->is_external)
16709             part_die->is_external = spec_die->is_external;
16710         }
16711     }
16712
16713   /* Set default names for some unnamed DIEs.  */
16714
16715   if (part_die->name == NULL && part_die->tag == DW_TAG_namespace)
16716     part_die->name = CP_ANONYMOUS_NAMESPACE_STR;
16717
16718   /* If there is no parent die to provide a namespace, and there are
16719      children, see if we can determine the namespace from their linkage
16720      name.  */
16721   if (cu->language == language_cplus
16722       && !VEC_empty (dwarf2_section_info_def, dwarf2_per_objfile->types)
16723       && part_die->die_parent == NULL
16724       && part_die->has_children
16725       && (part_die->tag == DW_TAG_class_type
16726           || part_die->tag == DW_TAG_structure_type
16727           || part_die->tag == DW_TAG_union_type))
16728     guess_partial_die_structure_name (part_die, cu);
16729
16730   /* GCC might emit a nameless struct or union that has a linkage
16731      name.  See http://gcc.gnu.org/bugzilla/show_bug.cgi?id=47510.  */
16732   if (part_die->name == NULL
16733       && (part_die->tag == DW_TAG_class_type
16734           || part_die->tag == DW_TAG_interface_type
16735           || part_die->tag == DW_TAG_structure_type
16736           || part_die->tag == DW_TAG_union_type)
16737       && part_die->linkage_name != NULL)
16738     {
16739       char *demangled;
16740
16741       demangled = gdb_demangle (part_die->linkage_name, DMGL_TYPES);
16742       if (demangled)
16743         {
16744           const char *base;
16745
16746           /* Strip any leading namespaces/classes, keep only the base name.
16747              DW_AT_name for named DIEs does not contain the prefixes.  */
16748           base = strrchr (demangled, ':');
16749           if (base && base > demangled && base[-1] == ':')
16750             base++;
16751           else
16752             base = demangled;
16753
16754           part_die->name
16755             = ((const char *)
16756                obstack_copy0 (&cu->objfile->per_bfd->storage_obstack,
16757                               base, strlen (base)));
16758           xfree (demangled);
16759         }
16760     }
16761
16762   part_die->fixup_called = 1;
16763 }
16764
16765 /* Read an attribute value described by an attribute form.  */
16766
16767 static const gdb_byte *
16768 read_attribute_value (const struct die_reader_specs *reader,
16769                       struct attribute *attr, unsigned form,
16770                       LONGEST implicit_const, const gdb_byte *info_ptr)
16771 {
16772   struct dwarf2_cu *cu = reader->cu;
16773   struct objfile *objfile = cu->objfile;
16774   struct gdbarch *gdbarch = get_objfile_arch (objfile);
16775   bfd *abfd = reader->abfd;
16776   struct comp_unit_head *cu_header = &cu->header;
16777   unsigned int bytes_read;
16778   struct dwarf_block *blk;
16779
16780   attr->form = (enum dwarf_form) form;
16781   switch (form)
16782     {
16783     case DW_FORM_ref_addr:
16784       if (cu->header.version == 2)
16785         DW_UNSND (attr) = read_address (abfd, info_ptr, cu, &bytes_read);
16786       else
16787         DW_UNSND (attr) = read_offset (abfd, info_ptr,
16788                                        &cu->header, &bytes_read);
16789       info_ptr += bytes_read;
16790       break;
16791     case DW_FORM_GNU_ref_alt:
16792       DW_UNSND (attr) = read_offset (abfd, info_ptr, &cu->header, &bytes_read);
16793       info_ptr += bytes_read;
16794       break;
16795     case DW_FORM_addr:
16796       DW_ADDR (attr) = read_address (abfd, info_ptr, cu, &bytes_read);
16797       DW_ADDR (attr) = gdbarch_adjust_dwarf2_addr (gdbarch, DW_ADDR (attr));
16798       info_ptr += bytes_read;
16799       break;
16800     case DW_FORM_block2:
16801       blk = dwarf_alloc_block (cu);
16802       blk->size = read_2_bytes (abfd, info_ptr);
16803       info_ptr += 2;
16804       blk->data = read_n_bytes (abfd, info_ptr, blk->size);
16805       info_ptr += blk->size;
16806       DW_BLOCK (attr) = blk;
16807       break;
16808     case DW_FORM_block4:
16809       blk = dwarf_alloc_block (cu);
16810       blk->size = read_4_bytes (abfd, info_ptr);
16811       info_ptr += 4;
16812       blk->data = read_n_bytes (abfd, info_ptr, blk->size);
16813       info_ptr += blk->size;
16814       DW_BLOCK (attr) = blk;
16815       break;
16816     case DW_FORM_data2:
16817       DW_UNSND (attr) = read_2_bytes (abfd, info_ptr);
16818       info_ptr += 2;
16819       break;
16820     case DW_FORM_data4:
16821       DW_UNSND (attr) = read_4_bytes (abfd, info_ptr);
16822       info_ptr += 4;
16823       break;
16824     case DW_FORM_data8:
16825       DW_UNSND (attr) = read_8_bytes (abfd, info_ptr);
16826       info_ptr += 8;
16827       break;
16828     case DW_FORM_data16:
16829       blk = dwarf_alloc_block (cu);
16830       blk->size = 16;
16831       blk->data = read_n_bytes (abfd, info_ptr, 16);
16832       info_ptr += 16;
16833       DW_BLOCK (attr) = blk;
16834       break;
16835     case DW_FORM_sec_offset:
16836       DW_UNSND (attr) = read_offset (abfd, info_ptr, &cu->header, &bytes_read);
16837       info_ptr += bytes_read;
16838       break;
16839     case DW_FORM_string:
16840       DW_STRING (attr) = read_direct_string (abfd, info_ptr, &bytes_read);
16841       DW_STRING_IS_CANONICAL (attr) = 0;
16842       info_ptr += bytes_read;
16843       break;
16844     case DW_FORM_strp:
16845       if (!cu->per_cu->is_dwz)
16846         {
16847           DW_STRING (attr) = read_indirect_string (abfd, info_ptr, cu_header,
16848                                                    &bytes_read);
16849           DW_STRING_IS_CANONICAL (attr) = 0;
16850           info_ptr += bytes_read;
16851           break;
16852         }
16853       /* FALLTHROUGH */
16854     case DW_FORM_line_strp:
16855       if (!cu->per_cu->is_dwz)
16856         {
16857           DW_STRING (attr) = read_indirect_line_string (abfd, info_ptr,
16858                                                         cu_header, &bytes_read);
16859           DW_STRING_IS_CANONICAL (attr) = 0;
16860           info_ptr += bytes_read;
16861           break;
16862         }
16863       /* FALLTHROUGH */
16864     case DW_FORM_GNU_strp_alt:
16865       {
16866         struct dwz_file *dwz = dwarf2_get_dwz_file ();
16867         LONGEST str_offset = read_offset (abfd, info_ptr, cu_header,
16868                                           &bytes_read);
16869
16870         DW_STRING (attr) = read_indirect_string_from_dwz (dwz, str_offset);
16871         DW_STRING_IS_CANONICAL (attr) = 0;
16872         info_ptr += bytes_read;
16873       }
16874       break;
16875     case DW_FORM_exprloc:
16876     case DW_FORM_block:
16877       blk = dwarf_alloc_block (cu);
16878       blk->size = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
16879       info_ptr += bytes_read;
16880       blk->data = read_n_bytes (abfd, info_ptr, blk->size);
16881       info_ptr += blk->size;
16882       DW_BLOCK (attr) = blk;
16883       break;
16884     case DW_FORM_block1:
16885       blk = dwarf_alloc_block (cu);
16886       blk->size = read_1_byte (abfd, info_ptr);
16887       info_ptr += 1;
16888       blk->data = read_n_bytes (abfd, info_ptr, blk->size);
16889       info_ptr += blk->size;
16890       DW_BLOCK (attr) = blk;
16891       break;
16892     case DW_FORM_data1:
16893       DW_UNSND (attr) = read_1_byte (abfd, info_ptr);
16894       info_ptr += 1;
16895       break;
16896     case DW_FORM_flag:
16897       DW_UNSND (attr) = read_1_byte (abfd, info_ptr);
16898       info_ptr += 1;
16899       break;
16900     case DW_FORM_flag_present:
16901       DW_UNSND (attr) = 1;
16902       break;
16903     case DW_FORM_sdata:
16904       DW_SND (attr) = read_signed_leb128 (abfd, info_ptr, &bytes_read);
16905       info_ptr += bytes_read;
16906       break;
16907     case DW_FORM_udata:
16908       DW_UNSND (attr) = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
16909       info_ptr += bytes_read;
16910       break;
16911     case DW_FORM_ref1:
16912       DW_UNSND (attr) = (to_underlying (cu->header.sect_off)
16913                          + read_1_byte (abfd, info_ptr));
16914       info_ptr += 1;
16915       break;
16916     case DW_FORM_ref2:
16917       DW_UNSND (attr) = (to_underlying (cu->header.sect_off)
16918                          + read_2_bytes (abfd, info_ptr));
16919       info_ptr += 2;
16920       break;
16921     case DW_FORM_ref4:
16922       DW_UNSND (attr) = (to_underlying (cu->header.sect_off)
16923                          + read_4_bytes (abfd, info_ptr));
16924       info_ptr += 4;
16925       break;
16926     case DW_FORM_ref8:
16927       DW_UNSND (attr) = (to_underlying (cu->header.sect_off)
16928                          + read_8_bytes (abfd, info_ptr));
16929       info_ptr += 8;
16930       break;
16931     case DW_FORM_ref_sig8:
16932       DW_SIGNATURE (attr) = read_8_bytes (abfd, info_ptr);
16933       info_ptr += 8;
16934       break;
16935     case DW_FORM_ref_udata:
16936       DW_UNSND (attr) = (to_underlying (cu->header.sect_off)
16937                          + read_unsigned_leb128 (abfd, info_ptr, &bytes_read));
16938       info_ptr += bytes_read;
16939       break;
16940     case DW_FORM_indirect:
16941       form = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
16942       info_ptr += bytes_read;
16943       if (form == DW_FORM_implicit_const)
16944         {
16945           implicit_const = read_signed_leb128 (abfd, info_ptr, &bytes_read);
16946           info_ptr += bytes_read;
16947         }
16948       info_ptr = read_attribute_value (reader, attr, form, implicit_const,
16949                                        info_ptr);
16950       break;
16951     case DW_FORM_implicit_const:
16952       DW_SND (attr) = implicit_const;
16953       break;
16954     case DW_FORM_GNU_addr_index:
16955       if (reader->dwo_file == NULL)
16956         {
16957           /* For now flag a hard error.
16958              Later we can turn this into a complaint.  */
16959           error (_("Dwarf Error: %s found in non-DWO CU [in module %s]"),
16960                  dwarf_form_name (form),
16961                  bfd_get_filename (abfd));
16962         }
16963       DW_ADDR (attr) = read_addr_index_from_leb128 (cu, info_ptr, &bytes_read);
16964       info_ptr += bytes_read;
16965       break;
16966     case DW_FORM_GNU_str_index:
16967       if (reader->dwo_file == NULL)
16968         {
16969           /* For now flag a hard error.
16970              Later we can turn this into a complaint if warranted.  */
16971           error (_("Dwarf Error: %s found in non-DWO CU [in module %s]"),
16972                  dwarf_form_name (form),
16973                  bfd_get_filename (abfd));
16974         }
16975       {
16976         ULONGEST str_index =
16977           read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
16978
16979         DW_STRING (attr) = read_str_index (reader, str_index);
16980         DW_STRING_IS_CANONICAL (attr) = 0;
16981         info_ptr += bytes_read;
16982       }
16983       break;
16984     default:
16985       error (_("Dwarf Error: Cannot handle %s in DWARF reader [in module %s]"),
16986              dwarf_form_name (form),
16987              bfd_get_filename (abfd));
16988     }
16989
16990   /* Super hack.  */
16991   if (cu->per_cu->is_dwz && attr_form_is_ref (attr))
16992     attr->form = DW_FORM_GNU_ref_alt;
16993
16994   /* We have seen instances where the compiler tried to emit a byte
16995      size attribute of -1 which ended up being encoded as an unsigned
16996      0xffffffff.  Although 0xffffffff is technically a valid size value,
16997      an object of this size seems pretty unlikely so we can relatively
16998      safely treat these cases as if the size attribute was invalid and
16999      treat them as zero by default.  */
17000   if (attr->name == DW_AT_byte_size
17001       && form == DW_FORM_data4
17002       && DW_UNSND (attr) >= 0xffffffff)
17003     {
17004       complaint
17005         (&symfile_complaints,
17006          _("Suspicious DW_AT_byte_size value treated as zero instead of %s"),
17007          hex_string (DW_UNSND (attr)));
17008       DW_UNSND (attr) = 0;
17009     }
17010
17011   return info_ptr;
17012 }
17013
17014 /* Read an attribute described by an abbreviated attribute.  */
17015
17016 static const gdb_byte *
17017 read_attribute (const struct die_reader_specs *reader,
17018                 struct attribute *attr, struct attr_abbrev *abbrev,
17019                 const gdb_byte *info_ptr)
17020 {
17021   attr->name = abbrev->name;
17022   return read_attribute_value (reader, attr, abbrev->form,
17023                                abbrev->implicit_const, info_ptr);
17024 }
17025
17026 /* Read dwarf information from a buffer.  */
17027
17028 static unsigned int
17029 read_1_byte (bfd *abfd, const gdb_byte *buf)
17030 {
17031   return bfd_get_8 (abfd, buf);
17032 }
17033
17034 static int
17035 read_1_signed_byte (bfd *abfd, const gdb_byte *buf)
17036 {
17037   return bfd_get_signed_8 (abfd, buf);
17038 }
17039
17040 static unsigned int
17041 read_2_bytes (bfd *abfd, const gdb_byte *buf)
17042 {
17043   return bfd_get_16 (abfd, buf);
17044 }
17045
17046 static int
17047 read_2_signed_bytes (bfd *abfd, const gdb_byte *buf)
17048 {
17049   return bfd_get_signed_16 (abfd, buf);
17050 }
17051
17052 static unsigned int
17053 read_4_bytes (bfd *abfd, const gdb_byte *buf)
17054 {
17055   return bfd_get_32 (abfd, buf);
17056 }
17057
17058 static int
17059 read_4_signed_bytes (bfd *abfd, const gdb_byte *buf)
17060 {
17061   return bfd_get_signed_32 (abfd, buf);
17062 }
17063
17064 static ULONGEST
17065 read_8_bytes (bfd *abfd, const gdb_byte *buf)
17066 {
17067   return bfd_get_64 (abfd, buf);
17068 }
17069
17070 static CORE_ADDR
17071 read_address (bfd *abfd, const gdb_byte *buf, struct dwarf2_cu *cu,
17072               unsigned int *bytes_read)
17073 {
17074   struct comp_unit_head *cu_header = &cu->header;
17075   CORE_ADDR retval = 0;
17076
17077   if (cu_header->signed_addr_p)
17078     {
17079       switch (cu_header->addr_size)
17080         {
17081         case 2:
17082           retval = bfd_get_signed_16 (abfd, buf);
17083           break;
17084         case 4:
17085           retval = bfd_get_signed_32 (abfd, buf);
17086           break;
17087         case 8:
17088           retval = bfd_get_signed_64 (abfd, buf);
17089           break;
17090         default:
17091           internal_error (__FILE__, __LINE__,
17092                           _("read_address: bad switch, signed [in module %s]"),
17093                           bfd_get_filename (abfd));
17094         }
17095     }
17096   else
17097     {
17098       switch (cu_header->addr_size)
17099         {
17100         case 2:
17101           retval = bfd_get_16 (abfd, buf);
17102           break;
17103         case 4:
17104           retval = bfd_get_32 (abfd, buf);
17105           break;
17106         case 8:
17107           retval = bfd_get_64 (abfd, buf);
17108           break;
17109         default:
17110           internal_error (__FILE__, __LINE__,
17111                           _("read_address: bad switch, "
17112                             "unsigned [in module %s]"),
17113                           bfd_get_filename (abfd));
17114         }
17115     }
17116
17117   *bytes_read = cu_header->addr_size;
17118   return retval;
17119 }
17120
17121 /* Read the initial length from a section.  The (draft) DWARF 3
17122    specification allows the initial length to take up either 4 bytes
17123    or 12 bytes.  If the first 4 bytes are 0xffffffff, then the next 8
17124    bytes describe the length and all offsets will be 8 bytes in length
17125    instead of 4.
17126
17127    An older, non-standard 64-bit format is also handled by this
17128    function.  The older format in question stores the initial length
17129    as an 8-byte quantity without an escape value.  Lengths greater
17130    than 2^32 aren't very common which means that the initial 4 bytes
17131    is almost always zero.  Since a length value of zero doesn't make
17132    sense for the 32-bit format, this initial zero can be considered to
17133    be an escape value which indicates the presence of the older 64-bit
17134    format.  As written, the code can't detect (old format) lengths
17135    greater than 4GB.  If it becomes necessary to handle lengths
17136    somewhat larger than 4GB, we could allow other small values (such
17137    as the non-sensical values of 1, 2, and 3) to also be used as
17138    escape values indicating the presence of the old format.
17139
17140    The value returned via bytes_read should be used to increment the
17141    relevant pointer after calling read_initial_length().
17142
17143    [ Note:  read_initial_length() and read_offset() are based on the
17144      document entitled "DWARF Debugging Information Format", revision
17145      3, draft 8, dated November 19, 2001.  This document was obtained
17146      from:
17147
17148         http://reality.sgiweb.org/davea/dwarf3-draft8-011125.pdf
17149
17150      This document is only a draft and is subject to change.  (So beware.)
17151
17152      Details regarding the older, non-standard 64-bit format were
17153      determined empirically by examining 64-bit ELF files produced by
17154      the SGI toolchain on an IRIX 6.5 machine.
17155
17156      - Kevin, July 16, 2002
17157    ] */
17158
17159 static LONGEST
17160 read_initial_length (bfd *abfd, const gdb_byte *buf, unsigned int *bytes_read)
17161 {
17162   LONGEST length = bfd_get_32 (abfd, buf);
17163
17164   if (length == 0xffffffff)
17165     {
17166       length = bfd_get_64 (abfd, buf + 4);
17167       *bytes_read = 12;
17168     }
17169   else if (length == 0)
17170     {
17171       /* Handle the (non-standard) 64-bit DWARF2 format used by IRIX.  */
17172       length = bfd_get_64 (abfd, buf);
17173       *bytes_read = 8;
17174     }
17175   else
17176     {
17177       *bytes_read = 4;
17178     }
17179
17180   return length;
17181 }
17182
17183 /* Cover function for read_initial_length.
17184    Returns the length of the object at BUF, and stores the size of the
17185    initial length in *BYTES_READ and stores the size that offsets will be in
17186    *OFFSET_SIZE.
17187    If the initial length size is not equivalent to that specified in
17188    CU_HEADER then issue a complaint.
17189    This is useful when reading non-comp-unit headers.  */
17190
17191 static LONGEST
17192 read_checked_initial_length_and_offset (bfd *abfd, const gdb_byte *buf,
17193                                         const struct comp_unit_head *cu_header,
17194                                         unsigned int *bytes_read,
17195                                         unsigned int *offset_size)
17196 {
17197   LONGEST length = read_initial_length (abfd, buf, bytes_read);
17198
17199   gdb_assert (cu_header->initial_length_size == 4
17200               || cu_header->initial_length_size == 8
17201               || cu_header->initial_length_size == 12);
17202
17203   if (cu_header->initial_length_size != *bytes_read)
17204     complaint (&symfile_complaints,
17205                _("intermixed 32-bit and 64-bit DWARF sections"));
17206
17207   *offset_size = (*bytes_read == 4) ? 4 : 8;
17208   return length;
17209 }
17210
17211 /* Read an offset from the data stream.  The size of the offset is
17212    given by cu_header->offset_size.  */
17213
17214 static LONGEST
17215 read_offset (bfd *abfd, const gdb_byte *buf,
17216              const struct comp_unit_head *cu_header,
17217              unsigned int *bytes_read)
17218 {
17219   LONGEST offset = read_offset_1 (abfd, buf, cu_header->offset_size);
17220
17221   *bytes_read = cu_header->offset_size;
17222   return offset;
17223 }
17224
17225 /* Read an offset from the data stream.  */
17226
17227 static LONGEST
17228 read_offset_1 (bfd *abfd, const gdb_byte *buf, unsigned int offset_size)
17229 {
17230   LONGEST retval = 0;
17231
17232   switch (offset_size)
17233     {
17234     case 4:
17235       retval = bfd_get_32 (abfd, buf);
17236       break;
17237     case 8:
17238       retval = bfd_get_64 (abfd, buf);
17239       break;
17240     default:
17241       internal_error (__FILE__, __LINE__,
17242                       _("read_offset_1: bad switch [in module %s]"),
17243                       bfd_get_filename (abfd));
17244     }
17245
17246   return retval;
17247 }
17248
17249 static const gdb_byte *
17250 read_n_bytes (bfd *abfd, const gdb_byte *buf, unsigned int size)
17251 {
17252   /* If the size of a host char is 8 bits, we can return a pointer
17253      to the buffer, otherwise we have to copy the data to a buffer
17254      allocated on the temporary obstack.  */
17255   gdb_assert (HOST_CHAR_BIT == 8);
17256   return buf;
17257 }
17258
17259 static const char *
17260 read_direct_string (bfd *abfd, const gdb_byte *buf,
17261                     unsigned int *bytes_read_ptr)
17262 {
17263   /* If the size of a host char is 8 bits, we can return a pointer
17264      to the string, otherwise we have to copy the string to a buffer
17265      allocated on the temporary obstack.  */
17266   gdb_assert (HOST_CHAR_BIT == 8);
17267   if (*buf == '\0')
17268     {
17269       *bytes_read_ptr = 1;
17270       return NULL;
17271     }
17272   *bytes_read_ptr = strlen ((const char *) buf) + 1;
17273   return (const char *) buf;
17274 }
17275
17276 /* Return pointer to string at section SECT offset STR_OFFSET with error
17277    reporting strings FORM_NAME and SECT_NAME.  */
17278
17279 static const char *
17280 read_indirect_string_at_offset_from (bfd *abfd, LONGEST str_offset,
17281                                      struct dwarf2_section_info *sect,
17282                                      const char *form_name,
17283                                      const char *sect_name)
17284 {
17285   dwarf2_read_section (dwarf2_per_objfile->objfile, sect);
17286   if (sect->buffer == NULL)
17287     error (_("%s used without %s section [in module %s]"),
17288            form_name, sect_name, bfd_get_filename (abfd));
17289   if (str_offset >= sect->size)
17290     error (_("%s pointing outside of %s section [in module %s]"),
17291            form_name, sect_name, bfd_get_filename (abfd));
17292   gdb_assert (HOST_CHAR_BIT == 8);
17293   if (sect->buffer[str_offset] == '\0')
17294     return NULL;
17295   return (const char *) (sect->buffer + str_offset);
17296 }
17297
17298 /* Return pointer to string at .debug_str offset STR_OFFSET.  */
17299
17300 static const char *
17301 read_indirect_string_at_offset (bfd *abfd, LONGEST str_offset)
17302 {
17303   return read_indirect_string_at_offset_from (abfd, str_offset,
17304                                               &dwarf2_per_objfile->str,
17305                                               "DW_FORM_strp", ".debug_str");
17306 }
17307
17308 /* Return pointer to string at .debug_line_str offset STR_OFFSET.  */
17309
17310 static const char *
17311 read_indirect_line_string_at_offset (bfd *abfd, LONGEST str_offset)
17312 {
17313   return read_indirect_string_at_offset_from (abfd, str_offset,
17314                                               &dwarf2_per_objfile->line_str,
17315                                               "DW_FORM_line_strp",
17316                                               ".debug_line_str");
17317 }
17318
17319 /* Read a string at offset STR_OFFSET in the .debug_str section from
17320    the .dwz file DWZ.  Throw an error if the offset is too large.  If
17321    the string consists of a single NUL byte, return NULL; otherwise
17322    return a pointer to the string.  */
17323
17324 static const char *
17325 read_indirect_string_from_dwz (struct dwz_file *dwz, LONGEST str_offset)
17326 {
17327   dwarf2_read_section (dwarf2_per_objfile->objfile, &dwz->str);
17328
17329   if (dwz->str.buffer == NULL)
17330     error (_("DW_FORM_GNU_strp_alt used without .debug_str "
17331              "section [in module %s]"),
17332            bfd_get_filename (dwz->dwz_bfd));
17333   if (str_offset >= dwz->str.size)
17334     error (_("DW_FORM_GNU_strp_alt pointing outside of "
17335              ".debug_str section [in module %s]"),
17336            bfd_get_filename (dwz->dwz_bfd));
17337   gdb_assert (HOST_CHAR_BIT == 8);
17338   if (dwz->str.buffer[str_offset] == '\0')
17339     return NULL;
17340   return (const char *) (dwz->str.buffer + str_offset);
17341 }
17342
17343 /* Return pointer to string at .debug_str offset as read from BUF.
17344    BUF is assumed to be in a compilation unit described by CU_HEADER.
17345    Return *BYTES_READ_PTR count of bytes read from BUF.  */
17346
17347 static const char *
17348 read_indirect_string (bfd *abfd, const gdb_byte *buf,
17349                       const struct comp_unit_head *cu_header,
17350                       unsigned int *bytes_read_ptr)
17351 {
17352   LONGEST str_offset = read_offset (abfd, buf, cu_header, bytes_read_ptr);
17353
17354   return read_indirect_string_at_offset (abfd, str_offset);
17355 }
17356
17357 /* Return pointer to string at .debug_line_str offset as read from BUF.
17358    BUF is assumed to be in a compilation unit described by CU_HEADER.
17359    Return *BYTES_READ_PTR count of bytes read from BUF.  */
17360
17361 static const char *
17362 read_indirect_line_string (bfd *abfd, const gdb_byte *buf,
17363                            const struct comp_unit_head *cu_header,
17364                            unsigned int *bytes_read_ptr)
17365 {
17366   LONGEST str_offset = read_offset (abfd, buf, cu_header, bytes_read_ptr);
17367
17368   return read_indirect_line_string_at_offset (abfd, str_offset);
17369 }
17370
17371 ULONGEST
17372 read_unsigned_leb128 (bfd *abfd, const gdb_byte *buf,
17373                           unsigned int *bytes_read_ptr)
17374 {
17375   ULONGEST result;
17376   unsigned int num_read;
17377   int shift;
17378   unsigned char byte;
17379
17380   result = 0;
17381   shift = 0;
17382   num_read = 0;
17383   while (1)
17384     {
17385       byte = bfd_get_8 (abfd, buf);
17386       buf++;
17387       num_read++;
17388       result |= ((ULONGEST) (byte & 127) << shift);
17389       if ((byte & 128) == 0)
17390         {
17391           break;
17392         }
17393       shift += 7;
17394     }
17395   *bytes_read_ptr = num_read;
17396   return result;
17397 }
17398
17399 static LONGEST
17400 read_signed_leb128 (bfd *abfd, const gdb_byte *buf,
17401                     unsigned int *bytes_read_ptr)
17402 {
17403   LONGEST result;
17404   int shift, num_read;
17405   unsigned char byte;
17406
17407   result = 0;
17408   shift = 0;
17409   num_read = 0;
17410   while (1)
17411     {
17412       byte = bfd_get_8 (abfd, buf);
17413       buf++;
17414       num_read++;
17415       result |= ((LONGEST) (byte & 127) << shift);
17416       shift += 7;
17417       if ((byte & 128) == 0)
17418         {
17419           break;
17420         }
17421     }
17422   if ((shift < 8 * sizeof (result)) && (byte & 0x40))
17423     result |= -(((LONGEST) 1) << shift);
17424   *bytes_read_ptr = num_read;
17425   return result;
17426 }
17427
17428 /* Given index ADDR_INDEX in .debug_addr, fetch the value.
17429    ADDR_BASE is the DW_AT_GNU_addr_base attribute or zero.
17430    ADDR_SIZE is the size of addresses from the CU header.  */
17431
17432 static CORE_ADDR
17433 read_addr_index_1 (unsigned int addr_index, ULONGEST addr_base, int addr_size)
17434 {
17435   struct objfile *objfile = dwarf2_per_objfile->objfile;
17436   bfd *abfd = objfile->obfd;
17437   const gdb_byte *info_ptr;
17438
17439   dwarf2_read_section (objfile, &dwarf2_per_objfile->addr);
17440   if (dwarf2_per_objfile->addr.buffer == NULL)
17441     error (_("DW_FORM_addr_index used without .debug_addr section [in module %s]"),
17442            objfile_name (objfile));
17443   if (addr_base + addr_index * addr_size >= dwarf2_per_objfile->addr.size)
17444     error (_("DW_FORM_addr_index pointing outside of "
17445              ".debug_addr section [in module %s]"),
17446            objfile_name (objfile));
17447   info_ptr = (dwarf2_per_objfile->addr.buffer
17448               + addr_base + addr_index * addr_size);
17449   if (addr_size == 4)
17450     return bfd_get_32 (abfd, info_ptr);
17451   else
17452     return bfd_get_64 (abfd, info_ptr);
17453 }
17454
17455 /* Given index ADDR_INDEX in .debug_addr, fetch the value.  */
17456
17457 static CORE_ADDR
17458 read_addr_index (struct dwarf2_cu *cu, unsigned int addr_index)
17459 {
17460   return read_addr_index_1 (addr_index, cu->addr_base, cu->header.addr_size);
17461 }
17462
17463 /* Given a pointer to an leb128 value, fetch the value from .debug_addr.  */
17464
17465 static CORE_ADDR
17466 read_addr_index_from_leb128 (struct dwarf2_cu *cu, const gdb_byte *info_ptr,
17467                              unsigned int *bytes_read)
17468 {
17469   bfd *abfd = cu->objfile->obfd;
17470   unsigned int addr_index = read_unsigned_leb128 (abfd, info_ptr, bytes_read);
17471
17472   return read_addr_index (cu, addr_index);
17473 }
17474
17475 /* Data structure to pass results from dwarf2_read_addr_index_reader
17476    back to dwarf2_read_addr_index.  */
17477
17478 struct dwarf2_read_addr_index_data
17479 {
17480   ULONGEST addr_base;
17481   int addr_size;
17482 };
17483
17484 /* die_reader_func for dwarf2_read_addr_index.  */
17485
17486 static void
17487 dwarf2_read_addr_index_reader (const struct die_reader_specs *reader,
17488                                const gdb_byte *info_ptr,
17489                                struct die_info *comp_unit_die,
17490                                int has_children,
17491                                void *data)
17492 {
17493   struct dwarf2_cu *cu = reader->cu;
17494   struct dwarf2_read_addr_index_data *aidata =
17495     (struct dwarf2_read_addr_index_data *) data;
17496
17497   aidata->addr_base = cu->addr_base;
17498   aidata->addr_size = cu->header.addr_size;
17499 }
17500
17501 /* Given an index in .debug_addr, fetch the value.
17502    NOTE: This can be called during dwarf expression evaluation,
17503    long after the debug information has been read, and thus per_cu->cu
17504    may no longer exist.  */
17505
17506 CORE_ADDR
17507 dwarf2_read_addr_index (struct dwarf2_per_cu_data *per_cu,
17508                         unsigned int addr_index)
17509 {
17510   struct objfile *objfile = per_cu->objfile;
17511   struct dwarf2_cu *cu = per_cu->cu;
17512   ULONGEST addr_base;
17513   int addr_size;
17514
17515   /* This is intended to be called from outside this file.  */
17516   dw2_setup (objfile);
17517
17518   /* We need addr_base and addr_size.
17519      If we don't have PER_CU->cu, we have to get it.
17520      Nasty, but the alternative is storing the needed info in PER_CU,
17521      which at this point doesn't seem justified: it's not clear how frequently
17522      it would get used and it would increase the size of every PER_CU.
17523      Entry points like dwarf2_per_cu_addr_size do a similar thing
17524      so we're not in uncharted territory here.
17525      Alas we need to be a bit more complicated as addr_base is contained
17526      in the DIE.
17527
17528      We don't need to read the entire CU(/TU).
17529      We just need the header and top level die.
17530
17531      IWBN to use the aging mechanism to let us lazily later discard the CU.
17532      For now we skip this optimization.  */
17533
17534   if (cu != NULL)
17535     {
17536       addr_base = cu->addr_base;
17537       addr_size = cu->header.addr_size;
17538     }
17539   else
17540     {
17541       struct dwarf2_read_addr_index_data aidata;
17542
17543       /* Note: We can't use init_cutu_and_read_dies_simple here,
17544          we need addr_base.  */
17545       init_cutu_and_read_dies (per_cu, NULL, 0, 0,
17546                                dwarf2_read_addr_index_reader, &aidata);
17547       addr_base = aidata.addr_base;
17548       addr_size = aidata.addr_size;
17549     }
17550
17551   return read_addr_index_1 (addr_index, addr_base, addr_size);
17552 }
17553
17554 /* Given a DW_FORM_GNU_str_index, fetch the string.
17555    This is only used by the Fission support.  */
17556
17557 static const char *
17558 read_str_index (const struct die_reader_specs *reader, ULONGEST str_index)
17559 {
17560   struct objfile *objfile = dwarf2_per_objfile->objfile;
17561   const char *objf_name = objfile_name (objfile);
17562   bfd *abfd = objfile->obfd;
17563   struct dwarf2_cu *cu = reader->cu;
17564   struct dwarf2_section_info *str_section = &reader->dwo_file->sections.str;
17565   struct dwarf2_section_info *str_offsets_section =
17566     &reader->dwo_file->sections.str_offsets;
17567   const gdb_byte *info_ptr;
17568   ULONGEST str_offset;
17569   static const char form_name[] = "DW_FORM_GNU_str_index";
17570
17571   dwarf2_read_section (objfile, str_section);
17572   dwarf2_read_section (objfile, str_offsets_section);
17573   if (str_section->buffer == NULL)
17574     error (_("%s used without .debug_str.dwo section"
17575              " in CU at offset 0x%x [in module %s]"),
17576            form_name, to_underlying (cu->header.sect_off), objf_name);
17577   if (str_offsets_section->buffer == NULL)
17578     error (_("%s used without .debug_str_offsets.dwo section"
17579              " in CU at offset 0x%x [in module %s]"),
17580            form_name, to_underlying (cu->header.sect_off), objf_name);
17581   if (str_index * cu->header.offset_size >= str_offsets_section->size)
17582     error (_("%s pointing outside of .debug_str_offsets.dwo"
17583              " section in CU at offset 0x%x [in module %s]"),
17584            form_name, to_underlying (cu->header.sect_off), objf_name);
17585   info_ptr = (str_offsets_section->buffer
17586               + str_index * cu->header.offset_size);
17587   if (cu->header.offset_size == 4)
17588     str_offset = bfd_get_32 (abfd, info_ptr);
17589   else
17590     str_offset = bfd_get_64 (abfd, info_ptr);
17591   if (str_offset >= str_section->size)
17592     error (_("Offset from %s pointing outside of"
17593              " .debug_str.dwo section in CU at offset 0x%x [in module %s]"),
17594            form_name, to_underlying (cu->header.sect_off), objf_name);
17595   return (const char *) (str_section->buffer + str_offset);
17596 }
17597
17598 /* Return the length of an LEB128 number in BUF.  */
17599
17600 static int
17601 leb128_size (const gdb_byte *buf)
17602 {
17603   const gdb_byte *begin = buf;
17604   gdb_byte byte;
17605
17606   while (1)
17607     {
17608       byte = *buf++;
17609       if ((byte & 128) == 0)
17610         return buf - begin;
17611     }
17612 }
17613
17614 static void
17615 set_cu_language (unsigned int lang, struct dwarf2_cu *cu)
17616 {
17617   switch (lang)
17618     {
17619     case DW_LANG_C89:
17620     case DW_LANG_C99:
17621     case DW_LANG_C11:
17622     case DW_LANG_C:
17623     case DW_LANG_UPC:
17624       cu->language = language_c;
17625       break;
17626     case DW_LANG_Java:
17627     case DW_LANG_C_plus_plus:
17628     case DW_LANG_C_plus_plus_11:
17629     case DW_LANG_C_plus_plus_14:
17630       cu->language = language_cplus;
17631       break;
17632     case DW_LANG_D:
17633       cu->language = language_d;
17634       break;
17635     case DW_LANG_Fortran77:
17636     case DW_LANG_Fortran90:
17637     case DW_LANG_Fortran95:
17638     case DW_LANG_Fortran03:
17639     case DW_LANG_Fortran08:
17640       cu->language = language_fortran;
17641       break;
17642     case DW_LANG_Go:
17643       cu->language = language_go;
17644       break;
17645     case DW_LANG_Mips_Assembler:
17646       cu->language = language_asm;
17647       break;
17648     case DW_LANG_Ada83:
17649     case DW_LANG_Ada95:
17650       cu->language = language_ada;
17651       break;
17652     case DW_LANG_Modula2:
17653       cu->language = language_m2;
17654       break;
17655     case DW_LANG_Pascal83:
17656       cu->language = language_pascal;
17657       break;
17658     case DW_LANG_ObjC:
17659       cu->language = language_objc;
17660       break;
17661     case DW_LANG_Rust:
17662     case DW_LANG_Rust_old:
17663       cu->language = language_rust;
17664       break;
17665     case DW_LANG_Cobol74:
17666     case DW_LANG_Cobol85:
17667     default:
17668       cu->language = language_minimal;
17669       break;
17670     }
17671   cu->language_defn = language_def (cu->language);
17672 }
17673
17674 /* Return the named attribute or NULL if not there.  */
17675
17676 static struct attribute *
17677 dwarf2_attr (struct die_info *die, unsigned int name, struct dwarf2_cu *cu)
17678 {
17679   for (;;)
17680     {
17681       unsigned int i;
17682       struct attribute *spec = NULL;
17683
17684       for (i = 0; i < die->num_attrs; ++i)
17685         {
17686           if (die->attrs[i].name == name)
17687             return &die->attrs[i];
17688           if (die->attrs[i].name == DW_AT_specification
17689               || die->attrs[i].name == DW_AT_abstract_origin)
17690             spec = &die->attrs[i];
17691         }
17692
17693       if (!spec)
17694         break;
17695
17696       die = follow_die_ref (die, spec, &cu);
17697     }
17698
17699   return NULL;
17700 }
17701
17702 /* Return the named attribute or NULL if not there,
17703    but do not follow DW_AT_specification, etc.
17704    This is for use in contexts where we're reading .debug_types dies.
17705    Following DW_AT_specification, DW_AT_abstract_origin will take us
17706    back up the chain, and we want to go down.  */
17707
17708 static struct attribute *
17709 dwarf2_attr_no_follow (struct die_info *die, unsigned int name)
17710 {
17711   unsigned int i;
17712
17713   for (i = 0; i < die->num_attrs; ++i)
17714     if (die->attrs[i].name == name)
17715       return &die->attrs[i];
17716
17717   return NULL;
17718 }
17719
17720 /* Return the string associated with a string-typed attribute, or NULL if it
17721    is either not found or is of an incorrect type.  */
17722
17723 static const char *
17724 dwarf2_string_attr (struct die_info *die, unsigned int name, struct dwarf2_cu *cu)
17725 {
17726   struct attribute *attr;
17727   const char *str = NULL;
17728
17729   attr = dwarf2_attr (die, name, cu);
17730
17731   if (attr != NULL)
17732     {
17733       if (attr->form == DW_FORM_strp || attr->form == DW_FORM_line_strp
17734           || attr->form == DW_FORM_string
17735           || attr->form == DW_FORM_GNU_str_index
17736           || attr->form == DW_FORM_GNU_strp_alt)
17737         str = DW_STRING (attr);
17738       else
17739         complaint (&symfile_complaints,
17740                    _("string type expected for attribute %s for "
17741                      "DIE at 0x%x in module %s"),
17742                    dwarf_attr_name (name), to_underlying (die->sect_off),
17743                    objfile_name (cu->objfile));
17744     }
17745
17746   return str;
17747 }
17748
17749 /* Return non-zero iff the attribute NAME is defined for the given DIE,
17750    and holds a non-zero value.  This function should only be used for
17751    DW_FORM_flag or DW_FORM_flag_present attributes.  */
17752
17753 static int
17754 dwarf2_flag_true_p (struct die_info *die, unsigned name, struct dwarf2_cu *cu)
17755 {
17756   struct attribute *attr = dwarf2_attr (die, name, cu);
17757
17758   return (attr && DW_UNSND (attr));
17759 }
17760
17761 static int
17762 die_is_declaration (struct die_info *die, struct dwarf2_cu *cu)
17763 {
17764   /* A DIE is a declaration if it has a DW_AT_declaration attribute
17765      which value is non-zero.  However, we have to be careful with
17766      DIEs having a DW_AT_specification attribute, because dwarf2_attr()
17767      (via dwarf2_flag_true_p) follows this attribute.  So we may
17768      end up accidently finding a declaration attribute that belongs
17769      to a different DIE referenced by the specification attribute,
17770      even though the given DIE does not have a declaration attribute.  */
17771   return (dwarf2_flag_true_p (die, DW_AT_declaration, cu)
17772           && dwarf2_attr (die, DW_AT_specification, cu) == NULL);
17773 }
17774
17775 /* Return the die giving the specification for DIE, if there is
17776    one.  *SPEC_CU is the CU containing DIE on input, and the CU
17777    containing the return value on output.  If there is no
17778    specification, but there is an abstract origin, that is
17779    returned.  */
17780
17781 static struct die_info *
17782 die_specification (struct die_info *die, struct dwarf2_cu **spec_cu)
17783 {
17784   struct attribute *spec_attr = dwarf2_attr (die, DW_AT_specification,
17785                                              *spec_cu);
17786
17787   if (spec_attr == NULL)
17788     spec_attr = dwarf2_attr (die, DW_AT_abstract_origin, *spec_cu);
17789
17790   if (spec_attr == NULL)
17791     return NULL;
17792   else
17793     return follow_die_ref (die, spec_attr, spec_cu);
17794 }
17795
17796 /* Stub for free_line_header to match void * callback types.  */
17797
17798 static void
17799 free_line_header_voidp (void *arg)
17800 {
17801   struct line_header *lh = (struct line_header *) arg;
17802
17803   delete lh;
17804 }
17805
17806 void
17807 line_header::add_include_dir (const char *include_dir)
17808 {
17809   if (dwarf_line_debug >= 2)
17810     fprintf_unfiltered (gdb_stdlog, "Adding dir %zu: %s\n",
17811                         include_dirs.size () + 1, include_dir);
17812
17813   include_dirs.push_back (include_dir);
17814 }
17815
17816 void
17817 line_header::add_file_name (const char *name,
17818                             dir_index d_index,
17819                             unsigned int mod_time,
17820                             unsigned int length)
17821 {
17822   if (dwarf_line_debug >= 2)
17823     fprintf_unfiltered (gdb_stdlog, "Adding file %u: %s\n",
17824                         (unsigned) file_names.size () + 1, name);
17825
17826   file_names.emplace_back (name, d_index, mod_time, length);
17827 }
17828
17829 /* A convenience function to find the proper .debug_line section for a CU.  */
17830
17831 static struct dwarf2_section_info *
17832 get_debug_line_section (struct dwarf2_cu *cu)
17833 {
17834   struct dwarf2_section_info *section;
17835
17836   /* For TUs in DWO files, the DW_AT_stmt_list attribute lives in the
17837      DWO file.  */
17838   if (cu->dwo_unit && cu->per_cu->is_debug_types)
17839     section = &cu->dwo_unit->dwo_file->sections.line;
17840   else if (cu->per_cu->is_dwz)
17841     {
17842       struct dwz_file *dwz = dwarf2_get_dwz_file ();
17843
17844       section = &dwz->line;
17845     }
17846   else
17847     section = &dwarf2_per_objfile->line;
17848
17849   return section;
17850 }
17851
17852 /* Read directory or file name entry format, starting with byte of
17853    format count entries, ULEB128 pairs of entry formats, ULEB128 of
17854    entries count and the entries themselves in the described entry
17855    format.  */
17856
17857 static void
17858 read_formatted_entries (bfd *abfd, const gdb_byte **bufp,
17859                         struct line_header *lh,
17860                         const struct comp_unit_head *cu_header,
17861                         void (*callback) (struct line_header *lh,
17862                                           const char *name,
17863                                           dir_index d_index,
17864                                           unsigned int mod_time,
17865                                           unsigned int length))
17866 {
17867   gdb_byte format_count, formati;
17868   ULONGEST data_count, datai;
17869   const gdb_byte *buf = *bufp;
17870   const gdb_byte *format_header_data;
17871   int i;
17872   unsigned int bytes_read;
17873
17874   format_count = read_1_byte (abfd, buf);
17875   buf += 1;
17876   format_header_data = buf;
17877   for (formati = 0; formati < format_count; formati++)
17878     {
17879       read_unsigned_leb128 (abfd, buf, &bytes_read);
17880       buf += bytes_read;
17881       read_unsigned_leb128 (abfd, buf, &bytes_read);
17882       buf += bytes_read;
17883     }
17884
17885   data_count = read_unsigned_leb128 (abfd, buf, &bytes_read);
17886   buf += bytes_read;
17887   for (datai = 0; datai < data_count; datai++)
17888     {
17889       const gdb_byte *format = format_header_data;
17890       struct file_entry fe;
17891
17892       for (formati = 0; formati < format_count; formati++)
17893         {
17894           ULONGEST content_type = read_unsigned_leb128 (abfd, format, &bytes_read);
17895           format += bytes_read;
17896
17897           ULONGEST form  = read_unsigned_leb128 (abfd, format, &bytes_read);
17898           format += bytes_read;
17899
17900           gdb::optional<const char *> string;
17901           gdb::optional<unsigned int> uint;
17902
17903           switch (form)
17904             {
17905             case DW_FORM_string:
17906               string.emplace (read_direct_string (abfd, buf, &bytes_read));
17907               buf += bytes_read;
17908               break;
17909
17910             case DW_FORM_line_strp:
17911               string.emplace (read_indirect_line_string (abfd, buf,
17912                                                          cu_header,
17913                                                          &bytes_read));
17914               buf += bytes_read;
17915               break;
17916
17917             case DW_FORM_data1:
17918               uint.emplace (read_1_byte (abfd, buf));
17919               buf += 1;
17920               break;
17921
17922             case DW_FORM_data2:
17923               uint.emplace (read_2_bytes (abfd, buf));
17924               buf += 2;
17925               break;
17926
17927             case DW_FORM_data4:
17928               uint.emplace (read_4_bytes (abfd, buf));
17929               buf += 4;
17930               break;
17931
17932             case DW_FORM_data8:
17933               uint.emplace (read_8_bytes (abfd, buf));
17934               buf += 8;
17935               break;
17936
17937             case DW_FORM_udata:
17938               uint.emplace (read_unsigned_leb128 (abfd, buf, &bytes_read));
17939               buf += bytes_read;
17940               break;
17941
17942             case DW_FORM_block:
17943               /* It is valid only for DW_LNCT_timestamp which is ignored by
17944                  current GDB.  */
17945               break;
17946             }
17947
17948           switch (content_type)
17949             {
17950             case DW_LNCT_path:
17951               if (string.has_value ())
17952                 fe.name = *string;
17953               break;
17954             case DW_LNCT_directory_index:
17955               if (uint.has_value ())
17956                 fe.d_index = (dir_index) *uint;
17957               break;
17958             case DW_LNCT_timestamp:
17959               if (uint.has_value ())
17960                 fe.mod_time = *uint;
17961               break;
17962             case DW_LNCT_size:
17963               if (uint.has_value ())
17964                 fe.length = *uint;
17965               break;
17966             case DW_LNCT_MD5:
17967               break;
17968             default:
17969               complaint (&symfile_complaints,
17970                          _("Unknown format content type %s"),
17971                          pulongest (content_type));
17972             }
17973         }
17974
17975       callback (lh, fe.name, fe.d_index, fe.mod_time, fe.length);
17976     }
17977
17978   *bufp = buf;
17979 }
17980
17981 /* Read the statement program header starting at OFFSET in
17982    .debug_line, or .debug_line.dwo.  Return a pointer
17983    to a struct line_header, allocated using xmalloc.
17984    Returns NULL if there is a problem reading the header, e.g., if it
17985    has a version we don't understand.
17986
17987    NOTE: the strings in the include directory and file name tables of
17988    the returned object point into the dwarf line section buffer,
17989    and must not be freed.  */
17990
17991 static line_header_up
17992 dwarf_decode_line_header (sect_offset sect_off, struct dwarf2_cu *cu)
17993 {
17994   const gdb_byte *line_ptr;
17995   unsigned int bytes_read, offset_size;
17996   int i;
17997   const char *cur_dir, *cur_file;
17998   struct dwarf2_section_info *section;
17999   bfd *abfd;
18000
18001   section = get_debug_line_section (cu);
18002   dwarf2_read_section (dwarf2_per_objfile->objfile, section);
18003   if (section->buffer == NULL)
18004     {
18005       if (cu->dwo_unit && cu->per_cu->is_debug_types)
18006         complaint (&symfile_complaints, _("missing .debug_line.dwo section"));
18007       else
18008         complaint (&symfile_complaints, _("missing .debug_line section"));
18009       return 0;
18010     }
18011
18012   /* We can't do this until we know the section is non-empty.
18013      Only then do we know we have such a section.  */
18014   abfd = get_section_bfd_owner (section);
18015
18016   /* Make sure that at least there's room for the total_length field.
18017      That could be 12 bytes long, but we're just going to fudge that.  */
18018   if (to_underlying (sect_off) + 4 >= section->size)
18019     {
18020       dwarf2_statement_list_fits_in_line_number_section_complaint ();
18021       return 0;
18022     }
18023
18024   line_header_up lh (new line_header ());
18025
18026   lh->sect_off = sect_off;
18027   lh->offset_in_dwz = cu->per_cu->is_dwz;
18028
18029   line_ptr = section->buffer + to_underlying (sect_off);
18030
18031   /* Read in the header.  */
18032   lh->total_length =
18033     read_checked_initial_length_and_offset (abfd, line_ptr, &cu->header,
18034                                             &bytes_read, &offset_size);
18035   line_ptr += bytes_read;
18036   if (line_ptr + lh->total_length > (section->buffer + section->size))
18037     {
18038       dwarf2_statement_list_fits_in_line_number_section_complaint ();
18039       return 0;
18040     }
18041   lh->statement_program_end = line_ptr + lh->total_length;
18042   lh->version = read_2_bytes (abfd, line_ptr);
18043   line_ptr += 2;
18044   if (lh->version > 5)
18045     {
18046       /* This is a version we don't understand.  The format could have
18047          changed in ways we don't handle properly so just punt.  */
18048       complaint (&symfile_complaints,
18049                  _("unsupported version in .debug_line section"));
18050       return NULL;
18051     }
18052   if (lh->version >= 5)
18053     {
18054       gdb_byte segment_selector_size;
18055
18056       /* Skip address size.  */
18057       read_1_byte (abfd, line_ptr);
18058       line_ptr += 1;
18059
18060       segment_selector_size = read_1_byte (abfd, line_ptr);
18061       line_ptr += 1;
18062       if (segment_selector_size != 0)
18063         {
18064           complaint (&symfile_complaints,
18065                      _("unsupported segment selector size %u "
18066                        "in .debug_line section"),
18067                      segment_selector_size);
18068           return NULL;
18069         }
18070     }
18071   lh->header_length = read_offset_1 (abfd, line_ptr, offset_size);
18072   line_ptr += offset_size;
18073   lh->minimum_instruction_length = read_1_byte (abfd, line_ptr);
18074   line_ptr += 1;
18075   if (lh->version >= 4)
18076     {
18077       lh->maximum_ops_per_instruction = read_1_byte (abfd, line_ptr);
18078       line_ptr += 1;
18079     }
18080   else
18081     lh->maximum_ops_per_instruction = 1;
18082
18083   if (lh->maximum_ops_per_instruction == 0)
18084     {
18085       lh->maximum_ops_per_instruction = 1;
18086       complaint (&symfile_complaints,
18087                  _("invalid maximum_ops_per_instruction "
18088                    "in `.debug_line' section"));
18089     }
18090
18091   lh->default_is_stmt = read_1_byte (abfd, line_ptr);
18092   line_ptr += 1;
18093   lh->line_base = read_1_signed_byte (abfd, line_ptr);
18094   line_ptr += 1;
18095   lh->line_range = read_1_byte (abfd, line_ptr);
18096   line_ptr += 1;
18097   lh->opcode_base = read_1_byte (abfd, line_ptr);
18098   line_ptr += 1;
18099   lh->standard_opcode_lengths.reset (new unsigned char[lh->opcode_base]);
18100
18101   lh->standard_opcode_lengths[0] = 1;  /* This should never be used anyway.  */
18102   for (i = 1; i < lh->opcode_base; ++i)
18103     {
18104       lh->standard_opcode_lengths[i] = read_1_byte (abfd, line_ptr);
18105       line_ptr += 1;
18106     }
18107
18108   if (lh->version >= 5)
18109     {
18110       /* Read directory table.  */
18111       read_formatted_entries (abfd, &line_ptr, lh.get (), &cu->header,
18112                               [] (struct line_header *lh, const char *name,
18113                                   dir_index d_index, unsigned int mod_time,
18114                                   unsigned int length)
18115         {
18116           lh->add_include_dir (name);
18117         });
18118
18119       /* Read file name table.  */
18120       read_formatted_entries (abfd, &line_ptr, lh.get (), &cu->header,
18121                               [] (struct line_header *lh, const char *name,
18122                                   dir_index d_index, unsigned int mod_time,
18123                                   unsigned int length)
18124         {
18125           lh->add_file_name (name, d_index, mod_time, length);
18126         });
18127     }
18128   else
18129     {
18130       /* Read directory table.  */
18131       while ((cur_dir = read_direct_string (abfd, line_ptr, &bytes_read)) != NULL)
18132         {
18133           line_ptr += bytes_read;
18134           lh->add_include_dir (cur_dir);
18135         }
18136       line_ptr += bytes_read;
18137
18138       /* Read file name table.  */
18139       while ((cur_file = read_direct_string (abfd, line_ptr, &bytes_read)) != NULL)
18140         {
18141           unsigned int mod_time, length;
18142           dir_index d_index;
18143
18144           line_ptr += bytes_read;
18145           d_index = (dir_index) read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
18146           line_ptr += bytes_read;
18147           mod_time = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
18148           line_ptr += bytes_read;
18149           length = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
18150           line_ptr += bytes_read;
18151
18152           lh->add_file_name (cur_file, d_index, mod_time, length);
18153         }
18154       line_ptr += bytes_read;
18155     }
18156   lh->statement_program_start = line_ptr;
18157
18158   if (line_ptr > (section->buffer + section->size))
18159     complaint (&symfile_complaints,
18160                _("line number info header doesn't "
18161                  "fit in `.debug_line' section"));
18162
18163   return lh;
18164 }
18165
18166 /* Subroutine of dwarf_decode_lines to simplify it.
18167    Return the file name of the psymtab for included file FILE_INDEX
18168    in line header LH of PST.
18169    COMP_DIR is the compilation directory (DW_AT_comp_dir) or NULL if unknown.
18170    If space for the result is malloc'd, it will be freed by a cleanup.
18171    Returns NULL if FILE_INDEX should be ignored, i.e., it is pst->filename.
18172
18173    The function creates dangling cleanup registration.  */
18174
18175 static const char *
18176 psymtab_include_file_name (const struct line_header *lh, int file_index,
18177                            const struct partial_symtab *pst,
18178                            const char *comp_dir)
18179 {
18180   const file_entry &fe = lh->file_names[file_index];
18181   const char *include_name = fe.name;
18182   const char *include_name_to_compare = include_name;
18183   const char *pst_filename;
18184   char *copied_name = NULL;
18185   int file_is_pst;
18186
18187   const char *dir_name = fe.include_dir (lh);
18188
18189   if (!IS_ABSOLUTE_PATH (include_name)
18190       && (dir_name != NULL || comp_dir != NULL))
18191     {
18192       /* Avoid creating a duplicate psymtab for PST.
18193          We do this by comparing INCLUDE_NAME and PST_FILENAME.
18194          Before we do the comparison, however, we need to account
18195          for DIR_NAME and COMP_DIR.
18196          First prepend dir_name (if non-NULL).  If we still don't
18197          have an absolute path prepend comp_dir (if non-NULL).
18198          However, the directory we record in the include-file's
18199          psymtab does not contain COMP_DIR (to match the
18200          corresponding symtab(s)).
18201
18202          Example:
18203
18204          bash$ cd /tmp
18205          bash$ gcc -g ./hello.c
18206          include_name = "hello.c"
18207          dir_name = "."
18208          DW_AT_comp_dir = comp_dir = "/tmp"
18209          DW_AT_name = "./hello.c"
18210
18211       */
18212
18213       if (dir_name != NULL)
18214         {
18215           char *tem = concat (dir_name, SLASH_STRING,
18216                               include_name, (char *)NULL);
18217
18218           make_cleanup (xfree, tem);
18219           include_name = tem;
18220           include_name_to_compare = include_name;
18221         }
18222       if (!IS_ABSOLUTE_PATH (include_name) && comp_dir != NULL)
18223         {
18224           char *tem = concat (comp_dir, SLASH_STRING,
18225                               include_name, (char *)NULL);
18226
18227           make_cleanup (xfree, tem);
18228           include_name_to_compare = tem;
18229         }
18230     }
18231
18232   pst_filename = pst->filename;
18233   if (!IS_ABSOLUTE_PATH (pst_filename) && pst->dirname != NULL)
18234     {
18235       copied_name = concat (pst->dirname, SLASH_STRING,
18236                             pst_filename, (char *)NULL);
18237       pst_filename = copied_name;
18238     }
18239
18240   file_is_pst = FILENAME_CMP (include_name_to_compare, pst_filename) == 0;
18241
18242   if (copied_name != NULL)
18243     xfree (copied_name);
18244
18245   if (file_is_pst)
18246     return NULL;
18247   return include_name;
18248 }
18249
18250 /* State machine to track the state of the line number program.  */
18251
18252 class lnp_state_machine
18253 {
18254 public:
18255   /* Initialize a machine state for the start of a line number
18256      program.  */
18257   lnp_state_machine (gdbarch *arch, line_header *lh, bool record_lines_p);
18258
18259   file_entry *current_file ()
18260   {
18261     /* lh->file_names is 0-based, but the file name numbers in the
18262        statement program are 1-based.  */
18263     return m_line_header->file_name_at (m_file);
18264   }
18265
18266   /* Record the line in the state machine.  END_SEQUENCE is true if
18267      we're processing the end of a sequence.  */
18268   void record_line (bool end_sequence);
18269
18270   /* Check address and if invalid nop-out the rest of the lines in this
18271      sequence.  */
18272   void check_line_address (struct dwarf2_cu *cu,
18273                            const gdb_byte *line_ptr,
18274                            CORE_ADDR lowpc, CORE_ADDR address);
18275
18276   void handle_set_discriminator (unsigned int discriminator)
18277   {
18278     m_discriminator = discriminator;
18279     m_line_has_non_zero_discriminator |= discriminator != 0;
18280   }
18281
18282   /* Handle DW_LNE_set_address.  */
18283   void handle_set_address (CORE_ADDR baseaddr, CORE_ADDR address)
18284   {
18285     m_op_index = 0;
18286     address += baseaddr;
18287     m_address = gdbarch_adjust_dwarf2_line (m_gdbarch, address, false);
18288   }
18289
18290   /* Handle DW_LNS_advance_pc.  */
18291   void handle_advance_pc (CORE_ADDR adjust);
18292
18293   /* Handle a special opcode.  */
18294   void handle_special_opcode (unsigned char op_code);
18295
18296   /* Handle DW_LNS_advance_line.  */
18297   void handle_advance_line (int line_delta)
18298   {
18299     advance_line (line_delta);
18300   }
18301
18302   /* Handle DW_LNS_set_file.  */
18303   void handle_set_file (file_name_index file);
18304
18305   /* Handle DW_LNS_negate_stmt.  */
18306   void handle_negate_stmt ()
18307   {
18308     m_is_stmt = !m_is_stmt;
18309   }
18310
18311   /* Handle DW_LNS_const_add_pc.  */
18312   void handle_const_add_pc ();
18313
18314   /* Handle DW_LNS_fixed_advance_pc.  */
18315   void handle_fixed_advance_pc (CORE_ADDR addr_adj)
18316   {
18317     m_address += gdbarch_adjust_dwarf2_line (m_gdbarch, addr_adj, true);
18318     m_op_index = 0;
18319   }
18320
18321   /* Handle DW_LNS_copy.  */
18322   void handle_copy ()
18323   {
18324     record_line (false);
18325     m_discriminator = 0;
18326   }
18327
18328   /* Handle DW_LNE_end_sequence.  */
18329   void handle_end_sequence ()
18330   {
18331     m_record_line_callback = ::record_line;
18332   }
18333
18334 private:
18335   /* Advance the line by LINE_DELTA.  */
18336   void advance_line (int line_delta)
18337   {
18338     m_line += line_delta;
18339
18340     if (line_delta != 0)
18341       m_line_has_non_zero_discriminator = m_discriminator != 0;
18342   }
18343
18344   gdbarch *m_gdbarch;
18345
18346   /* True if we're recording lines.
18347      Otherwise we're building partial symtabs and are just interested in
18348      finding include files mentioned by the line number program.  */
18349   bool m_record_lines_p;
18350
18351   /* The line number header.  */
18352   line_header *m_line_header;
18353
18354   /* These are part of the standard DWARF line number state machine,
18355      and initialized according to the DWARF spec.  */
18356
18357   unsigned char m_op_index = 0;
18358   /* The line table index (1-based) of the current file.  */
18359   file_name_index m_file = (file_name_index) 1;
18360   unsigned int m_line = 1;
18361
18362   /* These are initialized in the constructor.  */
18363
18364   CORE_ADDR m_address;
18365   bool m_is_stmt;
18366   unsigned int m_discriminator;
18367
18368   /* Additional bits of state we need to track.  */
18369
18370   /* The last file that we called dwarf2_start_subfile for.
18371      This is only used for TLLs.  */
18372   unsigned int m_last_file = 0;
18373   /* The last file a line number was recorded for.  */
18374   struct subfile *m_last_subfile = NULL;
18375
18376   /* The function to call to record a line.  */
18377   record_line_ftype *m_record_line_callback = NULL;
18378
18379   /* The last line number that was recorded, used to coalesce
18380      consecutive entries for the same line.  This can happen, for
18381      example, when discriminators are present.  PR 17276.  */
18382   unsigned int m_last_line = 0;
18383   bool m_line_has_non_zero_discriminator = false;
18384 };
18385
18386 void
18387 lnp_state_machine::handle_advance_pc (CORE_ADDR adjust)
18388 {
18389   CORE_ADDR addr_adj = (((m_op_index + adjust)
18390                          / m_line_header->maximum_ops_per_instruction)
18391                         * m_line_header->minimum_instruction_length);
18392   m_address += gdbarch_adjust_dwarf2_line (m_gdbarch, addr_adj, true);
18393   m_op_index = ((m_op_index + adjust)
18394                 % m_line_header->maximum_ops_per_instruction);
18395 }
18396
18397 void
18398 lnp_state_machine::handle_special_opcode (unsigned char op_code)
18399 {
18400   unsigned char adj_opcode = op_code - m_line_header->opcode_base;
18401   CORE_ADDR addr_adj = (((m_op_index
18402                           + (adj_opcode / m_line_header->line_range))
18403                          / m_line_header->maximum_ops_per_instruction)
18404                         * m_line_header->minimum_instruction_length);
18405   m_address += gdbarch_adjust_dwarf2_line (m_gdbarch, addr_adj, true);
18406   m_op_index = ((m_op_index + (adj_opcode / m_line_header->line_range))
18407                 % m_line_header->maximum_ops_per_instruction);
18408
18409   int line_delta = (m_line_header->line_base
18410                     + (adj_opcode % m_line_header->line_range));
18411   advance_line (line_delta);
18412   record_line (false);
18413   m_discriminator = 0;
18414 }
18415
18416 void
18417 lnp_state_machine::handle_set_file (file_name_index file)
18418 {
18419   m_file = file;
18420
18421   const file_entry *fe = current_file ();
18422   if (fe == NULL)
18423     dwarf2_debug_line_missing_file_complaint ();
18424   else if (m_record_lines_p)
18425     {
18426       const char *dir = fe->include_dir (m_line_header);
18427
18428       m_last_subfile = current_subfile;
18429       m_line_has_non_zero_discriminator = m_discriminator != 0;
18430       dwarf2_start_subfile (fe->name, dir);
18431     }
18432 }
18433
18434 void
18435 lnp_state_machine::handle_const_add_pc ()
18436 {
18437   CORE_ADDR adjust
18438     = (255 - m_line_header->opcode_base) / m_line_header->line_range;
18439
18440   CORE_ADDR addr_adj
18441     = (((m_op_index + adjust)
18442         / m_line_header->maximum_ops_per_instruction)
18443        * m_line_header->minimum_instruction_length);
18444
18445   m_address += gdbarch_adjust_dwarf2_line (m_gdbarch, addr_adj, true);
18446   m_op_index = ((m_op_index + adjust)
18447                 % m_line_header->maximum_ops_per_instruction);
18448 }
18449
18450 /* Ignore this record_line request.  */
18451
18452 static void
18453 noop_record_line (struct subfile *subfile, int line, CORE_ADDR pc)
18454 {
18455   return;
18456 }
18457
18458 /* Return non-zero if we should add LINE to the line number table.
18459    LINE is the line to add, LAST_LINE is the last line that was added,
18460    LAST_SUBFILE is the subfile for LAST_LINE.
18461    LINE_HAS_NON_ZERO_DISCRIMINATOR is non-zero if LINE has ever
18462    had a non-zero discriminator.
18463
18464    We have to be careful in the presence of discriminators.
18465    E.g., for this line:
18466
18467      for (i = 0; i < 100000; i++);
18468
18469    clang can emit four line number entries for that one line,
18470    each with a different discriminator.
18471    See gdb.dwarf2/dw2-single-line-discriminators.exp for an example.
18472
18473    However, we want gdb to coalesce all four entries into one.
18474    Otherwise the user could stepi into the middle of the line and
18475    gdb would get confused about whether the pc really was in the
18476    middle of the line.
18477
18478    Things are further complicated by the fact that two consecutive
18479    line number entries for the same line is a heuristic used by gcc
18480    to denote the end of the prologue.  So we can't just discard duplicate
18481    entries, we have to be selective about it.  The heuristic we use is
18482    that we only collapse consecutive entries for the same line if at least
18483    one of those entries has a non-zero discriminator.  PR 17276.
18484
18485    Note: Addresses in the line number state machine can never go backwards
18486    within one sequence, thus this coalescing is ok.  */
18487
18488 static int
18489 dwarf_record_line_p (unsigned int line, unsigned int last_line,
18490                      int line_has_non_zero_discriminator,
18491                      struct subfile *last_subfile)
18492 {
18493   if (current_subfile != last_subfile)
18494     return 1;
18495   if (line != last_line)
18496     return 1;
18497   /* Same line for the same file that we've seen already.
18498      As a last check, for pr 17276, only record the line if the line
18499      has never had a non-zero discriminator.  */
18500   if (!line_has_non_zero_discriminator)
18501     return 1;
18502   return 0;
18503 }
18504
18505 /* Use P_RECORD_LINE to record line number LINE beginning at address ADDRESS
18506    in the line table of subfile SUBFILE.  */
18507
18508 static void
18509 dwarf_record_line_1 (struct gdbarch *gdbarch, struct subfile *subfile,
18510                      unsigned int line, CORE_ADDR address,
18511                      record_line_ftype p_record_line)
18512 {
18513   CORE_ADDR addr = gdbarch_addr_bits_remove (gdbarch, address);
18514
18515   if (dwarf_line_debug)
18516     {
18517       fprintf_unfiltered (gdb_stdlog,
18518                           "Recording line %u, file %s, address %s\n",
18519                           line, lbasename (subfile->name),
18520                           paddress (gdbarch, address));
18521     }
18522
18523   (*p_record_line) (subfile, line, addr);
18524 }
18525
18526 /* Subroutine of dwarf_decode_lines_1 to simplify it.
18527    Mark the end of a set of line number records.
18528    The arguments are the same as for dwarf_record_line_1.
18529    If SUBFILE is NULL the request is ignored.  */
18530
18531 static void
18532 dwarf_finish_line (struct gdbarch *gdbarch, struct subfile *subfile,
18533                    CORE_ADDR address, record_line_ftype p_record_line)
18534 {
18535   if (subfile == NULL)
18536     return;
18537
18538   if (dwarf_line_debug)
18539     {
18540       fprintf_unfiltered (gdb_stdlog,
18541                           "Finishing current line, file %s, address %s\n",
18542                           lbasename (subfile->name),
18543                           paddress (gdbarch, address));
18544     }
18545
18546   dwarf_record_line_1 (gdbarch, subfile, 0, address, p_record_line);
18547 }
18548
18549 void
18550 lnp_state_machine::record_line (bool end_sequence)
18551 {
18552   if (dwarf_line_debug)
18553     {
18554       fprintf_unfiltered (gdb_stdlog,
18555                           "Processing actual line %u: file %u,"
18556                           " address %s, is_stmt %u, discrim %u\n",
18557                           m_line, to_underlying (m_file),
18558                           paddress (m_gdbarch, m_address),
18559                           m_is_stmt, m_discriminator);
18560     }
18561
18562   file_entry *fe = current_file ();
18563
18564   if (fe == NULL)
18565     dwarf2_debug_line_missing_file_complaint ();
18566   /* For now we ignore lines not starting on an instruction boundary.
18567      But not when processing end_sequence for compatibility with the
18568      previous version of the code.  */
18569   else if (m_op_index == 0 || end_sequence)
18570     {
18571       fe->included_p = 1;
18572       if (m_record_lines_p && m_is_stmt)
18573         {
18574           if (m_last_subfile != current_subfile || end_sequence)
18575             {
18576               dwarf_finish_line (m_gdbarch, m_last_subfile,
18577                                  m_address, m_record_line_callback);
18578             }
18579
18580           if (!end_sequence)
18581             {
18582               if (dwarf_record_line_p (m_line, m_last_line,
18583                                        m_line_has_non_zero_discriminator,
18584                                        m_last_subfile))
18585                 {
18586                   dwarf_record_line_1 (m_gdbarch, current_subfile,
18587                                        m_line, m_address,
18588                                        m_record_line_callback);
18589                 }
18590               m_last_subfile = current_subfile;
18591               m_last_line = m_line;
18592             }
18593         }
18594     }
18595 }
18596
18597 lnp_state_machine::lnp_state_machine (gdbarch *arch, line_header *lh,
18598                                       bool record_lines_p)
18599 {
18600   m_gdbarch = arch;
18601   m_record_lines_p = record_lines_p;
18602   m_line_header = lh;
18603
18604   m_record_line_callback = ::record_line;
18605
18606   /* Call `gdbarch_adjust_dwarf2_line' on the initial 0 address as if there
18607      was a line entry for it so that the backend has a chance to adjust it
18608      and also record it in case it needs it.  This is currently used by MIPS
18609      code, cf. `mips_adjust_dwarf2_line'.  */
18610   m_address = gdbarch_adjust_dwarf2_line (arch, 0, 0);
18611   m_is_stmt = lh->default_is_stmt;
18612   m_discriminator = 0;
18613 }
18614
18615 void
18616 lnp_state_machine::check_line_address (struct dwarf2_cu *cu,
18617                                        const gdb_byte *line_ptr,
18618                                        CORE_ADDR lowpc, CORE_ADDR address)
18619 {
18620   /* If address < lowpc then it's not a usable value, it's outside the
18621      pc range of the CU.  However, we restrict the test to only address
18622      values of zero to preserve GDB's previous behaviour which is to
18623      handle the specific case of a function being GC'd by the linker.  */
18624
18625   if (address == 0 && address < lowpc)
18626     {
18627       /* This line table is for a function which has been
18628          GCd by the linker.  Ignore it.  PR gdb/12528 */
18629
18630       struct objfile *objfile = cu->objfile;
18631       long line_offset = line_ptr - get_debug_line_section (cu)->buffer;
18632
18633       complaint (&symfile_complaints,
18634                  _(".debug_line address at offset 0x%lx is 0 [in module %s]"),
18635                  line_offset, objfile_name (objfile));
18636       m_record_line_callback = noop_record_line;
18637       /* Note: record_line_callback is left as noop_record_line until
18638          we see DW_LNE_end_sequence.  */
18639     }
18640 }
18641
18642 /* Subroutine of dwarf_decode_lines to simplify it.
18643    Process the line number information in LH.
18644    If DECODE_FOR_PST_P is non-zero, all we do is process the line number
18645    program in order to set included_p for every referenced header.  */
18646
18647 static void
18648 dwarf_decode_lines_1 (struct line_header *lh, struct dwarf2_cu *cu,
18649                       const int decode_for_pst_p, CORE_ADDR lowpc)
18650 {
18651   const gdb_byte *line_ptr, *extended_end;
18652   const gdb_byte *line_end;
18653   unsigned int bytes_read, extended_len;
18654   unsigned char op_code, extended_op;
18655   CORE_ADDR baseaddr;
18656   struct objfile *objfile = cu->objfile;
18657   bfd *abfd = objfile->obfd;
18658   struct gdbarch *gdbarch = get_objfile_arch (objfile);
18659   /* True if we're recording line info (as opposed to building partial
18660      symtabs and just interested in finding include files mentioned by
18661      the line number program).  */
18662   bool record_lines_p = !decode_for_pst_p;
18663
18664   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
18665
18666   line_ptr = lh->statement_program_start;
18667   line_end = lh->statement_program_end;
18668
18669   /* Read the statement sequences until there's nothing left.  */
18670   while (line_ptr < line_end)
18671     {
18672       /* The DWARF line number program state machine.  Reset the state
18673          machine at the start of each sequence.  */
18674       lnp_state_machine state_machine (gdbarch, lh, record_lines_p);
18675       bool end_sequence = false;
18676
18677       if (record_lines_p)
18678         {
18679           /* Start a subfile for the current file of the state
18680              machine.  */
18681           const file_entry *fe = state_machine.current_file ();
18682
18683           if (fe != NULL)
18684             dwarf2_start_subfile (fe->name, fe->include_dir (lh));
18685         }
18686
18687       /* Decode the table.  */
18688       while (line_ptr < line_end && !end_sequence)
18689         {
18690           op_code = read_1_byte (abfd, line_ptr);
18691           line_ptr += 1;
18692
18693           if (op_code >= lh->opcode_base)
18694             {
18695               /* Special opcode.  */
18696               state_machine.handle_special_opcode (op_code);
18697             }
18698           else switch (op_code)
18699             {
18700             case DW_LNS_extended_op:
18701               extended_len = read_unsigned_leb128 (abfd, line_ptr,
18702                                                    &bytes_read);
18703               line_ptr += bytes_read;
18704               extended_end = line_ptr + extended_len;
18705               extended_op = read_1_byte (abfd, line_ptr);
18706               line_ptr += 1;
18707               switch (extended_op)
18708                 {
18709                 case DW_LNE_end_sequence:
18710                   state_machine.handle_end_sequence ();
18711                   end_sequence = true;
18712                   break;
18713                 case DW_LNE_set_address:
18714                   {
18715                     CORE_ADDR address
18716                       = read_address (abfd, line_ptr, cu, &bytes_read);
18717                     line_ptr += bytes_read;
18718
18719                     state_machine.check_line_address (cu, line_ptr,
18720                                                       lowpc, address);
18721                     state_machine.handle_set_address (baseaddr, address);
18722                   }
18723                   break;
18724                 case DW_LNE_define_file:
18725                   {
18726                     const char *cur_file;
18727                     unsigned int mod_time, length;
18728                     dir_index dindex;
18729
18730                     cur_file = read_direct_string (abfd, line_ptr,
18731                                                    &bytes_read);
18732                     line_ptr += bytes_read;
18733                     dindex = (dir_index)
18734                       read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
18735                     line_ptr += bytes_read;
18736                     mod_time =
18737                       read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
18738                     line_ptr += bytes_read;
18739                     length =
18740                       read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
18741                     line_ptr += bytes_read;
18742                     lh->add_file_name (cur_file, dindex, mod_time, length);
18743                   }
18744                   break;
18745                 case DW_LNE_set_discriminator:
18746                   {
18747                     /* The discriminator is not interesting to the
18748                        debugger; just ignore it.  We still need to
18749                        check its value though:
18750                        if there are consecutive entries for the same
18751                        (non-prologue) line we want to coalesce them.
18752                        PR 17276.  */
18753                     unsigned int discr
18754                       = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
18755                     line_ptr += bytes_read;
18756
18757                     state_machine.handle_set_discriminator (discr);
18758                   }
18759                   break;
18760                 default:
18761                   complaint (&symfile_complaints,
18762                              _("mangled .debug_line section"));
18763                   return;
18764                 }
18765               /* Make sure that we parsed the extended op correctly.  If e.g.
18766                  we expected a different address size than the producer used,
18767                  we may have read the wrong number of bytes.  */
18768               if (line_ptr != extended_end)
18769                 {
18770                   complaint (&symfile_complaints,
18771                              _("mangled .debug_line section"));
18772                   return;
18773                 }
18774               break;
18775             case DW_LNS_copy:
18776               state_machine.handle_copy ();
18777               break;
18778             case DW_LNS_advance_pc:
18779               {
18780                 CORE_ADDR adjust
18781                   = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
18782                 line_ptr += bytes_read;
18783
18784                 state_machine.handle_advance_pc (adjust);
18785               }
18786               break;
18787             case DW_LNS_advance_line:
18788               {
18789                 int line_delta
18790                   = read_signed_leb128 (abfd, line_ptr, &bytes_read);
18791                 line_ptr += bytes_read;
18792
18793                 state_machine.handle_advance_line (line_delta);
18794               }
18795               break;
18796             case DW_LNS_set_file:
18797               {
18798                 file_name_index file
18799                   = (file_name_index) read_unsigned_leb128 (abfd, line_ptr,
18800                                                             &bytes_read);
18801                 line_ptr += bytes_read;
18802
18803                 state_machine.handle_set_file (file);
18804               }
18805               break;
18806             case DW_LNS_set_column:
18807               (void) read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
18808               line_ptr += bytes_read;
18809               break;
18810             case DW_LNS_negate_stmt:
18811               state_machine.handle_negate_stmt ();
18812               break;
18813             case DW_LNS_set_basic_block:
18814               break;
18815             /* Add to the address register of the state machine the
18816                address increment value corresponding to special opcode
18817                255.  I.e., this value is scaled by the minimum
18818                instruction length since special opcode 255 would have
18819                scaled the increment.  */
18820             case DW_LNS_const_add_pc:
18821               state_machine.handle_const_add_pc ();
18822               break;
18823             case DW_LNS_fixed_advance_pc:
18824               {
18825                 CORE_ADDR addr_adj = read_2_bytes (abfd, line_ptr);
18826                 line_ptr += 2;
18827
18828                 state_machine.handle_fixed_advance_pc (addr_adj);
18829               }
18830               break;
18831             default:
18832               {
18833                 /* Unknown standard opcode, ignore it.  */
18834                 int i;
18835
18836                 for (i = 0; i < lh->standard_opcode_lengths[op_code]; i++)
18837                   {
18838                     (void) read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
18839                     line_ptr += bytes_read;
18840                   }
18841               }
18842             }
18843         }
18844
18845       if (!end_sequence)
18846         dwarf2_debug_line_missing_end_sequence_complaint ();
18847
18848       /* We got a DW_LNE_end_sequence (or we ran off the end of the buffer,
18849          in which case we still finish recording the last line).  */
18850       state_machine.record_line (true);
18851     }
18852 }
18853
18854 /* Decode the Line Number Program (LNP) for the given line_header
18855    structure and CU.  The actual information extracted and the type
18856    of structures created from the LNP depends on the value of PST.
18857
18858    1. If PST is NULL, then this procedure uses the data from the program
18859       to create all necessary symbol tables, and their linetables.
18860
18861    2. If PST is not NULL, this procedure reads the program to determine
18862       the list of files included by the unit represented by PST, and
18863       builds all the associated partial symbol tables.
18864
18865    COMP_DIR is the compilation directory (DW_AT_comp_dir) or NULL if unknown.
18866    It is used for relative paths in the line table.
18867    NOTE: When processing partial symtabs (pst != NULL),
18868    comp_dir == pst->dirname.
18869
18870    NOTE: It is important that psymtabs have the same file name (via strcmp)
18871    as the corresponding symtab.  Since COMP_DIR is not used in the name of the
18872    symtab we don't use it in the name of the psymtabs we create.
18873    E.g. expand_line_sal requires this when finding psymtabs to expand.
18874    A good testcase for this is mb-inline.exp.
18875
18876    LOWPC is the lowest address in CU (or 0 if not known).
18877
18878    Boolean DECODE_MAPPING specifies we need to fully decode .debug_line
18879    for its PC<->lines mapping information.  Otherwise only the filename
18880    table is read in.  */
18881
18882 static void
18883 dwarf_decode_lines (struct line_header *lh, const char *comp_dir,
18884                     struct dwarf2_cu *cu, struct partial_symtab *pst,
18885                     CORE_ADDR lowpc, int decode_mapping)
18886 {
18887   struct objfile *objfile = cu->objfile;
18888   const int decode_for_pst_p = (pst != NULL);
18889
18890   if (decode_mapping)
18891     dwarf_decode_lines_1 (lh, cu, decode_for_pst_p, lowpc);
18892
18893   if (decode_for_pst_p)
18894     {
18895       int file_index;
18896
18897       /* Now that we're done scanning the Line Header Program, we can
18898          create the psymtab of each included file.  */
18899       for (file_index = 0; file_index < lh->file_names.size (); file_index++)
18900         if (lh->file_names[file_index].included_p == 1)
18901           {
18902             const char *include_name =
18903               psymtab_include_file_name (lh, file_index, pst, comp_dir);
18904             if (include_name != NULL)
18905               dwarf2_create_include_psymtab (include_name, pst, objfile);
18906           }
18907     }
18908   else
18909     {
18910       /* Make sure a symtab is created for every file, even files
18911          which contain only variables (i.e. no code with associated
18912          line numbers).  */
18913       struct compunit_symtab *cust = buildsym_compunit_symtab ();
18914       int i;
18915
18916       for (i = 0; i < lh->file_names.size (); i++)
18917         {
18918           file_entry &fe = lh->file_names[i];
18919
18920           dwarf2_start_subfile (fe.name, fe.include_dir (lh));
18921
18922           if (current_subfile->symtab == NULL)
18923             {
18924               current_subfile->symtab
18925                 = allocate_symtab (cust, current_subfile->name);
18926             }
18927           fe.symtab = current_subfile->symtab;
18928         }
18929     }
18930 }
18931
18932 /* Start a subfile for DWARF.  FILENAME is the name of the file and
18933    DIRNAME the name of the source directory which contains FILENAME
18934    or NULL if not known.
18935    This routine tries to keep line numbers from identical absolute and
18936    relative file names in a common subfile.
18937
18938    Using the `list' example from the GDB testsuite, which resides in
18939    /srcdir and compiling it with Irix6.2 cc in /compdir using a filename
18940    of /srcdir/list0.c yields the following debugging information for list0.c:
18941
18942    DW_AT_name:          /srcdir/list0.c
18943    DW_AT_comp_dir:      /compdir
18944    files.files[0].name: list0.h
18945    files.files[0].dir:  /srcdir
18946    files.files[1].name: list0.c
18947    files.files[1].dir:  /srcdir
18948
18949    The line number information for list0.c has to end up in a single
18950    subfile, so that `break /srcdir/list0.c:1' works as expected.
18951    start_subfile will ensure that this happens provided that we pass the
18952    concatenation of files.files[1].dir and files.files[1].name as the
18953    subfile's name.  */
18954
18955 static void
18956 dwarf2_start_subfile (const char *filename, const char *dirname)
18957 {
18958   char *copy = NULL;
18959
18960   /* In order not to lose the line information directory,
18961      we concatenate it to the filename when it makes sense.
18962      Note that the Dwarf3 standard says (speaking of filenames in line
18963      information): ``The directory index is ignored for file names
18964      that represent full path names''.  Thus ignoring dirname in the
18965      `else' branch below isn't an issue.  */
18966
18967   if (!IS_ABSOLUTE_PATH (filename) && dirname != NULL)
18968     {
18969       copy = concat (dirname, SLASH_STRING, filename, (char *)NULL);
18970       filename = copy;
18971     }
18972
18973   start_subfile (filename);
18974
18975   if (copy != NULL)
18976     xfree (copy);
18977 }
18978
18979 /* Start a symtab for DWARF.
18980    NAME, COMP_DIR, LOW_PC are passed to start_symtab.  */
18981
18982 static struct compunit_symtab *
18983 dwarf2_start_symtab (struct dwarf2_cu *cu,
18984                      const char *name, const char *comp_dir, CORE_ADDR low_pc)
18985 {
18986   struct compunit_symtab *cust
18987     = start_symtab (cu->objfile, name, comp_dir, low_pc);
18988
18989   record_debugformat ("DWARF 2");
18990   record_producer (cu->producer);
18991
18992   /* We assume that we're processing GCC output.  */
18993   processing_gcc_compilation = 2;
18994
18995   cu->processing_has_namespace_info = 0;
18996
18997   return cust;
18998 }
18999
19000 static void
19001 var_decode_location (struct attribute *attr, struct symbol *sym,
19002                      struct dwarf2_cu *cu)
19003 {
19004   struct objfile *objfile = cu->objfile;
19005   struct comp_unit_head *cu_header = &cu->header;
19006
19007   /* NOTE drow/2003-01-30: There used to be a comment and some special
19008      code here to turn a symbol with DW_AT_external and a
19009      SYMBOL_VALUE_ADDRESS of 0 into a LOC_UNRESOLVED symbol.  This was
19010      necessary for platforms (maybe Alpha, certainly PowerPC GNU/Linux
19011      with some versions of binutils) where shared libraries could have
19012      relocations against symbols in their debug information - the
19013      minimal symbol would have the right address, but the debug info
19014      would not.  It's no longer necessary, because we will explicitly
19015      apply relocations when we read in the debug information now.  */
19016
19017   /* A DW_AT_location attribute with no contents indicates that a
19018      variable has been optimized away.  */
19019   if (attr_form_is_block (attr) && DW_BLOCK (attr)->size == 0)
19020     {
19021       SYMBOL_ACLASS_INDEX (sym) = LOC_OPTIMIZED_OUT;
19022       return;
19023     }
19024
19025   /* Handle one degenerate form of location expression specially, to
19026      preserve GDB's previous behavior when section offsets are
19027      specified.  If this is just a DW_OP_addr or DW_OP_GNU_addr_index
19028      then mark this symbol as LOC_STATIC.  */
19029
19030   if (attr_form_is_block (attr)
19031       && ((DW_BLOCK (attr)->data[0] == DW_OP_addr
19032            && DW_BLOCK (attr)->size == 1 + cu_header->addr_size)
19033           || (DW_BLOCK (attr)->data[0] == DW_OP_GNU_addr_index
19034               && (DW_BLOCK (attr)->size
19035                   == 1 + leb128_size (&DW_BLOCK (attr)->data[1])))))
19036     {
19037       unsigned int dummy;
19038
19039       if (DW_BLOCK (attr)->data[0] == DW_OP_addr)
19040         SYMBOL_VALUE_ADDRESS (sym) =
19041           read_address (objfile->obfd, DW_BLOCK (attr)->data + 1, cu, &dummy);
19042       else
19043         SYMBOL_VALUE_ADDRESS (sym) =
19044           read_addr_index_from_leb128 (cu, DW_BLOCK (attr)->data + 1, &dummy);
19045       SYMBOL_ACLASS_INDEX (sym) = LOC_STATIC;
19046       fixup_symbol_section (sym, objfile);
19047       SYMBOL_VALUE_ADDRESS (sym) += ANOFFSET (objfile->section_offsets,
19048                                               SYMBOL_SECTION (sym));
19049       return;
19050     }
19051
19052   /* NOTE drow/2002-01-30: It might be worthwhile to have a static
19053      expression evaluator, and use LOC_COMPUTED only when necessary
19054      (i.e. when the value of a register or memory location is
19055      referenced, or a thread-local block, etc.).  Then again, it might
19056      not be worthwhile.  I'm assuming that it isn't unless performance
19057      or memory numbers show me otherwise.  */
19058
19059   dwarf2_symbol_mark_computed (attr, sym, cu, 0);
19060
19061   if (SYMBOL_COMPUTED_OPS (sym)->location_has_loclist)
19062     cu->has_loclist = 1;
19063 }
19064
19065 /* Given a pointer to a DWARF information entry, figure out if we need
19066    to make a symbol table entry for it, and if so, create a new entry
19067    and return a pointer to it.
19068    If TYPE is NULL, determine symbol type from the die, otherwise
19069    used the passed type.
19070    If SPACE is not NULL, use it to hold the new symbol.  If it is
19071    NULL, allocate a new symbol on the objfile's obstack.  */
19072
19073 static struct symbol *
19074 new_symbol_full (struct die_info *die, struct type *type, struct dwarf2_cu *cu,
19075                  struct symbol *space)
19076 {
19077   struct objfile *objfile = cu->objfile;
19078   struct gdbarch *gdbarch = get_objfile_arch (objfile);
19079   struct symbol *sym = NULL;
19080   const char *name;
19081   struct attribute *attr = NULL;
19082   struct attribute *attr2 = NULL;
19083   CORE_ADDR baseaddr;
19084   struct pending **list_to_add = NULL;
19085
19086   int inlined_func = (die->tag == DW_TAG_inlined_subroutine);
19087
19088   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
19089
19090   name = dwarf2_name (die, cu);
19091   if (name)
19092     {
19093       const char *linkagename;
19094       int suppress_add = 0;
19095
19096       if (space)
19097         sym = space;
19098       else
19099         sym = allocate_symbol (objfile);
19100       OBJSTAT (objfile, n_syms++);
19101
19102       /* Cache this symbol's name and the name's demangled form (if any).  */
19103       SYMBOL_SET_LANGUAGE (sym, cu->language, &objfile->objfile_obstack);
19104       linkagename = dwarf2_physname (name, die, cu);
19105       SYMBOL_SET_NAMES (sym, linkagename, strlen (linkagename), 0, objfile);
19106
19107       /* Fortran does not have mangling standard and the mangling does differ
19108          between gfortran, iFort etc.  */
19109       if (cu->language == language_fortran
19110           && symbol_get_demangled_name (&(sym->ginfo)) == NULL)
19111         symbol_set_demangled_name (&(sym->ginfo),
19112                                    dwarf2_full_name (name, die, cu),
19113                                    NULL);
19114
19115       /* Default assumptions.
19116          Use the passed type or decode it from the die.  */
19117       SYMBOL_DOMAIN (sym) = VAR_DOMAIN;
19118       SYMBOL_ACLASS_INDEX (sym) = LOC_OPTIMIZED_OUT;
19119       if (type != NULL)
19120         SYMBOL_TYPE (sym) = type;
19121       else
19122         SYMBOL_TYPE (sym) = die_type (die, cu);
19123       attr = dwarf2_attr (die,
19124                           inlined_func ? DW_AT_call_line : DW_AT_decl_line,
19125                           cu);
19126       if (attr)
19127         {
19128           SYMBOL_LINE (sym) = DW_UNSND (attr);
19129         }
19130
19131       attr = dwarf2_attr (die,
19132                           inlined_func ? DW_AT_call_file : DW_AT_decl_file,
19133                           cu);
19134       if (attr)
19135         {
19136           file_name_index file_index = (file_name_index) DW_UNSND (attr);
19137           struct file_entry *fe;
19138
19139           if (cu->line_header != NULL)
19140             fe = cu->line_header->file_name_at (file_index);
19141           else
19142             fe = NULL;
19143
19144           if (fe == NULL)
19145             complaint (&symfile_complaints,
19146                        _("file index out of range"));
19147           else
19148             symbol_set_symtab (sym, fe->symtab);
19149         }
19150
19151       switch (die->tag)
19152         {
19153         case DW_TAG_label:
19154           attr = dwarf2_attr (die, DW_AT_low_pc, cu);
19155           if (attr)
19156             {
19157               CORE_ADDR addr;
19158
19159               addr = attr_value_as_address (attr);
19160               addr = gdbarch_adjust_dwarf2_addr (gdbarch, addr + baseaddr);
19161               SYMBOL_VALUE_ADDRESS (sym) = addr;
19162             }
19163           SYMBOL_TYPE (sym) = objfile_type (objfile)->builtin_core_addr;
19164           SYMBOL_DOMAIN (sym) = LABEL_DOMAIN;
19165           SYMBOL_ACLASS_INDEX (sym) = LOC_LABEL;
19166           add_symbol_to_list (sym, cu->list_in_scope);
19167           break;
19168         case DW_TAG_subprogram:
19169           /* SYMBOL_BLOCK_VALUE (sym) will be filled in later by
19170              finish_block.  */
19171           SYMBOL_ACLASS_INDEX (sym) = LOC_BLOCK;
19172           attr2 = dwarf2_attr (die, DW_AT_external, cu);
19173           if ((attr2 && (DW_UNSND (attr2) != 0))
19174               || cu->language == language_ada)
19175             {
19176               /* Subprograms marked external are stored as a global symbol.
19177                  Ada subprograms, whether marked external or not, are always
19178                  stored as a global symbol, because we want to be able to
19179                  access them globally.  For instance, we want to be able
19180                  to break on a nested subprogram without having to
19181                  specify the context.  */
19182               list_to_add = &global_symbols;
19183             }
19184           else
19185             {
19186               list_to_add = cu->list_in_scope;
19187             }
19188           break;
19189         case DW_TAG_inlined_subroutine:
19190           /* SYMBOL_BLOCK_VALUE (sym) will be filled in later by
19191              finish_block.  */
19192           SYMBOL_ACLASS_INDEX (sym) = LOC_BLOCK;
19193           SYMBOL_INLINED (sym) = 1;
19194           list_to_add = cu->list_in_scope;
19195           break;
19196         case DW_TAG_template_value_param:
19197           suppress_add = 1;
19198           /* Fall through.  */
19199         case DW_TAG_constant:
19200         case DW_TAG_variable:
19201         case DW_TAG_member:
19202           /* Compilation with minimal debug info may result in
19203              variables with missing type entries.  Change the
19204              misleading `void' type to something sensible.  */
19205           if (TYPE_CODE (SYMBOL_TYPE (sym)) == TYPE_CODE_VOID)
19206             SYMBOL_TYPE (sym) = objfile_type (objfile)->builtin_int;
19207
19208           attr = dwarf2_attr (die, DW_AT_const_value, cu);
19209           /* In the case of DW_TAG_member, we should only be called for
19210              static const members.  */
19211           if (die->tag == DW_TAG_member)
19212             {
19213               /* dwarf2_add_field uses die_is_declaration,
19214                  so we do the same.  */
19215               gdb_assert (die_is_declaration (die, cu));
19216               gdb_assert (attr);
19217             }
19218           if (attr)
19219             {
19220               dwarf2_const_value (attr, sym, cu);
19221               attr2 = dwarf2_attr (die, DW_AT_external, cu);
19222               if (!suppress_add)
19223                 {
19224                   if (attr2 && (DW_UNSND (attr2) != 0))
19225                     list_to_add = &global_symbols;
19226                   else
19227                     list_to_add = cu->list_in_scope;
19228                 }
19229               break;
19230             }
19231           attr = dwarf2_attr (die, DW_AT_location, cu);
19232           if (attr)
19233             {
19234               var_decode_location (attr, sym, cu);
19235               attr2 = dwarf2_attr (die, DW_AT_external, cu);
19236
19237               /* Fortran explicitly imports any global symbols to the local
19238                  scope by DW_TAG_common_block.  */
19239               if (cu->language == language_fortran && die->parent
19240                   && die->parent->tag == DW_TAG_common_block)
19241                 attr2 = NULL;
19242
19243               if (SYMBOL_CLASS (sym) == LOC_STATIC
19244                   && SYMBOL_VALUE_ADDRESS (sym) == 0
19245                   && !dwarf2_per_objfile->has_section_at_zero)
19246                 {
19247                   /* When a static variable is eliminated by the linker,
19248                      the corresponding debug information is not stripped
19249                      out, but the variable address is set to null;
19250                      do not add such variables into symbol table.  */
19251                 }
19252               else if (attr2 && (DW_UNSND (attr2) != 0))
19253                 {
19254                   /* Workaround gfortran PR debug/40040 - it uses
19255                      DW_AT_location for variables in -fPIC libraries which may
19256                      get overriden by other libraries/executable and get
19257                      a different address.  Resolve it by the minimal symbol
19258                      which may come from inferior's executable using copy
19259                      relocation.  Make this workaround only for gfortran as for
19260                      other compilers GDB cannot guess the minimal symbol
19261                      Fortran mangling kind.  */
19262                   if (cu->language == language_fortran && die->parent
19263                       && die->parent->tag == DW_TAG_module
19264                       && cu->producer
19265                       && startswith (cu->producer, "GNU Fortran"))
19266                     SYMBOL_ACLASS_INDEX (sym) = LOC_UNRESOLVED;
19267
19268                   /* A variable with DW_AT_external is never static,
19269                      but it may be block-scoped.  */
19270                   list_to_add = (cu->list_in_scope == &file_symbols
19271                                  ? &global_symbols : cu->list_in_scope);
19272                 }
19273               else
19274                 list_to_add = cu->list_in_scope;
19275             }
19276           else
19277             {
19278               /* We do not know the address of this symbol.
19279                  If it is an external symbol and we have type information
19280                  for it, enter the symbol as a LOC_UNRESOLVED symbol.
19281                  The address of the variable will then be determined from
19282                  the minimal symbol table whenever the variable is
19283                  referenced.  */
19284               attr2 = dwarf2_attr (die, DW_AT_external, cu);
19285
19286               /* Fortran explicitly imports any global symbols to the local
19287                  scope by DW_TAG_common_block.  */
19288               if (cu->language == language_fortran && die->parent
19289                   && die->parent->tag == DW_TAG_common_block)
19290                 {
19291                   /* SYMBOL_CLASS doesn't matter here because
19292                      read_common_block is going to reset it.  */
19293                   if (!suppress_add)
19294                     list_to_add = cu->list_in_scope;
19295                 }
19296               else if (attr2 && (DW_UNSND (attr2) != 0)
19297                        && dwarf2_attr (die, DW_AT_type, cu) != NULL)
19298                 {
19299                   /* A variable with DW_AT_external is never static, but it
19300                      may be block-scoped.  */
19301                   list_to_add = (cu->list_in_scope == &file_symbols
19302                                  ? &global_symbols : cu->list_in_scope);
19303
19304                   SYMBOL_ACLASS_INDEX (sym) = LOC_UNRESOLVED;
19305                 }
19306               else if (!die_is_declaration (die, cu))
19307                 {
19308                   /* Use the default LOC_OPTIMIZED_OUT class.  */
19309                   gdb_assert (SYMBOL_CLASS (sym) == LOC_OPTIMIZED_OUT);
19310                   if (!suppress_add)
19311                     list_to_add = cu->list_in_scope;
19312                 }
19313             }
19314           break;
19315         case DW_TAG_formal_parameter:
19316           /* If we are inside a function, mark this as an argument.  If
19317              not, we might be looking at an argument to an inlined function
19318              when we do not have enough information to show inlined frames;
19319              pretend it's a local variable in that case so that the user can
19320              still see it.  */
19321           if (context_stack_depth > 0
19322               && context_stack[context_stack_depth - 1].name != NULL)
19323             SYMBOL_IS_ARGUMENT (sym) = 1;
19324           attr = dwarf2_attr (die, DW_AT_location, cu);
19325           if (attr)
19326             {
19327               var_decode_location (attr, sym, cu);
19328             }
19329           attr = dwarf2_attr (die, DW_AT_const_value, cu);
19330           if (attr)
19331             {
19332               dwarf2_const_value (attr, sym, cu);
19333             }
19334
19335           list_to_add = cu->list_in_scope;
19336           break;
19337         case DW_TAG_unspecified_parameters:
19338           /* From varargs functions; gdb doesn't seem to have any
19339              interest in this information, so just ignore it for now.
19340              (FIXME?) */
19341           break;
19342         case DW_TAG_template_type_param:
19343           suppress_add = 1;
19344           /* Fall through.  */
19345         case DW_TAG_class_type:
19346         case DW_TAG_interface_type:
19347         case DW_TAG_structure_type:
19348         case DW_TAG_union_type:
19349         case DW_TAG_set_type:
19350         case DW_TAG_enumeration_type:
19351           SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
19352           SYMBOL_DOMAIN (sym) = STRUCT_DOMAIN;
19353
19354           {
19355             /* NOTE: carlton/2003-11-10: C++ class symbols shouldn't
19356                really ever be static objects: otherwise, if you try
19357                to, say, break of a class's method and you're in a file
19358                which doesn't mention that class, it won't work unless
19359                the check for all static symbols in lookup_symbol_aux
19360                saves you.  See the OtherFileClass tests in
19361                gdb.c++/namespace.exp.  */
19362
19363             if (!suppress_add)
19364               {
19365                 list_to_add = (cu->list_in_scope == &file_symbols
19366                                && cu->language == language_cplus
19367                                ? &global_symbols : cu->list_in_scope);
19368
19369                 /* The semantics of C++ state that "struct foo {
19370                    ... }" also defines a typedef for "foo".  */
19371                 if (cu->language == language_cplus
19372                     || cu->language == language_ada
19373                     || cu->language == language_d
19374                     || cu->language == language_rust)
19375                   {
19376                     /* The symbol's name is already allocated along
19377                        with this objfile, so we don't need to
19378                        duplicate it for the type.  */
19379                     if (TYPE_NAME (SYMBOL_TYPE (sym)) == 0)
19380                       TYPE_NAME (SYMBOL_TYPE (sym)) = SYMBOL_SEARCH_NAME (sym);
19381                   }
19382               }
19383           }
19384           break;
19385         case DW_TAG_typedef:
19386           SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
19387           SYMBOL_DOMAIN (sym) = VAR_DOMAIN;
19388           list_to_add = cu->list_in_scope;
19389           break;
19390         case DW_TAG_base_type:
19391         case DW_TAG_subrange_type:
19392           SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
19393           SYMBOL_DOMAIN (sym) = VAR_DOMAIN;
19394           list_to_add = cu->list_in_scope;
19395           break;
19396         case DW_TAG_enumerator:
19397           attr = dwarf2_attr (die, DW_AT_const_value, cu);
19398           if (attr)
19399             {
19400               dwarf2_const_value (attr, sym, cu);
19401             }
19402           {
19403             /* NOTE: carlton/2003-11-10: See comment above in the
19404                DW_TAG_class_type, etc. block.  */
19405
19406             list_to_add = (cu->list_in_scope == &file_symbols
19407                            && cu->language == language_cplus
19408                            ? &global_symbols : cu->list_in_scope);
19409           }
19410           break;
19411         case DW_TAG_imported_declaration:
19412         case DW_TAG_namespace:
19413           SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
19414           list_to_add = &global_symbols;
19415           break;
19416         case DW_TAG_module:
19417           SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
19418           SYMBOL_DOMAIN (sym) = MODULE_DOMAIN;
19419           list_to_add = &global_symbols;
19420           break;
19421         case DW_TAG_common_block:
19422           SYMBOL_ACLASS_INDEX (sym) = LOC_COMMON_BLOCK;
19423           SYMBOL_DOMAIN (sym) = COMMON_BLOCK_DOMAIN;
19424           add_symbol_to_list (sym, cu->list_in_scope);
19425           break;
19426         default:
19427           /* Not a tag we recognize.  Hopefully we aren't processing
19428              trash data, but since we must specifically ignore things
19429              we don't recognize, there is nothing else we should do at
19430              this point.  */
19431           complaint (&symfile_complaints, _("unsupported tag: '%s'"),
19432                      dwarf_tag_name (die->tag));
19433           break;
19434         }
19435
19436       if (suppress_add)
19437         {
19438           sym->hash_next = objfile->template_symbols;
19439           objfile->template_symbols = sym;
19440           list_to_add = NULL;
19441         }
19442
19443       if (list_to_add != NULL)
19444         add_symbol_to_list (sym, list_to_add);
19445
19446       /* For the benefit of old versions of GCC, check for anonymous
19447          namespaces based on the demangled name.  */
19448       if (!cu->processing_has_namespace_info
19449           && cu->language == language_cplus)
19450         cp_scan_for_anonymous_namespaces (sym, objfile);
19451     }
19452   return (sym);
19453 }
19454
19455 /* A wrapper for new_symbol_full that always allocates a new symbol.  */
19456
19457 static struct symbol *
19458 new_symbol (struct die_info *die, struct type *type, struct dwarf2_cu *cu)
19459 {
19460   return new_symbol_full (die, type, cu, NULL);
19461 }
19462
19463 /* Given an attr with a DW_FORM_dataN value in host byte order,
19464    zero-extend it as appropriate for the symbol's type.  The DWARF
19465    standard (v4) is not entirely clear about the meaning of using
19466    DW_FORM_dataN for a constant with a signed type, where the type is
19467    wider than the data.  The conclusion of a discussion on the DWARF
19468    list was that this is unspecified.  We choose to always zero-extend
19469    because that is the interpretation long in use by GCC.  */
19470
19471 static gdb_byte *
19472 dwarf2_const_value_data (const struct attribute *attr, struct obstack *obstack,
19473                          struct dwarf2_cu *cu, LONGEST *value, int bits)
19474 {
19475   struct objfile *objfile = cu->objfile;
19476   enum bfd_endian byte_order = bfd_big_endian (objfile->obfd) ?
19477                                 BFD_ENDIAN_BIG : BFD_ENDIAN_LITTLE;
19478   LONGEST l = DW_UNSND (attr);
19479
19480   if (bits < sizeof (*value) * 8)
19481     {
19482       l &= ((LONGEST) 1 << bits) - 1;
19483       *value = l;
19484     }
19485   else if (bits == sizeof (*value) * 8)
19486     *value = l;
19487   else
19488     {
19489       gdb_byte *bytes = (gdb_byte *) obstack_alloc (obstack, bits / 8);
19490       store_unsigned_integer (bytes, bits / 8, byte_order, l);
19491       return bytes;
19492     }
19493
19494   return NULL;
19495 }
19496
19497 /* Read a constant value from an attribute.  Either set *VALUE, or if
19498    the value does not fit in *VALUE, set *BYTES - either already
19499    allocated on the objfile obstack, or newly allocated on OBSTACK,
19500    or, set *BATON, if we translated the constant to a location
19501    expression.  */
19502
19503 static void
19504 dwarf2_const_value_attr (const struct attribute *attr, struct type *type,
19505                          const char *name, struct obstack *obstack,
19506                          struct dwarf2_cu *cu,
19507                          LONGEST *value, const gdb_byte **bytes,
19508                          struct dwarf2_locexpr_baton **baton)
19509 {
19510   struct objfile *objfile = cu->objfile;
19511   struct comp_unit_head *cu_header = &cu->header;
19512   struct dwarf_block *blk;
19513   enum bfd_endian byte_order = (bfd_big_endian (objfile->obfd) ?
19514                                 BFD_ENDIAN_BIG : BFD_ENDIAN_LITTLE);
19515
19516   *value = 0;
19517   *bytes = NULL;
19518   *baton = NULL;
19519
19520   switch (attr->form)
19521     {
19522     case DW_FORM_addr:
19523     case DW_FORM_GNU_addr_index:
19524       {
19525         gdb_byte *data;
19526
19527         if (TYPE_LENGTH (type) != cu_header->addr_size)
19528           dwarf2_const_value_length_mismatch_complaint (name,
19529                                                         cu_header->addr_size,
19530                                                         TYPE_LENGTH (type));
19531         /* Symbols of this form are reasonably rare, so we just
19532            piggyback on the existing location code rather than writing
19533            a new implementation of symbol_computed_ops.  */
19534         *baton = XOBNEW (obstack, struct dwarf2_locexpr_baton);
19535         (*baton)->per_cu = cu->per_cu;
19536         gdb_assert ((*baton)->per_cu);
19537
19538         (*baton)->size = 2 + cu_header->addr_size;
19539         data = (gdb_byte *) obstack_alloc (obstack, (*baton)->size);
19540         (*baton)->data = data;
19541
19542         data[0] = DW_OP_addr;
19543         store_unsigned_integer (&data[1], cu_header->addr_size,
19544                                 byte_order, DW_ADDR (attr));
19545         data[cu_header->addr_size + 1] = DW_OP_stack_value;
19546       }
19547       break;
19548     case DW_FORM_string:
19549     case DW_FORM_strp:
19550     case DW_FORM_GNU_str_index:
19551     case DW_FORM_GNU_strp_alt:
19552       /* DW_STRING is already allocated on the objfile obstack, point
19553          directly to it.  */
19554       *bytes = (const gdb_byte *) DW_STRING (attr);
19555       break;
19556     case DW_FORM_block1:
19557     case DW_FORM_block2:
19558     case DW_FORM_block4:
19559     case DW_FORM_block:
19560     case DW_FORM_exprloc:
19561     case DW_FORM_data16:
19562       blk = DW_BLOCK (attr);
19563       if (TYPE_LENGTH (type) != blk->size)
19564         dwarf2_const_value_length_mismatch_complaint (name, blk->size,
19565                                                       TYPE_LENGTH (type));
19566       *bytes = blk->data;
19567       break;
19568
19569       /* The DW_AT_const_value attributes are supposed to carry the
19570          symbol's value "represented as it would be on the target
19571          architecture."  By the time we get here, it's already been
19572          converted to host endianness, so we just need to sign- or
19573          zero-extend it as appropriate.  */
19574     case DW_FORM_data1:
19575       *bytes = dwarf2_const_value_data (attr, obstack, cu, value, 8);
19576       break;
19577     case DW_FORM_data2:
19578       *bytes = dwarf2_const_value_data (attr, obstack, cu, value, 16);
19579       break;
19580     case DW_FORM_data4:
19581       *bytes = dwarf2_const_value_data (attr, obstack, cu, value, 32);
19582       break;
19583     case DW_FORM_data8:
19584       *bytes = dwarf2_const_value_data (attr, obstack, cu, value, 64);
19585       break;
19586
19587     case DW_FORM_sdata:
19588     case DW_FORM_implicit_const:
19589       *value = DW_SND (attr);
19590       break;
19591
19592     case DW_FORM_udata:
19593       *value = DW_UNSND (attr);
19594       break;
19595
19596     default:
19597       complaint (&symfile_complaints,
19598                  _("unsupported const value attribute form: '%s'"),
19599                  dwarf_form_name (attr->form));
19600       *value = 0;
19601       break;
19602     }
19603 }
19604
19605
19606 /* Copy constant value from an attribute to a symbol.  */
19607
19608 static void
19609 dwarf2_const_value (const struct attribute *attr, struct symbol *sym,
19610                     struct dwarf2_cu *cu)
19611 {
19612   struct objfile *objfile = cu->objfile;
19613   LONGEST value;
19614   const gdb_byte *bytes;
19615   struct dwarf2_locexpr_baton *baton;
19616
19617   dwarf2_const_value_attr (attr, SYMBOL_TYPE (sym),
19618                            SYMBOL_PRINT_NAME (sym),
19619                            &objfile->objfile_obstack, cu,
19620                            &value, &bytes, &baton);
19621
19622   if (baton != NULL)
19623     {
19624       SYMBOL_LOCATION_BATON (sym) = baton;
19625       SYMBOL_ACLASS_INDEX (sym) = dwarf2_locexpr_index;
19626     }
19627   else if (bytes != NULL)
19628      {
19629       SYMBOL_VALUE_BYTES (sym) = bytes;
19630       SYMBOL_ACLASS_INDEX (sym) = LOC_CONST_BYTES;
19631     }
19632   else
19633     {
19634       SYMBOL_VALUE (sym) = value;
19635       SYMBOL_ACLASS_INDEX (sym) = LOC_CONST;
19636     }
19637 }
19638
19639 /* Return the type of the die in question using its DW_AT_type attribute.  */
19640
19641 static struct type *
19642 die_type (struct die_info *die, struct dwarf2_cu *cu)
19643 {
19644   struct attribute *type_attr;
19645
19646   type_attr = dwarf2_attr (die, DW_AT_type, cu);
19647   if (!type_attr)
19648     {
19649       /* A missing DW_AT_type represents a void type.  */
19650       return objfile_type (cu->objfile)->builtin_void;
19651     }
19652
19653   return lookup_die_type (die, type_attr, cu);
19654 }
19655
19656 /* True iff CU's producer generates GNAT Ada auxiliary information
19657    that allows to find parallel types through that information instead
19658    of having to do expensive parallel lookups by type name.  */
19659
19660 static int
19661 need_gnat_info (struct dwarf2_cu *cu)
19662 {
19663   /* FIXME: brobecker/2010-10-12: As of now, only the AdaCore version
19664      of GNAT produces this auxiliary information, without any indication
19665      that it is produced.  Part of enhancing the FSF version of GNAT
19666      to produce that information will be to put in place an indicator
19667      that we can use in order to determine whether the descriptive type
19668      info is available or not.  One suggestion that has been made is
19669      to use a new attribute, attached to the CU die.  For now, assume
19670      that the descriptive type info is not available.  */
19671   return 0;
19672 }
19673
19674 /* Return the auxiliary type of the die in question using its
19675    DW_AT_GNAT_descriptive_type attribute.  Returns NULL if the
19676    attribute is not present.  */
19677
19678 static struct type *
19679 die_descriptive_type (struct die_info *die, struct dwarf2_cu *cu)
19680 {
19681   struct attribute *type_attr;
19682
19683   type_attr = dwarf2_attr (die, DW_AT_GNAT_descriptive_type, cu);
19684   if (!type_attr)
19685     return NULL;
19686
19687   return lookup_die_type (die, type_attr, cu);
19688 }
19689
19690 /* If DIE has a descriptive_type attribute, then set the TYPE's
19691    descriptive type accordingly.  */
19692
19693 static void
19694 set_descriptive_type (struct type *type, struct die_info *die,
19695                       struct dwarf2_cu *cu)
19696 {
19697   struct type *descriptive_type = die_descriptive_type (die, cu);
19698
19699   if (descriptive_type)
19700     {
19701       ALLOCATE_GNAT_AUX_TYPE (type);
19702       TYPE_DESCRIPTIVE_TYPE (type) = descriptive_type;
19703     }
19704 }
19705
19706 /* Return the containing type of the die in question using its
19707    DW_AT_containing_type attribute.  */
19708
19709 static struct type *
19710 die_containing_type (struct die_info *die, struct dwarf2_cu *cu)
19711 {
19712   struct attribute *type_attr;
19713
19714   type_attr = dwarf2_attr (die, DW_AT_containing_type, cu);
19715   if (!type_attr)
19716     error (_("Dwarf Error: Problem turning containing type into gdb type "
19717              "[in module %s]"), objfile_name (cu->objfile));
19718
19719   return lookup_die_type (die, type_attr, cu);
19720 }
19721
19722 /* Return an error marker type to use for the ill formed type in DIE/CU.  */
19723
19724 static struct type *
19725 build_error_marker_type (struct dwarf2_cu *cu, struct die_info *die)
19726 {
19727   struct objfile *objfile = dwarf2_per_objfile->objfile;
19728   char *message, *saved;
19729
19730   message = xstrprintf (_("<unknown type in %s, CU 0x%x, DIE 0x%x>"),
19731                         objfile_name (objfile),
19732                         to_underlying (cu->header.sect_off),
19733                         to_underlying (die->sect_off));
19734   saved = (char *) obstack_copy0 (&objfile->objfile_obstack,
19735                                   message, strlen (message));
19736   xfree (message);
19737
19738   return init_type (objfile, TYPE_CODE_ERROR, 0, saved);
19739 }
19740
19741 /* Look up the type of DIE in CU using its type attribute ATTR.
19742    ATTR must be one of: DW_AT_type, DW_AT_GNAT_descriptive_type,
19743    DW_AT_containing_type.
19744    If there is no type substitute an error marker.  */
19745
19746 static struct type *
19747 lookup_die_type (struct die_info *die, const struct attribute *attr,
19748                  struct dwarf2_cu *cu)
19749 {
19750   struct objfile *objfile = cu->objfile;
19751   struct type *this_type;
19752
19753   gdb_assert (attr->name == DW_AT_type
19754               || attr->name == DW_AT_GNAT_descriptive_type
19755               || attr->name == DW_AT_containing_type);
19756
19757   /* First see if we have it cached.  */
19758
19759   if (attr->form == DW_FORM_GNU_ref_alt)
19760     {
19761       struct dwarf2_per_cu_data *per_cu;
19762       sect_offset sect_off = dwarf2_get_ref_die_offset (attr);
19763
19764       per_cu = dwarf2_find_containing_comp_unit (sect_off, 1, cu->objfile);
19765       this_type = get_die_type_at_offset (sect_off, per_cu);
19766     }
19767   else if (attr_form_is_ref (attr))
19768     {
19769       sect_offset sect_off = dwarf2_get_ref_die_offset (attr);
19770
19771       this_type = get_die_type_at_offset (sect_off, cu->per_cu);
19772     }
19773   else if (attr->form == DW_FORM_ref_sig8)
19774     {
19775       ULONGEST signature = DW_SIGNATURE (attr);
19776
19777       return get_signatured_type (die, signature, cu);
19778     }
19779   else
19780     {
19781       complaint (&symfile_complaints,
19782                  _("Dwarf Error: Bad type attribute %s in DIE"
19783                    " at 0x%x [in module %s]"),
19784                  dwarf_attr_name (attr->name), to_underlying (die->sect_off),
19785                  objfile_name (objfile));
19786       return build_error_marker_type (cu, die);
19787     }
19788
19789   /* If not cached we need to read it in.  */
19790
19791   if (this_type == NULL)
19792     {
19793       struct die_info *type_die = NULL;
19794       struct dwarf2_cu *type_cu = cu;
19795
19796       if (attr_form_is_ref (attr))
19797         type_die = follow_die_ref (die, attr, &type_cu);
19798       if (type_die == NULL)
19799         return build_error_marker_type (cu, die);
19800       /* If we find the type now, it's probably because the type came
19801          from an inter-CU reference and the type's CU got expanded before
19802          ours.  */
19803       this_type = read_type_die (type_die, type_cu);
19804     }
19805
19806   /* If we still don't have a type use an error marker.  */
19807
19808   if (this_type == NULL)
19809     return build_error_marker_type (cu, die);
19810
19811   return this_type;
19812 }
19813
19814 /* Return the type in DIE, CU.
19815    Returns NULL for invalid types.
19816
19817    This first does a lookup in die_type_hash,
19818    and only reads the die in if necessary.
19819
19820    NOTE: This can be called when reading in partial or full symbols.  */
19821
19822 static struct type *
19823 read_type_die (struct die_info *die, struct dwarf2_cu *cu)
19824 {
19825   struct type *this_type;
19826
19827   this_type = get_die_type (die, cu);
19828   if (this_type)
19829     return this_type;
19830
19831   return read_type_die_1 (die, cu);
19832 }
19833
19834 /* Read the type in DIE, CU.
19835    Returns NULL for invalid types.  */
19836
19837 static struct type *
19838 read_type_die_1 (struct die_info *die, struct dwarf2_cu *cu)
19839 {
19840   struct type *this_type = NULL;
19841
19842   switch (die->tag)
19843     {
19844     case DW_TAG_class_type:
19845     case DW_TAG_interface_type:
19846     case DW_TAG_structure_type:
19847     case DW_TAG_union_type:
19848       this_type = read_structure_type (die, cu);
19849       break;
19850     case DW_TAG_enumeration_type:
19851       this_type = read_enumeration_type (die, cu);
19852       break;
19853     case DW_TAG_subprogram:
19854     case DW_TAG_subroutine_type:
19855     case DW_TAG_inlined_subroutine:
19856       this_type = read_subroutine_type (die, cu);
19857       break;
19858     case DW_TAG_array_type:
19859       this_type = read_array_type (die, cu);
19860       break;
19861     case DW_TAG_set_type:
19862       this_type = read_set_type (die, cu);
19863       break;
19864     case DW_TAG_pointer_type:
19865       this_type = read_tag_pointer_type (die, cu);
19866       break;
19867     case DW_TAG_ptr_to_member_type:
19868       this_type = read_tag_ptr_to_member_type (die, cu);
19869       break;
19870     case DW_TAG_reference_type:
19871       this_type = read_tag_reference_type (die, cu, TYPE_CODE_REF);
19872       break;
19873     case DW_TAG_rvalue_reference_type:
19874       this_type = read_tag_reference_type (die, cu, TYPE_CODE_RVALUE_REF);
19875       break;
19876     case DW_TAG_const_type:
19877       this_type = read_tag_const_type (die, cu);
19878       break;
19879     case DW_TAG_volatile_type:
19880       this_type = read_tag_volatile_type (die, cu);
19881       break;
19882     case DW_TAG_restrict_type:
19883       this_type = read_tag_restrict_type (die, cu);
19884       break;
19885     case DW_TAG_string_type:
19886       this_type = read_tag_string_type (die, cu);
19887       break;
19888     case DW_TAG_typedef:
19889       this_type = read_typedef (die, cu);
19890       break;
19891     case DW_TAG_subrange_type:
19892       this_type = read_subrange_type (die, cu);
19893       break;
19894     case DW_TAG_base_type:
19895       this_type = read_base_type (die, cu);
19896       break;
19897     case DW_TAG_unspecified_type:
19898       this_type = read_unspecified_type (die, cu);
19899       break;
19900     case DW_TAG_namespace:
19901       this_type = read_namespace_type (die, cu);
19902       break;
19903     case DW_TAG_module:
19904       this_type = read_module_type (die, cu);
19905       break;
19906     case DW_TAG_atomic_type:
19907       this_type = read_tag_atomic_type (die, cu);
19908       break;
19909     default:
19910       complaint (&symfile_complaints,
19911                  _("unexpected tag in read_type_die: '%s'"),
19912                  dwarf_tag_name (die->tag));
19913       break;
19914     }
19915
19916   return this_type;
19917 }
19918
19919 /* See if we can figure out if the class lives in a namespace.  We do
19920    this by looking for a member function; its demangled name will
19921    contain namespace info, if there is any.
19922    Return the computed name or NULL.
19923    Space for the result is allocated on the objfile's obstack.
19924    This is the full-die version of guess_partial_die_structure_name.
19925    In this case we know DIE has no useful parent.  */
19926
19927 static char *
19928 guess_full_die_structure_name (struct die_info *die, struct dwarf2_cu *cu)
19929 {
19930   struct die_info *spec_die;
19931   struct dwarf2_cu *spec_cu;
19932   struct die_info *child;
19933
19934   spec_cu = cu;
19935   spec_die = die_specification (die, &spec_cu);
19936   if (spec_die != NULL)
19937     {
19938       die = spec_die;
19939       cu = spec_cu;
19940     }
19941
19942   for (child = die->child;
19943        child != NULL;
19944        child = child->sibling)
19945     {
19946       if (child->tag == DW_TAG_subprogram)
19947         {
19948           const char *linkage_name = dw2_linkage_name (child, cu);
19949
19950           if (linkage_name != NULL)
19951             {
19952               char *actual_name
19953                 = language_class_name_from_physname (cu->language_defn,
19954                                                      linkage_name);
19955               char *name = NULL;
19956
19957               if (actual_name != NULL)
19958                 {
19959                   const char *die_name = dwarf2_name (die, cu);
19960
19961                   if (die_name != NULL
19962                       && strcmp (die_name, actual_name) != 0)
19963                     {
19964                       /* Strip off the class name from the full name.
19965                          We want the prefix.  */
19966                       int die_name_len = strlen (die_name);
19967                       int actual_name_len = strlen (actual_name);
19968
19969                       /* Test for '::' as a sanity check.  */
19970                       if (actual_name_len > die_name_len + 2
19971                           && actual_name[actual_name_len
19972                                          - die_name_len - 1] == ':')
19973                         name = (char *) obstack_copy0 (
19974                           &cu->objfile->per_bfd->storage_obstack,
19975                           actual_name, actual_name_len - die_name_len - 2);
19976                     }
19977                 }
19978               xfree (actual_name);
19979               return name;
19980             }
19981         }
19982     }
19983
19984   return NULL;
19985 }
19986
19987 /* GCC might emit a nameless typedef that has a linkage name.  Determine the
19988    prefix part in such case.  See
19989    http://gcc.gnu.org/bugzilla/show_bug.cgi?id=47510.  */
19990
19991 static const char *
19992 anonymous_struct_prefix (struct die_info *die, struct dwarf2_cu *cu)
19993 {
19994   struct attribute *attr;
19995   const char *base;
19996
19997   if (die->tag != DW_TAG_class_type && die->tag != DW_TAG_interface_type
19998       && die->tag != DW_TAG_structure_type && die->tag != DW_TAG_union_type)
19999     return NULL;
20000
20001   if (dwarf2_string_attr (die, DW_AT_name, cu) != NULL)
20002     return NULL;
20003
20004   attr = dw2_linkage_name_attr (die, cu);
20005   if (attr == NULL || DW_STRING (attr) == NULL)
20006     return NULL;
20007
20008   /* dwarf2_name had to be already called.  */
20009   gdb_assert (DW_STRING_IS_CANONICAL (attr));
20010
20011   /* Strip the base name, keep any leading namespaces/classes.  */
20012   base = strrchr (DW_STRING (attr), ':');
20013   if (base == NULL || base == DW_STRING (attr) || base[-1] != ':')
20014     return "";
20015
20016   return (char *) obstack_copy0 (&cu->objfile->per_bfd->storage_obstack,
20017                                  DW_STRING (attr),
20018                                  &base[-1] - DW_STRING (attr));
20019 }
20020
20021 /* Return the name of the namespace/class that DIE is defined within,
20022    or "" if we can't tell.  The caller should not xfree the result.
20023
20024    For example, if we're within the method foo() in the following
20025    code:
20026
20027    namespace N {
20028      class C {
20029        void foo () {
20030        }
20031      };
20032    }
20033
20034    then determine_prefix on foo's die will return "N::C".  */
20035
20036 static const char *
20037 determine_prefix (struct die_info *die, struct dwarf2_cu *cu)
20038 {
20039   struct die_info *parent, *spec_die;
20040   struct dwarf2_cu *spec_cu;
20041   struct type *parent_type;
20042   const char *retval;
20043
20044   if (cu->language != language_cplus
20045       && cu->language != language_fortran && cu->language != language_d
20046       && cu->language != language_rust)
20047     return "";
20048
20049   retval = anonymous_struct_prefix (die, cu);
20050   if (retval)
20051     return retval;
20052
20053   /* We have to be careful in the presence of DW_AT_specification.
20054      For example, with GCC 3.4, given the code
20055
20056      namespace N {
20057        void foo() {
20058          // Definition of N::foo.
20059        }
20060      }
20061
20062      then we'll have a tree of DIEs like this:
20063
20064      1: DW_TAG_compile_unit
20065        2: DW_TAG_namespace        // N
20066          3: DW_TAG_subprogram     // declaration of N::foo
20067        4: DW_TAG_subprogram       // definition of N::foo
20068             DW_AT_specification   // refers to die #3
20069
20070      Thus, when processing die #4, we have to pretend that we're in
20071      the context of its DW_AT_specification, namely the contex of die
20072      #3.  */
20073   spec_cu = cu;
20074   spec_die = die_specification (die, &spec_cu);
20075   if (spec_die == NULL)
20076     parent = die->parent;
20077   else
20078     {
20079       parent = spec_die->parent;
20080       cu = spec_cu;
20081     }
20082
20083   if (parent == NULL)
20084     return "";
20085   else if (parent->building_fullname)
20086     {
20087       const char *name;
20088       const char *parent_name;
20089
20090       /* It has been seen on RealView 2.2 built binaries,
20091          DW_TAG_template_type_param types actually _defined_ as
20092          children of the parent class:
20093
20094          enum E {};
20095          template class <class Enum> Class{};
20096          Class<enum E> class_e;
20097
20098          1: DW_TAG_class_type (Class)
20099            2: DW_TAG_enumeration_type (E)
20100              3: DW_TAG_enumerator (enum1:0)
20101              3: DW_TAG_enumerator (enum2:1)
20102              ...
20103            2: DW_TAG_template_type_param
20104               DW_AT_type  DW_FORM_ref_udata (E)
20105
20106          Besides being broken debug info, it can put GDB into an
20107          infinite loop.  Consider:
20108
20109          When we're building the full name for Class<E>, we'll start
20110          at Class, and go look over its template type parameters,
20111          finding E.  We'll then try to build the full name of E, and
20112          reach here.  We're now trying to build the full name of E,
20113          and look over the parent DIE for containing scope.  In the
20114          broken case, if we followed the parent DIE of E, we'd again
20115          find Class, and once again go look at its template type
20116          arguments, etc., etc.  Simply don't consider such parent die
20117          as source-level parent of this die (it can't be, the language
20118          doesn't allow it), and break the loop here.  */
20119       name = dwarf2_name (die, cu);
20120       parent_name = dwarf2_name (parent, cu);
20121       complaint (&symfile_complaints,
20122                  _("template param type '%s' defined within parent '%s'"),
20123                  name ? name : "<unknown>",
20124                  parent_name ? parent_name : "<unknown>");
20125       return "";
20126     }
20127   else
20128     switch (parent->tag)
20129       {
20130       case DW_TAG_namespace:
20131         parent_type = read_type_die (parent, cu);
20132         /* GCC 4.0 and 4.1 had a bug (PR c++/28460) where they generated bogus
20133            DW_TAG_namespace DIEs with a name of "::" for the global namespace.
20134            Work around this problem here.  */
20135         if (cu->language == language_cplus
20136             && strcmp (TYPE_TAG_NAME (parent_type), "::") == 0)
20137           return "";
20138         /* We give a name to even anonymous namespaces.  */
20139         return TYPE_TAG_NAME (parent_type);
20140       case DW_TAG_class_type:
20141       case DW_TAG_interface_type:
20142       case DW_TAG_structure_type:
20143       case DW_TAG_union_type:
20144       case DW_TAG_module:
20145         parent_type = read_type_die (parent, cu);
20146         if (TYPE_TAG_NAME (parent_type) != NULL)
20147           return TYPE_TAG_NAME (parent_type);
20148         else
20149           /* An anonymous structure is only allowed non-static data
20150              members; no typedefs, no member functions, et cetera.
20151              So it does not need a prefix.  */
20152           return "";
20153       case DW_TAG_compile_unit:
20154       case DW_TAG_partial_unit:
20155         /* gcc-4.5 -gdwarf-4 can drop the enclosing namespace.  Cope.  */
20156         if (cu->language == language_cplus
20157             && !VEC_empty (dwarf2_section_info_def, dwarf2_per_objfile->types)
20158             && die->child != NULL
20159             && (die->tag == DW_TAG_class_type
20160                 || die->tag == DW_TAG_structure_type
20161                 || die->tag == DW_TAG_union_type))
20162           {
20163             char *name = guess_full_die_structure_name (die, cu);
20164             if (name != NULL)
20165               return name;
20166           }
20167         return "";
20168       case DW_TAG_enumeration_type:
20169         parent_type = read_type_die (parent, cu);
20170         if (TYPE_DECLARED_CLASS (parent_type))
20171           {
20172             if (TYPE_TAG_NAME (parent_type) != NULL)
20173               return TYPE_TAG_NAME (parent_type);
20174             return "";
20175           }
20176         /* Fall through.  */
20177       default:
20178         return determine_prefix (parent, cu);
20179       }
20180 }
20181
20182 /* Return a newly-allocated string formed by concatenating PREFIX and SUFFIX
20183    with appropriate separator.  If PREFIX or SUFFIX is NULL or empty, then
20184    simply copy the SUFFIX or PREFIX, respectively.  If OBS is non-null, perform
20185    an obconcat, otherwise allocate storage for the result.  The CU argument is
20186    used to determine the language and hence, the appropriate separator.  */
20187
20188 #define MAX_SEP_LEN 7  /* strlen ("__") + strlen ("_MOD_")  */
20189
20190 static char *
20191 typename_concat (struct obstack *obs, const char *prefix, const char *suffix,
20192                  int physname, struct dwarf2_cu *cu)
20193 {
20194   const char *lead = "";
20195   const char *sep;
20196
20197   if (suffix == NULL || suffix[0] == '\0'
20198       || prefix == NULL || prefix[0] == '\0')
20199     sep = "";
20200   else if (cu->language == language_d)
20201     {
20202       /* For D, the 'main' function could be defined in any module, but it
20203          should never be prefixed.  */
20204       if (strcmp (suffix, "D main") == 0)
20205         {
20206           prefix = "";
20207           sep = "";
20208         }
20209       else
20210         sep = ".";
20211     }
20212   else if (cu->language == language_fortran && physname)
20213     {
20214       /* This is gfortran specific mangling.  Normally DW_AT_linkage_name or
20215          DW_AT_MIPS_linkage_name is preferred and used instead.  */
20216
20217       lead = "__";
20218       sep = "_MOD_";
20219     }
20220   else
20221     sep = "::";
20222
20223   if (prefix == NULL)
20224     prefix = "";
20225   if (suffix == NULL)
20226     suffix = "";
20227
20228   if (obs == NULL)
20229     {
20230       char *retval
20231         = ((char *)
20232            xmalloc (strlen (prefix) + MAX_SEP_LEN + strlen (suffix) + 1));
20233
20234       strcpy (retval, lead);
20235       strcat (retval, prefix);
20236       strcat (retval, sep);
20237       strcat (retval, suffix);
20238       return retval;
20239     }
20240   else
20241     {
20242       /* We have an obstack.  */
20243       return obconcat (obs, lead, prefix, sep, suffix, (char *) NULL);
20244     }
20245 }
20246
20247 /* Return sibling of die, NULL if no sibling.  */
20248
20249 static struct die_info *
20250 sibling_die (struct die_info *die)
20251 {
20252   return die->sibling;
20253 }
20254
20255 /* Get name of a die, return NULL if not found.  */
20256
20257 static const char *
20258 dwarf2_canonicalize_name (const char *name, struct dwarf2_cu *cu,
20259                           struct obstack *obstack)
20260 {
20261   if (name && cu->language == language_cplus)
20262     {
20263       std::string canon_name = cp_canonicalize_string (name);
20264
20265       if (!canon_name.empty ())
20266         {
20267           if (canon_name != name)
20268             name = (const char *) obstack_copy0 (obstack,
20269                                                  canon_name.c_str (),
20270                                                  canon_name.length ());
20271         }
20272     }
20273
20274   return name;
20275 }
20276
20277 /* Get name of a die, return NULL if not found.
20278    Anonymous namespaces are converted to their magic string.  */
20279
20280 static const char *
20281 dwarf2_name (struct die_info *die, struct dwarf2_cu *cu)
20282 {
20283   struct attribute *attr;
20284
20285   attr = dwarf2_attr (die, DW_AT_name, cu);
20286   if ((!attr || !DW_STRING (attr))
20287       && die->tag != DW_TAG_namespace
20288       && die->tag != DW_TAG_class_type
20289       && die->tag != DW_TAG_interface_type
20290       && die->tag != DW_TAG_structure_type
20291       && die->tag != DW_TAG_union_type)
20292     return NULL;
20293
20294   switch (die->tag)
20295     {
20296     case DW_TAG_compile_unit:
20297     case DW_TAG_partial_unit:
20298       /* Compilation units have a DW_AT_name that is a filename, not
20299          a source language identifier.  */
20300     case DW_TAG_enumeration_type:
20301     case DW_TAG_enumerator:
20302       /* These tags always have simple identifiers already; no need
20303          to canonicalize them.  */
20304       return DW_STRING (attr);
20305
20306     case DW_TAG_namespace:
20307       if (attr != NULL && DW_STRING (attr) != NULL)
20308         return DW_STRING (attr);
20309       return CP_ANONYMOUS_NAMESPACE_STR;
20310
20311     case DW_TAG_class_type:
20312     case DW_TAG_interface_type:
20313     case DW_TAG_structure_type:
20314     case DW_TAG_union_type:
20315       /* Some GCC versions emit spurious DW_AT_name attributes for unnamed
20316          structures or unions.  These were of the form "._%d" in GCC 4.1,
20317          or simply "<anonymous struct>" or "<anonymous union>" in GCC 4.3
20318          and GCC 4.4.  We work around this problem by ignoring these.  */
20319       if (attr && DW_STRING (attr)
20320           && (startswith (DW_STRING (attr), "._")
20321               || startswith (DW_STRING (attr), "<anonymous")))
20322         return NULL;
20323
20324       /* GCC might emit a nameless typedef that has a linkage name.  See
20325          http://gcc.gnu.org/bugzilla/show_bug.cgi?id=47510.  */
20326       if (!attr || DW_STRING (attr) == NULL)
20327         {
20328           char *demangled = NULL;
20329
20330           attr = dw2_linkage_name_attr (die, cu);
20331           if (attr == NULL || DW_STRING (attr) == NULL)
20332             return NULL;
20333
20334           /* Avoid demangling DW_STRING (attr) the second time on a second
20335              call for the same DIE.  */
20336           if (!DW_STRING_IS_CANONICAL (attr))
20337             demangled = gdb_demangle (DW_STRING (attr), DMGL_TYPES);
20338
20339           if (demangled)
20340             {
20341               const char *base;
20342
20343               /* FIXME: we already did this for the partial symbol... */
20344               DW_STRING (attr)
20345                 = ((const char *)
20346                    obstack_copy0 (&cu->objfile->per_bfd->storage_obstack,
20347                                   demangled, strlen (demangled)));
20348               DW_STRING_IS_CANONICAL (attr) = 1;
20349               xfree (demangled);
20350
20351               /* Strip any leading namespaces/classes, keep only the base name.
20352                  DW_AT_name for named DIEs does not contain the prefixes.  */
20353               base = strrchr (DW_STRING (attr), ':');
20354               if (base && base > DW_STRING (attr) && base[-1] == ':')
20355                 return &base[1];
20356               else
20357                 return DW_STRING (attr);
20358             }
20359         }
20360       break;
20361
20362     default:
20363       break;
20364     }
20365
20366   if (!DW_STRING_IS_CANONICAL (attr))
20367     {
20368       DW_STRING (attr)
20369         = dwarf2_canonicalize_name (DW_STRING (attr), cu,
20370                                     &cu->objfile->per_bfd->storage_obstack);
20371       DW_STRING_IS_CANONICAL (attr) = 1;
20372     }
20373   return DW_STRING (attr);
20374 }
20375
20376 /* Return the die that this die in an extension of, or NULL if there
20377    is none.  *EXT_CU is the CU containing DIE on input, and the CU
20378    containing the return value on output.  */
20379
20380 static struct die_info *
20381 dwarf2_extension (struct die_info *die, struct dwarf2_cu **ext_cu)
20382 {
20383   struct attribute *attr;
20384
20385   attr = dwarf2_attr (die, DW_AT_extension, *ext_cu);
20386   if (attr == NULL)
20387     return NULL;
20388
20389   return follow_die_ref (die, attr, ext_cu);
20390 }
20391
20392 /* Convert a DIE tag into its string name.  */
20393
20394 static const char *
20395 dwarf_tag_name (unsigned tag)
20396 {
20397   const char *name = get_DW_TAG_name (tag);
20398
20399   if (name == NULL)
20400     return "DW_TAG_<unknown>";
20401
20402   return name;
20403 }
20404
20405 /* Convert a DWARF attribute code into its string name.  */
20406
20407 static const char *
20408 dwarf_attr_name (unsigned attr)
20409 {
20410   const char *name;
20411
20412 #ifdef MIPS /* collides with DW_AT_HP_block_index */
20413   if (attr == DW_AT_MIPS_fde)
20414     return "DW_AT_MIPS_fde";
20415 #else
20416   if (attr == DW_AT_HP_block_index)
20417     return "DW_AT_HP_block_index";
20418 #endif
20419
20420   name = get_DW_AT_name (attr);
20421
20422   if (name == NULL)
20423     return "DW_AT_<unknown>";
20424
20425   return name;
20426 }
20427
20428 /* Convert a DWARF value form code into its string name.  */
20429
20430 static const char *
20431 dwarf_form_name (unsigned form)
20432 {
20433   const char *name = get_DW_FORM_name (form);
20434
20435   if (name == NULL)
20436     return "DW_FORM_<unknown>";
20437
20438   return name;
20439 }
20440
20441 static const char *
20442 dwarf_bool_name (unsigned mybool)
20443 {
20444   if (mybool)
20445     return "TRUE";
20446   else
20447     return "FALSE";
20448 }
20449
20450 /* Convert a DWARF type code into its string name.  */
20451
20452 static const char *
20453 dwarf_type_encoding_name (unsigned enc)
20454 {
20455   const char *name = get_DW_ATE_name (enc);
20456
20457   if (name == NULL)
20458     return "DW_ATE_<unknown>";
20459
20460   return name;
20461 }
20462
20463 static void
20464 dump_die_shallow (struct ui_file *f, int indent, struct die_info *die)
20465 {
20466   unsigned int i;
20467
20468   print_spaces (indent, f);
20469   fprintf_unfiltered (f, "Die: %s (abbrev %d, offset 0x%x)\n",
20470                       dwarf_tag_name (die->tag), die->abbrev,
20471                       to_underlying (die->sect_off));
20472
20473   if (die->parent != NULL)
20474     {
20475       print_spaces (indent, f);
20476       fprintf_unfiltered (f, "  parent at offset: 0x%x\n",
20477                           to_underlying (die->parent->sect_off));
20478     }
20479
20480   print_spaces (indent, f);
20481   fprintf_unfiltered (f, "  has children: %s\n",
20482            dwarf_bool_name (die->child != NULL));
20483
20484   print_spaces (indent, f);
20485   fprintf_unfiltered (f, "  attributes:\n");
20486
20487   for (i = 0; i < die->num_attrs; ++i)
20488     {
20489       print_spaces (indent, f);
20490       fprintf_unfiltered (f, "    %s (%s) ",
20491                dwarf_attr_name (die->attrs[i].name),
20492                dwarf_form_name (die->attrs[i].form));
20493
20494       switch (die->attrs[i].form)
20495         {
20496         case DW_FORM_addr:
20497         case DW_FORM_GNU_addr_index:
20498           fprintf_unfiltered (f, "address: ");
20499           fputs_filtered (hex_string (DW_ADDR (&die->attrs[i])), f);
20500           break;
20501         case DW_FORM_block2:
20502         case DW_FORM_block4:
20503         case DW_FORM_block:
20504         case DW_FORM_block1:
20505           fprintf_unfiltered (f, "block: size %s",
20506                               pulongest (DW_BLOCK (&die->attrs[i])->size));
20507           break;
20508         case DW_FORM_exprloc:
20509           fprintf_unfiltered (f, "expression: size %s",
20510                               pulongest (DW_BLOCK (&die->attrs[i])->size));
20511           break;
20512         case DW_FORM_data16:
20513           fprintf_unfiltered (f, "constant of 16 bytes");
20514           break;
20515         case DW_FORM_ref_addr:
20516           fprintf_unfiltered (f, "ref address: ");
20517           fputs_filtered (hex_string (DW_UNSND (&die->attrs[i])), f);
20518           break;
20519         case DW_FORM_GNU_ref_alt:
20520           fprintf_unfiltered (f, "alt ref address: ");
20521           fputs_filtered (hex_string (DW_UNSND (&die->attrs[i])), f);
20522           break;
20523         case DW_FORM_ref1:
20524         case DW_FORM_ref2:
20525         case DW_FORM_ref4:
20526         case DW_FORM_ref8:
20527         case DW_FORM_ref_udata:
20528           fprintf_unfiltered (f, "constant ref: 0x%lx (adjusted)",
20529                               (long) (DW_UNSND (&die->attrs[i])));
20530           break;
20531         case DW_FORM_data1:
20532         case DW_FORM_data2:
20533         case DW_FORM_data4:
20534         case DW_FORM_data8:
20535         case DW_FORM_udata:
20536         case DW_FORM_sdata:
20537           fprintf_unfiltered (f, "constant: %s",
20538                               pulongest (DW_UNSND (&die->attrs[i])));
20539           break;
20540         case DW_FORM_sec_offset:
20541           fprintf_unfiltered (f, "section offset: %s",
20542                               pulongest (DW_UNSND (&die->attrs[i])));
20543           break;
20544         case DW_FORM_ref_sig8:
20545           fprintf_unfiltered (f, "signature: %s",
20546                               hex_string (DW_SIGNATURE (&die->attrs[i])));
20547           break;
20548         case DW_FORM_string:
20549         case DW_FORM_strp:
20550         case DW_FORM_line_strp:
20551         case DW_FORM_GNU_str_index:
20552         case DW_FORM_GNU_strp_alt:
20553           fprintf_unfiltered (f, "string: \"%s\" (%s canonicalized)",
20554                    DW_STRING (&die->attrs[i])
20555                    ? DW_STRING (&die->attrs[i]) : "",
20556                    DW_STRING_IS_CANONICAL (&die->attrs[i]) ? "is" : "not");
20557           break;
20558         case DW_FORM_flag:
20559           if (DW_UNSND (&die->attrs[i]))
20560             fprintf_unfiltered (f, "flag: TRUE");
20561           else
20562             fprintf_unfiltered (f, "flag: FALSE");
20563           break;
20564         case DW_FORM_flag_present:
20565           fprintf_unfiltered (f, "flag: TRUE");
20566           break;
20567         case DW_FORM_indirect:
20568           /* The reader will have reduced the indirect form to
20569              the "base form" so this form should not occur.  */
20570           fprintf_unfiltered (f, 
20571                               "unexpected attribute form: DW_FORM_indirect");
20572           break;
20573         case DW_FORM_implicit_const:
20574           fprintf_unfiltered (f, "constant: %s",
20575                               plongest (DW_SND (&die->attrs[i])));
20576           break;
20577         default:
20578           fprintf_unfiltered (f, "unsupported attribute form: %d.",
20579                    die->attrs[i].form);
20580           break;
20581         }
20582       fprintf_unfiltered (f, "\n");
20583     }
20584 }
20585
20586 static void
20587 dump_die_for_error (struct die_info *die)
20588 {
20589   dump_die_shallow (gdb_stderr, 0, die);
20590 }
20591
20592 static void
20593 dump_die_1 (struct ui_file *f, int level, int max_level, struct die_info *die)
20594 {
20595   int indent = level * 4;
20596
20597   gdb_assert (die != NULL);
20598
20599   if (level >= max_level)
20600     return;
20601
20602   dump_die_shallow (f, indent, die);
20603
20604   if (die->child != NULL)
20605     {
20606       print_spaces (indent, f);
20607       fprintf_unfiltered (f, "  Children:");
20608       if (level + 1 < max_level)
20609         {
20610           fprintf_unfiltered (f, "\n");
20611           dump_die_1 (f, level + 1, max_level, die->child);
20612         }
20613       else
20614         {
20615           fprintf_unfiltered (f,
20616                               " [not printed, max nesting level reached]\n");
20617         }
20618     }
20619
20620   if (die->sibling != NULL && level > 0)
20621     {
20622       dump_die_1 (f, level, max_level, die->sibling);
20623     }
20624 }
20625
20626 /* This is called from the pdie macro in gdbinit.in.
20627    It's not static so gcc will keep a copy callable from gdb.  */
20628
20629 void
20630 dump_die (struct die_info *die, int max_level)
20631 {
20632   dump_die_1 (gdb_stdlog, 0, max_level, die);
20633 }
20634
20635 static void
20636 store_in_ref_table (struct die_info *die, struct dwarf2_cu *cu)
20637 {
20638   void **slot;
20639
20640   slot = htab_find_slot_with_hash (cu->die_hash, die,
20641                                    to_underlying (die->sect_off),
20642                                    INSERT);
20643
20644   *slot = die;
20645 }
20646
20647 /* Return DIE offset of ATTR.  Return 0 with complaint if ATTR is not of the
20648    required kind.  */
20649
20650 static sect_offset
20651 dwarf2_get_ref_die_offset (const struct attribute *attr)
20652 {
20653   if (attr_form_is_ref (attr))
20654     return (sect_offset) DW_UNSND (attr);
20655
20656   complaint (&symfile_complaints,
20657              _("unsupported die ref attribute form: '%s'"),
20658              dwarf_form_name (attr->form));
20659   return {};
20660 }
20661
20662 /* Return the constant value held by ATTR.  Return DEFAULT_VALUE if
20663  * the value held by the attribute is not constant.  */
20664
20665 static LONGEST
20666 dwarf2_get_attr_constant_value (const struct attribute *attr, int default_value)
20667 {
20668   if (attr->form == DW_FORM_sdata || attr->form == DW_FORM_implicit_const)
20669     return DW_SND (attr);
20670   else if (attr->form == DW_FORM_udata
20671            || attr->form == DW_FORM_data1
20672            || attr->form == DW_FORM_data2
20673            || attr->form == DW_FORM_data4
20674            || attr->form == DW_FORM_data8)
20675     return DW_UNSND (attr);
20676   else
20677     {
20678       /* For DW_FORM_data16 see attr_form_is_constant.  */
20679       complaint (&symfile_complaints,
20680                  _("Attribute value is not a constant (%s)"),
20681                  dwarf_form_name (attr->form));
20682       return default_value;
20683     }
20684 }
20685
20686 /* Follow reference or signature attribute ATTR of SRC_DIE.
20687    On entry *REF_CU is the CU of SRC_DIE.
20688    On exit *REF_CU is the CU of the result.  */
20689
20690 static struct die_info *
20691 follow_die_ref_or_sig (struct die_info *src_die, const struct attribute *attr,
20692                        struct dwarf2_cu **ref_cu)
20693 {
20694   struct die_info *die;
20695
20696   if (attr_form_is_ref (attr))
20697     die = follow_die_ref (src_die, attr, ref_cu);
20698   else if (attr->form == DW_FORM_ref_sig8)
20699     die = follow_die_sig (src_die, attr, ref_cu);
20700   else
20701     {
20702       dump_die_for_error (src_die);
20703       error (_("Dwarf Error: Expected reference attribute [in module %s]"),
20704              objfile_name ((*ref_cu)->objfile));
20705     }
20706
20707   return die;
20708 }
20709
20710 /* Follow reference OFFSET.
20711    On entry *REF_CU is the CU of the source die referencing OFFSET.
20712    On exit *REF_CU is the CU of the result.
20713    Returns NULL if OFFSET is invalid.  */
20714
20715 static struct die_info *
20716 follow_die_offset (sect_offset sect_off, int offset_in_dwz,
20717                    struct dwarf2_cu **ref_cu)
20718 {
20719   struct die_info temp_die;
20720   struct dwarf2_cu *target_cu, *cu = *ref_cu;
20721
20722   gdb_assert (cu->per_cu != NULL);
20723
20724   target_cu = cu;
20725
20726   if (cu->per_cu->is_debug_types)
20727     {
20728       /* .debug_types CUs cannot reference anything outside their CU.
20729          If they need to, they have to reference a signatured type via
20730          DW_FORM_ref_sig8.  */
20731       if (!offset_in_cu_p (&cu->header, sect_off))
20732         return NULL;
20733     }
20734   else if (offset_in_dwz != cu->per_cu->is_dwz
20735            || !offset_in_cu_p (&cu->header, sect_off))
20736     {
20737       struct dwarf2_per_cu_data *per_cu;
20738
20739       per_cu = dwarf2_find_containing_comp_unit (sect_off, offset_in_dwz,
20740                                                  cu->objfile);
20741
20742       /* If necessary, add it to the queue and load its DIEs.  */
20743       if (maybe_queue_comp_unit (cu, per_cu, cu->language))
20744         load_full_comp_unit (per_cu, cu->language);
20745
20746       target_cu = per_cu->cu;
20747     }
20748   else if (cu->dies == NULL)
20749     {
20750       /* We're loading full DIEs during partial symbol reading.  */
20751       gdb_assert (dwarf2_per_objfile->reading_partial_symbols);
20752       load_full_comp_unit (cu->per_cu, language_minimal);
20753     }
20754
20755   *ref_cu = target_cu;
20756   temp_die.sect_off = sect_off;
20757   return (struct die_info *) htab_find_with_hash (target_cu->die_hash,
20758                                                   &temp_die,
20759                                                   to_underlying (sect_off));
20760 }
20761
20762 /* Follow reference attribute ATTR of SRC_DIE.
20763    On entry *REF_CU is the CU of SRC_DIE.
20764    On exit *REF_CU is the CU of the result.  */
20765
20766 static struct die_info *
20767 follow_die_ref (struct die_info *src_die, const struct attribute *attr,
20768                 struct dwarf2_cu **ref_cu)
20769 {
20770   sect_offset sect_off = dwarf2_get_ref_die_offset (attr);
20771   struct dwarf2_cu *cu = *ref_cu;
20772   struct die_info *die;
20773
20774   die = follow_die_offset (sect_off,
20775                            (attr->form == DW_FORM_GNU_ref_alt
20776                             || cu->per_cu->is_dwz),
20777                            ref_cu);
20778   if (!die)
20779     error (_("Dwarf Error: Cannot find DIE at 0x%x referenced from DIE "
20780            "at 0x%x [in module %s]"),
20781            to_underlying (sect_off), to_underlying (src_die->sect_off),
20782            objfile_name (cu->objfile));
20783
20784   return die;
20785 }
20786
20787 /* Return DWARF block referenced by DW_AT_location of DIE at SECT_OFF at PER_CU.
20788    Returned value is intended for DW_OP_call*.  Returned
20789    dwarf2_locexpr_baton->data has lifetime of PER_CU->OBJFILE.  */
20790
20791 struct dwarf2_locexpr_baton
20792 dwarf2_fetch_die_loc_sect_off (sect_offset sect_off,
20793                                struct dwarf2_per_cu_data *per_cu,
20794                                CORE_ADDR (*get_frame_pc) (void *baton),
20795                                void *baton)
20796 {
20797   struct dwarf2_cu *cu;
20798   struct die_info *die;
20799   struct attribute *attr;
20800   struct dwarf2_locexpr_baton retval;
20801
20802   dw2_setup (per_cu->objfile);
20803
20804   if (per_cu->cu == NULL)
20805     load_cu (per_cu);
20806   cu = per_cu->cu;
20807   if (cu == NULL)
20808     {
20809       /* We shouldn't get here for a dummy CU, but don't crash on the user.
20810          Instead just throw an error, not much else we can do.  */
20811       error (_("Dwarf Error: Dummy CU at 0x%x referenced in module %s"),
20812              to_underlying (sect_off), objfile_name (per_cu->objfile));
20813     }
20814
20815   die = follow_die_offset (sect_off, per_cu->is_dwz, &cu);
20816   if (!die)
20817     error (_("Dwarf Error: Cannot find DIE at 0x%x referenced in module %s"),
20818            to_underlying (sect_off), objfile_name (per_cu->objfile));
20819
20820   attr = dwarf2_attr (die, DW_AT_location, cu);
20821   if (!attr)
20822     {
20823       /* DWARF: "If there is no such attribute, then there is no effect.".
20824          DATA is ignored if SIZE is 0.  */
20825
20826       retval.data = NULL;
20827       retval.size = 0;
20828     }
20829   else if (attr_form_is_section_offset (attr))
20830     {
20831       struct dwarf2_loclist_baton loclist_baton;
20832       CORE_ADDR pc = (*get_frame_pc) (baton);
20833       size_t size;
20834
20835       fill_in_loclist_baton (cu, &loclist_baton, attr);
20836
20837       retval.data = dwarf2_find_location_expression (&loclist_baton,
20838                                                      &size, pc);
20839       retval.size = size;
20840     }
20841   else
20842     {
20843       if (!attr_form_is_block (attr))
20844         error (_("Dwarf Error: DIE at 0x%x referenced in module %s "
20845                  "is neither DW_FORM_block* nor DW_FORM_exprloc"),
20846                to_underlying (sect_off), objfile_name (per_cu->objfile));
20847
20848       retval.data = DW_BLOCK (attr)->data;
20849       retval.size = DW_BLOCK (attr)->size;
20850     }
20851   retval.per_cu = cu->per_cu;
20852
20853   age_cached_comp_units ();
20854
20855   return retval;
20856 }
20857
20858 /* Like dwarf2_fetch_die_loc_sect_off, but take a CU
20859    offset.  */
20860
20861 struct dwarf2_locexpr_baton
20862 dwarf2_fetch_die_loc_cu_off (cu_offset offset_in_cu,
20863                              struct dwarf2_per_cu_data *per_cu,
20864                              CORE_ADDR (*get_frame_pc) (void *baton),
20865                              void *baton)
20866 {
20867   sect_offset sect_off = per_cu->sect_off + to_underlying (offset_in_cu);
20868
20869   return dwarf2_fetch_die_loc_sect_off (sect_off, per_cu, get_frame_pc, baton);
20870 }
20871
20872 /* Write a constant of a given type as target-ordered bytes into
20873    OBSTACK.  */
20874
20875 static const gdb_byte *
20876 write_constant_as_bytes (struct obstack *obstack,
20877                          enum bfd_endian byte_order,
20878                          struct type *type,
20879                          ULONGEST value,
20880                          LONGEST *len)
20881 {
20882   gdb_byte *result;
20883
20884   *len = TYPE_LENGTH (type);
20885   result = (gdb_byte *) obstack_alloc (obstack, *len);
20886   store_unsigned_integer (result, *len, byte_order, value);
20887
20888   return result;
20889 }
20890
20891 /* If the DIE at OFFSET in PER_CU has a DW_AT_const_value, return a
20892    pointer to the constant bytes and set LEN to the length of the
20893    data.  If memory is needed, allocate it on OBSTACK.  If the DIE
20894    does not have a DW_AT_const_value, return NULL.  */
20895
20896 const gdb_byte *
20897 dwarf2_fetch_constant_bytes (sect_offset sect_off,
20898                              struct dwarf2_per_cu_data *per_cu,
20899                              struct obstack *obstack,
20900                              LONGEST *len)
20901 {
20902   struct dwarf2_cu *cu;
20903   struct die_info *die;
20904   struct attribute *attr;
20905   const gdb_byte *result = NULL;
20906   struct type *type;
20907   LONGEST value;
20908   enum bfd_endian byte_order;
20909
20910   dw2_setup (per_cu->objfile);
20911
20912   if (per_cu->cu == NULL)
20913     load_cu (per_cu);
20914   cu = per_cu->cu;
20915   if (cu == NULL)
20916     {
20917       /* We shouldn't get here for a dummy CU, but don't crash on the user.
20918          Instead just throw an error, not much else we can do.  */
20919       error (_("Dwarf Error: Dummy CU at 0x%x referenced in module %s"),
20920              to_underlying (sect_off), objfile_name (per_cu->objfile));
20921     }
20922
20923   die = follow_die_offset (sect_off, per_cu->is_dwz, &cu);
20924   if (!die)
20925     error (_("Dwarf Error: Cannot find DIE at 0x%x referenced in module %s"),
20926            to_underlying (sect_off), objfile_name (per_cu->objfile));
20927
20928
20929   attr = dwarf2_attr (die, DW_AT_const_value, cu);
20930   if (attr == NULL)
20931     return NULL;
20932
20933   byte_order = (bfd_big_endian (per_cu->objfile->obfd)
20934                 ? BFD_ENDIAN_BIG : BFD_ENDIAN_LITTLE);
20935
20936   switch (attr->form)
20937     {
20938     case DW_FORM_addr:
20939     case DW_FORM_GNU_addr_index:
20940       {
20941         gdb_byte *tem;
20942
20943         *len = cu->header.addr_size;
20944         tem = (gdb_byte *) obstack_alloc (obstack, *len);
20945         store_unsigned_integer (tem, *len, byte_order, DW_ADDR (attr));
20946         result = tem;
20947       }
20948       break;
20949     case DW_FORM_string:
20950     case DW_FORM_strp:
20951     case DW_FORM_GNU_str_index:
20952     case DW_FORM_GNU_strp_alt:
20953       /* DW_STRING is already allocated on the objfile obstack, point
20954          directly to it.  */
20955       result = (const gdb_byte *) DW_STRING (attr);
20956       *len = strlen (DW_STRING (attr));
20957       break;
20958     case DW_FORM_block1:
20959     case DW_FORM_block2:
20960     case DW_FORM_block4:
20961     case DW_FORM_block:
20962     case DW_FORM_exprloc:
20963     case DW_FORM_data16:
20964       result = DW_BLOCK (attr)->data;
20965       *len = DW_BLOCK (attr)->size;
20966       break;
20967
20968       /* The DW_AT_const_value attributes are supposed to carry the
20969          symbol's value "represented as it would be on the target
20970          architecture."  By the time we get here, it's already been
20971          converted to host endianness, so we just need to sign- or
20972          zero-extend it as appropriate.  */
20973     case DW_FORM_data1:
20974       type = die_type (die, cu);
20975       result = dwarf2_const_value_data (attr, obstack, cu, &value, 8);
20976       if (result == NULL)
20977         result = write_constant_as_bytes (obstack, byte_order,
20978                                           type, value, len);
20979       break;
20980     case DW_FORM_data2:
20981       type = die_type (die, cu);
20982       result = dwarf2_const_value_data (attr, obstack, cu, &value, 16);
20983       if (result == NULL)
20984         result = write_constant_as_bytes (obstack, byte_order,
20985                                           type, value, len);
20986       break;
20987     case DW_FORM_data4:
20988       type = die_type (die, cu);
20989       result = dwarf2_const_value_data (attr, obstack, cu, &value, 32);
20990       if (result == NULL)
20991         result = write_constant_as_bytes (obstack, byte_order,
20992                                           type, value, len);
20993       break;
20994     case DW_FORM_data8:
20995       type = die_type (die, cu);
20996       result = dwarf2_const_value_data (attr, obstack, cu, &value, 64);
20997       if (result == NULL)
20998         result = write_constant_as_bytes (obstack, byte_order,
20999                                           type, value, len);
21000       break;
21001
21002     case DW_FORM_sdata:
21003     case DW_FORM_implicit_const:
21004       type = die_type (die, cu);
21005       result = write_constant_as_bytes (obstack, byte_order,
21006                                         type, DW_SND (attr), len);
21007       break;
21008
21009     case DW_FORM_udata:
21010       type = die_type (die, cu);
21011       result = write_constant_as_bytes (obstack, byte_order,
21012                                         type, DW_UNSND (attr), len);
21013       break;
21014
21015     default:
21016       complaint (&symfile_complaints,
21017                  _("unsupported const value attribute form: '%s'"),
21018                  dwarf_form_name (attr->form));
21019       break;
21020     }
21021
21022   return result;
21023 }
21024
21025 /* Return the type of the die at OFFSET in PER_CU.  Return NULL if no
21026    valid type for this die is found.  */
21027
21028 struct type *
21029 dwarf2_fetch_die_type_sect_off (sect_offset sect_off,
21030                                 struct dwarf2_per_cu_data *per_cu)
21031 {
21032   struct dwarf2_cu *cu;
21033   struct die_info *die;
21034
21035   dw2_setup (per_cu->objfile);
21036
21037   if (per_cu->cu == NULL)
21038     load_cu (per_cu);
21039   cu = per_cu->cu;
21040   if (!cu)
21041     return NULL;
21042
21043   die = follow_die_offset (sect_off, per_cu->is_dwz, &cu);
21044   if (!die)
21045     return NULL;
21046
21047   return die_type (die, cu);
21048 }
21049
21050 /* Return the type of the DIE at DIE_OFFSET in the CU named by
21051    PER_CU.  */
21052
21053 struct type *
21054 dwarf2_get_die_type (cu_offset die_offset,
21055                      struct dwarf2_per_cu_data *per_cu)
21056 {
21057   dw2_setup (per_cu->objfile);
21058
21059   sect_offset die_offset_sect = per_cu->sect_off + to_underlying (die_offset);
21060   return get_die_type_at_offset (die_offset_sect, per_cu);
21061 }
21062
21063 /* Follow type unit SIG_TYPE referenced by SRC_DIE.
21064    On entry *REF_CU is the CU of SRC_DIE.
21065    On exit *REF_CU is the CU of the result.
21066    Returns NULL if the referenced DIE isn't found.  */
21067
21068 static struct die_info *
21069 follow_die_sig_1 (struct die_info *src_die, struct signatured_type *sig_type,
21070                   struct dwarf2_cu **ref_cu)
21071 {
21072   struct die_info temp_die;
21073   struct dwarf2_cu *sig_cu;
21074   struct die_info *die;
21075
21076   /* While it might be nice to assert sig_type->type == NULL here,
21077      we can get here for DW_AT_imported_declaration where we need
21078      the DIE not the type.  */
21079
21080   /* If necessary, add it to the queue and load its DIEs.  */
21081
21082   if (maybe_queue_comp_unit (*ref_cu, &sig_type->per_cu, language_minimal))
21083     read_signatured_type (sig_type);
21084
21085   sig_cu = sig_type->per_cu.cu;
21086   gdb_assert (sig_cu != NULL);
21087   gdb_assert (to_underlying (sig_type->type_offset_in_section) != 0);
21088   temp_die.sect_off = sig_type->type_offset_in_section;
21089   die = (struct die_info *) htab_find_with_hash (sig_cu->die_hash, &temp_die,
21090                                                  to_underlying (temp_die.sect_off));
21091   if (die)
21092     {
21093       /* For .gdb_index version 7 keep track of included TUs.
21094          http://sourceware.org/bugzilla/show_bug.cgi?id=15021.  */
21095       if (dwarf2_per_objfile->index_table != NULL
21096           && dwarf2_per_objfile->index_table->version <= 7)
21097         {
21098           VEC_safe_push (dwarf2_per_cu_ptr,
21099                          (*ref_cu)->per_cu->imported_symtabs,
21100                          sig_cu->per_cu);
21101         }
21102
21103       *ref_cu = sig_cu;
21104       return die;
21105     }
21106
21107   return NULL;
21108 }
21109
21110 /* Follow signatured type referenced by ATTR in SRC_DIE.
21111    On entry *REF_CU is the CU of SRC_DIE.
21112    On exit *REF_CU is the CU of the result.
21113    The result is the DIE of the type.
21114    If the referenced type cannot be found an error is thrown.  */
21115
21116 static struct die_info *
21117 follow_die_sig (struct die_info *src_die, const struct attribute *attr,
21118                 struct dwarf2_cu **ref_cu)
21119 {
21120   ULONGEST signature = DW_SIGNATURE (attr);
21121   struct signatured_type *sig_type;
21122   struct die_info *die;
21123
21124   gdb_assert (attr->form == DW_FORM_ref_sig8);
21125
21126   sig_type = lookup_signatured_type (*ref_cu, signature);
21127   /* sig_type will be NULL if the signatured type is missing from
21128      the debug info.  */
21129   if (sig_type == NULL)
21130     {
21131       error (_("Dwarf Error: Cannot find signatured DIE %s referenced"
21132                " from DIE at 0x%x [in module %s]"),
21133              hex_string (signature), to_underlying (src_die->sect_off),
21134              objfile_name ((*ref_cu)->objfile));
21135     }
21136
21137   die = follow_die_sig_1 (src_die, sig_type, ref_cu);
21138   if (die == NULL)
21139     {
21140       dump_die_for_error (src_die);
21141       error (_("Dwarf Error: Problem reading signatured DIE %s referenced"
21142                " from DIE at 0x%x [in module %s]"),
21143              hex_string (signature), to_underlying (src_die->sect_off),
21144              objfile_name ((*ref_cu)->objfile));
21145     }
21146
21147   return die;
21148 }
21149
21150 /* Get the type specified by SIGNATURE referenced in DIE/CU,
21151    reading in and processing the type unit if necessary.  */
21152
21153 static struct type *
21154 get_signatured_type (struct die_info *die, ULONGEST signature,
21155                      struct dwarf2_cu *cu)
21156 {
21157   struct signatured_type *sig_type;
21158   struct dwarf2_cu *type_cu;
21159   struct die_info *type_die;
21160   struct type *type;
21161
21162   sig_type = lookup_signatured_type (cu, signature);
21163   /* sig_type will be NULL if the signatured type is missing from
21164      the debug info.  */
21165   if (sig_type == NULL)
21166     {
21167       complaint (&symfile_complaints,
21168                  _("Dwarf Error: Cannot find signatured DIE %s referenced"
21169                    " from DIE at 0x%x [in module %s]"),
21170                  hex_string (signature), to_underlying (die->sect_off),
21171                  objfile_name (dwarf2_per_objfile->objfile));
21172       return build_error_marker_type (cu, die);
21173     }
21174
21175   /* If we already know the type we're done.  */
21176   if (sig_type->type != NULL)
21177     return sig_type->type;
21178
21179   type_cu = cu;
21180   type_die = follow_die_sig_1 (die, sig_type, &type_cu);
21181   if (type_die != NULL)
21182     {
21183       /* N.B. We need to call get_die_type to ensure only one type for this DIE
21184          is created.  This is important, for example, because for c++ classes
21185          we need TYPE_NAME set which is only done by new_symbol.  Blech.  */
21186       type = read_type_die (type_die, type_cu);
21187       if (type == NULL)
21188         {
21189           complaint (&symfile_complaints,
21190                      _("Dwarf Error: Cannot build signatured type %s"
21191                        " referenced from DIE at 0x%x [in module %s]"),
21192                      hex_string (signature), to_underlying (die->sect_off),
21193                      objfile_name (dwarf2_per_objfile->objfile));
21194           type = build_error_marker_type (cu, die);
21195         }
21196     }
21197   else
21198     {
21199       complaint (&symfile_complaints,
21200                  _("Dwarf Error: Problem reading signatured DIE %s referenced"
21201                    " from DIE at 0x%x [in module %s]"),
21202                  hex_string (signature), to_underlying (die->sect_off),
21203                  objfile_name (dwarf2_per_objfile->objfile));
21204       type = build_error_marker_type (cu, die);
21205     }
21206   sig_type->type = type;
21207
21208   return type;
21209 }
21210
21211 /* Get the type specified by the DW_AT_signature ATTR in DIE/CU,
21212    reading in and processing the type unit if necessary.  */
21213
21214 static struct type *
21215 get_DW_AT_signature_type (struct die_info *die, const struct attribute *attr,
21216                           struct dwarf2_cu *cu) /* ARI: editCase function */
21217 {
21218   /* Yes, DW_AT_signature can use a non-ref_sig8 reference.  */
21219   if (attr_form_is_ref (attr))
21220     {
21221       struct dwarf2_cu *type_cu = cu;
21222       struct die_info *type_die = follow_die_ref (die, attr, &type_cu);
21223
21224       return read_type_die (type_die, type_cu);
21225     }
21226   else if (attr->form == DW_FORM_ref_sig8)
21227     {
21228       return get_signatured_type (die, DW_SIGNATURE (attr), cu);
21229     }
21230   else
21231     {
21232       complaint (&symfile_complaints,
21233                  _("Dwarf Error: DW_AT_signature has bad form %s in DIE"
21234                    " at 0x%x [in module %s]"),
21235                  dwarf_form_name (attr->form), to_underlying (die->sect_off),
21236                  objfile_name (dwarf2_per_objfile->objfile));
21237       return build_error_marker_type (cu, die);
21238     }
21239 }
21240
21241 /* Load the DIEs associated with type unit PER_CU into memory.  */
21242
21243 static void
21244 load_full_type_unit (struct dwarf2_per_cu_data *per_cu)
21245 {
21246   struct signatured_type *sig_type;
21247
21248   /* Caller is responsible for ensuring type_unit_groups don't get here.  */
21249   gdb_assert (! IS_TYPE_UNIT_GROUP (per_cu));
21250
21251   /* We have the per_cu, but we need the signatured_type.
21252      Fortunately this is an easy translation.  */
21253   gdb_assert (per_cu->is_debug_types);
21254   sig_type = (struct signatured_type *) per_cu;
21255
21256   gdb_assert (per_cu->cu == NULL);
21257
21258   read_signatured_type (sig_type);
21259
21260   gdb_assert (per_cu->cu != NULL);
21261 }
21262
21263 /* die_reader_func for read_signatured_type.
21264    This is identical to load_full_comp_unit_reader,
21265    but is kept separate for now.  */
21266
21267 static void
21268 read_signatured_type_reader (const struct die_reader_specs *reader,
21269                              const gdb_byte *info_ptr,
21270                              struct die_info *comp_unit_die,
21271                              int has_children,
21272                              void *data)
21273 {
21274   struct dwarf2_cu *cu = reader->cu;
21275
21276   gdb_assert (cu->die_hash == NULL);
21277   cu->die_hash =
21278     htab_create_alloc_ex (cu->header.length / 12,
21279                           die_hash,
21280                           die_eq,
21281                           NULL,
21282                           &cu->comp_unit_obstack,
21283                           hashtab_obstack_allocate,
21284                           dummy_obstack_deallocate);
21285
21286   if (has_children)
21287     comp_unit_die->child = read_die_and_siblings (reader, info_ptr,
21288                                                   &info_ptr, comp_unit_die);
21289   cu->dies = comp_unit_die;
21290   /* comp_unit_die is not stored in die_hash, no need.  */
21291
21292   /* We try not to read any attributes in this function, because not
21293      all CUs needed for references have been loaded yet, and symbol
21294      table processing isn't initialized.  But we have to set the CU language,
21295      or we won't be able to build types correctly.
21296      Similarly, if we do not read the producer, we can not apply
21297      producer-specific interpretation.  */
21298   prepare_one_comp_unit (cu, cu->dies, language_minimal);
21299 }
21300
21301 /* Read in a signatured type and build its CU and DIEs.
21302    If the type is a stub for the real type in a DWO file,
21303    read in the real type from the DWO file as well.  */
21304
21305 static void
21306 read_signatured_type (struct signatured_type *sig_type)
21307 {
21308   struct dwarf2_per_cu_data *per_cu = &sig_type->per_cu;
21309
21310   gdb_assert (per_cu->is_debug_types);
21311   gdb_assert (per_cu->cu == NULL);
21312
21313   init_cutu_and_read_dies (per_cu, NULL, 0, 1,
21314                            read_signatured_type_reader, NULL);
21315   sig_type->per_cu.tu_read = 1;
21316 }
21317
21318 /* Decode simple location descriptions.
21319    Given a pointer to a dwarf block that defines a location, compute
21320    the location and return the value.
21321
21322    NOTE drow/2003-11-18: This function is called in two situations
21323    now: for the address of static or global variables (partial symbols
21324    only) and for offsets into structures which are expected to be
21325    (more or less) constant.  The partial symbol case should go away,
21326    and only the constant case should remain.  That will let this
21327    function complain more accurately.  A few special modes are allowed
21328    without complaint for global variables (for instance, global
21329    register values and thread-local values).
21330
21331    A location description containing no operations indicates that the
21332    object is optimized out.  The return value is 0 for that case.
21333    FIXME drow/2003-11-16: No callers check for this case any more; soon all
21334    callers will only want a very basic result and this can become a
21335    complaint.
21336
21337    Note that stack[0] is unused except as a default error return.  */
21338
21339 static CORE_ADDR
21340 decode_locdesc (struct dwarf_block *blk, struct dwarf2_cu *cu)
21341 {
21342   struct objfile *objfile = cu->objfile;
21343   size_t i;
21344   size_t size = blk->size;
21345   const gdb_byte *data = blk->data;
21346   CORE_ADDR stack[64];
21347   int stacki;
21348   unsigned int bytes_read, unsnd;
21349   gdb_byte op;
21350
21351   i = 0;
21352   stacki = 0;
21353   stack[stacki] = 0;
21354   stack[++stacki] = 0;
21355
21356   while (i < size)
21357     {
21358       op = data[i++];
21359       switch (op)
21360         {
21361         case DW_OP_lit0:
21362         case DW_OP_lit1:
21363         case DW_OP_lit2:
21364         case DW_OP_lit3:
21365         case DW_OP_lit4:
21366         case DW_OP_lit5:
21367         case DW_OP_lit6:
21368         case DW_OP_lit7:
21369         case DW_OP_lit8:
21370         case DW_OP_lit9:
21371         case DW_OP_lit10:
21372         case DW_OP_lit11:
21373         case DW_OP_lit12:
21374         case DW_OP_lit13:
21375         case DW_OP_lit14:
21376         case DW_OP_lit15:
21377         case DW_OP_lit16:
21378         case DW_OP_lit17:
21379         case DW_OP_lit18:
21380         case DW_OP_lit19:
21381         case DW_OP_lit20:
21382         case DW_OP_lit21:
21383         case DW_OP_lit22:
21384         case DW_OP_lit23:
21385         case DW_OP_lit24:
21386         case DW_OP_lit25:
21387         case DW_OP_lit26:
21388         case DW_OP_lit27:
21389         case DW_OP_lit28:
21390         case DW_OP_lit29:
21391         case DW_OP_lit30:
21392         case DW_OP_lit31:
21393           stack[++stacki] = op - DW_OP_lit0;
21394           break;
21395
21396         case DW_OP_reg0:
21397         case DW_OP_reg1:
21398         case DW_OP_reg2:
21399         case DW_OP_reg3:
21400         case DW_OP_reg4:
21401         case DW_OP_reg5:
21402         case DW_OP_reg6:
21403         case DW_OP_reg7:
21404         case DW_OP_reg8:
21405         case DW_OP_reg9:
21406         case DW_OP_reg10:
21407         case DW_OP_reg11:
21408         case DW_OP_reg12:
21409         case DW_OP_reg13:
21410         case DW_OP_reg14:
21411         case DW_OP_reg15:
21412         case DW_OP_reg16:
21413         case DW_OP_reg17:
21414         case DW_OP_reg18:
21415         case DW_OP_reg19:
21416         case DW_OP_reg20:
21417         case DW_OP_reg21:
21418         case DW_OP_reg22:
21419         case DW_OP_reg23:
21420         case DW_OP_reg24:
21421         case DW_OP_reg25:
21422         case DW_OP_reg26:
21423         case DW_OP_reg27:
21424         case DW_OP_reg28:
21425         case DW_OP_reg29:
21426         case DW_OP_reg30:
21427         case DW_OP_reg31:
21428           stack[++stacki] = op - DW_OP_reg0;
21429           if (i < size)
21430             dwarf2_complex_location_expr_complaint ();
21431           break;
21432
21433         case DW_OP_regx:
21434           unsnd = read_unsigned_leb128 (NULL, (data + i), &bytes_read);
21435           i += bytes_read;
21436           stack[++stacki] = unsnd;
21437           if (i < size)
21438             dwarf2_complex_location_expr_complaint ();
21439           break;
21440
21441         case DW_OP_addr:
21442           stack[++stacki] = read_address (objfile->obfd, &data[i],
21443                                           cu, &bytes_read);
21444           i += bytes_read;
21445           break;
21446
21447         case DW_OP_const1u:
21448           stack[++stacki] = read_1_byte (objfile->obfd, &data[i]);
21449           i += 1;
21450           break;
21451
21452         case DW_OP_const1s:
21453           stack[++stacki] = read_1_signed_byte (objfile->obfd, &data[i]);
21454           i += 1;
21455           break;
21456
21457         case DW_OP_const2u:
21458           stack[++stacki] = read_2_bytes (objfile->obfd, &data[i]);
21459           i += 2;
21460           break;
21461
21462         case DW_OP_const2s:
21463           stack[++stacki] = read_2_signed_bytes (objfile->obfd, &data[i]);
21464           i += 2;
21465           break;
21466
21467         case DW_OP_const4u:
21468           stack[++stacki] = read_4_bytes (objfile->obfd, &data[i]);
21469           i += 4;
21470           break;
21471
21472         case DW_OP_const4s:
21473           stack[++stacki] = read_4_signed_bytes (objfile->obfd, &data[i]);
21474           i += 4;
21475           break;
21476
21477         case DW_OP_const8u:
21478           stack[++stacki] = read_8_bytes (objfile->obfd, &data[i]);
21479           i += 8;
21480           break;
21481
21482         case DW_OP_constu:
21483           stack[++stacki] = read_unsigned_leb128 (NULL, (data + i),
21484                                                   &bytes_read);
21485           i += bytes_read;
21486           break;
21487
21488         case DW_OP_consts:
21489           stack[++stacki] = read_signed_leb128 (NULL, (data + i), &bytes_read);
21490           i += bytes_read;
21491           break;
21492
21493         case DW_OP_dup:
21494           stack[stacki + 1] = stack[stacki];
21495           stacki++;
21496           break;
21497
21498         case DW_OP_plus:
21499           stack[stacki - 1] += stack[stacki];
21500           stacki--;
21501           break;
21502
21503         case DW_OP_plus_uconst:
21504           stack[stacki] += read_unsigned_leb128 (NULL, (data + i),
21505                                                  &bytes_read);
21506           i += bytes_read;
21507           break;
21508
21509         case DW_OP_minus:
21510           stack[stacki - 1] -= stack[stacki];
21511           stacki--;
21512           break;
21513
21514         case DW_OP_deref:
21515           /* If we're not the last op, then we definitely can't encode
21516              this using GDB's address_class enum.  This is valid for partial
21517              global symbols, although the variable's address will be bogus
21518              in the psymtab.  */
21519           if (i < size)
21520             dwarf2_complex_location_expr_complaint ();
21521           break;
21522
21523         case DW_OP_GNU_push_tls_address:
21524         case DW_OP_form_tls_address:
21525           /* The top of the stack has the offset from the beginning
21526              of the thread control block at which the variable is located.  */
21527           /* Nothing should follow this operator, so the top of stack would
21528              be returned.  */
21529           /* This is valid for partial global symbols, but the variable's
21530              address will be bogus in the psymtab.  Make it always at least
21531              non-zero to not look as a variable garbage collected by linker
21532              which have DW_OP_addr 0.  */
21533           if (i < size)
21534             dwarf2_complex_location_expr_complaint ();
21535           stack[stacki]++;
21536           break;
21537
21538         case DW_OP_GNU_uninit:
21539           break;
21540
21541         case DW_OP_GNU_addr_index:
21542         case DW_OP_GNU_const_index:
21543           stack[++stacki] = read_addr_index_from_leb128 (cu, &data[i],
21544                                                          &bytes_read);
21545           i += bytes_read;
21546           break;
21547
21548         default:
21549           {
21550             const char *name = get_DW_OP_name (op);
21551
21552             if (name)
21553               complaint (&symfile_complaints, _("unsupported stack op: '%s'"),
21554                          name);
21555             else
21556               complaint (&symfile_complaints, _("unsupported stack op: '%02x'"),
21557                          op);
21558           }
21559
21560           return (stack[stacki]);
21561         }
21562
21563       /* Enforce maximum stack depth of SIZE-1 to avoid writing
21564          outside of the allocated space.  Also enforce minimum>0.  */
21565       if (stacki >= ARRAY_SIZE (stack) - 1)
21566         {
21567           complaint (&symfile_complaints,
21568                      _("location description stack overflow"));
21569           return 0;
21570         }
21571
21572       if (stacki <= 0)
21573         {
21574           complaint (&symfile_complaints,
21575                      _("location description stack underflow"));
21576           return 0;
21577         }
21578     }
21579   return (stack[stacki]);
21580 }
21581
21582 /* memory allocation interface */
21583
21584 static struct dwarf_block *
21585 dwarf_alloc_block (struct dwarf2_cu *cu)
21586 {
21587   return XOBNEW (&cu->comp_unit_obstack, struct dwarf_block);
21588 }
21589
21590 static struct die_info *
21591 dwarf_alloc_die (struct dwarf2_cu *cu, int num_attrs)
21592 {
21593   struct die_info *die;
21594   size_t size = sizeof (struct die_info);
21595
21596   if (num_attrs > 1)
21597     size += (num_attrs - 1) * sizeof (struct attribute);
21598
21599   die = (struct die_info *) obstack_alloc (&cu->comp_unit_obstack, size);
21600   memset (die, 0, sizeof (struct die_info));
21601   return (die);
21602 }
21603
21604 \f
21605 /* Macro support.  */
21606
21607 /* Return file name relative to the compilation directory of file number I in
21608    *LH's file name table.  The result is allocated using xmalloc; the caller is
21609    responsible for freeing it.  */
21610
21611 static char *
21612 file_file_name (int file, struct line_header *lh)
21613 {
21614   /* Is the file number a valid index into the line header's file name
21615      table?  Remember that file numbers start with one, not zero.  */
21616   if (1 <= file && file <= lh->file_names.size ())
21617     {
21618       const file_entry &fe = lh->file_names[file - 1];
21619
21620       if (!IS_ABSOLUTE_PATH (fe.name))
21621         {
21622           const char *dir = fe.include_dir (lh);
21623           if (dir != NULL)
21624             return concat (dir, SLASH_STRING, fe.name, (char *) NULL);
21625         }
21626       return xstrdup (fe.name);
21627     }
21628   else
21629     {
21630       /* The compiler produced a bogus file number.  We can at least
21631          record the macro definitions made in the file, even if we
21632          won't be able to find the file by name.  */
21633       char fake_name[80];
21634
21635       xsnprintf (fake_name, sizeof (fake_name),
21636                  "<bad macro file number %d>", file);
21637
21638       complaint (&symfile_complaints,
21639                  _("bad file number in macro information (%d)"),
21640                  file);
21641
21642       return xstrdup (fake_name);
21643     }
21644 }
21645
21646 /* Return the full name of file number I in *LH's file name table.
21647    Use COMP_DIR as the name of the current directory of the
21648    compilation.  The result is allocated using xmalloc; the caller is
21649    responsible for freeing it.  */
21650 static char *
21651 file_full_name (int file, struct line_header *lh, const char *comp_dir)
21652 {
21653   /* Is the file number a valid index into the line header's file name
21654      table?  Remember that file numbers start with one, not zero.  */
21655   if (1 <= file && file <= lh->file_names.size ())
21656     {
21657       char *relative = file_file_name (file, lh);
21658
21659       if (IS_ABSOLUTE_PATH (relative) || comp_dir == NULL)
21660         return relative;
21661       return reconcat (relative, comp_dir, SLASH_STRING,
21662                        relative, (char *) NULL);
21663     }
21664   else
21665     return file_file_name (file, lh);
21666 }
21667
21668
21669 static struct macro_source_file *
21670 macro_start_file (int file, int line,
21671                   struct macro_source_file *current_file,
21672                   struct line_header *lh)
21673 {
21674   /* File name relative to the compilation directory of this source file.  */
21675   char *file_name = file_file_name (file, lh);
21676
21677   if (! current_file)
21678     {
21679       /* Note: We don't create a macro table for this compilation unit
21680          at all until we actually get a filename.  */
21681       struct macro_table *macro_table = get_macro_table ();
21682
21683       /* If we have no current file, then this must be the start_file
21684          directive for the compilation unit's main source file.  */
21685       current_file = macro_set_main (macro_table, file_name);
21686       macro_define_special (macro_table);
21687     }
21688   else
21689     current_file = macro_include (current_file, line, file_name);
21690
21691   xfree (file_name);
21692
21693   return current_file;
21694 }
21695
21696
21697 /* Copy the LEN characters at BUF to a xmalloc'ed block of memory,
21698    followed by a null byte.  */
21699 static char *
21700 copy_string (const char *buf, int len)
21701 {
21702   char *s = (char *) xmalloc (len + 1);
21703
21704   memcpy (s, buf, len);
21705   s[len] = '\0';
21706   return s;
21707 }
21708
21709
21710 static const char *
21711 consume_improper_spaces (const char *p, const char *body)
21712 {
21713   if (*p == ' ')
21714     {
21715       complaint (&symfile_complaints,
21716                  _("macro definition contains spaces "
21717                    "in formal argument list:\n`%s'"),
21718                  body);
21719
21720       while (*p == ' ')
21721         p++;
21722     }
21723
21724   return p;
21725 }
21726
21727
21728 static void
21729 parse_macro_definition (struct macro_source_file *file, int line,
21730                         const char *body)
21731 {
21732   const char *p;
21733
21734   /* The body string takes one of two forms.  For object-like macro
21735      definitions, it should be:
21736
21737         <macro name> " " <definition>
21738
21739      For function-like macro definitions, it should be:
21740
21741         <macro name> "() " <definition>
21742      or
21743         <macro name> "(" <arg name> ( "," <arg name> ) * ") " <definition>
21744
21745      Spaces may appear only where explicitly indicated, and in the
21746      <definition>.
21747
21748      The Dwarf 2 spec says that an object-like macro's name is always
21749      followed by a space, but versions of GCC around March 2002 omit
21750      the space when the macro's definition is the empty string.
21751
21752      The Dwarf 2 spec says that there should be no spaces between the
21753      formal arguments in a function-like macro's formal argument list,
21754      but versions of GCC around March 2002 include spaces after the
21755      commas.  */
21756
21757
21758   /* Find the extent of the macro name.  The macro name is terminated
21759      by either a space or null character (for an object-like macro) or
21760      an opening paren (for a function-like macro).  */
21761   for (p = body; *p; p++)
21762     if (*p == ' ' || *p == '(')
21763       break;
21764
21765   if (*p == ' ' || *p == '\0')
21766     {
21767       /* It's an object-like macro.  */
21768       int name_len = p - body;
21769       char *name = copy_string (body, name_len);
21770       const char *replacement;
21771
21772       if (*p == ' ')
21773         replacement = body + name_len + 1;
21774       else
21775         {
21776           dwarf2_macro_malformed_definition_complaint (body);
21777           replacement = body + name_len;
21778         }
21779
21780       macro_define_object (file, line, name, replacement);
21781
21782       xfree (name);
21783     }
21784   else if (*p == '(')
21785     {
21786       /* It's a function-like macro.  */
21787       char *name = copy_string (body, p - body);
21788       int argc = 0;
21789       int argv_size = 1;
21790       char **argv = XNEWVEC (char *, argv_size);
21791
21792       p++;
21793
21794       p = consume_improper_spaces (p, body);
21795
21796       /* Parse the formal argument list.  */
21797       while (*p && *p != ')')
21798         {
21799           /* Find the extent of the current argument name.  */
21800           const char *arg_start = p;
21801
21802           while (*p && *p != ',' && *p != ')' && *p != ' ')
21803             p++;
21804
21805           if (! *p || p == arg_start)
21806             dwarf2_macro_malformed_definition_complaint (body);
21807           else
21808             {
21809               /* Make sure argv has room for the new argument.  */
21810               if (argc >= argv_size)
21811                 {
21812                   argv_size *= 2;
21813                   argv = XRESIZEVEC (char *, argv, argv_size);
21814                 }
21815
21816               argv[argc++] = copy_string (arg_start, p - arg_start);
21817             }
21818
21819           p = consume_improper_spaces (p, body);
21820
21821           /* Consume the comma, if present.  */
21822           if (*p == ',')
21823             {
21824               p++;
21825
21826               p = consume_improper_spaces (p, body);
21827             }
21828         }
21829
21830       if (*p == ')')
21831         {
21832           p++;
21833
21834           if (*p == ' ')
21835             /* Perfectly formed definition, no complaints.  */
21836             macro_define_function (file, line, name,
21837                                    argc, (const char **) argv,
21838                                    p + 1);
21839           else if (*p == '\0')
21840             {
21841               /* Complain, but do define it.  */
21842               dwarf2_macro_malformed_definition_complaint (body);
21843               macro_define_function (file, line, name,
21844                                      argc, (const char **) argv,
21845                                      p);
21846             }
21847           else
21848             /* Just complain.  */
21849             dwarf2_macro_malformed_definition_complaint (body);
21850         }
21851       else
21852         /* Just complain.  */
21853         dwarf2_macro_malformed_definition_complaint (body);
21854
21855       xfree (name);
21856       {
21857         int i;
21858
21859         for (i = 0; i < argc; i++)
21860           xfree (argv[i]);
21861       }
21862       xfree (argv);
21863     }
21864   else
21865     dwarf2_macro_malformed_definition_complaint (body);
21866 }
21867
21868 /* Skip some bytes from BYTES according to the form given in FORM.
21869    Returns the new pointer.  */
21870
21871 static const gdb_byte *
21872 skip_form_bytes (bfd *abfd, const gdb_byte *bytes, const gdb_byte *buffer_end,
21873                  enum dwarf_form form,
21874                  unsigned int offset_size,
21875                  struct dwarf2_section_info *section)
21876 {
21877   unsigned int bytes_read;
21878
21879   switch (form)
21880     {
21881     case DW_FORM_data1:
21882     case DW_FORM_flag:
21883       ++bytes;
21884       break;
21885
21886     case DW_FORM_data2:
21887       bytes += 2;
21888       break;
21889
21890     case DW_FORM_data4:
21891       bytes += 4;
21892       break;
21893
21894     case DW_FORM_data8:
21895       bytes += 8;
21896       break;
21897
21898     case DW_FORM_data16:
21899       bytes += 16;
21900       break;
21901
21902     case DW_FORM_string:
21903       read_direct_string (abfd, bytes, &bytes_read);
21904       bytes += bytes_read;
21905       break;
21906
21907     case DW_FORM_sec_offset:
21908     case DW_FORM_strp:
21909     case DW_FORM_GNU_strp_alt:
21910       bytes += offset_size;
21911       break;
21912
21913     case DW_FORM_block:
21914       bytes += read_unsigned_leb128 (abfd, bytes, &bytes_read);
21915       bytes += bytes_read;
21916       break;
21917
21918     case DW_FORM_block1:
21919       bytes += 1 + read_1_byte (abfd, bytes);
21920       break;
21921     case DW_FORM_block2:
21922       bytes += 2 + read_2_bytes (abfd, bytes);
21923       break;
21924     case DW_FORM_block4:
21925       bytes += 4 + read_4_bytes (abfd, bytes);
21926       break;
21927
21928     case DW_FORM_sdata:
21929     case DW_FORM_udata:
21930     case DW_FORM_GNU_addr_index:
21931     case DW_FORM_GNU_str_index:
21932       bytes = gdb_skip_leb128 (bytes, buffer_end);
21933       if (bytes == NULL)
21934         {
21935           dwarf2_section_buffer_overflow_complaint (section);
21936           return NULL;
21937         }
21938       break;
21939
21940     case DW_FORM_implicit_const:
21941       break;
21942
21943     default:
21944       {
21945       complain:
21946         complaint (&symfile_complaints,
21947                    _("invalid form 0x%x in `%s'"),
21948                    form, get_section_name (section));
21949         return NULL;
21950       }
21951     }
21952
21953   return bytes;
21954 }
21955
21956 /* A helper for dwarf_decode_macros that handles skipping an unknown
21957    opcode.  Returns an updated pointer to the macro data buffer; or,
21958    on error, issues a complaint and returns NULL.  */
21959
21960 static const gdb_byte *
21961 skip_unknown_opcode (unsigned int opcode,
21962                      const gdb_byte **opcode_definitions,
21963                      const gdb_byte *mac_ptr, const gdb_byte *mac_end,
21964                      bfd *abfd,
21965                      unsigned int offset_size,
21966                      struct dwarf2_section_info *section)
21967 {
21968   unsigned int bytes_read, i;
21969   unsigned long arg;
21970   const gdb_byte *defn;
21971
21972   if (opcode_definitions[opcode] == NULL)
21973     {
21974       complaint (&symfile_complaints,
21975                  _("unrecognized DW_MACFINO opcode 0x%x"),
21976                  opcode);
21977       return NULL;
21978     }
21979
21980   defn = opcode_definitions[opcode];
21981   arg = read_unsigned_leb128 (abfd, defn, &bytes_read);
21982   defn += bytes_read;
21983
21984   for (i = 0; i < arg; ++i)
21985     {
21986       mac_ptr = skip_form_bytes (abfd, mac_ptr, mac_end,
21987                                  (enum dwarf_form) defn[i], offset_size,
21988                                  section);
21989       if (mac_ptr == NULL)
21990         {
21991           /* skip_form_bytes already issued the complaint.  */
21992           return NULL;
21993         }
21994     }
21995
21996   return mac_ptr;
21997 }
21998
21999 /* A helper function which parses the header of a macro section.
22000    If the macro section is the extended (for now called "GNU") type,
22001    then this updates *OFFSET_SIZE.  Returns a pointer to just after
22002    the header, or issues a complaint and returns NULL on error.  */
22003
22004 static const gdb_byte *
22005 dwarf_parse_macro_header (const gdb_byte **opcode_definitions,
22006                           bfd *abfd,
22007                           const gdb_byte *mac_ptr,
22008                           unsigned int *offset_size,
22009                           int section_is_gnu)
22010 {
22011   memset (opcode_definitions, 0, 256 * sizeof (gdb_byte *));
22012
22013   if (section_is_gnu)
22014     {
22015       unsigned int version, flags;
22016
22017       version = read_2_bytes (abfd, mac_ptr);
22018       if (version != 4 && version != 5)
22019         {
22020           complaint (&symfile_complaints,
22021                      _("unrecognized version `%d' in .debug_macro section"),
22022                      version);
22023           return NULL;
22024         }
22025       mac_ptr += 2;
22026
22027       flags = read_1_byte (abfd, mac_ptr);
22028       ++mac_ptr;
22029       *offset_size = (flags & 1) ? 8 : 4;
22030
22031       if ((flags & 2) != 0)
22032         /* We don't need the line table offset.  */
22033         mac_ptr += *offset_size;
22034
22035       /* Vendor opcode descriptions.  */
22036       if ((flags & 4) != 0)
22037         {
22038           unsigned int i, count;
22039
22040           count = read_1_byte (abfd, mac_ptr);
22041           ++mac_ptr;
22042           for (i = 0; i < count; ++i)
22043             {
22044               unsigned int opcode, bytes_read;
22045               unsigned long arg;
22046
22047               opcode = read_1_byte (abfd, mac_ptr);
22048               ++mac_ptr;
22049               opcode_definitions[opcode] = mac_ptr;
22050               arg = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
22051               mac_ptr += bytes_read;
22052               mac_ptr += arg;
22053             }
22054         }
22055     }
22056
22057   return mac_ptr;
22058 }
22059
22060 /* A helper for dwarf_decode_macros that handles the GNU extensions,
22061    including DW_MACRO_import.  */
22062
22063 static void
22064 dwarf_decode_macro_bytes (bfd *abfd,
22065                           const gdb_byte *mac_ptr, const gdb_byte *mac_end,
22066                           struct macro_source_file *current_file,
22067                           struct line_header *lh,
22068                           struct dwarf2_section_info *section,
22069                           int section_is_gnu, int section_is_dwz,
22070                           unsigned int offset_size,
22071                           htab_t include_hash)
22072 {
22073   struct objfile *objfile = dwarf2_per_objfile->objfile;
22074   enum dwarf_macro_record_type macinfo_type;
22075   int at_commandline;
22076   const gdb_byte *opcode_definitions[256];
22077
22078   mac_ptr = dwarf_parse_macro_header (opcode_definitions, abfd, mac_ptr,
22079                                       &offset_size, section_is_gnu);
22080   if (mac_ptr == NULL)
22081     {
22082       /* We already issued a complaint.  */
22083       return;
22084     }
22085
22086   /* Determines if GDB is still before first DW_MACINFO_start_file.  If true
22087      GDB is still reading the definitions from command line.  First
22088      DW_MACINFO_start_file will need to be ignored as it was already executed
22089      to create CURRENT_FILE for the main source holding also the command line
22090      definitions.  On first met DW_MACINFO_start_file this flag is reset to
22091      normally execute all the remaining DW_MACINFO_start_file macinfos.  */
22092
22093   at_commandline = 1;
22094
22095   do
22096     {
22097       /* Do we at least have room for a macinfo type byte?  */
22098       if (mac_ptr >= mac_end)
22099         {
22100           dwarf2_section_buffer_overflow_complaint (section);
22101           break;
22102         }
22103
22104       macinfo_type = (enum dwarf_macro_record_type) read_1_byte (abfd, mac_ptr);
22105       mac_ptr++;
22106
22107       /* Note that we rely on the fact that the corresponding GNU and
22108          DWARF constants are the same.  */
22109       switch (macinfo_type)
22110         {
22111           /* A zero macinfo type indicates the end of the macro
22112              information.  */
22113         case 0:
22114           break;
22115
22116         case DW_MACRO_define:
22117         case DW_MACRO_undef:
22118         case DW_MACRO_define_strp:
22119         case DW_MACRO_undef_strp:
22120         case DW_MACRO_define_sup:
22121         case DW_MACRO_undef_sup:
22122           {
22123             unsigned int bytes_read;
22124             int line;
22125             const char *body;
22126             int is_define;
22127
22128             line = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
22129             mac_ptr += bytes_read;
22130
22131             if (macinfo_type == DW_MACRO_define
22132                 || macinfo_type == DW_MACRO_undef)
22133               {
22134                 body = read_direct_string (abfd, mac_ptr, &bytes_read);
22135                 mac_ptr += bytes_read;
22136               }
22137             else
22138               {
22139                 LONGEST str_offset;
22140
22141                 str_offset = read_offset_1 (abfd, mac_ptr, offset_size);
22142                 mac_ptr += offset_size;
22143
22144                 if (macinfo_type == DW_MACRO_define_sup
22145                     || macinfo_type == DW_MACRO_undef_sup
22146                     || section_is_dwz)
22147                   {
22148                     struct dwz_file *dwz = dwarf2_get_dwz_file ();
22149
22150                     body = read_indirect_string_from_dwz (dwz, str_offset);
22151                   }
22152                 else
22153                   body = read_indirect_string_at_offset (abfd, str_offset);
22154               }
22155
22156             is_define = (macinfo_type == DW_MACRO_define
22157                          || macinfo_type == DW_MACRO_define_strp
22158                          || macinfo_type == DW_MACRO_define_sup);
22159             if (! current_file)
22160               {
22161                 /* DWARF violation as no main source is present.  */
22162                 complaint (&symfile_complaints,
22163                            _("debug info with no main source gives macro %s "
22164                              "on line %d: %s"),
22165                            is_define ? _("definition") : _("undefinition"),
22166                            line, body);
22167                 break;
22168               }
22169             if ((line == 0 && !at_commandline)
22170                 || (line != 0 && at_commandline))
22171               complaint (&symfile_complaints,
22172                          _("debug info gives %s macro %s with %s line %d: %s"),
22173                          at_commandline ? _("command-line") : _("in-file"),
22174                          is_define ? _("definition") : _("undefinition"),
22175                          line == 0 ? _("zero") : _("non-zero"), line, body);
22176
22177             if (is_define)
22178               parse_macro_definition (current_file, line, body);
22179             else
22180               {
22181                 gdb_assert (macinfo_type == DW_MACRO_undef
22182                             || macinfo_type == DW_MACRO_undef_strp
22183                             || macinfo_type == DW_MACRO_undef_sup);
22184                 macro_undef (current_file, line, body);
22185               }
22186           }
22187           break;
22188
22189         case DW_MACRO_start_file:
22190           {
22191             unsigned int bytes_read;
22192             int line, file;
22193
22194             line = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
22195             mac_ptr += bytes_read;
22196             file = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
22197             mac_ptr += bytes_read;
22198
22199             if ((line == 0 && !at_commandline)
22200                 || (line != 0 && at_commandline))
22201               complaint (&symfile_complaints,
22202                          _("debug info gives source %d included "
22203                            "from %s at %s line %d"),
22204                          file, at_commandline ? _("command-line") : _("file"),
22205                          line == 0 ? _("zero") : _("non-zero"), line);
22206
22207             if (at_commandline)
22208               {
22209                 /* This DW_MACRO_start_file was executed in the
22210                    pass one.  */
22211                 at_commandline = 0;
22212               }
22213             else
22214               current_file = macro_start_file (file, line, current_file, lh);
22215           }
22216           break;
22217
22218         case DW_MACRO_end_file:
22219           if (! current_file)
22220             complaint (&symfile_complaints,
22221                        _("macro debug info has an unmatched "
22222                          "`close_file' directive"));
22223           else
22224             {
22225               current_file = current_file->included_by;
22226               if (! current_file)
22227                 {
22228                   enum dwarf_macro_record_type next_type;
22229
22230                   /* GCC circa March 2002 doesn't produce the zero
22231                      type byte marking the end of the compilation
22232                      unit.  Complain if it's not there, but exit no
22233                      matter what.  */
22234
22235                   /* Do we at least have room for a macinfo type byte?  */
22236                   if (mac_ptr >= mac_end)
22237                     {
22238                       dwarf2_section_buffer_overflow_complaint (section);
22239                       return;
22240                     }
22241
22242                   /* We don't increment mac_ptr here, so this is just
22243                      a look-ahead.  */
22244                   next_type
22245                     = (enum dwarf_macro_record_type) read_1_byte (abfd,
22246                                                                   mac_ptr);
22247                   if (next_type != 0)
22248                     complaint (&symfile_complaints,
22249                                _("no terminating 0-type entry for "
22250                                  "macros in `.debug_macinfo' section"));
22251
22252                   return;
22253                 }
22254             }
22255           break;
22256
22257         case DW_MACRO_import:
22258         case DW_MACRO_import_sup:
22259           {
22260             LONGEST offset;
22261             void **slot;
22262             bfd *include_bfd = abfd;
22263             struct dwarf2_section_info *include_section = section;
22264             const gdb_byte *include_mac_end = mac_end;
22265             int is_dwz = section_is_dwz;
22266             const gdb_byte *new_mac_ptr;
22267
22268             offset = read_offset_1 (abfd, mac_ptr, offset_size);
22269             mac_ptr += offset_size;
22270
22271             if (macinfo_type == DW_MACRO_import_sup)
22272               {
22273                 struct dwz_file *dwz = dwarf2_get_dwz_file ();
22274
22275                 dwarf2_read_section (objfile, &dwz->macro);
22276
22277                 include_section = &dwz->macro;
22278                 include_bfd = get_section_bfd_owner (include_section);
22279                 include_mac_end = dwz->macro.buffer + dwz->macro.size;
22280                 is_dwz = 1;
22281               }
22282
22283             new_mac_ptr = include_section->buffer + offset;
22284             slot = htab_find_slot (include_hash, new_mac_ptr, INSERT);
22285
22286             if (*slot != NULL)
22287               {
22288                 /* This has actually happened; see
22289                    http://sourceware.org/bugzilla/show_bug.cgi?id=13568.  */
22290                 complaint (&symfile_complaints,
22291                            _("recursive DW_MACRO_import in "
22292                              ".debug_macro section"));
22293               }
22294             else
22295               {
22296                 *slot = (void *) new_mac_ptr;
22297
22298                 dwarf_decode_macro_bytes (include_bfd, new_mac_ptr,
22299                                           include_mac_end, current_file, lh,
22300                                           section, section_is_gnu, is_dwz,
22301                                           offset_size, include_hash);
22302
22303                 htab_remove_elt (include_hash, (void *) new_mac_ptr);
22304               }
22305           }
22306           break;
22307
22308         case DW_MACINFO_vendor_ext:
22309           if (!section_is_gnu)
22310             {
22311               unsigned int bytes_read;
22312
22313               /* This reads the constant, but since we don't recognize
22314                  any vendor extensions, we ignore it.  */
22315               read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
22316               mac_ptr += bytes_read;
22317               read_direct_string (abfd, mac_ptr, &bytes_read);
22318               mac_ptr += bytes_read;
22319
22320               /* We don't recognize any vendor extensions.  */
22321               break;
22322             }
22323           /* FALLTHROUGH */
22324
22325         default:
22326           mac_ptr = skip_unknown_opcode (macinfo_type, opcode_definitions,
22327                                          mac_ptr, mac_end, abfd, offset_size,
22328                                          section);
22329           if (mac_ptr == NULL)
22330             return;
22331           break;
22332         }
22333     } while (macinfo_type != 0);
22334 }
22335
22336 static void
22337 dwarf_decode_macros (struct dwarf2_cu *cu, unsigned int offset,
22338                      int section_is_gnu)
22339 {
22340   struct objfile *objfile = dwarf2_per_objfile->objfile;
22341   struct line_header *lh = cu->line_header;
22342   bfd *abfd;
22343   const gdb_byte *mac_ptr, *mac_end;
22344   struct macro_source_file *current_file = 0;
22345   enum dwarf_macro_record_type macinfo_type;
22346   unsigned int offset_size = cu->header.offset_size;
22347   const gdb_byte *opcode_definitions[256];
22348   struct cleanup *cleanup;
22349   void **slot;
22350   struct dwarf2_section_info *section;
22351   const char *section_name;
22352
22353   if (cu->dwo_unit != NULL)
22354     {
22355       if (section_is_gnu)
22356         {
22357           section = &cu->dwo_unit->dwo_file->sections.macro;
22358           section_name = ".debug_macro.dwo";
22359         }
22360       else
22361         {
22362           section = &cu->dwo_unit->dwo_file->sections.macinfo;
22363           section_name = ".debug_macinfo.dwo";
22364         }
22365     }
22366   else
22367     {
22368       if (section_is_gnu)
22369         {
22370           section = &dwarf2_per_objfile->macro;
22371           section_name = ".debug_macro";
22372         }
22373       else
22374         {
22375           section = &dwarf2_per_objfile->macinfo;
22376           section_name = ".debug_macinfo";
22377         }
22378     }
22379
22380   dwarf2_read_section (objfile, section);
22381   if (section->buffer == NULL)
22382     {
22383       complaint (&symfile_complaints, _("missing %s section"), section_name);
22384       return;
22385     }
22386   abfd = get_section_bfd_owner (section);
22387
22388   /* First pass: Find the name of the base filename.
22389      This filename is needed in order to process all macros whose definition
22390      (or undefinition) comes from the command line.  These macros are defined
22391      before the first DW_MACINFO_start_file entry, and yet still need to be
22392      associated to the base file.
22393
22394      To determine the base file name, we scan the macro definitions until we
22395      reach the first DW_MACINFO_start_file entry.  We then initialize
22396      CURRENT_FILE accordingly so that any macro definition found before the
22397      first DW_MACINFO_start_file can still be associated to the base file.  */
22398
22399   mac_ptr = section->buffer + offset;
22400   mac_end = section->buffer + section->size;
22401
22402   mac_ptr = dwarf_parse_macro_header (opcode_definitions, abfd, mac_ptr,
22403                                       &offset_size, section_is_gnu);
22404   if (mac_ptr == NULL)
22405     {
22406       /* We already issued a complaint.  */
22407       return;
22408     }
22409
22410   do
22411     {
22412       /* Do we at least have room for a macinfo type byte?  */
22413       if (mac_ptr >= mac_end)
22414         {
22415           /* Complaint is printed during the second pass as GDB will probably
22416              stop the first pass earlier upon finding
22417              DW_MACINFO_start_file.  */
22418           break;
22419         }
22420
22421       macinfo_type = (enum dwarf_macro_record_type) read_1_byte (abfd, mac_ptr);
22422       mac_ptr++;
22423
22424       /* Note that we rely on the fact that the corresponding GNU and
22425          DWARF constants are the same.  */
22426       switch (macinfo_type)
22427         {
22428           /* A zero macinfo type indicates the end of the macro
22429              information.  */
22430         case 0:
22431           break;
22432
22433         case DW_MACRO_define:
22434         case DW_MACRO_undef:
22435           /* Only skip the data by MAC_PTR.  */
22436           {
22437             unsigned int bytes_read;
22438
22439             read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
22440             mac_ptr += bytes_read;
22441             read_direct_string (abfd, mac_ptr, &bytes_read);
22442             mac_ptr += bytes_read;
22443           }
22444           break;
22445
22446         case DW_MACRO_start_file:
22447           {
22448             unsigned int bytes_read;
22449             int line, file;
22450
22451             line = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
22452             mac_ptr += bytes_read;
22453             file = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
22454             mac_ptr += bytes_read;
22455
22456             current_file = macro_start_file (file, line, current_file, lh);
22457           }
22458           break;
22459
22460         case DW_MACRO_end_file:
22461           /* No data to skip by MAC_PTR.  */
22462           break;
22463
22464         case DW_MACRO_define_strp:
22465         case DW_MACRO_undef_strp:
22466         case DW_MACRO_define_sup:
22467         case DW_MACRO_undef_sup:
22468           {
22469             unsigned int bytes_read;
22470
22471             read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
22472             mac_ptr += bytes_read;
22473             mac_ptr += offset_size;
22474           }
22475           break;
22476
22477         case DW_MACRO_import:
22478         case DW_MACRO_import_sup:
22479           /* Note that, according to the spec, a transparent include
22480              chain cannot call DW_MACRO_start_file.  So, we can just
22481              skip this opcode.  */
22482           mac_ptr += offset_size;
22483           break;
22484
22485         case DW_MACINFO_vendor_ext:
22486           /* Only skip the data by MAC_PTR.  */
22487           if (!section_is_gnu)
22488             {
22489               unsigned int bytes_read;
22490
22491               read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
22492               mac_ptr += bytes_read;
22493               read_direct_string (abfd, mac_ptr, &bytes_read);
22494               mac_ptr += bytes_read;
22495             }
22496           /* FALLTHROUGH */
22497
22498         default:
22499           mac_ptr = skip_unknown_opcode (macinfo_type, opcode_definitions,
22500                                          mac_ptr, mac_end, abfd, offset_size,
22501                                          section);
22502           if (mac_ptr == NULL)
22503             return;
22504           break;
22505         }
22506     } while (macinfo_type != 0 && current_file == NULL);
22507
22508   /* Second pass: Process all entries.
22509
22510      Use the AT_COMMAND_LINE flag to determine whether we are still processing
22511      command-line macro definitions/undefinitions.  This flag is unset when we
22512      reach the first DW_MACINFO_start_file entry.  */
22513
22514   htab_up include_hash (htab_create_alloc (1, htab_hash_pointer,
22515                                            htab_eq_pointer,
22516                                            NULL, xcalloc, xfree));
22517   mac_ptr = section->buffer + offset;
22518   slot = htab_find_slot (include_hash.get (), mac_ptr, INSERT);
22519   *slot = (void *) mac_ptr;
22520   dwarf_decode_macro_bytes (abfd, mac_ptr, mac_end,
22521                             current_file, lh, section,
22522                             section_is_gnu, 0, offset_size,
22523                             include_hash.get ());
22524 }
22525
22526 /* Check if the attribute's form is a DW_FORM_block*
22527    if so return true else false.  */
22528
22529 static int
22530 attr_form_is_block (const struct attribute *attr)
22531 {
22532   return (attr == NULL ? 0 :
22533       attr->form == DW_FORM_block1
22534       || attr->form == DW_FORM_block2
22535       || attr->form == DW_FORM_block4
22536       || attr->form == DW_FORM_block
22537       || attr->form == DW_FORM_exprloc);
22538 }
22539
22540 /* Return non-zero if ATTR's value is a section offset --- classes
22541    lineptr, loclistptr, macptr or rangelistptr --- or zero, otherwise.
22542    You may use DW_UNSND (attr) to retrieve such offsets.
22543
22544    Section 7.5.4, "Attribute Encodings", explains that no attribute
22545    may have a value that belongs to more than one of these classes; it
22546    would be ambiguous if we did, because we use the same forms for all
22547    of them.  */
22548
22549 static int
22550 attr_form_is_section_offset (const struct attribute *attr)
22551 {
22552   return (attr->form == DW_FORM_data4
22553           || attr->form == DW_FORM_data8
22554           || attr->form == DW_FORM_sec_offset);
22555 }
22556
22557 /* Return non-zero if ATTR's value falls in the 'constant' class, or
22558    zero otherwise.  When this function returns true, you can apply
22559    dwarf2_get_attr_constant_value to it.
22560
22561    However, note that for some attributes you must check
22562    attr_form_is_section_offset before using this test.  DW_FORM_data4
22563    and DW_FORM_data8 are members of both the constant class, and of
22564    the classes that contain offsets into other debug sections
22565    (lineptr, loclistptr, macptr or rangelistptr).  The DWARF spec says
22566    that, if an attribute's can be either a constant or one of the
22567    section offset classes, DW_FORM_data4 and DW_FORM_data8 should be
22568    taken as section offsets, not constants.
22569
22570    DW_FORM_data16 is not considered as dwarf2_get_attr_constant_value
22571    cannot handle that.  */
22572
22573 static int
22574 attr_form_is_constant (const struct attribute *attr)
22575 {
22576   switch (attr->form)
22577     {
22578     case DW_FORM_sdata:
22579     case DW_FORM_udata:
22580     case DW_FORM_data1:
22581     case DW_FORM_data2:
22582     case DW_FORM_data4:
22583     case DW_FORM_data8:
22584     case DW_FORM_implicit_const:
22585       return 1;
22586     default:
22587       return 0;
22588     }
22589 }
22590
22591
22592 /* DW_ADDR is always stored already as sect_offset; despite for the forms
22593    besides DW_FORM_ref_addr it is stored as cu_offset in the DWARF file.  */
22594
22595 static int
22596 attr_form_is_ref (const struct attribute *attr)
22597 {
22598   switch (attr->form)
22599     {
22600     case DW_FORM_ref_addr:
22601     case DW_FORM_ref1:
22602     case DW_FORM_ref2:
22603     case DW_FORM_ref4:
22604     case DW_FORM_ref8:
22605     case DW_FORM_ref_udata:
22606     case DW_FORM_GNU_ref_alt:
22607       return 1;
22608     default:
22609       return 0;
22610     }
22611 }
22612
22613 /* Return the .debug_loc section to use for CU.
22614    For DWO files use .debug_loc.dwo.  */
22615
22616 static struct dwarf2_section_info *
22617 cu_debug_loc_section (struct dwarf2_cu *cu)
22618 {
22619   if (cu->dwo_unit)
22620     {
22621       struct dwo_sections *sections = &cu->dwo_unit->dwo_file->sections;
22622       
22623       return cu->header.version >= 5 ? &sections->loclists : &sections->loc;
22624     }
22625   return (cu->header.version >= 5 ? &dwarf2_per_objfile->loclists
22626                                   : &dwarf2_per_objfile->loc);
22627 }
22628
22629 /* A helper function that fills in a dwarf2_loclist_baton.  */
22630
22631 static void
22632 fill_in_loclist_baton (struct dwarf2_cu *cu,
22633                        struct dwarf2_loclist_baton *baton,
22634                        const struct attribute *attr)
22635 {
22636   struct dwarf2_section_info *section = cu_debug_loc_section (cu);
22637
22638   dwarf2_read_section (dwarf2_per_objfile->objfile, section);
22639
22640   baton->per_cu = cu->per_cu;
22641   gdb_assert (baton->per_cu);
22642   /* We don't know how long the location list is, but make sure we
22643      don't run off the edge of the section.  */
22644   baton->size = section->size - DW_UNSND (attr);
22645   baton->data = section->buffer + DW_UNSND (attr);
22646   baton->base_address = cu->base_address;
22647   baton->from_dwo = cu->dwo_unit != NULL;
22648 }
22649
22650 static void
22651 dwarf2_symbol_mark_computed (const struct attribute *attr, struct symbol *sym,
22652                              struct dwarf2_cu *cu, int is_block)
22653 {
22654   struct objfile *objfile = dwarf2_per_objfile->objfile;
22655   struct dwarf2_section_info *section = cu_debug_loc_section (cu);
22656
22657   if (attr_form_is_section_offset (attr)
22658       /* .debug_loc{,.dwo} may not exist at all, or the offset may be outside
22659          the section.  If so, fall through to the complaint in the
22660          other branch.  */
22661       && DW_UNSND (attr) < dwarf2_section_size (objfile, section))
22662     {
22663       struct dwarf2_loclist_baton *baton;
22664
22665       baton = XOBNEW (&objfile->objfile_obstack, struct dwarf2_loclist_baton);
22666
22667       fill_in_loclist_baton (cu, baton, attr);
22668
22669       if (cu->base_known == 0)
22670         complaint (&symfile_complaints,
22671                    _("Location list used without "
22672                      "specifying the CU base address."));
22673
22674       SYMBOL_ACLASS_INDEX (sym) = (is_block
22675                                    ? dwarf2_loclist_block_index
22676                                    : dwarf2_loclist_index);
22677       SYMBOL_LOCATION_BATON (sym) = baton;
22678     }
22679   else
22680     {
22681       struct dwarf2_locexpr_baton *baton;
22682
22683       baton = XOBNEW (&objfile->objfile_obstack, struct dwarf2_locexpr_baton);
22684       baton->per_cu = cu->per_cu;
22685       gdb_assert (baton->per_cu);
22686
22687       if (attr_form_is_block (attr))
22688         {
22689           /* Note that we're just copying the block's data pointer
22690              here, not the actual data.  We're still pointing into the
22691              info_buffer for SYM's objfile; right now we never release
22692              that buffer, but when we do clean up properly this may
22693              need to change.  */
22694           baton->size = DW_BLOCK (attr)->size;
22695           baton->data = DW_BLOCK (attr)->data;
22696         }
22697       else
22698         {
22699           dwarf2_invalid_attrib_class_complaint ("location description",
22700                                                  SYMBOL_NATURAL_NAME (sym));
22701           baton->size = 0;
22702         }
22703
22704       SYMBOL_ACLASS_INDEX (sym) = (is_block
22705                                    ? dwarf2_locexpr_block_index
22706                                    : dwarf2_locexpr_index);
22707       SYMBOL_LOCATION_BATON (sym) = baton;
22708     }
22709 }
22710
22711 /* Return the OBJFILE associated with the compilation unit CU.  If CU
22712    came from a separate debuginfo file, then the master objfile is
22713    returned.  */
22714
22715 struct objfile *
22716 dwarf2_per_cu_objfile (struct dwarf2_per_cu_data *per_cu)
22717 {
22718   struct objfile *objfile = per_cu->objfile;
22719
22720   /* Return the master objfile, so that we can report and look up the
22721      correct file containing this variable.  */
22722   if (objfile->separate_debug_objfile_backlink)
22723     objfile = objfile->separate_debug_objfile_backlink;
22724
22725   return objfile;
22726 }
22727
22728 /* Return comp_unit_head for PER_CU, either already available in PER_CU->CU
22729    (CU_HEADERP is unused in such case) or prepare a temporary copy at
22730    CU_HEADERP first.  */
22731
22732 static const struct comp_unit_head *
22733 per_cu_header_read_in (struct comp_unit_head *cu_headerp,
22734                        struct dwarf2_per_cu_data *per_cu)
22735 {
22736   const gdb_byte *info_ptr;
22737
22738   if (per_cu->cu)
22739     return &per_cu->cu->header;
22740
22741   info_ptr = per_cu->section->buffer + to_underlying (per_cu->sect_off);
22742
22743   memset (cu_headerp, 0, sizeof (*cu_headerp));
22744   read_comp_unit_head (cu_headerp, info_ptr, per_cu->section,
22745                        rcuh_kind::COMPILE);
22746
22747   return cu_headerp;
22748 }
22749
22750 /* Return the address size given in the compilation unit header for CU.  */
22751
22752 int
22753 dwarf2_per_cu_addr_size (struct dwarf2_per_cu_data *per_cu)
22754 {
22755   struct comp_unit_head cu_header_local;
22756   const struct comp_unit_head *cu_headerp;
22757
22758   cu_headerp = per_cu_header_read_in (&cu_header_local, per_cu);
22759
22760   return cu_headerp->addr_size;
22761 }
22762
22763 /* Return the offset size given in the compilation unit header for CU.  */
22764
22765 int
22766 dwarf2_per_cu_offset_size (struct dwarf2_per_cu_data *per_cu)
22767 {
22768   struct comp_unit_head cu_header_local;
22769   const struct comp_unit_head *cu_headerp;
22770
22771   cu_headerp = per_cu_header_read_in (&cu_header_local, per_cu);
22772
22773   return cu_headerp->offset_size;
22774 }
22775
22776 /* See its dwarf2loc.h declaration.  */
22777
22778 int
22779 dwarf2_per_cu_ref_addr_size (struct dwarf2_per_cu_data *per_cu)
22780 {
22781   struct comp_unit_head cu_header_local;
22782   const struct comp_unit_head *cu_headerp;
22783
22784   cu_headerp = per_cu_header_read_in (&cu_header_local, per_cu);
22785
22786   if (cu_headerp->version == 2)
22787     return cu_headerp->addr_size;
22788   else
22789     return cu_headerp->offset_size;
22790 }
22791
22792 /* Return the text offset of the CU.  The returned offset comes from
22793    this CU's objfile.  If this objfile came from a separate debuginfo
22794    file, then the offset may be different from the corresponding
22795    offset in the parent objfile.  */
22796
22797 CORE_ADDR
22798 dwarf2_per_cu_text_offset (struct dwarf2_per_cu_data *per_cu)
22799 {
22800   struct objfile *objfile = per_cu->objfile;
22801
22802   return ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
22803 }
22804
22805 /* Return DWARF version number of PER_CU.  */
22806
22807 short
22808 dwarf2_version (struct dwarf2_per_cu_data *per_cu)
22809 {
22810   return per_cu->dwarf_version;
22811 }
22812
22813 /* Locate the .debug_info compilation unit from CU's objfile which contains
22814    the DIE at OFFSET.  Raises an error on failure.  */
22815
22816 static struct dwarf2_per_cu_data *
22817 dwarf2_find_containing_comp_unit (sect_offset sect_off,
22818                                   unsigned int offset_in_dwz,
22819                                   struct objfile *objfile)
22820 {
22821   struct dwarf2_per_cu_data *this_cu;
22822   int low, high;
22823   const sect_offset *cu_off;
22824
22825   low = 0;
22826   high = dwarf2_per_objfile->n_comp_units - 1;
22827   while (high > low)
22828     {
22829       struct dwarf2_per_cu_data *mid_cu;
22830       int mid = low + (high - low) / 2;
22831
22832       mid_cu = dwarf2_per_objfile->all_comp_units[mid];
22833       cu_off = &mid_cu->sect_off;
22834       if (mid_cu->is_dwz > offset_in_dwz
22835           || (mid_cu->is_dwz == offset_in_dwz && *cu_off >= sect_off))
22836         high = mid;
22837       else
22838         low = mid + 1;
22839     }
22840   gdb_assert (low == high);
22841   this_cu = dwarf2_per_objfile->all_comp_units[low];
22842   cu_off = &this_cu->sect_off;
22843   if (this_cu->is_dwz != offset_in_dwz || *cu_off > sect_off)
22844     {
22845       if (low == 0 || this_cu->is_dwz != offset_in_dwz)
22846         error (_("Dwarf Error: could not find partial DIE containing "
22847                "offset 0x%x [in module %s]"),
22848                to_underlying (sect_off), bfd_get_filename (objfile->obfd));
22849
22850       gdb_assert (dwarf2_per_objfile->all_comp_units[low-1]->sect_off
22851                   <= sect_off);
22852       return dwarf2_per_objfile->all_comp_units[low-1];
22853     }
22854   else
22855     {
22856       this_cu = dwarf2_per_objfile->all_comp_units[low];
22857       if (low == dwarf2_per_objfile->n_comp_units - 1
22858           && sect_off >= this_cu->sect_off + this_cu->length)
22859         error (_("invalid dwarf2 offset %u"), to_underlying (sect_off));
22860       gdb_assert (sect_off < this_cu->sect_off + this_cu->length);
22861       return this_cu;
22862     }
22863 }
22864
22865 /* Initialize dwarf2_cu CU, owned by PER_CU.  */
22866
22867 static void
22868 init_one_comp_unit (struct dwarf2_cu *cu, struct dwarf2_per_cu_data *per_cu)
22869 {
22870   memset (cu, 0, sizeof (*cu));
22871   per_cu->cu = cu;
22872   cu->per_cu = per_cu;
22873   cu->objfile = per_cu->objfile;
22874   obstack_init (&cu->comp_unit_obstack);
22875 }
22876
22877 /* Initialize basic fields of dwarf_cu CU according to DIE COMP_UNIT_DIE.  */
22878
22879 static void
22880 prepare_one_comp_unit (struct dwarf2_cu *cu, struct die_info *comp_unit_die,
22881                        enum language pretend_language)
22882 {
22883   struct attribute *attr;
22884
22885   /* Set the language we're debugging.  */
22886   attr = dwarf2_attr (comp_unit_die, DW_AT_language, cu);
22887   if (attr)
22888     set_cu_language (DW_UNSND (attr), cu);
22889   else
22890     {
22891       cu->language = pretend_language;
22892       cu->language_defn = language_def (cu->language);
22893     }
22894
22895   cu->producer = dwarf2_string_attr (comp_unit_die, DW_AT_producer, cu);
22896 }
22897
22898 /* Release one cached compilation unit, CU.  We unlink it from the tree
22899    of compilation units, but we don't remove it from the read_in_chain;
22900    the caller is responsible for that.
22901    NOTE: DATA is a void * because this function is also used as a
22902    cleanup routine.  */
22903
22904 static void
22905 free_heap_comp_unit (void *data)
22906 {
22907   struct dwarf2_cu *cu = (struct dwarf2_cu *) data;
22908
22909   gdb_assert (cu->per_cu != NULL);
22910   cu->per_cu->cu = NULL;
22911   cu->per_cu = NULL;
22912
22913   obstack_free (&cu->comp_unit_obstack, NULL);
22914
22915   xfree (cu);
22916 }
22917
22918 /* This cleanup function is passed the address of a dwarf2_cu on the stack
22919    when we're finished with it.  We can't free the pointer itself, but be
22920    sure to unlink it from the cache.  Also release any associated storage.  */
22921
22922 static void
22923 free_stack_comp_unit (void *data)
22924 {
22925   struct dwarf2_cu *cu = (struct dwarf2_cu *) data;
22926
22927   gdb_assert (cu->per_cu != NULL);
22928   cu->per_cu->cu = NULL;
22929   cu->per_cu = NULL;
22930
22931   obstack_free (&cu->comp_unit_obstack, NULL);
22932   cu->partial_dies = NULL;
22933 }
22934
22935 /* Free all cached compilation units.  */
22936
22937 static void
22938 free_cached_comp_units (void *data)
22939 {
22940   dwarf2_per_objfile->free_cached_comp_units ();
22941 }
22942
22943 /* Increase the age counter on each cached compilation unit, and free
22944    any that are too old.  */
22945
22946 static void
22947 age_cached_comp_units (void)
22948 {
22949   struct dwarf2_per_cu_data *per_cu, **last_chain;
22950
22951   dwarf2_clear_marks (dwarf2_per_objfile->read_in_chain);
22952   per_cu = dwarf2_per_objfile->read_in_chain;
22953   while (per_cu != NULL)
22954     {
22955       per_cu->cu->last_used ++;
22956       if (per_cu->cu->last_used <= dwarf_max_cache_age)
22957         dwarf2_mark (per_cu->cu);
22958       per_cu = per_cu->cu->read_in_chain;
22959     }
22960
22961   per_cu = dwarf2_per_objfile->read_in_chain;
22962   last_chain = &dwarf2_per_objfile->read_in_chain;
22963   while (per_cu != NULL)
22964     {
22965       struct dwarf2_per_cu_data *next_cu;
22966
22967       next_cu = per_cu->cu->read_in_chain;
22968
22969       if (!per_cu->cu->mark)
22970         {
22971           free_heap_comp_unit (per_cu->cu);
22972           *last_chain = next_cu;
22973         }
22974       else
22975         last_chain = &per_cu->cu->read_in_chain;
22976
22977       per_cu = next_cu;
22978     }
22979 }
22980
22981 /* Remove a single compilation unit from the cache.  */
22982
22983 static void
22984 free_one_cached_comp_unit (struct dwarf2_per_cu_data *target_per_cu)
22985 {
22986   struct dwarf2_per_cu_data *per_cu, **last_chain;
22987
22988   per_cu = dwarf2_per_objfile->read_in_chain;
22989   last_chain = &dwarf2_per_objfile->read_in_chain;
22990   while (per_cu != NULL)
22991     {
22992       struct dwarf2_per_cu_data *next_cu;
22993
22994       next_cu = per_cu->cu->read_in_chain;
22995
22996       if (per_cu == target_per_cu)
22997         {
22998           free_heap_comp_unit (per_cu->cu);
22999           per_cu->cu = NULL;
23000           *last_chain = next_cu;
23001           break;
23002         }
23003       else
23004         last_chain = &per_cu->cu->read_in_chain;
23005
23006       per_cu = next_cu;
23007     }
23008 }
23009
23010 /* Release all extra memory associated with OBJFILE.  */
23011
23012 void
23013 dwarf2_free_objfile (struct objfile *objfile)
23014 {
23015   dwarf2_per_objfile
23016     = (struct dwarf2_per_objfile *) objfile_data (objfile,
23017                                                   dwarf2_objfile_data_key);
23018
23019   if (dwarf2_per_objfile == NULL)
23020     return;
23021
23022   dwarf2_per_objfile->~dwarf2_per_objfile ();
23023 }
23024
23025 /* A set of CU "per_cu" pointer, DIE offset, and GDB type pointer.
23026    We store these in a hash table separate from the DIEs, and preserve them
23027    when the DIEs are flushed out of cache.
23028
23029    The CU "per_cu" pointer is needed because offset alone is not enough to
23030    uniquely identify the type.  A file may have multiple .debug_types sections,
23031    or the type may come from a DWO file.  Furthermore, while it's more logical
23032    to use per_cu->section+offset, with Fission the section with the data is in
23033    the DWO file but we don't know that section at the point we need it.
23034    We have to use something in dwarf2_per_cu_data (or the pointer to it)
23035    because we can enter the lookup routine, get_die_type_at_offset, from
23036    outside this file, and thus won't necessarily have PER_CU->cu.
23037    Fortunately, PER_CU is stable for the life of the objfile.  */
23038
23039 struct dwarf2_per_cu_offset_and_type
23040 {
23041   const struct dwarf2_per_cu_data *per_cu;
23042   sect_offset sect_off;
23043   struct type *type;
23044 };
23045
23046 /* Hash function for a dwarf2_per_cu_offset_and_type.  */
23047
23048 static hashval_t
23049 per_cu_offset_and_type_hash (const void *item)
23050 {
23051   const struct dwarf2_per_cu_offset_and_type *ofs
23052     = (const struct dwarf2_per_cu_offset_and_type *) item;
23053
23054   return (uintptr_t) ofs->per_cu + to_underlying (ofs->sect_off);
23055 }
23056
23057 /* Equality function for a dwarf2_per_cu_offset_and_type.  */
23058
23059 static int
23060 per_cu_offset_and_type_eq (const void *item_lhs, const void *item_rhs)
23061 {
23062   const struct dwarf2_per_cu_offset_and_type *ofs_lhs
23063     = (const struct dwarf2_per_cu_offset_and_type *) item_lhs;
23064   const struct dwarf2_per_cu_offset_and_type *ofs_rhs
23065     = (const struct dwarf2_per_cu_offset_and_type *) item_rhs;
23066
23067   return (ofs_lhs->per_cu == ofs_rhs->per_cu
23068           && ofs_lhs->sect_off == ofs_rhs->sect_off);
23069 }
23070
23071 /* Set the type associated with DIE to TYPE.  Save it in CU's hash
23072    table if necessary.  For convenience, return TYPE.
23073
23074    The DIEs reading must have careful ordering to:
23075     * Not cause infite loops trying to read in DIEs as a prerequisite for
23076       reading current DIE.
23077     * Not trying to dereference contents of still incompletely read in types
23078       while reading in other DIEs.
23079     * Enable referencing still incompletely read in types just by a pointer to
23080       the type without accessing its fields.
23081
23082    Therefore caller should follow these rules:
23083      * Try to fetch any prerequisite types we may need to build this DIE type
23084        before building the type and calling set_die_type.
23085      * After building type call set_die_type for current DIE as soon as
23086        possible before fetching more types to complete the current type.
23087      * Make the type as complete as possible before fetching more types.  */
23088
23089 static struct type *
23090 set_die_type (struct die_info *die, struct type *type, struct dwarf2_cu *cu)
23091 {
23092   struct dwarf2_per_cu_offset_and_type **slot, ofs;
23093   struct objfile *objfile = cu->objfile;
23094   struct attribute *attr;
23095   struct dynamic_prop prop;
23096
23097   /* For Ada types, make sure that the gnat-specific data is always
23098      initialized (if not already set).  There are a few types where
23099      we should not be doing so, because the type-specific area is
23100      already used to hold some other piece of info (eg: TYPE_CODE_FLT
23101      where the type-specific area is used to store the floatformat).
23102      But this is not a problem, because the gnat-specific information
23103      is actually not needed for these types.  */
23104   if (need_gnat_info (cu)
23105       && TYPE_CODE (type) != TYPE_CODE_FUNC
23106       && TYPE_CODE (type) != TYPE_CODE_FLT
23107       && TYPE_CODE (type) != TYPE_CODE_METHODPTR
23108       && TYPE_CODE (type) != TYPE_CODE_MEMBERPTR
23109       && TYPE_CODE (type) != TYPE_CODE_METHOD
23110       && !HAVE_GNAT_AUX_INFO (type))
23111     INIT_GNAT_SPECIFIC (type);
23112
23113   /* Read DW_AT_allocated and set in type.  */
23114   attr = dwarf2_attr (die, DW_AT_allocated, cu);
23115   if (attr_form_is_block (attr))
23116     {
23117       if (attr_to_dynamic_prop (attr, die, cu, &prop))
23118         add_dyn_prop (DYN_PROP_ALLOCATED, prop, type, objfile);
23119     }
23120   else if (attr != NULL)
23121     {
23122       complaint (&symfile_complaints,
23123                  _("DW_AT_allocated has the wrong form (%s) at DIE 0x%x"),
23124                  (attr != NULL ? dwarf_form_name (attr->form) : "n/a"),
23125                  to_underlying (die->sect_off));
23126     }
23127
23128   /* Read DW_AT_associated and set in type.  */
23129   attr = dwarf2_attr (die, DW_AT_associated, cu);
23130   if (attr_form_is_block (attr))
23131     {
23132       if (attr_to_dynamic_prop (attr, die, cu, &prop))
23133         add_dyn_prop (DYN_PROP_ASSOCIATED, prop, type, objfile);
23134     }
23135   else if (attr != NULL)
23136     {
23137       complaint (&symfile_complaints,
23138                  _("DW_AT_associated has the wrong form (%s) at DIE 0x%x"),
23139                  (attr != NULL ? dwarf_form_name (attr->form) : "n/a"),
23140                  to_underlying (die->sect_off));
23141     }
23142
23143   /* Read DW_AT_data_location and set in type.  */
23144   attr = dwarf2_attr (die, DW_AT_data_location, cu);
23145   if (attr_to_dynamic_prop (attr, die, cu, &prop))
23146     add_dyn_prop (DYN_PROP_DATA_LOCATION, prop, type, objfile);
23147
23148   if (dwarf2_per_objfile->die_type_hash == NULL)
23149     {
23150       dwarf2_per_objfile->die_type_hash =
23151         htab_create_alloc_ex (127,
23152                               per_cu_offset_and_type_hash,
23153                               per_cu_offset_and_type_eq,
23154                               NULL,
23155                               &objfile->objfile_obstack,
23156                               hashtab_obstack_allocate,
23157                               dummy_obstack_deallocate);
23158     }
23159
23160   ofs.per_cu = cu->per_cu;
23161   ofs.sect_off = die->sect_off;
23162   ofs.type = type;
23163   slot = (struct dwarf2_per_cu_offset_and_type **)
23164     htab_find_slot (dwarf2_per_objfile->die_type_hash, &ofs, INSERT);
23165   if (*slot)
23166     complaint (&symfile_complaints,
23167                _("A problem internal to GDB: DIE 0x%x has type already set"),
23168                to_underlying (die->sect_off));
23169   *slot = XOBNEW (&objfile->objfile_obstack,
23170                   struct dwarf2_per_cu_offset_and_type);
23171   **slot = ofs;
23172   return type;
23173 }
23174
23175 /* Look up the type for the die at SECT_OFF in PER_CU in die_type_hash,
23176    or return NULL if the die does not have a saved type.  */
23177
23178 static struct type *
23179 get_die_type_at_offset (sect_offset sect_off,
23180                         struct dwarf2_per_cu_data *per_cu)
23181 {
23182   struct dwarf2_per_cu_offset_and_type *slot, ofs;
23183
23184   if (dwarf2_per_objfile->die_type_hash == NULL)
23185     return NULL;
23186
23187   ofs.per_cu = per_cu;
23188   ofs.sect_off = sect_off;
23189   slot = ((struct dwarf2_per_cu_offset_and_type *)
23190           htab_find (dwarf2_per_objfile->die_type_hash, &ofs));
23191   if (slot)
23192     return slot->type;
23193   else
23194     return NULL;
23195 }
23196
23197 /* Look up the type for DIE in CU in die_type_hash,
23198    or return NULL if DIE does not have a saved type.  */
23199
23200 static struct type *
23201 get_die_type (struct die_info *die, struct dwarf2_cu *cu)
23202 {
23203   return get_die_type_at_offset (die->sect_off, cu->per_cu);
23204 }
23205
23206 /* Add a dependence relationship from CU to REF_PER_CU.  */
23207
23208 static void
23209 dwarf2_add_dependence (struct dwarf2_cu *cu,
23210                        struct dwarf2_per_cu_data *ref_per_cu)
23211 {
23212   void **slot;
23213
23214   if (cu->dependencies == NULL)
23215     cu->dependencies
23216       = htab_create_alloc_ex (5, htab_hash_pointer, htab_eq_pointer,
23217                               NULL, &cu->comp_unit_obstack,
23218                               hashtab_obstack_allocate,
23219                               dummy_obstack_deallocate);
23220
23221   slot = htab_find_slot (cu->dependencies, ref_per_cu, INSERT);
23222   if (*slot == NULL)
23223     *slot = ref_per_cu;
23224 }
23225
23226 /* Subroutine of dwarf2_mark to pass to htab_traverse.
23227    Set the mark field in every compilation unit in the
23228    cache that we must keep because we are keeping CU.  */
23229
23230 static int
23231 dwarf2_mark_helper (void **slot, void *data)
23232 {
23233   struct dwarf2_per_cu_data *per_cu;
23234
23235   per_cu = (struct dwarf2_per_cu_data *) *slot;
23236
23237   /* cu->dependencies references may not yet have been ever read if QUIT aborts
23238      reading of the chain.  As such dependencies remain valid it is not much
23239      useful to track and undo them during QUIT cleanups.  */
23240   if (per_cu->cu == NULL)
23241     return 1;
23242
23243   if (per_cu->cu->mark)
23244     return 1;
23245   per_cu->cu->mark = 1;
23246
23247   if (per_cu->cu->dependencies != NULL)
23248     htab_traverse (per_cu->cu->dependencies, dwarf2_mark_helper, NULL);
23249
23250   return 1;
23251 }
23252
23253 /* Set the mark field in CU and in every other compilation unit in the
23254    cache that we must keep because we are keeping CU.  */
23255
23256 static void
23257 dwarf2_mark (struct dwarf2_cu *cu)
23258 {
23259   if (cu->mark)
23260     return;
23261   cu->mark = 1;
23262   if (cu->dependencies != NULL)
23263     htab_traverse (cu->dependencies, dwarf2_mark_helper, NULL);
23264 }
23265
23266 static void
23267 dwarf2_clear_marks (struct dwarf2_per_cu_data *per_cu)
23268 {
23269   while (per_cu)
23270     {
23271       per_cu->cu->mark = 0;
23272       per_cu = per_cu->cu->read_in_chain;
23273     }
23274 }
23275
23276 /* Trivial hash function for partial_die_info: the hash value of a DIE
23277    is its offset in .debug_info for this objfile.  */
23278
23279 static hashval_t
23280 partial_die_hash (const void *item)
23281 {
23282   const struct partial_die_info *part_die
23283     = (const struct partial_die_info *) item;
23284
23285   return to_underlying (part_die->sect_off);
23286 }
23287
23288 /* Trivial comparison function for partial_die_info structures: two DIEs
23289    are equal if they have the same offset.  */
23290
23291 static int
23292 partial_die_eq (const void *item_lhs, const void *item_rhs)
23293 {
23294   const struct partial_die_info *part_die_lhs
23295     = (const struct partial_die_info *) item_lhs;
23296   const struct partial_die_info *part_die_rhs
23297     = (const struct partial_die_info *) item_rhs;
23298
23299   return part_die_lhs->sect_off == part_die_rhs->sect_off;
23300 }
23301
23302 static struct cmd_list_element *set_dwarf_cmdlist;
23303 static struct cmd_list_element *show_dwarf_cmdlist;
23304
23305 static void
23306 set_dwarf_cmd (char *args, int from_tty)
23307 {
23308   help_list (set_dwarf_cmdlist, "maintenance set dwarf ", all_commands,
23309              gdb_stdout);
23310 }
23311
23312 static void
23313 show_dwarf_cmd (char *args, int from_tty)
23314 {
23315   cmd_show_list (show_dwarf_cmdlist, from_tty, "");
23316 }
23317
23318 /* Free data associated with OBJFILE, if necessary.  */
23319
23320 static void
23321 dwarf2_per_objfile_free (struct objfile *objfile, void *d)
23322 {
23323   struct dwarf2_per_objfile *data = (struct dwarf2_per_objfile *) d;
23324   int ix;
23325
23326   /* Make sure we don't accidentally use dwarf2_per_objfile while
23327      cleaning up.  */
23328   dwarf2_per_objfile = NULL;
23329
23330   for (ix = 0; ix < data->n_comp_units; ++ix)
23331    VEC_free (dwarf2_per_cu_ptr, data->all_comp_units[ix]->imported_symtabs);
23332
23333   for (ix = 0; ix < data->n_type_units; ++ix)
23334     VEC_free (dwarf2_per_cu_ptr,
23335               data->all_type_units[ix]->per_cu.imported_symtabs);
23336   xfree (data->all_type_units);
23337
23338   VEC_free (dwarf2_section_info_def, data->types);
23339
23340   if (data->dwo_files)
23341     free_dwo_files (data->dwo_files, objfile);
23342   if (data->dwp_file)
23343     gdb_bfd_unref (data->dwp_file->dbfd);
23344
23345   if (data->dwz_file && data->dwz_file->dwz_bfd)
23346     gdb_bfd_unref (data->dwz_file->dwz_bfd);
23347 }
23348
23349 \f
23350 /* The "save gdb-index" command.  */
23351
23352 /* In-memory buffer to prepare data to be written later to a file.  */
23353 class data_buf
23354 {
23355 public:
23356   /* Copy DATA to the end of the buffer.  */
23357   template<typename T>
23358   void append_data (const T &data)
23359   {
23360     std::copy (reinterpret_cast<const gdb_byte *> (&data),
23361                reinterpret_cast<const gdb_byte *> (&data + 1),
23362                grow (sizeof (data)));
23363   }
23364
23365   /* Copy CSTR (a zero-terminated string) to the end of buffer.  The
23366      terminating zero is appended too.  */
23367   void append_cstr0 (const char *cstr)
23368   {
23369     const size_t size = strlen (cstr) + 1;
23370     std::copy (cstr, cstr + size, grow (size));
23371   }
23372
23373   /* Accept a host-format integer in VAL and append it to the buffer
23374      as a target-format integer which is LEN bytes long.  */
23375   void append_uint (size_t len, bfd_endian byte_order, ULONGEST val)
23376   {
23377     ::store_unsigned_integer (grow (len), len, byte_order, val);
23378   }
23379
23380   /* Return the size of the buffer.  */
23381   size_t size () const
23382   {
23383     return m_vec.size ();
23384   }
23385
23386   /* Write the buffer to FILE.  */
23387   void file_write (FILE *file) const
23388   {
23389     if (::fwrite (m_vec.data (), 1, m_vec.size (), file) != m_vec.size ())
23390       error (_("couldn't write data to file"));
23391   }
23392
23393 private:
23394   /* Grow SIZE bytes at the end of the buffer.  Returns a pointer to
23395      the start of the new block.  */
23396   gdb_byte *grow (size_t size)
23397   {
23398     m_vec.resize (m_vec.size () + size);
23399     return &*m_vec.end () - size;
23400   }
23401
23402   gdb::byte_vector m_vec;
23403 };
23404
23405 /* An entry in the symbol table.  */
23406 struct symtab_index_entry
23407 {
23408   /* The name of the symbol.  */
23409   const char *name;
23410   /* The offset of the name in the constant pool.  */
23411   offset_type index_offset;
23412   /* A sorted vector of the indices of all the CUs that hold an object
23413      of this name.  */
23414   std::vector<offset_type> cu_indices;
23415 };
23416
23417 /* The symbol table.  This is a power-of-2-sized hash table.  */
23418 struct mapped_symtab
23419 {
23420   mapped_symtab ()
23421   {
23422     data.resize (1024);
23423   }
23424
23425   offset_type n_elements = 0;
23426   std::vector<symtab_index_entry> data;
23427 };
23428
23429 /* Find a slot in SYMTAB for the symbol NAME.  Returns a reference to
23430    the slot.
23431    
23432    Function is used only during write_hash_table so no index format backward
23433    compatibility is needed.  */
23434
23435 static symtab_index_entry &
23436 find_slot (struct mapped_symtab *symtab, const char *name)
23437 {
23438   offset_type index, step, hash = mapped_index_string_hash (INT_MAX, name);
23439
23440   index = hash & (symtab->data.size () - 1);
23441   step = ((hash * 17) & (symtab->data.size () - 1)) | 1;
23442
23443   for (;;)
23444     {
23445       if (symtab->data[index].name == NULL
23446           || strcmp (name, symtab->data[index].name) == 0)
23447         return symtab->data[index];
23448       index = (index + step) & (symtab->data.size () - 1);
23449     }
23450 }
23451
23452 /* Expand SYMTAB's hash table.  */
23453
23454 static void
23455 hash_expand (struct mapped_symtab *symtab)
23456 {
23457   auto old_entries = std::move (symtab->data);
23458
23459   symtab->data.clear ();
23460   symtab->data.resize (old_entries.size () * 2);
23461
23462   for (auto &it : old_entries)
23463     if (it.name != NULL)
23464       {
23465         auto &ref = find_slot (symtab, it.name);
23466         ref = std::move (it);
23467       }
23468 }
23469
23470 /* Add an entry to SYMTAB.  NAME is the name of the symbol.
23471    CU_INDEX is the index of the CU in which the symbol appears.
23472    IS_STATIC is one if the symbol is static, otherwise zero (global).  */
23473
23474 static void
23475 add_index_entry (struct mapped_symtab *symtab, const char *name,
23476                  int is_static, gdb_index_symbol_kind kind,
23477                  offset_type cu_index)
23478 {
23479   offset_type cu_index_and_attrs;
23480
23481   ++symtab->n_elements;
23482   if (4 * symtab->n_elements / 3 >= symtab->data.size ())
23483     hash_expand (symtab);
23484
23485   symtab_index_entry &slot = find_slot (symtab, name);
23486   if (slot.name == NULL)
23487     {
23488       slot.name = name;
23489       /* index_offset is set later.  */
23490     }
23491
23492   cu_index_and_attrs = 0;
23493   DW2_GDB_INDEX_CU_SET_VALUE (cu_index_and_attrs, cu_index);
23494   DW2_GDB_INDEX_SYMBOL_STATIC_SET_VALUE (cu_index_and_attrs, is_static);
23495   DW2_GDB_INDEX_SYMBOL_KIND_SET_VALUE (cu_index_and_attrs, kind);
23496
23497   /* We don't want to record an index value twice as we want to avoid the
23498      duplication.
23499      We process all global symbols and then all static symbols
23500      (which would allow us to avoid the duplication by only having to check
23501      the last entry pushed), but a symbol could have multiple kinds in one CU.
23502      To keep things simple we don't worry about the duplication here and
23503      sort and uniqufy the list after we've processed all symbols.  */
23504   slot.cu_indices.push_back (cu_index_and_attrs);
23505 }
23506
23507 /* Sort and remove duplicates of all symbols' cu_indices lists.  */
23508
23509 static void
23510 uniquify_cu_indices (struct mapped_symtab *symtab)
23511 {
23512   for (auto &entry : symtab->data)
23513     {
23514       if (entry.name != NULL && !entry.cu_indices.empty ())
23515         {
23516           auto &cu_indices = entry.cu_indices;
23517           std::sort (cu_indices.begin (), cu_indices.end ());
23518           auto from = std::unique (cu_indices.begin (), cu_indices.end ());
23519           cu_indices.erase (from, cu_indices.end ());
23520         }
23521     }
23522 }
23523
23524 /* A form of 'const char *' suitable for container keys.  Only the
23525    pointer is stored.  The strings themselves are compared, not the
23526    pointers.  */
23527 class c_str_view
23528 {
23529 public:
23530   c_str_view (const char *cstr)
23531     : m_cstr (cstr)
23532   {}
23533
23534   bool operator== (const c_str_view &other) const
23535   {
23536     return strcmp (m_cstr, other.m_cstr) == 0;
23537   }
23538
23539 private:
23540   friend class c_str_view_hasher;
23541   const char *const m_cstr;
23542 };
23543
23544 /* A std::unordered_map::hasher for c_str_view that uses the right
23545    hash function for strings in a mapped index.  */
23546 class c_str_view_hasher
23547 {
23548 public:
23549   size_t operator () (const c_str_view &x) const
23550   {
23551     return mapped_index_string_hash (INT_MAX, x.m_cstr);
23552   }
23553 };
23554
23555 /* A std::unordered_map::hasher for std::vector<>.  */
23556 template<typename T>
23557 class vector_hasher
23558 {
23559 public:
23560   size_t operator () (const std::vector<T> &key) const
23561   {
23562     return iterative_hash (key.data (),
23563                            sizeof (key.front ()) * key.size (), 0);
23564   }
23565 };
23566
23567 /* Write the mapped hash table SYMTAB to the data buffer OUTPUT, with
23568    constant pool entries going into the data buffer CPOOL.  */
23569
23570 static void
23571 write_hash_table (mapped_symtab *symtab, data_buf &output, data_buf &cpool)
23572 {
23573   {
23574     /* Elements are sorted vectors of the indices of all the CUs that
23575        hold an object of this name.  */
23576     std::unordered_map<std::vector<offset_type>, offset_type,
23577                        vector_hasher<offset_type>>
23578       symbol_hash_table;
23579
23580     /* We add all the index vectors to the constant pool first, to
23581        ensure alignment is ok.  */
23582     for (symtab_index_entry &entry : symtab->data)
23583       {
23584         if (entry.name == NULL)
23585           continue;
23586         gdb_assert (entry.index_offset == 0);
23587
23588         /* Finding before inserting is faster than always trying to
23589            insert, because inserting always allocates a node, does the
23590            lookup, and then destroys the new node if another node
23591            already had the same key.  C++17 try_emplace will avoid
23592            this.  */
23593         const auto found
23594           = symbol_hash_table.find (entry.cu_indices);
23595         if (found != symbol_hash_table.end ())
23596           {
23597             entry.index_offset = found->second;
23598             continue;
23599           }
23600
23601         symbol_hash_table.emplace (entry.cu_indices, cpool.size ());
23602         entry.index_offset = cpool.size ();
23603         cpool.append_data (MAYBE_SWAP (entry.cu_indices.size ()));
23604         for (const auto index : entry.cu_indices)
23605           cpool.append_data (MAYBE_SWAP (index));
23606       }
23607   }
23608
23609   /* Now write out the hash table.  */
23610   std::unordered_map<c_str_view, offset_type, c_str_view_hasher> str_table;
23611   for (const auto &entry : symtab->data)
23612     {
23613       offset_type str_off, vec_off;
23614
23615       if (entry.name != NULL)
23616         {
23617           const auto insertpair = str_table.emplace (entry.name, cpool.size ());
23618           if (insertpair.second)
23619             cpool.append_cstr0 (entry.name);
23620           str_off = insertpair.first->second;
23621           vec_off = entry.index_offset;
23622         }
23623       else
23624         {
23625           /* While 0 is a valid constant pool index, it is not valid
23626              to have 0 for both offsets.  */
23627           str_off = 0;
23628           vec_off = 0;
23629         }
23630
23631       output.append_data (MAYBE_SWAP (str_off));
23632       output.append_data (MAYBE_SWAP (vec_off));
23633     }
23634 }
23635
23636 typedef std::unordered_map<partial_symtab *, unsigned int> psym_index_map;
23637
23638 /* Helper struct for building the address table.  */
23639 struct addrmap_index_data
23640 {
23641   addrmap_index_data (data_buf &addr_vec_, psym_index_map &cu_index_htab_)
23642     : addr_vec (addr_vec_), cu_index_htab (cu_index_htab_)
23643   {}
23644
23645   struct objfile *objfile;
23646   data_buf &addr_vec;
23647   psym_index_map &cu_index_htab;
23648
23649   /* Non-zero if the previous_* fields are valid.
23650      We can't write an entry until we see the next entry (since it is only then
23651      that we know the end of the entry).  */
23652   int previous_valid;
23653   /* Index of the CU in the table of all CUs in the index file.  */
23654   unsigned int previous_cu_index;
23655   /* Start address of the CU.  */
23656   CORE_ADDR previous_cu_start;
23657 };
23658
23659 /* Write an address entry to ADDR_VEC.  */
23660
23661 static void
23662 add_address_entry (struct objfile *objfile, data_buf &addr_vec,
23663                    CORE_ADDR start, CORE_ADDR end, unsigned int cu_index)
23664 {
23665   CORE_ADDR baseaddr;
23666
23667   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
23668
23669   addr_vec.append_uint (8, BFD_ENDIAN_LITTLE, start - baseaddr);
23670   addr_vec.append_uint (8, BFD_ENDIAN_LITTLE, end - baseaddr);
23671   addr_vec.append_data (MAYBE_SWAP (cu_index));
23672 }
23673
23674 /* Worker function for traversing an addrmap to build the address table.  */
23675
23676 static int
23677 add_address_entry_worker (void *datap, CORE_ADDR start_addr, void *obj)
23678 {
23679   struct addrmap_index_data *data = (struct addrmap_index_data *) datap;
23680   struct partial_symtab *pst = (struct partial_symtab *) obj;
23681
23682   if (data->previous_valid)
23683     add_address_entry (data->objfile, data->addr_vec,
23684                        data->previous_cu_start, start_addr,
23685                        data->previous_cu_index);
23686
23687   data->previous_cu_start = start_addr;
23688   if (pst != NULL)
23689     {
23690       const auto it = data->cu_index_htab.find (pst);
23691       gdb_assert (it != data->cu_index_htab.cend ());
23692       data->previous_cu_index = it->second;
23693       data->previous_valid = 1;
23694     }
23695   else
23696     data->previous_valid = 0;
23697
23698   return 0;
23699 }
23700
23701 /* Write OBJFILE's address map to ADDR_VEC.
23702    CU_INDEX_HTAB is used to map addrmap entries to their CU indices
23703    in the index file.  */
23704
23705 static void
23706 write_address_map (struct objfile *objfile, data_buf &addr_vec,
23707                    psym_index_map &cu_index_htab)
23708 {
23709   struct addrmap_index_data addrmap_index_data (addr_vec, cu_index_htab);
23710
23711   /* When writing the address table, we have to cope with the fact that
23712      the addrmap iterator only provides the start of a region; we have to
23713      wait until the next invocation to get the start of the next region.  */
23714
23715   addrmap_index_data.objfile = objfile;
23716   addrmap_index_data.previous_valid = 0;
23717
23718   addrmap_foreach (objfile->psymtabs_addrmap, add_address_entry_worker,
23719                    &addrmap_index_data);
23720
23721   /* It's highly unlikely the last entry (end address = 0xff...ff)
23722      is valid, but we should still handle it.
23723      The end address is recorded as the start of the next region, but that
23724      doesn't work here.  To cope we pass 0xff...ff, this is a rare situation
23725      anyway.  */
23726   if (addrmap_index_data.previous_valid)
23727     add_address_entry (objfile, addr_vec,
23728                        addrmap_index_data.previous_cu_start, (CORE_ADDR) -1,
23729                        addrmap_index_data.previous_cu_index);
23730 }
23731
23732 /* Return the symbol kind of PSYM.  */
23733
23734 static gdb_index_symbol_kind
23735 symbol_kind (struct partial_symbol *psym)
23736 {
23737   domain_enum domain = PSYMBOL_DOMAIN (psym);
23738   enum address_class aclass = PSYMBOL_CLASS (psym);
23739
23740   switch (domain)
23741     {
23742     case VAR_DOMAIN:
23743       switch (aclass)
23744         {
23745         case LOC_BLOCK:
23746           return GDB_INDEX_SYMBOL_KIND_FUNCTION;
23747         case LOC_TYPEDEF:
23748           return GDB_INDEX_SYMBOL_KIND_TYPE;
23749         case LOC_COMPUTED:
23750         case LOC_CONST_BYTES:
23751         case LOC_OPTIMIZED_OUT:
23752         case LOC_STATIC:
23753           return GDB_INDEX_SYMBOL_KIND_VARIABLE;
23754         case LOC_CONST:
23755           /* Note: It's currently impossible to recognize psyms as enum values
23756              short of reading the type info.  For now punt.  */
23757           return GDB_INDEX_SYMBOL_KIND_VARIABLE;
23758         default:
23759           /* There are other LOC_FOO values that one might want to classify
23760              as variables, but dwarf2read.c doesn't currently use them.  */
23761           return GDB_INDEX_SYMBOL_KIND_OTHER;
23762         }
23763     case STRUCT_DOMAIN:
23764       return GDB_INDEX_SYMBOL_KIND_TYPE;
23765     default:
23766       return GDB_INDEX_SYMBOL_KIND_OTHER;
23767     }
23768 }
23769
23770 /* Add a list of partial symbols to SYMTAB.  */
23771
23772 static void
23773 write_psymbols (struct mapped_symtab *symtab,
23774                 std::unordered_set<partial_symbol *> &psyms_seen,
23775                 struct partial_symbol **psymp,
23776                 int count,
23777                 offset_type cu_index,
23778                 int is_static)
23779 {
23780   for (; count-- > 0; ++psymp)
23781     {
23782       struct partial_symbol *psym = *psymp;
23783
23784       if (SYMBOL_LANGUAGE (psym) == language_ada)
23785         error (_("Ada is not currently supported by the index"));
23786
23787       /* Only add a given psymbol once.  */
23788       if (psyms_seen.insert (psym).second)
23789         {
23790           gdb_index_symbol_kind kind = symbol_kind (psym);
23791
23792           add_index_entry (symtab, SYMBOL_SEARCH_NAME (psym),
23793                            is_static, kind, cu_index);
23794         }
23795     }
23796 }
23797
23798 /* A helper struct used when iterating over debug_types.  */
23799 struct signatured_type_index_data
23800 {
23801   signatured_type_index_data (data_buf &types_list_,
23802                               std::unordered_set<partial_symbol *> &psyms_seen_)
23803     : types_list (types_list_), psyms_seen (psyms_seen_)
23804   {}
23805
23806   struct objfile *objfile;
23807   struct mapped_symtab *symtab;
23808   data_buf &types_list;
23809   std::unordered_set<partial_symbol *> &psyms_seen;
23810   int cu_index;
23811 };
23812
23813 /* A helper function that writes a single signatured_type to an
23814    obstack.  */
23815
23816 static int
23817 write_one_signatured_type (void **slot, void *d)
23818 {
23819   struct signatured_type_index_data *info
23820     = (struct signatured_type_index_data *) d;
23821   struct signatured_type *entry = (struct signatured_type *) *slot;
23822   struct partial_symtab *psymtab = entry->per_cu.v.psymtab;
23823
23824   write_psymbols (info->symtab,
23825                   info->psyms_seen,
23826                   info->objfile->global_psymbols.list
23827                   + psymtab->globals_offset,
23828                   psymtab->n_global_syms, info->cu_index,
23829                   0);
23830   write_psymbols (info->symtab,
23831                   info->psyms_seen,
23832                   info->objfile->static_psymbols.list
23833                   + psymtab->statics_offset,
23834                   psymtab->n_static_syms, info->cu_index,
23835                   1);
23836
23837   info->types_list.append_uint (8, BFD_ENDIAN_LITTLE,
23838                                 to_underlying (entry->per_cu.sect_off));
23839   info->types_list.append_uint (8, BFD_ENDIAN_LITTLE,
23840                                 to_underlying (entry->type_offset_in_tu));
23841   info->types_list.append_uint (8, BFD_ENDIAN_LITTLE, entry->signature);
23842
23843   ++info->cu_index;
23844
23845   return 1;
23846 }
23847
23848 /* Recurse into all "included" dependencies and count their symbols as
23849    if they appeared in this psymtab.  */
23850
23851 static void
23852 recursively_count_psymbols (struct partial_symtab *psymtab,
23853                             size_t &psyms_seen)
23854 {
23855   for (int i = 0; i < psymtab->number_of_dependencies; ++i)
23856     if (psymtab->dependencies[i]->user != NULL)
23857       recursively_count_psymbols (psymtab->dependencies[i],
23858                                   psyms_seen);
23859
23860   psyms_seen += psymtab->n_global_syms;
23861   psyms_seen += psymtab->n_static_syms;
23862 }
23863
23864 /* Recurse into all "included" dependencies and write their symbols as
23865    if they appeared in this psymtab.  */
23866
23867 static void
23868 recursively_write_psymbols (struct objfile *objfile,
23869                             struct partial_symtab *psymtab,
23870                             struct mapped_symtab *symtab,
23871                             std::unordered_set<partial_symbol *> &psyms_seen,
23872                             offset_type cu_index)
23873 {
23874   int i;
23875
23876   for (i = 0; i < psymtab->number_of_dependencies; ++i)
23877     if (psymtab->dependencies[i]->user != NULL)
23878       recursively_write_psymbols (objfile, psymtab->dependencies[i],
23879                                   symtab, psyms_seen, cu_index);
23880
23881   write_psymbols (symtab,
23882                   psyms_seen,
23883                   objfile->global_psymbols.list + psymtab->globals_offset,
23884                   psymtab->n_global_syms, cu_index,
23885                   0);
23886   write_psymbols (symtab,
23887                   psyms_seen,
23888                   objfile->static_psymbols.list + psymtab->statics_offset,
23889                   psymtab->n_static_syms, cu_index,
23890                   1);
23891 }
23892
23893 /* Create an index file for OBJFILE in the directory DIR.  */
23894
23895 static void
23896 write_psymtabs_to_index (struct objfile *objfile, const char *dir)
23897 {
23898   if (dwarf2_per_objfile->using_index)
23899     error (_("Cannot use an index to create the index"));
23900
23901   if (VEC_length (dwarf2_section_info_def, dwarf2_per_objfile->types) > 1)
23902     error (_("Cannot make an index when the file has multiple .debug_types sections"));
23903
23904   if (!objfile->psymtabs || !objfile->psymtabs_addrmap)
23905     return;
23906
23907   struct stat st;
23908   if (stat (objfile_name (objfile), &st) < 0)
23909     perror_with_name (objfile_name (objfile));
23910
23911   std::string filename (std::string (dir) + SLASH_STRING
23912                         + lbasename (objfile_name (objfile)) + INDEX_SUFFIX);
23913
23914   FILE *out_file = gdb_fopen_cloexec (filename.c_str (), "wb").release ();
23915   if (!out_file)
23916     error (_("Can't open `%s' for writing"), filename.c_str ());
23917
23918   /* Order matters here; we want FILE to be closed before FILENAME is
23919      unlinked, because on MS-Windows one cannot delete a file that is
23920      still open.  (Don't call anything here that might throw until
23921      file_closer is created.)  */
23922   gdb::unlinker unlink_file (filename.c_str ());
23923   gdb_file_up close_out_file (out_file);
23924
23925   mapped_symtab symtab;
23926   data_buf cu_list;
23927
23928   /* While we're scanning CU's create a table that maps a psymtab pointer
23929      (which is what addrmap records) to its index (which is what is recorded
23930      in the index file).  This will later be needed to write the address
23931      table.  */
23932   psym_index_map cu_index_htab;
23933   cu_index_htab.reserve (dwarf2_per_objfile->n_comp_units);
23934
23935   /* The CU list is already sorted, so we don't need to do additional
23936      work here.  Also, the debug_types entries do not appear in
23937      all_comp_units, but only in their own hash table.  */
23938
23939   /* The psyms_seen set is potentially going to be largish (~40k
23940      elements when indexing a -g3 build of GDB itself).  Estimate the
23941      number of elements in order to avoid too many rehashes, which
23942      require rebuilding buckets and thus many trips to
23943      malloc/free.  */
23944   size_t psyms_count = 0;
23945   for (int i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
23946     {
23947       struct dwarf2_per_cu_data *per_cu
23948         = dwarf2_per_objfile->all_comp_units[i];
23949       struct partial_symtab *psymtab = per_cu->v.psymtab;
23950
23951       if (psymtab != NULL && psymtab->user == NULL)
23952         recursively_count_psymbols (psymtab, psyms_count);
23953     }
23954   /* Generating an index for gdb itself shows a ratio of
23955      TOTAL_SEEN_SYMS/UNIQUE_SYMS or ~5.  4 seems like a good bet.  */
23956   std::unordered_set<partial_symbol *> psyms_seen (psyms_count / 4);
23957   for (int i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
23958     {
23959       struct dwarf2_per_cu_data *per_cu
23960         = dwarf2_per_objfile->all_comp_units[i];
23961       struct partial_symtab *psymtab = per_cu->v.psymtab;
23962
23963       /* CU of a shared file from 'dwz -m' may be unused by this main file.
23964          It may be referenced from a local scope but in such case it does not
23965          need to be present in .gdb_index.  */
23966       if (psymtab == NULL)
23967         continue;
23968
23969       if (psymtab->user == NULL)
23970         recursively_write_psymbols (objfile, psymtab, &symtab,
23971                                     psyms_seen, i);
23972
23973       const auto insertpair = cu_index_htab.emplace (psymtab, i);
23974       gdb_assert (insertpair.second);
23975
23976       cu_list.append_uint (8, BFD_ENDIAN_LITTLE,
23977                            to_underlying (per_cu->sect_off));
23978       cu_list.append_uint (8, BFD_ENDIAN_LITTLE, per_cu->length);
23979     }
23980
23981   /* Dump the address map.  */
23982   data_buf addr_vec;
23983   write_address_map (objfile, addr_vec, cu_index_htab);
23984
23985   /* Write out the .debug_type entries, if any.  */
23986   data_buf types_cu_list;
23987   if (dwarf2_per_objfile->signatured_types)
23988     {
23989       signatured_type_index_data sig_data (types_cu_list,
23990                                            psyms_seen);
23991
23992       sig_data.objfile = objfile;
23993       sig_data.symtab = &symtab;
23994       sig_data.cu_index = dwarf2_per_objfile->n_comp_units;
23995       htab_traverse_noresize (dwarf2_per_objfile->signatured_types,
23996                               write_one_signatured_type, &sig_data);
23997     }
23998
23999   /* Now that we've processed all symbols we can shrink their cu_indices
24000      lists.  */
24001   uniquify_cu_indices (&symtab);
24002
24003   data_buf symtab_vec, constant_pool;
24004   write_hash_table (&symtab, symtab_vec, constant_pool);
24005
24006   data_buf contents;
24007   const offset_type size_of_contents = 6 * sizeof (offset_type);
24008   offset_type total_len = size_of_contents;
24009
24010   /* The version number.  */
24011   contents.append_data (MAYBE_SWAP (8));
24012
24013   /* The offset of the CU list from the start of the file.  */
24014   contents.append_data (MAYBE_SWAP (total_len));
24015   total_len += cu_list.size ();
24016
24017   /* The offset of the types CU list from the start of the file.  */
24018   contents.append_data (MAYBE_SWAP (total_len));
24019   total_len += types_cu_list.size ();
24020
24021   /* The offset of the address table from the start of the file.  */
24022   contents.append_data (MAYBE_SWAP (total_len));
24023   total_len += addr_vec.size ();
24024
24025   /* The offset of the symbol table from the start of the file.  */
24026   contents.append_data (MAYBE_SWAP (total_len));
24027   total_len += symtab_vec.size ();
24028
24029   /* The offset of the constant pool from the start of the file.  */
24030   contents.append_data (MAYBE_SWAP (total_len));
24031   total_len += constant_pool.size ();
24032
24033   gdb_assert (contents.size () == size_of_contents);
24034
24035   contents.file_write (out_file);
24036   cu_list.file_write (out_file);
24037   types_cu_list.file_write (out_file);
24038   addr_vec.file_write (out_file);
24039   symtab_vec.file_write (out_file);
24040   constant_pool.file_write (out_file);
24041
24042   /* We want to keep the file.  */
24043   unlink_file.keep ();
24044 }
24045
24046 /* Implementation of the `save gdb-index' command.
24047    
24048    Note that the file format used by this command is documented in the
24049    GDB manual.  Any changes here must be documented there.  */
24050
24051 static void
24052 save_gdb_index_command (char *arg, int from_tty)
24053 {
24054   struct objfile *objfile;
24055
24056   if (!arg || !*arg)
24057     error (_("usage: save gdb-index DIRECTORY"));
24058
24059   ALL_OBJFILES (objfile)
24060   {
24061     struct stat st;
24062
24063     /* If the objfile does not correspond to an actual file, skip it.  */
24064     if (stat (objfile_name (objfile), &st) < 0)
24065       continue;
24066
24067     dwarf2_per_objfile
24068       = (struct dwarf2_per_objfile *) objfile_data (objfile,
24069                                                     dwarf2_objfile_data_key);
24070     if (dwarf2_per_objfile)
24071       {
24072
24073         TRY
24074           {
24075             write_psymtabs_to_index (objfile, arg);
24076           }
24077         CATCH (except, RETURN_MASK_ERROR)
24078           {
24079             exception_fprintf (gdb_stderr, except,
24080                                _("Error while writing index for `%s': "),
24081                                objfile_name (objfile));
24082           }
24083         END_CATCH
24084       }
24085   }
24086 }
24087
24088 \f
24089
24090 int dwarf_always_disassemble;
24091
24092 static void
24093 show_dwarf_always_disassemble (struct ui_file *file, int from_tty,
24094                                struct cmd_list_element *c, const char *value)
24095 {
24096   fprintf_filtered (file,
24097                     _("Whether to always disassemble "
24098                       "DWARF expressions is %s.\n"),
24099                     value);
24100 }
24101
24102 static void
24103 show_check_physname (struct ui_file *file, int from_tty,
24104                      struct cmd_list_element *c, const char *value)
24105 {
24106   fprintf_filtered (file,
24107                     _("Whether to check \"physname\" is %s.\n"),
24108                     value);
24109 }
24110
24111 void _initialize_dwarf2_read (void);
24112
24113 void
24114 _initialize_dwarf2_read (void)
24115 {
24116   struct cmd_list_element *c;
24117
24118   dwarf2_objfile_data_key
24119     = register_objfile_data_with_cleanup (NULL, dwarf2_per_objfile_free);
24120
24121   add_prefix_cmd ("dwarf", class_maintenance, set_dwarf_cmd, _("\
24122 Set DWARF specific variables.\n\
24123 Configure DWARF variables such as the cache size"),
24124                   &set_dwarf_cmdlist, "maintenance set dwarf ",
24125                   0/*allow-unknown*/, &maintenance_set_cmdlist);
24126
24127   add_prefix_cmd ("dwarf", class_maintenance, show_dwarf_cmd, _("\
24128 Show DWARF specific variables\n\
24129 Show DWARF variables such as the cache size"),
24130                   &show_dwarf_cmdlist, "maintenance show dwarf ",
24131                   0/*allow-unknown*/, &maintenance_show_cmdlist);
24132
24133   add_setshow_zinteger_cmd ("max-cache-age", class_obscure,
24134                             &dwarf_max_cache_age, _("\
24135 Set the upper bound on the age of cached DWARF compilation units."), _("\
24136 Show the upper bound on the age of cached DWARF compilation units."), _("\
24137 A higher limit means that cached compilation units will be stored\n\
24138 in memory longer, and more total memory will be used.  Zero disables\n\
24139 caching, which can slow down startup."),
24140                             NULL,
24141                             show_dwarf_max_cache_age,
24142                             &set_dwarf_cmdlist,
24143                             &show_dwarf_cmdlist);
24144
24145   add_setshow_boolean_cmd ("always-disassemble", class_obscure,
24146                            &dwarf_always_disassemble, _("\
24147 Set whether `info address' always disassembles DWARF expressions."), _("\
24148 Show whether `info address' always disassembles DWARF expressions."), _("\
24149 When enabled, DWARF expressions are always printed in an assembly-like\n\
24150 syntax.  When disabled, expressions will be printed in a more\n\
24151 conversational style, when possible."),
24152                            NULL,
24153                            show_dwarf_always_disassemble,
24154                            &set_dwarf_cmdlist,
24155                            &show_dwarf_cmdlist);
24156
24157   add_setshow_zuinteger_cmd ("dwarf-read", no_class, &dwarf_read_debug, _("\
24158 Set debugging of the DWARF reader."), _("\
24159 Show debugging of the DWARF reader."), _("\
24160 When enabled (non-zero), debugging messages are printed during DWARF\n\
24161 reading and symtab expansion.  A value of 1 (one) provides basic\n\
24162 information.  A value greater than 1 provides more verbose information."),
24163                             NULL,
24164                             NULL,
24165                             &setdebuglist, &showdebuglist);
24166
24167   add_setshow_zuinteger_cmd ("dwarf-die", no_class, &dwarf_die_debug, _("\
24168 Set debugging of the DWARF DIE reader."), _("\
24169 Show debugging of the DWARF DIE reader."), _("\
24170 When enabled (non-zero), DIEs are dumped after they are read in.\n\
24171 The value is the maximum depth to print."),
24172                              NULL,
24173                              NULL,
24174                              &setdebuglist, &showdebuglist);
24175
24176   add_setshow_zuinteger_cmd ("dwarf-line", no_class, &dwarf_line_debug, _("\
24177 Set debugging of the dwarf line reader."), _("\
24178 Show debugging of the dwarf line reader."), _("\
24179 When enabled (non-zero), line number entries are dumped as they are read in.\n\
24180 A value of 1 (one) provides basic information.\n\
24181 A value greater than 1 provides more verbose information."),
24182                              NULL,
24183                              NULL,
24184                              &setdebuglist, &showdebuglist);
24185
24186   add_setshow_boolean_cmd ("check-physname", no_class, &check_physname, _("\
24187 Set cross-checking of \"physname\" code against demangler."), _("\
24188 Show cross-checking of \"physname\" code against demangler."), _("\
24189 When enabled, GDB's internal \"physname\" code is checked against\n\
24190 the demangler."),
24191                            NULL, show_check_physname,
24192                            &setdebuglist, &showdebuglist);
24193
24194   add_setshow_boolean_cmd ("use-deprecated-index-sections",
24195                            no_class, &use_deprecated_index_sections, _("\
24196 Set whether to use deprecated gdb_index sections."), _("\
24197 Show whether to use deprecated gdb_index sections."), _("\
24198 When enabled, deprecated .gdb_index sections are used anyway.\n\
24199 Normally they are ignored either because of a missing feature or\n\
24200 performance issue.\n\
24201 Warning: This option must be enabled before gdb reads the file."),
24202                            NULL,
24203                            NULL,
24204                            &setlist, &showlist);
24205
24206   c = add_cmd ("gdb-index", class_files, save_gdb_index_command,
24207                _("\
24208 Save a gdb-index file.\n\
24209 Usage: save gdb-index DIRECTORY"),
24210                &save_cmdlist);
24211   set_cmd_completer (c, filename_completer);
24212
24213   dwarf2_locexpr_index = register_symbol_computed_impl (LOC_COMPUTED,
24214                                                         &dwarf2_locexpr_funcs);
24215   dwarf2_loclist_index = register_symbol_computed_impl (LOC_COMPUTED,
24216                                                         &dwarf2_loclist_funcs);
24217
24218   dwarf2_locexpr_block_index = register_symbol_block_impl (LOC_BLOCK,
24219                                         &dwarf2_block_frame_base_locexpr_funcs);
24220   dwarf2_loclist_block_index = register_symbol_block_impl (LOC_BLOCK,
24221                                         &dwarf2_block_frame_base_loclist_funcs);
24222 }