Change gdb_realpath to return a unique_xmalloc_ptr
[external/binutils.git] / gdb / dwarf2read.c
1 /* DWARF 2 debugging format support for GDB.
2
3    Copyright (C) 1994-2017 Free Software Foundation, Inc.
4
5    Adapted by Gary Funck (gary@intrepid.com), Intrepid Technology,
6    Inc.  with support from Florida State University (under contract
7    with the Ada Joint Program Office), and Silicon Graphics, Inc.
8    Initial contribution by Brent Benson, Harris Computer Systems, Inc.,
9    based on Fred Fish's (Cygnus Support) implementation of DWARF 1
10    support.
11
12    This file is part of GDB.
13
14    This program is free software; you can redistribute it and/or modify
15    it under the terms of the GNU General Public License as published by
16    the Free Software Foundation; either version 3 of the License, or
17    (at your option) any later version.
18
19    This program is distributed in the hope that it will be useful,
20    but WITHOUT ANY WARRANTY; without even the implied warranty of
21    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
22    GNU General Public License for more details.
23
24    You should have received a copy of the GNU General Public License
25    along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
26
27 /* FIXME: Various die-reading functions need to be more careful with
28    reading off the end of the section.
29    E.g., load_partial_dies, read_partial_die.  */
30
31 #include "defs.h"
32 #include "bfd.h"
33 #include "elf-bfd.h"
34 #include "symtab.h"
35 #include "gdbtypes.h"
36 #include "objfiles.h"
37 #include "dwarf2.h"
38 #include "buildsym.h"
39 #include "demangle.h"
40 #include "gdb-demangle.h"
41 #include "expression.h"
42 #include "filenames.h"  /* for DOSish file names */
43 #include "macrotab.h"
44 #include "language.h"
45 #include "complaints.h"
46 #include "bcache.h"
47 #include "dwarf2expr.h"
48 #include "dwarf2loc.h"
49 #include "cp-support.h"
50 #include "hashtab.h"
51 #include "command.h"
52 #include "gdbcmd.h"
53 #include "block.h"
54 #include "addrmap.h"
55 #include "typeprint.h"
56 #include "psympriv.h"
57 #include <sys/stat.h>
58 #include "completer.h"
59 #include "vec.h"
60 #include "c-lang.h"
61 #include "go-lang.h"
62 #include "valprint.h"
63 #include "gdbcore.h" /* for gnutarget */
64 #include "gdb/gdb-index.h"
65 #include <ctype.h>
66 #include "gdb_bfd.h"
67 #include "f-lang.h"
68 #include "source.h"
69 #include "filestuff.h"
70 #include "build-id.h"
71 #include "namespace.h"
72 #include "common/gdb_unlinker.h"
73 #include "common/function-view.h"
74 #include "common/gdb_optional.h"
75 #include "common/underlying.h"
76 #include "common/byte-vector.h"
77 #include "filename-seen-cache.h"
78 #include <fcntl.h>
79 #include <sys/types.h>
80 #include <algorithm>
81 #include <unordered_set>
82 #include <unordered_map>
83
84 typedef struct symbol *symbolp;
85 DEF_VEC_P (symbolp);
86
87 /* When == 1, print basic high level tracing messages.
88    When > 1, be more verbose.
89    This is in contrast to the low level DIE reading of dwarf_die_debug.  */
90 static unsigned int dwarf_read_debug = 0;
91
92 /* When non-zero, dump DIEs after they are read in.  */
93 static unsigned int dwarf_die_debug = 0;
94
95 /* When non-zero, dump line number entries as they are read in.  */
96 static unsigned int dwarf_line_debug = 0;
97
98 /* When non-zero, cross-check physname against demangler.  */
99 static int check_physname = 0;
100
101 /* When non-zero, do not reject deprecated .gdb_index sections.  */
102 static int use_deprecated_index_sections = 0;
103
104 static const struct objfile_data *dwarf2_objfile_data_key;
105
106 /* The "aclass" indices for various kinds of computed DWARF symbols.  */
107
108 static int dwarf2_locexpr_index;
109 static int dwarf2_loclist_index;
110 static int dwarf2_locexpr_block_index;
111 static int dwarf2_loclist_block_index;
112
113 /* A descriptor for dwarf sections.
114
115    S.ASECTION, SIZE are typically initialized when the objfile is first
116    scanned.  BUFFER, READIN are filled in later when the section is read.
117    If the section contained compressed data then SIZE is updated to record
118    the uncompressed size of the section.
119
120    DWP file format V2 introduces a wrinkle that is easiest to handle by
121    creating the concept of virtual sections contained within a real section.
122    In DWP V2 the sections of the input DWO files are concatenated together
123    into one section, but section offsets are kept relative to the original
124    input section.
125    If this is a virtual dwp-v2 section, S.CONTAINING_SECTION is a backlink to
126    the real section this "virtual" section is contained in, and BUFFER,SIZE
127    describe the virtual section.  */
128
129 struct dwarf2_section_info
130 {
131   union
132   {
133     /* If this is a real section, the bfd section.  */
134     asection *section;
135     /* If this is a virtual section, pointer to the containing ("real")
136        section.  */
137     struct dwarf2_section_info *containing_section;
138   } s;
139   /* Pointer to section data, only valid if readin.  */
140   const gdb_byte *buffer;
141   /* The size of the section, real or virtual.  */
142   bfd_size_type size;
143   /* If this is a virtual section, the offset in the real section.
144      Only valid if is_virtual.  */
145   bfd_size_type virtual_offset;
146   /* True if we have tried to read this section.  */
147   char readin;
148   /* True if this is a virtual section, False otherwise.
149      This specifies which of s.section and s.containing_section to use.  */
150   char is_virtual;
151 };
152
153 typedef struct dwarf2_section_info dwarf2_section_info_def;
154 DEF_VEC_O (dwarf2_section_info_def);
155
156 /* All offsets in the index are of this type.  It must be
157    architecture-independent.  */
158 typedef uint32_t offset_type;
159
160 DEF_VEC_I (offset_type);
161
162 /* Ensure only legit values are used.  */
163 #define DW2_GDB_INDEX_SYMBOL_STATIC_SET_VALUE(cu_index, value) \
164   do { \
165     gdb_assert ((unsigned int) (value) <= 1); \
166     GDB_INDEX_SYMBOL_STATIC_SET_VALUE((cu_index), (value)); \
167   } while (0)
168
169 /* Ensure only legit values are used.  */
170 #define DW2_GDB_INDEX_SYMBOL_KIND_SET_VALUE(cu_index, value) \
171   do { \
172     gdb_assert ((value) >= GDB_INDEX_SYMBOL_KIND_TYPE \
173                 && (value) <= GDB_INDEX_SYMBOL_KIND_OTHER); \
174     GDB_INDEX_SYMBOL_KIND_SET_VALUE((cu_index), (value)); \
175   } while (0)
176
177 /* Ensure we don't use more than the alloted nuber of bits for the CU.  */
178 #define DW2_GDB_INDEX_CU_SET_VALUE(cu_index, value) \
179   do { \
180     gdb_assert (((value) & ~GDB_INDEX_CU_MASK) == 0); \
181     GDB_INDEX_CU_SET_VALUE((cu_index), (value)); \
182   } while (0)
183
184 /* A description of the mapped index.  The file format is described in
185    a comment by the code that writes the index.  */
186 struct mapped_index
187 {
188   /* Index data format version.  */
189   int version;
190
191   /* The total length of the buffer.  */
192   off_t total_size;
193
194   /* A pointer to the address table data.  */
195   const gdb_byte *address_table;
196
197   /* Size of the address table data in bytes.  */
198   offset_type address_table_size;
199
200   /* The symbol table, implemented as a hash table.  */
201   const offset_type *symbol_table;
202
203   /* Size in slots, each slot is 2 offset_types.  */
204   offset_type symbol_table_slots;
205
206   /* A pointer to the constant pool.  */
207   const char *constant_pool;
208 };
209
210 typedef struct dwarf2_per_cu_data *dwarf2_per_cu_ptr;
211 DEF_VEC_P (dwarf2_per_cu_ptr);
212
213 struct tu_stats
214 {
215   int nr_uniq_abbrev_tables;
216   int nr_symtabs;
217   int nr_symtab_sharers;
218   int nr_stmt_less_type_units;
219   int nr_all_type_units_reallocs;
220 };
221
222 /* Collection of data recorded per objfile.
223    This hangs off of dwarf2_objfile_data_key.  */
224
225 struct dwarf2_per_objfile
226 {
227   /* Construct a dwarf2_per_objfile for OBJFILE.  NAMES points to the
228      dwarf2 section names, or is NULL if the standard ELF names are
229      used.  */
230   dwarf2_per_objfile (struct objfile *objfile,
231                       const dwarf2_debug_sections *names);
232
233   ~dwarf2_per_objfile ();
234
235   /* Disable copy.  */
236   dwarf2_per_objfile (const dwarf2_per_objfile &) = delete;
237   void operator= (const dwarf2_per_objfile &) = delete;
238
239   /* Free all cached compilation units.  */
240   void free_cached_comp_units ();
241 private:
242   /* This function is mapped across the sections and remembers the
243      offset and size of each of the debugging sections we are
244      interested in.  */
245   void locate_sections (bfd *abfd, asection *sectp,
246                         const dwarf2_debug_sections &names);
247
248 public:
249   dwarf2_section_info info {};
250   dwarf2_section_info abbrev {};
251   dwarf2_section_info line {};
252   dwarf2_section_info loc {};
253   dwarf2_section_info loclists {};
254   dwarf2_section_info macinfo {};
255   dwarf2_section_info macro {};
256   dwarf2_section_info str {};
257   dwarf2_section_info line_str {};
258   dwarf2_section_info ranges {};
259   dwarf2_section_info rnglists {};
260   dwarf2_section_info addr {};
261   dwarf2_section_info frame {};
262   dwarf2_section_info eh_frame {};
263   dwarf2_section_info gdb_index {};
264
265   VEC (dwarf2_section_info_def) *types = NULL;
266
267   /* Back link.  */
268   struct objfile *objfile = NULL;
269
270   /* Table of all the compilation units.  This is used to locate
271      the target compilation unit of a particular reference.  */
272   struct dwarf2_per_cu_data **all_comp_units = NULL;
273
274   /* The number of compilation units in ALL_COMP_UNITS.  */
275   int n_comp_units = 0;
276
277   /* The number of .debug_types-related CUs.  */
278   int n_type_units = 0;
279
280   /* The number of elements allocated in all_type_units.
281      If there are skeleton-less TUs, we add them to all_type_units lazily.  */
282   int n_allocated_type_units = 0;
283
284   /* The .debug_types-related CUs (TUs).
285      This is stored in malloc space because we may realloc it.  */
286   struct signatured_type **all_type_units = NULL;
287
288   /* Table of struct type_unit_group objects.
289      The hash key is the DW_AT_stmt_list value.  */
290   htab_t type_unit_groups {};
291
292   /* A table mapping .debug_types signatures to its signatured_type entry.
293      This is NULL if the .debug_types section hasn't been read in yet.  */
294   htab_t signatured_types {};
295
296   /* Type unit statistics, to see how well the scaling improvements
297      are doing.  */
298   struct tu_stats tu_stats {};
299
300   /* A chain of compilation units that are currently read in, so that
301      they can be freed later.  */
302   dwarf2_per_cu_data *read_in_chain = NULL;
303
304   /* A table mapping DW_AT_dwo_name values to struct dwo_file objects.
305      This is NULL if the table hasn't been allocated yet.  */
306   htab_t dwo_files {};
307
308   /* True if we've checked for whether there is a DWP file.  */
309   bool dwp_checked = false;
310
311   /* The DWP file if there is one, or NULL.  */
312   struct dwp_file *dwp_file = NULL;
313
314   /* The shared '.dwz' file, if one exists.  This is used when the
315      original data was compressed using 'dwz -m'.  */
316   struct dwz_file *dwz_file = NULL;
317
318   /* A flag indicating whether this objfile has a section loaded at a
319      VMA of 0.  */
320   bool has_section_at_zero = false;
321
322   /* True if we are using the mapped index,
323      or we are faking it for OBJF_READNOW's sake.  */
324   bool using_index = false;
325
326   /* The mapped index, or NULL if .gdb_index is missing or not being used.  */
327   mapped_index *index_table = NULL;
328
329   /* When using index_table, this keeps track of all quick_file_names entries.
330      TUs typically share line table entries with a CU, so we maintain a
331      separate table of all line table entries to support the sharing.
332      Note that while there can be way more TUs than CUs, we've already
333      sorted all the TUs into "type unit groups", grouped by their
334      DW_AT_stmt_list value.  Therefore the only sharing done here is with a
335      CU and its associated TU group if there is one.  */
336   htab_t quick_file_names_table {};
337
338   /* Set during partial symbol reading, to prevent queueing of full
339      symbols.  */
340   bool reading_partial_symbols = false;
341
342   /* Table mapping type DIEs to their struct type *.
343      This is NULL if not allocated yet.
344      The mapping is done via (CU/TU + DIE offset) -> type.  */
345   htab_t die_type_hash {};
346
347   /* The CUs we recently read.  */
348   VEC (dwarf2_per_cu_ptr) *just_read_cus = NULL;
349
350   /* Table containing line_header indexed by offset and offset_in_dwz.  */
351   htab_t line_header_hash {};
352
353   /* Table containing all filenames.  This is an optional because the
354      table is lazily constructed on first access.  */
355   gdb::optional<filename_seen_cache> filenames_cache;
356 };
357
358 static struct dwarf2_per_objfile *dwarf2_per_objfile;
359
360 /* Default names of the debugging sections.  */
361
362 /* Note that if the debugging section has been compressed, it might
363    have a name like .zdebug_info.  */
364
365 static const struct dwarf2_debug_sections dwarf2_elf_names =
366 {
367   { ".debug_info", ".zdebug_info" },
368   { ".debug_abbrev", ".zdebug_abbrev" },
369   { ".debug_line", ".zdebug_line" },
370   { ".debug_loc", ".zdebug_loc" },
371   { ".debug_loclists", ".zdebug_loclists" },
372   { ".debug_macinfo", ".zdebug_macinfo" },
373   { ".debug_macro", ".zdebug_macro" },
374   { ".debug_str", ".zdebug_str" },
375   { ".debug_line_str", ".zdebug_line_str" },
376   { ".debug_ranges", ".zdebug_ranges" },
377   { ".debug_rnglists", ".zdebug_rnglists" },
378   { ".debug_types", ".zdebug_types" },
379   { ".debug_addr", ".zdebug_addr" },
380   { ".debug_frame", ".zdebug_frame" },
381   { ".eh_frame", NULL },
382   { ".gdb_index", ".zgdb_index" },
383   23
384 };
385
386 /* List of DWO/DWP sections.  */
387
388 static const struct dwop_section_names
389 {
390   struct dwarf2_section_names abbrev_dwo;
391   struct dwarf2_section_names info_dwo;
392   struct dwarf2_section_names line_dwo;
393   struct dwarf2_section_names loc_dwo;
394   struct dwarf2_section_names loclists_dwo;
395   struct dwarf2_section_names macinfo_dwo;
396   struct dwarf2_section_names macro_dwo;
397   struct dwarf2_section_names str_dwo;
398   struct dwarf2_section_names str_offsets_dwo;
399   struct dwarf2_section_names types_dwo;
400   struct dwarf2_section_names cu_index;
401   struct dwarf2_section_names tu_index;
402 }
403 dwop_section_names =
404 {
405   { ".debug_abbrev.dwo", ".zdebug_abbrev.dwo" },
406   { ".debug_info.dwo", ".zdebug_info.dwo" },
407   { ".debug_line.dwo", ".zdebug_line.dwo" },
408   { ".debug_loc.dwo", ".zdebug_loc.dwo" },
409   { ".debug_loclists.dwo", ".zdebug_loclists.dwo" },
410   { ".debug_macinfo.dwo", ".zdebug_macinfo.dwo" },
411   { ".debug_macro.dwo", ".zdebug_macro.dwo" },
412   { ".debug_str.dwo", ".zdebug_str.dwo" },
413   { ".debug_str_offsets.dwo", ".zdebug_str_offsets.dwo" },
414   { ".debug_types.dwo", ".zdebug_types.dwo" },
415   { ".debug_cu_index", ".zdebug_cu_index" },
416   { ".debug_tu_index", ".zdebug_tu_index" },
417 };
418
419 /* local data types */
420
421 /* The data in a compilation unit header, after target2host
422    translation, looks like this.  */
423 struct comp_unit_head
424 {
425   unsigned int length;
426   short version;
427   unsigned char addr_size;
428   unsigned char signed_addr_p;
429   sect_offset abbrev_sect_off;
430
431   /* Size of file offsets; either 4 or 8.  */
432   unsigned int offset_size;
433
434   /* Size of the length field; either 4 or 12.  */
435   unsigned int initial_length_size;
436
437   enum dwarf_unit_type unit_type;
438
439   /* Offset to the first byte of this compilation unit header in the
440      .debug_info section, for resolving relative reference dies.  */
441   sect_offset sect_off;
442
443   /* Offset to first die in this cu from the start of the cu.
444      This will be the first byte following the compilation unit header.  */
445   cu_offset first_die_cu_offset;
446
447   /* 64-bit signature of this type unit - it is valid only for
448      UNIT_TYPE DW_UT_type.  */
449   ULONGEST signature;
450
451   /* For types, offset in the type's DIE of the type defined by this TU.  */
452   cu_offset type_cu_offset_in_tu;
453 };
454
455 /* Type used for delaying computation of method physnames.
456    See comments for compute_delayed_physnames.  */
457 struct delayed_method_info
458 {
459   /* The type to which the method is attached, i.e., its parent class.  */
460   struct type *type;
461
462   /* The index of the method in the type's function fieldlists.  */
463   int fnfield_index;
464
465   /* The index of the method in the fieldlist.  */
466   int index;
467
468   /* The name of the DIE.  */
469   const char *name;
470
471   /*  The DIE associated with this method.  */
472   struct die_info *die;
473 };
474
475 typedef struct delayed_method_info delayed_method_info;
476 DEF_VEC_O (delayed_method_info);
477
478 /* Internal state when decoding a particular compilation unit.  */
479 struct dwarf2_cu
480 {
481   /* The objfile containing this compilation unit.  */
482   struct objfile *objfile;
483
484   /* The header of the compilation unit.  */
485   struct comp_unit_head header;
486
487   /* Base address of this compilation unit.  */
488   CORE_ADDR base_address;
489
490   /* Non-zero if base_address has been set.  */
491   int base_known;
492
493   /* The language we are debugging.  */
494   enum language language;
495   const struct language_defn *language_defn;
496
497   const char *producer;
498
499   /* The generic symbol table building routines have separate lists for
500      file scope symbols and all all other scopes (local scopes).  So
501      we need to select the right one to pass to add_symbol_to_list().
502      We do it by keeping a pointer to the correct list in list_in_scope.
503
504      FIXME: The original dwarf code just treated the file scope as the
505      first local scope, and all other local scopes as nested local
506      scopes, and worked fine.  Check to see if we really need to
507      distinguish these in buildsym.c.  */
508   struct pending **list_in_scope;
509
510   /* The abbrev table for this CU.
511      Normally this points to the abbrev table in the objfile.
512      But if DWO_UNIT is non-NULL this is the abbrev table in the DWO file.  */
513   struct abbrev_table *abbrev_table;
514
515   /* Hash table holding all the loaded partial DIEs
516      with partial_die->offset.SECT_OFF as hash.  */
517   htab_t partial_dies;
518
519   /* Storage for things with the same lifetime as this read-in compilation
520      unit, including partial DIEs.  */
521   struct obstack comp_unit_obstack;
522
523   /* When multiple dwarf2_cu structures are living in memory, this field
524      chains them all together, so that they can be released efficiently.
525      We will probably also want a generation counter so that most-recently-used
526      compilation units are cached...  */
527   struct dwarf2_per_cu_data *read_in_chain;
528
529   /* Backlink to our per_cu entry.  */
530   struct dwarf2_per_cu_data *per_cu;
531
532   /* How many compilation units ago was this CU last referenced?  */
533   int last_used;
534
535   /* A hash table of DIE cu_offset for following references with
536      die_info->offset.sect_off as hash.  */
537   htab_t die_hash;
538
539   /* Full DIEs if read in.  */
540   struct die_info *dies;
541
542   /* A set of pointers to dwarf2_per_cu_data objects for compilation
543      units referenced by this one.  Only set during full symbol processing;
544      partial symbol tables do not have dependencies.  */
545   htab_t dependencies;
546
547   /* Header data from the line table, during full symbol processing.  */
548   struct line_header *line_header;
549   /* Non-NULL if LINE_HEADER is owned by this DWARF_CU.  Otherwise,
550      it's owned by dwarf2_per_objfile::line_header_hash.  If non-NULL,
551      this is the DW_TAG_compile_unit die for this CU.  We'll hold on
552      to the line header as long as this DIE is being processed.  See
553      process_die_scope.  */
554   die_info *line_header_die_owner;
555
556   /* A list of methods which need to have physnames computed
557      after all type information has been read.  */
558   VEC (delayed_method_info) *method_list;
559
560   /* To be copied to symtab->call_site_htab.  */
561   htab_t call_site_htab;
562
563   /* Non-NULL if this CU came from a DWO file.
564      There is an invariant here that is important to remember:
565      Except for attributes copied from the top level DIE in the "main"
566      (or "stub") file in preparation for reading the DWO file
567      (e.g., DW_AT_GNU_addr_base), we KISS: there is only *one* CU.
568      Either there isn't a DWO file (in which case this is NULL and the point
569      is moot), or there is and either we're not going to read it (in which
570      case this is NULL) or there is and we are reading it (in which case this
571      is non-NULL).  */
572   struct dwo_unit *dwo_unit;
573
574   /* The DW_AT_addr_base attribute if present, zero otherwise
575      (zero is a valid value though).
576      Note this value comes from the Fission stub CU/TU's DIE.  */
577   ULONGEST addr_base;
578
579   /* The DW_AT_ranges_base attribute if present, zero otherwise
580      (zero is a valid value though).
581      Note this value comes from the Fission stub CU/TU's DIE.
582      Also note that the value is zero in the non-DWO case so this value can
583      be used without needing to know whether DWO files are in use or not.
584      N.B. This does not apply to DW_AT_ranges appearing in
585      DW_TAG_compile_unit dies.  This is a bit of a wart, consider if ever
586      DW_AT_ranges appeared in the DW_TAG_compile_unit of DWO DIEs: then
587      DW_AT_ranges_base *would* have to be applied, and we'd have to care
588      whether the DW_AT_ranges attribute came from the skeleton or DWO.  */
589   ULONGEST ranges_base;
590
591   /* Mark used when releasing cached dies.  */
592   unsigned int mark : 1;
593
594   /* This CU references .debug_loc.  See the symtab->locations_valid field.
595      This test is imperfect as there may exist optimized debug code not using
596      any location list and still facing inlining issues if handled as
597      unoptimized code.  For a future better test see GCC PR other/32998.  */
598   unsigned int has_loclist : 1;
599
600   /* These cache the results for producer_is_* fields.  CHECKED_PRODUCER is set
601      if all the producer_is_* fields are valid.  This information is cached
602      because profiling CU expansion showed excessive time spent in
603      producer_is_gxx_lt_4_6.  */
604   unsigned int checked_producer : 1;
605   unsigned int producer_is_gxx_lt_4_6 : 1;
606   unsigned int producer_is_gcc_lt_4_3 : 1;
607   unsigned int producer_is_icc : 1;
608
609   /* When set, the file that we're processing is known to have
610      debugging info for C++ namespaces.  GCC 3.3.x did not produce
611      this information, but later versions do.  */
612
613   unsigned int processing_has_namespace_info : 1;
614 };
615
616 /* Persistent data held for a compilation unit, even when not
617    processing it.  We put a pointer to this structure in the
618    read_symtab_private field of the psymtab.  */
619
620 struct dwarf2_per_cu_data
621 {
622   /* The start offset and length of this compilation unit.
623      NOTE: Unlike comp_unit_head.length, this length includes
624      initial_length_size.
625      If the DIE refers to a DWO file, this is always of the original die,
626      not the DWO file.  */
627   sect_offset sect_off;
628   unsigned int length;
629
630   /* DWARF standard version this data has been read from (such as 4 or 5).  */
631   short dwarf_version;
632
633   /* Flag indicating this compilation unit will be read in before
634      any of the current compilation units are processed.  */
635   unsigned int queued : 1;
636
637   /* This flag will be set when reading partial DIEs if we need to load
638      absolutely all DIEs for this compilation unit, instead of just the ones
639      we think are interesting.  It gets set if we look for a DIE in the
640      hash table and don't find it.  */
641   unsigned int load_all_dies : 1;
642
643   /* Non-zero if this CU is from .debug_types.
644      Struct dwarf2_per_cu_data is contained in struct signatured_type iff
645      this is non-zero.  */
646   unsigned int is_debug_types : 1;
647
648   /* Non-zero if this CU is from the .dwz file.  */
649   unsigned int is_dwz : 1;
650
651   /* Non-zero if reading a TU directly from a DWO file, bypassing the stub.
652      This flag is only valid if is_debug_types is true.
653      We can't read a CU directly from a DWO file: There are required
654      attributes in the stub.  */
655   unsigned int reading_dwo_directly : 1;
656
657   /* Non-zero if the TU has been read.
658      This is used to assist the "Stay in DWO Optimization" for Fission:
659      When reading a DWO, it's faster to read TUs from the DWO instead of
660      fetching them from random other DWOs (due to comdat folding).
661      If the TU has already been read, the optimization is unnecessary
662      (and unwise - we don't want to change where gdb thinks the TU lives
663      "midflight").
664      This flag is only valid if is_debug_types is true.  */
665   unsigned int tu_read : 1;
666
667   /* The section this CU/TU lives in.
668      If the DIE refers to a DWO file, this is always the original die,
669      not the DWO file.  */
670   struct dwarf2_section_info *section;
671
672   /* Set to non-NULL iff this CU is currently loaded.  When it gets freed out
673      of the CU cache it gets reset to NULL again.  This is left as NULL for
674      dummy CUs (a CU header, but nothing else).  */
675   struct dwarf2_cu *cu;
676
677   /* The corresponding objfile.
678      Normally we can get the objfile from dwarf2_per_objfile.
679      However we can enter this file with just a "per_cu" handle.  */
680   struct objfile *objfile;
681
682   /* When dwarf2_per_objfile->using_index is true, the 'quick' field
683      is active.  Otherwise, the 'psymtab' field is active.  */
684   union
685   {
686     /* The partial symbol table associated with this compilation unit,
687        or NULL for unread partial units.  */
688     struct partial_symtab *psymtab;
689
690     /* Data needed by the "quick" functions.  */
691     struct dwarf2_per_cu_quick_data *quick;
692   } v;
693
694   /* The CUs we import using DW_TAG_imported_unit.  This is filled in
695      while reading psymtabs, used to compute the psymtab dependencies,
696      and then cleared.  Then it is filled in again while reading full
697      symbols, and only deleted when the objfile is destroyed.
698
699      This is also used to work around a difference between the way gold
700      generates .gdb_index version <=7 and the way gdb does.  Arguably this
701      is a gold bug.  For symbols coming from TUs, gold records in the index
702      the CU that includes the TU instead of the TU itself.  This breaks
703      dw2_lookup_symbol: It assumes that if the index says symbol X lives
704      in CU/TU Y, then one need only expand Y and a subsequent lookup in Y
705      will find X.  Alas TUs live in their own symtab, so after expanding CU Y
706      we need to look in TU Z to find X.  Fortunately, this is akin to
707      DW_TAG_imported_unit, so we just use the same mechanism: For
708      .gdb_index version <=7 this also records the TUs that the CU referred
709      to.  Concurrently with this change gdb was modified to emit version 8
710      indices so we only pay a price for gold generated indices.
711      http://sourceware.org/bugzilla/show_bug.cgi?id=15021.  */
712   VEC (dwarf2_per_cu_ptr) *imported_symtabs;
713 };
714
715 /* Entry in the signatured_types hash table.  */
716
717 struct signatured_type
718 {
719   /* The "per_cu" object of this type.
720      This struct is used iff per_cu.is_debug_types.
721      N.B.: This is the first member so that it's easy to convert pointers
722      between them.  */
723   struct dwarf2_per_cu_data per_cu;
724
725   /* The type's signature.  */
726   ULONGEST signature;
727
728   /* Offset in the TU of the type's DIE, as read from the TU header.
729      If this TU is a DWO stub and the definition lives in a DWO file
730      (specified by DW_AT_GNU_dwo_name), this value is unusable.  */
731   cu_offset type_offset_in_tu;
732
733   /* Offset in the section of the type's DIE.
734      If the definition lives in a DWO file, this is the offset in the
735      .debug_types.dwo section.
736      The value is zero until the actual value is known.
737      Zero is otherwise not a valid section offset.  */
738   sect_offset type_offset_in_section;
739
740   /* Type units are grouped by their DW_AT_stmt_list entry so that they
741      can share them.  This points to the containing symtab.  */
742   struct type_unit_group *type_unit_group;
743
744   /* The type.
745      The first time we encounter this type we fully read it in and install it
746      in the symbol tables.  Subsequent times we only need the type.  */
747   struct type *type;
748
749   /* Containing DWO unit.
750      This field is valid iff per_cu.reading_dwo_directly.  */
751   struct dwo_unit *dwo_unit;
752 };
753
754 typedef struct signatured_type *sig_type_ptr;
755 DEF_VEC_P (sig_type_ptr);
756
757 /* A struct that can be used as a hash key for tables based on DW_AT_stmt_list.
758    This includes type_unit_group and quick_file_names.  */
759
760 struct stmt_list_hash
761 {
762   /* The DWO unit this table is from or NULL if there is none.  */
763   struct dwo_unit *dwo_unit;
764
765   /* Offset in .debug_line or .debug_line.dwo.  */
766   sect_offset line_sect_off;
767 };
768
769 /* Each element of dwarf2_per_objfile->type_unit_groups is a pointer to
770    an object of this type.  */
771
772 struct type_unit_group
773 {
774   /* dwarf2read.c's main "handle" on a TU symtab.
775      To simplify things we create an artificial CU that "includes" all the
776      type units using this stmt_list so that the rest of the code still has
777      a "per_cu" handle on the symtab.
778      This PER_CU is recognized by having no section.  */
779 #define IS_TYPE_UNIT_GROUP(per_cu) ((per_cu)->section == NULL)
780   struct dwarf2_per_cu_data per_cu;
781
782   /* The TUs that share this DW_AT_stmt_list entry.
783      This is added to while parsing type units to build partial symtabs,
784      and is deleted afterwards and not used again.  */
785   VEC (sig_type_ptr) *tus;
786
787   /* The compunit symtab.
788      Type units in a group needn't all be defined in the same source file,
789      so we create an essentially anonymous symtab as the compunit symtab.  */
790   struct compunit_symtab *compunit_symtab;
791
792   /* The data used to construct the hash key.  */
793   struct stmt_list_hash hash;
794
795   /* The number of symtabs from the line header.
796      The value here must match line_header.num_file_names.  */
797   unsigned int num_symtabs;
798
799   /* The symbol tables for this TU (obtained from the files listed in
800      DW_AT_stmt_list).
801      WARNING: The order of entries here must match the order of entries
802      in the line header.  After the first TU using this type_unit_group, the
803      line header for the subsequent TUs is recreated from this.  This is done
804      because we need to use the same symtabs for each TU using the same
805      DW_AT_stmt_list value.  Also note that symtabs may be repeated here,
806      there's no guarantee the line header doesn't have duplicate entries.  */
807   struct symtab **symtabs;
808 };
809
810 /* These sections are what may appear in a (real or virtual) DWO file.  */
811
812 struct dwo_sections
813 {
814   struct dwarf2_section_info abbrev;
815   struct dwarf2_section_info line;
816   struct dwarf2_section_info loc;
817   struct dwarf2_section_info loclists;
818   struct dwarf2_section_info macinfo;
819   struct dwarf2_section_info macro;
820   struct dwarf2_section_info str;
821   struct dwarf2_section_info str_offsets;
822   /* In the case of a virtual DWO file, these two are unused.  */
823   struct dwarf2_section_info info;
824   VEC (dwarf2_section_info_def) *types;
825 };
826
827 /* CUs/TUs in DWP/DWO files.  */
828
829 struct dwo_unit
830 {
831   /* Backlink to the containing struct dwo_file.  */
832   struct dwo_file *dwo_file;
833
834   /* The "id" that distinguishes this CU/TU.
835      .debug_info calls this "dwo_id", .debug_types calls this "signature".
836      Since signatures came first, we stick with it for consistency.  */
837   ULONGEST signature;
838
839   /* The section this CU/TU lives in, in the DWO file.  */
840   struct dwarf2_section_info *section;
841
842   /* Same as dwarf2_per_cu_data:{sect_off,length} but in the DWO section.  */
843   sect_offset sect_off;
844   unsigned int length;
845
846   /* For types, offset in the type's DIE of the type defined by this TU.  */
847   cu_offset type_offset_in_tu;
848 };
849
850 /* include/dwarf2.h defines the DWP section codes.
851    It defines a max value but it doesn't define a min value, which we
852    use for error checking, so provide one.  */
853
854 enum dwp_v2_section_ids
855 {
856   DW_SECT_MIN = 1
857 };
858
859 /* Data for one DWO file.
860
861    This includes virtual DWO files (a virtual DWO file is a DWO file as it
862    appears in a DWP file).  DWP files don't really have DWO files per se -
863    comdat folding of types "loses" the DWO file they came from, and from
864    a high level view DWP files appear to contain a mass of random types.
865    However, to maintain consistency with the non-DWP case we pretend DWP
866    files contain virtual DWO files, and we assign each TU with one virtual
867    DWO file (generally based on the line and abbrev section offsets -
868    a heuristic that seems to work in practice).  */
869
870 struct dwo_file
871 {
872   /* The DW_AT_GNU_dwo_name attribute.
873      For virtual DWO files the name is constructed from the section offsets
874      of abbrev,line,loc,str_offsets so that we combine virtual DWO files
875      from related CU+TUs.  */
876   const char *dwo_name;
877
878   /* The DW_AT_comp_dir attribute.  */
879   const char *comp_dir;
880
881   /* The bfd, when the file is open.  Otherwise this is NULL.
882      This is unused(NULL) for virtual DWO files where we use dwp_file.dbfd.  */
883   bfd *dbfd;
884
885   /* The sections that make up this DWO file.
886      Remember that for virtual DWO files in DWP V2, these are virtual
887      sections (for lack of a better name).  */
888   struct dwo_sections sections;
889
890   /* The CUs in the file.
891      Each element is a struct dwo_unit. Multiple CUs per DWO are supported as
892      an extension to handle LLVM's Link Time Optimization output (where
893      multiple source files may be compiled into a single object/dwo pair). */
894   htab_t cus;
895
896   /* Table of TUs in the file.
897      Each element is a struct dwo_unit.  */
898   htab_t tus;
899 };
900
901 /* These sections are what may appear in a DWP file.  */
902
903 struct dwp_sections
904 {
905   /* These are used by both DWP version 1 and 2.  */
906   struct dwarf2_section_info str;
907   struct dwarf2_section_info cu_index;
908   struct dwarf2_section_info tu_index;
909
910   /* These are only used by DWP version 2 files.
911      In DWP version 1 the .debug_info.dwo, .debug_types.dwo, and other
912      sections are referenced by section number, and are not recorded here.
913      In DWP version 2 there is at most one copy of all these sections, each
914      section being (effectively) comprised of the concatenation of all of the
915      individual sections that exist in the version 1 format.
916      To keep the code simple we treat each of these concatenated pieces as a
917      section itself (a virtual section?).  */
918   struct dwarf2_section_info abbrev;
919   struct dwarf2_section_info info;
920   struct dwarf2_section_info line;
921   struct dwarf2_section_info loc;
922   struct dwarf2_section_info macinfo;
923   struct dwarf2_section_info macro;
924   struct dwarf2_section_info str_offsets;
925   struct dwarf2_section_info types;
926 };
927
928 /* These sections are what may appear in a virtual DWO file in DWP version 1.
929    A virtual DWO file is a DWO file as it appears in a DWP file.  */
930
931 struct virtual_v1_dwo_sections
932 {
933   struct dwarf2_section_info abbrev;
934   struct dwarf2_section_info line;
935   struct dwarf2_section_info loc;
936   struct dwarf2_section_info macinfo;
937   struct dwarf2_section_info macro;
938   struct dwarf2_section_info str_offsets;
939   /* Each DWP hash table entry records one CU or one TU.
940      That is recorded here, and copied to dwo_unit.section.  */
941   struct dwarf2_section_info info_or_types;
942 };
943
944 /* Similar to virtual_v1_dwo_sections, but for DWP version 2.
945    In version 2, the sections of the DWO files are concatenated together
946    and stored in one section of that name.  Thus each ELF section contains
947    several "virtual" sections.  */
948
949 struct virtual_v2_dwo_sections
950 {
951   bfd_size_type abbrev_offset;
952   bfd_size_type abbrev_size;
953
954   bfd_size_type line_offset;
955   bfd_size_type line_size;
956
957   bfd_size_type loc_offset;
958   bfd_size_type loc_size;
959
960   bfd_size_type macinfo_offset;
961   bfd_size_type macinfo_size;
962
963   bfd_size_type macro_offset;
964   bfd_size_type macro_size;
965
966   bfd_size_type str_offsets_offset;
967   bfd_size_type str_offsets_size;
968
969   /* Each DWP hash table entry records one CU or one TU.
970      That is recorded here, and copied to dwo_unit.section.  */
971   bfd_size_type info_or_types_offset;
972   bfd_size_type info_or_types_size;
973 };
974
975 /* Contents of DWP hash tables.  */
976
977 struct dwp_hash_table
978 {
979   uint32_t version, nr_columns;
980   uint32_t nr_units, nr_slots;
981   const gdb_byte *hash_table, *unit_table;
982   union
983   {
984     struct
985     {
986       const gdb_byte *indices;
987     } v1;
988     struct
989     {
990       /* This is indexed by column number and gives the id of the section
991          in that column.  */
992 #define MAX_NR_V2_DWO_SECTIONS \
993   (1 /* .debug_info or .debug_types */ \
994    + 1 /* .debug_abbrev */ \
995    + 1 /* .debug_line */ \
996    + 1 /* .debug_loc */ \
997    + 1 /* .debug_str_offsets */ \
998    + 1 /* .debug_macro or .debug_macinfo */)
999       int section_ids[MAX_NR_V2_DWO_SECTIONS];
1000       const gdb_byte *offsets;
1001       const gdb_byte *sizes;
1002     } v2;
1003   } section_pool;
1004 };
1005
1006 /* Data for one DWP file.  */
1007
1008 struct dwp_file
1009 {
1010   /* Name of the file.  */
1011   const char *name;
1012
1013   /* File format version.  */
1014   int version;
1015
1016   /* The bfd.  */
1017   bfd *dbfd;
1018
1019   /* Section info for this file.  */
1020   struct dwp_sections sections;
1021
1022   /* Table of CUs in the file.  */
1023   const struct dwp_hash_table *cus;
1024
1025   /* Table of TUs in the file.  */
1026   const struct dwp_hash_table *tus;
1027
1028   /* Tables of loaded CUs/TUs.  Each entry is a struct dwo_unit *.  */
1029   htab_t loaded_cus;
1030   htab_t loaded_tus;
1031
1032   /* Table to map ELF section numbers to their sections.
1033      This is only needed for the DWP V1 file format.  */
1034   unsigned int num_sections;
1035   asection **elf_sections;
1036 };
1037
1038 /* This represents a '.dwz' file.  */
1039
1040 struct dwz_file
1041 {
1042   /* A dwz file can only contain a few sections.  */
1043   struct dwarf2_section_info abbrev;
1044   struct dwarf2_section_info info;
1045   struct dwarf2_section_info str;
1046   struct dwarf2_section_info line;
1047   struct dwarf2_section_info macro;
1048   struct dwarf2_section_info gdb_index;
1049
1050   /* The dwz's BFD.  */
1051   bfd *dwz_bfd;
1052 };
1053
1054 /* Struct used to pass misc. parameters to read_die_and_children, et
1055    al.  which are used for both .debug_info and .debug_types dies.
1056    All parameters here are unchanging for the life of the call.  This
1057    struct exists to abstract away the constant parameters of die reading.  */
1058
1059 struct die_reader_specs
1060 {
1061   /* The bfd of die_section.  */
1062   bfd* abfd;
1063
1064   /* The CU of the DIE we are parsing.  */
1065   struct dwarf2_cu *cu;
1066
1067   /* Non-NULL if reading a DWO file (including one packaged into a DWP).  */
1068   struct dwo_file *dwo_file;
1069
1070   /* The section the die comes from.
1071      This is either .debug_info or .debug_types, or the .dwo variants.  */
1072   struct dwarf2_section_info *die_section;
1073
1074   /* die_section->buffer.  */
1075   const gdb_byte *buffer;
1076
1077   /* The end of the buffer.  */
1078   const gdb_byte *buffer_end;
1079
1080   /* The value of the DW_AT_comp_dir attribute.  */
1081   const char *comp_dir;
1082 };
1083
1084 /* Type of function passed to init_cutu_and_read_dies, et.al.  */
1085 typedef void (die_reader_func_ftype) (const struct die_reader_specs *reader,
1086                                       const gdb_byte *info_ptr,
1087                                       struct die_info *comp_unit_die,
1088                                       int has_children,
1089                                       void *data);
1090
1091 /* A 1-based directory index.  This is a strong typedef to prevent
1092    accidentally using a directory index as a 0-based index into an
1093    array/vector.  */
1094 enum class dir_index : unsigned int {};
1095
1096 /* Likewise, a 1-based file name index.  */
1097 enum class file_name_index : unsigned int {};
1098
1099 struct file_entry
1100 {
1101   file_entry () = default;
1102
1103   file_entry (const char *name_, dir_index d_index_,
1104               unsigned int mod_time_, unsigned int length_)
1105     : name (name_),
1106       d_index (d_index_),
1107       mod_time (mod_time_),
1108       length (length_)
1109   {}
1110
1111   /* Return the include directory at D_INDEX stored in LH.  Returns
1112      NULL if D_INDEX is out of bounds.  */
1113   const char *include_dir (const line_header *lh) const;
1114
1115   /* The file name.  Note this is an observing pointer.  The memory is
1116      owned by debug_line_buffer.  */
1117   const char *name {};
1118
1119   /* The directory index (1-based).  */
1120   dir_index d_index {};
1121
1122   unsigned int mod_time {};
1123
1124   unsigned int length {};
1125
1126   /* True if referenced by the Line Number Program.  */
1127   bool included_p {};
1128
1129   /* The associated symbol table, if any.  */
1130   struct symtab *symtab {};
1131 };
1132
1133 /* The line number information for a compilation unit (found in the
1134    .debug_line section) begins with a "statement program header",
1135    which contains the following information.  */
1136 struct line_header
1137 {
1138   line_header ()
1139     : offset_in_dwz {}
1140   {}
1141
1142   /* Add an entry to the include directory table.  */
1143   void add_include_dir (const char *include_dir);
1144
1145   /* Add an entry to the file name table.  */
1146   void add_file_name (const char *name, dir_index d_index,
1147                       unsigned int mod_time, unsigned int length);
1148
1149   /* Return the include dir at INDEX (1-based).  Returns NULL if INDEX
1150      is out of bounds.  */
1151   const char *include_dir_at (dir_index index) const
1152   {
1153     /* Convert directory index number (1-based) to vector index
1154        (0-based).  */
1155     size_t vec_index = to_underlying (index) - 1;
1156
1157     if (vec_index >= include_dirs.size ())
1158       return NULL;
1159     return include_dirs[vec_index];
1160   }
1161
1162   /* Return the file name at INDEX (1-based).  Returns NULL if INDEX
1163      is out of bounds.  */
1164   file_entry *file_name_at (file_name_index index)
1165   {
1166     /* Convert file name index number (1-based) to vector index
1167        (0-based).  */
1168     size_t vec_index = to_underlying (index) - 1;
1169
1170     if (vec_index >= file_names.size ())
1171       return NULL;
1172     return &file_names[vec_index];
1173   }
1174
1175   /* Const version of the above.  */
1176   const file_entry *file_name_at (unsigned int index) const
1177   {
1178     if (index >= file_names.size ())
1179       return NULL;
1180     return &file_names[index];
1181   }
1182
1183   /* Offset of line number information in .debug_line section.  */
1184   sect_offset sect_off {};
1185
1186   /* OFFSET is for struct dwz_file associated with dwarf2_per_objfile.  */
1187   unsigned offset_in_dwz : 1; /* Can't initialize bitfields in-class.  */
1188
1189   unsigned int total_length {};
1190   unsigned short version {};
1191   unsigned int header_length {};
1192   unsigned char minimum_instruction_length {};
1193   unsigned char maximum_ops_per_instruction {};
1194   unsigned char default_is_stmt {};
1195   int line_base {};
1196   unsigned char line_range {};
1197   unsigned char opcode_base {};
1198
1199   /* standard_opcode_lengths[i] is the number of operands for the
1200      standard opcode whose value is i.  This means that
1201      standard_opcode_lengths[0] is unused, and the last meaningful
1202      element is standard_opcode_lengths[opcode_base - 1].  */
1203   std::unique_ptr<unsigned char[]> standard_opcode_lengths;
1204
1205   /* The include_directories table.  Note these are observing
1206      pointers.  The memory is owned by debug_line_buffer.  */
1207   std::vector<const char *> include_dirs;
1208
1209   /* The file_names table.  */
1210   std::vector<file_entry> file_names;
1211
1212   /* The start and end of the statement program following this
1213      header.  These point into dwarf2_per_objfile->line_buffer.  */
1214   const gdb_byte *statement_program_start {}, *statement_program_end {};
1215 };
1216
1217 typedef std::unique_ptr<line_header> line_header_up;
1218
1219 const char *
1220 file_entry::include_dir (const line_header *lh) const
1221 {
1222   return lh->include_dir_at (d_index);
1223 }
1224
1225 /* When we construct a partial symbol table entry we only
1226    need this much information.  */
1227 struct partial_die_info
1228   {
1229     /* Offset of this DIE.  */
1230     sect_offset sect_off;
1231
1232     /* DWARF-2 tag for this DIE.  */
1233     ENUM_BITFIELD(dwarf_tag) tag : 16;
1234
1235     /* Assorted flags describing the data found in this DIE.  */
1236     unsigned int has_children : 1;
1237     unsigned int is_external : 1;
1238     unsigned int is_declaration : 1;
1239     unsigned int has_type : 1;
1240     unsigned int has_specification : 1;
1241     unsigned int has_pc_info : 1;
1242     unsigned int may_be_inlined : 1;
1243
1244     /* This DIE has been marked DW_AT_main_subprogram.  */
1245     unsigned int main_subprogram : 1;
1246
1247     /* Flag set if the SCOPE field of this structure has been
1248        computed.  */
1249     unsigned int scope_set : 1;
1250
1251     /* Flag set if the DIE has a byte_size attribute.  */
1252     unsigned int has_byte_size : 1;
1253
1254     /* Flag set if the DIE has a DW_AT_const_value attribute.  */
1255     unsigned int has_const_value : 1;
1256
1257     /* Flag set if any of the DIE's children are template arguments.  */
1258     unsigned int has_template_arguments : 1;
1259
1260     /* Flag set if fixup_partial_die has been called on this die.  */
1261     unsigned int fixup_called : 1;
1262
1263     /* Flag set if DW_TAG_imported_unit uses DW_FORM_GNU_ref_alt.  */
1264     unsigned int is_dwz : 1;
1265
1266     /* Flag set if spec_offset uses DW_FORM_GNU_ref_alt.  */
1267     unsigned int spec_is_dwz : 1;
1268
1269     /* The name of this DIE.  Normally the value of DW_AT_name, but
1270        sometimes a default name for unnamed DIEs.  */
1271     const char *name;
1272
1273     /* The linkage name, if present.  */
1274     const char *linkage_name;
1275
1276     /* The scope to prepend to our children.  This is generally
1277        allocated on the comp_unit_obstack, so will disappear
1278        when this compilation unit leaves the cache.  */
1279     const char *scope;
1280
1281     /* Some data associated with the partial DIE.  The tag determines
1282        which field is live.  */
1283     union
1284     {
1285       /* The location description associated with this DIE, if any.  */
1286       struct dwarf_block *locdesc;
1287       /* The offset of an import, for DW_TAG_imported_unit.  */
1288       sect_offset sect_off;
1289     } d;
1290
1291     /* If HAS_PC_INFO, the PC range associated with this DIE.  */
1292     CORE_ADDR lowpc;
1293     CORE_ADDR highpc;
1294
1295     /* Pointer into the info_buffer (or types_buffer) pointing at the target of
1296        DW_AT_sibling, if any.  */
1297     /* NOTE: This member isn't strictly necessary, read_partial_die could
1298        return DW_AT_sibling values to its caller load_partial_dies.  */
1299     const gdb_byte *sibling;
1300
1301     /* If HAS_SPECIFICATION, the offset of the DIE referred to by
1302        DW_AT_specification (or DW_AT_abstract_origin or
1303        DW_AT_extension).  */
1304     sect_offset spec_offset;
1305
1306     /* Pointers to this DIE's parent, first child, and next sibling,
1307        if any.  */
1308     struct partial_die_info *die_parent, *die_child, *die_sibling;
1309   };
1310
1311 /* This data structure holds the information of an abbrev.  */
1312 struct abbrev_info
1313   {
1314     unsigned int number;        /* number identifying abbrev */
1315     enum dwarf_tag tag;         /* dwarf tag */
1316     unsigned short has_children;                /* boolean */
1317     unsigned short num_attrs;   /* number of attributes */
1318     struct attr_abbrev *attrs;  /* an array of attribute descriptions */
1319     struct abbrev_info *next;   /* next in chain */
1320   };
1321
1322 struct attr_abbrev
1323   {
1324     ENUM_BITFIELD(dwarf_attribute) name : 16;
1325     ENUM_BITFIELD(dwarf_form) form : 16;
1326
1327     /* It is valid only if FORM is DW_FORM_implicit_const.  */
1328     LONGEST implicit_const;
1329   };
1330
1331 /* Size of abbrev_table.abbrev_hash_table.  */
1332 #define ABBREV_HASH_SIZE 121
1333
1334 /* Top level data structure to contain an abbreviation table.  */
1335
1336 struct abbrev_table
1337 {
1338   /* Where the abbrev table came from.
1339      This is used as a sanity check when the table is used.  */
1340   sect_offset sect_off;
1341
1342   /* Storage for the abbrev table.  */
1343   struct obstack abbrev_obstack;
1344
1345   /* Hash table of abbrevs.
1346      This is an array of size ABBREV_HASH_SIZE allocated in abbrev_obstack.
1347      It could be statically allocated, but the previous code didn't so we
1348      don't either.  */
1349   struct abbrev_info **abbrevs;
1350 };
1351
1352 /* Attributes have a name and a value.  */
1353 struct attribute
1354   {
1355     ENUM_BITFIELD(dwarf_attribute) name : 16;
1356     ENUM_BITFIELD(dwarf_form) form : 15;
1357
1358     /* Has DW_STRING already been updated by dwarf2_canonicalize_name?  This
1359        field should be in u.str (existing only for DW_STRING) but it is kept
1360        here for better struct attribute alignment.  */
1361     unsigned int string_is_canonical : 1;
1362
1363     union
1364       {
1365         const char *str;
1366         struct dwarf_block *blk;
1367         ULONGEST unsnd;
1368         LONGEST snd;
1369         CORE_ADDR addr;
1370         ULONGEST signature;
1371       }
1372     u;
1373   };
1374
1375 /* This data structure holds a complete die structure.  */
1376 struct die_info
1377   {
1378     /* DWARF-2 tag for this DIE.  */
1379     ENUM_BITFIELD(dwarf_tag) tag : 16;
1380
1381     /* Number of attributes */
1382     unsigned char num_attrs;
1383
1384     /* True if we're presently building the full type name for the
1385        type derived from this DIE.  */
1386     unsigned char building_fullname : 1;
1387
1388     /* True if this die is in process.  PR 16581.  */
1389     unsigned char in_process : 1;
1390
1391     /* Abbrev number */
1392     unsigned int abbrev;
1393
1394     /* Offset in .debug_info or .debug_types section.  */
1395     sect_offset sect_off;
1396
1397     /* The dies in a compilation unit form an n-ary tree.  PARENT
1398        points to this die's parent; CHILD points to the first child of
1399        this node; and all the children of a given node are chained
1400        together via their SIBLING fields.  */
1401     struct die_info *child;     /* Its first child, if any.  */
1402     struct die_info *sibling;   /* Its next sibling, if any.  */
1403     struct die_info *parent;    /* Its parent, if any.  */
1404
1405     /* An array of attributes, with NUM_ATTRS elements.  There may be
1406        zero, but it's not common and zero-sized arrays are not
1407        sufficiently portable C.  */
1408     struct attribute attrs[1];
1409   };
1410
1411 /* Get at parts of an attribute structure.  */
1412
1413 #define DW_STRING(attr)    ((attr)->u.str)
1414 #define DW_STRING_IS_CANONICAL(attr) ((attr)->string_is_canonical)
1415 #define DW_UNSND(attr)     ((attr)->u.unsnd)
1416 #define DW_BLOCK(attr)     ((attr)->u.blk)
1417 #define DW_SND(attr)       ((attr)->u.snd)
1418 #define DW_ADDR(attr)      ((attr)->u.addr)
1419 #define DW_SIGNATURE(attr) ((attr)->u.signature)
1420
1421 /* Blocks are a bunch of untyped bytes.  */
1422 struct dwarf_block
1423   {
1424     size_t size;
1425
1426     /* Valid only if SIZE is not zero.  */
1427     const gdb_byte *data;
1428   };
1429
1430 #ifndef ATTR_ALLOC_CHUNK
1431 #define ATTR_ALLOC_CHUNK 4
1432 #endif
1433
1434 /* Allocate fields for structs, unions and enums in this size.  */
1435 #ifndef DW_FIELD_ALLOC_CHUNK
1436 #define DW_FIELD_ALLOC_CHUNK 4
1437 #endif
1438
1439 /* FIXME: We might want to set this from BFD via bfd_arch_bits_per_byte,
1440    but this would require a corresponding change in unpack_field_as_long
1441    and friends.  */
1442 static int bits_per_byte = 8;
1443
1444 struct nextfield
1445 {
1446   struct nextfield *next;
1447   int accessibility;
1448   int virtuality;
1449   struct field field;
1450 };
1451
1452 struct nextfnfield
1453 {
1454   struct nextfnfield *next;
1455   struct fn_field fnfield;
1456 };
1457
1458 struct fnfieldlist
1459 {
1460   const char *name;
1461   int length;
1462   struct nextfnfield *head;
1463 };
1464
1465 struct typedef_field_list
1466 {
1467   struct typedef_field field;
1468   struct typedef_field_list *next;
1469 };
1470
1471 /* The routines that read and process dies for a C struct or C++ class
1472    pass lists of data member fields and lists of member function fields
1473    in an instance of a field_info structure, as defined below.  */
1474 struct field_info
1475   {
1476     /* List of data member and baseclasses fields.  */
1477     struct nextfield *fields, *baseclasses;
1478
1479     /* Number of fields (including baseclasses).  */
1480     int nfields;
1481
1482     /* Number of baseclasses.  */
1483     int nbaseclasses;
1484
1485     /* Set if the accesibility of one of the fields is not public.  */
1486     int non_public_fields;
1487
1488     /* Member function fields array, entries are allocated in the order they
1489        are encountered in the object file.  */
1490     struct nextfnfield *fnfields;
1491
1492     /* Member function fieldlist array, contains name of possibly overloaded
1493        member function, number of overloaded member functions and a pointer
1494        to the head of the member function field chain.  */
1495     struct fnfieldlist *fnfieldlists;
1496
1497     /* Number of entries in the fnfieldlists array.  */
1498     int nfnfields;
1499
1500     /* typedefs defined inside this class.  TYPEDEF_FIELD_LIST contains head of
1501        a NULL terminated list of TYPEDEF_FIELD_LIST_COUNT elements.  */
1502     struct typedef_field_list *typedef_field_list;
1503     unsigned typedef_field_list_count;
1504   };
1505
1506 /* One item on the queue of compilation units to read in full symbols
1507    for.  */
1508 struct dwarf2_queue_item
1509 {
1510   struct dwarf2_per_cu_data *per_cu;
1511   enum language pretend_language;
1512   struct dwarf2_queue_item *next;
1513 };
1514
1515 /* The current queue.  */
1516 static struct dwarf2_queue_item *dwarf2_queue, *dwarf2_queue_tail;
1517
1518 /* Loaded secondary compilation units are kept in memory until they
1519    have not been referenced for the processing of this many
1520    compilation units.  Set this to zero to disable caching.  Cache
1521    sizes of up to at least twenty will improve startup time for
1522    typical inter-CU-reference binaries, at an obvious memory cost.  */
1523 static int dwarf_max_cache_age = 5;
1524 static void
1525 show_dwarf_max_cache_age (struct ui_file *file, int from_tty,
1526                           struct cmd_list_element *c, const char *value)
1527 {
1528   fprintf_filtered (file, _("The upper bound on the age of cached "
1529                             "DWARF compilation units is %s.\n"),
1530                     value);
1531 }
1532 \f
1533 /* local function prototypes */
1534
1535 static const char *get_section_name (const struct dwarf2_section_info *);
1536
1537 static const char *get_section_file_name (const struct dwarf2_section_info *);
1538
1539 static void dwarf2_find_base_address (struct die_info *die,
1540                                       struct dwarf2_cu *cu);
1541
1542 static struct partial_symtab *create_partial_symtab
1543   (struct dwarf2_per_cu_data *per_cu, const char *name);
1544
1545 static void dwarf2_build_psymtabs_hard (struct objfile *);
1546
1547 static void scan_partial_symbols (struct partial_die_info *,
1548                                   CORE_ADDR *, CORE_ADDR *,
1549                                   int, struct dwarf2_cu *);
1550
1551 static void add_partial_symbol (struct partial_die_info *,
1552                                 struct dwarf2_cu *);
1553
1554 static void add_partial_namespace (struct partial_die_info *pdi,
1555                                    CORE_ADDR *lowpc, CORE_ADDR *highpc,
1556                                    int set_addrmap, struct dwarf2_cu *cu);
1557
1558 static void add_partial_module (struct partial_die_info *pdi, CORE_ADDR *lowpc,
1559                                 CORE_ADDR *highpc, int set_addrmap,
1560                                 struct dwarf2_cu *cu);
1561
1562 static void add_partial_enumeration (struct partial_die_info *enum_pdi,
1563                                      struct dwarf2_cu *cu);
1564
1565 static void add_partial_subprogram (struct partial_die_info *pdi,
1566                                     CORE_ADDR *lowpc, CORE_ADDR *highpc,
1567                                     int need_pc, struct dwarf2_cu *cu);
1568
1569 static void dwarf2_read_symtab (struct partial_symtab *,
1570                                 struct objfile *);
1571
1572 static void psymtab_to_symtab_1 (struct partial_symtab *);
1573
1574 static struct abbrev_info *abbrev_table_lookup_abbrev
1575   (const struct abbrev_table *, unsigned int);
1576
1577 static struct abbrev_table *abbrev_table_read_table
1578   (struct dwarf2_section_info *, sect_offset);
1579
1580 static void abbrev_table_free (struct abbrev_table *);
1581
1582 static void abbrev_table_free_cleanup (void *);
1583
1584 static void dwarf2_read_abbrevs (struct dwarf2_cu *,
1585                                  struct dwarf2_section_info *);
1586
1587 static void dwarf2_free_abbrev_table (void *);
1588
1589 static unsigned int peek_abbrev_code (bfd *, const gdb_byte *);
1590
1591 static struct partial_die_info *load_partial_dies
1592   (const struct die_reader_specs *, const gdb_byte *, int);
1593
1594 static const gdb_byte *read_partial_die (const struct die_reader_specs *,
1595                                          struct partial_die_info *,
1596                                          struct abbrev_info *,
1597                                          unsigned int,
1598                                          const gdb_byte *);
1599
1600 static struct partial_die_info *find_partial_die (sect_offset, int,
1601                                                   struct dwarf2_cu *);
1602
1603 static void fixup_partial_die (struct partial_die_info *,
1604                                struct dwarf2_cu *);
1605
1606 static const gdb_byte *read_attribute (const struct die_reader_specs *,
1607                                        struct attribute *, struct attr_abbrev *,
1608                                        const gdb_byte *);
1609
1610 static unsigned int read_1_byte (bfd *, const gdb_byte *);
1611
1612 static int read_1_signed_byte (bfd *, const gdb_byte *);
1613
1614 static unsigned int read_2_bytes (bfd *, const gdb_byte *);
1615
1616 static unsigned int read_4_bytes (bfd *, const gdb_byte *);
1617
1618 static ULONGEST read_8_bytes (bfd *, const gdb_byte *);
1619
1620 static CORE_ADDR read_address (bfd *, const gdb_byte *ptr, struct dwarf2_cu *,
1621                                unsigned int *);
1622
1623 static LONGEST read_initial_length (bfd *, const gdb_byte *, unsigned int *);
1624
1625 static LONGEST read_checked_initial_length_and_offset
1626   (bfd *, const gdb_byte *, const struct comp_unit_head *,
1627    unsigned int *, unsigned int *);
1628
1629 static LONGEST read_offset (bfd *, const gdb_byte *,
1630                             const struct comp_unit_head *,
1631                             unsigned int *);
1632
1633 static LONGEST read_offset_1 (bfd *, const gdb_byte *, unsigned int);
1634
1635 static sect_offset read_abbrev_offset (struct dwarf2_section_info *,
1636                                        sect_offset);
1637
1638 static const gdb_byte *read_n_bytes (bfd *, const gdb_byte *, unsigned int);
1639
1640 static const char *read_direct_string (bfd *, const gdb_byte *, unsigned int *);
1641
1642 static const char *read_indirect_string (bfd *, const gdb_byte *,
1643                                          const struct comp_unit_head *,
1644                                          unsigned int *);
1645
1646 static const char *read_indirect_line_string (bfd *, const gdb_byte *,
1647                                               const struct comp_unit_head *,
1648                                               unsigned int *);
1649
1650 static const char *read_indirect_string_from_dwz (struct dwz_file *, LONGEST);
1651
1652 static LONGEST read_signed_leb128 (bfd *, const gdb_byte *, unsigned int *);
1653
1654 static CORE_ADDR read_addr_index_from_leb128 (struct dwarf2_cu *,
1655                                               const gdb_byte *,
1656                                               unsigned int *);
1657
1658 static const char *read_str_index (const struct die_reader_specs *reader,
1659                                    ULONGEST str_index);
1660
1661 static void set_cu_language (unsigned int, struct dwarf2_cu *);
1662
1663 static struct attribute *dwarf2_attr (struct die_info *, unsigned int,
1664                                       struct dwarf2_cu *);
1665
1666 static struct attribute *dwarf2_attr_no_follow (struct die_info *,
1667                                                 unsigned int);
1668
1669 static const char *dwarf2_string_attr (struct die_info *die, unsigned int name,
1670                                        struct dwarf2_cu *cu);
1671
1672 static int dwarf2_flag_true_p (struct die_info *die, unsigned name,
1673                                struct dwarf2_cu *cu);
1674
1675 static int die_is_declaration (struct die_info *, struct dwarf2_cu *cu);
1676
1677 static struct die_info *die_specification (struct die_info *die,
1678                                            struct dwarf2_cu **);
1679
1680 static line_header_up dwarf_decode_line_header (sect_offset sect_off,
1681                                                 struct dwarf2_cu *cu);
1682
1683 static void dwarf_decode_lines (struct line_header *, const char *,
1684                                 struct dwarf2_cu *, struct partial_symtab *,
1685                                 CORE_ADDR, int decode_mapping);
1686
1687 static void dwarf2_start_subfile (const char *, const char *);
1688
1689 static struct compunit_symtab *dwarf2_start_symtab (struct dwarf2_cu *,
1690                                                     const char *, const char *,
1691                                                     CORE_ADDR);
1692
1693 static struct symbol *new_symbol (struct die_info *, struct type *,
1694                                   struct dwarf2_cu *);
1695
1696 static struct symbol *new_symbol_full (struct die_info *, struct type *,
1697                                        struct dwarf2_cu *, struct symbol *);
1698
1699 static void dwarf2_const_value (const struct attribute *, struct symbol *,
1700                                 struct dwarf2_cu *);
1701
1702 static void dwarf2_const_value_attr (const struct attribute *attr,
1703                                      struct type *type,
1704                                      const char *name,
1705                                      struct obstack *obstack,
1706                                      struct dwarf2_cu *cu, LONGEST *value,
1707                                      const gdb_byte **bytes,
1708                                      struct dwarf2_locexpr_baton **baton);
1709
1710 static struct type *die_type (struct die_info *, struct dwarf2_cu *);
1711
1712 static int need_gnat_info (struct dwarf2_cu *);
1713
1714 static struct type *die_descriptive_type (struct die_info *,
1715                                           struct dwarf2_cu *);
1716
1717 static void set_descriptive_type (struct type *, struct die_info *,
1718                                   struct dwarf2_cu *);
1719
1720 static struct type *die_containing_type (struct die_info *,
1721                                          struct dwarf2_cu *);
1722
1723 static struct type *lookup_die_type (struct die_info *, const struct attribute *,
1724                                      struct dwarf2_cu *);
1725
1726 static struct type *read_type_die (struct die_info *, struct dwarf2_cu *);
1727
1728 static struct type *read_type_die_1 (struct die_info *, struct dwarf2_cu *);
1729
1730 static const char *determine_prefix (struct die_info *die, struct dwarf2_cu *);
1731
1732 static char *typename_concat (struct obstack *obs, const char *prefix,
1733                               const char *suffix, int physname,
1734                               struct dwarf2_cu *cu);
1735
1736 static void read_file_scope (struct die_info *, struct dwarf2_cu *);
1737
1738 static void read_type_unit_scope (struct die_info *, struct dwarf2_cu *);
1739
1740 static void read_func_scope (struct die_info *, struct dwarf2_cu *);
1741
1742 static void read_lexical_block_scope (struct die_info *, struct dwarf2_cu *);
1743
1744 static void read_call_site_scope (struct die_info *die, struct dwarf2_cu *cu);
1745
1746 static int dwarf2_ranges_read (unsigned, CORE_ADDR *, CORE_ADDR *,
1747                                struct dwarf2_cu *, struct partial_symtab *);
1748
1749 /* How dwarf2_get_pc_bounds constructed its *LOWPC and *HIGHPC return
1750    values.  Keep the items ordered with increasing constraints compliance.  */
1751 enum pc_bounds_kind
1752 {
1753   /* No attribute DW_AT_low_pc, DW_AT_high_pc or DW_AT_ranges was found.  */
1754   PC_BOUNDS_NOT_PRESENT,
1755
1756   /* Some of the attributes DW_AT_low_pc, DW_AT_high_pc or DW_AT_ranges
1757      were present but they do not form a valid range of PC addresses.  */
1758   PC_BOUNDS_INVALID,
1759
1760   /* Discontiguous range was found - that is DW_AT_ranges was found.  */
1761   PC_BOUNDS_RANGES,
1762
1763   /* Contiguous range was found - DW_AT_low_pc and DW_AT_high_pc were found.  */
1764   PC_BOUNDS_HIGH_LOW,
1765 };
1766
1767 static enum pc_bounds_kind dwarf2_get_pc_bounds (struct die_info *,
1768                                                  CORE_ADDR *, CORE_ADDR *,
1769                                                  struct dwarf2_cu *,
1770                                                  struct partial_symtab *);
1771
1772 static void get_scope_pc_bounds (struct die_info *,
1773                                  CORE_ADDR *, CORE_ADDR *,
1774                                  struct dwarf2_cu *);
1775
1776 static void dwarf2_record_block_ranges (struct die_info *, struct block *,
1777                                         CORE_ADDR, struct dwarf2_cu *);
1778
1779 static void dwarf2_add_field (struct field_info *, struct die_info *,
1780                               struct dwarf2_cu *);
1781
1782 static void dwarf2_attach_fields_to_type (struct field_info *,
1783                                           struct type *, struct dwarf2_cu *);
1784
1785 static void dwarf2_add_member_fn (struct field_info *,
1786                                   struct die_info *, struct type *,
1787                                   struct dwarf2_cu *);
1788
1789 static void dwarf2_attach_fn_fields_to_type (struct field_info *,
1790                                              struct type *,
1791                                              struct dwarf2_cu *);
1792
1793 static void process_structure_scope (struct die_info *, struct dwarf2_cu *);
1794
1795 static void read_common_block (struct die_info *, struct dwarf2_cu *);
1796
1797 static void read_namespace (struct die_info *die, struct dwarf2_cu *);
1798
1799 static void read_module (struct die_info *die, struct dwarf2_cu *cu);
1800
1801 static struct using_direct **using_directives (enum language);
1802
1803 static void read_import_statement (struct die_info *die, struct dwarf2_cu *);
1804
1805 static int read_namespace_alias (struct die_info *die, struct dwarf2_cu *cu);
1806
1807 static struct type *read_module_type (struct die_info *die,
1808                                       struct dwarf2_cu *cu);
1809
1810 static const char *namespace_name (struct die_info *die,
1811                                    int *is_anonymous, struct dwarf2_cu *);
1812
1813 static void process_enumeration_scope (struct die_info *, struct dwarf2_cu *);
1814
1815 static CORE_ADDR decode_locdesc (struct dwarf_block *, struct dwarf2_cu *);
1816
1817 static enum dwarf_array_dim_ordering read_array_order (struct die_info *,
1818                                                        struct dwarf2_cu *);
1819
1820 static struct die_info *read_die_and_siblings_1
1821   (const struct die_reader_specs *, const gdb_byte *, const gdb_byte **,
1822    struct die_info *);
1823
1824 static struct die_info *read_die_and_siblings (const struct die_reader_specs *,
1825                                                const gdb_byte *info_ptr,
1826                                                const gdb_byte **new_info_ptr,
1827                                                struct die_info *parent);
1828
1829 static const gdb_byte *read_full_die_1 (const struct die_reader_specs *,
1830                                         struct die_info **, const gdb_byte *,
1831                                         int *, int);
1832
1833 static const gdb_byte *read_full_die (const struct die_reader_specs *,
1834                                       struct die_info **, const gdb_byte *,
1835                                       int *);
1836
1837 static void process_die (struct die_info *, struct dwarf2_cu *);
1838
1839 static const char *dwarf2_canonicalize_name (const char *, struct dwarf2_cu *,
1840                                              struct obstack *);
1841
1842 static const char *dwarf2_name (struct die_info *die, struct dwarf2_cu *);
1843
1844 static const char *dwarf2_full_name (const char *name,
1845                                      struct die_info *die,
1846                                      struct dwarf2_cu *cu);
1847
1848 static const char *dwarf2_physname (const char *name, struct die_info *die,
1849                                     struct dwarf2_cu *cu);
1850
1851 static struct die_info *dwarf2_extension (struct die_info *die,
1852                                           struct dwarf2_cu **);
1853
1854 static const char *dwarf_tag_name (unsigned int);
1855
1856 static const char *dwarf_attr_name (unsigned int);
1857
1858 static const char *dwarf_form_name (unsigned int);
1859
1860 static const char *dwarf_bool_name (unsigned int);
1861
1862 static const char *dwarf_type_encoding_name (unsigned int);
1863
1864 static struct die_info *sibling_die (struct die_info *);
1865
1866 static void dump_die_shallow (struct ui_file *, int indent, struct die_info *);
1867
1868 static void dump_die_for_error (struct die_info *);
1869
1870 static void dump_die_1 (struct ui_file *, int level, int max_level,
1871                         struct die_info *);
1872
1873 /*static*/ void dump_die (struct die_info *, int max_level);
1874
1875 static void store_in_ref_table (struct die_info *,
1876                                 struct dwarf2_cu *);
1877
1878 static sect_offset dwarf2_get_ref_die_offset (const struct attribute *);
1879
1880 static LONGEST dwarf2_get_attr_constant_value (const struct attribute *, int);
1881
1882 static struct die_info *follow_die_ref_or_sig (struct die_info *,
1883                                                const struct attribute *,
1884                                                struct dwarf2_cu **);
1885
1886 static struct die_info *follow_die_ref (struct die_info *,
1887                                         const struct attribute *,
1888                                         struct dwarf2_cu **);
1889
1890 static struct die_info *follow_die_sig (struct die_info *,
1891                                         const struct attribute *,
1892                                         struct dwarf2_cu **);
1893
1894 static struct type *get_signatured_type (struct die_info *, ULONGEST,
1895                                          struct dwarf2_cu *);
1896
1897 static struct type *get_DW_AT_signature_type (struct die_info *,
1898                                               const struct attribute *,
1899                                               struct dwarf2_cu *);
1900
1901 static void load_full_type_unit (struct dwarf2_per_cu_data *per_cu);
1902
1903 static void read_signatured_type (struct signatured_type *);
1904
1905 static int attr_to_dynamic_prop (const struct attribute *attr,
1906                                  struct die_info *die, struct dwarf2_cu *cu,
1907                                  struct dynamic_prop *prop);
1908
1909 /* memory allocation interface */
1910
1911 static struct dwarf_block *dwarf_alloc_block (struct dwarf2_cu *);
1912
1913 static struct die_info *dwarf_alloc_die (struct dwarf2_cu *, int);
1914
1915 static void dwarf_decode_macros (struct dwarf2_cu *, unsigned int, int);
1916
1917 static int attr_form_is_block (const struct attribute *);
1918
1919 static int attr_form_is_section_offset (const struct attribute *);
1920
1921 static int attr_form_is_constant (const struct attribute *);
1922
1923 static int attr_form_is_ref (const struct attribute *);
1924
1925 static void fill_in_loclist_baton (struct dwarf2_cu *cu,
1926                                    struct dwarf2_loclist_baton *baton,
1927                                    const struct attribute *attr);
1928
1929 static void dwarf2_symbol_mark_computed (const struct attribute *attr,
1930                                          struct symbol *sym,
1931                                          struct dwarf2_cu *cu,
1932                                          int is_block);
1933
1934 static const gdb_byte *skip_one_die (const struct die_reader_specs *reader,
1935                                      const gdb_byte *info_ptr,
1936                                      struct abbrev_info *abbrev);
1937
1938 static void free_stack_comp_unit (void *);
1939
1940 static hashval_t partial_die_hash (const void *item);
1941
1942 static int partial_die_eq (const void *item_lhs, const void *item_rhs);
1943
1944 static struct dwarf2_per_cu_data *dwarf2_find_containing_comp_unit
1945   (sect_offset sect_off, unsigned int offset_in_dwz, struct objfile *objfile);
1946
1947 static void init_one_comp_unit (struct dwarf2_cu *cu,
1948                                 struct dwarf2_per_cu_data *per_cu);
1949
1950 static void prepare_one_comp_unit (struct dwarf2_cu *cu,
1951                                    struct die_info *comp_unit_die,
1952                                    enum language pretend_language);
1953
1954 static void free_heap_comp_unit (void *);
1955
1956 static void free_cached_comp_units (void *);
1957
1958 static void age_cached_comp_units (void);
1959
1960 static void free_one_cached_comp_unit (struct dwarf2_per_cu_data *);
1961
1962 static struct type *set_die_type (struct die_info *, struct type *,
1963                                   struct dwarf2_cu *);
1964
1965 static void create_all_comp_units (struct objfile *);
1966
1967 static int create_all_type_units (struct objfile *);
1968
1969 static void load_full_comp_unit (struct dwarf2_per_cu_data *,
1970                                  enum language);
1971
1972 static void process_full_comp_unit (struct dwarf2_per_cu_data *,
1973                                     enum language);
1974
1975 static void process_full_type_unit (struct dwarf2_per_cu_data *,
1976                                     enum language);
1977
1978 static void dwarf2_add_dependence (struct dwarf2_cu *,
1979                                    struct dwarf2_per_cu_data *);
1980
1981 static void dwarf2_mark (struct dwarf2_cu *);
1982
1983 static void dwarf2_clear_marks (struct dwarf2_per_cu_data *);
1984
1985 static struct type *get_die_type_at_offset (sect_offset,
1986                                             struct dwarf2_per_cu_data *);
1987
1988 static struct type *get_die_type (struct die_info *die, struct dwarf2_cu *cu);
1989
1990 static void dwarf2_release_queue (void *dummy);
1991
1992 static void queue_comp_unit (struct dwarf2_per_cu_data *per_cu,
1993                              enum language pretend_language);
1994
1995 static void process_queue (void);
1996
1997 /* The return type of find_file_and_directory.  Note, the enclosed
1998    string pointers are only valid while this object is valid.  */
1999
2000 struct file_and_directory
2001 {
2002   /* The filename.  This is never NULL.  */
2003   const char *name;
2004
2005   /* The compilation directory.  NULL if not known.  If we needed to
2006      compute a new string, this points to COMP_DIR_STORAGE, otherwise,
2007      points directly to the DW_AT_comp_dir string attribute owned by
2008      the obstack that owns the DIE.  */
2009   const char *comp_dir;
2010
2011   /* If we needed to build a new string for comp_dir, this is what
2012      owns the storage.  */
2013   std::string comp_dir_storage;
2014 };
2015
2016 static file_and_directory find_file_and_directory (struct die_info *die,
2017                                                    struct dwarf2_cu *cu);
2018
2019 static char *file_full_name (int file, struct line_header *lh,
2020                              const char *comp_dir);
2021
2022 /* Expected enum dwarf_unit_type for read_comp_unit_head.  */
2023 enum class rcuh_kind { COMPILE, TYPE };
2024
2025 static const gdb_byte *read_and_check_comp_unit_head
2026   (struct comp_unit_head *header,
2027    struct dwarf2_section_info *section,
2028    struct dwarf2_section_info *abbrev_section, const gdb_byte *info_ptr,
2029    rcuh_kind section_kind);
2030
2031 static void init_cutu_and_read_dies
2032   (struct dwarf2_per_cu_data *this_cu, struct abbrev_table *abbrev_table,
2033    int use_existing_cu, int keep,
2034    die_reader_func_ftype *die_reader_func, void *data);
2035
2036 static void init_cutu_and_read_dies_simple
2037   (struct dwarf2_per_cu_data *this_cu,
2038    die_reader_func_ftype *die_reader_func, void *data);
2039
2040 static htab_t allocate_signatured_type_table (struct objfile *objfile);
2041
2042 static htab_t allocate_dwo_unit_table (struct objfile *objfile);
2043
2044 static struct dwo_unit *lookup_dwo_unit_in_dwp
2045   (struct dwp_file *dwp_file, const char *comp_dir,
2046    ULONGEST signature, int is_debug_types);
2047
2048 static struct dwp_file *get_dwp_file (void);
2049
2050 static struct dwo_unit *lookup_dwo_comp_unit
2051   (struct dwarf2_per_cu_data *, const char *, const char *, ULONGEST);
2052
2053 static struct dwo_unit *lookup_dwo_type_unit
2054   (struct signatured_type *, const char *, const char *);
2055
2056 static void queue_and_load_all_dwo_tus (struct dwarf2_per_cu_data *);
2057
2058 static void free_dwo_file_cleanup (void *);
2059
2060 static void process_cu_includes (void);
2061
2062 static void check_producer (struct dwarf2_cu *cu);
2063
2064 static void free_line_header_voidp (void *arg);
2065 \f
2066 /* Various complaints about symbol reading that don't abort the process.  */
2067
2068 static void
2069 dwarf2_statement_list_fits_in_line_number_section_complaint (void)
2070 {
2071   complaint (&symfile_complaints,
2072              _("statement list doesn't fit in .debug_line section"));
2073 }
2074
2075 static void
2076 dwarf2_debug_line_missing_file_complaint (void)
2077 {
2078   complaint (&symfile_complaints,
2079              _(".debug_line section has line data without a file"));
2080 }
2081
2082 static void
2083 dwarf2_debug_line_missing_end_sequence_complaint (void)
2084 {
2085   complaint (&symfile_complaints,
2086              _(".debug_line section has line "
2087                "program sequence without an end"));
2088 }
2089
2090 static void
2091 dwarf2_complex_location_expr_complaint (void)
2092 {
2093   complaint (&symfile_complaints, _("location expression too complex"));
2094 }
2095
2096 static void
2097 dwarf2_const_value_length_mismatch_complaint (const char *arg1, int arg2,
2098                                               int arg3)
2099 {
2100   complaint (&symfile_complaints,
2101              _("const value length mismatch for '%s', got %d, expected %d"),
2102              arg1, arg2, arg3);
2103 }
2104
2105 static void
2106 dwarf2_section_buffer_overflow_complaint (struct dwarf2_section_info *section)
2107 {
2108   complaint (&symfile_complaints,
2109              _("debug info runs off end of %s section"
2110                " [in module %s]"),
2111              get_section_name (section),
2112              get_section_file_name (section));
2113 }
2114
2115 static void
2116 dwarf2_macro_malformed_definition_complaint (const char *arg1)
2117 {
2118   complaint (&symfile_complaints,
2119              _("macro debug info contains a "
2120                "malformed macro definition:\n`%s'"),
2121              arg1);
2122 }
2123
2124 static void
2125 dwarf2_invalid_attrib_class_complaint (const char *arg1, const char *arg2)
2126 {
2127   complaint (&symfile_complaints,
2128              _("invalid attribute class or form for '%s' in '%s'"),
2129              arg1, arg2);
2130 }
2131
2132 /* Hash function for line_header_hash.  */
2133
2134 static hashval_t
2135 line_header_hash (const struct line_header *ofs)
2136 {
2137   return to_underlying (ofs->sect_off) ^ ofs->offset_in_dwz;
2138 }
2139
2140 /* Hash function for htab_create_alloc_ex for line_header_hash.  */
2141
2142 static hashval_t
2143 line_header_hash_voidp (const void *item)
2144 {
2145   const struct line_header *ofs = (const struct line_header *) item;
2146
2147   return line_header_hash (ofs);
2148 }
2149
2150 /* Equality function for line_header_hash.  */
2151
2152 static int
2153 line_header_eq_voidp (const void *item_lhs, const void *item_rhs)
2154 {
2155   const struct line_header *ofs_lhs = (const struct line_header *) item_lhs;
2156   const struct line_header *ofs_rhs = (const struct line_header *) item_rhs;
2157
2158   return (ofs_lhs->sect_off == ofs_rhs->sect_off
2159           && ofs_lhs->offset_in_dwz == ofs_rhs->offset_in_dwz);
2160 }
2161
2162 \f
2163 #if WORDS_BIGENDIAN
2164
2165 /* Convert VALUE between big- and little-endian.  */
2166 static offset_type
2167 byte_swap (offset_type value)
2168 {
2169   offset_type result;
2170
2171   result = (value & 0xff) << 24;
2172   result |= (value & 0xff00) << 8;
2173   result |= (value & 0xff0000) >> 8;
2174   result |= (value & 0xff000000) >> 24;
2175   return result;
2176 }
2177
2178 #define MAYBE_SWAP(V)  byte_swap (V)
2179
2180 #else
2181 #define MAYBE_SWAP(V) static_cast<offset_type> (V)
2182 #endif /* WORDS_BIGENDIAN */
2183
2184 /* Read the given attribute value as an address, taking the attribute's
2185    form into account.  */
2186
2187 static CORE_ADDR
2188 attr_value_as_address (struct attribute *attr)
2189 {
2190   CORE_ADDR addr;
2191
2192   if (attr->form != DW_FORM_addr && attr->form != DW_FORM_GNU_addr_index)
2193     {
2194       /* Aside from a few clearly defined exceptions, attributes that
2195          contain an address must always be in DW_FORM_addr form.
2196          Unfortunately, some compilers happen to be violating this
2197          requirement by encoding addresses using other forms, such
2198          as DW_FORM_data4 for example.  For those broken compilers,
2199          we try to do our best, without any guarantee of success,
2200          to interpret the address correctly.  It would also be nice
2201          to generate a complaint, but that would require us to maintain
2202          a list of legitimate cases where a non-address form is allowed,
2203          as well as update callers to pass in at least the CU's DWARF
2204          version.  This is more overhead than what we're willing to
2205          expand for a pretty rare case.  */
2206       addr = DW_UNSND (attr);
2207     }
2208   else
2209     addr = DW_ADDR (attr);
2210
2211   return addr;
2212 }
2213
2214 /* The suffix for an index file.  */
2215 #define INDEX_SUFFIX ".gdb-index"
2216
2217 /* See declaration.  */
2218
2219 dwarf2_per_objfile::dwarf2_per_objfile (struct objfile *objfile_,
2220                                         const dwarf2_debug_sections *names)
2221   : objfile (objfile_)
2222 {
2223   if (names == NULL)
2224     names = &dwarf2_elf_names;
2225
2226   bfd *obfd = objfile->obfd;
2227
2228   for (asection *sec = obfd->sections; sec != NULL; sec = sec->next)
2229     locate_sections (obfd, sec, *names);
2230 }
2231
2232 dwarf2_per_objfile::~dwarf2_per_objfile ()
2233 {
2234   /* Cached DIE trees use xmalloc and the comp_unit_obstack.  */
2235   free_cached_comp_units ();
2236
2237   if (quick_file_names_table)
2238     htab_delete (quick_file_names_table);
2239
2240   if (line_header_hash)
2241     htab_delete (line_header_hash);
2242
2243   /* Everything else should be on the objfile obstack.  */
2244 }
2245
2246 /* See declaration.  */
2247
2248 void
2249 dwarf2_per_objfile::free_cached_comp_units ()
2250 {
2251   dwarf2_per_cu_data *per_cu = read_in_chain;
2252   dwarf2_per_cu_data **last_chain = &read_in_chain;
2253   while (per_cu != NULL)
2254     {
2255       dwarf2_per_cu_data *next_cu = per_cu->cu->read_in_chain;
2256
2257       free_heap_comp_unit (per_cu->cu);
2258       *last_chain = next_cu;
2259       per_cu = next_cu;
2260     }
2261 }
2262
2263 /* Try to locate the sections we need for DWARF 2 debugging
2264    information and return true if we have enough to do something.
2265    NAMES points to the dwarf2 section names, or is NULL if the standard
2266    ELF names are used.  */
2267
2268 int
2269 dwarf2_has_info (struct objfile *objfile,
2270                  const struct dwarf2_debug_sections *names)
2271 {
2272   dwarf2_per_objfile = ((struct dwarf2_per_objfile *)
2273                         objfile_data (objfile, dwarf2_objfile_data_key));
2274   if (!dwarf2_per_objfile)
2275     {
2276       /* Initialize per-objfile state.  */
2277       struct dwarf2_per_objfile *data
2278         = XOBNEW (&objfile->objfile_obstack, struct dwarf2_per_objfile);
2279
2280       dwarf2_per_objfile = new (data) struct dwarf2_per_objfile (objfile, names);
2281       set_objfile_data (objfile, dwarf2_objfile_data_key, dwarf2_per_objfile);
2282     }
2283   return (!dwarf2_per_objfile->info.is_virtual
2284           && dwarf2_per_objfile->info.s.section != NULL
2285           && !dwarf2_per_objfile->abbrev.is_virtual
2286           && dwarf2_per_objfile->abbrev.s.section != NULL);
2287 }
2288
2289 /* Return the containing section of virtual section SECTION.  */
2290
2291 static struct dwarf2_section_info *
2292 get_containing_section (const struct dwarf2_section_info *section)
2293 {
2294   gdb_assert (section->is_virtual);
2295   return section->s.containing_section;
2296 }
2297
2298 /* Return the bfd owner of SECTION.  */
2299
2300 static struct bfd *
2301 get_section_bfd_owner (const struct dwarf2_section_info *section)
2302 {
2303   if (section->is_virtual)
2304     {
2305       section = get_containing_section (section);
2306       gdb_assert (!section->is_virtual);
2307     }
2308   return section->s.section->owner;
2309 }
2310
2311 /* Return the bfd section of SECTION.
2312    Returns NULL if the section is not present.  */
2313
2314 static asection *
2315 get_section_bfd_section (const struct dwarf2_section_info *section)
2316 {
2317   if (section->is_virtual)
2318     {
2319       section = get_containing_section (section);
2320       gdb_assert (!section->is_virtual);
2321     }
2322   return section->s.section;
2323 }
2324
2325 /* Return the name of SECTION.  */
2326
2327 static const char *
2328 get_section_name (const struct dwarf2_section_info *section)
2329 {
2330   asection *sectp = get_section_bfd_section (section);
2331
2332   gdb_assert (sectp != NULL);
2333   return bfd_section_name (get_section_bfd_owner (section), sectp);
2334 }
2335
2336 /* Return the name of the file SECTION is in.  */
2337
2338 static const char *
2339 get_section_file_name (const struct dwarf2_section_info *section)
2340 {
2341   bfd *abfd = get_section_bfd_owner (section);
2342
2343   return bfd_get_filename (abfd);
2344 }
2345
2346 /* Return the id of SECTION.
2347    Returns 0 if SECTION doesn't exist.  */
2348
2349 static int
2350 get_section_id (const struct dwarf2_section_info *section)
2351 {
2352   asection *sectp = get_section_bfd_section (section);
2353
2354   if (sectp == NULL)
2355     return 0;
2356   return sectp->id;
2357 }
2358
2359 /* Return the flags of SECTION.
2360    SECTION (or containing section if this is a virtual section) must exist.  */
2361
2362 static int
2363 get_section_flags (const struct dwarf2_section_info *section)
2364 {
2365   asection *sectp = get_section_bfd_section (section);
2366
2367   gdb_assert (sectp != NULL);
2368   return bfd_get_section_flags (sectp->owner, sectp);
2369 }
2370
2371 /* When loading sections, we look either for uncompressed section or for
2372    compressed section names.  */
2373
2374 static int
2375 section_is_p (const char *section_name,
2376               const struct dwarf2_section_names *names)
2377 {
2378   if (names->normal != NULL
2379       && strcmp (section_name, names->normal) == 0)
2380     return 1;
2381   if (names->compressed != NULL
2382       && strcmp (section_name, names->compressed) == 0)
2383     return 1;
2384   return 0;
2385 }
2386
2387 /* See declaration.  */
2388
2389 void
2390 dwarf2_per_objfile::locate_sections (bfd *abfd, asection *sectp,
2391                                      const dwarf2_debug_sections &names)
2392 {
2393   flagword aflag = bfd_get_section_flags (abfd, sectp);
2394
2395   if ((aflag & SEC_HAS_CONTENTS) == 0)
2396     {
2397     }
2398   else if (section_is_p (sectp->name, &names.info))
2399     {
2400       this->info.s.section = sectp;
2401       this->info.size = bfd_get_section_size (sectp);
2402     }
2403   else if (section_is_p (sectp->name, &names.abbrev))
2404     {
2405       this->abbrev.s.section = sectp;
2406       this->abbrev.size = bfd_get_section_size (sectp);
2407     }
2408   else if (section_is_p (sectp->name, &names.line))
2409     {
2410       this->line.s.section = sectp;
2411       this->line.size = bfd_get_section_size (sectp);
2412     }
2413   else if (section_is_p (sectp->name, &names.loc))
2414     {
2415       this->loc.s.section = sectp;
2416       this->loc.size = bfd_get_section_size (sectp);
2417     }
2418   else if (section_is_p (sectp->name, &names.loclists))
2419     {
2420       this->loclists.s.section = sectp;
2421       this->loclists.size = bfd_get_section_size (sectp);
2422     }
2423   else if (section_is_p (sectp->name, &names.macinfo))
2424     {
2425       this->macinfo.s.section = sectp;
2426       this->macinfo.size = bfd_get_section_size (sectp);
2427     }
2428   else if (section_is_p (sectp->name, &names.macro))
2429     {
2430       this->macro.s.section = sectp;
2431       this->macro.size = bfd_get_section_size (sectp);
2432     }
2433   else if (section_is_p (sectp->name, &names.str))
2434     {
2435       this->str.s.section = sectp;
2436       this->str.size = bfd_get_section_size (sectp);
2437     }
2438   else if (section_is_p (sectp->name, &names.line_str))
2439     {
2440       this->line_str.s.section = sectp;
2441       this->line_str.size = bfd_get_section_size (sectp);
2442     }
2443   else if (section_is_p (sectp->name, &names.addr))
2444     {
2445       this->addr.s.section = sectp;
2446       this->addr.size = bfd_get_section_size (sectp);
2447     }
2448   else if (section_is_p (sectp->name, &names.frame))
2449     {
2450       this->frame.s.section = sectp;
2451       this->frame.size = bfd_get_section_size (sectp);
2452     }
2453   else if (section_is_p (sectp->name, &names.eh_frame))
2454     {
2455       this->eh_frame.s.section = sectp;
2456       this->eh_frame.size = bfd_get_section_size (sectp);
2457     }
2458   else if (section_is_p (sectp->name, &names.ranges))
2459     {
2460       this->ranges.s.section = sectp;
2461       this->ranges.size = bfd_get_section_size (sectp);
2462     }
2463   else if (section_is_p (sectp->name, &names.rnglists))
2464     {
2465       this->rnglists.s.section = sectp;
2466       this->rnglists.size = bfd_get_section_size (sectp);
2467     }
2468   else if (section_is_p (sectp->name, &names.types))
2469     {
2470       struct dwarf2_section_info type_section;
2471
2472       memset (&type_section, 0, sizeof (type_section));
2473       type_section.s.section = sectp;
2474       type_section.size = bfd_get_section_size (sectp);
2475
2476       VEC_safe_push (dwarf2_section_info_def, this->types,
2477                      &type_section);
2478     }
2479   else if (section_is_p (sectp->name, &names.gdb_index))
2480     {
2481       this->gdb_index.s.section = sectp;
2482       this->gdb_index.size = bfd_get_section_size (sectp);
2483     }
2484
2485   if ((bfd_get_section_flags (abfd, sectp) & (SEC_LOAD | SEC_ALLOC))
2486       && bfd_section_vma (abfd, sectp) == 0)
2487     this->has_section_at_zero = true;
2488 }
2489
2490 /* A helper function that decides whether a section is empty,
2491    or not present.  */
2492
2493 static int
2494 dwarf2_section_empty_p (const struct dwarf2_section_info *section)
2495 {
2496   if (section->is_virtual)
2497     return section->size == 0;
2498   return section->s.section == NULL || section->size == 0;
2499 }
2500
2501 /* Read the contents of the section INFO.
2502    OBJFILE is the main object file, but not necessarily the file where
2503    the section comes from.  E.g., for DWO files the bfd of INFO is the bfd
2504    of the DWO file.
2505    If the section is compressed, uncompress it before returning.  */
2506
2507 static void
2508 dwarf2_read_section (struct objfile *objfile, struct dwarf2_section_info *info)
2509 {
2510   asection *sectp;
2511   bfd *abfd;
2512   gdb_byte *buf, *retbuf;
2513
2514   if (info->readin)
2515     return;
2516   info->buffer = NULL;
2517   info->readin = 1;
2518
2519   if (dwarf2_section_empty_p (info))
2520     return;
2521
2522   sectp = get_section_bfd_section (info);
2523
2524   /* If this is a virtual section we need to read in the real one first.  */
2525   if (info->is_virtual)
2526     {
2527       struct dwarf2_section_info *containing_section =
2528         get_containing_section (info);
2529
2530       gdb_assert (sectp != NULL);
2531       if ((sectp->flags & SEC_RELOC) != 0)
2532         {
2533           error (_("Dwarf Error: DWP format V2 with relocations is not"
2534                    " supported in section %s [in module %s]"),
2535                  get_section_name (info), get_section_file_name (info));
2536         }
2537       dwarf2_read_section (objfile, containing_section);
2538       /* Other code should have already caught virtual sections that don't
2539          fit.  */
2540       gdb_assert (info->virtual_offset + info->size
2541                   <= containing_section->size);
2542       /* If the real section is empty or there was a problem reading the
2543          section we shouldn't get here.  */
2544       gdb_assert (containing_section->buffer != NULL);
2545       info->buffer = containing_section->buffer + info->virtual_offset;
2546       return;
2547     }
2548
2549   /* If the section has relocations, we must read it ourselves.
2550      Otherwise we attach it to the BFD.  */
2551   if ((sectp->flags & SEC_RELOC) == 0)
2552     {
2553       info->buffer = gdb_bfd_map_section (sectp, &info->size);
2554       return;
2555     }
2556
2557   buf = (gdb_byte *) obstack_alloc (&objfile->objfile_obstack, info->size);
2558   info->buffer = buf;
2559
2560   /* When debugging .o files, we may need to apply relocations; see
2561      http://sourceware.org/ml/gdb-patches/2002-04/msg00136.html .
2562      We never compress sections in .o files, so we only need to
2563      try this when the section is not compressed.  */
2564   retbuf = symfile_relocate_debug_section (objfile, sectp, buf);
2565   if (retbuf != NULL)
2566     {
2567       info->buffer = retbuf;
2568       return;
2569     }
2570
2571   abfd = get_section_bfd_owner (info);
2572   gdb_assert (abfd != NULL);
2573
2574   if (bfd_seek (abfd, sectp->filepos, SEEK_SET) != 0
2575       || bfd_bread (buf, info->size, abfd) != info->size)
2576     {
2577       error (_("Dwarf Error: Can't read DWARF data"
2578                " in section %s [in module %s]"),
2579              bfd_section_name (abfd, sectp), bfd_get_filename (abfd));
2580     }
2581 }
2582
2583 /* A helper function that returns the size of a section in a safe way.
2584    If you are positive that the section has been read before using the
2585    size, then it is safe to refer to the dwarf2_section_info object's
2586    "size" field directly.  In other cases, you must call this
2587    function, because for compressed sections the size field is not set
2588    correctly until the section has been read.  */
2589
2590 static bfd_size_type
2591 dwarf2_section_size (struct objfile *objfile,
2592                      struct dwarf2_section_info *info)
2593 {
2594   if (!info->readin)
2595     dwarf2_read_section (objfile, info);
2596   return info->size;
2597 }
2598
2599 /* Fill in SECTP, BUFP and SIZEP with section info, given OBJFILE and
2600    SECTION_NAME.  */
2601
2602 void
2603 dwarf2_get_section_info (struct objfile *objfile,
2604                          enum dwarf2_section_enum sect,
2605                          asection **sectp, const gdb_byte **bufp,
2606                          bfd_size_type *sizep)
2607 {
2608   struct dwarf2_per_objfile *data
2609     = (struct dwarf2_per_objfile *) objfile_data (objfile,
2610                                                   dwarf2_objfile_data_key);
2611   struct dwarf2_section_info *info;
2612
2613   /* We may see an objfile without any DWARF, in which case we just
2614      return nothing.  */
2615   if (data == NULL)
2616     {
2617       *sectp = NULL;
2618       *bufp = NULL;
2619       *sizep = 0;
2620       return;
2621     }
2622   switch (sect)
2623     {
2624     case DWARF2_DEBUG_FRAME:
2625       info = &data->frame;
2626       break;
2627     case DWARF2_EH_FRAME:
2628       info = &data->eh_frame;
2629       break;
2630     default:
2631       gdb_assert_not_reached ("unexpected section");
2632     }
2633
2634   dwarf2_read_section (objfile, info);
2635
2636   *sectp = get_section_bfd_section (info);
2637   *bufp = info->buffer;
2638   *sizep = info->size;
2639 }
2640
2641 /* A helper function to find the sections for a .dwz file.  */
2642
2643 static void
2644 locate_dwz_sections (bfd *abfd, asection *sectp, void *arg)
2645 {
2646   struct dwz_file *dwz_file = (struct dwz_file *) arg;
2647
2648   /* Note that we only support the standard ELF names, because .dwz
2649      is ELF-only (at the time of writing).  */
2650   if (section_is_p (sectp->name, &dwarf2_elf_names.abbrev))
2651     {
2652       dwz_file->abbrev.s.section = sectp;
2653       dwz_file->abbrev.size = bfd_get_section_size (sectp);
2654     }
2655   else if (section_is_p (sectp->name, &dwarf2_elf_names.info))
2656     {
2657       dwz_file->info.s.section = sectp;
2658       dwz_file->info.size = bfd_get_section_size (sectp);
2659     }
2660   else if (section_is_p (sectp->name, &dwarf2_elf_names.str))
2661     {
2662       dwz_file->str.s.section = sectp;
2663       dwz_file->str.size = bfd_get_section_size (sectp);
2664     }
2665   else if (section_is_p (sectp->name, &dwarf2_elf_names.line))
2666     {
2667       dwz_file->line.s.section = sectp;
2668       dwz_file->line.size = bfd_get_section_size (sectp);
2669     }
2670   else if (section_is_p (sectp->name, &dwarf2_elf_names.macro))
2671     {
2672       dwz_file->macro.s.section = sectp;
2673       dwz_file->macro.size = bfd_get_section_size (sectp);
2674     }
2675   else if (section_is_p (sectp->name, &dwarf2_elf_names.gdb_index))
2676     {
2677       dwz_file->gdb_index.s.section = sectp;
2678       dwz_file->gdb_index.size = bfd_get_section_size (sectp);
2679     }
2680 }
2681
2682 /* Open the separate '.dwz' debug file, if needed.  Return NULL if
2683    there is no .gnu_debugaltlink section in the file.  Error if there
2684    is such a section but the file cannot be found.  */
2685
2686 static struct dwz_file *
2687 dwarf2_get_dwz_file (void)
2688 {
2689   char *data;
2690   struct cleanup *cleanup;
2691   const char *filename;
2692   struct dwz_file *result;
2693   bfd_size_type buildid_len_arg;
2694   size_t buildid_len;
2695   bfd_byte *buildid;
2696
2697   if (dwarf2_per_objfile->dwz_file != NULL)
2698     return dwarf2_per_objfile->dwz_file;
2699
2700   bfd_set_error (bfd_error_no_error);
2701   data = bfd_get_alt_debug_link_info (dwarf2_per_objfile->objfile->obfd,
2702                                       &buildid_len_arg, &buildid);
2703   if (data == NULL)
2704     {
2705       if (bfd_get_error () == bfd_error_no_error)
2706         return NULL;
2707       error (_("could not read '.gnu_debugaltlink' section: %s"),
2708              bfd_errmsg (bfd_get_error ()));
2709     }
2710   cleanup = make_cleanup (xfree, data);
2711   make_cleanup (xfree, buildid);
2712
2713   buildid_len = (size_t) buildid_len_arg;
2714
2715   filename = (const char *) data;
2716
2717   std::string abs_storage;
2718   if (!IS_ABSOLUTE_PATH (filename))
2719     {
2720       gdb::unique_xmalloc_ptr<char> abs
2721         = gdb_realpath (objfile_name (dwarf2_per_objfile->objfile));
2722
2723       abs_storage = ldirname (abs.get ()) + SLASH_STRING + filename;
2724       filename = abs_storage.c_str ();
2725     }
2726
2727   /* First try the file name given in the section.  If that doesn't
2728      work, try to use the build-id instead.  */
2729   gdb_bfd_ref_ptr dwz_bfd (gdb_bfd_open (filename, gnutarget, -1));
2730   if (dwz_bfd != NULL)
2731     {
2732       if (!build_id_verify (dwz_bfd.get (), buildid_len, buildid))
2733         dwz_bfd.release ();
2734     }
2735
2736   if (dwz_bfd == NULL)
2737     dwz_bfd = build_id_to_debug_bfd (buildid_len, buildid);
2738
2739   if (dwz_bfd == NULL)
2740     error (_("could not find '.gnu_debugaltlink' file for %s"),
2741            objfile_name (dwarf2_per_objfile->objfile));
2742
2743   result = OBSTACK_ZALLOC (&dwarf2_per_objfile->objfile->objfile_obstack,
2744                            struct dwz_file);
2745   result->dwz_bfd = dwz_bfd.release ();
2746
2747   bfd_map_over_sections (result->dwz_bfd, locate_dwz_sections, result);
2748
2749   do_cleanups (cleanup);
2750
2751   gdb_bfd_record_inclusion (dwarf2_per_objfile->objfile->obfd, result->dwz_bfd);
2752   dwarf2_per_objfile->dwz_file = result;
2753   return result;
2754 }
2755 \f
2756 /* DWARF quick_symbols_functions support.  */
2757
2758 /* TUs can share .debug_line entries, and there can be a lot more TUs than
2759    unique line tables, so we maintain a separate table of all .debug_line
2760    derived entries to support the sharing.
2761    All the quick functions need is the list of file names.  We discard the
2762    line_header when we're done and don't need to record it here.  */
2763 struct quick_file_names
2764 {
2765   /* The data used to construct the hash key.  */
2766   struct stmt_list_hash hash;
2767
2768   /* The number of entries in file_names, real_names.  */
2769   unsigned int num_file_names;
2770
2771   /* The file names from the line table, after being run through
2772      file_full_name.  */
2773   const char **file_names;
2774
2775   /* The file names from the line table after being run through
2776      gdb_realpath.  These are computed lazily.  */
2777   const char **real_names;
2778 };
2779
2780 /* When using the index (and thus not using psymtabs), each CU has an
2781    object of this type.  This is used to hold information needed by
2782    the various "quick" methods.  */
2783 struct dwarf2_per_cu_quick_data
2784 {
2785   /* The file table.  This can be NULL if there was no file table
2786      or it's currently not read in.
2787      NOTE: This points into dwarf2_per_objfile->quick_file_names_table.  */
2788   struct quick_file_names *file_names;
2789
2790   /* The corresponding symbol table.  This is NULL if symbols for this
2791      CU have not yet been read.  */
2792   struct compunit_symtab *compunit_symtab;
2793
2794   /* A temporary mark bit used when iterating over all CUs in
2795      expand_symtabs_matching.  */
2796   unsigned int mark : 1;
2797
2798   /* True if we've tried to read the file table and found there isn't one.
2799      There will be no point in trying to read it again next time.  */
2800   unsigned int no_file_data : 1;
2801 };
2802
2803 /* Utility hash function for a stmt_list_hash.  */
2804
2805 static hashval_t
2806 hash_stmt_list_entry (const struct stmt_list_hash *stmt_list_hash)
2807 {
2808   hashval_t v = 0;
2809
2810   if (stmt_list_hash->dwo_unit != NULL)
2811     v += (uintptr_t) stmt_list_hash->dwo_unit->dwo_file;
2812   v += to_underlying (stmt_list_hash->line_sect_off);
2813   return v;
2814 }
2815
2816 /* Utility equality function for a stmt_list_hash.  */
2817
2818 static int
2819 eq_stmt_list_entry (const struct stmt_list_hash *lhs,
2820                     const struct stmt_list_hash *rhs)
2821 {
2822   if ((lhs->dwo_unit != NULL) != (rhs->dwo_unit != NULL))
2823     return 0;
2824   if (lhs->dwo_unit != NULL
2825       && lhs->dwo_unit->dwo_file != rhs->dwo_unit->dwo_file)
2826     return 0;
2827
2828   return lhs->line_sect_off == rhs->line_sect_off;
2829 }
2830
2831 /* Hash function for a quick_file_names.  */
2832
2833 static hashval_t
2834 hash_file_name_entry (const void *e)
2835 {
2836   const struct quick_file_names *file_data
2837     = (const struct quick_file_names *) e;
2838
2839   return hash_stmt_list_entry (&file_data->hash);
2840 }
2841
2842 /* Equality function for a quick_file_names.  */
2843
2844 static int
2845 eq_file_name_entry (const void *a, const void *b)
2846 {
2847   const struct quick_file_names *ea = (const struct quick_file_names *) a;
2848   const struct quick_file_names *eb = (const struct quick_file_names *) b;
2849
2850   return eq_stmt_list_entry (&ea->hash, &eb->hash);
2851 }
2852
2853 /* Delete function for a quick_file_names.  */
2854
2855 static void
2856 delete_file_name_entry (void *e)
2857 {
2858   struct quick_file_names *file_data = (struct quick_file_names *) e;
2859   int i;
2860
2861   for (i = 0; i < file_data->num_file_names; ++i)
2862     {
2863       xfree ((void*) file_data->file_names[i]);
2864       if (file_data->real_names)
2865         xfree ((void*) file_data->real_names[i]);
2866     }
2867
2868   /* The space for the struct itself lives on objfile_obstack,
2869      so we don't free it here.  */
2870 }
2871
2872 /* Create a quick_file_names hash table.  */
2873
2874 static htab_t
2875 create_quick_file_names_table (unsigned int nr_initial_entries)
2876 {
2877   return htab_create_alloc (nr_initial_entries,
2878                             hash_file_name_entry, eq_file_name_entry,
2879                             delete_file_name_entry, xcalloc, xfree);
2880 }
2881
2882 /* Read in PER_CU->CU.  This function is unrelated to symtabs, symtab would
2883    have to be created afterwards.  You should call age_cached_comp_units after
2884    processing PER_CU->CU.  dw2_setup must have been already called.  */
2885
2886 static void
2887 load_cu (struct dwarf2_per_cu_data *per_cu)
2888 {
2889   if (per_cu->is_debug_types)
2890     load_full_type_unit (per_cu);
2891   else
2892     load_full_comp_unit (per_cu, language_minimal);
2893
2894   if (per_cu->cu == NULL)
2895     return;  /* Dummy CU.  */
2896
2897   dwarf2_find_base_address (per_cu->cu->dies, per_cu->cu);
2898 }
2899
2900 /* Read in the symbols for PER_CU.  */
2901
2902 static void
2903 dw2_do_instantiate_symtab (struct dwarf2_per_cu_data *per_cu)
2904 {
2905   struct cleanup *back_to;
2906
2907   /* Skip type_unit_groups, reading the type units they contain
2908      is handled elsewhere.  */
2909   if (IS_TYPE_UNIT_GROUP (per_cu))
2910     return;
2911
2912   back_to = make_cleanup (dwarf2_release_queue, NULL);
2913
2914   if (dwarf2_per_objfile->using_index
2915       ? per_cu->v.quick->compunit_symtab == NULL
2916       : (per_cu->v.psymtab == NULL || !per_cu->v.psymtab->readin))
2917     {
2918       queue_comp_unit (per_cu, language_minimal);
2919       load_cu (per_cu);
2920
2921       /* If we just loaded a CU from a DWO, and we're working with an index
2922          that may badly handle TUs, load all the TUs in that DWO as well.
2923          http://sourceware.org/bugzilla/show_bug.cgi?id=15021  */
2924       if (!per_cu->is_debug_types
2925           && per_cu->cu != NULL
2926           && per_cu->cu->dwo_unit != NULL
2927           && dwarf2_per_objfile->index_table != NULL
2928           && dwarf2_per_objfile->index_table->version <= 7
2929           /* DWP files aren't supported yet.  */
2930           && get_dwp_file () == NULL)
2931         queue_and_load_all_dwo_tus (per_cu);
2932     }
2933
2934   process_queue ();
2935
2936   /* Age the cache, releasing compilation units that have not
2937      been used recently.  */
2938   age_cached_comp_units ();
2939
2940   do_cleanups (back_to);
2941 }
2942
2943 /* Ensure that the symbols for PER_CU have been read in.  OBJFILE is
2944    the objfile from which this CU came.  Returns the resulting symbol
2945    table.  */
2946
2947 static struct compunit_symtab *
2948 dw2_instantiate_symtab (struct dwarf2_per_cu_data *per_cu)
2949 {
2950   gdb_assert (dwarf2_per_objfile->using_index);
2951   if (!per_cu->v.quick->compunit_symtab)
2952     {
2953       struct cleanup *back_to = make_cleanup (free_cached_comp_units, NULL);
2954       scoped_restore decrementer = increment_reading_symtab ();
2955       dw2_do_instantiate_symtab (per_cu);
2956       process_cu_includes ();
2957       do_cleanups (back_to);
2958     }
2959
2960   return per_cu->v.quick->compunit_symtab;
2961 }
2962
2963 /* Return the CU/TU given its index.
2964
2965    This is intended for loops like:
2966
2967    for (i = 0; i < (dwarf2_per_objfile->n_comp_units
2968                     + dwarf2_per_objfile->n_type_units); ++i)
2969      {
2970        struct dwarf2_per_cu_data *per_cu = dw2_get_cutu (i);
2971
2972        ...;
2973      }
2974 */
2975
2976 static struct dwarf2_per_cu_data *
2977 dw2_get_cutu (int index)
2978 {
2979   if (index >= dwarf2_per_objfile->n_comp_units)
2980     {
2981       index -= dwarf2_per_objfile->n_comp_units;
2982       gdb_assert (index < dwarf2_per_objfile->n_type_units);
2983       return &dwarf2_per_objfile->all_type_units[index]->per_cu;
2984     }
2985
2986   return dwarf2_per_objfile->all_comp_units[index];
2987 }
2988
2989 /* Return the CU given its index.
2990    This differs from dw2_get_cutu in that it's for when you know INDEX
2991    refers to a CU.  */
2992
2993 static struct dwarf2_per_cu_data *
2994 dw2_get_cu (int index)
2995 {
2996   gdb_assert (index >= 0 && index < dwarf2_per_objfile->n_comp_units);
2997
2998   return dwarf2_per_objfile->all_comp_units[index];
2999 }
3000
3001 /* A helper for create_cus_from_index that handles a given list of
3002    CUs.  */
3003
3004 static void
3005 create_cus_from_index_list (struct objfile *objfile,
3006                             const gdb_byte *cu_list, offset_type n_elements,
3007                             struct dwarf2_section_info *section,
3008                             int is_dwz,
3009                             int base_offset)
3010 {
3011   offset_type i;
3012
3013   for (i = 0; i < n_elements; i += 2)
3014     {
3015       gdb_static_assert (sizeof (ULONGEST) >= 8);
3016
3017       sect_offset sect_off
3018         = (sect_offset) extract_unsigned_integer (cu_list, 8, BFD_ENDIAN_LITTLE);
3019       ULONGEST length = extract_unsigned_integer (cu_list + 8, 8, BFD_ENDIAN_LITTLE);
3020       cu_list += 2 * 8;
3021
3022       dwarf2_per_cu_data *the_cu
3023         = OBSTACK_ZALLOC (&objfile->objfile_obstack,
3024                           struct dwarf2_per_cu_data);
3025       the_cu->sect_off = sect_off;
3026       the_cu->length = length;
3027       the_cu->objfile = objfile;
3028       the_cu->section = section;
3029       the_cu->v.quick = OBSTACK_ZALLOC (&objfile->objfile_obstack,
3030                                         struct dwarf2_per_cu_quick_data);
3031       the_cu->is_dwz = is_dwz;
3032       dwarf2_per_objfile->all_comp_units[base_offset + i / 2] = the_cu;
3033     }
3034 }
3035
3036 /* Read the CU list from the mapped index, and use it to create all
3037    the CU objects for this objfile.  */
3038
3039 static void
3040 create_cus_from_index (struct objfile *objfile,
3041                        const gdb_byte *cu_list, offset_type cu_list_elements,
3042                        const gdb_byte *dwz_list, offset_type dwz_elements)
3043 {
3044   struct dwz_file *dwz;
3045
3046   dwarf2_per_objfile->n_comp_units = (cu_list_elements + dwz_elements) / 2;
3047   dwarf2_per_objfile->all_comp_units =
3048     XOBNEWVEC (&objfile->objfile_obstack, struct dwarf2_per_cu_data *,
3049                dwarf2_per_objfile->n_comp_units);
3050
3051   create_cus_from_index_list (objfile, cu_list, cu_list_elements,
3052                               &dwarf2_per_objfile->info, 0, 0);
3053
3054   if (dwz_elements == 0)
3055     return;
3056
3057   dwz = dwarf2_get_dwz_file ();
3058   create_cus_from_index_list (objfile, dwz_list, dwz_elements, &dwz->info, 1,
3059                               cu_list_elements / 2);
3060 }
3061
3062 /* Create the signatured type hash table from the index.  */
3063
3064 static void
3065 create_signatured_type_table_from_index (struct objfile *objfile,
3066                                          struct dwarf2_section_info *section,
3067                                          const gdb_byte *bytes,
3068                                          offset_type elements)
3069 {
3070   offset_type i;
3071   htab_t sig_types_hash;
3072
3073   dwarf2_per_objfile->n_type_units
3074     = dwarf2_per_objfile->n_allocated_type_units
3075     = elements / 3;
3076   dwarf2_per_objfile->all_type_units =
3077     XNEWVEC (struct signatured_type *, dwarf2_per_objfile->n_type_units);
3078
3079   sig_types_hash = allocate_signatured_type_table (objfile);
3080
3081   for (i = 0; i < elements; i += 3)
3082     {
3083       struct signatured_type *sig_type;
3084       ULONGEST signature;
3085       void **slot;
3086       cu_offset type_offset_in_tu;
3087
3088       gdb_static_assert (sizeof (ULONGEST) >= 8);
3089       sect_offset sect_off
3090         = (sect_offset) extract_unsigned_integer (bytes, 8, BFD_ENDIAN_LITTLE);
3091       type_offset_in_tu
3092         = (cu_offset) extract_unsigned_integer (bytes + 8, 8,
3093                                                 BFD_ENDIAN_LITTLE);
3094       signature = extract_unsigned_integer (bytes + 16, 8, BFD_ENDIAN_LITTLE);
3095       bytes += 3 * 8;
3096
3097       sig_type = OBSTACK_ZALLOC (&objfile->objfile_obstack,
3098                                  struct signatured_type);
3099       sig_type->signature = signature;
3100       sig_type->type_offset_in_tu = type_offset_in_tu;
3101       sig_type->per_cu.is_debug_types = 1;
3102       sig_type->per_cu.section = section;
3103       sig_type->per_cu.sect_off = sect_off;
3104       sig_type->per_cu.objfile = objfile;
3105       sig_type->per_cu.v.quick
3106         = OBSTACK_ZALLOC (&objfile->objfile_obstack,
3107                           struct dwarf2_per_cu_quick_data);
3108
3109       slot = htab_find_slot (sig_types_hash, sig_type, INSERT);
3110       *slot = sig_type;
3111
3112       dwarf2_per_objfile->all_type_units[i / 3] = sig_type;
3113     }
3114
3115   dwarf2_per_objfile->signatured_types = sig_types_hash;
3116 }
3117
3118 /* Read the address map data from the mapped index, and use it to
3119    populate the objfile's psymtabs_addrmap.  */
3120
3121 static void
3122 create_addrmap_from_index (struct objfile *objfile, struct mapped_index *index)
3123 {
3124   struct gdbarch *gdbarch = get_objfile_arch (objfile);
3125   const gdb_byte *iter, *end;
3126   struct addrmap *mutable_map;
3127   CORE_ADDR baseaddr;
3128
3129   auto_obstack temp_obstack;
3130
3131   mutable_map = addrmap_create_mutable (&temp_obstack);
3132
3133   iter = index->address_table;
3134   end = iter + index->address_table_size;
3135
3136   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
3137
3138   while (iter < end)
3139     {
3140       ULONGEST hi, lo, cu_index;
3141       lo = extract_unsigned_integer (iter, 8, BFD_ENDIAN_LITTLE);
3142       iter += 8;
3143       hi = extract_unsigned_integer (iter, 8, BFD_ENDIAN_LITTLE);
3144       iter += 8;
3145       cu_index = extract_unsigned_integer (iter, 4, BFD_ENDIAN_LITTLE);
3146       iter += 4;
3147
3148       if (lo > hi)
3149         {
3150           complaint (&symfile_complaints,
3151                      _(".gdb_index address table has invalid range (%s - %s)"),
3152                      hex_string (lo), hex_string (hi));
3153           continue;
3154         }
3155
3156       if (cu_index >= dwarf2_per_objfile->n_comp_units)
3157         {
3158           complaint (&symfile_complaints,
3159                      _(".gdb_index address table has invalid CU number %u"),
3160                      (unsigned) cu_index);
3161           continue;
3162         }
3163
3164       lo = gdbarch_adjust_dwarf2_addr (gdbarch, lo + baseaddr);
3165       hi = gdbarch_adjust_dwarf2_addr (gdbarch, hi + baseaddr);
3166       addrmap_set_empty (mutable_map, lo, hi - 1, dw2_get_cutu (cu_index));
3167     }
3168
3169   objfile->psymtabs_addrmap = addrmap_create_fixed (mutable_map,
3170                                                     &objfile->objfile_obstack);
3171 }
3172
3173 /* The hash function for strings in the mapped index.  This is the same as
3174    SYMBOL_HASH_NEXT, but we keep a separate copy to maintain control over the
3175    implementation.  This is necessary because the hash function is tied to the
3176    format of the mapped index file.  The hash values do not have to match with
3177    SYMBOL_HASH_NEXT.
3178    
3179    Use INT_MAX for INDEX_VERSION if you generate the current index format.  */
3180
3181 static hashval_t
3182 mapped_index_string_hash (int index_version, const void *p)
3183 {
3184   const unsigned char *str = (const unsigned char *) p;
3185   hashval_t r = 0;
3186   unsigned char c;
3187
3188   while ((c = *str++) != 0)
3189     {
3190       if (index_version >= 5)
3191         c = tolower (c);
3192       r = r * 67 + c - 113;
3193     }
3194
3195   return r;
3196 }
3197
3198 /* Find a slot in the mapped index INDEX for the object named NAME.
3199    If NAME is found, set *VEC_OUT to point to the CU vector in the
3200    constant pool and return 1.  If NAME cannot be found, return 0.  */
3201
3202 static int
3203 find_slot_in_mapped_hash (struct mapped_index *index, const char *name,
3204                           offset_type **vec_out)
3205 {
3206   struct cleanup *back_to = make_cleanup (null_cleanup, 0);
3207   offset_type hash;
3208   offset_type slot, step;
3209   int (*cmp) (const char *, const char *);
3210
3211   if (current_language->la_language == language_cplus
3212       || current_language->la_language == language_fortran
3213       || current_language->la_language == language_d)
3214     {
3215       /* NAME is already canonical.  Drop any qualifiers as .gdb_index does
3216          not contain any.  */
3217
3218       if (strchr (name, '(') != NULL)
3219         {
3220           char *without_params = cp_remove_params (name);
3221
3222           if (without_params != NULL)
3223             {
3224               make_cleanup (xfree, without_params);
3225               name = without_params;
3226             }
3227         }
3228     }
3229
3230   /* Index version 4 did not support case insensitive searches.  But the
3231      indices for case insensitive languages are built in lowercase, therefore
3232      simulate our NAME being searched is also lowercased.  */
3233   hash = mapped_index_string_hash ((index->version == 4
3234                                     && case_sensitivity == case_sensitive_off
3235                                     ? 5 : index->version),
3236                                    name);
3237
3238   slot = hash & (index->symbol_table_slots - 1);
3239   step = ((hash * 17) & (index->symbol_table_slots - 1)) | 1;
3240   cmp = (case_sensitivity == case_sensitive_on ? strcmp : strcasecmp);
3241
3242   for (;;)
3243     {
3244       /* Convert a slot number to an offset into the table.  */
3245       offset_type i = 2 * slot;
3246       const char *str;
3247       if (index->symbol_table[i] == 0 && index->symbol_table[i + 1] == 0)
3248         {
3249           do_cleanups (back_to);
3250           return 0;
3251         }
3252
3253       str = index->constant_pool + MAYBE_SWAP (index->symbol_table[i]);
3254       if (!cmp (name, str))
3255         {
3256           *vec_out = (offset_type *) (index->constant_pool
3257                                       + MAYBE_SWAP (index->symbol_table[i + 1]));
3258           do_cleanups (back_to);
3259           return 1;
3260         }
3261
3262       slot = (slot + step) & (index->symbol_table_slots - 1);
3263     }
3264 }
3265
3266 /* A helper function that reads the .gdb_index from SECTION and fills
3267    in MAP.  FILENAME is the name of the file containing the section;
3268    it is used for error reporting.  DEPRECATED_OK is nonzero if it is
3269    ok to use deprecated sections.
3270
3271    CU_LIST, CU_LIST_ELEMENTS, TYPES_LIST, and TYPES_LIST_ELEMENTS are
3272    out parameters that are filled in with information about the CU and
3273    TU lists in the section.
3274
3275    Returns 1 if all went well, 0 otherwise.  */
3276
3277 static int
3278 read_index_from_section (struct objfile *objfile,
3279                          const char *filename,
3280                          int deprecated_ok,
3281                          struct dwarf2_section_info *section,
3282                          struct mapped_index *map,
3283                          const gdb_byte **cu_list,
3284                          offset_type *cu_list_elements,
3285                          const gdb_byte **types_list,
3286                          offset_type *types_list_elements)
3287 {
3288   const gdb_byte *addr;
3289   offset_type version;
3290   offset_type *metadata;
3291   int i;
3292
3293   if (dwarf2_section_empty_p (section))
3294     return 0;
3295
3296   /* Older elfutils strip versions could keep the section in the main
3297      executable while splitting it for the separate debug info file.  */
3298   if ((get_section_flags (section) & SEC_HAS_CONTENTS) == 0)
3299     return 0;
3300
3301   dwarf2_read_section (objfile, section);
3302
3303   addr = section->buffer;
3304   /* Version check.  */
3305   version = MAYBE_SWAP (*(offset_type *) addr);
3306   /* Versions earlier than 3 emitted every copy of a psymbol.  This
3307      causes the index to behave very poorly for certain requests.  Version 3
3308      contained incomplete addrmap.  So, it seems better to just ignore such
3309      indices.  */
3310   if (version < 4)
3311     {
3312       static int warning_printed = 0;
3313       if (!warning_printed)
3314         {
3315           warning (_("Skipping obsolete .gdb_index section in %s."),
3316                    filename);
3317           warning_printed = 1;
3318         }
3319       return 0;
3320     }
3321   /* Index version 4 uses a different hash function than index version
3322      5 and later.
3323
3324      Versions earlier than 6 did not emit psymbols for inlined
3325      functions.  Using these files will cause GDB not to be able to
3326      set breakpoints on inlined functions by name, so we ignore these
3327      indices unless the user has done
3328      "set use-deprecated-index-sections on".  */
3329   if (version < 6 && !deprecated_ok)
3330     {
3331       static int warning_printed = 0;
3332       if (!warning_printed)
3333         {
3334           warning (_("\
3335 Skipping deprecated .gdb_index section in %s.\n\
3336 Do \"set use-deprecated-index-sections on\" before the file is read\n\
3337 to use the section anyway."),
3338                    filename);
3339           warning_printed = 1;
3340         }
3341       return 0;
3342     }
3343   /* Version 7 indices generated by gold refer to the CU for a symbol instead
3344      of the TU (for symbols coming from TUs),
3345      http://sourceware.org/bugzilla/show_bug.cgi?id=15021.
3346      Plus gold-generated indices can have duplicate entries for global symbols,
3347      http://sourceware.org/bugzilla/show_bug.cgi?id=15646.
3348      These are just performance bugs, and we can't distinguish gdb-generated
3349      indices from gold-generated ones, so issue no warning here.  */
3350
3351   /* Indexes with higher version than the one supported by GDB may be no
3352      longer backward compatible.  */
3353   if (version > 8)
3354     return 0;
3355
3356   map->version = version;
3357   map->total_size = section->size;
3358
3359   metadata = (offset_type *) (addr + sizeof (offset_type));
3360
3361   i = 0;
3362   *cu_list = addr + MAYBE_SWAP (metadata[i]);
3363   *cu_list_elements = ((MAYBE_SWAP (metadata[i + 1]) - MAYBE_SWAP (metadata[i]))
3364                        / 8);
3365   ++i;
3366
3367   *types_list = addr + MAYBE_SWAP (metadata[i]);
3368   *types_list_elements = ((MAYBE_SWAP (metadata[i + 1])
3369                            - MAYBE_SWAP (metadata[i]))
3370                           / 8);
3371   ++i;
3372
3373   map->address_table = addr + MAYBE_SWAP (metadata[i]);
3374   map->address_table_size = (MAYBE_SWAP (metadata[i + 1])
3375                              - MAYBE_SWAP (metadata[i]));
3376   ++i;
3377
3378   map->symbol_table = (offset_type *) (addr + MAYBE_SWAP (metadata[i]));
3379   map->symbol_table_slots = ((MAYBE_SWAP (metadata[i + 1])
3380                               - MAYBE_SWAP (metadata[i]))
3381                              / (2 * sizeof (offset_type)));
3382   ++i;
3383
3384   map->constant_pool = (char *) (addr + MAYBE_SWAP (metadata[i]));
3385
3386   return 1;
3387 }
3388
3389
3390 /* Read the index file.  If everything went ok, initialize the "quick"
3391    elements of all the CUs and return 1.  Otherwise, return 0.  */
3392
3393 static int
3394 dwarf2_read_index (struct objfile *objfile)
3395 {
3396   struct mapped_index local_map, *map;
3397   const gdb_byte *cu_list, *types_list, *dwz_list = NULL;
3398   offset_type cu_list_elements, types_list_elements, dwz_list_elements = 0;
3399   struct dwz_file *dwz;
3400
3401   if (!read_index_from_section (objfile, objfile_name (objfile),
3402                                 use_deprecated_index_sections,
3403                                 &dwarf2_per_objfile->gdb_index, &local_map,
3404                                 &cu_list, &cu_list_elements,
3405                                 &types_list, &types_list_elements))
3406     return 0;
3407
3408   /* Don't use the index if it's empty.  */
3409   if (local_map.symbol_table_slots == 0)
3410     return 0;
3411
3412   /* If there is a .dwz file, read it so we can get its CU list as
3413      well.  */
3414   dwz = dwarf2_get_dwz_file ();
3415   if (dwz != NULL)
3416     {
3417       struct mapped_index dwz_map;
3418       const gdb_byte *dwz_types_ignore;
3419       offset_type dwz_types_elements_ignore;
3420
3421       if (!read_index_from_section (objfile, bfd_get_filename (dwz->dwz_bfd),
3422                                     1,
3423                                     &dwz->gdb_index, &dwz_map,
3424                                     &dwz_list, &dwz_list_elements,
3425                                     &dwz_types_ignore,
3426                                     &dwz_types_elements_ignore))
3427         {
3428           warning (_("could not read '.gdb_index' section from %s; skipping"),
3429                    bfd_get_filename (dwz->dwz_bfd));
3430           return 0;
3431         }
3432     }
3433
3434   create_cus_from_index (objfile, cu_list, cu_list_elements, dwz_list,
3435                          dwz_list_elements);
3436
3437   if (types_list_elements)
3438     {
3439       struct dwarf2_section_info *section;
3440
3441       /* We can only handle a single .debug_types when we have an
3442          index.  */
3443       if (VEC_length (dwarf2_section_info_def, dwarf2_per_objfile->types) != 1)
3444         return 0;
3445
3446       section = VEC_index (dwarf2_section_info_def,
3447                            dwarf2_per_objfile->types, 0);
3448
3449       create_signatured_type_table_from_index (objfile, section, types_list,
3450                                                types_list_elements);
3451     }
3452
3453   create_addrmap_from_index (objfile, &local_map);
3454
3455   map = XOBNEW (&objfile->objfile_obstack, struct mapped_index);
3456   *map = local_map;
3457
3458   dwarf2_per_objfile->index_table = map;
3459   dwarf2_per_objfile->using_index = 1;
3460   dwarf2_per_objfile->quick_file_names_table =
3461     create_quick_file_names_table (dwarf2_per_objfile->n_comp_units);
3462
3463   return 1;
3464 }
3465
3466 /* A helper for the "quick" functions which sets the global
3467    dwarf2_per_objfile according to OBJFILE.  */
3468
3469 static void
3470 dw2_setup (struct objfile *objfile)
3471 {
3472   dwarf2_per_objfile = ((struct dwarf2_per_objfile *)
3473                         objfile_data (objfile, dwarf2_objfile_data_key));
3474   gdb_assert (dwarf2_per_objfile);
3475 }
3476
3477 /* die_reader_func for dw2_get_file_names.  */
3478
3479 static void
3480 dw2_get_file_names_reader (const struct die_reader_specs *reader,
3481                            const gdb_byte *info_ptr,
3482                            struct die_info *comp_unit_die,
3483                            int has_children,
3484                            void *data)
3485 {
3486   struct dwarf2_cu *cu = reader->cu;
3487   struct dwarf2_per_cu_data *this_cu = cu->per_cu;  
3488   struct objfile *objfile = dwarf2_per_objfile->objfile;
3489   struct dwarf2_per_cu_data *lh_cu;
3490   struct attribute *attr;
3491   int i;
3492   void **slot;
3493   struct quick_file_names *qfn;
3494
3495   gdb_assert (! this_cu->is_debug_types);
3496
3497   /* Our callers never want to match partial units -- instead they
3498      will match the enclosing full CU.  */
3499   if (comp_unit_die->tag == DW_TAG_partial_unit)
3500     {
3501       this_cu->v.quick->no_file_data = 1;
3502       return;
3503     }
3504
3505   lh_cu = this_cu;
3506   slot = NULL;
3507
3508   line_header_up lh;
3509   sect_offset line_offset {};
3510
3511   attr = dwarf2_attr (comp_unit_die, DW_AT_stmt_list, cu);
3512   if (attr)
3513     {
3514       struct quick_file_names find_entry;
3515
3516       line_offset = (sect_offset) DW_UNSND (attr);
3517
3518       /* We may have already read in this line header (TU line header sharing).
3519          If we have we're done.  */
3520       find_entry.hash.dwo_unit = cu->dwo_unit;
3521       find_entry.hash.line_sect_off = line_offset;
3522       slot = htab_find_slot (dwarf2_per_objfile->quick_file_names_table,
3523                              &find_entry, INSERT);
3524       if (*slot != NULL)
3525         {
3526           lh_cu->v.quick->file_names = (struct quick_file_names *) *slot;
3527           return;
3528         }
3529
3530       lh = dwarf_decode_line_header (line_offset, cu);
3531     }
3532   if (lh == NULL)
3533     {
3534       lh_cu->v.quick->no_file_data = 1;
3535       return;
3536     }
3537
3538   qfn = XOBNEW (&objfile->objfile_obstack, struct quick_file_names);
3539   qfn->hash.dwo_unit = cu->dwo_unit;
3540   qfn->hash.line_sect_off = line_offset;
3541   gdb_assert (slot != NULL);
3542   *slot = qfn;
3543
3544   file_and_directory fnd = find_file_and_directory (comp_unit_die, cu);
3545
3546   qfn->num_file_names = lh->file_names.size ();
3547   qfn->file_names =
3548     XOBNEWVEC (&objfile->objfile_obstack, const char *, lh->file_names.size ());
3549   for (i = 0; i < lh->file_names.size (); ++i)
3550     qfn->file_names[i] = file_full_name (i + 1, lh.get (), fnd.comp_dir);
3551   qfn->real_names = NULL;
3552
3553   lh_cu->v.quick->file_names = qfn;
3554 }
3555
3556 /* A helper for the "quick" functions which attempts to read the line
3557    table for THIS_CU.  */
3558
3559 static struct quick_file_names *
3560 dw2_get_file_names (struct dwarf2_per_cu_data *this_cu)
3561 {
3562   /* This should never be called for TUs.  */
3563   gdb_assert (! this_cu->is_debug_types);
3564   /* Nor type unit groups.  */
3565   gdb_assert (! IS_TYPE_UNIT_GROUP (this_cu));
3566
3567   if (this_cu->v.quick->file_names != NULL)
3568     return this_cu->v.quick->file_names;
3569   /* If we know there is no line data, no point in looking again.  */
3570   if (this_cu->v.quick->no_file_data)
3571     return NULL;
3572
3573   init_cutu_and_read_dies_simple (this_cu, dw2_get_file_names_reader, NULL);
3574
3575   if (this_cu->v.quick->no_file_data)
3576     return NULL;
3577   return this_cu->v.quick->file_names;
3578 }
3579
3580 /* A helper for the "quick" functions which computes and caches the
3581    real path for a given file name from the line table.  */
3582
3583 static const char *
3584 dw2_get_real_path (struct objfile *objfile,
3585                    struct quick_file_names *qfn, int index)
3586 {
3587   if (qfn->real_names == NULL)
3588     qfn->real_names = OBSTACK_CALLOC (&objfile->objfile_obstack,
3589                                       qfn->num_file_names, const char *);
3590
3591   if (qfn->real_names[index] == NULL)
3592     qfn->real_names[index] = gdb_realpath (qfn->file_names[index]).release ();
3593
3594   return qfn->real_names[index];
3595 }
3596
3597 static struct symtab *
3598 dw2_find_last_source_symtab (struct objfile *objfile)
3599 {
3600   struct compunit_symtab *cust;
3601   int index;
3602
3603   dw2_setup (objfile);
3604   index = dwarf2_per_objfile->n_comp_units - 1;
3605   cust = dw2_instantiate_symtab (dw2_get_cutu (index));
3606   if (cust == NULL)
3607     return NULL;
3608   return compunit_primary_filetab (cust);
3609 }
3610
3611 /* Traversal function for dw2_forget_cached_source_info.  */
3612
3613 static int
3614 dw2_free_cached_file_names (void **slot, void *info)
3615 {
3616   struct quick_file_names *file_data = (struct quick_file_names *) *slot;
3617
3618   if (file_data->real_names)
3619     {
3620       int i;
3621
3622       for (i = 0; i < file_data->num_file_names; ++i)
3623         {
3624           xfree ((void*) file_data->real_names[i]);
3625           file_data->real_names[i] = NULL;
3626         }
3627     }
3628
3629   return 1;
3630 }
3631
3632 static void
3633 dw2_forget_cached_source_info (struct objfile *objfile)
3634 {
3635   dw2_setup (objfile);
3636
3637   htab_traverse_noresize (dwarf2_per_objfile->quick_file_names_table,
3638                           dw2_free_cached_file_names, NULL);
3639 }
3640
3641 /* Helper function for dw2_map_symtabs_matching_filename that expands
3642    the symtabs and calls the iterator.  */
3643
3644 static int
3645 dw2_map_expand_apply (struct objfile *objfile,
3646                       struct dwarf2_per_cu_data *per_cu,
3647                       const char *name, const char *real_path,
3648                       gdb::function_view<bool (symtab *)> callback)
3649 {
3650   struct compunit_symtab *last_made = objfile->compunit_symtabs;
3651
3652   /* Don't visit already-expanded CUs.  */
3653   if (per_cu->v.quick->compunit_symtab)
3654     return 0;
3655
3656   /* This may expand more than one symtab, and we want to iterate over
3657      all of them.  */
3658   dw2_instantiate_symtab (per_cu);
3659
3660   return iterate_over_some_symtabs (name, real_path, objfile->compunit_symtabs,
3661                                     last_made, callback);
3662 }
3663
3664 /* Implementation of the map_symtabs_matching_filename method.  */
3665
3666 static bool
3667 dw2_map_symtabs_matching_filename
3668   (struct objfile *objfile, const char *name, const char *real_path,
3669    gdb::function_view<bool (symtab *)> callback)
3670 {
3671   int i;
3672   const char *name_basename = lbasename (name);
3673
3674   dw2_setup (objfile);
3675
3676   /* The rule is CUs specify all the files, including those used by
3677      any TU, so there's no need to scan TUs here.  */
3678
3679   for (i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
3680     {
3681       int j;
3682       struct dwarf2_per_cu_data *per_cu = dw2_get_cu (i);
3683       struct quick_file_names *file_data;
3684
3685       /* We only need to look at symtabs not already expanded.  */
3686       if (per_cu->v.quick->compunit_symtab)
3687         continue;
3688
3689       file_data = dw2_get_file_names (per_cu);
3690       if (file_data == NULL)
3691         continue;
3692
3693       for (j = 0; j < file_data->num_file_names; ++j)
3694         {
3695           const char *this_name = file_data->file_names[j];
3696           const char *this_real_name;
3697
3698           if (compare_filenames_for_search (this_name, name))
3699             {
3700               if (dw2_map_expand_apply (objfile, per_cu, name, real_path,
3701                                         callback))
3702                 return true;
3703               continue;
3704             }
3705
3706           /* Before we invoke realpath, which can get expensive when many
3707              files are involved, do a quick comparison of the basenames.  */
3708           if (! basenames_may_differ
3709               && FILENAME_CMP (lbasename (this_name), name_basename) != 0)
3710             continue;
3711
3712           this_real_name = dw2_get_real_path (objfile, file_data, j);
3713           if (compare_filenames_for_search (this_real_name, name))
3714             {
3715               if (dw2_map_expand_apply (objfile, per_cu, name, real_path,
3716                                         callback))
3717                 return true;
3718               continue;
3719             }
3720
3721           if (real_path != NULL)
3722             {
3723               gdb_assert (IS_ABSOLUTE_PATH (real_path));
3724               gdb_assert (IS_ABSOLUTE_PATH (name));
3725               if (this_real_name != NULL
3726                   && FILENAME_CMP (real_path, this_real_name) == 0)
3727                 {
3728                   if (dw2_map_expand_apply (objfile, per_cu, name, real_path,
3729                                             callback))
3730                     return true;
3731                   continue;
3732                 }
3733             }
3734         }
3735     }
3736
3737   return false;
3738 }
3739
3740 /* Struct used to manage iterating over all CUs looking for a symbol.  */
3741
3742 struct dw2_symtab_iterator
3743 {
3744   /* The internalized form of .gdb_index.  */
3745   struct mapped_index *index;
3746   /* If non-zero, only look for symbols that match BLOCK_INDEX.  */
3747   int want_specific_block;
3748   /* One of GLOBAL_BLOCK or STATIC_BLOCK.
3749      Unused if !WANT_SPECIFIC_BLOCK.  */
3750   int block_index;
3751   /* The kind of symbol we're looking for.  */
3752   domain_enum domain;
3753   /* The list of CUs from the index entry of the symbol,
3754      or NULL if not found.  */
3755   offset_type *vec;
3756   /* The next element in VEC to look at.  */
3757   int next;
3758   /* The number of elements in VEC, or zero if there is no match.  */
3759   int length;
3760   /* Have we seen a global version of the symbol?
3761      If so we can ignore all further global instances.
3762      This is to work around gold/15646, inefficient gold-generated
3763      indices.  */
3764   int global_seen;
3765 };
3766
3767 /* Initialize the index symtab iterator ITER.
3768    If WANT_SPECIFIC_BLOCK is non-zero, only look for symbols
3769    in block BLOCK_INDEX.  Otherwise BLOCK_INDEX is ignored.  */
3770
3771 static void
3772 dw2_symtab_iter_init (struct dw2_symtab_iterator *iter,
3773                       struct mapped_index *index,
3774                       int want_specific_block,
3775                       int block_index,
3776                       domain_enum domain,
3777                       const char *name)
3778 {
3779   iter->index = index;
3780   iter->want_specific_block = want_specific_block;
3781   iter->block_index = block_index;
3782   iter->domain = domain;
3783   iter->next = 0;
3784   iter->global_seen = 0;
3785
3786   if (find_slot_in_mapped_hash (index, name, &iter->vec))
3787     iter->length = MAYBE_SWAP (*iter->vec);
3788   else
3789     {
3790       iter->vec = NULL;
3791       iter->length = 0;
3792     }
3793 }
3794
3795 /* Return the next matching CU or NULL if there are no more.  */
3796
3797 static struct dwarf2_per_cu_data *
3798 dw2_symtab_iter_next (struct dw2_symtab_iterator *iter)
3799 {
3800   for ( ; iter->next < iter->length; ++iter->next)
3801     {
3802       offset_type cu_index_and_attrs =
3803         MAYBE_SWAP (iter->vec[iter->next + 1]);
3804       offset_type cu_index = GDB_INDEX_CU_VALUE (cu_index_and_attrs);
3805       struct dwarf2_per_cu_data *per_cu;
3806       int want_static = iter->block_index != GLOBAL_BLOCK;
3807       /* This value is only valid for index versions >= 7.  */
3808       int is_static = GDB_INDEX_SYMBOL_STATIC_VALUE (cu_index_and_attrs);
3809       gdb_index_symbol_kind symbol_kind =
3810         GDB_INDEX_SYMBOL_KIND_VALUE (cu_index_and_attrs);
3811       /* Only check the symbol attributes if they're present.
3812          Indices prior to version 7 don't record them,
3813          and indices >= 7 may elide them for certain symbols
3814          (gold does this).  */
3815       int attrs_valid =
3816         (iter->index->version >= 7
3817          && symbol_kind != GDB_INDEX_SYMBOL_KIND_NONE);
3818
3819       /* Don't crash on bad data.  */
3820       if (cu_index >= (dwarf2_per_objfile->n_comp_units
3821                        + dwarf2_per_objfile->n_type_units))
3822         {
3823           complaint (&symfile_complaints,
3824                      _(".gdb_index entry has bad CU index"
3825                        " [in module %s]"),
3826                      objfile_name (dwarf2_per_objfile->objfile));
3827           continue;
3828         }
3829
3830       per_cu = dw2_get_cutu (cu_index);
3831
3832       /* Skip if already read in.  */
3833       if (per_cu->v.quick->compunit_symtab)
3834         continue;
3835
3836       /* Check static vs global.  */
3837       if (attrs_valid)
3838         {
3839           if (iter->want_specific_block
3840               && want_static != is_static)
3841             continue;
3842           /* Work around gold/15646.  */
3843           if (!is_static && iter->global_seen)
3844             continue;
3845           if (!is_static)
3846             iter->global_seen = 1;
3847         }
3848
3849       /* Only check the symbol's kind if it has one.  */
3850       if (attrs_valid)
3851         {
3852           switch (iter->domain)
3853             {
3854             case VAR_DOMAIN:
3855               if (symbol_kind != GDB_INDEX_SYMBOL_KIND_VARIABLE
3856                   && symbol_kind != GDB_INDEX_SYMBOL_KIND_FUNCTION
3857                   /* Some types are also in VAR_DOMAIN.  */
3858                   && symbol_kind != GDB_INDEX_SYMBOL_KIND_TYPE)
3859                 continue;
3860               break;
3861             case STRUCT_DOMAIN:
3862               if (symbol_kind != GDB_INDEX_SYMBOL_KIND_TYPE)
3863                 continue;
3864               break;
3865             case LABEL_DOMAIN:
3866               if (symbol_kind != GDB_INDEX_SYMBOL_KIND_OTHER)
3867                 continue;
3868               break;
3869             default:
3870               break;
3871             }
3872         }
3873
3874       ++iter->next;
3875       return per_cu;
3876     }
3877
3878   return NULL;
3879 }
3880
3881 static struct compunit_symtab *
3882 dw2_lookup_symbol (struct objfile *objfile, int block_index,
3883                    const char *name, domain_enum domain)
3884 {
3885   struct compunit_symtab *stab_best = NULL;
3886   struct mapped_index *index;
3887
3888   dw2_setup (objfile);
3889
3890   index = dwarf2_per_objfile->index_table;
3891
3892   /* index is NULL if OBJF_READNOW.  */
3893   if (index)
3894     {
3895       struct dw2_symtab_iterator iter;
3896       struct dwarf2_per_cu_data *per_cu;
3897
3898       dw2_symtab_iter_init (&iter, index, 1, block_index, domain, name);
3899
3900       while ((per_cu = dw2_symtab_iter_next (&iter)) != NULL)
3901         {
3902           struct symbol *sym, *with_opaque = NULL;
3903           struct compunit_symtab *stab = dw2_instantiate_symtab (per_cu);
3904           const struct blockvector *bv = COMPUNIT_BLOCKVECTOR (stab);
3905           struct block *block = BLOCKVECTOR_BLOCK (bv, block_index);
3906
3907           sym = block_find_symbol (block, name, domain,
3908                                    block_find_non_opaque_type_preferred,
3909                                    &with_opaque);
3910
3911           /* Some caution must be observed with overloaded functions
3912              and methods, since the index will not contain any overload
3913              information (but NAME might contain it).  */
3914
3915           if (sym != NULL
3916               && SYMBOL_MATCHES_SEARCH_NAME (sym, name))
3917             return stab;
3918           if (with_opaque != NULL
3919               && SYMBOL_MATCHES_SEARCH_NAME (with_opaque, name))
3920             stab_best = stab;
3921
3922           /* Keep looking through other CUs.  */
3923         }
3924     }
3925
3926   return stab_best;
3927 }
3928
3929 static void
3930 dw2_print_stats (struct objfile *objfile)
3931 {
3932   int i, total, count;
3933
3934   dw2_setup (objfile);
3935   total = dwarf2_per_objfile->n_comp_units + dwarf2_per_objfile->n_type_units;
3936   count = 0;
3937   for (i = 0; i < total; ++i)
3938     {
3939       struct dwarf2_per_cu_data *per_cu = dw2_get_cutu (i);
3940
3941       if (!per_cu->v.quick->compunit_symtab)
3942         ++count;
3943     }
3944   printf_filtered (_("  Number of read CUs: %d\n"), total - count);
3945   printf_filtered (_("  Number of unread CUs: %d\n"), count);
3946 }
3947
3948 /* This dumps minimal information about the index.
3949    It is called via "mt print objfiles".
3950    One use is to verify .gdb_index has been loaded by the
3951    gdb.dwarf2/gdb-index.exp testcase.  */
3952
3953 static void
3954 dw2_dump (struct objfile *objfile)
3955 {
3956   dw2_setup (objfile);
3957   gdb_assert (dwarf2_per_objfile->using_index);
3958   printf_filtered (".gdb_index:");
3959   if (dwarf2_per_objfile->index_table != NULL)
3960     {
3961       printf_filtered (" version %d\n",
3962                        dwarf2_per_objfile->index_table->version);
3963     }
3964   else
3965     printf_filtered (" faked for \"readnow\"\n");
3966   printf_filtered ("\n");
3967 }
3968
3969 static void
3970 dw2_relocate (struct objfile *objfile,
3971               const struct section_offsets *new_offsets,
3972               const struct section_offsets *delta)
3973 {
3974   /* There's nothing to relocate here.  */
3975 }
3976
3977 static void
3978 dw2_expand_symtabs_for_function (struct objfile *objfile,
3979                                  const char *func_name)
3980 {
3981   struct mapped_index *index;
3982
3983   dw2_setup (objfile);
3984
3985   index = dwarf2_per_objfile->index_table;
3986
3987   /* index is NULL if OBJF_READNOW.  */
3988   if (index)
3989     {
3990       struct dw2_symtab_iterator iter;
3991       struct dwarf2_per_cu_data *per_cu;
3992
3993       /* Note: It doesn't matter what we pass for block_index here.  */
3994       dw2_symtab_iter_init (&iter, index, 0, GLOBAL_BLOCK, VAR_DOMAIN,
3995                             func_name);
3996
3997       while ((per_cu = dw2_symtab_iter_next (&iter)) != NULL)
3998         dw2_instantiate_symtab (per_cu);
3999     }
4000 }
4001
4002 static void
4003 dw2_expand_all_symtabs (struct objfile *objfile)
4004 {
4005   int i;
4006
4007   dw2_setup (objfile);
4008
4009   for (i = 0; i < (dwarf2_per_objfile->n_comp_units
4010                    + dwarf2_per_objfile->n_type_units); ++i)
4011     {
4012       struct dwarf2_per_cu_data *per_cu = dw2_get_cutu (i);
4013
4014       dw2_instantiate_symtab (per_cu);
4015     }
4016 }
4017
4018 static void
4019 dw2_expand_symtabs_with_fullname (struct objfile *objfile,
4020                                   const char *fullname)
4021 {
4022   int i;
4023
4024   dw2_setup (objfile);
4025
4026   /* We don't need to consider type units here.
4027      This is only called for examining code, e.g. expand_line_sal.
4028      There can be an order of magnitude (or more) more type units
4029      than comp units, and we avoid them if we can.  */
4030
4031   for (i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
4032     {
4033       int j;
4034       struct dwarf2_per_cu_data *per_cu = dw2_get_cutu (i);
4035       struct quick_file_names *file_data;
4036
4037       /* We only need to look at symtabs not already expanded.  */
4038       if (per_cu->v.quick->compunit_symtab)
4039         continue;
4040
4041       file_data = dw2_get_file_names (per_cu);
4042       if (file_data == NULL)
4043         continue;
4044
4045       for (j = 0; j < file_data->num_file_names; ++j)
4046         {
4047           const char *this_fullname = file_data->file_names[j];
4048
4049           if (filename_cmp (this_fullname, fullname) == 0)
4050             {
4051               dw2_instantiate_symtab (per_cu);
4052               break;
4053             }
4054         }
4055     }
4056 }
4057
4058 static void
4059 dw2_map_matching_symbols (struct objfile *objfile,
4060                           const char * name, domain_enum domain,
4061                           int global,
4062                           int (*callback) (struct block *,
4063                                            struct symbol *, void *),
4064                           void *data, symbol_compare_ftype *match,
4065                           symbol_compare_ftype *ordered_compare)
4066 {
4067   /* Currently unimplemented; used for Ada.  The function can be called if the
4068      current language is Ada for a non-Ada objfile using GNU index.  As Ada
4069      does not look for non-Ada symbols this function should just return.  */
4070 }
4071
4072 static void
4073 dw2_expand_symtabs_matching
4074   (struct objfile *objfile,
4075    gdb::function_view<expand_symtabs_file_matcher_ftype> file_matcher,
4076    gdb::function_view<expand_symtabs_symbol_matcher_ftype> symbol_matcher,
4077    gdb::function_view<expand_symtabs_exp_notify_ftype> expansion_notify,
4078    enum search_domain kind)
4079 {
4080   int i;
4081   offset_type iter;
4082   struct mapped_index *index;
4083
4084   dw2_setup (objfile);
4085
4086   /* index_table is NULL if OBJF_READNOW.  */
4087   if (!dwarf2_per_objfile->index_table)
4088     return;
4089   index = dwarf2_per_objfile->index_table;
4090
4091   if (file_matcher != NULL)
4092     {
4093       htab_up visited_found (htab_create_alloc (10, htab_hash_pointer,
4094                                                 htab_eq_pointer,
4095                                                 NULL, xcalloc, xfree));
4096       htab_up visited_not_found (htab_create_alloc (10, htab_hash_pointer,
4097                                                     htab_eq_pointer,
4098                                                     NULL, xcalloc, xfree));
4099
4100       /* The rule is CUs specify all the files, including those used by
4101          any TU, so there's no need to scan TUs here.  */
4102
4103       for (i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
4104         {
4105           int j;
4106           struct dwarf2_per_cu_data *per_cu = dw2_get_cu (i);
4107           struct quick_file_names *file_data;
4108           void **slot;
4109
4110           QUIT;
4111
4112           per_cu->v.quick->mark = 0;
4113
4114           /* We only need to look at symtabs not already expanded.  */
4115           if (per_cu->v.quick->compunit_symtab)
4116             continue;
4117
4118           file_data = dw2_get_file_names (per_cu);
4119           if (file_data == NULL)
4120             continue;
4121
4122           if (htab_find (visited_not_found.get (), file_data) != NULL)
4123             continue;
4124           else if (htab_find (visited_found.get (), file_data) != NULL)
4125             {
4126               per_cu->v.quick->mark = 1;
4127               continue;
4128             }
4129
4130           for (j = 0; j < file_data->num_file_names; ++j)
4131             {
4132               const char *this_real_name;
4133
4134               if (file_matcher (file_data->file_names[j], false))
4135                 {
4136                   per_cu->v.quick->mark = 1;
4137                   break;
4138                 }
4139
4140               /* Before we invoke realpath, which can get expensive when many
4141                  files are involved, do a quick comparison of the basenames.  */
4142               if (!basenames_may_differ
4143                   && !file_matcher (lbasename (file_data->file_names[j]),
4144                                     true))
4145                 continue;
4146
4147               this_real_name = dw2_get_real_path (objfile, file_data, j);
4148               if (file_matcher (this_real_name, false))
4149                 {
4150                   per_cu->v.quick->mark = 1;
4151                   break;
4152                 }
4153             }
4154
4155           slot = htab_find_slot (per_cu->v.quick->mark
4156                                  ? visited_found.get ()
4157                                  : visited_not_found.get (),
4158                                  file_data, INSERT);
4159           *slot = file_data;
4160         }
4161     }
4162
4163   for (iter = 0; iter < index->symbol_table_slots; ++iter)
4164     {
4165       offset_type idx = 2 * iter;
4166       const char *name;
4167       offset_type *vec, vec_len, vec_idx;
4168       int global_seen = 0;
4169
4170       QUIT;
4171
4172       if (index->symbol_table[idx] == 0 && index->symbol_table[idx + 1] == 0)
4173         continue;
4174
4175       name = index->constant_pool + MAYBE_SWAP (index->symbol_table[idx]);
4176
4177       if (!symbol_matcher (name))
4178         continue;
4179
4180       /* The name was matched, now expand corresponding CUs that were
4181          marked.  */
4182       vec = (offset_type *) (index->constant_pool
4183                              + MAYBE_SWAP (index->symbol_table[idx + 1]));
4184       vec_len = MAYBE_SWAP (vec[0]);
4185       for (vec_idx = 0; vec_idx < vec_len; ++vec_idx)
4186         {
4187           struct dwarf2_per_cu_data *per_cu;
4188           offset_type cu_index_and_attrs = MAYBE_SWAP (vec[vec_idx + 1]);
4189           /* This value is only valid for index versions >= 7.  */
4190           int is_static = GDB_INDEX_SYMBOL_STATIC_VALUE (cu_index_and_attrs);
4191           gdb_index_symbol_kind symbol_kind =
4192             GDB_INDEX_SYMBOL_KIND_VALUE (cu_index_and_attrs);
4193           int cu_index = GDB_INDEX_CU_VALUE (cu_index_and_attrs);
4194           /* Only check the symbol attributes if they're present.
4195              Indices prior to version 7 don't record them,
4196              and indices >= 7 may elide them for certain symbols
4197              (gold does this).  */
4198           int attrs_valid =
4199             (index->version >= 7
4200              && symbol_kind != GDB_INDEX_SYMBOL_KIND_NONE);
4201
4202           /* Work around gold/15646.  */
4203           if (attrs_valid)
4204             {
4205               if (!is_static && global_seen)
4206                 continue;
4207               if (!is_static)
4208                 global_seen = 1;
4209             }
4210
4211           /* Only check the symbol's kind if it has one.  */
4212           if (attrs_valid)
4213             {
4214               switch (kind)
4215                 {
4216                 case VARIABLES_DOMAIN:
4217                   if (symbol_kind != GDB_INDEX_SYMBOL_KIND_VARIABLE)
4218                     continue;
4219                   break;
4220                 case FUNCTIONS_DOMAIN:
4221                   if (symbol_kind != GDB_INDEX_SYMBOL_KIND_FUNCTION)
4222                     continue;
4223                   break;
4224                 case TYPES_DOMAIN:
4225                   if (symbol_kind != GDB_INDEX_SYMBOL_KIND_TYPE)
4226                     continue;
4227                   break;
4228                 default:
4229                   break;
4230                 }
4231             }
4232
4233           /* Don't crash on bad data.  */
4234           if (cu_index >= (dwarf2_per_objfile->n_comp_units
4235                            + dwarf2_per_objfile->n_type_units))
4236             {
4237               complaint (&symfile_complaints,
4238                          _(".gdb_index entry has bad CU index"
4239                            " [in module %s]"), objfile_name (objfile));
4240               continue;
4241             }
4242
4243           per_cu = dw2_get_cutu (cu_index);
4244           if (file_matcher == NULL || per_cu->v.quick->mark)
4245             {
4246               int symtab_was_null =
4247                 (per_cu->v.quick->compunit_symtab == NULL);
4248
4249               dw2_instantiate_symtab (per_cu);
4250
4251               if (expansion_notify != NULL
4252                   && symtab_was_null
4253                   && per_cu->v.quick->compunit_symtab != NULL)
4254                 {
4255                   expansion_notify (per_cu->v.quick->compunit_symtab);
4256                 }
4257             }
4258         }
4259     }
4260 }
4261
4262 /* A helper for dw2_find_pc_sect_compunit_symtab which finds the most specific
4263    symtab.  */
4264
4265 static struct compunit_symtab *
4266 recursively_find_pc_sect_compunit_symtab (struct compunit_symtab *cust,
4267                                           CORE_ADDR pc)
4268 {
4269   int i;
4270
4271   if (COMPUNIT_BLOCKVECTOR (cust) != NULL
4272       && blockvector_contains_pc (COMPUNIT_BLOCKVECTOR (cust), pc))
4273     return cust;
4274
4275   if (cust->includes == NULL)
4276     return NULL;
4277
4278   for (i = 0; cust->includes[i]; ++i)
4279     {
4280       struct compunit_symtab *s = cust->includes[i];
4281
4282       s = recursively_find_pc_sect_compunit_symtab (s, pc);
4283       if (s != NULL)
4284         return s;
4285     }
4286
4287   return NULL;
4288 }
4289
4290 static struct compunit_symtab *
4291 dw2_find_pc_sect_compunit_symtab (struct objfile *objfile,
4292                                   struct bound_minimal_symbol msymbol,
4293                                   CORE_ADDR pc,
4294                                   struct obj_section *section,
4295                                   int warn_if_readin)
4296 {
4297   struct dwarf2_per_cu_data *data;
4298   struct compunit_symtab *result;
4299
4300   dw2_setup (objfile);
4301
4302   if (!objfile->psymtabs_addrmap)
4303     return NULL;
4304
4305   data = (struct dwarf2_per_cu_data *) addrmap_find (objfile->psymtabs_addrmap,
4306                                                      pc);
4307   if (!data)
4308     return NULL;
4309
4310   if (warn_if_readin && data->v.quick->compunit_symtab)
4311     warning (_("(Internal error: pc %s in read in CU, but not in symtab.)"),
4312              paddress (get_objfile_arch (objfile), pc));
4313
4314   result
4315     = recursively_find_pc_sect_compunit_symtab (dw2_instantiate_symtab (data),
4316                                                 pc);
4317   gdb_assert (result != NULL);
4318   return result;
4319 }
4320
4321 static void
4322 dw2_map_symbol_filenames (struct objfile *objfile, symbol_filename_ftype *fun,
4323                           void *data, int need_fullname)
4324 {
4325   dw2_setup (objfile);
4326
4327   if (!dwarf2_per_objfile->filenames_cache)
4328     {
4329       dwarf2_per_objfile->filenames_cache.emplace ();
4330
4331       htab_up visited (htab_create_alloc (10,
4332                                           htab_hash_pointer, htab_eq_pointer,
4333                                           NULL, xcalloc, xfree));
4334
4335       /* The rule is CUs specify all the files, including those used
4336          by any TU, so there's no need to scan TUs here.  We can
4337          ignore file names coming from already-expanded CUs.  */
4338
4339       for (int i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
4340         {
4341           struct dwarf2_per_cu_data *per_cu = dw2_get_cutu (i);
4342
4343           if (per_cu->v.quick->compunit_symtab)
4344             {
4345               void **slot = htab_find_slot (visited.get (),
4346                                             per_cu->v.quick->file_names,
4347                                             INSERT);
4348
4349               *slot = per_cu->v.quick->file_names;
4350             }
4351         }
4352
4353       for (int i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
4354         {
4355           int j;
4356           struct dwarf2_per_cu_data *per_cu = dw2_get_cu (i);
4357           struct quick_file_names *file_data;
4358           void **slot;
4359
4360           /* We only need to look at symtabs not already expanded.  */
4361           if (per_cu->v.quick->compunit_symtab)
4362             continue;
4363
4364           file_data = dw2_get_file_names (per_cu);
4365           if (file_data == NULL)
4366             continue;
4367
4368           slot = htab_find_slot (visited.get (), file_data, INSERT);
4369           if (*slot)
4370             {
4371               /* Already visited.  */
4372               continue;
4373             }
4374           *slot = file_data;
4375
4376           for (int j = 0; j < file_data->num_file_names; ++j)
4377             {
4378               const char *filename = file_data->file_names[j];
4379               dwarf2_per_objfile->filenames_cache->seen (filename);
4380             }
4381         }
4382     }
4383
4384   dwarf2_per_objfile->filenames_cache->traverse ([&] (const char *filename)
4385     {
4386       gdb::unique_xmalloc_ptr<char> this_real_name;
4387
4388       if (need_fullname)
4389         this_real_name = gdb_realpath (filename);
4390       (*fun) (filename, this_real_name.get (), data);
4391     });
4392 }
4393
4394 static int
4395 dw2_has_symbols (struct objfile *objfile)
4396 {
4397   return 1;
4398 }
4399
4400 const struct quick_symbol_functions dwarf2_gdb_index_functions =
4401 {
4402   dw2_has_symbols,
4403   dw2_find_last_source_symtab,
4404   dw2_forget_cached_source_info,
4405   dw2_map_symtabs_matching_filename,
4406   dw2_lookup_symbol,
4407   dw2_print_stats,
4408   dw2_dump,
4409   dw2_relocate,
4410   dw2_expand_symtabs_for_function,
4411   dw2_expand_all_symtabs,
4412   dw2_expand_symtabs_with_fullname,
4413   dw2_map_matching_symbols,
4414   dw2_expand_symtabs_matching,
4415   dw2_find_pc_sect_compunit_symtab,
4416   dw2_map_symbol_filenames
4417 };
4418
4419 /* Initialize for reading DWARF for this objfile.  Return 0 if this
4420    file will use psymtabs, or 1 if using the GNU index.  */
4421
4422 int
4423 dwarf2_initialize_objfile (struct objfile *objfile)
4424 {
4425   /* If we're about to read full symbols, don't bother with the
4426      indices.  In this case we also don't care if some other debug
4427      format is making psymtabs, because they are all about to be
4428      expanded anyway.  */
4429   if ((objfile->flags & OBJF_READNOW))
4430     {
4431       int i;
4432
4433       dwarf2_per_objfile->using_index = 1;
4434       create_all_comp_units (objfile);
4435       create_all_type_units (objfile);
4436       dwarf2_per_objfile->quick_file_names_table =
4437         create_quick_file_names_table (dwarf2_per_objfile->n_comp_units);
4438
4439       for (i = 0; i < (dwarf2_per_objfile->n_comp_units
4440                        + dwarf2_per_objfile->n_type_units); ++i)
4441         {
4442           struct dwarf2_per_cu_data *per_cu = dw2_get_cutu (i);
4443
4444           per_cu->v.quick = OBSTACK_ZALLOC (&objfile->objfile_obstack,
4445                                             struct dwarf2_per_cu_quick_data);
4446         }
4447
4448       /* Return 1 so that gdb sees the "quick" functions.  However,
4449          these functions will be no-ops because we will have expanded
4450          all symtabs.  */
4451       return 1;
4452     }
4453
4454   if (dwarf2_read_index (objfile))
4455     return 1;
4456
4457   return 0;
4458 }
4459
4460 \f
4461
4462 /* Build a partial symbol table.  */
4463
4464 void
4465 dwarf2_build_psymtabs (struct objfile *objfile)
4466 {
4467
4468   if (objfile->global_psymbols.size == 0 && objfile->static_psymbols.size == 0)
4469     {
4470       init_psymbol_list (objfile, 1024);
4471     }
4472
4473   TRY
4474     {
4475       /* This isn't really ideal: all the data we allocate on the
4476          objfile's obstack is still uselessly kept around.  However,
4477          freeing it seems unsafe.  */
4478       psymtab_discarder psymtabs (objfile);
4479       dwarf2_build_psymtabs_hard (objfile);
4480       psymtabs.keep ();
4481     }
4482   CATCH (except, RETURN_MASK_ERROR)
4483     {
4484       exception_print (gdb_stderr, except);
4485     }
4486   END_CATCH
4487 }
4488
4489 /* Return the total length of the CU described by HEADER.  */
4490
4491 static unsigned int
4492 get_cu_length (const struct comp_unit_head *header)
4493 {
4494   return header->initial_length_size + header->length;
4495 }
4496
4497 /* Return TRUE if SECT_OFF is within CU_HEADER.  */
4498
4499 static inline bool
4500 offset_in_cu_p (const comp_unit_head *cu_header, sect_offset sect_off)
4501 {
4502   sect_offset bottom = cu_header->sect_off;
4503   sect_offset top = cu_header->sect_off + get_cu_length (cu_header);
4504
4505   return sect_off >= bottom && sect_off < top;
4506 }
4507
4508 /* Find the base address of the compilation unit for range lists and
4509    location lists.  It will normally be specified by DW_AT_low_pc.
4510    In DWARF-3 draft 4, the base address could be overridden by
4511    DW_AT_entry_pc.  It's been removed, but GCC still uses this for
4512    compilation units with discontinuous ranges.  */
4513
4514 static void
4515 dwarf2_find_base_address (struct die_info *die, struct dwarf2_cu *cu)
4516 {
4517   struct attribute *attr;
4518
4519   cu->base_known = 0;
4520   cu->base_address = 0;
4521
4522   attr = dwarf2_attr (die, DW_AT_entry_pc, cu);
4523   if (attr)
4524     {
4525       cu->base_address = attr_value_as_address (attr);
4526       cu->base_known = 1;
4527     }
4528   else
4529     {
4530       attr = dwarf2_attr (die, DW_AT_low_pc, cu);
4531       if (attr)
4532         {
4533           cu->base_address = attr_value_as_address (attr);
4534           cu->base_known = 1;
4535         }
4536     }
4537 }
4538
4539 /* Read in the comp unit header information from the debug_info at info_ptr.
4540    Use rcuh_kind::COMPILE as the default type if not known by the caller.
4541    NOTE: This leaves members offset, first_die_offset to be filled in
4542    by the caller.  */
4543
4544 static const gdb_byte *
4545 read_comp_unit_head (struct comp_unit_head *cu_header,
4546                      const gdb_byte *info_ptr,
4547                      struct dwarf2_section_info *section,
4548                      rcuh_kind section_kind)
4549 {
4550   int signed_addr;
4551   unsigned int bytes_read;
4552   const char *filename = get_section_file_name (section);
4553   bfd *abfd = get_section_bfd_owner (section);
4554
4555   cu_header->length = read_initial_length (abfd, info_ptr, &bytes_read);
4556   cu_header->initial_length_size = bytes_read;
4557   cu_header->offset_size = (bytes_read == 4) ? 4 : 8;
4558   info_ptr += bytes_read;
4559   cu_header->version = read_2_bytes (abfd, info_ptr);
4560   info_ptr += 2;
4561   if (cu_header->version < 5)
4562     switch (section_kind)
4563       {
4564       case rcuh_kind::COMPILE:
4565         cu_header->unit_type = DW_UT_compile;
4566         break;
4567       case rcuh_kind::TYPE:
4568         cu_header->unit_type = DW_UT_type;
4569         break;
4570       default:
4571         internal_error (__FILE__, __LINE__,
4572                         _("read_comp_unit_head: invalid section_kind"));
4573       }
4574   else
4575     {
4576       cu_header->unit_type = static_cast<enum dwarf_unit_type>
4577                                                  (read_1_byte (abfd, info_ptr));
4578       info_ptr += 1;
4579       switch (cu_header->unit_type)
4580         {
4581         case DW_UT_compile:
4582           if (section_kind != rcuh_kind::COMPILE)
4583             error (_("Dwarf Error: wrong unit_type in compilation unit header "
4584                    "(is DW_UT_compile, should be DW_UT_type) [in module %s]"),
4585                    filename);
4586           break;
4587         case DW_UT_type:
4588           section_kind = rcuh_kind::TYPE;
4589           break;
4590         default:
4591           error (_("Dwarf Error: wrong unit_type in compilation unit header "
4592                  "(is %d, should be %d or %d) [in module %s]"),
4593                  cu_header->unit_type, DW_UT_compile, DW_UT_type, filename);
4594         }
4595
4596       cu_header->addr_size = read_1_byte (abfd, info_ptr);
4597       info_ptr += 1;
4598     }
4599   cu_header->abbrev_sect_off = (sect_offset) read_offset (abfd, info_ptr,
4600                                                           cu_header,
4601                                                           &bytes_read);
4602   info_ptr += bytes_read;
4603   if (cu_header->version < 5)
4604     {
4605       cu_header->addr_size = read_1_byte (abfd, info_ptr);
4606       info_ptr += 1;
4607     }
4608   signed_addr = bfd_get_sign_extend_vma (abfd);
4609   if (signed_addr < 0)
4610     internal_error (__FILE__, __LINE__,
4611                     _("read_comp_unit_head: dwarf from non elf file"));
4612   cu_header->signed_addr_p = signed_addr;
4613
4614   if (section_kind == rcuh_kind::TYPE)
4615     {
4616       LONGEST type_offset;
4617
4618       cu_header->signature = read_8_bytes (abfd, info_ptr);
4619       info_ptr += 8;
4620
4621       type_offset = read_offset (abfd, info_ptr, cu_header, &bytes_read);
4622       info_ptr += bytes_read;
4623       cu_header->type_cu_offset_in_tu = (cu_offset) type_offset;
4624       if (to_underlying (cu_header->type_cu_offset_in_tu) != type_offset)
4625         error (_("Dwarf Error: Too big type_offset in compilation unit "
4626                "header (is %s) [in module %s]"), plongest (type_offset),
4627                filename);
4628     }
4629
4630   return info_ptr;
4631 }
4632
4633 /* Helper function that returns the proper abbrev section for
4634    THIS_CU.  */
4635
4636 static struct dwarf2_section_info *
4637 get_abbrev_section_for_cu (struct dwarf2_per_cu_data *this_cu)
4638 {
4639   struct dwarf2_section_info *abbrev;
4640
4641   if (this_cu->is_dwz)
4642     abbrev = &dwarf2_get_dwz_file ()->abbrev;
4643   else
4644     abbrev = &dwarf2_per_objfile->abbrev;
4645
4646   return abbrev;
4647 }
4648
4649 /* Subroutine of read_and_check_comp_unit_head and
4650    read_and_check_type_unit_head to simplify them.
4651    Perform various error checking on the header.  */
4652
4653 static void
4654 error_check_comp_unit_head (struct comp_unit_head *header,
4655                             struct dwarf2_section_info *section,
4656                             struct dwarf2_section_info *abbrev_section)
4657 {
4658   const char *filename = get_section_file_name (section);
4659
4660   if (header->version < 2 || header->version > 5)
4661     error (_("Dwarf Error: wrong version in compilation unit header "
4662            "(is %d, should be 2, 3, 4 or 5) [in module %s]"), header->version,
4663            filename);
4664
4665   if (to_underlying (header->abbrev_sect_off)
4666       >= dwarf2_section_size (dwarf2_per_objfile->objfile, abbrev_section))
4667     error (_("Dwarf Error: bad offset (0x%x) in compilation unit header "
4668            "(offset 0x%x + 6) [in module %s]"),
4669            to_underlying (header->abbrev_sect_off),
4670            to_underlying (header->sect_off),
4671            filename);
4672
4673   /* Cast to ULONGEST to use 64-bit arithmetic when possible to
4674      avoid potential 32-bit overflow.  */
4675   if (((ULONGEST) header->sect_off + get_cu_length (header))
4676       > section->size)
4677     error (_("Dwarf Error: bad length (0x%x) in compilation unit header "
4678            "(offset 0x%x + 0) [in module %s]"),
4679            header->length, to_underlying (header->sect_off),
4680            filename);
4681 }
4682
4683 /* Read in a CU/TU header and perform some basic error checking.
4684    The contents of the header are stored in HEADER.
4685    The result is a pointer to the start of the first DIE.  */
4686
4687 static const gdb_byte *
4688 read_and_check_comp_unit_head (struct comp_unit_head *header,
4689                                struct dwarf2_section_info *section,
4690                                struct dwarf2_section_info *abbrev_section,
4691                                const gdb_byte *info_ptr,
4692                                rcuh_kind section_kind)
4693 {
4694   const gdb_byte *beg_of_comp_unit = info_ptr;
4695   bfd *abfd = get_section_bfd_owner (section);
4696
4697   header->sect_off = (sect_offset) (beg_of_comp_unit - section->buffer);
4698
4699   info_ptr = read_comp_unit_head (header, info_ptr, section, section_kind);
4700
4701   header->first_die_cu_offset = (cu_offset) (info_ptr - beg_of_comp_unit);
4702
4703   error_check_comp_unit_head (header, section, abbrev_section);
4704
4705   return info_ptr;
4706 }
4707
4708 /* Fetch the abbreviation table offset from a comp or type unit header.  */
4709
4710 static sect_offset
4711 read_abbrev_offset (struct dwarf2_section_info *section,
4712                     sect_offset sect_off)
4713 {
4714   bfd *abfd = get_section_bfd_owner (section);
4715   const gdb_byte *info_ptr;
4716   unsigned int initial_length_size, offset_size;
4717   uint16_t version;
4718
4719   dwarf2_read_section (dwarf2_per_objfile->objfile, section);
4720   info_ptr = section->buffer + to_underlying (sect_off);
4721   read_initial_length (abfd, info_ptr, &initial_length_size);
4722   offset_size = initial_length_size == 4 ? 4 : 8;
4723   info_ptr += initial_length_size;
4724
4725   version = read_2_bytes (abfd, info_ptr);
4726   info_ptr += 2;
4727   if (version >= 5)
4728     {
4729       /* Skip unit type and address size.  */
4730       info_ptr += 2;
4731     }
4732
4733   return (sect_offset) read_offset_1 (abfd, info_ptr, offset_size);
4734 }
4735
4736 /* Allocate a new partial symtab for file named NAME and mark this new
4737    partial symtab as being an include of PST.  */
4738
4739 static void
4740 dwarf2_create_include_psymtab (const char *name, struct partial_symtab *pst,
4741                                struct objfile *objfile)
4742 {
4743   struct partial_symtab *subpst = allocate_psymtab (name, objfile);
4744
4745   if (!IS_ABSOLUTE_PATH (subpst->filename))
4746     {
4747       /* It shares objfile->objfile_obstack.  */
4748       subpst->dirname = pst->dirname;
4749     }
4750
4751   subpst->textlow = 0;
4752   subpst->texthigh = 0;
4753
4754   subpst->dependencies
4755     = XOBNEW (&objfile->objfile_obstack, struct partial_symtab *);
4756   subpst->dependencies[0] = pst;
4757   subpst->number_of_dependencies = 1;
4758
4759   subpst->globals_offset = 0;
4760   subpst->n_global_syms = 0;
4761   subpst->statics_offset = 0;
4762   subpst->n_static_syms = 0;
4763   subpst->compunit_symtab = NULL;
4764   subpst->read_symtab = pst->read_symtab;
4765   subpst->readin = 0;
4766
4767   /* No private part is necessary for include psymtabs.  This property
4768      can be used to differentiate between such include psymtabs and
4769      the regular ones.  */
4770   subpst->read_symtab_private = NULL;
4771 }
4772
4773 /* Read the Line Number Program data and extract the list of files
4774    included by the source file represented by PST.  Build an include
4775    partial symtab for each of these included files.  */
4776
4777 static void
4778 dwarf2_build_include_psymtabs (struct dwarf2_cu *cu,
4779                                struct die_info *die,
4780                                struct partial_symtab *pst)
4781 {
4782   line_header_up lh;
4783   struct attribute *attr;
4784
4785   attr = dwarf2_attr (die, DW_AT_stmt_list, cu);
4786   if (attr)
4787     lh = dwarf_decode_line_header ((sect_offset) DW_UNSND (attr), cu);
4788   if (lh == NULL)
4789     return;  /* No linetable, so no includes.  */
4790
4791   /* NOTE: pst->dirname is DW_AT_comp_dir (if present).  */
4792   dwarf_decode_lines (lh.get (), pst->dirname, cu, pst, pst->textlow, 1);
4793 }
4794
4795 static hashval_t
4796 hash_signatured_type (const void *item)
4797 {
4798   const struct signatured_type *sig_type
4799     = (const struct signatured_type *) item;
4800
4801   /* This drops the top 32 bits of the signature, but is ok for a hash.  */
4802   return sig_type->signature;
4803 }
4804
4805 static int
4806 eq_signatured_type (const void *item_lhs, const void *item_rhs)
4807 {
4808   const struct signatured_type *lhs = (const struct signatured_type *) item_lhs;
4809   const struct signatured_type *rhs = (const struct signatured_type *) item_rhs;
4810
4811   return lhs->signature == rhs->signature;
4812 }
4813
4814 /* Allocate a hash table for signatured types.  */
4815
4816 static htab_t
4817 allocate_signatured_type_table (struct objfile *objfile)
4818 {
4819   return htab_create_alloc_ex (41,
4820                                hash_signatured_type,
4821                                eq_signatured_type,
4822                                NULL,
4823                                &objfile->objfile_obstack,
4824                                hashtab_obstack_allocate,
4825                                dummy_obstack_deallocate);
4826 }
4827
4828 /* A helper function to add a signatured type CU to a table.  */
4829
4830 static int
4831 add_signatured_type_cu_to_table (void **slot, void *datum)
4832 {
4833   struct signatured_type *sigt = (struct signatured_type *) *slot;
4834   struct signatured_type ***datap = (struct signatured_type ***) datum;
4835
4836   **datap = sigt;
4837   ++*datap;
4838
4839   return 1;
4840 }
4841
4842 /* A helper for create_debug_types_hash_table.  Read types from SECTION
4843    and fill them into TYPES_HTAB.  It will process only type units,
4844    therefore DW_UT_type.  */
4845
4846 static void
4847 create_debug_type_hash_table (struct dwo_file *dwo_file,
4848                               dwarf2_section_info *section, htab_t &types_htab,
4849                               rcuh_kind section_kind)
4850 {
4851   struct objfile *objfile = dwarf2_per_objfile->objfile;
4852   struct dwarf2_section_info *abbrev_section;
4853   bfd *abfd;
4854   const gdb_byte *info_ptr, *end_ptr;
4855
4856   abbrev_section = (dwo_file != NULL
4857                     ? &dwo_file->sections.abbrev
4858                     : &dwarf2_per_objfile->abbrev);
4859
4860   if (dwarf_read_debug)
4861     fprintf_unfiltered (gdb_stdlog, "Reading %s for %s:\n",
4862                         get_section_name (section),
4863                         get_section_file_name (abbrev_section));
4864
4865   dwarf2_read_section (objfile, section);
4866   info_ptr = section->buffer;
4867
4868   if (info_ptr == NULL)
4869     return;
4870
4871   /* We can't set abfd until now because the section may be empty or
4872      not present, in which case the bfd is unknown.  */
4873   abfd = get_section_bfd_owner (section);
4874
4875   /* We don't use init_cutu_and_read_dies_simple, or some such, here
4876      because we don't need to read any dies: the signature is in the
4877      header.  */
4878
4879   end_ptr = info_ptr + section->size;
4880   while (info_ptr < end_ptr)
4881     {
4882       struct signatured_type *sig_type;
4883       struct dwo_unit *dwo_tu;
4884       void **slot;
4885       const gdb_byte *ptr = info_ptr;
4886       struct comp_unit_head header;
4887       unsigned int length;
4888
4889       sect_offset sect_off = (sect_offset) (ptr - section->buffer);
4890
4891       /* Initialize it due to a false compiler warning.  */
4892       header.signature = -1;
4893       header.type_cu_offset_in_tu = (cu_offset) -1;
4894
4895       /* We need to read the type's signature in order to build the hash
4896          table, but we don't need anything else just yet.  */
4897
4898       ptr = read_and_check_comp_unit_head (&header, section,
4899                                            abbrev_section, ptr, section_kind);
4900
4901       length = get_cu_length (&header);
4902
4903       /* Skip dummy type units.  */
4904       if (ptr >= info_ptr + length
4905           || peek_abbrev_code (abfd, ptr) == 0
4906           || header.unit_type != DW_UT_type)
4907         {
4908           info_ptr += length;
4909           continue;
4910         }
4911
4912       if (types_htab == NULL)
4913         {
4914           if (dwo_file)
4915             types_htab = allocate_dwo_unit_table (objfile);
4916           else
4917             types_htab = allocate_signatured_type_table (objfile);
4918         }
4919
4920       if (dwo_file)
4921         {
4922           sig_type = NULL;
4923           dwo_tu = OBSTACK_ZALLOC (&objfile->objfile_obstack,
4924                                    struct dwo_unit);
4925           dwo_tu->dwo_file = dwo_file;
4926           dwo_tu->signature = header.signature;
4927           dwo_tu->type_offset_in_tu = header.type_cu_offset_in_tu;
4928           dwo_tu->section = section;
4929           dwo_tu->sect_off = sect_off;
4930           dwo_tu->length = length;
4931         }
4932       else
4933         {
4934           /* N.B.: type_offset is not usable if this type uses a DWO file.
4935              The real type_offset is in the DWO file.  */
4936           dwo_tu = NULL;
4937           sig_type = OBSTACK_ZALLOC (&objfile->objfile_obstack,
4938                                      struct signatured_type);
4939           sig_type->signature = header.signature;
4940           sig_type->type_offset_in_tu = header.type_cu_offset_in_tu;
4941           sig_type->per_cu.objfile = objfile;
4942           sig_type->per_cu.is_debug_types = 1;
4943           sig_type->per_cu.section = section;
4944           sig_type->per_cu.sect_off = sect_off;
4945           sig_type->per_cu.length = length;
4946         }
4947
4948       slot = htab_find_slot (types_htab,
4949                              dwo_file ? (void*) dwo_tu : (void *) sig_type,
4950                              INSERT);
4951       gdb_assert (slot != NULL);
4952       if (*slot != NULL)
4953         {
4954           sect_offset dup_sect_off;
4955
4956           if (dwo_file)
4957             {
4958               const struct dwo_unit *dup_tu
4959                 = (const struct dwo_unit *) *slot;
4960
4961               dup_sect_off = dup_tu->sect_off;
4962             }
4963           else
4964             {
4965               const struct signatured_type *dup_tu
4966                 = (const struct signatured_type *) *slot;
4967
4968               dup_sect_off = dup_tu->per_cu.sect_off;
4969             }
4970
4971           complaint (&symfile_complaints,
4972                      _("debug type entry at offset 0x%x is duplicate to"
4973                        " the entry at offset 0x%x, signature %s"),
4974                      to_underlying (sect_off), to_underlying (dup_sect_off),
4975                      hex_string (header.signature));
4976         }
4977       *slot = dwo_file ? (void *) dwo_tu : (void *) sig_type;
4978
4979       if (dwarf_read_debug > 1)
4980         fprintf_unfiltered (gdb_stdlog, "  offset 0x%x, signature %s\n",
4981                             to_underlying (sect_off),
4982                             hex_string (header.signature));
4983
4984       info_ptr += length;
4985     }
4986 }
4987
4988 /* Create the hash table of all entries in the .debug_types
4989    (or .debug_types.dwo) section(s).
4990    If reading a DWO file, then DWO_FILE is a pointer to the DWO file object,
4991    otherwise it is NULL.
4992
4993    The result is a pointer to the hash table or NULL if there are no types.
4994
4995    Note: This function processes DWO files only, not DWP files.  */
4996
4997 static void
4998 create_debug_types_hash_table (struct dwo_file *dwo_file,
4999                                VEC (dwarf2_section_info_def) *types,
5000                                htab_t &types_htab)
5001 {
5002   int ix;
5003   struct dwarf2_section_info *section;
5004
5005   if (VEC_empty (dwarf2_section_info_def, types))
5006     return;
5007
5008   for (ix = 0;
5009        VEC_iterate (dwarf2_section_info_def, types, ix, section);
5010        ++ix)
5011     create_debug_type_hash_table (dwo_file, section, types_htab,
5012                                   rcuh_kind::TYPE);
5013 }
5014
5015 /* Create the hash table of all entries in the .debug_types section,
5016    and initialize all_type_units.
5017    The result is zero if there is an error (e.g. missing .debug_types section),
5018    otherwise non-zero.  */
5019
5020 static int
5021 create_all_type_units (struct objfile *objfile)
5022 {
5023   htab_t types_htab = NULL;
5024   struct signatured_type **iter;
5025
5026   create_debug_type_hash_table (NULL, &dwarf2_per_objfile->info, types_htab,
5027                                 rcuh_kind::COMPILE);
5028   create_debug_types_hash_table (NULL, dwarf2_per_objfile->types, types_htab);
5029   if (types_htab == NULL)
5030     {
5031       dwarf2_per_objfile->signatured_types = NULL;
5032       return 0;
5033     }
5034
5035   dwarf2_per_objfile->signatured_types = types_htab;
5036
5037   dwarf2_per_objfile->n_type_units
5038     = dwarf2_per_objfile->n_allocated_type_units
5039     = htab_elements (types_htab);
5040   dwarf2_per_objfile->all_type_units =
5041     XNEWVEC (struct signatured_type *, dwarf2_per_objfile->n_type_units);
5042   iter = &dwarf2_per_objfile->all_type_units[0];
5043   htab_traverse_noresize (types_htab, add_signatured_type_cu_to_table, &iter);
5044   gdb_assert (iter - &dwarf2_per_objfile->all_type_units[0]
5045               == dwarf2_per_objfile->n_type_units);
5046
5047   return 1;
5048 }
5049
5050 /* Add an entry for signature SIG to dwarf2_per_objfile->signatured_types.
5051    If SLOT is non-NULL, it is the entry to use in the hash table.
5052    Otherwise we find one.  */
5053
5054 static struct signatured_type *
5055 add_type_unit (ULONGEST sig, void **slot)
5056 {
5057   struct objfile *objfile = dwarf2_per_objfile->objfile;
5058   int n_type_units = dwarf2_per_objfile->n_type_units;
5059   struct signatured_type *sig_type;
5060
5061   gdb_assert (n_type_units <= dwarf2_per_objfile->n_allocated_type_units);
5062   ++n_type_units;
5063   if (n_type_units > dwarf2_per_objfile->n_allocated_type_units)
5064     {
5065       if (dwarf2_per_objfile->n_allocated_type_units == 0)
5066         dwarf2_per_objfile->n_allocated_type_units = 1;
5067       dwarf2_per_objfile->n_allocated_type_units *= 2;
5068       dwarf2_per_objfile->all_type_units
5069         = XRESIZEVEC (struct signatured_type *,
5070                       dwarf2_per_objfile->all_type_units,
5071                       dwarf2_per_objfile->n_allocated_type_units);
5072       ++dwarf2_per_objfile->tu_stats.nr_all_type_units_reallocs;
5073     }
5074   dwarf2_per_objfile->n_type_units = n_type_units;
5075
5076   sig_type = OBSTACK_ZALLOC (&objfile->objfile_obstack,
5077                              struct signatured_type);
5078   dwarf2_per_objfile->all_type_units[n_type_units - 1] = sig_type;
5079   sig_type->signature = sig;
5080   sig_type->per_cu.is_debug_types = 1;
5081   if (dwarf2_per_objfile->using_index)
5082     {
5083       sig_type->per_cu.v.quick =
5084         OBSTACK_ZALLOC (&objfile->objfile_obstack,
5085                         struct dwarf2_per_cu_quick_data);
5086     }
5087
5088   if (slot == NULL)
5089     {
5090       slot = htab_find_slot (dwarf2_per_objfile->signatured_types,
5091                              sig_type, INSERT);
5092     }
5093   gdb_assert (*slot == NULL);
5094   *slot = sig_type;
5095   /* The rest of sig_type must be filled in by the caller.  */
5096   return sig_type;
5097 }
5098
5099 /* Subroutine of lookup_dwo_signatured_type and lookup_dwp_signatured_type.
5100    Fill in SIG_ENTRY with DWO_ENTRY.  */
5101
5102 static void
5103 fill_in_sig_entry_from_dwo_entry (struct objfile *objfile,
5104                                   struct signatured_type *sig_entry,
5105                                   struct dwo_unit *dwo_entry)
5106 {
5107   /* Make sure we're not clobbering something we don't expect to.  */
5108   gdb_assert (! sig_entry->per_cu.queued);
5109   gdb_assert (sig_entry->per_cu.cu == NULL);
5110   if (dwarf2_per_objfile->using_index)
5111     {
5112       gdb_assert (sig_entry->per_cu.v.quick != NULL);
5113       gdb_assert (sig_entry->per_cu.v.quick->compunit_symtab == NULL);
5114     }
5115   else
5116       gdb_assert (sig_entry->per_cu.v.psymtab == NULL);
5117   gdb_assert (sig_entry->signature == dwo_entry->signature);
5118   gdb_assert (to_underlying (sig_entry->type_offset_in_section) == 0);
5119   gdb_assert (sig_entry->type_unit_group == NULL);
5120   gdb_assert (sig_entry->dwo_unit == NULL);
5121
5122   sig_entry->per_cu.section = dwo_entry->section;
5123   sig_entry->per_cu.sect_off = dwo_entry->sect_off;
5124   sig_entry->per_cu.length = dwo_entry->length;
5125   sig_entry->per_cu.reading_dwo_directly = 1;
5126   sig_entry->per_cu.objfile = objfile;
5127   sig_entry->type_offset_in_tu = dwo_entry->type_offset_in_tu;
5128   sig_entry->dwo_unit = dwo_entry;
5129 }
5130
5131 /* Subroutine of lookup_signatured_type.
5132    If we haven't read the TU yet, create the signatured_type data structure
5133    for a TU to be read in directly from a DWO file, bypassing the stub.
5134    This is the "Stay in DWO Optimization": When there is no DWP file and we're
5135    using .gdb_index, then when reading a CU we want to stay in the DWO file
5136    containing that CU.  Otherwise we could end up reading several other DWO
5137    files (due to comdat folding) to process the transitive closure of all the
5138    mentioned TUs, and that can be slow.  The current DWO file will have every
5139    type signature that it needs.
5140    We only do this for .gdb_index because in the psymtab case we already have
5141    to read all the DWOs to build the type unit groups.  */
5142
5143 static struct signatured_type *
5144 lookup_dwo_signatured_type (struct dwarf2_cu *cu, ULONGEST sig)
5145 {
5146   struct objfile *objfile = dwarf2_per_objfile->objfile;
5147   struct dwo_file *dwo_file;
5148   struct dwo_unit find_dwo_entry, *dwo_entry;
5149   struct signatured_type find_sig_entry, *sig_entry;
5150   void **slot;
5151
5152   gdb_assert (cu->dwo_unit && dwarf2_per_objfile->using_index);
5153
5154   /* If TU skeletons have been removed then we may not have read in any
5155      TUs yet.  */
5156   if (dwarf2_per_objfile->signatured_types == NULL)
5157     {
5158       dwarf2_per_objfile->signatured_types
5159         = allocate_signatured_type_table (objfile);
5160     }
5161
5162   /* We only ever need to read in one copy of a signatured type.
5163      Use the global signatured_types array to do our own comdat-folding
5164      of types.  If this is the first time we're reading this TU, and
5165      the TU has an entry in .gdb_index, replace the recorded data from
5166      .gdb_index with this TU.  */
5167
5168   find_sig_entry.signature = sig;
5169   slot = htab_find_slot (dwarf2_per_objfile->signatured_types,
5170                          &find_sig_entry, INSERT);
5171   sig_entry = (struct signatured_type *) *slot;
5172
5173   /* We can get here with the TU already read, *or* in the process of being
5174      read.  Don't reassign the global entry to point to this DWO if that's
5175      the case.  Also note that if the TU is already being read, it may not
5176      have come from a DWO, the program may be a mix of Fission-compiled
5177      code and non-Fission-compiled code.  */
5178
5179   /* Have we already tried to read this TU?
5180      Note: sig_entry can be NULL if the skeleton TU was removed (thus it
5181      needn't exist in the global table yet).  */
5182   if (sig_entry != NULL && sig_entry->per_cu.tu_read)
5183     return sig_entry;
5184
5185   /* Note: cu->dwo_unit is the dwo_unit that references this TU, not the
5186      dwo_unit of the TU itself.  */
5187   dwo_file = cu->dwo_unit->dwo_file;
5188
5189   /* Ok, this is the first time we're reading this TU.  */
5190   if (dwo_file->tus == NULL)
5191     return NULL;
5192   find_dwo_entry.signature = sig;
5193   dwo_entry = (struct dwo_unit *) htab_find (dwo_file->tus, &find_dwo_entry);
5194   if (dwo_entry == NULL)
5195     return NULL;
5196
5197   /* If the global table doesn't have an entry for this TU, add one.  */
5198   if (sig_entry == NULL)
5199     sig_entry = add_type_unit (sig, slot);
5200
5201   fill_in_sig_entry_from_dwo_entry (objfile, sig_entry, dwo_entry);
5202   sig_entry->per_cu.tu_read = 1;
5203   return sig_entry;
5204 }
5205
5206 /* Subroutine of lookup_signatured_type.
5207    Look up the type for signature SIG, and if we can't find SIG in .gdb_index
5208    then try the DWP file.  If the TU stub (skeleton) has been removed then
5209    it won't be in .gdb_index.  */
5210
5211 static struct signatured_type *
5212 lookup_dwp_signatured_type (struct dwarf2_cu *cu, ULONGEST sig)
5213 {
5214   struct objfile *objfile = dwarf2_per_objfile->objfile;
5215   struct dwp_file *dwp_file = get_dwp_file ();
5216   struct dwo_unit *dwo_entry;
5217   struct signatured_type find_sig_entry, *sig_entry;
5218   void **slot;
5219
5220   gdb_assert (cu->dwo_unit && dwarf2_per_objfile->using_index);
5221   gdb_assert (dwp_file != NULL);
5222
5223   /* If TU skeletons have been removed then we may not have read in any
5224      TUs yet.  */
5225   if (dwarf2_per_objfile->signatured_types == NULL)
5226     {
5227       dwarf2_per_objfile->signatured_types
5228         = allocate_signatured_type_table (objfile);
5229     }
5230
5231   find_sig_entry.signature = sig;
5232   slot = htab_find_slot (dwarf2_per_objfile->signatured_types,
5233                          &find_sig_entry, INSERT);
5234   sig_entry = (struct signatured_type *) *slot;
5235
5236   /* Have we already tried to read this TU?
5237      Note: sig_entry can be NULL if the skeleton TU was removed (thus it
5238      needn't exist in the global table yet).  */
5239   if (sig_entry != NULL)
5240     return sig_entry;
5241
5242   if (dwp_file->tus == NULL)
5243     return NULL;
5244   dwo_entry = lookup_dwo_unit_in_dwp (dwp_file, NULL,
5245                                       sig, 1 /* is_debug_types */);
5246   if (dwo_entry == NULL)
5247     return NULL;
5248
5249   sig_entry = add_type_unit (sig, slot);
5250   fill_in_sig_entry_from_dwo_entry (objfile, sig_entry, dwo_entry);
5251
5252   return sig_entry;
5253 }
5254
5255 /* Lookup a signature based type for DW_FORM_ref_sig8.
5256    Returns NULL if signature SIG is not present in the table.
5257    It is up to the caller to complain about this.  */
5258
5259 static struct signatured_type *
5260 lookup_signatured_type (struct dwarf2_cu *cu, ULONGEST sig)
5261 {
5262   if (cu->dwo_unit
5263       && dwarf2_per_objfile->using_index)
5264     {
5265       /* We're in a DWO/DWP file, and we're using .gdb_index.
5266          These cases require special processing.  */
5267       if (get_dwp_file () == NULL)
5268         return lookup_dwo_signatured_type (cu, sig);
5269       else
5270         return lookup_dwp_signatured_type (cu, sig);
5271     }
5272   else
5273     {
5274       struct signatured_type find_entry, *entry;
5275
5276       if (dwarf2_per_objfile->signatured_types == NULL)
5277         return NULL;
5278       find_entry.signature = sig;
5279       entry = ((struct signatured_type *)
5280                htab_find (dwarf2_per_objfile->signatured_types, &find_entry));
5281       return entry;
5282     }
5283 }
5284 \f
5285 /* Low level DIE reading support.  */
5286
5287 /* Initialize a die_reader_specs struct from a dwarf2_cu struct.  */
5288
5289 static void
5290 init_cu_die_reader (struct die_reader_specs *reader,
5291                     struct dwarf2_cu *cu,
5292                     struct dwarf2_section_info *section,
5293                     struct dwo_file *dwo_file)
5294 {
5295   gdb_assert (section->readin && section->buffer != NULL);
5296   reader->abfd = get_section_bfd_owner (section);
5297   reader->cu = cu;
5298   reader->dwo_file = dwo_file;
5299   reader->die_section = section;
5300   reader->buffer = section->buffer;
5301   reader->buffer_end = section->buffer + section->size;
5302   reader->comp_dir = NULL;
5303 }
5304
5305 /* Subroutine of init_cutu_and_read_dies to simplify it.
5306    Read in the rest of a CU/TU top level DIE from DWO_UNIT.
5307    There's just a lot of work to do, and init_cutu_and_read_dies is big enough
5308    already.
5309
5310    STUB_COMP_UNIT_DIE is for the stub DIE, we copy over certain attributes
5311    from it to the DIE in the DWO.  If NULL we are skipping the stub.
5312    STUB_COMP_DIR is similar to STUB_COMP_UNIT_DIE: When reading a TU directly
5313    from the DWO file, bypassing the stub, it contains the DW_AT_comp_dir
5314    attribute of the referencing CU.  At most one of STUB_COMP_UNIT_DIE and
5315    STUB_COMP_DIR may be non-NULL.
5316    *RESULT_READER,*RESULT_INFO_PTR,*RESULT_COMP_UNIT_DIE,*RESULT_HAS_CHILDREN
5317    are filled in with the info of the DIE from the DWO file.
5318    ABBREV_TABLE_PROVIDED is non-zero if the caller of init_cutu_and_read_dies
5319    provided an abbrev table to use.
5320    The result is non-zero if a valid (non-dummy) DIE was found.  */
5321
5322 static int
5323 read_cutu_die_from_dwo (struct dwarf2_per_cu_data *this_cu,
5324                         struct dwo_unit *dwo_unit,
5325                         int abbrev_table_provided,
5326                         struct die_info *stub_comp_unit_die,
5327                         const char *stub_comp_dir,
5328                         struct die_reader_specs *result_reader,
5329                         const gdb_byte **result_info_ptr,
5330                         struct die_info **result_comp_unit_die,
5331                         int *result_has_children)
5332 {
5333   struct objfile *objfile = dwarf2_per_objfile->objfile;
5334   struct dwarf2_cu *cu = this_cu->cu;
5335   struct dwarf2_section_info *section;
5336   bfd *abfd;
5337   const gdb_byte *begin_info_ptr, *info_ptr;
5338   ULONGEST signature; /* Or dwo_id.  */
5339   struct attribute *comp_dir, *stmt_list, *low_pc, *high_pc, *ranges;
5340   int i,num_extra_attrs;
5341   struct dwarf2_section_info *dwo_abbrev_section;
5342   struct attribute *attr;
5343   struct die_info *comp_unit_die;
5344
5345   /* At most one of these may be provided.  */
5346   gdb_assert ((stub_comp_unit_die != NULL) + (stub_comp_dir != NULL) <= 1);
5347
5348   /* These attributes aren't processed until later:
5349      DW_AT_stmt_list, DW_AT_low_pc, DW_AT_high_pc, DW_AT_ranges.
5350      DW_AT_comp_dir is used now, to find the DWO file, but it is also
5351      referenced later.  However, these attributes are found in the stub
5352      which we won't have later.  In order to not impose this complication
5353      on the rest of the code, we read them here and copy them to the
5354      DWO CU/TU die.  */
5355
5356   stmt_list = NULL;
5357   low_pc = NULL;
5358   high_pc = NULL;
5359   ranges = NULL;
5360   comp_dir = NULL;
5361
5362   if (stub_comp_unit_die != NULL)
5363     {
5364       /* For TUs in DWO files, the DW_AT_stmt_list attribute lives in the
5365          DWO file.  */
5366       if (! this_cu->is_debug_types)
5367         stmt_list = dwarf2_attr (stub_comp_unit_die, DW_AT_stmt_list, cu);
5368       low_pc = dwarf2_attr (stub_comp_unit_die, DW_AT_low_pc, cu);
5369       high_pc = dwarf2_attr (stub_comp_unit_die, DW_AT_high_pc, cu);
5370       ranges = dwarf2_attr (stub_comp_unit_die, DW_AT_ranges, cu);
5371       comp_dir = dwarf2_attr (stub_comp_unit_die, DW_AT_comp_dir, cu);
5372
5373       /* There should be a DW_AT_addr_base attribute here (if needed).
5374          We need the value before we can process DW_FORM_GNU_addr_index.  */
5375       cu->addr_base = 0;
5376       attr = dwarf2_attr (stub_comp_unit_die, DW_AT_GNU_addr_base, cu);
5377       if (attr)
5378         cu->addr_base = DW_UNSND (attr);
5379
5380       /* There should be a DW_AT_ranges_base attribute here (if needed).
5381          We need the value before we can process DW_AT_ranges.  */
5382       cu->ranges_base = 0;
5383       attr = dwarf2_attr (stub_comp_unit_die, DW_AT_GNU_ranges_base, cu);
5384       if (attr)
5385         cu->ranges_base = DW_UNSND (attr);
5386     }
5387   else if (stub_comp_dir != NULL)
5388     {
5389       /* Reconstruct the comp_dir attribute to simplify the code below.  */
5390       comp_dir = XOBNEW (&cu->comp_unit_obstack, struct attribute);
5391       comp_dir->name = DW_AT_comp_dir;
5392       comp_dir->form = DW_FORM_string;
5393       DW_STRING_IS_CANONICAL (comp_dir) = 0;
5394       DW_STRING (comp_dir) = stub_comp_dir;
5395     }
5396
5397   /* Set up for reading the DWO CU/TU.  */
5398   cu->dwo_unit = dwo_unit;
5399   section = dwo_unit->section;
5400   dwarf2_read_section (objfile, section);
5401   abfd = get_section_bfd_owner (section);
5402   begin_info_ptr = info_ptr = (section->buffer
5403                                + to_underlying (dwo_unit->sect_off));
5404   dwo_abbrev_section = &dwo_unit->dwo_file->sections.abbrev;
5405   init_cu_die_reader (result_reader, cu, section, dwo_unit->dwo_file);
5406
5407   if (this_cu->is_debug_types)
5408     {
5409       struct signatured_type *sig_type = (struct signatured_type *) this_cu;
5410
5411       info_ptr = read_and_check_comp_unit_head (&cu->header, section,
5412                                                 dwo_abbrev_section,
5413                                                 info_ptr, rcuh_kind::TYPE);
5414       /* This is not an assert because it can be caused by bad debug info.  */
5415       if (sig_type->signature != cu->header.signature)
5416         {
5417           error (_("Dwarf Error: signature mismatch %s vs %s while reading"
5418                    " TU at offset 0x%x [in module %s]"),
5419                  hex_string (sig_type->signature),
5420                  hex_string (cu->header.signature),
5421                  to_underlying (dwo_unit->sect_off),
5422                  bfd_get_filename (abfd));
5423         }
5424       gdb_assert (dwo_unit->sect_off == cu->header.sect_off);
5425       /* For DWOs coming from DWP files, we don't know the CU length
5426          nor the type's offset in the TU until now.  */
5427       dwo_unit->length = get_cu_length (&cu->header);
5428       dwo_unit->type_offset_in_tu = cu->header.type_cu_offset_in_tu;
5429
5430       /* Establish the type offset that can be used to lookup the type.
5431          For DWO files, we don't know it until now.  */
5432       sig_type->type_offset_in_section
5433         = dwo_unit->sect_off + to_underlying (dwo_unit->type_offset_in_tu);
5434     }
5435   else
5436     {
5437       info_ptr = read_and_check_comp_unit_head (&cu->header, section,
5438                                                 dwo_abbrev_section,
5439                                                 info_ptr, rcuh_kind::COMPILE);
5440       gdb_assert (dwo_unit->sect_off == cu->header.sect_off);
5441       /* For DWOs coming from DWP files, we don't know the CU length
5442          until now.  */
5443       dwo_unit->length = get_cu_length (&cu->header);
5444     }
5445
5446   /* Replace the CU's original abbrev table with the DWO's.
5447      Reminder: We can't read the abbrev table until we've read the header.  */
5448   if (abbrev_table_provided)
5449     {
5450       /* Don't free the provided abbrev table, the caller of
5451          init_cutu_and_read_dies owns it.  */
5452       dwarf2_read_abbrevs (cu, dwo_abbrev_section);
5453       /* Ensure the DWO abbrev table gets freed.  */
5454       make_cleanup (dwarf2_free_abbrev_table, cu);
5455     }
5456   else
5457     {
5458       dwarf2_free_abbrev_table (cu);
5459       dwarf2_read_abbrevs (cu, dwo_abbrev_section);
5460       /* Leave any existing abbrev table cleanup as is.  */
5461     }
5462
5463   /* Read in the die, but leave space to copy over the attributes
5464      from the stub.  This has the benefit of simplifying the rest of
5465      the code - all the work to maintain the illusion of a single
5466      DW_TAG_{compile,type}_unit DIE is done here.  */
5467   num_extra_attrs = ((stmt_list != NULL)
5468                      + (low_pc != NULL)
5469                      + (high_pc != NULL)
5470                      + (ranges != NULL)
5471                      + (comp_dir != NULL));
5472   info_ptr = read_full_die_1 (result_reader, result_comp_unit_die, info_ptr,
5473                               result_has_children, num_extra_attrs);
5474
5475   /* Copy over the attributes from the stub to the DIE we just read in.  */
5476   comp_unit_die = *result_comp_unit_die;
5477   i = comp_unit_die->num_attrs;
5478   if (stmt_list != NULL)
5479     comp_unit_die->attrs[i++] = *stmt_list;
5480   if (low_pc != NULL)
5481     comp_unit_die->attrs[i++] = *low_pc;
5482   if (high_pc != NULL)
5483     comp_unit_die->attrs[i++] = *high_pc;
5484   if (ranges != NULL)
5485     comp_unit_die->attrs[i++] = *ranges;
5486   if (comp_dir != NULL)
5487     comp_unit_die->attrs[i++] = *comp_dir;
5488   comp_unit_die->num_attrs += num_extra_attrs;
5489
5490   if (dwarf_die_debug)
5491     {
5492       fprintf_unfiltered (gdb_stdlog,
5493                           "Read die from %s@0x%x of %s:\n",
5494                           get_section_name (section),
5495                           (unsigned) (begin_info_ptr - section->buffer),
5496                           bfd_get_filename (abfd));
5497       dump_die (comp_unit_die, dwarf_die_debug);
5498     }
5499
5500   /* Save the comp_dir attribute.  If there is no DWP file then we'll read
5501      TUs by skipping the stub and going directly to the entry in the DWO file.
5502      However, skipping the stub means we won't get DW_AT_comp_dir, so we have
5503      to get it via circuitous means.  Blech.  */
5504   if (comp_dir != NULL)
5505     result_reader->comp_dir = DW_STRING (comp_dir);
5506
5507   /* Skip dummy compilation units.  */
5508   if (info_ptr >= begin_info_ptr + dwo_unit->length
5509       || peek_abbrev_code (abfd, info_ptr) == 0)
5510     return 0;
5511
5512   *result_info_ptr = info_ptr;
5513   return 1;
5514 }
5515
5516 /* Subroutine of init_cutu_and_read_dies to simplify it.
5517    Look up the DWO unit specified by COMP_UNIT_DIE of THIS_CU.
5518    Returns NULL if the specified DWO unit cannot be found.  */
5519
5520 static struct dwo_unit *
5521 lookup_dwo_unit (struct dwarf2_per_cu_data *this_cu,
5522                  struct die_info *comp_unit_die)
5523 {
5524   struct dwarf2_cu *cu = this_cu->cu;
5525   struct attribute *attr;
5526   ULONGEST signature;
5527   struct dwo_unit *dwo_unit;
5528   const char *comp_dir, *dwo_name;
5529
5530   gdb_assert (cu != NULL);
5531
5532   /* Yeah, we look dwo_name up again, but it simplifies the code.  */
5533   dwo_name = dwarf2_string_attr (comp_unit_die, DW_AT_GNU_dwo_name, cu);
5534   comp_dir = dwarf2_string_attr (comp_unit_die, DW_AT_comp_dir, cu);
5535
5536   if (this_cu->is_debug_types)
5537     {
5538       struct signatured_type *sig_type;
5539
5540       /* Since this_cu is the first member of struct signatured_type,
5541          we can go from a pointer to one to a pointer to the other.  */
5542       sig_type = (struct signatured_type *) this_cu;
5543       signature = sig_type->signature;
5544       dwo_unit = lookup_dwo_type_unit (sig_type, dwo_name, comp_dir);
5545     }
5546   else
5547     {
5548       struct attribute *attr;
5549
5550       attr = dwarf2_attr (comp_unit_die, DW_AT_GNU_dwo_id, cu);
5551       if (! attr)
5552         error (_("Dwarf Error: missing dwo_id for dwo_name %s"
5553                  " [in module %s]"),
5554                dwo_name, objfile_name (this_cu->objfile));
5555       signature = DW_UNSND (attr);
5556       dwo_unit = lookup_dwo_comp_unit (this_cu, dwo_name, comp_dir,
5557                                        signature);
5558     }
5559
5560   return dwo_unit;
5561 }
5562
5563 /* Subroutine of init_cutu_and_read_dies to simplify it.
5564    See it for a description of the parameters.
5565    Read a TU directly from a DWO file, bypassing the stub.
5566
5567    Note: This function could be a little bit simpler if we shared cleanups
5568    with our caller, init_cutu_and_read_dies.  That's generally a fragile thing
5569    to do, so we keep this function self-contained.  Or we could move this
5570    into our caller, but it's complex enough already.  */
5571
5572 static void
5573 init_tu_and_read_dwo_dies (struct dwarf2_per_cu_data *this_cu,
5574                            int use_existing_cu, int keep,
5575                            die_reader_func_ftype *die_reader_func,
5576                            void *data)
5577 {
5578   struct dwarf2_cu *cu;
5579   struct signatured_type *sig_type;
5580   struct cleanup *cleanups, *free_cu_cleanup = NULL;
5581   struct die_reader_specs reader;
5582   const gdb_byte *info_ptr;
5583   struct die_info *comp_unit_die;
5584   int has_children;
5585
5586   /* Verify we can do the following downcast, and that we have the
5587      data we need.  */
5588   gdb_assert (this_cu->is_debug_types && this_cu->reading_dwo_directly);
5589   sig_type = (struct signatured_type *) this_cu;
5590   gdb_assert (sig_type->dwo_unit != NULL);
5591
5592   cleanups = make_cleanup (null_cleanup, NULL);
5593
5594   if (use_existing_cu && this_cu->cu != NULL)
5595     {
5596       gdb_assert (this_cu->cu->dwo_unit == sig_type->dwo_unit);
5597       cu = this_cu->cu;
5598       /* There's no need to do the rereading_dwo_cu handling that
5599          init_cutu_and_read_dies does since we don't read the stub.  */
5600     }
5601   else
5602     {
5603       /* If !use_existing_cu, this_cu->cu must be NULL.  */
5604       gdb_assert (this_cu->cu == NULL);
5605       cu = XNEW (struct dwarf2_cu);
5606       init_one_comp_unit (cu, this_cu);
5607       /* If an error occurs while loading, release our storage.  */
5608       free_cu_cleanup = make_cleanup (free_heap_comp_unit, cu);
5609     }
5610
5611   /* A future optimization, if needed, would be to use an existing
5612      abbrev table.  When reading DWOs with skeletonless TUs, all the TUs
5613      could share abbrev tables.  */
5614
5615   if (read_cutu_die_from_dwo (this_cu, sig_type->dwo_unit,
5616                               0 /* abbrev_table_provided */,
5617                               NULL /* stub_comp_unit_die */,
5618                               sig_type->dwo_unit->dwo_file->comp_dir,
5619                               &reader, &info_ptr,
5620                               &comp_unit_die, &has_children) == 0)
5621     {
5622       /* Dummy die.  */
5623       do_cleanups (cleanups);
5624       return;
5625     }
5626
5627   /* All the "real" work is done here.  */
5628   die_reader_func (&reader, info_ptr, comp_unit_die, has_children, data);
5629
5630   /* This duplicates the code in init_cutu_and_read_dies,
5631      but the alternative is making the latter more complex.
5632      This function is only for the special case of using DWO files directly:
5633      no point in overly complicating the general case just to handle this.  */
5634   if (free_cu_cleanup != NULL)
5635     {
5636       if (keep)
5637         {
5638           /* We've successfully allocated this compilation unit.  Let our
5639              caller clean it up when finished with it.  */
5640           discard_cleanups (free_cu_cleanup);
5641
5642           /* We can only discard free_cu_cleanup and all subsequent cleanups.
5643              So we have to manually free the abbrev table.  */
5644           dwarf2_free_abbrev_table (cu);
5645
5646           /* Link this CU into read_in_chain.  */
5647           this_cu->cu->read_in_chain = dwarf2_per_objfile->read_in_chain;
5648           dwarf2_per_objfile->read_in_chain = this_cu;
5649         }
5650       else
5651         do_cleanups (free_cu_cleanup);
5652     }
5653
5654   do_cleanups (cleanups);
5655 }
5656
5657 /* Initialize a CU (or TU) and read its DIEs.
5658    If the CU defers to a DWO file, read the DWO file as well.
5659
5660    ABBREV_TABLE, if non-NULL, is the abbreviation table to use.
5661    Otherwise the table specified in the comp unit header is read in and used.
5662    This is an optimization for when we already have the abbrev table.
5663
5664    If USE_EXISTING_CU is non-zero, and THIS_CU->cu is non-NULL, then use it.
5665    Otherwise, a new CU is allocated with xmalloc.
5666
5667    If KEEP is non-zero, then if we allocated a dwarf2_cu we add it to
5668    read_in_chain.  Otherwise the dwarf2_cu data is freed at the end.
5669
5670    WARNING: If THIS_CU is a "dummy CU" (used as filler by the incremental
5671    linker) then DIE_READER_FUNC will not get called.  */
5672
5673 static void
5674 init_cutu_and_read_dies (struct dwarf2_per_cu_data *this_cu,
5675                          struct abbrev_table *abbrev_table,
5676                          int use_existing_cu, int keep,
5677                          die_reader_func_ftype *die_reader_func,
5678                          void *data)
5679 {
5680   struct objfile *objfile = dwarf2_per_objfile->objfile;
5681   struct dwarf2_section_info *section = this_cu->section;
5682   bfd *abfd = get_section_bfd_owner (section);
5683   struct dwarf2_cu *cu;
5684   const gdb_byte *begin_info_ptr, *info_ptr;
5685   struct die_reader_specs reader;
5686   struct die_info *comp_unit_die;
5687   int has_children;
5688   struct attribute *attr;
5689   struct cleanup *cleanups, *free_cu_cleanup = NULL;
5690   struct signatured_type *sig_type = NULL;
5691   struct dwarf2_section_info *abbrev_section;
5692   /* Non-zero if CU currently points to a DWO file and we need to
5693      reread it.  When this happens we need to reread the skeleton die
5694      before we can reread the DWO file (this only applies to CUs, not TUs).  */
5695   int rereading_dwo_cu = 0;
5696
5697   if (dwarf_die_debug)
5698     fprintf_unfiltered (gdb_stdlog, "Reading %s unit at offset 0x%x\n",
5699                         this_cu->is_debug_types ? "type" : "comp",
5700                         to_underlying (this_cu->sect_off));
5701
5702   if (use_existing_cu)
5703     gdb_assert (keep);
5704
5705   /* If we're reading a TU directly from a DWO file, including a virtual DWO
5706      file (instead of going through the stub), short-circuit all of this.  */
5707   if (this_cu->reading_dwo_directly)
5708     {
5709       /* Narrow down the scope of possibilities to have to understand.  */
5710       gdb_assert (this_cu->is_debug_types);
5711       gdb_assert (abbrev_table == NULL);
5712       init_tu_and_read_dwo_dies (this_cu, use_existing_cu, keep,
5713                                  die_reader_func, data);
5714       return;
5715     }
5716
5717   cleanups = make_cleanup (null_cleanup, NULL);
5718
5719   /* This is cheap if the section is already read in.  */
5720   dwarf2_read_section (objfile, section);
5721
5722   begin_info_ptr = info_ptr = section->buffer + to_underlying (this_cu->sect_off);
5723
5724   abbrev_section = get_abbrev_section_for_cu (this_cu);
5725
5726   if (use_existing_cu && this_cu->cu != NULL)
5727     {
5728       cu = this_cu->cu;
5729       /* If this CU is from a DWO file we need to start over, we need to
5730          refetch the attributes from the skeleton CU.
5731          This could be optimized by retrieving those attributes from when we
5732          were here the first time: the previous comp_unit_die was stored in
5733          comp_unit_obstack.  But there's no data yet that we need this
5734          optimization.  */
5735       if (cu->dwo_unit != NULL)
5736         rereading_dwo_cu = 1;
5737     }
5738   else
5739     {
5740       /* If !use_existing_cu, this_cu->cu must be NULL.  */
5741       gdb_assert (this_cu->cu == NULL);
5742       cu = XNEW (struct dwarf2_cu);
5743       init_one_comp_unit (cu, this_cu);
5744       /* If an error occurs while loading, release our storage.  */
5745       free_cu_cleanup = make_cleanup (free_heap_comp_unit, cu);
5746     }
5747
5748   /* Get the header.  */
5749   if (to_underlying (cu->header.first_die_cu_offset) != 0 && !rereading_dwo_cu)
5750     {
5751       /* We already have the header, there's no need to read it in again.  */
5752       info_ptr += to_underlying (cu->header.first_die_cu_offset);
5753     }
5754   else
5755     {
5756       if (this_cu->is_debug_types)
5757         {
5758           info_ptr = read_and_check_comp_unit_head (&cu->header, section,
5759                                                     abbrev_section, info_ptr,
5760                                                     rcuh_kind::TYPE);
5761
5762           /* Since per_cu is the first member of struct signatured_type,
5763              we can go from a pointer to one to a pointer to the other.  */
5764           sig_type = (struct signatured_type *) this_cu;
5765           gdb_assert (sig_type->signature == cu->header.signature);
5766           gdb_assert (sig_type->type_offset_in_tu
5767                       == cu->header.type_cu_offset_in_tu);
5768           gdb_assert (this_cu->sect_off == cu->header.sect_off);
5769
5770           /* LENGTH has not been set yet for type units if we're
5771              using .gdb_index.  */
5772           this_cu->length = get_cu_length (&cu->header);
5773
5774           /* Establish the type offset that can be used to lookup the type.  */
5775           sig_type->type_offset_in_section =
5776             this_cu->sect_off + to_underlying (sig_type->type_offset_in_tu);
5777
5778           this_cu->dwarf_version = cu->header.version;
5779         }
5780       else
5781         {
5782           info_ptr = read_and_check_comp_unit_head (&cu->header, section,
5783                                                     abbrev_section,
5784                                                     info_ptr,
5785                                                     rcuh_kind::COMPILE);
5786
5787           gdb_assert (this_cu->sect_off == cu->header.sect_off);
5788           gdb_assert (this_cu->length == get_cu_length (&cu->header));
5789           this_cu->dwarf_version = cu->header.version;
5790         }
5791     }
5792
5793   /* Skip dummy compilation units.  */
5794   if (info_ptr >= begin_info_ptr + this_cu->length
5795       || peek_abbrev_code (abfd, info_ptr) == 0)
5796     {
5797       do_cleanups (cleanups);
5798       return;
5799     }
5800
5801   /* If we don't have them yet, read the abbrevs for this compilation unit.
5802      And if we need to read them now, make sure they're freed when we're
5803      done.  Note that it's important that if the CU had an abbrev table
5804      on entry we don't free it when we're done: Somewhere up the call stack
5805      it may be in use.  */
5806   if (abbrev_table != NULL)
5807     {
5808       gdb_assert (cu->abbrev_table == NULL);
5809       gdb_assert (cu->header.abbrev_sect_off == abbrev_table->sect_off);
5810       cu->abbrev_table = abbrev_table;
5811     }
5812   else if (cu->abbrev_table == NULL)
5813     {
5814       dwarf2_read_abbrevs (cu, abbrev_section);
5815       make_cleanup (dwarf2_free_abbrev_table, cu);
5816     }
5817   else if (rereading_dwo_cu)
5818     {
5819       dwarf2_free_abbrev_table (cu);
5820       dwarf2_read_abbrevs (cu, abbrev_section);
5821     }
5822
5823   /* Read the top level CU/TU die.  */
5824   init_cu_die_reader (&reader, cu, section, NULL);
5825   info_ptr = read_full_die (&reader, &comp_unit_die, info_ptr, &has_children);
5826
5827   /* If we are in a DWO stub, process it and then read in the "real" CU/TU
5828      from the DWO file.
5829      Note that if USE_EXISTING_OK != 0, and THIS_CU->cu already contains a
5830      DWO CU, that this test will fail (the attribute will not be present).  */
5831   attr = dwarf2_attr (comp_unit_die, DW_AT_GNU_dwo_name, cu);
5832   if (attr)
5833     {
5834       struct dwo_unit *dwo_unit;
5835       struct die_info *dwo_comp_unit_die;
5836
5837       if (has_children)
5838         {
5839           complaint (&symfile_complaints,
5840                      _("compilation unit with DW_AT_GNU_dwo_name"
5841                        " has children (offset 0x%x) [in module %s]"),
5842                      to_underlying (this_cu->sect_off), bfd_get_filename (abfd));
5843         }
5844       dwo_unit = lookup_dwo_unit (this_cu, comp_unit_die);
5845       if (dwo_unit != NULL)
5846         {
5847           if (read_cutu_die_from_dwo (this_cu, dwo_unit,
5848                                       abbrev_table != NULL,
5849                                       comp_unit_die, NULL,
5850                                       &reader, &info_ptr,
5851                                       &dwo_comp_unit_die, &has_children) == 0)
5852             {
5853               /* Dummy die.  */
5854               do_cleanups (cleanups);
5855               return;
5856             }
5857           comp_unit_die = dwo_comp_unit_die;
5858         }
5859       else
5860         {
5861           /* Yikes, we couldn't find the rest of the DIE, we only have
5862              the stub.  A complaint has already been logged.  There's
5863              not much more we can do except pass on the stub DIE to
5864              die_reader_func.  We don't want to throw an error on bad
5865              debug info.  */
5866         }
5867     }
5868
5869   /* All of the above is setup for this call.  Yikes.  */
5870   die_reader_func (&reader, info_ptr, comp_unit_die, has_children, data);
5871
5872   /* Done, clean up.  */
5873   if (free_cu_cleanup != NULL)
5874     {
5875       if (keep)
5876         {
5877           /* We've successfully allocated this compilation unit.  Let our
5878              caller clean it up when finished with it.  */
5879           discard_cleanups (free_cu_cleanup);
5880
5881           /* We can only discard free_cu_cleanup and all subsequent cleanups.
5882              So we have to manually free the abbrev table.  */
5883           dwarf2_free_abbrev_table (cu);
5884
5885           /* Link this CU into read_in_chain.  */
5886           this_cu->cu->read_in_chain = dwarf2_per_objfile->read_in_chain;
5887           dwarf2_per_objfile->read_in_chain = this_cu;
5888         }
5889       else
5890         do_cleanups (free_cu_cleanup);
5891     }
5892
5893   do_cleanups (cleanups);
5894 }
5895
5896 /* Read CU/TU THIS_CU but do not follow DW_AT_GNU_dwo_name if present.
5897    DWO_FILE, if non-NULL, is the DWO file to read (the caller is assumed
5898    to have already done the lookup to find the DWO file).
5899
5900    The caller is required to fill in THIS_CU->section, THIS_CU->offset, and
5901    THIS_CU->is_debug_types, but nothing else.
5902
5903    We fill in THIS_CU->length.
5904
5905    WARNING: If THIS_CU is a "dummy CU" (used as filler by the incremental
5906    linker) then DIE_READER_FUNC will not get called.
5907
5908    THIS_CU->cu is always freed when done.
5909    This is done in order to not leave THIS_CU->cu in a state where we have
5910    to care whether it refers to the "main" CU or the DWO CU.  */
5911
5912 static void
5913 init_cutu_and_read_dies_no_follow (struct dwarf2_per_cu_data *this_cu,
5914                                    struct dwo_file *dwo_file,
5915                                    die_reader_func_ftype *die_reader_func,
5916                                    void *data)
5917 {
5918   struct objfile *objfile = dwarf2_per_objfile->objfile;
5919   struct dwarf2_section_info *section = this_cu->section;
5920   bfd *abfd = get_section_bfd_owner (section);
5921   struct dwarf2_section_info *abbrev_section;
5922   struct dwarf2_cu cu;
5923   const gdb_byte *begin_info_ptr, *info_ptr;
5924   struct die_reader_specs reader;
5925   struct cleanup *cleanups;
5926   struct die_info *comp_unit_die;
5927   int has_children;
5928
5929   if (dwarf_die_debug)
5930     fprintf_unfiltered (gdb_stdlog, "Reading %s unit at offset 0x%x\n",
5931                         this_cu->is_debug_types ? "type" : "comp",
5932                         to_underlying (this_cu->sect_off));
5933
5934   gdb_assert (this_cu->cu == NULL);
5935
5936   abbrev_section = (dwo_file != NULL
5937                     ? &dwo_file->sections.abbrev
5938                     : get_abbrev_section_for_cu (this_cu));
5939
5940   /* This is cheap if the section is already read in.  */
5941   dwarf2_read_section (objfile, section);
5942
5943   init_one_comp_unit (&cu, this_cu);
5944
5945   cleanups = make_cleanup (free_stack_comp_unit, &cu);
5946
5947   begin_info_ptr = info_ptr = section->buffer + to_underlying (this_cu->sect_off);
5948   info_ptr = read_and_check_comp_unit_head (&cu.header, section,
5949                                             abbrev_section, info_ptr,
5950                                             (this_cu->is_debug_types
5951                                              ? rcuh_kind::TYPE
5952                                              : rcuh_kind::COMPILE));
5953
5954   this_cu->length = get_cu_length (&cu.header);
5955
5956   /* Skip dummy compilation units.  */
5957   if (info_ptr >= begin_info_ptr + this_cu->length
5958       || peek_abbrev_code (abfd, info_ptr) == 0)
5959     {
5960       do_cleanups (cleanups);
5961       return;
5962     }
5963
5964   dwarf2_read_abbrevs (&cu, abbrev_section);
5965   make_cleanup (dwarf2_free_abbrev_table, &cu);
5966
5967   init_cu_die_reader (&reader, &cu, section, dwo_file);
5968   info_ptr = read_full_die (&reader, &comp_unit_die, info_ptr, &has_children);
5969
5970   die_reader_func (&reader, info_ptr, comp_unit_die, has_children, data);
5971
5972   do_cleanups (cleanups);
5973 }
5974
5975 /* Read a CU/TU, except that this does not look for DW_AT_GNU_dwo_name and
5976    does not lookup the specified DWO file.
5977    This cannot be used to read DWO files.
5978
5979    THIS_CU->cu is always freed when done.
5980    This is done in order to not leave THIS_CU->cu in a state where we have
5981    to care whether it refers to the "main" CU or the DWO CU.
5982    We can revisit this if the data shows there's a performance issue.  */
5983
5984 static void
5985 init_cutu_and_read_dies_simple (struct dwarf2_per_cu_data *this_cu,
5986                                 die_reader_func_ftype *die_reader_func,
5987                                 void *data)
5988 {
5989   init_cutu_and_read_dies_no_follow (this_cu, NULL, die_reader_func, data);
5990 }
5991 \f
5992 /* Type Unit Groups.
5993
5994    Type Unit Groups are a way to collapse the set of all TUs (type units) into
5995    a more manageable set.  The grouping is done by DW_AT_stmt_list entry
5996    so that all types coming from the same compilation (.o file) are grouped
5997    together.  A future step could be to put the types in the same symtab as
5998    the CU the types ultimately came from.  */
5999
6000 static hashval_t
6001 hash_type_unit_group (const void *item)
6002 {
6003   const struct type_unit_group *tu_group
6004     = (const struct type_unit_group *) item;
6005
6006   return hash_stmt_list_entry (&tu_group->hash);
6007 }
6008
6009 static int
6010 eq_type_unit_group (const void *item_lhs, const void *item_rhs)
6011 {
6012   const struct type_unit_group *lhs = (const struct type_unit_group *) item_lhs;
6013   const struct type_unit_group *rhs = (const struct type_unit_group *) item_rhs;
6014
6015   return eq_stmt_list_entry (&lhs->hash, &rhs->hash);
6016 }
6017
6018 /* Allocate a hash table for type unit groups.  */
6019
6020 static htab_t
6021 allocate_type_unit_groups_table (void)
6022 {
6023   return htab_create_alloc_ex (3,
6024                                hash_type_unit_group,
6025                                eq_type_unit_group,
6026                                NULL,
6027                                &dwarf2_per_objfile->objfile->objfile_obstack,
6028                                hashtab_obstack_allocate,
6029                                dummy_obstack_deallocate);
6030 }
6031
6032 /* Type units that don't have DW_AT_stmt_list are grouped into their own
6033    partial symtabs.  We combine several TUs per psymtab to not let the size
6034    of any one psymtab grow too big.  */
6035 #define NO_STMT_LIST_TYPE_UNIT_PSYMTAB (1 << 31)
6036 #define NO_STMT_LIST_TYPE_UNIT_PSYMTAB_SIZE 10
6037
6038 /* Helper routine for get_type_unit_group.
6039    Create the type_unit_group object used to hold one or more TUs.  */
6040
6041 static struct type_unit_group *
6042 create_type_unit_group (struct dwarf2_cu *cu, sect_offset line_offset_struct)
6043 {
6044   struct objfile *objfile = dwarf2_per_objfile->objfile;
6045   struct dwarf2_per_cu_data *per_cu;
6046   struct type_unit_group *tu_group;
6047
6048   tu_group = OBSTACK_ZALLOC (&objfile->objfile_obstack,
6049                              struct type_unit_group);
6050   per_cu = &tu_group->per_cu;
6051   per_cu->objfile = objfile;
6052
6053   if (dwarf2_per_objfile->using_index)
6054     {
6055       per_cu->v.quick = OBSTACK_ZALLOC (&objfile->objfile_obstack,
6056                                         struct dwarf2_per_cu_quick_data);
6057     }
6058   else
6059     {
6060       unsigned int line_offset = to_underlying (line_offset_struct);
6061       struct partial_symtab *pst;
6062       char *name;
6063
6064       /* Give the symtab a useful name for debug purposes.  */
6065       if ((line_offset & NO_STMT_LIST_TYPE_UNIT_PSYMTAB) != 0)
6066         name = xstrprintf ("<type_units_%d>",
6067                            (line_offset & ~NO_STMT_LIST_TYPE_UNIT_PSYMTAB));
6068       else
6069         name = xstrprintf ("<type_units_at_0x%x>", line_offset);
6070
6071       pst = create_partial_symtab (per_cu, name);
6072       pst->anonymous = 1;
6073
6074       xfree (name);
6075     }
6076
6077   tu_group->hash.dwo_unit = cu->dwo_unit;
6078   tu_group->hash.line_sect_off = line_offset_struct;
6079
6080   return tu_group;
6081 }
6082
6083 /* Look up the type_unit_group for type unit CU, and create it if necessary.
6084    STMT_LIST is a DW_AT_stmt_list attribute.  */
6085
6086 static struct type_unit_group *
6087 get_type_unit_group (struct dwarf2_cu *cu, const struct attribute *stmt_list)
6088 {
6089   struct tu_stats *tu_stats = &dwarf2_per_objfile->tu_stats;
6090   struct type_unit_group *tu_group;
6091   void **slot;
6092   unsigned int line_offset;
6093   struct type_unit_group type_unit_group_for_lookup;
6094
6095   if (dwarf2_per_objfile->type_unit_groups == NULL)
6096     {
6097       dwarf2_per_objfile->type_unit_groups =
6098         allocate_type_unit_groups_table ();
6099     }
6100
6101   /* Do we need to create a new group, or can we use an existing one?  */
6102
6103   if (stmt_list)
6104     {
6105       line_offset = DW_UNSND (stmt_list);
6106       ++tu_stats->nr_symtab_sharers;
6107     }
6108   else
6109     {
6110       /* Ugh, no stmt_list.  Rare, but we have to handle it.
6111          We can do various things here like create one group per TU or
6112          spread them over multiple groups to split up the expansion work.
6113          To avoid worst case scenarios (too many groups or too large groups)
6114          we, umm, group them in bunches.  */
6115       line_offset = (NO_STMT_LIST_TYPE_UNIT_PSYMTAB
6116                      | (tu_stats->nr_stmt_less_type_units
6117                         / NO_STMT_LIST_TYPE_UNIT_PSYMTAB_SIZE));
6118       ++tu_stats->nr_stmt_less_type_units;
6119     }
6120
6121   type_unit_group_for_lookup.hash.dwo_unit = cu->dwo_unit;
6122   type_unit_group_for_lookup.hash.line_sect_off = (sect_offset) line_offset;
6123   slot = htab_find_slot (dwarf2_per_objfile->type_unit_groups,
6124                          &type_unit_group_for_lookup, INSERT);
6125   if (*slot != NULL)
6126     {
6127       tu_group = (struct type_unit_group *) *slot;
6128       gdb_assert (tu_group != NULL);
6129     }
6130   else
6131     {
6132       sect_offset line_offset_struct = (sect_offset) line_offset;
6133       tu_group = create_type_unit_group (cu, line_offset_struct);
6134       *slot = tu_group;
6135       ++tu_stats->nr_symtabs;
6136     }
6137
6138   return tu_group;
6139 }
6140 \f
6141 /* Partial symbol tables.  */
6142
6143 /* Create a psymtab named NAME and assign it to PER_CU.
6144
6145    The caller must fill in the following details:
6146    dirname, textlow, texthigh.  */
6147
6148 static struct partial_symtab *
6149 create_partial_symtab (struct dwarf2_per_cu_data *per_cu, const char *name)
6150 {
6151   struct objfile *objfile = per_cu->objfile;
6152   struct partial_symtab *pst;
6153
6154   pst = start_psymtab_common (objfile, name, 0,
6155                               objfile->global_psymbols.next,
6156                               objfile->static_psymbols.next);
6157
6158   pst->psymtabs_addrmap_supported = 1;
6159
6160   /* This is the glue that links PST into GDB's symbol API.  */
6161   pst->read_symtab_private = per_cu;
6162   pst->read_symtab = dwarf2_read_symtab;
6163   per_cu->v.psymtab = pst;
6164
6165   return pst;
6166 }
6167
6168 /* The DATA object passed to process_psymtab_comp_unit_reader has this
6169    type.  */
6170
6171 struct process_psymtab_comp_unit_data
6172 {
6173   /* True if we are reading a DW_TAG_partial_unit.  */
6174
6175   int want_partial_unit;
6176
6177   /* The "pretend" language that is used if the CU doesn't declare a
6178      language.  */
6179
6180   enum language pretend_language;
6181 };
6182
6183 /* die_reader_func for process_psymtab_comp_unit.  */
6184
6185 static void
6186 process_psymtab_comp_unit_reader (const struct die_reader_specs *reader,
6187                                   const gdb_byte *info_ptr,
6188                                   struct die_info *comp_unit_die,
6189                                   int has_children,
6190                                   void *data)
6191 {
6192   struct dwarf2_cu *cu = reader->cu;
6193   struct objfile *objfile = cu->objfile;
6194   struct gdbarch *gdbarch = get_objfile_arch (objfile);
6195   struct dwarf2_per_cu_data *per_cu = cu->per_cu;
6196   CORE_ADDR baseaddr;
6197   CORE_ADDR best_lowpc = 0, best_highpc = 0;
6198   struct partial_symtab *pst;
6199   enum pc_bounds_kind cu_bounds_kind;
6200   const char *filename;
6201   struct process_psymtab_comp_unit_data *info
6202     = (struct process_psymtab_comp_unit_data *) data;
6203
6204   if (comp_unit_die->tag == DW_TAG_partial_unit && !info->want_partial_unit)
6205     return;
6206
6207   gdb_assert (! per_cu->is_debug_types);
6208
6209   prepare_one_comp_unit (cu, comp_unit_die, info->pretend_language);
6210
6211   cu->list_in_scope = &file_symbols;
6212
6213   /* Allocate a new partial symbol table structure.  */
6214   filename = dwarf2_string_attr (comp_unit_die, DW_AT_name, cu);
6215   if (filename == NULL)
6216     filename = "";
6217
6218   pst = create_partial_symtab (per_cu, filename);
6219
6220   /* This must be done before calling dwarf2_build_include_psymtabs.  */
6221   pst->dirname = dwarf2_string_attr (comp_unit_die, DW_AT_comp_dir, cu);
6222
6223   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
6224
6225   dwarf2_find_base_address (comp_unit_die, cu);
6226
6227   /* Possibly set the default values of LOWPC and HIGHPC from
6228      `DW_AT_ranges'.  */
6229   cu_bounds_kind = dwarf2_get_pc_bounds (comp_unit_die, &best_lowpc,
6230                                          &best_highpc, cu, pst);
6231   if (cu_bounds_kind == PC_BOUNDS_HIGH_LOW && best_lowpc < best_highpc)
6232     /* Store the contiguous range if it is not empty; it can be empty for
6233        CUs with no code.  */
6234     addrmap_set_empty (objfile->psymtabs_addrmap,
6235                        gdbarch_adjust_dwarf2_addr (gdbarch,
6236                                                    best_lowpc + baseaddr),
6237                        gdbarch_adjust_dwarf2_addr (gdbarch,
6238                                                    best_highpc + baseaddr) - 1,
6239                        pst);
6240
6241   /* Check if comp unit has_children.
6242      If so, read the rest of the partial symbols from this comp unit.
6243      If not, there's no more debug_info for this comp unit.  */
6244   if (has_children)
6245     {
6246       struct partial_die_info *first_die;
6247       CORE_ADDR lowpc, highpc;
6248
6249       lowpc = ((CORE_ADDR) -1);
6250       highpc = ((CORE_ADDR) 0);
6251
6252       first_die = load_partial_dies (reader, info_ptr, 1);
6253
6254       scan_partial_symbols (first_die, &lowpc, &highpc,
6255                             cu_bounds_kind <= PC_BOUNDS_INVALID, cu);
6256
6257       /* If we didn't find a lowpc, set it to highpc to avoid
6258          complaints from `maint check'.  */
6259       if (lowpc == ((CORE_ADDR) -1))
6260         lowpc = highpc;
6261
6262       /* If the compilation unit didn't have an explicit address range,
6263          then use the information extracted from its child dies.  */
6264       if (cu_bounds_kind <= PC_BOUNDS_INVALID)
6265         {
6266           best_lowpc = lowpc;
6267           best_highpc = highpc;
6268         }
6269     }
6270   pst->textlow = gdbarch_adjust_dwarf2_addr (gdbarch, best_lowpc + baseaddr);
6271   pst->texthigh = gdbarch_adjust_dwarf2_addr (gdbarch, best_highpc + baseaddr);
6272
6273   end_psymtab_common (objfile, pst);
6274
6275   if (!VEC_empty (dwarf2_per_cu_ptr, cu->per_cu->imported_symtabs))
6276     {
6277       int i;
6278       int len = VEC_length (dwarf2_per_cu_ptr, cu->per_cu->imported_symtabs);
6279       struct dwarf2_per_cu_data *iter;
6280
6281       /* Fill in 'dependencies' here; we fill in 'users' in a
6282          post-pass.  */
6283       pst->number_of_dependencies = len;
6284       pst->dependencies =
6285         XOBNEWVEC (&objfile->objfile_obstack, struct partial_symtab *, len);
6286       for (i = 0;
6287            VEC_iterate (dwarf2_per_cu_ptr, cu->per_cu->imported_symtabs,
6288                         i, iter);
6289            ++i)
6290         pst->dependencies[i] = iter->v.psymtab;
6291
6292       VEC_free (dwarf2_per_cu_ptr, cu->per_cu->imported_symtabs);
6293     }
6294
6295   /* Get the list of files included in the current compilation unit,
6296      and build a psymtab for each of them.  */
6297   dwarf2_build_include_psymtabs (cu, comp_unit_die, pst);
6298
6299   if (dwarf_read_debug)
6300     {
6301       struct gdbarch *gdbarch = get_objfile_arch (objfile);
6302
6303       fprintf_unfiltered (gdb_stdlog,
6304                           "Psymtab for %s unit @0x%x: %s - %s"
6305                           ", %d global, %d static syms\n",
6306                           per_cu->is_debug_types ? "type" : "comp",
6307                           to_underlying (per_cu->sect_off),
6308                           paddress (gdbarch, pst->textlow),
6309                           paddress (gdbarch, pst->texthigh),
6310                           pst->n_global_syms, pst->n_static_syms);
6311     }
6312 }
6313
6314 /* Subroutine of dwarf2_build_psymtabs_hard to simplify it.
6315    Process compilation unit THIS_CU for a psymtab.  */
6316
6317 static void
6318 process_psymtab_comp_unit (struct dwarf2_per_cu_data *this_cu,
6319                            int want_partial_unit,
6320                            enum language pretend_language)
6321 {
6322   struct process_psymtab_comp_unit_data info;
6323
6324   /* If this compilation unit was already read in, free the
6325      cached copy in order to read it in again.  This is
6326      necessary because we skipped some symbols when we first
6327      read in the compilation unit (see load_partial_dies).
6328      This problem could be avoided, but the benefit is unclear.  */
6329   if (this_cu->cu != NULL)
6330     free_one_cached_comp_unit (this_cu);
6331
6332   gdb_assert (! this_cu->is_debug_types);
6333   info.want_partial_unit = want_partial_unit;
6334   info.pretend_language = pretend_language;
6335   init_cutu_and_read_dies (this_cu, NULL, 0, 0,
6336                            process_psymtab_comp_unit_reader,
6337                            &info);
6338
6339   /* Age out any secondary CUs.  */
6340   age_cached_comp_units ();
6341 }
6342
6343 /* Reader function for build_type_psymtabs.  */
6344
6345 static void
6346 build_type_psymtabs_reader (const struct die_reader_specs *reader,
6347                             const gdb_byte *info_ptr,
6348                             struct die_info *type_unit_die,
6349                             int has_children,
6350                             void *data)
6351 {
6352   struct objfile *objfile = dwarf2_per_objfile->objfile;
6353   struct dwarf2_cu *cu = reader->cu;
6354   struct dwarf2_per_cu_data *per_cu = cu->per_cu;
6355   struct signatured_type *sig_type;
6356   struct type_unit_group *tu_group;
6357   struct attribute *attr;
6358   struct partial_die_info *first_die;
6359   CORE_ADDR lowpc, highpc;
6360   struct partial_symtab *pst;
6361
6362   gdb_assert (data == NULL);
6363   gdb_assert (per_cu->is_debug_types);
6364   sig_type = (struct signatured_type *) per_cu;
6365
6366   if (! has_children)
6367     return;
6368
6369   attr = dwarf2_attr_no_follow (type_unit_die, DW_AT_stmt_list);
6370   tu_group = get_type_unit_group (cu, attr);
6371
6372   VEC_safe_push (sig_type_ptr, tu_group->tus, sig_type);
6373
6374   prepare_one_comp_unit (cu, type_unit_die, language_minimal);
6375   cu->list_in_scope = &file_symbols;
6376   pst = create_partial_symtab (per_cu, "");
6377   pst->anonymous = 1;
6378
6379   first_die = load_partial_dies (reader, info_ptr, 1);
6380
6381   lowpc = (CORE_ADDR) -1;
6382   highpc = (CORE_ADDR) 0;
6383   scan_partial_symbols (first_die, &lowpc, &highpc, 0, cu);
6384
6385   end_psymtab_common (objfile, pst);
6386 }
6387
6388 /* Struct used to sort TUs by their abbreviation table offset.  */
6389
6390 struct tu_abbrev_offset
6391 {
6392   struct signatured_type *sig_type;
6393   sect_offset abbrev_offset;
6394 };
6395
6396 /* Helper routine for build_type_psymtabs_1, passed to qsort.  */
6397
6398 static int
6399 sort_tu_by_abbrev_offset (const void *ap, const void *bp)
6400 {
6401   const struct tu_abbrev_offset * const *a
6402     = (const struct tu_abbrev_offset * const*) ap;
6403   const struct tu_abbrev_offset * const *b
6404     = (const struct tu_abbrev_offset * const*) bp;
6405   sect_offset aoff = (*a)->abbrev_offset;
6406   sect_offset boff = (*b)->abbrev_offset;
6407
6408   return (aoff > boff) - (aoff < boff);
6409 }
6410
6411 /* Efficiently read all the type units.
6412    This does the bulk of the work for build_type_psymtabs.
6413
6414    The efficiency is because we sort TUs by the abbrev table they use and
6415    only read each abbrev table once.  In one program there are 200K TUs
6416    sharing 8K abbrev tables.
6417
6418    The main purpose of this function is to support building the
6419    dwarf2_per_objfile->type_unit_groups table.
6420    TUs typically share the DW_AT_stmt_list of the CU they came from, so we
6421    can collapse the search space by grouping them by stmt_list.
6422    The savings can be significant, in the same program from above the 200K TUs
6423    share 8K stmt_list tables.
6424
6425    FUNC is expected to call get_type_unit_group, which will create the
6426    struct type_unit_group if necessary and add it to
6427    dwarf2_per_objfile->type_unit_groups.  */
6428
6429 static void
6430 build_type_psymtabs_1 (void)
6431 {
6432   struct tu_stats *tu_stats = &dwarf2_per_objfile->tu_stats;
6433   struct cleanup *cleanups;
6434   struct abbrev_table *abbrev_table;
6435   sect_offset abbrev_offset;
6436   struct tu_abbrev_offset *sorted_by_abbrev;
6437   int i;
6438
6439   /* It's up to the caller to not call us multiple times.  */
6440   gdb_assert (dwarf2_per_objfile->type_unit_groups == NULL);
6441
6442   if (dwarf2_per_objfile->n_type_units == 0)
6443     return;
6444
6445   /* TUs typically share abbrev tables, and there can be way more TUs than
6446      abbrev tables.  Sort by abbrev table to reduce the number of times we
6447      read each abbrev table in.
6448      Alternatives are to punt or to maintain a cache of abbrev tables.
6449      This is simpler and efficient enough for now.
6450
6451      Later we group TUs by their DW_AT_stmt_list value (as this defines the
6452      symtab to use).  Typically TUs with the same abbrev offset have the same
6453      stmt_list value too so in practice this should work well.
6454
6455      The basic algorithm here is:
6456
6457       sort TUs by abbrev table
6458       for each TU with same abbrev table:
6459         read abbrev table if first user
6460         read TU top level DIE
6461           [IWBN if DWO skeletons had DW_AT_stmt_list]
6462         call FUNC  */
6463
6464   if (dwarf_read_debug)
6465     fprintf_unfiltered (gdb_stdlog, "Building type unit groups ...\n");
6466
6467   /* Sort in a separate table to maintain the order of all_type_units
6468      for .gdb_index: TU indices directly index all_type_units.  */
6469   sorted_by_abbrev = XNEWVEC (struct tu_abbrev_offset,
6470                               dwarf2_per_objfile->n_type_units);
6471   for (i = 0; i < dwarf2_per_objfile->n_type_units; ++i)
6472     {
6473       struct signatured_type *sig_type = dwarf2_per_objfile->all_type_units[i];
6474
6475       sorted_by_abbrev[i].sig_type = sig_type;
6476       sorted_by_abbrev[i].abbrev_offset =
6477         read_abbrev_offset (sig_type->per_cu.section,
6478                             sig_type->per_cu.sect_off);
6479     }
6480   cleanups = make_cleanup (xfree, sorted_by_abbrev);
6481   qsort (sorted_by_abbrev, dwarf2_per_objfile->n_type_units,
6482          sizeof (struct tu_abbrev_offset), sort_tu_by_abbrev_offset);
6483
6484   abbrev_offset = (sect_offset) ~(unsigned) 0;
6485   abbrev_table = NULL;
6486   make_cleanup (abbrev_table_free_cleanup, &abbrev_table);
6487
6488   for (i = 0; i < dwarf2_per_objfile->n_type_units; ++i)
6489     {
6490       const struct tu_abbrev_offset *tu = &sorted_by_abbrev[i];
6491
6492       /* Switch to the next abbrev table if necessary.  */
6493       if (abbrev_table == NULL
6494           || tu->abbrev_offset != abbrev_offset)
6495         {
6496           if (abbrev_table != NULL)
6497             {
6498               abbrev_table_free (abbrev_table);
6499               /* Reset to NULL in case abbrev_table_read_table throws
6500                  an error: abbrev_table_free_cleanup will get called.  */
6501               abbrev_table = NULL;
6502             }
6503           abbrev_offset = tu->abbrev_offset;
6504           abbrev_table =
6505             abbrev_table_read_table (&dwarf2_per_objfile->abbrev,
6506                                      abbrev_offset);
6507           ++tu_stats->nr_uniq_abbrev_tables;
6508         }
6509
6510       init_cutu_and_read_dies (&tu->sig_type->per_cu, abbrev_table, 0, 0,
6511                                build_type_psymtabs_reader, NULL);
6512     }
6513
6514   do_cleanups (cleanups);
6515 }
6516
6517 /* Print collected type unit statistics.  */
6518
6519 static void
6520 print_tu_stats (void)
6521 {
6522   struct tu_stats *tu_stats = &dwarf2_per_objfile->tu_stats;
6523
6524   fprintf_unfiltered (gdb_stdlog, "Type unit statistics:\n");
6525   fprintf_unfiltered (gdb_stdlog, "  %d TUs\n",
6526                       dwarf2_per_objfile->n_type_units);
6527   fprintf_unfiltered (gdb_stdlog, "  %d uniq abbrev tables\n",
6528                       tu_stats->nr_uniq_abbrev_tables);
6529   fprintf_unfiltered (gdb_stdlog, "  %d symtabs from stmt_list entries\n",
6530                       tu_stats->nr_symtabs);
6531   fprintf_unfiltered (gdb_stdlog, "  %d symtab sharers\n",
6532                       tu_stats->nr_symtab_sharers);
6533   fprintf_unfiltered (gdb_stdlog, "  %d type units without a stmt_list\n",
6534                       tu_stats->nr_stmt_less_type_units);
6535   fprintf_unfiltered (gdb_stdlog, "  %d all_type_units reallocs\n",
6536                       tu_stats->nr_all_type_units_reallocs);
6537 }
6538
6539 /* Traversal function for build_type_psymtabs.  */
6540
6541 static int
6542 build_type_psymtab_dependencies (void **slot, void *info)
6543 {
6544   struct objfile *objfile = dwarf2_per_objfile->objfile;
6545   struct type_unit_group *tu_group = (struct type_unit_group *) *slot;
6546   struct dwarf2_per_cu_data *per_cu = &tu_group->per_cu;
6547   struct partial_symtab *pst = per_cu->v.psymtab;
6548   int len = VEC_length (sig_type_ptr, tu_group->tus);
6549   struct signatured_type *iter;
6550   int i;
6551
6552   gdb_assert (len > 0);
6553   gdb_assert (IS_TYPE_UNIT_GROUP (per_cu));
6554
6555   pst->number_of_dependencies = len;
6556   pst->dependencies =
6557     XOBNEWVEC (&objfile->objfile_obstack, struct partial_symtab *, len);
6558   for (i = 0;
6559        VEC_iterate (sig_type_ptr, tu_group->tus, i, iter);
6560        ++i)
6561     {
6562       gdb_assert (iter->per_cu.is_debug_types);
6563       pst->dependencies[i] = iter->per_cu.v.psymtab;
6564       iter->type_unit_group = tu_group;
6565     }
6566
6567   VEC_free (sig_type_ptr, tu_group->tus);
6568
6569   return 1;
6570 }
6571
6572 /* Subroutine of dwarf2_build_psymtabs_hard to simplify it.
6573    Build partial symbol tables for the .debug_types comp-units.  */
6574
6575 static void
6576 build_type_psymtabs (struct objfile *objfile)
6577 {
6578   if (! create_all_type_units (objfile))
6579     return;
6580
6581   build_type_psymtabs_1 ();
6582 }
6583
6584 /* Traversal function for process_skeletonless_type_unit.
6585    Read a TU in a DWO file and build partial symbols for it.  */
6586
6587 static int
6588 process_skeletonless_type_unit (void **slot, void *info)
6589 {
6590   struct dwo_unit *dwo_unit = (struct dwo_unit *) *slot;
6591   struct objfile *objfile = (struct objfile *) info;
6592   struct signatured_type find_entry, *entry;
6593
6594   /* If this TU doesn't exist in the global table, add it and read it in.  */
6595
6596   if (dwarf2_per_objfile->signatured_types == NULL)
6597     {
6598       dwarf2_per_objfile->signatured_types
6599         = allocate_signatured_type_table (objfile);
6600     }
6601
6602   find_entry.signature = dwo_unit->signature;
6603   slot = htab_find_slot (dwarf2_per_objfile->signatured_types, &find_entry,
6604                          INSERT);
6605   /* If we've already seen this type there's nothing to do.  What's happening
6606      is we're doing our own version of comdat-folding here.  */
6607   if (*slot != NULL)
6608     return 1;
6609
6610   /* This does the job that create_all_type_units would have done for
6611      this TU.  */
6612   entry = add_type_unit (dwo_unit->signature, slot);
6613   fill_in_sig_entry_from_dwo_entry (objfile, entry, dwo_unit);
6614   *slot = entry;
6615
6616   /* This does the job that build_type_psymtabs_1 would have done.  */
6617   init_cutu_and_read_dies (&entry->per_cu, NULL, 0, 0,
6618                            build_type_psymtabs_reader, NULL);
6619
6620   return 1;
6621 }
6622
6623 /* Traversal function for process_skeletonless_type_units.  */
6624
6625 static int
6626 process_dwo_file_for_skeletonless_type_units (void **slot, void *info)
6627 {
6628   struct dwo_file *dwo_file = (struct dwo_file *) *slot;
6629
6630   if (dwo_file->tus != NULL)
6631     {
6632       htab_traverse_noresize (dwo_file->tus,
6633                               process_skeletonless_type_unit, info);
6634     }
6635
6636   return 1;
6637 }
6638
6639 /* Scan all TUs of DWO files, verifying we've processed them.
6640    This is needed in case a TU was emitted without its skeleton.
6641    Note: This can't be done until we know what all the DWO files are.  */
6642
6643 static void
6644 process_skeletonless_type_units (struct objfile *objfile)
6645 {
6646   /* Skeletonless TUs in DWP files without .gdb_index is not supported yet.  */
6647   if (get_dwp_file () == NULL
6648       && dwarf2_per_objfile->dwo_files != NULL)
6649     {
6650       htab_traverse_noresize (dwarf2_per_objfile->dwo_files,
6651                               process_dwo_file_for_skeletonless_type_units,
6652                               objfile);
6653     }
6654 }
6655
6656 /* A cleanup function that clears objfile's psymtabs_addrmap field.  */
6657
6658 static void
6659 psymtabs_addrmap_cleanup (void *o)
6660 {
6661   struct objfile *objfile = (struct objfile *) o;
6662
6663   objfile->psymtabs_addrmap = NULL;
6664 }
6665
6666 /* Compute the 'user' field for each psymtab in OBJFILE.  */
6667
6668 static void
6669 set_partial_user (struct objfile *objfile)
6670 {
6671   int i;
6672
6673   for (i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
6674     {
6675       struct dwarf2_per_cu_data *per_cu = dw2_get_cutu (i);
6676       struct partial_symtab *pst = per_cu->v.psymtab;
6677       int j;
6678
6679       if (pst == NULL)
6680         continue;
6681
6682       for (j = 0; j < pst->number_of_dependencies; ++j)
6683         {
6684           /* Set the 'user' field only if it is not already set.  */
6685           if (pst->dependencies[j]->user == NULL)
6686             pst->dependencies[j]->user = pst;
6687         }
6688     }
6689 }
6690
6691 /* Build the partial symbol table by doing a quick pass through the
6692    .debug_info and .debug_abbrev sections.  */
6693
6694 static void
6695 dwarf2_build_psymtabs_hard (struct objfile *objfile)
6696 {
6697   struct cleanup *back_to, *addrmap_cleanup;
6698   int i;
6699
6700   if (dwarf_read_debug)
6701     {
6702       fprintf_unfiltered (gdb_stdlog, "Building psymtabs of objfile %s ...\n",
6703                           objfile_name (objfile));
6704     }
6705
6706   dwarf2_per_objfile->reading_partial_symbols = 1;
6707
6708   dwarf2_read_section (objfile, &dwarf2_per_objfile->info);
6709
6710   /* Any cached compilation units will be linked by the per-objfile
6711      read_in_chain.  Make sure to free them when we're done.  */
6712   back_to = make_cleanup (free_cached_comp_units, NULL);
6713
6714   build_type_psymtabs (objfile);
6715
6716   create_all_comp_units (objfile);
6717
6718   /* Create a temporary address map on a temporary obstack.  We later
6719      copy this to the final obstack.  */
6720   auto_obstack temp_obstack;
6721   objfile->psymtabs_addrmap = addrmap_create_mutable (&temp_obstack);
6722   addrmap_cleanup = make_cleanup (psymtabs_addrmap_cleanup, objfile);
6723
6724   for (i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
6725     {
6726       struct dwarf2_per_cu_data *per_cu = dw2_get_cutu (i);
6727
6728       process_psymtab_comp_unit (per_cu, 0, language_minimal);
6729     }
6730
6731   /* This has to wait until we read the CUs, we need the list of DWOs.  */
6732   process_skeletonless_type_units (objfile);
6733
6734   /* Now that all TUs have been processed we can fill in the dependencies.  */
6735   if (dwarf2_per_objfile->type_unit_groups != NULL)
6736     {
6737       htab_traverse_noresize (dwarf2_per_objfile->type_unit_groups,
6738                               build_type_psymtab_dependencies, NULL);
6739     }
6740
6741   if (dwarf_read_debug)
6742     print_tu_stats ();
6743
6744   set_partial_user (objfile);
6745
6746   objfile->psymtabs_addrmap = addrmap_create_fixed (objfile->psymtabs_addrmap,
6747                                                     &objfile->objfile_obstack);
6748   discard_cleanups (addrmap_cleanup);
6749
6750   do_cleanups (back_to);
6751
6752   if (dwarf_read_debug)
6753     fprintf_unfiltered (gdb_stdlog, "Done building psymtabs of %s\n",
6754                         objfile_name (objfile));
6755 }
6756
6757 /* die_reader_func for load_partial_comp_unit.  */
6758
6759 static void
6760 load_partial_comp_unit_reader (const struct die_reader_specs *reader,
6761                                const gdb_byte *info_ptr,
6762                                struct die_info *comp_unit_die,
6763                                int has_children,
6764                                void *data)
6765 {
6766   struct dwarf2_cu *cu = reader->cu;
6767
6768   prepare_one_comp_unit (cu, comp_unit_die, language_minimal);
6769
6770   /* Check if comp unit has_children.
6771      If so, read the rest of the partial symbols from this comp unit.
6772      If not, there's no more debug_info for this comp unit.  */
6773   if (has_children)
6774     load_partial_dies (reader, info_ptr, 0);
6775 }
6776
6777 /* Load the partial DIEs for a secondary CU into memory.
6778    This is also used when rereading a primary CU with load_all_dies.  */
6779
6780 static void
6781 load_partial_comp_unit (struct dwarf2_per_cu_data *this_cu)
6782 {
6783   init_cutu_and_read_dies (this_cu, NULL, 1, 1,
6784                            load_partial_comp_unit_reader, NULL);
6785 }
6786
6787 static void
6788 read_comp_units_from_section (struct objfile *objfile,
6789                               struct dwarf2_section_info *section,
6790                               unsigned int is_dwz,
6791                               int *n_allocated,
6792                               int *n_comp_units,
6793                               struct dwarf2_per_cu_data ***all_comp_units)
6794 {
6795   const gdb_byte *info_ptr;
6796   bfd *abfd = get_section_bfd_owner (section);
6797
6798   if (dwarf_read_debug)
6799     fprintf_unfiltered (gdb_stdlog, "Reading %s for %s\n",
6800                         get_section_name (section),
6801                         get_section_file_name (section));
6802
6803   dwarf2_read_section (objfile, section);
6804
6805   info_ptr = section->buffer;
6806
6807   while (info_ptr < section->buffer + section->size)
6808     {
6809       unsigned int length, initial_length_size;
6810       struct dwarf2_per_cu_data *this_cu;
6811
6812       sect_offset sect_off = (sect_offset) (info_ptr - section->buffer);
6813
6814       /* Read just enough information to find out where the next
6815          compilation unit is.  */
6816       length = read_initial_length (abfd, info_ptr, &initial_length_size);
6817
6818       /* Save the compilation unit for later lookup.  */
6819       this_cu = XOBNEW (&objfile->objfile_obstack, struct dwarf2_per_cu_data);
6820       memset (this_cu, 0, sizeof (*this_cu));
6821       this_cu->sect_off = sect_off;
6822       this_cu->length = length + initial_length_size;
6823       this_cu->is_dwz = is_dwz;
6824       this_cu->objfile = objfile;
6825       this_cu->section = section;
6826
6827       if (*n_comp_units == *n_allocated)
6828         {
6829           *n_allocated *= 2;
6830           *all_comp_units = XRESIZEVEC (struct dwarf2_per_cu_data *,
6831                                         *all_comp_units, *n_allocated);
6832         }
6833       (*all_comp_units)[*n_comp_units] = this_cu;
6834       ++*n_comp_units;
6835
6836       info_ptr = info_ptr + this_cu->length;
6837     }
6838 }
6839
6840 /* Create a list of all compilation units in OBJFILE.
6841    This is only done for -readnow and building partial symtabs.  */
6842
6843 static void
6844 create_all_comp_units (struct objfile *objfile)
6845 {
6846   int n_allocated;
6847   int n_comp_units;
6848   struct dwarf2_per_cu_data **all_comp_units;
6849   struct dwz_file *dwz;
6850
6851   n_comp_units = 0;
6852   n_allocated = 10;
6853   all_comp_units = XNEWVEC (struct dwarf2_per_cu_data *, n_allocated);
6854
6855   read_comp_units_from_section (objfile, &dwarf2_per_objfile->info, 0,
6856                                 &n_allocated, &n_comp_units, &all_comp_units);
6857
6858   dwz = dwarf2_get_dwz_file ();
6859   if (dwz != NULL)
6860     read_comp_units_from_section (objfile, &dwz->info, 1,
6861                                   &n_allocated, &n_comp_units,
6862                                   &all_comp_units);
6863
6864   dwarf2_per_objfile->all_comp_units = XOBNEWVEC (&objfile->objfile_obstack,
6865                                                   struct dwarf2_per_cu_data *,
6866                                                   n_comp_units);
6867   memcpy (dwarf2_per_objfile->all_comp_units, all_comp_units,
6868           n_comp_units * sizeof (struct dwarf2_per_cu_data *));
6869   xfree (all_comp_units);
6870   dwarf2_per_objfile->n_comp_units = n_comp_units;
6871 }
6872
6873 /* Process all loaded DIEs for compilation unit CU, starting at
6874    FIRST_DIE.  The caller should pass SET_ADDRMAP == 1 if the compilation
6875    unit DIE did not have PC info (DW_AT_low_pc and DW_AT_high_pc, or
6876    DW_AT_ranges).  See the comments of add_partial_subprogram on how
6877    SET_ADDRMAP is used and how *LOWPC and *HIGHPC are updated.  */
6878
6879 static void
6880 scan_partial_symbols (struct partial_die_info *first_die, CORE_ADDR *lowpc,
6881                       CORE_ADDR *highpc, int set_addrmap,
6882                       struct dwarf2_cu *cu)
6883 {
6884   struct partial_die_info *pdi;
6885
6886   /* Now, march along the PDI's, descending into ones which have
6887      interesting children but skipping the children of the other ones,
6888      until we reach the end of the compilation unit.  */
6889
6890   pdi = first_die;
6891
6892   while (pdi != NULL)
6893     {
6894       fixup_partial_die (pdi, cu);
6895
6896       /* Anonymous namespaces or modules have no name but have interesting
6897          children, so we need to look at them.  Ditto for anonymous
6898          enums.  */
6899
6900       if (pdi->name != NULL || pdi->tag == DW_TAG_namespace
6901           || pdi->tag == DW_TAG_module || pdi->tag == DW_TAG_enumeration_type
6902           || pdi->tag == DW_TAG_imported_unit)
6903         {
6904           switch (pdi->tag)
6905             {
6906             case DW_TAG_subprogram:
6907               add_partial_subprogram (pdi, lowpc, highpc, set_addrmap, cu);
6908               break;
6909             case DW_TAG_constant:
6910             case DW_TAG_variable:
6911             case DW_TAG_typedef:
6912             case DW_TAG_union_type:
6913               if (!pdi->is_declaration)
6914                 {
6915                   add_partial_symbol (pdi, cu);
6916                 }
6917               break;
6918             case DW_TAG_class_type:
6919             case DW_TAG_interface_type:
6920             case DW_TAG_structure_type:
6921               if (!pdi->is_declaration)
6922                 {
6923                   add_partial_symbol (pdi, cu);
6924                 }
6925               if (cu->language == language_rust && pdi->has_children)
6926                 scan_partial_symbols (pdi->die_child, lowpc, highpc,
6927                                       set_addrmap, cu);
6928               break;
6929             case DW_TAG_enumeration_type:
6930               if (!pdi->is_declaration)
6931                 add_partial_enumeration (pdi, cu);
6932               break;
6933             case DW_TAG_base_type:
6934             case DW_TAG_subrange_type:
6935               /* File scope base type definitions are added to the partial
6936                  symbol table.  */
6937               add_partial_symbol (pdi, cu);
6938               break;
6939             case DW_TAG_namespace:
6940               add_partial_namespace (pdi, lowpc, highpc, set_addrmap, cu);
6941               break;
6942             case DW_TAG_module:
6943               add_partial_module (pdi, lowpc, highpc, set_addrmap, cu);
6944               break;
6945             case DW_TAG_imported_unit:
6946               {
6947                 struct dwarf2_per_cu_data *per_cu;
6948
6949                 /* For now we don't handle imported units in type units.  */
6950                 if (cu->per_cu->is_debug_types)
6951                   {
6952                     error (_("Dwarf Error: DW_TAG_imported_unit is not"
6953                              " supported in type units [in module %s]"),
6954                            objfile_name (cu->objfile));
6955                   }
6956
6957                 per_cu = dwarf2_find_containing_comp_unit (pdi->d.sect_off,
6958                                                            pdi->is_dwz,
6959                                                            cu->objfile);
6960
6961                 /* Go read the partial unit, if needed.  */
6962                 if (per_cu->v.psymtab == NULL)
6963                   process_psymtab_comp_unit (per_cu, 1, cu->language);
6964
6965                 VEC_safe_push (dwarf2_per_cu_ptr,
6966                                cu->per_cu->imported_symtabs, per_cu);
6967               }
6968               break;
6969             case DW_TAG_imported_declaration:
6970               add_partial_symbol (pdi, cu);
6971               break;
6972             default:
6973               break;
6974             }
6975         }
6976
6977       /* If the die has a sibling, skip to the sibling.  */
6978
6979       pdi = pdi->die_sibling;
6980     }
6981 }
6982
6983 /* Functions used to compute the fully scoped name of a partial DIE.
6984
6985    Normally, this is simple.  For C++, the parent DIE's fully scoped
6986    name is concatenated with "::" and the partial DIE's name.
6987    Enumerators are an exception; they use the scope of their parent
6988    enumeration type, i.e. the name of the enumeration type is not
6989    prepended to the enumerator.
6990
6991    There are two complexities.  One is DW_AT_specification; in this
6992    case "parent" means the parent of the target of the specification,
6993    instead of the direct parent of the DIE.  The other is compilers
6994    which do not emit DW_TAG_namespace; in this case we try to guess
6995    the fully qualified name of structure types from their members'
6996    linkage names.  This must be done using the DIE's children rather
6997    than the children of any DW_AT_specification target.  We only need
6998    to do this for structures at the top level, i.e. if the target of
6999    any DW_AT_specification (if any; otherwise the DIE itself) does not
7000    have a parent.  */
7001
7002 /* Compute the scope prefix associated with PDI's parent, in
7003    compilation unit CU.  The result will be allocated on CU's
7004    comp_unit_obstack, or a copy of the already allocated PDI->NAME
7005    field.  NULL is returned if no prefix is necessary.  */
7006 static const char *
7007 partial_die_parent_scope (struct partial_die_info *pdi,
7008                           struct dwarf2_cu *cu)
7009 {
7010   const char *grandparent_scope;
7011   struct partial_die_info *parent, *real_pdi;
7012
7013   /* We need to look at our parent DIE; if we have a DW_AT_specification,
7014      then this means the parent of the specification DIE.  */
7015
7016   real_pdi = pdi;
7017   while (real_pdi->has_specification)
7018     real_pdi = find_partial_die (real_pdi->spec_offset,
7019                                  real_pdi->spec_is_dwz, cu);
7020
7021   parent = real_pdi->die_parent;
7022   if (parent == NULL)
7023     return NULL;
7024
7025   if (parent->scope_set)
7026     return parent->scope;
7027
7028   fixup_partial_die (parent, cu);
7029
7030   grandparent_scope = partial_die_parent_scope (parent, cu);
7031
7032   /* GCC 4.0 and 4.1 had a bug (PR c++/28460) where they generated bogus
7033      DW_TAG_namespace DIEs with a name of "::" for the global namespace.
7034      Work around this problem here.  */
7035   if (cu->language == language_cplus
7036       && parent->tag == DW_TAG_namespace
7037       && strcmp (parent->name, "::") == 0
7038       && grandparent_scope == NULL)
7039     {
7040       parent->scope = NULL;
7041       parent->scope_set = 1;
7042       return NULL;
7043     }
7044
7045   if (pdi->tag == DW_TAG_enumerator)
7046     /* Enumerators should not get the name of the enumeration as a prefix.  */
7047     parent->scope = grandparent_scope;
7048   else if (parent->tag == DW_TAG_namespace
7049       || parent->tag == DW_TAG_module
7050       || parent->tag == DW_TAG_structure_type
7051       || parent->tag == DW_TAG_class_type
7052       || parent->tag == DW_TAG_interface_type
7053       || parent->tag == DW_TAG_union_type
7054       || parent->tag == DW_TAG_enumeration_type)
7055     {
7056       if (grandparent_scope == NULL)
7057         parent->scope = parent->name;
7058       else
7059         parent->scope = typename_concat (&cu->comp_unit_obstack,
7060                                          grandparent_scope,
7061                                          parent->name, 0, cu);
7062     }
7063   else
7064     {
7065       /* FIXME drow/2004-04-01: What should we be doing with
7066          function-local names?  For partial symbols, we should probably be
7067          ignoring them.  */
7068       complaint (&symfile_complaints,
7069                  _("unhandled containing DIE tag %d for DIE at %d"),
7070                  parent->tag, to_underlying (pdi->sect_off));
7071       parent->scope = grandparent_scope;
7072     }
7073
7074   parent->scope_set = 1;
7075   return parent->scope;
7076 }
7077
7078 /* Return the fully scoped name associated with PDI, from compilation unit
7079    CU.  The result will be allocated with malloc.  */
7080
7081 static char *
7082 partial_die_full_name (struct partial_die_info *pdi,
7083                        struct dwarf2_cu *cu)
7084 {
7085   const char *parent_scope;
7086
7087   /* If this is a template instantiation, we can not work out the
7088      template arguments from partial DIEs.  So, unfortunately, we have
7089      to go through the full DIEs.  At least any work we do building
7090      types here will be reused if full symbols are loaded later.  */
7091   if (pdi->has_template_arguments)
7092     {
7093       fixup_partial_die (pdi, cu);
7094
7095       if (pdi->name != NULL && strchr (pdi->name, '<') == NULL)
7096         {
7097           struct die_info *die;
7098           struct attribute attr;
7099           struct dwarf2_cu *ref_cu = cu;
7100
7101           /* DW_FORM_ref_addr is using section offset.  */
7102           attr.name = (enum dwarf_attribute) 0;
7103           attr.form = DW_FORM_ref_addr;
7104           attr.u.unsnd = to_underlying (pdi->sect_off);
7105           die = follow_die_ref (NULL, &attr, &ref_cu);
7106
7107           return xstrdup (dwarf2_full_name (NULL, die, ref_cu));
7108         }
7109     }
7110
7111   parent_scope = partial_die_parent_scope (pdi, cu);
7112   if (parent_scope == NULL)
7113     return NULL;
7114   else
7115     return typename_concat (NULL, parent_scope, pdi->name, 0, cu);
7116 }
7117
7118 static void
7119 add_partial_symbol (struct partial_die_info *pdi, struct dwarf2_cu *cu)
7120 {
7121   struct objfile *objfile = cu->objfile;
7122   struct gdbarch *gdbarch = get_objfile_arch (objfile);
7123   CORE_ADDR addr = 0;
7124   const char *actual_name = NULL;
7125   CORE_ADDR baseaddr;
7126   char *built_actual_name;
7127
7128   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
7129
7130   built_actual_name = partial_die_full_name (pdi, cu);
7131   if (built_actual_name != NULL)
7132     actual_name = built_actual_name;
7133
7134   if (actual_name == NULL)
7135     actual_name = pdi->name;
7136
7137   switch (pdi->tag)
7138     {
7139     case DW_TAG_subprogram:
7140       addr = gdbarch_adjust_dwarf2_addr (gdbarch, pdi->lowpc + baseaddr);
7141       if (pdi->is_external || cu->language == language_ada)
7142         {
7143           /* brobecker/2007-12-26: Normally, only "external" DIEs are part
7144              of the global scope.  But in Ada, we want to be able to access
7145              nested procedures globally.  So all Ada subprograms are stored
7146              in the global scope.  */
7147           add_psymbol_to_list (actual_name, strlen (actual_name),
7148                                built_actual_name != NULL,
7149                                VAR_DOMAIN, LOC_BLOCK,
7150                                &objfile->global_psymbols,
7151                                addr, cu->language, objfile);
7152         }
7153       else
7154         {
7155           add_psymbol_to_list (actual_name, strlen (actual_name),
7156                                built_actual_name != NULL,
7157                                VAR_DOMAIN, LOC_BLOCK,
7158                                &objfile->static_psymbols,
7159                                addr, cu->language, objfile);
7160         }
7161
7162       if (pdi->main_subprogram && actual_name != NULL)
7163         set_objfile_main_name (objfile, actual_name, cu->language);
7164       break;
7165     case DW_TAG_constant:
7166       {
7167         struct psymbol_allocation_list *list;
7168
7169         if (pdi->is_external)
7170           list = &objfile->global_psymbols;
7171         else
7172           list = &objfile->static_psymbols;
7173         add_psymbol_to_list (actual_name, strlen (actual_name),
7174                              built_actual_name != NULL, VAR_DOMAIN, LOC_STATIC,
7175                              list, 0, cu->language, objfile);
7176       }
7177       break;
7178     case DW_TAG_variable:
7179       if (pdi->d.locdesc)
7180         addr = decode_locdesc (pdi->d.locdesc, cu);
7181
7182       if (pdi->d.locdesc
7183           && addr == 0
7184           && !dwarf2_per_objfile->has_section_at_zero)
7185         {
7186           /* A global or static variable may also have been stripped
7187              out by the linker if unused, in which case its address
7188              will be nullified; do not add such variables into partial
7189              symbol table then.  */
7190         }
7191       else if (pdi->is_external)
7192         {
7193           /* Global Variable.
7194              Don't enter into the minimal symbol tables as there is
7195              a minimal symbol table entry from the ELF symbols already.
7196              Enter into partial symbol table if it has a location
7197              descriptor or a type.
7198              If the location descriptor is missing, new_symbol will create
7199              a LOC_UNRESOLVED symbol, the address of the variable will then
7200              be determined from the minimal symbol table whenever the variable
7201              is referenced.
7202              The address for the partial symbol table entry is not
7203              used by GDB, but it comes in handy for debugging partial symbol
7204              table building.  */
7205
7206           if (pdi->d.locdesc || pdi->has_type)
7207             add_psymbol_to_list (actual_name, strlen (actual_name),
7208                                  built_actual_name != NULL,
7209                                  VAR_DOMAIN, LOC_STATIC,
7210                                  &objfile->global_psymbols,
7211                                  addr + baseaddr,
7212                                  cu->language, objfile);
7213         }
7214       else
7215         {
7216           int has_loc = pdi->d.locdesc != NULL;
7217
7218           /* Static Variable.  Skip symbols whose value we cannot know (those
7219              without location descriptors or constant values).  */
7220           if (!has_loc && !pdi->has_const_value)
7221             {
7222               xfree (built_actual_name);
7223               return;
7224             }
7225
7226           add_psymbol_to_list (actual_name, strlen (actual_name),
7227                                built_actual_name != NULL,
7228                                VAR_DOMAIN, LOC_STATIC,
7229                                &objfile->static_psymbols,
7230                                has_loc ? addr + baseaddr : (CORE_ADDR) 0,
7231                                cu->language, objfile);
7232         }
7233       break;
7234     case DW_TAG_typedef:
7235     case DW_TAG_base_type:
7236     case DW_TAG_subrange_type:
7237       add_psymbol_to_list (actual_name, strlen (actual_name),
7238                            built_actual_name != NULL,
7239                            VAR_DOMAIN, LOC_TYPEDEF,
7240                            &objfile->static_psymbols,
7241                            0, cu->language, objfile);
7242       break;
7243     case DW_TAG_imported_declaration:
7244     case DW_TAG_namespace:
7245       add_psymbol_to_list (actual_name, strlen (actual_name),
7246                            built_actual_name != NULL,
7247                            VAR_DOMAIN, LOC_TYPEDEF,
7248                            &objfile->global_psymbols,
7249                            0, cu->language, objfile);
7250       break;
7251     case DW_TAG_module:
7252       add_psymbol_to_list (actual_name, strlen (actual_name),
7253                            built_actual_name != NULL,
7254                            MODULE_DOMAIN, LOC_TYPEDEF,
7255                            &objfile->global_psymbols,
7256                            0, cu->language, objfile);
7257       break;
7258     case DW_TAG_class_type:
7259     case DW_TAG_interface_type:
7260     case DW_TAG_structure_type:
7261     case DW_TAG_union_type:
7262     case DW_TAG_enumeration_type:
7263       /* Skip external references.  The DWARF standard says in the section
7264          about "Structure, Union, and Class Type Entries": "An incomplete
7265          structure, union or class type is represented by a structure,
7266          union or class entry that does not have a byte size attribute
7267          and that has a DW_AT_declaration attribute."  */
7268       if (!pdi->has_byte_size && pdi->is_declaration)
7269         {
7270           xfree (built_actual_name);
7271           return;
7272         }
7273
7274       /* NOTE: carlton/2003-10-07: See comment in new_symbol about
7275          static vs. global.  */
7276       add_psymbol_to_list (actual_name, strlen (actual_name),
7277                            built_actual_name != NULL,
7278                            STRUCT_DOMAIN, LOC_TYPEDEF,
7279                            cu->language == language_cplus
7280                            ? &objfile->global_psymbols
7281                            : &objfile->static_psymbols,
7282                            0, cu->language, objfile);
7283
7284       break;
7285     case DW_TAG_enumerator:
7286       add_psymbol_to_list (actual_name, strlen (actual_name),
7287                            built_actual_name != NULL,
7288                            VAR_DOMAIN, LOC_CONST,
7289                            cu->language == language_cplus
7290                            ? &objfile->global_psymbols
7291                            : &objfile->static_psymbols,
7292                            0, cu->language, objfile);
7293       break;
7294     default:
7295       break;
7296     }
7297
7298   xfree (built_actual_name);
7299 }
7300
7301 /* Read a partial die corresponding to a namespace; also, add a symbol
7302    corresponding to that namespace to the symbol table.  NAMESPACE is
7303    the name of the enclosing namespace.  */
7304
7305 static void
7306 add_partial_namespace (struct partial_die_info *pdi,
7307                        CORE_ADDR *lowpc, CORE_ADDR *highpc,
7308                        int set_addrmap, struct dwarf2_cu *cu)
7309 {
7310   /* Add a symbol for the namespace.  */
7311
7312   add_partial_symbol (pdi, cu);
7313
7314   /* Now scan partial symbols in that namespace.  */
7315
7316   if (pdi->has_children)
7317     scan_partial_symbols (pdi->die_child, lowpc, highpc, set_addrmap, cu);
7318 }
7319
7320 /* Read a partial die corresponding to a Fortran module.  */
7321
7322 static void
7323 add_partial_module (struct partial_die_info *pdi, CORE_ADDR *lowpc,
7324                     CORE_ADDR *highpc, int set_addrmap, struct dwarf2_cu *cu)
7325 {
7326   /* Add a symbol for the namespace.  */
7327
7328   add_partial_symbol (pdi, cu);
7329
7330   /* Now scan partial symbols in that module.  */
7331
7332   if (pdi->has_children)
7333     scan_partial_symbols (pdi->die_child, lowpc, highpc, set_addrmap, cu);
7334 }
7335
7336 /* Read a partial die corresponding to a subprogram and create a partial
7337    symbol for that subprogram.  When the CU language allows it, this
7338    routine also defines a partial symbol for each nested subprogram
7339    that this subprogram contains.  If SET_ADDRMAP is true, record the
7340    covered ranges in the addrmap.  Set *LOWPC and *HIGHPC to the lowest
7341    and highest PC values found in PDI.
7342
7343    PDI may also be a lexical block, in which case we simply search
7344    recursively for subprograms defined inside that lexical block.
7345    Again, this is only performed when the CU language allows this
7346    type of definitions.  */
7347
7348 static void
7349 add_partial_subprogram (struct partial_die_info *pdi,
7350                         CORE_ADDR *lowpc, CORE_ADDR *highpc,
7351                         int set_addrmap, struct dwarf2_cu *cu)
7352 {
7353   if (pdi->tag == DW_TAG_subprogram)
7354     {
7355       if (pdi->has_pc_info)
7356         {
7357           if (pdi->lowpc < *lowpc)
7358             *lowpc = pdi->lowpc;
7359           if (pdi->highpc > *highpc)
7360             *highpc = pdi->highpc;
7361           if (set_addrmap)
7362             {
7363               struct objfile *objfile = cu->objfile;
7364               struct gdbarch *gdbarch = get_objfile_arch (objfile);
7365               CORE_ADDR baseaddr;
7366               CORE_ADDR highpc;
7367               CORE_ADDR lowpc;
7368
7369               baseaddr = ANOFFSET (objfile->section_offsets,
7370                                    SECT_OFF_TEXT (objfile));
7371               lowpc = gdbarch_adjust_dwarf2_addr (gdbarch,
7372                                                   pdi->lowpc + baseaddr);
7373               highpc = gdbarch_adjust_dwarf2_addr (gdbarch,
7374                                                    pdi->highpc + baseaddr);
7375               addrmap_set_empty (objfile->psymtabs_addrmap, lowpc, highpc - 1,
7376                                  cu->per_cu->v.psymtab);
7377             }
7378         }
7379
7380       if (pdi->has_pc_info || (!pdi->is_external && pdi->may_be_inlined))
7381         {
7382           if (!pdi->is_declaration)
7383             /* Ignore subprogram DIEs that do not have a name, they are
7384                illegal.  Do not emit a complaint at this point, we will
7385                do so when we convert this psymtab into a symtab.  */
7386             if (pdi->name)
7387               add_partial_symbol (pdi, cu);
7388         }
7389     }
7390
7391   if (! pdi->has_children)
7392     return;
7393
7394   if (cu->language == language_ada)
7395     {
7396       pdi = pdi->die_child;
7397       while (pdi != NULL)
7398         {
7399           fixup_partial_die (pdi, cu);
7400           if (pdi->tag == DW_TAG_subprogram
7401               || pdi->tag == DW_TAG_lexical_block)
7402             add_partial_subprogram (pdi, lowpc, highpc, set_addrmap, cu);
7403           pdi = pdi->die_sibling;
7404         }
7405     }
7406 }
7407
7408 /* Read a partial die corresponding to an enumeration type.  */
7409
7410 static void
7411 add_partial_enumeration (struct partial_die_info *enum_pdi,
7412                          struct dwarf2_cu *cu)
7413 {
7414   struct partial_die_info *pdi;
7415
7416   if (enum_pdi->name != NULL)
7417     add_partial_symbol (enum_pdi, cu);
7418
7419   pdi = enum_pdi->die_child;
7420   while (pdi)
7421     {
7422       if (pdi->tag != DW_TAG_enumerator || pdi->name == NULL)
7423         complaint (&symfile_complaints, _("malformed enumerator DIE ignored"));
7424       else
7425         add_partial_symbol (pdi, cu);
7426       pdi = pdi->die_sibling;
7427     }
7428 }
7429
7430 /* Return the initial uleb128 in the die at INFO_PTR.  */
7431
7432 static unsigned int
7433 peek_abbrev_code (bfd *abfd, const gdb_byte *info_ptr)
7434 {
7435   unsigned int bytes_read;
7436
7437   return read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
7438 }
7439
7440 /* Read the initial uleb128 in the die at INFO_PTR in compilation unit CU.
7441    Return the corresponding abbrev, or NULL if the number is zero (indicating
7442    an empty DIE).  In either case *BYTES_READ will be set to the length of
7443    the initial number.  */
7444
7445 static struct abbrev_info *
7446 peek_die_abbrev (const gdb_byte *info_ptr, unsigned int *bytes_read,
7447                  struct dwarf2_cu *cu)
7448 {
7449   bfd *abfd = cu->objfile->obfd;
7450   unsigned int abbrev_number;
7451   struct abbrev_info *abbrev;
7452
7453   abbrev_number = read_unsigned_leb128 (abfd, info_ptr, bytes_read);
7454
7455   if (abbrev_number == 0)
7456     return NULL;
7457
7458   abbrev = abbrev_table_lookup_abbrev (cu->abbrev_table, abbrev_number);
7459   if (!abbrev)
7460     {
7461       error (_("Dwarf Error: Could not find abbrev number %d in %s"
7462                " at offset 0x%x [in module %s]"),
7463              abbrev_number, cu->per_cu->is_debug_types ? "TU" : "CU",
7464              to_underlying (cu->header.sect_off), bfd_get_filename (abfd));
7465     }
7466
7467   return abbrev;
7468 }
7469
7470 /* Scan the debug information for CU starting at INFO_PTR in buffer BUFFER.
7471    Returns a pointer to the end of a series of DIEs, terminated by an empty
7472    DIE.  Any children of the skipped DIEs will also be skipped.  */
7473
7474 static const gdb_byte *
7475 skip_children (const struct die_reader_specs *reader, const gdb_byte *info_ptr)
7476 {
7477   struct dwarf2_cu *cu = reader->cu;
7478   struct abbrev_info *abbrev;
7479   unsigned int bytes_read;
7480
7481   while (1)
7482     {
7483       abbrev = peek_die_abbrev (info_ptr, &bytes_read, cu);
7484       if (abbrev == NULL)
7485         return info_ptr + bytes_read;
7486       else
7487         info_ptr = skip_one_die (reader, info_ptr + bytes_read, abbrev);
7488     }
7489 }
7490
7491 /* Scan the debug information for CU starting at INFO_PTR in buffer BUFFER.
7492    INFO_PTR should point just after the initial uleb128 of a DIE, and the
7493    abbrev corresponding to that skipped uleb128 should be passed in
7494    ABBREV.  Returns a pointer to this DIE's sibling, skipping any
7495    children.  */
7496
7497 static const gdb_byte *
7498 skip_one_die (const struct die_reader_specs *reader, const gdb_byte *info_ptr,
7499               struct abbrev_info *abbrev)
7500 {
7501   unsigned int bytes_read;
7502   struct attribute attr;
7503   bfd *abfd = reader->abfd;
7504   struct dwarf2_cu *cu = reader->cu;
7505   const gdb_byte *buffer = reader->buffer;
7506   const gdb_byte *buffer_end = reader->buffer_end;
7507   unsigned int form, i;
7508
7509   for (i = 0; i < abbrev->num_attrs; i++)
7510     {
7511       /* The only abbrev we care about is DW_AT_sibling.  */
7512       if (abbrev->attrs[i].name == DW_AT_sibling)
7513         {
7514           read_attribute (reader, &attr, &abbrev->attrs[i], info_ptr);
7515           if (attr.form == DW_FORM_ref_addr)
7516             complaint (&symfile_complaints,
7517                        _("ignoring absolute DW_AT_sibling"));
7518           else
7519             {
7520               sect_offset off = dwarf2_get_ref_die_offset (&attr);
7521               const gdb_byte *sibling_ptr = buffer + to_underlying (off);
7522
7523               if (sibling_ptr < info_ptr)
7524                 complaint (&symfile_complaints,
7525                            _("DW_AT_sibling points backwards"));
7526               else if (sibling_ptr > reader->buffer_end)
7527                 dwarf2_section_buffer_overflow_complaint (reader->die_section);
7528               else
7529                 return sibling_ptr;
7530             }
7531         }
7532
7533       /* If it isn't DW_AT_sibling, skip this attribute.  */
7534       form = abbrev->attrs[i].form;
7535     skip_attribute:
7536       switch (form)
7537         {
7538         case DW_FORM_ref_addr:
7539           /* In DWARF 2, DW_FORM_ref_addr is address sized; in DWARF 3
7540              and later it is offset sized.  */
7541           if (cu->header.version == 2)
7542             info_ptr += cu->header.addr_size;
7543           else
7544             info_ptr += cu->header.offset_size;
7545           break;
7546         case DW_FORM_GNU_ref_alt:
7547           info_ptr += cu->header.offset_size;
7548           break;
7549         case DW_FORM_addr:
7550           info_ptr += cu->header.addr_size;
7551           break;
7552         case DW_FORM_data1:
7553         case DW_FORM_ref1:
7554         case DW_FORM_flag:
7555           info_ptr += 1;
7556           break;
7557         case DW_FORM_flag_present:
7558         case DW_FORM_implicit_const:
7559           break;
7560         case DW_FORM_data2:
7561         case DW_FORM_ref2:
7562           info_ptr += 2;
7563           break;
7564         case DW_FORM_data4:
7565         case DW_FORM_ref4:
7566           info_ptr += 4;
7567           break;
7568         case DW_FORM_data8:
7569         case DW_FORM_ref8:
7570         case DW_FORM_ref_sig8:
7571           info_ptr += 8;
7572           break;
7573         case DW_FORM_data16:
7574           info_ptr += 16;
7575           break;
7576         case DW_FORM_string:
7577           read_direct_string (abfd, info_ptr, &bytes_read);
7578           info_ptr += bytes_read;
7579           break;
7580         case DW_FORM_sec_offset:
7581         case DW_FORM_strp:
7582         case DW_FORM_GNU_strp_alt:
7583           info_ptr += cu->header.offset_size;
7584           break;
7585         case DW_FORM_exprloc:
7586         case DW_FORM_block:
7587           info_ptr += read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
7588           info_ptr += bytes_read;
7589           break;
7590         case DW_FORM_block1:
7591           info_ptr += 1 + read_1_byte (abfd, info_ptr);
7592           break;
7593         case DW_FORM_block2:
7594           info_ptr += 2 + read_2_bytes (abfd, info_ptr);
7595           break;
7596         case DW_FORM_block4:
7597           info_ptr += 4 + read_4_bytes (abfd, info_ptr);
7598           break;
7599         case DW_FORM_sdata:
7600         case DW_FORM_udata:
7601         case DW_FORM_ref_udata:
7602         case DW_FORM_GNU_addr_index:
7603         case DW_FORM_GNU_str_index:
7604           info_ptr = safe_skip_leb128 (info_ptr, buffer_end);
7605           break;
7606         case DW_FORM_indirect:
7607           form = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
7608           info_ptr += bytes_read;
7609           /* We need to continue parsing from here, so just go back to
7610              the top.  */
7611           goto skip_attribute;
7612
7613         default:
7614           error (_("Dwarf Error: Cannot handle %s "
7615                    "in DWARF reader [in module %s]"),
7616                  dwarf_form_name (form),
7617                  bfd_get_filename (abfd));
7618         }
7619     }
7620
7621   if (abbrev->has_children)
7622     return skip_children (reader, info_ptr);
7623   else
7624     return info_ptr;
7625 }
7626
7627 /* Locate ORIG_PDI's sibling.
7628    INFO_PTR should point to the start of the next DIE after ORIG_PDI.  */
7629
7630 static const gdb_byte *
7631 locate_pdi_sibling (const struct die_reader_specs *reader,
7632                     struct partial_die_info *orig_pdi,
7633                     const gdb_byte *info_ptr)
7634 {
7635   /* Do we know the sibling already?  */
7636
7637   if (orig_pdi->sibling)
7638     return orig_pdi->sibling;
7639
7640   /* Are there any children to deal with?  */
7641
7642   if (!orig_pdi->has_children)
7643     return info_ptr;
7644
7645   /* Skip the children the long way.  */
7646
7647   return skip_children (reader, info_ptr);
7648 }
7649
7650 /* Expand this partial symbol table into a full symbol table.  SELF is
7651    not NULL.  */
7652
7653 static void
7654 dwarf2_read_symtab (struct partial_symtab *self,
7655                     struct objfile *objfile)
7656 {
7657   if (self->readin)
7658     {
7659       warning (_("bug: psymtab for %s is already read in."),
7660                self->filename);
7661     }
7662   else
7663     {
7664       if (info_verbose)
7665         {
7666           printf_filtered (_("Reading in symbols for %s..."),
7667                            self->filename);
7668           gdb_flush (gdb_stdout);
7669         }
7670
7671       /* Restore our global data.  */
7672       dwarf2_per_objfile
7673         = (struct dwarf2_per_objfile *) objfile_data (objfile,
7674                                                       dwarf2_objfile_data_key);
7675
7676       /* If this psymtab is constructed from a debug-only objfile, the
7677          has_section_at_zero flag will not necessarily be correct.  We
7678          can get the correct value for this flag by looking at the data
7679          associated with the (presumably stripped) associated objfile.  */
7680       if (objfile->separate_debug_objfile_backlink)
7681         {
7682           struct dwarf2_per_objfile *dpo_backlink
7683             = ((struct dwarf2_per_objfile *)
7684                objfile_data (objfile->separate_debug_objfile_backlink,
7685                              dwarf2_objfile_data_key));
7686
7687           dwarf2_per_objfile->has_section_at_zero
7688             = dpo_backlink->has_section_at_zero;
7689         }
7690
7691       dwarf2_per_objfile->reading_partial_symbols = 0;
7692
7693       psymtab_to_symtab_1 (self);
7694
7695       /* Finish up the debug error message.  */
7696       if (info_verbose)
7697         printf_filtered (_("done.\n"));
7698     }
7699
7700   process_cu_includes ();
7701 }
7702 \f
7703 /* Reading in full CUs.  */
7704
7705 /* Add PER_CU to the queue.  */
7706
7707 static void
7708 queue_comp_unit (struct dwarf2_per_cu_data *per_cu,
7709                  enum language pretend_language)
7710 {
7711   struct dwarf2_queue_item *item;
7712
7713   per_cu->queued = 1;
7714   item = XNEW (struct dwarf2_queue_item);
7715   item->per_cu = per_cu;
7716   item->pretend_language = pretend_language;
7717   item->next = NULL;
7718
7719   if (dwarf2_queue == NULL)
7720     dwarf2_queue = item;
7721   else
7722     dwarf2_queue_tail->next = item;
7723
7724   dwarf2_queue_tail = item;
7725 }
7726
7727 /* If PER_CU is not yet queued, add it to the queue.
7728    If DEPENDENT_CU is non-NULL, it has a reference to PER_CU so add a
7729    dependency.
7730    The result is non-zero if PER_CU was queued, otherwise the result is zero
7731    meaning either PER_CU is already queued or it is already loaded.
7732
7733    N.B. There is an invariant here that if a CU is queued then it is loaded.
7734    The caller is required to load PER_CU if we return non-zero.  */
7735
7736 static int
7737 maybe_queue_comp_unit (struct dwarf2_cu *dependent_cu,
7738                        struct dwarf2_per_cu_data *per_cu,
7739                        enum language pretend_language)
7740 {
7741   /* We may arrive here during partial symbol reading, if we need full
7742      DIEs to process an unusual case (e.g. template arguments).  Do
7743      not queue PER_CU, just tell our caller to load its DIEs.  */
7744   if (dwarf2_per_objfile->reading_partial_symbols)
7745     {
7746       if (per_cu->cu == NULL || per_cu->cu->dies == NULL)
7747         return 1;
7748       return 0;
7749     }
7750
7751   /* Mark the dependence relation so that we don't flush PER_CU
7752      too early.  */
7753   if (dependent_cu != NULL)
7754     dwarf2_add_dependence (dependent_cu, per_cu);
7755
7756   /* If it's already on the queue, we have nothing to do.  */
7757   if (per_cu->queued)
7758     return 0;
7759
7760   /* If the compilation unit is already loaded, just mark it as
7761      used.  */
7762   if (per_cu->cu != NULL)
7763     {
7764       per_cu->cu->last_used = 0;
7765       return 0;
7766     }
7767
7768   /* Add it to the queue.  */
7769   queue_comp_unit (per_cu, pretend_language);
7770
7771   return 1;
7772 }
7773
7774 /* Process the queue.  */
7775
7776 static void
7777 process_queue (void)
7778 {
7779   struct dwarf2_queue_item *item, *next_item;
7780
7781   if (dwarf_read_debug)
7782     {
7783       fprintf_unfiltered (gdb_stdlog,
7784                           "Expanding one or more symtabs of objfile %s ...\n",
7785                           objfile_name (dwarf2_per_objfile->objfile));
7786     }
7787
7788   /* The queue starts out with one item, but following a DIE reference
7789      may load a new CU, adding it to the end of the queue.  */
7790   for (item = dwarf2_queue; item != NULL; dwarf2_queue = item = next_item)
7791     {
7792       if ((dwarf2_per_objfile->using_index
7793            ? !item->per_cu->v.quick->compunit_symtab
7794            : (item->per_cu->v.psymtab && !item->per_cu->v.psymtab->readin))
7795           /* Skip dummy CUs.  */
7796           && item->per_cu->cu != NULL)
7797         {
7798           struct dwarf2_per_cu_data *per_cu = item->per_cu;
7799           unsigned int debug_print_threshold;
7800           char buf[100];
7801
7802           if (per_cu->is_debug_types)
7803             {
7804               struct signatured_type *sig_type =
7805                 (struct signatured_type *) per_cu;
7806
7807               sprintf (buf, "TU %s at offset 0x%x",
7808                        hex_string (sig_type->signature),
7809                        to_underlying (per_cu->sect_off));
7810               /* There can be 100s of TUs.
7811                  Only print them in verbose mode.  */
7812               debug_print_threshold = 2;
7813             }
7814           else
7815             {
7816               sprintf (buf, "CU at offset 0x%x",
7817                        to_underlying (per_cu->sect_off));
7818               debug_print_threshold = 1;
7819             }
7820
7821           if (dwarf_read_debug >= debug_print_threshold)
7822             fprintf_unfiltered (gdb_stdlog, "Expanding symtab of %s\n", buf);
7823
7824           if (per_cu->is_debug_types)
7825             process_full_type_unit (per_cu, item->pretend_language);
7826           else
7827             process_full_comp_unit (per_cu, item->pretend_language);
7828
7829           if (dwarf_read_debug >= debug_print_threshold)
7830             fprintf_unfiltered (gdb_stdlog, "Done expanding %s\n", buf);
7831         }
7832
7833       item->per_cu->queued = 0;
7834       next_item = item->next;
7835       xfree (item);
7836     }
7837
7838   dwarf2_queue_tail = NULL;
7839
7840   if (dwarf_read_debug)
7841     {
7842       fprintf_unfiltered (gdb_stdlog, "Done expanding symtabs of %s.\n",
7843                           objfile_name (dwarf2_per_objfile->objfile));
7844     }
7845 }
7846
7847 /* Free all allocated queue entries.  This function only releases anything if
7848    an error was thrown; if the queue was processed then it would have been
7849    freed as we went along.  */
7850
7851 static void
7852 dwarf2_release_queue (void *dummy)
7853 {
7854   struct dwarf2_queue_item *item, *last;
7855
7856   item = dwarf2_queue;
7857   while (item)
7858     {
7859       /* Anything still marked queued is likely to be in an
7860          inconsistent state, so discard it.  */
7861       if (item->per_cu->queued)
7862         {
7863           if (item->per_cu->cu != NULL)
7864             free_one_cached_comp_unit (item->per_cu);
7865           item->per_cu->queued = 0;
7866         }
7867
7868       last = item;
7869       item = item->next;
7870       xfree (last);
7871     }
7872
7873   dwarf2_queue = dwarf2_queue_tail = NULL;
7874 }
7875
7876 /* Read in full symbols for PST, and anything it depends on.  */
7877
7878 static void
7879 psymtab_to_symtab_1 (struct partial_symtab *pst)
7880 {
7881   struct dwarf2_per_cu_data *per_cu;
7882   int i;
7883
7884   if (pst->readin)
7885     return;
7886
7887   for (i = 0; i < pst->number_of_dependencies; i++)
7888     if (!pst->dependencies[i]->readin
7889         && pst->dependencies[i]->user == NULL)
7890       {
7891         /* Inform about additional files that need to be read in.  */
7892         if (info_verbose)
7893           {
7894             /* FIXME: i18n: Need to make this a single string.  */
7895             fputs_filtered (" ", gdb_stdout);
7896             wrap_here ("");
7897             fputs_filtered ("and ", gdb_stdout);
7898             wrap_here ("");
7899             printf_filtered ("%s...", pst->dependencies[i]->filename);
7900             wrap_here ("");     /* Flush output.  */
7901             gdb_flush (gdb_stdout);
7902           }
7903         psymtab_to_symtab_1 (pst->dependencies[i]);
7904       }
7905
7906   per_cu = (struct dwarf2_per_cu_data *) pst->read_symtab_private;
7907
7908   if (per_cu == NULL)
7909     {
7910       /* It's an include file, no symbols to read for it.
7911          Everything is in the parent symtab.  */
7912       pst->readin = 1;
7913       return;
7914     }
7915
7916   dw2_do_instantiate_symtab (per_cu);
7917 }
7918
7919 /* Trivial hash function for die_info: the hash value of a DIE
7920    is its offset in .debug_info for this objfile.  */
7921
7922 static hashval_t
7923 die_hash (const void *item)
7924 {
7925   const struct die_info *die = (const struct die_info *) item;
7926
7927   return to_underlying (die->sect_off);
7928 }
7929
7930 /* Trivial comparison function for die_info structures: two DIEs
7931    are equal if they have the same offset.  */
7932
7933 static int
7934 die_eq (const void *item_lhs, const void *item_rhs)
7935 {
7936   const struct die_info *die_lhs = (const struct die_info *) item_lhs;
7937   const struct die_info *die_rhs = (const struct die_info *) item_rhs;
7938
7939   return die_lhs->sect_off == die_rhs->sect_off;
7940 }
7941
7942 /* die_reader_func for load_full_comp_unit.
7943    This is identical to read_signatured_type_reader,
7944    but is kept separate for now.  */
7945
7946 static void
7947 load_full_comp_unit_reader (const struct die_reader_specs *reader,
7948                             const gdb_byte *info_ptr,
7949                             struct die_info *comp_unit_die,
7950                             int has_children,
7951                             void *data)
7952 {
7953   struct dwarf2_cu *cu = reader->cu;
7954   enum language *language_ptr = (enum language *) data;
7955
7956   gdb_assert (cu->die_hash == NULL);
7957   cu->die_hash =
7958     htab_create_alloc_ex (cu->header.length / 12,
7959                           die_hash,
7960                           die_eq,
7961                           NULL,
7962                           &cu->comp_unit_obstack,
7963                           hashtab_obstack_allocate,
7964                           dummy_obstack_deallocate);
7965
7966   if (has_children)
7967     comp_unit_die->child = read_die_and_siblings (reader, info_ptr,
7968                                                   &info_ptr, comp_unit_die);
7969   cu->dies = comp_unit_die;
7970   /* comp_unit_die is not stored in die_hash, no need.  */
7971
7972   /* We try not to read any attributes in this function, because not
7973      all CUs needed for references have been loaded yet, and symbol
7974      table processing isn't initialized.  But we have to set the CU language,
7975      or we won't be able to build types correctly.
7976      Similarly, if we do not read the producer, we can not apply
7977      producer-specific interpretation.  */
7978   prepare_one_comp_unit (cu, cu->dies, *language_ptr);
7979 }
7980
7981 /* Load the DIEs associated with PER_CU into memory.  */
7982
7983 static void
7984 load_full_comp_unit (struct dwarf2_per_cu_data *this_cu,
7985                      enum language pretend_language)
7986 {
7987   gdb_assert (! this_cu->is_debug_types);
7988
7989   init_cutu_and_read_dies (this_cu, NULL, 1, 1,
7990                            load_full_comp_unit_reader, &pretend_language);
7991 }
7992
7993 /* Add a DIE to the delayed physname list.  */
7994
7995 static void
7996 add_to_method_list (struct type *type, int fnfield_index, int index,
7997                     const char *name, struct die_info *die,
7998                     struct dwarf2_cu *cu)
7999 {
8000   struct delayed_method_info mi;
8001   mi.type = type;
8002   mi.fnfield_index = fnfield_index;
8003   mi.index = index;
8004   mi.name = name;
8005   mi.die = die;
8006   VEC_safe_push (delayed_method_info, cu->method_list, &mi);
8007 }
8008
8009 /* A cleanup for freeing the delayed method list.  */
8010
8011 static void
8012 free_delayed_list (void *ptr)
8013 {
8014   struct dwarf2_cu *cu = (struct dwarf2_cu *) ptr;
8015   if (cu->method_list != NULL)
8016     {
8017       VEC_free (delayed_method_info, cu->method_list);
8018       cu->method_list = NULL;
8019     }
8020 }
8021
8022 /* Compute the physnames of any methods on the CU's method list.
8023
8024    The computation of method physnames is delayed in order to avoid the
8025    (bad) condition that one of the method's formal parameters is of an as yet
8026    incomplete type.  */
8027
8028 static void
8029 compute_delayed_physnames (struct dwarf2_cu *cu)
8030 {
8031   int i;
8032   struct delayed_method_info *mi;
8033   for (i = 0; VEC_iterate (delayed_method_info, cu->method_list, i, mi) ; ++i)
8034     {
8035       const char *physname;
8036       struct fn_fieldlist *fn_flp
8037         = &TYPE_FN_FIELDLIST (mi->type, mi->fnfield_index);
8038       physname = dwarf2_physname (mi->name, mi->die, cu);
8039       TYPE_FN_FIELD_PHYSNAME (fn_flp->fn_fields, mi->index)
8040         = physname ? physname : "";
8041     }
8042 }
8043
8044 /* Go objects should be embedded in a DW_TAG_module DIE,
8045    and it's not clear if/how imported objects will appear.
8046    To keep Go support simple until that's worked out,
8047    go back through what we've read and create something usable.
8048    We could do this while processing each DIE, and feels kinda cleaner,
8049    but that way is more invasive.
8050    This is to, for example, allow the user to type "p var" or "b main"
8051    without having to specify the package name, and allow lookups
8052    of module.object to work in contexts that use the expression
8053    parser.  */
8054
8055 static void
8056 fixup_go_packaging (struct dwarf2_cu *cu)
8057 {
8058   char *package_name = NULL;
8059   struct pending *list;
8060   int i;
8061
8062   for (list = global_symbols; list != NULL; list = list->next)
8063     {
8064       for (i = 0; i < list->nsyms; ++i)
8065         {
8066           struct symbol *sym = list->symbol[i];
8067
8068           if (SYMBOL_LANGUAGE (sym) == language_go
8069               && SYMBOL_CLASS (sym) == LOC_BLOCK)
8070             {
8071               char *this_package_name = go_symbol_package_name (sym);
8072
8073               if (this_package_name == NULL)
8074                 continue;
8075               if (package_name == NULL)
8076                 package_name = this_package_name;
8077               else
8078                 {
8079                   if (strcmp (package_name, this_package_name) != 0)
8080                     complaint (&symfile_complaints,
8081                                _("Symtab %s has objects from two different Go packages: %s and %s"),
8082                                (symbol_symtab (sym) != NULL
8083                                 ? symtab_to_filename_for_display
8084                                     (symbol_symtab (sym))
8085                                 : objfile_name (cu->objfile)),
8086                                this_package_name, package_name);
8087                   xfree (this_package_name);
8088                 }
8089             }
8090         }
8091     }
8092
8093   if (package_name != NULL)
8094     {
8095       struct objfile *objfile = cu->objfile;
8096       const char *saved_package_name
8097         = (const char *) obstack_copy0 (&objfile->per_bfd->storage_obstack,
8098                                         package_name,
8099                                         strlen (package_name));
8100       struct type *type = init_type (objfile, TYPE_CODE_MODULE, 0,
8101                                      saved_package_name);
8102       struct symbol *sym;
8103
8104       TYPE_TAG_NAME (type) = TYPE_NAME (type);
8105
8106       sym = allocate_symbol (objfile);
8107       SYMBOL_SET_LANGUAGE (sym, language_go, &objfile->objfile_obstack);
8108       SYMBOL_SET_NAMES (sym, saved_package_name,
8109                         strlen (saved_package_name), 0, objfile);
8110       /* This is not VAR_DOMAIN because we want a way to ensure a lookup of,
8111          e.g., "main" finds the "main" module and not C's main().  */
8112       SYMBOL_DOMAIN (sym) = STRUCT_DOMAIN;
8113       SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
8114       SYMBOL_TYPE (sym) = type;
8115
8116       add_symbol_to_list (sym, &global_symbols);
8117
8118       xfree (package_name);
8119     }
8120 }
8121
8122 /* Return the symtab for PER_CU.  This works properly regardless of
8123    whether we're using the index or psymtabs.  */
8124
8125 static struct compunit_symtab *
8126 get_compunit_symtab (struct dwarf2_per_cu_data *per_cu)
8127 {
8128   return (dwarf2_per_objfile->using_index
8129           ? per_cu->v.quick->compunit_symtab
8130           : per_cu->v.psymtab->compunit_symtab);
8131 }
8132
8133 /* A helper function for computing the list of all symbol tables
8134    included by PER_CU.  */
8135
8136 static void
8137 recursively_compute_inclusions (VEC (compunit_symtab_ptr) **result,
8138                                 htab_t all_children, htab_t all_type_symtabs,
8139                                 struct dwarf2_per_cu_data *per_cu,
8140                                 struct compunit_symtab *immediate_parent)
8141 {
8142   void **slot;
8143   int ix;
8144   struct compunit_symtab *cust;
8145   struct dwarf2_per_cu_data *iter;
8146
8147   slot = htab_find_slot (all_children, per_cu, INSERT);
8148   if (*slot != NULL)
8149     {
8150       /* This inclusion and its children have been processed.  */
8151       return;
8152     }
8153
8154   *slot = per_cu;
8155   /* Only add a CU if it has a symbol table.  */
8156   cust = get_compunit_symtab (per_cu);
8157   if (cust != NULL)
8158     {
8159       /* If this is a type unit only add its symbol table if we haven't
8160          seen it yet (type unit per_cu's can share symtabs).  */
8161       if (per_cu->is_debug_types)
8162         {
8163           slot = htab_find_slot (all_type_symtabs, cust, INSERT);
8164           if (*slot == NULL)
8165             {
8166               *slot = cust;
8167               VEC_safe_push (compunit_symtab_ptr, *result, cust);
8168               if (cust->user == NULL)
8169                 cust->user = immediate_parent;
8170             }
8171         }
8172       else
8173         {
8174           VEC_safe_push (compunit_symtab_ptr, *result, cust);
8175           if (cust->user == NULL)
8176             cust->user = immediate_parent;
8177         }
8178     }
8179
8180   for (ix = 0;
8181        VEC_iterate (dwarf2_per_cu_ptr, per_cu->imported_symtabs, ix, iter);
8182        ++ix)
8183     {
8184       recursively_compute_inclusions (result, all_children,
8185                                       all_type_symtabs, iter, cust);
8186     }
8187 }
8188
8189 /* Compute the compunit_symtab 'includes' fields for the compunit_symtab of
8190    PER_CU.  */
8191
8192 static void
8193 compute_compunit_symtab_includes (struct dwarf2_per_cu_data *per_cu)
8194 {
8195   gdb_assert (! per_cu->is_debug_types);
8196
8197   if (!VEC_empty (dwarf2_per_cu_ptr, per_cu->imported_symtabs))
8198     {
8199       int ix, len;
8200       struct dwarf2_per_cu_data *per_cu_iter;
8201       struct compunit_symtab *compunit_symtab_iter;
8202       VEC (compunit_symtab_ptr) *result_symtabs = NULL;
8203       htab_t all_children, all_type_symtabs;
8204       struct compunit_symtab *cust = get_compunit_symtab (per_cu);
8205
8206       /* If we don't have a symtab, we can just skip this case.  */
8207       if (cust == NULL)
8208         return;
8209
8210       all_children = htab_create_alloc (1, htab_hash_pointer, htab_eq_pointer,
8211                                         NULL, xcalloc, xfree);
8212       all_type_symtabs = htab_create_alloc (1, htab_hash_pointer, htab_eq_pointer,
8213                                             NULL, xcalloc, xfree);
8214
8215       for (ix = 0;
8216            VEC_iterate (dwarf2_per_cu_ptr, per_cu->imported_symtabs,
8217                         ix, per_cu_iter);
8218            ++ix)
8219         {
8220           recursively_compute_inclusions (&result_symtabs, all_children,
8221                                           all_type_symtabs, per_cu_iter,
8222                                           cust);
8223         }
8224
8225       /* Now we have a transitive closure of all the included symtabs.  */
8226       len = VEC_length (compunit_symtab_ptr, result_symtabs);
8227       cust->includes
8228         = XOBNEWVEC (&dwarf2_per_objfile->objfile->objfile_obstack,
8229                      struct compunit_symtab *, len + 1);
8230       for (ix = 0;
8231            VEC_iterate (compunit_symtab_ptr, result_symtabs, ix,
8232                         compunit_symtab_iter);
8233            ++ix)
8234         cust->includes[ix] = compunit_symtab_iter;
8235       cust->includes[len] = NULL;
8236
8237       VEC_free (compunit_symtab_ptr, result_symtabs);
8238       htab_delete (all_children);
8239       htab_delete (all_type_symtabs);
8240     }
8241 }
8242
8243 /* Compute the 'includes' field for the symtabs of all the CUs we just
8244    read.  */
8245
8246 static void
8247 process_cu_includes (void)
8248 {
8249   int ix;
8250   struct dwarf2_per_cu_data *iter;
8251
8252   for (ix = 0;
8253        VEC_iterate (dwarf2_per_cu_ptr, dwarf2_per_objfile->just_read_cus,
8254                     ix, iter);
8255        ++ix)
8256     {
8257       if (! iter->is_debug_types)
8258         compute_compunit_symtab_includes (iter);
8259     }
8260
8261   VEC_free (dwarf2_per_cu_ptr, dwarf2_per_objfile->just_read_cus);
8262 }
8263
8264 /* Generate full symbol information for PER_CU, whose DIEs have
8265    already been loaded into memory.  */
8266
8267 static void
8268 process_full_comp_unit (struct dwarf2_per_cu_data *per_cu,
8269                         enum language pretend_language)
8270 {
8271   struct dwarf2_cu *cu = per_cu->cu;
8272   struct objfile *objfile = per_cu->objfile;
8273   struct gdbarch *gdbarch = get_objfile_arch (objfile);
8274   CORE_ADDR lowpc, highpc;
8275   struct compunit_symtab *cust;
8276   struct cleanup *back_to, *delayed_list_cleanup;
8277   CORE_ADDR baseaddr;
8278   struct block *static_block;
8279   CORE_ADDR addr;
8280
8281   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
8282
8283   buildsym_init ();
8284   back_to = make_cleanup (really_free_pendings, NULL);
8285   delayed_list_cleanup = make_cleanup (free_delayed_list, cu);
8286
8287   cu->list_in_scope = &file_symbols;
8288
8289   cu->language = pretend_language;
8290   cu->language_defn = language_def (cu->language);
8291
8292   /* Do line number decoding in read_file_scope () */
8293   process_die (cu->dies, cu);
8294
8295   /* For now fudge the Go package.  */
8296   if (cu->language == language_go)
8297     fixup_go_packaging (cu);
8298
8299   /* Now that we have processed all the DIEs in the CU, all the types 
8300      should be complete, and it should now be safe to compute all of the
8301      physnames.  */
8302   compute_delayed_physnames (cu);
8303   do_cleanups (delayed_list_cleanup);
8304
8305   /* Some compilers don't define a DW_AT_high_pc attribute for the
8306      compilation unit.  If the DW_AT_high_pc is missing, synthesize
8307      it, by scanning the DIE's below the compilation unit.  */
8308   get_scope_pc_bounds (cu->dies, &lowpc, &highpc, cu);
8309
8310   addr = gdbarch_adjust_dwarf2_addr (gdbarch, highpc + baseaddr);
8311   static_block = end_symtab_get_static_block (addr, 0, 1);
8312
8313   /* If the comp unit has DW_AT_ranges, it may have discontiguous ranges.
8314      Also, DW_AT_ranges may record ranges not belonging to any child DIEs
8315      (such as virtual method tables).  Record the ranges in STATIC_BLOCK's
8316      addrmap to help ensure it has an accurate map of pc values belonging to
8317      this comp unit.  */
8318   dwarf2_record_block_ranges (cu->dies, static_block, baseaddr, cu);
8319
8320   cust = end_symtab_from_static_block (static_block,
8321                                        SECT_OFF_TEXT (objfile), 0);
8322
8323   if (cust != NULL)
8324     {
8325       int gcc_4_minor = producer_is_gcc_ge_4 (cu->producer);
8326
8327       /* Set symtab language to language from DW_AT_language.  If the
8328          compilation is from a C file generated by language preprocessors, do
8329          not set the language if it was already deduced by start_subfile.  */
8330       if (!(cu->language == language_c
8331             && COMPUNIT_FILETABS (cust)->language != language_unknown))
8332         COMPUNIT_FILETABS (cust)->language = cu->language;
8333
8334       /* GCC-4.0 has started to support -fvar-tracking.  GCC-3.x still can
8335          produce DW_AT_location with location lists but it can be possibly
8336          invalid without -fvar-tracking.  Still up to GCC-4.4.x incl. 4.4.0
8337          there were bugs in prologue debug info, fixed later in GCC-4.5
8338          by "unwind info for epilogues" patch (which is not directly related).
8339
8340          For -gdwarf-4 type units LOCATIONS_VALID indication is fortunately not
8341          needed, it would be wrong due to missing DW_AT_producer there.
8342
8343          Still one can confuse GDB by using non-standard GCC compilation
8344          options - this waits on GCC PR other/32998 (-frecord-gcc-switches).
8345          */ 
8346       if (cu->has_loclist && gcc_4_minor >= 5)
8347         cust->locations_valid = 1;
8348
8349       if (gcc_4_minor >= 5)
8350         cust->epilogue_unwind_valid = 1;
8351
8352       cust->call_site_htab = cu->call_site_htab;
8353     }
8354
8355   if (dwarf2_per_objfile->using_index)
8356     per_cu->v.quick->compunit_symtab = cust;
8357   else
8358     {
8359       struct partial_symtab *pst = per_cu->v.psymtab;
8360       pst->compunit_symtab = cust;
8361       pst->readin = 1;
8362     }
8363
8364   /* Push it for inclusion processing later.  */
8365   VEC_safe_push (dwarf2_per_cu_ptr, dwarf2_per_objfile->just_read_cus, per_cu);
8366
8367   do_cleanups (back_to);
8368 }
8369
8370 /* Generate full symbol information for type unit PER_CU, whose DIEs have
8371    already been loaded into memory.  */
8372
8373 static void
8374 process_full_type_unit (struct dwarf2_per_cu_data *per_cu,
8375                         enum language pretend_language)
8376 {
8377   struct dwarf2_cu *cu = per_cu->cu;
8378   struct objfile *objfile = per_cu->objfile;
8379   struct compunit_symtab *cust;
8380   struct cleanup *back_to, *delayed_list_cleanup;
8381   struct signatured_type *sig_type;
8382
8383   gdb_assert (per_cu->is_debug_types);
8384   sig_type = (struct signatured_type *) per_cu;
8385
8386   buildsym_init ();
8387   back_to = make_cleanup (really_free_pendings, NULL);
8388   delayed_list_cleanup = make_cleanup (free_delayed_list, cu);
8389
8390   cu->list_in_scope = &file_symbols;
8391
8392   cu->language = pretend_language;
8393   cu->language_defn = language_def (cu->language);
8394
8395   /* The symbol tables are set up in read_type_unit_scope.  */
8396   process_die (cu->dies, cu);
8397
8398   /* For now fudge the Go package.  */
8399   if (cu->language == language_go)
8400     fixup_go_packaging (cu);
8401
8402   /* Now that we have processed all the DIEs in the CU, all the types 
8403      should be complete, and it should now be safe to compute all of the
8404      physnames.  */
8405   compute_delayed_physnames (cu);
8406   do_cleanups (delayed_list_cleanup);
8407
8408   /* TUs share symbol tables.
8409      If this is the first TU to use this symtab, complete the construction
8410      of it with end_expandable_symtab.  Otherwise, complete the addition of
8411      this TU's symbols to the existing symtab.  */
8412   if (sig_type->type_unit_group->compunit_symtab == NULL)
8413     {
8414       cust = end_expandable_symtab (0, SECT_OFF_TEXT (objfile));
8415       sig_type->type_unit_group->compunit_symtab = cust;
8416
8417       if (cust != NULL)
8418         {
8419           /* Set symtab language to language from DW_AT_language.  If the
8420              compilation is from a C file generated by language preprocessors,
8421              do not set the language if it was already deduced by
8422              start_subfile.  */
8423           if (!(cu->language == language_c
8424                 && COMPUNIT_FILETABS (cust)->language != language_c))
8425             COMPUNIT_FILETABS (cust)->language = cu->language;
8426         }
8427     }
8428   else
8429     {
8430       augment_type_symtab ();
8431       cust = sig_type->type_unit_group->compunit_symtab;
8432     }
8433
8434   if (dwarf2_per_objfile->using_index)
8435     per_cu->v.quick->compunit_symtab = cust;
8436   else
8437     {
8438       struct partial_symtab *pst = per_cu->v.psymtab;
8439       pst->compunit_symtab = cust;
8440       pst->readin = 1;
8441     }
8442
8443   do_cleanups (back_to);
8444 }
8445
8446 /* Process an imported unit DIE.  */
8447
8448 static void
8449 process_imported_unit_die (struct die_info *die, struct dwarf2_cu *cu)
8450 {
8451   struct attribute *attr;
8452
8453   /* For now we don't handle imported units in type units.  */
8454   if (cu->per_cu->is_debug_types)
8455     {
8456       error (_("Dwarf Error: DW_TAG_imported_unit is not"
8457                " supported in type units [in module %s]"),
8458              objfile_name (cu->objfile));
8459     }
8460
8461   attr = dwarf2_attr (die, DW_AT_import, cu);
8462   if (attr != NULL)
8463     {
8464       sect_offset sect_off = dwarf2_get_ref_die_offset (attr);
8465       bool is_dwz = (attr->form == DW_FORM_GNU_ref_alt || cu->per_cu->is_dwz);
8466       dwarf2_per_cu_data *per_cu
8467         = dwarf2_find_containing_comp_unit (sect_off, is_dwz, cu->objfile);
8468
8469       /* If necessary, add it to the queue and load its DIEs.  */
8470       if (maybe_queue_comp_unit (cu, per_cu, cu->language))
8471         load_full_comp_unit (per_cu, cu->language);
8472
8473       VEC_safe_push (dwarf2_per_cu_ptr, cu->per_cu->imported_symtabs,
8474                      per_cu);
8475     }
8476 }
8477
8478 /* RAII object that represents a process_die scope: i.e.,
8479    starts/finishes processing a DIE.  */
8480 class process_die_scope
8481 {
8482 public:
8483   process_die_scope (die_info *die, dwarf2_cu *cu)
8484     : m_die (die), m_cu (cu)
8485   {
8486     /* We should only be processing DIEs not already in process.  */
8487     gdb_assert (!m_die->in_process);
8488     m_die->in_process = true;
8489   }
8490
8491   ~process_die_scope ()
8492   {
8493     m_die->in_process = false;
8494
8495     /* If we're done processing the DIE for the CU that owns the line
8496        header, we don't need the line header anymore.  */
8497     if (m_cu->line_header_die_owner == m_die)
8498       {
8499         delete m_cu->line_header;
8500         m_cu->line_header = NULL;
8501         m_cu->line_header_die_owner = NULL;
8502       }
8503   }
8504
8505 private:
8506   die_info *m_die;
8507   dwarf2_cu *m_cu;
8508 };
8509
8510 /* Process a die and its children.  */
8511
8512 static void
8513 process_die (struct die_info *die, struct dwarf2_cu *cu)
8514 {
8515   process_die_scope scope (die, cu);
8516
8517   switch (die->tag)
8518     {
8519     case DW_TAG_padding:
8520       break;
8521     case DW_TAG_compile_unit:
8522     case DW_TAG_partial_unit:
8523       read_file_scope (die, cu);
8524       break;
8525     case DW_TAG_type_unit:
8526       read_type_unit_scope (die, cu);
8527       break;
8528     case DW_TAG_subprogram:
8529     case DW_TAG_inlined_subroutine:
8530       read_func_scope (die, cu);
8531       break;
8532     case DW_TAG_lexical_block:
8533     case DW_TAG_try_block:
8534     case DW_TAG_catch_block:
8535       read_lexical_block_scope (die, cu);
8536       break;
8537     case DW_TAG_call_site:
8538     case DW_TAG_GNU_call_site:
8539       read_call_site_scope (die, cu);
8540       break;
8541     case DW_TAG_class_type:
8542     case DW_TAG_interface_type:
8543     case DW_TAG_structure_type:
8544     case DW_TAG_union_type:
8545       process_structure_scope (die, cu);
8546       break;
8547     case DW_TAG_enumeration_type:
8548       process_enumeration_scope (die, cu);
8549       break;
8550
8551     /* These dies have a type, but processing them does not create
8552        a symbol or recurse to process the children.  Therefore we can
8553        read them on-demand through read_type_die.  */
8554     case DW_TAG_subroutine_type:
8555     case DW_TAG_set_type:
8556     case DW_TAG_array_type:
8557     case DW_TAG_pointer_type:
8558     case DW_TAG_ptr_to_member_type:
8559     case DW_TAG_reference_type:
8560     case DW_TAG_rvalue_reference_type:
8561     case DW_TAG_string_type:
8562       break;
8563
8564     case DW_TAG_base_type:
8565     case DW_TAG_subrange_type:
8566     case DW_TAG_typedef:
8567       /* Add a typedef symbol for the type definition, if it has a
8568          DW_AT_name.  */
8569       new_symbol (die, read_type_die (die, cu), cu);
8570       break;
8571     case DW_TAG_common_block:
8572       read_common_block (die, cu);
8573       break;
8574     case DW_TAG_common_inclusion:
8575       break;
8576     case DW_TAG_namespace:
8577       cu->processing_has_namespace_info = 1;
8578       read_namespace (die, cu);
8579       break;
8580     case DW_TAG_module:
8581       cu->processing_has_namespace_info = 1;
8582       read_module (die, cu);
8583       break;
8584     case DW_TAG_imported_declaration:
8585       cu->processing_has_namespace_info = 1;
8586       if (read_namespace_alias (die, cu))
8587         break;
8588       /* The declaration is not a global namespace alias: fall through.  */
8589     case DW_TAG_imported_module:
8590       cu->processing_has_namespace_info = 1;
8591       if (die->child != NULL && (die->tag == DW_TAG_imported_declaration
8592                                  || cu->language != language_fortran))
8593         complaint (&symfile_complaints, _("Tag '%s' has unexpected children"),
8594                    dwarf_tag_name (die->tag));
8595       read_import_statement (die, cu);
8596       break;
8597
8598     case DW_TAG_imported_unit:
8599       process_imported_unit_die (die, cu);
8600       break;
8601
8602     default:
8603       new_symbol (die, NULL, cu);
8604       break;
8605     }
8606 }
8607 \f
8608 /* DWARF name computation.  */
8609
8610 /* A helper function for dwarf2_compute_name which determines whether DIE
8611    needs to have the name of the scope prepended to the name listed in the
8612    die.  */
8613
8614 static int
8615 die_needs_namespace (struct die_info *die, struct dwarf2_cu *cu)
8616 {
8617   struct attribute *attr;
8618
8619   switch (die->tag)
8620     {
8621     case DW_TAG_namespace:
8622     case DW_TAG_typedef:
8623     case DW_TAG_class_type:
8624     case DW_TAG_interface_type:
8625     case DW_TAG_structure_type:
8626     case DW_TAG_union_type:
8627     case DW_TAG_enumeration_type:
8628     case DW_TAG_enumerator:
8629     case DW_TAG_subprogram:
8630     case DW_TAG_inlined_subroutine:
8631     case DW_TAG_member:
8632     case DW_TAG_imported_declaration:
8633       return 1;
8634
8635     case DW_TAG_variable:
8636     case DW_TAG_constant:
8637       /* We only need to prefix "globally" visible variables.  These include
8638          any variable marked with DW_AT_external or any variable that
8639          lives in a namespace.  [Variables in anonymous namespaces
8640          require prefixing, but they are not DW_AT_external.]  */
8641
8642       if (dwarf2_attr (die, DW_AT_specification, cu))
8643         {
8644           struct dwarf2_cu *spec_cu = cu;
8645
8646           return die_needs_namespace (die_specification (die, &spec_cu),
8647                                       spec_cu);
8648         }
8649
8650       attr = dwarf2_attr (die, DW_AT_external, cu);
8651       if (attr == NULL && die->parent->tag != DW_TAG_namespace
8652           && die->parent->tag != DW_TAG_module)
8653         return 0;
8654       /* A variable in a lexical block of some kind does not need a
8655          namespace, even though in C++ such variables may be external
8656          and have a mangled name.  */
8657       if (die->parent->tag ==  DW_TAG_lexical_block
8658           || die->parent->tag ==  DW_TAG_try_block
8659           || die->parent->tag ==  DW_TAG_catch_block
8660           || die->parent->tag == DW_TAG_subprogram)
8661         return 0;
8662       return 1;
8663
8664     default:
8665       return 0;
8666     }
8667 }
8668
8669 /* Compute the fully qualified name of DIE in CU.  If PHYSNAME is nonzero,
8670    compute the physname for the object, which include a method's:
8671    - formal parameters (C++),
8672    - receiver type (Go),
8673
8674    The term "physname" is a bit confusing.
8675    For C++, for example, it is the demangled name.
8676    For Go, for example, it's the mangled name.
8677
8678    For Ada, return the DIE's linkage name rather than the fully qualified
8679    name.  PHYSNAME is ignored..
8680
8681    The result is allocated on the objfile_obstack and canonicalized.  */
8682
8683 static const char *
8684 dwarf2_compute_name (const char *name,
8685                      struct die_info *die, struct dwarf2_cu *cu,
8686                      int physname)
8687 {
8688   struct objfile *objfile = cu->objfile;
8689
8690   if (name == NULL)
8691     name = dwarf2_name (die, cu);
8692
8693   /* For Fortran GDB prefers DW_AT_*linkage_name for the physname if present
8694      but otherwise compute it by typename_concat inside GDB.
8695      FIXME: Actually this is not really true, or at least not always true.
8696      It's all very confusing.  SYMBOL_SET_NAMES doesn't try to demangle
8697      Fortran names because there is no mangling standard.  So new_symbol_full
8698      will set the demangled name to the result of dwarf2_full_name, and it is
8699      the demangled name that GDB uses if it exists.  */
8700   if (cu->language == language_ada
8701       || (cu->language == language_fortran && physname))
8702     {
8703       /* For Ada unit, we prefer the linkage name over the name, as
8704          the former contains the exported name, which the user expects
8705          to be able to reference.  Ideally, we want the user to be able
8706          to reference this entity using either natural or linkage name,
8707          but we haven't started looking at this enhancement yet.  */
8708       const char *linkage_name;
8709
8710       linkage_name = dwarf2_string_attr (die, DW_AT_linkage_name, cu);
8711       if (linkage_name == NULL)
8712         linkage_name = dwarf2_string_attr (die, DW_AT_MIPS_linkage_name, cu);
8713       if (linkage_name != NULL)
8714         return linkage_name;
8715     }
8716
8717   /* These are the only languages we know how to qualify names in.  */
8718   if (name != NULL
8719       && (cu->language == language_cplus
8720           || cu->language == language_fortran || cu->language == language_d
8721           || cu->language == language_rust))
8722     {
8723       if (die_needs_namespace (die, cu))
8724         {
8725           long length;
8726           const char *prefix;
8727           const char *canonical_name = NULL;
8728
8729           string_file buf;
8730
8731           prefix = determine_prefix (die, cu);
8732           if (*prefix != '\0')
8733             {
8734               char *prefixed_name = typename_concat (NULL, prefix, name,
8735                                                      physname, cu);
8736
8737               buf.puts (prefixed_name);
8738               xfree (prefixed_name);
8739             }
8740           else
8741             buf.puts (name);
8742
8743           /* Template parameters may be specified in the DIE's DW_AT_name, or
8744              as children with DW_TAG_template_type_param or
8745              DW_TAG_value_type_param.  If the latter, add them to the name
8746              here.  If the name already has template parameters, then
8747              skip this step; some versions of GCC emit both, and
8748              it is more efficient to use the pre-computed name.
8749
8750              Something to keep in mind about this process: it is very
8751              unlikely, or in some cases downright impossible, to produce
8752              something that will match the mangled name of a function.
8753              If the definition of the function has the same debug info,
8754              we should be able to match up with it anyway.  But fallbacks
8755              using the minimal symbol, for instance to find a method
8756              implemented in a stripped copy of libstdc++, will not work.
8757              If we do not have debug info for the definition, we will have to
8758              match them up some other way.
8759
8760              When we do name matching there is a related problem with function
8761              templates; two instantiated function templates are allowed to
8762              differ only by their return types, which we do not add here.  */
8763
8764           if (cu->language == language_cplus && strchr (name, '<') == NULL)
8765             {
8766               struct attribute *attr;
8767               struct die_info *child;
8768               int first = 1;
8769
8770               die->building_fullname = 1;
8771
8772               for (child = die->child; child != NULL; child = child->sibling)
8773                 {
8774                   struct type *type;
8775                   LONGEST value;
8776                   const gdb_byte *bytes;
8777                   struct dwarf2_locexpr_baton *baton;
8778                   struct value *v;
8779
8780                   if (child->tag != DW_TAG_template_type_param
8781                       && child->tag != DW_TAG_template_value_param)
8782                     continue;
8783
8784                   if (first)
8785                     {
8786                       buf.puts ("<");
8787                       first = 0;
8788                     }
8789                   else
8790                     buf.puts (", ");
8791
8792                   attr = dwarf2_attr (child, DW_AT_type, cu);
8793                   if (attr == NULL)
8794                     {
8795                       complaint (&symfile_complaints,
8796                                  _("template parameter missing DW_AT_type"));
8797                       buf.puts ("UNKNOWN_TYPE");
8798                       continue;
8799                     }
8800                   type = die_type (child, cu);
8801
8802                   if (child->tag == DW_TAG_template_type_param)
8803                     {
8804                       c_print_type (type, "", &buf, -1, 0, &type_print_raw_options);
8805                       continue;
8806                     }
8807
8808                   attr = dwarf2_attr (child, DW_AT_const_value, cu);
8809                   if (attr == NULL)
8810                     {
8811                       complaint (&symfile_complaints,
8812                                  _("template parameter missing "
8813                                    "DW_AT_const_value"));
8814                       buf.puts ("UNKNOWN_VALUE");
8815                       continue;
8816                     }
8817
8818                   dwarf2_const_value_attr (attr, type, name,
8819                                            &cu->comp_unit_obstack, cu,
8820                                            &value, &bytes, &baton);
8821
8822                   if (TYPE_NOSIGN (type))
8823                     /* GDB prints characters as NUMBER 'CHAR'.  If that's
8824                        changed, this can use value_print instead.  */
8825                     c_printchar (value, type, &buf);
8826                   else
8827                     {
8828                       struct value_print_options opts;
8829
8830                       if (baton != NULL)
8831                         v = dwarf2_evaluate_loc_desc (type, NULL,
8832                                                       baton->data,
8833                                                       baton->size,
8834                                                       baton->per_cu);
8835                       else if (bytes != NULL)
8836                         {
8837                           v = allocate_value (type);
8838                           memcpy (value_contents_writeable (v), bytes,
8839                                   TYPE_LENGTH (type));
8840                         }
8841                       else
8842                         v = value_from_longest (type, value);
8843
8844                       /* Specify decimal so that we do not depend on
8845                          the radix.  */
8846                       get_formatted_print_options (&opts, 'd');
8847                       opts.raw = 1;
8848                       value_print (v, &buf, &opts);
8849                       release_value (v);
8850                       value_free (v);
8851                     }
8852                 }
8853
8854               die->building_fullname = 0;
8855
8856               if (!first)
8857                 {
8858                   /* Close the argument list, with a space if necessary
8859                      (nested templates).  */
8860                   if (!buf.empty () && buf.string ().back () == '>')
8861                     buf.puts (" >");
8862                   else
8863                     buf.puts (">");
8864                 }
8865             }
8866
8867           /* For C++ methods, append formal parameter type
8868              information, if PHYSNAME.  */
8869
8870           if (physname && die->tag == DW_TAG_subprogram
8871               && cu->language == language_cplus)
8872             {
8873               struct type *type = read_type_die (die, cu);
8874
8875               c_type_print_args (type, &buf, 1, cu->language,
8876                                  &type_print_raw_options);
8877
8878               if (cu->language == language_cplus)
8879                 {
8880                   /* Assume that an artificial first parameter is
8881                      "this", but do not crash if it is not.  RealView
8882                      marks unnamed (and thus unused) parameters as
8883                      artificial; there is no way to differentiate
8884                      the two cases.  */
8885                   if (TYPE_NFIELDS (type) > 0
8886                       && TYPE_FIELD_ARTIFICIAL (type, 0)
8887                       && TYPE_CODE (TYPE_FIELD_TYPE (type, 0)) == TYPE_CODE_PTR
8888                       && TYPE_CONST (TYPE_TARGET_TYPE (TYPE_FIELD_TYPE (type,
8889                                                                         0))))
8890                     buf.puts (" const");
8891                 }
8892             }
8893
8894           const std::string &intermediate_name = buf.string ();
8895
8896           if (cu->language == language_cplus)
8897             canonical_name
8898               = dwarf2_canonicalize_name (intermediate_name.c_str (), cu,
8899                                           &objfile->per_bfd->storage_obstack);
8900
8901           /* If we only computed INTERMEDIATE_NAME, or if
8902              INTERMEDIATE_NAME is already canonical, then we need to
8903              copy it to the appropriate obstack.  */
8904           if (canonical_name == NULL || canonical_name == intermediate_name.c_str ())
8905             name = ((const char *)
8906                     obstack_copy0 (&objfile->per_bfd->storage_obstack,
8907                                    intermediate_name.c_str (),
8908                                    intermediate_name.length ()));
8909           else
8910             name = canonical_name;
8911         }
8912     }
8913
8914   return name;
8915 }
8916
8917 /* Return the fully qualified name of DIE, based on its DW_AT_name.
8918    If scope qualifiers are appropriate they will be added.  The result
8919    will be allocated on the storage_obstack, or NULL if the DIE does
8920    not have a name.  NAME may either be from a previous call to
8921    dwarf2_name or NULL.
8922
8923    The output string will be canonicalized (if C++).  */
8924
8925 static const char *
8926 dwarf2_full_name (const char *name, struct die_info *die, struct dwarf2_cu *cu)
8927 {
8928   return dwarf2_compute_name (name, die, cu, 0);
8929 }
8930
8931 /* Construct a physname for the given DIE in CU.  NAME may either be
8932    from a previous call to dwarf2_name or NULL.  The result will be
8933    allocated on the objfile_objstack or NULL if the DIE does not have a
8934    name.
8935
8936    The output string will be canonicalized (if C++).  */
8937
8938 static const char *
8939 dwarf2_physname (const char *name, struct die_info *die, struct dwarf2_cu *cu)
8940 {
8941   struct objfile *objfile = cu->objfile;
8942   const char *retval, *mangled = NULL, *canon = NULL;
8943   struct cleanup *back_to;
8944   int need_copy = 1;
8945
8946   /* In this case dwarf2_compute_name is just a shortcut not building anything
8947      on its own.  */
8948   if (!die_needs_namespace (die, cu))
8949     return dwarf2_compute_name (name, die, cu, 1);
8950
8951   back_to = make_cleanup (null_cleanup, NULL);
8952
8953   mangled = dwarf2_string_attr (die, DW_AT_linkage_name, cu);
8954   if (mangled == NULL)
8955     mangled = dwarf2_string_attr (die, DW_AT_MIPS_linkage_name, cu);
8956
8957   /* rustc emits invalid values for DW_AT_linkage_name.  Ignore these.
8958      See https://github.com/rust-lang/rust/issues/32925.  */
8959   if (cu->language == language_rust && mangled != NULL
8960       && strchr (mangled, '{') != NULL)
8961     mangled = NULL;
8962
8963   /* DW_AT_linkage_name is missing in some cases - depend on what GDB
8964      has computed.  */
8965   if (mangled != NULL)
8966     {
8967       char *demangled;
8968
8969       /* Use DMGL_RET_DROP for C++ template functions to suppress their return
8970          type.  It is easier for GDB users to search for such functions as
8971          `name(params)' than `long name(params)'.  In such case the minimal
8972          symbol names do not match the full symbol names but for template
8973          functions there is never a need to look up their definition from their
8974          declaration so the only disadvantage remains the minimal symbol
8975          variant `long name(params)' does not have the proper inferior type.
8976          */
8977
8978       if (cu->language == language_go)
8979         {
8980           /* This is a lie, but we already lie to the caller new_symbol_full.
8981              new_symbol_full assumes we return the mangled name.
8982              This just undoes that lie until things are cleaned up.  */
8983           demangled = NULL;
8984         }
8985       else
8986         {
8987           demangled = gdb_demangle (mangled,
8988                                     (DMGL_PARAMS | DMGL_ANSI | DMGL_RET_DROP));
8989         }
8990       if (demangled)
8991         {
8992           make_cleanup (xfree, demangled);
8993           canon = demangled;
8994         }
8995       else
8996         {
8997           canon = mangled;
8998           need_copy = 0;
8999         }
9000     }
9001
9002   if (canon == NULL || check_physname)
9003     {
9004       const char *physname = dwarf2_compute_name (name, die, cu, 1);
9005
9006       if (canon != NULL && strcmp (physname, canon) != 0)
9007         {
9008           /* It may not mean a bug in GDB.  The compiler could also
9009              compute DW_AT_linkage_name incorrectly.  But in such case
9010              GDB would need to be bug-to-bug compatible.  */
9011
9012           complaint (&symfile_complaints,
9013                      _("Computed physname <%s> does not match demangled <%s> "
9014                        "(from linkage <%s>) - DIE at 0x%x [in module %s]"),
9015                      physname, canon, mangled, to_underlying (die->sect_off),
9016                      objfile_name (objfile));
9017
9018           /* Prefer DW_AT_linkage_name (in the CANON form) - when it
9019              is available here - over computed PHYSNAME.  It is safer
9020              against both buggy GDB and buggy compilers.  */
9021
9022           retval = canon;
9023         }
9024       else
9025         {
9026           retval = physname;
9027           need_copy = 0;
9028         }
9029     }
9030   else
9031     retval = canon;
9032
9033   if (need_copy)
9034     retval = ((const char *)
9035               obstack_copy0 (&objfile->per_bfd->storage_obstack,
9036                              retval, strlen (retval)));
9037
9038   do_cleanups (back_to);
9039   return retval;
9040 }
9041
9042 /* Inspect DIE in CU for a namespace alias.  If one exists, record
9043    a new symbol for it.
9044
9045    Returns 1 if a namespace alias was recorded, 0 otherwise.  */
9046
9047 static int
9048 read_namespace_alias (struct die_info *die, struct dwarf2_cu *cu)
9049 {
9050   struct attribute *attr;
9051
9052   /* If the die does not have a name, this is not a namespace
9053      alias.  */
9054   attr = dwarf2_attr (die, DW_AT_name, cu);
9055   if (attr != NULL)
9056     {
9057       int num;
9058       struct die_info *d = die;
9059       struct dwarf2_cu *imported_cu = cu;
9060
9061       /* If the compiler has nested DW_AT_imported_declaration DIEs,
9062          keep inspecting DIEs until we hit the underlying import.  */
9063 #define MAX_NESTED_IMPORTED_DECLARATIONS 100
9064       for (num = 0; num  < MAX_NESTED_IMPORTED_DECLARATIONS; ++num)
9065         {
9066           attr = dwarf2_attr (d, DW_AT_import, cu);
9067           if (attr == NULL)
9068             break;
9069
9070           d = follow_die_ref (d, attr, &imported_cu);
9071           if (d->tag != DW_TAG_imported_declaration)
9072             break;
9073         }
9074
9075       if (num == MAX_NESTED_IMPORTED_DECLARATIONS)
9076         {
9077           complaint (&symfile_complaints,
9078                      _("DIE at 0x%x has too many recursively imported "
9079                        "declarations"), to_underlying (d->sect_off));
9080           return 0;
9081         }
9082
9083       if (attr != NULL)
9084         {
9085           struct type *type;
9086           sect_offset sect_off = dwarf2_get_ref_die_offset (attr);
9087
9088           type = get_die_type_at_offset (sect_off, cu->per_cu);
9089           if (type != NULL && TYPE_CODE (type) == TYPE_CODE_NAMESPACE)
9090             {
9091               /* This declaration is a global namespace alias.  Add
9092                  a symbol for it whose type is the aliased namespace.  */
9093               new_symbol (die, type, cu);
9094               return 1;
9095             }
9096         }
9097     }
9098
9099   return 0;
9100 }
9101
9102 /* Return the using directives repository (global or local?) to use in the
9103    current context for LANGUAGE.
9104
9105    For Ada, imported declarations can materialize renamings, which *may* be
9106    global.  However it is impossible (for now?) in DWARF to distinguish
9107    "external" imported declarations and "static" ones.  As all imported
9108    declarations seem to be static in all other languages, make them all CU-wide
9109    global only in Ada.  */
9110
9111 static struct using_direct **
9112 using_directives (enum language language)
9113 {
9114   if (language == language_ada && context_stack_depth == 0)
9115     return &global_using_directives;
9116   else
9117     return &local_using_directives;
9118 }
9119
9120 /* Read the import statement specified by the given die and record it.  */
9121
9122 static void
9123 read_import_statement (struct die_info *die, struct dwarf2_cu *cu)
9124 {
9125   struct objfile *objfile = cu->objfile;
9126   struct attribute *import_attr;
9127   struct die_info *imported_die, *child_die;
9128   struct dwarf2_cu *imported_cu;
9129   const char *imported_name;
9130   const char *imported_name_prefix;
9131   const char *canonical_name;
9132   const char *import_alias;
9133   const char *imported_declaration = NULL;
9134   const char *import_prefix;
9135   VEC (const_char_ptr) *excludes = NULL;
9136   struct cleanup *cleanups;
9137
9138   import_attr = dwarf2_attr (die, DW_AT_import, cu);
9139   if (import_attr == NULL)
9140     {
9141       complaint (&symfile_complaints, _("Tag '%s' has no DW_AT_import"),
9142                  dwarf_tag_name (die->tag));
9143       return;
9144     }
9145
9146   imported_cu = cu;
9147   imported_die = follow_die_ref_or_sig (die, import_attr, &imported_cu);
9148   imported_name = dwarf2_name (imported_die, imported_cu);
9149   if (imported_name == NULL)
9150     {
9151       /* GCC bug: https://bugzilla.redhat.com/show_bug.cgi?id=506524
9152
9153         The import in the following code:
9154         namespace A
9155           {
9156             typedef int B;
9157           }
9158
9159         int main ()
9160           {
9161             using A::B;
9162             B b;
9163             return b;
9164           }
9165
9166         ...
9167          <2><51>: Abbrev Number: 3 (DW_TAG_imported_declaration)
9168             <52>   DW_AT_decl_file   : 1
9169             <53>   DW_AT_decl_line   : 6
9170             <54>   DW_AT_import      : <0x75>
9171          <2><58>: Abbrev Number: 4 (DW_TAG_typedef)
9172             <59>   DW_AT_name        : B
9173             <5b>   DW_AT_decl_file   : 1
9174             <5c>   DW_AT_decl_line   : 2
9175             <5d>   DW_AT_type        : <0x6e>
9176         ...
9177          <1><75>: Abbrev Number: 7 (DW_TAG_base_type)
9178             <76>   DW_AT_byte_size   : 4
9179             <77>   DW_AT_encoding    : 5        (signed)
9180
9181         imports the wrong die ( 0x75 instead of 0x58 ).
9182         This case will be ignored until the gcc bug is fixed.  */
9183       return;
9184     }
9185
9186   /* Figure out the local name after import.  */
9187   import_alias = dwarf2_name (die, cu);
9188
9189   /* Figure out where the statement is being imported to.  */
9190   import_prefix = determine_prefix (die, cu);
9191
9192   /* Figure out what the scope of the imported die is and prepend it
9193      to the name of the imported die.  */
9194   imported_name_prefix = determine_prefix (imported_die, imported_cu);
9195
9196   if (imported_die->tag != DW_TAG_namespace
9197       && imported_die->tag != DW_TAG_module)
9198     {
9199       imported_declaration = imported_name;
9200       canonical_name = imported_name_prefix;
9201     }
9202   else if (strlen (imported_name_prefix) > 0)
9203     canonical_name = obconcat (&objfile->objfile_obstack,
9204                                imported_name_prefix,
9205                                (cu->language == language_d ? "." : "::"),
9206                                imported_name, (char *) NULL);
9207   else
9208     canonical_name = imported_name;
9209
9210   cleanups = make_cleanup (VEC_cleanup (const_char_ptr), &excludes);
9211
9212   if (die->tag == DW_TAG_imported_module && cu->language == language_fortran)
9213     for (child_die = die->child; child_die && child_die->tag;
9214          child_die = sibling_die (child_die))
9215       {
9216         /* DWARF-4: A Fortran use statement with a “rename list” may be
9217            represented by an imported module entry with an import attribute
9218            referring to the module and owned entries corresponding to those
9219            entities that are renamed as part of being imported.  */
9220
9221         if (child_die->tag != DW_TAG_imported_declaration)
9222           {
9223             complaint (&symfile_complaints,
9224                        _("child DW_TAG_imported_declaration expected "
9225                          "- DIE at 0x%x [in module %s]"),
9226                        to_underlying (child_die->sect_off), objfile_name (objfile));
9227             continue;
9228           }
9229
9230         import_attr = dwarf2_attr (child_die, DW_AT_import, cu);
9231         if (import_attr == NULL)
9232           {
9233             complaint (&symfile_complaints, _("Tag '%s' has no DW_AT_import"),
9234                        dwarf_tag_name (child_die->tag));
9235             continue;
9236           }
9237
9238         imported_cu = cu;
9239         imported_die = follow_die_ref_or_sig (child_die, import_attr,
9240                                               &imported_cu);
9241         imported_name = dwarf2_name (imported_die, imported_cu);
9242         if (imported_name == NULL)
9243           {
9244             complaint (&symfile_complaints,
9245                        _("child DW_TAG_imported_declaration has unknown "
9246                          "imported name - DIE at 0x%x [in module %s]"),
9247                        to_underlying (child_die->sect_off), objfile_name (objfile));
9248             continue;
9249           }
9250
9251         VEC_safe_push (const_char_ptr, excludes, imported_name);
9252
9253         process_die (child_die, cu);
9254       }
9255
9256   add_using_directive (using_directives (cu->language),
9257                        import_prefix,
9258                        canonical_name,
9259                        import_alias,
9260                        imported_declaration,
9261                        excludes,
9262                        0,
9263                        &objfile->objfile_obstack);
9264
9265   do_cleanups (cleanups);
9266 }
9267
9268 /* Check for possibly missing DW_AT_comp_dir with relative .debug_line
9269    directory paths.  GCC SVN r127613 (new option -fdebug-prefix-map) fixed
9270    this, it was first present in GCC release 4.3.0.  */
9271
9272 static int
9273 producer_is_gcc_lt_4_3 (struct dwarf2_cu *cu)
9274 {
9275   if (!cu->checked_producer)
9276     check_producer (cu);
9277
9278   return cu->producer_is_gcc_lt_4_3;
9279 }
9280
9281 static file_and_directory
9282 find_file_and_directory (struct die_info *die, struct dwarf2_cu *cu)
9283 {
9284   file_and_directory res;
9285
9286   /* Find the filename.  Do not use dwarf2_name here, since the filename
9287      is not a source language identifier.  */
9288   res.name = dwarf2_string_attr (die, DW_AT_name, cu);
9289   res.comp_dir = dwarf2_string_attr (die, DW_AT_comp_dir, cu);
9290
9291   if (res.comp_dir == NULL
9292       && producer_is_gcc_lt_4_3 (cu) && res.name != NULL
9293       && IS_ABSOLUTE_PATH (res.name))
9294     {
9295       res.comp_dir_storage = ldirname (res.name);
9296       if (!res.comp_dir_storage.empty ())
9297         res.comp_dir = res.comp_dir_storage.c_str ();
9298     }
9299   if (res.comp_dir != NULL)
9300     {
9301       /* Irix 6.2 native cc prepends <machine>.: to the compilation
9302          directory, get rid of it.  */
9303       const char *cp = strchr (res.comp_dir, ':');
9304
9305       if (cp && cp != res.comp_dir && cp[-1] == '.' && cp[1] == '/')
9306         res.comp_dir = cp + 1;
9307     }
9308
9309   if (res.name == NULL)
9310     res.name = "<unknown>";
9311
9312   return res;
9313 }
9314
9315 /* Handle DW_AT_stmt_list for a compilation unit.
9316    DIE is the DW_TAG_compile_unit die for CU.
9317    COMP_DIR is the compilation directory.  LOWPC is passed to
9318    dwarf_decode_lines.  See dwarf_decode_lines comments about it.  */
9319
9320 static void
9321 handle_DW_AT_stmt_list (struct die_info *die, struct dwarf2_cu *cu,
9322                         const char *comp_dir, CORE_ADDR lowpc) /* ARI: editCase function */
9323 {
9324   struct objfile *objfile = dwarf2_per_objfile->objfile;
9325   struct attribute *attr;
9326   struct line_header line_header_local;
9327   hashval_t line_header_local_hash;
9328   unsigned u;
9329   void **slot;
9330   int decode_mapping;
9331
9332   gdb_assert (! cu->per_cu->is_debug_types);
9333
9334   attr = dwarf2_attr (die, DW_AT_stmt_list, cu);
9335   if (attr == NULL)
9336     return;
9337
9338   sect_offset line_offset = (sect_offset) DW_UNSND (attr);
9339
9340   /* The line header hash table is only created if needed (it exists to
9341      prevent redundant reading of the line table for partial_units).
9342      If we're given a partial_unit, we'll need it.  If we're given a
9343      compile_unit, then use the line header hash table if it's already
9344      created, but don't create one just yet.  */
9345
9346   if (dwarf2_per_objfile->line_header_hash == NULL
9347       && die->tag == DW_TAG_partial_unit)
9348     {
9349       dwarf2_per_objfile->line_header_hash
9350         = htab_create_alloc_ex (127, line_header_hash_voidp,
9351                                 line_header_eq_voidp,
9352                                 free_line_header_voidp,
9353                                 &objfile->objfile_obstack,
9354                                 hashtab_obstack_allocate,
9355                                 dummy_obstack_deallocate);
9356     }
9357
9358   line_header_local.sect_off = line_offset;
9359   line_header_local.offset_in_dwz = cu->per_cu->is_dwz;
9360   line_header_local_hash = line_header_hash (&line_header_local);
9361   if (dwarf2_per_objfile->line_header_hash != NULL)
9362     {
9363       slot = htab_find_slot_with_hash (dwarf2_per_objfile->line_header_hash,
9364                                        &line_header_local,
9365                                        line_header_local_hash, NO_INSERT);
9366
9367       /* For DW_TAG_compile_unit we need info like symtab::linetable which
9368          is not present in *SLOT (since if there is something in *SLOT then
9369          it will be for a partial_unit).  */
9370       if (die->tag == DW_TAG_partial_unit && slot != NULL)
9371         {
9372           gdb_assert (*slot != NULL);
9373           cu->line_header = (struct line_header *) *slot;
9374           return;
9375         }
9376     }
9377
9378   /* dwarf_decode_line_header does not yet provide sufficient information.
9379      We always have to call also dwarf_decode_lines for it.  */
9380   line_header_up lh = dwarf_decode_line_header (line_offset, cu);
9381   if (lh == NULL)
9382     return;
9383
9384   cu->line_header = lh.release ();
9385   cu->line_header_die_owner = die;
9386
9387   if (dwarf2_per_objfile->line_header_hash == NULL)
9388     slot = NULL;
9389   else
9390     {
9391       slot = htab_find_slot_with_hash (dwarf2_per_objfile->line_header_hash,
9392                                        &line_header_local,
9393                                        line_header_local_hash, INSERT);
9394       gdb_assert (slot != NULL);
9395     }
9396   if (slot != NULL && *slot == NULL)
9397     {
9398       /* This newly decoded line number information unit will be owned
9399          by line_header_hash hash table.  */
9400       *slot = cu->line_header;
9401       cu->line_header_die_owner = NULL;
9402     }
9403   else
9404     {
9405       /* We cannot free any current entry in (*slot) as that struct line_header
9406          may be already used by multiple CUs.  Create only temporary decoded
9407          line_header for this CU - it may happen at most once for each line
9408          number information unit.  And if we're not using line_header_hash
9409          then this is what we want as well.  */
9410       gdb_assert (die->tag != DW_TAG_partial_unit);
9411     }
9412   decode_mapping = (die->tag != DW_TAG_partial_unit);
9413   dwarf_decode_lines (cu->line_header, comp_dir, cu, NULL, lowpc,
9414                       decode_mapping);
9415
9416 }
9417
9418 /* Process DW_TAG_compile_unit or DW_TAG_partial_unit.  */
9419
9420 static void
9421 read_file_scope (struct die_info *die, struct dwarf2_cu *cu)
9422 {
9423   struct objfile *objfile = dwarf2_per_objfile->objfile;
9424   struct gdbarch *gdbarch = get_objfile_arch (objfile);
9425   CORE_ADDR lowpc = ((CORE_ADDR) -1);
9426   CORE_ADDR highpc = ((CORE_ADDR) 0);
9427   struct attribute *attr;
9428   struct die_info *child_die;
9429   CORE_ADDR baseaddr;
9430
9431   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
9432
9433   get_scope_pc_bounds (die, &lowpc, &highpc, cu);
9434
9435   /* If we didn't find a lowpc, set it to highpc to avoid complaints
9436      from finish_block.  */
9437   if (lowpc == ((CORE_ADDR) -1))
9438     lowpc = highpc;
9439   lowpc = gdbarch_adjust_dwarf2_addr (gdbarch, lowpc + baseaddr);
9440
9441   file_and_directory fnd = find_file_and_directory (die, cu);
9442
9443   prepare_one_comp_unit (cu, die, cu->language);
9444
9445   /* The XLCL doesn't generate DW_LANG_OpenCL because this attribute is not
9446      standardised yet.  As a workaround for the language detection we fall
9447      back to the DW_AT_producer string.  */
9448   if (cu->producer && strstr (cu->producer, "IBM XL C for OpenCL") != NULL)
9449     cu->language = language_opencl;
9450
9451   /* Similar hack for Go.  */
9452   if (cu->producer && strstr (cu->producer, "GNU Go ") != NULL)
9453     set_cu_language (DW_LANG_Go, cu);
9454
9455   dwarf2_start_symtab (cu, fnd.name, fnd.comp_dir, lowpc);
9456
9457   /* Decode line number information if present.  We do this before
9458      processing child DIEs, so that the line header table is available
9459      for DW_AT_decl_file.  */
9460   handle_DW_AT_stmt_list (die, cu, fnd.comp_dir, lowpc);
9461
9462   /* Process all dies in compilation unit.  */
9463   if (die->child != NULL)
9464     {
9465       child_die = die->child;
9466       while (child_die && child_die->tag)
9467         {
9468           process_die (child_die, cu);
9469           child_die = sibling_die (child_die);
9470         }
9471     }
9472
9473   /* Decode macro information, if present.  Dwarf 2 macro information
9474      refers to information in the line number info statement program
9475      header, so we can only read it if we've read the header
9476      successfully.  */
9477   attr = dwarf2_attr (die, DW_AT_macros, cu);
9478   if (attr == NULL)
9479     attr = dwarf2_attr (die, DW_AT_GNU_macros, cu);
9480   if (attr && cu->line_header)
9481     {
9482       if (dwarf2_attr (die, DW_AT_macro_info, cu))
9483         complaint (&symfile_complaints,
9484                    _("CU refers to both DW_AT_macros and DW_AT_macro_info"));
9485
9486       dwarf_decode_macros (cu, DW_UNSND (attr), 1);
9487     }
9488   else
9489     {
9490       attr = dwarf2_attr (die, DW_AT_macro_info, cu);
9491       if (attr && cu->line_header)
9492         {
9493           unsigned int macro_offset = DW_UNSND (attr);
9494
9495           dwarf_decode_macros (cu, macro_offset, 0);
9496         }
9497     }
9498 }
9499
9500 /* TU version of handle_DW_AT_stmt_list for read_type_unit_scope.
9501    Create the set of symtabs used by this TU, or if this TU is sharing
9502    symtabs with another TU and the symtabs have already been created
9503    then restore those symtabs in the line header.
9504    We don't need the pc/line-number mapping for type units.  */
9505
9506 static void
9507 setup_type_unit_groups (struct die_info *die, struct dwarf2_cu *cu)
9508 {
9509   struct dwarf2_per_cu_data *per_cu = cu->per_cu;
9510   struct type_unit_group *tu_group;
9511   int first_time;
9512   struct attribute *attr;
9513   unsigned int i;
9514   struct signatured_type *sig_type;
9515
9516   gdb_assert (per_cu->is_debug_types);
9517   sig_type = (struct signatured_type *) per_cu;
9518
9519   attr = dwarf2_attr (die, DW_AT_stmt_list, cu);
9520
9521   /* If we're using .gdb_index (includes -readnow) then
9522      per_cu->type_unit_group may not have been set up yet.  */
9523   if (sig_type->type_unit_group == NULL)
9524     sig_type->type_unit_group = get_type_unit_group (cu, attr);
9525   tu_group = sig_type->type_unit_group;
9526
9527   /* If we've already processed this stmt_list there's no real need to
9528      do it again, we could fake it and just recreate the part we need
9529      (file name,index -> symtab mapping).  If data shows this optimization
9530      is useful we can do it then.  */
9531   first_time = tu_group->compunit_symtab == NULL;
9532
9533   /* We have to handle the case of both a missing DW_AT_stmt_list or bad
9534      debug info.  */
9535   line_header_up lh;
9536   if (attr != NULL)
9537     {
9538       sect_offset line_offset = (sect_offset) DW_UNSND (attr);
9539       lh = dwarf_decode_line_header (line_offset, cu);
9540     }
9541   if (lh == NULL)
9542     {
9543       if (first_time)
9544         dwarf2_start_symtab (cu, "", NULL, 0);
9545       else
9546         {
9547           gdb_assert (tu_group->symtabs == NULL);
9548           restart_symtab (tu_group->compunit_symtab, "", 0);
9549         }
9550       return;
9551     }
9552
9553   cu->line_header = lh.release ();
9554   cu->line_header_die_owner = die;
9555
9556   if (first_time)
9557     {
9558       struct compunit_symtab *cust = dwarf2_start_symtab (cu, "", NULL, 0);
9559
9560       /* Note: We don't assign tu_group->compunit_symtab yet because we're
9561          still initializing it, and our caller (a few levels up)
9562          process_full_type_unit still needs to know if this is the first
9563          time.  */
9564
9565       tu_group->num_symtabs = cu->line_header->file_names.size ();
9566       tu_group->symtabs = XNEWVEC (struct symtab *,
9567                                    cu->line_header->file_names.size ());
9568
9569       for (i = 0; i < cu->line_header->file_names.size (); ++i)
9570         {
9571           file_entry &fe = cu->line_header->file_names[i];
9572
9573           dwarf2_start_subfile (fe.name, fe.include_dir (cu->line_header));
9574
9575           if (current_subfile->symtab == NULL)
9576             {
9577               /* NOTE: start_subfile will recognize when it's been
9578                  passed a file it has already seen.  So we can't
9579                  assume there's a simple mapping from
9580                  cu->line_header->file_names to subfiles, plus
9581                  cu->line_header->file_names may contain dups.  */
9582               current_subfile->symtab
9583                 = allocate_symtab (cust, current_subfile->name);
9584             }
9585
9586           fe.symtab = current_subfile->symtab;
9587           tu_group->symtabs[i] = fe.symtab;
9588         }
9589     }
9590   else
9591     {
9592       restart_symtab (tu_group->compunit_symtab, "", 0);
9593
9594       for (i = 0; i < cu->line_header->file_names.size (); ++i)
9595         {
9596           file_entry &fe = cu->line_header->file_names[i];
9597
9598           fe.symtab = tu_group->symtabs[i];
9599         }
9600     }
9601
9602   /* The main symtab is allocated last.  Type units don't have DW_AT_name
9603      so they don't have a "real" (so to speak) symtab anyway.
9604      There is later code that will assign the main symtab to all symbols
9605      that don't have one.  We need to handle the case of a symbol with a
9606      missing symtab (DW_AT_decl_file) anyway.  */
9607 }
9608
9609 /* Process DW_TAG_type_unit.
9610    For TUs we want to skip the first top level sibling if it's not the
9611    actual type being defined by this TU.  In this case the first top
9612    level sibling is there to provide context only.  */
9613
9614 static void
9615 read_type_unit_scope (struct die_info *die, struct dwarf2_cu *cu)
9616 {
9617   struct die_info *child_die;
9618
9619   prepare_one_comp_unit (cu, die, language_minimal);
9620
9621   /* Initialize (or reinitialize) the machinery for building symtabs.
9622      We do this before processing child DIEs, so that the line header table
9623      is available for DW_AT_decl_file.  */
9624   setup_type_unit_groups (die, cu);
9625
9626   if (die->child != NULL)
9627     {
9628       child_die = die->child;
9629       while (child_die && child_die->tag)
9630         {
9631           process_die (child_die, cu);
9632           child_die = sibling_die (child_die);
9633         }
9634     }
9635 }
9636 \f
9637 /* DWO/DWP files.
9638
9639    http://gcc.gnu.org/wiki/DebugFission
9640    http://gcc.gnu.org/wiki/DebugFissionDWP
9641
9642    To simplify handling of both DWO files ("object" files with the DWARF info)
9643    and DWP files (a file with the DWOs packaged up into one file), we treat
9644    DWP files as having a collection of virtual DWO files.  */
9645
9646 static hashval_t
9647 hash_dwo_file (const void *item)
9648 {
9649   const struct dwo_file *dwo_file = (const struct dwo_file *) item;
9650   hashval_t hash;
9651
9652   hash = htab_hash_string (dwo_file->dwo_name);
9653   if (dwo_file->comp_dir != NULL)
9654     hash += htab_hash_string (dwo_file->comp_dir);
9655   return hash;
9656 }
9657
9658 static int
9659 eq_dwo_file (const void *item_lhs, const void *item_rhs)
9660 {
9661   const struct dwo_file *lhs = (const struct dwo_file *) item_lhs;
9662   const struct dwo_file *rhs = (const struct dwo_file *) item_rhs;
9663
9664   if (strcmp (lhs->dwo_name, rhs->dwo_name) != 0)
9665     return 0;
9666   if (lhs->comp_dir == NULL || rhs->comp_dir == NULL)
9667     return lhs->comp_dir == rhs->comp_dir;
9668   return strcmp (lhs->comp_dir, rhs->comp_dir) == 0;
9669 }
9670
9671 /* Allocate a hash table for DWO files.  */
9672
9673 static htab_t
9674 allocate_dwo_file_hash_table (void)
9675 {
9676   struct objfile *objfile = dwarf2_per_objfile->objfile;
9677
9678   return htab_create_alloc_ex (41,
9679                                hash_dwo_file,
9680                                eq_dwo_file,
9681                                NULL,
9682                                &objfile->objfile_obstack,
9683                                hashtab_obstack_allocate,
9684                                dummy_obstack_deallocate);
9685 }
9686
9687 /* Lookup DWO file DWO_NAME.  */
9688
9689 static void **
9690 lookup_dwo_file_slot (const char *dwo_name, const char *comp_dir)
9691 {
9692   struct dwo_file find_entry;
9693   void **slot;
9694
9695   if (dwarf2_per_objfile->dwo_files == NULL)
9696     dwarf2_per_objfile->dwo_files = allocate_dwo_file_hash_table ();
9697
9698   memset (&find_entry, 0, sizeof (find_entry));
9699   find_entry.dwo_name = dwo_name;
9700   find_entry.comp_dir = comp_dir;
9701   slot = htab_find_slot (dwarf2_per_objfile->dwo_files, &find_entry, INSERT);
9702
9703   return slot;
9704 }
9705
9706 static hashval_t
9707 hash_dwo_unit (const void *item)
9708 {
9709   const struct dwo_unit *dwo_unit = (const struct dwo_unit *) item;
9710
9711   /* This drops the top 32 bits of the id, but is ok for a hash.  */
9712   return dwo_unit->signature;
9713 }
9714
9715 static int
9716 eq_dwo_unit (const void *item_lhs, const void *item_rhs)
9717 {
9718   const struct dwo_unit *lhs = (const struct dwo_unit *) item_lhs;
9719   const struct dwo_unit *rhs = (const struct dwo_unit *) item_rhs;
9720
9721   /* The signature is assumed to be unique within the DWO file.
9722      So while object file CU dwo_id's always have the value zero,
9723      that's OK, assuming each object file DWO file has only one CU,
9724      and that's the rule for now.  */
9725   return lhs->signature == rhs->signature;
9726 }
9727
9728 /* Allocate a hash table for DWO CUs,TUs.
9729    There is one of these tables for each of CUs,TUs for each DWO file.  */
9730
9731 static htab_t
9732 allocate_dwo_unit_table (struct objfile *objfile)
9733 {
9734   /* Start out with a pretty small number.
9735      Generally DWO files contain only one CU and maybe some TUs.  */
9736   return htab_create_alloc_ex (3,
9737                                hash_dwo_unit,
9738                                eq_dwo_unit,
9739                                NULL,
9740                                &objfile->objfile_obstack,
9741                                hashtab_obstack_allocate,
9742                                dummy_obstack_deallocate);
9743 }
9744
9745 /* Structure used to pass data to create_dwo_debug_info_hash_table_reader.  */
9746
9747 struct create_dwo_cu_data
9748 {
9749   struct dwo_file *dwo_file;
9750   struct dwo_unit dwo_unit;
9751 };
9752
9753 /* die_reader_func for create_dwo_cu.  */
9754
9755 static void
9756 create_dwo_cu_reader (const struct die_reader_specs *reader,
9757                       const gdb_byte *info_ptr,
9758                       struct die_info *comp_unit_die,
9759                       int has_children,
9760                       void *datap)
9761 {
9762   struct dwarf2_cu *cu = reader->cu;
9763   sect_offset sect_off = cu->per_cu->sect_off;
9764   struct dwarf2_section_info *section = cu->per_cu->section;
9765   struct create_dwo_cu_data *data = (struct create_dwo_cu_data *) datap;
9766   struct dwo_file *dwo_file = data->dwo_file;
9767   struct dwo_unit *dwo_unit = &data->dwo_unit;
9768   struct attribute *attr;
9769
9770   attr = dwarf2_attr (comp_unit_die, DW_AT_GNU_dwo_id, cu);
9771   if (attr == NULL)
9772     {
9773       complaint (&symfile_complaints,
9774                  _("Dwarf Error: debug entry at offset 0x%x is missing"
9775                    " its dwo_id [in module %s]"),
9776                  to_underlying (sect_off), dwo_file->dwo_name);
9777       return;
9778     }
9779
9780   dwo_unit->dwo_file = dwo_file;
9781   dwo_unit->signature = DW_UNSND (attr);
9782   dwo_unit->section = section;
9783   dwo_unit->sect_off = sect_off;
9784   dwo_unit->length = cu->per_cu->length;
9785
9786   if (dwarf_read_debug)
9787     fprintf_unfiltered (gdb_stdlog, "  offset 0x%x, dwo_id %s\n",
9788                         to_underlying (sect_off),
9789                         hex_string (dwo_unit->signature));
9790 }
9791
9792 /* Create the dwo_units for the CUs in a DWO_FILE.
9793    Note: This function processes DWO files only, not DWP files.  */
9794
9795 static void
9796 create_cus_hash_table (struct dwo_file &dwo_file, dwarf2_section_info &section,
9797                        htab_t &cus_htab)
9798 {
9799   struct objfile *objfile = dwarf2_per_objfile->objfile;
9800   const struct dwarf2_section_info *abbrev_section = &dwo_file.sections.abbrev;
9801   const gdb_byte *info_ptr, *end_ptr;
9802
9803   dwarf2_read_section (objfile, &section);
9804   info_ptr = section.buffer;
9805
9806   if (info_ptr == NULL)
9807     return;
9808
9809   if (dwarf_read_debug)
9810     {
9811       fprintf_unfiltered (gdb_stdlog, "Reading %s for %s:\n",
9812                           get_section_name (&section),
9813                           get_section_file_name (&section));
9814     }
9815
9816   end_ptr = info_ptr + section.size;
9817   while (info_ptr < end_ptr)
9818     {
9819       struct dwarf2_per_cu_data per_cu;
9820       struct create_dwo_cu_data create_dwo_cu_data;
9821       struct dwo_unit *dwo_unit;
9822       void **slot;
9823       sect_offset sect_off = (sect_offset) (info_ptr - section.buffer);
9824
9825       memset (&create_dwo_cu_data.dwo_unit, 0,
9826               sizeof (create_dwo_cu_data.dwo_unit));
9827       memset (&per_cu, 0, sizeof (per_cu));
9828       per_cu.objfile = objfile;
9829       per_cu.is_debug_types = 0;
9830       per_cu.sect_off = sect_offset (info_ptr - section.buffer);
9831       per_cu.section = &section;
9832       create_dwo_cu_data.dwo_file = &dwo_file;
9833
9834       init_cutu_and_read_dies_no_follow (
9835           &per_cu, &dwo_file, create_dwo_cu_reader, &create_dwo_cu_data);
9836       info_ptr += per_cu.length;
9837
9838       // If the unit could not be parsed, skip it.
9839       if (create_dwo_cu_data.dwo_unit.dwo_file == NULL)
9840         continue;
9841
9842       if (cus_htab == NULL)
9843         cus_htab = allocate_dwo_unit_table (objfile);
9844
9845       dwo_unit = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_unit);
9846       *dwo_unit = create_dwo_cu_data.dwo_unit;
9847       slot = htab_find_slot (cus_htab, dwo_unit, INSERT);
9848       gdb_assert (slot != NULL);
9849       if (*slot != NULL)
9850         {
9851           const struct dwo_unit *dup_cu = (const struct dwo_unit *)*slot;
9852           sect_offset dup_sect_off = dup_cu->sect_off;
9853
9854           complaint (&symfile_complaints,
9855                      _("debug cu entry at offset 0x%x is duplicate to"
9856                        " the entry at offset 0x%x, signature %s"),
9857                      to_underlying (sect_off), to_underlying (dup_sect_off),
9858                      hex_string (dwo_unit->signature));
9859         }
9860       *slot = (void *)dwo_unit;
9861     }
9862 }
9863
9864 /* DWP file .debug_{cu,tu}_index section format:
9865    [ref: http://gcc.gnu.org/wiki/DebugFissionDWP]
9866
9867    DWP Version 1:
9868
9869    Both index sections have the same format, and serve to map a 64-bit
9870    signature to a set of section numbers.  Each section begins with a header,
9871    followed by a hash table of 64-bit signatures, a parallel table of 32-bit
9872    indexes, and a pool of 32-bit section numbers.  The index sections will be
9873    aligned at 8-byte boundaries in the file.
9874
9875    The index section header consists of:
9876
9877     V, 32 bit version number
9878     -, 32 bits unused
9879     N, 32 bit number of compilation units or type units in the index
9880     M, 32 bit number of slots in the hash table
9881
9882    Numbers are recorded using the byte order of the application binary.
9883
9884    The hash table begins at offset 16 in the section, and consists of an array
9885    of M 64-bit slots.  Each slot contains a 64-bit signature (using the byte
9886    order of the application binary).  Unused slots in the hash table are 0.
9887    (We rely on the extreme unlikeliness of a signature being exactly 0.)
9888
9889    The parallel table begins immediately after the hash table
9890    (at offset 16 + 8 * M from the beginning of the section), and consists of an
9891    array of 32-bit indexes (using the byte order of the application binary),
9892    corresponding 1-1 with slots in the hash table.  Each entry in the parallel
9893    table contains a 32-bit index into the pool of section numbers.  For unused
9894    hash table slots, the corresponding entry in the parallel table will be 0.
9895
9896    The pool of section numbers begins immediately following the hash table
9897    (at offset 16 + 12 * M from the beginning of the section).  The pool of
9898    section numbers consists of an array of 32-bit words (using the byte order
9899    of the application binary).  Each item in the array is indexed starting
9900    from 0.  The hash table entry provides the index of the first section
9901    number in the set.  Additional section numbers in the set follow, and the
9902    set is terminated by a 0 entry (section number 0 is not used in ELF).
9903
9904    In each set of section numbers, the .debug_info.dwo or .debug_types.dwo
9905    section must be the first entry in the set, and the .debug_abbrev.dwo must
9906    be the second entry. Other members of the set may follow in any order.
9907
9908    ---
9909
9910    DWP Version 2:
9911
9912    DWP Version 2 combines all the .debug_info, etc. sections into one,
9913    and the entries in the index tables are now offsets into these sections.
9914    CU offsets begin at 0.  TU offsets begin at the size of the .debug_info
9915    section.
9916
9917    Index Section Contents:
9918     Header
9919     Hash Table of Signatures   dwp_hash_table.hash_table
9920     Parallel Table of Indices  dwp_hash_table.unit_table
9921     Table of Section Offsets   dwp_hash_table.v2.{section_ids,offsets}
9922     Table of Section Sizes     dwp_hash_table.v2.sizes
9923
9924    The index section header consists of:
9925
9926     V, 32 bit version number
9927     L, 32 bit number of columns in the table of section offsets
9928     N, 32 bit number of compilation units or type units in the index
9929     M, 32 bit number of slots in the hash table
9930
9931    Numbers are recorded using the byte order of the application binary.
9932
9933    The hash table has the same format as version 1.
9934    The parallel table of indices has the same format as version 1,
9935    except that the entries are origin-1 indices into the table of sections
9936    offsets and the table of section sizes.
9937
9938    The table of offsets begins immediately following the parallel table
9939    (at offset 16 + 12 * M from the beginning of the section).  The table is
9940    a two-dimensional array of 32-bit words (using the byte order of the
9941    application binary), with L columns and N+1 rows, in row-major order.
9942    Each row in the array is indexed starting from 0.  The first row provides
9943    a key to the remaining rows: each column in this row provides an identifier
9944    for a debug section, and the offsets in the same column of subsequent rows
9945    refer to that section.  The section identifiers are:
9946
9947     DW_SECT_INFO         1  .debug_info.dwo
9948     DW_SECT_TYPES        2  .debug_types.dwo
9949     DW_SECT_ABBREV       3  .debug_abbrev.dwo
9950     DW_SECT_LINE         4  .debug_line.dwo
9951     DW_SECT_LOC          5  .debug_loc.dwo
9952     DW_SECT_STR_OFFSETS  6  .debug_str_offsets.dwo
9953     DW_SECT_MACINFO      7  .debug_macinfo.dwo
9954     DW_SECT_MACRO        8  .debug_macro.dwo
9955
9956    The offsets provided by the CU and TU index sections are the base offsets
9957    for the contributions made by each CU or TU to the corresponding section
9958    in the package file.  Each CU and TU header contains an abbrev_offset
9959    field, used to find the abbreviations table for that CU or TU within the
9960    contribution to the .debug_abbrev.dwo section for that CU or TU, and should
9961    be interpreted as relative to the base offset given in the index section.
9962    Likewise, offsets into .debug_line.dwo from DW_AT_stmt_list attributes
9963    should be interpreted as relative to the base offset for .debug_line.dwo,
9964    and offsets into other debug sections obtained from DWARF attributes should
9965    also be interpreted as relative to the corresponding base offset.
9966
9967    The table of sizes begins immediately following the table of offsets.
9968    Like the table of offsets, it is a two-dimensional array of 32-bit words,
9969    with L columns and N rows, in row-major order.  Each row in the array is
9970    indexed starting from 1 (row 0 is shared by the two tables).
9971
9972    ---
9973
9974    Hash table lookup is handled the same in version 1 and 2:
9975
9976    We assume that N and M will not exceed 2^32 - 1.
9977    The size of the hash table, M, must be 2^k such that 2^k > 3*N/2.
9978
9979    Given a 64-bit compilation unit signature or a type signature S, an entry
9980    in the hash table is located as follows:
9981
9982    1) Calculate a primary hash H = S & MASK(k), where MASK(k) is a mask with
9983       the low-order k bits all set to 1.
9984
9985    2) Calculate a secondary hash H' = (((S >> 32) & MASK(k)) | 1).
9986
9987    3) If the hash table entry at index H matches the signature, use that
9988       entry.  If the hash table entry at index H is unused (all zeroes),
9989       terminate the search: the signature is not present in the table.
9990
9991    4) Let H = (H + H') modulo M. Repeat at Step 3.
9992
9993    Because M > N and H' and M are relatively prime, the search is guaranteed
9994    to stop at an unused slot or find the match.  */
9995
9996 /* Create a hash table to map DWO IDs to their CU/TU entry in
9997    .debug_{info,types}.dwo in DWP_FILE.
9998    Returns NULL if there isn't one.
9999    Note: This function processes DWP files only, not DWO files.  */
10000
10001 static struct dwp_hash_table *
10002 create_dwp_hash_table (struct dwp_file *dwp_file, int is_debug_types)
10003 {
10004   struct objfile *objfile = dwarf2_per_objfile->objfile;
10005   bfd *dbfd = dwp_file->dbfd;
10006   const gdb_byte *index_ptr, *index_end;
10007   struct dwarf2_section_info *index;
10008   uint32_t version, nr_columns, nr_units, nr_slots;
10009   struct dwp_hash_table *htab;
10010
10011   if (is_debug_types)
10012     index = &dwp_file->sections.tu_index;
10013   else
10014     index = &dwp_file->sections.cu_index;
10015
10016   if (dwarf2_section_empty_p (index))
10017     return NULL;
10018   dwarf2_read_section (objfile, index);
10019
10020   index_ptr = index->buffer;
10021   index_end = index_ptr + index->size;
10022
10023   version = read_4_bytes (dbfd, index_ptr);
10024   index_ptr += 4;
10025   if (version == 2)
10026     nr_columns = read_4_bytes (dbfd, index_ptr);
10027   else
10028     nr_columns = 0;
10029   index_ptr += 4;
10030   nr_units = read_4_bytes (dbfd, index_ptr);
10031   index_ptr += 4;
10032   nr_slots = read_4_bytes (dbfd, index_ptr);
10033   index_ptr += 4;
10034
10035   if (version != 1 && version != 2)
10036     {
10037       error (_("Dwarf Error: unsupported DWP file version (%s)"
10038                " [in module %s]"),
10039              pulongest (version), dwp_file->name);
10040     }
10041   if (nr_slots != (nr_slots & -nr_slots))
10042     {
10043       error (_("Dwarf Error: number of slots in DWP hash table (%s)"
10044                " is not power of 2 [in module %s]"),
10045              pulongest (nr_slots), dwp_file->name);
10046     }
10047
10048   htab = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwp_hash_table);
10049   htab->version = version;
10050   htab->nr_columns = nr_columns;
10051   htab->nr_units = nr_units;
10052   htab->nr_slots = nr_slots;
10053   htab->hash_table = index_ptr;
10054   htab->unit_table = htab->hash_table + sizeof (uint64_t) * nr_slots;
10055
10056   /* Exit early if the table is empty.  */
10057   if (nr_slots == 0 || nr_units == 0
10058       || (version == 2 && nr_columns == 0))
10059     {
10060       /* All must be zero.  */
10061       if (nr_slots != 0 || nr_units != 0
10062           || (version == 2 && nr_columns != 0))
10063         {
10064           complaint (&symfile_complaints,
10065                      _("Empty DWP but nr_slots,nr_units,nr_columns not"
10066                        " all zero [in modules %s]"),
10067                      dwp_file->name);
10068         }
10069       return htab;
10070     }
10071
10072   if (version == 1)
10073     {
10074       htab->section_pool.v1.indices =
10075         htab->unit_table + sizeof (uint32_t) * nr_slots;
10076       /* It's harder to decide whether the section is too small in v1.
10077          V1 is deprecated anyway so we punt.  */
10078     }
10079   else
10080     {
10081       const gdb_byte *ids_ptr = htab->unit_table + sizeof (uint32_t) * nr_slots;
10082       int *ids = htab->section_pool.v2.section_ids;
10083       /* Reverse map for error checking.  */
10084       int ids_seen[DW_SECT_MAX + 1];
10085       int i;
10086
10087       if (nr_columns < 2)
10088         {
10089           error (_("Dwarf Error: bad DWP hash table, too few columns"
10090                    " in section table [in module %s]"),
10091                  dwp_file->name);
10092         }
10093       if (nr_columns > MAX_NR_V2_DWO_SECTIONS)
10094         {
10095           error (_("Dwarf Error: bad DWP hash table, too many columns"
10096                    " in section table [in module %s]"),
10097                  dwp_file->name);
10098         }
10099       memset (ids, 255, (DW_SECT_MAX + 1) * sizeof (int32_t));
10100       memset (ids_seen, 255, (DW_SECT_MAX + 1) * sizeof (int32_t));
10101       for (i = 0; i < nr_columns; ++i)
10102         {
10103           int id = read_4_bytes (dbfd, ids_ptr + i * sizeof (uint32_t));
10104
10105           if (id < DW_SECT_MIN || id > DW_SECT_MAX)
10106             {
10107               error (_("Dwarf Error: bad DWP hash table, bad section id %d"
10108                        " in section table [in module %s]"),
10109                      id, dwp_file->name);
10110             }
10111           if (ids_seen[id] != -1)
10112             {
10113               error (_("Dwarf Error: bad DWP hash table, duplicate section"
10114                        " id %d in section table [in module %s]"),
10115                      id, dwp_file->name);
10116             }
10117           ids_seen[id] = i;
10118           ids[i] = id;
10119         }
10120       /* Must have exactly one info or types section.  */
10121       if (((ids_seen[DW_SECT_INFO] != -1)
10122            + (ids_seen[DW_SECT_TYPES] != -1))
10123           != 1)
10124         {
10125           error (_("Dwarf Error: bad DWP hash table, missing/duplicate"
10126                    " DWO info/types section [in module %s]"),
10127                  dwp_file->name);
10128         }
10129       /* Must have an abbrev section.  */
10130       if (ids_seen[DW_SECT_ABBREV] == -1)
10131         {
10132           error (_("Dwarf Error: bad DWP hash table, missing DWO abbrev"
10133                    " section [in module %s]"),
10134                  dwp_file->name);
10135         }
10136       htab->section_pool.v2.offsets = ids_ptr + sizeof (uint32_t) * nr_columns;
10137       htab->section_pool.v2.sizes =
10138         htab->section_pool.v2.offsets + (sizeof (uint32_t)
10139                                          * nr_units * nr_columns);
10140       if ((htab->section_pool.v2.sizes + (sizeof (uint32_t)
10141                                           * nr_units * nr_columns))
10142           > index_end)
10143         {
10144           error (_("Dwarf Error: DWP index section is corrupt (too small)"
10145                    " [in module %s]"),
10146                  dwp_file->name);
10147         }
10148     }
10149
10150   return htab;
10151 }
10152
10153 /* Update SECTIONS with the data from SECTP.
10154
10155    This function is like the other "locate" section routines that are
10156    passed to bfd_map_over_sections, but in this context the sections to
10157    read comes from the DWP V1 hash table, not the full ELF section table.
10158
10159    The result is non-zero for success, or zero if an error was found.  */
10160
10161 static int
10162 locate_v1_virtual_dwo_sections (asection *sectp,
10163                                 struct virtual_v1_dwo_sections *sections)
10164 {
10165   const struct dwop_section_names *names = &dwop_section_names;
10166
10167   if (section_is_p (sectp->name, &names->abbrev_dwo))
10168     {
10169       /* There can be only one.  */
10170       if (sections->abbrev.s.section != NULL)
10171         return 0;
10172       sections->abbrev.s.section = sectp;
10173       sections->abbrev.size = bfd_get_section_size (sectp);
10174     }
10175   else if (section_is_p (sectp->name, &names->info_dwo)
10176            || section_is_p (sectp->name, &names->types_dwo))
10177     {
10178       /* There can be only one.  */
10179       if (sections->info_or_types.s.section != NULL)
10180         return 0;
10181       sections->info_or_types.s.section = sectp;
10182       sections->info_or_types.size = bfd_get_section_size (sectp);
10183     }
10184   else if (section_is_p (sectp->name, &names->line_dwo))
10185     {
10186       /* There can be only one.  */
10187       if (sections->line.s.section != NULL)
10188         return 0;
10189       sections->line.s.section = sectp;
10190       sections->line.size = bfd_get_section_size (sectp);
10191     }
10192   else if (section_is_p (sectp->name, &names->loc_dwo))
10193     {
10194       /* There can be only one.  */
10195       if (sections->loc.s.section != NULL)
10196         return 0;
10197       sections->loc.s.section = sectp;
10198       sections->loc.size = bfd_get_section_size (sectp);
10199     }
10200   else if (section_is_p (sectp->name, &names->macinfo_dwo))
10201     {
10202       /* There can be only one.  */
10203       if (sections->macinfo.s.section != NULL)
10204         return 0;
10205       sections->macinfo.s.section = sectp;
10206       sections->macinfo.size = bfd_get_section_size (sectp);
10207     }
10208   else if (section_is_p (sectp->name, &names->macro_dwo))
10209     {
10210       /* There can be only one.  */
10211       if (sections->macro.s.section != NULL)
10212         return 0;
10213       sections->macro.s.section = sectp;
10214       sections->macro.size = bfd_get_section_size (sectp);
10215     }
10216   else if (section_is_p (sectp->name, &names->str_offsets_dwo))
10217     {
10218       /* There can be only one.  */
10219       if (sections->str_offsets.s.section != NULL)
10220         return 0;
10221       sections->str_offsets.s.section = sectp;
10222       sections->str_offsets.size = bfd_get_section_size (sectp);
10223     }
10224   else
10225     {
10226       /* No other kind of section is valid.  */
10227       return 0;
10228     }
10229
10230   return 1;
10231 }
10232
10233 /* Create a dwo_unit object for the DWO unit with signature SIGNATURE.
10234    UNIT_INDEX is the index of the DWO unit in the DWP hash table.
10235    COMP_DIR is the DW_AT_comp_dir attribute of the referencing CU.
10236    This is for DWP version 1 files.  */
10237
10238 static struct dwo_unit *
10239 create_dwo_unit_in_dwp_v1 (struct dwp_file *dwp_file,
10240                            uint32_t unit_index,
10241                            const char *comp_dir,
10242                            ULONGEST signature, int is_debug_types)
10243 {
10244   struct objfile *objfile = dwarf2_per_objfile->objfile;
10245   const struct dwp_hash_table *dwp_htab =
10246     is_debug_types ? dwp_file->tus : dwp_file->cus;
10247   bfd *dbfd = dwp_file->dbfd;
10248   const char *kind = is_debug_types ? "TU" : "CU";
10249   struct dwo_file *dwo_file;
10250   struct dwo_unit *dwo_unit;
10251   struct virtual_v1_dwo_sections sections;
10252   void **dwo_file_slot;
10253   char *virtual_dwo_name;
10254   struct cleanup *cleanups;
10255   int i;
10256
10257   gdb_assert (dwp_file->version == 1);
10258
10259   if (dwarf_read_debug)
10260     {
10261       fprintf_unfiltered (gdb_stdlog, "Reading %s %s/%s in DWP V1 file: %s\n",
10262                           kind,
10263                           pulongest (unit_index), hex_string (signature),
10264                           dwp_file->name);
10265     }
10266
10267   /* Fetch the sections of this DWO unit.
10268      Put a limit on the number of sections we look for so that bad data
10269      doesn't cause us to loop forever.  */
10270
10271 #define MAX_NR_V1_DWO_SECTIONS \
10272   (1 /* .debug_info or .debug_types */ \
10273    + 1 /* .debug_abbrev */ \
10274    + 1 /* .debug_line */ \
10275    + 1 /* .debug_loc */ \
10276    + 1 /* .debug_str_offsets */ \
10277    + 1 /* .debug_macro or .debug_macinfo */ \
10278    + 1 /* trailing zero */)
10279
10280   memset (&sections, 0, sizeof (sections));
10281   cleanups = make_cleanup (null_cleanup, 0);
10282
10283   for (i = 0; i < MAX_NR_V1_DWO_SECTIONS; ++i)
10284     {
10285       asection *sectp;
10286       uint32_t section_nr =
10287         read_4_bytes (dbfd,
10288                       dwp_htab->section_pool.v1.indices
10289                       + (unit_index + i) * sizeof (uint32_t));
10290
10291       if (section_nr == 0)
10292         break;
10293       if (section_nr >= dwp_file->num_sections)
10294         {
10295           error (_("Dwarf Error: bad DWP hash table, section number too large"
10296                    " [in module %s]"),
10297                  dwp_file->name);
10298         }
10299
10300       sectp = dwp_file->elf_sections[section_nr];
10301       if (! locate_v1_virtual_dwo_sections (sectp, &sections))
10302         {
10303           error (_("Dwarf Error: bad DWP hash table, invalid section found"
10304                    " [in module %s]"),
10305                  dwp_file->name);
10306         }
10307     }
10308
10309   if (i < 2
10310       || dwarf2_section_empty_p (&sections.info_or_types)
10311       || dwarf2_section_empty_p (&sections.abbrev))
10312     {
10313       error (_("Dwarf Error: bad DWP hash table, missing DWO sections"
10314                " [in module %s]"),
10315              dwp_file->name);
10316     }
10317   if (i == MAX_NR_V1_DWO_SECTIONS)
10318     {
10319       error (_("Dwarf Error: bad DWP hash table, too many DWO sections"
10320                " [in module %s]"),
10321              dwp_file->name);
10322     }
10323
10324   /* It's easier for the rest of the code if we fake a struct dwo_file and
10325      have dwo_unit "live" in that.  At least for now.
10326
10327      The DWP file can be made up of a random collection of CUs and TUs.
10328      However, for each CU + set of TUs that came from the same original DWO
10329      file, we can combine them back into a virtual DWO file to save space
10330      (fewer struct dwo_file objects to allocate).  Remember that for really
10331      large apps there can be on the order of 8K CUs and 200K TUs, or more.  */
10332
10333   virtual_dwo_name =
10334     xstrprintf ("virtual-dwo/%d-%d-%d-%d",
10335                 get_section_id (&sections.abbrev),
10336                 get_section_id (&sections.line),
10337                 get_section_id (&sections.loc),
10338                 get_section_id (&sections.str_offsets));
10339   make_cleanup (xfree, virtual_dwo_name);
10340   /* Can we use an existing virtual DWO file?  */
10341   dwo_file_slot = lookup_dwo_file_slot (virtual_dwo_name, comp_dir);
10342   /* Create one if necessary.  */
10343   if (*dwo_file_slot == NULL)
10344     {
10345       if (dwarf_read_debug)
10346         {
10347           fprintf_unfiltered (gdb_stdlog, "Creating virtual DWO: %s\n",
10348                               virtual_dwo_name);
10349         }
10350       dwo_file = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_file);
10351       dwo_file->dwo_name
10352         = (const char *) obstack_copy0 (&objfile->objfile_obstack,
10353                                         virtual_dwo_name,
10354                                         strlen (virtual_dwo_name));
10355       dwo_file->comp_dir = comp_dir;
10356       dwo_file->sections.abbrev = sections.abbrev;
10357       dwo_file->sections.line = sections.line;
10358       dwo_file->sections.loc = sections.loc;
10359       dwo_file->sections.macinfo = sections.macinfo;
10360       dwo_file->sections.macro = sections.macro;
10361       dwo_file->sections.str_offsets = sections.str_offsets;
10362       /* The "str" section is global to the entire DWP file.  */
10363       dwo_file->sections.str = dwp_file->sections.str;
10364       /* The info or types section is assigned below to dwo_unit,
10365          there's no need to record it in dwo_file.
10366          Also, we can't simply record type sections in dwo_file because
10367          we record a pointer into the vector in dwo_unit.  As we collect more
10368          types we'll grow the vector and eventually have to reallocate space
10369          for it, invalidating all copies of pointers into the previous
10370          contents.  */
10371       *dwo_file_slot = dwo_file;
10372     }
10373   else
10374     {
10375       if (dwarf_read_debug)
10376         {
10377           fprintf_unfiltered (gdb_stdlog, "Using existing virtual DWO: %s\n",
10378                               virtual_dwo_name);
10379         }
10380       dwo_file = (struct dwo_file *) *dwo_file_slot;
10381     }
10382   do_cleanups (cleanups);
10383
10384   dwo_unit = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_unit);
10385   dwo_unit->dwo_file = dwo_file;
10386   dwo_unit->signature = signature;
10387   dwo_unit->section =
10388     XOBNEW (&objfile->objfile_obstack, struct dwarf2_section_info);
10389   *dwo_unit->section = sections.info_or_types;
10390   /* dwo_unit->{offset,length,type_offset_in_tu} are set later.  */
10391
10392   return dwo_unit;
10393 }
10394
10395 /* Subroutine of create_dwo_unit_in_dwp_v2 to simplify it.
10396    Given a pointer to the containing section SECTION, and OFFSET,SIZE of the
10397    piece within that section used by a TU/CU, return a virtual section
10398    of just that piece.  */
10399
10400 static struct dwarf2_section_info
10401 create_dwp_v2_section (struct dwarf2_section_info *section,
10402                        bfd_size_type offset, bfd_size_type size)
10403 {
10404   struct dwarf2_section_info result;
10405   asection *sectp;
10406
10407   gdb_assert (section != NULL);
10408   gdb_assert (!section->is_virtual);
10409
10410   memset (&result, 0, sizeof (result));
10411   result.s.containing_section = section;
10412   result.is_virtual = 1;
10413
10414   if (size == 0)
10415     return result;
10416
10417   sectp = get_section_bfd_section (section);
10418
10419   /* Flag an error if the piece denoted by OFFSET,SIZE is outside the
10420      bounds of the real section.  This is a pretty-rare event, so just
10421      flag an error (easier) instead of a warning and trying to cope.  */
10422   if (sectp == NULL
10423       || offset + size > bfd_get_section_size (sectp))
10424     {
10425       bfd *abfd = sectp->owner;
10426
10427       error (_("Dwarf Error: Bad DWP V2 section info, doesn't fit"
10428                " in section %s [in module %s]"),
10429              sectp ? bfd_section_name (abfd, sectp) : "<unknown>",
10430              objfile_name (dwarf2_per_objfile->objfile));
10431     }
10432
10433   result.virtual_offset = offset;
10434   result.size = size;
10435   return result;
10436 }
10437
10438 /* Create a dwo_unit object for the DWO unit with signature SIGNATURE.
10439    UNIT_INDEX is the index of the DWO unit in the DWP hash table.
10440    COMP_DIR is the DW_AT_comp_dir attribute of the referencing CU.
10441    This is for DWP version 2 files.  */
10442
10443 static struct dwo_unit *
10444 create_dwo_unit_in_dwp_v2 (struct dwp_file *dwp_file,
10445                            uint32_t unit_index,
10446                            const char *comp_dir,
10447                            ULONGEST signature, int is_debug_types)
10448 {
10449   struct objfile *objfile = dwarf2_per_objfile->objfile;
10450   const struct dwp_hash_table *dwp_htab =
10451     is_debug_types ? dwp_file->tus : dwp_file->cus;
10452   bfd *dbfd = dwp_file->dbfd;
10453   const char *kind = is_debug_types ? "TU" : "CU";
10454   struct dwo_file *dwo_file;
10455   struct dwo_unit *dwo_unit;
10456   struct virtual_v2_dwo_sections sections;
10457   void **dwo_file_slot;
10458   char *virtual_dwo_name;
10459   struct cleanup *cleanups;
10460   int i;
10461
10462   gdb_assert (dwp_file->version == 2);
10463
10464   if (dwarf_read_debug)
10465     {
10466       fprintf_unfiltered (gdb_stdlog, "Reading %s %s/%s in DWP V2 file: %s\n",
10467                           kind,
10468                           pulongest (unit_index), hex_string (signature),
10469                           dwp_file->name);
10470     }
10471
10472   /* Fetch the section offsets of this DWO unit.  */
10473
10474   memset (&sections, 0, sizeof (sections));
10475   cleanups = make_cleanup (null_cleanup, 0);
10476
10477   for (i = 0; i < dwp_htab->nr_columns; ++i)
10478     {
10479       uint32_t offset = read_4_bytes (dbfd,
10480                                       dwp_htab->section_pool.v2.offsets
10481                                       + (((unit_index - 1) * dwp_htab->nr_columns
10482                                           + i)
10483                                          * sizeof (uint32_t)));
10484       uint32_t size = read_4_bytes (dbfd,
10485                                     dwp_htab->section_pool.v2.sizes
10486                                     + (((unit_index - 1) * dwp_htab->nr_columns
10487                                         + i)
10488                                        * sizeof (uint32_t)));
10489
10490       switch (dwp_htab->section_pool.v2.section_ids[i])
10491         {
10492         case DW_SECT_INFO:
10493         case DW_SECT_TYPES:
10494           sections.info_or_types_offset = offset;
10495           sections.info_or_types_size = size;
10496           break;
10497         case DW_SECT_ABBREV:
10498           sections.abbrev_offset = offset;
10499           sections.abbrev_size = size;
10500           break;
10501         case DW_SECT_LINE:
10502           sections.line_offset = offset;
10503           sections.line_size = size;
10504           break;
10505         case DW_SECT_LOC:
10506           sections.loc_offset = offset;
10507           sections.loc_size = size;
10508           break;
10509         case DW_SECT_STR_OFFSETS:
10510           sections.str_offsets_offset = offset;
10511           sections.str_offsets_size = size;
10512           break;
10513         case DW_SECT_MACINFO:
10514           sections.macinfo_offset = offset;
10515           sections.macinfo_size = size;
10516           break;
10517         case DW_SECT_MACRO:
10518           sections.macro_offset = offset;
10519           sections.macro_size = size;
10520           break;
10521         }
10522     }
10523
10524   /* It's easier for the rest of the code if we fake a struct dwo_file and
10525      have dwo_unit "live" in that.  At least for now.
10526
10527      The DWP file can be made up of a random collection of CUs and TUs.
10528      However, for each CU + set of TUs that came from the same original DWO
10529      file, we can combine them back into a virtual DWO file to save space
10530      (fewer struct dwo_file objects to allocate).  Remember that for really
10531      large apps there can be on the order of 8K CUs and 200K TUs, or more.  */
10532
10533   virtual_dwo_name =
10534     xstrprintf ("virtual-dwo/%ld-%ld-%ld-%ld",
10535                 (long) (sections.abbrev_size ? sections.abbrev_offset : 0),
10536                 (long) (sections.line_size ? sections.line_offset : 0),
10537                 (long) (sections.loc_size ? sections.loc_offset : 0),
10538                 (long) (sections.str_offsets_size
10539                         ? sections.str_offsets_offset : 0));
10540   make_cleanup (xfree, virtual_dwo_name);
10541   /* Can we use an existing virtual DWO file?  */
10542   dwo_file_slot = lookup_dwo_file_slot (virtual_dwo_name, comp_dir);
10543   /* Create one if necessary.  */
10544   if (*dwo_file_slot == NULL)
10545     {
10546       if (dwarf_read_debug)
10547         {
10548           fprintf_unfiltered (gdb_stdlog, "Creating virtual DWO: %s\n",
10549                               virtual_dwo_name);
10550         }
10551       dwo_file = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_file);
10552       dwo_file->dwo_name
10553         = (const char *) obstack_copy0 (&objfile->objfile_obstack,
10554                                         virtual_dwo_name,
10555                                         strlen (virtual_dwo_name));
10556       dwo_file->comp_dir = comp_dir;
10557       dwo_file->sections.abbrev =
10558         create_dwp_v2_section (&dwp_file->sections.abbrev,
10559                                sections.abbrev_offset, sections.abbrev_size);
10560       dwo_file->sections.line =
10561         create_dwp_v2_section (&dwp_file->sections.line,
10562                                sections.line_offset, sections.line_size);
10563       dwo_file->sections.loc =
10564         create_dwp_v2_section (&dwp_file->sections.loc,
10565                                sections.loc_offset, sections.loc_size);
10566       dwo_file->sections.macinfo =
10567         create_dwp_v2_section (&dwp_file->sections.macinfo,
10568                                sections.macinfo_offset, sections.macinfo_size);
10569       dwo_file->sections.macro =
10570         create_dwp_v2_section (&dwp_file->sections.macro,
10571                                sections.macro_offset, sections.macro_size);
10572       dwo_file->sections.str_offsets =
10573         create_dwp_v2_section (&dwp_file->sections.str_offsets,
10574                                sections.str_offsets_offset,
10575                                sections.str_offsets_size);
10576       /* The "str" section is global to the entire DWP file.  */
10577       dwo_file->sections.str = dwp_file->sections.str;
10578       /* The info or types section is assigned below to dwo_unit,
10579          there's no need to record it in dwo_file.
10580          Also, we can't simply record type sections in dwo_file because
10581          we record a pointer into the vector in dwo_unit.  As we collect more
10582          types we'll grow the vector and eventually have to reallocate space
10583          for it, invalidating all copies of pointers into the previous
10584          contents.  */
10585       *dwo_file_slot = dwo_file;
10586     }
10587   else
10588     {
10589       if (dwarf_read_debug)
10590         {
10591           fprintf_unfiltered (gdb_stdlog, "Using existing virtual DWO: %s\n",
10592                               virtual_dwo_name);
10593         }
10594       dwo_file = (struct dwo_file *) *dwo_file_slot;
10595     }
10596   do_cleanups (cleanups);
10597
10598   dwo_unit = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_unit);
10599   dwo_unit->dwo_file = dwo_file;
10600   dwo_unit->signature = signature;
10601   dwo_unit->section =
10602     XOBNEW (&objfile->objfile_obstack, struct dwarf2_section_info);
10603   *dwo_unit->section = create_dwp_v2_section (is_debug_types
10604                                               ? &dwp_file->sections.types
10605                                               : &dwp_file->sections.info,
10606                                               sections.info_or_types_offset,
10607                                               sections.info_or_types_size);
10608   /* dwo_unit->{offset,length,type_offset_in_tu} are set later.  */
10609
10610   return dwo_unit;
10611 }
10612
10613 /* Lookup the DWO unit with SIGNATURE in DWP_FILE.
10614    Returns NULL if the signature isn't found.  */
10615
10616 static struct dwo_unit *
10617 lookup_dwo_unit_in_dwp (struct dwp_file *dwp_file, const char *comp_dir,
10618                         ULONGEST signature, int is_debug_types)
10619 {
10620   const struct dwp_hash_table *dwp_htab =
10621     is_debug_types ? dwp_file->tus : dwp_file->cus;
10622   bfd *dbfd = dwp_file->dbfd;
10623   uint32_t mask = dwp_htab->nr_slots - 1;
10624   uint32_t hash = signature & mask;
10625   uint32_t hash2 = ((signature >> 32) & mask) | 1;
10626   unsigned int i;
10627   void **slot;
10628   struct dwo_unit find_dwo_cu;
10629
10630   memset (&find_dwo_cu, 0, sizeof (find_dwo_cu));
10631   find_dwo_cu.signature = signature;
10632   slot = htab_find_slot (is_debug_types
10633                          ? dwp_file->loaded_tus
10634                          : dwp_file->loaded_cus,
10635                          &find_dwo_cu, INSERT);
10636
10637   if (*slot != NULL)
10638     return (struct dwo_unit *) *slot;
10639
10640   /* Use a for loop so that we don't loop forever on bad debug info.  */
10641   for (i = 0; i < dwp_htab->nr_slots; ++i)
10642     {
10643       ULONGEST signature_in_table;
10644
10645       signature_in_table =
10646         read_8_bytes (dbfd, dwp_htab->hash_table + hash * sizeof (uint64_t));
10647       if (signature_in_table == signature)
10648         {
10649           uint32_t unit_index =
10650             read_4_bytes (dbfd,
10651                           dwp_htab->unit_table + hash * sizeof (uint32_t));
10652
10653           if (dwp_file->version == 1)
10654             {
10655               *slot = create_dwo_unit_in_dwp_v1 (dwp_file, unit_index,
10656                                                  comp_dir, signature,
10657                                                  is_debug_types);
10658             }
10659           else
10660             {
10661               *slot = create_dwo_unit_in_dwp_v2 (dwp_file, unit_index,
10662                                                  comp_dir, signature,
10663                                                  is_debug_types);
10664             }
10665           return (struct dwo_unit *) *slot;
10666         }
10667       if (signature_in_table == 0)
10668         return NULL;
10669       hash = (hash + hash2) & mask;
10670     }
10671
10672   error (_("Dwarf Error: bad DWP hash table, lookup didn't terminate"
10673            " [in module %s]"),
10674          dwp_file->name);
10675 }
10676
10677 /* Subroutine of open_dwo_file,open_dwp_file to simplify them.
10678    Open the file specified by FILE_NAME and hand it off to BFD for
10679    preliminary analysis.  Return a newly initialized bfd *, which
10680    includes a canonicalized copy of FILE_NAME.
10681    If IS_DWP is TRUE, we're opening a DWP file, otherwise a DWO file.
10682    SEARCH_CWD is true if the current directory is to be searched.
10683    It will be searched before debug-file-directory.
10684    If successful, the file is added to the bfd include table of the
10685    objfile's bfd (see gdb_bfd_record_inclusion).
10686    If unable to find/open the file, return NULL.
10687    NOTE: This function is derived from symfile_bfd_open.  */
10688
10689 static gdb_bfd_ref_ptr
10690 try_open_dwop_file (const char *file_name, int is_dwp, int search_cwd)
10691 {
10692   int desc, flags;
10693   char *absolute_name;
10694   /* Blech.  OPF_TRY_CWD_FIRST also disables searching the path list if
10695      FILE_NAME contains a '/'.  So we can't use it.  Instead prepend "."
10696      to debug_file_directory.  */
10697   char *search_path;
10698   static const char dirname_separator_string[] = { DIRNAME_SEPARATOR, '\0' };
10699
10700   if (search_cwd)
10701     {
10702       if (*debug_file_directory != '\0')
10703         search_path = concat (".", dirname_separator_string,
10704                               debug_file_directory, (char *) NULL);
10705       else
10706         search_path = xstrdup (".");
10707     }
10708   else
10709     search_path = xstrdup (debug_file_directory);
10710
10711   flags = OPF_RETURN_REALPATH;
10712   if (is_dwp)
10713     flags |= OPF_SEARCH_IN_PATH;
10714   desc = openp (search_path, flags, file_name,
10715                 O_RDONLY | O_BINARY, &absolute_name);
10716   xfree (search_path);
10717   if (desc < 0)
10718     return NULL;
10719
10720   gdb_bfd_ref_ptr sym_bfd (gdb_bfd_open (absolute_name, gnutarget, desc));
10721   xfree (absolute_name);
10722   if (sym_bfd == NULL)
10723     return NULL;
10724   bfd_set_cacheable (sym_bfd.get (), 1);
10725
10726   if (!bfd_check_format (sym_bfd.get (), bfd_object))
10727     return NULL;
10728
10729   /* Success.  Record the bfd as having been included by the objfile's bfd.
10730      This is important because things like demangled_names_hash lives in the
10731      objfile's per_bfd space and may have references to things like symbol
10732      names that live in the DWO/DWP file's per_bfd space.  PR 16426.  */
10733   gdb_bfd_record_inclusion (dwarf2_per_objfile->objfile->obfd, sym_bfd.get ());
10734
10735   return sym_bfd;
10736 }
10737
10738 /* Try to open DWO file FILE_NAME.
10739    COMP_DIR is the DW_AT_comp_dir attribute.
10740    The result is the bfd handle of the file.
10741    If there is a problem finding or opening the file, return NULL.
10742    Upon success, the canonicalized path of the file is stored in the bfd,
10743    same as symfile_bfd_open.  */
10744
10745 static gdb_bfd_ref_ptr
10746 open_dwo_file (const char *file_name, const char *comp_dir)
10747 {
10748   if (IS_ABSOLUTE_PATH (file_name))
10749     return try_open_dwop_file (file_name, 0 /*is_dwp*/, 0 /*search_cwd*/);
10750
10751   /* Before trying the search path, try DWO_NAME in COMP_DIR.  */
10752
10753   if (comp_dir != NULL)
10754     {
10755       char *path_to_try = concat (comp_dir, SLASH_STRING,
10756                                   file_name, (char *) NULL);
10757
10758       /* NOTE: If comp_dir is a relative path, this will also try the
10759          search path, which seems useful.  */
10760       gdb_bfd_ref_ptr abfd (try_open_dwop_file (path_to_try, 0 /*is_dwp*/,
10761                                                 1 /*search_cwd*/));
10762       xfree (path_to_try);
10763       if (abfd != NULL)
10764         return abfd;
10765     }
10766
10767   /* That didn't work, try debug-file-directory, which, despite its name,
10768      is a list of paths.  */
10769
10770   if (*debug_file_directory == '\0')
10771     return NULL;
10772
10773   return try_open_dwop_file (file_name, 0 /*is_dwp*/, 1 /*search_cwd*/);
10774 }
10775
10776 /* This function is mapped across the sections and remembers the offset and
10777    size of each of the DWO debugging sections we are interested in.  */
10778
10779 static void
10780 dwarf2_locate_dwo_sections (bfd *abfd, asection *sectp, void *dwo_sections_ptr)
10781 {
10782   struct dwo_sections *dwo_sections = (struct dwo_sections *) dwo_sections_ptr;
10783   const struct dwop_section_names *names = &dwop_section_names;
10784
10785   if (section_is_p (sectp->name, &names->abbrev_dwo))
10786     {
10787       dwo_sections->abbrev.s.section = sectp;
10788       dwo_sections->abbrev.size = bfd_get_section_size (sectp);
10789     }
10790   else if (section_is_p (sectp->name, &names->info_dwo))
10791     {
10792       dwo_sections->info.s.section = sectp;
10793       dwo_sections->info.size = bfd_get_section_size (sectp);
10794     }
10795   else if (section_is_p (sectp->name, &names->line_dwo))
10796     {
10797       dwo_sections->line.s.section = sectp;
10798       dwo_sections->line.size = bfd_get_section_size (sectp);
10799     }
10800   else if (section_is_p (sectp->name, &names->loc_dwo))
10801     {
10802       dwo_sections->loc.s.section = sectp;
10803       dwo_sections->loc.size = bfd_get_section_size (sectp);
10804     }
10805   else if (section_is_p (sectp->name, &names->macinfo_dwo))
10806     {
10807       dwo_sections->macinfo.s.section = sectp;
10808       dwo_sections->macinfo.size = bfd_get_section_size (sectp);
10809     }
10810   else if (section_is_p (sectp->name, &names->macro_dwo))
10811     {
10812       dwo_sections->macro.s.section = sectp;
10813       dwo_sections->macro.size = bfd_get_section_size (sectp);
10814     }
10815   else if (section_is_p (sectp->name, &names->str_dwo))
10816     {
10817       dwo_sections->str.s.section = sectp;
10818       dwo_sections->str.size = bfd_get_section_size (sectp);
10819     }
10820   else if (section_is_p (sectp->name, &names->str_offsets_dwo))
10821     {
10822       dwo_sections->str_offsets.s.section = sectp;
10823       dwo_sections->str_offsets.size = bfd_get_section_size (sectp);
10824     }
10825   else if (section_is_p (sectp->name, &names->types_dwo))
10826     {
10827       struct dwarf2_section_info type_section;
10828
10829       memset (&type_section, 0, sizeof (type_section));
10830       type_section.s.section = sectp;
10831       type_section.size = bfd_get_section_size (sectp);
10832       VEC_safe_push (dwarf2_section_info_def, dwo_sections->types,
10833                      &type_section);
10834     }
10835 }
10836
10837 /* Initialize the use of the DWO file specified by DWO_NAME and referenced
10838    by PER_CU.  This is for the non-DWP case.
10839    The result is NULL if DWO_NAME can't be found.  */
10840
10841 static struct dwo_file *
10842 open_and_init_dwo_file (struct dwarf2_per_cu_data *per_cu,
10843                         const char *dwo_name, const char *comp_dir)
10844 {
10845   struct objfile *objfile = dwarf2_per_objfile->objfile;
10846   struct dwo_file *dwo_file;
10847   struct cleanup *cleanups;
10848
10849   gdb_bfd_ref_ptr dbfd (open_dwo_file (dwo_name, comp_dir));
10850   if (dbfd == NULL)
10851     {
10852       if (dwarf_read_debug)
10853         fprintf_unfiltered (gdb_stdlog, "DWO file not found: %s\n", dwo_name);
10854       return NULL;
10855     }
10856   dwo_file = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_file);
10857   dwo_file->dwo_name = dwo_name;
10858   dwo_file->comp_dir = comp_dir;
10859   dwo_file->dbfd = dbfd.release ();
10860
10861   cleanups = make_cleanup (free_dwo_file_cleanup, dwo_file);
10862
10863   bfd_map_over_sections (dwo_file->dbfd, dwarf2_locate_dwo_sections,
10864                          &dwo_file->sections);
10865
10866   create_cus_hash_table (*dwo_file, dwo_file->sections.info, dwo_file->cus);
10867
10868   create_debug_types_hash_table (dwo_file, dwo_file->sections.types,
10869                                  dwo_file->tus);
10870
10871   discard_cleanups (cleanups);
10872
10873   if (dwarf_read_debug)
10874     fprintf_unfiltered (gdb_stdlog, "DWO file found: %s\n", dwo_name);
10875
10876   return dwo_file;
10877 }
10878
10879 /* This function is mapped across the sections and remembers the offset and
10880    size of each of the DWP debugging sections common to version 1 and 2 that
10881    we are interested in.  */
10882
10883 static void
10884 dwarf2_locate_common_dwp_sections (bfd *abfd, asection *sectp,
10885                                    void *dwp_file_ptr)
10886 {
10887   struct dwp_file *dwp_file = (struct dwp_file *) dwp_file_ptr;
10888   const struct dwop_section_names *names = &dwop_section_names;
10889   unsigned int elf_section_nr = elf_section_data (sectp)->this_idx;
10890
10891   /* Record the ELF section number for later lookup: this is what the
10892      .debug_cu_index,.debug_tu_index tables use in DWP V1.  */
10893   gdb_assert (elf_section_nr < dwp_file->num_sections);
10894   dwp_file->elf_sections[elf_section_nr] = sectp;
10895
10896   /* Look for specific sections that we need.  */
10897   if (section_is_p (sectp->name, &names->str_dwo))
10898     {
10899       dwp_file->sections.str.s.section = sectp;
10900       dwp_file->sections.str.size = bfd_get_section_size (sectp);
10901     }
10902   else if (section_is_p (sectp->name, &names->cu_index))
10903     {
10904       dwp_file->sections.cu_index.s.section = sectp;
10905       dwp_file->sections.cu_index.size = bfd_get_section_size (sectp);
10906     }
10907   else if (section_is_p (sectp->name, &names->tu_index))
10908     {
10909       dwp_file->sections.tu_index.s.section = sectp;
10910       dwp_file->sections.tu_index.size = bfd_get_section_size (sectp);
10911     }
10912 }
10913
10914 /* This function is mapped across the sections and remembers the offset and
10915    size of each of the DWP version 2 debugging sections that we are interested
10916    in.  This is split into a separate function because we don't know if we
10917    have version 1 or 2 until we parse the cu_index/tu_index sections.  */
10918
10919 static void
10920 dwarf2_locate_v2_dwp_sections (bfd *abfd, asection *sectp, void *dwp_file_ptr)
10921 {
10922   struct dwp_file *dwp_file = (struct dwp_file *) dwp_file_ptr;
10923   const struct dwop_section_names *names = &dwop_section_names;
10924   unsigned int elf_section_nr = elf_section_data (sectp)->this_idx;
10925
10926   /* Record the ELF section number for later lookup: this is what the
10927      .debug_cu_index,.debug_tu_index tables use in DWP V1.  */
10928   gdb_assert (elf_section_nr < dwp_file->num_sections);
10929   dwp_file->elf_sections[elf_section_nr] = sectp;
10930
10931   /* Look for specific sections that we need.  */
10932   if (section_is_p (sectp->name, &names->abbrev_dwo))
10933     {
10934       dwp_file->sections.abbrev.s.section = sectp;
10935       dwp_file->sections.abbrev.size = bfd_get_section_size (sectp);
10936     }
10937   else if (section_is_p (sectp->name, &names->info_dwo))
10938     {
10939       dwp_file->sections.info.s.section = sectp;
10940       dwp_file->sections.info.size = bfd_get_section_size (sectp);
10941     }
10942   else if (section_is_p (sectp->name, &names->line_dwo))
10943     {
10944       dwp_file->sections.line.s.section = sectp;
10945       dwp_file->sections.line.size = bfd_get_section_size (sectp);
10946     }
10947   else if (section_is_p (sectp->name, &names->loc_dwo))
10948     {
10949       dwp_file->sections.loc.s.section = sectp;
10950       dwp_file->sections.loc.size = bfd_get_section_size (sectp);
10951     }
10952   else if (section_is_p (sectp->name, &names->macinfo_dwo))
10953     {
10954       dwp_file->sections.macinfo.s.section = sectp;
10955       dwp_file->sections.macinfo.size = bfd_get_section_size (sectp);
10956     }
10957   else if (section_is_p (sectp->name, &names->macro_dwo))
10958     {
10959       dwp_file->sections.macro.s.section = sectp;
10960       dwp_file->sections.macro.size = bfd_get_section_size (sectp);
10961     }
10962   else if (section_is_p (sectp->name, &names->str_offsets_dwo))
10963     {
10964       dwp_file->sections.str_offsets.s.section = sectp;
10965       dwp_file->sections.str_offsets.size = bfd_get_section_size (sectp);
10966     }
10967   else if (section_is_p (sectp->name, &names->types_dwo))
10968     {
10969       dwp_file->sections.types.s.section = sectp;
10970       dwp_file->sections.types.size = bfd_get_section_size (sectp);
10971     }
10972 }
10973
10974 /* Hash function for dwp_file loaded CUs/TUs.  */
10975
10976 static hashval_t
10977 hash_dwp_loaded_cutus (const void *item)
10978 {
10979   const struct dwo_unit *dwo_unit = (const struct dwo_unit *) item;
10980
10981   /* This drops the top 32 bits of the signature, but is ok for a hash.  */
10982   return dwo_unit->signature;
10983 }
10984
10985 /* Equality function for dwp_file loaded CUs/TUs.  */
10986
10987 static int
10988 eq_dwp_loaded_cutus (const void *a, const void *b)
10989 {
10990   const struct dwo_unit *dua = (const struct dwo_unit *) a;
10991   const struct dwo_unit *dub = (const struct dwo_unit *) b;
10992
10993   return dua->signature == dub->signature;
10994 }
10995
10996 /* Allocate a hash table for dwp_file loaded CUs/TUs.  */
10997
10998 static htab_t
10999 allocate_dwp_loaded_cutus_table (struct objfile *objfile)
11000 {
11001   return htab_create_alloc_ex (3,
11002                                hash_dwp_loaded_cutus,
11003                                eq_dwp_loaded_cutus,
11004                                NULL,
11005                                &objfile->objfile_obstack,
11006                                hashtab_obstack_allocate,
11007                                dummy_obstack_deallocate);
11008 }
11009
11010 /* Try to open DWP file FILE_NAME.
11011    The result is the bfd handle of the file.
11012    If there is a problem finding or opening the file, return NULL.
11013    Upon success, the canonicalized path of the file is stored in the bfd,
11014    same as symfile_bfd_open.  */
11015
11016 static gdb_bfd_ref_ptr
11017 open_dwp_file (const char *file_name)
11018 {
11019   gdb_bfd_ref_ptr abfd (try_open_dwop_file (file_name, 1 /*is_dwp*/,
11020                                             1 /*search_cwd*/));
11021   if (abfd != NULL)
11022     return abfd;
11023
11024   /* Work around upstream bug 15652.
11025      http://sourceware.org/bugzilla/show_bug.cgi?id=15652
11026      [Whether that's a "bug" is debatable, but it is getting in our way.]
11027      We have no real idea where the dwp file is, because gdb's realpath-ing
11028      of the executable's path may have discarded the needed info.
11029      [IWBN if the dwp file name was recorded in the executable, akin to
11030      .gnu_debuglink, but that doesn't exist yet.]
11031      Strip the directory from FILE_NAME and search again.  */
11032   if (*debug_file_directory != '\0')
11033     {
11034       /* Don't implicitly search the current directory here.
11035          If the user wants to search "." to handle this case,
11036          it must be added to debug-file-directory.  */
11037       return try_open_dwop_file (lbasename (file_name), 1 /*is_dwp*/,
11038                                  0 /*search_cwd*/);
11039     }
11040
11041   return NULL;
11042 }
11043
11044 /* Initialize the use of the DWP file for the current objfile.
11045    By convention the name of the DWP file is ${objfile}.dwp.
11046    The result is NULL if it can't be found.  */
11047
11048 static struct dwp_file *
11049 open_and_init_dwp_file (void)
11050 {
11051   struct objfile *objfile = dwarf2_per_objfile->objfile;
11052   struct dwp_file *dwp_file;
11053
11054   /* Try to find first .dwp for the binary file before any symbolic links
11055      resolving.  */
11056
11057   /* If the objfile is a debug file, find the name of the real binary
11058      file and get the name of dwp file from there.  */
11059   std::string dwp_name;
11060   if (objfile->separate_debug_objfile_backlink != NULL)
11061     {
11062       struct objfile *backlink = objfile->separate_debug_objfile_backlink;
11063       const char *backlink_basename = lbasename (backlink->original_name);
11064
11065       dwp_name = ldirname (objfile->original_name) + SLASH_STRING + backlink_basename;
11066     }
11067   else
11068     dwp_name = objfile->original_name;
11069
11070   dwp_name += ".dwp";
11071
11072   gdb_bfd_ref_ptr dbfd (open_dwp_file (dwp_name.c_str ()));
11073   if (dbfd == NULL
11074       && strcmp (objfile->original_name, objfile_name (objfile)) != 0)
11075     {
11076       /* Try to find .dwp for the binary file after gdb_realpath resolving.  */
11077       dwp_name = objfile_name (objfile);
11078       dwp_name += ".dwp";
11079       dbfd = open_dwp_file (dwp_name.c_str ());
11080     }
11081
11082   if (dbfd == NULL)
11083     {
11084       if (dwarf_read_debug)
11085         fprintf_unfiltered (gdb_stdlog, "DWP file not found: %s\n", dwp_name.c_str ());
11086       return NULL;
11087     }
11088   dwp_file = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwp_file);
11089   dwp_file->name = bfd_get_filename (dbfd.get ());
11090   dwp_file->dbfd = dbfd.release ();
11091
11092   /* +1: section 0 is unused */
11093   dwp_file->num_sections = bfd_count_sections (dwp_file->dbfd) + 1;
11094   dwp_file->elf_sections =
11095     OBSTACK_CALLOC (&objfile->objfile_obstack,
11096                     dwp_file->num_sections, asection *);
11097
11098   bfd_map_over_sections (dwp_file->dbfd, dwarf2_locate_common_dwp_sections,
11099                          dwp_file);
11100
11101   dwp_file->cus = create_dwp_hash_table (dwp_file, 0);
11102
11103   dwp_file->tus = create_dwp_hash_table (dwp_file, 1);
11104
11105   /* The DWP file version is stored in the hash table.  Oh well.  */
11106   if (dwp_file->cus->version != dwp_file->tus->version)
11107     {
11108       /* Technically speaking, we should try to limp along, but this is
11109          pretty bizarre.  We use pulongest here because that's the established
11110          portability solution (e.g, we cannot use %u for uint32_t).  */
11111       error (_("Dwarf Error: DWP file CU version %s doesn't match"
11112                " TU version %s [in DWP file %s]"),
11113              pulongest (dwp_file->cus->version),
11114              pulongest (dwp_file->tus->version), dwp_name.c_str ());
11115     }
11116   dwp_file->version = dwp_file->cus->version;
11117
11118   if (dwp_file->version == 2)
11119     bfd_map_over_sections (dwp_file->dbfd, dwarf2_locate_v2_dwp_sections,
11120                            dwp_file);
11121
11122   dwp_file->loaded_cus = allocate_dwp_loaded_cutus_table (objfile);
11123   dwp_file->loaded_tus = allocate_dwp_loaded_cutus_table (objfile);
11124
11125   if (dwarf_read_debug)
11126     {
11127       fprintf_unfiltered (gdb_stdlog, "DWP file found: %s\n", dwp_file->name);
11128       fprintf_unfiltered (gdb_stdlog,
11129                           "    %s CUs, %s TUs\n",
11130                           pulongest (dwp_file->cus ? dwp_file->cus->nr_units : 0),
11131                           pulongest (dwp_file->tus ? dwp_file->tus->nr_units : 0));
11132     }
11133
11134   return dwp_file;
11135 }
11136
11137 /* Wrapper around open_and_init_dwp_file, only open it once.  */
11138
11139 static struct dwp_file *
11140 get_dwp_file (void)
11141 {
11142   if (! dwarf2_per_objfile->dwp_checked)
11143     {
11144       dwarf2_per_objfile->dwp_file = open_and_init_dwp_file ();
11145       dwarf2_per_objfile->dwp_checked = 1;
11146     }
11147   return dwarf2_per_objfile->dwp_file;
11148 }
11149
11150 /* Subroutine of lookup_dwo_comp_unit, lookup_dwo_type_unit.
11151    Look up the CU/TU with signature SIGNATURE, either in DWO file DWO_NAME
11152    or in the DWP file for the objfile, referenced by THIS_UNIT.
11153    If non-NULL, comp_dir is the DW_AT_comp_dir attribute.
11154    IS_DEBUG_TYPES is non-zero if reading a TU, otherwise read a CU.
11155
11156    This is called, for example, when wanting to read a variable with a
11157    complex location.  Therefore we don't want to do file i/o for every call.
11158    Therefore we don't want to look for a DWO file on every call.
11159    Therefore we first see if we've already seen SIGNATURE in a DWP file,
11160    then we check if we've already seen DWO_NAME, and only THEN do we check
11161    for a DWO file.
11162
11163    The result is a pointer to the dwo_unit object or NULL if we didn't find it
11164    (dwo_id mismatch or couldn't find the DWO/DWP file).  */
11165
11166 static struct dwo_unit *
11167 lookup_dwo_cutu (struct dwarf2_per_cu_data *this_unit,
11168                  const char *dwo_name, const char *comp_dir,
11169                  ULONGEST signature, int is_debug_types)
11170 {
11171   struct objfile *objfile = dwarf2_per_objfile->objfile;
11172   const char *kind = is_debug_types ? "TU" : "CU";
11173   void **dwo_file_slot;
11174   struct dwo_file *dwo_file;
11175   struct dwp_file *dwp_file;
11176
11177   /* First see if there's a DWP file.
11178      If we have a DWP file but didn't find the DWO inside it, don't
11179      look for the original DWO file.  It makes gdb behave differently
11180      depending on whether one is debugging in the build tree.  */
11181
11182   dwp_file = get_dwp_file ();
11183   if (dwp_file != NULL)
11184     {
11185       const struct dwp_hash_table *dwp_htab =
11186         is_debug_types ? dwp_file->tus : dwp_file->cus;
11187
11188       if (dwp_htab != NULL)
11189         {
11190           struct dwo_unit *dwo_cutu =
11191             lookup_dwo_unit_in_dwp (dwp_file, comp_dir,
11192                                     signature, is_debug_types);
11193
11194           if (dwo_cutu != NULL)
11195             {
11196               if (dwarf_read_debug)
11197                 {
11198                   fprintf_unfiltered (gdb_stdlog,
11199                                       "Virtual DWO %s %s found: @%s\n",
11200                                       kind, hex_string (signature),
11201                                       host_address_to_string (dwo_cutu));
11202                 }
11203               return dwo_cutu;
11204             }
11205         }
11206     }
11207   else
11208     {
11209       /* No DWP file, look for the DWO file.  */
11210
11211       dwo_file_slot = lookup_dwo_file_slot (dwo_name, comp_dir);
11212       if (*dwo_file_slot == NULL)
11213         {
11214           /* Read in the file and build a table of the CUs/TUs it contains.  */
11215           *dwo_file_slot = open_and_init_dwo_file (this_unit, dwo_name, comp_dir);
11216         }
11217       /* NOTE: This will be NULL if unable to open the file.  */
11218       dwo_file = (struct dwo_file *) *dwo_file_slot;
11219
11220       if (dwo_file != NULL)
11221         {
11222           struct dwo_unit *dwo_cutu = NULL;
11223
11224           if (is_debug_types && dwo_file->tus)
11225             {
11226               struct dwo_unit find_dwo_cutu;
11227
11228               memset (&find_dwo_cutu, 0, sizeof (find_dwo_cutu));
11229               find_dwo_cutu.signature = signature;
11230               dwo_cutu
11231                 = (struct dwo_unit *) htab_find (dwo_file->tus, &find_dwo_cutu);
11232             }
11233           else if (!is_debug_types && dwo_file->cus)
11234             {
11235               struct dwo_unit find_dwo_cutu;
11236
11237               memset (&find_dwo_cutu, 0, sizeof (find_dwo_cutu));
11238               find_dwo_cutu.signature = signature;
11239               dwo_cutu = (struct dwo_unit *)htab_find (dwo_file->cus,
11240                                                        &find_dwo_cutu);
11241             }
11242
11243           if (dwo_cutu != NULL)
11244             {
11245               if (dwarf_read_debug)
11246                 {
11247                   fprintf_unfiltered (gdb_stdlog, "DWO %s %s(%s) found: @%s\n",
11248                                       kind, dwo_name, hex_string (signature),
11249                                       host_address_to_string (dwo_cutu));
11250                 }
11251               return dwo_cutu;
11252             }
11253         }
11254     }
11255
11256   /* We didn't find it.  This could mean a dwo_id mismatch, or
11257      someone deleted the DWO/DWP file, or the search path isn't set up
11258      correctly to find the file.  */
11259
11260   if (dwarf_read_debug)
11261     {
11262       fprintf_unfiltered (gdb_stdlog, "DWO %s %s(%s) not found\n",
11263                           kind, dwo_name, hex_string (signature));
11264     }
11265
11266   /* This is a warning and not a complaint because it can be caused by
11267      pilot error (e.g., user accidentally deleting the DWO).  */
11268   {
11269     /* Print the name of the DWP file if we looked there, helps the user
11270        better diagnose the problem.  */
11271     char *dwp_text = NULL;
11272     struct cleanup *cleanups;
11273
11274     if (dwp_file != NULL)
11275       dwp_text = xstrprintf (" [in DWP file %s]", lbasename (dwp_file->name));
11276     cleanups = make_cleanup (xfree, dwp_text);
11277
11278     warning (_("Could not find DWO %s %s(%s)%s referenced by %s at offset 0x%x"
11279                " [in module %s]"),
11280              kind, dwo_name, hex_string (signature),
11281              dwp_text != NULL ? dwp_text : "",
11282              this_unit->is_debug_types ? "TU" : "CU",
11283              to_underlying (this_unit->sect_off), objfile_name (objfile));
11284
11285     do_cleanups (cleanups);
11286   }
11287   return NULL;
11288 }
11289
11290 /* Lookup the DWO CU DWO_NAME/SIGNATURE referenced from THIS_CU.
11291    See lookup_dwo_cutu_unit for details.  */
11292
11293 static struct dwo_unit *
11294 lookup_dwo_comp_unit (struct dwarf2_per_cu_data *this_cu,
11295                       const char *dwo_name, const char *comp_dir,
11296                       ULONGEST signature)
11297 {
11298   return lookup_dwo_cutu (this_cu, dwo_name, comp_dir, signature, 0);
11299 }
11300
11301 /* Lookup the DWO TU DWO_NAME/SIGNATURE referenced from THIS_TU.
11302    See lookup_dwo_cutu_unit for details.  */
11303
11304 static struct dwo_unit *
11305 lookup_dwo_type_unit (struct signatured_type *this_tu,
11306                       const char *dwo_name, const char *comp_dir)
11307 {
11308   return lookup_dwo_cutu (&this_tu->per_cu, dwo_name, comp_dir, this_tu->signature, 1);
11309 }
11310
11311 /* Traversal function for queue_and_load_all_dwo_tus.  */
11312
11313 static int
11314 queue_and_load_dwo_tu (void **slot, void *info)
11315 {
11316   struct dwo_unit *dwo_unit = (struct dwo_unit *) *slot;
11317   struct dwarf2_per_cu_data *per_cu = (struct dwarf2_per_cu_data *) info;
11318   ULONGEST signature = dwo_unit->signature;
11319   struct signatured_type *sig_type =
11320     lookup_dwo_signatured_type (per_cu->cu, signature);
11321
11322   if (sig_type != NULL)
11323     {
11324       struct dwarf2_per_cu_data *sig_cu = &sig_type->per_cu;
11325
11326       /* We pass NULL for DEPENDENT_CU because we don't yet know if there's
11327          a real dependency of PER_CU on SIG_TYPE.  That is detected later
11328          while processing PER_CU.  */
11329       if (maybe_queue_comp_unit (NULL, sig_cu, per_cu->cu->language))
11330         load_full_type_unit (sig_cu);
11331       VEC_safe_push (dwarf2_per_cu_ptr, per_cu->imported_symtabs, sig_cu);
11332     }
11333
11334   return 1;
11335 }
11336
11337 /* Queue all TUs contained in the DWO of PER_CU to be read in.
11338    The DWO may have the only definition of the type, though it may not be
11339    referenced anywhere in PER_CU.  Thus we have to load *all* its TUs.
11340    http://sourceware.org/bugzilla/show_bug.cgi?id=15021  */
11341
11342 static void
11343 queue_and_load_all_dwo_tus (struct dwarf2_per_cu_data *per_cu)
11344 {
11345   struct dwo_unit *dwo_unit;
11346   struct dwo_file *dwo_file;
11347
11348   gdb_assert (!per_cu->is_debug_types);
11349   gdb_assert (get_dwp_file () == NULL);
11350   gdb_assert (per_cu->cu != NULL);
11351
11352   dwo_unit = per_cu->cu->dwo_unit;
11353   gdb_assert (dwo_unit != NULL);
11354
11355   dwo_file = dwo_unit->dwo_file;
11356   if (dwo_file->tus != NULL)
11357     htab_traverse_noresize (dwo_file->tus, queue_and_load_dwo_tu, per_cu);
11358 }
11359
11360 /* Free all resources associated with DWO_FILE.
11361    Close the DWO file and munmap the sections.
11362    All memory should be on the objfile obstack.  */
11363
11364 static void
11365 free_dwo_file (struct dwo_file *dwo_file, struct objfile *objfile)
11366 {
11367
11368   /* Note: dbfd is NULL for virtual DWO files.  */
11369   gdb_bfd_unref (dwo_file->dbfd);
11370
11371   VEC_free (dwarf2_section_info_def, dwo_file->sections.types);
11372 }
11373
11374 /* Wrapper for free_dwo_file for use in cleanups.  */
11375
11376 static void
11377 free_dwo_file_cleanup (void *arg)
11378 {
11379   struct dwo_file *dwo_file = (struct dwo_file *) arg;
11380   struct objfile *objfile = dwarf2_per_objfile->objfile;
11381
11382   free_dwo_file (dwo_file, objfile);
11383 }
11384
11385 /* Traversal function for free_dwo_files.  */
11386
11387 static int
11388 free_dwo_file_from_slot (void **slot, void *info)
11389 {
11390   struct dwo_file *dwo_file = (struct dwo_file *) *slot;
11391   struct objfile *objfile = (struct objfile *) info;
11392
11393   free_dwo_file (dwo_file, objfile);
11394
11395   return 1;
11396 }
11397
11398 /* Free all resources associated with DWO_FILES.  */
11399
11400 static void
11401 free_dwo_files (htab_t dwo_files, struct objfile *objfile)
11402 {
11403   htab_traverse_noresize (dwo_files, free_dwo_file_from_slot, objfile);
11404 }
11405 \f
11406 /* Read in various DIEs.  */
11407
11408 /* qsort helper for inherit_abstract_dies.  */
11409
11410 static int
11411 unsigned_int_compar (const void *ap, const void *bp)
11412 {
11413   unsigned int a = *(unsigned int *) ap;
11414   unsigned int b = *(unsigned int *) bp;
11415
11416   return (a > b) - (b > a);
11417 }
11418
11419 /* DW_AT_abstract_origin inherits whole DIEs (not just their attributes).
11420    Inherit only the children of the DW_AT_abstract_origin DIE not being
11421    already referenced by DW_AT_abstract_origin from the children of the
11422    current DIE.  */
11423
11424 static void
11425 inherit_abstract_dies (struct die_info *die, struct dwarf2_cu *cu)
11426 {
11427   struct die_info *child_die;
11428   unsigned die_children_count;
11429   /* CU offsets which were referenced by children of the current DIE.  */
11430   sect_offset *offsets;
11431   sect_offset *offsets_end, *offsetp;
11432   /* Parent of DIE - referenced by DW_AT_abstract_origin.  */
11433   struct die_info *origin_die;
11434   /* Iterator of the ORIGIN_DIE children.  */
11435   struct die_info *origin_child_die;
11436   struct cleanup *cleanups;
11437   struct attribute *attr;
11438   struct dwarf2_cu *origin_cu;
11439   struct pending **origin_previous_list_in_scope;
11440
11441   attr = dwarf2_attr (die, DW_AT_abstract_origin, cu);
11442   if (!attr)
11443     return;
11444
11445   /* Note that following die references may follow to a die in a
11446      different cu.  */
11447
11448   origin_cu = cu;
11449   origin_die = follow_die_ref (die, attr, &origin_cu);
11450
11451   /* We're inheriting ORIGIN's children into the scope we'd put DIE's
11452      symbols in.  */
11453   origin_previous_list_in_scope = origin_cu->list_in_scope;
11454   origin_cu->list_in_scope = cu->list_in_scope;
11455
11456   if (die->tag != origin_die->tag
11457       && !(die->tag == DW_TAG_inlined_subroutine
11458            && origin_die->tag == DW_TAG_subprogram))
11459     complaint (&symfile_complaints,
11460                _("DIE 0x%x and its abstract origin 0x%x have different tags"),
11461                to_underlying (die->sect_off),
11462                to_underlying (origin_die->sect_off));
11463
11464   child_die = die->child;
11465   die_children_count = 0;
11466   while (child_die && child_die->tag)
11467     {
11468       child_die = sibling_die (child_die);
11469       die_children_count++;
11470     }
11471   offsets = XNEWVEC (sect_offset, die_children_count);
11472   cleanups = make_cleanup (xfree, offsets);
11473
11474   offsets_end = offsets;
11475   for (child_die = die->child;
11476        child_die && child_die->tag;
11477        child_die = sibling_die (child_die))
11478     {
11479       struct die_info *child_origin_die;
11480       struct dwarf2_cu *child_origin_cu;
11481
11482       /* We are trying to process concrete instance entries:
11483          DW_TAG_call_site DIEs indeed have a DW_AT_abstract_origin tag, but
11484          it's not relevant to our analysis here. i.e. detecting DIEs that are
11485          present in the abstract instance but not referenced in the concrete
11486          one.  */
11487       if (child_die->tag == DW_TAG_call_site
11488           || child_die->tag == DW_TAG_GNU_call_site)
11489         continue;
11490
11491       /* For each CHILD_DIE, find the corresponding child of
11492          ORIGIN_DIE.  If there is more than one layer of
11493          DW_AT_abstract_origin, follow them all; there shouldn't be,
11494          but GCC versions at least through 4.4 generate this (GCC PR
11495          40573).  */
11496       child_origin_die = child_die;
11497       child_origin_cu = cu;
11498       while (1)
11499         {
11500           attr = dwarf2_attr (child_origin_die, DW_AT_abstract_origin,
11501                               child_origin_cu);
11502           if (attr == NULL)
11503             break;
11504           child_origin_die = follow_die_ref (child_origin_die, attr,
11505                                              &child_origin_cu);
11506         }
11507
11508       /* According to DWARF3 3.3.8.2 #3 new entries without their abstract
11509          counterpart may exist.  */
11510       if (child_origin_die != child_die)
11511         {
11512           if (child_die->tag != child_origin_die->tag
11513               && !(child_die->tag == DW_TAG_inlined_subroutine
11514                    && child_origin_die->tag == DW_TAG_subprogram))
11515             complaint (&symfile_complaints,
11516                        _("Child DIE 0x%x and its abstract origin 0x%x have "
11517                          "different tags"),
11518                        to_underlying (child_die->sect_off),
11519                        to_underlying (child_origin_die->sect_off));
11520           if (child_origin_die->parent != origin_die)
11521             complaint (&symfile_complaints,
11522                        _("Child DIE 0x%x and its abstract origin 0x%x have "
11523                          "different parents"),
11524                        to_underlying (child_die->sect_off),
11525                        to_underlying (child_origin_die->sect_off));
11526           else
11527             *offsets_end++ = child_origin_die->sect_off;
11528         }
11529     }
11530   qsort (offsets, offsets_end - offsets, sizeof (*offsets),
11531          unsigned_int_compar);
11532   for (offsetp = offsets + 1; offsetp < offsets_end; offsetp++)
11533     if (offsetp[-1] == *offsetp)
11534       complaint (&symfile_complaints,
11535                  _("Multiple children of DIE 0x%x refer "
11536                    "to DIE 0x%x as their abstract origin"),
11537                  to_underlying (die->sect_off), to_underlying (*offsetp));
11538
11539   offsetp = offsets;
11540   origin_child_die = origin_die->child;
11541   while (origin_child_die && origin_child_die->tag)
11542     {
11543       /* Is ORIGIN_CHILD_DIE referenced by any of the DIE children?  */
11544       while (offsetp < offsets_end
11545              && *offsetp < origin_child_die->sect_off)
11546         offsetp++;
11547       if (offsetp >= offsets_end
11548           || *offsetp > origin_child_die->sect_off)
11549         {
11550           /* Found that ORIGIN_CHILD_DIE is really not referenced.
11551              Check whether we're already processing ORIGIN_CHILD_DIE.
11552              This can happen with mutually referenced abstract_origins.
11553              PR 16581.  */
11554           if (!origin_child_die->in_process)
11555             process_die (origin_child_die, origin_cu);
11556         }
11557       origin_child_die = sibling_die (origin_child_die);
11558     }
11559   origin_cu->list_in_scope = origin_previous_list_in_scope;
11560
11561   do_cleanups (cleanups);
11562 }
11563
11564 static void
11565 read_func_scope (struct die_info *die, struct dwarf2_cu *cu)
11566 {
11567   struct objfile *objfile = cu->objfile;
11568   struct gdbarch *gdbarch = get_objfile_arch (objfile);
11569   struct context_stack *newobj;
11570   CORE_ADDR lowpc;
11571   CORE_ADDR highpc;
11572   struct die_info *child_die;
11573   struct attribute *attr, *call_line, *call_file;
11574   const char *name;
11575   CORE_ADDR baseaddr;
11576   struct block *block;
11577   int inlined_func = (die->tag == DW_TAG_inlined_subroutine);
11578   VEC (symbolp) *template_args = NULL;
11579   struct template_symbol *templ_func = NULL;
11580
11581   if (inlined_func)
11582     {
11583       /* If we do not have call site information, we can't show the
11584          caller of this inlined function.  That's too confusing, so
11585          only use the scope for local variables.  */
11586       call_line = dwarf2_attr (die, DW_AT_call_line, cu);
11587       call_file = dwarf2_attr (die, DW_AT_call_file, cu);
11588       if (call_line == NULL || call_file == NULL)
11589         {
11590           read_lexical_block_scope (die, cu);
11591           return;
11592         }
11593     }
11594
11595   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
11596
11597   name = dwarf2_name (die, cu);
11598
11599   /* Ignore functions with missing or empty names.  These are actually
11600      illegal according to the DWARF standard.  */
11601   if (name == NULL)
11602     {
11603       complaint (&symfile_complaints,
11604                  _("missing name for subprogram DIE at %d"),
11605                  to_underlying (die->sect_off));
11606       return;
11607     }
11608
11609   /* Ignore functions with missing or invalid low and high pc attributes.  */
11610   if (dwarf2_get_pc_bounds (die, &lowpc, &highpc, cu, NULL)
11611       <= PC_BOUNDS_INVALID)
11612     {
11613       attr = dwarf2_attr (die, DW_AT_external, cu);
11614       if (!attr || !DW_UNSND (attr))
11615         complaint (&symfile_complaints,
11616                    _("cannot get low and high bounds "
11617                      "for subprogram DIE at %d"),
11618                    to_underlying (die->sect_off));
11619       return;
11620     }
11621
11622   lowpc = gdbarch_adjust_dwarf2_addr (gdbarch, lowpc + baseaddr);
11623   highpc = gdbarch_adjust_dwarf2_addr (gdbarch, highpc + baseaddr);
11624
11625   /* If we have any template arguments, then we must allocate a
11626      different sort of symbol.  */
11627   for (child_die = die->child; child_die; child_die = sibling_die (child_die))
11628     {
11629       if (child_die->tag == DW_TAG_template_type_param
11630           || child_die->tag == DW_TAG_template_value_param)
11631         {
11632           templ_func = allocate_template_symbol (objfile);
11633           templ_func->base.is_cplus_template_function = 1;
11634           break;
11635         }
11636     }
11637
11638   newobj = push_context (0, lowpc);
11639   newobj->name = new_symbol_full (die, read_type_die (die, cu), cu,
11640                                (struct symbol *) templ_func);
11641
11642   /* If there is a location expression for DW_AT_frame_base, record
11643      it.  */
11644   attr = dwarf2_attr (die, DW_AT_frame_base, cu);
11645   if (attr)
11646     dwarf2_symbol_mark_computed (attr, newobj->name, cu, 1);
11647
11648   /* If there is a location for the static link, record it.  */
11649   newobj->static_link = NULL;
11650   attr = dwarf2_attr (die, DW_AT_static_link, cu);
11651   if (attr)
11652     {
11653       newobj->static_link
11654         = XOBNEW (&objfile->objfile_obstack, struct dynamic_prop);
11655       attr_to_dynamic_prop (attr, die, cu, newobj->static_link);
11656     }
11657
11658   cu->list_in_scope = &local_symbols;
11659
11660   if (die->child != NULL)
11661     {
11662       child_die = die->child;
11663       while (child_die && child_die->tag)
11664         {
11665           if (child_die->tag == DW_TAG_template_type_param
11666               || child_die->tag == DW_TAG_template_value_param)
11667             {
11668               struct symbol *arg = new_symbol (child_die, NULL, cu);
11669
11670               if (arg != NULL)
11671                 VEC_safe_push (symbolp, template_args, arg);
11672             }
11673           else
11674             process_die (child_die, cu);
11675           child_die = sibling_die (child_die);
11676         }
11677     }
11678
11679   inherit_abstract_dies (die, cu);
11680
11681   /* If we have a DW_AT_specification, we might need to import using
11682      directives from the context of the specification DIE.  See the
11683      comment in determine_prefix.  */
11684   if (cu->language == language_cplus
11685       && dwarf2_attr (die, DW_AT_specification, cu))
11686     {
11687       struct dwarf2_cu *spec_cu = cu;
11688       struct die_info *spec_die = die_specification (die, &spec_cu);
11689
11690       while (spec_die)
11691         {
11692           child_die = spec_die->child;
11693           while (child_die && child_die->tag)
11694             {
11695               if (child_die->tag == DW_TAG_imported_module)
11696                 process_die (child_die, spec_cu);
11697               child_die = sibling_die (child_die);
11698             }
11699
11700           /* In some cases, GCC generates specification DIEs that
11701              themselves contain DW_AT_specification attributes.  */
11702           spec_die = die_specification (spec_die, &spec_cu);
11703         }
11704     }
11705
11706   newobj = pop_context ();
11707   /* Make a block for the local symbols within.  */
11708   block = finish_block (newobj->name, &local_symbols, newobj->old_blocks,
11709                         newobj->static_link, lowpc, highpc);
11710
11711   /* For C++, set the block's scope.  */
11712   if ((cu->language == language_cplus
11713        || cu->language == language_fortran
11714        || cu->language == language_d
11715        || cu->language == language_rust)
11716       && cu->processing_has_namespace_info)
11717     block_set_scope (block, determine_prefix (die, cu),
11718                      &objfile->objfile_obstack);
11719
11720   /* If we have address ranges, record them.  */
11721   dwarf2_record_block_ranges (die, block, baseaddr, cu);
11722
11723   gdbarch_make_symbol_special (gdbarch, newobj->name, objfile);
11724
11725   /* Attach template arguments to function.  */
11726   if (! VEC_empty (symbolp, template_args))
11727     {
11728       gdb_assert (templ_func != NULL);
11729
11730       templ_func->n_template_arguments = VEC_length (symbolp, template_args);
11731       templ_func->template_arguments
11732         = XOBNEWVEC (&objfile->objfile_obstack, struct symbol *,
11733                      templ_func->n_template_arguments);
11734       memcpy (templ_func->template_arguments,
11735               VEC_address (symbolp, template_args),
11736               (templ_func->n_template_arguments * sizeof (struct symbol *)));
11737       VEC_free (symbolp, template_args);
11738     }
11739
11740   /* In C++, we can have functions nested inside functions (e.g., when
11741      a function declares a class that has methods).  This means that
11742      when we finish processing a function scope, we may need to go
11743      back to building a containing block's symbol lists.  */
11744   local_symbols = newobj->locals;
11745   local_using_directives = newobj->local_using_directives;
11746
11747   /* If we've finished processing a top-level function, subsequent
11748      symbols go in the file symbol list.  */
11749   if (outermost_context_p ())
11750     cu->list_in_scope = &file_symbols;
11751 }
11752
11753 /* Process all the DIES contained within a lexical block scope.  Start
11754    a new scope, process the dies, and then close the scope.  */
11755
11756 static void
11757 read_lexical_block_scope (struct die_info *die, struct dwarf2_cu *cu)
11758 {
11759   struct objfile *objfile = cu->objfile;
11760   struct gdbarch *gdbarch = get_objfile_arch (objfile);
11761   struct context_stack *newobj;
11762   CORE_ADDR lowpc, highpc;
11763   struct die_info *child_die;
11764   CORE_ADDR baseaddr;
11765
11766   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
11767
11768   /* Ignore blocks with missing or invalid low and high pc attributes.  */
11769   /* ??? Perhaps consider discontiguous blocks defined by DW_AT_ranges
11770      as multiple lexical blocks?  Handling children in a sane way would
11771      be nasty.  Might be easier to properly extend generic blocks to
11772      describe ranges.  */
11773   switch (dwarf2_get_pc_bounds (die, &lowpc, &highpc, cu, NULL))
11774     {
11775     case PC_BOUNDS_NOT_PRESENT:
11776       /* DW_TAG_lexical_block has no attributes, process its children as if
11777          there was no wrapping by that DW_TAG_lexical_block.
11778          GCC does no longer produces such DWARF since GCC r224161.  */
11779       for (child_die = die->child;
11780            child_die != NULL && child_die->tag;
11781            child_die = sibling_die (child_die))
11782         process_die (child_die, cu);
11783       return;
11784     case PC_BOUNDS_INVALID:
11785       return;
11786     }
11787   lowpc = gdbarch_adjust_dwarf2_addr (gdbarch, lowpc + baseaddr);
11788   highpc = gdbarch_adjust_dwarf2_addr (gdbarch, highpc + baseaddr);
11789
11790   push_context (0, lowpc);
11791   if (die->child != NULL)
11792     {
11793       child_die = die->child;
11794       while (child_die && child_die->tag)
11795         {
11796           process_die (child_die, cu);
11797           child_die = sibling_die (child_die);
11798         }
11799     }
11800   inherit_abstract_dies (die, cu);
11801   newobj = pop_context ();
11802
11803   if (local_symbols != NULL || local_using_directives != NULL)
11804     {
11805       struct block *block
11806         = finish_block (0, &local_symbols, newobj->old_blocks, NULL,
11807                         newobj->start_addr, highpc);
11808
11809       /* Note that recording ranges after traversing children, as we
11810          do here, means that recording a parent's ranges entails
11811          walking across all its children's ranges as they appear in
11812          the address map, which is quadratic behavior.
11813
11814          It would be nicer to record the parent's ranges before
11815          traversing its children, simply overriding whatever you find
11816          there.  But since we don't even decide whether to create a
11817          block until after we've traversed its children, that's hard
11818          to do.  */
11819       dwarf2_record_block_ranges (die, block, baseaddr, cu);
11820     }
11821   local_symbols = newobj->locals;
11822   local_using_directives = newobj->local_using_directives;
11823 }
11824
11825 /* Read in DW_TAG_call_site and insert it to CU->call_site_htab.  */
11826
11827 static void
11828 read_call_site_scope (struct die_info *die, struct dwarf2_cu *cu)
11829 {
11830   struct objfile *objfile = cu->objfile;
11831   struct gdbarch *gdbarch = get_objfile_arch (objfile);
11832   CORE_ADDR pc, baseaddr;
11833   struct attribute *attr;
11834   struct call_site *call_site, call_site_local;
11835   void **slot;
11836   int nparams;
11837   struct die_info *child_die;
11838
11839   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
11840
11841   attr = dwarf2_attr (die, DW_AT_call_return_pc, cu);
11842   if (attr == NULL)
11843     {
11844       /* This was a pre-DWARF-5 GNU extension alias
11845          for DW_AT_call_return_pc.  */
11846       attr = dwarf2_attr (die, DW_AT_low_pc, cu);
11847     }
11848   if (!attr)
11849     {
11850       complaint (&symfile_complaints,
11851                  _("missing DW_AT_call_return_pc for DW_TAG_call_site "
11852                    "DIE 0x%x [in module %s]"),
11853                  to_underlying (die->sect_off), objfile_name (objfile));
11854       return;
11855     }
11856   pc = attr_value_as_address (attr) + baseaddr;
11857   pc = gdbarch_adjust_dwarf2_addr (gdbarch, pc);
11858
11859   if (cu->call_site_htab == NULL)
11860     cu->call_site_htab = htab_create_alloc_ex (16, core_addr_hash, core_addr_eq,
11861                                                NULL, &objfile->objfile_obstack,
11862                                                hashtab_obstack_allocate, NULL);
11863   call_site_local.pc = pc;
11864   slot = htab_find_slot (cu->call_site_htab, &call_site_local, INSERT);
11865   if (*slot != NULL)
11866     {
11867       complaint (&symfile_complaints,
11868                  _("Duplicate PC %s for DW_TAG_call_site "
11869                    "DIE 0x%x [in module %s]"),
11870                  paddress (gdbarch, pc), to_underlying (die->sect_off),
11871                  objfile_name (objfile));
11872       return;
11873     }
11874
11875   /* Count parameters at the caller.  */
11876
11877   nparams = 0;
11878   for (child_die = die->child; child_die && child_die->tag;
11879        child_die = sibling_die (child_die))
11880     {
11881       if (child_die->tag != DW_TAG_call_site_parameter
11882           && child_die->tag != DW_TAG_GNU_call_site_parameter)
11883         {
11884           complaint (&symfile_complaints,
11885                      _("Tag %d is not DW_TAG_call_site_parameter in "
11886                        "DW_TAG_call_site child DIE 0x%x [in module %s]"),
11887                      child_die->tag, to_underlying (child_die->sect_off),
11888                      objfile_name (objfile));
11889           continue;
11890         }
11891
11892       nparams++;
11893     }
11894
11895   call_site
11896     = ((struct call_site *)
11897        obstack_alloc (&objfile->objfile_obstack,
11898                       sizeof (*call_site)
11899                       + (sizeof (*call_site->parameter) * (nparams - 1))));
11900   *slot = call_site;
11901   memset (call_site, 0, sizeof (*call_site) - sizeof (*call_site->parameter));
11902   call_site->pc = pc;
11903
11904   if (dwarf2_flag_true_p (die, DW_AT_call_tail_call, cu)
11905       || dwarf2_flag_true_p (die, DW_AT_GNU_tail_call, cu))
11906     {
11907       struct die_info *func_die;
11908
11909       /* Skip also over DW_TAG_inlined_subroutine.  */
11910       for (func_die = die->parent;
11911            func_die && func_die->tag != DW_TAG_subprogram
11912            && func_die->tag != DW_TAG_subroutine_type;
11913            func_die = func_die->parent);
11914
11915       /* DW_AT_call_all_calls is a superset
11916          of DW_AT_call_all_tail_calls.  */
11917       if (func_die
11918           && !dwarf2_flag_true_p (func_die, DW_AT_call_all_calls, cu)
11919           && !dwarf2_flag_true_p (func_die, DW_AT_GNU_all_call_sites, cu)
11920           && !dwarf2_flag_true_p (func_die, DW_AT_call_all_tail_calls, cu)
11921           && !dwarf2_flag_true_p (func_die, DW_AT_GNU_all_tail_call_sites, cu))
11922         {
11923           /* TYPE_TAIL_CALL_LIST is not interesting in functions where it is
11924              not complete.  But keep CALL_SITE for look ups via call_site_htab,
11925              both the initial caller containing the real return address PC and
11926              the final callee containing the current PC of a chain of tail
11927              calls do not need to have the tail call list complete.  But any
11928              function candidate for a virtual tail call frame searched via
11929              TYPE_TAIL_CALL_LIST must have the tail call list complete to be
11930              determined unambiguously.  */
11931         }
11932       else
11933         {
11934           struct type *func_type = NULL;
11935
11936           if (func_die)
11937             func_type = get_die_type (func_die, cu);
11938           if (func_type != NULL)
11939             {
11940               gdb_assert (TYPE_CODE (func_type) == TYPE_CODE_FUNC);
11941
11942               /* Enlist this call site to the function.  */
11943               call_site->tail_call_next = TYPE_TAIL_CALL_LIST (func_type);
11944               TYPE_TAIL_CALL_LIST (func_type) = call_site;
11945             }
11946           else
11947             complaint (&symfile_complaints,
11948                        _("Cannot find function owning DW_TAG_call_site "
11949                          "DIE 0x%x [in module %s]"),
11950                        to_underlying (die->sect_off), objfile_name (objfile));
11951         }
11952     }
11953
11954   attr = dwarf2_attr (die, DW_AT_call_target, cu);
11955   if (attr == NULL)
11956     attr = dwarf2_attr (die, DW_AT_GNU_call_site_target, cu);
11957   if (attr == NULL)
11958     attr = dwarf2_attr (die, DW_AT_call_origin, cu);
11959   if (attr == NULL)
11960     {
11961       /* This was a pre-DWARF-5 GNU extension alias for DW_AT_call_origin.  */
11962       attr = dwarf2_attr (die, DW_AT_abstract_origin, cu);
11963     }
11964   SET_FIELD_DWARF_BLOCK (call_site->target, NULL);
11965   if (!attr || (attr_form_is_block (attr) && DW_BLOCK (attr)->size == 0))
11966     /* Keep NULL DWARF_BLOCK.  */;
11967   else if (attr_form_is_block (attr))
11968     {
11969       struct dwarf2_locexpr_baton *dlbaton;
11970
11971       dlbaton = XOBNEW (&objfile->objfile_obstack, struct dwarf2_locexpr_baton);
11972       dlbaton->data = DW_BLOCK (attr)->data;
11973       dlbaton->size = DW_BLOCK (attr)->size;
11974       dlbaton->per_cu = cu->per_cu;
11975
11976       SET_FIELD_DWARF_BLOCK (call_site->target, dlbaton);
11977     }
11978   else if (attr_form_is_ref (attr))
11979     {
11980       struct dwarf2_cu *target_cu = cu;
11981       struct die_info *target_die;
11982
11983       target_die = follow_die_ref (die, attr, &target_cu);
11984       gdb_assert (target_cu->objfile == objfile);
11985       if (die_is_declaration (target_die, target_cu))
11986         {
11987           const char *target_physname;
11988
11989           /* Prefer the mangled name; otherwise compute the demangled one.  */
11990           target_physname = dwarf2_string_attr (target_die,
11991                                                 DW_AT_linkage_name,
11992                                                 target_cu);
11993           if (target_physname == NULL)
11994             target_physname = dwarf2_string_attr (target_die,
11995                                                  DW_AT_MIPS_linkage_name,
11996                                                  target_cu);
11997           if (target_physname == NULL)
11998             target_physname = dwarf2_physname (NULL, target_die, target_cu);
11999           if (target_physname == NULL)
12000             complaint (&symfile_complaints,
12001                        _("DW_AT_call_target target DIE has invalid "
12002                          "physname, for referencing DIE 0x%x [in module %s]"),
12003                        to_underlying (die->sect_off), objfile_name (objfile));
12004           else
12005             SET_FIELD_PHYSNAME (call_site->target, target_physname);
12006         }
12007       else
12008         {
12009           CORE_ADDR lowpc;
12010
12011           /* DW_AT_entry_pc should be preferred.  */
12012           if (dwarf2_get_pc_bounds (target_die, &lowpc, NULL, target_cu, NULL)
12013               <= PC_BOUNDS_INVALID)
12014             complaint (&symfile_complaints,
12015                        _("DW_AT_call_target target DIE has invalid "
12016                          "low pc, for referencing DIE 0x%x [in module %s]"),
12017                        to_underlying (die->sect_off), objfile_name (objfile));
12018           else
12019             {
12020               lowpc = gdbarch_adjust_dwarf2_addr (gdbarch, lowpc + baseaddr);
12021               SET_FIELD_PHYSADDR (call_site->target, lowpc);
12022             }
12023         }
12024     }
12025   else
12026     complaint (&symfile_complaints,
12027                _("DW_TAG_call_site DW_AT_call_target is neither "
12028                  "block nor reference, for DIE 0x%x [in module %s]"),
12029                to_underlying (die->sect_off), objfile_name (objfile));
12030
12031   call_site->per_cu = cu->per_cu;
12032
12033   for (child_die = die->child;
12034        child_die && child_die->tag;
12035        child_die = sibling_die (child_die))
12036     {
12037       struct call_site_parameter *parameter;
12038       struct attribute *loc, *origin;
12039
12040       if (child_die->tag != DW_TAG_call_site_parameter
12041           && child_die->tag != DW_TAG_GNU_call_site_parameter)
12042         {
12043           /* Already printed the complaint above.  */
12044           continue;
12045         }
12046
12047       gdb_assert (call_site->parameter_count < nparams);
12048       parameter = &call_site->parameter[call_site->parameter_count];
12049
12050       /* DW_AT_location specifies the register number or DW_AT_abstract_origin
12051          specifies DW_TAG_formal_parameter.  Value of the data assumed for the
12052          register is contained in DW_AT_call_value.  */
12053
12054       loc = dwarf2_attr (child_die, DW_AT_location, cu);
12055       origin = dwarf2_attr (child_die, DW_AT_call_parameter, cu);
12056       if (origin == NULL)
12057         {
12058           /* This was a pre-DWARF-5 GNU extension alias
12059              for DW_AT_call_parameter.  */
12060           origin = dwarf2_attr (child_die, DW_AT_abstract_origin, cu);
12061         }
12062       if (loc == NULL && origin != NULL && attr_form_is_ref (origin))
12063         {
12064           parameter->kind = CALL_SITE_PARAMETER_PARAM_OFFSET;
12065
12066           sect_offset sect_off
12067             = (sect_offset) dwarf2_get_ref_die_offset (origin);
12068           if (!offset_in_cu_p (&cu->header, sect_off))
12069             {
12070               /* As DW_OP_GNU_parameter_ref uses CU-relative offset this
12071                  binding can be done only inside one CU.  Such referenced DIE
12072                  therefore cannot be even moved to DW_TAG_partial_unit.  */
12073               complaint (&symfile_complaints,
12074                          _("DW_AT_call_parameter offset is not in CU for "
12075                            "DW_TAG_call_site child DIE 0x%x [in module %s]"),
12076                          to_underlying (child_die->sect_off),
12077                          objfile_name (objfile));
12078               continue;
12079             }
12080           parameter->u.param_cu_off
12081             = (cu_offset) (sect_off - cu->header.sect_off);
12082         }
12083       else if (loc == NULL || origin != NULL || !attr_form_is_block (loc))
12084         {
12085           complaint (&symfile_complaints,
12086                      _("No DW_FORM_block* DW_AT_location for "
12087                        "DW_TAG_call_site child DIE 0x%x [in module %s]"),
12088                      to_underlying (child_die->sect_off), objfile_name (objfile));
12089           continue;
12090         }
12091       else
12092         {
12093           parameter->u.dwarf_reg = dwarf_block_to_dwarf_reg
12094             (DW_BLOCK (loc)->data, &DW_BLOCK (loc)->data[DW_BLOCK (loc)->size]);
12095           if (parameter->u.dwarf_reg != -1)
12096             parameter->kind = CALL_SITE_PARAMETER_DWARF_REG;
12097           else if (dwarf_block_to_sp_offset (gdbarch, DW_BLOCK (loc)->data,
12098                                     &DW_BLOCK (loc)->data[DW_BLOCK (loc)->size],
12099                                              &parameter->u.fb_offset))
12100             parameter->kind = CALL_SITE_PARAMETER_FB_OFFSET;
12101           else
12102             {
12103               complaint (&symfile_complaints,
12104                          _("Only single DW_OP_reg or DW_OP_fbreg is supported "
12105                            "for DW_FORM_block* DW_AT_location is supported for "
12106                            "DW_TAG_call_site child DIE 0x%x "
12107                            "[in module %s]"),
12108                          to_underlying (child_die->sect_off),
12109                          objfile_name (objfile));
12110               continue;
12111             }
12112         }
12113
12114       attr = dwarf2_attr (child_die, DW_AT_call_value, cu);
12115       if (attr == NULL)
12116         attr = dwarf2_attr (child_die, DW_AT_GNU_call_site_value, cu);
12117       if (!attr_form_is_block (attr))
12118         {
12119           complaint (&symfile_complaints,
12120                      _("No DW_FORM_block* DW_AT_call_value for "
12121                        "DW_TAG_call_site child DIE 0x%x [in module %s]"),
12122                      to_underlying (child_die->sect_off),
12123                      objfile_name (objfile));
12124           continue;
12125         }
12126       parameter->value = DW_BLOCK (attr)->data;
12127       parameter->value_size = DW_BLOCK (attr)->size;
12128
12129       /* Parameters are not pre-cleared by memset above.  */
12130       parameter->data_value = NULL;
12131       parameter->data_value_size = 0;
12132       call_site->parameter_count++;
12133
12134       attr = dwarf2_attr (child_die, DW_AT_call_data_value, cu);
12135       if (attr == NULL)
12136         attr = dwarf2_attr (child_die, DW_AT_GNU_call_site_data_value, cu);
12137       if (attr)
12138         {
12139           if (!attr_form_is_block (attr))
12140             complaint (&symfile_complaints,
12141                        _("No DW_FORM_block* DW_AT_call_data_value for "
12142                          "DW_TAG_call_site child DIE 0x%x [in module %s]"),
12143                        to_underlying (child_die->sect_off),
12144                        objfile_name (objfile));
12145           else
12146             {
12147               parameter->data_value = DW_BLOCK (attr)->data;
12148               parameter->data_value_size = DW_BLOCK (attr)->size;
12149             }
12150         }
12151     }
12152 }
12153
12154 /* Call CALLBACK from DW_AT_ranges attribute value OFFSET
12155    reading .debug_rnglists.
12156    Callback's type should be:
12157     void (CORE_ADDR range_beginning, CORE_ADDR range_end)
12158    Return true if the attributes are present and valid, otherwise,
12159    return false.  */
12160
12161 template <typename Callback>
12162 static bool
12163 dwarf2_rnglists_process (unsigned offset, struct dwarf2_cu *cu,
12164                          Callback &&callback)
12165 {
12166   struct objfile *objfile = cu->objfile;
12167   struct gdbarch *gdbarch = get_objfile_arch (objfile);
12168   struct comp_unit_head *cu_header = &cu->header;
12169   bfd *obfd = objfile->obfd;
12170   unsigned int addr_size = cu_header->addr_size;
12171   CORE_ADDR mask = ~(~(CORE_ADDR)1 << (addr_size * 8 - 1));
12172   /* Base address selection entry.  */
12173   CORE_ADDR base;
12174   int found_base;
12175   unsigned int dummy;
12176   const gdb_byte *buffer;
12177   CORE_ADDR low = 0;
12178   CORE_ADDR high = 0;
12179   CORE_ADDR baseaddr;
12180   bool overflow = false;
12181
12182   found_base = cu->base_known;
12183   base = cu->base_address;
12184
12185   dwarf2_read_section (objfile, &dwarf2_per_objfile->rnglists);
12186   if (offset >= dwarf2_per_objfile->rnglists.size)
12187     {
12188       complaint (&symfile_complaints,
12189                  _("Offset %d out of bounds for DW_AT_ranges attribute"),
12190                  offset);
12191       return false;
12192     }
12193   buffer = dwarf2_per_objfile->rnglists.buffer + offset;
12194
12195   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
12196
12197   while (1)
12198     {
12199       /* Initialize it due to a false compiler warning.  */
12200       CORE_ADDR range_beginning = 0, range_end = 0;
12201       const gdb_byte *buf_end = (dwarf2_per_objfile->rnglists.buffer
12202                                  + dwarf2_per_objfile->rnglists.size);
12203       unsigned int bytes_read;
12204
12205       if (buffer == buf_end)
12206         {
12207           overflow = true;
12208           break;
12209         }
12210       const auto rlet = static_cast<enum dwarf_range_list_entry>(*buffer++);
12211       switch (rlet)
12212         {
12213         case DW_RLE_end_of_list:
12214           break;
12215         case DW_RLE_base_address:
12216           if (buffer + cu->header.addr_size > buf_end)
12217             {
12218               overflow = true;
12219               break;
12220             }
12221           base = read_address (obfd, buffer, cu, &bytes_read);
12222           found_base = 1;
12223           buffer += bytes_read;
12224           break;
12225         case DW_RLE_start_length:
12226           if (buffer + cu->header.addr_size > buf_end)
12227             {
12228               overflow = true;
12229               break;
12230             }
12231           range_beginning = read_address (obfd, buffer, cu, &bytes_read);
12232           buffer += bytes_read;
12233           range_end = (range_beginning
12234                        + read_unsigned_leb128 (obfd, buffer, &bytes_read));
12235           buffer += bytes_read;
12236           if (buffer > buf_end)
12237             {
12238               overflow = true;
12239               break;
12240             }
12241           break;
12242         case DW_RLE_offset_pair:
12243           range_beginning = read_unsigned_leb128 (obfd, buffer, &bytes_read);
12244           buffer += bytes_read;
12245           if (buffer > buf_end)
12246             {
12247               overflow = true;
12248               break;
12249             }
12250           range_end = read_unsigned_leb128 (obfd, buffer, &bytes_read);
12251           buffer += bytes_read;
12252           if (buffer > buf_end)
12253             {
12254               overflow = true;
12255               break;
12256             }
12257           break;
12258         case DW_RLE_start_end:
12259           if (buffer + 2 * cu->header.addr_size > buf_end)
12260             {
12261               overflow = true;
12262               break;
12263             }
12264           range_beginning = read_address (obfd, buffer, cu, &bytes_read);
12265           buffer += bytes_read;
12266           range_end = read_address (obfd, buffer, cu, &bytes_read);
12267           buffer += bytes_read;
12268           break;
12269         default:
12270           complaint (&symfile_complaints,
12271                      _("Invalid .debug_rnglists data (no base address)"));
12272           return false;
12273         }
12274       if (rlet == DW_RLE_end_of_list || overflow)
12275         break;
12276       if (rlet == DW_RLE_base_address)
12277         continue;
12278
12279       if (!found_base)
12280         {
12281           /* We have no valid base address for the ranges
12282              data.  */
12283           complaint (&symfile_complaints,
12284                      _("Invalid .debug_rnglists data (no base address)"));
12285           return false;
12286         }
12287
12288       if (range_beginning > range_end)
12289         {
12290           /* Inverted range entries are invalid.  */
12291           complaint (&symfile_complaints,
12292                      _("Invalid .debug_rnglists data (inverted range)"));
12293           return false;
12294         }
12295
12296       /* Empty range entries have no effect.  */
12297       if (range_beginning == range_end)
12298         continue;
12299
12300       range_beginning += base;
12301       range_end += base;
12302
12303       /* A not-uncommon case of bad debug info.
12304          Don't pollute the addrmap with bad data.  */
12305       if (range_beginning + baseaddr == 0
12306           && !dwarf2_per_objfile->has_section_at_zero)
12307         {
12308           complaint (&symfile_complaints,
12309                      _(".debug_rnglists entry has start address of zero"
12310                        " [in module %s]"), objfile_name (objfile));
12311           continue;
12312         }
12313
12314       callback (range_beginning, range_end);
12315     }
12316
12317   if (overflow)
12318     {
12319       complaint (&symfile_complaints,
12320                  _("Offset %d is not terminated "
12321                    "for DW_AT_ranges attribute"),
12322                  offset);
12323       return false;
12324     }
12325
12326   return true;
12327 }
12328
12329 /* Call CALLBACK from DW_AT_ranges attribute value OFFSET reading .debug_ranges.
12330    Callback's type should be:
12331     void (CORE_ADDR range_beginning, CORE_ADDR range_end)
12332    Return 1 if the attributes are present and valid, otherwise, return 0.  */
12333
12334 template <typename Callback>
12335 static int
12336 dwarf2_ranges_process (unsigned offset, struct dwarf2_cu *cu,
12337                        Callback &&callback)
12338 {
12339   struct objfile *objfile = cu->objfile;
12340   struct gdbarch *gdbarch = get_objfile_arch (objfile);
12341   struct comp_unit_head *cu_header = &cu->header;
12342   bfd *obfd = objfile->obfd;
12343   unsigned int addr_size = cu_header->addr_size;
12344   CORE_ADDR mask = ~(~(CORE_ADDR)1 << (addr_size * 8 - 1));
12345   /* Base address selection entry.  */
12346   CORE_ADDR base;
12347   int found_base;
12348   unsigned int dummy;
12349   const gdb_byte *buffer;
12350   CORE_ADDR baseaddr;
12351
12352   if (cu_header->version >= 5)
12353     return dwarf2_rnglists_process (offset, cu, callback);
12354
12355   found_base = cu->base_known;
12356   base = cu->base_address;
12357
12358   dwarf2_read_section (objfile, &dwarf2_per_objfile->ranges);
12359   if (offset >= dwarf2_per_objfile->ranges.size)
12360     {
12361       complaint (&symfile_complaints,
12362                  _("Offset %d out of bounds for DW_AT_ranges attribute"),
12363                  offset);
12364       return 0;
12365     }
12366   buffer = dwarf2_per_objfile->ranges.buffer + offset;
12367
12368   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
12369
12370   while (1)
12371     {
12372       CORE_ADDR range_beginning, range_end;
12373
12374       range_beginning = read_address (obfd, buffer, cu, &dummy);
12375       buffer += addr_size;
12376       range_end = read_address (obfd, buffer, cu, &dummy);
12377       buffer += addr_size;
12378       offset += 2 * addr_size;
12379
12380       /* An end of list marker is a pair of zero addresses.  */
12381       if (range_beginning == 0 && range_end == 0)
12382         /* Found the end of list entry.  */
12383         break;
12384
12385       /* Each base address selection entry is a pair of 2 values.
12386          The first is the largest possible address, the second is
12387          the base address.  Check for a base address here.  */
12388       if ((range_beginning & mask) == mask)
12389         {
12390           /* If we found the largest possible address, then we already
12391              have the base address in range_end.  */
12392           base = range_end;
12393           found_base = 1;
12394           continue;
12395         }
12396
12397       if (!found_base)
12398         {
12399           /* We have no valid base address for the ranges
12400              data.  */
12401           complaint (&symfile_complaints,
12402                      _("Invalid .debug_ranges data (no base address)"));
12403           return 0;
12404         }
12405
12406       if (range_beginning > range_end)
12407         {
12408           /* Inverted range entries are invalid.  */
12409           complaint (&symfile_complaints,
12410                      _("Invalid .debug_ranges data (inverted range)"));
12411           return 0;
12412         }
12413
12414       /* Empty range entries have no effect.  */
12415       if (range_beginning == range_end)
12416         continue;
12417
12418       range_beginning += base;
12419       range_end += base;
12420
12421       /* A not-uncommon case of bad debug info.
12422          Don't pollute the addrmap with bad data.  */
12423       if (range_beginning + baseaddr == 0
12424           && !dwarf2_per_objfile->has_section_at_zero)
12425         {
12426           complaint (&symfile_complaints,
12427                      _(".debug_ranges entry has start address of zero"
12428                        " [in module %s]"), objfile_name (objfile));
12429           continue;
12430         }
12431
12432       callback (range_beginning, range_end);
12433     }
12434
12435   return 1;
12436 }
12437
12438 /* Get low and high pc attributes from DW_AT_ranges attribute value OFFSET.
12439    Return 1 if the attributes are present and valid, otherwise, return 0.
12440    If RANGES_PST is not NULL we should setup `objfile->psymtabs_addrmap'.  */
12441
12442 static int
12443 dwarf2_ranges_read (unsigned offset, CORE_ADDR *low_return,
12444                     CORE_ADDR *high_return, struct dwarf2_cu *cu,
12445                     struct partial_symtab *ranges_pst)
12446 {
12447   struct objfile *objfile = cu->objfile;
12448   struct gdbarch *gdbarch = get_objfile_arch (objfile);
12449   const CORE_ADDR baseaddr = ANOFFSET (objfile->section_offsets,
12450                                        SECT_OFF_TEXT (objfile));
12451   int low_set = 0;
12452   CORE_ADDR low = 0;
12453   CORE_ADDR high = 0;
12454   int retval;
12455
12456   retval = dwarf2_ranges_process (offset, cu,
12457     [&] (CORE_ADDR range_beginning, CORE_ADDR range_end)
12458     {
12459       if (ranges_pst != NULL)
12460         {
12461           CORE_ADDR lowpc;
12462           CORE_ADDR highpc;
12463
12464           lowpc = gdbarch_adjust_dwarf2_addr (gdbarch,
12465                                               range_beginning + baseaddr);
12466           highpc = gdbarch_adjust_dwarf2_addr (gdbarch,
12467                                                range_end + baseaddr);
12468           addrmap_set_empty (objfile->psymtabs_addrmap, lowpc, highpc - 1,
12469                              ranges_pst);
12470         }
12471
12472       /* FIXME: This is recording everything as a low-high
12473          segment of consecutive addresses.  We should have a
12474          data structure for discontiguous block ranges
12475          instead.  */
12476       if (! low_set)
12477         {
12478           low = range_beginning;
12479           high = range_end;
12480           low_set = 1;
12481         }
12482       else
12483         {
12484           if (range_beginning < low)
12485             low = range_beginning;
12486           if (range_end > high)
12487             high = range_end;
12488         }
12489     });
12490   if (!retval)
12491     return 0;
12492
12493   if (! low_set)
12494     /* If the first entry is an end-of-list marker, the range
12495        describes an empty scope, i.e. no instructions.  */
12496     return 0;
12497
12498   if (low_return)
12499     *low_return = low;
12500   if (high_return)
12501     *high_return = high;
12502   return 1;
12503 }
12504
12505 /* Get low and high pc attributes from a die.  See enum pc_bounds_kind
12506    definition for the return value.  *LOWPC and *HIGHPC are set iff
12507    neither PC_BOUNDS_NOT_PRESENT nor PC_BOUNDS_INVALID are returned.  */
12508
12509 static enum pc_bounds_kind
12510 dwarf2_get_pc_bounds (struct die_info *die, CORE_ADDR *lowpc,
12511                       CORE_ADDR *highpc, struct dwarf2_cu *cu,
12512                       struct partial_symtab *pst)
12513 {
12514   struct attribute *attr;
12515   struct attribute *attr_high;
12516   CORE_ADDR low = 0;
12517   CORE_ADDR high = 0;
12518   enum pc_bounds_kind ret;
12519
12520   attr_high = dwarf2_attr (die, DW_AT_high_pc, cu);
12521   if (attr_high)
12522     {
12523       attr = dwarf2_attr (die, DW_AT_low_pc, cu);
12524       if (attr)
12525         {
12526           low = attr_value_as_address (attr);
12527           high = attr_value_as_address (attr_high);
12528           if (cu->header.version >= 4 && attr_form_is_constant (attr_high))
12529             high += low;
12530         }
12531       else
12532         /* Found high w/o low attribute.  */
12533         return PC_BOUNDS_INVALID;
12534
12535       /* Found consecutive range of addresses.  */
12536       ret = PC_BOUNDS_HIGH_LOW;
12537     }
12538   else
12539     {
12540       attr = dwarf2_attr (die, DW_AT_ranges, cu);
12541       if (attr != NULL)
12542         {
12543           /* DW_AT_ranges_base does not apply to DIEs from the DWO skeleton.
12544              We take advantage of the fact that DW_AT_ranges does not appear
12545              in DW_TAG_compile_unit of DWO files.  */
12546           int need_ranges_base = die->tag != DW_TAG_compile_unit;
12547           unsigned int ranges_offset = (DW_UNSND (attr)
12548                                         + (need_ranges_base
12549                                            ? cu->ranges_base
12550                                            : 0));
12551
12552           /* Value of the DW_AT_ranges attribute is the offset in the
12553              .debug_ranges section.  */
12554           if (!dwarf2_ranges_read (ranges_offset, &low, &high, cu, pst))
12555             return PC_BOUNDS_INVALID;
12556           /* Found discontinuous range of addresses.  */
12557           ret = PC_BOUNDS_RANGES;
12558         }
12559       else
12560         return PC_BOUNDS_NOT_PRESENT;
12561     }
12562
12563   /* read_partial_die has also the strict LOW < HIGH requirement.  */
12564   if (high <= low)
12565     return PC_BOUNDS_INVALID;
12566
12567   /* When using the GNU linker, .gnu.linkonce. sections are used to
12568      eliminate duplicate copies of functions and vtables and such.
12569      The linker will arbitrarily choose one and discard the others.
12570      The AT_*_pc values for such functions refer to local labels in
12571      these sections.  If the section from that file was discarded, the
12572      labels are not in the output, so the relocs get a value of 0.
12573      If this is a discarded function, mark the pc bounds as invalid,
12574      so that GDB will ignore it.  */
12575   if (low == 0 && !dwarf2_per_objfile->has_section_at_zero)
12576     return PC_BOUNDS_INVALID;
12577
12578   *lowpc = low;
12579   if (highpc)
12580     *highpc = high;
12581   return ret;
12582 }
12583
12584 /* Assuming that DIE represents a subprogram DIE or a lexical block, get
12585    its low and high PC addresses.  Do nothing if these addresses could not
12586    be determined.  Otherwise, set LOWPC to the low address if it is smaller,
12587    and HIGHPC to the high address if greater than HIGHPC.  */
12588
12589 static void
12590 dwarf2_get_subprogram_pc_bounds (struct die_info *die,
12591                                  CORE_ADDR *lowpc, CORE_ADDR *highpc,
12592                                  struct dwarf2_cu *cu)
12593 {
12594   CORE_ADDR low, high;
12595   struct die_info *child = die->child;
12596
12597   if (dwarf2_get_pc_bounds (die, &low, &high, cu, NULL) >= PC_BOUNDS_RANGES)
12598     {
12599       *lowpc = std::min (*lowpc, low);
12600       *highpc = std::max (*highpc, high);
12601     }
12602
12603   /* If the language does not allow nested subprograms (either inside
12604      subprograms or lexical blocks), we're done.  */
12605   if (cu->language != language_ada)
12606     return;
12607
12608   /* Check all the children of the given DIE.  If it contains nested
12609      subprograms, then check their pc bounds.  Likewise, we need to
12610      check lexical blocks as well, as they may also contain subprogram
12611      definitions.  */
12612   while (child && child->tag)
12613     {
12614       if (child->tag == DW_TAG_subprogram
12615           || child->tag == DW_TAG_lexical_block)
12616         dwarf2_get_subprogram_pc_bounds (child, lowpc, highpc, cu);
12617       child = sibling_die (child);
12618     }
12619 }
12620
12621 /* Get the low and high pc's represented by the scope DIE, and store
12622    them in *LOWPC and *HIGHPC.  If the correct values can't be
12623    determined, set *LOWPC to -1 and *HIGHPC to 0.  */
12624
12625 static void
12626 get_scope_pc_bounds (struct die_info *die,
12627                      CORE_ADDR *lowpc, CORE_ADDR *highpc,
12628                      struct dwarf2_cu *cu)
12629 {
12630   CORE_ADDR best_low = (CORE_ADDR) -1;
12631   CORE_ADDR best_high = (CORE_ADDR) 0;
12632   CORE_ADDR current_low, current_high;
12633
12634   if (dwarf2_get_pc_bounds (die, &current_low, &current_high, cu, NULL)
12635       >= PC_BOUNDS_RANGES)
12636     {
12637       best_low = current_low;
12638       best_high = current_high;
12639     }
12640   else
12641     {
12642       struct die_info *child = die->child;
12643
12644       while (child && child->tag)
12645         {
12646           switch (child->tag) {
12647           case DW_TAG_subprogram:
12648             dwarf2_get_subprogram_pc_bounds (child, &best_low, &best_high, cu);
12649             break;
12650           case DW_TAG_namespace:
12651           case DW_TAG_module:
12652             /* FIXME: carlton/2004-01-16: Should we do this for
12653                DW_TAG_class_type/DW_TAG_structure_type, too?  I think
12654                that current GCC's always emit the DIEs corresponding
12655                to definitions of methods of classes as children of a
12656                DW_TAG_compile_unit or DW_TAG_namespace (as opposed to
12657                the DIEs giving the declarations, which could be
12658                anywhere).  But I don't see any reason why the
12659                standards says that they have to be there.  */
12660             get_scope_pc_bounds (child, &current_low, &current_high, cu);
12661
12662             if (current_low != ((CORE_ADDR) -1))
12663               {
12664                 best_low = std::min (best_low, current_low);
12665                 best_high = std::max (best_high, current_high);
12666               }
12667             break;
12668           default:
12669             /* Ignore.  */
12670             break;
12671           }
12672
12673           child = sibling_die (child);
12674         }
12675     }
12676
12677   *lowpc = best_low;
12678   *highpc = best_high;
12679 }
12680
12681 /* Record the address ranges for BLOCK, offset by BASEADDR, as given
12682    in DIE.  */
12683
12684 static void
12685 dwarf2_record_block_ranges (struct die_info *die, struct block *block,
12686                             CORE_ADDR baseaddr, struct dwarf2_cu *cu)
12687 {
12688   struct objfile *objfile = cu->objfile;
12689   struct gdbarch *gdbarch = get_objfile_arch (objfile);
12690   struct attribute *attr;
12691   struct attribute *attr_high;
12692
12693   attr_high = dwarf2_attr (die, DW_AT_high_pc, cu);
12694   if (attr_high)
12695     {
12696       attr = dwarf2_attr (die, DW_AT_low_pc, cu);
12697       if (attr)
12698         {
12699           CORE_ADDR low = attr_value_as_address (attr);
12700           CORE_ADDR high = attr_value_as_address (attr_high);
12701
12702           if (cu->header.version >= 4 && attr_form_is_constant (attr_high))
12703             high += low;
12704
12705           low = gdbarch_adjust_dwarf2_addr (gdbarch, low + baseaddr);
12706           high = gdbarch_adjust_dwarf2_addr (gdbarch, high + baseaddr);
12707           record_block_range (block, low, high - 1);
12708         }
12709     }
12710
12711   attr = dwarf2_attr (die, DW_AT_ranges, cu);
12712   if (attr)
12713     {
12714       bfd *obfd = objfile->obfd;
12715       /* DW_AT_ranges_base does not apply to DIEs from the DWO skeleton.
12716          We take advantage of the fact that DW_AT_ranges does not appear
12717          in DW_TAG_compile_unit of DWO files.  */
12718       int need_ranges_base = die->tag != DW_TAG_compile_unit;
12719
12720       /* The value of the DW_AT_ranges attribute is the offset of the
12721          address range list in the .debug_ranges section.  */
12722       unsigned long offset = (DW_UNSND (attr)
12723                               + (need_ranges_base ? cu->ranges_base : 0));
12724       const gdb_byte *buffer;
12725
12726       /* For some target architectures, but not others, the
12727          read_address function sign-extends the addresses it returns.
12728          To recognize base address selection entries, we need a
12729          mask.  */
12730       unsigned int addr_size = cu->header.addr_size;
12731       CORE_ADDR base_select_mask = ~(~(CORE_ADDR)1 << (addr_size * 8 - 1));
12732
12733       /* The base address, to which the next pair is relative.  Note
12734          that this 'base' is a DWARF concept: most entries in a range
12735          list are relative, to reduce the number of relocs against the
12736          debugging information.  This is separate from this function's
12737          'baseaddr' argument, which GDB uses to relocate debugging
12738          information from a shared library based on the address at
12739          which the library was loaded.  */
12740       CORE_ADDR base = cu->base_address;
12741       int base_known = cu->base_known;
12742
12743       dwarf2_ranges_process (offset, cu,
12744         [&] (CORE_ADDR start, CORE_ADDR end)
12745         {
12746           start += baseaddr;
12747           end += baseaddr;
12748           start = gdbarch_adjust_dwarf2_addr (gdbarch, start);
12749           end = gdbarch_adjust_dwarf2_addr (gdbarch, end);
12750           record_block_range (block, start, end - 1);
12751         });
12752     }
12753 }
12754
12755 /* Check whether the producer field indicates either of GCC < 4.6, or the
12756    Intel C/C++ compiler, and cache the result in CU.  */
12757
12758 static void
12759 check_producer (struct dwarf2_cu *cu)
12760 {
12761   int major, minor;
12762
12763   if (cu->producer == NULL)
12764     {
12765       /* For unknown compilers expect their behavior is DWARF version
12766          compliant.
12767
12768          GCC started to support .debug_types sections by -gdwarf-4 since
12769          gcc-4.5.x.  As the .debug_types sections are missing DW_AT_producer
12770          for their space efficiency GDB cannot workaround gcc-4.5.x -gdwarf-4
12771          combination.  gcc-4.5.x -gdwarf-4 binaries have DW_AT_accessibility
12772          interpreted incorrectly by GDB now - GCC PR debug/48229.  */
12773     }
12774   else if (producer_is_gcc (cu->producer, &major, &minor))
12775     {
12776       cu->producer_is_gxx_lt_4_6 = major < 4 || (major == 4 && minor < 6);
12777       cu->producer_is_gcc_lt_4_3 = major < 4 || (major == 4 && minor < 3);
12778     }
12779   else if (startswith (cu->producer, "Intel(R) C"))
12780     cu->producer_is_icc = 1;
12781   else
12782     {
12783       /* For other non-GCC compilers, expect their behavior is DWARF version
12784          compliant.  */
12785     }
12786
12787   cu->checked_producer = 1;
12788 }
12789
12790 /* Check for GCC PR debug/45124 fix which is not present in any G++ version up
12791    to 4.5.any while it is present already in G++ 4.6.0 - the PR has been fixed
12792    during 4.6.0 experimental.  */
12793
12794 static int
12795 producer_is_gxx_lt_4_6 (struct dwarf2_cu *cu)
12796 {
12797   if (!cu->checked_producer)
12798     check_producer (cu);
12799
12800   return cu->producer_is_gxx_lt_4_6;
12801 }
12802
12803 /* Return the default accessibility type if it is not overriden by
12804    DW_AT_accessibility.  */
12805
12806 static enum dwarf_access_attribute
12807 dwarf2_default_access_attribute (struct die_info *die, struct dwarf2_cu *cu)
12808 {
12809   if (cu->header.version < 3 || producer_is_gxx_lt_4_6 (cu))
12810     {
12811       /* The default DWARF 2 accessibility for members is public, the default
12812          accessibility for inheritance is private.  */
12813
12814       if (die->tag != DW_TAG_inheritance)
12815         return DW_ACCESS_public;
12816       else
12817         return DW_ACCESS_private;
12818     }
12819   else
12820     {
12821       /* DWARF 3+ defines the default accessibility a different way.  The same
12822          rules apply now for DW_TAG_inheritance as for the members and it only
12823          depends on the container kind.  */
12824
12825       if (die->parent->tag == DW_TAG_class_type)
12826         return DW_ACCESS_private;
12827       else
12828         return DW_ACCESS_public;
12829     }
12830 }
12831
12832 /* Look for DW_AT_data_member_location.  Set *OFFSET to the byte
12833    offset.  If the attribute was not found return 0, otherwise return
12834    1.  If it was found but could not properly be handled, set *OFFSET
12835    to 0.  */
12836
12837 static int
12838 handle_data_member_location (struct die_info *die, struct dwarf2_cu *cu,
12839                              LONGEST *offset)
12840 {
12841   struct attribute *attr;
12842
12843   attr = dwarf2_attr (die, DW_AT_data_member_location, cu);
12844   if (attr != NULL)
12845     {
12846       *offset = 0;
12847
12848       /* Note that we do not check for a section offset first here.
12849          This is because DW_AT_data_member_location is new in DWARF 4,
12850          so if we see it, we can assume that a constant form is really
12851          a constant and not a section offset.  */
12852       if (attr_form_is_constant (attr))
12853         *offset = dwarf2_get_attr_constant_value (attr, 0);
12854       else if (attr_form_is_section_offset (attr))
12855         dwarf2_complex_location_expr_complaint ();
12856       else if (attr_form_is_block (attr))
12857         *offset = decode_locdesc (DW_BLOCK (attr), cu);
12858       else
12859         dwarf2_complex_location_expr_complaint ();
12860
12861       return 1;
12862     }
12863
12864   return 0;
12865 }
12866
12867 /* Add an aggregate field to the field list.  */
12868
12869 static void
12870 dwarf2_add_field (struct field_info *fip, struct die_info *die,
12871                   struct dwarf2_cu *cu)
12872 {
12873   struct objfile *objfile = cu->objfile;
12874   struct gdbarch *gdbarch = get_objfile_arch (objfile);
12875   struct nextfield *new_field;
12876   struct attribute *attr;
12877   struct field *fp;
12878   const char *fieldname = "";
12879
12880   /* Allocate a new field list entry and link it in.  */
12881   new_field = XNEW (struct nextfield);
12882   make_cleanup (xfree, new_field);
12883   memset (new_field, 0, sizeof (struct nextfield));
12884
12885   if (die->tag == DW_TAG_inheritance)
12886     {
12887       new_field->next = fip->baseclasses;
12888       fip->baseclasses = new_field;
12889     }
12890   else
12891     {
12892       new_field->next = fip->fields;
12893       fip->fields = new_field;
12894     }
12895   fip->nfields++;
12896
12897   attr = dwarf2_attr (die, DW_AT_accessibility, cu);
12898   if (attr)
12899     new_field->accessibility = DW_UNSND (attr);
12900   else
12901     new_field->accessibility = dwarf2_default_access_attribute (die, cu);
12902   if (new_field->accessibility != DW_ACCESS_public)
12903     fip->non_public_fields = 1;
12904
12905   attr = dwarf2_attr (die, DW_AT_virtuality, cu);
12906   if (attr)
12907     new_field->virtuality = DW_UNSND (attr);
12908   else
12909     new_field->virtuality = DW_VIRTUALITY_none;
12910
12911   fp = &new_field->field;
12912
12913   if (die->tag == DW_TAG_member && ! die_is_declaration (die, cu))
12914     {
12915       LONGEST offset;
12916
12917       /* Data member other than a C++ static data member.  */
12918
12919       /* Get type of field.  */
12920       fp->type = die_type (die, cu);
12921
12922       SET_FIELD_BITPOS (*fp, 0);
12923
12924       /* Get bit size of field (zero if none).  */
12925       attr = dwarf2_attr (die, DW_AT_bit_size, cu);
12926       if (attr)
12927         {
12928           FIELD_BITSIZE (*fp) = DW_UNSND (attr);
12929         }
12930       else
12931         {
12932           FIELD_BITSIZE (*fp) = 0;
12933         }
12934
12935       /* Get bit offset of field.  */
12936       if (handle_data_member_location (die, cu, &offset))
12937         SET_FIELD_BITPOS (*fp, offset * bits_per_byte);
12938       attr = dwarf2_attr (die, DW_AT_bit_offset, cu);
12939       if (attr)
12940         {
12941           if (gdbarch_bits_big_endian (gdbarch))
12942             {
12943               /* For big endian bits, the DW_AT_bit_offset gives the
12944                  additional bit offset from the MSB of the containing
12945                  anonymous object to the MSB of the field.  We don't
12946                  have to do anything special since we don't need to
12947                  know the size of the anonymous object.  */
12948               SET_FIELD_BITPOS (*fp, FIELD_BITPOS (*fp) + DW_UNSND (attr));
12949             }
12950           else
12951             {
12952               /* For little endian bits, compute the bit offset to the
12953                  MSB of the anonymous object, subtract off the number of
12954                  bits from the MSB of the field to the MSB of the
12955                  object, and then subtract off the number of bits of
12956                  the field itself.  The result is the bit offset of
12957                  the LSB of the field.  */
12958               int anonymous_size;
12959               int bit_offset = DW_UNSND (attr);
12960
12961               attr = dwarf2_attr (die, DW_AT_byte_size, cu);
12962               if (attr)
12963                 {
12964                   /* The size of the anonymous object containing
12965                      the bit field is explicit, so use the
12966                      indicated size (in bytes).  */
12967                   anonymous_size = DW_UNSND (attr);
12968                 }
12969               else
12970                 {
12971                   /* The size of the anonymous object containing
12972                      the bit field must be inferred from the type
12973                      attribute of the data member containing the
12974                      bit field.  */
12975                   anonymous_size = TYPE_LENGTH (fp->type);
12976                 }
12977               SET_FIELD_BITPOS (*fp,
12978                                 (FIELD_BITPOS (*fp)
12979                                  + anonymous_size * bits_per_byte
12980                                  - bit_offset - FIELD_BITSIZE (*fp)));
12981             }
12982         }
12983       attr = dwarf2_attr (die, DW_AT_data_bit_offset, cu);
12984       if (attr != NULL)
12985         SET_FIELD_BITPOS (*fp, (FIELD_BITPOS (*fp)
12986                                 + dwarf2_get_attr_constant_value (attr, 0)));
12987
12988       /* Get name of field.  */
12989       fieldname = dwarf2_name (die, cu);
12990       if (fieldname == NULL)
12991         fieldname = "";
12992
12993       /* The name is already allocated along with this objfile, so we don't
12994          need to duplicate it for the type.  */
12995       fp->name = fieldname;
12996
12997       /* Change accessibility for artificial fields (e.g. virtual table
12998          pointer or virtual base class pointer) to private.  */
12999       if (dwarf2_attr (die, DW_AT_artificial, cu))
13000         {
13001           FIELD_ARTIFICIAL (*fp) = 1;
13002           new_field->accessibility = DW_ACCESS_private;
13003           fip->non_public_fields = 1;
13004         }
13005     }
13006   else if (die->tag == DW_TAG_member || die->tag == DW_TAG_variable)
13007     {
13008       /* C++ static member.  */
13009
13010       /* NOTE: carlton/2002-11-05: It should be a DW_TAG_member that
13011          is a declaration, but all versions of G++ as of this writing
13012          (so through at least 3.2.1) incorrectly generate
13013          DW_TAG_variable tags.  */
13014
13015       const char *physname;
13016
13017       /* Get name of field.  */
13018       fieldname = dwarf2_name (die, cu);
13019       if (fieldname == NULL)
13020         return;
13021
13022       attr = dwarf2_attr (die, DW_AT_const_value, cu);
13023       if (attr
13024           /* Only create a symbol if this is an external value.
13025              new_symbol checks this and puts the value in the global symbol
13026              table, which we want.  If it is not external, new_symbol
13027              will try to put the value in cu->list_in_scope which is wrong.  */
13028           && dwarf2_flag_true_p (die, DW_AT_external, cu))
13029         {
13030           /* A static const member, not much different than an enum as far as
13031              we're concerned, except that we can support more types.  */
13032           new_symbol (die, NULL, cu);
13033         }
13034
13035       /* Get physical name.  */
13036       physname = dwarf2_physname (fieldname, die, cu);
13037
13038       /* The name is already allocated along with this objfile, so we don't
13039          need to duplicate it for the type.  */
13040       SET_FIELD_PHYSNAME (*fp, physname ? physname : "");
13041       FIELD_TYPE (*fp) = die_type (die, cu);
13042       FIELD_NAME (*fp) = fieldname;
13043     }
13044   else if (die->tag == DW_TAG_inheritance)
13045     {
13046       LONGEST offset;
13047
13048       /* C++ base class field.  */
13049       if (handle_data_member_location (die, cu, &offset))
13050         SET_FIELD_BITPOS (*fp, offset * bits_per_byte);
13051       FIELD_BITSIZE (*fp) = 0;
13052       FIELD_TYPE (*fp) = die_type (die, cu);
13053       FIELD_NAME (*fp) = type_name_no_tag (fp->type);
13054       fip->nbaseclasses++;
13055     }
13056 }
13057
13058 /* Add a typedef defined in the scope of the FIP's class.  */
13059
13060 static void
13061 dwarf2_add_typedef (struct field_info *fip, struct die_info *die,
13062                     struct dwarf2_cu *cu)
13063 {
13064   struct typedef_field_list *new_field;
13065   struct typedef_field *fp;
13066
13067   /* Allocate a new field list entry and link it in.  */
13068   new_field = XCNEW (struct typedef_field_list);
13069   make_cleanup (xfree, new_field);
13070
13071   gdb_assert (die->tag == DW_TAG_typedef);
13072
13073   fp = &new_field->field;
13074
13075   /* Get name of field.  */
13076   fp->name = dwarf2_name (die, cu);
13077   if (fp->name == NULL)
13078     return;
13079
13080   fp->type = read_type_die (die, cu);
13081
13082   new_field->next = fip->typedef_field_list;
13083   fip->typedef_field_list = new_field;
13084   fip->typedef_field_list_count++;
13085 }
13086
13087 /* Create the vector of fields, and attach it to the type.  */
13088
13089 static void
13090 dwarf2_attach_fields_to_type (struct field_info *fip, struct type *type,
13091                               struct dwarf2_cu *cu)
13092 {
13093   int nfields = fip->nfields;
13094
13095   /* Record the field count, allocate space for the array of fields,
13096      and create blank accessibility bitfields if necessary.  */
13097   TYPE_NFIELDS (type) = nfields;
13098   TYPE_FIELDS (type) = (struct field *)
13099     TYPE_ALLOC (type, sizeof (struct field) * nfields);
13100   memset (TYPE_FIELDS (type), 0, sizeof (struct field) * nfields);
13101
13102   if (fip->non_public_fields && cu->language != language_ada)
13103     {
13104       ALLOCATE_CPLUS_STRUCT_TYPE (type);
13105
13106       TYPE_FIELD_PRIVATE_BITS (type) =
13107         (B_TYPE *) TYPE_ALLOC (type, B_BYTES (nfields));
13108       B_CLRALL (TYPE_FIELD_PRIVATE_BITS (type), nfields);
13109
13110       TYPE_FIELD_PROTECTED_BITS (type) =
13111         (B_TYPE *) TYPE_ALLOC (type, B_BYTES (nfields));
13112       B_CLRALL (TYPE_FIELD_PROTECTED_BITS (type), nfields);
13113
13114       TYPE_FIELD_IGNORE_BITS (type) =
13115         (B_TYPE *) TYPE_ALLOC (type, B_BYTES (nfields));
13116       B_CLRALL (TYPE_FIELD_IGNORE_BITS (type), nfields);
13117     }
13118
13119   /* If the type has baseclasses, allocate and clear a bit vector for
13120      TYPE_FIELD_VIRTUAL_BITS.  */
13121   if (fip->nbaseclasses && cu->language != language_ada)
13122     {
13123       int num_bytes = B_BYTES (fip->nbaseclasses);
13124       unsigned char *pointer;
13125
13126       ALLOCATE_CPLUS_STRUCT_TYPE (type);
13127       pointer = (unsigned char *) TYPE_ALLOC (type, num_bytes);
13128       TYPE_FIELD_VIRTUAL_BITS (type) = pointer;
13129       B_CLRALL (TYPE_FIELD_VIRTUAL_BITS (type), fip->nbaseclasses);
13130       TYPE_N_BASECLASSES (type) = fip->nbaseclasses;
13131     }
13132
13133   /* Copy the saved-up fields into the field vector.  Start from the head of
13134      the list, adding to the tail of the field array, so that they end up in
13135      the same order in the array in which they were added to the list.  */
13136   while (nfields-- > 0)
13137     {
13138       struct nextfield *fieldp;
13139
13140       if (fip->fields)
13141         {
13142           fieldp = fip->fields;
13143           fip->fields = fieldp->next;
13144         }
13145       else
13146         {
13147           fieldp = fip->baseclasses;
13148           fip->baseclasses = fieldp->next;
13149         }
13150
13151       TYPE_FIELD (type, nfields) = fieldp->field;
13152       switch (fieldp->accessibility)
13153         {
13154         case DW_ACCESS_private:
13155           if (cu->language != language_ada)
13156             SET_TYPE_FIELD_PRIVATE (type, nfields);
13157           break;
13158
13159         case DW_ACCESS_protected:
13160           if (cu->language != language_ada)
13161             SET_TYPE_FIELD_PROTECTED (type, nfields);
13162           break;
13163
13164         case DW_ACCESS_public:
13165           break;
13166
13167         default:
13168           /* Unknown accessibility.  Complain and treat it as public.  */
13169           {
13170             complaint (&symfile_complaints, _("unsupported accessibility %d"),
13171                        fieldp->accessibility);
13172           }
13173           break;
13174         }
13175       if (nfields < fip->nbaseclasses)
13176         {
13177           switch (fieldp->virtuality)
13178             {
13179             case DW_VIRTUALITY_virtual:
13180             case DW_VIRTUALITY_pure_virtual:
13181               if (cu->language == language_ada)
13182                 error (_("unexpected virtuality in component of Ada type"));
13183               SET_TYPE_FIELD_VIRTUAL (type, nfields);
13184               break;
13185             }
13186         }
13187     }
13188 }
13189
13190 /* Return true if this member function is a constructor, false
13191    otherwise.  */
13192
13193 static int
13194 dwarf2_is_constructor (struct die_info *die, struct dwarf2_cu *cu)
13195 {
13196   const char *fieldname;
13197   const char *type_name;
13198   int len;
13199
13200   if (die->parent == NULL)
13201     return 0;
13202
13203   if (die->parent->tag != DW_TAG_structure_type
13204       && die->parent->tag != DW_TAG_union_type
13205       && die->parent->tag != DW_TAG_class_type)
13206     return 0;
13207
13208   fieldname = dwarf2_name (die, cu);
13209   type_name = dwarf2_name (die->parent, cu);
13210   if (fieldname == NULL || type_name == NULL)
13211     return 0;
13212
13213   len = strlen (fieldname);
13214   return (strncmp (fieldname, type_name, len) == 0
13215           && (type_name[len] == '\0' || type_name[len] == '<'));
13216 }
13217
13218 /* Add a member function to the proper fieldlist.  */
13219
13220 static void
13221 dwarf2_add_member_fn (struct field_info *fip, struct die_info *die,
13222                       struct type *type, struct dwarf2_cu *cu)
13223 {
13224   struct objfile *objfile = cu->objfile;
13225   struct attribute *attr;
13226   struct fnfieldlist *flp;
13227   int i;
13228   struct fn_field *fnp;
13229   const char *fieldname;
13230   struct nextfnfield *new_fnfield;
13231   struct type *this_type;
13232   enum dwarf_access_attribute accessibility;
13233
13234   if (cu->language == language_ada)
13235     error (_("unexpected member function in Ada type"));
13236
13237   /* Get name of member function.  */
13238   fieldname = dwarf2_name (die, cu);
13239   if (fieldname == NULL)
13240     return;
13241
13242   /* Look up member function name in fieldlist.  */
13243   for (i = 0; i < fip->nfnfields; i++)
13244     {
13245       if (strcmp (fip->fnfieldlists[i].name, fieldname) == 0)
13246         break;
13247     }
13248
13249   /* Create new list element if necessary.  */
13250   if (i < fip->nfnfields)
13251     flp = &fip->fnfieldlists[i];
13252   else
13253     {
13254       if ((fip->nfnfields % DW_FIELD_ALLOC_CHUNK) == 0)
13255         {
13256           fip->fnfieldlists = (struct fnfieldlist *)
13257             xrealloc (fip->fnfieldlists,
13258                       (fip->nfnfields + DW_FIELD_ALLOC_CHUNK)
13259                       * sizeof (struct fnfieldlist));
13260           if (fip->nfnfields == 0)
13261             make_cleanup (free_current_contents, &fip->fnfieldlists);
13262         }
13263       flp = &fip->fnfieldlists[fip->nfnfields];
13264       flp->name = fieldname;
13265       flp->length = 0;
13266       flp->head = NULL;
13267       i = fip->nfnfields++;
13268     }
13269
13270   /* Create a new member function field and chain it to the field list
13271      entry.  */
13272   new_fnfield = XNEW (struct nextfnfield);
13273   make_cleanup (xfree, new_fnfield);
13274   memset (new_fnfield, 0, sizeof (struct nextfnfield));
13275   new_fnfield->next = flp->head;
13276   flp->head = new_fnfield;
13277   flp->length++;
13278
13279   /* Fill in the member function field info.  */
13280   fnp = &new_fnfield->fnfield;
13281
13282   /* Delay processing of the physname until later.  */
13283   if (cu->language == language_cplus)
13284     {
13285       add_to_method_list (type, i, flp->length - 1, fieldname,
13286                           die, cu);
13287     }
13288   else
13289     {
13290       const char *physname = dwarf2_physname (fieldname, die, cu);
13291       fnp->physname = physname ? physname : "";
13292     }
13293
13294   fnp->type = alloc_type (objfile);
13295   this_type = read_type_die (die, cu);
13296   if (this_type && TYPE_CODE (this_type) == TYPE_CODE_FUNC)
13297     {
13298       int nparams = TYPE_NFIELDS (this_type);
13299
13300       /* TYPE is the domain of this method, and THIS_TYPE is the type
13301            of the method itself (TYPE_CODE_METHOD).  */
13302       smash_to_method_type (fnp->type, type,
13303                             TYPE_TARGET_TYPE (this_type),
13304                             TYPE_FIELDS (this_type),
13305                             TYPE_NFIELDS (this_type),
13306                             TYPE_VARARGS (this_type));
13307
13308       /* Handle static member functions.
13309          Dwarf2 has no clean way to discern C++ static and non-static
13310          member functions.  G++ helps GDB by marking the first
13311          parameter for non-static member functions (which is the this
13312          pointer) as artificial.  We obtain this information from
13313          read_subroutine_type via TYPE_FIELD_ARTIFICIAL.  */
13314       if (nparams == 0 || TYPE_FIELD_ARTIFICIAL (this_type, 0) == 0)
13315         fnp->voffset = VOFFSET_STATIC;
13316     }
13317   else
13318     complaint (&symfile_complaints, _("member function type missing for '%s'"),
13319                dwarf2_full_name (fieldname, die, cu));
13320
13321   /* Get fcontext from DW_AT_containing_type if present.  */
13322   if (dwarf2_attr (die, DW_AT_containing_type, cu) != NULL)
13323     fnp->fcontext = die_containing_type (die, cu);
13324
13325   /* dwarf2 doesn't have stubbed physical names, so the setting of is_const and
13326      is_volatile is irrelevant, as it is needed by gdb_mangle_name only.  */
13327
13328   /* Get accessibility.  */
13329   attr = dwarf2_attr (die, DW_AT_accessibility, cu);
13330   if (attr)
13331     accessibility = (enum dwarf_access_attribute) DW_UNSND (attr);
13332   else
13333     accessibility = dwarf2_default_access_attribute (die, cu);
13334   switch (accessibility)
13335     {
13336     case DW_ACCESS_private:
13337       fnp->is_private = 1;
13338       break;
13339     case DW_ACCESS_protected:
13340       fnp->is_protected = 1;
13341       break;
13342     }
13343
13344   /* Check for artificial methods.  */
13345   attr = dwarf2_attr (die, DW_AT_artificial, cu);
13346   if (attr && DW_UNSND (attr) != 0)
13347     fnp->is_artificial = 1;
13348
13349   fnp->is_constructor = dwarf2_is_constructor (die, cu);
13350
13351   /* Get index in virtual function table if it is a virtual member
13352      function.  For older versions of GCC, this is an offset in the
13353      appropriate virtual table, as specified by DW_AT_containing_type.
13354      For everyone else, it is an expression to be evaluated relative
13355      to the object address.  */
13356
13357   attr = dwarf2_attr (die, DW_AT_vtable_elem_location, cu);
13358   if (attr)
13359     {
13360       if (attr_form_is_block (attr) && DW_BLOCK (attr)->size > 0)
13361         {
13362           if (DW_BLOCK (attr)->data[0] == DW_OP_constu)
13363             {
13364               /* Old-style GCC.  */
13365               fnp->voffset = decode_locdesc (DW_BLOCK (attr), cu) + 2;
13366             }
13367           else if (DW_BLOCK (attr)->data[0] == DW_OP_deref
13368                    || (DW_BLOCK (attr)->size > 1
13369                        && DW_BLOCK (attr)->data[0] == DW_OP_deref_size
13370                        && DW_BLOCK (attr)->data[1] == cu->header.addr_size))
13371             {
13372               fnp->voffset = decode_locdesc (DW_BLOCK (attr), cu);
13373               if ((fnp->voffset % cu->header.addr_size) != 0)
13374                 dwarf2_complex_location_expr_complaint ();
13375               else
13376                 fnp->voffset /= cu->header.addr_size;
13377               fnp->voffset += 2;
13378             }
13379           else
13380             dwarf2_complex_location_expr_complaint ();
13381
13382           if (!fnp->fcontext)
13383             {
13384               /* If there is no `this' field and no DW_AT_containing_type,
13385                  we cannot actually find a base class context for the
13386                  vtable!  */
13387               if (TYPE_NFIELDS (this_type) == 0
13388                   || !TYPE_FIELD_ARTIFICIAL (this_type, 0))
13389                 {
13390                   complaint (&symfile_complaints,
13391                              _("cannot determine context for virtual member "
13392                                "function \"%s\" (offset %d)"),
13393                              fieldname, to_underlying (die->sect_off));
13394                 }
13395               else
13396                 {
13397                   fnp->fcontext
13398                     = TYPE_TARGET_TYPE (TYPE_FIELD_TYPE (this_type, 0));
13399                 }
13400             }
13401         }
13402       else if (attr_form_is_section_offset (attr))
13403         {
13404           dwarf2_complex_location_expr_complaint ();
13405         }
13406       else
13407         {
13408           dwarf2_invalid_attrib_class_complaint ("DW_AT_vtable_elem_location",
13409                                                  fieldname);
13410         }
13411     }
13412   else
13413     {
13414       attr = dwarf2_attr (die, DW_AT_virtuality, cu);
13415       if (attr && DW_UNSND (attr))
13416         {
13417           /* GCC does this, as of 2008-08-25; PR debug/37237.  */
13418           complaint (&symfile_complaints,
13419                      _("Member function \"%s\" (offset %d) is virtual "
13420                        "but the vtable offset is not specified"),
13421                      fieldname, to_underlying (die->sect_off));
13422           ALLOCATE_CPLUS_STRUCT_TYPE (type);
13423           TYPE_CPLUS_DYNAMIC (type) = 1;
13424         }
13425     }
13426 }
13427
13428 /* Create the vector of member function fields, and attach it to the type.  */
13429
13430 static void
13431 dwarf2_attach_fn_fields_to_type (struct field_info *fip, struct type *type,
13432                                  struct dwarf2_cu *cu)
13433 {
13434   struct fnfieldlist *flp;
13435   int i;
13436
13437   if (cu->language == language_ada)
13438     error (_("unexpected member functions in Ada type"));
13439
13440   ALLOCATE_CPLUS_STRUCT_TYPE (type);
13441   TYPE_FN_FIELDLISTS (type) = (struct fn_fieldlist *)
13442     TYPE_ALLOC (type, sizeof (struct fn_fieldlist) * fip->nfnfields);
13443
13444   for (i = 0, flp = fip->fnfieldlists; i < fip->nfnfields; i++, flp++)
13445     {
13446       struct nextfnfield *nfp = flp->head;
13447       struct fn_fieldlist *fn_flp = &TYPE_FN_FIELDLIST (type, i);
13448       int k;
13449
13450       TYPE_FN_FIELDLIST_NAME (type, i) = flp->name;
13451       TYPE_FN_FIELDLIST_LENGTH (type, i) = flp->length;
13452       fn_flp->fn_fields = (struct fn_field *)
13453         TYPE_ALLOC (type, sizeof (struct fn_field) * flp->length);
13454       for (k = flp->length; (k--, nfp); nfp = nfp->next)
13455         fn_flp->fn_fields[k] = nfp->fnfield;
13456     }
13457
13458   TYPE_NFN_FIELDS (type) = fip->nfnfields;
13459 }
13460
13461 /* Returns non-zero if NAME is the name of a vtable member in CU's
13462    language, zero otherwise.  */
13463 static int
13464 is_vtable_name (const char *name, struct dwarf2_cu *cu)
13465 {
13466   static const char vptr[] = "_vptr";
13467   static const char vtable[] = "vtable";
13468
13469   /* Look for the C++ form of the vtable.  */
13470   if (startswith (name, vptr) && is_cplus_marker (name[sizeof (vptr) - 1]))
13471     return 1;
13472
13473   return 0;
13474 }
13475
13476 /* GCC outputs unnamed structures that are really pointers to member
13477    functions, with the ABI-specified layout.  If TYPE describes
13478    such a structure, smash it into a member function type.
13479
13480    GCC shouldn't do this; it should just output pointer to member DIEs.
13481    This is GCC PR debug/28767.  */
13482
13483 static void
13484 quirk_gcc_member_function_pointer (struct type *type, struct objfile *objfile)
13485 {
13486   struct type *pfn_type, *self_type, *new_type;
13487
13488   /* Check for a structure with no name and two children.  */
13489   if (TYPE_CODE (type) != TYPE_CODE_STRUCT || TYPE_NFIELDS (type) != 2)
13490     return;
13491
13492   /* Check for __pfn and __delta members.  */
13493   if (TYPE_FIELD_NAME (type, 0) == NULL
13494       || strcmp (TYPE_FIELD_NAME (type, 0), "__pfn") != 0
13495       || TYPE_FIELD_NAME (type, 1) == NULL
13496       || strcmp (TYPE_FIELD_NAME (type, 1), "__delta") != 0)
13497     return;
13498
13499   /* Find the type of the method.  */
13500   pfn_type = TYPE_FIELD_TYPE (type, 0);
13501   if (pfn_type == NULL
13502       || TYPE_CODE (pfn_type) != TYPE_CODE_PTR
13503       || TYPE_CODE (TYPE_TARGET_TYPE (pfn_type)) != TYPE_CODE_FUNC)
13504     return;
13505
13506   /* Look for the "this" argument.  */
13507   pfn_type = TYPE_TARGET_TYPE (pfn_type);
13508   if (TYPE_NFIELDS (pfn_type) == 0
13509       /* || TYPE_FIELD_TYPE (pfn_type, 0) == NULL */
13510       || TYPE_CODE (TYPE_FIELD_TYPE (pfn_type, 0)) != TYPE_CODE_PTR)
13511     return;
13512
13513   self_type = TYPE_TARGET_TYPE (TYPE_FIELD_TYPE (pfn_type, 0));
13514   new_type = alloc_type (objfile);
13515   smash_to_method_type (new_type, self_type, TYPE_TARGET_TYPE (pfn_type),
13516                         TYPE_FIELDS (pfn_type), TYPE_NFIELDS (pfn_type),
13517                         TYPE_VARARGS (pfn_type));
13518   smash_to_methodptr_type (type, new_type);
13519 }
13520
13521 /* Return non-zero if the CU's PRODUCER string matches the Intel C/C++ compiler
13522    (icc).  */
13523
13524 static int
13525 producer_is_icc (struct dwarf2_cu *cu)
13526 {
13527   if (!cu->checked_producer)
13528     check_producer (cu);
13529
13530   return cu->producer_is_icc;
13531 }
13532
13533 /* Called when we find the DIE that starts a structure or union scope
13534    (definition) to create a type for the structure or union.  Fill in
13535    the type's name and general properties; the members will not be
13536    processed until process_structure_scope.  A symbol table entry for
13537    the type will also not be done until process_structure_scope (assuming
13538    the type has a name).
13539
13540    NOTE: we need to call these functions regardless of whether or not the
13541    DIE has a DW_AT_name attribute, since it might be an anonymous
13542    structure or union.  This gets the type entered into our set of
13543    user defined types.  */
13544
13545 static struct type *
13546 read_structure_type (struct die_info *die, struct dwarf2_cu *cu)
13547 {
13548   struct objfile *objfile = cu->objfile;
13549   struct type *type;
13550   struct attribute *attr;
13551   const char *name;
13552
13553   /* If the definition of this type lives in .debug_types, read that type.
13554      Don't follow DW_AT_specification though, that will take us back up
13555      the chain and we want to go down.  */
13556   attr = dwarf2_attr_no_follow (die, DW_AT_signature);
13557   if (attr)
13558     {
13559       type = get_DW_AT_signature_type (die, attr, cu);
13560
13561       /* The type's CU may not be the same as CU.
13562          Ensure TYPE is recorded with CU in die_type_hash.  */
13563       return set_die_type (die, type, cu);
13564     }
13565
13566   type = alloc_type (objfile);
13567   INIT_CPLUS_SPECIFIC (type);
13568
13569   name = dwarf2_name (die, cu);
13570   if (name != NULL)
13571     {
13572       if (cu->language == language_cplus
13573           || cu->language == language_d
13574           || cu->language == language_rust)
13575         {
13576           const char *full_name = dwarf2_full_name (name, die, cu);
13577
13578           /* dwarf2_full_name might have already finished building the DIE's
13579              type.  If so, there is no need to continue.  */
13580           if (get_die_type (die, cu) != NULL)
13581             return get_die_type (die, cu);
13582
13583           TYPE_TAG_NAME (type) = full_name;
13584           if (die->tag == DW_TAG_structure_type
13585               || die->tag == DW_TAG_class_type)
13586             TYPE_NAME (type) = TYPE_TAG_NAME (type);
13587         }
13588       else
13589         {
13590           /* The name is already allocated along with this objfile, so
13591              we don't need to duplicate it for the type.  */
13592           TYPE_TAG_NAME (type) = name;
13593           if (die->tag == DW_TAG_class_type)
13594             TYPE_NAME (type) = TYPE_TAG_NAME (type);
13595         }
13596     }
13597
13598   if (die->tag == DW_TAG_structure_type)
13599     {
13600       TYPE_CODE (type) = TYPE_CODE_STRUCT;
13601     }
13602   else if (die->tag == DW_TAG_union_type)
13603     {
13604       TYPE_CODE (type) = TYPE_CODE_UNION;
13605     }
13606   else
13607     {
13608       TYPE_CODE (type) = TYPE_CODE_STRUCT;
13609     }
13610
13611   if (cu->language == language_cplus && die->tag == DW_TAG_class_type)
13612     TYPE_DECLARED_CLASS (type) = 1;
13613
13614   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
13615   if (attr)
13616     {
13617       if (attr_form_is_constant (attr))
13618         TYPE_LENGTH (type) = DW_UNSND (attr);
13619       else
13620         {
13621           /* For the moment, dynamic type sizes are not supported
13622              by GDB's struct type.  The actual size is determined
13623              on-demand when resolving the type of a given object,
13624              so set the type's length to zero for now.  Otherwise,
13625              we record an expression as the length, and that expression
13626              could lead to a very large value, which could eventually
13627              lead to us trying to allocate that much memory when creating
13628              a value of that type.  */
13629           TYPE_LENGTH (type) = 0;
13630         }
13631     }
13632   else
13633     {
13634       TYPE_LENGTH (type) = 0;
13635     }
13636
13637   if (producer_is_icc (cu) && (TYPE_LENGTH (type) == 0))
13638     {
13639       /* ICC does not output the required DW_AT_declaration
13640          on incomplete types, but gives them a size of zero.  */
13641       TYPE_STUB (type) = 1;
13642     }
13643   else
13644     TYPE_STUB_SUPPORTED (type) = 1;
13645
13646   if (die_is_declaration (die, cu))
13647     TYPE_STUB (type) = 1;
13648   else if (attr == NULL && die->child == NULL
13649            && producer_is_realview (cu->producer))
13650     /* RealView does not output the required DW_AT_declaration
13651        on incomplete types.  */
13652     TYPE_STUB (type) = 1;
13653
13654   /* We need to add the type field to the die immediately so we don't
13655      infinitely recurse when dealing with pointers to the structure
13656      type within the structure itself.  */
13657   set_die_type (die, type, cu);
13658
13659   /* set_die_type should be already done.  */
13660   set_descriptive_type (type, die, cu);
13661
13662   return type;
13663 }
13664
13665 /* Finish creating a structure or union type, including filling in
13666    its members and creating a symbol for it.  */
13667
13668 static void
13669 process_structure_scope (struct die_info *die, struct dwarf2_cu *cu)
13670 {
13671   struct objfile *objfile = cu->objfile;
13672   struct die_info *child_die;
13673   struct type *type;
13674
13675   type = get_die_type (die, cu);
13676   if (type == NULL)
13677     type = read_structure_type (die, cu);
13678
13679   if (die->child != NULL && ! die_is_declaration (die, cu))
13680     {
13681       struct field_info fi;
13682       VEC (symbolp) *template_args = NULL;
13683       struct cleanup *back_to = make_cleanup (null_cleanup, 0);
13684
13685       memset (&fi, 0, sizeof (struct field_info));
13686
13687       child_die = die->child;
13688
13689       while (child_die && child_die->tag)
13690         {
13691           if (child_die->tag == DW_TAG_member
13692               || child_die->tag == DW_TAG_variable)
13693             {
13694               /* NOTE: carlton/2002-11-05: A C++ static data member
13695                  should be a DW_TAG_member that is a declaration, but
13696                  all versions of G++ as of this writing (so through at
13697                  least 3.2.1) incorrectly generate DW_TAG_variable
13698                  tags for them instead.  */
13699               dwarf2_add_field (&fi, child_die, cu);
13700             }
13701           else if (child_die->tag == DW_TAG_subprogram)
13702             {
13703               /* Rust doesn't have member functions in the C++ sense.
13704                  However, it does emit ordinary functions as children
13705                  of a struct DIE.  */
13706               if (cu->language == language_rust)
13707                 read_func_scope (child_die, cu);
13708               else
13709                 {
13710                   /* C++ member function.  */
13711                   dwarf2_add_member_fn (&fi, child_die, type, cu);
13712                 }
13713             }
13714           else if (child_die->tag == DW_TAG_inheritance)
13715             {
13716               /* C++ base class field.  */
13717               dwarf2_add_field (&fi, child_die, cu);
13718             }
13719           else if (child_die->tag == DW_TAG_typedef)
13720             dwarf2_add_typedef (&fi, child_die, cu);
13721           else if (child_die->tag == DW_TAG_template_type_param
13722                    || child_die->tag == DW_TAG_template_value_param)
13723             {
13724               struct symbol *arg = new_symbol (child_die, NULL, cu);
13725
13726               if (arg != NULL)
13727                 VEC_safe_push (symbolp, template_args, arg);
13728             }
13729
13730           child_die = sibling_die (child_die);
13731         }
13732
13733       /* Attach template arguments to type.  */
13734       if (! VEC_empty (symbolp, template_args))
13735         {
13736           ALLOCATE_CPLUS_STRUCT_TYPE (type);
13737           TYPE_N_TEMPLATE_ARGUMENTS (type)
13738             = VEC_length (symbolp, template_args);
13739           TYPE_TEMPLATE_ARGUMENTS (type)
13740             = XOBNEWVEC (&objfile->objfile_obstack,
13741                          struct symbol *,
13742                          TYPE_N_TEMPLATE_ARGUMENTS (type));
13743           memcpy (TYPE_TEMPLATE_ARGUMENTS (type),
13744                   VEC_address (symbolp, template_args),
13745                   (TYPE_N_TEMPLATE_ARGUMENTS (type)
13746                    * sizeof (struct symbol *)));
13747           VEC_free (symbolp, template_args);
13748         }
13749
13750       /* Attach fields and member functions to the type.  */
13751       if (fi.nfields)
13752         dwarf2_attach_fields_to_type (&fi, type, cu);
13753       if (fi.nfnfields)
13754         {
13755           dwarf2_attach_fn_fields_to_type (&fi, type, cu);
13756
13757           /* Get the type which refers to the base class (possibly this
13758              class itself) which contains the vtable pointer for the current
13759              class from the DW_AT_containing_type attribute.  This use of
13760              DW_AT_containing_type is a GNU extension.  */
13761
13762           if (dwarf2_attr (die, DW_AT_containing_type, cu) != NULL)
13763             {
13764               struct type *t = die_containing_type (die, cu);
13765
13766               set_type_vptr_basetype (type, t);
13767               if (type == t)
13768                 {
13769                   int i;
13770
13771                   /* Our own class provides vtbl ptr.  */
13772                   for (i = TYPE_NFIELDS (t) - 1;
13773                        i >= TYPE_N_BASECLASSES (t);
13774                        --i)
13775                     {
13776                       const char *fieldname = TYPE_FIELD_NAME (t, i);
13777
13778                       if (is_vtable_name (fieldname, cu))
13779                         {
13780                           set_type_vptr_fieldno (type, i);
13781                           break;
13782                         }
13783                     }
13784
13785                   /* Complain if virtual function table field not found.  */
13786                   if (i < TYPE_N_BASECLASSES (t))
13787                     complaint (&symfile_complaints,
13788                                _("virtual function table pointer "
13789                                  "not found when defining class '%s'"),
13790                                TYPE_TAG_NAME (type) ? TYPE_TAG_NAME (type) :
13791                                "");
13792                 }
13793               else
13794                 {
13795                   set_type_vptr_fieldno (type, TYPE_VPTR_FIELDNO (t));
13796                 }
13797             }
13798           else if (cu->producer
13799                    && startswith (cu->producer, "IBM(R) XL C/C++ Advanced Edition"))
13800             {
13801               /* The IBM XLC compiler does not provide direct indication
13802                  of the containing type, but the vtable pointer is
13803                  always named __vfp.  */
13804
13805               int i;
13806
13807               for (i = TYPE_NFIELDS (type) - 1;
13808                    i >= TYPE_N_BASECLASSES (type);
13809                    --i)
13810                 {
13811                   if (strcmp (TYPE_FIELD_NAME (type, i), "__vfp") == 0)
13812                     {
13813                       set_type_vptr_fieldno (type, i);
13814                       set_type_vptr_basetype (type, type);
13815                       break;
13816                     }
13817                 }
13818             }
13819         }
13820
13821       /* Copy fi.typedef_field_list linked list elements content into the
13822          allocated array TYPE_TYPEDEF_FIELD_ARRAY (type).  */
13823       if (fi.typedef_field_list)
13824         {
13825           int i = fi.typedef_field_list_count;
13826
13827           ALLOCATE_CPLUS_STRUCT_TYPE (type);
13828           TYPE_TYPEDEF_FIELD_ARRAY (type)
13829             = ((struct typedef_field *)
13830                TYPE_ALLOC (type, sizeof (TYPE_TYPEDEF_FIELD (type, 0)) * i));
13831           TYPE_TYPEDEF_FIELD_COUNT (type) = i;
13832
13833           /* Reverse the list order to keep the debug info elements order.  */
13834           while (--i >= 0)
13835             {
13836               struct typedef_field *dest, *src;
13837
13838               dest = &TYPE_TYPEDEF_FIELD (type, i);
13839               src = &fi.typedef_field_list->field;
13840               fi.typedef_field_list = fi.typedef_field_list->next;
13841               *dest = *src;
13842             }
13843         }
13844
13845       do_cleanups (back_to);
13846     }
13847
13848   quirk_gcc_member_function_pointer (type, objfile);
13849
13850   /* NOTE: carlton/2004-03-16: GCC 3.4 (or at least one of its
13851      snapshots) has been known to create a die giving a declaration
13852      for a class that has, as a child, a die giving a definition for a
13853      nested class.  So we have to process our children even if the
13854      current die is a declaration.  Normally, of course, a declaration
13855      won't have any children at all.  */
13856
13857   child_die = die->child;
13858
13859   while (child_die != NULL && child_die->tag)
13860     {
13861       if (child_die->tag == DW_TAG_member
13862           || child_die->tag == DW_TAG_variable
13863           || child_die->tag == DW_TAG_inheritance
13864           || child_die->tag == DW_TAG_template_value_param
13865           || child_die->tag == DW_TAG_template_type_param)
13866         {
13867           /* Do nothing.  */
13868         }
13869       else
13870         process_die (child_die, cu);
13871
13872       child_die = sibling_die (child_die);
13873     }
13874
13875   /* Do not consider external references.  According to the DWARF standard,
13876      these DIEs are identified by the fact that they have no byte_size
13877      attribute, and a declaration attribute.  */
13878   if (dwarf2_attr (die, DW_AT_byte_size, cu) != NULL
13879       || !die_is_declaration (die, cu))
13880     new_symbol (die, type, cu);
13881 }
13882
13883 /* Assuming DIE is an enumeration type, and TYPE is its associated type,
13884    update TYPE using some information only available in DIE's children.  */
13885
13886 static void
13887 update_enumeration_type_from_children (struct die_info *die,
13888                                        struct type *type,
13889                                        struct dwarf2_cu *cu)
13890 {
13891   struct die_info *child_die;
13892   int unsigned_enum = 1;
13893   int flag_enum = 1;
13894   ULONGEST mask = 0;
13895
13896   auto_obstack obstack;
13897
13898   for (child_die = die->child;
13899        child_die != NULL && child_die->tag;
13900        child_die = sibling_die (child_die))
13901     {
13902       struct attribute *attr;
13903       LONGEST value;
13904       const gdb_byte *bytes;
13905       struct dwarf2_locexpr_baton *baton;
13906       const char *name;
13907
13908       if (child_die->tag != DW_TAG_enumerator)
13909         continue;
13910
13911       attr = dwarf2_attr (child_die, DW_AT_const_value, cu);
13912       if (attr == NULL)
13913         continue;
13914
13915       name = dwarf2_name (child_die, cu);
13916       if (name == NULL)
13917         name = "<anonymous enumerator>";
13918
13919       dwarf2_const_value_attr (attr, type, name, &obstack, cu,
13920                                &value, &bytes, &baton);
13921       if (value < 0)
13922         {
13923           unsigned_enum = 0;
13924           flag_enum = 0;
13925         }
13926       else if ((mask & value) != 0)
13927         flag_enum = 0;
13928       else
13929         mask |= value;
13930
13931       /* If we already know that the enum type is neither unsigned, nor
13932          a flag type, no need to look at the rest of the enumerates.  */
13933       if (!unsigned_enum && !flag_enum)
13934         break;
13935     }
13936
13937   if (unsigned_enum)
13938     TYPE_UNSIGNED (type) = 1;
13939   if (flag_enum)
13940     TYPE_FLAG_ENUM (type) = 1;
13941 }
13942
13943 /* Given a DW_AT_enumeration_type die, set its type.  We do not
13944    complete the type's fields yet, or create any symbols.  */
13945
13946 static struct type *
13947 read_enumeration_type (struct die_info *die, struct dwarf2_cu *cu)
13948 {
13949   struct objfile *objfile = cu->objfile;
13950   struct type *type;
13951   struct attribute *attr;
13952   const char *name;
13953
13954   /* If the definition of this type lives in .debug_types, read that type.
13955      Don't follow DW_AT_specification though, that will take us back up
13956      the chain and we want to go down.  */
13957   attr = dwarf2_attr_no_follow (die, DW_AT_signature);
13958   if (attr)
13959     {
13960       type = get_DW_AT_signature_type (die, attr, cu);
13961
13962       /* The type's CU may not be the same as CU.
13963          Ensure TYPE is recorded with CU in die_type_hash.  */
13964       return set_die_type (die, type, cu);
13965     }
13966
13967   type = alloc_type (objfile);
13968
13969   TYPE_CODE (type) = TYPE_CODE_ENUM;
13970   name = dwarf2_full_name (NULL, die, cu);
13971   if (name != NULL)
13972     TYPE_TAG_NAME (type) = name;
13973
13974   attr = dwarf2_attr (die, DW_AT_type, cu);
13975   if (attr != NULL)
13976     {
13977       struct type *underlying_type = die_type (die, cu);
13978
13979       TYPE_TARGET_TYPE (type) = underlying_type;
13980     }
13981
13982   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
13983   if (attr)
13984     {
13985       TYPE_LENGTH (type) = DW_UNSND (attr);
13986     }
13987   else
13988     {
13989       TYPE_LENGTH (type) = 0;
13990     }
13991
13992   /* The enumeration DIE can be incomplete.  In Ada, any type can be
13993      declared as private in the package spec, and then defined only
13994      inside the package body.  Such types are known as Taft Amendment
13995      Types.  When another package uses such a type, an incomplete DIE
13996      may be generated by the compiler.  */
13997   if (die_is_declaration (die, cu))
13998     TYPE_STUB (type) = 1;
13999
14000   /* Finish the creation of this type by using the enum's children.
14001      We must call this even when the underlying type has been provided
14002      so that we can determine if we're looking at a "flag" enum.  */
14003   update_enumeration_type_from_children (die, type, cu);
14004
14005   /* If this type has an underlying type that is not a stub, then we
14006      may use its attributes.  We always use the "unsigned" attribute
14007      in this situation, because ordinarily we guess whether the type
14008      is unsigned -- but the guess can be wrong and the underlying type
14009      can tell us the reality.  However, we defer to a local size
14010      attribute if one exists, because this lets the compiler override
14011      the underlying type if needed.  */
14012   if (TYPE_TARGET_TYPE (type) != NULL && !TYPE_STUB (TYPE_TARGET_TYPE (type)))
14013     {
14014       TYPE_UNSIGNED (type) = TYPE_UNSIGNED (TYPE_TARGET_TYPE (type));
14015       if (TYPE_LENGTH (type) == 0)
14016         TYPE_LENGTH (type) = TYPE_LENGTH (TYPE_TARGET_TYPE (type));
14017     }
14018
14019   TYPE_DECLARED_CLASS (type) = dwarf2_flag_true_p (die, DW_AT_enum_class, cu);
14020
14021   return set_die_type (die, type, cu);
14022 }
14023
14024 /* Given a pointer to a die which begins an enumeration, process all
14025    the dies that define the members of the enumeration, and create the
14026    symbol for the enumeration type.
14027
14028    NOTE: We reverse the order of the element list.  */
14029
14030 static void
14031 process_enumeration_scope (struct die_info *die, struct dwarf2_cu *cu)
14032 {
14033   struct type *this_type;
14034
14035   this_type = get_die_type (die, cu);
14036   if (this_type == NULL)
14037     this_type = read_enumeration_type (die, cu);
14038
14039   if (die->child != NULL)
14040     {
14041       struct die_info *child_die;
14042       struct symbol *sym;
14043       struct field *fields = NULL;
14044       int num_fields = 0;
14045       const char *name;
14046
14047       child_die = die->child;
14048       while (child_die && child_die->tag)
14049         {
14050           if (child_die->tag != DW_TAG_enumerator)
14051             {
14052               process_die (child_die, cu);
14053             }
14054           else
14055             {
14056               name = dwarf2_name (child_die, cu);
14057               if (name)
14058                 {
14059                   sym = new_symbol (child_die, this_type, cu);
14060
14061                   if ((num_fields % DW_FIELD_ALLOC_CHUNK) == 0)
14062                     {
14063                       fields = (struct field *)
14064                         xrealloc (fields,
14065                                   (num_fields + DW_FIELD_ALLOC_CHUNK)
14066                                   * sizeof (struct field));
14067                     }
14068
14069                   FIELD_NAME (fields[num_fields]) = SYMBOL_LINKAGE_NAME (sym);
14070                   FIELD_TYPE (fields[num_fields]) = NULL;
14071                   SET_FIELD_ENUMVAL (fields[num_fields], SYMBOL_VALUE (sym));
14072                   FIELD_BITSIZE (fields[num_fields]) = 0;
14073
14074                   num_fields++;
14075                 }
14076             }
14077
14078           child_die = sibling_die (child_die);
14079         }
14080
14081       if (num_fields)
14082         {
14083           TYPE_NFIELDS (this_type) = num_fields;
14084           TYPE_FIELDS (this_type) = (struct field *)
14085             TYPE_ALLOC (this_type, sizeof (struct field) * num_fields);
14086           memcpy (TYPE_FIELDS (this_type), fields,
14087                   sizeof (struct field) * num_fields);
14088           xfree (fields);
14089         }
14090     }
14091
14092   /* If we are reading an enum from a .debug_types unit, and the enum
14093      is a declaration, and the enum is not the signatured type in the
14094      unit, then we do not want to add a symbol for it.  Adding a
14095      symbol would in some cases obscure the true definition of the
14096      enum, giving users an incomplete type when the definition is
14097      actually available.  Note that we do not want to do this for all
14098      enums which are just declarations, because C++0x allows forward
14099      enum declarations.  */
14100   if (cu->per_cu->is_debug_types
14101       && die_is_declaration (die, cu))
14102     {
14103       struct signatured_type *sig_type;
14104
14105       sig_type = (struct signatured_type *) cu->per_cu;
14106       gdb_assert (to_underlying (sig_type->type_offset_in_section) != 0);
14107       if (sig_type->type_offset_in_section != die->sect_off)
14108         return;
14109     }
14110
14111   new_symbol (die, this_type, cu);
14112 }
14113
14114 /* Extract all information from a DW_TAG_array_type DIE and put it in
14115    the DIE's type field.  For now, this only handles one dimensional
14116    arrays.  */
14117
14118 static struct type *
14119 read_array_type (struct die_info *die, struct dwarf2_cu *cu)
14120 {
14121   struct objfile *objfile = cu->objfile;
14122   struct die_info *child_die;
14123   struct type *type;
14124   struct type *element_type, *range_type, *index_type;
14125   struct type **range_types = NULL;
14126   struct attribute *attr;
14127   int ndim = 0;
14128   struct cleanup *back_to;
14129   const char *name;
14130   unsigned int bit_stride = 0;
14131
14132   element_type = die_type (die, cu);
14133
14134   /* The die_type call above may have already set the type for this DIE.  */
14135   type = get_die_type (die, cu);
14136   if (type)
14137     return type;
14138
14139   attr = dwarf2_attr (die, DW_AT_byte_stride, cu);
14140   if (attr != NULL)
14141     bit_stride = DW_UNSND (attr) * 8;
14142
14143   attr = dwarf2_attr (die, DW_AT_bit_stride, cu);
14144   if (attr != NULL)
14145     bit_stride = DW_UNSND (attr);
14146
14147   /* Irix 6.2 native cc creates array types without children for
14148      arrays with unspecified length.  */
14149   if (die->child == NULL)
14150     {
14151       index_type = objfile_type (objfile)->builtin_int;
14152       range_type = create_static_range_type (NULL, index_type, 0, -1);
14153       type = create_array_type_with_stride (NULL, element_type, range_type,
14154                                             bit_stride);
14155       return set_die_type (die, type, cu);
14156     }
14157
14158   back_to = make_cleanup (null_cleanup, NULL);
14159   child_die = die->child;
14160   while (child_die && child_die->tag)
14161     {
14162       if (child_die->tag == DW_TAG_subrange_type)
14163         {
14164           struct type *child_type = read_type_die (child_die, cu);
14165
14166           if (child_type != NULL)
14167             {
14168               /* The range type was succesfully read.  Save it for the
14169                  array type creation.  */
14170               if ((ndim % DW_FIELD_ALLOC_CHUNK) == 0)
14171                 {
14172                   range_types = (struct type **)
14173                     xrealloc (range_types, (ndim + DW_FIELD_ALLOC_CHUNK)
14174                               * sizeof (struct type *));
14175                   if (ndim == 0)
14176                     make_cleanup (free_current_contents, &range_types);
14177                 }
14178               range_types[ndim++] = child_type;
14179             }
14180         }
14181       child_die = sibling_die (child_die);
14182     }
14183
14184   /* Dwarf2 dimensions are output from left to right, create the
14185      necessary array types in backwards order.  */
14186
14187   type = element_type;
14188
14189   if (read_array_order (die, cu) == DW_ORD_col_major)
14190     {
14191       int i = 0;
14192
14193       while (i < ndim)
14194         type = create_array_type_with_stride (NULL, type, range_types[i++],
14195                                               bit_stride);
14196     }
14197   else
14198     {
14199       while (ndim-- > 0)
14200         type = create_array_type_with_stride (NULL, type, range_types[ndim],
14201                                               bit_stride);
14202     }
14203
14204   /* Understand Dwarf2 support for vector types (like they occur on
14205      the PowerPC w/ AltiVec).  Gcc just adds another attribute to the
14206      array type.  This is not part of the Dwarf2/3 standard yet, but a
14207      custom vendor extension.  The main difference between a regular
14208      array and the vector variant is that vectors are passed by value
14209      to functions.  */
14210   attr = dwarf2_attr (die, DW_AT_GNU_vector, cu);
14211   if (attr)
14212     make_vector_type (type);
14213
14214   /* The DIE may have DW_AT_byte_size set.  For example an OpenCL
14215      implementation may choose to implement triple vectors using this
14216      attribute.  */
14217   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
14218   if (attr)
14219     {
14220       if (DW_UNSND (attr) >= TYPE_LENGTH (type))
14221         TYPE_LENGTH (type) = DW_UNSND (attr);
14222       else
14223         complaint (&symfile_complaints,
14224                    _("DW_AT_byte_size for array type smaller "
14225                      "than the total size of elements"));
14226     }
14227
14228   name = dwarf2_name (die, cu);
14229   if (name)
14230     TYPE_NAME (type) = name;
14231
14232   /* Install the type in the die.  */
14233   set_die_type (die, type, cu);
14234
14235   /* set_die_type should be already done.  */
14236   set_descriptive_type (type, die, cu);
14237
14238   do_cleanups (back_to);
14239
14240   return type;
14241 }
14242
14243 static enum dwarf_array_dim_ordering
14244 read_array_order (struct die_info *die, struct dwarf2_cu *cu)
14245 {
14246   struct attribute *attr;
14247
14248   attr = dwarf2_attr (die, DW_AT_ordering, cu);
14249
14250   if (attr)
14251     return (enum dwarf_array_dim_ordering) DW_SND (attr);
14252
14253   /* GNU F77 is a special case, as at 08/2004 array type info is the
14254      opposite order to the dwarf2 specification, but data is still
14255      laid out as per normal fortran.
14256
14257      FIXME: dsl/2004-8-20: If G77 is ever fixed, this will also need
14258      version checking.  */
14259
14260   if (cu->language == language_fortran
14261       && cu->producer && strstr (cu->producer, "GNU F77"))
14262     {
14263       return DW_ORD_row_major;
14264     }
14265
14266   switch (cu->language_defn->la_array_ordering)
14267     {
14268     case array_column_major:
14269       return DW_ORD_col_major;
14270     case array_row_major:
14271     default:
14272       return DW_ORD_row_major;
14273     };
14274 }
14275
14276 /* Extract all information from a DW_TAG_set_type DIE and put it in
14277    the DIE's type field.  */
14278
14279 static struct type *
14280 read_set_type (struct die_info *die, struct dwarf2_cu *cu)
14281 {
14282   struct type *domain_type, *set_type;
14283   struct attribute *attr;
14284
14285   domain_type = die_type (die, cu);
14286
14287   /* The die_type call above may have already set the type for this DIE.  */
14288   set_type = get_die_type (die, cu);
14289   if (set_type)
14290     return set_type;
14291
14292   set_type = create_set_type (NULL, domain_type);
14293
14294   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
14295   if (attr)
14296     TYPE_LENGTH (set_type) = DW_UNSND (attr);
14297
14298   return set_die_type (die, set_type, cu);
14299 }
14300
14301 /* A helper for read_common_block that creates a locexpr baton.
14302    SYM is the symbol which we are marking as computed.
14303    COMMON_DIE is the DIE for the common block.
14304    COMMON_LOC is the location expression attribute for the common
14305    block itself.
14306    MEMBER_LOC is the location expression attribute for the particular
14307    member of the common block that we are processing.
14308    CU is the CU from which the above come.  */
14309
14310 static void
14311 mark_common_block_symbol_computed (struct symbol *sym,
14312                                    struct die_info *common_die,
14313                                    struct attribute *common_loc,
14314                                    struct attribute *member_loc,
14315                                    struct dwarf2_cu *cu)
14316 {
14317   struct objfile *objfile = dwarf2_per_objfile->objfile;
14318   struct dwarf2_locexpr_baton *baton;
14319   gdb_byte *ptr;
14320   unsigned int cu_off;
14321   enum bfd_endian byte_order = gdbarch_byte_order (get_objfile_arch (objfile));
14322   LONGEST offset = 0;
14323
14324   gdb_assert (common_loc && member_loc);
14325   gdb_assert (attr_form_is_block (common_loc));
14326   gdb_assert (attr_form_is_block (member_loc)
14327               || attr_form_is_constant (member_loc));
14328
14329   baton = XOBNEW (&objfile->objfile_obstack, struct dwarf2_locexpr_baton);
14330   baton->per_cu = cu->per_cu;
14331   gdb_assert (baton->per_cu);
14332
14333   baton->size = 5 /* DW_OP_call4 */ + 1 /* DW_OP_plus */;
14334
14335   if (attr_form_is_constant (member_loc))
14336     {
14337       offset = dwarf2_get_attr_constant_value (member_loc, 0);
14338       baton->size += 1 /* DW_OP_addr */ + cu->header.addr_size;
14339     }
14340   else
14341     baton->size += DW_BLOCK (member_loc)->size;
14342
14343   ptr = (gdb_byte *) obstack_alloc (&objfile->objfile_obstack, baton->size);
14344   baton->data = ptr;
14345
14346   *ptr++ = DW_OP_call4;
14347   cu_off = common_die->sect_off - cu->per_cu->sect_off;
14348   store_unsigned_integer (ptr, 4, byte_order, cu_off);
14349   ptr += 4;
14350
14351   if (attr_form_is_constant (member_loc))
14352     {
14353       *ptr++ = DW_OP_addr;
14354       store_unsigned_integer (ptr, cu->header.addr_size, byte_order, offset);
14355       ptr += cu->header.addr_size;
14356     }
14357   else
14358     {
14359       /* We have to copy the data here, because DW_OP_call4 will only
14360          use a DW_AT_location attribute.  */
14361       memcpy (ptr, DW_BLOCK (member_loc)->data, DW_BLOCK (member_loc)->size);
14362       ptr += DW_BLOCK (member_loc)->size;
14363     }
14364
14365   *ptr++ = DW_OP_plus;
14366   gdb_assert (ptr - baton->data == baton->size);
14367
14368   SYMBOL_LOCATION_BATON (sym) = baton;
14369   SYMBOL_ACLASS_INDEX (sym) = dwarf2_locexpr_index;
14370 }
14371
14372 /* Create appropriate locally-scoped variables for all the
14373    DW_TAG_common_block entries.  Also create a struct common_block
14374    listing all such variables for `info common'.  COMMON_BLOCK_DOMAIN
14375    is used to sepate the common blocks name namespace from regular
14376    variable names.  */
14377
14378 static void
14379 read_common_block (struct die_info *die, struct dwarf2_cu *cu)
14380 {
14381   struct attribute *attr;
14382
14383   attr = dwarf2_attr (die, DW_AT_location, cu);
14384   if (attr)
14385     {
14386       /* Support the .debug_loc offsets.  */
14387       if (attr_form_is_block (attr))
14388         {
14389           /* Ok.  */
14390         }
14391       else if (attr_form_is_section_offset (attr))
14392         {
14393           dwarf2_complex_location_expr_complaint ();
14394           attr = NULL;
14395         }
14396       else
14397         {
14398           dwarf2_invalid_attrib_class_complaint ("DW_AT_location",
14399                                                  "common block member");
14400           attr = NULL;
14401         }
14402     }
14403
14404   if (die->child != NULL)
14405     {
14406       struct objfile *objfile = cu->objfile;
14407       struct die_info *child_die;
14408       size_t n_entries = 0, size;
14409       struct common_block *common_block;
14410       struct symbol *sym;
14411
14412       for (child_die = die->child;
14413            child_die && child_die->tag;
14414            child_die = sibling_die (child_die))
14415         ++n_entries;
14416
14417       size = (sizeof (struct common_block)
14418               + (n_entries - 1) * sizeof (struct symbol *));
14419       common_block
14420         = (struct common_block *) obstack_alloc (&objfile->objfile_obstack,
14421                                                  size);
14422       memset (common_block->contents, 0, n_entries * sizeof (struct symbol *));
14423       common_block->n_entries = 0;
14424
14425       for (child_die = die->child;
14426            child_die && child_die->tag;
14427            child_die = sibling_die (child_die))
14428         {
14429           /* Create the symbol in the DW_TAG_common_block block in the current
14430              symbol scope.  */
14431           sym = new_symbol (child_die, NULL, cu);
14432           if (sym != NULL)
14433             {
14434               struct attribute *member_loc;
14435
14436               common_block->contents[common_block->n_entries++] = sym;
14437
14438               member_loc = dwarf2_attr (child_die, DW_AT_data_member_location,
14439                                         cu);
14440               if (member_loc)
14441                 {
14442                   /* GDB has handled this for a long time, but it is
14443                      not specified by DWARF.  It seems to have been
14444                      emitted by gfortran at least as recently as:
14445                      http://gcc.gnu.org/bugzilla/show_bug.cgi?id=23057.  */
14446                   complaint (&symfile_complaints,
14447                              _("Variable in common block has "
14448                                "DW_AT_data_member_location "
14449                                "- DIE at 0x%x [in module %s]"),
14450                              to_underlying (child_die->sect_off),
14451                              objfile_name (cu->objfile));
14452
14453                   if (attr_form_is_section_offset (member_loc))
14454                     dwarf2_complex_location_expr_complaint ();
14455                   else if (attr_form_is_constant (member_loc)
14456                            || attr_form_is_block (member_loc))
14457                     {
14458                       if (attr)
14459                         mark_common_block_symbol_computed (sym, die, attr,
14460                                                            member_loc, cu);
14461                     }
14462                   else
14463                     dwarf2_complex_location_expr_complaint ();
14464                 }
14465             }
14466         }
14467
14468       sym = new_symbol (die, objfile_type (objfile)->builtin_void, cu);
14469       SYMBOL_VALUE_COMMON_BLOCK (sym) = common_block;
14470     }
14471 }
14472
14473 /* Create a type for a C++ namespace.  */
14474
14475 static struct type *
14476 read_namespace_type (struct die_info *die, struct dwarf2_cu *cu)
14477 {
14478   struct objfile *objfile = cu->objfile;
14479   const char *previous_prefix, *name;
14480   int is_anonymous;
14481   struct type *type;
14482
14483   /* For extensions, reuse the type of the original namespace.  */
14484   if (dwarf2_attr (die, DW_AT_extension, cu) != NULL)
14485     {
14486       struct die_info *ext_die;
14487       struct dwarf2_cu *ext_cu = cu;
14488
14489       ext_die = dwarf2_extension (die, &ext_cu);
14490       type = read_type_die (ext_die, ext_cu);
14491
14492       /* EXT_CU may not be the same as CU.
14493          Ensure TYPE is recorded with CU in die_type_hash.  */
14494       return set_die_type (die, type, cu);
14495     }
14496
14497   name = namespace_name (die, &is_anonymous, cu);
14498
14499   /* Now build the name of the current namespace.  */
14500
14501   previous_prefix = determine_prefix (die, cu);
14502   if (previous_prefix[0] != '\0')
14503     name = typename_concat (&objfile->objfile_obstack,
14504                             previous_prefix, name, 0, cu);
14505
14506   /* Create the type.  */
14507   type = init_type (objfile, TYPE_CODE_NAMESPACE, 0, name);
14508   TYPE_TAG_NAME (type) = TYPE_NAME (type);
14509
14510   return set_die_type (die, type, cu);
14511 }
14512
14513 /* Read a namespace scope.  */
14514
14515 static void
14516 read_namespace (struct die_info *die, struct dwarf2_cu *cu)
14517 {
14518   struct objfile *objfile = cu->objfile;
14519   int is_anonymous;
14520
14521   /* Add a symbol associated to this if we haven't seen the namespace
14522      before.  Also, add a using directive if it's an anonymous
14523      namespace.  */
14524
14525   if (dwarf2_attr (die, DW_AT_extension, cu) == NULL)
14526     {
14527       struct type *type;
14528
14529       type = read_type_die (die, cu);
14530       new_symbol (die, type, cu);
14531
14532       namespace_name (die, &is_anonymous, cu);
14533       if (is_anonymous)
14534         {
14535           const char *previous_prefix = determine_prefix (die, cu);
14536
14537           add_using_directive (using_directives (cu->language),
14538                                previous_prefix, TYPE_NAME (type), NULL,
14539                                NULL, NULL, 0, &objfile->objfile_obstack);
14540         }
14541     }
14542
14543   if (die->child != NULL)
14544     {
14545       struct die_info *child_die = die->child;
14546
14547       while (child_die && child_die->tag)
14548         {
14549           process_die (child_die, cu);
14550           child_die = sibling_die (child_die);
14551         }
14552     }
14553 }
14554
14555 /* Read a Fortran module as type.  This DIE can be only a declaration used for
14556    imported module.  Still we need that type as local Fortran "use ... only"
14557    declaration imports depend on the created type in determine_prefix.  */
14558
14559 static struct type *
14560 read_module_type (struct die_info *die, struct dwarf2_cu *cu)
14561 {
14562   struct objfile *objfile = cu->objfile;
14563   const char *module_name;
14564   struct type *type;
14565
14566   module_name = dwarf2_name (die, cu);
14567   if (!module_name)
14568     complaint (&symfile_complaints,
14569                _("DW_TAG_module has no name, offset 0x%x"),
14570                to_underlying (die->sect_off));
14571   type = init_type (objfile, TYPE_CODE_MODULE, 0, module_name);
14572
14573   /* determine_prefix uses TYPE_TAG_NAME.  */
14574   TYPE_TAG_NAME (type) = TYPE_NAME (type);
14575
14576   return set_die_type (die, type, cu);
14577 }
14578
14579 /* Read a Fortran module.  */
14580
14581 static void
14582 read_module (struct die_info *die, struct dwarf2_cu *cu)
14583 {
14584   struct die_info *child_die = die->child;
14585   struct type *type;
14586
14587   type = read_type_die (die, cu);
14588   new_symbol (die, type, cu);
14589
14590   while (child_die && child_die->tag)
14591     {
14592       process_die (child_die, cu);
14593       child_die = sibling_die (child_die);
14594     }
14595 }
14596
14597 /* Return the name of the namespace represented by DIE.  Set
14598    *IS_ANONYMOUS to tell whether or not the namespace is an anonymous
14599    namespace.  */
14600
14601 static const char *
14602 namespace_name (struct die_info *die, int *is_anonymous, struct dwarf2_cu *cu)
14603 {
14604   struct die_info *current_die;
14605   const char *name = NULL;
14606
14607   /* Loop through the extensions until we find a name.  */
14608
14609   for (current_die = die;
14610        current_die != NULL;
14611        current_die = dwarf2_extension (die, &cu))
14612     {
14613       /* We don't use dwarf2_name here so that we can detect the absence
14614          of a name -> anonymous namespace.  */
14615       name = dwarf2_string_attr (die, DW_AT_name, cu);
14616
14617       if (name != NULL)
14618         break;
14619     }
14620
14621   /* Is it an anonymous namespace?  */
14622
14623   *is_anonymous = (name == NULL);
14624   if (*is_anonymous)
14625     name = CP_ANONYMOUS_NAMESPACE_STR;
14626
14627   return name;
14628 }
14629
14630 /* Extract all information from a DW_TAG_pointer_type DIE and add to
14631    the user defined type vector.  */
14632
14633 static struct type *
14634 read_tag_pointer_type (struct die_info *die, struct dwarf2_cu *cu)
14635 {
14636   struct gdbarch *gdbarch = get_objfile_arch (cu->objfile);
14637   struct comp_unit_head *cu_header = &cu->header;
14638   struct type *type;
14639   struct attribute *attr_byte_size;
14640   struct attribute *attr_address_class;
14641   int byte_size, addr_class;
14642   struct type *target_type;
14643
14644   target_type = die_type (die, cu);
14645
14646   /* The die_type call above may have already set the type for this DIE.  */
14647   type = get_die_type (die, cu);
14648   if (type)
14649     return type;
14650
14651   type = lookup_pointer_type (target_type);
14652
14653   attr_byte_size = dwarf2_attr (die, DW_AT_byte_size, cu);
14654   if (attr_byte_size)
14655     byte_size = DW_UNSND (attr_byte_size);
14656   else
14657     byte_size = cu_header->addr_size;
14658
14659   attr_address_class = dwarf2_attr (die, DW_AT_address_class, cu);
14660   if (attr_address_class)
14661     addr_class = DW_UNSND (attr_address_class);
14662   else
14663     addr_class = DW_ADDR_none;
14664
14665   /* If the pointer size or address class is different than the
14666      default, create a type variant marked as such and set the
14667      length accordingly.  */
14668   if (TYPE_LENGTH (type) != byte_size || addr_class != DW_ADDR_none)
14669     {
14670       if (gdbarch_address_class_type_flags_p (gdbarch))
14671         {
14672           int type_flags;
14673
14674           type_flags = gdbarch_address_class_type_flags
14675                          (gdbarch, byte_size, addr_class);
14676           gdb_assert ((type_flags & ~TYPE_INSTANCE_FLAG_ADDRESS_CLASS_ALL)
14677                       == 0);
14678           type = make_type_with_address_space (type, type_flags);
14679         }
14680       else if (TYPE_LENGTH (type) != byte_size)
14681         {
14682           complaint (&symfile_complaints,
14683                      _("invalid pointer size %d"), byte_size);
14684         }
14685       else
14686         {
14687           /* Should we also complain about unhandled address classes?  */
14688         }
14689     }
14690
14691   TYPE_LENGTH (type) = byte_size;
14692   return set_die_type (die, type, cu);
14693 }
14694
14695 /* Extract all information from a DW_TAG_ptr_to_member_type DIE and add to
14696    the user defined type vector.  */
14697
14698 static struct type *
14699 read_tag_ptr_to_member_type (struct die_info *die, struct dwarf2_cu *cu)
14700 {
14701   struct type *type;
14702   struct type *to_type;
14703   struct type *domain;
14704
14705   to_type = die_type (die, cu);
14706   domain = die_containing_type (die, cu);
14707
14708   /* The calls above may have already set the type for this DIE.  */
14709   type = get_die_type (die, cu);
14710   if (type)
14711     return type;
14712
14713   if (TYPE_CODE (check_typedef (to_type)) == TYPE_CODE_METHOD)
14714     type = lookup_methodptr_type (to_type);
14715   else if (TYPE_CODE (check_typedef (to_type)) == TYPE_CODE_FUNC)
14716     {
14717       struct type *new_type = alloc_type (cu->objfile);
14718
14719       smash_to_method_type (new_type, domain, TYPE_TARGET_TYPE (to_type),
14720                             TYPE_FIELDS (to_type), TYPE_NFIELDS (to_type),
14721                             TYPE_VARARGS (to_type));
14722       type = lookup_methodptr_type (new_type);
14723     }
14724   else
14725     type = lookup_memberptr_type (to_type, domain);
14726
14727   return set_die_type (die, type, cu);
14728 }
14729
14730 /* Extract all information from a DW_TAG_{rvalue_,}reference_type DIE and add to
14731    the user defined type vector.  */
14732
14733 static struct type *
14734 read_tag_reference_type (struct die_info *die, struct dwarf2_cu *cu,
14735                           enum type_code refcode)
14736 {
14737   struct comp_unit_head *cu_header = &cu->header;
14738   struct type *type, *target_type;
14739   struct attribute *attr;
14740
14741   gdb_assert (refcode == TYPE_CODE_REF || refcode == TYPE_CODE_RVALUE_REF);
14742
14743   target_type = die_type (die, cu);
14744
14745   /* The die_type call above may have already set the type for this DIE.  */
14746   type = get_die_type (die, cu);
14747   if (type)
14748     return type;
14749
14750   type = lookup_reference_type (target_type, refcode);
14751   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
14752   if (attr)
14753     {
14754       TYPE_LENGTH (type) = DW_UNSND (attr);
14755     }
14756   else
14757     {
14758       TYPE_LENGTH (type) = cu_header->addr_size;
14759     }
14760   return set_die_type (die, type, cu);
14761 }
14762
14763 /* Add the given cv-qualifiers to the element type of the array.  GCC
14764    outputs DWARF type qualifiers that apply to an array, not the
14765    element type.  But GDB relies on the array element type to carry
14766    the cv-qualifiers.  This mimics section 6.7.3 of the C99
14767    specification.  */
14768
14769 static struct type *
14770 add_array_cv_type (struct die_info *die, struct dwarf2_cu *cu,
14771                    struct type *base_type, int cnst, int voltl)
14772 {
14773   struct type *el_type, *inner_array;
14774
14775   base_type = copy_type (base_type);
14776   inner_array = base_type;
14777
14778   while (TYPE_CODE (TYPE_TARGET_TYPE (inner_array)) == TYPE_CODE_ARRAY)
14779     {
14780       TYPE_TARGET_TYPE (inner_array) =
14781         copy_type (TYPE_TARGET_TYPE (inner_array));
14782       inner_array = TYPE_TARGET_TYPE (inner_array);
14783     }
14784
14785   el_type = TYPE_TARGET_TYPE (inner_array);
14786   cnst |= TYPE_CONST (el_type);
14787   voltl |= TYPE_VOLATILE (el_type);
14788   TYPE_TARGET_TYPE (inner_array) = make_cv_type (cnst, voltl, el_type, NULL);
14789
14790   return set_die_type (die, base_type, cu);
14791 }
14792
14793 static struct type *
14794 read_tag_const_type (struct die_info *die, struct dwarf2_cu *cu)
14795 {
14796   struct type *base_type, *cv_type;
14797
14798   base_type = die_type (die, cu);
14799
14800   /* The die_type call above may have already set the type for this DIE.  */
14801   cv_type = get_die_type (die, cu);
14802   if (cv_type)
14803     return cv_type;
14804
14805   /* In case the const qualifier is applied to an array type, the element type
14806      is so qualified, not the array type (section 6.7.3 of C99).  */
14807   if (TYPE_CODE (base_type) == TYPE_CODE_ARRAY)
14808     return add_array_cv_type (die, cu, base_type, 1, 0);
14809
14810   cv_type = make_cv_type (1, TYPE_VOLATILE (base_type), base_type, 0);
14811   return set_die_type (die, cv_type, cu);
14812 }
14813
14814 static struct type *
14815 read_tag_volatile_type (struct die_info *die, struct dwarf2_cu *cu)
14816 {
14817   struct type *base_type, *cv_type;
14818
14819   base_type = die_type (die, cu);
14820
14821   /* The die_type call above may have already set the type for this DIE.  */
14822   cv_type = get_die_type (die, cu);
14823   if (cv_type)
14824     return cv_type;
14825
14826   /* In case the volatile qualifier is applied to an array type, the
14827      element type is so qualified, not the array type (section 6.7.3
14828      of C99).  */
14829   if (TYPE_CODE (base_type) == TYPE_CODE_ARRAY)
14830     return add_array_cv_type (die, cu, base_type, 0, 1);
14831
14832   cv_type = make_cv_type (TYPE_CONST (base_type), 1, base_type, 0);
14833   return set_die_type (die, cv_type, cu);
14834 }
14835
14836 /* Handle DW_TAG_restrict_type.  */
14837
14838 static struct type *
14839 read_tag_restrict_type (struct die_info *die, struct dwarf2_cu *cu)
14840 {
14841   struct type *base_type, *cv_type;
14842
14843   base_type = die_type (die, cu);
14844
14845   /* The die_type call above may have already set the type for this DIE.  */
14846   cv_type = get_die_type (die, cu);
14847   if (cv_type)
14848     return cv_type;
14849
14850   cv_type = make_restrict_type (base_type);
14851   return set_die_type (die, cv_type, cu);
14852 }
14853
14854 /* Handle DW_TAG_atomic_type.  */
14855
14856 static struct type *
14857 read_tag_atomic_type (struct die_info *die, struct dwarf2_cu *cu)
14858 {
14859   struct type *base_type, *cv_type;
14860
14861   base_type = die_type (die, cu);
14862
14863   /* The die_type call above may have already set the type for this DIE.  */
14864   cv_type = get_die_type (die, cu);
14865   if (cv_type)
14866     return cv_type;
14867
14868   cv_type = make_atomic_type (base_type);
14869   return set_die_type (die, cv_type, cu);
14870 }
14871
14872 /* Extract all information from a DW_TAG_string_type DIE and add to
14873    the user defined type vector.  It isn't really a user defined type,
14874    but it behaves like one, with other DIE's using an AT_user_def_type
14875    attribute to reference it.  */
14876
14877 static struct type *
14878 read_tag_string_type (struct die_info *die, struct dwarf2_cu *cu)
14879 {
14880   struct objfile *objfile = cu->objfile;
14881   struct gdbarch *gdbarch = get_objfile_arch (objfile);
14882   struct type *type, *range_type, *index_type, *char_type;
14883   struct attribute *attr;
14884   unsigned int length;
14885
14886   attr = dwarf2_attr (die, DW_AT_string_length, cu);
14887   if (attr)
14888     {
14889       length = DW_UNSND (attr);
14890     }
14891   else
14892     {
14893       /* Check for the DW_AT_byte_size attribute.  */
14894       attr = dwarf2_attr (die, DW_AT_byte_size, cu);
14895       if (attr)
14896         {
14897           length = DW_UNSND (attr);
14898         }
14899       else
14900         {
14901           length = 1;
14902         }
14903     }
14904
14905   index_type = objfile_type (objfile)->builtin_int;
14906   range_type = create_static_range_type (NULL, index_type, 1, length);
14907   char_type = language_string_char_type (cu->language_defn, gdbarch);
14908   type = create_string_type (NULL, char_type, range_type);
14909
14910   return set_die_type (die, type, cu);
14911 }
14912
14913 /* Assuming that DIE corresponds to a function, returns nonzero
14914    if the function is prototyped.  */
14915
14916 static int
14917 prototyped_function_p (struct die_info *die, struct dwarf2_cu *cu)
14918 {
14919   struct attribute *attr;
14920
14921   attr = dwarf2_attr (die, DW_AT_prototyped, cu);
14922   if (attr && (DW_UNSND (attr) != 0))
14923     return 1;
14924
14925   /* The DWARF standard implies that the DW_AT_prototyped attribute
14926      is only meaninful for C, but the concept also extends to other
14927      languages that allow unprototyped functions (Eg: Objective C).
14928      For all other languages, assume that functions are always
14929      prototyped.  */
14930   if (cu->language != language_c
14931       && cu->language != language_objc
14932       && cu->language != language_opencl)
14933     return 1;
14934
14935   /* RealView does not emit DW_AT_prototyped.  We can not distinguish
14936      prototyped and unprototyped functions; default to prototyped,
14937      since that is more common in modern code (and RealView warns
14938      about unprototyped functions).  */
14939   if (producer_is_realview (cu->producer))
14940     return 1;
14941
14942   return 0;
14943 }
14944
14945 /* Handle DIES due to C code like:
14946
14947    struct foo
14948    {
14949    int (*funcp)(int a, long l);
14950    int b;
14951    };
14952
14953    ('funcp' generates a DW_TAG_subroutine_type DIE).  */
14954
14955 static struct type *
14956 read_subroutine_type (struct die_info *die, struct dwarf2_cu *cu)
14957 {
14958   struct objfile *objfile = cu->objfile;
14959   struct type *type;            /* Type that this function returns.  */
14960   struct type *ftype;           /* Function that returns above type.  */
14961   struct attribute *attr;
14962
14963   type = die_type (die, cu);
14964
14965   /* The die_type call above may have already set the type for this DIE.  */
14966   ftype = get_die_type (die, cu);
14967   if (ftype)
14968     return ftype;
14969
14970   ftype = lookup_function_type (type);
14971
14972   if (prototyped_function_p (die, cu))
14973     TYPE_PROTOTYPED (ftype) = 1;
14974
14975   /* Store the calling convention in the type if it's available in
14976      the subroutine die.  Otherwise set the calling convention to
14977      the default value DW_CC_normal.  */
14978   attr = dwarf2_attr (die, DW_AT_calling_convention, cu);
14979   if (attr)
14980     TYPE_CALLING_CONVENTION (ftype) = DW_UNSND (attr);
14981   else if (cu->producer && strstr (cu->producer, "IBM XL C for OpenCL"))
14982     TYPE_CALLING_CONVENTION (ftype) = DW_CC_GDB_IBM_OpenCL;
14983   else
14984     TYPE_CALLING_CONVENTION (ftype) = DW_CC_normal;
14985
14986   /* Record whether the function returns normally to its caller or not
14987      if the DWARF producer set that information.  */
14988   attr = dwarf2_attr (die, DW_AT_noreturn, cu);
14989   if (attr && (DW_UNSND (attr) != 0))
14990     TYPE_NO_RETURN (ftype) = 1;
14991
14992   /* We need to add the subroutine type to the die immediately so
14993      we don't infinitely recurse when dealing with parameters
14994      declared as the same subroutine type.  */
14995   set_die_type (die, ftype, cu);
14996
14997   if (die->child != NULL)
14998     {
14999       struct type *void_type = objfile_type (objfile)->builtin_void;
15000       struct die_info *child_die;
15001       int nparams, iparams;
15002
15003       /* Count the number of parameters.
15004          FIXME: GDB currently ignores vararg functions, but knows about
15005          vararg member functions.  */
15006       nparams = 0;
15007       child_die = die->child;
15008       while (child_die && child_die->tag)
15009         {
15010           if (child_die->tag == DW_TAG_formal_parameter)
15011             nparams++;
15012           else if (child_die->tag == DW_TAG_unspecified_parameters)
15013             TYPE_VARARGS (ftype) = 1;
15014           child_die = sibling_die (child_die);
15015         }
15016
15017       /* Allocate storage for parameters and fill them in.  */
15018       TYPE_NFIELDS (ftype) = nparams;
15019       TYPE_FIELDS (ftype) = (struct field *)
15020         TYPE_ZALLOC (ftype, nparams * sizeof (struct field));
15021
15022       /* TYPE_FIELD_TYPE must never be NULL.  Pre-fill the array to ensure it
15023          even if we error out during the parameters reading below.  */
15024       for (iparams = 0; iparams < nparams; iparams++)
15025         TYPE_FIELD_TYPE (ftype, iparams) = void_type;
15026
15027       iparams = 0;
15028       child_die = die->child;
15029       while (child_die && child_die->tag)
15030         {
15031           if (child_die->tag == DW_TAG_formal_parameter)
15032             {
15033               struct type *arg_type;
15034
15035               /* DWARF version 2 has no clean way to discern C++
15036                  static and non-static member functions.  G++ helps
15037                  GDB by marking the first parameter for non-static
15038                  member functions (which is the this pointer) as
15039                  artificial.  We pass this information to
15040                  dwarf2_add_member_fn via TYPE_FIELD_ARTIFICIAL.
15041
15042                  DWARF version 3 added DW_AT_object_pointer, which GCC
15043                  4.5 does not yet generate.  */
15044               attr = dwarf2_attr (child_die, DW_AT_artificial, cu);
15045               if (attr)
15046                 TYPE_FIELD_ARTIFICIAL (ftype, iparams) = DW_UNSND (attr);
15047               else
15048                 TYPE_FIELD_ARTIFICIAL (ftype, iparams) = 0;
15049               arg_type = die_type (child_die, cu);
15050
15051               /* RealView does not mark THIS as const, which the testsuite
15052                  expects.  GCC marks THIS as const in method definitions,
15053                  but not in the class specifications (GCC PR 43053).  */
15054               if (cu->language == language_cplus && !TYPE_CONST (arg_type)
15055                   && TYPE_FIELD_ARTIFICIAL (ftype, iparams))
15056                 {
15057                   int is_this = 0;
15058                   struct dwarf2_cu *arg_cu = cu;
15059                   const char *name = dwarf2_name (child_die, cu);
15060
15061                   attr = dwarf2_attr (die, DW_AT_object_pointer, cu);
15062                   if (attr)
15063                     {
15064                       /* If the compiler emits this, use it.  */
15065                       if (follow_die_ref (die, attr, &arg_cu) == child_die)
15066                         is_this = 1;
15067                     }
15068                   else if (name && strcmp (name, "this") == 0)
15069                     /* Function definitions will have the argument names.  */
15070                     is_this = 1;
15071                   else if (name == NULL && iparams == 0)
15072                     /* Declarations may not have the names, so like
15073                        elsewhere in GDB, assume an artificial first
15074                        argument is "this".  */
15075                     is_this = 1;
15076
15077                   if (is_this)
15078                     arg_type = make_cv_type (1, TYPE_VOLATILE (arg_type),
15079                                              arg_type, 0);
15080                 }
15081
15082               TYPE_FIELD_TYPE (ftype, iparams) = arg_type;
15083               iparams++;
15084             }
15085           child_die = sibling_die (child_die);
15086         }
15087     }
15088
15089   return ftype;
15090 }
15091
15092 static struct type *
15093 read_typedef (struct die_info *die, struct dwarf2_cu *cu)
15094 {
15095   struct objfile *objfile = cu->objfile;
15096   const char *name = NULL;
15097   struct type *this_type, *target_type;
15098
15099   name = dwarf2_full_name (NULL, die, cu);
15100   this_type = init_type (objfile, TYPE_CODE_TYPEDEF, 0, name);
15101   TYPE_TARGET_STUB (this_type) = 1;
15102   set_die_type (die, this_type, cu);
15103   target_type = die_type (die, cu);
15104   if (target_type != this_type)
15105     TYPE_TARGET_TYPE (this_type) = target_type;
15106   else
15107     {
15108       /* Self-referential typedefs are, it seems, not allowed by the DWARF
15109          spec and cause infinite loops in GDB.  */
15110       complaint (&symfile_complaints,
15111                  _("Self-referential DW_TAG_typedef "
15112                    "- DIE at 0x%x [in module %s]"),
15113                  to_underlying (die->sect_off), objfile_name (objfile));
15114       TYPE_TARGET_TYPE (this_type) = NULL;
15115     }
15116   return this_type;
15117 }
15118
15119 /* Allocate a floating-point type of size BITS and name NAME.  Pass NAME_HINT
15120    (which may be different from NAME) to the architecture back-end to allow
15121    it to guess the correct format if necessary.  */
15122
15123 static struct type *
15124 dwarf2_init_float_type (struct objfile *objfile, int bits, const char *name,
15125                         const char *name_hint)
15126 {
15127   struct gdbarch *gdbarch = get_objfile_arch (objfile);
15128   const struct floatformat **format;
15129   struct type *type;
15130
15131   format = gdbarch_floatformat_for_type (gdbarch, name_hint, bits);
15132   if (format)
15133     type = init_float_type (objfile, bits, name, format);
15134   else
15135     type = init_type (objfile, TYPE_CODE_ERROR, bits / TARGET_CHAR_BIT, name);
15136
15137   return type;
15138 }
15139
15140 /* Find a representation of a given base type and install
15141    it in the TYPE field of the die.  */
15142
15143 static struct type *
15144 read_base_type (struct die_info *die, struct dwarf2_cu *cu)
15145 {
15146   struct objfile *objfile = cu->objfile;
15147   struct type *type;
15148   struct attribute *attr;
15149   int encoding = 0, bits = 0;
15150   const char *name;
15151
15152   attr = dwarf2_attr (die, DW_AT_encoding, cu);
15153   if (attr)
15154     {
15155       encoding = DW_UNSND (attr);
15156     }
15157   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
15158   if (attr)
15159     {
15160       bits = DW_UNSND (attr) * TARGET_CHAR_BIT;
15161     }
15162   name = dwarf2_name (die, cu);
15163   if (!name)
15164     {
15165       complaint (&symfile_complaints,
15166                  _("DW_AT_name missing from DW_TAG_base_type"));
15167     }
15168
15169   switch (encoding)
15170     {
15171       case DW_ATE_address:
15172         /* Turn DW_ATE_address into a void * pointer.  */
15173         type = init_type (objfile, TYPE_CODE_VOID, 1, NULL);
15174         type = init_pointer_type (objfile, bits, name, type);
15175         break;
15176       case DW_ATE_boolean:
15177         type = init_boolean_type (objfile, bits, 1, name);
15178         break;
15179       case DW_ATE_complex_float:
15180         type = dwarf2_init_float_type (objfile, bits / 2, NULL, name);
15181         type = init_complex_type (objfile, name, type);
15182         break;
15183       case DW_ATE_decimal_float:
15184         type = init_decfloat_type (objfile, bits, name);
15185         break;
15186       case DW_ATE_float:
15187         type = dwarf2_init_float_type (objfile, bits, name, name);
15188         break;
15189       case DW_ATE_signed:
15190         type = init_integer_type (objfile, bits, 0, name);
15191         break;
15192       case DW_ATE_unsigned:
15193         if (cu->language == language_fortran
15194             && name
15195             && startswith (name, "character("))
15196           type = init_character_type (objfile, bits, 1, name);
15197         else
15198           type = init_integer_type (objfile, bits, 1, name);
15199         break;
15200       case DW_ATE_signed_char:
15201         if (cu->language == language_ada || cu->language == language_m2
15202             || cu->language == language_pascal
15203             || cu->language == language_fortran)
15204           type = init_character_type (objfile, bits, 0, name);
15205         else
15206           type = init_integer_type (objfile, bits, 0, name);
15207         break;
15208       case DW_ATE_unsigned_char:
15209         if (cu->language == language_ada || cu->language == language_m2
15210             || cu->language == language_pascal
15211             || cu->language == language_fortran
15212             || cu->language == language_rust)
15213           type = init_character_type (objfile, bits, 1, name);
15214         else
15215           type = init_integer_type (objfile, bits, 1, name);
15216         break;
15217       case DW_ATE_UTF:
15218         {
15219           gdbarch *arch = get_objfile_arch (objfile);
15220
15221           if (bits == 16)
15222             type = builtin_type (arch)->builtin_char16;
15223           else if (bits == 32)
15224             type = builtin_type (arch)->builtin_char32;
15225           else
15226             {
15227               complaint (&symfile_complaints,
15228                          _("unsupported DW_ATE_UTF bit size: '%d'"),
15229                          bits);
15230               type = init_integer_type (objfile, bits, 1, name);
15231             }
15232           return set_die_type (die, type, cu);
15233         }
15234         break;
15235
15236       default:
15237         complaint (&symfile_complaints, _("unsupported DW_AT_encoding: '%s'"),
15238                    dwarf_type_encoding_name (encoding));
15239         type = init_type (objfile, TYPE_CODE_ERROR,
15240                           bits / TARGET_CHAR_BIT, name);
15241         break;
15242     }
15243
15244   if (name && strcmp (name, "char") == 0)
15245     TYPE_NOSIGN (type) = 1;
15246
15247   return set_die_type (die, type, cu);
15248 }
15249
15250 /* Parse dwarf attribute if it's a block, reference or constant and put the
15251    resulting value of the attribute into struct bound_prop.
15252    Returns 1 if ATTR could be resolved into PROP, 0 otherwise.  */
15253
15254 static int
15255 attr_to_dynamic_prop (const struct attribute *attr, struct die_info *die,
15256                       struct dwarf2_cu *cu, struct dynamic_prop *prop)
15257 {
15258   struct dwarf2_property_baton *baton;
15259   struct obstack *obstack = &cu->objfile->objfile_obstack;
15260
15261   if (attr == NULL || prop == NULL)
15262     return 0;
15263
15264   if (attr_form_is_block (attr))
15265     {
15266       baton = XOBNEW (obstack, struct dwarf2_property_baton);
15267       baton->referenced_type = NULL;
15268       baton->locexpr.per_cu = cu->per_cu;
15269       baton->locexpr.size = DW_BLOCK (attr)->size;
15270       baton->locexpr.data = DW_BLOCK (attr)->data;
15271       prop->data.baton = baton;
15272       prop->kind = PROP_LOCEXPR;
15273       gdb_assert (prop->data.baton != NULL);
15274     }
15275   else if (attr_form_is_ref (attr))
15276     {
15277       struct dwarf2_cu *target_cu = cu;
15278       struct die_info *target_die;
15279       struct attribute *target_attr;
15280
15281       target_die = follow_die_ref (die, attr, &target_cu);
15282       target_attr = dwarf2_attr (target_die, DW_AT_location, target_cu);
15283       if (target_attr == NULL)
15284         target_attr = dwarf2_attr (target_die, DW_AT_data_member_location,
15285                                    target_cu);
15286       if (target_attr == NULL)
15287         return 0;
15288
15289       switch (target_attr->name)
15290         {
15291           case DW_AT_location:
15292             if (attr_form_is_section_offset (target_attr))
15293               {
15294                 baton = XOBNEW (obstack, struct dwarf2_property_baton);
15295                 baton->referenced_type = die_type (target_die, target_cu);
15296                 fill_in_loclist_baton (cu, &baton->loclist, target_attr);
15297                 prop->data.baton = baton;
15298                 prop->kind = PROP_LOCLIST;
15299                 gdb_assert (prop->data.baton != NULL);
15300               }
15301             else if (attr_form_is_block (target_attr))
15302               {
15303                 baton = XOBNEW (obstack, struct dwarf2_property_baton);
15304                 baton->referenced_type = die_type (target_die, target_cu);
15305                 baton->locexpr.per_cu = cu->per_cu;
15306                 baton->locexpr.size = DW_BLOCK (target_attr)->size;
15307                 baton->locexpr.data = DW_BLOCK (target_attr)->data;
15308                 prop->data.baton = baton;
15309                 prop->kind = PROP_LOCEXPR;
15310                 gdb_assert (prop->data.baton != NULL);
15311               }
15312             else
15313               {
15314                 dwarf2_invalid_attrib_class_complaint ("DW_AT_location",
15315                                                        "dynamic property");
15316                 return 0;
15317               }
15318             break;
15319           case DW_AT_data_member_location:
15320             {
15321               LONGEST offset;
15322
15323               if (!handle_data_member_location (target_die, target_cu,
15324                                                 &offset))
15325                 return 0;
15326
15327               baton = XOBNEW (obstack, struct dwarf2_property_baton);
15328               baton->referenced_type = read_type_die (target_die->parent,
15329                                                       target_cu);
15330               baton->offset_info.offset = offset;
15331               baton->offset_info.type = die_type (target_die, target_cu);
15332               prop->data.baton = baton;
15333               prop->kind = PROP_ADDR_OFFSET;
15334               break;
15335             }
15336         }
15337     }
15338   else if (attr_form_is_constant (attr))
15339     {
15340       prop->data.const_val = dwarf2_get_attr_constant_value (attr, 0);
15341       prop->kind = PROP_CONST;
15342     }
15343   else
15344     {
15345       dwarf2_invalid_attrib_class_complaint (dwarf_form_name (attr->form),
15346                                              dwarf2_name (die, cu));
15347       return 0;
15348     }
15349
15350   return 1;
15351 }
15352
15353 /* Read the given DW_AT_subrange DIE.  */
15354
15355 static struct type *
15356 read_subrange_type (struct die_info *die, struct dwarf2_cu *cu)
15357 {
15358   struct type *base_type, *orig_base_type;
15359   struct type *range_type;
15360   struct attribute *attr;
15361   struct dynamic_prop low, high;
15362   int low_default_is_valid;
15363   int high_bound_is_count = 0;
15364   const char *name;
15365   LONGEST negative_mask;
15366
15367   orig_base_type = die_type (die, cu);
15368   /* If ORIG_BASE_TYPE is a typedef, it will not be TYPE_UNSIGNED,
15369      whereas the real type might be.  So, we use ORIG_BASE_TYPE when
15370      creating the range type, but we use the result of check_typedef
15371      when examining properties of the type.  */
15372   base_type = check_typedef (orig_base_type);
15373
15374   /* The die_type call above may have already set the type for this DIE.  */
15375   range_type = get_die_type (die, cu);
15376   if (range_type)
15377     return range_type;
15378
15379   low.kind = PROP_CONST;
15380   high.kind = PROP_CONST;
15381   high.data.const_val = 0;
15382
15383   /* Set LOW_DEFAULT_IS_VALID if current language and DWARF version allow
15384      omitting DW_AT_lower_bound.  */
15385   switch (cu->language)
15386     {
15387     case language_c:
15388     case language_cplus:
15389       low.data.const_val = 0;
15390       low_default_is_valid = 1;
15391       break;
15392     case language_fortran:
15393       low.data.const_val = 1;
15394       low_default_is_valid = 1;
15395       break;
15396     case language_d:
15397     case language_objc:
15398     case language_rust:
15399       low.data.const_val = 0;
15400       low_default_is_valid = (cu->header.version >= 4);
15401       break;
15402     case language_ada:
15403     case language_m2:
15404     case language_pascal:
15405       low.data.const_val = 1;
15406       low_default_is_valid = (cu->header.version >= 4);
15407       break;
15408     default:
15409       low.data.const_val = 0;
15410       low_default_is_valid = 0;
15411       break;
15412     }
15413
15414   attr = dwarf2_attr (die, DW_AT_lower_bound, cu);
15415   if (attr)
15416     attr_to_dynamic_prop (attr, die, cu, &low);
15417   else if (!low_default_is_valid)
15418     complaint (&symfile_complaints, _("Missing DW_AT_lower_bound "
15419                                       "- DIE at 0x%x [in module %s]"),
15420                to_underlying (die->sect_off), objfile_name (cu->objfile));
15421
15422   attr = dwarf2_attr (die, DW_AT_upper_bound, cu);
15423   if (!attr_to_dynamic_prop (attr, die, cu, &high))
15424     {
15425       attr = dwarf2_attr (die, DW_AT_count, cu);
15426       if (attr_to_dynamic_prop (attr, die, cu, &high))
15427         {
15428           /* If bounds are constant do the final calculation here.  */
15429           if (low.kind == PROP_CONST && high.kind == PROP_CONST)
15430             high.data.const_val = low.data.const_val + high.data.const_val - 1;
15431           else
15432             high_bound_is_count = 1;
15433         }
15434     }
15435
15436   /* Dwarf-2 specifications explicitly allows to create subrange types
15437      without specifying a base type.
15438      In that case, the base type must be set to the type of
15439      the lower bound, upper bound or count, in that order, if any of these
15440      three attributes references an object that has a type.
15441      If no base type is found, the Dwarf-2 specifications say that
15442      a signed integer type of size equal to the size of an address should
15443      be used.
15444      For the following C code: `extern char gdb_int [];'
15445      GCC produces an empty range DIE.
15446      FIXME: muller/2010-05-28: Possible references to object for low bound,
15447      high bound or count are not yet handled by this code.  */
15448   if (TYPE_CODE (base_type) == TYPE_CODE_VOID)
15449     {
15450       struct objfile *objfile = cu->objfile;
15451       struct gdbarch *gdbarch = get_objfile_arch (objfile);
15452       int addr_size = gdbarch_addr_bit (gdbarch) /8;
15453       struct type *int_type = objfile_type (objfile)->builtin_int;
15454
15455       /* Test "int", "long int", and "long long int" objfile types,
15456          and select the first one having a size above or equal to the
15457          architecture address size.  */
15458       if (int_type && TYPE_LENGTH (int_type) >= addr_size)
15459         base_type = int_type;
15460       else
15461         {
15462           int_type = objfile_type (objfile)->builtin_long;
15463           if (int_type && TYPE_LENGTH (int_type) >= addr_size)
15464             base_type = int_type;
15465           else
15466             {
15467               int_type = objfile_type (objfile)->builtin_long_long;
15468               if (int_type && TYPE_LENGTH (int_type) >= addr_size)
15469                 base_type = int_type;
15470             }
15471         }
15472     }
15473
15474   /* Normally, the DWARF producers are expected to use a signed
15475      constant form (Eg. DW_FORM_sdata) to express negative bounds.
15476      But this is unfortunately not always the case, as witnessed
15477      with GCC, for instance, where the ambiguous DW_FORM_dataN form
15478      is used instead.  To work around that ambiguity, we treat
15479      the bounds as signed, and thus sign-extend their values, when
15480      the base type is signed.  */
15481   negative_mask =
15482     -((LONGEST) 1 << (TYPE_LENGTH (base_type) * TARGET_CHAR_BIT - 1));
15483   if (low.kind == PROP_CONST
15484       && !TYPE_UNSIGNED (base_type) && (low.data.const_val & negative_mask))
15485     low.data.const_val |= negative_mask;
15486   if (high.kind == PROP_CONST
15487       && !TYPE_UNSIGNED (base_type) && (high.data.const_val & negative_mask))
15488     high.data.const_val |= negative_mask;
15489
15490   range_type = create_range_type (NULL, orig_base_type, &low, &high);
15491
15492   if (high_bound_is_count)
15493     TYPE_RANGE_DATA (range_type)->flag_upper_bound_is_count = 1;
15494
15495   /* Ada expects an empty array on no boundary attributes.  */
15496   if (attr == NULL && cu->language != language_ada)
15497     TYPE_HIGH_BOUND_KIND (range_type) = PROP_UNDEFINED;
15498
15499   name = dwarf2_name (die, cu);
15500   if (name)
15501     TYPE_NAME (range_type) = name;
15502
15503   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
15504   if (attr)
15505     TYPE_LENGTH (range_type) = DW_UNSND (attr);
15506
15507   set_die_type (die, range_type, cu);
15508
15509   /* set_die_type should be already done.  */
15510   set_descriptive_type (range_type, die, cu);
15511
15512   return range_type;
15513 }
15514
15515 static struct type *
15516 read_unspecified_type (struct die_info *die, struct dwarf2_cu *cu)
15517 {
15518   struct type *type;
15519
15520   /* For now, we only support the C meaning of an unspecified type: void.  */
15521
15522   type = init_type (cu->objfile, TYPE_CODE_VOID, 0, NULL);
15523   TYPE_NAME (type) = dwarf2_name (die, cu);
15524
15525   return set_die_type (die, type, cu);
15526 }
15527
15528 /* Read a single die and all its descendents.  Set the die's sibling
15529    field to NULL; set other fields in the die correctly, and set all
15530    of the descendents' fields correctly.  Set *NEW_INFO_PTR to the
15531    location of the info_ptr after reading all of those dies.  PARENT
15532    is the parent of the die in question.  */
15533
15534 static struct die_info *
15535 read_die_and_children (const struct die_reader_specs *reader,
15536                        const gdb_byte *info_ptr,
15537                        const gdb_byte **new_info_ptr,
15538                        struct die_info *parent)
15539 {
15540   struct die_info *die;
15541   const gdb_byte *cur_ptr;
15542   int has_children;
15543
15544   cur_ptr = read_full_die_1 (reader, &die, info_ptr, &has_children, 0);
15545   if (die == NULL)
15546     {
15547       *new_info_ptr = cur_ptr;
15548       return NULL;
15549     }
15550   store_in_ref_table (die, reader->cu);
15551
15552   if (has_children)
15553     die->child = read_die_and_siblings_1 (reader, cur_ptr, new_info_ptr, die);
15554   else
15555     {
15556       die->child = NULL;
15557       *new_info_ptr = cur_ptr;
15558     }
15559
15560   die->sibling = NULL;
15561   die->parent = parent;
15562   return die;
15563 }
15564
15565 /* Read a die, all of its descendents, and all of its siblings; set
15566    all of the fields of all of the dies correctly.  Arguments are as
15567    in read_die_and_children.  */
15568
15569 static struct die_info *
15570 read_die_and_siblings_1 (const struct die_reader_specs *reader,
15571                          const gdb_byte *info_ptr,
15572                          const gdb_byte **new_info_ptr,
15573                          struct die_info *parent)
15574 {
15575   struct die_info *first_die, *last_sibling;
15576   const gdb_byte *cur_ptr;
15577
15578   cur_ptr = info_ptr;
15579   first_die = last_sibling = NULL;
15580
15581   while (1)
15582     {
15583       struct die_info *die
15584         = read_die_and_children (reader, cur_ptr, &cur_ptr, parent);
15585
15586       if (die == NULL)
15587         {
15588           *new_info_ptr = cur_ptr;
15589           return first_die;
15590         }
15591
15592       if (!first_die)
15593         first_die = die;
15594       else
15595         last_sibling->sibling = die;
15596
15597       last_sibling = die;
15598     }
15599 }
15600
15601 /* Read a die, all of its descendents, and all of its siblings; set
15602    all of the fields of all of the dies correctly.  Arguments are as
15603    in read_die_and_children.
15604    This the main entry point for reading a DIE and all its children.  */
15605
15606 static struct die_info *
15607 read_die_and_siblings (const struct die_reader_specs *reader,
15608                        const gdb_byte *info_ptr,
15609                        const gdb_byte **new_info_ptr,
15610                        struct die_info *parent)
15611 {
15612   struct die_info *die = read_die_and_siblings_1 (reader, info_ptr,
15613                                                   new_info_ptr, parent);
15614
15615   if (dwarf_die_debug)
15616     {
15617       fprintf_unfiltered (gdb_stdlog,
15618                           "Read die from %s@0x%x of %s:\n",
15619                           get_section_name (reader->die_section),
15620                           (unsigned) (info_ptr - reader->die_section->buffer),
15621                           bfd_get_filename (reader->abfd));
15622       dump_die (die, dwarf_die_debug);
15623     }
15624
15625   return die;
15626 }
15627
15628 /* Read a die and all its attributes, leave space for NUM_EXTRA_ATTRS
15629    attributes.
15630    The caller is responsible for filling in the extra attributes
15631    and updating (*DIEP)->num_attrs.
15632    Set DIEP to point to a newly allocated die with its information,
15633    except for its child, sibling, and parent fields.
15634    Set HAS_CHILDREN to tell whether the die has children or not.  */
15635
15636 static const gdb_byte *
15637 read_full_die_1 (const struct die_reader_specs *reader,
15638                  struct die_info **diep, const gdb_byte *info_ptr,
15639                  int *has_children, int num_extra_attrs)
15640 {
15641   unsigned int abbrev_number, bytes_read, i;
15642   struct abbrev_info *abbrev;
15643   struct die_info *die;
15644   struct dwarf2_cu *cu = reader->cu;
15645   bfd *abfd = reader->abfd;
15646
15647   sect_offset sect_off = (sect_offset) (info_ptr - reader->buffer);
15648   abbrev_number = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
15649   info_ptr += bytes_read;
15650   if (!abbrev_number)
15651     {
15652       *diep = NULL;
15653       *has_children = 0;
15654       return info_ptr;
15655     }
15656
15657   abbrev = abbrev_table_lookup_abbrev (cu->abbrev_table, abbrev_number);
15658   if (!abbrev)
15659     error (_("Dwarf Error: could not find abbrev number %d [in module %s]"),
15660            abbrev_number,
15661            bfd_get_filename (abfd));
15662
15663   die = dwarf_alloc_die (cu, abbrev->num_attrs + num_extra_attrs);
15664   die->sect_off = sect_off;
15665   die->tag = abbrev->tag;
15666   die->abbrev = abbrev_number;
15667
15668   /* Make the result usable.
15669      The caller needs to update num_attrs after adding the extra
15670      attributes.  */
15671   die->num_attrs = abbrev->num_attrs;
15672
15673   for (i = 0; i < abbrev->num_attrs; ++i)
15674     info_ptr = read_attribute (reader, &die->attrs[i], &abbrev->attrs[i],
15675                                info_ptr);
15676
15677   *diep = die;
15678   *has_children = abbrev->has_children;
15679   return info_ptr;
15680 }
15681
15682 /* Read a die and all its attributes.
15683    Set DIEP to point to a newly allocated die with its information,
15684    except for its child, sibling, and parent fields.
15685    Set HAS_CHILDREN to tell whether the die has children or not.  */
15686
15687 static const gdb_byte *
15688 read_full_die (const struct die_reader_specs *reader,
15689                struct die_info **diep, const gdb_byte *info_ptr,
15690                int *has_children)
15691 {
15692   const gdb_byte *result;
15693
15694   result = read_full_die_1 (reader, diep, info_ptr, has_children, 0);
15695
15696   if (dwarf_die_debug)
15697     {
15698       fprintf_unfiltered (gdb_stdlog,
15699                           "Read die from %s@0x%x of %s:\n",
15700                           get_section_name (reader->die_section),
15701                           (unsigned) (info_ptr - reader->die_section->buffer),
15702                           bfd_get_filename (reader->abfd));
15703       dump_die (*diep, dwarf_die_debug);
15704     }
15705
15706   return result;
15707 }
15708 \f
15709 /* Abbreviation tables.
15710
15711    In DWARF version 2, the description of the debugging information is
15712    stored in a separate .debug_abbrev section.  Before we read any
15713    dies from a section we read in all abbreviations and install them
15714    in a hash table.  */
15715
15716 /* Allocate space for a struct abbrev_info object in ABBREV_TABLE.  */
15717
15718 static struct abbrev_info *
15719 abbrev_table_alloc_abbrev (struct abbrev_table *abbrev_table)
15720 {
15721   struct abbrev_info *abbrev;
15722
15723   abbrev = XOBNEW (&abbrev_table->abbrev_obstack, struct abbrev_info);
15724   memset (abbrev, 0, sizeof (struct abbrev_info));
15725
15726   return abbrev;
15727 }
15728
15729 /* Add an abbreviation to the table.  */
15730
15731 static void
15732 abbrev_table_add_abbrev (struct abbrev_table *abbrev_table,
15733                          unsigned int abbrev_number,
15734                          struct abbrev_info *abbrev)
15735 {
15736   unsigned int hash_number;
15737
15738   hash_number = abbrev_number % ABBREV_HASH_SIZE;
15739   abbrev->next = abbrev_table->abbrevs[hash_number];
15740   abbrev_table->abbrevs[hash_number] = abbrev;
15741 }
15742
15743 /* Look up an abbrev in the table.
15744    Returns NULL if the abbrev is not found.  */
15745
15746 static struct abbrev_info *
15747 abbrev_table_lookup_abbrev (const struct abbrev_table *abbrev_table,
15748                             unsigned int abbrev_number)
15749 {
15750   unsigned int hash_number;
15751   struct abbrev_info *abbrev;
15752
15753   hash_number = abbrev_number % ABBREV_HASH_SIZE;
15754   abbrev = abbrev_table->abbrevs[hash_number];
15755
15756   while (abbrev)
15757     {
15758       if (abbrev->number == abbrev_number)
15759         return abbrev;
15760       abbrev = abbrev->next;
15761     }
15762   return NULL;
15763 }
15764
15765 /* Read in an abbrev table.  */
15766
15767 static struct abbrev_table *
15768 abbrev_table_read_table (struct dwarf2_section_info *section,
15769                          sect_offset sect_off)
15770 {
15771   struct objfile *objfile = dwarf2_per_objfile->objfile;
15772   bfd *abfd = get_section_bfd_owner (section);
15773   struct abbrev_table *abbrev_table;
15774   const gdb_byte *abbrev_ptr;
15775   struct abbrev_info *cur_abbrev;
15776   unsigned int abbrev_number, bytes_read, abbrev_name;
15777   unsigned int abbrev_form;
15778   struct attr_abbrev *cur_attrs;
15779   unsigned int allocated_attrs;
15780
15781   abbrev_table = XNEW (struct abbrev_table);
15782   abbrev_table->sect_off = sect_off;
15783   obstack_init (&abbrev_table->abbrev_obstack);
15784   abbrev_table->abbrevs =
15785     XOBNEWVEC (&abbrev_table->abbrev_obstack, struct abbrev_info *,
15786                ABBREV_HASH_SIZE);
15787   memset (abbrev_table->abbrevs, 0,
15788           ABBREV_HASH_SIZE * sizeof (struct abbrev_info *));
15789
15790   dwarf2_read_section (objfile, section);
15791   abbrev_ptr = section->buffer + to_underlying (sect_off);
15792   abbrev_number = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
15793   abbrev_ptr += bytes_read;
15794
15795   allocated_attrs = ATTR_ALLOC_CHUNK;
15796   cur_attrs = XNEWVEC (struct attr_abbrev, allocated_attrs);
15797
15798   /* Loop until we reach an abbrev number of 0.  */
15799   while (abbrev_number)
15800     {
15801       cur_abbrev = abbrev_table_alloc_abbrev (abbrev_table);
15802
15803       /* read in abbrev header */
15804       cur_abbrev->number = abbrev_number;
15805       cur_abbrev->tag
15806         = (enum dwarf_tag) read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
15807       abbrev_ptr += bytes_read;
15808       cur_abbrev->has_children = read_1_byte (abfd, abbrev_ptr);
15809       abbrev_ptr += 1;
15810
15811       /* now read in declarations */
15812       for (;;)
15813         {
15814           LONGEST implicit_const;
15815
15816           abbrev_name = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
15817           abbrev_ptr += bytes_read;
15818           abbrev_form = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
15819           abbrev_ptr += bytes_read;
15820           if (abbrev_form == DW_FORM_implicit_const)
15821             {
15822               implicit_const = read_signed_leb128 (abfd, abbrev_ptr,
15823                                                    &bytes_read);
15824               abbrev_ptr += bytes_read;
15825             }
15826           else
15827             {
15828               /* Initialize it due to a false compiler warning.  */
15829               implicit_const = -1;
15830             }
15831
15832           if (abbrev_name == 0)
15833             break;
15834
15835           if (cur_abbrev->num_attrs == allocated_attrs)
15836             {
15837               allocated_attrs += ATTR_ALLOC_CHUNK;
15838               cur_attrs
15839                 = XRESIZEVEC (struct attr_abbrev, cur_attrs, allocated_attrs);
15840             }
15841
15842           cur_attrs[cur_abbrev->num_attrs].name
15843             = (enum dwarf_attribute) abbrev_name;
15844           cur_attrs[cur_abbrev->num_attrs].form
15845             = (enum dwarf_form) abbrev_form;
15846           cur_attrs[cur_abbrev->num_attrs].implicit_const = implicit_const;
15847           ++cur_abbrev->num_attrs;
15848         }
15849
15850       cur_abbrev->attrs =
15851         XOBNEWVEC (&abbrev_table->abbrev_obstack, struct attr_abbrev,
15852                    cur_abbrev->num_attrs);
15853       memcpy (cur_abbrev->attrs, cur_attrs,
15854               cur_abbrev->num_attrs * sizeof (struct attr_abbrev));
15855
15856       abbrev_table_add_abbrev (abbrev_table, abbrev_number, cur_abbrev);
15857
15858       /* Get next abbreviation.
15859          Under Irix6 the abbreviations for a compilation unit are not
15860          always properly terminated with an abbrev number of 0.
15861          Exit loop if we encounter an abbreviation which we have
15862          already read (which means we are about to read the abbreviations
15863          for the next compile unit) or if the end of the abbreviation
15864          table is reached.  */
15865       if ((unsigned int) (abbrev_ptr - section->buffer) >= section->size)
15866         break;
15867       abbrev_number = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
15868       abbrev_ptr += bytes_read;
15869       if (abbrev_table_lookup_abbrev (abbrev_table, abbrev_number) != NULL)
15870         break;
15871     }
15872
15873   xfree (cur_attrs);
15874   return abbrev_table;
15875 }
15876
15877 /* Free the resources held by ABBREV_TABLE.  */
15878
15879 static void
15880 abbrev_table_free (struct abbrev_table *abbrev_table)
15881 {
15882   obstack_free (&abbrev_table->abbrev_obstack, NULL);
15883   xfree (abbrev_table);
15884 }
15885
15886 /* Same as abbrev_table_free but as a cleanup.
15887    We pass in a pointer to the pointer to the table so that we can
15888    set the pointer to NULL when we're done.  It also simplifies
15889    build_type_psymtabs_1.  */
15890
15891 static void
15892 abbrev_table_free_cleanup (void *table_ptr)
15893 {
15894   struct abbrev_table **abbrev_table_ptr = (struct abbrev_table **) table_ptr;
15895
15896   if (*abbrev_table_ptr != NULL)
15897     abbrev_table_free (*abbrev_table_ptr);
15898   *abbrev_table_ptr = NULL;
15899 }
15900
15901 /* Read the abbrev table for CU from ABBREV_SECTION.  */
15902
15903 static void
15904 dwarf2_read_abbrevs (struct dwarf2_cu *cu,
15905                      struct dwarf2_section_info *abbrev_section)
15906 {
15907   cu->abbrev_table =
15908     abbrev_table_read_table (abbrev_section, cu->header.abbrev_sect_off);
15909 }
15910
15911 /* Release the memory used by the abbrev table for a compilation unit.  */
15912
15913 static void
15914 dwarf2_free_abbrev_table (void *ptr_to_cu)
15915 {
15916   struct dwarf2_cu *cu = (struct dwarf2_cu *) ptr_to_cu;
15917
15918   if (cu->abbrev_table != NULL)
15919     abbrev_table_free (cu->abbrev_table);
15920   /* Set this to NULL so that we SEGV if we try to read it later,
15921      and also because free_comp_unit verifies this is NULL.  */
15922   cu->abbrev_table = NULL;
15923 }
15924 \f
15925 /* Returns nonzero if TAG represents a type that we might generate a partial
15926    symbol for.  */
15927
15928 static int
15929 is_type_tag_for_partial (int tag)
15930 {
15931   switch (tag)
15932     {
15933 #if 0
15934     /* Some types that would be reasonable to generate partial symbols for,
15935        that we don't at present.  */
15936     case DW_TAG_array_type:
15937     case DW_TAG_file_type:
15938     case DW_TAG_ptr_to_member_type:
15939     case DW_TAG_set_type:
15940     case DW_TAG_string_type:
15941     case DW_TAG_subroutine_type:
15942 #endif
15943     case DW_TAG_base_type:
15944     case DW_TAG_class_type:
15945     case DW_TAG_interface_type:
15946     case DW_TAG_enumeration_type:
15947     case DW_TAG_structure_type:
15948     case DW_TAG_subrange_type:
15949     case DW_TAG_typedef:
15950     case DW_TAG_union_type:
15951       return 1;
15952     default:
15953       return 0;
15954     }
15955 }
15956
15957 /* Load all DIEs that are interesting for partial symbols into memory.  */
15958
15959 static struct partial_die_info *
15960 load_partial_dies (const struct die_reader_specs *reader,
15961                    const gdb_byte *info_ptr, int building_psymtab)
15962 {
15963   struct dwarf2_cu *cu = reader->cu;
15964   struct objfile *objfile = cu->objfile;
15965   struct partial_die_info *part_die;
15966   struct partial_die_info *parent_die, *last_die, *first_die = NULL;
15967   struct abbrev_info *abbrev;
15968   unsigned int bytes_read;
15969   unsigned int load_all = 0;
15970   int nesting_level = 1;
15971
15972   parent_die = NULL;
15973   last_die = NULL;
15974
15975   gdb_assert (cu->per_cu != NULL);
15976   if (cu->per_cu->load_all_dies)
15977     load_all = 1;
15978
15979   cu->partial_dies
15980     = htab_create_alloc_ex (cu->header.length / 12,
15981                             partial_die_hash,
15982                             partial_die_eq,
15983                             NULL,
15984                             &cu->comp_unit_obstack,
15985                             hashtab_obstack_allocate,
15986                             dummy_obstack_deallocate);
15987
15988   part_die = XOBNEW (&cu->comp_unit_obstack, struct partial_die_info);
15989
15990   while (1)
15991     {
15992       abbrev = peek_die_abbrev (info_ptr, &bytes_read, cu);
15993
15994       /* A NULL abbrev means the end of a series of children.  */
15995       if (abbrev == NULL)
15996         {
15997           if (--nesting_level == 0)
15998             {
15999               /* PART_DIE was probably the last thing allocated on the
16000                  comp_unit_obstack, so we could call obstack_free
16001                  here.  We don't do that because the waste is small,
16002                  and will be cleaned up when we're done with this
16003                  compilation unit.  This way, we're also more robust
16004                  against other users of the comp_unit_obstack.  */
16005               return first_die;
16006             }
16007           info_ptr += bytes_read;
16008           last_die = parent_die;
16009           parent_die = parent_die->die_parent;
16010           continue;
16011         }
16012
16013       /* Check for template arguments.  We never save these; if
16014          they're seen, we just mark the parent, and go on our way.  */
16015       if (parent_die != NULL
16016           && cu->language == language_cplus
16017           && (abbrev->tag == DW_TAG_template_type_param
16018               || abbrev->tag == DW_TAG_template_value_param))
16019         {
16020           parent_die->has_template_arguments = 1;
16021
16022           if (!load_all)
16023             {
16024               /* We don't need a partial DIE for the template argument.  */
16025               info_ptr = skip_one_die (reader, info_ptr + bytes_read, abbrev);
16026               continue;
16027             }
16028         }
16029
16030       /* We only recurse into c++ subprograms looking for template arguments.
16031          Skip their other children.  */
16032       if (!load_all
16033           && cu->language == language_cplus
16034           && parent_die != NULL
16035           && parent_die->tag == DW_TAG_subprogram)
16036         {
16037           info_ptr = skip_one_die (reader, info_ptr + bytes_read, abbrev);
16038           continue;
16039         }
16040
16041       /* Check whether this DIE is interesting enough to save.  Normally
16042          we would not be interested in members here, but there may be
16043          later variables referencing them via DW_AT_specification (for
16044          static members).  */
16045       if (!load_all
16046           && !is_type_tag_for_partial (abbrev->tag)
16047           && abbrev->tag != DW_TAG_constant
16048           && abbrev->tag != DW_TAG_enumerator
16049           && abbrev->tag != DW_TAG_subprogram
16050           && abbrev->tag != DW_TAG_lexical_block
16051           && abbrev->tag != DW_TAG_variable
16052           && abbrev->tag != DW_TAG_namespace
16053           && abbrev->tag != DW_TAG_module
16054           && abbrev->tag != DW_TAG_member
16055           && abbrev->tag != DW_TAG_imported_unit
16056           && abbrev->tag != DW_TAG_imported_declaration)
16057         {
16058           /* Otherwise we skip to the next sibling, if any.  */
16059           info_ptr = skip_one_die (reader, info_ptr + bytes_read, abbrev);
16060           continue;
16061         }
16062
16063       info_ptr = read_partial_die (reader, part_die, abbrev, bytes_read,
16064                                    info_ptr);
16065
16066       /* This two-pass algorithm for processing partial symbols has a
16067          high cost in cache pressure.  Thus, handle some simple cases
16068          here which cover the majority of C partial symbols.  DIEs
16069          which neither have specification tags in them, nor could have
16070          specification tags elsewhere pointing at them, can simply be
16071          processed and discarded.
16072
16073          This segment is also optional; scan_partial_symbols and
16074          add_partial_symbol will handle these DIEs if we chain
16075          them in normally.  When compilers which do not emit large
16076          quantities of duplicate debug information are more common,
16077          this code can probably be removed.  */
16078
16079       /* Any complete simple types at the top level (pretty much all
16080          of them, for a language without namespaces), can be processed
16081          directly.  */
16082       if (parent_die == NULL
16083           && part_die->has_specification == 0
16084           && part_die->is_declaration == 0
16085           && ((part_die->tag == DW_TAG_typedef && !part_die->has_children)
16086               || part_die->tag == DW_TAG_base_type
16087               || part_die->tag == DW_TAG_subrange_type))
16088         {
16089           if (building_psymtab && part_die->name != NULL)
16090             add_psymbol_to_list (part_die->name, strlen (part_die->name), 0,
16091                                  VAR_DOMAIN, LOC_TYPEDEF,
16092                                  &objfile->static_psymbols,
16093                                  0, cu->language, objfile);
16094           info_ptr = locate_pdi_sibling (reader, part_die, info_ptr);
16095           continue;
16096         }
16097
16098       /* The exception for DW_TAG_typedef with has_children above is
16099          a workaround of GCC PR debug/47510.  In the case of this complaint
16100          type_name_no_tag_or_error will error on such types later.
16101
16102          GDB skipped children of DW_TAG_typedef by the shortcut above and then
16103          it could not find the child DIEs referenced later, this is checked
16104          above.  In correct DWARF DW_TAG_typedef should have no children.  */
16105
16106       if (part_die->tag == DW_TAG_typedef && part_die->has_children)
16107         complaint (&symfile_complaints,
16108                    _("DW_TAG_typedef has childen - GCC PR debug/47510 bug "
16109                      "- DIE at 0x%x [in module %s]"),
16110                    to_underlying (part_die->sect_off), objfile_name (objfile));
16111
16112       /* If we're at the second level, and we're an enumerator, and
16113          our parent has no specification (meaning possibly lives in a
16114          namespace elsewhere), then we can add the partial symbol now
16115          instead of queueing it.  */
16116       if (part_die->tag == DW_TAG_enumerator
16117           && parent_die != NULL
16118           && parent_die->die_parent == NULL
16119           && parent_die->tag == DW_TAG_enumeration_type
16120           && parent_die->has_specification == 0)
16121         {
16122           if (part_die->name == NULL)
16123             complaint (&symfile_complaints,
16124                        _("malformed enumerator DIE ignored"));
16125           else if (building_psymtab)
16126             add_psymbol_to_list (part_die->name, strlen (part_die->name), 0,
16127                                  VAR_DOMAIN, LOC_CONST,
16128                                  cu->language == language_cplus
16129                                  ? &objfile->global_psymbols
16130                                  : &objfile->static_psymbols,
16131                                  0, cu->language, objfile);
16132
16133           info_ptr = locate_pdi_sibling (reader, part_die, info_ptr);
16134           continue;
16135         }
16136
16137       /* We'll save this DIE so link it in.  */
16138       part_die->die_parent = parent_die;
16139       part_die->die_sibling = NULL;
16140       part_die->die_child = NULL;
16141
16142       if (last_die && last_die == parent_die)
16143         last_die->die_child = part_die;
16144       else if (last_die)
16145         last_die->die_sibling = part_die;
16146
16147       last_die = part_die;
16148
16149       if (first_die == NULL)
16150         first_die = part_die;
16151
16152       /* Maybe add the DIE to the hash table.  Not all DIEs that we
16153          find interesting need to be in the hash table, because we
16154          also have the parent/sibling/child chains; only those that we
16155          might refer to by offset later during partial symbol reading.
16156
16157          For now this means things that might have be the target of a
16158          DW_AT_specification, DW_AT_abstract_origin, or
16159          DW_AT_extension.  DW_AT_extension will refer only to
16160          namespaces; DW_AT_abstract_origin refers to functions (and
16161          many things under the function DIE, but we do not recurse
16162          into function DIEs during partial symbol reading) and
16163          possibly variables as well; DW_AT_specification refers to
16164          declarations.  Declarations ought to have the DW_AT_declaration
16165          flag.  It happens that GCC forgets to put it in sometimes, but
16166          only for functions, not for types.
16167
16168          Adding more things than necessary to the hash table is harmless
16169          except for the performance cost.  Adding too few will result in
16170          wasted time in find_partial_die, when we reread the compilation
16171          unit with load_all_dies set.  */
16172
16173       if (load_all
16174           || abbrev->tag == DW_TAG_constant
16175           || abbrev->tag == DW_TAG_subprogram
16176           || abbrev->tag == DW_TAG_variable
16177           || abbrev->tag == DW_TAG_namespace
16178           || part_die->is_declaration)
16179         {
16180           void **slot;
16181
16182           slot = htab_find_slot_with_hash (cu->partial_dies, part_die,
16183                                            to_underlying (part_die->sect_off),
16184                                            INSERT);
16185           *slot = part_die;
16186         }
16187
16188       part_die = XOBNEW (&cu->comp_unit_obstack, struct partial_die_info);
16189
16190       /* For some DIEs we want to follow their children (if any).  For C
16191          we have no reason to follow the children of structures; for other
16192          languages we have to, so that we can get at method physnames
16193          to infer fully qualified class names, for DW_AT_specification,
16194          and for C++ template arguments.  For C++, we also look one level
16195          inside functions to find template arguments (if the name of the
16196          function does not already contain the template arguments).
16197
16198          For Ada, we need to scan the children of subprograms and lexical
16199          blocks as well because Ada allows the definition of nested
16200          entities that could be interesting for the debugger, such as
16201          nested subprograms for instance.  */
16202       if (last_die->has_children
16203           && (load_all
16204               || last_die->tag == DW_TAG_namespace
16205               || last_die->tag == DW_TAG_module
16206               || last_die->tag == DW_TAG_enumeration_type
16207               || (cu->language == language_cplus
16208                   && last_die->tag == DW_TAG_subprogram
16209                   && (last_die->name == NULL
16210                       || strchr (last_die->name, '<') == NULL))
16211               || (cu->language != language_c
16212                   && (last_die->tag == DW_TAG_class_type
16213                       || last_die->tag == DW_TAG_interface_type
16214                       || last_die->tag == DW_TAG_structure_type
16215                       || last_die->tag == DW_TAG_union_type))
16216               || (cu->language == language_ada
16217                   && (last_die->tag == DW_TAG_subprogram
16218                       || last_die->tag == DW_TAG_lexical_block))))
16219         {
16220           nesting_level++;
16221           parent_die = last_die;
16222           continue;
16223         }
16224
16225       /* Otherwise we skip to the next sibling, if any.  */
16226       info_ptr = locate_pdi_sibling (reader, last_die, info_ptr);
16227
16228       /* Back to the top, do it again.  */
16229     }
16230 }
16231
16232 /* Read a minimal amount of information into the minimal die structure.  */
16233
16234 static const gdb_byte *
16235 read_partial_die (const struct die_reader_specs *reader,
16236                   struct partial_die_info *part_die,
16237                   struct abbrev_info *abbrev, unsigned int abbrev_len,
16238                   const gdb_byte *info_ptr)
16239 {
16240   struct dwarf2_cu *cu = reader->cu;
16241   struct objfile *objfile = cu->objfile;
16242   const gdb_byte *buffer = reader->buffer;
16243   unsigned int i;
16244   struct attribute attr;
16245   int has_low_pc_attr = 0;
16246   int has_high_pc_attr = 0;
16247   int high_pc_relative = 0;
16248
16249   memset (part_die, 0, sizeof (struct partial_die_info));
16250
16251   part_die->sect_off = (sect_offset) (info_ptr - buffer);
16252
16253   info_ptr += abbrev_len;
16254
16255   if (abbrev == NULL)
16256     return info_ptr;
16257
16258   part_die->tag = abbrev->tag;
16259   part_die->has_children = abbrev->has_children;
16260
16261   for (i = 0; i < abbrev->num_attrs; ++i)
16262     {
16263       info_ptr = read_attribute (reader, &attr, &abbrev->attrs[i], info_ptr);
16264
16265       /* Store the data if it is of an attribute we want to keep in a
16266          partial symbol table.  */
16267       switch (attr.name)
16268         {
16269         case DW_AT_name:
16270           switch (part_die->tag)
16271             {
16272             case DW_TAG_compile_unit:
16273             case DW_TAG_partial_unit:
16274             case DW_TAG_type_unit:
16275               /* Compilation units have a DW_AT_name that is a filename, not
16276                  a source language identifier.  */
16277             case DW_TAG_enumeration_type:
16278             case DW_TAG_enumerator:
16279               /* These tags always have simple identifiers already; no need
16280                  to canonicalize them.  */
16281               part_die->name = DW_STRING (&attr);
16282               break;
16283             default:
16284               part_die->name
16285                 = dwarf2_canonicalize_name (DW_STRING (&attr), cu,
16286                                             &objfile->per_bfd->storage_obstack);
16287               break;
16288             }
16289           break;
16290         case DW_AT_linkage_name:
16291         case DW_AT_MIPS_linkage_name:
16292           /* Note that both forms of linkage name might appear.  We
16293              assume they will be the same, and we only store the last
16294              one we see.  */
16295           if (cu->language == language_ada)
16296             part_die->name = DW_STRING (&attr);
16297           part_die->linkage_name = DW_STRING (&attr);
16298           break;
16299         case DW_AT_low_pc:
16300           has_low_pc_attr = 1;
16301           part_die->lowpc = attr_value_as_address (&attr);
16302           break;
16303         case DW_AT_high_pc:
16304           has_high_pc_attr = 1;
16305           part_die->highpc = attr_value_as_address (&attr);
16306           if (cu->header.version >= 4 && attr_form_is_constant (&attr))
16307                 high_pc_relative = 1;
16308           break;
16309         case DW_AT_location:
16310           /* Support the .debug_loc offsets.  */
16311           if (attr_form_is_block (&attr))
16312             {
16313                part_die->d.locdesc = DW_BLOCK (&attr);
16314             }
16315           else if (attr_form_is_section_offset (&attr))
16316             {
16317               dwarf2_complex_location_expr_complaint ();
16318             }
16319           else
16320             {
16321               dwarf2_invalid_attrib_class_complaint ("DW_AT_location",
16322                                                      "partial symbol information");
16323             }
16324           break;
16325         case DW_AT_external:
16326           part_die->is_external = DW_UNSND (&attr);
16327           break;
16328         case DW_AT_declaration:
16329           part_die->is_declaration = DW_UNSND (&attr);
16330           break;
16331         case DW_AT_type:
16332           part_die->has_type = 1;
16333           break;
16334         case DW_AT_abstract_origin:
16335         case DW_AT_specification:
16336         case DW_AT_extension:
16337           part_die->has_specification = 1;
16338           part_die->spec_offset = dwarf2_get_ref_die_offset (&attr);
16339           part_die->spec_is_dwz = (attr.form == DW_FORM_GNU_ref_alt
16340                                    || cu->per_cu->is_dwz);
16341           break;
16342         case DW_AT_sibling:
16343           /* Ignore absolute siblings, they might point outside of
16344              the current compile unit.  */
16345           if (attr.form == DW_FORM_ref_addr)
16346             complaint (&symfile_complaints,
16347                        _("ignoring absolute DW_AT_sibling"));
16348           else
16349             {
16350               sect_offset off = dwarf2_get_ref_die_offset (&attr);
16351               const gdb_byte *sibling_ptr = buffer + to_underlying (off);
16352
16353               if (sibling_ptr < info_ptr)
16354                 complaint (&symfile_complaints,
16355                            _("DW_AT_sibling points backwards"));
16356               else if (sibling_ptr > reader->buffer_end)
16357                 dwarf2_section_buffer_overflow_complaint (reader->die_section);
16358               else
16359                 part_die->sibling = sibling_ptr;
16360             }
16361           break;
16362         case DW_AT_byte_size:
16363           part_die->has_byte_size = 1;
16364           break;
16365         case DW_AT_const_value:
16366           part_die->has_const_value = 1;
16367           break;
16368         case DW_AT_calling_convention:
16369           /* DWARF doesn't provide a way to identify a program's source-level
16370              entry point.  DW_AT_calling_convention attributes are only meant
16371              to describe functions' calling conventions.
16372
16373              However, because it's a necessary piece of information in
16374              Fortran, and before DWARF 4 DW_CC_program was the only
16375              piece of debugging information whose definition refers to
16376              a 'main program' at all, several compilers marked Fortran
16377              main programs with DW_CC_program --- even when those
16378              functions use the standard calling conventions.
16379
16380              Although DWARF now specifies a way to provide this
16381              information, we support this practice for backward
16382              compatibility.  */
16383           if (DW_UNSND (&attr) == DW_CC_program
16384               && cu->language == language_fortran)
16385             part_die->main_subprogram = 1;
16386           break;
16387         case DW_AT_inline:
16388           if (DW_UNSND (&attr) == DW_INL_inlined
16389               || DW_UNSND (&attr) == DW_INL_declared_inlined)
16390             part_die->may_be_inlined = 1;
16391           break;
16392
16393         case DW_AT_import:
16394           if (part_die->tag == DW_TAG_imported_unit)
16395             {
16396               part_die->d.sect_off = dwarf2_get_ref_die_offset (&attr);
16397               part_die->is_dwz = (attr.form == DW_FORM_GNU_ref_alt
16398                                   || cu->per_cu->is_dwz);
16399             }
16400           break;
16401
16402         case DW_AT_main_subprogram:
16403           part_die->main_subprogram = DW_UNSND (&attr);
16404           break;
16405
16406         default:
16407           break;
16408         }
16409     }
16410
16411   if (high_pc_relative)
16412     part_die->highpc += part_die->lowpc;
16413
16414   if (has_low_pc_attr && has_high_pc_attr)
16415     {
16416       /* When using the GNU linker, .gnu.linkonce. sections are used to
16417          eliminate duplicate copies of functions and vtables and such.
16418          The linker will arbitrarily choose one and discard the others.
16419          The AT_*_pc values for such functions refer to local labels in
16420          these sections.  If the section from that file was discarded, the
16421          labels are not in the output, so the relocs get a value of 0.
16422          If this is a discarded function, mark the pc bounds as invalid,
16423          so that GDB will ignore it.  */
16424       if (part_die->lowpc == 0 && !dwarf2_per_objfile->has_section_at_zero)
16425         {
16426           struct gdbarch *gdbarch = get_objfile_arch (objfile);
16427
16428           complaint (&symfile_complaints,
16429                      _("DW_AT_low_pc %s is zero "
16430                        "for DIE at 0x%x [in module %s]"),
16431                      paddress (gdbarch, part_die->lowpc),
16432                      to_underlying (part_die->sect_off), objfile_name (objfile));
16433         }
16434       /* dwarf2_get_pc_bounds has also the strict low < high requirement.  */
16435       else if (part_die->lowpc >= part_die->highpc)
16436         {
16437           struct gdbarch *gdbarch = get_objfile_arch (objfile);
16438
16439           complaint (&symfile_complaints,
16440                      _("DW_AT_low_pc %s is not < DW_AT_high_pc %s "
16441                        "for DIE at 0x%x [in module %s]"),
16442                      paddress (gdbarch, part_die->lowpc),
16443                      paddress (gdbarch, part_die->highpc),
16444                      to_underlying (part_die->sect_off),
16445                      objfile_name (objfile));
16446         }
16447       else
16448         part_die->has_pc_info = 1;
16449     }
16450
16451   return info_ptr;
16452 }
16453
16454 /* Find a cached partial DIE at OFFSET in CU.  */
16455
16456 static struct partial_die_info *
16457 find_partial_die_in_comp_unit (sect_offset sect_off, struct dwarf2_cu *cu)
16458 {
16459   struct partial_die_info *lookup_die = NULL;
16460   struct partial_die_info part_die;
16461
16462   part_die.sect_off = sect_off;
16463   lookup_die = ((struct partial_die_info *)
16464                 htab_find_with_hash (cu->partial_dies, &part_die,
16465                                      to_underlying (sect_off)));
16466
16467   return lookup_die;
16468 }
16469
16470 /* Find a partial DIE at OFFSET, which may or may not be in CU,
16471    except in the case of .debug_types DIEs which do not reference
16472    outside their CU (they do however referencing other types via
16473    DW_FORM_ref_sig8).  */
16474
16475 static struct partial_die_info *
16476 find_partial_die (sect_offset sect_off, int offset_in_dwz, struct dwarf2_cu *cu)
16477 {
16478   struct objfile *objfile = cu->objfile;
16479   struct dwarf2_per_cu_data *per_cu = NULL;
16480   struct partial_die_info *pd = NULL;
16481
16482   if (offset_in_dwz == cu->per_cu->is_dwz
16483       && offset_in_cu_p (&cu->header, sect_off))
16484     {
16485       pd = find_partial_die_in_comp_unit (sect_off, cu);
16486       if (pd != NULL)
16487         return pd;
16488       /* We missed recording what we needed.
16489          Load all dies and try again.  */
16490       per_cu = cu->per_cu;
16491     }
16492   else
16493     {
16494       /* TUs don't reference other CUs/TUs (except via type signatures).  */
16495       if (cu->per_cu->is_debug_types)
16496         {
16497           error (_("Dwarf Error: Type Unit at offset 0x%x contains"
16498                    " external reference to offset 0x%x [in module %s].\n"),
16499                  to_underlying (cu->header.sect_off), to_underlying (sect_off),
16500                  bfd_get_filename (objfile->obfd));
16501         }
16502       per_cu = dwarf2_find_containing_comp_unit (sect_off, offset_in_dwz,
16503                                                  objfile);
16504
16505       if (per_cu->cu == NULL || per_cu->cu->partial_dies == NULL)
16506         load_partial_comp_unit (per_cu);
16507
16508       per_cu->cu->last_used = 0;
16509       pd = find_partial_die_in_comp_unit (sect_off, per_cu->cu);
16510     }
16511
16512   /* If we didn't find it, and not all dies have been loaded,
16513      load them all and try again.  */
16514
16515   if (pd == NULL && per_cu->load_all_dies == 0)
16516     {
16517       per_cu->load_all_dies = 1;
16518
16519       /* This is nasty.  When we reread the DIEs, somewhere up the call chain
16520          THIS_CU->cu may already be in use.  So we can't just free it and
16521          replace its DIEs with the ones we read in.  Instead, we leave those
16522          DIEs alone (which can still be in use, e.g. in scan_partial_symbols),
16523          and clobber THIS_CU->cu->partial_dies with the hash table for the new
16524          set.  */
16525       load_partial_comp_unit (per_cu);
16526
16527       pd = find_partial_die_in_comp_unit (sect_off, per_cu->cu);
16528     }
16529
16530   if (pd == NULL)
16531     internal_error (__FILE__, __LINE__,
16532                     _("could not find partial DIE 0x%x "
16533                       "in cache [from module %s]\n"),
16534                     to_underlying (sect_off), bfd_get_filename (objfile->obfd));
16535   return pd;
16536 }
16537
16538 /* See if we can figure out if the class lives in a namespace.  We do
16539    this by looking for a member function; its demangled name will
16540    contain namespace info, if there is any.  */
16541
16542 static void
16543 guess_partial_die_structure_name (struct partial_die_info *struct_pdi,
16544                                   struct dwarf2_cu *cu)
16545 {
16546   /* NOTE: carlton/2003-10-07: Getting the info this way changes
16547      what template types look like, because the demangler
16548      frequently doesn't give the same name as the debug info.  We
16549      could fix this by only using the demangled name to get the
16550      prefix (but see comment in read_structure_type).  */
16551
16552   struct partial_die_info *real_pdi;
16553   struct partial_die_info *child_pdi;
16554
16555   /* If this DIE (this DIE's specification, if any) has a parent, then
16556      we should not do this.  We'll prepend the parent's fully qualified
16557      name when we create the partial symbol.  */
16558
16559   real_pdi = struct_pdi;
16560   while (real_pdi->has_specification)
16561     real_pdi = find_partial_die (real_pdi->spec_offset,
16562                                  real_pdi->spec_is_dwz, cu);
16563
16564   if (real_pdi->die_parent != NULL)
16565     return;
16566
16567   for (child_pdi = struct_pdi->die_child;
16568        child_pdi != NULL;
16569        child_pdi = child_pdi->die_sibling)
16570     {
16571       if (child_pdi->tag == DW_TAG_subprogram
16572           && child_pdi->linkage_name != NULL)
16573         {
16574           char *actual_class_name
16575             = language_class_name_from_physname (cu->language_defn,
16576                                                  child_pdi->linkage_name);
16577           if (actual_class_name != NULL)
16578             {
16579               struct_pdi->name
16580                 = ((const char *)
16581                    obstack_copy0 (&cu->objfile->per_bfd->storage_obstack,
16582                                   actual_class_name,
16583                                   strlen (actual_class_name)));
16584               xfree (actual_class_name);
16585             }
16586           break;
16587         }
16588     }
16589 }
16590
16591 /* Adjust PART_DIE before generating a symbol for it.  This function
16592    may set the is_external flag or change the DIE's name.  */
16593
16594 static void
16595 fixup_partial_die (struct partial_die_info *part_die,
16596                    struct dwarf2_cu *cu)
16597 {
16598   /* Once we've fixed up a die, there's no point in doing so again.
16599      This also avoids a memory leak if we were to call
16600      guess_partial_die_structure_name multiple times.  */
16601   if (part_die->fixup_called)
16602     return;
16603
16604   /* If we found a reference attribute and the DIE has no name, try
16605      to find a name in the referred to DIE.  */
16606
16607   if (part_die->name == NULL && part_die->has_specification)
16608     {
16609       struct partial_die_info *spec_die;
16610
16611       spec_die = find_partial_die (part_die->spec_offset,
16612                                    part_die->spec_is_dwz, cu);
16613
16614       fixup_partial_die (spec_die, cu);
16615
16616       if (spec_die->name)
16617         {
16618           part_die->name = spec_die->name;
16619
16620           /* Copy DW_AT_external attribute if it is set.  */
16621           if (spec_die->is_external)
16622             part_die->is_external = spec_die->is_external;
16623         }
16624     }
16625
16626   /* Set default names for some unnamed DIEs.  */
16627
16628   if (part_die->name == NULL && part_die->tag == DW_TAG_namespace)
16629     part_die->name = CP_ANONYMOUS_NAMESPACE_STR;
16630
16631   /* If there is no parent die to provide a namespace, and there are
16632      children, see if we can determine the namespace from their linkage
16633      name.  */
16634   if (cu->language == language_cplus
16635       && !VEC_empty (dwarf2_section_info_def, dwarf2_per_objfile->types)
16636       && part_die->die_parent == NULL
16637       && part_die->has_children
16638       && (part_die->tag == DW_TAG_class_type
16639           || part_die->tag == DW_TAG_structure_type
16640           || part_die->tag == DW_TAG_union_type))
16641     guess_partial_die_structure_name (part_die, cu);
16642
16643   /* GCC might emit a nameless struct or union that has a linkage
16644      name.  See http://gcc.gnu.org/bugzilla/show_bug.cgi?id=47510.  */
16645   if (part_die->name == NULL
16646       && (part_die->tag == DW_TAG_class_type
16647           || part_die->tag == DW_TAG_interface_type
16648           || part_die->tag == DW_TAG_structure_type
16649           || part_die->tag == DW_TAG_union_type)
16650       && part_die->linkage_name != NULL)
16651     {
16652       char *demangled;
16653
16654       demangled = gdb_demangle (part_die->linkage_name, DMGL_TYPES);
16655       if (demangled)
16656         {
16657           const char *base;
16658
16659           /* Strip any leading namespaces/classes, keep only the base name.
16660              DW_AT_name for named DIEs does not contain the prefixes.  */
16661           base = strrchr (demangled, ':');
16662           if (base && base > demangled && base[-1] == ':')
16663             base++;
16664           else
16665             base = demangled;
16666
16667           part_die->name
16668             = ((const char *)
16669                obstack_copy0 (&cu->objfile->per_bfd->storage_obstack,
16670                               base, strlen (base)));
16671           xfree (demangled);
16672         }
16673     }
16674
16675   part_die->fixup_called = 1;
16676 }
16677
16678 /* Read an attribute value described by an attribute form.  */
16679
16680 static const gdb_byte *
16681 read_attribute_value (const struct die_reader_specs *reader,
16682                       struct attribute *attr, unsigned form,
16683                       LONGEST implicit_const, const gdb_byte *info_ptr)
16684 {
16685   struct dwarf2_cu *cu = reader->cu;
16686   struct objfile *objfile = cu->objfile;
16687   struct gdbarch *gdbarch = get_objfile_arch (objfile);
16688   bfd *abfd = reader->abfd;
16689   struct comp_unit_head *cu_header = &cu->header;
16690   unsigned int bytes_read;
16691   struct dwarf_block *blk;
16692
16693   attr->form = (enum dwarf_form) form;
16694   switch (form)
16695     {
16696     case DW_FORM_ref_addr:
16697       if (cu->header.version == 2)
16698         DW_UNSND (attr) = read_address (abfd, info_ptr, cu, &bytes_read);
16699       else
16700         DW_UNSND (attr) = read_offset (abfd, info_ptr,
16701                                        &cu->header, &bytes_read);
16702       info_ptr += bytes_read;
16703       break;
16704     case DW_FORM_GNU_ref_alt:
16705       DW_UNSND (attr) = read_offset (abfd, info_ptr, &cu->header, &bytes_read);
16706       info_ptr += bytes_read;
16707       break;
16708     case DW_FORM_addr:
16709       DW_ADDR (attr) = read_address (abfd, info_ptr, cu, &bytes_read);
16710       DW_ADDR (attr) = gdbarch_adjust_dwarf2_addr (gdbarch, DW_ADDR (attr));
16711       info_ptr += bytes_read;
16712       break;
16713     case DW_FORM_block2:
16714       blk = dwarf_alloc_block (cu);
16715       blk->size = read_2_bytes (abfd, info_ptr);
16716       info_ptr += 2;
16717       blk->data = read_n_bytes (abfd, info_ptr, blk->size);
16718       info_ptr += blk->size;
16719       DW_BLOCK (attr) = blk;
16720       break;
16721     case DW_FORM_block4:
16722       blk = dwarf_alloc_block (cu);
16723       blk->size = read_4_bytes (abfd, info_ptr);
16724       info_ptr += 4;
16725       blk->data = read_n_bytes (abfd, info_ptr, blk->size);
16726       info_ptr += blk->size;
16727       DW_BLOCK (attr) = blk;
16728       break;
16729     case DW_FORM_data2:
16730       DW_UNSND (attr) = read_2_bytes (abfd, info_ptr);
16731       info_ptr += 2;
16732       break;
16733     case DW_FORM_data4:
16734       DW_UNSND (attr) = read_4_bytes (abfd, info_ptr);
16735       info_ptr += 4;
16736       break;
16737     case DW_FORM_data8:
16738       DW_UNSND (attr) = read_8_bytes (abfd, info_ptr);
16739       info_ptr += 8;
16740       break;
16741     case DW_FORM_data16:
16742       blk = dwarf_alloc_block (cu);
16743       blk->size = 16;
16744       blk->data = read_n_bytes (abfd, info_ptr, 16);
16745       info_ptr += 16;
16746       DW_BLOCK (attr) = blk;
16747       break;
16748     case DW_FORM_sec_offset:
16749       DW_UNSND (attr) = read_offset (abfd, info_ptr, &cu->header, &bytes_read);
16750       info_ptr += bytes_read;
16751       break;
16752     case DW_FORM_string:
16753       DW_STRING (attr) = read_direct_string (abfd, info_ptr, &bytes_read);
16754       DW_STRING_IS_CANONICAL (attr) = 0;
16755       info_ptr += bytes_read;
16756       break;
16757     case DW_FORM_strp:
16758       if (!cu->per_cu->is_dwz)
16759         {
16760           DW_STRING (attr) = read_indirect_string (abfd, info_ptr, cu_header,
16761                                                    &bytes_read);
16762           DW_STRING_IS_CANONICAL (attr) = 0;
16763           info_ptr += bytes_read;
16764           break;
16765         }
16766       /* FALLTHROUGH */
16767     case DW_FORM_line_strp:
16768       if (!cu->per_cu->is_dwz)
16769         {
16770           DW_STRING (attr) = read_indirect_line_string (abfd, info_ptr,
16771                                                         cu_header, &bytes_read);
16772           DW_STRING_IS_CANONICAL (attr) = 0;
16773           info_ptr += bytes_read;
16774           break;
16775         }
16776       /* FALLTHROUGH */
16777     case DW_FORM_GNU_strp_alt:
16778       {
16779         struct dwz_file *dwz = dwarf2_get_dwz_file ();
16780         LONGEST str_offset = read_offset (abfd, info_ptr, cu_header,
16781                                           &bytes_read);
16782
16783         DW_STRING (attr) = read_indirect_string_from_dwz (dwz, str_offset);
16784         DW_STRING_IS_CANONICAL (attr) = 0;
16785         info_ptr += bytes_read;
16786       }
16787       break;
16788     case DW_FORM_exprloc:
16789     case DW_FORM_block:
16790       blk = dwarf_alloc_block (cu);
16791       blk->size = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
16792       info_ptr += bytes_read;
16793       blk->data = read_n_bytes (abfd, info_ptr, blk->size);
16794       info_ptr += blk->size;
16795       DW_BLOCK (attr) = blk;
16796       break;
16797     case DW_FORM_block1:
16798       blk = dwarf_alloc_block (cu);
16799       blk->size = read_1_byte (abfd, info_ptr);
16800       info_ptr += 1;
16801       blk->data = read_n_bytes (abfd, info_ptr, blk->size);
16802       info_ptr += blk->size;
16803       DW_BLOCK (attr) = blk;
16804       break;
16805     case DW_FORM_data1:
16806       DW_UNSND (attr) = read_1_byte (abfd, info_ptr);
16807       info_ptr += 1;
16808       break;
16809     case DW_FORM_flag:
16810       DW_UNSND (attr) = read_1_byte (abfd, info_ptr);
16811       info_ptr += 1;
16812       break;
16813     case DW_FORM_flag_present:
16814       DW_UNSND (attr) = 1;
16815       break;
16816     case DW_FORM_sdata:
16817       DW_SND (attr) = read_signed_leb128 (abfd, info_ptr, &bytes_read);
16818       info_ptr += bytes_read;
16819       break;
16820     case DW_FORM_udata:
16821       DW_UNSND (attr) = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
16822       info_ptr += bytes_read;
16823       break;
16824     case DW_FORM_ref1:
16825       DW_UNSND (attr) = (to_underlying (cu->header.sect_off)
16826                          + read_1_byte (abfd, info_ptr));
16827       info_ptr += 1;
16828       break;
16829     case DW_FORM_ref2:
16830       DW_UNSND (attr) = (to_underlying (cu->header.sect_off)
16831                          + read_2_bytes (abfd, info_ptr));
16832       info_ptr += 2;
16833       break;
16834     case DW_FORM_ref4:
16835       DW_UNSND (attr) = (to_underlying (cu->header.sect_off)
16836                          + read_4_bytes (abfd, info_ptr));
16837       info_ptr += 4;
16838       break;
16839     case DW_FORM_ref8:
16840       DW_UNSND (attr) = (to_underlying (cu->header.sect_off)
16841                          + read_8_bytes (abfd, info_ptr));
16842       info_ptr += 8;
16843       break;
16844     case DW_FORM_ref_sig8:
16845       DW_SIGNATURE (attr) = read_8_bytes (abfd, info_ptr);
16846       info_ptr += 8;
16847       break;
16848     case DW_FORM_ref_udata:
16849       DW_UNSND (attr) = (to_underlying (cu->header.sect_off)
16850                          + read_unsigned_leb128 (abfd, info_ptr, &bytes_read));
16851       info_ptr += bytes_read;
16852       break;
16853     case DW_FORM_indirect:
16854       form = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
16855       info_ptr += bytes_read;
16856       if (form == DW_FORM_implicit_const)
16857         {
16858           implicit_const = read_signed_leb128 (abfd, info_ptr, &bytes_read);
16859           info_ptr += bytes_read;
16860         }
16861       info_ptr = read_attribute_value (reader, attr, form, implicit_const,
16862                                        info_ptr);
16863       break;
16864     case DW_FORM_implicit_const:
16865       DW_SND (attr) = implicit_const;
16866       break;
16867     case DW_FORM_GNU_addr_index:
16868       if (reader->dwo_file == NULL)
16869         {
16870           /* For now flag a hard error.
16871              Later we can turn this into a complaint.  */
16872           error (_("Dwarf Error: %s found in non-DWO CU [in module %s]"),
16873                  dwarf_form_name (form),
16874                  bfd_get_filename (abfd));
16875         }
16876       DW_ADDR (attr) = read_addr_index_from_leb128 (cu, info_ptr, &bytes_read);
16877       info_ptr += bytes_read;
16878       break;
16879     case DW_FORM_GNU_str_index:
16880       if (reader->dwo_file == NULL)
16881         {
16882           /* For now flag a hard error.
16883              Later we can turn this into a complaint if warranted.  */
16884           error (_("Dwarf Error: %s found in non-DWO CU [in module %s]"),
16885                  dwarf_form_name (form),
16886                  bfd_get_filename (abfd));
16887         }
16888       {
16889         ULONGEST str_index =
16890           read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
16891
16892         DW_STRING (attr) = read_str_index (reader, str_index);
16893         DW_STRING_IS_CANONICAL (attr) = 0;
16894         info_ptr += bytes_read;
16895       }
16896       break;
16897     default:
16898       error (_("Dwarf Error: Cannot handle %s in DWARF reader [in module %s]"),
16899              dwarf_form_name (form),
16900              bfd_get_filename (abfd));
16901     }
16902
16903   /* Super hack.  */
16904   if (cu->per_cu->is_dwz && attr_form_is_ref (attr))
16905     attr->form = DW_FORM_GNU_ref_alt;
16906
16907   /* We have seen instances where the compiler tried to emit a byte
16908      size attribute of -1 which ended up being encoded as an unsigned
16909      0xffffffff.  Although 0xffffffff is technically a valid size value,
16910      an object of this size seems pretty unlikely so we can relatively
16911      safely treat these cases as if the size attribute was invalid and
16912      treat them as zero by default.  */
16913   if (attr->name == DW_AT_byte_size
16914       && form == DW_FORM_data4
16915       && DW_UNSND (attr) >= 0xffffffff)
16916     {
16917       complaint
16918         (&symfile_complaints,
16919          _("Suspicious DW_AT_byte_size value treated as zero instead of %s"),
16920          hex_string (DW_UNSND (attr)));
16921       DW_UNSND (attr) = 0;
16922     }
16923
16924   return info_ptr;
16925 }
16926
16927 /* Read an attribute described by an abbreviated attribute.  */
16928
16929 static const gdb_byte *
16930 read_attribute (const struct die_reader_specs *reader,
16931                 struct attribute *attr, struct attr_abbrev *abbrev,
16932                 const gdb_byte *info_ptr)
16933 {
16934   attr->name = abbrev->name;
16935   return read_attribute_value (reader, attr, abbrev->form,
16936                                abbrev->implicit_const, info_ptr);
16937 }
16938
16939 /* Read dwarf information from a buffer.  */
16940
16941 static unsigned int
16942 read_1_byte (bfd *abfd, const gdb_byte *buf)
16943 {
16944   return bfd_get_8 (abfd, buf);
16945 }
16946
16947 static int
16948 read_1_signed_byte (bfd *abfd, const gdb_byte *buf)
16949 {
16950   return bfd_get_signed_8 (abfd, buf);
16951 }
16952
16953 static unsigned int
16954 read_2_bytes (bfd *abfd, const gdb_byte *buf)
16955 {
16956   return bfd_get_16 (abfd, buf);
16957 }
16958
16959 static int
16960 read_2_signed_bytes (bfd *abfd, const gdb_byte *buf)
16961 {
16962   return bfd_get_signed_16 (abfd, buf);
16963 }
16964
16965 static unsigned int
16966 read_4_bytes (bfd *abfd, const gdb_byte *buf)
16967 {
16968   return bfd_get_32 (abfd, buf);
16969 }
16970
16971 static int
16972 read_4_signed_bytes (bfd *abfd, const gdb_byte *buf)
16973 {
16974   return bfd_get_signed_32 (abfd, buf);
16975 }
16976
16977 static ULONGEST
16978 read_8_bytes (bfd *abfd, const gdb_byte *buf)
16979 {
16980   return bfd_get_64 (abfd, buf);
16981 }
16982
16983 static CORE_ADDR
16984 read_address (bfd *abfd, const gdb_byte *buf, struct dwarf2_cu *cu,
16985               unsigned int *bytes_read)
16986 {
16987   struct comp_unit_head *cu_header = &cu->header;
16988   CORE_ADDR retval = 0;
16989
16990   if (cu_header->signed_addr_p)
16991     {
16992       switch (cu_header->addr_size)
16993         {
16994         case 2:
16995           retval = bfd_get_signed_16 (abfd, buf);
16996           break;
16997         case 4:
16998           retval = bfd_get_signed_32 (abfd, buf);
16999           break;
17000         case 8:
17001           retval = bfd_get_signed_64 (abfd, buf);
17002           break;
17003         default:
17004           internal_error (__FILE__, __LINE__,
17005                           _("read_address: bad switch, signed [in module %s]"),
17006                           bfd_get_filename (abfd));
17007         }
17008     }
17009   else
17010     {
17011       switch (cu_header->addr_size)
17012         {
17013         case 2:
17014           retval = bfd_get_16 (abfd, buf);
17015           break;
17016         case 4:
17017           retval = bfd_get_32 (abfd, buf);
17018           break;
17019         case 8:
17020           retval = bfd_get_64 (abfd, buf);
17021           break;
17022         default:
17023           internal_error (__FILE__, __LINE__,
17024                           _("read_address: bad switch, "
17025                             "unsigned [in module %s]"),
17026                           bfd_get_filename (abfd));
17027         }
17028     }
17029
17030   *bytes_read = cu_header->addr_size;
17031   return retval;
17032 }
17033
17034 /* Read the initial length from a section.  The (draft) DWARF 3
17035    specification allows the initial length to take up either 4 bytes
17036    or 12 bytes.  If the first 4 bytes are 0xffffffff, then the next 8
17037    bytes describe the length and all offsets will be 8 bytes in length
17038    instead of 4.
17039
17040    An older, non-standard 64-bit format is also handled by this
17041    function.  The older format in question stores the initial length
17042    as an 8-byte quantity without an escape value.  Lengths greater
17043    than 2^32 aren't very common which means that the initial 4 bytes
17044    is almost always zero.  Since a length value of zero doesn't make
17045    sense for the 32-bit format, this initial zero can be considered to
17046    be an escape value which indicates the presence of the older 64-bit
17047    format.  As written, the code can't detect (old format) lengths
17048    greater than 4GB.  If it becomes necessary to handle lengths
17049    somewhat larger than 4GB, we could allow other small values (such
17050    as the non-sensical values of 1, 2, and 3) to also be used as
17051    escape values indicating the presence of the old format.
17052
17053    The value returned via bytes_read should be used to increment the
17054    relevant pointer after calling read_initial_length().
17055
17056    [ Note:  read_initial_length() and read_offset() are based on the
17057      document entitled "DWARF Debugging Information Format", revision
17058      3, draft 8, dated November 19, 2001.  This document was obtained
17059      from:
17060
17061         http://reality.sgiweb.org/davea/dwarf3-draft8-011125.pdf
17062
17063      This document is only a draft and is subject to change.  (So beware.)
17064
17065      Details regarding the older, non-standard 64-bit format were
17066      determined empirically by examining 64-bit ELF files produced by
17067      the SGI toolchain on an IRIX 6.5 machine.
17068
17069      - Kevin, July 16, 2002
17070    ] */
17071
17072 static LONGEST
17073 read_initial_length (bfd *abfd, const gdb_byte *buf, unsigned int *bytes_read)
17074 {
17075   LONGEST length = bfd_get_32 (abfd, buf);
17076
17077   if (length == 0xffffffff)
17078     {
17079       length = bfd_get_64 (abfd, buf + 4);
17080       *bytes_read = 12;
17081     }
17082   else if (length == 0)
17083     {
17084       /* Handle the (non-standard) 64-bit DWARF2 format used by IRIX.  */
17085       length = bfd_get_64 (abfd, buf);
17086       *bytes_read = 8;
17087     }
17088   else
17089     {
17090       *bytes_read = 4;
17091     }
17092
17093   return length;
17094 }
17095
17096 /* Cover function for read_initial_length.
17097    Returns the length of the object at BUF, and stores the size of the
17098    initial length in *BYTES_READ and stores the size that offsets will be in
17099    *OFFSET_SIZE.
17100    If the initial length size is not equivalent to that specified in
17101    CU_HEADER then issue a complaint.
17102    This is useful when reading non-comp-unit headers.  */
17103
17104 static LONGEST
17105 read_checked_initial_length_and_offset (bfd *abfd, const gdb_byte *buf,
17106                                         const struct comp_unit_head *cu_header,
17107                                         unsigned int *bytes_read,
17108                                         unsigned int *offset_size)
17109 {
17110   LONGEST length = read_initial_length (abfd, buf, bytes_read);
17111
17112   gdb_assert (cu_header->initial_length_size == 4
17113               || cu_header->initial_length_size == 8
17114               || cu_header->initial_length_size == 12);
17115
17116   if (cu_header->initial_length_size != *bytes_read)
17117     complaint (&symfile_complaints,
17118                _("intermixed 32-bit and 64-bit DWARF sections"));
17119
17120   *offset_size = (*bytes_read == 4) ? 4 : 8;
17121   return length;
17122 }
17123
17124 /* Read an offset from the data stream.  The size of the offset is
17125    given by cu_header->offset_size.  */
17126
17127 static LONGEST
17128 read_offset (bfd *abfd, const gdb_byte *buf,
17129              const struct comp_unit_head *cu_header,
17130              unsigned int *bytes_read)
17131 {
17132   LONGEST offset = read_offset_1 (abfd, buf, cu_header->offset_size);
17133
17134   *bytes_read = cu_header->offset_size;
17135   return offset;
17136 }
17137
17138 /* Read an offset from the data stream.  */
17139
17140 static LONGEST
17141 read_offset_1 (bfd *abfd, const gdb_byte *buf, unsigned int offset_size)
17142 {
17143   LONGEST retval = 0;
17144
17145   switch (offset_size)
17146     {
17147     case 4:
17148       retval = bfd_get_32 (abfd, buf);
17149       break;
17150     case 8:
17151       retval = bfd_get_64 (abfd, buf);
17152       break;
17153     default:
17154       internal_error (__FILE__, __LINE__,
17155                       _("read_offset_1: bad switch [in module %s]"),
17156                       bfd_get_filename (abfd));
17157     }
17158
17159   return retval;
17160 }
17161
17162 static const gdb_byte *
17163 read_n_bytes (bfd *abfd, const gdb_byte *buf, unsigned int size)
17164 {
17165   /* If the size of a host char is 8 bits, we can return a pointer
17166      to the buffer, otherwise we have to copy the data to a buffer
17167      allocated on the temporary obstack.  */
17168   gdb_assert (HOST_CHAR_BIT == 8);
17169   return buf;
17170 }
17171
17172 static const char *
17173 read_direct_string (bfd *abfd, const gdb_byte *buf,
17174                     unsigned int *bytes_read_ptr)
17175 {
17176   /* If the size of a host char is 8 bits, we can return a pointer
17177      to the string, otherwise we have to copy the string to a buffer
17178      allocated on the temporary obstack.  */
17179   gdb_assert (HOST_CHAR_BIT == 8);
17180   if (*buf == '\0')
17181     {
17182       *bytes_read_ptr = 1;
17183       return NULL;
17184     }
17185   *bytes_read_ptr = strlen ((const char *) buf) + 1;
17186   return (const char *) buf;
17187 }
17188
17189 /* Return pointer to string at section SECT offset STR_OFFSET with error
17190    reporting strings FORM_NAME and SECT_NAME.  */
17191
17192 static const char *
17193 read_indirect_string_at_offset_from (bfd *abfd, LONGEST str_offset,
17194                                      struct dwarf2_section_info *sect,
17195                                      const char *form_name,
17196                                      const char *sect_name)
17197 {
17198   dwarf2_read_section (dwarf2_per_objfile->objfile, sect);
17199   if (sect->buffer == NULL)
17200     error (_("%s used without %s section [in module %s]"),
17201            form_name, sect_name, bfd_get_filename (abfd));
17202   if (str_offset >= sect->size)
17203     error (_("%s pointing outside of %s section [in module %s]"),
17204            form_name, sect_name, bfd_get_filename (abfd));
17205   gdb_assert (HOST_CHAR_BIT == 8);
17206   if (sect->buffer[str_offset] == '\0')
17207     return NULL;
17208   return (const char *) (sect->buffer + str_offset);
17209 }
17210
17211 /* Return pointer to string at .debug_str offset STR_OFFSET.  */
17212
17213 static const char *
17214 read_indirect_string_at_offset (bfd *abfd, LONGEST str_offset)
17215 {
17216   return read_indirect_string_at_offset_from (abfd, str_offset,
17217                                               &dwarf2_per_objfile->str,
17218                                               "DW_FORM_strp", ".debug_str");
17219 }
17220
17221 /* Return pointer to string at .debug_line_str offset STR_OFFSET.  */
17222
17223 static const char *
17224 read_indirect_line_string_at_offset (bfd *abfd, LONGEST str_offset)
17225 {
17226   return read_indirect_string_at_offset_from (abfd, str_offset,
17227                                               &dwarf2_per_objfile->line_str,
17228                                               "DW_FORM_line_strp",
17229                                               ".debug_line_str");
17230 }
17231
17232 /* Read a string at offset STR_OFFSET in the .debug_str section from
17233    the .dwz file DWZ.  Throw an error if the offset is too large.  If
17234    the string consists of a single NUL byte, return NULL; otherwise
17235    return a pointer to the string.  */
17236
17237 static const char *
17238 read_indirect_string_from_dwz (struct dwz_file *dwz, LONGEST str_offset)
17239 {
17240   dwarf2_read_section (dwarf2_per_objfile->objfile, &dwz->str);
17241
17242   if (dwz->str.buffer == NULL)
17243     error (_("DW_FORM_GNU_strp_alt used without .debug_str "
17244              "section [in module %s]"),
17245            bfd_get_filename (dwz->dwz_bfd));
17246   if (str_offset >= dwz->str.size)
17247     error (_("DW_FORM_GNU_strp_alt pointing outside of "
17248              ".debug_str section [in module %s]"),
17249            bfd_get_filename (dwz->dwz_bfd));
17250   gdb_assert (HOST_CHAR_BIT == 8);
17251   if (dwz->str.buffer[str_offset] == '\0')
17252     return NULL;
17253   return (const char *) (dwz->str.buffer + str_offset);
17254 }
17255
17256 /* Return pointer to string at .debug_str offset as read from BUF.
17257    BUF is assumed to be in a compilation unit described by CU_HEADER.
17258    Return *BYTES_READ_PTR count of bytes read from BUF.  */
17259
17260 static const char *
17261 read_indirect_string (bfd *abfd, const gdb_byte *buf,
17262                       const struct comp_unit_head *cu_header,
17263                       unsigned int *bytes_read_ptr)
17264 {
17265   LONGEST str_offset = read_offset (abfd, buf, cu_header, bytes_read_ptr);
17266
17267   return read_indirect_string_at_offset (abfd, str_offset);
17268 }
17269
17270 /* Return pointer to string at .debug_line_str offset as read from BUF.
17271    BUF is assumed to be in a compilation unit described by CU_HEADER.
17272    Return *BYTES_READ_PTR count of bytes read from BUF.  */
17273
17274 static const char *
17275 read_indirect_line_string (bfd *abfd, const gdb_byte *buf,
17276                            const struct comp_unit_head *cu_header,
17277                            unsigned int *bytes_read_ptr)
17278 {
17279   LONGEST str_offset = read_offset (abfd, buf, cu_header, bytes_read_ptr);
17280
17281   return read_indirect_line_string_at_offset (abfd, str_offset);
17282 }
17283
17284 ULONGEST
17285 read_unsigned_leb128 (bfd *abfd, const gdb_byte *buf,
17286                           unsigned int *bytes_read_ptr)
17287 {
17288   ULONGEST result;
17289   unsigned int num_read;
17290   int shift;
17291   unsigned char byte;
17292
17293   result = 0;
17294   shift = 0;
17295   num_read = 0;
17296   while (1)
17297     {
17298       byte = bfd_get_8 (abfd, buf);
17299       buf++;
17300       num_read++;
17301       result |= ((ULONGEST) (byte & 127) << shift);
17302       if ((byte & 128) == 0)
17303         {
17304           break;
17305         }
17306       shift += 7;
17307     }
17308   *bytes_read_ptr = num_read;
17309   return result;
17310 }
17311
17312 static LONGEST
17313 read_signed_leb128 (bfd *abfd, const gdb_byte *buf,
17314                     unsigned int *bytes_read_ptr)
17315 {
17316   LONGEST result;
17317   int shift, num_read;
17318   unsigned char byte;
17319
17320   result = 0;
17321   shift = 0;
17322   num_read = 0;
17323   while (1)
17324     {
17325       byte = bfd_get_8 (abfd, buf);
17326       buf++;
17327       num_read++;
17328       result |= ((LONGEST) (byte & 127) << shift);
17329       shift += 7;
17330       if ((byte & 128) == 0)
17331         {
17332           break;
17333         }
17334     }
17335   if ((shift < 8 * sizeof (result)) && (byte & 0x40))
17336     result |= -(((LONGEST) 1) << shift);
17337   *bytes_read_ptr = num_read;
17338   return result;
17339 }
17340
17341 /* Given index ADDR_INDEX in .debug_addr, fetch the value.
17342    ADDR_BASE is the DW_AT_GNU_addr_base attribute or zero.
17343    ADDR_SIZE is the size of addresses from the CU header.  */
17344
17345 static CORE_ADDR
17346 read_addr_index_1 (unsigned int addr_index, ULONGEST addr_base, int addr_size)
17347 {
17348   struct objfile *objfile = dwarf2_per_objfile->objfile;
17349   bfd *abfd = objfile->obfd;
17350   const gdb_byte *info_ptr;
17351
17352   dwarf2_read_section (objfile, &dwarf2_per_objfile->addr);
17353   if (dwarf2_per_objfile->addr.buffer == NULL)
17354     error (_("DW_FORM_addr_index used without .debug_addr section [in module %s]"),
17355            objfile_name (objfile));
17356   if (addr_base + addr_index * addr_size >= dwarf2_per_objfile->addr.size)
17357     error (_("DW_FORM_addr_index pointing outside of "
17358              ".debug_addr section [in module %s]"),
17359            objfile_name (objfile));
17360   info_ptr = (dwarf2_per_objfile->addr.buffer
17361               + addr_base + addr_index * addr_size);
17362   if (addr_size == 4)
17363     return bfd_get_32 (abfd, info_ptr);
17364   else
17365     return bfd_get_64 (abfd, info_ptr);
17366 }
17367
17368 /* Given index ADDR_INDEX in .debug_addr, fetch the value.  */
17369
17370 static CORE_ADDR
17371 read_addr_index (struct dwarf2_cu *cu, unsigned int addr_index)
17372 {
17373   return read_addr_index_1 (addr_index, cu->addr_base, cu->header.addr_size);
17374 }
17375
17376 /* Given a pointer to an leb128 value, fetch the value from .debug_addr.  */
17377
17378 static CORE_ADDR
17379 read_addr_index_from_leb128 (struct dwarf2_cu *cu, const gdb_byte *info_ptr,
17380                              unsigned int *bytes_read)
17381 {
17382   bfd *abfd = cu->objfile->obfd;
17383   unsigned int addr_index = read_unsigned_leb128 (abfd, info_ptr, bytes_read);
17384
17385   return read_addr_index (cu, addr_index);
17386 }
17387
17388 /* Data structure to pass results from dwarf2_read_addr_index_reader
17389    back to dwarf2_read_addr_index.  */
17390
17391 struct dwarf2_read_addr_index_data
17392 {
17393   ULONGEST addr_base;
17394   int addr_size;
17395 };
17396
17397 /* die_reader_func for dwarf2_read_addr_index.  */
17398
17399 static void
17400 dwarf2_read_addr_index_reader (const struct die_reader_specs *reader,
17401                                const gdb_byte *info_ptr,
17402                                struct die_info *comp_unit_die,
17403                                int has_children,
17404                                void *data)
17405 {
17406   struct dwarf2_cu *cu = reader->cu;
17407   struct dwarf2_read_addr_index_data *aidata =
17408     (struct dwarf2_read_addr_index_data *) data;
17409
17410   aidata->addr_base = cu->addr_base;
17411   aidata->addr_size = cu->header.addr_size;
17412 }
17413
17414 /* Given an index in .debug_addr, fetch the value.
17415    NOTE: This can be called during dwarf expression evaluation,
17416    long after the debug information has been read, and thus per_cu->cu
17417    may no longer exist.  */
17418
17419 CORE_ADDR
17420 dwarf2_read_addr_index (struct dwarf2_per_cu_data *per_cu,
17421                         unsigned int addr_index)
17422 {
17423   struct objfile *objfile = per_cu->objfile;
17424   struct dwarf2_cu *cu = per_cu->cu;
17425   ULONGEST addr_base;
17426   int addr_size;
17427
17428   /* This is intended to be called from outside this file.  */
17429   dw2_setup (objfile);
17430
17431   /* We need addr_base and addr_size.
17432      If we don't have PER_CU->cu, we have to get it.
17433      Nasty, but the alternative is storing the needed info in PER_CU,
17434      which at this point doesn't seem justified: it's not clear how frequently
17435      it would get used and it would increase the size of every PER_CU.
17436      Entry points like dwarf2_per_cu_addr_size do a similar thing
17437      so we're not in uncharted territory here.
17438      Alas we need to be a bit more complicated as addr_base is contained
17439      in the DIE.
17440
17441      We don't need to read the entire CU(/TU).
17442      We just need the header and top level die.
17443
17444      IWBN to use the aging mechanism to let us lazily later discard the CU.
17445      For now we skip this optimization.  */
17446
17447   if (cu != NULL)
17448     {
17449       addr_base = cu->addr_base;
17450       addr_size = cu->header.addr_size;
17451     }
17452   else
17453     {
17454       struct dwarf2_read_addr_index_data aidata;
17455
17456       /* Note: We can't use init_cutu_and_read_dies_simple here,
17457          we need addr_base.  */
17458       init_cutu_and_read_dies (per_cu, NULL, 0, 0,
17459                                dwarf2_read_addr_index_reader, &aidata);
17460       addr_base = aidata.addr_base;
17461       addr_size = aidata.addr_size;
17462     }
17463
17464   return read_addr_index_1 (addr_index, addr_base, addr_size);
17465 }
17466
17467 /* Given a DW_FORM_GNU_str_index, fetch the string.
17468    This is only used by the Fission support.  */
17469
17470 static const char *
17471 read_str_index (const struct die_reader_specs *reader, ULONGEST str_index)
17472 {
17473   struct objfile *objfile = dwarf2_per_objfile->objfile;
17474   const char *objf_name = objfile_name (objfile);
17475   bfd *abfd = objfile->obfd;
17476   struct dwarf2_cu *cu = reader->cu;
17477   struct dwarf2_section_info *str_section = &reader->dwo_file->sections.str;
17478   struct dwarf2_section_info *str_offsets_section =
17479     &reader->dwo_file->sections.str_offsets;
17480   const gdb_byte *info_ptr;
17481   ULONGEST str_offset;
17482   static const char form_name[] = "DW_FORM_GNU_str_index";
17483
17484   dwarf2_read_section (objfile, str_section);
17485   dwarf2_read_section (objfile, str_offsets_section);
17486   if (str_section->buffer == NULL)
17487     error (_("%s used without .debug_str.dwo section"
17488              " in CU at offset 0x%x [in module %s]"),
17489            form_name, to_underlying (cu->header.sect_off), objf_name);
17490   if (str_offsets_section->buffer == NULL)
17491     error (_("%s used without .debug_str_offsets.dwo section"
17492              " in CU at offset 0x%x [in module %s]"),
17493            form_name, to_underlying (cu->header.sect_off), objf_name);
17494   if (str_index * cu->header.offset_size >= str_offsets_section->size)
17495     error (_("%s pointing outside of .debug_str_offsets.dwo"
17496              " section in CU at offset 0x%x [in module %s]"),
17497            form_name, to_underlying (cu->header.sect_off), objf_name);
17498   info_ptr = (str_offsets_section->buffer
17499               + str_index * cu->header.offset_size);
17500   if (cu->header.offset_size == 4)
17501     str_offset = bfd_get_32 (abfd, info_ptr);
17502   else
17503     str_offset = bfd_get_64 (abfd, info_ptr);
17504   if (str_offset >= str_section->size)
17505     error (_("Offset from %s pointing outside of"
17506              " .debug_str.dwo section in CU at offset 0x%x [in module %s]"),
17507            form_name, to_underlying (cu->header.sect_off), objf_name);
17508   return (const char *) (str_section->buffer + str_offset);
17509 }
17510
17511 /* Return the length of an LEB128 number in BUF.  */
17512
17513 static int
17514 leb128_size (const gdb_byte *buf)
17515 {
17516   const gdb_byte *begin = buf;
17517   gdb_byte byte;
17518
17519   while (1)
17520     {
17521       byte = *buf++;
17522       if ((byte & 128) == 0)
17523         return buf - begin;
17524     }
17525 }
17526
17527 static void
17528 set_cu_language (unsigned int lang, struct dwarf2_cu *cu)
17529 {
17530   switch (lang)
17531     {
17532     case DW_LANG_C89:
17533     case DW_LANG_C99:
17534     case DW_LANG_C11:
17535     case DW_LANG_C:
17536     case DW_LANG_UPC:
17537       cu->language = language_c;
17538       break;
17539     case DW_LANG_Java:
17540     case DW_LANG_C_plus_plus:
17541     case DW_LANG_C_plus_plus_11:
17542     case DW_LANG_C_plus_plus_14:
17543       cu->language = language_cplus;
17544       break;
17545     case DW_LANG_D:
17546       cu->language = language_d;
17547       break;
17548     case DW_LANG_Fortran77:
17549     case DW_LANG_Fortran90:
17550     case DW_LANG_Fortran95:
17551     case DW_LANG_Fortran03:
17552     case DW_LANG_Fortran08:
17553       cu->language = language_fortran;
17554       break;
17555     case DW_LANG_Go:
17556       cu->language = language_go;
17557       break;
17558     case DW_LANG_Mips_Assembler:
17559       cu->language = language_asm;
17560       break;
17561     case DW_LANG_Ada83:
17562     case DW_LANG_Ada95:
17563       cu->language = language_ada;
17564       break;
17565     case DW_LANG_Modula2:
17566       cu->language = language_m2;
17567       break;
17568     case DW_LANG_Pascal83:
17569       cu->language = language_pascal;
17570       break;
17571     case DW_LANG_ObjC:
17572       cu->language = language_objc;
17573       break;
17574     case DW_LANG_Rust:
17575     case DW_LANG_Rust_old:
17576       cu->language = language_rust;
17577       break;
17578     case DW_LANG_Cobol74:
17579     case DW_LANG_Cobol85:
17580     default:
17581       cu->language = language_minimal;
17582       break;
17583     }
17584   cu->language_defn = language_def (cu->language);
17585 }
17586
17587 /* Return the named attribute or NULL if not there.  */
17588
17589 static struct attribute *
17590 dwarf2_attr (struct die_info *die, unsigned int name, struct dwarf2_cu *cu)
17591 {
17592   for (;;)
17593     {
17594       unsigned int i;
17595       struct attribute *spec = NULL;
17596
17597       for (i = 0; i < die->num_attrs; ++i)
17598         {
17599           if (die->attrs[i].name == name)
17600             return &die->attrs[i];
17601           if (die->attrs[i].name == DW_AT_specification
17602               || die->attrs[i].name == DW_AT_abstract_origin)
17603             spec = &die->attrs[i];
17604         }
17605
17606       if (!spec)
17607         break;
17608
17609       die = follow_die_ref (die, spec, &cu);
17610     }
17611
17612   return NULL;
17613 }
17614
17615 /* Return the named attribute or NULL if not there,
17616    but do not follow DW_AT_specification, etc.
17617    This is for use in contexts where we're reading .debug_types dies.
17618    Following DW_AT_specification, DW_AT_abstract_origin will take us
17619    back up the chain, and we want to go down.  */
17620
17621 static struct attribute *
17622 dwarf2_attr_no_follow (struct die_info *die, unsigned int name)
17623 {
17624   unsigned int i;
17625
17626   for (i = 0; i < die->num_attrs; ++i)
17627     if (die->attrs[i].name == name)
17628       return &die->attrs[i];
17629
17630   return NULL;
17631 }
17632
17633 /* Return the string associated with a string-typed attribute, or NULL if it
17634    is either not found or is of an incorrect type.  */
17635
17636 static const char *
17637 dwarf2_string_attr (struct die_info *die, unsigned int name, struct dwarf2_cu *cu)
17638 {
17639   struct attribute *attr;
17640   const char *str = NULL;
17641
17642   attr = dwarf2_attr (die, name, cu);
17643
17644   if (attr != NULL)
17645     {
17646       if (attr->form == DW_FORM_strp || attr->form == DW_FORM_line_strp
17647           || attr->form == DW_FORM_string
17648           || attr->form == DW_FORM_GNU_str_index
17649           || attr->form == DW_FORM_GNU_strp_alt)
17650         str = DW_STRING (attr);
17651       else
17652         complaint (&symfile_complaints,
17653                    _("string type expected for attribute %s for "
17654                      "DIE at 0x%x in module %s"),
17655                    dwarf_attr_name (name), to_underlying (die->sect_off),
17656                    objfile_name (cu->objfile));
17657     }
17658
17659   return str;
17660 }
17661
17662 /* Return non-zero iff the attribute NAME is defined for the given DIE,
17663    and holds a non-zero value.  This function should only be used for
17664    DW_FORM_flag or DW_FORM_flag_present attributes.  */
17665
17666 static int
17667 dwarf2_flag_true_p (struct die_info *die, unsigned name, struct dwarf2_cu *cu)
17668 {
17669   struct attribute *attr = dwarf2_attr (die, name, cu);
17670
17671   return (attr && DW_UNSND (attr));
17672 }
17673
17674 static int
17675 die_is_declaration (struct die_info *die, struct dwarf2_cu *cu)
17676 {
17677   /* A DIE is a declaration if it has a DW_AT_declaration attribute
17678      which value is non-zero.  However, we have to be careful with
17679      DIEs having a DW_AT_specification attribute, because dwarf2_attr()
17680      (via dwarf2_flag_true_p) follows this attribute.  So we may
17681      end up accidently finding a declaration attribute that belongs
17682      to a different DIE referenced by the specification attribute,
17683      even though the given DIE does not have a declaration attribute.  */
17684   return (dwarf2_flag_true_p (die, DW_AT_declaration, cu)
17685           && dwarf2_attr (die, DW_AT_specification, cu) == NULL);
17686 }
17687
17688 /* Return the die giving the specification for DIE, if there is
17689    one.  *SPEC_CU is the CU containing DIE on input, and the CU
17690    containing the return value on output.  If there is no
17691    specification, but there is an abstract origin, that is
17692    returned.  */
17693
17694 static struct die_info *
17695 die_specification (struct die_info *die, struct dwarf2_cu **spec_cu)
17696 {
17697   struct attribute *spec_attr = dwarf2_attr (die, DW_AT_specification,
17698                                              *spec_cu);
17699
17700   if (spec_attr == NULL)
17701     spec_attr = dwarf2_attr (die, DW_AT_abstract_origin, *spec_cu);
17702
17703   if (spec_attr == NULL)
17704     return NULL;
17705   else
17706     return follow_die_ref (die, spec_attr, spec_cu);
17707 }
17708
17709 /* Stub for free_line_header to match void * callback types.  */
17710
17711 static void
17712 free_line_header_voidp (void *arg)
17713 {
17714   struct line_header *lh = (struct line_header *) arg;
17715
17716   delete lh;
17717 }
17718
17719 void
17720 line_header::add_include_dir (const char *include_dir)
17721 {
17722   if (dwarf_line_debug >= 2)
17723     fprintf_unfiltered (gdb_stdlog, "Adding dir %zu: %s\n",
17724                         include_dirs.size () + 1, include_dir);
17725
17726   include_dirs.push_back (include_dir);
17727 }
17728
17729 void
17730 line_header::add_file_name (const char *name,
17731                             dir_index d_index,
17732                             unsigned int mod_time,
17733                             unsigned int length)
17734 {
17735   if (dwarf_line_debug >= 2)
17736     fprintf_unfiltered (gdb_stdlog, "Adding file %u: %s\n",
17737                         (unsigned) file_names.size () + 1, name);
17738
17739   file_names.emplace_back (name, d_index, mod_time, length);
17740 }
17741
17742 /* A convenience function to find the proper .debug_line section for a CU.  */
17743
17744 static struct dwarf2_section_info *
17745 get_debug_line_section (struct dwarf2_cu *cu)
17746 {
17747   struct dwarf2_section_info *section;
17748
17749   /* For TUs in DWO files, the DW_AT_stmt_list attribute lives in the
17750      DWO file.  */
17751   if (cu->dwo_unit && cu->per_cu->is_debug_types)
17752     section = &cu->dwo_unit->dwo_file->sections.line;
17753   else if (cu->per_cu->is_dwz)
17754     {
17755       struct dwz_file *dwz = dwarf2_get_dwz_file ();
17756
17757       section = &dwz->line;
17758     }
17759   else
17760     section = &dwarf2_per_objfile->line;
17761
17762   return section;
17763 }
17764
17765 /* Read directory or file name entry format, starting with byte of
17766    format count entries, ULEB128 pairs of entry formats, ULEB128 of
17767    entries count and the entries themselves in the described entry
17768    format.  */
17769
17770 static void
17771 read_formatted_entries (bfd *abfd, const gdb_byte **bufp,
17772                         struct line_header *lh,
17773                         const struct comp_unit_head *cu_header,
17774                         void (*callback) (struct line_header *lh,
17775                                           const char *name,
17776                                           dir_index d_index,
17777                                           unsigned int mod_time,
17778                                           unsigned int length))
17779 {
17780   gdb_byte format_count, formati;
17781   ULONGEST data_count, datai;
17782   const gdb_byte *buf = *bufp;
17783   const gdb_byte *format_header_data;
17784   int i;
17785   unsigned int bytes_read;
17786
17787   format_count = read_1_byte (abfd, buf);
17788   buf += 1;
17789   format_header_data = buf;
17790   for (formati = 0; formati < format_count; formati++)
17791     {
17792       read_unsigned_leb128 (abfd, buf, &bytes_read);
17793       buf += bytes_read;
17794       read_unsigned_leb128 (abfd, buf, &bytes_read);
17795       buf += bytes_read;
17796     }
17797
17798   data_count = read_unsigned_leb128 (abfd, buf, &bytes_read);
17799   buf += bytes_read;
17800   for (datai = 0; datai < data_count; datai++)
17801     {
17802       const gdb_byte *format = format_header_data;
17803       struct file_entry fe;
17804
17805       for (formati = 0; formati < format_count; formati++)
17806         {
17807           ULONGEST content_type = read_unsigned_leb128 (abfd, format, &bytes_read);
17808           format += bytes_read;
17809
17810           ULONGEST form  = read_unsigned_leb128 (abfd, format, &bytes_read);
17811           format += bytes_read;
17812
17813           gdb::optional<const char *> string;
17814           gdb::optional<unsigned int> uint;
17815
17816           switch (form)
17817             {
17818             case DW_FORM_string:
17819               string.emplace (read_direct_string (abfd, buf, &bytes_read));
17820               buf += bytes_read;
17821               break;
17822
17823             case DW_FORM_line_strp:
17824               string.emplace (read_indirect_line_string (abfd, buf,
17825                                                          cu_header,
17826                                                          &bytes_read));
17827               buf += bytes_read;
17828               break;
17829
17830             case DW_FORM_data1:
17831               uint.emplace (read_1_byte (abfd, buf));
17832               buf += 1;
17833               break;
17834
17835             case DW_FORM_data2:
17836               uint.emplace (read_2_bytes (abfd, buf));
17837               buf += 2;
17838               break;
17839
17840             case DW_FORM_data4:
17841               uint.emplace (read_4_bytes (abfd, buf));
17842               buf += 4;
17843               break;
17844
17845             case DW_FORM_data8:
17846               uint.emplace (read_8_bytes (abfd, buf));
17847               buf += 8;
17848               break;
17849
17850             case DW_FORM_udata:
17851               uint.emplace (read_unsigned_leb128 (abfd, buf, &bytes_read));
17852               buf += bytes_read;
17853               break;
17854
17855             case DW_FORM_block:
17856               /* It is valid only for DW_LNCT_timestamp which is ignored by
17857                  current GDB.  */
17858               break;
17859             }
17860
17861           switch (content_type)
17862             {
17863             case DW_LNCT_path:
17864               if (string.has_value ())
17865                 fe.name = *string;
17866               break;
17867             case DW_LNCT_directory_index:
17868               if (uint.has_value ())
17869                 fe.d_index = (dir_index) *uint;
17870               break;
17871             case DW_LNCT_timestamp:
17872               if (uint.has_value ())
17873                 fe.mod_time = *uint;
17874               break;
17875             case DW_LNCT_size:
17876               if (uint.has_value ())
17877                 fe.length = *uint;
17878               break;
17879             case DW_LNCT_MD5:
17880               break;
17881             default:
17882               complaint (&symfile_complaints,
17883                          _("Unknown format content type %s"),
17884                          pulongest (content_type));
17885             }
17886         }
17887
17888       callback (lh, fe.name, fe.d_index, fe.mod_time, fe.length);
17889     }
17890
17891   *bufp = buf;
17892 }
17893
17894 /* Read the statement program header starting at OFFSET in
17895    .debug_line, or .debug_line.dwo.  Return a pointer
17896    to a struct line_header, allocated using xmalloc.
17897    Returns NULL if there is a problem reading the header, e.g., if it
17898    has a version we don't understand.
17899
17900    NOTE: the strings in the include directory and file name tables of
17901    the returned object point into the dwarf line section buffer,
17902    and must not be freed.  */
17903
17904 static line_header_up
17905 dwarf_decode_line_header (sect_offset sect_off, struct dwarf2_cu *cu)
17906 {
17907   const gdb_byte *line_ptr;
17908   unsigned int bytes_read, offset_size;
17909   int i;
17910   const char *cur_dir, *cur_file;
17911   struct dwarf2_section_info *section;
17912   bfd *abfd;
17913
17914   section = get_debug_line_section (cu);
17915   dwarf2_read_section (dwarf2_per_objfile->objfile, section);
17916   if (section->buffer == NULL)
17917     {
17918       if (cu->dwo_unit && cu->per_cu->is_debug_types)
17919         complaint (&symfile_complaints, _("missing .debug_line.dwo section"));
17920       else
17921         complaint (&symfile_complaints, _("missing .debug_line section"));
17922       return 0;
17923     }
17924
17925   /* We can't do this until we know the section is non-empty.
17926      Only then do we know we have such a section.  */
17927   abfd = get_section_bfd_owner (section);
17928
17929   /* Make sure that at least there's room for the total_length field.
17930      That could be 12 bytes long, but we're just going to fudge that.  */
17931   if (to_underlying (sect_off) + 4 >= section->size)
17932     {
17933       dwarf2_statement_list_fits_in_line_number_section_complaint ();
17934       return 0;
17935     }
17936
17937   line_header_up lh (new line_header ());
17938
17939   lh->sect_off = sect_off;
17940   lh->offset_in_dwz = cu->per_cu->is_dwz;
17941
17942   line_ptr = section->buffer + to_underlying (sect_off);
17943
17944   /* Read in the header.  */
17945   lh->total_length =
17946     read_checked_initial_length_and_offset (abfd, line_ptr, &cu->header,
17947                                             &bytes_read, &offset_size);
17948   line_ptr += bytes_read;
17949   if (line_ptr + lh->total_length > (section->buffer + section->size))
17950     {
17951       dwarf2_statement_list_fits_in_line_number_section_complaint ();
17952       return 0;
17953     }
17954   lh->statement_program_end = line_ptr + lh->total_length;
17955   lh->version = read_2_bytes (abfd, line_ptr);
17956   line_ptr += 2;
17957   if (lh->version > 5)
17958     {
17959       /* This is a version we don't understand.  The format could have
17960          changed in ways we don't handle properly so just punt.  */
17961       complaint (&symfile_complaints,
17962                  _("unsupported version in .debug_line section"));
17963       return NULL;
17964     }
17965   if (lh->version >= 5)
17966     {
17967       gdb_byte segment_selector_size;
17968
17969       /* Skip address size.  */
17970       read_1_byte (abfd, line_ptr);
17971       line_ptr += 1;
17972
17973       segment_selector_size = read_1_byte (abfd, line_ptr);
17974       line_ptr += 1;
17975       if (segment_selector_size != 0)
17976         {
17977           complaint (&symfile_complaints,
17978                      _("unsupported segment selector size %u "
17979                        "in .debug_line section"),
17980                      segment_selector_size);
17981           return NULL;
17982         }
17983     }
17984   lh->header_length = read_offset_1 (abfd, line_ptr, offset_size);
17985   line_ptr += offset_size;
17986   lh->minimum_instruction_length = read_1_byte (abfd, line_ptr);
17987   line_ptr += 1;
17988   if (lh->version >= 4)
17989     {
17990       lh->maximum_ops_per_instruction = read_1_byte (abfd, line_ptr);
17991       line_ptr += 1;
17992     }
17993   else
17994     lh->maximum_ops_per_instruction = 1;
17995
17996   if (lh->maximum_ops_per_instruction == 0)
17997     {
17998       lh->maximum_ops_per_instruction = 1;
17999       complaint (&symfile_complaints,
18000                  _("invalid maximum_ops_per_instruction "
18001                    "in `.debug_line' section"));
18002     }
18003
18004   lh->default_is_stmt = read_1_byte (abfd, line_ptr);
18005   line_ptr += 1;
18006   lh->line_base = read_1_signed_byte (abfd, line_ptr);
18007   line_ptr += 1;
18008   lh->line_range = read_1_byte (abfd, line_ptr);
18009   line_ptr += 1;
18010   lh->opcode_base = read_1_byte (abfd, line_ptr);
18011   line_ptr += 1;
18012   lh->standard_opcode_lengths.reset (new unsigned char[lh->opcode_base]);
18013
18014   lh->standard_opcode_lengths[0] = 1;  /* This should never be used anyway.  */
18015   for (i = 1; i < lh->opcode_base; ++i)
18016     {
18017       lh->standard_opcode_lengths[i] = read_1_byte (abfd, line_ptr);
18018       line_ptr += 1;
18019     }
18020
18021   if (lh->version >= 5)
18022     {
18023       /* Read directory table.  */
18024       read_formatted_entries (abfd, &line_ptr, lh.get (), &cu->header,
18025                               [] (struct line_header *lh, const char *name,
18026                                   dir_index d_index, unsigned int mod_time,
18027                                   unsigned int length)
18028         {
18029           lh->add_include_dir (name);
18030         });
18031
18032       /* Read file name table.  */
18033       read_formatted_entries (abfd, &line_ptr, lh.get (), &cu->header,
18034                               [] (struct line_header *lh, const char *name,
18035                                   dir_index d_index, unsigned int mod_time,
18036                                   unsigned int length)
18037         {
18038           lh->add_file_name (name, d_index, mod_time, length);
18039         });
18040     }
18041   else
18042     {
18043       /* Read directory table.  */
18044       while ((cur_dir = read_direct_string (abfd, line_ptr, &bytes_read)) != NULL)
18045         {
18046           line_ptr += bytes_read;
18047           lh->add_include_dir (cur_dir);
18048         }
18049       line_ptr += bytes_read;
18050
18051       /* Read file name table.  */
18052       while ((cur_file = read_direct_string (abfd, line_ptr, &bytes_read)) != NULL)
18053         {
18054           unsigned int mod_time, length;
18055           dir_index d_index;
18056
18057           line_ptr += bytes_read;
18058           d_index = (dir_index) read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
18059           line_ptr += bytes_read;
18060           mod_time = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
18061           line_ptr += bytes_read;
18062           length = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
18063           line_ptr += bytes_read;
18064
18065           lh->add_file_name (cur_file, d_index, mod_time, length);
18066         }
18067       line_ptr += bytes_read;
18068     }
18069   lh->statement_program_start = line_ptr;
18070
18071   if (line_ptr > (section->buffer + section->size))
18072     complaint (&symfile_complaints,
18073                _("line number info header doesn't "
18074                  "fit in `.debug_line' section"));
18075
18076   return lh;
18077 }
18078
18079 /* Subroutine of dwarf_decode_lines to simplify it.
18080    Return the file name of the psymtab for included file FILE_INDEX
18081    in line header LH of PST.
18082    COMP_DIR is the compilation directory (DW_AT_comp_dir) or NULL if unknown.
18083    If space for the result is malloc'd, it will be freed by a cleanup.
18084    Returns NULL if FILE_INDEX should be ignored, i.e., it is pst->filename.
18085
18086    The function creates dangling cleanup registration.  */
18087
18088 static const char *
18089 psymtab_include_file_name (const struct line_header *lh, int file_index,
18090                            const struct partial_symtab *pst,
18091                            const char *comp_dir)
18092 {
18093   const file_entry &fe = lh->file_names[file_index];
18094   const char *include_name = fe.name;
18095   const char *include_name_to_compare = include_name;
18096   const char *pst_filename;
18097   char *copied_name = NULL;
18098   int file_is_pst;
18099
18100   const char *dir_name = fe.include_dir (lh);
18101
18102   if (!IS_ABSOLUTE_PATH (include_name)
18103       && (dir_name != NULL || comp_dir != NULL))
18104     {
18105       /* Avoid creating a duplicate psymtab for PST.
18106          We do this by comparing INCLUDE_NAME and PST_FILENAME.
18107          Before we do the comparison, however, we need to account
18108          for DIR_NAME and COMP_DIR.
18109          First prepend dir_name (if non-NULL).  If we still don't
18110          have an absolute path prepend comp_dir (if non-NULL).
18111          However, the directory we record in the include-file's
18112          psymtab does not contain COMP_DIR (to match the
18113          corresponding symtab(s)).
18114
18115          Example:
18116
18117          bash$ cd /tmp
18118          bash$ gcc -g ./hello.c
18119          include_name = "hello.c"
18120          dir_name = "."
18121          DW_AT_comp_dir = comp_dir = "/tmp"
18122          DW_AT_name = "./hello.c"
18123
18124       */
18125
18126       if (dir_name != NULL)
18127         {
18128           char *tem = concat (dir_name, SLASH_STRING,
18129                               include_name, (char *)NULL);
18130
18131           make_cleanup (xfree, tem);
18132           include_name = tem;
18133           include_name_to_compare = include_name;
18134         }
18135       if (!IS_ABSOLUTE_PATH (include_name) && comp_dir != NULL)
18136         {
18137           char *tem = concat (comp_dir, SLASH_STRING,
18138                               include_name, (char *)NULL);
18139
18140           make_cleanup (xfree, tem);
18141           include_name_to_compare = tem;
18142         }
18143     }
18144
18145   pst_filename = pst->filename;
18146   if (!IS_ABSOLUTE_PATH (pst_filename) && pst->dirname != NULL)
18147     {
18148       copied_name = concat (pst->dirname, SLASH_STRING,
18149                             pst_filename, (char *)NULL);
18150       pst_filename = copied_name;
18151     }
18152
18153   file_is_pst = FILENAME_CMP (include_name_to_compare, pst_filename) == 0;
18154
18155   if (copied_name != NULL)
18156     xfree (copied_name);
18157
18158   if (file_is_pst)
18159     return NULL;
18160   return include_name;
18161 }
18162
18163 /* State machine to track the state of the line number program.  */
18164
18165 class lnp_state_machine
18166 {
18167 public:
18168   /* Initialize a machine state for the start of a line number
18169      program.  */
18170   lnp_state_machine (gdbarch *arch, line_header *lh, bool record_lines_p);
18171
18172   file_entry *current_file ()
18173   {
18174     /* lh->file_names is 0-based, but the file name numbers in the
18175        statement program are 1-based.  */
18176     return m_line_header->file_name_at (m_file);
18177   }
18178
18179   /* Record the line in the state machine.  END_SEQUENCE is true if
18180      we're processing the end of a sequence.  */
18181   void record_line (bool end_sequence);
18182
18183   /* Check address and if invalid nop-out the rest of the lines in this
18184      sequence.  */
18185   void check_line_address (struct dwarf2_cu *cu,
18186                            const gdb_byte *line_ptr,
18187                            CORE_ADDR lowpc, CORE_ADDR address);
18188
18189   void handle_set_discriminator (unsigned int discriminator)
18190   {
18191     m_discriminator = discriminator;
18192     m_line_has_non_zero_discriminator |= discriminator != 0;
18193   }
18194
18195   /* Handle DW_LNE_set_address.  */
18196   void handle_set_address (CORE_ADDR baseaddr, CORE_ADDR address)
18197   {
18198     m_op_index = 0;
18199     address += baseaddr;
18200     m_address = gdbarch_adjust_dwarf2_line (m_gdbarch, address, false);
18201   }
18202
18203   /* Handle DW_LNS_advance_pc.  */
18204   void handle_advance_pc (CORE_ADDR adjust);
18205
18206   /* Handle a special opcode.  */
18207   void handle_special_opcode (unsigned char op_code);
18208
18209   /* Handle DW_LNS_advance_line.  */
18210   void handle_advance_line (int line_delta)
18211   {
18212     advance_line (line_delta);
18213   }
18214
18215   /* Handle DW_LNS_set_file.  */
18216   void handle_set_file (file_name_index file);
18217
18218   /* Handle DW_LNS_negate_stmt.  */
18219   void handle_negate_stmt ()
18220   {
18221     m_is_stmt = !m_is_stmt;
18222   }
18223
18224   /* Handle DW_LNS_const_add_pc.  */
18225   void handle_const_add_pc ();
18226
18227   /* Handle DW_LNS_fixed_advance_pc.  */
18228   void handle_fixed_advance_pc (CORE_ADDR addr_adj)
18229   {
18230     m_address += gdbarch_adjust_dwarf2_line (m_gdbarch, addr_adj, true);
18231     m_op_index = 0;
18232   }
18233
18234   /* Handle DW_LNS_copy.  */
18235   void handle_copy ()
18236   {
18237     record_line (false);
18238     m_discriminator = 0;
18239   }
18240
18241   /* Handle DW_LNE_end_sequence.  */
18242   void handle_end_sequence ()
18243   {
18244     m_record_line_callback = ::record_line;
18245   }
18246
18247 private:
18248   /* Advance the line by LINE_DELTA.  */
18249   void advance_line (int line_delta)
18250   {
18251     m_line += line_delta;
18252
18253     if (line_delta != 0)
18254       m_line_has_non_zero_discriminator = m_discriminator != 0;
18255   }
18256
18257   gdbarch *m_gdbarch;
18258
18259   /* True if we're recording lines.
18260      Otherwise we're building partial symtabs and are just interested in
18261      finding include files mentioned by the line number program.  */
18262   bool m_record_lines_p;
18263
18264   /* The line number header.  */
18265   line_header *m_line_header;
18266
18267   /* These are part of the standard DWARF line number state machine,
18268      and initialized according to the DWARF spec.  */
18269
18270   unsigned char m_op_index = 0;
18271   /* The line table index (1-based) of the current file.  */
18272   file_name_index m_file = (file_name_index) 1;
18273   unsigned int m_line = 1;
18274
18275   /* These are initialized in the constructor.  */
18276
18277   CORE_ADDR m_address;
18278   bool m_is_stmt;
18279   unsigned int m_discriminator;
18280
18281   /* Additional bits of state we need to track.  */
18282
18283   /* The last file that we called dwarf2_start_subfile for.
18284      This is only used for TLLs.  */
18285   unsigned int m_last_file = 0;
18286   /* The last file a line number was recorded for.  */
18287   struct subfile *m_last_subfile = NULL;
18288
18289   /* The function to call to record a line.  */
18290   record_line_ftype *m_record_line_callback = NULL;
18291
18292   /* The last line number that was recorded, used to coalesce
18293      consecutive entries for the same line.  This can happen, for
18294      example, when discriminators are present.  PR 17276.  */
18295   unsigned int m_last_line = 0;
18296   bool m_line_has_non_zero_discriminator = false;
18297 };
18298
18299 void
18300 lnp_state_machine::handle_advance_pc (CORE_ADDR adjust)
18301 {
18302   CORE_ADDR addr_adj = (((m_op_index + adjust)
18303                          / m_line_header->maximum_ops_per_instruction)
18304                         * m_line_header->minimum_instruction_length);
18305   m_address += gdbarch_adjust_dwarf2_line (m_gdbarch, addr_adj, true);
18306   m_op_index = ((m_op_index + adjust)
18307                 % m_line_header->maximum_ops_per_instruction);
18308 }
18309
18310 void
18311 lnp_state_machine::handle_special_opcode (unsigned char op_code)
18312 {
18313   unsigned char adj_opcode = op_code - m_line_header->opcode_base;
18314   CORE_ADDR addr_adj = (((m_op_index
18315                           + (adj_opcode / m_line_header->line_range))
18316                          / m_line_header->maximum_ops_per_instruction)
18317                         * m_line_header->minimum_instruction_length);
18318   m_address += gdbarch_adjust_dwarf2_line (m_gdbarch, addr_adj, true);
18319   m_op_index = ((m_op_index + (adj_opcode / m_line_header->line_range))
18320                 % m_line_header->maximum_ops_per_instruction);
18321
18322   int line_delta = (m_line_header->line_base
18323                     + (adj_opcode % m_line_header->line_range));
18324   advance_line (line_delta);
18325   record_line (false);
18326   m_discriminator = 0;
18327 }
18328
18329 void
18330 lnp_state_machine::handle_set_file (file_name_index file)
18331 {
18332   m_file = file;
18333
18334   const file_entry *fe = current_file ();
18335   if (fe == NULL)
18336     dwarf2_debug_line_missing_file_complaint ();
18337   else if (m_record_lines_p)
18338     {
18339       const char *dir = fe->include_dir (m_line_header);
18340
18341       m_last_subfile = current_subfile;
18342       m_line_has_non_zero_discriminator = m_discriminator != 0;
18343       dwarf2_start_subfile (fe->name, dir);
18344     }
18345 }
18346
18347 void
18348 lnp_state_machine::handle_const_add_pc ()
18349 {
18350   CORE_ADDR adjust
18351     = (255 - m_line_header->opcode_base) / m_line_header->line_range;
18352
18353   CORE_ADDR addr_adj
18354     = (((m_op_index + adjust)
18355         / m_line_header->maximum_ops_per_instruction)
18356        * m_line_header->minimum_instruction_length);
18357
18358   m_address += gdbarch_adjust_dwarf2_line (m_gdbarch, addr_adj, true);
18359   m_op_index = ((m_op_index + adjust)
18360                 % m_line_header->maximum_ops_per_instruction);
18361 }
18362
18363 /* Ignore this record_line request.  */
18364
18365 static void
18366 noop_record_line (struct subfile *subfile, int line, CORE_ADDR pc)
18367 {
18368   return;
18369 }
18370
18371 /* Return non-zero if we should add LINE to the line number table.
18372    LINE is the line to add, LAST_LINE is the last line that was added,
18373    LAST_SUBFILE is the subfile for LAST_LINE.
18374    LINE_HAS_NON_ZERO_DISCRIMINATOR is non-zero if LINE has ever
18375    had a non-zero discriminator.
18376
18377    We have to be careful in the presence of discriminators.
18378    E.g., for this line:
18379
18380      for (i = 0; i < 100000; i++);
18381
18382    clang can emit four line number entries for that one line,
18383    each with a different discriminator.
18384    See gdb.dwarf2/dw2-single-line-discriminators.exp for an example.
18385
18386    However, we want gdb to coalesce all four entries into one.
18387    Otherwise the user could stepi into the middle of the line and
18388    gdb would get confused about whether the pc really was in the
18389    middle of the line.
18390
18391    Things are further complicated by the fact that two consecutive
18392    line number entries for the same line is a heuristic used by gcc
18393    to denote the end of the prologue.  So we can't just discard duplicate
18394    entries, we have to be selective about it.  The heuristic we use is
18395    that we only collapse consecutive entries for the same line if at least
18396    one of those entries has a non-zero discriminator.  PR 17276.
18397
18398    Note: Addresses in the line number state machine can never go backwards
18399    within one sequence, thus this coalescing is ok.  */
18400
18401 static int
18402 dwarf_record_line_p (unsigned int line, unsigned int last_line,
18403                      int line_has_non_zero_discriminator,
18404                      struct subfile *last_subfile)
18405 {
18406   if (current_subfile != last_subfile)
18407     return 1;
18408   if (line != last_line)
18409     return 1;
18410   /* Same line for the same file that we've seen already.
18411      As a last check, for pr 17276, only record the line if the line
18412      has never had a non-zero discriminator.  */
18413   if (!line_has_non_zero_discriminator)
18414     return 1;
18415   return 0;
18416 }
18417
18418 /* Use P_RECORD_LINE to record line number LINE beginning at address ADDRESS
18419    in the line table of subfile SUBFILE.  */
18420
18421 static void
18422 dwarf_record_line_1 (struct gdbarch *gdbarch, struct subfile *subfile,
18423                      unsigned int line, CORE_ADDR address,
18424                      record_line_ftype p_record_line)
18425 {
18426   CORE_ADDR addr = gdbarch_addr_bits_remove (gdbarch, address);
18427
18428   if (dwarf_line_debug)
18429     {
18430       fprintf_unfiltered (gdb_stdlog,
18431                           "Recording line %u, file %s, address %s\n",
18432                           line, lbasename (subfile->name),
18433                           paddress (gdbarch, address));
18434     }
18435
18436   (*p_record_line) (subfile, line, addr);
18437 }
18438
18439 /* Subroutine of dwarf_decode_lines_1 to simplify it.
18440    Mark the end of a set of line number records.
18441    The arguments are the same as for dwarf_record_line_1.
18442    If SUBFILE is NULL the request is ignored.  */
18443
18444 static void
18445 dwarf_finish_line (struct gdbarch *gdbarch, struct subfile *subfile,
18446                    CORE_ADDR address, record_line_ftype p_record_line)
18447 {
18448   if (subfile == NULL)
18449     return;
18450
18451   if (dwarf_line_debug)
18452     {
18453       fprintf_unfiltered (gdb_stdlog,
18454                           "Finishing current line, file %s, address %s\n",
18455                           lbasename (subfile->name),
18456                           paddress (gdbarch, address));
18457     }
18458
18459   dwarf_record_line_1 (gdbarch, subfile, 0, address, p_record_line);
18460 }
18461
18462 void
18463 lnp_state_machine::record_line (bool end_sequence)
18464 {
18465   if (dwarf_line_debug)
18466     {
18467       fprintf_unfiltered (gdb_stdlog,
18468                           "Processing actual line %u: file %u,"
18469                           " address %s, is_stmt %u, discrim %u\n",
18470                           m_line, to_underlying (m_file),
18471                           paddress (m_gdbarch, m_address),
18472                           m_is_stmt, m_discriminator);
18473     }
18474
18475   file_entry *fe = current_file ();
18476
18477   if (fe == NULL)
18478     dwarf2_debug_line_missing_file_complaint ();
18479   /* For now we ignore lines not starting on an instruction boundary.
18480      But not when processing end_sequence for compatibility with the
18481      previous version of the code.  */
18482   else if (m_op_index == 0 || end_sequence)
18483     {
18484       fe->included_p = 1;
18485       if (m_record_lines_p && m_is_stmt)
18486         {
18487           if (m_last_subfile != current_subfile || end_sequence)
18488             {
18489               dwarf_finish_line (m_gdbarch, m_last_subfile,
18490                                  m_address, m_record_line_callback);
18491             }
18492
18493           if (!end_sequence)
18494             {
18495               if (dwarf_record_line_p (m_line, m_last_line,
18496                                        m_line_has_non_zero_discriminator,
18497                                        m_last_subfile))
18498                 {
18499                   dwarf_record_line_1 (m_gdbarch, current_subfile,
18500                                        m_line, m_address,
18501                                        m_record_line_callback);
18502                 }
18503               m_last_subfile = current_subfile;
18504               m_last_line = m_line;
18505             }
18506         }
18507     }
18508 }
18509
18510 lnp_state_machine::lnp_state_machine (gdbarch *arch, line_header *lh,
18511                                       bool record_lines_p)
18512 {
18513   m_gdbarch = arch;
18514   m_record_lines_p = record_lines_p;
18515   m_line_header = lh;
18516
18517   m_record_line_callback = ::record_line;
18518
18519   /* Call `gdbarch_adjust_dwarf2_line' on the initial 0 address as if there
18520      was a line entry for it so that the backend has a chance to adjust it
18521      and also record it in case it needs it.  This is currently used by MIPS
18522      code, cf. `mips_adjust_dwarf2_line'.  */
18523   m_address = gdbarch_adjust_dwarf2_line (arch, 0, 0);
18524   m_is_stmt = lh->default_is_stmt;
18525   m_discriminator = 0;
18526 }
18527
18528 void
18529 lnp_state_machine::check_line_address (struct dwarf2_cu *cu,
18530                                        const gdb_byte *line_ptr,
18531                                        CORE_ADDR lowpc, CORE_ADDR address)
18532 {
18533   /* If address < lowpc then it's not a usable value, it's outside the
18534      pc range of the CU.  However, we restrict the test to only address
18535      values of zero to preserve GDB's previous behaviour which is to
18536      handle the specific case of a function being GC'd by the linker.  */
18537
18538   if (address == 0 && address < lowpc)
18539     {
18540       /* This line table is for a function which has been
18541          GCd by the linker.  Ignore it.  PR gdb/12528 */
18542
18543       struct objfile *objfile = cu->objfile;
18544       long line_offset = line_ptr - get_debug_line_section (cu)->buffer;
18545
18546       complaint (&symfile_complaints,
18547                  _(".debug_line address at offset 0x%lx is 0 [in module %s]"),
18548                  line_offset, objfile_name (objfile));
18549       m_record_line_callback = noop_record_line;
18550       /* Note: record_line_callback is left as noop_record_line until
18551          we see DW_LNE_end_sequence.  */
18552     }
18553 }
18554
18555 /* Subroutine of dwarf_decode_lines to simplify it.
18556    Process the line number information in LH.
18557    If DECODE_FOR_PST_P is non-zero, all we do is process the line number
18558    program in order to set included_p for every referenced header.  */
18559
18560 static void
18561 dwarf_decode_lines_1 (struct line_header *lh, struct dwarf2_cu *cu,
18562                       const int decode_for_pst_p, CORE_ADDR lowpc)
18563 {
18564   const gdb_byte *line_ptr, *extended_end;
18565   const gdb_byte *line_end;
18566   unsigned int bytes_read, extended_len;
18567   unsigned char op_code, extended_op;
18568   CORE_ADDR baseaddr;
18569   struct objfile *objfile = cu->objfile;
18570   bfd *abfd = objfile->obfd;
18571   struct gdbarch *gdbarch = get_objfile_arch (objfile);
18572   /* True if we're recording line info (as opposed to building partial
18573      symtabs and just interested in finding include files mentioned by
18574      the line number program).  */
18575   bool record_lines_p = !decode_for_pst_p;
18576
18577   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
18578
18579   line_ptr = lh->statement_program_start;
18580   line_end = lh->statement_program_end;
18581
18582   /* Read the statement sequences until there's nothing left.  */
18583   while (line_ptr < line_end)
18584     {
18585       /* The DWARF line number program state machine.  Reset the state
18586          machine at the start of each sequence.  */
18587       lnp_state_machine state_machine (gdbarch, lh, record_lines_p);
18588       bool end_sequence = false;
18589
18590       if (record_lines_p)
18591         {
18592           /* Start a subfile for the current file of the state
18593              machine.  */
18594           const file_entry *fe = state_machine.current_file ();
18595
18596           if (fe != NULL)
18597             dwarf2_start_subfile (fe->name, fe->include_dir (lh));
18598         }
18599
18600       /* Decode the table.  */
18601       while (line_ptr < line_end && !end_sequence)
18602         {
18603           op_code = read_1_byte (abfd, line_ptr);
18604           line_ptr += 1;
18605
18606           if (op_code >= lh->opcode_base)
18607             {
18608               /* Special opcode.  */
18609               state_machine.handle_special_opcode (op_code);
18610             }
18611           else switch (op_code)
18612             {
18613             case DW_LNS_extended_op:
18614               extended_len = read_unsigned_leb128 (abfd, line_ptr,
18615                                                    &bytes_read);
18616               line_ptr += bytes_read;
18617               extended_end = line_ptr + extended_len;
18618               extended_op = read_1_byte (abfd, line_ptr);
18619               line_ptr += 1;
18620               switch (extended_op)
18621                 {
18622                 case DW_LNE_end_sequence:
18623                   state_machine.handle_end_sequence ();
18624                   end_sequence = true;
18625                   break;
18626                 case DW_LNE_set_address:
18627                   {
18628                     CORE_ADDR address
18629                       = read_address (abfd, line_ptr, cu, &bytes_read);
18630                     line_ptr += bytes_read;
18631
18632                     state_machine.check_line_address (cu, line_ptr,
18633                                                       lowpc, address);
18634                     state_machine.handle_set_address (baseaddr, address);
18635                   }
18636                   break;
18637                 case DW_LNE_define_file:
18638                   {
18639                     const char *cur_file;
18640                     unsigned int mod_time, length;
18641                     dir_index dindex;
18642
18643                     cur_file = read_direct_string (abfd, line_ptr,
18644                                                    &bytes_read);
18645                     line_ptr += bytes_read;
18646                     dindex = (dir_index)
18647                       read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
18648                     line_ptr += bytes_read;
18649                     mod_time =
18650                       read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
18651                     line_ptr += bytes_read;
18652                     length =
18653                       read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
18654                     line_ptr += bytes_read;
18655                     lh->add_file_name (cur_file, dindex, mod_time, length);
18656                   }
18657                   break;
18658                 case DW_LNE_set_discriminator:
18659                   {
18660                     /* The discriminator is not interesting to the
18661                        debugger; just ignore it.  We still need to
18662                        check its value though:
18663                        if there are consecutive entries for the same
18664                        (non-prologue) line we want to coalesce them.
18665                        PR 17276.  */
18666                     unsigned int discr
18667                       = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
18668                     line_ptr += bytes_read;
18669
18670                     state_machine.handle_set_discriminator (discr);
18671                   }
18672                   break;
18673                 default:
18674                   complaint (&symfile_complaints,
18675                              _("mangled .debug_line section"));
18676                   return;
18677                 }
18678               /* Make sure that we parsed the extended op correctly.  If e.g.
18679                  we expected a different address size than the producer used,
18680                  we may have read the wrong number of bytes.  */
18681               if (line_ptr != extended_end)
18682                 {
18683                   complaint (&symfile_complaints,
18684                              _("mangled .debug_line section"));
18685                   return;
18686                 }
18687               break;
18688             case DW_LNS_copy:
18689               state_machine.handle_copy ();
18690               break;
18691             case DW_LNS_advance_pc:
18692               {
18693                 CORE_ADDR adjust
18694                   = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
18695                 line_ptr += bytes_read;
18696
18697                 state_machine.handle_advance_pc (adjust);
18698               }
18699               break;
18700             case DW_LNS_advance_line:
18701               {
18702                 int line_delta
18703                   = read_signed_leb128 (abfd, line_ptr, &bytes_read);
18704                 line_ptr += bytes_read;
18705
18706                 state_machine.handle_advance_line (line_delta);
18707               }
18708               break;
18709             case DW_LNS_set_file:
18710               {
18711                 file_name_index file
18712                   = (file_name_index) read_unsigned_leb128 (abfd, line_ptr,
18713                                                             &bytes_read);
18714                 line_ptr += bytes_read;
18715
18716                 state_machine.handle_set_file (file);
18717               }
18718               break;
18719             case DW_LNS_set_column:
18720               (void) read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
18721               line_ptr += bytes_read;
18722               break;
18723             case DW_LNS_negate_stmt:
18724               state_machine.handle_negate_stmt ();
18725               break;
18726             case DW_LNS_set_basic_block:
18727               break;
18728             /* Add to the address register of the state machine the
18729                address increment value corresponding to special opcode
18730                255.  I.e., this value is scaled by the minimum
18731                instruction length since special opcode 255 would have
18732                scaled the increment.  */
18733             case DW_LNS_const_add_pc:
18734               state_machine.handle_const_add_pc ();
18735               break;
18736             case DW_LNS_fixed_advance_pc:
18737               {
18738                 CORE_ADDR addr_adj = read_2_bytes (abfd, line_ptr);
18739                 line_ptr += 2;
18740
18741                 state_machine.handle_fixed_advance_pc (addr_adj);
18742               }
18743               break;
18744             default:
18745               {
18746                 /* Unknown standard opcode, ignore it.  */
18747                 int i;
18748
18749                 for (i = 0; i < lh->standard_opcode_lengths[op_code]; i++)
18750                   {
18751                     (void) read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
18752                     line_ptr += bytes_read;
18753                   }
18754               }
18755             }
18756         }
18757
18758       if (!end_sequence)
18759         dwarf2_debug_line_missing_end_sequence_complaint ();
18760
18761       /* We got a DW_LNE_end_sequence (or we ran off the end of the buffer,
18762          in which case we still finish recording the last line).  */
18763       state_machine.record_line (true);
18764     }
18765 }
18766
18767 /* Decode the Line Number Program (LNP) for the given line_header
18768    structure and CU.  The actual information extracted and the type
18769    of structures created from the LNP depends on the value of PST.
18770
18771    1. If PST is NULL, then this procedure uses the data from the program
18772       to create all necessary symbol tables, and their linetables.
18773
18774    2. If PST is not NULL, this procedure reads the program to determine
18775       the list of files included by the unit represented by PST, and
18776       builds all the associated partial symbol tables.
18777
18778    COMP_DIR is the compilation directory (DW_AT_comp_dir) or NULL if unknown.
18779    It is used for relative paths in the line table.
18780    NOTE: When processing partial symtabs (pst != NULL),
18781    comp_dir == pst->dirname.
18782
18783    NOTE: It is important that psymtabs have the same file name (via strcmp)
18784    as the corresponding symtab.  Since COMP_DIR is not used in the name of the
18785    symtab we don't use it in the name of the psymtabs we create.
18786    E.g. expand_line_sal requires this when finding psymtabs to expand.
18787    A good testcase for this is mb-inline.exp.
18788
18789    LOWPC is the lowest address in CU (or 0 if not known).
18790
18791    Boolean DECODE_MAPPING specifies we need to fully decode .debug_line
18792    for its PC<->lines mapping information.  Otherwise only the filename
18793    table is read in.  */
18794
18795 static void
18796 dwarf_decode_lines (struct line_header *lh, const char *comp_dir,
18797                     struct dwarf2_cu *cu, struct partial_symtab *pst,
18798                     CORE_ADDR lowpc, int decode_mapping)
18799 {
18800   struct objfile *objfile = cu->objfile;
18801   const int decode_for_pst_p = (pst != NULL);
18802
18803   if (decode_mapping)
18804     dwarf_decode_lines_1 (lh, cu, decode_for_pst_p, lowpc);
18805
18806   if (decode_for_pst_p)
18807     {
18808       int file_index;
18809
18810       /* Now that we're done scanning the Line Header Program, we can
18811          create the psymtab of each included file.  */
18812       for (file_index = 0; file_index < lh->file_names.size (); file_index++)
18813         if (lh->file_names[file_index].included_p == 1)
18814           {
18815             const char *include_name =
18816               psymtab_include_file_name (lh, file_index, pst, comp_dir);
18817             if (include_name != NULL)
18818               dwarf2_create_include_psymtab (include_name, pst, objfile);
18819           }
18820     }
18821   else
18822     {
18823       /* Make sure a symtab is created for every file, even files
18824          which contain only variables (i.e. no code with associated
18825          line numbers).  */
18826       struct compunit_symtab *cust = buildsym_compunit_symtab ();
18827       int i;
18828
18829       for (i = 0; i < lh->file_names.size (); i++)
18830         {
18831           file_entry &fe = lh->file_names[i];
18832
18833           dwarf2_start_subfile (fe.name, fe.include_dir (lh));
18834
18835           if (current_subfile->symtab == NULL)
18836             {
18837               current_subfile->symtab
18838                 = allocate_symtab (cust, current_subfile->name);
18839             }
18840           fe.symtab = current_subfile->symtab;
18841         }
18842     }
18843 }
18844
18845 /* Start a subfile for DWARF.  FILENAME is the name of the file and
18846    DIRNAME the name of the source directory which contains FILENAME
18847    or NULL if not known.
18848    This routine tries to keep line numbers from identical absolute and
18849    relative file names in a common subfile.
18850
18851    Using the `list' example from the GDB testsuite, which resides in
18852    /srcdir and compiling it with Irix6.2 cc in /compdir using a filename
18853    of /srcdir/list0.c yields the following debugging information for list0.c:
18854
18855    DW_AT_name:          /srcdir/list0.c
18856    DW_AT_comp_dir:      /compdir
18857    files.files[0].name: list0.h
18858    files.files[0].dir:  /srcdir
18859    files.files[1].name: list0.c
18860    files.files[1].dir:  /srcdir
18861
18862    The line number information for list0.c has to end up in a single
18863    subfile, so that `break /srcdir/list0.c:1' works as expected.
18864    start_subfile will ensure that this happens provided that we pass the
18865    concatenation of files.files[1].dir and files.files[1].name as the
18866    subfile's name.  */
18867
18868 static void
18869 dwarf2_start_subfile (const char *filename, const char *dirname)
18870 {
18871   char *copy = NULL;
18872
18873   /* In order not to lose the line information directory,
18874      we concatenate it to the filename when it makes sense.
18875      Note that the Dwarf3 standard says (speaking of filenames in line
18876      information): ``The directory index is ignored for file names
18877      that represent full path names''.  Thus ignoring dirname in the
18878      `else' branch below isn't an issue.  */
18879
18880   if (!IS_ABSOLUTE_PATH (filename) && dirname != NULL)
18881     {
18882       copy = concat (dirname, SLASH_STRING, filename, (char *)NULL);
18883       filename = copy;
18884     }
18885
18886   start_subfile (filename);
18887
18888   if (copy != NULL)
18889     xfree (copy);
18890 }
18891
18892 /* Start a symtab for DWARF.
18893    NAME, COMP_DIR, LOW_PC are passed to start_symtab.  */
18894
18895 static struct compunit_symtab *
18896 dwarf2_start_symtab (struct dwarf2_cu *cu,
18897                      const char *name, const char *comp_dir, CORE_ADDR low_pc)
18898 {
18899   struct compunit_symtab *cust
18900     = start_symtab (cu->objfile, name, comp_dir, low_pc);
18901
18902   record_debugformat ("DWARF 2");
18903   record_producer (cu->producer);
18904
18905   /* We assume that we're processing GCC output.  */
18906   processing_gcc_compilation = 2;
18907
18908   cu->processing_has_namespace_info = 0;
18909
18910   return cust;
18911 }
18912
18913 static void
18914 var_decode_location (struct attribute *attr, struct symbol *sym,
18915                      struct dwarf2_cu *cu)
18916 {
18917   struct objfile *objfile = cu->objfile;
18918   struct comp_unit_head *cu_header = &cu->header;
18919
18920   /* NOTE drow/2003-01-30: There used to be a comment and some special
18921      code here to turn a symbol with DW_AT_external and a
18922      SYMBOL_VALUE_ADDRESS of 0 into a LOC_UNRESOLVED symbol.  This was
18923      necessary for platforms (maybe Alpha, certainly PowerPC GNU/Linux
18924      with some versions of binutils) where shared libraries could have
18925      relocations against symbols in their debug information - the
18926      minimal symbol would have the right address, but the debug info
18927      would not.  It's no longer necessary, because we will explicitly
18928      apply relocations when we read in the debug information now.  */
18929
18930   /* A DW_AT_location attribute with no contents indicates that a
18931      variable has been optimized away.  */
18932   if (attr_form_is_block (attr) && DW_BLOCK (attr)->size == 0)
18933     {
18934       SYMBOL_ACLASS_INDEX (sym) = LOC_OPTIMIZED_OUT;
18935       return;
18936     }
18937
18938   /* Handle one degenerate form of location expression specially, to
18939      preserve GDB's previous behavior when section offsets are
18940      specified.  If this is just a DW_OP_addr or DW_OP_GNU_addr_index
18941      then mark this symbol as LOC_STATIC.  */
18942
18943   if (attr_form_is_block (attr)
18944       && ((DW_BLOCK (attr)->data[0] == DW_OP_addr
18945            && DW_BLOCK (attr)->size == 1 + cu_header->addr_size)
18946           || (DW_BLOCK (attr)->data[0] == DW_OP_GNU_addr_index
18947               && (DW_BLOCK (attr)->size
18948                   == 1 + leb128_size (&DW_BLOCK (attr)->data[1])))))
18949     {
18950       unsigned int dummy;
18951
18952       if (DW_BLOCK (attr)->data[0] == DW_OP_addr)
18953         SYMBOL_VALUE_ADDRESS (sym) =
18954           read_address (objfile->obfd, DW_BLOCK (attr)->data + 1, cu, &dummy);
18955       else
18956         SYMBOL_VALUE_ADDRESS (sym) =
18957           read_addr_index_from_leb128 (cu, DW_BLOCK (attr)->data + 1, &dummy);
18958       SYMBOL_ACLASS_INDEX (sym) = LOC_STATIC;
18959       fixup_symbol_section (sym, objfile);
18960       SYMBOL_VALUE_ADDRESS (sym) += ANOFFSET (objfile->section_offsets,
18961                                               SYMBOL_SECTION (sym));
18962       return;
18963     }
18964
18965   /* NOTE drow/2002-01-30: It might be worthwhile to have a static
18966      expression evaluator, and use LOC_COMPUTED only when necessary
18967      (i.e. when the value of a register or memory location is
18968      referenced, or a thread-local block, etc.).  Then again, it might
18969      not be worthwhile.  I'm assuming that it isn't unless performance
18970      or memory numbers show me otherwise.  */
18971
18972   dwarf2_symbol_mark_computed (attr, sym, cu, 0);
18973
18974   if (SYMBOL_COMPUTED_OPS (sym)->location_has_loclist)
18975     cu->has_loclist = 1;
18976 }
18977
18978 /* Given a pointer to a DWARF information entry, figure out if we need
18979    to make a symbol table entry for it, and if so, create a new entry
18980    and return a pointer to it.
18981    If TYPE is NULL, determine symbol type from the die, otherwise
18982    used the passed type.
18983    If SPACE is not NULL, use it to hold the new symbol.  If it is
18984    NULL, allocate a new symbol on the objfile's obstack.  */
18985
18986 static struct symbol *
18987 new_symbol_full (struct die_info *die, struct type *type, struct dwarf2_cu *cu,
18988                  struct symbol *space)
18989 {
18990   struct objfile *objfile = cu->objfile;
18991   struct gdbarch *gdbarch = get_objfile_arch (objfile);
18992   struct symbol *sym = NULL;
18993   const char *name;
18994   struct attribute *attr = NULL;
18995   struct attribute *attr2 = NULL;
18996   CORE_ADDR baseaddr;
18997   struct pending **list_to_add = NULL;
18998
18999   int inlined_func = (die->tag == DW_TAG_inlined_subroutine);
19000
19001   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
19002
19003   name = dwarf2_name (die, cu);
19004   if (name)
19005     {
19006       const char *linkagename;
19007       int suppress_add = 0;
19008
19009       if (space)
19010         sym = space;
19011       else
19012         sym = allocate_symbol (objfile);
19013       OBJSTAT (objfile, n_syms++);
19014
19015       /* Cache this symbol's name and the name's demangled form (if any).  */
19016       SYMBOL_SET_LANGUAGE (sym, cu->language, &objfile->objfile_obstack);
19017       linkagename = dwarf2_physname (name, die, cu);
19018       SYMBOL_SET_NAMES (sym, linkagename, strlen (linkagename), 0, objfile);
19019
19020       /* Fortran does not have mangling standard and the mangling does differ
19021          between gfortran, iFort etc.  */
19022       if (cu->language == language_fortran
19023           && symbol_get_demangled_name (&(sym->ginfo)) == NULL)
19024         symbol_set_demangled_name (&(sym->ginfo),
19025                                    dwarf2_full_name (name, die, cu),
19026                                    NULL);
19027
19028       /* Default assumptions.
19029          Use the passed type or decode it from the die.  */
19030       SYMBOL_DOMAIN (sym) = VAR_DOMAIN;
19031       SYMBOL_ACLASS_INDEX (sym) = LOC_OPTIMIZED_OUT;
19032       if (type != NULL)
19033         SYMBOL_TYPE (sym) = type;
19034       else
19035         SYMBOL_TYPE (sym) = die_type (die, cu);
19036       attr = dwarf2_attr (die,
19037                           inlined_func ? DW_AT_call_line : DW_AT_decl_line,
19038                           cu);
19039       if (attr)
19040         {
19041           SYMBOL_LINE (sym) = DW_UNSND (attr);
19042         }
19043
19044       attr = dwarf2_attr (die,
19045                           inlined_func ? DW_AT_call_file : DW_AT_decl_file,
19046                           cu);
19047       if (attr)
19048         {
19049           file_name_index file_index = (file_name_index) DW_UNSND (attr);
19050           struct file_entry *fe;
19051
19052           if (cu->line_header != NULL)
19053             fe = cu->line_header->file_name_at (file_index);
19054           else
19055             fe = NULL;
19056
19057           if (fe == NULL)
19058             complaint (&symfile_complaints,
19059                        _("file index out of range"));
19060           else
19061             symbol_set_symtab (sym, fe->symtab);
19062         }
19063
19064       switch (die->tag)
19065         {
19066         case DW_TAG_label:
19067           attr = dwarf2_attr (die, DW_AT_low_pc, cu);
19068           if (attr)
19069             {
19070               CORE_ADDR addr;
19071
19072               addr = attr_value_as_address (attr);
19073               addr = gdbarch_adjust_dwarf2_addr (gdbarch, addr + baseaddr);
19074               SYMBOL_VALUE_ADDRESS (sym) = addr;
19075             }
19076           SYMBOL_TYPE (sym) = objfile_type (objfile)->builtin_core_addr;
19077           SYMBOL_DOMAIN (sym) = LABEL_DOMAIN;
19078           SYMBOL_ACLASS_INDEX (sym) = LOC_LABEL;
19079           add_symbol_to_list (sym, cu->list_in_scope);
19080           break;
19081         case DW_TAG_subprogram:
19082           /* SYMBOL_BLOCK_VALUE (sym) will be filled in later by
19083              finish_block.  */
19084           SYMBOL_ACLASS_INDEX (sym) = LOC_BLOCK;
19085           attr2 = dwarf2_attr (die, DW_AT_external, cu);
19086           if ((attr2 && (DW_UNSND (attr2) != 0))
19087               || cu->language == language_ada)
19088             {
19089               /* Subprograms marked external are stored as a global symbol.
19090                  Ada subprograms, whether marked external or not, are always
19091                  stored as a global symbol, because we want to be able to
19092                  access them globally.  For instance, we want to be able
19093                  to break on a nested subprogram without having to
19094                  specify the context.  */
19095               list_to_add = &global_symbols;
19096             }
19097           else
19098             {
19099               list_to_add = cu->list_in_scope;
19100             }
19101           break;
19102         case DW_TAG_inlined_subroutine:
19103           /* SYMBOL_BLOCK_VALUE (sym) will be filled in later by
19104              finish_block.  */
19105           SYMBOL_ACLASS_INDEX (sym) = LOC_BLOCK;
19106           SYMBOL_INLINED (sym) = 1;
19107           list_to_add = cu->list_in_scope;
19108           break;
19109         case DW_TAG_template_value_param:
19110           suppress_add = 1;
19111           /* Fall through.  */
19112         case DW_TAG_constant:
19113         case DW_TAG_variable:
19114         case DW_TAG_member:
19115           /* Compilation with minimal debug info may result in
19116              variables with missing type entries.  Change the
19117              misleading `void' type to something sensible.  */
19118           if (TYPE_CODE (SYMBOL_TYPE (sym)) == TYPE_CODE_VOID)
19119             SYMBOL_TYPE (sym)
19120               = objfile_type (objfile)->nodebug_data_symbol;
19121
19122           attr = dwarf2_attr (die, DW_AT_const_value, cu);
19123           /* In the case of DW_TAG_member, we should only be called for
19124              static const members.  */
19125           if (die->tag == DW_TAG_member)
19126             {
19127               /* dwarf2_add_field uses die_is_declaration,
19128                  so we do the same.  */
19129               gdb_assert (die_is_declaration (die, cu));
19130               gdb_assert (attr);
19131             }
19132           if (attr)
19133             {
19134               dwarf2_const_value (attr, sym, cu);
19135               attr2 = dwarf2_attr (die, DW_AT_external, cu);
19136               if (!suppress_add)
19137                 {
19138                   if (attr2 && (DW_UNSND (attr2) != 0))
19139                     list_to_add = &global_symbols;
19140                   else
19141                     list_to_add = cu->list_in_scope;
19142                 }
19143               break;
19144             }
19145           attr = dwarf2_attr (die, DW_AT_location, cu);
19146           if (attr)
19147             {
19148               var_decode_location (attr, sym, cu);
19149               attr2 = dwarf2_attr (die, DW_AT_external, cu);
19150
19151               /* Fortran explicitly imports any global symbols to the local
19152                  scope by DW_TAG_common_block.  */
19153               if (cu->language == language_fortran && die->parent
19154                   && die->parent->tag == DW_TAG_common_block)
19155                 attr2 = NULL;
19156
19157               if (SYMBOL_CLASS (sym) == LOC_STATIC
19158                   && SYMBOL_VALUE_ADDRESS (sym) == 0
19159                   && !dwarf2_per_objfile->has_section_at_zero)
19160                 {
19161                   /* When a static variable is eliminated by the linker,
19162                      the corresponding debug information is not stripped
19163                      out, but the variable address is set to null;
19164                      do not add such variables into symbol table.  */
19165                 }
19166               else if (attr2 && (DW_UNSND (attr2) != 0))
19167                 {
19168                   /* Workaround gfortran PR debug/40040 - it uses
19169                      DW_AT_location for variables in -fPIC libraries which may
19170                      get overriden by other libraries/executable and get
19171                      a different address.  Resolve it by the minimal symbol
19172                      which may come from inferior's executable using copy
19173                      relocation.  Make this workaround only for gfortran as for
19174                      other compilers GDB cannot guess the minimal symbol
19175                      Fortran mangling kind.  */
19176                   if (cu->language == language_fortran && die->parent
19177                       && die->parent->tag == DW_TAG_module
19178                       && cu->producer
19179                       && startswith (cu->producer, "GNU Fortran"))
19180                     SYMBOL_ACLASS_INDEX (sym) = LOC_UNRESOLVED;
19181
19182                   /* A variable with DW_AT_external is never static,
19183                      but it may be block-scoped.  */
19184                   list_to_add = (cu->list_in_scope == &file_symbols
19185                                  ? &global_symbols : cu->list_in_scope);
19186                 }
19187               else
19188                 list_to_add = cu->list_in_scope;
19189             }
19190           else
19191             {
19192               /* We do not know the address of this symbol.
19193                  If it is an external symbol and we have type information
19194                  for it, enter the symbol as a LOC_UNRESOLVED symbol.
19195                  The address of the variable will then be determined from
19196                  the minimal symbol table whenever the variable is
19197                  referenced.  */
19198               attr2 = dwarf2_attr (die, DW_AT_external, cu);
19199
19200               /* Fortran explicitly imports any global symbols to the local
19201                  scope by DW_TAG_common_block.  */
19202               if (cu->language == language_fortran && die->parent
19203                   && die->parent->tag == DW_TAG_common_block)
19204                 {
19205                   /* SYMBOL_CLASS doesn't matter here because
19206                      read_common_block is going to reset it.  */
19207                   if (!suppress_add)
19208                     list_to_add = cu->list_in_scope;
19209                 }
19210               else if (attr2 && (DW_UNSND (attr2) != 0)
19211                        && dwarf2_attr (die, DW_AT_type, cu) != NULL)
19212                 {
19213                   /* A variable with DW_AT_external is never static, but it
19214                      may be block-scoped.  */
19215                   list_to_add = (cu->list_in_scope == &file_symbols
19216                                  ? &global_symbols : cu->list_in_scope);
19217
19218                   SYMBOL_ACLASS_INDEX (sym) = LOC_UNRESOLVED;
19219                 }
19220               else if (!die_is_declaration (die, cu))
19221                 {
19222                   /* Use the default LOC_OPTIMIZED_OUT class.  */
19223                   gdb_assert (SYMBOL_CLASS (sym) == LOC_OPTIMIZED_OUT);
19224                   if (!suppress_add)
19225                     list_to_add = cu->list_in_scope;
19226                 }
19227             }
19228           break;
19229         case DW_TAG_formal_parameter:
19230           /* If we are inside a function, mark this as an argument.  If
19231              not, we might be looking at an argument to an inlined function
19232              when we do not have enough information to show inlined frames;
19233              pretend it's a local variable in that case so that the user can
19234              still see it.  */
19235           if (context_stack_depth > 0
19236               && context_stack[context_stack_depth - 1].name != NULL)
19237             SYMBOL_IS_ARGUMENT (sym) = 1;
19238           attr = dwarf2_attr (die, DW_AT_location, cu);
19239           if (attr)
19240             {
19241               var_decode_location (attr, sym, cu);
19242             }
19243           attr = dwarf2_attr (die, DW_AT_const_value, cu);
19244           if (attr)
19245             {
19246               dwarf2_const_value (attr, sym, cu);
19247             }
19248
19249           list_to_add = cu->list_in_scope;
19250           break;
19251         case DW_TAG_unspecified_parameters:
19252           /* From varargs functions; gdb doesn't seem to have any
19253              interest in this information, so just ignore it for now.
19254              (FIXME?) */
19255           break;
19256         case DW_TAG_template_type_param:
19257           suppress_add = 1;
19258           /* Fall through.  */
19259         case DW_TAG_class_type:
19260         case DW_TAG_interface_type:
19261         case DW_TAG_structure_type:
19262         case DW_TAG_union_type:
19263         case DW_TAG_set_type:
19264         case DW_TAG_enumeration_type:
19265           SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
19266           SYMBOL_DOMAIN (sym) = STRUCT_DOMAIN;
19267
19268           {
19269             /* NOTE: carlton/2003-11-10: C++ class symbols shouldn't
19270                really ever be static objects: otherwise, if you try
19271                to, say, break of a class's method and you're in a file
19272                which doesn't mention that class, it won't work unless
19273                the check for all static symbols in lookup_symbol_aux
19274                saves you.  See the OtherFileClass tests in
19275                gdb.c++/namespace.exp.  */
19276
19277             if (!suppress_add)
19278               {
19279                 list_to_add = (cu->list_in_scope == &file_symbols
19280                                && cu->language == language_cplus
19281                                ? &global_symbols : cu->list_in_scope);
19282
19283                 /* The semantics of C++ state that "struct foo {
19284                    ... }" also defines a typedef for "foo".  */
19285                 if (cu->language == language_cplus
19286                     || cu->language == language_ada
19287                     || cu->language == language_d
19288                     || cu->language == language_rust)
19289                   {
19290                     /* The symbol's name is already allocated along
19291                        with this objfile, so we don't need to
19292                        duplicate it for the type.  */
19293                     if (TYPE_NAME (SYMBOL_TYPE (sym)) == 0)
19294                       TYPE_NAME (SYMBOL_TYPE (sym)) = SYMBOL_SEARCH_NAME (sym);
19295                   }
19296               }
19297           }
19298           break;
19299         case DW_TAG_typedef:
19300           SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
19301           SYMBOL_DOMAIN (sym) = VAR_DOMAIN;
19302           list_to_add = cu->list_in_scope;
19303           break;
19304         case DW_TAG_base_type:
19305         case DW_TAG_subrange_type:
19306           SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
19307           SYMBOL_DOMAIN (sym) = VAR_DOMAIN;
19308           list_to_add = cu->list_in_scope;
19309           break;
19310         case DW_TAG_enumerator:
19311           attr = dwarf2_attr (die, DW_AT_const_value, cu);
19312           if (attr)
19313             {
19314               dwarf2_const_value (attr, sym, cu);
19315             }
19316           {
19317             /* NOTE: carlton/2003-11-10: See comment above in the
19318                DW_TAG_class_type, etc. block.  */
19319
19320             list_to_add = (cu->list_in_scope == &file_symbols
19321                            && cu->language == language_cplus
19322                            ? &global_symbols : cu->list_in_scope);
19323           }
19324           break;
19325         case DW_TAG_imported_declaration:
19326         case DW_TAG_namespace:
19327           SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
19328           list_to_add = &global_symbols;
19329           break;
19330         case DW_TAG_module:
19331           SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
19332           SYMBOL_DOMAIN (sym) = MODULE_DOMAIN;
19333           list_to_add = &global_symbols;
19334           break;
19335         case DW_TAG_common_block:
19336           SYMBOL_ACLASS_INDEX (sym) = LOC_COMMON_BLOCK;
19337           SYMBOL_DOMAIN (sym) = COMMON_BLOCK_DOMAIN;
19338           add_symbol_to_list (sym, cu->list_in_scope);
19339           break;
19340         default:
19341           /* Not a tag we recognize.  Hopefully we aren't processing
19342              trash data, but since we must specifically ignore things
19343              we don't recognize, there is nothing else we should do at
19344              this point.  */
19345           complaint (&symfile_complaints, _("unsupported tag: '%s'"),
19346                      dwarf_tag_name (die->tag));
19347           break;
19348         }
19349
19350       if (suppress_add)
19351         {
19352           sym->hash_next = objfile->template_symbols;
19353           objfile->template_symbols = sym;
19354           list_to_add = NULL;
19355         }
19356
19357       if (list_to_add != NULL)
19358         add_symbol_to_list (sym, list_to_add);
19359
19360       /* For the benefit of old versions of GCC, check for anonymous
19361          namespaces based on the demangled name.  */
19362       if (!cu->processing_has_namespace_info
19363           && cu->language == language_cplus)
19364         cp_scan_for_anonymous_namespaces (sym, objfile);
19365     }
19366   return (sym);
19367 }
19368
19369 /* A wrapper for new_symbol_full that always allocates a new symbol.  */
19370
19371 static struct symbol *
19372 new_symbol (struct die_info *die, struct type *type, struct dwarf2_cu *cu)
19373 {
19374   return new_symbol_full (die, type, cu, NULL);
19375 }
19376
19377 /* Given an attr with a DW_FORM_dataN value in host byte order,
19378    zero-extend it as appropriate for the symbol's type.  The DWARF
19379    standard (v4) is not entirely clear about the meaning of using
19380    DW_FORM_dataN for a constant with a signed type, where the type is
19381    wider than the data.  The conclusion of a discussion on the DWARF
19382    list was that this is unspecified.  We choose to always zero-extend
19383    because that is the interpretation long in use by GCC.  */
19384
19385 static gdb_byte *
19386 dwarf2_const_value_data (const struct attribute *attr, struct obstack *obstack,
19387                          struct dwarf2_cu *cu, LONGEST *value, int bits)
19388 {
19389   struct objfile *objfile = cu->objfile;
19390   enum bfd_endian byte_order = bfd_big_endian (objfile->obfd) ?
19391                                 BFD_ENDIAN_BIG : BFD_ENDIAN_LITTLE;
19392   LONGEST l = DW_UNSND (attr);
19393
19394   if (bits < sizeof (*value) * 8)
19395     {
19396       l &= ((LONGEST) 1 << bits) - 1;
19397       *value = l;
19398     }
19399   else if (bits == sizeof (*value) * 8)
19400     *value = l;
19401   else
19402     {
19403       gdb_byte *bytes = (gdb_byte *) obstack_alloc (obstack, bits / 8);
19404       store_unsigned_integer (bytes, bits / 8, byte_order, l);
19405       return bytes;
19406     }
19407
19408   return NULL;
19409 }
19410
19411 /* Read a constant value from an attribute.  Either set *VALUE, or if
19412    the value does not fit in *VALUE, set *BYTES - either already
19413    allocated on the objfile obstack, or newly allocated on OBSTACK,
19414    or, set *BATON, if we translated the constant to a location
19415    expression.  */
19416
19417 static void
19418 dwarf2_const_value_attr (const struct attribute *attr, struct type *type,
19419                          const char *name, struct obstack *obstack,
19420                          struct dwarf2_cu *cu,
19421                          LONGEST *value, const gdb_byte **bytes,
19422                          struct dwarf2_locexpr_baton **baton)
19423 {
19424   struct objfile *objfile = cu->objfile;
19425   struct comp_unit_head *cu_header = &cu->header;
19426   struct dwarf_block *blk;
19427   enum bfd_endian byte_order = (bfd_big_endian (objfile->obfd) ?
19428                                 BFD_ENDIAN_BIG : BFD_ENDIAN_LITTLE);
19429
19430   *value = 0;
19431   *bytes = NULL;
19432   *baton = NULL;
19433
19434   switch (attr->form)
19435     {
19436     case DW_FORM_addr:
19437     case DW_FORM_GNU_addr_index:
19438       {
19439         gdb_byte *data;
19440
19441         if (TYPE_LENGTH (type) != cu_header->addr_size)
19442           dwarf2_const_value_length_mismatch_complaint (name,
19443                                                         cu_header->addr_size,
19444                                                         TYPE_LENGTH (type));
19445         /* Symbols of this form are reasonably rare, so we just
19446            piggyback on the existing location code rather than writing
19447            a new implementation of symbol_computed_ops.  */
19448         *baton = XOBNEW (obstack, struct dwarf2_locexpr_baton);
19449         (*baton)->per_cu = cu->per_cu;
19450         gdb_assert ((*baton)->per_cu);
19451
19452         (*baton)->size = 2 + cu_header->addr_size;
19453         data = (gdb_byte *) obstack_alloc (obstack, (*baton)->size);
19454         (*baton)->data = data;
19455
19456         data[0] = DW_OP_addr;
19457         store_unsigned_integer (&data[1], cu_header->addr_size,
19458                                 byte_order, DW_ADDR (attr));
19459         data[cu_header->addr_size + 1] = DW_OP_stack_value;
19460       }
19461       break;
19462     case DW_FORM_string:
19463     case DW_FORM_strp:
19464     case DW_FORM_GNU_str_index:
19465     case DW_FORM_GNU_strp_alt:
19466       /* DW_STRING is already allocated on the objfile obstack, point
19467          directly to it.  */
19468       *bytes = (const gdb_byte *) DW_STRING (attr);
19469       break;
19470     case DW_FORM_block1:
19471     case DW_FORM_block2:
19472     case DW_FORM_block4:
19473     case DW_FORM_block:
19474     case DW_FORM_exprloc:
19475     case DW_FORM_data16:
19476       blk = DW_BLOCK (attr);
19477       if (TYPE_LENGTH (type) != blk->size)
19478         dwarf2_const_value_length_mismatch_complaint (name, blk->size,
19479                                                       TYPE_LENGTH (type));
19480       *bytes = blk->data;
19481       break;
19482
19483       /* The DW_AT_const_value attributes are supposed to carry the
19484          symbol's value "represented as it would be on the target
19485          architecture."  By the time we get here, it's already been
19486          converted to host endianness, so we just need to sign- or
19487          zero-extend it as appropriate.  */
19488     case DW_FORM_data1:
19489       *bytes = dwarf2_const_value_data (attr, obstack, cu, value, 8);
19490       break;
19491     case DW_FORM_data2:
19492       *bytes = dwarf2_const_value_data (attr, obstack, cu, value, 16);
19493       break;
19494     case DW_FORM_data4:
19495       *bytes = dwarf2_const_value_data (attr, obstack, cu, value, 32);
19496       break;
19497     case DW_FORM_data8:
19498       *bytes = dwarf2_const_value_data (attr, obstack, cu, value, 64);
19499       break;
19500
19501     case DW_FORM_sdata:
19502       *value = DW_SND (attr);
19503       break;
19504
19505     case DW_FORM_udata:
19506       *value = DW_UNSND (attr);
19507       break;
19508
19509     default:
19510       complaint (&symfile_complaints,
19511                  _("unsupported const value attribute form: '%s'"),
19512                  dwarf_form_name (attr->form));
19513       *value = 0;
19514       break;
19515     }
19516 }
19517
19518
19519 /* Copy constant value from an attribute to a symbol.  */
19520
19521 static void
19522 dwarf2_const_value (const struct attribute *attr, struct symbol *sym,
19523                     struct dwarf2_cu *cu)
19524 {
19525   struct objfile *objfile = cu->objfile;
19526   LONGEST value;
19527   const gdb_byte *bytes;
19528   struct dwarf2_locexpr_baton *baton;
19529
19530   dwarf2_const_value_attr (attr, SYMBOL_TYPE (sym),
19531                            SYMBOL_PRINT_NAME (sym),
19532                            &objfile->objfile_obstack, cu,
19533                            &value, &bytes, &baton);
19534
19535   if (baton != NULL)
19536     {
19537       SYMBOL_LOCATION_BATON (sym) = baton;
19538       SYMBOL_ACLASS_INDEX (sym) = dwarf2_locexpr_index;
19539     }
19540   else if (bytes != NULL)
19541      {
19542       SYMBOL_VALUE_BYTES (sym) = bytes;
19543       SYMBOL_ACLASS_INDEX (sym) = LOC_CONST_BYTES;
19544     }
19545   else
19546     {
19547       SYMBOL_VALUE (sym) = value;
19548       SYMBOL_ACLASS_INDEX (sym) = LOC_CONST;
19549     }
19550 }
19551
19552 /* Return the type of the die in question using its DW_AT_type attribute.  */
19553
19554 static struct type *
19555 die_type (struct die_info *die, struct dwarf2_cu *cu)
19556 {
19557   struct attribute *type_attr;
19558
19559   type_attr = dwarf2_attr (die, DW_AT_type, cu);
19560   if (!type_attr)
19561     {
19562       /* A missing DW_AT_type represents a void type.  */
19563       return objfile_type (cu->objfile)->builtin_void;
19564     }
19565
19566   return lookup_die_type (die, type_attr, cu);
19567 }
19568
19569 /* True iff CU's producer generates GNAT Ada auxiliary information
19570    that allows to find parallel types through that information instead
19571    of having to do expensive parallel lookups by type name.  */
19572
19573 static int
19574 need_gnat_info (struct dwarf2_cu *cu)
19575 {
19576   /* FIXME: brobecker/2010-10-12: As of now, only the AdaCore version
19577      of GNAT produces this auxiliary information, without any indication
19578      that it is produced.  Part of enhancing the FSF version of GNAT
19579      to produce that information will be to put in place an indicator
19580      that we can use in order to determine whether the descriptive type
19581      info is available or not.  One suggestion that has been made is
19582      to use a new attribute, attached to the CU die.  For now, assume
19583      that the descriptive type info is not available.  */
19584   return 0;
19585 }
19586
19587 /* Return the auxiliary type of the die in question using its
19588    DW_AT_GNAT_descriptive_type attribute.  Returns NULL if the
19589    attribute is not present.  */
19590
19591 static struct type *
19592 die_descriptive_type (struct die_info *die, struct dwarf2_cu *cu)
19593 {
19594   struct attribute *type_attr;
19595
19596   type_attr = dwarf2_attr (die, DW_AT_GNAT_descriptive_type, cu);
19597   if (!type_attr)
19598     return NULL;
19599
19600   return lookup_die_type (die, type_attr, cu);
19601 }
19602
19603 /* If DIE has a descriptive_type attribute, then set the TYPE's
19604    descriptive type accordingly.  */
19605
19606 static void
19607 set_descriptive_type (struct type *type, struct die_info *die,
19608                       struct dwarf2_cu *cu)
19609 {
19610   struct type *descriptive_type = die_descriptive_type (die, cu);
19611
19612   if (descriptive_type)
19613     {
19614       ALLOCATE_GNAT_AUX_TYPE (type);
19615       TYPE_DESCRIPTIVE_TYPE (type) = descriptive_type;
19616     }
19617 }
19618
19619 /* Return the containing type of the die in question using its
19620    DW_AT_containing_type attribute.  */
19621
19622 static struct type *
19623 die_containing_type (struct die_info *die, struct dwarf2_cu *cu)
19624 {
19625   struct attribute *type_attr;
19626
19627   type_attr = dwarf2_attr (die, DW_AT_containing_type, cu);
19628   if (!type_attr)
19629     error (_("Dwarf Error: Problem turning containing type into gdb type "
19630              "[in module %s]"), objfile_name (cu->objfile));
19631
19632   return lookup_die_type (die, type_attr, cu);
19633 }
19634
19635 /* Return an error marker type to use for the ill formed type in DIE/CU.  */
19636
19637 static struct type *
19638 build_error_marker_type (struct dwarf2_cu *cu, struct die_info *die)
19639 {
19640   struct objfile *objfile = dwarf2_per_objfile->objfile;
19641   char *message, *saved;
19642
19643   message = xstrprintf (_("<unknown type in %s, CU 0x%x, DIE 0x%x>"),
19644                         objfile_name (objfile),
19645                         to_underlying (cu->header.sect_off),
19646                         to_underlying (die->sect_off));
19647   saved = (char *) obstack_copy0 (&objfile->objfile_obstack,
19648                                   message, strlen (message));
19649   xfree (message);
19650
19651   return init_type (objfile, TYPE_CODE_ERROR, 0, saved);
19652 }
19653
19654 /* Look up the type of DIE in CU using its type attribute ATTR.
19655    ATTR must be one of: DW_AT_type, DW_AT_GNAT_descriptive_type,
19656    DW_AT_containing_type.
19657    If there is no type substitute an error marker.  */
19658
19659 static struct type *
19660 lookup_die_type (struct die_info *die, const struct attribute *attr,
19661                  struct dwarf2_cu *cu)
19662 {
19663   struct objfile *objfile = cu->objfile;
19664   struct type *this_type;
19665
19666   gdb_assert (attr->name == DW_AT_type
19667               || attr->name == DW_AT_GNAT_descriptive_type
19668               || attr->name == DW_AT_containing_type);
19669
19670   /* First see if we have it cached.  */
19671
19672   if (attr->form == DW_FORM_GNU_ref_alt)
19673     {
19674       struct dwarf2_per_cu_data *per_cu;
19675       sect_offset sect_off = dwarf2_get_ref_die_offset (attr);
19676
19677       per_cu = dwarf2_find_containing_comp_unit (sect_off, 1, cu->objfile);
19678       this_type = get_die_type_at_offset (sect_off, per_cu);
19679     }
19680   else if (attr_form_is_ref (attr))
19681     {
19682       sect_offset sect_off = dwarf2_get_ref_die_offset (attr);
19683
19684       this_type = get_die_type_at_offset (sect_off, cu->per_cu);
19685     }
19686   else if (attr->form == DW_FORM_ref_sig8)
19687     {
19688       ULONGEST signature = DW_SIGNATURE (attr);
19689
19690       return get_signatured_type (die, signature, cu);
19691     }
19692   else
19693     {
19694       complaint (&symfile_complaints,
19695                  _("Dwarf Error: Bad type attribute %s in DIE"
19696                    " at 0x%x [in module %s]"),
19697                  dwarf_attr_name (attr->name), to_underlying (die->sect_off),
19698                  objfile_name (objfile));
19699       return build_error_marker_type (cu, die);
19700     }
19701
19702   /* If not cached we need to read it in.  */
19703
19704   if (this_type == NULL)
19705     {
19706       struct die_info *type_die = NULL;
19707       struct dwarf2_cu *type_cu = cu;
19708
19709       if (attr_form_is_ref (attr))
19710         type_die = follow_die_ref (die, attr, &type_cu);
19711       if (type_die == NULL)
19712         return build_error_marker_type (cu, die);
19713       /* If we find the type now, it's probably because the type came
19714          from an inter-CU reference and the type's CU got expanded before
19715          ours.  */
19716       this_type = read_type_die (type_die, type_cu);
19717     }
19718
19719   /* If we still don't have a type use an error marker.  */
19720
19721   if (this_type == NULL)
19722     return build_error_marker_type (cu, die);
19723
19724   return this_type;
19725 }
19726
19727 /* Return the type in DIE, CU.
19728    Returns NULL for invalid types.
19729
19730    This first does a lookup in die_type_hash,
19731    and only reads the die in if necessary.
19732
19733    NOTE: This can be called when reading in partial or full symbols.  */
19734
19735 static struct type *
19736 read_type_die (struct die_info *die, struct dwarf2_cu *cu)
19737 {
19738   struct type *this_type;
19739
19740   this_type = get_die_type (die, cu);
19741   if (this_type)
19742     return this_type;
19743
19744   return read_type_die_1 (die, cu);
19745 }
19746
19747 /* Read the type in DIE, CU.
19748    Returns NULL for invalid types.  */
19749
19750 static struct type *
19751 read_type_die_1 (struct die_info *die, struct dwarf2_cu *cu)
19752 {
19753   struct type *this_type = NULL;
19754
19755   switch (die->tag)
19756     {
19757     case DW_TAG_class_type:
19758     case DW_TAG_interface_type:
19759     case DW_TAG_structure_type:
19760     case DW_TAG_union_type:
19761       this_type = read_structure_type (die, cu);
19762       break;
19763     case DW_TAG_enumeration_type:
19764       this_type = read_enumeration_type (die, cu);
19765       break;
19766     case DW_TAG_subprogram:
19767     case DW_TAG_subroutine_type:
19768     case DW_TAG_inlined_subroutine:
19769       this_type = read_subroutine_type (die, cu);
19770       break;
19771     case DW_TAG_array_type:
19772       this_type = read_array_type (die, cu);
19773       break;
19774     case DW_TAG_set_type:
19775       this_type = read_set_type (die, cu);
19776       break;
19777     case DW_TAG_pointer_type:
19778       this_type = read_tag_pointer_type (die, cu);
19779       break;
19780     case DW_TAG_ptr_to_member_type:
19781       this_type = read_tag_ptr_to_member_type (die, cu);
19782       break;
19783     case DW_TAG_reference_type:
19784       this_type = read_tag_reference_type (die, cu, TYPE_CODE_REF);
19785       break;
19786     case DW_TAG_rvalue_reference_type:
19787       this_type = read_tag_reference_type (die, cu, TYPE_CODE_RVALUE_REF);
19788       break;
19789     case DW_TAG_const_type:
19790       this_type = read_tag_const_type (die, cu);
19791       break;
19792     case DW_TAG_volatile_type:
19793       this_type = read_tag_volatile_type (die, cu);
19794       break;
19795     case DW_TAG_restrict_type:
19796       this_type = read_tag_restrict_type (die, cu);
19797       break;
19798     case DW_TAG_string_type:
19799       this_type = read_tag_string_type (die, cu);
19800       break;
19801     case DW_TAG_typedef:
19802       this_type = read_typedef (die, cu);
19803       break;
19804     case DW_TAG_subrange_type:
19805       this_type = read_subrange_type (die, cu);
19806       break;
19807     case DW_TAG_base_type:
19808       this_type = read_base_type (die, cu);
19809       break;
19810     case DW_TAG_unspecified_type:
19811       this_type = read_unspecified_type (die, cu);
19812       break;
19813     case DW_TAG_namespace:
19814       this_type = read_namespace_type (die, cu);
19815       break;
19816     case DW_TAG_module:
19817       this_type = read_module_type (die, cu);
19818       break;
19819     case DW_TAG_atomic_type:
19820       this_type = read_tag_atomic_type (die, cu);
19821       break;
19822     default:
19823       complaint (&symfile_complaints,
19824                  _("unexpected tag in read_type_die: '%s'"),
19825                  dwarf_tag_name (die->tag));
19826       break;
19827     }
19828
19829   return this_type;
19830 }
19831
19832 /* See if we can figure out if the class lives in a namespace.  We do
19833    this by looking for a member function; its demangled name will
19834    contain namespace info, if there is any.
19835    Return the computed name or NULL.
19836    Space for the result is allocated on the objfile's obstack.
19837    This is the full-die version of guess_partial_die_structure_name.
19838    In this case we know DIE has no useful parent.  */
19839
19840 static char *
19841 guess_full_die_structure_name (struct die_info *die, struct dwarf2_cu *cu)
19842 {
19843   struct die_info *spec_die;
19844   struct dwarf2_cu *spec_cu;
19845   struct die_info *child;
19846
19847   spec_cu = cu;
19848   spec_die = die_specification (die, &spec_cu);
19849   if (spec_die != NULL)
19850     {
19851       die = spec_die;
19852       cu = spec_cu;
19853     }
19854
19855   for (child = die->child;
19856        child != NULL;
19857        child = child->sibling)
19858     {
19859       if (child->tag == DW_TAG_subprogram)
19860         {
19861           const char *linkage_name;
19862
19863           linkage_name = dwarf2_string_attr (child, DW_AT_linkage_name, cu);
19864           if (linkage_name == NULL)
19865             linkage_name = dwarf2_string_attr (child, DW_AT_MIPS_linkage_name,
19866                                                cu);
19867           if (linkage_name != NULL)
19868             {
19869               char *actual_name
19870                 = language_class_name_from_physname (cu->language_defn,
19871                                                      linkage_name);
19872               char *name = NULL;
19873
19874               if (actual_name != NULL)
19875                 {
19876                   const char *die_name = dwarf2_name (die, cu);
19877
19878                   if (die_name != NULL
19879                       && strcmp (die_name, actual_name) != 0)
19880                     {
19881                       /* Strip off the class name from the full name.
19882                          We want the prefix.  */
19883                       int die_name_len = strlen (die_name);
19884                       int actual_name_len = strlen (actual_name);
19885
19886                       /* Test for '::' as a sanity check.  */
19887                       if (actual_name_len > die_name_len + 2
19888                           && actual_name[actual_name_len
19889                                          - die_name_len - 1] == ':')
19890                         name = (char *) obstack_copy0 (
19891                           &cu->objfile->per_bfd->storage_obstack,
19892                           actual_name, actual_name_len - die_name_len - 2);
19893                     }
19894                 }
19895               xfree (actual_name);
19896               return name;
19897             }
19898         }
19899     }
19900
19901   return NULL;
19902 }
19903
19904 /* GCC might emit a nameless typedef that has a linkage name.  Determine the
19905    prefix part in such case.  See
19906    http://gcc.gnu.org/bugzilla/show_bug.cgi?id=47510.  */
19907
19908 static const char *
19909 anonymous_struct_prefix (struct die_info *die, struct dwarf2_cu *cu)
19910 {
19911   struct attribute *attr;
19912   const char *base;
19913
19914   if (die->tag != DW_TAG_class_type && die->tag != DW_TAG_interface_type
19915       && die->tag != DW_TAG_structure_type && die->tag != DW_TAG_union_type)
19916     return NULL;
19917
19918   if (dwarf2_string_attr (die, DW_AT_name, cu) != NULL)
19919     return NULL;
19920
19921   attr = dwarf2_attr (die, DW_AT_linkage_name, cu);
19922   if (attr == NULL)
19923     attr = dwarf2_attr (die, DW_AT_MIPS_linkage_name, cu);
19924   if (attr == NULL || DW_STRING (attr) == NULL)
19925     return NULL;
19926
19927   /* dwarf2_name had to be already called.  */
19928   gdb_assert (DW_STRING_IS_CANONICAL (attr));
19929
19930   /* Strip the base name, keep any leading namespaces/classes.  */
19931   base = strrchr (DW_STRING (attr), ':');
19932   if (base == NULL || base == DW_STRING (attr) || base[-1] != ':')
19933     return "";
19934
19935   return (char *) obstack_copy0 (&cu->objfile->per_bfd->storage_obstack,
19936                                  DW_STRING (attr),
19937                                  &base[-1] - DW_STRING (attr));
19938 }
19939
19940 /* Return the name of the namespace/class that DIE is defined within,
19941    or "" if we can't tell.  The caller should not xfree the result.
19942
19943    For example, if we're within the method foo() in the following
19944    code:
19945
19946    namespace N {
19947      class C {
19948        void foo () {
19949        }
19950      };
19951    }
19952
19953    then determine_prefix on foo's die will return "N::C".  */
19954
19955 static const char *
19956 determine_prefix (struct die_info *die, struct dwarf2_cu *cu)
19957 {
19958   struct die_info *parent, *spec_die;
19959   struct dwarf2_cu *spec_cu;
19960   struct type *parent_type;
19961   const char *retval;
19962
19963   if (cu->language != language_cplus
19964       && cu->language != language_fortran && cu->language != language_d
19965       && cu->language != language_rust)
19966     return "";
19967
19968   retval = anonymous_struct_prefix (die, cu);
19969   if (retval)
19970     return retval;
19971
19972   /* We have to be careful in the presence of DW_AT_specification.
19973      For example, with GCC 3.4, given the code
19974
19975      namespace N {
19976        void foo() {
19977          // Definition of N::foo.
19978        }
19979      }
19980
19981      then we'll have a tree of DIEs like this:
19982
19983      1: DW_TAG_compile_unit
19984        2: DW_TAG_namespace        // N
19985          3: DW_TAG_subprogram     // declaration of N::foo
19986        4: DW_TAG_subprogram       // definition of N::foo
19987             DW_AT_specification   // refers to die #3
19988
19989      Thus, when processing die #4, we have to pretend that we're in
19990      the context of its DW_AT_specification, namely the contex of die
19991      #3.  */
19992   spec_cu = cu;
19993   spec_die = die_specification (die, &spec_cu);
19994   if (spec_die == NULL)
19995     parent = die->parent;
19996   else
19997     {
19998       parent = spec_die->parent;
19999       cu = spec_cu;
20000     }
20001
20002   if (parent == NULL)
20003     return "";
20004   else if (parent->building_fullname)
20005     {
20006       const char *name;
20007       const char *parent_name;
20008
20009       /* It has been seen on RealView 2.2 built binaries,
20010          DW_TAG_template_type_param types actually _defined_ as
20011          children of the parent class:
20012
20013          enum E {};
20014          template class <class Enum> Class{};
20015          Class<enum E> class_e;
20016
20017          1: DW_TAG_class_type (Class)
20018            2: DW_TAG_enumeration_type (E)
20019              3: DW_TAG_enumerator (enum1:0)
20020              3: DW_TAG_enumerator (enum2:1)
20021              ...
20022            2: DW_TAG_template_type_param
20023               DW_AT_type  DW_FORM_ref_udata (E)
20024
20025          Besides being broken debug info, it can put GDB into an
20026          infinite loop.  Consider:
20027
20028          When we're building the full name for Class<E>, we'll start
20029          at Class, and go look over its template type parameters,
20030          finding E.  We'll then try to build the full name of E, and
20031          reach here.  We're now trying to build the full name of E,
20032          and look over the parent DIE for containing scope.  In the
20033          broken case, if we followed the parent DIE of E, we'd again
20034          find Class, and once again go look at its template type
20035          arguments, etc., etc.  Simply don't consider such parent die
20036          as source-level parent of this die (it can't be, the language
20037          doesn't allow it), and break the loop here.  */
20038       name = dwarf2_name (die, cu);
20039       parent_name = dwarf2_name (parent, cu);
20040       complaint (&symfile_complaints,
20041                  _("template param type '%s' defined within parent '%s'"),
20042                  name ? name : "<unknown>",
20043                  parent_name ? parent_name : "<unknown>");
20044       return "";
20045     }
20046   else
20047     switch (parent->tag)
20048       {
20049       case DW_TAG_namespace:
20050         parent_type = read_type_die (parent, cu);
20051         /* GCC 4.0 and 4.1 had a bug (PR c++/28460) where they generated bogus
20052            DW_TAG_namespace DIEs with a name of "::" for the global namespace.
20053            Work around this problem here.  */
20054         if (cu->language == language_cplus
20055             && strcmp (TYPE_TAG_NAME (parent_type), "::") == 0)
20056           return "";
20057         /* We give a name to even anonymous namespaces.  */
20058         return TYPE_TAG_NAME (parent_type);
20059       case DW_TAG_class_type:
20060       case DW_TAG_interface_type:
20061       case DW_TAG_structure_type:
20062       case DW_TAG_union_type:
20063       case DW_TAG_module:
20064         parent_type = read_type_die (parent, cu);
20065         if (TYPE_TAG_NAME (parent_type) != NULL)
20066           return TYPE_TAG_NAME (parent_type);
20067         else
20068           /* An anonymous structure is only allowed non-static data
20069              members; no typedefs, no member functions, et cetera.
20070              So it does not need a prefix.  */
20071           return "";
20072       case DW_TAG_compile_unit:
20073       case DW_TAG_partial_unit:
20074         /* gcc-4.5 -gdwarf-4 can drop the enclosing namespace.  Cope.  */
20075         if (cu->language == language_cplus
20076             && !VEC_empty (dwarf2_section_info_def, dwarf2_per_objfile->types)
20077             && die->child != NULL
20078             && (die->tag == DW_TAG_class_type
20079                 || die->tag == DW_TAG_structure_type
20080                 || die->tag == DW_TAG_union_type))
20081           {
20082             char *name = guess_full_die_structure_name (die, cu);
20083             if (name != NULL)
20084               return name;
20085           }
20086         return "";
20087       case DW_TAG_enumeration_type:
20088         parent_type = read_type_die (parent, cu);
20089         if (TYPE_DECLARED_CLASS (parent_type))
20090           {
20091             if (TYPE_TAG_NAME (parent_type) != NULL)
20092               return TYPE_TAG_NAME (parent_type);
20093             return "";
20094           }
20095         /* Fall through.  */
20096       default:
20097         return determine_prefix (parent, cu);
20098       }
20099 }
20100
20101 /* Return a newly-allocated string formed by concatenating PREFIX and SUFFIX
20102    with appropriate separator.  If PREFIX or SUFFIX is NULL or empty, then
20103    simply copy the SUFFIX or PREFIX, respectively.  If OBS is non-null, perform
20104    an obconcat, otherwise allocate storage for the result.  The CU argument is
20105    used to determine the language and hence, the appropriate separator.  */
20106
20107 #define MAX_SEP_LEN 7  /* strlen ("__") + strlen ("_MOD_")  */
20108
20109 static char *
20110 typename_concat (struct obstack *obs, const char *prefix, const char *suffix,
20111                  int physname, struct dwarf2_cu *cu)
20112 {
20113   const char *lead = "";
20114   const char *sep;
20115
20116   if (suffix == NULL || suffix[0] == '\0'
20117       || prefix == NULL || prefix[0] == '\0')
20118     sep = "";
20119   else if (cu->language == language_d)
20120     {
20121       /* For D, the 'main' function could be defined in any module, but it
20122          should never be prefixed.  */
20123       if (strcmp (suffix, "D main") == 0)
20124         {
20125           prefix = "";
20126           sep = "";
20127         }
20128       else
20129         sep = ".";
20130     }
20131   else if (cu->language == language_fortran && physname)
20132     {
20133       /* This is gfortran specific mangling.  Normally DW_AT_linkage_name or
20134          DW_AT_MIPS_linkage_name is preferred and used instead.  */
20135
20136       lead = "__";
20137       sep = "_MOD_";
20138     }
20139   else
20140     sep = "::";
20141
20142   if (prefix == NULL)
20143     prefix = "";
20144   if (suffix == NULL)
20145     suffix = "";
20146
20147   if (obs == NULL)
20148     {
20149       char *retval
20150         = ((char *)
20151            xmalloc (strlen (prefix) + MAX_SEP_LEN + strlen (suffix) + 1));
20152
20153       strcpy (retval, lead);
20154       strcat (retval, prefix);
20155       strcat (retval, sep);
20156       strcat (retval, suffix);
20157       return retval;
20158     }
20159   else
20160     {
20161       /* We have an obstack.  */
20162       return obconcat (obs, lead, prefix, sep, suffix, (char *) NULL);
20163     }
20164 }
20165
20166 /* Return sibling of die, NULL if no sibling.  */
20167
20168 static struct die_info *
20169 sibling_die (struct die_info *die)
20170 {
20171   return die->sibling;
20172 }
20173
20174 /* Get name of a die, return NULL if not found.  */
20175
20176 static const char *
20177 dwarf2_canonicalize_name (const char *name, struct dwarf2_cu *cu,
20178                           struct obstack *obstack)
20179 {
20180   if (name && cu->language == language_cplus)
20181     {
20182       std::string canon_name = cp_canonicalize_string (name);
20183
20184       if (!canon_name.empty ())
20185         {
20186           if (canon_name != name)
20187             name = (const char *) obstack_copy0 (obstack,
20188                                                  canon_name.c_str (),
20189                                                  canon_name.length ());
20190         }
20191     }
20192
20193   return name;
20194 }
20195
20196 /* Get name of a die, return NULL if not found.
20197    Anonymous namespaces are converted to their magic string.  */
20198
20199 static const char *
20200 dwarf2_name (struct die_info *die, struct dwarf2_cu *cu)
20201 {
20202   struct attribute *attr;
20203
20204   attr = dwarf2_attr (die, DW_AT_name, cu);
20205   if ((!attr || !DW_STRING (attr))
20206       && die->tag != DW_TAG_namespace
20207       && die->tag != DW_TAG_class_type
20208       && die->tag != DW_TAG_interface_type
20209       && die->tag != DW_TAG_structure_type
20210       && die->tag != DW_TAG_union_type)
20211     return NULL;
20212
20213   switch (die->tag)
20214     {
20215     case DW_TAG_compile_unit:
20216     case DW_TAG_partial_unit:
20217       /* Compilation units have a DW_AT_name that is a filename, not
20218          a source language identifier.  */
20219     case DW_TAG_enumeration_type:
20220     case DW_TAG_enumerator:
20221       /* These tags always have simple identifiers already; no need
20222          to canonicalize them.  */
20223       return DW_STRING (attr);
20224
20225     case DW_TAG_namespace:
20226       if (attr != NULL && DW_STRING (attr) != NULL)
20227         return DW_STRING (attr);
20228       return CP_ANONYMOUS_NAMESPACE_STR;
20229
20230     case DW_TAG_class_type:
20231     case DW_TAG_interface_type:
20232     case DW_TAG_structure_type:
20233     case DW_TAG_union_type:
20234       /* Some GCC versions emit spurious DW_AT_name attributes for unnamed
20235          structures or unions.  These were of the form "._%d" in GCC 4.1,
20236          or simply "<anonymous struct>" or "<anonymous union>" in GCC 4.3
20237          and GCC 4.4.  We work around this problem by ignoring these.  */
20238       if (attr && DW_STRING (attr)
20239           && (startswith (DW_STRING (attr), "._")
20240               || startswith (DW_STRING (attr), "<anonymous")))
20241         return NULL;
20242
20243       /* GCC might emit a nameless typedef that has a linkage name.  See
20244          http://gcc.gnu.org/bugzilla/show_bug.cgi?id=47510.  */
20245       if (!attr || DW_STRING (attr) == NULL)
20246         {
20247           char *demangled = NULL;
20248
20249           attr = dwarf2_attr (die, DW_AT_linkage_name, cu);
20250           if (attr == NULL)
20251             attr = dwarf2_attr (die, DW_AT_MIPS_linkage_name, cu);
20252
20253           if (attr == NULL || DW_STRING (attr) == NULL)
20254             return NULL;
20255
20256           /* Avoid demangling DW_STRING (attr) the second time on a second
20257              call for the same DIE.  */
20258           if (!DW_STRING_IS_CANONICAL (attr))
20259             demangled = gdb_demangle (DW_STRING (attr), DMGL_TYPES);
20260
20261           if (demangled)
20262             {
20263               const char *base;
20264
20265               /* FIXME: we already did this for the partial symbol... */
20266               DW_STRING (attr)
20267                 = ((const char *)
20268                    obstack_copy0 (&cu->objfile->per_bfd->storage_obstack,
20269                                   demangled, strlen (demangled)));
20270               DW_STRING_IS_CANONICAL (attr) = 1;
20271               xfree (demangled);
20272
20273               /* Strip any leading namespaces/classes, keep only the base name.
20274                  DW_AT_name for named DIEs does not contain the prefixes.  */
20275               base = strrchr (DW_STRING (attr), ':');
20276               if (base && base > DW_STRING (attr) && base[-1] == ':')
20277                 return &base[1];
20278               else
20279                 return DW_STRING (attr);
20280             }
20281         }
20282       break;
20283
20284     default:
20285       break;
20286     }
20287
20288   if (!DW_STRING_IS_CANONICAL (attr))
20289     {
20290       DW_STRING (attr)
20291         = dwarf2_canonicalize_name (DW_STRING (attr), cu,
20292                                     &cu->objfile->per_bfd->storage_obstack);
20293       DW_STRING_IS_CANONICAL (attr) = 1;
20294     }
20295   return DW_STRING (attr);
20296 }
20297
20298 /* Return the die that this die in an extension of, or NULL if there
20299    is none.  *EXT_CU is the CU containing DIE on input, and the CU
20300    containing the return value on output.  */
20301
20302 static struct die_info *
20303 dwarf2_extension (struct die_info *die, struct dwarf2_cu **ext_cu)
20304 {
20305   struct attribute *attr;
20306
20307   attr = dwarf2_attr (die, DW_AT_extension, *ext_cu);
20308   if (attr == NULL)
20309     return NULL;
20310
20311   return follow_die_ref (die, attr, ext_cu);
20312 }
20313
20314 /* Convert a DIE tag into its string name.  */
20315
20316 static const char *
20317 dwarf_tag_name (unsigned tag)
20318 {
20319   const char *name = get_DW_TAG_name (tag);
20320
20321   if (name == NULL)
20322     return "DW_TAG_<unknown>";
20323
20324   return name;
20325 }
20326
20327 /* Convert a DWARF attribute code into its string name.  */
20328
20329 static const char *
20330 dwarf_attr_name (unsigned attr)
20331 {
20332   const char *name;
20333
20334 #ifdef MIPS /* collides with DW_AT_HP_block_index */
20335   if (attr == DW_AT_MIPS_fde)
20336     return "DW_AT_MIPS_fde";
20337 #else
20338   if (attr == DW_AT_HP_block_index)
20339     return "DW_AT_HP_block_index";
20340 #endif
20341
20342   name = get_DW_AT_name (attr);
20343
20344   if (name == NULL)
20345     return "DW_AT_<unknown>";
20346
20347   return name;
20348 }
20349
20350 /* Convert a DWARF value form code into its string name.  */
20351
20352 static const char *
20353 dwarf_form_name (unsigned form)
20354 {
20355   const char *name = get_DW_FORM_name (form);
20356
20357   if (name == NULL)
20358     return "DW_FORM_<unknown>";
20359
20360   return name;
20361 }
20362
20363 static const char *
20364 dwarf_bool_name (unsigned mybool)
20365 {
20366   if (mybool)
20367     return "TRUE";
20368   else
20369     return "FALSE";
20370 }
20371
20372 /* Convert a DWARF type code into its string name.  */
20373
20374 static const char *
20375 dwarf_type_encoding_name (unsigned enc)
20376 {
20377   const char *name = get_DW_ATE_name (enc);
20378
20379   if (name == NULL)
20380     return "DW_ATE_<unknown>";
20381
20382   return name;
20383 }
20384
20385 static void
20386 dump_die_shallow (struct ui_file *f, int indent, struct die_info *die)
20387 {
20388   unsigned int i;
20389
20390   print_spaces (indent, f);
20391   fprintf_unfiltered (f, "Die: %s (abbrev %d, offset 0x%x)\n",
20392                       dwarf_tag_name (die->tag), die->abbrev,
20393                       to_underlying (die->sect_off));
20394
20395   if (die->parent != NULL)
20396     {
20397       print_spaces (indent, f);
20398       fprintf_unfiltered (f, "  parent at offset: 0x%x\n",
20399                           to_underlying (die->parent->sect_off));
20400     }
20401
20402   print_spaces (indent, f);
20403   fprintf_unfiltered (f, "  has children: %s\n",
20404            dwarf_bool_name (die->child != NULL));
20405
20406   print_spaces (indent, f);
20407   fprintf_unfiltered (f, "  attributes:\n");
20408
20409   for (i = 0; i < die->num_attrs; ++i)
20410     {
20411       print_spaces (indent, f);
20412       fprintf_unfiltered (f, "    %s (%s) ",
20413                dwarf_attr_name (die->attrs[i].name),
20414                dwarf_form_name (die->attrs[i].form));
20415
20416       switch (die->attrs[i].form)
20417         {
20418         case DW_FORM_addr:
20419         case DW_FORM_GNU_addr_index:
20420           fprintf_unfiltered (f, "address: ");
20421           fputs_filtered (hex_string (DW_ADDR (&die->attrs[i])), f);
20422           break;
20423         case DW_FORM_block2:
20424         case DW_FORM_block4:
20425         case DW_FORM_block:
20426         case DW_FORM_block1:
20427           fprintf_unfiltered (f, "block: size %s",
20428                               pulongest (DW_BLOCK (&die->attrs[i])->size));
20429           break;
20430         case DW_FORM_exprloc:
20431           fprintf_unfiltered (f, "expression: size %s",
20432                               pulongest (DW_BLOCK (&die->attrs[i])->size));
20433           break;
20434         case DW_FORM_data16:
20435           fprintf_unfiltered (f, "constant of 16 bytes");
20436           break;
20437         case DW_FORM_ref_addr:
20438           fprintf_unfiltered (f, "ref address: ");
20439           fputs_filtered (hex_string (DW_UNSND (&die->attrs[i])), f);
20440           break;
20441         case DW_FORM_GNU_ref_alt:
20442           fprintf_unfiltered (f, "alt ref address: ");
20443           fputs_filtered (hex_string (DW_UNSND (&die->attrs[i])), f);
20444           break;
20445         case DW_FORM_ref1:
20446         case DW_FORM_ref2:
20447         case DW_FORM_ref4:
20448         case DW_FORM_ref8:
20449         case DW_FORM_ref_udata:
20450           fprintf_unfiltered (f, "constant ref: 0x%lx (adjusted)",
20451                               (long) (DW_UNSND (&die->attrs[i])));
20452           break;
20453         case DW_FORM_data1:
20454         case DW_FORM_data2:
20455         case DW_FORM_data4:
20456         case DW_FORM_data8:
20457         case DW_FORM_udata:
20458         case DW_FORM_sdata:
20459           fprintf_unfiltered (f, "constant: %s",
20460                               pulongest (DW_UNSND (&die->attrs[i])));
20461           break;
20462         case DW_FORM_sec_offset:
20463           fprintf_unfiltered (f, "section offset: %s",
20464                               pulongest (DW_UNSND (&die->attrs[i])));
20465           break;
20466         case DW_FORM_ref_sig8:
20467           fprintf_unfiltered (f, "signature: %s",
20468                               hex_string (DW_SIGNATURE (&die->attrs[i])));
20469           break;
20470         case DW_FORM_string:
20471         case DW_FORM_strp:
20472         case DW_FORM_line_strp:
20473         case DW_FORM_GNU_str_index:
20474         case DW_FORM_GNU_strp_alt:
20475           fprintf_unfiltered (f, "string: \"%s\" (%s canonicalized)",
20476                    DW_STRING (&die->attrs[i])
20477                    ? DW_STRING (&die->attrs[i]) : "",
20478                    DW_STRING_IS_CANONICAL (&die->attrs[i]) ? "is" : "not");
20479           break;
20480         case DW_FORM_flag:
20481           if (DW_UNSND (&die->attrs[i]))
20482             fprintf_unfiltered (f, "flag: TRUE");
20483           else
20484             fprintf_unfiltered (f, "flag: FALSE");
20485           break;
20486         case DW_FORM_flag_present:
20487           fprintf_unfiltered (f, "flag: TRUE");
20488           break;
20489         case DW_FORM_indirect:
20490           /* The reader will have reduced the indirect form to
20491              the "base form" so this form should not occur.  */
20492           fprintf_unfiltered (f, 
20493                               "unexpected attribute form: DW_FORM_indirect");
20494           break;
20495         default:
20496           fprintf_unfiltered (f, "unsupported attribute form: %d.",
20497                    die->attrs[i].form);
20498           break;
20499         }
20500       fprintf_unfiltered (f, "\n");
20501     }
20502 }
20503
20504 static void
20505 dump_die_for_error (struct die_info *die)
20506 {
20507   dump_die_shallow (gdb_stderr, 0, die);
20508 }
20509
20510 static void
20511 dump_die_1 (struct ui_file *f, int level, int max_level, struct die_info *die)
20512 {
20513   int indent = level * 4;
20514
20515   gdb_assert (die != NULL);
20516
20517   if (level >= max_level)
20518     return;
20519
20520   dump_die_shallow (f, indent, die);
20521
20522   if (die->child != NULL)
20523     {
20524       print_spaces (indent, f);
20525       fprintf_unfiltered (f, "  Children:");
20526       if (level + 1 < max_level)
20527         {
20528           fprintf_unfiltered (f, "\n");
20529           dump_die_1 (f, level + 1, max_level, die->child);
20530         }
20531       else
20532         {
20533           fprintf_unfiltered (f,
20534                               " [not printed, max nesting level reached]\n");
20535         }
20536     }
20537
20538   if (die->sibling != NULL && level > 0)
20539     {
20540       dump_die_1 (f, level, max_level, die->sibling);
20541     }
20542 }
20543
20544 /* This is called from the pdie macro in gdbinit.in.
20545    It's not static so gcc will keep a copy callable from gdb.  */
20546
20547 void
20548 dump_die (struct die_info *die, int max_level)
20549 {
20550   dump_die_1 (gdb_stdlog, 0, max_level, die);
20551 }
20552
20553 static void
20554 store_in_ref_table (struct die_info *die, struct dwarf2_cu *cu)
20555 {
20556   void **slot;
20557
20558   slot = htab_find_slot_with_hash (cu->die_hash, die,
20559                                    to_underlying (die->sect_off),
20560                                    INSERT);
20561
20562   *slot = die;
20563 }
20564
20565 /* Return DIE offset of ATTR.  Return 0 with complaint if ATTR is not of the
20566    required kind.  */
20567
20568 static sect_offset
20569 dwarf2_get_ref_die_offset (const struct attribute *attr)
20570 {
20571   if (attr_form_is_ref (attr))
20572     return (sect_offset) DW_UNSND (attr);
20573
20574   complaint (&symfile_complaints,
20575              _("unsupported die ref attribute form: '%s'"),
20576              dwarf_form_name (attr->form));
20577   return {};
20578 }
20579
20580 /* Return the constant value held by ATTR.  Return DEFAULT_VALUE if
20581  * the value held by the attribute is not constant.  */
20582
20583 static LONGEST
20584 dwarf2_get_attr_constant_value (const struct attribute *attr, int default_value)
20585 {
20586   if (attr->form == DW_FORM_sdata)
20587     return DW_SND (attr);
20588   else if (attr->form == DW_FORM_udata
20589            || attr->form == DW_FORM_data1
20590            || attr->form == DW_FORM_data2
20591            || attr->form == DW_FORM_data4
20592            || attr->form == DW_FORM_data8)
20593     return DW_UNSND (attr);
20594   else
20595     {
20596       /* For DW_FORM_data16 see attr_form_is_constant.  */
20597       complaint (&symfile_complaints,
20598                  _("Attribute value is not a constant (%s)"),
20599                  dwarf_form_name (attr->form));
20600       return default_value;
20601     }
20602 }
20603
20604 /* Follow reference or signature attribute ATTR of SRC_DIE.
20605    On entry *REF_CU is the CU of SRC_DIE.
20606    On exit *REF_CU is the CU of the result.  */
20607
20608 static struct die_info *
20609 follow_die_ref_or_sig (struct die_info *src_die, const struct attribute *attr,
20610                        struct dwarf2_cu **ref_cu)
20611 {
20612   struct die_info *die;
20613
20614   if (attr_form_is_ref (attr))
20615     die = follow_die_ref (src_die, attr, ref_cu);
20616   else if (attr->form == DW_FORM_ref_sig8)
20617     die = follow_die_sig (src_die, attr, ref_cu);
20618   else
20619     {
20620       dump_die_for_error (src_die);
20621       error (_("Dwarf Error: Expected reference attribute [in module %s]"),
20622              objfile_name ((*ref_cu)->objfile));
20623     }
20624
20625   return die;
20626 }
20627
20628 /* Follow reference OFFSET.
20629    On entry *REF_CU is the CU of the source die referencing OFFSET.
20630    On exit *REF_CU is the CU of the result.
20631    Returns NULL if OFFSET is invalid.  */
20632
20633 static struct die_info *
20634 follow_die_offset (sect_offset sect_off, int offset_in_dwz,
20635                    struct dwarf2_cu **ref_cu)
20636 {
20637   struct die_info temp_die;
20638   struct dwarf2_cu *target_cu, *cu = *ref_cu;
20639
20640   gdb_assert (cu->per_cu != NULL);
20641
20642   target_cu = cu;
20643
20644   if (cu->per_cu->is_debug_types)
20645     {
20646       /* .debug_types CUs cannot reference anything outside their CU.
20647          If they need to, they have to reference a signatured type via
20648          DW_FORM_ref_sig8.  */
20649       if (!offset_in_cu_p (&cu->header, sect_off))
20650         return NULL;
20651     }
20652   else if (offset_in_dwz != cu->per_cu->is_dwz
20653            || !offset_in_cu_p (&cu->header, sect_off))
20654     {
20655       struct dwarf2_per_cu_data *per_cu;
20656
20657       per_cu = dwarf2_find_containing_comp_unit (sect_off, offset_in_dwz,
20658                                                  cu->objfile);
20659
20660       /* If necessary, add it to the queue and load its DIEs.  */
20661       if (maybe_queue_comp_unit (cu, per_cu, cu->language))
20662         load_full_comp_unit (per_cu, cu->language);
20663
20664       target_cu = per_cu->cu;
20665     }
20666   else if (cu->dies == NULL)
20667     {
20668       /* We're loading full DIEs during partial symbol reading.  */
20669       gdb_assert (dwarf2_per_objfile->reading_partial_symbols);
20670       load_full_comp_unit (cu->per_cu, language_minimal);
20671     }
20672
20673   *ref_cu = target_cu;
20674   temp_die.sect_off = sect_off;
20675   return (struct die_info *) htab_find_with_hash (target_cu->die_hash,
20676                                                   &temp_die,
20677                                                   to_underlying (sect_off));
20678 }
20679
20680 /* Follow reference attribute ATTR of SRC_DIE.
20681    On entry *REF_CU is the CU of SRC_DIE.
20682    On exit *REF_CU is the CU of the result.  */
20683
20684 static struct die_info *
20685 follow_die_ref (struct die_info *src_die, const struct attribute *attr,
20686                 struct dwarf2_cu **ref_cu)
20687 {
20688   sect_offset sect_off = dwarf2_get_ref_die_offset (attr);
20689   struct dwarf2_cu *cu = *ref_cu;
20690   struct die_info *die;
20691
20692   die = follow_die_offset (sect_off,
20693                            (attr->form == DW_FORM_GNU_ref_alt
20694                             || cu->per_cu->is_dwz),
20695                            ref_cu);
20696   if (!die)
20697     error (_("Dwarf Error: Cannot find DIE at 0x%x referenced from DIE "
20698            "at 0x%x [in module %s]"),
20699            to_underlying (sect_off), to_underlying (src_die->sect_off),
20700            objfile_name (cu->objfile));
20701
20702   return die;
20703 }
20704
20705 /* Return DWARF block referenced by DW_AT_location of DIE at SECT_OFF at PER_CU.
20706    Returned value is intended for DW_OP_call*.  Returned
20707    dwarf2_locexpr_baton->data has lifetime of PER_CU->OBJFILE.  */
20708
20709 struct dwarf2_locexpr_baton
20710 dwarf2_fetch_die_loc_sect_off (sect_offset sect_off,
20711                                struct dwarf2_per_cu_data *per_cu,
20712                                CORE_ADDR (*get_frame_pc) (void *baton),
20713                                void *baton)
20714 {
20715   struct dwarf2_cu *cu;
20716   struct die_info *die;
20717   struct attribute *attr;
20718   struct dwarf2_locexpr_baton retval;
20719
20720   dw2_setup (per_cu->objfile);
20721
20722   if (per_cu->cu == NULL)
20723     load_cu (per_cu);
20724   cu = per_cu->cu;
20725   if (cu == NULL)
20726     {
20727       /* We shouldn't get here for a dummy CU, but don't crash on the user.
20728          Instead just throw an error, not much else we can do.  */
20729       error (_("Dwarf Error: Dummy CU at 0x%x referenced in module %s"),
20730              to_underlying (sect_off), objfile_name (per_cu->objfile));
20731     }
20732
20733   die = follow_die_offset (sect_off, per_cu->is_dwz, &cu);
20734   if (!die)
20735     error (_("Dwarf Error: Cannot find DIE at 0x%x referenced in module %s"),
20736            to_underlying (sect_off), objfile_name (per_cu->objfile));
20737
20738   attr = dwarf2_attr (die, DW_AT_location, cu);
20739   if (!attr)
20740     {
20741       /* DWARF: "If there is no such attribute, then there is no effect.".
20742          DATA is ignored if SIZE is 0.  */
20743
20744       retval.data = NULL;
20745       retval.size = 0;
20746     }
20747   else if (attr_form_is_section_offset (attr))
20748     {
20749       struct dwarf2_loclist_baton loclist_baton;
20750       CORE_ADDR pc = (*get_frame_pc) (baton);
20751       size_t size;
20752
20753       fill_in_loclist_baton (cu, &loclist_baton, attr);
20754
20755       retval.data = dwarf2_find_location_expression (&loclist_baton,
20756                                                      &size, pc);
20757       retval.size = size;
20758     }
20759   else
20760     {
20761       if (!attr_form_is_block (attr))
20762         error (_("Dwarf Error: DIE at 0x%x referenced in module %s "
20763                  "is neither DW_FORM_block* nor DW_FORM_exprloc"),
20764                to_underlying (sect_off), objfile_name (per_cu->objfile));
20765
20766       retval.data = DW_BLOCK (attr)->data;
20767       retval.size = DW_BLOCK (attr)->size;
20768     }
20769   retval.per_cu = cu->per_cu;
20770
20771   age_cached_comp_units ();
20772
20773   return retval;
20774 }
20775
20776 /* Like dwarf2_fetch_die_loc_sect_off, but take a CU
20777    offset.  */
20778
20779 struct dwarf2_locexpr_baton
20780 dwarf2_fetch_die_loc_cu_off (cu_offset offset_in_cu,
20781                              struct dwarf2_per_cu_data *per_cu,
20782                              CORE_ADDR (*get_frame_pc) (void *baton),
20783                              void *baton)
20784 {
20785   sect_offset sect_off = per_cu->sect_off + to_underlying (offset_in_cu);
20786
20787   return dwarf2_fetch_die_loc_sect_off (sect_off, per_cu, get_frame_pc, baton);
20788 }
20789
20790 /* Write a constant of a given type as target-ordered bytes into
20791    OBSTACK.  */
20792
20793 static const gdb_byte *
20794 write_constant_as_bytes (struct obstack *obstack,
20795                          enum bfd_endian byte_order,
20796                          struct type *type,
20797                          ULONGEST value,
20798                          LONGEST *len)
20799 {
20800   gdb_byte *result;
20801
20802   *len = TYPE_LENGTH (type);
20803   result = (gdb_byte *) obstack_alloc (obstack, *len);
20804   store_unsigned_integer (result, *len, byte_order, value);
20805
20806   return result;
20807 }
20808
20809 /* If the DIE at OFFSET in PER_CU has a DW_AT_const_value, return a
20810    pointer to the constant bytes and set LEN to the length of the
20811    data.  If memory is needed, allocate it on OBSTACK.  If the DIE
20812    does not have a DW_AT_const_value, return NULL.  */
20813
20814 const gdb_byte *
20815 dwarf2_fetch_constant_bytes (sect_offset sect_off,
20816                              struct dwarf2_per_cu_data *per_cu,
20817                              struct obstack *obstack,
20818                              LONGEST *len)
20819 {
20820   struct dwarf2_cu *cu;
20821   struct die_info *die;
20822   struct attribute *attr;
20823   const gdb_byte *result = NULL;
20824   struct type *type;
20825   LONGEST value;
20826   enum bfd_endian byte_order;
20827
20828   dw2_setup (per_cu->objfile);
20829
20830   if (per_cu->cu == NULL)
20831     load_cu (per_cu);
20832   cu = per_cu->cu;
20833   if (cu == NULL)
20834     {
20835       /* We shouldn't get here for a dummy CU, but don't crash on the user.
20836          Instead just throw an error, not much else we can do.  */
20837       error (_("Dwarf Error: Dummy CU at 0x%x referenced in module %s"),
20838              to_underlying (sect_off), objfile_name (per_cu->objfile));
20839     }
20840
20841   die = follow_die_offset (sect_off, per_cu->is_dwz, &cu);
20842   if (!die)
20843     error (_("Dwarf Error: Cannot find DIE at 0x%x referenced in module %s"),
20844            to_underlying (sect_off), objfile_name (per_cu->objfile));
20845
20846
20847   attr = dwarf2_attr (die, DW_AT_const_value, cu);
20848   if (attr == NULL)
20849     return NULL;
20850
20851   byte_order = (bfd_big_endian (per_cu->objfile->obfd)
20852                 ? BFD_ENDIAN_BIG : BFD_ENDIAN_LITTLE);
20853
20854   switch (attr->form)
20855     {
20856     case DW_FORM_addr:
20857     case DW_FORM_GNU_addr_index:
20858       {
20859         gdb_byte *tem;
20860
20861         *len = cu->header.addr_size;
20862         tem = (gdb_byte *) obstack_alloc (obstack, *len);
20863         store_unsigned_integer (tem, *len, byte_order, DW_ADDR (attr));
20864         result = tem;
20865       }
20866       break;
20867     case DW_FORM_string:
20868     case DW_FORM_strp:
20869     case DW_FORM_GNU_str_index:
20870     case DW_FORM_GNU_strp_alt:
20871       /* DW_STRING is already allocated on the objfile obstack, point
20872          directly to it.  */
20873       result = (const gdb_byte *) DW_STRING (attr);
20874       *len = strlen (DW_STRING (attr));
20875       break;
20876     case DW_FORM_block1:
20877     case DW_FORM_block2:
20878     case DW_FORM_block4:
20879     case DW_FORM_block:
20880     case DW_FORM_exprloc:
20881     case DW_FORM_data16:
20882       result = DW_BLOCK (attr)->data;
20883       *len = DW_BLOCK (attr)->size;
20884       break;
20885
20886       /* The DW_AT_const_value attributes are supposed to carry the
20887          symbol's value "represented as it would be on the target
20888          architecture."  By the time we get here, it's already been
20889          converted to host endianness, so we just need to sign- or
20890          zero-extend it as appropriate.  */
20891     case DW_FORM_data1:
20892       type = die_type (die, cu);
20893       result = dwarf2_const_value_data (attr, obstack, cu, &value, 8);
20894       if (result == NULL)
20895         result = write_constant_as_bytes (obstack, byte_order,
20896                                           type, value, len);
20897       break;
20898     case DW_FORM_data2:
20899       type = die_type (die, cu);
20900       result = dwarf2_const_value_data (attr, obstack, cu, &value, 16);
20901       if (result == NULL)
20902         result = write_constant_as_bytes (obstack, byte_order,
20903                                           type, value, len);
20904       break;
20905     case DW_FORM_data4:
20906       type = die_type (die, cu);
20907       result = dwarf2_const_value_data (attr, obstack, cu, &value, 32);
20908       if (result == NULL)
20909         result = write_constant_as_bytes (obstack, byte_order,
20910                                           type, value, len);
20911       break;
20912     case DW_FORM_data8:
20913       type = die_type (die, cu);
20914       result = dwarf2_const_value_data (attr, obstack, cu, &value, 64);
20915       if (result == NULL)
20916         result = write_constant_as_bytes (obstack, byte_order,
20917                                           type, value, len);
20918       break;
20919
20920     case DW_FORM_sdata:
20921       type = die_type (die, cu);
20922       result = write_constant_as_bytes (obstack, byte_order,
20923                                         type, DW_SND (attr), len);
20924       break;
20925
20926     case DW_FORM_udata:
20927       type = die_type (die, cu);
20928       result = write_constant_as_bytes (obstack, byte_order,
20929                                         type, DW_UNSND (attr), len);
20930       break;
20931
20932     default:
20933       complaint (&symfile_complaints,
20934                  _("unsupported const value attribute form: '%s'"),
20935                  dwarf_form_name (attr->form));
20936       break;
20937     }
20938
20939   return result;
20940 }
20941
20942 /* Return the type of the die at OFFSET in PER_CU.  Return NULL if no
20943    valid type for this die is found.  */
20944
20945 struct type *
20946 dwarf2_fetch_die_type_sect_off (sect_offset sect_off,
20947                                 struct dwarf2_per_cu_data *per_cu)
20948 {
20949   struct dwarf2_cu *cu;
20950   struct die_info *die;
20951
20952   dw2_setup (per_cu->objfile);
20953
20954   if (per_cu->cu == NULL)
20955     load_cu (per_cu);
20956   cu = per_cu->cu;
20957   if (!cu)
20958     return NULL;
20959
20960   die = follow_die_offset (sect_off, per_cu->is_dwz, &cu);
20961   if (!die)
20962     return NULL;
20963
20964   return die_type (die, cu);
20965 }
20966
20967 /* Return the type of the DIE at DIE_OFFSET in the CU named by
20968    PER_CU.  */
20969
20970 struct type *
20971 dwarf2_get_die_type (cu_offset die_offset,
20972                      struct dwarf2_per_cu_data *per_cu)
20973 {
20974   dw2_setup (per_cu->objfile);
20975
20976   sect_offset die_offset_sect = per_cu->sect_off + to_underlying (die_offset);
20977   return get_die_type_at_offset (die_offset_sect, per_cu);
20978 }
20979
20980 /* Follow type unit SIG_TYPE referenced by SRC_DIE.
20981    On entry *REF_CU is the CU of SRC_DIE.
20982    On exit *REF_CU is the CU of the result.
20983    Returns NULL if the referenced DIE isn't found.  */
20984
20985 static struct die_info *
20986 follow_die_sig_1 (struct die_info *src_die, struct signatured_type *sig_type,
20987                   struct dwarf2_cu **ref_cu)
20988 {
20989   struct die_info temp_die;
20990   struct dwarf2_cu *sig_cu;
20991   struct die_info *die;
20992
20993   /* While it might be nice to assert sig_type->type == NULL here,
20994      we can get here for DW_AT_imported_declaration where we need
20995      the DIE not the type.  */
20996
20997   /* If necessary, add it to the queue and load its DIEs.  */
20998
20999   if (maybe_queue_comp_unit (*ref_cu, &sig_type->per_cu, language_minimal))
21000     read_signatured_type (sig_type);
21001
21002   sig_cu = sig_type->per_cu.cu;
21003   gdb_assert (sig_cu != NULL);
21004   gdb_assert (to_underlying (sig_type->type_offset_in_section) != 0);
21005   temp_die.sect_off = sig_type->type_offset_in_section;
21006   die = (struct die_info *) htab_find_with_hash (sig_cu->die_hash, &temp_die,
21007                                                  to_underlying (temp_die.sect_off));
21008   if (die)
21009     {
21010       /* For .gdb_index version 7 keep track of included TUs.
21011          http://sourceware.org/bugzilla/show_bug.cgi?id=15021.  */
21012       if (dwarf2_per_objfile->index_table != NULL
21013           && dwarf2_per_objfile->index_table->version <= 7)
21014         {
21015           VEC_safe_push (dwarf2_per_cu_ptr,
21016                          (*ref_cu)->per_cu->imported_symtabs,
21017                          sig_cu->per_cu);
21018         }
21019
21020       *ref_cu = sig_cu;
21021       return die;
21022     }
21023
21024   return NULL;
21025 }
21026
21027 /* Follow signatured type referenced by ATTR in SRC_DIE.
21028    On entry *REF_CU is the CU of SRC_DIE.
21029    On exit *REF_CU is the CU of the result.
21030    The result is the DIE of the type.
21031    If the referenced type cannot be found an error is thrown.  */
21032
21033 static struct die_info *
21034 follow_die_sig (struct die_info *src_die, const struct attribute *attr,
21035                 struct dwarf2_cu **ref_cu)
21036 {
21037   ULONGEST signature = DW_SIGNATURE (attr);
21038   struct signatured_type *sig_type;
21039   struct die_info *die;
21040
21041   gdb_assert (attr->form == DW_FORM_ref_sig8);
21042
21043   sig_type = lookup_signatured_type (*ref_cu, signature);
21044   /* sig_type will be NULL if the signatured type is missing from
21045      the debug info.  */
21046   if (sig_type == NULL)
21047     {
21048       error (_("Dwarf Error: Cannot find signatured DIE %s referenced"
21049                " from DIE at 0x%x [in module %s]"),
21050              hex_string (signature), to_underlying (src_die->sect_off),
21051              objfile_name ((*ref_cu)->objfile));
21052     }
21053
21054   die = follow_die_sig_1 (src_die, sig_type, ref_cu);
21055   if (die == NULL)
21056     {
21057       dump_die_for_error (src_die);
21058       error (_("Dwarf Error: Problem reading signatured DIE %s referenced"
21059                " from DIE at 0x%x [in module %s]"),
21060              hex_string (signature), to_underlying (src_die->sect_off),
21061              objfile_name ((*ref_cu)->objfile));
21062     }
21063
21064   return die;
21065 }
21066
21067 /* Get the type specified by SIGNATURE referenced in DIE/CU,
21068    reading in and processing the type unit if necessary.  */
21069
21070 static struct type *
21071 get_signatured_type (struct die_info *die, ULONGEST signature,
21072                      struct dwarf2_cu *cu)
21073 {
21074   struct signatured_type *sig_type;
21075   struct dwarf2_cu *type_cu;
21076   struct die_info *type_die;
21077   struct type *type;
21078
21079   sig_type = lookup_signatured_type (cu, signature);
21080   /* sig_type will be NULL if the signatured type is missing from
21081      the debug info.  */
21082   if (sig_type == NULL)
21083     {
21084       complaint (&symfile_complaints,
21085                  _("Dwarf Error: Cannot find signatured DIE %s referenced"
21086                    " from DIE at 0x%x [in module %s]"),
21087                  hex_string (signature), to_underlying (die->sect_off),
21088                  objfile_name (dwarf2_per_objfile->objfile));
21089       return build_error_marker_type (cu, die);
21090     }
21091
21092   /* If we already know the type we're done.  */
21093   if (sig_type->type != NULL)
21094     return sig_type->type;
21095
21096   type_cu = cu;
21097   type_die = follow_die_sig_1 (die, sig_type, &type_cu);
21098   if (type_die != NULL)
21099     {
21100       /* N.B. We need to call get_die_type to ensure only one type for this DIE
21101          is created.  This is important, for example, because for c++ classes
21102          we need TYPE_NAME set which is only done by new_symbol.  Blech.  */
21103       type = read_type_die (type_die, type_cu);
21104       if (type == NULL)
21105         {
21106           complaint (&symfile_complaints,
21107                      _("Dwarf Error: Cannot build signatured type %s"
21108                        " referenced from DIE at 0x%x [in module %s]"),
21109                      hex_string (signature), to_underlying (die->sect_off),
21110                      objfile_name (dwarf2_per_objfile->objfile));
21111           type = build_error_marker_type (cu, die);
21112         }
21113     }
21114   else
21115     {
21116       complaint (&symfile_complaints,
21117                  _("Dwarf Error: Problem reading signatured DIE %s referenced"
21118                    " from DIE at 0x%x [in module %s]"),
21119                  hex_string (signature), to_underlying (die->sect_off),
21120                  objfile_name (dwarf2_per_objfile->objfile));
21121       type = build_error_marker_type (cu, die);
21122     }
21123   sig_type->type = type;
21124
21125   return type;
21126 }
21127
21128 /* Get the type specified by the DW_AT_signature ATTR in DIE/CU,
21129    reading in and processing the type unit if necessary.  */
21130
21131 static struct type *
21132 get_DW_AT_signature_type (struct die_info *die, const struct attribute *attr,
21133                           struct dwarf2_cu *cu) /* ARI: editCase function */
21134 {
21135   /* Yes, DW_AT_signature can use a non-ref_sig8 reference.  */
21136   if (attr_form_is_ref (attr))
21137     {
21138       struct dwarf2_cu *type_cu = cu;
21139       struct die_info *type_die = follow_die_ref (die, attr, &type_cu);
21140
21141       return read_type_die (type_die, type_cu);
21142     }
21143   else if (attr->form == DW_FORM_ref_sig8)
21144     {
21145       return get_signatured_type (die, DW_SIGNATURE (attr), cu);
21146     }
21147   else
21148     {
21149       complaint (&symfile_complaints,
21150                  _("Dwarf Error: DW_AT_signature has bad form %s in DIE"
21151                    " at 0x%x [in module %s]"),
21152                  dwarf_form_name (attr->form), to_underlying (die->sect_off),
21153                  objfile_name (dwarf2_per_objfile->objfile));
21154       return build_error_marker_type (cu, die);
21155     }
21156 }
21157
21158 /* Load the DIEs associated with type unit PER_CU into memory.  */
21159
21160 static void
21161 load_full_type_unit (struct dwarf2_per_cu_data *per_cu)
21162 {
21163   struct signatured_type *sig_type;
21164
21165   /* Caller is responsible for ensuring type_unit_groups don't get here.  */
21166   gdb_assert (! IS_TYPE_UNIT_GROUP (per_cu));
21167
21168   /* We have the per_cu, but we need the signatured_type.
21169      Fortunately this is an easy translation.  */
21170   gdb_assert (per_cu->is_debug_types);
21171   sig_type = (struct signatured_type *) per_cu;
21172
21173   gdb_assert (per_cu->cu == NULL);
21174
21175   read_signatured_type (sig_type);
21176
21177   gdb_assert (per_cu->cu != NULL);
21178 }
21179
21180 /* die_reader_func for read_signatured_type.
21181    This is identical to load_full_comp_unit_reader,
21182    but is kept separate for now.  */
21183
21184 static void
21185 read_signatured_type_reader (const struct die_reader_specs *reader,
21186                              const gdb_byte *info_ptr,
21187                              struct die_info *comp_unit_die,
21188                              int has_children,
21189                              void *data)
21190 {
21191   struct dwarf2_cu *cu = reader->cu;
21192
21193   gdb_assert (cu->die_hash == NULL);
21194   cu->die_hash =
21195     htab_create_alloc_ex (cu->header.length / 12,
21196                           die_hash,
21197                           die_eq,
21198                           NULL,
21199                           &cu->comp_unit_obstack,
21200                           hashtab_obstack_allocate,
21201                           dummy_obstack_deallocate);
21202
21203   if (has_children)
21204     comp_unit_die->child = read_die_and_siblings (reader, info_ptr,
21205                                                   &info_ptr, comp_unit_die);
21206   cu->dies = comp_unit_die;
21207   /* comp_unit_die is not stored in die_hash, no need.  */
21208
21209   /* We try not to read any attributes in this function, because not
21210      all CUs needed for references have been loaded yet, and symbol
21211      table processing isn't initialized.  But we have to set the CU language,
21212      or we won't be able to build types correctly.
21213      Similarly, if we do not read the producer, we can not apply
21214      producer-specific interpretation.  */
21215   prepare_one_comp_unit (cu, cu->dies, language_minimal);
21216 }
21217
21218 /* Read in a signatured type and build its CU and DIEs.
21219    If the type is a stub for the real type in a DWO file,
21220    read in the real type from the DWO file as well.  */
21221
21222 static void
21223 read_signatured_type (struct signatured_type *sig_type)
21224 {
21225   struct dwarf2_per_cu_data *per_cu = &sig_type->per_cu;
21226
21227   gdb_assert (per_cu->is_debug_types);
21228   gdb_assert (per_cu->cu == NULL);
21229
21230   init_cutu_and_read_dies (per_cu, NULL, 0, 1,
21231                            read_signatured_type_reader, NULL);
21232   sig_type->per_cu.tu_read = 1;
21233 }
21234
21235 /* Decode simple location descriptions.
21236    Given a pointer to a dwarf block that defines a location, compute
21237    the location and return the value.
21238
21239    NOTE drow/2003-11-18: This function is called in two situations
21240    now: for the address of static or global variables (partial symbols
21241    only) and for offsets into structures which are expected to be
21242    (more or less) constant.  The partial symbol case should go away,
21243    and only the constant case should remain.  That will let this
21244    function complain more accurately.  A few special modes are allowed
21245    without complaint for global variables (for instance, global
21246    register values and thread-local values).
21247
21248    A location description containing no operations indicates that the
21249    object is optimized out.  The return value is 0 for that case.
21250    FIXME drow/2003-11-16: No callers check for this case any more; soon all
21251    callers will only want a very basic result and this can become a
21252    complaint.
21253
21254    Note that stack[0] is unused except as a default error return.  */
21255
21256 static CORE_ADDR
21257 decode_locdesc (struct dwarf_block *blk, struct dwarf2_cu *cu)
21258 {
21259   struct objfile *objfile = cu->objfile;
21260   size_t i;
21261   size_t size = blk->size;
21262   const gdb_byte *data = blk->data;
21263   CORE_ADDR stack[64];
21264   int stacki;
21265   unsigned int bytes_read, unsnd;
21266   gdb_byte op;
21267
21268   i = 0;
21269   stacki = 0;
21270   stack[stacki] = 0;
21271   stack[++stacki] = 0;
21272
21273   while (i < size)
21274     {
21275       op = data[i++];
21276       switch (op)
21277         {
21278         case DW_OP_lit0:
21279         case DW_OP_lit1:
21280         case DW_OP_lit2:
21281         case DW_OP_lit3:
21282         case DW_OP_lit4:
21283         case DW_OP_lit5:
21284         case DW_OP_lit6:
21285         case DW_OP_lit7:
21286         case DW_OP_lit8:
21287         case DW_OP_lit9:
21288         case DW_OP_lit10:
21289         case DW_OP_lit11:
21290         case DW_OP_lit12:
21291         case DW_OP_lit13:
21292         case DW_OP_lit14:
21293         case DW_OP_lit15:
21294         case DW_OP_lit16:
21295         case DW_OP_lit17:
21296         case DW_OP_lit18:
21297         case DW_OP_lit19:
21298         case DW_OP_lit20:
21299         case DW_OP_lit21:
21300         case DW_OP_lit22:
21301         case DW_OP_lit23:
21302         case DW_OP_lit24:
21303         case DW_OP_lit25:
21304         case DW_OP_lit26:
21305         case DW_OP_lit27:
21306         case DW_OP_lit28:
21307         case DW_OP_lit29:
21308         case DW_OP_lit30:
21309         case DW_OP_lit31:
21310           stack[++stacki] = op - DW_OP_lit0;
21311           break;
21312
21313         case DW_OP_reg0:
21314         case DW_OP_reg1:
21315         case DW_OP_reg2:
21316         case DW_OP_reg3:
21317         case DW_OP_reg4:
21318         case DW_OP_reg5:
21319         case DW_OP_reg6:
21320         case DW_OP_reg7:
21321         case DW_OP_reg8:
21322         case DW_OP_reg9:
21323         case DW_OP_reg10:
21324         case DW_OP_reg11:
21325         case DW_OP_reg12:
21326         case DW_OP_reg13:
21327         case DW_OP_reg14:
21328         case DW_OP_reg15:
21329         case DW_OP_reg16:
21330         case DW_OP_reg17:
21331         case DW_OP_reg18:
21332         case DW_OP_reg19:
21333         case DW_OP_reg20:
21334         case DW_OP_reg21:
21335         case DW_OP_reg22:
21336         case DW_OP_reg23:
21337         case DW_OP_reg24:
21338         case DW_OP_reg25:
21339         case DW_OP_reg26:
21340         case DW_OP_reg27:
21341         case DW_OP_reg28:
21342         case DW_OP_reg29:
21343         case DW_OP_reg30:
21344         case DW_OP_reg31:
21345           stack[++stacki] = op - DW_OP_reg0;
21346           if (i < size)
21347             dwarf2_complex_location_expr_complaint ();
21348           break;
21349
21350         case DW_OP_regx:
21351           unsnd = read_unsigned_leb128 (NULL, (data + i), &bytes_read);
21352           i += bytes_read;
21353           stack[++stacki] = unsnd;
21354           if (i < size)
21355             dwarf2_complex_location_expr_complaint ();
21356           break;
21357
21358         case DW_OP_addr:
21359           stack[++stacki] = read_address (objfile->obfd, &data[i],
21360                                           cu, &bytes_read);
21361           i += bytes_read;
21362           break;
21363
21364         case DW_OP_const1u:
21365           stack[++stacki] = read_1_byte (objfile->obfd, &data[i]);
21366           i += 1;
21367           break;
21368
21369         case DW_OP_const1s:
21370           stack[++stacki] = read_1_signed_byte (objfile->obfd, &data[i]);
21371           i += 1;
21372           break;
21373
21374         case DW_OP_const2u:
21375           stack[++stacki] = read_2_bytes (objfile->obfd, &data[i]);
21376           i += 2;
21377           break;
21378
21379         case DW_OP_const2s:
21380           stack[++stacki] = read_2_signed_bytes (objfile->obfd, &data[i]);
21381           i += 2;
21382           break;
21383
21384         case DW_OP_const4u:
21385           stack[++stacki] = read_4_bytes (objfile->obfd, &data[i]);
21386           i += 4;
21387           break;
21388
21389         case DW_OP_const4s:
21390           stack[++stacki] = read_4_signed_bytes (objfile->obfd, &data[i]);
21391           i += 4;
21392           break;
21393
21394         case DW_OP_const8u:
21395           stack[++stacki] = read_8_bytes (objfile->obfd, &data[i]);
21396           i += 8;
21397           break;
21398
21399         case DW_OP_constu:
21400           stack[++stacki] = read_unsigned_leb128 (NULL, (data + i),
21401                                                   &bytes_read);
21402           i += bytes_read;
21403           break;
21404
21405         case DW_OP_consts:
21406           stack[++stacki] = read_signed_leb128 (NULL, (data + i), &bytes_read);
21407           i += bytes_read;
21408           break;
21409
21410         case DW_OP_dup:
21411           stack[stacki + 1] = stack[stacki];
21412           stacki++;
21413           break;
21414
21415         case DW_OP_plus:
21416           stack[stacki - 1] += stack[stacki];
21417           stacki--;
21418           break;
21419
21420         case DW_OP_plus_uconst:
21421           stack[stacki] += read_unsigned_leb128 (NULL, (data + i),
21422                                                  &bytes_read);
21423           i += bytes_read;
21424           break;
21425
21426         case DW_OP_minus:
21427           stack[stacki - 1] -= stack[stacki];
21428           stacki--;
21429           break;
21430
21431         case DW_OP_deref:
21432           /* If we're not the last op, then we definitely can't encode
21433              this using GDB's address_class enum.  This is valid for partial
21434              global symbols, although the variable's address will be bogus
21435              in the psymtab.  */
21436           if (i < size)
21437             dwarf2_complex_location_expr_complaint ();
21438           break;
21439
21440         case DW_OP_GNU_push_tls_address:
21441         case DW_OP_form_tls_address:
21442           /* The top of the stack has the offset from the beginning
21443              of the thread control block at which the variable is located.  */
21444           /* Nothing should follow this operator, so the top of stack would
21445              be returned.  */
21446           /* This is valid for partial global symbols, but the variable's
21447              address will be bogus in the psymtab.  Make it always at least
21448              non-zero to not look as a variable garbage collected by linker
21449              which have DW_OP_addr 0.  */
21450           if (i < size)
21451             dwarf2_complex_location_expr_complaint ();
21452           stack[stacki]++;
21453           break;
21454
21455         case DW_OP_GNU_uninit:
21456           break;
21457
21458         case DW_OP_GNU_addr_index:
21459         case DW_OP_GNU_const_index:
21460           stack[++stacki] = read_addr_index_from_leb128 (cu, &data[i],
21461                                                          &bytes_read);
21462           i += bytes_read;
21463           break;
21464
21465         default:
21466           {
21467             const char *name = get_DW_OP_name (op);
21468
21469             if (name)
21470               complaint (&symfile_complaints, _("unsupported stack op: '%s'"),
21471                          name);
21472             else
21473               complaint (&symfile_complaints, _("unsupported stack op: '%02x'"),
21474                          op);
21475           }
21476
21477           return (stack[stacki]);
21478         }
21479
21480       /* Enforce maximum stack depth of SIZE-1 to avoid writing
21481          outside of the allocated space.  Also enforce minimum>0.  */
21482       if (stacki >= ARRAY_SIZE (stack) - 1)
21483         {
21484           complaint (&symfile_complaints,
21485                      _("location description stack overflow"));
21486           return 0;
21487         }
21488
21489       if (stacki <= 0)
21490         {
21491           complaint (&symfile_complaints,
21492                      _("location description stack underflow"));
21493           return 0;
21494         }
21495     }
21496   return (stack[stacki]);
21497 }
21498
21499 /* memory allocation interface */
21500
21501 static struct dwarf_block *
21502 dwarf_alloc_block (struct dwarf2_cu *cu)
21503 {
21504   return XOBNEW (&cu->comp_unit_obstack, struct dwarf_block);
21505 }
21506
21507 static struct die_info *
21508 dwarf_alloc_die (struct dwarf2_cu *cu, int num_attrs)
21509 {
21510   struct die_info *die;
21511   size_t size = sizeof (struct die_info);
21512
21513   if (num_attrs > 1)
21514     size += (num_attrs - 1) * sizeof (struct attribute);
21515
21516   die = (struct die_info *) obstack_alloc (&cu->comp_unit_obstack, size);
21517   memset (die, 0, sizeof (struct die_info));
21518   return (die);
21519 }
21520
21521 \f
21522 /* Macro support.  */
21523
21524 /* Return file name relative to the compilation directory of file number I in
21525    *LH's file name table.  The result is allocated using xmalloc; the caller is
21526    responsible for freeing it.  */
21527
21528 static char *
21529 file_file_name (int file, struct line_header *lh)
21530 {
21531   /* Is the file number a valid index into the line header's file name
21532      table?  Remember that file numbers start with one, not zero.  */
21533   if (1 <= file && file <= lh->file_names.size ())
21534     {
21535       const file_entry &fe = lh->file_names[file - 1];
21536
21537       if (!IS_ABSOLUTE_PATH (fe.name))
21538         {
21539           const char *dir = fe.include_dir (lh);
21540           if (dir != NULL)
21541             return concat (dir, SLASH_STRING, fe.name, (char *) NULL);
21542         }
21543       return xstrdup (fe.name);
21544     }
21545   else
21546     {
21547       /* The compiler produced a bogus file number.  We can at least
21548          record the macro definitions made in the file, even if we
21549          won't be able to find the file by name.  */
21550       char fake_name[80];
21551
21552       xsnprintf (fake_name, sizeof (fake_name),
21553                  "<bad macro file number %d>", file);
21554
21555       complaint (&symfile_complaints,
21556                  _("bad file number in macro information (%d)"),
21557                  file);
21558
21559       return xstrdup (fake_name);
21560     }
21561 }
21562
21563 /* Return the full name of file number I in *LH's file name table.
21564    Use COMP_DIR as the name of the current directory of the
21565    compilation.  The result is allocated using xmalloc; the caller is
21566    responsible for freeing it.  */
21567 static char *
21568 file_full_name (int file, struct line_header *lh, const char *comp_dir)
21569 {
21570   /* Is the file number a valid index into the line header's file name
21571      table?  Remember that file numbers start with one, not zero.  */
21572   if (1 <= file && file <= lh->file_names.size ())
21573     {
21574       char *relative = file_file_name (file, lh);
21575
21576       if (IS_ABSOLUTE_PATH (relative) || comp_dir == NULL)
21577         return relative;
21578       return reconcat (relative, comp_dir, SLASH_STRING,
21579                        relative, (char *) NULL);
21580     }
21581   else
21582     return file_file_name (file, lh);
21583 }
21584
21585
21586 static struct macro_source_file *
21587 macro_start_file (int file, int line,
21588                   struct macro_source_file *current_file,
21589                   struct line_header *lh)
21590 {
21591   /* File name relative to the compilation directory of this source file.  */
21592   char *file_name = file_file_name (file, lh);
21593
21594   if (! current_file)
21595     {
21596       /* Note: We don't create a macro table for this compilation unit
21597          at all until we actually get a filename.  */
21598       struct macro_table *macro_table = get_macro_table ();
21599
21600       /* If we have no current file, then this must be the start_file
21601          directive for the compilation unit's main source file.  */
21602       current_file = macro_set_main (macro_table, file_name);
21603       macro_define_special (macro_table);
21604     }
21605   else
21606     current_file = macro_include (current_file, line, file_name);
21607
21608   xfree (file_name);
21609
21610   return current_file;
21611 }
21612
21613
21614 /* Copy the LEN characters at BUF to a xmalloc'ed block of memory,
21615    followed by a null byte.  */
21616 static char *
21617 copy_string (const char *buf, int len)
21618 {
21619   char *s = (char *) xmalloc (len + 1);
21620
21621   memcpy (s, buf, len);
21622   s[len] = '\0';
21623   return s;
21624 }
21625
21626
21627 static const char *
21628 consume_improper_spaces (const char *p, const char *body)
21629 {
21630   if (*p == ' ')
21631     {
21632       complaint (&symfile_complaints,
21633                  _("macro definition contains spaces "
21634                    "in formal argument list:\n`%s'"),
21635                  body);
21636
21637       while (*p == ' ')
21638         p++;
21639     }
21640
21641   return p;
21642 }
21643
21644
21645 static void
21646 parse_macro_definition (struct macro_source_file *file, int line,
21647                         const char *body)
21648 {
21649   const char *p;
21650
21651   /* The body string takes one of two forms.  For object-like macro
21652      definitions, it should be:
21653
21654         <macro name> " " <definition>
21655
21656      For function-like macro definitions, it should be:
21657
21658         <macro name> "() " <definition>
21659      or
21660         <macro name> "(" <arg name> ( "," <arg name> ) * ") " <definition>
21661
21662      Spaces may appear only where explicitly indicated, and in the
21663      <definition>.
21664
21665      The Dwarf 2 spec says that an object-like macro's name is always
21666      followed by a space, but versions of GCC around March 2002 omit
21667      the space when the macro's definition is the empty string.
21668
21669      The Dwarf 2 spec says that there should be no spaces between the
21670      formal arguments in a function-like macro's formal argument list,
21671      but versions of GCC around March 2002 include spaces after the
21672      commas.  */
21673
21674
21675   /* Find the extent of the macro name.  The macro name is terminated
21676      by either a space or null character (for an object-like macro) or
21677      an opening paren (for a function-like macro).  */
21678   for (p = body; *p; p++)
21679     if (*p == ' ' || *p == '(')
21680       break;
21681
21682   if (*p == ' ' || *p == '\0')
21683     {
21684       /* It's an object-like macro.  */
21685       int name_len = p - body;
21686       char *name = copy_string (body, name_len);
21687       const char *replacement;
21688
21689       if (*p == ' ')
21690         replacement = body + name_len + 1;
21691       else
21692         {
21693           dwarf2_macro_malformed_definition_complaint (body);
21694           replacement = body + name_len;
21695         }
21696
21697       macro_define_object (file, line, name, replacement);
21698
21699       xfree (name);
21700     }
21701   else if (*p == '(')
21702     {
21703       /* It's a function-like macro.  */
21704       char *name = copy_string (body, p - body);
21705       int argc = 0;
21706       int argv_size = 1;
21707       char **argv = XNEWVEC (char *, argv_size);
21708
21709       p++;
21710
21711       p = consume_improper_spaces (p, body);
21712
21713       /* Parse the formal argument list.  */
21714       while (*p && *p != ')')
21715         {
21716           /* Find the extent of the current argument name.  */
21717           const char *arg_start = p;
21718
21719           while (*p && *p != ',' && *p != ')' && *p != ' ')
21720             p++;
21721
21722           if (! *p || p == arg_start)
21723             dwarf2_macro_malformed_definition_complaint (body);
21724           else
21725             {
21726               /* Make sure argv has room for the new argument.  */
21727               if (argc >= argv_size)
21728                 {
21729                   argv_size *= 2;
21730                   argv = XRESIZEVEC (char *, argv, argv_size);
21731                 }
21732
21733               argv[argc++] = copy_string (arg_start, p - arg_start);
21734             }
21735
21736           p = consume_improper_spaces (p, body);
21737
21738           /* Consume the comma, if present.  */
21739           if (*p == ',')
21740             {
21741               p++;
21742
21743               p = consume_improper_spaces (p, body);
21744             }
21745         }
21746
21747       if (*p == ')')
21748         {
21749           p++;
21750
21751           if (*p == ' ')
21752             /* Perfectly formed definition, no complaints.  */
21753             macro_define_function (file, line, name,
21754                                    argc, (const char **) argv,
21755                                    p + 1);
21756           else if (*p == '\0')
21757             {
21758               /* Complain, but do define it.  */
21759               dwarf2_macro_malformed_definition_complaint (body);
21760               macro_define_function (file, line, name,
21761                                      argc, (const char **) argv,
21762                                      p);
21763             }
21764           else
21765             /* Just complain.  */
21766             dwarf2_macro_malformed_definition_complaint (body);
21767         }
21768       else
21769         /* Just complain.  */
21770         dwarf2_macro_malformed_definition_complaint (body);
21771
21772       xfree (name);
21773       {
21774         int i;
21775
21776         for (i = 0; i < argc; i++)
21777           xfree (argv[i]);
21778       }
21779       xfree (argv);
21780     }
21781   else
21782     dwarf2_macro_malformed_definition_complaint (body);
21783 }
21784
21785 /* Skip some bytes from BYTES according to the form given in FORM.
21786    Returns the new pointer.  */
21787
21788 static const gdb_byte *
21789 skip_form_bytes (bfd *abfd, const gdb_byte *bytes, const gdb_byte *buffer_end,
21790                  enum dwarf_form form,
21791                  unsigned int offset_size,
21792                  struct dwarf2_section_info *section)
21793 {
21794   unsigned int bytes_read;
21795
21796   switch (form)
21797     {
21798     case DW_FORM_data1:
21799     case DW_FORM_flag:
21800       ++bytes;
21801       break;
21802
21803     case DW_FORM_data2:
21804       bytes += 2;
21805       break;
21806
21807     case DW_FORM_data4:
21808       bytes += 4;
21809       break;
21810
21811     case DW_FORM_data8:
21812       bytes += 8;
21813       break;
21814
21815     case DW_FORM_data16:
21816       bytes += 16;
21817       break;
21818
21819     case DW_FORM_string:
21820       read_direct_string (abfd, bytes, &bytes_read);
21821       bytes += bytes_read;
21822       break;
21823
21824     case DW_FORM_sec_offset:
21825     case DW_FORM_strp:
21826     case DW_FORM_GNU_strp_alt:
21827       bytes += offset_size;
21828       break;
21829
21830     case DW_FORM_block:
21831       bytes += read_unsigned_leb128 (abfd, bytes, &bytes_read);
21832       bytes += bytes_read;
21833       break;
21834
21835     case DW_FORM_block1:
21836       bytes += 1 + read_1_byte (abfd, bytes);
21837       break;
21838     case DW_FORM_block2:
21839       bytes += 2 + read_2_bytes (abfd, bytes);
21840       break;
21841     case DW_FORM_block4:
21842       bytes += 4 + read_4_bytes (abfd, bytes);
21843       break;
21844
21845     case DW_FORM_sdata:
21846     case DW_FORM_udata:
21847     case DW_FORM_GNU_addr_index:
21848     case DW_FORM_GNU_str_index:
21849       bytes = gdb_skip_leb128 (bytes, buffer_end);
21850       if (bytes == NULL)
21851         {
21852           dwarf2_section_buffer_overflow_complaint (section);
21853           return NULL;
21854         }
21855       break;
21856
21857     default:
21858       {
21859       complain:
21860         complaint (&symfile_complaints,
21861                    _("invalid form 0x%x in `%s'"),
21862                    form, get_section_name (section));
21863         return NULL;
21864       }
21865     }
21866
21867   return bytes;
21868 }
21869
21870 /* A helper for dwarf_decode_macros that handles skipping an unknown
21871    opcode.  Returns an updated pointer to the macro data buffer; or,
21872    on error, issues a complaint and returns NULL.  */
21873
21874 static const gdb_byte *
21875 skip_unknown_opcode (unsigned int opcode,
21876                      const gdb_byte **opcode_definitions,
21877                      const gdb_byte *mac_ptr, const gdb_byte *mac_end,
21878                      bfd *abfd,
21879                      unsigned int offset_size,
21880                      struct dwarf2_section_info *section)
21881 {
21882   unsigned int bytes_read, i;
21883   unsigned long arg;
21884   const gdb_byte *defn;
21885
21886   if (opcode_definitions[opcode] == NULL)
21887     {
21888       complaint (&symfile_complaints,
21889                  _("unrecognized DW_MACFINO opcode 0x%x"),
21890                  opcode);
21891       return NULL;
21892     }
21893
21894   defn = opcode_definitions[opcode];
21895   arg = read_unsigned_leb128 (abfd, defn, &bytes_read);
21896   defn += bytes_read;
21897
21898   for (i = 0; i < arg; ++i)
21899     {
21900       mac_ptr = skip_form_bytes (abfd, mac_ptr, mac_end,
21901                                  (enum dwarf_form) defn[i], offset_size,
21902                                  section);
21903       if (mac_ptr == NULL)
21904         {
21905           /* skip_form_bytes already issued the complaint.  */
21906           return NULL;
21907         }
21908     }
21909
21910   return mac_ptr;
21911 }
21912
21913 /* A helper function which parses the header of a macro section.
21914    If the macro section is the extended (for now called "GNU") type,
21915    then this updates *OFFSET_SIZE.  Returns a pointer to just after
21916    the header, or issues a complaint and returns NULL on error.  */
21917
21918 static const gdb_byte *
21919 dwarf_parse_macro_header (const gdb_byte **opcode_definitions,
21920                           bfd *abfd,
21921                           const gdb_byte *mac_ptr,
21922                           unsigned int *offset_size,
21923                           int section_is_gnu)
21924 {
21925   memset (opcode_definitions, 0, 256 * sizeof (gdb_byte *));
21926
21927   if (section_is_gnu)
21928     {
21929       unsigned int version, flags;
21930
21931       version = read_2_bytes (abfd, mac_ptr);
21932       if (version != 4 && version != 5)
21933         {
21934           complaint (&symfile_complaints,
21935                      _("unrecognized version `%d' in .debug_macro section"),
21936                      version);
21937           return NULL;
21938         }
21939       mac_ptr += 2;
21940
21941       flags = read_1_byte (abfd, mac_ptr);
21942       ++mac_ptr;
21943       *offset_size = (flags & 1) ? 8 : 4;
21944
21945       if ((flags & 2) != 0)
21946         /* We don't need the line table offset.  */
21947         mac_ptr += *offset_size;
21948
21949       /* Vendor opcode descriptions.  */
21950       if ((flags & 4) != 0)
21951         {
21952           unsigned int i, count;
21953
21954           count = read_1_byte (abfd, mac_ptr);
21955           ++mac_ptr;
21956           for (i = 0; i < count; ++i)
21957             {
21958               unsigned int opcode, bytes_read;
21959               unsigned long arg;
21960
21961               opcode = read_1_byte (abfd, mac_ptr);
21962               ++mac_ptr;
21963               opcode_definitions[opcode] = mac_ptr;
21964               arg = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
21965               mac_ptr += bytes_read;
21966               mac_ptr += arg;
21967             }
21968         }
21969     }
21970
21971   return mac_ptr;
21972 }
21973
21974 /* A helper for dwarf_decode_macros that handles the GNU extensions,
21975    including DW_MACRO_import.  */
21976
21977 static void
21978 dwarf_decode_macro_bytes (bfd *abfd,
21979                           const gdb_byte *mac_ptr, const gdb_byte *mac_end,
21980                           struct macro_source_file *current_file,
21981                           struct line_header *lh,
21982                           struct dwarf2_section_info *section,
21983                           int section_is_gnu, int section_is_dwz,
21984                           unsigned int offset_size,
21985                           htab_t include_hash)
21986 {
21987   struct objfile *objfile = dwarf2_per_objfile->objfile;
21988   enum dwarf_macro_record_type macinfo_type;
21989   int at_commandline;
21990   const gdb_byte *opcode_definitions[256];
21991
21992   mac_ptr = dwarf_parse_macro_header (opcode_definitions, abfd, mac_ptr,
21993                                       &offset_size, section_is_gnu);
21994   if (mac_ptr == NULL)
21995     {
21996       /* We already issued a complaint.  */
21997       return;
21998     }
21999
22000   /* Determines if GDB is still before first DW_MACINFO_start_file.  If true
22001      GDB is still reading the definitions from command line.  First
22002      DW_MACINFO_start_file will need to be ignored as it was already executed
22003      to create CURRENT_FILE for the main source holding also the command line
22004      definitions.  On first met DW_MACINFO_start_file this flag is reset to
22005      normally execute all the remaining DW_MACINFO_start_file macinfos.  */
22006
22007   at_commandline = 1;
22008
22009   do
22010     {
22011       /* Do we at least have room for a macinfo type byte?  */
22012       if (mac_ptr >= mac_end)
22013         {
22014           dwarf2_section_buffer_overflow_complaint (section);
22015           break;
22016         }
22017
22018       macinfo_type = (enum dwarf_macro_record_type) read_1_byte (abfd, mac_ptr);
22019       mac_ptr++;
22020
22021       /* Note that we rely on the fact that the corresponding GNU and
22022          DWARF constants are the same.  */
22023       switch (macinfo_type)
22024         {
22025           /* A zero macinfo type indicates the end of the macro
22026              information.  */
22027         case 0:
22028           break;
22029
22030         case DW_MACRO_define:
22031         case DW_MACRO_undef:
22032         case DW_MACRO_define_strp:
22033         case DW_MACRO_undef_strp:
22034         case DW_MACRO_define_sup:
22035         case DW_MACRO_undef_sup:
22036           {
22037             unsigned int bytes_read;
22038             int line;
22039             const char *body;
22040             int is_define;
22041
22042             line = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
22043             mac_ptr += bytes_read;
22044
22045             if (macinfo_type == DW_MACRO_define
22046                 || macinfo_type == DW_MACRO_undef)
22047               {
22048                 body = read_direct_string (abfd, mac_ptr, &bytes_read);
22049                 mac_ptr += bytes_read;
22050               }
22051             else
22052               {
22053                 LONGEST str_offset;
22054
22055                 str_offset = read_offset_1 (abfd, mac_ptr, offset_size);
22056                 mac_ptr += offset_size;
22057
22058                 if (macinfo_type == DW_MACRO_define_sup
22059                     || macinfo_type == DW_MACRO_undef_sup
22060                     || section_is_dwz)
22061                   {
22062                     struct dwz_file *dwz = dwarf2_get_dwz_file ();
22063
22064                     body = read_indirect_string_from_dwz (dwz, str_offset);
22065                   }
22066                 else
22067                   body = read_indirect_string_at_offset (abfd, str_offset);
22068               }
22069
22070             is_define = (macinfo_type == DW_MACRO_define
22071                          || macinfo_type == DW_MACRO_define_strp
22072                          || macinfo_type == DW_MACRO_define_sup);
22073             if (! current_file)
22074               {
22075                 /* DWARF violation as no main source is present.  */
22076                 complaint (&symfile_complaints,
22077                            _("debug info with no main source gives macro %s "
22078                              "on line %d: %s"),
22079                            is_define ? _("definition") : _("undefinition"),
22080                            line, body);
22081                 break;
22082               }
22083             if ((line == 0 && !at_commandline)
22084                 || (line != 0 && at_commandline))
22085               complaint (&symfile_complaints,
22086                          _("debug info gives %s macro %s with %s line %d: %s"),
22087                          at_commandline ? _("command-line") : _("in-file"),
22088                          is_define ? _("definition") : _("undefinition"),
22089                          line == 0 ? _("zero") : _("non-zero"), line, body);
22090
22091             if (is_define)
22092               parse_macro_definition (current_file, line, body);
22093             else
22094               {
22095                 gdb_assert (macinfo_type == DW_MACRO_undef
22096                             || macinfo_type == DW_MACRO_undef_strp
22097                             || macinfo_type == DW_MACRO_undef_sup);
22098                 macro_undef (current_file, line, body);
22099               }
22100           }
22101           break;
22102
22103         case DW_MACRO_start_file:
22104           {
22105             unsigned int bytes_read;
22106             int line, file;
22107
22108             line = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
22109             mac_ptr += bytes_read;
22110             file = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
22111             mac_ptr += bytes_read;
22112
22113             if ((line == 0 && !at_commandline)
22114                 || (line != 0 && at_commandline))
22115               complaint (&symfile_complaints,
22116                          _("debug info gives source %d included "
22117                            "from %s at %s line %d"),
22118                          file, at_commandline ? _("command-line") : _("file"),
22119                          line == 0 ? _("zero") : _("non-zero"), line);
22120
22121             if (at_commandline)
22122               {
22123                 /* This DW_MACRO_start_file was executed in the
22124                    pass one.  */
22125                 at_commandline = 0;
22126               }
22127             else
22128               current_file = macro_start_file (file, line, current_file, lh);
22129           }
22130           break;
22131
22132         case DW_MACRO_end_file:
22133           if (! current_file)
22134             complaint (&symfile_complaints,
22135                        _("macro debug info has an unmatched "
22136                          "`close_file' directive"));
22137           else
22138             {
22139               current_file = current_file->included_by;
22140               if (! current_file)
22141                 {
22142                   enum dwarf_macro_record_type next_type;
22143
22144                   /* GCC circa March 2002 doesn't produce the zero
22145                      type byte marking the end of the compilation
22146                      unit.  Complain if it's not there, but exit no
22147                      matter what.  */
22148
22149                   /* Do we at least have room for a macinfo type byte?  */
22150                   if (mac_ptr >= mac_end)
22151                     {
22152                       dwarf2_section_buffer_overflow_complaint (section);
22153                       return;
22154                     }
22155
22156                   /* We don't increment mac_ptr here, so this is just
22157                      a look-ahead.  */
22158                   next_type
22159                     = (enum dwarf_macro_record_type) read_1_byte (abfd,
22160                                                                   mac_ptr);
22161                   if (next_type != 0)
22162                     complaint (&symfile_complaints,
22163                                _("no terminating 0-type entry for "
22164                                  "macros in `.debug_macinfo' section"));
22165
22166                   return;
22167                 }
22168             }
22169           break;
22170
22171         case DW_MACRO_import:
22172         case DW_MACRO_import_sup:
22173           {
22174             LONGEST offset;
22175             void **slot;
22176             bfd *include_bfd = abfd;
22177             struct dwarf2_section_info *include_section = section;
22178             const gdb_byte *include_mac_end = mac_end;
22179             int is_dwz = section_is_dwz;
22180             const gdb_byte *new_mac_ptr;
22181
22182             offset = read_offset_1 (abfd, mac_ptr, offset_size);
22183             mac_ptr += offset_size;
22184
22185             if (macinfo_type == DW_MACRO_import_sup)
22186               {
22187                 struct dwz_file *dwz = dwarf2_get_dwz_file ();
22188
22189                 dwarf2_read_section (objfile, &dwz->macro);
22190
22191                 include_section = &dwz->macro;
22192                 include_bfd = get_section_bfd_owner (include_section);
22193                 include_mac_end = dwz->macro.buffer + dwz->macro.size;
22194                 is_dwz = 1;
22195               }
22196
22197             new_mac_ptr = include_section->buffer + offset;
22198             slot = htab_find_slot (include_hash, new_mac_ptr, INSERT);
22199
22200             if (*slot != NULL)
22201               {
22202                 /* This has actually happened; see
22203                    http://sourceware.org/bugzilla/show_bug.cgi?id=13568.  */
22204                 complaint (&symfile_complaints,
22205                            _("recursive DW_MACRO_import in "
22206                              ".debug_macro section"));
22207               }
22208             else
22209               {
22210                 *slot = (void *) new_mac_ptr;
22211
22212                 dwarf_decode_macro_bytes (include_bfd, new_mac_ptr,
22213                                           include_mac_end, current_file, lh,
22214                                           section, section_is_gnu, is_dwz,
22215                                           offset_size, include_hash);
22216
22217                 htab_remove_elt (include_hash, (void *) new_mac_ptr);
22218               }
22219           }
22220           break;
22221
22222         case DW_MACINFO_vendor_ext:
22223           if (!section_is_gnu)
22224             {
22225               unsigned int bytes_read;
22226
22227               /* This reads the constant, but since we don't recognize
22228                  any vendor extensions, we ignore it.  */
22229               read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
22230               mac_ptr += bytes_read;
22231               read_direct_string (abfd, mac_ptr, &bytes_read);
22232               mac_ptr += bytes_read;
22233
22234               /* We don't recognize any vendor extensions.  */
22235               break;
22236             }
22237           /* FALLTHROUGH */
22238
22239         default:
22240           mac_ptr = skip_unknown_opcode (macinfo_type, opcode_definitions,
22241                                          mac_ptr, mac_end, abfd, offset_size,
22242                                          section);
22243           if (mac_ptr == NULL)
22244             return;
22245           break;
22246         }
22247     } while (macinfo_type != 0);
22248 }
22249
22250 static void
22251 dwarf_decode_macros (struct dwarf2_cu *cu, unsigned int offset,
22252                      int section_is_gnu)
22253 {
22254   struct objfile *objfile = dwarf2_per_objfile->objfile;
22255   struct line_header *lh = cu->line_header;
22256   bfd *abfd;
22257   const gdb_byte *mac_ptr, *mac_end;
22258   struct macro_source_file *current_file = 0;
22259   enum dwarf_macro_record_type macinfo_type;
22260   unsigned int offset_size = cu->header.offset_size;
22261   const gdb_byte *opcode_definitions[256];
22262   struct cleanup *cleanup;
22263   void **slot;
22264   struct dwarf2_section_info *section;
22265   const char *section_name;
22266
22267   if (cu->dwo_unit != NULL)
22268     {
22269       if (section_is_gnu)
22270         {
22271           section = &cu->dwo_unit->dwo_file->sections.macro;
22272           section_name = ".debug_macro.dwo";
22273         }
22274       else
22275         {
22276           section = &cu->dwo_unit->dwo_file->sections.macinfo;
22277           section_name = ".debug_macinfo.dwo";
22278         }
22279     }
22280   else
22281     {
22282       if (section_is_gnu)
22283         {
22284           section = &dwarf2_per_objfile->macro;
22285           section_name = ".debug_macro";
22286         }
22287       else
22288         {
22289           section = &dwarf2_per_objfile->macinfo;
22290           section_name = ".debug_macinfo";
22291         }
22292     }
22293
22294   dwarf2_read_section (objfile, section);
22295   if (section->buffer == NULL)
22296     {
22297       complaint (&symfile_complaints, _("missing %s section"), section_name);
22298       return;
22299     }
22300   abfd = get_section_bfd_owner (section);
22301
22302   /* First pass: Find the name of the base filename.
22303      This filename is needed in order to process all macros whose definition
22304      (or undefinition) comes from the command line.  These macros are defined
22305      before the first DW_MACINFO_start_file entry, and yet still need to be
22306      associated to the base file.
22307
22308      To determine the base file name, we scan the macro definitions until we
22309      reach the first DW_MACINFO_start_file entry.  We then initialize
22310      CURRENT_FILE accordingly so that any macro definition found before the
22311      first DW_MACINFO_start_file can still be associated to the base file.  */
22312
22313   mac_ptr = section->buffer + offset;
22314   mac_end = section->buffer + section->size;
22315
22316   mac_ptr = dwarf_parse_macro_header (opcode_definitions, abfd, mac_ptr,
22317                                       &offset_size, section_is_gnu);
22318   if (mac_ptr == NULL)
22319     {
22320       /* We already issued a complaint.  */
22321       return;
22322     }
22323
22324   do
22325     {
22326       /* Do we at least have room for a macinfo type byte?  */
22327       if (mac_ptr >= mac_end)
22328         {
22329           /* Complaint is printed during the second pass as GDB will probably
22330              stop the first pass earlier upon finding
22331              DW_MACINFO_start_file.  */
22332           break;
22333         }
22334
22335       macinfo_type = (enum dwarf_macro_record_type) read_1_byte (abfd, mac_ptr);
22336       mac_ptr++;
22337
22338       /* Note that we rely on the fact that the corresponding GNU and
22339          DWARF constants are the same.  */
22340       switch (macinfo_type)
22341         {
22342           /* A zero macinfo type indicates the end of the macro
22343              information.  */
22344         case 0:
22345           break;
22346
22347         case DW_MACRO_define:
22348         case DW_MACRO_undef:
22349           /* Only skip the data by MAC_PTR.  */
22350           {
22351             unsigned int bytes_read;
22352
22353             read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
22354             mac_ptr += bytes_read;
22355             read_direct_string (abfd, mac_ptr, &bytes_read);
22356             mac_ptr += bytes_read;
22357           }
22358           break;
22359
22360         case DW_MACRO_start_file:
22361           {
22362             unsigned int bytes_read;
22363             int line, file;
22364
22365             line = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
22366             mac_ptr += bytes_read;
22367             file = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
22368             mac_ptr += bytes_read;
22369
22370             current_file = macro_start_file (file, line, current_file, lh);
22371           }
22372           break;
22373
22374         case DW_MACRO_end_file:
22375           /* No data to skip by MAC_PTR.  */
22376           break;
22377
22378         case DW_MACRO_define_strp:
22379         case DW_MACRO_undef_strp:
22380         case DW_MACRO_define_sup:
22381         case DW_MACRO_undef_sup:
22382           {
22383             unsigned int bytes_read;
22384
22385             read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
22386             mac_ptr += bytes_read;
22387             mac_ptr += offset_size;
22388           }
22389           break;
22390
22391         case DW_MACRO_import:
22392         case DW_MACRO_import_sup:
22393           /* Note that, according to the spec, a transparent include
22394              chain cannot call DW_MACRO_start_file.  So, we can just
22395              skip this opcode.  */
22396           mac_ptr += offset_size;
22397           break;
22398
22399         case DW_MACINFO_vendor_ext:
22400           /* Only skip the data by MAC_PTR.  */
22401           if (!section_is_gnu)
22402             {
22403               unsigned int bytes_read;
22404
22405               read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
22406               mac_ptr += bytes_read;
22407               read_direct_string (abfd, mac_ptr, &bytes_read);
22408               mac_ptr += bytes_read;
22409             }
22410           /* FALLTHROUGH */
22411
22412         default:
22413           mac_ptr = skip_unknown_opcode (macinfo_type, opcode_definitions,
22414                                          mac_ptr, mac_end, abfd, offset_size,
22415                                          section);
22416           if (mac_ptr == NULL)
22417             return;
22418           break;
22419         }
22420     } while (macinfo_type != 0 && current_file == NULL);
22421
22422   /* Second pass: Process all entries.
22423
22424      Use the AT_COMMAND_LINE flag to determine whether we are still processing
22425      command-line macro definitions/undefinitions.  This flag is unset when we
22426      reach the first DW_MACINFO_start_file entry.  */
22427
22428   htab_up include_hash (htab_create_alloc (1, htab_hash_pointer,
22429                                            htab_eq_pointer,
22430                                            NULL, xcalloc, xfree));
22431   mac_ptr = section->buffer + offset;
22432   slot = htab_find_slot (include_hash.get (), mac_ptr, INSERT);
22433   *slot = (void *) mac_ptr;
22434   dwarf_decode_macro_bytes (abfd, mac_ptr, mac_end,
22435                             current_file, lh, section,
22436                             section_is_gnu, 0, offset_size,
22437                             include_hash.get ());
22438 }
22439
22440 /* Check if the attribute's form is a DW_FORM_block*
22441    if so return true else false.  */
22442
22443 static int
22444 attr_form_is_block (const struct attribute *attr)
22445 {
22446   return (attr == NULL ? 0 :
22447       attr->form == DW_FORM_block1
22448       || attr->form == DW_FORM_block2
22449       || attr->form == DW_FORM_block4
22450       || attr->form == DW_FORM_block
22451       || attr->form == DW_FORM_exprloc);
22452 }
22453
22454 /* Return non-zero if ATTR's value is a section offset --- classes
22455    lineptr, loclistptr, macptr or rangelistptr --- or zero, otherwise.
22456    You may use DW_UNSND (attr) to retrieve such offsets.
22457
22458    Section 7.5.4, "Attribute Encodings", explains that no attribute
22459    may have a value that belongs to more than one of these classes; it
22460    would be ambiguous if we did, because we use the same forms for all
22461    of them.  */
22462
22463 static int
22464 attr_form_is_section_offset (const struct attribute *attr)
22465 {
22466   return (attr->form == DW_FORM_data4
22467           || attr->form == DW_FORM_data8
22468           || attr->form == DW_FORM_sec_offset);
22469 }
22470
22471 /* Return non-zero if ATTR's value falls in the 'constant' class, or
22472    zero otherwise.  When this function returns true, you can apply
22473    dwarf2_get_attr_constant_value to it.
22474
22475    However, note that for some attributes you must check
22476    attr_form_is_section_offset before using this test.  DW_FORM_data4
22477    and DW_FORM_data8 are members of both the constant class, and of
22478    the classes that contain offsets into other debug sections
22479    (lineptr, loclistptr, macptr or rangelistptr).  The DWARF spec says
22480    that, if an attribute's can be either a constant or one of the
22481    section offset classes, DW_FORM_data4 and DW_FORM_data8 should be
22482    taken as section offsets, not constants.
22483
22484    DW_FORM_data16 is not considered as dwarf2_get_attr_constant_value
22485    cannot handle that.  */
22486
22487 static int
22488 attr_form_is_constant (const struct attribute *attr)
22489 {
22490   switch (attr->form)
22491     {
22492     case DW_FORM_sdata:
22493     case DW_FORM_udata:
22494     case DW_FORM_data1:
22495     case DW_FORM_data2:
22496     case DW_FORM_data4:
22497     case DW_FORM_data8:
22498       return 1;
22499     default:
22500       return 0;
22501     }
22502 }
22503
22504
22505 /* DW_ADDR is always stored already as sect_offset; despite for the forms
22506    besides DW_FORM_ref_addr it is stored as cu_offset in the DWARF file.  */
22507
22508 static int
22509 attr_form_is_ref (const struct attribute *attr)
22510 {
22511   switch (attr->form)
22512     {
22513     case DW_FORM_ref_addr:
22514     case DW_FORM_ref1:
22515     case DW_FORM_ref2:
22516     case DW_FORM_ref4:
22517     case DW_FORM_ref8:
22518     case DW_FORM_ref_udata:
22519     case DW_FORM_GNU_ref_alt:
22520       return 1;
22521     default:
22522       return 0;
22523     }
22524 }
22525
22526 /* Return the .debug_loc section to use for CU.
22527    For DWO files use .debug_loc.dwo.  */
22528
22529 static struct dwarf2_section_info *
22530 cu_debug_loc_section (struct dwarf2_cu *cu)
22531 {
22532   if (cu->dwo_unit)
22533     {
22534       struct dwo_sections *sections = &cu->dwo_unit->dwo_file->sections;
22535       
22536       return cu->header.version >= 5 ? &sections->loclists : &sections->loc;
22537     }
22538   return (cu->header.version >= 5 ? &dwarf2_per_objfile->loclists
22539                                   : &dwarf2_per_objfile->loc);
22540 }
22541
22542 /* A helper function that fills in a dwarf2_loclist_baton.  */
22543
22544 static void
22545 fill_in_loclist_baton (struct dwarf2_cu *cu,
22546                        struct dwarf2_loclist_baton *baton,
22547                        const struct attribute *attr)
22548 {
22549   struct dwarf2_section_info *section = cu_debug_loc_section (cu);
22550
22551   dwarf2_read_section (dwarf2_per_objfile->objfile, section);
22552
22553   baton->per_cu = cu->per_cu;
22554   gdb_assert (baton->per_cu);
22555   /* We don't know how long the location list is, but make sure we
22556      don't run off the edge of the section.  */
22557   baton->size = section->size - DW_UNSND (attr);
22558   baton->data = section->buffer + DW_UNSND (attr);
22559   baton->base_address = cu->base_address;
22560   baton->from_dwo = cu->dwo_unit != NULL;
22561 }
22562
22563 static void
22564 dwarf2_symbol_mark_computed (const struct attribute *attr, struct symbol *sym,
22565                              struct dwarf2_cu *cu, int is_block)
22566 {
22567   struct objfile *objfile = dwarf2_per_objfile->objfile;
22568   struct dwarf2_section_info *section = cu_debug_loc_section (cu);
22569
22570   if (attr_form_is_section_offset (attr)
22571       /* .debug_loc{,.dwo} may not exist at all, or the offset may be outside
22572          the section.  If so, fall through to the complaint in the
22573          other branch.  */
22574       && DW_UNSND (attr) < dwarf2_section_size (objfile, section))
22575     {
22576       struct dwarf2_loclist_baton *baton;
22577
22578       baton = XOBNEW (&objfile->objfile_obstack, struct dwarf2_loclist_baton);
22579
22580       fill_in_loclist_baton (cu, baton, attr);
22581
22582       if (cu->base_known == 0)
22583         complaint (&symfile_complaints,
22584                    _("Location list used without "
22585                      "specifying the CU base address."));
22586
22587       SYMBOL_ACLASS_INDEX (sym) = (is_block
22588                                    ? dwarf2_loclist_block_index
22589                                    : dwarf2_loclist_index);
22590       SYMBOL_LOCATION_BATON (sym) = baton;
22591     }
22592   else
22593     {
22594       struct dwarf2_locexpr_baton *baton;
22595
22596       baton = XOBNEW (&objfile->objfile_obstack, struct dwarf2_locexpr_baton);
22597       baton->per_cu = cu->per_cu;
22598       gdb_assert (baton->per_cu);
22599
22600       if (attr_form_is_block (attr))
22601         {
22602           /* Note that we're just copying the block's data pointer
22603              here, not the actual data.  We're still pointing into the
22604              info_buffer for SYM's objfile; right now we never release
22605              that buffer, but when we do clean up properly this may
22606              need to change.  */
22607           baton->size = DW_BLOCK (attr)->size;
22608           baton->data = DW_BLOCK (attr)->data;
22609         }
22610       else
22611         {
22612           dwarf2_invalid_attrib_class_complaint ("location description",
22613                                                  SYMBOL_NATURAL_NAME (sym));
22614           baton->size = 0;
22615         }
22616
22617       SYMBOL_ACLASS_INDEX (sym) = (is_block
22618                                    ? dwarf2_locexpr_block_index
22619                                    : dwarf2_locexpr_index);
22620       SYMBOL_LOCATION_BATON (sym) = baton;
22621     }
22622 }
22623
22624 /* Return the OBJFILE associated with the compilation unit CU.  If CU
22625    came from a separate debuginfo file, then the master objfile is
22626    returned.  */
22627
22628 struct objfile *
22629 dwarf2_per_cu_objfile (struct dwarf2_per_cu_data *per_cu)
22630 {
22631   struct objfile *objfile = per_cu->objfile;
22632
22633   /* Return the master objfile, so that we can report and look up the
22634      correct file containing this variable.  */
22635   if (objfile->separate_debug_objfile_backlink)
22636     objfile = objfile->separate_debug_objfile_backlink;
22637
22638   return objfile;
22639 }
22640
22641 /* Return comp_unit_head for PER_CU, either already available in PER_CU->CU
22642    (CU_HEADERP is unused in such case) or prepare a temporary copy at
22643    CU_HEADERP first.  */
22644
22645 static const struct comp_unit_head *
22646 per_cu_header_read_in (struct comp_unit_head *cu_headerp,
22647                        struct dwarf2_per_cu_data *per_cu)
22648 {
22649   const gdb_byte *info_ptr;
22650
22651   if (per_cu->cu)
22652     return &per_cu->cu->header;
22653
22654   info_ptr = per_cu->section->buffer + to_underlying (per_cu->sect_off);
22655
22656   memset (cu_headerp, 0, sizeof (*cu_headerp));
22657   read_comp_unit_head (cu_headerp, info_ptr, per_cu->section,
22658                        rcuh_kind::COMPILE);
22659
22660   return cu_headerp;
22661 }
22662
22663 /* Return the address size given in the compilation unit header for CU.  */
22664
22665 int
22666 dwarf2_per_cu_addr_size (struct dwarf2_per_cu_data *per_cu)
22667 {
22668   struct comp_unit_head cu_header_local;
22669   const struct comp_unit_head *cu_headerp;
22670
22671   cu_headerp = per_cu_header_read_in (&cu_header_local, per_cu);
22672
22673   return cu_headerp->addr_size;
22674 }
22675
22676 /* Return the offset size given in the compilation unit header for CU.  */
22677
22678 int
22679 dwarf2_per_cu_offset_size (struct dwarf2_per_cu_data *per_cu)
22680 {
22681   struct comp_unit_head cu_header_local;
22682   const struct comp_unit_head *cu_headerp;
22683
22684   cu_headerp = per_cu_header_read_in (&cu_header_local, per_cu);
22685
22686   return cu_headerp->offset_size;
22687 }
22688
22689 /* See its dwarf2loc.h declaration.  */
22690
22691 int
22692 dwarf2_per_cu_ref_addr_size (struct dwarf2_per_cu_data *per_cu)
22693 {
22694   struct comp_unit_head cu_header_local;
22695   const struct comp_unit_head *cu_headerp;
22696
22697   cu_headerp = per_cu_header_read_in (&cu_header_local, per_cu);
22698
22699   if (cu_headerp->version == 2)
22700     return cu_headerp->addr_size;
22701   else
22702     return cu_headerp->offset_size;
22703 }
22704
22705 /* Return the text offset of the CU.  The returned offset comes from
22706    this CU's objfile.  If this objfile came from a separate debuginfo
22707    file, then the offset may be different from the corresponding
22708    offset in the parent objfile.  */
22709
22710 CORE_ADDR
22711 dwarf2_per_cu_text_offset (struct dwarf2_per_cu_data *per_cu)
22712 {
22713   struct objfile *objfile = per_cu->objfile;
22714
22715   return ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
22716 }
22717
22718 /* Return DWARF version number of PER_CU.  */
22719
22720 short
22721 dwarf2_version (struct dwarf2_per_cu_data *per_cu)
22722 {
22723   return per_cu->dwarf_version;
22724 }
22725
22726 /* Locate the .debug_info compilation unit from CU's objfile which contains
22727    the DIE at OFFSET.  Raises an error on failure.  */
22728
22729 static struct dwarf2_per_cu_data *
22730 dwarf2_find_containing_comp_unit (sect_offset sect_off,
22731                                   unsigned int offset_in_dwz,
22732                                   struct objfile *objfile)
22733 {
22734   struct dwarf2_per_cu_data *this_cu;
22735   int low, high;
22736   const sect_offset *cu_off;
22737
22738   low = 0;
22739   high = dwarf2_per_objfile->n_comp_units - 1;
22740   while (high > low)
22741     {
22742       struct dwarf2_per_cu_data *mid_cu;
22743       int mid = low + (high - low) / 2;
22744
22745       mid_cu = dwarf2_per_objfile->all_comp_units[mid];
22746       cu_off = &mid_cu->sect_off;
22747       if (mid_cu->is_dwz > offset_in_dwz
22748           || (mid_cu->is_dwz == offset_in_dwz && *cu_off >= sect_off))
22749         high = mid;
22750       else
22751         low = mid + 1;
22752     }
22753   gdb_assert (low == high);
22754   this_cu = dwarf2_per_objfile->all_comp_units[low];
22755   cu_off = &this_cu->sect_off;
22756   if (this_cu->is_dwz != offset_in_dwz || *cu_off > sect_off)
22757     {
22758       if (low == 0 || this_cu->is_dwz != offset_in_dwz)
22759         error (_("Dwarf Error: could not find partial DIE containing "
22760                "offset 0x%x [in module %s]"),
22761                to_underlying (sect_off), bfd_get_filename (objfile->obfd));
22762
22763       gdb_assert (dwarf2_per_objfile->all_comp_units[low-1]->sect_off
22764                   <= sect_off);
22765       return dwarf2_per_objfile->all_comp_units[low-1];
22766     }
22767   else
22768     {
22769       this_cu = dwarf2_per_objfile->all_comp_units[low];
22770       if (low == dwarf2_per_objfile->n_comp_units - 1
22771           && sect_off >= this_cu->sect_off + this_cu->length)
22772         error (_("invalid dwarf2 offset %u"), to_underlying (sect_off));
22773       gdb_assert (sect_off < this_cu->sect_off + this_cu->length);
22774       return this_cu;
22775     }
22776 }
22777
22778 /* Initialize dwarf2_cu CU, owned by PER_CU.  */
22779
22780 static void
22781 init_one_comp_unit (struct dwarf2_cu *cu, struct dwarf2_per_cu_data *per_cu)
22782 {
22783   memset (cu, 0, sizeof (*cu));
22784   per_cu->cu = cu;
22785   cu->per_cu = per_cu;
22786   cu->objfile = per_cu->objfile;
22787   obstack_init (&cu->comp_unit_obstack);
22788 }
22789
22790 /* Initialize basic fields of dwarf_cu CU according to DIE COMP_UNIT_DIE.  */
22791
22792 static void
22793 prepare_one_comp_unit (struct dwarf2_cu *cu, struct die_info *comp_unit_die,
22794                        enum language pretend_language)
22795 {
22796   struct attribute *attr;
22797
22798   /* Set the language we're debugging.  */
22799   attr = dwarf2_attr (comp_unit_die, DW_AT_language, cu);
22800   if (attr)
22801     set_cu_language (DW_UNSND (attr), cu);
22802   else
22803     {
22804       cu->language = pretend_language;
22805       cu->language_defn = language_def (cu->language);
22806     }
22807
22808   cu->producer = dwarf2_string_attr (comp_unit_die, DW_AT_producer, cu);
22809 }
22810
22811 /* Release one cached compilation unit, CU.  We unlink it from the tree
22812    of compilation units, but we don't remove it from the read_in_chain;
22813    the caller is responsible for that.
22814    NOTE: DATA is a void * because this function is also used as a
22815    cleanup routine.  */
22816
22817 static void
22818 free_heap_comp_unit (void *data)
22819 {
22820   struct dwarf2_cu *cu = (struct dwarf2_cu *) data;
22821
22822   gdb_assert (cu->per_cu != NULL);
22823   cu->per_cu->cu = NULL;
22824   cu->per_cu = NULL;
22825
22826   obstack_free (&cu->comp_unit_obstack, NULL);
22827
22828   xfree (cu);
22829 }
22830
22831 /* This cleanup function is passed the address of a dwarf2_cu on the stack
22832    when we're finished with it.  We can't free the pointer itself, but be
22833    sure to unlink it from the cache.  Also release any associated storage.  */
22834
22835 static void
22836 free_stack_comp_unit (void *data)
22837 {
22838   struct dwarf2_cu *cu = (struct dwarf2_cu *) data;
22839
22840   gdb_assert (cu->per_cu != NULL);
22841   cu->per_cu->cu = NULL;
22842   cu->per_cu = NULL;
22843
22844   obstack_free (&cu->comp_unit_obstack, NULL);
22845   cu->partial_dies = NULL;
22846 }
22847
22848 /* Free all cached compilation units.  */
22849
22850 static void
22851 free_cached_comp_units (void *data)
22852 {
22853   dwarf2_per_objfile->free_cached_comp_units ();
22854 }
22855
22856 /* Increase the age counter on each cached compilation unit, and free
22857    any that are too old.  */
22858
22859 static void
22860 age_cached_comp_units (void)
22861 {
22862   struct dwarf2_per_cu_data *per_cu, **last_chain;
22863
22864   dwarf2_clear_marks (dwarf2_per_objfile->read_in_chain);
22865   per_cu = dwarf2_per_objfile->read_in_chain;
22866   while (per_cu != NULL)
22867     {
22868       per_cu->cu->last_used ++;
22869       if (per_cu->cu->last_used <= dwarf_max_cache_age)
22870         dwarf2_mark (per_cu->cu);
22871       per_cu = per_cu->cu->read_in_chain;
22872     }
22873
22874   per_cu = dwarf2_per_objfile->read_in_chain;
22875   last_chain = &dwarf2_per_objfile->read_in_chain;
22876   while (per_cu != NULL)
22877     {
22878       struct dwarf2_per_cu_data *next_cu;
22879
22880       next_cu = per_cu->cu->read_in_chain;
22881
22882       if (!per_cu->cu->mark)
22883         {
22884           free_heap_comp_unit (per_cu->cu);
22885           *last_chain = next_cu;
22886         }
22887       else
22888         last_chain = &per_cu->cu->read_in_chain;
22889
22890       per_cu = next_cu;
22891     }
22892 }
22893
22894 /* Remove a single compilation unit from the cache.  */
22895
22896 static void
22897 free_one_cached_comp_unit (struct dwarf2_per_cu_data *target_per_cu)
22898 {
22899   struct dwarf2_per_cu_data *per_cu, **last_chain;
22900
22901   per_cu = dwarf2_per_objfile->read_in_chain;
22902   last_chain = &dwarf2_per_objfile->read_in_chain;
22903   while (per_cu != NULL)
22904     {
22905       struct dwarf2_per_cu_data *next_cu;
22906
22907       next_cu = per_cu->cu->read_in_chain;
22908
22909       if (per_cu == target_per_cu)
22910         {
22911           free_heap_comp_unit (per_cu->cu);
22912           per_cu->cu = NULL;
22913           *last_chain = next_cu;
22914           break;
22915         }
22916       else
22917         last_chain = &per_cu->cu->read_in_chain;
22918
22919       per_cu = next_cu;
22920     }
22921 }
22922
22923 /* Release all extra memory associated with OBJFILE.  */
22924
22925 void
22926 dwarf2_free_objfile (struct objfile *objfile)
22927 {
22928   dwarf2_per_objfile
22929     = (struct dwarf2_per_objfile *) objfile_data (objfile,
22930                                                   dwarf2_objfile_data_key);
22931
22932   if (dwarf2_per_objfile == NULL)
22933     return;
22934
22935   dwarf2_per_objfile->~dwarf2_per_objfile ();
22936 }
22937
22938 /* A set of CU "per_cu" pointer, DIE offset, and GDB type pointer.
22939    We store these in a hash table separate from the DIEs, and preserve them
22940    when the DIEs are flushed out of cache.
22941
22942    The CU "per_cu" pointer is needed because offset alone is not enough to
22943    uniquely identify the type.  A file may have multiple .debug_types sections,
22944    or the type may come from a DWO file.  Furthermore, while it's more logical
22945    to use per_cu->section+offset, with Fission the section with the data is in
22946    the DWO file but we don't know that section at the point we need it.
22947    We have to use something in dwarf2_per_cu_data (or the pointer to it)
22948    because we can enter the lookup routine, get_die_type_at_offset, from
22949    outside this file, and thus won't necessarily have PER_CU->cu.
22950    Fortunately, PER_CU is stable for the life of the objfile.  */
22951
22952 struct dwarf2_per_cu_offset_and_type
22953 {
22954   const struct dwarf2_per_cu_data *per_cu;
22955   sect_offset sect_off;
22956   struct type *type;
22957 };
22958
22959 /* Hash function for a dwarf2_per_cu_offset_and_type.  */
22960
22961 static hashval_t
22962 per_cu_offset_and_type_hash (const void *item)
22963 {
22964   const struct dwarf2_per_cu_offset_and_type *ofs
22965     = (const struct dwarf2_per_cu_offset_and_type *) item;
22966
22967   return (uintptr_t) ofs->per_cu + to_underlying (ofs->sect_off);
22968 }
22969
22970 /* Equality function for a dwarf2_per_cu_offset_and_type.  */
22971
22972 static int
22973 per_cu_offset_and_type_eq (const void *item_lhs, const void *item_rhs)
22974 {
22975   const struct dwarf2_per_cu_offset_and_type *ofs_lhs
22976     = (const struct dwarf2_per_cu_offset_and_type *) item_lhs;
22977   const struct dwarf2_per_cu_offset_and_type *ofs_rhs
22978     = (const struct dwarf2_per_cu_offset_and_type *) item_rhs;
22979
22980   return (ofs_lhs->per_cu == ofs_rhs->per_cu
22981           && ofs_lhs->sect_off == ofs_rhs->sect_off);
22982 }
22983
22984 /* Set the type associated with DIE to TYPE.  Save it in CU's hash
22985    table if necessary.  For convenience, return TYPE.
22986
22987    The DIEs reading must have careful ordering to:
22988     * Not cause infite loops trying to read in DIEs as a prerequisite for
22989       reading current DIE.
22990     * Not trying to dereference contents of still incompletely read in types
22991       while reading in other DIEs.
22992     * Enable referencing still incompletely read in types just by a pointer to
22993       the type without accessing its fields.
22994
22995    Therefore caller should follow these rules:
22996      * Try to fetch any prerequisite types we may need to build this DIE type
22997        before building the type and calling set_die_type.
22998      * After building type call set_die_type for current DIE as soon as
22999        possible before fetching more types to complete the current type.
23000      * Make the type as complete as possible before fetching more types.  */
23001
23002 static struct type *
23003 set_die_type (struct die_info *die, struct type *type, struct dwarf2_cu *cu)
23004 {
23005   struct dwarf2_per_cu_offset_and_type **slot, ofs;
23006   struct objfile *objfile = cu->objfile;
23007   struct attribute *attr;
23008   struct dynamic_prop prop;
23009
23010   /* For Ada types, make sure that the gnat-specific data is always
23011      initialized (if not already set).  There are a few types where
23012      we should not be doing so, because the type-specific area is
23013      already used to hold some other piece of info (eg: TYPE_CODE_FLT
23014      where the type-specific area is used to store the floatformat).
23015      But this is not a problem, because the gnat-specific information
23016      is actually not needed for these types.  */
23017   if (need_gnat_info (cu)
23018       && TYPE_CODE (type) != TYPE_CODE_FUNC
23019       && TYPE_CODE (type) != TYPE_CODE_FLT
23020       && TYPE_CODE (type) != TYPE_CODE_METHODPTR
23021       && TYPE_CODE (type) != TYPE_CODE_MEMBERPTR
23022       && TYPE_CODE (type) != TYPE_CODE_METHOD
23023       && !HAVE_GNAT_AUX_INFO (type))
23024     INIT_GNAT_SPECIFIC (type);
23025
23026   /* Read DW_AT_allocated and set in type.  */
23027   attr = dwarf2_attr (die, DW_AT_allocated, cu);
23028   if (attr_form_is_block (attr))
23029     {
23030       if (attr_to_dynamic_prop (attr, die, cu, &prop))
23031         add_dyn_prop (DYN_PROP_ALLOCATED, prop, type, objfile);
23032     }
23033   else if (attr != NULL)
23034     {
23035       complaint (&symfile_complaints,
23036                  _("DW_AT_allocated has the wrong form (%s) at DIE 0x%x"),
23037                  (attr != NULL ? dwarf_form_name (attr->form) : "n/a"),
23038                  to_underlying (die->sect_off));
23039     }
23040
23041   /* Read DW_AT_associated and set in type.  */
23042   attr = dwarf2_attr (die, DW_AT_associated, cu);
23043   if (attr_form_is_block (attr))
23044     {
23045       if (attr_to_dynamic_prop (attr, die, cu, &prop))
23046         add_dyn_prop (DYN_PROP_ASSOCIATED, prop, type, objfile);
23047     }
23048   else if (attr != NULL)
23049     {
23050       complaint (&symfile_complaints,
23051                  _("DW_AT_associated has the wrong form (%s) at DIE 0x%x"),
23052                  (attr != NULL ? dwarf_form_name (attr->form) : "n/a"),
23053                  to_underlying (die->sect_off));
23054     }
23055
23056   /* Read DW_AT_data_location and set in type.  */
23057   attr = dwarf2_attr (die, DW_AT_data_location, cu);
23058   if (attr_to_dynamic_prop (attr, die, cu, &prop))
23059     add_dyn_prop (DYN_PROP_DATA_LOCATION, prop, type, objfile);
23060
23061   if (dwarf2_per_objfile->die_type_hash == NULL)
23062     {
23063       dwarf2_per_objfile->die_type_hash =
23064         htab_create_alloc_ex (127,
23065                               per_cu_offset_and_type_hash,
23066                               per_cu_offset_and_type_eq,
23067                               NULL,
23068                               &objfile->objfile_obstack,
23069                               hashtab_obstack_allocate,
23070                               dummy_obstack_deallocate);
23071     }
23072
23073   ofs.per_cu = cu->per_cu;
23074   ofs.sect_off = die->sect_off;
23075   ofs.type = type;
23076   slot = (struct dwarf2_per_cu_offset_and_type **)
23077     htab_find_slot (dwarf2_per_objfile->die_type_hash, &ofs, INSERT);
23078   if (*slot)
23079     complaint (&symfile_complaints,
23080                _("A problem internal to GDB: DIE 0x%x has type already set"),
23081                to_underlying (die->sect_off));
23082   *slot = XOBNEW (&objfile->objfile_obstack,
23083                   struct dwarf2_per_cu_offset_and_type);
23084   **slot = ofs;
23085   return type;
23086 }
23087
23088 /* Look up the type for the die at SECT_OFF in PER_CU in die_type_hash,
23089    or return NULL if the die does not have a saved type.  */
23090
23091 static struct type *
23092 get_die_type_at_offset (sect_offset sect_off,
23093                         struct dwarf2_per_cu_data *per_cu)
23094 {
23095   struct dwarf2_per_cu_offset_and_type *slot, ofs;
23096
23097   if (dwarf2_per_objfile->die_type_hash == NULL)
23098     return NULL;
23099
23100   ofs.per_cu = per_cu;
23101   ofs.sect_off = sect_off;
23102   slot = ((struct dwarf2_per_cu_offset_and_type *)
23103           htab_find (dwarf2_per_objfile->die_type_hash, &ofs));
23104   if (slot)
23105     return slot->type;
23106   else
23107     return NULL;
23108 }
23109
23110 /* Look up the type for DIE in CU in die_type_hash,
23111    or return NULL if DIE does not have a saved type.  */
23112
23113 static struct type *
23114 get_die_type (struct die_info *die, struct dwarf2_cu *cu)
23115 {
23116   return get_die_type_at_offset (die->sect_off, cu->per_cu);
23117 }
23118
23119 /* Add a dependence relationship from CU to REF_PER_CU.  */
23120
23121 static void
23122 dwarf2_add_dependence (struct dwarf2_cu *cu,
23123                        struct dwarf2_per_cu_data *ref_per_cu)
23124 {
23125   void **slot;
23126
23127   if (cu->dependencies == NULL)
23128     cu->dependencies
23129       = htab_create_alloc_ex (5, htab_hash_pointer, htab_eq_pointer,
23130                               NULL, &cu->comp_unit_obstack,
23131                               hashtab_obstack_allocate,
23132                               dummy_obstack_deallocate);
23133
23134   slot = htab_find_slot (cu->dependencies, ref_per_cu, INSERT);
23135   if (*slot == NULL)
23136     *slot = ref_per_cu;
23137 }
23138
23139 /* Subroutine of dwarf2_mark to pass to htab_traverse.
23140    Set the mark field in every compilation unit in the
23141    cache that we must keep because we are keeping CU.  */
23142
23143 static int
23144 dwarf2_mark_helper (void **slot, void *data)
23145 {
23146   struct dwarf2_per_cu_data *per_cu;
23147
23148   per_cu = (struct dwarf2_per_cu_data *) *slot;
23149
23150   /* cu->dependencies references may not yet have been ever read if QUIT aborts
23151      reading of the chain.  As such dependencies remain valid it is not much
23152      useful to track and undo them during QUIT cleanups.  */
23153   if (per_cu->cu == NULL)
23154     return 1;
23155
23156   if (per_cu->cu->mark)
23157     return 1;
23158   per_cu->cu->mark = 1;
23159
23160   if (per_cu->cu->dependencies != NULL)
23161     htab_traverse (per_cu->cu->dependencies, dwarf2_mark_helper, NULL);
23162
23163   return 1;
23164 }
23165
23166 /* Set the mark field in CU and in every other compilation unit in the
23167    cache that we must keep because we are keeping CU.  */
23168
23169 static void
23170 dwarf2_mark (struct dwarf2_cu *cu)
23171 {
23172   if (cu->mark)
23173     return;
23174   cu->mark = 1;
23175   if (cu->dependencies != NULL)
23176     htab_traverse (cu->dependencies, dwarf2_mark_helper, NULL);
23177 }
23178
23179 static void
23180 dwarf2_clear_marks (struct dwarf2_per_cu_data *per_cu)
23181 {
23182   while (per_cu)
23183     {
23184       per_cu->cu->mark = 0;
23185       per_cu = per_cu->cu->read_in_chain;
23186     }
23187 }
23188
23189 /* Trivial hash function for partial_die_info: the hash value of a DIE
23190    is its offset in .debug_info for this objfile.  */
23191
23192 static hashval_t
23193 partial_die_hash (const void *item)
23194 {
23195   const struct partial_die_info *part_die
23196     = (const struct partial_die_info *) item;
23197
23198   return to_underlying (part_die->sect_off);
23199 }
23200
23201 /* Trivial comparison function for partial_die_info structures: two DIEs
23202    are equal if they have the same offset.  */
23203
23204 static int
23205 partial_die_eq (const void *item_lhs, const void *item_rhs)
23206 {
23207   const struct partial_die_info *part_die_lhs
23208     = (const struct partial_die_info *) item_lhs;
23209   const struct partial_die_info *part_die_rhs
23210     = (const struct partial_die_info *) item_rhs;
23211
23212   return part_die_lhs->sect_off == part_die_rhs->sect_off;
23213 }
23214
23215 static struct cmd_list_element *set_dwarf_cmdlist;
23216 static struct cmd_list_element *show_dwarf_cmdlist;
23217
23218 static void
23219 set_dwarf_cmd (char *args, int from_tty)
23220 {
23221   help_list (set_dwarf_cmdlist, "maintenance set dwarf ", all_commands,
23222              gdb_stdout);
23223 }
23224
23225 static void
23226 show_dwarf_cmd (char *args, int from_tty)
23227 {
23228   cmd_show_list (show_dwarf_cmdlist, from_tty, "");
23229 }
23230
23231 /* Free data associated with OBJFILE, if necessary.  */
23232
23233 static void
23234 dwarf2_per_objfile_free (struct objfile *objfile, void *d)
23235 {
23236   struct dwarf2_per_objfile *data = (struct dwarf2_per_objfile *) d;
23237   int ix;
23238
23239   /* Make sure we don't accidentally use dwarf2_per_objfile while
23240      cleaning up.  */
23241   dwarf2_per_objfile = NULL;
23242
23243   for (ix = 0; ix < data->n_comp_units; ++ix)
23244    VEC_free (dwarf2_per_cu_ptr, data->all_comp_units[ix]->imported_symtabs);
23245
23246   for (ix = 0; ix < data->n_type_units; ++ix)
23247     VEC_free (dwarf2_per_cu_ptr,
23248               data->all_type_units[ix]->per_cu.imported_symtabs);
23249   xfree (data->all_type_units);
23250
23251   VEC_free (dwarf2_section_info_def, data->types);
23252
23253   if (data->dwo_files)
23254     free_dwo_files (data->dwo_files, objfile);
23255   if (data->dwp_file)
23256     gdb_bfd_unref (data->dwp_file->dbfd);
23257
23258   if (data->dwz_file && data->dwz_file->dwz_bfd)
23259     gdb_bfd_unref (data->dwz_file->dwz_bfd);
23260 }
23261
23262 \f
23263 /* The "save gdb-index" command.  */
23264
23265 /* In-memory buffer to prepare data to be written later to a file.  */
23266 class data_buf
23267 {
23268 public:
23269   /* Copy DATA to the end of the buffer.  */
23270   template<typename T>
23271   void append_data (const T &data)
23272   {
23273     std::copy (reinterpret_cast<const gdb_byte *> (&data),
23274                reinterpret_cast<const gdb_byte *> (&data + 1),
23275                grow (sizeof (data)));
23276   }
23277
23278   /* Copy CSTR (a zero-terminated string) to the end of buffer.  The
23279      terminating zero is appended too.  */
23280   void append_cstr0 (const char *cstr)
23281   {
23282     const size_t size = strlen (cstr) + 1;
23283     std::copy (cstr, cstr + size, grow (size));
23284   }
23285
23286   /* Accept a host-format integer in VAL and append it to the buffer
23287      as a target-format integer which is LEN bytes long.  */
23288   void append_uint (size_t len, bfd_endian byte_order, ULONGEST val)
23289   {
23290     ::store_unsigned_integer (grow (len), len, byte_order, val);
23291   }
23292
23293   /* Return the size of the buffer.  */
23294   size_t size () const
23295   {
23296     return m_vec.size ();
23297   }
23298
23299   /* Write the buffer to FILE.  */
23300   void file_write (FILE *file) const
23301   {
23302     if (::fwrite (m_vec.data (), 1, m_vec.size (), file) != m_vec.size ())
23303       error (_("couldn't write data to file"));
23304   }
23305
23306 private:
23307   /* Grow SIZE bytes at the end of the buffer.  Returns a pointer to
23308      the start of the new block.  */
23309   gdb_byte *grow (size_t size)
23310   {
23311     m_vec.resize (m_vec.size () + size);
23312     return &*m_vec.end () - size;
23313   }
23314
23315   gdb::byte_vector m_vec;
23316 };
23317
23318 /* An entry in the symbol table.  */
23319 struct symtab_index_entry
23320 {
23321   /* The name of the symbol.  */
23322   const char *name;
23323   /* The offset of the name in the constant pool.  */
23324   offset_type index_offset;
23325   /* A sorted vector of the indices of all the CUs that hold an object
23326      of this name.  */
23327   std::vector<offset_type> cu_indices;
23328 };
23329
23330 /* The symbol table.  This is a power-of-2-sized hash table.  */
23331 struct mapped_symtab
23332 {
23333   mapped_symtab ()
23334   {
23335     data.resize (1024);
23336   }
23337
23338   offset_type n_elements = 0;
23339   std::vector<symtab_index_entry> data;
23340 };
23341
23342 /* Find a slot in SYMTAB for the symbol NAME.  Returns a reference to
23343    the slot.
23344    
23345    Function is used only during write_hash_table so no index format backward
23346    compatibility is needed.  */
23347
23348 static symtab_index_entry &
23349 find_slot (struct mapped_symtab *symtab, const char *name)
23350 {
23351   offset_type index, step, hash = mapped_index_string_hash (INT_MAX, name);
23352
23353   index = hash & (symtab->data.size () - 1);
23354   step = ((hash * 17) & (symtab->data.size () - 1)) | 1;
23355
23356   for (;;)
23357     {
23358       if (symtab->data[index].name == NULL
23359           || strcmp (name, symtab->data[index].name) == 0)
23360         return symtab->data[index];
23361       index = (index + step) & (symtab->data.size () - 1);
23362     }
23363 }
23364
23365 /* Expand SYMTAB's hash table.  */
23366
23367 static void
23368 hash_expand (struct mapped_symtab *symtab)
23369 {
23370   auto old_entries = std::move (symtab->data);
23371
23372   symtab->data.clear ();
23373   symtab->data.resize (old_entries.size () * 2);
23374
23375   for (auto &it : old_entries)
23376     if (it.name != NULL)
23377       {
23378         auto &ref = find_slot (symtab, it.name);
23379         ref = std::move (it);
23380       }
23381 }
23382
23383 /* Add an entry to SYMTAB.  NAME is the name of the symbol.
23384    CU_INDEX is the index of the CU in which the symbol appears.
23385    IS_STATIC is one if the symbol is static, otherwise zero (global).  */
23386
23387 static void
23388 add_index_entry (struct mapped_symtab *symtab, const char *name,
23389                  int is_static, gdb_index_symbol_kind kind,
23390                  offset_type cu_index)
23391 {
23392   offset_type cu_index_and_attrs;
23393
23394   ++symtab->n_elements;
23395   if (4 * symtab->n_elements / 3 >= symtab->data.size ())
23396     hash_expand (symtab);
23397
23398   symtab_index_entry &slot = find_slot (symtab, name);
23399   if (slot.name == NULL)
23400     {
23401       slot.name = name;
23402       /* index_offset is set later.  */
23403     }
23404
23405   cu_index_and_attrs = 0;
23406   DW2_GDB_INDEX_CU_SET_VALUE (cu_index_and_attrs, cu_index);
23407   DW2_GDB_INDEX_SYMBOL_STATIC_SET_VALUE (cu_index_and_attrs, is_static);
23408   DW2_GDB_INDEX_SYMBOL_KIND_SET_VALUE (cu_index_and_attrs, kind);
23409
23410   /* We don't want to record an index value twice as we want to avoid the
23411      duplication.
23412      We process all global symbols and then all static symbols
23413      (which would allow us to avoid the duplication by only having to check
23414      the last entry pushed), but a symbol could have multiple kinds in one CU.
23415      To keep things simple we don't worry about the duplication here and
23416      sort and uniqufy the list after we've processed all symbols.  */
23417   slot.cu_indices.push_back (cu_index_and_attrs);
23418 }
23419
23420 /* Sort and remove duplicates of all symbols' cu_indices lists.  */
23421
23422 static void
23423 uniquify_cu_indices (struct mapped_symtab *symtab)
23424 {
23425   for (auto &entry : symtab->data)
23426     {
23427       if (entry.name != NULL && !entry.cu_indices.empty ())
23428         {
23429           auto &cu_indices = entry.cu_indices;
23430           std::sort (cu_indices.begin (), cu_indices.end ());
23431           auto from = std::unique (cu_indices.begin (), cu_indices.end ());
23432           cu_indices.erase (from, cu_indices.end ());
23433         }
23434     }
23435 }
23436
23437 /* A form of 'const char *' suitable for container keys.  Only the
23438    pointer is stored.  The strings themselves are compared, not the
23439    pointers.  */
23440 class c_str_view
23441 {
23442 public:
23443   c_str_view (const char *cstr)
23444     : m_cstr (cstr)
23445   {}
23446
23447   bool operator== (const c_str_view &other) const
23448   {
23449     return strcmp (m_cstr, other.m_cstr) == 0;
23450   }
23451
23452 private:
23453   friend class c_str_view_hasher;
23454   const char *const m_cstr;
23455 };
23456
23457 /* A std::unordered_map::hasher for c_str_view that uses the right
23458    hash function for strings in a mapped index.  */
23459 class c_str_view_hasher
23460 {
23461 public:
23462   size_t operator () (const c_str_view &x) const
23463   {
23464     return mapped_index_string_hash (INT_MAX, x.m_cstr);
23465   }
23466 };
23467
23468 /* A std::unordered_map::hasher for std::vector<>.  */
23469 template<typename T>
23470 class vector_hasher
23471 {
23472 public:
23473   size_t operator () (const std::vector<T> &key) const
23474   {
23475     return iterative_hash (key.data (),
23476                            sizeof (key.front ()) * key.size (), 0);
23477   }
23478 };
23479
23480 /* Write the mapped hash table SYMTAB to the data buffer OUTPUT, with
23481    constant pool entries going into the data buffer CPOOL.  */
23482
23483 static void
23484 write_hash_table (mapped_symtab *symtab, data_buf &output, data_buf &cpool)
23485 {
23486   {
23487     /* Elements are sorted vectors of the indices of all the CUs that
23488        hold an object of this name.  */
23489     std::unordered_map<std::vector<offset_type>, offset_type,
23490                        vector_hasher<offset_type>>
23491       symbol_hash_table;
23492
23493     /* We add all the index vectors to the constant pool first, to
23494        ensure alignment is ok.  */
23495     for (symtab_index_entry &entry : symtab->data)
23496       {
23497         if (entry.name == NULL)
23498           continue;
23499         gdb_assert (entry.index_offset == 0);
23500
23501         /* Finding before inserting is faster than always trying to
23502            insert, because inserting always allocates a node, does the
23503            lookup, and then destroys the new node if another node
23504            already had the same key.  C++17 try_emplace will avoid
23505            this.  */
23506         const auto found
23507           = symbol_hash_table.find (entry.cu_indices);
23508         if (found != symbol_hash_table.end ())
23509           {
23510             entry.index_offset = found->second;
23511             continue;
23512           }
23513
23514         symbol_hash_table.emplace (entry.cu_indices, cpool.size ());
23515         entry.index_offset = cpool.size ();
23516         cpool.append_data (MAYBE_SWAP (entry.cu_indices.size ()));
23517         for (const auto index : entry.cu_indices)
23518           cpool.append_data (MAYBE_SWAP (index));
23519       }
23520   }
23521
23522   /* Now write out the hash table.  */
23523   std::unordered_map<c_str_view, offset_type, c_str_view_hasher> str_table;
23524   for (const auto &entry : symtab->data)
23525     {
23526       offset_type str_off, vec_off;
23527
23528       if (entry.name != NULL)
23529         {
23530           const auto insertpair = str_table.emplace (entry.name, cpool.size ());
23531           if (insertpair.second)
23532             cpool.append_cstr0 (entry.name);
23533           str_off = insertpair.first->second;
23534           vec_off = entry.index_offset;
23535         }
23536       else
23537         {
23538           /* While 0 is a valid constant pool index, it is not valid
23539              to have 0 for both offsets.  */
23540           str_off = 0;
23541           vec_off = 0;
23542         }
23543
23544       output.append_data (MAYBE_SWAP (str_off));
23545       output.append_data (MAYBE_SWAP (vec_off));
23546     }
23547 }
23548
23549 typedef std::unordered_map<partial_symtab *, unsigned int> psym_index_map;
23550
23551 /* Helper struct for building the address table.  */
23552 struct addrmap_index_data
23553 {
23554   addrmap_index_data (data_buf &addr_vec_, psym_index_map &cu_index_htab_)
23555     : addr_vec (addr_vec_), cu_index_htab (cu_index_htab_)
23556   {}
23557
23558   struct objfile *objfile;
23559   data_buf &addr_vec;
23560   psym_index_map &cu_index_htab;
23561
23562   /* Non-zero if the previous_* fields are valid.
23563      We can't write an entry until we see the next entry (since it is only then
23564      that we know the end of the entry).  */
23565   int previous_valid;
23566   /* Index of the CU in the table of all CUs in the index file.  */
23567   unsigned int previous_cu_index;
23568   /* Start address of the CU.  */
23569   CORE_ADDR previous_cu_start;
23570 };
23571
23572 /* Write an address entry to ADDR_VEC.  */
23573
23574 static void
23575 add_address_entry (struct objfile *objfile, data_buf &addr_vec,
23576                    CORE_ADDR start, CORE_ADDR end, unsigned int cu_index)
23577 {
23578   CORE_ADDR baseaddr;
23579
23580   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
23581
23582   addr_vec.append_uint (8, BFD_ENDIAN_LITTLE, start - baseaddr);
23583   addr_vec.append_uint (8, BFD_ENDIAN_LITTLE, end - baseaddr);
23584   addr_vec.append_data (MAYBE_SWAP (cu_index));
23585 }
23586
23587 /* Worker function for traversing an addrmap to build the address table.  */
23588
23589 static int
23590 add_address_entry_worker (void *datap, CORE_ADDR start_addr, void *obj)
23591 {
23592   struct addrmap_index_data *data = (struct addrmap_index_data *) datap;
23593   struct partial_symtab *pst = (struct partial_symtab *) obj;
23594
23595   if (data->previous_valid)
23596     add_address_entry (data->objfile, data->addr_vec,
23597                        data->previous_cu_start, start_addr,
23598                        data->previous_cu_index);
23599
23600   data->previous_cu_start = start_addr;
23601   if (pst != NULL)
23602     {
23603       const auto it = data->cu_index_htab.find (pst);
23604       gdb_assert (it != data->cu_index_htab.cend ());
23605       data->previous_cu_index = it->second;
23606       data->previous_valid = 1;
23607     }
23608   else
23609     data->previous_valid = 0;
23610
23611   return 0;
23612 }
23613
23614 /* Write OBJFILE's address map to ADDR_VEC.
23615    CU_INDEX_HTAB is used to map addrmap entries to their CU indices
23616    in the index file.  */
23617
23618 static void
23619 write_address_map (struct objfile *objfile, data_buf &addr_vec,
23620                    psym_index_map &cu_index_htab)
23621 {
23622   struct addrmap_index_data addrmap_index_data (addr_vec, cu_index_htab);
23623
23624   /* When writing the address table, we have to cope with the fact that
23625      the addrmap iterator only provides the start of a region; we have to
23626      wait until the next invocation to get the start of the next region.  */
23627
23628   addrmap_index_data.objfile = objfile;
23629   addrmap_index_data.previous_valid = 0;
23630
23631   addrmap_foreach (objfile->psymtabs_addrmap, add_address_entry_worker,
23632                    &addrmap_index_data);
23633
23634   /* It's highly unlikely the last entry (end address = 0xff...ff)
23635      is valid, but we should still handle it.
23636      The end address is recorded as the start of the next region, but that
23637      doesn't work here.  To cope we pass 0xff...ff, this is a rare situation
23638      anyway.  */
23639   if (addrmap_index_data.previous_valid)
23640     add_address_entry (objfile, addr_vec,
23641                        addrmap_index_data.previous_cu_start, (CORE_ADDR) -1,
23642                        addrmap_index_data.previous_cu_index);
23643 }
23644
23645 /* Return the symbol kind of PSYM.  */
23646
23647 static gdb_index_symbol_kind
23648 symbol_kind (struct partial_symbol *psym)
23649 {
23650   domain_enum domain = PSYMBOL_DOMAIN (psym);
23651   enum address_class aclass = PSYMBOL_CLASS (psym);
23652
23653   switch (domain)
23654     {
23655     case VAR_DOMAIN:
23656       switch (aclass)
23657         {
23658         case LOC_BLOCK:
23659           return GDB_INDEX_SYMBOL_KIND_FUNCTION;
23660         case LOC_TYPEDEF:
23661           return GDB_INDEX_SYMBOL_KIND_TYPE;
23662         case LOC_COMPUTED:
23663         case LOC_CONST_BYTES:
23664         case LOC_OPTIMIZED_OUT:
23665         case LOC_STATIC:
23666           return GDB_INDEX_SYMBOL_KIND_VARIABLE;
23667         case LOC_CONST:
23668           /* Note: It's currently impossible to recognize psyms as enum values
23669              short of reading the type info.  For now punt.  */
23670           return GDB_INDEX_SYMBOL_KIND_VARIABLE;
23671         default:
23672           /* There are other LOC_FOO values that one might want to classify
23673              as variables, but dwarf2read.c doesn't currently use them.  */
23674           return GDB_INDEX_SYMBOL_KIND_OTHER;
23675         }
23676     case STRUCT_DOMAIN:
23677       return GDB_INDEX_SYMBOL_KIND_TYPE;
23678     default:
23679       return GDB_INDEX_SYMBOL_KIND_OTHER;
23680     }
23681 }
23682
23683 /* Add a list of partial symbols to SYMTAB.  */
23684
23685 static void
23686 write_psymbols (struct mapped_symtab *symtab,
23687                 std::unordered_set<partial_symbol *> &psyms_seen,
23688                 struct partial_symbol **psymp,
23689                 int count,
23690                 offset_type cu_index,
23691                 int is_static)
23692 {
23693   for (; count-- > 0; ++psymp)
23694     {
23695       struct partial_symbol *psym = *psymp;
23696
23697       if (SYMBOL_LANGUAGE (psym) == language_ada)
23698         error (_("Ada is not currently supported by the index"));
23699
23700       /* Only add a given psymbol once.  */
23701       if (psyms_seen.insert (psym).second)
23702         {
23703           gdb_index_symbol_kind kind = symbol_kind (psym);
23704
23705           add_index_entry (symtab, SYMBOL_SEARCH_NAME (psym),
23706                            is_static, kind, cu_index);
23707         }
23708     }
23709 }
23710
23711 /* A helper struct used when iterating over debug_types.  */
23712 struct signatured_type_index_data
23713 {
23714   signatured_type_index_data (data_buf &types_list_,
23715                               std::unordered_set<partial_symbol *> &psyms_seen_)
23716     : types_list (types_list_), psyms_seen (psyms_seen_)
23717   {}
23718
23719   struct objfile *objfile;
23720   struct mapped_symtab *symtab;
23721   data_buf &types_list;
23722   std::unordered_set<partial_symbol *> &psyms_seen;
23723   int cu_index;
23724 };
23725
23726 /* A helper function that writes a single signatured_type to an
23727    obstack.  */
23728
23729 static int
23730 write_one_signatured_type (void **slot, void *d)
23731 {
23732   struct signatured_type_index_data *info
23733     = (struct signatured_type_index_data *) d;
23734   struct signatured_type *entry = (struct signatured_type *) *slot;
23735   struct partial_symtab *psymtab = entry->per_cu.v.psymtab;
23736
23737   write_psymbols (info->symtab,
23738                   info->psyms_seen,
23739                   info->objfile->global_psymbols.list
23740                   + psymtab->globals_offset,
23741                   psymtab->n_global_syms, info->cu_index,
23742                   0);
23743   write_psymbols (info->symtab,
23744                   info->psyms_seen,
23745                   info->objfile->static_psymbols.list
23746                   + psymtab->statics_offset,
23747                   psymtab->n_static_syms, info->cu_index,
23748                   1);
23749
23750   info->types_list.append_uint (8, BFD_ENDIAN_LITTLE,
23751                                 to_underlying (entry->per_cu.sect_off));
23752   info->types_list.append_uint (8, BFD_ENDIAN_LITTLE,
23753                                 to_underlying (entry->type_offset_in_tu));
23754   info->types_list.append_uint (8, BFD_ENDIAN_LITTLE, entry->signature);
23755
23756   ++info->cu_index;
23757
23758   return 1;
23759 }
23760
23761 /* Recurse into all "included" dependencies and count their symbols as
23762    if they appeared in this psymtab.  */
23763
23764 static void
23765 recursively_count_psymbols (struct partial_symtab *psymtab,
23766                             size_t &psyms_seen)
23767 {
23768   for (int i = 0; i < psymtab->number_of_dependencies; ++i)
23769     if (psymtab->dependencies[i]->user != NULL)
23770       recursively_count_psymbols (psymtab->dependencies[i],
23771                                   psyms_seen);
23772
23773   psyms_seen += psymtab->n_global_syms;
23774   psyms_seen += psymtab->n_static_syms;
23775 }
23776
23777 /* Recurse into all "included" dependencies and write their symbols as
23778    if they appeared in this psymtab.  */
23779
23780 static void
23781 recursively_write_psymbols (struct objfile *objfile,
23782                             struct partial_symtab *psymtab,
23783                             struct mapped_symtab *symtab,
23784                             std::unordered_set<partial_symbol *> &psyms_seen,
23785                             offset_type cu_index)
23786 {
23787   int i;
23788
23789   for (i = 0; i < psymtab->number_of_dependencies; ++i)
23790     if (psymtab->dependencies[i]->user != NULL)
23791       recursively_write_psymbols (objfile, psymtab->dependencies[i],
23792                                   symtab, psyms_seen, cu_index);
23793
23794   write_psymbols (symtab,
23795                   psyms_seen,
23796                   objfile->global_psymbols.list + psymtab->globals_offset,
23797                   psymtab->n_global_syms, cu_index,
23798                   0);
23799   write_psymbols (symtab,
23800                   psyms_seen,
23801                   objfile->static_psymbols.list + psymtab->statics_offset,
23802                   psymtab->n_static_syms, cu_index,
23803                   1);
23804 }
23805
23806 /* Create an index file for OBJFILE in the directory DIR.  */
23807
23808 static void
23809 write_psymtabs_to_index (struct objfile *objfile, const char *dir)
23810 {
23811   if (dwarf2_per_objfile->using_index)
23812     error (_("Cannot use an index to create the index"));
23813
23814   if (VEC_length (dwarf2_section_info_def, dwarf2_per_objfile->types) > 1)
23815     error (_("Cannot make an index when the file has multiple .debug_types sections"));
23816
23817   if (!objfile->psymtabs || !objfile->psymtabs_addrmap)
23818     return;
23819
23820   struct stat st;
23821   if (stat (objfile_name (objfile), &st) < 0)
23822     perror_with_name (objfile_name (objfile));
23823
23824   std::string filename (std::string (dir) + SLASH_STRING
23825                         + lbasename (objfile_name (objfile)) + INDEX_SUFFIX);
23826
23827   FILE *out_file = gdb_fopen_cloexec (filename.c_str (), "wb").release ();
23828   if (!out_file)
23829     error (_("Can't open `%s' for writing"), filename.c_str ());
23830
23831   /* Order matters here; we want FILE to be closed before FILENAME is
23832      unlinked, because on MS-Windows one cannot delete a file that is
23833      still open.  (Don't call anything here that might throw until
23834      file_closer is created.)  */
23835   gdb::unlinker unlink_file (filename.c_str ());
23836   gdb_file_up close_out_file (out_file);
23837
23838   mapped_symtab symtab;
23839   data_buf cu_list;
23840
23841   /* While we're scanning CU's create a table that maps a psymtab pointer
23842      (which is what addrmap records) to its index (which is what is recorded
23843      in the index file).  This will later be needed to write the address
23844      table.  */
23845   psym_index_map cu_index_htab;
23846   cu_index_htab.reserve (dwarf2_per_objfile->n_comp_units);
23847
23848   /* The CU list is already sorted, so we don't need to do additional
23849      work here.  Also, the debug_types entries do not appear in
23850      all_comp_units, but only in their own hash table.  */
23851
23852   /* The psyms_seen set is potentially going to be largish (~40k
23853      elements when indexing a -g3 build of GDB itself).  Estimate the
23854      number of elements in order to avoid too many rehashes, which
23855      require rebuilding buckets and thus many trips to
23856      malloc/free.  */
23857   size_t psyms_count = 0;
23858   for (int i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
23859     {
23860       struct dwarf2_per_cu_data *per_cu
23861         = dwarf2_per_objfile->all_comp_units[i];
23862       struct partial_symtab *psymtab = per_cu->v.psymtab;
23863
23864       if (psymtab != NULL && psymtab->user == NULL)
23865         recursively_count_psymbols (psymtab, psyms_count);
23866     }
23867   /* Generating an index for gdb itself shows a ratio of
23868      TOTAL_SEEN_SYMS/UNIQUE_SYMS or ~5.  4 seems like a good bet.  */
23869   std::unordered_set<partial_symbol *> psyms_seen (psyms_count / 4);
23870   for (int i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
23871     {
23872       struct dwarf2_per_cu_data *per_cu
23873         = dwarf2_per_objfile->all_comp_units[i];
23874       struct partial_symtab *psymtab = per_cu->v.psymtab;
23875
23876       /* CU of a shared file from 'dwz -m' may be unused by this main file.
23877          It may be referenced from a local scope but in such case it does not
23878          need to be present in .gdb_index.  */
23879       if (psymtab == NULL)
23880         continue;
23881
23882       if (psymtab->user == NULL)
23883         recursively_write_psymbols (objfile, psymtab, &symtab,
23884                                     psyms_seen, i);
23885
23886       const auto insertpair = cu_index_htab.emplace (psymtab, i);
23887       gdb_assert (insertpair.second);
23888
23889       cu_list.append_uint (8, BFD_ENDIAN_LITTLE,
23890                            to_underlying (per_cu->sect_off));
23891       cu_list.append_uint (8, BFD_ENDIAN_LITTLE, per_cu->length);
23892     }
23893
23894   /* Dump the address map.  */
23895   data_buf addr_vec;
23896   write_address_map (objfile, addr_vec, cu_index_htab);
23897
23898   /* Write out the .debug_type entries, if any.  */
23899   data_buf types_cu_list;
23900   if (dwarf2_per_objfile->signatured_types)
23901     {
23902       signatured_type_index_data sig_data (types_cu_list,
23903                                            psyms_seen);
23904
23905       sig_data.objfile = objfile;
23906       sig_data.symtab = &symtab;
23907       sig_data.cu_index = dwarf2_per_objfile->n_comp_units;
23908       htab_traverse_noresize (dwarf2_per_objfile->signatured_types,
23909                               write_one_signatured_type, &sig_data);
23910     }
23911
23912   /* Now that we've processed all symbols we can shrink their cu_indices
23913      lists.  */
23914   uniquify_cu_indices (&symtab);
23915
23916   data_buf symtab_vec, constant_pool;
23917   write_hash_table (&symtab, symtab_vec, constant_pool);
23918
23919   data_buf contents;
23920   const offset_type size_of_contents = 6 * sizeof (offset_type);
23921   offset_type total_len = size_of_contents;
23922
23923   /* The version number.  */
23924   contents.append_data (MAYBE_SWAP (8));
23925
23926   /* The offset of the CU list from the start of the file.  */
23927   contents.append_data (MAYBE_SWAP (total_len));
23928   total_len += cu_list.size ();
23929
23930   /* The offset of the types CU list from the start of the file.  */
23931   contents.append_data (MAYBE_SWAP (total_len));
23932   total_len += types_cu_list.size ();
23933
23934   /* The offset of the address table from the start of the file.  */
23935   contents.append_data (MAYBE_SWAP (total_len));
23936   total_len += addr_vec.size ();
23937
23938   /* The offset of the symbol table from the start of the file.  */
23939   contents.append_data (MAYBE_SWAP (total_len));
23940   total_len += symtab_vec.size ();
23941
23942   /* The offset of the constant pool from the start of the file.  */
23943   contents.append_data (MAYBE_SWAP (total_len));
23944   total_len += constant_pool.size ();
23945
23946   gdb_assert (contents.size () == size_of_contents);
23947
23948   contents.file_write (out_file);
23949   cu_list.file_write (out_file);
23950   types_cu_list.file_write (out_file);
23951   addr_vec.file_write (out_file);
23952   symtab_vec.file_write (out_file);
23953   constant_pool.file_write (out_file);
23954
23955   /* We want to keep the file.  */
23956   unlink_file.keep ();
23957 }
23958
23959 /* Implementation of the `save gdb-index' command.
23960    
23961    Note that the file format used by this command is documented in the
23962    GDB manual.  Any changes here must be documented there.  */
23963
23964 static void
23965 save_gdb_index_command (char *arg, int from_tty)
23966 {
23967   struct objfile *objfile;
23968
23969   if (!arg || !*arg)
23970     error (_("usage: save gdb-index DIRECTORY"));
23971
23972   ALL_OBJFILES (objfile)
23973   {
23974     struct stat st;
23975
23976     /* If the objfile does not correspond to an actual file, skip it.  */
23977     if (stat (objfile_name (objfile), &st) < 0)
23978       continue;
23979
23980     dwarf2_per_objfile
23981       = (struct dwarf2_per_objfile *) objfile_data (objfile,
23982                                                     dwarf2_objfile_data_key);
23983     if (dwarf2_per_objfile)
23984       {
23985
23986         TRY
23987           {
23988             write_psymtabs_to_index (objfile, arg);
23989           }
23990         CATCH (except, RETURN_MASK_ERROR)
23991           {
23992             exception_fprintf (gdb_stderr, except,
23993                                _("Error while writing index for `%s': "),
23994                                objfile_name (objfile));
23995           }
23996         END_CATCH
23997       }
23998   }
23999 }
24000
24001 \f
24002
24003 int dwarf_always_disassemble;
24004
24005 static void
24006 show_dwarf_always_disassemble (struct ui_file *file, int from_tty,
24007                                struct cmd_list_element *c, const char *value)
24008 {
24009   fprintf_filtered (file,
24010                     _("Whether to always disassemble "
24011                       "DWARF expressions is %s.\n"),
24012                     value);
24013 }
24014
24015 static void
24016 show_check_physname (struct ui_file *file, int from_tty,
24017                      struct cmd_list_element *c, const char *value)
24018 {
24019   fprintf_filtered (file,
24020                     _("Whether to check \"physname\" is %s.\n"),
24021                     value);
24022 }
24023
24024 void _initialize_dwarf2_read (void);
24025
24026 void
24027 _initialize_dwarf2_read (void)
24028 {
24029   struct cmd_list_element *c;
24030
24031   dwarf2_objfile_data_key
24032     = register_objfile_data_with_cleanup (NULL, dwarf2_per_objfile_free);
24033
24034   add_prefix_cmd ("dwarf", class_maintenance, set_dwarf_cmd, _("\
24035 Set DWARF specific variables.\n\
24036 Configure DWARF variables such as the cache size"),
24037                   &set_dwarf_cmdlist, "maintenance set dwarf ",
24038                   0/*allow-unknown*/, &maintenance_set_cmdlist);
24039
24040   add_prefix_cmd ("dwarf", class_maintenance, show_dwarf_cmd, _("\
24041 Show DWARF specific variables\n\
24042 Show DWARF variables such as the cache size"),
24043                   &show_dwarf_cmdlist, "maintenance show dwarf ",
24044                   0/*allow-unknown*/, &maintenance_show_cmdlist);
24045
24046   add_setshow_zinteger_cmd ("max-cache-age", class_obscure,
24047                             &dwarf_max_cache_age, _("\
24048 Set the upper bound on the age of cached DWARF compilation units."), _("\
24049 Show the upper bound on the age of cached DWARF compilation units."), _("\
24050 A higher limit means that cached compilation units will be stored\n\
24051 in memory longer, and more total memory will be used.  Zero disables\n\
24052 caching, which can slow down startup."),
24053                             NULL,
24054                             show_dwarf_max_cache_age,
24055                             &set_dwarf_cmdlist,
24056                             &show_dwarf_cmdlist);
24057
24058   add_setshow_boolean_cmd ("always-disassemble", class_obscure,
24059                            &dwarf_always_disassemble, _("\
24060 Set whether `info address' always disassembles DWARF expressions."), _("\
24061 Show whether `info address' always disassembles DWARF expressions."), _("\
24062 When enabled, DWARF expressions are always printed in an assembly-like\n\
24063 syntax.  When disabled, expressions will be printed in a more\n\
24064 conversational style, when possible."),
24065                            NULL,
24066                            show_dwarf_always_disassemble,
24067                            &set_dwarf_cmdlist,
24068                            &show_dwarf_cmdlist);
24069
24070   add_setshow_zuinteger_cmd ("dwarf-read", no_class, &dwarf_read_debug, _("\
24071 Set debugging of the DWARF reader."), _("\
24072 Show debugging of the DWARF reader."), _("\
24073 When enabled (non-zero), debugging messages are printed during DWARF\n\
24074 reading and symtab expansion.  A value of 1 (one) provides basic\n\
24075 information.  A value greater than 1 provides more verbose information."),
24076                             NULL,
24077                             NULL,
24078                             &setdebuglist, &showdebuglist);
24079
24080   add_setshow_zuinteger_cmd ("dwarf-die", no_class, &dwarf_die_debug, _("\
24081 Set debugging of the DWARF DIE reader."), _("\
24082 Show debugging of the DWARF DIE reader."), _("\
24083 When enabled (non-zero), DIEs are dumped after they are read in.\n\
24084 The value is the maximum depth to print."),
24085                              NULL,
24086                              NULL,
24087                              &setdebuglist, &showdebuglist);
24088
24089   add_setshow_zuinteger_cmd ("dwarf-line", no_class, &dwarf_line_debug, _("\
24090 Set debugging of the dwarf line reader."), _("\
24091 Show debugging of the dwarf line reader."), _("\
24092 When enabled (non-zero), line number entries are dumped as they are read in.\n\
24093 A value of 1 (one) provides basic information.\n\
24094 A value greater than 1 provides more verbose information."),
24095                              NULL,
24096                              NULL,
24097                              &setdebuglist, &showdebuglist);
24098
24099   add_setshow_boolean_cmd ("check-physname", no_class, &check_physname, _("\
24100 Set cross-checking of \"physname\" code against demangler."), _("\
24101 Show cross-checking of \"physname\" code against demangler."), _("\
24102 When enabled, GDB's internal \"physname\" code is checked against\n\
24103 the demangler."),
24104                            NULL, show_check_physname,
24105                            &setdebuglist, &showdebuglist);
24106
24107   add_setshow_boolean_cmd ("use-deprecated-index-sections",
24108                            no_class, &use_deprecated_index_sections, _("\
24109 Set whether to use deprecated gdb_index sections."), _("\
24110 Show whether to use deprecated gdb_index sections."), _("\
24111 When enabled, deprecated .gdb_index sections are used anyway.\n\
24112 Normally they are ignored either because of a missing feature or\n\
24113 performance issue.\n\
24114 Warning: This option must be enabled before gdb reads the file."),
24115                            NULL,
24116                            NULL,
24117                            &setlist, &showlist);
24118
24119   c = add_cmd ("gdb-index", class_files, save_gdb_index_command,
24120                _("\
24121 Save a gdb-index file.\n\
24122 Usage: save gdb-index DIRECTORY"),
24123                &save_cmdlist);
24124   set_cmd_completer (c, filename_completer);
24125
24126   dwarf2_locexpr_index = register_symbol_computed_impl (LOC_COMPUTED,
24127                                                         &dwarf2_locexpr_funcs);
24128   dwarf2_loclist_index = register_symbol_computed_impl (LOC_COMPUTED,
24129                                                         &dwarf2_loclist_funcs);
24130
24131   dwarf2_locexpr_block_index = register_symbol_block_impl (LOC_BLOCK,
24132                                         &dwarf2_block_frame_base_locexpr_funcs);
24133   dwarf2_loclist_block_index = register_symbol_block_impl (LOC_BLOCK,
24134                                         &dwarf2_block_frame_base_loclist_funcs);
24135 }