f1a10c403e567a11140c3e067f7ce1624ecba95a
[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
75 #include <fcntl.h>
76 #include <sys/types.h>
77 #include <algorithm>
78
79 typedef struct symbol *symbolp;
80 DEF_VEC_P (symbolp);
81
82 /* When == 1, print basic high level tracing messages.
83    When > 1, be more verbose.
84    This is in contrast to the low level DIE reading of dwarf_die_debug.  */
85 static unsigned int dwarf_read_debug = 0;
86
87 /* When non-zero, dump DIEs after they are read in.  */
88 static unsigned int dwarf_die_debug = 0;
89
90 /* When non-zero, dump line number entries as they are read in.  */
91 static unsigned int dwarf_line_debug = 0;
92
93 /* When non-zero, cross-check physname against demangler.  */
94 static int check_physname = 0;
95
96 /* When non-zero, do not reject deprecated .gdb_index sections.  */
97 static int use_deprecated_index_sections = 0;
98
99 static const struct objfile_data *dwarf2_objfile_data_key;
100
101 /* The "aclass" indices for various kinds of computed DWARF symbols.  */
102
103 static int dwarf2_locexpr_index;
104 static int dwarf2_loclist_index;
105 static int dwarf2_locexpr_block_index;
106 static int dwarf2_loclist_block_index;
107
108 /* A descriptor for dwarf sections.
109
110    S.ASECTION, SIZE are typically initialized when the objfile is first
111    scanned.  BUFFER, READIN are filled in later when the section is read.
112    If the section contained compressed data then SIZE is updated to record
113    the uncompressed size of the section.
114
115    DWP file format V2 introduces a wrinkle that is easiest to handle by
116    creating the concept of virtual sections contained within a real section.
117    In DWP V2 the sections of the input DWO files are concatenated together
118    into one section, but section offsets are kept relative to the original
119    input section.
120    If this is a virtual dwp-v2 section, S.CONTAINING_SECTION is a backlink to
121    the real section this "virtual" section is contained in, and BUFFER,SIZE
122    describe the virtual section.  */
123
124 struct dwarf2_section_info
125 {
126   union
127   {
128     /* If this is a real section, the bfd section.  */
129     asection *section;
130     /* If this is a virtual section, pointer to the containing ("real")
131        section.  */
132     struct dwarf2_section_info *containing_section;
133   } s;
134   /* Pointer to section data, only valid if readin.  */
135   const gdb_byte *buffer;
136   /* The size of the section, real or virtual.  */
137   bfd_size_type size;
138   /* If this is a virtual section, the offset in the real section.
139      Only valid if is_virtual.  */
140   bfd_size_type virtual_offset;
141   /* True if we have tried to read this section.  */
142   char readin;
143   /* True if this is a virtual section, False otherwise.
144      This specifies which of s.section and s.containing_section to use.  */
145   char is_virtual;
146 };
147
148 typedef struct dwarf2_section_info dwarf2_section_info_def;
149 DEF_VEC_O (dwarf2_section_info_def);
150
151 /* All offsets in the index are of this type.  It must be
152    architecture-independent.  */
153 typedef uint32_t offset_type;
154
155 DEF_VEC_I (offset_type);
156
157 /* Ensure only legit values are used.  */
158 #define DW2_GDB_INDEX_SYMBOL_STATIC_SET_VALUE(cu_index, value) \
159   do { \
160     gdb_assert ((unsigned int) (value) <= 1); \
161     GDB_INDEX_SYMBOL_STATIC_SET_VALUE((cu_index), (value)); \
162   } while (0)
163
164 /* Ensure only legit values are used.  */
165 #define DW2_GDB_INDEX_SYMBOL_KIND_SET_VALUE(cu_index, value) \
166   do { \
167     gdb_assert ((value) >= GDB_INDEX_SYMBOL_KIND_TYPE \
168                 && (value) <= GDB_INDEX_SYMBOL_KIND_OTHER); \
169     GDB_INDEX_SYMBOL_KIND_SET_VALUE((cu_index), (value)); \
170   } while (0)
171
172 /* Ensure we don't use more than the alloted nuber of bits for the CU.  */
173 #define DW2_GDB_INDEX_CU_SET_VALUE(cu_index, value) \
174   do { \
175     gdb_assert (((value) & ~GDB_INDEX_CU_MASK) == 0); \
176     GDB_INDEX_CU_SET_VALUE((cu_index), (value)); \
177   } while (0)
178
179 /* A description of the mapped index.  The file format is described in
180    a comment by the code that writes the index.  */
181 struct mapped_index
182 {
183   /* Index data format version.  */
184   int version;
185
186   /* The total length of the buffer.  */
187   off_t total_size;
188
189   /* A pointer to the address table data.  */
190   const gdb_byte *address_table;
191
192   /* Size of the address table data in bytes.  */
193   offset_type address_table_size;
194
195   /* The symbol table, implemented as a hash table.  */
196   const offset_type *symbol_table;
197
198   /* Size in slots, each slot is 2 offset_types.  */
199   offset_type symbol_table_slots;
200
201   /* A pointer to the constant pool.  */
202   const char *constant_pool;
203 };
204
205 typedef struct dwarf2_per_cu_data *dwarf2_per_cu_ptr;
206 DEF_VEC_P (dwarf2_per_cu_ptr);
207
208 struct tu_stats
209 {
210   int nr_uniq_abbrev_tables;
211   int nr_symtabs;
212   int nr_symtab_sharers;
213   int nr_stmt_less_type_units;
214   int nr_all_type_units_reallocs;
215 };
216
217 /* Collection of data recorded per objfile.
218    This hangs off of dwarf2_objfile_data_key.  */
219
220 struct dwarf2_per_objfile
221 {
222   struct dwarf2_section_info info;
223   struct dwarf2_section_info abbrev;
224   struct dwarf2_section_info line;
225   struct dwarf2_section_info loc;
226   struct dwarf2_section_info loclists;
227   struct dwarf2_section_info macinfo;
228   struct dwarf2_section_info macro;
229   struct dwarf2_section_info str;
230   struct dwarf2_section_info line_str;
231   struct dwarf2_section_info ranges;
232   struct dwarf2_section_info rnglists;
233   struct dwarf2_section_info addr;
234   struct dwarf2_section_info frame;
235   struct dwarf2_section_info eh_frame;
236   struct dwarf2_section_info gdb_index;
237
238   VEC (dwarf2_section_info_def) *types;
239
240   /* Back link.  */
241   struct objfile *objfile;
242
243   /* Table of all the compilation units.  This is used to locate
244      the target compilation unit of a particular reference.  */
245   struct dwarf2_per_cu_data **all_comp_units;
246
247   /* The number of compilation units in ALL_COMP_UNITS.  */
248   int n_comp_units;
249
250   /* The number of .debug_types-related CUs.  */
251   int n_type_units;
252
253   /* The number of elements allocated in all_type_units.
254      If there are skeleton-less TUs, we add them to all_type_units lazily.  */
255   int n_allocated_type_units;
256
257   /* The .debug_types-related CUs (TUs).
258      This is stored in malloc space because we may realloc it.  */
259   struct signatured_type **all_type_units;
260
261   /* Table of struct type_unit_group objects.
262      The hash key is the DW_AT_stmt_list value.  */
263   htab_t type_unit_groups;
264
265   /* A table mapping .debug_types signatures to its signatured_type entry.
266      This is NULL if the .debug_types section hasn't been read in yet.  */
267   htab_t signatured_types;
268
269   /* Type unit statistics, to see how well the scaling improvements
270      are doing.  */
271   struct tu_stats tu_stats;
272
273   /* A chain of compilation units that are currently read in, so that
274      they can be freed later.  */
275   struct dwarf2_per_cu_data *read_in_chain;
276
277   /* A table mapping DW_AT_dwo_name values to struct dwo_file objects.
278      This is NULL if the table hasn't been allocated yet.  */
279   htab_t dwo_files;
280
281   /* Non-zero if we've check for whether there is a DWP file.  */
282   int dwp_checked;
283
284   /* The DWP file if there is one, or NULL.  */
285   struct dwp_file *dwp_file;
286
287   /* The shared '.dwz' file, if one exists.  This is used when the
288      original data was compressed using 'dwz -m'.  */
289   struct dwz_file *dwz_file;
290
291   /* A flag indicating wether this objfile has a section loaded at a
292      VMA of 0.  */
293   int has_section_at_zero;
294
295   /* True if we are using the mapped index,
296      or we are faking it for OBJF_READNOW's sake.  */
297   unsigned char using_index;
298
299   /* The mapped index, or NULL if .gdb_index is missing or not being used.  */
300   struct mapped_index *index_table;
301
302   /* When using index_table, this keeps track of all quick_file_names entries.
303      TUs typically share line table entries with a CU, so we maintain a
304      separate table of all line table entries to support the sharing.
305      Note that while there can be way more TUs than CUs, we've already
306      sorted all the TUs into "type unit groups", grouped by their
307      DW_AT_stmt_list value.  Therefore the only sharing done here is with a
308      CU and its associated TU group if there is one.  */
309   htab_t quick_file_names_table;
310
311   /* Set during partial symbol reading, to prevent queueing of full
312      symbols.  */
313   int reading_partial_symbols;
314
315   /* Table mapping type DIEs to their struct type *.
316      This is NULL if not allocated yet.
317      The mapping is done via (CU/TU + DIE offset) -> type.  */
318   htab_t die_type_hash;
319
320   /* The CUs we recently read.  */
321   VEC (dwarf2_per_cu_ptr) *just_read_cus;
322
323   /* Table containing line_header indexed by offset and offset_in_dwz.  */
324   htab_t line_header_hash;
325 };
326
327 static struct dwarf2_per_objfile *dwarf2_per_objfile;
328
329 /* Default names of the debugging sections.  */
330
331 /* Note that if the debugging section has been compressed, it might
332    have a name like .zdebug_info.  */
333
334 static const struct dwarf2_debug_sections dwarf2_elf_names =
335 {
336   { ".debug_info", ".zdebug_info" },
337   { ".debug_abbrev", ".zdebug_abbrev" },
338   { ".debug_line", ".zdebug_line" },
339   { ".debug_loc", ".zdebug_loc" },
340   { ".debug_loclists", ".zdebug_loclists" },
341   { ".debug_macinfo", ".zdebug_macinfo" },
342   { ".debug_macro", ".zdebug_macro" },
343   { ".debug_str", ".zdebug_str" },
344   { ".debug_line_str", ".zdebug_line_str" },
345   { ".debug_ranges", ".zdebug_ranges" },
346   { ".debug_rnglists", ".zdebug_rnglists" },
347   { ".debug_types", ".zdebug_types" },
348   { ".debug_addr", ".zdebug_addr" },
349   { ".debug_frame", ".zdebug_frame" },
350   { ".eh_frame", NULL },
351   { ".gdb_index", ".zgdb_index" },
352   23
353 };
354
355 /* List of DWO/DWP sections.  */
356
357 static const struct dwop_section_names
358 {
359   struct dwarf2_section_names abbrev_dwo;
360   struct dwarf2_section_names info_dwo;
361   struct dwarf2_section_names line_dwo;
362   struct dwarf2_section_names loc_dwo;
363   struct dwarf2_section_names loclists_dwo;
364   struct dwarf2_section_names macinfo_dwo;
365   struct dwarf2_section_names macro_dwo;
366   struct dwarf2_section_names str_dwo;
367   struct dwarf2_section_names str_offsets_dwo;
368   struct dwarf2_section_names types_dwo;
369   struct dwarf2_section_names cu_index;
370   struct dwarf2_section_names tu_index;
371 }
372 dwop_section_names =
373 {
374   { ".debug_abbrev.dwo", ".zdebug_abbrev.dwo" },
375   { ".debug_info.dwo", ".zdebug_info.dwo" },
376   { ".debug_line.dwo", ".zdebug_line.dwo" },
377   { ".debug_loc.dwo", ".zdebug_loc.dwo" },
378   { ".debug_loclists.dwo", ".zdebug_loclists.dwo" },
379   { ".debug_macinfo.dwo", ".zdebug_macinfo.dwo" },
380   { ".debug_macro.dwo", ".zdebug_macro.dwo" },
381   { ".debug_str.dwo", ".zdebug_str.dwo" },
382   { ".debug_str_offsets.dwo", ".zdebug_str_offsets.dwo" },
383   { ".debug_types.dwo", ".zdebug_types.dwo" },
384   { ".debug_cu_index", ".zdebug_cu_index" },
385   { ".debug_tu_index", ".zdebug_tu_index" },
386 };
387
388 /* local data types */
389
390 /* The data in a compilation unit header, after target2host
391    translation, looks like this.  */
392 struct comp_unit_head
393 {
394   unsigned int length;
395   short version;
396   unsigned char addr_size;
397   unsigned char signed_addr_p;
398   sect_offset abbrev_offset;
399
400   /* Size of file offsets; either 4 or 8.  */
401   unsigned int offset_size;
402
403   /* Size of the length field; either 4 or 12.  */
404   unsigned int initial_length_size;
405
406   enum dwarf_unit_type unit_type;
407
408   /* Offset to the first byte of this compilation unit header in the
409      .debug_info section, for resolving relative reference dies.  */
410   sect_offset offset;
411
412   /* Offset to first die in this cu from the start of the cu.
413      This will be the first byte following the compilation unit header.  */
414   cu_offset first_die_offset;
415
416   /* 64-bit signature of this type unit - it is valid only for
417      UNIT_TYPE DW_UT_type.  */
418   ULONGEST signature;
419
420   /* For types, offset in the type's DIE of the type defined by this TU.  */
421   cu_offset type_offset_in_tu;
422 };
423
424 /* Type used for delaying computation of method physnames.
425    See comments for compute_delayed_physnames.  */
426 struct delayed_method_info
427 {
428   /* The type to which the method is attached, i.e., its parent class.  */
429   struct type *type;
430
431   /* The index of the method in the type's function fieldlists.  */
432   int fnfield_index;
433
434   /* The index of the method in the fieldlist.  */
435   int index;
436
437   /* The name of the DIE.  */
438   const char *name;
439
440   /*  The DIE associated with this method.  */
441   struct die_info *die;
442 };
443
444 typedef struct delayed_method_info delayed_method_info;
445 DEF_VEC_O (delayed_method_info);
446
447 /* Internal state when decoding a particular compilation unit.  */
448 struct dwarf2_cu
449 {
450   /* The objfile containing this compilation unit.  */
451   struct objfile *objfile;
452
453   /* The header of the compilation unit.  */
454   struct comp_unit_head header;
455
456   /* Base address of this compilation unit.  */
457   CORE_ADDR base_address;
458
459   /* Non-zero if base_address has been set.  */
460   int base_known;
461
462   /* The language we are debugging.  */
463   enum language language;
464   const struct language_defn *language_defn;
465
466   const char *producer;
467
468   /* The generic symbol table building routines have separate lists for
469      file scope symbols and all all other scopes (local scopes).  So
470      we need to select the right one to pass to add_symbol_to_list().
471      We do it by keeping a pointer to the correct list in list_in_scope.
472
473      FIXME: The original dwarf code just treated the file scope as the
474      first local scope, and all other local scopes as nested local
475      scopes, and worked fine.  Check to see if we really need to
476      distinguish these in buildsym.c.  */
477   struct pending **list_in_scope;
478
479   /* The abbrev table for this CU.
480      Normally this points to the abbrev table in the objfile.
481      But if DWO_UNIT is non-NULL this is the abbrev table in the DWO file.  */
482   struct abbrev_table *abbrev_table;
483
484   /* Hash table holding all the loaded partial DIEs
485      with partial_die->offset.SECT_OFF as hash.  */
486   htab_t partial_dies;
487
488   /* Storage for things with the same lifetime as this read-in compilation
489      unit, including partial DIEs.  */
490   struct obstack comp_unit_obstack;
491
492   /* When multiple dwarf2_cu structures are living in memory, this field
493      chains them all together, so that they can be released efficiently.
494      We will probably also want a generation counter so that most-recently-used
495      compilation units are cached...  */
496   struct dwarf2_per_cu_data *read_in_chain;
497
498   /* Backlink to our per_cu entry.  */
499   struct dwarf2_per_cu_data *per_cu;
500
501   /* How many compilation units ago was this CU last referenced?  */
502   int last_used;
503
504   /* A hash table of DIE cu_offset for following references with
505      die_info->offset.sect_off as hash.  */
506   htab_t die_hash;
507
508   /* Full DIEs if read in.  */
509   struct die_info *dies;
510
511   /* A set of pointers to dwarf2_per_cu_data objects for compilation
512      units referenced by this one.  Only set during full symbol processing;
513      partial symbol tables do not have dependencies.  */
514   htab_t dependencies;
515
516   /* Header data from the line table, during full symbol processing.  */
517   struct line_header *line_header;
518
519   /* A list of methods which need to have physnames computed
520      after all type information has been read.  */
521   VEC (delayed_method_info) *method_list;
522
523   /* To be copied to symtab->call_site_htab.  */
524   htab_t call_site_htab;
525
526   /* Non-NULL if this CU came from a DWO file.
527      There is an invariant here that is important to remember:
528      Except for attributes copied from the top level DIE in the "main"
529      (or "stub") file in preparation for reading the DWO file
530      (e.g., DW_AT_GNU_addr_base), we KISS: there is only *one* CU.
531      Either there isn't a DWO file (in which case this is NULL and the point
532      is moot), or there is and either we're not going to read it (in which
533      case this is NULL) or there is and we are reading it (in which case this
534      is non-NULL).  */
535   struct dwo_unit *dwo_unit;
536
537   /* The DW_AT_addr_base attribute if present, zero otherwise
538      (zero is a valid value though).
539      Note this value comes from the Fission stub CU/TU's DIE.  */
540   ULONGEST addr_base;
541
542   /* The DW_AT_ranges_base attribute if present, zero otherwise
543      (zero is a valid value though).
544      Note this value comes from the Fission stub CU/TU's DIE.
545      Also note that the value is zero in the non-DWO case so this value can
546      be used without needing to know whether DWO files are in use or not.
547      N.B. This does not apply to DW_AT_ranges appearing in
548      DW_TAG_compile_unit dies.  This is a bit of a wart, consider if ever
549      DW_AT_ranges appeared in the DW_TAG_compile_unit of DWO DIEs: then
550      DW_AT_ranges_base *would* have to be applied, and we'd have to care
551      whether the DW_AT_ranges attribute came from the skeleton or DWO.  */
552   ULONGEST ranges_base;
553
554   /* Mark used when releasing cached dies.  */
555   unsigned int mark : 1;
556
557   /* This CU references .debug_loc.  See the symtab->locations_valid field.
558      This test is imperfect as there may exist optimized debug code not using
559      any location list and still facing inlining issues if handled as
560      unoptimized code.  For a future better test see GCC PR other/32998.  */
561   unsigned int has_loclist : 1;
562
563   /* These cache the results for producer_is_* fields.  CHECKED_PRODUCER is set
564      if all the producer_is_* fields are valid.  This information is cached
565      because profiling CU expansion showed excessive time spent in
566      producer_is_gxx_lt_4_6.  */
567   unsigned int checked_producer : 1;
568   unsigned int producer_is_gxx_lt_4_6 : 1;
569   unsigned int producer_is_gcc_lt_4_3 : 1;
570   unsigned int producer_is_icc : 1;
571
572   /* When set, the file that we're processing is known to have
573      debugging info for C++ namespaces.  GCC 3.3.x did not produce
574      this information, but later versions do.  */
575
576   unsigned int processing_has_namespace_info : 1;
577 };
578
579 /* Persistent data held for a compilation unit, even when not
580    processing it.  We put a pointer to this structure in the
581    read_symtab_private field of the psymtab.  */
582
583 struct dwarf2_per_cu_data
584 {
585   /* The start offset and length of this compilation unit.
586      NOTE: Unlike comp_unit_head.length, this length includes
587      initial_length_size.
588      If the DIE refers to a DWO file, this is always of the original die,
589      not the DWO file.  */
590   sect_offset offset;
591   unsigned int length;
592
593   /* DWARF standard version this data has been read from (such as 4 or 5).  */
594   short dwarf_version;
595
596   /* Flag indicating this compilation unit will be read in before
597      any of the current compilation units are processed.  */
598   unsigned int queued : 1;
599
600   /* This flag will be set when reading partial DIEs if we need to load
601      absolutely all DIEs for this compilation unit, instead of just the ones
602      we think are interesting.  It gets set if we look for a DIE in the
603      hash table and don't find it.  */
604   unsigned int load_all_dies : 1;
605
606   /* Non-zero if this CU is from .debug_types.
607      Struct dwarf2_per_cu_data is contained in struct signatured_type iff
608      this is non-zero.  */
609   unsigned int is_debug_types : 1;
610
611   /* Non-zero if this CU is from the .dwz file.  */
612   unsigned int is_dwz : 1;
613
614   /* Non-zero if reading a TU directly from a DWO file, bypassing the stub.
615      This flag is only valid if is_debug_types is true.
616      We can't read a CU directly from a DWO file: There are required
617      attributes in the stub.  */
618   unsigned int reading_dwo_directly : 1;
619
620   /* Non-zero if the TU has been read.
621      This is used to assist the "Stay in DWO Optimization" for Fission:
622      When reading a DWO, it's faster to read TUs from the DWO instead of
623      fetching them from random other DWOs (due to comdat folding).
624      If the TU has already been read, the optimization is unnecessary
625      (and unwise - we don't want to change where gdb thinks the TU lives
626      "midflight").
627      This flag is only valid if is_debug_types is true.  */
628   unsigned int tu_read : 1;
629
630   /* The section this CU/TU lives in.
631      If the DIE refers to a DWO file, this is always the original die,
632      not the DWO file.  */
633   struct dwarf2_section_info *section;
634
635   /* Set to non-NULL iff this CU is currently loaded.  When it gets freed out
636      of the CU cache it gets reset to NULL again.  This is left as NULL for
637      dummy CUs (a CU header, but nothing else).  */
638   struct dwarf2_cu *cu;
639
640   /* The corresponding objfile.
641      Normally we can get the objfile from dwarf2_per_objfile.
642      However we can enter this file with just a "per_cu" handle.  */
643   struct objfile *objfile;
644
645   /* When dwarf2_per_objfile->using_index is true, the 'quick' field
646      is active.  Otherwise, the 'psymtab' field is active.  */
647   union
648   {
649     /* The partial symbol table associated with this compilation unit,
650        or NULL for unread partial units.  */
651     struct partial_symtab *psymtab;
652
653     /* Data needed by the "quick" functions.  */
654     struct dwarf2_per_cu_quick_data *quick;
655   } v;
656
657   /* The CUs we import using DW_TAG_imported_unit.  This is filled in
658      while reading psymtabs, used to compute the psymtab dependencies,
659      and then cleared.  Then it is filled in again while reading full
660      symbols, and only deleted when the objfile is destroyed.
661
662      This is also used to work around a difference between the way gold
663      generates .gdb_index version <=7 and the way gdb does.  Arguably this
664      is a gold bug.  For symbols coming from TUs, gold records in the index
665      the CU that includes the TU instead of the TU itself.  This breaks
666      dw2_lookup_symbol: It assumes that if the index says symbol X lives
667      in CU/TU Y, then one need only expand Y and a subsequent lookup in Y
668      will find X.  Alas TUs live in their own symtab, so after expanding CU Y
669      we need to look in TU Z to find X.  Fortunately, this is akin to
670      DW_TAG_imported_unit, so we just use the same mechanism: For
671      .gdb_index version <=7 this also records the TUs that the CU referred
672      to.  Concurrently with this change gdb was modified to emit version 8
673      indices so we only pay a price for gold generated indices.
674      http://sourceware.org/bugzilla/show_bug.cgi?id=15021.  */
675   VEC (dwarf2_per_cu_ptr) *imported_symtabs;
676 };
677
678 /* Entry in the signatured_types hash table.  */
679
680 struct signatured_type
681 {
682   /* The "per_cu" object of this type.
683      This struct is used iff per_cu.is_debug_types.
684      N.B.: This is the first member so that it's easy to convert pointers
685      between them.  */
686   struct dwarf2_per_cu_data per_cu;
687
688   /* The type's signature.  */
689   ULONGEST signature;
690
691   /* Offset in the TU of the type's DIE, as read from the TU header.
692      If this TU is a DWO stub and the definition lives in a DWO file
693      (specified by DW_AT_GNU_dwo_name), this value is unusable.  */
694   cu_offset type_offset_in_tu;
695
696   /* Offset in the section of the type's DIE.
697      If the definition lives in a DWO file, this is the offset in the
698      .debug_types.dwo section.
699      The value is zero until the actual value is known.
700      Zero is otherwise not a valid section offset.  */
701   sect_offset type_offset_in_section;
702
703   /* Type units are grouped by their DW_AT_stmt_list entry so that they
704      can share them.  This points to the containing symtab.  */
705   struct type_unit_group *type_unit_group;
706
707   /* The type.
708      The first time we encounter this type we fully read it in and install it
709      in the symbol tables.  Subsequent times we only need the type.  */
710   struct type *type;
711
712   /* Containing DWO unit.
713      This field is valid iff per_cu.reading_dwo_directly.  */
714   struct dwo_unit *dwo_unit;
715 };
716
717 typedef struct signatured_type *sig_type_ptr;
718 DEF_VEC_P (sig_type_ptr);
719
720 /* A struct that can be used as a hash key for tables based on DW_AT_stmt_list.
721    This includes type_unit_group and quick_file_names.  */
722
723 struct stmt_list_hash
724 {
725   /* The DWO unit this table is from or NULL if there is none.  */
726   struct dwo_unit *dwo_unit;
727
728   /* Offset in .debug_line or .debug_line.dwo.  */
729   sect_offset line_offset;
730 };
731
732 /* Each element of dwarf2_per_objfile->type_unit_groups is a pointer to
733    an object of this type.  */
734
735 struct type_unit_group
736 {
737   /* dwarf2read.c's main "handle" on a TU symtab.
738      To simplify things we create an artificial CU that "includes" all the
739      type units using this stmt_list so that the rest of the code still has
740      a "per_cu" handle on the symtab.
741      This PER_CU is recognized by having no section.  */
742 #define IS_TYPE_UNIT_GROUP(per_cu) ((per_cu)->section == NULL)
743   struct dwarf2_per_cu_data per_cu;
744
745   /* The TUs that share this DW_AT_stmt_list entry.
746      This is added to while parsing type units to build partial symtabs,
747      and is deleted afterwards and not used again.  */
748   VEC (sig_type_ptr) *tus;
749
750   /* The compunit symtab.
751      Type units in a group needn't all be defined in the same source file,
752      so we create an essentially anonymous symtab as the compunit symtab.  */
753   struct compunit_symtab *compunit_symtab;
754
755   /* The data used to construct the hash key.  */
756   struct stmt_list_hash hash;
757
758   /* The number of symtabs from the line header.
759      The value here must match line_header.num_file_names.  */
760   unsigned int num_symtabs;
761
762   /* The symbol tables for this TU (obtained from the files listed in
763      DW_AT_stmt_list).
764      WARNING: The order of entries here must match the order of entries
765      in the line header.  After the first TU using this type_unit_group, the
766      line header for the subsequent TUs is recreated from this.  This is done
767      because we need to use the same symtabs for each TU using the same
768      DW_AT_stmt_list value.  Also note that symtabs may be repeated here,
769      there's no guarantee the line header doesn't have duplicate entries.  */
770   struct symtab **symtabs;
771 };
772
773 /* These sections are what may appear in a (real or virtual) DWO file.  */
774
775 struct dwo_sections
776 {
777   struct dwarf2_section_info abbrev;
778   struct dwarf2_section_info line;
779   struct dwarf2_section_info loc;
780   struct dwarf2_section_info loclists;
781   struct dwarf2_section_info macinfo;
782   struct dwarf2_section_info macro;
783   struct dwarf2_section_info str;
784   struct dwarf2_section_info str_offsets;
785   /* In the case of a virtual DWO file, these two are unused.  */
786   struct dwarf2_section_info info;
787   VEC (dwarf2_section_info_def) *types;
788 };
789
790 /* CUs/TUs in DWP/DWO files.  */
791
792 struct dwo_unit
793 {
794   /* Backlink to the containing struct dwo_file.  */
795   struct dwo_file *dwo_file;
796
797   /* The "id" that distinguishes this CU/TU.
798      .debug_info calls this "dwo_id", .debug_types calls this "signature".
799      Since signatures came first, we stick with it for consistency.  */
800   ULONGEST signature;
801
802   /* The section this CU/TU lives in, in the DWO file.  */
803   struct dwarf2_section_info *section;
804
805   /* Same as dwarf2_per_cu_data:{offset,length} but in the DWO section.  */
806   sect_offset offset;
807   unsigned int length;
808
809   /* For types, offset in the type's DIE of the type defined by this TU.  */
810   cu_offset type_offset_in_tu;
811 };
812
813 /* include/dwarf2.h defines the DWP section codes.
814    It defines a max value but it doesn't define a min value, which we
815    use for error checking, so provide one.  */
816
817 enum dwp_v2_section_ids
818 {
819   DW_SECT_MIN = 1
820 };
821
822 /* Data for one DWO file.
823
824    This includes virtual DWO files (a virtual DWO file is a DWO file as it
825    appears in a DWP file).  DWP files don't really have DWO files per se -
826    comdat folding of types "loses" the DWO file they came from, and from
827    a high level view DWP files appear to contain a mass of random types.
828    However, to maintain consistency with the non-DWP case we pretend DWP
829    files contain virtual DWO files, and we assign each TU with one virtual
830    DWO file (generally based on the line and abbrev section offsets -
831    a heuristic that seems to work in practice).  */
832
833 struct dwo_file
834 {
835   /* The DW_AT_GNU_dwo_name attribute.
836      For virtual DWO files the name is constructed from the section offsets
837      of abbrev,line,loc,str_offsets so that we combine virtual DWO files
838      from related CU+TUs.  */
839   const char *dwo_name;
840
841   /* The DW_AT_comp_dir attribute.  */
842   const char *comp_dir;
843
844   /* The bfd, when the file is open.  Otherwise this is NULL.
845      This is unused(NULL) for virtual DWO files where we use dwp_file.dbfd.  */
846   bfd *dbfd;
847
848   /* The sections that make up this DWO file.
849      Remember that for virtual DWO files in DWP V2, these are virtual
850      sections (for lack of a better name).  */
851   struct dwo_sections sections;
852
853   /* The CU in the file.
854      We only support one because having more than one requires hacking the
855      dwo_name of each to match, which is highly unlikely to happen.
856      Doing this means all TUs can share comp_dir: We also assume that
857      DW_AT_comp_dir across all TUs in a DWO file will be identical.  */
858   struct dwo_unit *cu;
859
860   /* Table of TUs in the file.
861      Each element is a struct dwo_unit.  */
862   htab_t tus;
863 };
864
865 /* These sections are what may appear in a DWP file.  */
866
867 struct dwp_sections
868 {
869   /* These are used by both DWP version 1 and 2.  */
870   struct dwarf2_section_info str;
871   struct dwarf2_section_info cu_index;
872   struct dwarf2_section_info tu_index;
873
874   /* These are only used by DWP version 2 files.
875      In DWP version 1 the .debug_info.dwo, .debug_types.dwo, and other
876      sections are referenced by section number, and are not recorded here.
877      In DWP version 2 there is at most one copy of all these sections, each
878      section being (effectively) comprised of the concatenation of all of the
879      individual sections that exist in the version 1 format.
880      To keep the code simple we treat each of these concatenated pieces as a
881      section itself (a virtual section?).  */
882   struct dwarf2_section_info abbrev;
883   struct dwarf2_section_info info;
884   struct dwarf2_section_info line;
885   struct dwarf2_section_info loc;
886   struct dwarf2_section_info macinfo;
887   struct dwarf2_section_info macro;
888   struct dwarf2_section_info str_offsets;
889   struct dwarf2_section_info types;
890 };
891
892 /* These sections are what may appear in a virtual DWO file in DWP version 1.
893    A virtual DWO file is a DWO file as it appears in a DWP file.  */
894
895 struct virtual_v1_dwo_sections
896 {
897   struct dwarf2_section_info abbrev;
898   struct dwarf2_section_info line;
899   struct dwarf2_section_info loc;
900   struct dwarf2_section_info macinfo;
901   struct dwarf2_section_info macro;
902   struct dwarf2_section_info str_offsets;
903   /* Each DWP hash table entry records one CU or one TU.
904      That is recorded here, and copied to dwo_unit.section.  */
905   struct dwarf2_section_info info_or_types;
906 };
907
908 /* Similar to virtual_v1_dwo_sections, but for DWP version 2.
909    In version 2, the sections of the DWO files are concatenated together
910    and stored in one section of that name.  Thus each ELF section contains
911    several "virtual" sections.  */
912
913 struct virtual_v2_dwo_sections
914 {
915   bfd_size_type abbrev_offset;
916   bfd_size_type abbrev_size;
917
918   bfd_size_type line_offset;
919   bfd_size_type line_size;
920
921   bfd_size_type loc_offset;
922   bfd_size_type loc_size;
923
924   bfd_size_type macinfo_offset;
925   bfd_size_type macinfo_size;
926
927   bfd_size_type macro_offset;
928   bfd_size_type macro_size;
929
930   bfd_size_type str_offsets_offset;
931   bfd_size_type str_offsets_size;
932
933   /* Each DWP hash table entry records one CU or one TU.
934      That is recorded here, and copied to dwo_unit.section.  */
935   bfd_size_type info_or_types_offset;
936   bfd_size_type info_or_types_size;
937 };
938
939 /* Contents of DWP hash tables.  */
940
941 struct dwp_hash_table
942 {
943   uint32_t version, nr_columns;
944   uint32_t nr_units, nr_slots;
945   const gdb_byte *hash_table, *unit_table;
946   union
947   {
948     struct
949     {
950       const gdb_byte *indices;
951     } v1;
952     struct
953     {
954       /* This is indexed by column number and gives the id of the section
955          in that column.  */
956 #define MAX_NR_V2_DWO_SECTIONS \
957   (1 /* .debug_info or .debug_types */ \
958    + 1 /* .debug_abbrev */ \
959    + 1 /* .debug_line */ \
960    + 1 /* .debug_loc */ \
961    + 1 /* .debug_str_offsets */ \
962    + 1 /* .debug_macro or .debug_macinfo */)
963       int section_ids[MAX_NR_V2_DWO_SECTIONS];
964       const gdb_byte *offsets;
965       const gdb_byte *sizes;
966     } v2;
967   } section_pool;
968 };
969
970 /* Data for one DWP file.  */
971
972 struct dwp_file
973 {
974   /* Name of the file.  */
975   const char *name;
976
977   /* File format version.  */
978   int version;
979
980   /* The bfd.  */
981   bfd *dbfd;
982
983   /* Section info for this file.  */
984   struct dwp_sections sections;
985
986   /* Table of CUs in the file.  */
987   const struct dwp_hash_table *cus;
988
989   /* Table of TUs in the file.  */
990   const struct dwp_hash_table *tus;
991
992   /* Tables of loaded CUs/TUs.  Each entry is a struct dwo_unit *.  */
993   htab_t loaded_cus;
994   htab_t loaded_tus;
995
996   /* Table to map ELF section numbers to their sections.
997      This is only needed for the DWP V1 file format.  */
998   unsigned int num_sections;
999   asection **elf_sections;
1000 };
1001
1002 /* This represents a '.dwz' file.  */
1003
1004 struct dwz_file
1005 {
1006   /* A dwz file can only contain a few sections.  */
1007   struct dwarf2_section_info abbrev;
1008   struct dwarf2_section_info info;
1009   struct dwarf2_section_info str;
1010   struct dwarf2_section_info line;
1011   struct dwarf2_section_info macro;
1012   struct dwarf2_section_info gdb_index;
1013
1014   /* The dwz's BFD.  */
1015   bfd *dwz_bfd;
1016 };
1017
1018 /* Struct used to pass misc. parameters to read_die_and_children, et
1019    al.  which are used for both .debug_info and .debug_types dies.
1020    All parameters here are unchanging for the life of the call.  This
1021    struct exists to abstract away the constant parameters of die reading.  */
1022
1023 struct die_reader_specs
1024 {
1025   /* The bfd of die_section.  */
1026   bfd* abfd;
1027
1028   /* The CU of the DIE we are parsing.  */
1029   struct dwarf2_cu *cu;
1030
1031   /* Non-NULL if reading a DWO file (including one packaged into a DWP).  */
1032   struct dwo_file *dwo_file;
1033
1034   /* The section the die comes from.
1035      This is either .debug_info or .debug_types, or the .dwo variants.  */
1036   struct dwarf2_section_info *die_section;
1037
1038   /* die_section->buffer.  */
1039   const gdb_byte *buffer;
1040
1041   /* The end of the buffer.  */
1042   const gdb_byte *buffer_end;
1043
1044   /* The value of the DW_AT_comp_dir attribute.  */
1045   const char *comp_dir;
1046 };
1047
1048 /* Type of function passed to init_cutu_and_read_dies, et.al.  */
1049 typedef void (die_reader_func_ftype) (const struct die_reader_specs *reader,
1050                                       const gdb_byte *info_ptr,
1051                                       struct die_info *comp_unit_die,
1052                                       int has_children,
1053                                       void *data);
1054
1055 struct file_entry
1056 {
1057   /* Return the include directory at DIR_INDEX stored in LH.  Returns
1058      NULL if DIR_INDEX is out of bounds.  */
1059   const char *include_dir (const line_header *lh) const;
1060
1061   const char *name;
1062   /* The directory index (1-based).  */
1063   unsigned int dir_index;
1064   unsigned int mod_time;
1065   unsigned int length;
1066   /* Non-zero if referenced by the Line Number Program.  */
1067   int included_p;
1068   /* The associated symbol table, if any.  */
1069   struct symtab *symtab;
1070 };
1071
1072 /* The line number information for a compilation unit (found in the
1073    .debug_line section) begins with a "statement program header",
1074    which contains the following information.  */
1075 struct line_header
1076 {
1077   /* Return the include dir at INDEX (0-based).  Returns NULL if INDEX
1078      is out of bounds.  */
1079   const char *include_dir_at (unsigned int index) const
1080   {
1081     if (include_dirs == NULL || index >= num_include_dirs)
1082       return NULL;
1083     return include_dirs[index];
1084   }
1085
1086   /* Return the file name at INDEX (0-based).  Returns NULL if INDEX
1087      is out of bounds.  */
1088   file_entry *file_name_at (unsigned int index) const
1089   {
1090     if (file_names == NULL || index >= num_file_names)
1091       return NULL;
1092     return &file_names[index];
1093   }
1094
1095   /* Offset of line number information in .debug_line section.  */
1096   sect_offset offset;
1097
1098   /* OFFSET is for struct dwz_file associated with dwarf2_per_objfile.  */
1099   unsigned offset_in_dwz : 1;
1100
1101   unsigned int total_length;
1102   unsigned short version;
1103   unsigned int header_length;
1104   unsigned char minimum_instruction_length;
1105   unsigned char maximum_ops_per_instruction;
1106   unsigned char default_is_stmt;
1107   int line_base;
1108   unsigned char line_range;
1109   unsigned char opcode_base;
1110
1111   /* standard_opcode_lengths[i] is the number of operands for the
1112      standard opcode whose value is i.  This means that
1113      standard_opcode_lengths[0] is unused, and the last meaningful
1114      element is standard_opcode_lengths[opcode_base - 1].  */
1115   unsigned char *standard_opcode_lengths;
1116
1117   /* The include_directories table.  NOTE!  These strings are not
1118      allocated with xmalloc; instead, they are pointers into
1119      debug_line_buffer.  If you try to free them, `free' will get
1120      indigestion.  */
1121   unsigned int num_include_dirs, include_dirs_size;
1122   const char **include_dirs;
1123
1124   /* The file_names table.  NOTE!  These strings are not allocated
1125      with xmalloc; instead, they are pointers into debug_line_buffer.
1126      Don't try to free them directly.  */
1127   unsigned int num_file_names, file_names_size;
1128   struct file_entry *file_names;
1129
1130   /* The start and end of the statement program following this
1131      header.  These point into dwarf2_per_objfile->line_buffer.  */
1132   const gdb_byte *statement_program_start, *statement_program_end;
1133 };
1134
1135 const char *
1136 file_entry::include_dir (const line_header *lh) const
1137 {
1138   /* lh->include_dirs is 0-based, but the directory index numbers in
1139      the statement program are 1-based.  */
1140   return lh->include_dir_at (dir_index - 1);
1141 }
1142
1143 /* When we construct a partial symbol table entry we only
1144    need this much information.  */
1145 struct partial_die_info
1146   {
1147     /* Offset of this DIE.  */
1148     sect_offset offset;
1149
1150     /* DWARF-2 tag for this DIE.  */
1151     ENUM_BITFIELD(dwarf_tag) tag : 16;
1152
1153     /* Assorted flags describing the data found in this DIE.  */
1154     unsigned int has_children : 1;
1155     unsigned int is_external : 1;
1156     unsigned int is_declaration : 1;
1157     unsigned int has_type : 1;
1158     unsigned int has_specification : 1;
1159     unsigned int has_pc_info : 1;
1160     unsigned int may_be_inlined : 1;
1161
1162     /* This DIE has been marked DW_AT_main_subprogram.  */
1163     unsigned int main_subprogram : 1;
1164
1165     /* Flag set if the SCOPE field of this structure has been
1166        computed.  */
1167     unsigned int scope_set : 1;
1168
1169     /* Flag set if the DIE has a byte_size attribute.  */
1170     unsigned int has_byte_size : 1;
1171
1172     /* Flag set if the DIE has a DW_AT_const_value attribute.  */
1173     unsigned int has_const_value : 1;
1174
1175     /* Flag set if any of the DIE's children are template arguments.  */
1176     unsigned int has_template_arguments : 1;
1177
1178     /* Flag set if fixup_partial_die has been called on this die.  */
1179     unsigned int fixup_called : 1;
1180
1181     /* Flag set if DW_TAG_imported_unit uses DW_FORM_GNU_ref_alt.  */
1182     unsigned int is_dwz : 1;
1183
1184     /* Flag set if spec_offset uses DW_FORM_GNU_ref_alt.  */
1185     unsigned int spec_is_dwz : 1;
1186
1187     /* The name of this DIE.  Normally the value of DW_AT_name, but
1188        sometimes a default name for unnamed DIEs.  */
1189     const char *name;
1190
1191     /* The linkage name, if present.  */
1192     const char *linkage_name;
1193
1194     /* The scope to prepend to our children.  This is generally
1195        allocated on the comp_unit_obstack, so will disappear
1196        when this compilation unit leaves the cache.  */
1197     const char *scope;
1198
1199     /* Some data associated with the partial DIE.  The tag determines
1200        which field is live.  */
1201     union
1202     {
1203       /* The location description associated with this DIE, if any.  */
1204       struct dwarf_block *locdesc;
1205       /* The offset of an import, for DW_TAG_imported_unit.  */
1206       sect_offset offset;
1207     } d;
1208
1209     /* If HAS_PC_INFO, the PC range associated with this DIE.  */
1210     CORE_ADDR lowpc;
1211     CORE_ADDR highpc;
1212
1213     /* Pointer into the info_buffer (or types_buffer) pointing at the target of
1214        DW_AT_sibling, if any.  */
1215     /* NOTE: This member isn't strictly necessary, read_partial_die could
1216        return DW_AT_sibling values to its caller load_partial_dies.  */
1217     const gdb_byte *sibling;
1218
1219     /* If HAS_SPECIFICATION, the offset of the DIE referred to by
1220        DW_AT_specification (or DW_AT_abstract_origin or
1221        DW_AT_extension).  */
1222     sect_offset spec_offset;
1223
1224     /* Pointers to this DIE's parent, first child, and next sibling,
1225        if any.  */
1226     struct partial_die_info *die_parent, *die_child, *die_sibling;
1227   };
1228
1229 /* This data structure holds the information of an abbrev.  */
1230 struct abbrev_info
1231   {
1232     unsigned int number;        /* number identifying abbrev */
1233     enum dwarf_tag tag;         /* dwarf tag */
1234     unsigned short has_children;                /* boolean */
1235     unsigned short num_attrs;   /* number of attributes */
1236     struct attr_abbrev *attrs;  /* an array of attribute descriptions */
1237     struct abbrev_info *next;   /* next in chain */
1238   };
1239
1240 struct attr_abbrev
1241   {
1242     ENUM_BITFIELD(dwarf_attribute) name : 16;
1243     ENUM_BITFIELD(dwarf_form) form : 16;
1244
1245     /* It is valid only if FORM is DW_FORM_implicit_const.  */
1246     LONGEST implicit_const;
1247   };
1248
1249 /* Size of abbrev_table.abbrev_hash_table.  */
1250 #define ABBREV_HASH_SIZE 121
1251
1252 /* Top level data structure to contain an abbreviation table.  */
1253
1254 struct abbrev_table
1255 {
1256   /* Where the abbrev table came from.
1257      This is used as a sanity check when the table is used.  */
1258   sect_offset offset;
1259
1260   /* Storage for the abbrev table.  */
1261   struct obstack abbrev_obstack;
1262
1263   /* Hash table of abbrevs.
1264      This is an array of size ABBREV_HASH_SIZE allocated in abbrev_obstack.
1265      It could be statically allocated, but the previous code didn't so we
1266      don't either.  */
1267   struct abbrev_info **abbrevs;
1268 };
1269
1270 /* Attributes have a name and a value.  */
1271 struct attribute
1272   {
1273     ENUM_BITFIELD(dwarf_attribute) name : 16;
1274     ENUM_BITFIELD(dwarf_form) form : 15;
1275
1276     /* Has DW_STRING already been updated by dwarf2_canonicalize_name?  This
1277        field should be in u.str (existing only for DW_STRING) but it is kept
1278        here for better struct attribute alignment.  */
1279     unsigned int string_is_canonical : 1;
1280
1281     union
1282       {
1283         const char *str;
1284         struct dwarf_block *blk;
1285         ULONGEST unsnd;
1286         LONGEST snd;
1287         CORE_ADDR addr;
1288         ULONGEST signature;
1289       }
1290     u;
1291   };
1292
1293 /* This data structure holds a complete die structure.  */
1294 struct die_info
1295   {
1296     /* DWARF-2 tag for this DIE.  */
1297     ENUM_BITFIELD(dwarf_tag) tag : 16;
1298
1299     /* Number of attributes */
1300     unsigned char num_attrs;
1301
1302     /* True if we're presently building the full type name for the
1303        type derived from this DIE.  */
1304     unsigned char building_fullname : 1;
1305
1306     /* True if this die is in process.  PR 16581.  */
1307     unsigned char in_process : 1;
1308
1309     /* Abbrev number */
1310     unsigned int abbrev;
1311
1312     /* Offset in .debug_info or .debug_types section.  */
1313     sect_offset offset;
1314
1315     /* The dies in a compilation unit form an n-ary tree.  PARENT
1316        points to this die's parent; CHILD points to the first child of
1317        this node; and all the children of a given node are chained
1318        together via their SIBLING fields.  */
1319     struct die_info *child;     /* Its first child, if any.  */
1320     struct die_info *sibling;   /* Its next sibling, if any.  */
1321     struct die_info *parent;    /* Its parent, if any.  */
1322
1323     /* An array of attributes, with NUM_ATTRS elements.  There may be
1324        zero, but it's not common and zero-sized arrays are not
1325        sufficiently portable C.  */
1326     struct attribute attrs[1];
1327   };
1328
1329 /* Get at parts of an attribute structure.  */
1330
1331 #define DW_STRING(attr)    ((attr)->u.str)
1332 #define DW_STRING_IS_CANONICAL(attr) ((attr)->string_is_canonical)
1333 #define DW_UNSND(attr)     ((attr)->u.unsnd)
1334 #define DW_BLOCK(attr)     ((attr)->u.blk)
1335 #define DW_SND(attr)       ((attr)->u.snd)
1336 #define DW_ADDR(attr)      ((attr)->u.addr)
1337 #define DW_SIGNATURE(attr) ((attr)->u.signature)
1338
1339 /* Blocks are a bunch of untyped bytes.  */
1340 struct dwarf_block
1341   {
1342     size_t size;
1343
1344     /* Valid only if SIZE is not zero.  */
1345     const gdb_byte *data;
1346   };
1347
1348 #ifndef ATTR_ALLOC_CHUNK
1349 #define ATTR_ALLOC_CHUNK 4
1350 #endif
1351
1352 /* Allocate fields for structs, unions and enums in this size.  */
1353 #ifndef DW_FIELD_ALLOC_CHUNK
1354 #define DW_FIELD_ALLOC_CHUNK 4
1355 #endif
1356
1357 /* FIXME: We might want to set this from BFD via bfd_arch_bits_per_byte,
1358    but this would require a corresponding change in unpack_field_as_long
1359    and friends.  */
1360 static int bits_per_byte = 8;
1361
1362 struct nextfield
1363 {
1364   struct nextfield *next;
1365   int accessibility;
1366   int virtuality;
1367   struct field field;
1368 };
1369
1370 struct nextfnfield
1371 {
1372   struct nextfnfield *next;
1373   struct fn_field fnfield;
1374 };
1375
1376 struct fnfieldlist
1377 {
1378   const char *name;
1379   int length;
1380   struct nextfnfield *head;
1381 };
1382
1383 struct typedef_field_list
1384 {
1385   struct typedef_field field;
1386   struct typedef_field_list *next;
1387 };
1388
1389 /* The routines that read and process dies for a C struct or C++ class
1390    pass lists of data member fields and lists of member function fields
1391    in an instance of a field_info structure, as defined below.  */
1392 struct field_info
1393   {
1394     /* List of data member and baseclasses fields.  */
1395     struct nextfield *fields, *baseclasses;
1396
1397     /* Number of fields (including baseclasses).  */
1398     int nfields;
1399
1400     /* Number of baseclasses.  */
1401     int nbaseclasses;
1402
1403     /* Set if the accesibility of one of the fields is not public.  */
1404     int non_public_fields;
1405
1406     /* Member function fields array, entries are allocated in the order they
1407        are encountered in the object file.  */
1408     struct nextfnfield *fnfields;
1409
1410     /* Member function fieldlist array, contains name of possibly overloaded
1411        member function, number of overloaded member functions and a pointer
1412        to the head of the member function field chain.  */
1413     struct fnfieldlist *fnfieldlists;
1414
1415     /* Number of entries in the fnfieldlists array.  */
1416     int nfnfields;
1417
1418     /* typedefs defined inside this class.  TYPEDEF_FIELD_LIST contains head of
1419        a NULL terminated list of TYPEDEF_FIELD_LIST_COUNT elements.  */
1420     struct typedef_field_list *typedef_field_list;
1421     unsigned typedef_field_list_count;
1422   };
1423
1424 /* One item on the queue of compilation units to read in full symbols
1425    for.  */
1426 struct dwarf2_queue_item
1427 {
1428   struct dwarf2_per_cu_data *per_cu;
1429   enum language pretend_language;
1430   struct dwarf2_queue_item *next;
1431 };
1432
1433 /* The current queue.  */
1434 static struct dwarf2_queue_item *dwarf2_queue, *dwarf2_queue_tail;
1435
1436 /* Loaded secondary compilation units are kept in memory until they
1437    have not been referenced for the processing of this many
1438    compilation units.  Set this to zero to disable caching.  Cache
1439    sizes of up to at least twenty will improve startup time for
1440    typical inter-CU-reference binaries, at an obvious memory cost.  */
1441 static int dwarf_max_cache_age = 5;
1442 static void
1443 show_dwarf_max_cache_age (struct ui_file *file, int from_tty,
1444                           struct cmd_list_element *c, const char *value)
1445 {
1446   fprintf_filtered (file, _("The upper bound on the age of cached "
1447                             "DWARF compilation units is %s.\n"),
1448                     value);
1449 }
1450 \f
1451 /* local function prototypes */
1452
1453 static const char *get_section_name (const struct dwarf2_section_info *);
1454
1455 static const char *get_section_file_name (const struct dwarf2_section_info *);
1456
1457 static void dwarf2_locate_sections (bfd *, asection *, void *);
1458
1459 static void dwarf2_find_base_address (struct die_info *die,
1460                                       struct dwarf2_cu *cu);
1461
1462 static struct partial_symtab *create_partial_symtab
1463   (struct dwarf2_per_cu_data *per_cu, const char *name);
1464
1465 static void dwarf2_build_psymtabs_hard (struct objfile *);
1466
1467 static void scan_partial_symbols (struct partial_die_info *,
1468                                   CORE_ADDR *, CORE_ADDR *,
1469                                   int, struct dwarf2_cu *);
1470
1471 static void add_partial_symbol (struct partial_die_info *,
1472                                 struct dwarf2_cu *);
1473
1474 static void add_partial_namespace (struct partial_die_info *pdi,
1475                                    CORE_ADDR *lowpc, CORE_ADDR *highpc,
1476                                    int set_addrmap, struct dwarf2_cu *cu);
1477
1478 static void add_partial_module (struct partial_die_info *pdi, CORE_ADDR *lowpc,
1479                                 CORE_ADDR *highpc, int set_addrmap,
1480                                 struct dwarf2_cu *cu);
1481
1482 static void add_partial_enumeration (struct partial_die_info *enum_pdi,
1483                                      struct dwarf2_cu *cu);
1484
1485 static void add_partial_subprogram (struct partial_die_info *pdi,
1486                                     CORE_ADDR *lowpc, CORE_ADDR *highpc,
1487                                     int need_pc, struct dwarf2_cu *cu);
1488
1489 static void dwarf2_read_symtab (struct partial_symtab *,
1490                                 struct objfile *);
1491
1492 static void psymtab_to_symtab_1 (struct partial_symtab *);
1493
1494 static struct abbrev_info *abbrev_table_lookup_abbrev
1495   (const struct abbrev_table *, unsigned int);
1496
1497 static struct abbrev_table *abbrev_table_read_table
1498   (struct dwarf2_section_info *, sect_offset);
1499
1500 static void abbrev_table_free (struct abbrev_table *);
1501
1502 static void abbrev_table_free_cleanup (void *);
1503
1504 static void dwarf2_read_abbrevs (struct dwarf2_cu *,
1505                                  struct dwarf2_section_info *);
1506
1507 static void dwarf2_free_abbrev_table (void *);
1508
1509 static unsigned int peek_abbrev_code (bfd *, const gdb_byte *);
1510
1511 static struct partial_die_info *load_partial_dies
1512   (const struct die_reader_specs *, const gdb_byte *, int);
1513
1514 static const gdb_byte *read_partial_die (const struct die_reader_specs *,
1515                                          struct partial_die_info *,
1516                                          struct abbrev_info *,
1517                                          unsigned int,
1518                                          const gdb_byte *);
1519
1520 static struct partial_die_info *find_partial_die (sect_offset, int,
1521                                                   struct dwarf2_cu *);
1522
1523 static void fixup_partial_die (struct partial_die_info *,
1524                                struct dwarf2_cu *);
1525
1526 static const gdb_byte *read_attribute (const struct die_reader_specs *,
1527                                        struct attribute *, struct attr_abbrev *,
1528                                        const gdb_byte *);
1529
1530 static unsigned int read_1_byte (bfd *, const gdb_byte *);
1531
1532 static int read_1_signed_byte (bfd *, const gdb_byte *);
1533
1534 static unsigned int read_2_bytes (bfd *, const gdb_byte *);
1535
1536 static unsigned int read_4_bytes (bfd *, const gdb_byte *);
1537
1538 static ULONGEST read_8_bytes (bfd *, const gdb_byte *);
1539
1540 static CORE_ADDR read_address (bfd *, const gdb_byte *ptr, struct dwarf2_cu *,
1541                                unsigned int *);
1542
1543 static LONGEST read_initial_length (bfd *, const gdb_byte *, unsigned int *);
1544
1545 static LONGEST read_checked_initial_length_and_offset
1546   (bfd *, const gdb_byte *, const struct comp_unit_head *,
1547    unsigned int *, unsigned int *);
1548
1549 static LONGEST read_offset (bfd *, const gdb_byte *,
1550                             const struct comp_unit_head *,
1551                             unsigned int *);
1552
1553 static LONGEST read_offset_1 (bfd *, const gdb_byte *, unsigned int);
1554
1555 static sect_offset read_abbrev_offset (struct dwarf2_section_info *,
1556                                        sect_offset);
1557
1558 static const gdb_byte *read_n_bytes (bfd *, const gdb_byte *, unsigned int);
1559
1560 static const char *read_direct_string (bfd *, const gdb_byte *, unsigned int *);
1561
1562 static const char *read_indirect_string (bfd *, const gdb_byte *,
1563                                          const struct comp_unit_head *,
1564                                          unsigned int *);
1565
1566 static const char *read_indirect_line_string (bfd *, const gdb_byte *,
1567                                               const struct comp_unit_head *,
1568                                               unsigned int *);
1569
1570 static const char *read_indirect_string_from_dwz (struct dwz_file *, LONGEST);
1571
1572 static LONGEST read_signed_leb128 (bfd *, const gdb_byte *, unsigned int *);
1573
1574 static CORE_ADDR read_addr_index_from_leb128 (struct dwarf2_cu *,
1575                                               const gdb_byte *,
1576                                               unsigned int *);
1577
1578 static const char *read_str_index (const struct die_reader_specs *reader,
1579                                    ULONGEST str_index);
1580
1581 static void set_cu_language (unsigned int, struct dwarf2_cu *);
1582
1583 static struct attribute *dwarf2_attr (struct die_info *, unsigned int,
1584                                       struct dwarf2_cu *);
1585
1586 static struct attribute *dwarf2_attr_no_follow (struct die_info *,
1587                                                 unsigned int);
1588
1589 static const char *dwarf2_string_attr (struct die_info *die, unsigned int name,
1590                                        struct dwarf2_cu *cu);
1591
1592 static int dwarf2_flag_true_p (struct die_info *die, unsigned name,
1593                                struct dwarf2_cu *cu);
1594
1595 static int die_is_declaration (struct die_info *, struct dwarf2_cu *cu);
1596
1597 static struct die_info *die_specification (struct die_info *die,
1598                                            struct dwarf2_cu **);
1599
1600 static void free_line_header (struct line_header *lh);
1601
1602 static struct line_header *dwarf_decode_line_header (unsigned int offset,
1603                                                      struct dwarf2_cu *cu);
1604
1605 static void dwarf_decode_lines (struct line_header *, const char *,
1606                                 struct dwarf2_cu *, struct partial_symtab *,
1607                                 CORE_ADDR, int decode_mapping);
1608
1609 static void dwarf2_start_subfile (const char *, const char *);
1610
1611 static struct compunit_symtab *dwarf2_start_symtab (struct dwarf2_cu *,
1612                                                     const char *, const char *,
1613                                                     CORE_ADDR);
1614
1615 static struct symbol *new_symbol (struct die_info *, struct type *,
1616                                   struct dwarf2_cu *);
1617
1618 static struct symbol *new_symbol_full (struct die_info *, struct type *,
1619                                        struct dwarf2_cu *, struct symbol *);
1620
1621 static void dwarf2_const_value (const struct attribute *, struct symbol *,
1622                                 struct dwarf2_cu *);
1623
1624 static void dwarf2_const_value_attr (const struct attribute *attr,
1625                                      struct type *type,
1626                                      const char *name,
1627                                      struct obstack *obstack,
1628                                      struct dwarf2_cu *cu, LONGEST *value,
1629                                      const gdb_byte **bytes,
1630                                      struct dwarf2_locexpr_baton **baton);
1631
1632 static struct type *die_type (struct die_info *, struct dwarf2_cu *);
1633
1634 static int need_gnat_info (struct dwarf2_cu *);
1635
1636 static struct type *die_descriptive_type (struct die_info *,
1637                                           struct dwarf2_cu *);
1638
1639 static void set_descriptive_type (struct type *, struct die_info *,
1640                                   struct dwarf2_cu *);
1641
1642 static struct type *die_containing_type (struct die_info *,
1643                                          struct dwarf2_cu *);
1644
1645 static struct type *lookup_die_type (struct die_info *, const struct attribute *,
1646                                      struct dwarf2_cu *);
1647
1648 static struct type *read_type_die (struct die_info *, struct dwarf2_cu *);
1649
1650 static struct type *read_type_die_1 (struct die_info *, struct dwarf2_cu *);
1651
1652 static const char *determine_prefix (struct die_info *die, struct dwarf2_cu *);
1653
1654 static char *typename_concat (struct obstack *obs, const char *prefix,
1655                               const char *suffix, int physname,
1656                               struct dwarf2_cu *cu);
1657
1658 static void read_file_scope (struct die_info *, struct dwarf2_cu *);
1659
1660 static void read_type_unit_scope (struct die_info *, struct dwarf2_cu *);
1661
1662 static void read_func_scope (struct die_info *, struct dwarf2_cu *);
1663
1664 static void read_lexical_block_scope (struct die_info *, struct dwarf2_cu *);
1665
1666 static void read_call_site_scope (struct die_info *die, struct dwarf2_cu *cu);
1667
1668 static int dwarf2_ranges_read (unsigned, CORE_ADDR *, CORE_ADDR *,
1669                                struct dwarf2_cu *, struct partial_symtab *);
1670
1671 /* How dwarf2_get_pc_bounds constructed its *LOWPC and *HIGHPC return
1672    values.  Keep the items ordered with increasing constraints compliance.  */
1673 enum pc_bounds_kind
1674 {
1675   /* No attribute DW_AT_low_pc, DW_AT_high_pc or DW_AT_ranges was found.  */
1676   PC_BOUNDS_NOT_PRESENT,
1677
1678   /* Some of the attributes DW_AT_low_pc, DW_AT_high_pc or DW_AT_ranges
1679      were present but they do not form a valid range of PC addresses.  */
1680   PC_BOUNDS_INVALID,
1681
1682   /* Discontiguous range was found - that is DW_AT_ranges was found.  */
1683   PC_BOUNDS_RANGES,
1684
1685   /* Contiguous range was found - DW_AT_low_pc and DW_AT_high_pc were found.  */
1686   PC_BOUNDS_HIGH_LOW,
1687 };
1688
1689 static enum pc_bounds_kind dwarf2_get_pc_bounds (struct die_info *,
1690                                                  CORE_ADDR *, CORE_ADDR *,
1691                                                  struct dwarf2_cu *,
1692                                                  struct partial_symtab *);
1693
1694 static void get_scope_pc_bounds (struct die_info *,
1695                                  CORE_ADDR *, CORE_ADDR *,
1696                                  struct dwarf2_cu *);
1697
1698 static void dwarf2_record_block_ranges (struct die_info *, struct block *,
1699                                         CORE_ADDR, struct dwarf2_cu *);
1700
1701 static void dwarf2_add_field (struct field_info *, struct die_info *,
1702                               struct dwarf2_cu *);
1703
1704 static void dwarf2_attach_fields_to_type (struct field_info *,
1705                                           struct type *, struct dwarf2_cu *);
1706
1707 static void dwarf2_add_member_fn (struct field_info *,
1708                                   struct die_info *, struct type *,
1709                                   struct dwarf2_cu *);
1710
1711 static void dwarf2_attach_fn_fields_to_type (struct field_info *,
1712                                              struct type *,
1713                                              struct dwarf2_cu *);
1714
1715 static void process_structure_scope (struct die_info *, struct dwarf2_cu *);
1716
1717 static void read_common_block (struct die_info *, struct dwarf2_cu *);
1718
1719 static void read_namespace (struct die_info *die, struct dwarf2_cu *);
1720
1721 static void read_module (struct die_info *die, struct dwarf2_cu *cu);
1722
1723 static struct using_direct **using_directives (enum language);
1724
1725 static void read_import_statement (struct die_info *die, struct dwarf2_cu *);
1726
1727 static int read_namespace_alias (struct die_info *die, struct dwarf2_cu *cu);
1728
1729 static struct type *read_module_type (struct die_info *die,
1730                                       struct dwarf2_cu *cu);
1731
1732 static const char *namespace_name (struct die_info *die,
1733                                    int *is_anonymous, struct dwarf2_cu *);
1734
1735 static void process_enumeration_scope (struct die_info *, struct dwarf2_cu *);
1736
1737 static CORE_ADDR decode_locdesc (struct dwarf_block *, struct dwarf2_cu *);
1738
1739 static enum dwarf_array_dim_ordering read_array_order (struct die_info *,
1740                                                        struct dwarf2_cu *);
1741
1742 static struct die_info *read_die_and_siblings_1
1743   (const struct die_reader_specs *, const gdb_byte *, const gdb_byte **,
1744    struct die_info *);
1745
1746 static struct die_info *read_die_and_siblings (const struct die_reader_specs *,
1747                                                const gdb_byte *info_ptr,
1748                                                const gdb_byte **new_info_ptr,
1749                                                struct die_info *parent);
1750
1751 static const gdb_byte *read_full_die_1 (const struct die_reader_specs *,
1752                                         struct die_info **, const gdb_byte *,
1753                                         int *, int);
1754
1755 static const gdb_byte *read_full_die (const struct die_reader_specs *,
1756                                       struct die_info **, const gdb_byte *,
1757                                       int *);
1758
1759 static void process_die (struct die_info *, struct dwarf2_cu *);
1760
1761 static const char *dwarf2_canonicalize_name (const char *, struct dwarf2_cu *,
1762                                              struct obstack *);
1763
1764 static const char *dwarf2_name (struct die_info *die, struct dwarf2_cu *);
1765
1766 static const char *dwarf2_full_name (const char *name,
1767                                      struct die_info *die,
1768                                      struct dwarf2_cu *cu);
1769
1770 static const char *dwarf2_physname (const char *name, struct die_info *die,
1771                                     struct dwarf2_cu *cu);
1772
1773 static struct die_info *dwarf2_extension (struct die_info *die,
1774                                           struct dwarf2_cu **);
1775
1776 static const char *dwarf_tag_name (unsigned int);
1777
1778 static const char *dwarf_attr_name (unsigned int);
1779
1780 static const char *dwarf_form_name (unsigned int);
1781
1782 static char *dwarf_bool_name (unsigned int);
1783
1784 static const char *dwarf_type_encoding_name (unsigned int);
1785
1786 static struct die_info *sibling_die (struct die_info *);
1787
1788 static void dump_die_shallow (struct ui_file *, int indent, struct die_info *);
1789
1790 static void dump_die_for_error (struct die_info *);
1791
1792 static void dump_die_1 (struct ui_file *, int level, int max_level,
1793                         struct die_info *);
1794
1795 /*static*/ void dump_die (struct die_info *, int max_level);
1796
1797 static void store_in_ref_table (struct die_info *,
1798                                 struct dwarf2_cu *);
1799
1800 static sect_offset dwarf2_get_ref_die_offset (const struct attribute *);
1801
1802 static LONGEST dwarf2_get_attr_constant_value (const struct attribute *, int);
1803
1804 static struct die_info *follow_die_ref_or_sig (struct die_info *,
1805                                                const struct attribute *,
1806                                                struct dwarf2_cu **);
1807
1808 static struct die_info *follow_die_ref (struct die_info *,
1809                                         const struct attribute *,
1810                                         struct dwarf2_cu **);
1811
1812 static struct die_info *follow_die_sig (struct die_info *,
1813                                         const struct attribute *,
1814                                         struct dwarf2_cu **);
1815
1816 static struct type *get_signatured_type (struct die_info *, ULONGEST,
1817                                          struct dwarf2_cu *);
1818
1819 static struct type *get_DW_AT_signature_type (struct die_info *,
1820                                               const struct attribute *,
1821                                               struct dwarf2_cu *);
1822
1823 static void load_full_type_unit (struct dwarf2_per_cu_data *per_cu);
1824
1825 static void read_signatured_type (struct signatured_type *);
1826
1827 static int attr_to_dynamic_prop (const struct attribute *attr,
1828                                  struct die_info *die, struct dwarf2_cu *cu,
1829                                  struct dynamic_prop *prop);
1830
1831 /* memory allocation interface */
1832
1833 static struct dwarf_block *dwarf_alloc_block (struct dwarf2_cu *);
1834
1835 static struct die_info *dwarf_alloc_die (struct dwarf2_cu *, int);
1836
1837 static void dwarf_decode_macros (struct dwarf2_cu *, unsigned int, int);
1838
1839 static int attr_form_is_block (const struct attribute *);
1840
1841 static int attr_form_is_section_offset (const struct attribute *);
1842
1843 static int attr_form_is_constant (const struct attribute *);
1844
1845 static int attr_form_is_ref (const struct attribute *);
1846
1847 static void fill_in_loclist_baton (struct dwarf2_cu *cu,
1848                                    struct dwarf2_loclist_baton *baton,
1849                                    const struct attribute *attr);
1850
1851 static void dwarf2_symbol_mark_computed (const struct attribute *attr,
1852                                          struct symbol *sym,
1853                                          struct dwarf2_cu *cu,
1854                                          int is_block);
1855
1856 static const gdb_byte *skip_one_die (const struct die_reader_specs *reader,
1857                                      const gdb_byte *info_ptr,
1858                                      struct abbrev_info *abbrev);
1859
1860 static void free_stack_comp_unit (void *);
1861
1862 static hashval_t partial_die_hash (const void *item);
1863
1864 static int partial_die_eq (const void *item_lhs, const void *item_rhs);
1865
1866 static struct dwarf2_per_cu_data *dwarf2_find_containing_comp_unit
1867   (sect_offset offset, unsigned int offset_in_dwz, struct objfile *objfile);
1868
1869 static void init_one_comp_unit (struct dwarf2_cu *cu,
1870                                 struct dwarf2_per_cu_data *per_cu);
1871
1872 static void prepare_one_comp_unit (struct dwarf2_cu *cu,
1873                                    struct die_info *comp_unit_die,
1874                                    enum language pretend_language);
1875
1876 static void free_heap_comp_unit (void *);
1877
1878 static void free_cached_comp_units (void *);
1879
1880 static void age_cached_comp_units (void);
1881
1882 static void free_one_cached_comp_unit (struct dwarf2_per_cu_data *);
1883
1884 static struct type *set_die_type (struct die_info *, struct type *,
1885                                   struct dwarf2_cu *);
1886
1887 static void create_all_comp_units (struct objfile *);
1888
1889 static int create_all_type_units (struct objfile *);
1890
1891 static void load_full_comp_unit (struct dwarf2_per_cu_data *,
1892                                  enum language);
1893
1894 static void process_full_comp_unit (struct dwarf2_per_cu_data *,
1895                                     enum language);
1896
1897 static void process_full_type_unit (struct dwarf2_per_cu_data *,
1898                                     enum language);
1899
1900 static void dwarf2_add_dependence (struct dwarf2_cu *,
1901                                    struct dwarf2_per_cu_data *);
1902
1903 static void dwarf2_mark (struct dwarf2_cu *);
1904
1905 static void dwarf2_clear_marks (struct dwarf2_per_cu_data *);
1906
1907 static struct type *get_die_type_at_offset (sect_offset,
1908                                             struct dwarf2_per_cu_data *);
1909
1910 static struct type *get_die_type (struct die_info *die, struct dwarf2_cu *cu);
1911
1912 static void dwarf2_release_queue (void *dummy);
1913
1914 static void queue_comp_unit (struct dwarf2_per_cu_data *per_cu,
1915                              enum language pretend_language);
1916
1917 static void process_queue (void);
1918
1919 /* The return type of find_file_and_directory.  Note, the enclosed
1920    string pointers are only valid while this object is valid.  */
1921
1922 struct file_and_directory
1923 {
1924   /* The filename.  This is never NULL.  */
1925   const char *name;
1926
1927   /* The compilation directory.  NULL if not known.  If we needed to
1928      compute a new string, this points to COMP_DIR_STORAGE, otherwise,
1929      points directly to the DW_AT_comp_dir string attribute owned by
1930      the obstack that owns the DIE.  */
1931   const char *comp_dir;
1932
1933   /* If we needed to build a new string for comp_dir, this is what
1934      owns the storage.  */
1935   std::string comp_dir_storage;
1936 };
1937
1938 static file_and_directory find_file_and_directory (struct die_info *die,
1939                                                    struct dwarf2_cu *cu);
1940
1941 static char *file_full_name (int file, struct line_header *lh,
1942                              const char *comp_dir);
1943
1944 /* Expected enum dwarf_unit_type for read_comp_unit_head.  */
1945 enum class rcuh_kind { COMPILE, TYPE };
1946
1947 static const gdb_byte *read_and_check_comp_unit_head
1948   (struct comp_unit_head *header,
1949    struct dwarf2_section_info *section,
1950    struct dwarf2_section_info *abbrev_section, const gdb_byte *info_ptr,
1951    rcuh_kind section_kind);
1952
1953 static void init_cutu_and_read_dies
1954   (struct dwarf2_per_cu_data *this_cu, struct abbrev_table *abbrev_table,
1955    int use_existing_cu, int keep,
1956    die_reader_func_ftype *die_reader_func, void *data);
1957
1958 static void init_cutu_and_read_dies_simple
1959   (struct dwarf2_per_cu_data *this_cu,
1960    die_reader_func_ftype *die_reader_func, void *data);
1961
1962 static htab_t allocate_signatured_type_table (struct objfile *objfile);
1963
1964 static htab_t allocate_dwo_unit_table (struct objfile *objfile);
1965
1966 static struct dwo_unit *lookup_dwo_unit_in_dwp
1967   (struct dwp_file *dwp_file, const char *comp_dir,
1968    ULONGEST signature, int is_debug_types);
1969
1970 static struct dwp_file *get_dwp_file (void);
1971
1972 static struct dwo_unit *lookup_dwo_comp_unit
1973   (struct dwarf2_per_cu_data *, const char *, const char *, ULONGEST);
1974
1975 static struct dwo_unit *lookup_dwo_type_unit
1976   (struct signatured_type *, const char *, const char *);
1977
1978 static void queue_and_load_all_dwo_tus (struct dwarf2_per_cu_data *);
1979
1980 static void free_dwo_file_cleanup (void *);
1981
1982 static void process_cu_includes (void);
1983
1984 static void check_producer (struct dwarf2_cu *cu);
1985
1986 static void free_line_header_voidp (void *arg);
1987 \f
1988 /* Various complaints about symbol reading that don't abort the process.  */
1989
1990 static void
1991 dwarf2_statement_list_fits_in_line_number_section_complaint (void)
1992 {
1993   complaint (&symfile_complaints,
1994              _("statement list doesn't fit in .debug_line section"));
1995 }
1996
1997 static void
1998 dwarf2_debug_line_missing_file_complaint (void)
1999 {
2000   complaint (&symfile_complaints,
2001              _(".debug_line section has line data without a file"));
2002 }
2003
2004 static void
2005 dwarf2_debug_line_missing_end_sequence_complaint (void)
2006 {
2007   complaint (&symfile_complaints,
2008              _(".debug_line section has line "
2009                "program sequence without an end"));
2010 }
2011
2012 static void
2013 dwarf2_complex_location_expr_complaint (void)
2014 {
2015   complaint (&symfile_complaints, _("location expression too complex"));
2016 }
2017
2018 static void
2019 dwarf2_const_value_length_mismatch_complaint (const char *arg1, int arg2,
2020                                               int arg3)
2021 {
2022   complaint (&symfile_complaints,
2023              _("const value length mismatch for '%s', got %d, expected %d"),
2024              arg1, arg2, arg3);
2025 }
2026
2027 static void
2028 dwarf2_section_buffer_overflow_complaint (struct dwarf2_section_info *section)
2029 {
2030   complaint (&symfile_complaints,
2031              _("debug info runs off end of %s section"
2032                " [in module %s]"),
2033              get_section_name (section),
2034              get_section_file_name (section));
2035 }
2036
2037 static void
2038 dwarf2_macro_malformed_definition_complaint (const char *arg1)
2039 {
2040   complaint (&symfile_complaints,
2041              _("macro debug info contains a "
2042                "malformed macro definition:\n`%s'"),
2043              arg1);
2044 }
2045
2046 static void
2047 dwarf2_invalid_attrib_class_complaint (const char *arg1, const char *arg2)
2048 {
2049   complaint (&symfile_complaints,
2050              _("invalid attribute class or form for '%s' in '%s'"),
2051              arg1, arg2);
2052 }
2053
2054 /* Hash function for line_header_hash.  */
2055
2056 static hashval_t
2057 line_header_hash (const struct line_header *ofs)
2058 {
2059   return ofs->offset.sect_off ^ ofs->offset_in_dwz;
2060 }
2061
2062 /* Hash function for htab_create_alloc_ex for line_header_hash.  */
2063
2064 static hashval_t
2065 line_header_hash_voidp (const void *item)
2066 {
2067   const struct line_header *ofs = (const struct line_header *) item;
2068
2069   return line_header_hash (ofs);
2070 }
2071
2072 /* Equality function for line_header_hash.  */
2073
2074 static int
2075 line_header_eq_voidp (const void *item_lhs, const void *item_rhs)
2076 {
2077   const struct line_header *ofs_lhs = (const struct line_header *) item_lhs;
2078   const struct line_header *ofs_rhs = (const struct line_header *) item_rhs;
2079
2080   return (ofs_lhs->offset.sect_off == ofs_rhs->offset.sect_off
2081           && ofs_lhs->offset_in_dwz == ofs_rhs->offset_in_dwz);
2082 }
2083
2084 \f
2085 #if WORDS_BIGENDIAN
2086
2087 /* Convert VALUE between big- and little-endian.  */
2088 static offset_type
2089 byte_swap (offset_type value)
2090 {
2091   offset_type result;
2092
2093   result = (value & 0xff) << 24;
2094   result |= (value & 0xff00) << 8;
2095   result |= (value & 0xff0000) >> 8;
2096   result |= (value & 0xff000000) >> 24;
2097   return result;
2098 }
2099
2100 #define MAYBE_SWAP(V)  byte_swap (V)
2101
2102 #else
2103 #define MAYBE_SWAP(V) (V)
2104 #endif /* WORDS_BIGENDIAN */
2105
2106 /* Read the given attribute value as an address, taking the attribute's
2107    form into account.  */
2108
2109 static CORE_ADDR
2110 attr_value_as_address (struct attribute *attr)
2111 {
2112   CORE_ADDR addr;
2113
2114   if (attr->form != DW_FORM_addr && attr->form != DW_FORM_GNU_addr_index)
2115     {
2116       /* Aside from a few clearly defined exceptions, attributes that
2117          contain an address must always be in DW_FORM_addr form.
2118          Unfortunately, some compilers happen to be violating this
2119          requirement by encoding addresses using other forms, such
2120          as DW_FORM_data4 for example.  For those broken compilers,
2121          we try to do our best, without any guarantee of success,
2122          to interpret the address correctly.  It would also be nice
2123          to generate a complaint, but that would require us to maintain
2124          a list of legitimate cases where a non-address form is allowed,
2125          as well as update callers to pass in at least the CU's DWARF
2126          version.  This is more overhead than what we're willing to
2127          expand for a pretty rare case.  */
2128       addr = DW_UNSND (attr);
2129     }
2130   else
2131     addr = DW_ADDR (attr);
2132
2133   return addr;
2134 }
2135
2136 /* The suffix for an index file.  */
2137 #define INDEX_SUFFIX ".gdb-index"
2138
2139 /* Try to locate the sections we need for DWARF 2 debugging
2140    information and return true if we have enough to do something.
2141    NAMES points to the dwarf2 section names, or is NULL if the standard
2142    ELF names are used.  */
2143
2144 int
2145 dwarf2_has_info (struct objfile *objfile,
2146                  const struct dwarf2_debug_sections *names)
2147 {
2148   dwarf2_per_objfile = ((struct dwarf2_per_objfile *)
2149                         objfile_data (objfile, dwarf2_objfile_data_key));
2150   if (!dwarf2_per_objfile)
2151     {
2152       /* Initialize per-objfile state.  */
2153       struct dwarf2_per_objfile *data
2154         = XOBNEW (&objfile->objfile_obstack, struct dwarf2_per_objfile);
2155
2156       memset (data, 0, sizeof (*data));
2157       set_objfile_data (objfile, dwarf2_objfile_data_key, data);
2158       dwarf2_per_objfile = data;
2159
2160       bfd_map_over_sections (objfile->obfd, dwarf2_locate_sections,
2161                              (void *) names);
2162       dwarf2_per_objfile->objfile = objfile;
2163     }
2164   return (!dwarf2_per_objfile->info.is_virtual
2165           && dwarf2_per_objfile->info.s.section != NULL
2166           && !dwarf2_per_objfile->abbrev.is_virtual
2167           && dwarf2_per_objfile->abbrev.s.section != NULL);
2168 }
2169
2170 /* Return the containing section of virtual section SECTION.  */
2171
2172 static struct dwarf2_section_info *
2173 get_containing_section (const struct dwarf2_section_info *section)
2174 {
2175   gdb_assert (section->is_virtual);
2176   return section->s.containing_section;
2177 }
2178
2179 /* Return the bfd owner of SECTION.  */
2180
2181 static struct bfd *
2182 get_section_bfd_owner (const struct dwarf2_section_info *section)
2183 {
2184   if (section->is_virtual)
2185     {
2186       section = get_containing_section (section);
2187       gdb_assert (!section->is_virtual);
2188     }
2189   return section->s.section->owner;
2190 }
2191
2192 /* Return the bfd section of SECTION.
2193    Returns NULL if the section is not present.  */
2194
2195 static asection *
2196 get_section_bfd_section (const struct dwarf2_section_info *section)
2197 {
2198   if (section->is_virtual)
2199     {
2200       section = get_containing_section (section);
2201       gdb_assert (!section->is_virtual);
2202     }
2203   return section->s.section;
2204 }
2205
2206 /* Return the name of SECTION.  */
2207
2208 static const char *
2209 get_section_name (const struct dwarf2_section_info *section)
2210 {
2211   asection *sectp = get_section_bfd_section (section);
2212
2213   gdb_assert (sectp != NULL);
2214   return bfd_section_name (get_section_bfd_owner (section), sectp);
2215 }
2216
2217 /* Return the name of the file SECTION is in.  */
2218
2219 static const char *
2220 get_section_file_name (const struct dwarf2_section_info *section)
2221 {
2222   bfd *abfd = get_section_bfd_owner (section);
2223
2224   return bfd_get_filename (abfd);
2225 }
2226
2227 /* Return the id of SECTION.
2228    Returns 0 if SECTION doesn't exist.  */
2229
2230 static int
2231 get_section_id (const struct dwarf2_section_info *section)
2232 {
2233   asection *sectp = get_section_bfd_section (section);
2234
2235   if (sectp == NULL)
2236     return 0;
2237   return sectp->id;
2238 }
2239
2240 /* Return the flags of SECTION.
2241    SECTION (or containing section if this is a virtual section) must exist.  */
2242
2243 static int
2244 get_section_flags (const struct dwarf2_section_info *section)
2245 {
2246   asection *sectp = get_section_bfd_section (section);
2247
2248   gdb_assert (sectp != NULL);
2249   return bfd_get_section_flags (sectp->owner, sectp);
2250 }
2251
2252 /* When loading sections, we look either for uncompressed section or for
2253    compressed section names.  */
2254
2255 static int
2256 section_is_p (const char *section_name,
2257               const struct dwarf2_section_names *names)
2258 {
2259   if (names->normal != NULL
2260       && strcmp (section_name, names->normal) == 0)
2261     return 1;
2262   if (names->compressed != NULL
2263       && strcmp (section_name, names->compressed) == 0)
2264     return 1;
2265   return 0;
2266 }
2267
2268 /* This function is mapped across the sections and remembers the
2269    offset and size of each of the debugging sections we are interested
2270    in.  */
2271
2272 static void
2273 dwarf2_locate_sections (bfd *abfd, asection *sectp, void *vnames)
2274 {
2275   const struct dwarf2_debug_sections *names;
2276   flagword aflag = bfd_get_section_flags (abfd, sectp);
2277
2278   if (vnames == NULL)
2279     names = &dwarf2_elf_names;
2280   else
2281     names = (const struct dwarf2_debug_sections *) vnames;
2282
2283   if ((aflag & SEC_HAS_CONTENTS) == 0)
2284     {
2285     }
2286   else if (section_is_p (sectp->name, &names->info))
2287     {
2288       dwarf2_per_objfile->info.s.section = sectp;
2289       dwarf2_per_objfile->info.size = bfd_get_section_size (sectp);
2290     }
2291   else if (section_is_p (sectp->name, &names->abbrev))
2292     {
2293       dwarf2_per_objfile->abbrev.s.section = sectp;
2294       dwarf2_per_objfile->abbrev.size = bfd_get_section_size (sectp);
2295     }
2296   else if (section_is_p (sectp->name, &names->line))
2297     {
2298       dwarf2_per_objfile->line.s.section = sectp;
2299       dwarf2_per_objfile->line.size = bfd_get_section_size (sectp);
2300     }
2301   else if (section_is_p (sectp->name, &names->loc))
2302     {
2303       dwarf2_per_objfile->loc.s.section = sectp;
2304       dwarf2_per_objfile->loc.size = bfd_get_section_size (sectp);
2305     }
2306   else if (section_is_p (sectp->name, &names->loclists))
2307     {
2308       dwarf2_per_objfile->loclists.s.section = sectp;
2309       dwarf2_per_objfile->loclists.size = bfd_get_section_size (sectp);
2310     }
2311   else if (section_is_p (sectp->name, &names->macinfo))
2312     {
2313       dwarf2_per_objfile->macinfo.s.section = sectp;
2314       dwarf2_per_objfile->macinfo.size = bfd_get_section_size (sectp);
2315     }
2316   else if (section_is_p (sectp->name, &names->macro))
2317     {
2318       dwarf2_per_objfile->macro.s.section = sectp;
2319       dwarf2_per_objfile->macro.size = bfd_get_section_size (sectp);
2320     }
2321   else if (section_is_p (sectp->name, &names->str))
2322     {
2323       dwarf2_per_objfile->str.s.section = sectp;
2324       dwarf2_per_objfile->str.size = bfd_get_section_size (sectp);
2325     }
2326   else if (section_is_p (sectp->name, &names->line_str))
2327     {
2328       dwarf2_per_objfile->line_str.s.section = sectp;
2329       dwarf2_per_objfile->line_str.size = bfd_get_section_size (sectp);
2330     }
2331   else if (section_is_p (sectp->name, &names->addr))
2332     {
2333       dwarf2_per_objfile->addr.s.section = sectp;
2334       dwarf2_per_objfile->addr.size = bfd_get_section_size (sectp);
2335     }
2336   else if (section_is_p (sectp->name, &names->frame))
2337     {
2338       dwarf2_per_objfile->frame.s.section = sectp;
2339       dwarf2_per_objfile->frame.size = bfd_get_section_size (sectp);
2340     }
2341   else if (section_is_p (sectp->name, &names->eh_frame))
2342     {
2343       dwarf2_per_objfile->eh_frame.s.section = sectp;
2344       dwarf2_per_objfile->eh_frame.size = bfd_get_section_size (sectp);
2345     }
2346   else if (section_is_p (sectp->name, &names->ranges))
2347     {
2348       dwarf2_per_objfile->ranges.s.section = sectp;
2349       dwarf2_per_objfile->ranges.size = bfd_get_section_size (sectp);
2350     }
2351   else if (section_is_p (sectp->name, &names->rnglists))
2352     {
2353       dwarf2_per_objfile->rnglists.s.section = sectp;
2354       dwarf2_per_objfile->rnglists.size = bfd_get_section_size (sectp);
2355     }
2356   else if (section_is_p (sectp->name, &names->types))
2357     {
2358       struct dwarf2_section_info type_section;
2359
2360       memset (&type_section, 0, sizeof (type_section));
2361       type_section.s.section = sectp;
2362       type_section.size = bfd_get_section_size (sectp);
2363
2364       VEC_safe_push (dwarf2_section_info_def, dwarf2_per_objfile->types,
2365                      &type_section);
2366     }
2367   else if (section_is_p (sectp->name, &names->gdb_index))
2368     {
2369       dwarf2_per_objfile->gdb_index.s.section = sectp;
2370       dwarf2_per_objfile->gdb_index.size = bfd_get_section_size (sectp);
2371     }
2372
2373   if ((bfd_get_section_flags (abfd, sectp) & (SEC_LOAD | SEC_ALLOC))
2374       && bfd_section_vma (abfd, sectp) == 0)
2375     dwarf2_per_objfile->has_section_at_zero = 1;
2376 }
2377
2378 /* A helper function that decides whether a section is empty,
2379    or not present.  */
2380
2381 static int
2382 dwarf2_section_empty_p (const struct dwarf2_section_info *section)
2383 {
2384   if (section->is_virtual)
2385     return section->size == 0;
2386   return section->s.section == NULL || section->size == 0;
2387 }
2388
2389 /* Read the contents of the section INFO.
2390    OBJFILE is the main object file, but not necessarily the file where
2391    the section comes from.  E.g., for DWO files the bfd of INFO is the bfd
2392    of the DWO file.
2393    If the section is compressed, uncompress it before returning.  */
2394
2395 static void
2396 dwarf2_read_section (struct objfile *objfile, struct dwarf2_section_info *info)
2397 {
2398   asection *sectp;
2399   bfd *abfd;
2400   gdb_byte *buf, *retbuf;
2401
2402   if (info->readin)
2403     return;
2404   info->buffer = NULL;
2405   info->readin = 1;
2406
2407   if (dwarf2_section_empty_p (info))
2408     return;
2409
2410   sectp = get_section_bfd_section (info);
2411
2412   /* If this is a virtual section we need to read in the real one first.  */
2413   if (info->is_virtual)
2414     {
2415       struct dwarf2_section_info *containing_section =
2416         get_containing_section (info);
2417
2418       gdb_assert (sectp != NULL);
2419       if ((sectp->flags & SEC_RELOC) != 0)
2420         {
2421           error (_("Dwarf Error: DWP format V2 with relocations is not"
2422                    " supported in section %s [in module %s]"),
2423                  get_section_name (info), get_section_file_name (info));
2424         }
2425       dwarf2_read_section (objfile, containing_section);
2426       /* Other code should have already caught virtual sections that don't
2427          fit.  */
2428       gdb_assert (info->virtual_offset + info->size
2429                   <= containing_section->size);
2430       /* If the real section is empty or there was a problem reading the
2431          section we shouldn't get here.  */
2432       gdb_assert (containing_section->buffer != NULL);
2433       info->buffer = containing_section->buffer + info->virtual_offset;
2434       return;
2435     }
2436
2437   /* If the section has relocations, we must read it ourselves.
2438      Otherwise we attach it to the BFD.  */
2439   if ((sectp->flags & SEC_RELOC) == 0)
2440     {
2441       info->buffer = gdb_bfd_map_section (sectp, &info->size);
2442       return;
2443     }
2444
2445   buf = (gdb_byte *) obstack_alloc (&objfile->objfile_obstack, info->size);
2446   info->buffer = buf;
2447
2448   /* When debugging .o files, we may need to apply relocations; see
2449      http://sourceware.org/ml/gdb-patches/2002-04/msg00136.html .
2450      We never compress sections in .o files, so we only need to
2451      try this when the section is not compressed.  */
2452   retbuf = symfile_relocate_debug_section (objfile, sectp, buf);
2453   if (retbuf != NULL)
2454     {
2455       info->buffer = retbuf;
2456       return;
2457     }
2458
2459   abfd = get_section_bfd_owner (info);
2460   gdb_assert (abfd != NULL);
2461
2462   if (bfd_seek (abfd, sectp->filepos, SEEK_SET) != 0
2463       || bfd_bread (buf, info->size, abfd) != info->size)
2464     {
2465       error (_("Dwarf Error: Can't read DWARF data"
2466                " in section %s [in module %s]"),
2467              bfd_section_name (abfd, sectp), bfd_get_filename (abfd));
2468     }
2469 }
2470
2471 /* A helper function that returns the size of a section in a safe way.
2472    If you are positive that the section has been read before using the
2473    size, then it is safe to refer to the dwarf2_section_info object's
2474    "size" field directly.  In other cases, you must call this
2475    function, because for compressed sections the size field is not set
2476    correctly until the section has been read.  */
2477
2478 static bfd_size_type
2479 dwarf2_section_size (struct objfile *objfile,
2480                      struct dwarf2_section_info *info)
2481 {
2482   if (!info->readin)
2483     dwarf2_read_section (objfile, info);
2484   return info->size;
2485 }
2486
2487 /* Fill in SECTP, BUFP and SIZEP with section info, given OBJFILE and
2488    SECTION_NAME.  */
2489
2490 void
2491 dwarf2_get_section_info (struct objfile *objfile,
2492                          enum dwarf2_section_enum sect,
2493                          asection **sectp, const gdb_byte **bufp,
2494                          bfd_size_type *sizep)
2495 {
2496   struct dwarf2_per_objfile *data
2497     = (struct dwarf2_per_objfile *) objfile_data (objfile,
2498                                                   dwarf2_objfile_data_key);
2499   struct dwarf2_section_info *info;
2500
2501   /* We may see an objfile without any DWARF, in which case we just
2502      return nothing.  */
2503   if (data == NULL)
2504     {
2505       *sectp = NULL;
2506       *bufp = NULL;
2507       *sizep = 0;
2508       return;
2509     }
2510   switch (sect)
2511     {
2512     case DWARF2_DEBUG_FRAME:
2513       info = &data->frame;
2514       break;
2515     case DWARF2_EH_FRAME:
2516       info = &data->eh_frame;
2517       break;
2518     default:
2519       gdb_assert_not_reached ("unexpected section");
2520     }
2521
2522   dwarf2_read_section (objfile, info);
2523
2524   *sectp = get_section_bfd_section (info);
2525   *bufp = info->buffer;
2526   *sizep = info->size;
2527 }
2528
2529 /* A helper function to find the sections for a .dwz file.  */
2530
2531 static void
2532 locate_dwz_sections (bfd *abfd, asection *sectp, void *arg)
2533 {
2534   struct dwz_file *dwz_file = (struct dwz_file *) arg;
2535
2536   /* Note that we only support the standard ELF names, because .dwz
2537      is ELF-only (at the time of writing).  */
2538   if (section_is_p (sectp->name, &dwarf2_elf_names.abbrev))
2539     {
2540       dwz_file->abbrev.s.section = sectp;
2541       dwz_file->abbrev.size = bfd_get_section_size (sectp);
2542     }
2543   else if (section_is_p (sectp->name, &dwarf2_elf_names.info))
2544     {
2545       dwz_file->info.s.section = sectp;
2546       dwz_file->info.size = bfd_get_section_size (sectp);
2547     }
2548   else if (section_is_p (sectp->name, &dwarf2_elf_names.str))
2549     {
2550       dwz_file->str.s.section = sectp;
2551       dwz_file->str.size = bfd_get_section_size (sectp);
2552     }
2553   else if (section_is_p (sectp->name, &dwarf2_elf_names.line))
2554     {
2555       dwz_file->line.s.section = sectp;
2556       dwz_file->line.size = bfd_get_section_size (sectp);
2557     }
2558   else if (section_is_p (sectp->name, &dwarf2_elf_names.macro))
2559     {
2560       dwz_file->macro.s.section = sectp;
2561       dwz_file->macro.size = bfd_get_section_size (sectp);
2562     }
2563   else if (section_is_p (sectp->name, &dwarf2_elf_names.gdb_index))
2564     {
2565       dwz_file->gdb_index.s.section = sectp;
2566       dwz_file->gdb_index.size = bfd_get_section_size (sectp);
2567     }
2568 }
2569
2570 /* Open the separate '.dwz' debug file, if needed.  Return NULL if
2571    there is no .gnu_debugaltlink section in the file.  Error if there
2572    is such a section but the file cannot be found.  */
2573
2574 static struct dwz_file *
2575 dwarf2_get_dwz_file (void)
2576 {
2577   char *data;
2578   struct cleanup *cleanup;
2579   const char *filename;
2580   struct dwz_file *result;
2581   bfd_size_type buildid_len_arg;
2582   size_t buildid_len;
2583   bfd_byte *buildid;
2584
2585   if (dwarf2_per_objfile->dwz_file != NULL)
2586     return dwarf2_per_objfile->dwz_file;
2587
2588   bfd_set_error (bfd_error_no_error);
2589   data = bfd_get_alt_debug_link_info (dwarf2_per_objfile->objfile->obfd,
2590                                       &buildid_len_arg, &buildid);
2591   if (data == NULL)
2592     {
2593       if (bfd_get_error () == bfd_error_no_error)
2594         return NULL;
2595       error (_("could not read '.gnu_debugaltlink' section: %s"),
2596              bfd_errmsg (bfd_get_error ()));
2597     }
2598   cleanup = make_cleanup (xfree, data);
2599   make_cleanup (xfree, buildid);
2600
2601   buildid_len = (size_t) buildid_len_arg;
2602
2603   filename = (const char *) data;
2604
2605   std::string abs_storage;
2606   if (!IS_ABSOLUTE_PATH (filename))
2607     {
2608       char *abs = gdb_realpath (objfile_name (dwarf2_per_objfile->objfile));
2609
2610       make_cleanup (xfree, abs);
2611       abs_storage = ldirname (abs) + SLASH_STRING + filename;
2612       filename = abs_storage.c_str ();
2613     }
2614
2615   /* First try the file name given in the section.  If that doesn't
2616      work, try to use the build-id instead.  */
2617   gdb_bfd_ref_ptr dwz_bfd (gdb_bfd_open (filename, gnutarget, -1));
2618   if (dwz_bfd != NULL)
2619     {
2620       if (!build_id_verify (dwz_bfd.get (), buildid_len, buildid))
2621         dwz_bfd.release ();
2622     }
2623
2624   if (dwz_bfd == NULL)
2625     dwz_bfd = build_id_to_debug_bfd (buildid_len, buildid);
2626
2627   if (dwz_bfd == NULL)
2628     error (_("could not find '.gnu_debugaltlink' file for %s"),
2629            objfile_name (dwarf2_per_objfile->objfile));
2630
2631   result = OBSTACK_ZALLOC (&dwarf2_per_objfile->objfile->objfile_obstack,
2632                            struct dwz_file);
2633   result->dwz_bfd = dwz_bfd.release ();
2634
2635   bfd_map_over_sections (result->dwz_bfd, locate_dwz_sections, result);
2636
2637   do_cleanups (cleanup);
2638
2639   gdb_bfd_record_inclusion (dwarf2_per_objfile->objfile->obfd, result->dwz_bfd);
2640   dwarf2_per_objfile->dwz_file = result;
2641   return result;
2642 }
2643 \f
2644 /* DWARF quick_symbols_functions support.  */
2645
2646 /* TUs can share .debug_line entries, and there can be a lot more TUs than
2647    unique line tables, so we maintain a separate table of all .debug_line
2648    derived entries to support the sharing.
2649    All the quick functions need is the list of file names.  We discard the
2650    line_header when we're done and don't need to record it here.  */
2651 struct quick_file_names
2652 {
2653   /* The data used to construct the hash key.  */
2654   struct stmt_list_hash hash;
2655
2656   /* The number of entries in file_names, real_names.  */
2657   unsigned int num_file_names;
2658
2659   /* The file names from the line table, after being run through
2660      file_full_name.  */
2661   const char **file_names;
2662
2663   /* The file names from the line table after being run through
2664      gdb_realpath.  These are computed lazily.  */
2665   const char **real_names;
2666 };
2667
2668 /* When using the index (and thus not using psymtabs), each CU has an
2669    object of this type.  This is used to hold information needed by
2670    the various "quick" methods.  */
2671 struct dwarf2_per_cu_quick_data
2672 {
2673   /* The file table.  This can be NULL if there was no file table
2674      or it's currently not read in.
2675      NOTE: This points into dwarf2_per_objfile->quick_file_names_table.  */
2676   struct quick_file_names *file_names;
2677
2678   /* The corresponding symbol table.  This is NULL if symbols for this
2679      CU have not yet been read.  */
2680   struct compunit_symtab *compunit_symtab;
2681
2682   /* A temporary mark bit used when iterating over all CUs in
2683      expand_symtabs_matching.  */
2684   unsigned int mark : 1;
2685
2686   /* True if we've tried to read the file table and found there isn't one.
2687      There will be no point in trying to read it again next time.  */
2688   unsigned int no_file_data : 1;
2689 };
2690
2691 /* Utility hash function for a stmt_list_hash.  */
2692
2693 static hashval_t
2694 hash_stmt_list_entry (const struct stmt_list_hash *stmt_list_hash)
2695 {
2696   hashval_t v = 0;
2697
2698   if (stmt_list_hash->dwo_unit != NULL)
2699     v += (uintptr_t) stmt_list_hash->dwo_unit->dwo_file;
2700   v += stmt_list_hash->line_offset.sect_off;
2701   return v;
2702 }
2703
2704 /* Utility equality function for a stmt_list_hash.  */
2705
2706 static int
2707 eq_stmt_list_entry (const struct stmt_list_hash *lhs,
2708                     const struct stmt_list_hash *rhs)
2709 {
2710   if ((lhs->dwo_unit != NULL) != (rhs->dwo_unit != NULL))
2711     return 0;
2712   if (lhs->dwo_unit != NULL
2713       && lhs->dwo_unit->dwo_file != rhs->dwo_unit->dwo_file)
2714     return 0;
2715
2716   return lhs->line_offset.sect_off == rhs->line_offset.sect_off;
2717 }
2718
2719 /* Hash function for a quick_file_names.  */
2720
2721 static hashval_t
2722 hash_file_name_entry (const void *e)
2723 {
2724   const struct quick_file_names *file_data
2725     = (const struct quick_file_names *) e;
2726
2727   return hash_stmt_list_entry (&file_data->hash);
2728 }
2729
2730 /* Equality function for a quick_file_names.  */
2731
2732 static int
2733 eq_file_name_entry (const void *a, const void *b)
2734 {
2735   const struct quick_file_names *ea = (const struct quick_file_names *) a;
2736   const struct quick_file_names *eb = (const struct quick_file_names *) b;
2737
2738   return eq_stmt_list_entry (&ea->hash, &eb->hash);
2739 }
2740
2741 /* Delete function for a quick_file_names.  */
2742
2743 static void
2744 delete_file_name_entry (void *e)
2745 {
2746   struct quick_file_names *file_data = (struct quick_file_names *) e;
2747   int i;
2748
2749   for (i = 0; i < file_data->num_file_names; ++i)
2750     {
2751       xfree ((void*) file_data->file_names[i]);
2752       if (file_data->real_names)
2753         xfree ((void*) file_data->real_names[i]);
2754     }
2755
2756   /* The space for the struct itself lives on objfile_obstack,
2757      so we don't free it here.  */
2758 }
2759
2760 /* Create a quick_file_names hash table.  */
2761
2762 static htab_t
2763 create_quick_file_names_table (unsigned int nr_initial_entries)
2764 {
2765   return htab_create_alloc (nr_initial_entries,
2766                             hash_file_name_entry, eq_file_name_entry,
2767                             delete_file_name_entry, xcalloc, xfree);
2768 }
2769
2770 /* Read in PER_CU->CU.  This function is unrelated to symtabs, symtab would
2771    have to be created afterwards.  You should call age_cached_comp_units after
2772    processing PER_CU->CU.  dw2_setup must have been already called.  */
2773
2774 static void
2775 load_cu (struct dwarf2_per_cu_data *per_cu)
2776 {
2777   if (per_cu->is_debug_types)
2778     load_full_type_unit (per_cu);
2779   else
2780     load_full_comp_unit (per_cu, language_minimal);
2781
2782   if (per_cu->cu == NULL)
2783     return;  /* Dummy CU.  */
2784
2785   dwarf2_find_base_address (per_cu->cu->dies, per_cu->cu);
2786 }
2787
2788 /* Read in the symbols for PER_CU.  */
2789
2790 static void
2791 dw2_do_instantiate_symtab (struct dwarf2_per_cu_data *per_cu)
2792 {
2793   struct cleanup *back_to;
2794
2795   /* Skip type_unit_groups, reading the type units they contain
2796      is handled elsewhere.  */
2797   if (IS_TYPE_UNIT_GROUP (per_cu))
2798     return;
2799
2800   back_to = make_cleanup (dwarf2_release_queue, NULL);
2801
2802   if (dwarf2_per_objfile->using_index
2803       ? per_cu->v.quick->compunit_symtab == NULL
2804       : (per_cu->v.psymtab == NULL || !per_cu->v.psymtab->readin))
2805     {
2806       queue_comp_unit (per_cu, language_minimal);
2807       load_cu (per_cu);
2808
2809       /* If we just loaded a CU from a DWO, and we're working with an index
2810          that may badly handle TUs, load all the TUs in that DWO as well.
2811          http://sourceware.org/bugzilla/show_bug.cgi?id=15021  */
2812       if (!per_cu->is_debug_types
2813           && per_cu->cu != NULL
2814           && per_cu->cu->dwo_unit != NULL
2815           && dwarf2_per_objfile->index_table != NULL
2816           && dwarf2_per_objfile->index_table->version <= 7
2817           /* DWP files aren't supported yet.  */
2818           && get_dwp_file () == NULL)
2819         queue_and_load_all_dwo_tus (per_cu);
2820     }
2821
2822   process_queue ();
2823
2824   /* Age the cache, releasing compilation units that have not
2825      been used recently.  */
2826   age_cached_comp_units ();
2827
2828   do_cleanups (back_to);
2829 }
2830
2831 /* Ensure that the symbols for PER_CU have been read in.  OBJFILE is
2832    the objfile from which this CU came.  Returns the resulting symbol
2833    table.  */
2834
2835 static struct compunit_symtab *
2836 dw2_instantiate_symtab (struct dwarf2_per_cu_data *per_cu)
2837 {
2838   gdb_assert (dwarf2_per_objfile->using_index);
2839   if (!per_cu->v.quick->compunit_symtab)
2840     {
2841       struct cleanup *back_to = make_cleanup (free_cached_comp_units, NULL);
2842       increment_reading_symtab ();
2843       dw2_do_instantiate_symtab (per_cu);
2844       process_cu_includes ();
2845       do_cleanups (back_to);
2846     }
2847
2848   return per_cu->v.quick->compunit_symtab;
2849 }
2850
2851 /* Return the CU/TU given its index.
2852
2853    This is intended for loops like:
2854
2855    for (i = 0; i < (dwarf2_per_objfile->n_comp_units
2856                     + dwarf2_per_objfile->n_type_units); ++i)
2857      {
2858        struct dwarf2_per_cu_data *per_cu = dw2_get_cutu (i);
2859
2860        ...;
2861      }
2862 */
2863
2864 static struct dwarf2_per_cu_data *
2865 dw2_get_cutu (int index)
2866 {
2867   if (index >= dwarf2_per_objfile->n_comp_units)
2868     {
2869       index -= dwarf2_per_objfile->n_comp_units;
2870       gdb_assert (index < dwarf2_per_objfile->n_type_units);
2871       return &dwarf2_per_objfile->all_type_units[index]->per_cu;
2872     }
2873
2874   return dwarf2_per_objfile->all_comp_units[index];
2875 }
2876
2877 /* Return the CU given its index.
2878    This differs from dw2_get_cutu in that it's for when you know INDEX
2879    refers to a CU.  */
2880
2881 static struct dwarf2_per_cu_data *
2882 dw2_get_cu (int index)
2883 {
2884   gdb_assert (index >= 0 && index < dwarf2_per_objfile->n_comp_units);
2885
2886   return dwarf2_per_objfile->all_comp_units[index];
2887 }
2888
2889 /* A helper for create_cus_from_index that handles a given list of
2890    CUs.  */
2891
2892 static void
2893 create_cus_from_index_list (struct objfile *objfile,
2894                             const gdb_byte *cu_list, offset_type n_elements,
2895                             struct dwarf2_section_info *section,
2896                             int is_dwz,
2897                             int base_offset)
2898 {
2899   offset_type i;
2900
2901   for (i = 0; i < n_elements; i += 2)
2902     {
2903       struct dwarf2_per_cu_data *the_cu;
2904       ULONGEST offset, length;
2905
2906       gdb_static_assert (sizeof (ULONGEST) >= 8);
2907       offset = extract_unsigned_integer (cu_list, 8, BFD_ENDIAN_LITTLE);
2908       length = extract_unsigned_integer (cu_list + 8, 8, BFD_ENDIAN_LITTLE);
2909       cu_list += 2 * 8;
2910
2911       the_cu = OBSTACK_ZALLOC (&objfile->objfile_obstack,
2912                                struct dwarf2_per_cu_data);
2913       the_cu->offset.sect_off = offset;
2914       the_cu->length = length;
2915       the_cu->objfile = objfile;
2916       the_cu->section = section;
2917       the_cu->v.quick = OBSTACK_ZALLOC (&objfile->objfile_obstack,
2918                                         struct dwarf2_per_cu_quick_data);
2919       the_cu->is_dwz = is_dwz;
2920       dwarf2_per_objfile->all_comp_units[base_offset + i / 2] = the_cu;
2921     }
2922 }
2923
2924 /* Read the CU list from the mapped index, and use it to create all
2925    the CU objects for this objfile.  */
2926
2927 static void
2928 create_cus_from_index (struct objfile *objfile,
2929                        const gdb_byte *cu_list, offset_type cu_list_elements,
2930                        const gdb_byte *dwz_list, offset_type dwz_elements)
2931 {
2932   struct dwz_file *dwz;
2933
2934   dwarf2_per_objfile->n_comp_units = (cu_list_elements + dwz_elements) / 2;
2935   dwarf2_per_objfile->all_comp_units =
2936     XOBNEWVEC (&objfile->objfile_obstack, struct dwarf2_per_cu_data *,
2937                dwarf2_per_objfile->n_comp_units);
2938
2939   create_cus_from_index_list (objfile, cu_list, cu_list_elements,
2940                               &dwarf2_per_objfile->info, 0, 0);
2941
2942   if (dwz_elements == 0)
2943     return;
2944
2945   dwz = dwarf2_get_dwz_file ();
2946   create_cus_from_index_list (objfile, dwz_list, dwz_elements, &dwz->info, 1,
2947                               cu_list_elements / 2);
2948 }
2949
2950 /* Create the signatured type hash table from the index.  */
2951
2952 static void
2953 create_signatured_type_table_from_index (struct objfile *objfile,
2954                                          struct dwarf2_section_info *section,
2955                                          const gdb_byte *bytes,
2956                                          offset_type elements)
2957 {
2958   offset_type i;
2959   htab_t sig_types_hash;
2960
2961   dwarf2_per_objfile->n_type_units
2962     = dwarf2_per_objfile->n_allocated_type_units
2963     = elements / 3;
2964   dwarf2_per_objfile->all_type_units =
2965     XNEWVEC (struct signatured_type *, dwarf2_per_objfile->n_type_units);
2966
2967   sig_types_hash = allocate_signatured_type_table (objfile);
2968
2969   for (i = 0; i < elements; i += 3)
2970     {
2971       struct signatured_type *sig_type;
2972       ULONGEST offset, type_offset_in_tu, signature;
2973       void **slot;
2974
2975       gdb_static_assert (sizeof (ULONGEST) >= 8);
2976       offset = extract_unsigned_integer (bytes, 8, BFD_ENDIAN_LITTLE);
2977       type_offset_in_tu = extract_unsigned_integer (bytes + 8, 8,
2978                                                     BFD_ENDIAN_LITTLE);
2979       signature = extract_unsigned_integer (bytes + 16, 8, BFD_ENDIAN_LITTLE);
2980       bytes += 3 * 8;
2981
2982       sig_type = OBSTACK_ZALLOC (&objfile->objfile_obstack,
2983                                  struct signatured_type);
2984       sig_type->signature = signature;
2985       sig_type->type_offset_in_tu.cu_off = type_offset_in_tu;
2986       sig_type->per_cu.is_debug_types = 1;
2987       sig_type->per_cu.section = section;
2988       sig_type->per_cu.offset.sect_off = offset;
2989       sig_type->per_cu.objfile = objfile;
2990       sig_type->per_cu.v.quick
2991         = OBSTACK_ZALLOC (&objfile->objfile_obstack,
2992                           struct dwarf2_per_cu_quick_data);
2993
2994       slot = htab_find_slot (sig_types_hash, sig_type, INSERT);
2995       *slot = sig_type;
2996
2997       dwarf2_per_objfile->all_type_units[i / 3] = sig_type;
2998     }
2999
3000   dwarf2_per_objfile->signatured_types = sig_types_hash;
3001 }
3002
3003 /* Read the address map data from the mapped index, and use it to
3004    populate the objfile's psymtabs_addrmap.  */
3005
3006 static void
3007 create_addrmap_from_index (struct objfile *objfile, struct mapped_index *index)
3008 {
3009   struct gdbarch *gdbarch = get_objfile_arch (objfile);
3010   const gdb_byte *iter, *end;
3011   struct obstack temp_obstack;
3012   struct addrmap *mutable_map;
3013   struct cleanup *cleanup;
3014   CORE_ADDR baseaddr;
3015
3016   obstack_init (&temp_obstack);
3017   cleanup = make_cleanup_obstack_free (&temp_obstack);
3018   mutable_map = addrmap_create_mutable (&temp_obstack);
3019
3020   iter = index->address_table;
3021   end = iter + index->address_table_size;
3022
3023   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
3024
3025   while (iter < end)
3026     {
3027       ULONGEST hi, lo, cu_index;
3028       lo = extract_unsigned_integer (iter, 8, BFD_ENDIAN_LITTLE);
3029       iter += 8;
3030       hi = extract_unsigned_integer (iter, 8, BFD_ENDIAN_LITTLE);
3031       iter += 8;
3032       cu_index = extract_unsigned_integer (iter, 4, BFD_ENDIAN_LITTLE);
3033       iter += 4;
3034
3035       if (lo > hi)
3036         {
3037           complaint (&symfile_complaints,
3038                      _(".gdb_index address table has invalid range (%s - %s)"),
3039                      hex_string (lo), hex_string (hi));
3040           continue;
3041         }
3042
3043       if (cu_index >= dwarf2_per_objfile->n_comp_units)
3044         {
3045           complaint (&symfile_complaints,
3046                      _(".gdb_index address table has invalid CU number %u"),
3047                      (unsigned) cu_index);
3048           continue;
3049         }
3050
3051       lo = gdbarch_adjust_dwarf2_addr (gdbarch, lo + baseaddr);
3052       hi = gdbarch_adjust_dwarf2_addr (gdbarch, hi + baseaddr);
3053       addrmap_set_empty (mutable_map, lo, hi - 1, dw2_get_cutu (cu_index));
3054     }
3055
3056   objfile->psymtabs_addrmap = addrmap_create_fixed (mutable_map,
3057                                                     &objfile->objfile_obstack);
3058   do_cleanups (cleanup);
3059 }
3060
3061 /* The hash function for strings in the mapped index.  This is the same as
3062    SYMBOL_HASH_NEXT, but we keep a separate copy to maintain control over the
3063    implementation.  This is necessary because the hash function is tied to the
3064    format of the mapped index file.  The hash values do not have to match with
3065    SYMBOL_HASH_NEXT.
3066    
3067    Use INT_MAX for INDEX_VERSION if you generate the current index format.  */
3068
3069 static hashval_t
3070 mapped_index_string_hash (int index_version, const void *p)
3071 {
3072   const unsigned char *str = (const unsigned char *) p;
3073   hashval_t r = 0;
3074   unsigned char c;
3075
3076   while ((c = *str++) != 0)
3077     {
3078       if (index_version >= 5)
3079         c = tolower (c);
3080       r = r * 67 + c - 113;
3081     }
3082
3083   return r;
3084 }
3085
3086 /* Find a slot in the mapped index INDEX for the object named NAME.
3087    If NAME is found, set *VEC_OUT to point to the CU vector in the
3088    constant pool and return 1.  If NAME cannot be found, return 0.  */
3089
3090 static int
3091 find_slot_in_mapped_hash (struct mapped_index *index, const char *name,
3092                           offset_type **vec_out)
3093 {
3094   struct cleanup *back_to = make_cleanup (null_cleanup, 0);
3095   offset_type hash;
3096   offset_type slot, step;
3097   int (*cmp) (const char *, const char *);
3098
3099   if (current_language->la_language == language_cplus
3100       || current_language->la_language == language_fortran
3101       || current_language->la_language == language_d)
3102     {
3103       /* NAME is already canonical.  Drop any qualifiers as .gdb_index does
3104          not contain any.  */
3105
3106       if (strchr (name, '(') != NULL)
3107         {
3108           char *without_params = cp_remove_params (name);
3109
3110           if (without_params != NULL)
3111             {
3112               make_cleanup (xfree, without_params);
3113               name = without_params;
3114             }
3115         }
3116     }
3117
3118   /* Index version 4 did not support case insensitive searches.  But the
3119      indices for case insensitive languages are built in lowercase, therefore
3120      simulate our NAME being searched is also lowercased.  */
3121   hash = mapped_index_string_hash ((index->version == 4
3122                                     && case_sensitivity == case_sensitive_off
3123                                     ? 5 : index->version),
3124                                    name);
3125
3126   slot = hash & (index->symbol_table_slots - 1);
3127   step = ((hash * 17) & (index->symbol_table_slots - 1)) | 1;
3128   cmp = (case_sensitivity == case_sensitive_on ? strcmp : strcasecmp);
3129
3130   for (;;)
3131     {
3132       /* Convert a slot number to an offset into the table.  */
3133       offset_type i = 2 * slot;
3134       const char *str;
3135       if (index->symbol_table[i] == 0 && index->symbol_table[i + 1] == 0)
3136         {
3137           do_cleanups (back_to);
3138           return 0;
3139         }
3140
3141       str = index->constant_pool + MAYBE_SWAP (index->symbol_table[i]);
3142       if (!cmp (name, str))
3143         {
3144           *vec_out = (offset_type *) (index->constant_pool
3145                                       + MAYBE_SWAP (index->symbol_table[i + 1]));
3146           do_cleanups (back_to);
3147           return 1;
3148         }
3149
3150       slot = (slot + step) & (index->symbol_table_slots - 1);
3151     }
3152 }
3153
3154 /* A helper function that reads the .gdb_index from SECTION and fills
3155    in MAP.  FILENAME is the name of the file containing the section;
3156    it is used for error reporting.  DEPRECATED_OK is nonzero if it is
3157    ok to use deprecated sections.
3158
3159    CU_LIST, CU_LIST_ELEMENTS, TYPES_LIST, and TYPES_LIST_ELEMENTS are
3160    out parameters that are filled in with information about the CU and
3161    TU lists in the section.
3162
3163    Returns 1 if all went well, 0 otherwise.  */
3164
3165 static int
3166 read_index_from_section (struct objfile *objfile,
3167                          const char *filename,
3168                          int deprecated_ok,
3169                          struct dwarf2_section_info *section,
3170                          struct mapped_index *map,
3171                          const gdb_byte **cu_list,
3172                          offset_type *cu_list_elements,
3173                          const gdb_byte **types_list,
3174                          offset_type *types_list_elements)
3175 {
3176   const gdb_byte *addr;
3177   offset_type version;
3178   offset_type *metadata;
3179   int i;
3180
3181   if (dwarf2_section_empty_p (section))
3182     return 0;
3183
3184   /* Older elfutils strip versions could keep the section in the main
3185      executable while splitting it for the separate debug info file.  */
3186   if ((get_section_flags (section) & SEC_HAS_CONTENTS) == 0)
3187     return 0;
3188
3189   dwarf2_read_section (objfile, section);
3190
3191   addr = section->buffer;
3192   /* Version check.  */
3193   version = MAYBE_SWAP (*(offset_type *) addr);
3194   /* Versions earlier than 3 emitted every copy of a psymbol.  This
3195      causes the index to behave very poorly for certain requests.  Version 3
3196      contained incomplete addrmap.  So, it seems better to just ignore such
3197      indices.  */
3198   if (version < 4)
3199     {
3200       static int warning_printed = 0;
3201       if (!warning_printed)
3202         {
3203           warning (_("Skipping obsolete .gdb_index section in %s."),
3204                    filename);
3205           warning_printed = 1;
3206         }
3207       return 0;
3208     }
3209   /* Index version 4 uses a different hash function than index version
3210      5 and later.
3211
3212      Versions earlier than 6 did not emit psymbols for inlined
3213      functions.  Using these files will cause GDB not to be able to
3214      set breakpoints on inlined functions by name, so we ignore these
3215      indices unless the user has done
3216      "set use-deprecated-index-sections on".  */
3217   if (version < 6 && !deprecated_ok)
3218     {
3219       static int warning_printed = 0;
3220       if (!warning_printed)
3221         {
3222           warning (_("\
3223 Skipping deprecated .gdb_index section in %s.\n\
3224 Do \"set use-deprecated-index-sections on\" before the file is read\n\
3225 to use the section anyway."),
3226                    filename);
3227           warning_printed = 1;
3228         }
3229       return 0;
3230     }
3231   /* Version 7 indices generated by gold refer to the CU for a symbol instead
3232      of the TU (for symbols coming from TUs),
3233      http://sourceware.org/bugzilla/show_bug.cgi?id=15021.
3234      Plus gold-generated indices can have duplicate entries for global symbols,
3235      http://sourceware.org/bugzilla/show_bug.cgi?id=15646.
3236      These are just performance bugs, and we can't distinguish gdb-generated
3237      indices from gold-generated ones, so issue no warning here.  */
3238
3239   /* Indexes with higher version than the one supported by GDB may be no
3240      longer backward compatible.  */
3241   if (version > 8)
3242     return 0;
3243
3244   map->version = version;
3245   map->total_size = section->size;
3246
3247   metadata = (offset_type *) (addr + sizeof (offset_type));
3248
3249   i = 0;
3250   *cu_list = addr + MAYBE_SWAP (metadata[i]);
3251   *cu_list_elements = ((MAYBE_SWAP (metadata[i + 1]) - MAYBE_SWAP (metadata[i]))
3252                        / 8);
3253   ++i;
3254
3255   *types_list = addr + MAYBE_SWAP (metadata[i]);
3256   *types_list_elements = ((MAYBE_SWAP (metadata[i + 1])
3257                            - MAYBE_SWAP (metadata[i]))
3258                           / 8);
3259   ++i;
3260
3261   map->address_table = addr + MAYBE_SWAP (metadata[i]);
3262   map->address_table_size = (MAYBE_SWAP (metadata[i + 1])
3263                              - MAYBE_SWAP (metadata[i]));
3264   ++i;
3265
3266   map->symbol_table = (offset_type *) (addr + MAYBE_SWAP (metadata[i]));
3267   map->symbol_table_slots = ((MAYBE_SWAP (metadata[i + 1])
3268                               - MAYBE_SWAP (metadata[i]))
3269                              / (2 * sizeof (offset_type)));
3270   ++i;
3271
3272   map->constant_pool = (char *) (addr + MAYBE_SWAP (metadata[i]));
3273
3274   return 1;
3275 }
3276
3277
3278 /* Read the index file.  If everything went ok, initialize the "quick"
3279    elements of all the CUs and return 1.  Otherwise, return 0.  */
3280
3281 static int
3282 dwarf2_read_index (struct objfile *objfile)
3283 {
3284   struct mapped_index local_map, *map;
3285   const gdb_byte *cu_list, *types_list, *dwz_list = NULL;
3286   offset_type cu_list_elements, types_list_elements, dwz_list_elements = 0;
3287   struct dwz_file *dwz;
3288
3289   if (!read_index_from_section (objfile, objfile_name (objfile),
3290                                 use_deprecated_index_sections,
3291                                 &dwarf2_per_objfile->gdb_index, &local_map,
3292                                 &cu_list, &cu_list_elements,
3293                                 &types_list, &types_list_elements))
3294     return 0;
3295
3296   /* Don't use the index if it's empty.  */
3297   if (local_map.symbol_table_slots == 0)
3298     return 0;
3299
3300   /* If there is a .dwz file, read it so we can get its CU list as
3301      well.  */
3302   dwz = dwarf2_get_dwz_file ();
3303   if (dwz != NULL)
3304     {
3305       struct mapped_index dwz_map;
3306       const gdb_byte *dwz_types_ignore;
3307       offset_type dwz_types_elements_ignore;
3308
3309       if (!read_index_from_section (objfile, bfd_get_filename (dwz->dwz_bfd),
3310                                     1,
3311                                     &dwz->gdb_index, &dwz_map,
3312                                     &dwz_list, &dwz_list_elements,
3313                                     &dwz_types_ignore,
3314                                     &dwz_types_elements_ignore))
3315         {
3316           warning (_("could not read '.gdb_index' section from %s; skipping"),
3317                    bfd_get_filename (dwz->dwz_bfd));
3318           return 0;
3319         }
3320     }
3321
3322   create_cus_from_index (objfile, cu_list, cu_list_elements, dwz_list,
3323                          dwz_list_elements);
3324
3325   if (types_list_elements)
3326     {
3327       struct dwarf2_section_info *section;
3328
3329       /* We can only handle a single .debug_types when we have an
3330          index.  */
3331       if (VEC_length (dwarf2_section_info_def, dwarf2_per_objfile->types) != 1)
3332         return 0;
3333
3334       section = VEC_index (dwarf2_section_info_def,
3335                            dwarf2_per_objfile->types, 0);
3336
3337       create_signatured_type_table_from_index (objfile, section, types_list,
3338                                                types_list_elements);
3339     }
3340
3341   create_addrmap_from_index (objfile, &local_map);
3342
3343   map = XOBNEW (&objfile->objfile_obstack, struct mapped_index);
3344   *map = local_map;
3345
3346   dwarf2_per_objfile->index_table = map;
3347   dwarf2_per_objfile->using_index = 1;
3348   dwarf2_per_objfile->quick_file_names_table =
3349     create_quick_file_names_table (dwarf2_per_objfile->n_comp_units);
3350
3351   return 1;
3352 }
3353
3354 /* A helper for the "quick" functions which sets the global
3355    dwarf2_per_objfile according to OBJFILE.  */
3356
3357 static void
3358 dw2_setup (struct objfile *objfile)
3359 {
3360   dwarf2_per_objfile = ((struct dwarf2_per_objfile *)
3361                         objfile_data (objfile, dwarf2_objfile_data_key));
3362   gdb_assert (dwarf2_per_objfile);
3363 }
3364
3365 /* die_reader_func for dw2_get_file_names.  */
3366
3367 static void
3368 dw2_get_file_names_reader (const struct die_reader_specs *reader,
3369                            const gdb_byte *info_ptr,
3370                            struct die_info *comp_unit_die,
3371                            int has_children,
3372                            void *data)
3373 {
3374   struct dwarf2_cu *cu = reader->cu;
3375   struct dwarf2_per_cu_data *this_cu = cu->per_cu;  
3376   struct objfile *objfile = dwarf2_per_objfile->objfile;
3377   struct dwarf2_per_cu_data *lh_cu;
3378   struct line_header *lh;
3379   struct attribute *attr;
3380   int i;
3381   void **slot;
3382   struct quick_file_names *qfn;
3383   unsigned int line_offset;
3384
3385   gdb_assert (! this_cu->is_debug_types);
3386
3387   /* Our callers never want to match partial units -- instead they
3388      will match the enclosing full CU.  */
3389   if (comp_unit_die->tag == DW_TAG_partial_unit)
3390     {
3391       this_cu->v.quick->no_file_data = 1;
3392       return;
3393     }
3394
3395   lh_cu = this_cu;
3396   lh = NULL;
3397   slot = NULL;
3398   line_offset = 0;
3399
3400   attr = dwarf2_attr (comp_unit_die, DW_AT_stmt_list, cu);
3401   if (attr)
3402     {
3403       struct quick_file_names find_entry;
3404
3405       line_offset = DW_UNSND (attr);
3406
3407       /* We may have already read in this line header (TU line header sharing).
3408          If we have we're done.  */
3409       find_entry.hash.dwo_unit = cu->dwo_unit;
3410       find_entry.hash.line_offset.sect_off = line_offset;
3411       slot = htab_find_slot (dwarf2_per_objfile->quick_file_names_table,
3412                              &find_entry, INSERT);
3413       if (*slot != NULL)
3414         {
3415           lh_cu->v.quick->file_names = (struct quick_file_names *) *slot;
3416           return;
3417         }
3418
3419       lh = dwarf_decode_line_header (line_offset, cu);
3420     }
3421   if (lh == NULL)
3422     {
3423       lh_cu->v.quick->no_file_data = 1;
3424       return;
3425     }
3426
3427   qfn = XOBNEW (&objfile->objfile_obstack, struct quick_file_names);
3428   qfn->hash.dwo_unit = cu->dwo_unit;
3429   qfn->hash.line_offset.sect_off = line_offset;
3430   gdb_assert (slot != NULL);
3431   *slot = qfn;
3432
3433   file_and_directory fnd = find_file_and_directory (comp_unit_die, cu);
3434
3435   qfn->num_file_names = lh->num_file_names;
3436   qfn->file_names =
3437     XOBNEWVEC (&objfile->objfile_obstack, const char *, lh->num_file_names);
3438   for (i = 0; i < lh->num_file_names; ++i)
3439     qfn->file_names[i] = file_full_name (i + 1, lh, fnd.comp_dir);
3440   qfn->real_names = NULL;
3441
3442   free_line_header (lh);
3443
3444   lh_cu->v.quick->file_names = qfn;
3445 }
3446
3447 /* A helper for the "quick" functions which attempts to read the line
3448    table for THIS_CU.  */
3449
3450 static struct quick_file_names *
3451 dw2_get_file_names (struct dwarf2_per_cu_data *this_cu)
3452 {
3453   /* This should never be called for TUs.  */
3454   gdb_assert (! this_cu->is_debug_types);
3455   /* Nor type unit groups.  */
3456   gdb_assert (! IS_TYPE_UNIT_GROUP (this_cu));
3457
3458   if (this_cu->v.quick->file_names != NULL)
3459     return this_cu->v.quick->file_names;
3460   /* If we know there is no line data, no point in looking again.  */
3461   if (this_cu->v.quick->no_file_data)
3462     return NULL;
3463
3464   init_cutu_and_read_dies_simple (this_cu, dw2_get_file_names_reader, NULL);
3465
3466   if (this_cu->v.quick->no_file_data)
3467     return NULL;
3468   return this_cu->v.quick->file_names;
3469 }
3470
3471 /* A helper for the "quick" functions which computes and caches the
3472    real path for a given file name from the line table.  */
3473
3474 static const char *
3475 dw2_get_real_path (struct objfile *objfile,
3476                    struct quick_file_names *qfn, int index)
3477 {
3478   if (qfn->real_names == NULL)
3479     qfn->real_names = OBSTACK_CALLOC (&objfile->objfile_obstack,
3480                                       qfn->num_file_names, const char *);
3481
3482   if (qfn->real_names[index] == NULL)
3483     qfn->real_names[index] = gdb_realpath (qfn->file_names[index]);
3484
3485   return qfn->real_names[index];
3486 }
3487
3488 static struct symtab *
3489 dw2_find_last_source_symtab (struct objfile *objfile)
3490 {
3491   struct compunit_symtab *cust;
3492   int index;
3493
3494   dw2_setup (objfile);
3495   index = dwarf2_per_objfile->n_comp_units - 1;
3496   cust = dw2_instantiate_symtab (dw2_get_cutu (index));
3497   if (cust == NULL)
3498     return NULL;
3499   return compunit_primary_filetab (cust);
3500 }
3501
3502 /* Traversal function for dw2_forget_cached_source_info.  */
3503
3504 static int
3505 dw2_free_cached_file_names (void **slot, void *info)
3506 {
3507   struct quick_file_names *file_data = (struct quick_file_names *) *slot;
3508
3509   if (file_data->real_names)
3510     {
3511       int i;
3512
3513       for (i = 0; i < file_data->num_file_names; ++i)
3514         {
3515           xfree ((void*) file_data->real_names[i]);
3516           file_data->real_names[i] = NULL;
3517         }
3518     }
3519
3520   return 1;
3521 }
3522
3523 static void
3524 dw2_forget_cached_source_info (struct objfile *objfile)
3525 {
3526   dw2_setup (objfile);
3527
3528   htab_traverse_noresize (dwarf2_per_objfile->quick_file_names_table,
3529                           dw2_free_cached_file_names, NULL);
3530 }
3531
3532 /* Helper function for dw2_map_symtabs_matching_filename that expands
3533    the symtabs and calls the iterator.  */
3534
3535 static int
3536 dw2_map_expand_apply (struct objfile *objfile,
3537                       struct dwarf2_per_cu_data *per_cu,
3538                       const char *name, const char *real_path,
3539                       gdb::function_view<bool (symtab *)> callback)
3540 {
3541   struct compunit_symtab *last_made = objfile->compunit_symtabs;
3542
3543   /* Don't visit already-expanded CUs.  */
3544   if (per_cu->v.quick->compunit_symtab)
3545     return 0;
3546
3547   /* This may expand more than one symtab, and we want to iterate over
3548      all of them.  */
3549   dw2_instantiate_symtab (per_cu);
3550
3551   return iterate_over_some_symtabs (name, real_path, objfile->compunit_symtabs,
3552                                     last_made, callback);
3553 }
3554
3555 /* Implementation of the map_symtabs_matching_filename method.  */
3556
3557 static bool
3558 dw2_map_symtabs_matching_filename
3559   (struct objfile *objfile, const char *name, const char *real_path,
3560    gdb::function_view<bool (symtab *)> callback)
3561 {
3562   int i;
3563   const char *name_basename = lbasename (name);
3564
3565   dw2_setup (objfile);
3566
3567   /* The rule is CUs specify all the files, including those used by
3568      any TU, so there's no need to scan TUs here.  */
3569
3570   for (i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
3571     {
3572       int j;
3573       struct dwarf2_per_cu_data *per_cu = dw2_get_cu (i);
3574       struct quick_file_names *file_data;
3575
3576       /* We only need to look at symtabs not already expanded.  */
3577       if (per_cu->v.quick->compunit_symtab)
3578         continue;
3579
3580       file_data = dw2_get_file_names (per_cu);
3581       if (file_data == NULL)
3582         continue;
3583
3584       for (j = 0; j < file_data->num_file_names; ++j)
3585         {
3586           const char *this_name = file_data->file_names[j];
3587           const char *this_real_name;
3588
3589           if (compare_filenames_for_search (this_name, name))
3590             {
3591               if (dw2_map_expand_apply (objfile, per_cu, name, real_path,
3592                                         callback))
3593                 return true;
3594               continue;
3595             }
3596
3597           /* Before we invoke realpath, which can get expensive when many
3598              files are involved, do a quick comparison of the basenames.  */
3599           if (! basenames_may_differ
3600               && FILENAME_CMP (lbasename (this_name), name_basename) != 0)
3601             continue;
3602
3603           this_real_name = dw2_get_real_path (objfile, file_data, j);
3604           if (compare_filenames_for_search (this_real_name, name))
3605             {
3606               if (dw2_map_expand_apply (objfile, per_cu, name, real_path,
3607                                         callback))
3608                 return true;
3609               continue;
3610             }
3611
3612           if (real_path != NULL)
3613             {
3614               gdb_assert (IS_ABSOLUTE_PATH (real_path));
3615               gdb_assert (IS_ABSOLUTE_PATH (name));
3616               if (this_real_name != NULL
3617                   && FILENAME_CMP (real_path, this_real_name) == 0)
3618                 {
3619                   if (dw2_map_expand_apply (objfile, per_cu, name, real_path,
3620                                             callback))
3621                     return true;
3622                   continue;
3623                 }
3624             }
3625         }
3626     }
3627
3628   return false;
3629 }
3630
3631 /* Struct used to manage iterating over all CUs looking for a symbol.  */
3632
3633 struct dw2_symtab_iterator
3634 {
3635   /* The internalized form of .gdb_index.  */
3636   struct mapped_index *index;
3637   /* If non-zero, only look for symbols that match BLOCK_INDEX.  */
3638   int want_specific_block;
3639   /* One of GLOBAL_BLOCK or STATIC_BLOCK.
3640      Unused if !WANT_SPECIFIC_BLOCK.  */
3641   int block_index;
3642   /* The kind of symbol we're looking for.  */
3643   domain_enum domain;
3644   /* The list of CUs from the index entry of the symbol,
3645      or NULL if not found.  */
3646   offset_type *vec;
3647   /* The next element in VEC to look at.  */
3648   int next;
3649   /* The number of elements in VEC, or zero if there is no match.  */
3650   int length;
3651   /* Have we seen a global version of the symbol?
3652      If so we can ignore all further global instances.
3653      This is to work around gold/15646, inefficient gold-generated
3654      indices.  */
3655   int global_seen;
3656 };
3657
3658 /* Initialize the index symtab iterator ITER.
3659    If WANT_SPECIFIC_BLOCK is non-zero, only look for symbols
3660    in block BLOCK_INDEX.  Otherwise BLOCK_INDEX is ignored.  */
3661
3662 static void
3663 dw2_symtab_iter_init (struct dw2_symtab_iterator *iter,
3664                       struct mapped_index *index,
3665                       int want_specific_block,
3666                       int block_index,
3667                       domain_enum domain,
3668                       const char *name)
3669 {
3670   iter->index = index;
3671   iter->want_specific_block = want_specific_block;
3672   iter->block_index = block_index;
3673   iter->domain = domain;
3674   iter->next = 0;
3675   iter->global_seen = 0;
3676
3677   if (find_slot_in_mapped_hash (index, name, &iter->vec))
3678     iter->length = MAYBE_SWAP (*iter->vec);
3679   else
3680     {
3681       iter->vec = NULL;
3682       iter->length = 0;
3683     }
3684 }
3685
3686 /* Return the next matching CU or NULL if there are no more.  */
3687
3688 static struct dwarf2_per_cu_data *
3689 dw2_symtab_iter_next (struct dw2_symtab_iterator *iter)
3690 {
3691   for ( ; iter->next < iter->length; ++iter->next)
3692     {
3693       offset_type cu_index_and_attrs =
3694         MAYBE_SWAP (iter->vec[iter->next + 1]);
3695       offset_type cu_index = GDB_INDEX_CU_VALUE (cu_index_and_attrs);
3696       struct dwarf2_per_cu_data *per_cu;
3697       int want_static = iter->block_index != GLOBAL_BLOCK;
3698       /* This value is only valid for index versions >= 7.  */
3699       int is_static = GDB_INDEX_SYMBOL_STATIC_VALUE (cu_index_and_attrs);
3700       gdb_index_symbol_kind symbol_kind =
3701         GDB_INDEX_SYMBOL_KIND_VALUE (cu_index_and_attrs);
3702       /* Only check the symbol attributes if they're present.
3703          Indices prior to version 7 don't record them,
3704          and indices >= 7 may elide them for certain symbols
3705          (gold does this).  */
3706       int attrs_valid =
3707         (iter->index->version >= 7
3708          && symbol_kind != GDB_INDEX_SYMBOL_KIND_NONE);
3709
3710       /* Don't crash on bad data.  */
3711       if (cu_index >= (dwarf2_per_objfile->n_comp_units
3712                        + dwarf2_per_objfile->n_type_units))
3713         {
3714           complaint (&symfile_complaints,
3715                      _(".gdb_index entry has bad CU index"
3716                        " [in module %s]"),
3717                      objfile_name (dwarf2_per_objfile->objfile));
3718           continue;
3719         }
3720
3721       per_cu = dw2_get_cutu (cu_index);
3722
3723       /* Skip if already read in.  */
3724       if (per_cu->v.quick->compunit_symtab)
3725         continue;
3726
3727       /* Check static vs global.  */
3728       if (attrs_valid)
3729         {
3730           if (iter->want_specific_block
3731               && want_static != is_static)
3732             continue;
3733           /* Work around gold/15646.  */
3734           if (!is_static && iter->global_seen)
3735             continue;
3736           if (!is_static)
3737             iter->global_seen = 1;
3738         }
3739
3740       /* Only check the symbol's kind if it has one.  */
3741       if (attrs_valid)
3742         {
3743           switch (iter->domain)
3744             {
3745             case VAR_DOMAIN:
3746               if (symbol_kind != GDB_INDEX_SYMBOL_KIND_VARIABLE
3747                   && symbol_kind != GDB_INDEX_SYMBOL_KIND_FUNCTION
3748                   /* Some types are also in VAR_DOMAIN.  */
3749                   && symbol_kind != GDB_INDEX_SYMBOL_KIND_TYPE)
3750                 continue;
3751               break;
3752             case STRUCT_DOMAIN:
3753               if (symbol_kind != GDB_INDEX_SYMBOL_KIND_TYPE)
3754                 continue;
3755               break;
3756             case LABEL_DOMAIN:
3757               if (symbol_kind != GDB_INDEX_SYMBOL_KIND_OTHER)
3758                 continue;
3759               break;
3760             default:
3761               break;
3762             }
3763         }
3764
3765       ++iter->next;
3766       return per_cu;
3767     }
3768
3769   return NULL;
3770 }
3771
3772 static struct compunit_symtab *
3773 dw2_lookup_symbol (struct objfile *objfile, int block_index,
3774                    const char *name, domain_enum domain)
3775 {
3776   struct compunit_symtab *stab_best = NULL;
3777   struct mapped_index *index;
3778
3779   dw2_setup (objfile);
3780
3781   index = dwarf2_per_objfile->index_table;
3782
3783   /* index is NULL if OBJF_READNOW.  */
3784   if (index)
3785     {
3786       struct dw2_symtab_iterator iter;
3787       struct dwarf2_per_cu_data *per_cu;
3788
3789       dw2_symtab_iter_init (&iter, index, 1, block_index, domain, name);
3790
3791       while ((per_cu = dw2_symtab_iter_next (&iter)) != NULL)
3792         {
3793           struct symbol *sym, *with_opaque = NULL;
3794           struct compunit_symtab *stab = dw2_instantiate_symtab (per_cu);
3795           const struct blockvector *bv = COMPUNIT_BLOCKVECTOR (stab);
3796           struct block *block = BLOCKVECTOR_BLOCK (bv, block_index);
3797
3798           sym = block_find_symbol (block, name, domain,
3799                                    block_find_non_opaque_type_preferred,
3800                                    &with_opaque);
3801
3802           /* Some caution must be observed with overloaded functions
3803              and methods, since the index will not contain any overload
3804              information (but NAME might contain it).  */
3805
3806           if (sym != NULL
3807               && strcmp_iw (SYMBOL_SEARCH_NAME (sym), name) == 0)
3808             return stab;
3809           if (with_opaque != NULL
3810               && strcmp_iw (SYMBOL_SEARCH_NAME (with_opaque), name) == 0)
3811             stab_best = stab;
3812
3813           /* Keep looking through other CUs.  */
3814         }
3815     }
3816
3817   return stab_best;
3818 }
3819
3820 static void
3821 dw2_print_stats (struct objfile *objfile)
3822 {
3823   int i, total, count;
3824
3825   dw2_setup (objfile);
3826   total = dwarf2_per_objfile->n_comp_units + dwarf2_per_objfile->n_type_units;
3827   count = 0;
3828   for (i = 0; i < total; ++i)
3829     {
3830       struct dwarf2_per_cu_data *per_cu = dw2_get_cutu (i);
3831
3832       if (!per_cu->v.quick->compunit_symtab)
3833         ++count;
3834     }
3835   printf_filtered (_("  Number of read CUs: %d\n"), total - count);
3836   printf_filtered (_("  Number of unread CUs: %d\n"), count);
3837 }
3838
3839 /* This dumps minimal information about the index.
3840    It is called via "mt print objfiles".
3841    One use is to verify .gdb_index has been loaded by the
3842    gdb.dwarf2/gdb-index.exp testcase.  */
3843
3844 static void
3845 dw2_dump (struct objfile *objfile)
3846 {
3847   dw2_setup (objfile);
3848   gdb_assert (dwarf2_per_objfile->using_index);
3849   printf_filtered (".gdb_index:");
3850   if (dwarf2_per_objfile->index_table != NULL)
3851     {
3852       printf_filtered (" version %d\n",
3853                        dwarf2_per_objfile->index_table->version);
3854     }
3855   else
3856     printf_filtered (" faked for \"readnow\"\n");
3857   printf_filtered ("\n");
3858 }
3859
3860 static void
3861 dw2_relocate (struct objfile *objfile,
3862               const struct section_offsets *new_offsets,
3863               const struct section_offsets *delta)
3864 {
3865   /* There's nothing to relocate here.  */
3866 }
3867
3868 static void
3869 dw2_expand_symtabs_for_function (struct objfile *objfile,
3870                                  const char *func_name)
3871 {
3872   struct mapped_index *index;
3873
3874   dw2_setup (objfile);
3875
3876   index = dwarf2_per_objfile->index_table;
3877
3878   /* index is NULL if OBJF_READNOW.  */
3879   if (index)
3880     {
3881       struct dw2_symtab_iterator iter;
3882       struct dwarf2_per_cu_data *per_cu;
3883
3884       /* Note: It doesn't matter what we pass for block_index here.  */
3885       dw2_symtab_iter_init (&iter, index, 0, GLOBAL_BLOCK, VAR_DOMAIN,
3886                             func_name);
3887
3888       while ((per_cu = dw2_symtab_iter_next (&iter)) != NULL)
3889         dw2_instantiate_symtab (per_cu);
3890     }
3891 }
3892
3893 static void
3894 dw2_expand_all_symtabs (struct objfile *objfile)
3895 {
3896   int i;
3897
3898   dw2_setup (objfile);
3899
3900   for (i = 0; i < (dwarf2_per_objfile->n_comp_units
3901                    + dwarf2_per_objfile->n_type_units); ++i)
3902     {
3903       struct dwarf2_per_cu_data *per_cu = dw2_get_cutu (i);
3904
3905       dw2_instantiate_symtab (per_cu);
3906     }
3907 }
3908
3909 static void
3910 dw2_expand_symtabs_with_fullname (struct objfile *objfile,
3911                                   const char *fullname)
3912 {
3913   int i;
3914
3915   dw2_setup (objfile);
3916
3917   /* We don't need to consider type units here.
3918      This is only called for examining code, e.g. expand_line_sal.
3919      There can be an order of magnitude (or more) more type units
3920      than comp units, and we avoid them if we can.  */
3921
3922   for (i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
3923     {
3924       int j;
3925       struct dwarf2_per_cu_data *per_cu = dw2_get_cutu (i);
3926       struct quick_file_names *file_data;
3927
3928       /* We only need to look at symtabs not already expanded.  */
3929       if (per_cu->v.quick->compunit_symtab)
3930         continue;
3931
3932       file_data = dw2_get_file_names (per_cu);
3933       if (file_data == NULL)
3934         continue;
3935
3936       for (j = 0; j < file_data->num_file_names; ++j)
3937         {
3938           const char *this_fullname = file_data->file_names[j];
3939
3940           if (filename_cmp (this_fullname, fullname) == 0)
3941             {
3942               dw2_instantiate_symtab (per_cu);
3943               break;
3944             }
3945         }
3946     }
3947 }
3948
3949 static void
3950 dw2_map_matching_symbols (struct objfile *objfile,
3951                           const char * name, domain_enum domain,
3952                           int global,
3953                           int (*callback) (struct block *,
3954                                            struct symbol *, void *),
3955                           void *data, symbol_compare_ftype *match,
3956                           symbol_compare_ftype *ordered_compare)
3957 {
3958   /* Currently unimplemented; used for Ada.  The function can be called if the
3959      current language is Ada for a non-Ada objfile using GNU index.  As Ada
3960      does not look for non-Ada symbols this function should just return.  */
3961 }
3962
3963 static void
3964 dw2_expand_symtabs_matching
3965   (struct objfile *objfile,
3966    gdb::function_view<expand_symtabs_file_matcher_ftype> file_matcher,
3967    gdb::function_view<expand_symtabs_symbol_matcher_ftype> symbol_matcher,
3968    gdb::function_view<expand_symtabs_exp_notify_ftype> expansion_notify,
3969    enum search_domain kind)
3970 {
3971   int i;
3972   offset_type iter;
3973   struct mapped_index *index;
3974
3975   dw2_setup (objfile);
3976
3977   /* index_table is NULL if OBJF_READNOW.  */
3978   if (!dwarf2_per_objfile->index_table)
3979     return;
3980   index = dwarf2_per_objfile->index_table;
3981
3982   if (file_matcher != NULL)
3983     {
3984       htab_up visited_found (htab_create_alloc (10, htab_hash_pointer,
3985                                                 htab_eq_pointer,
3986                                                 NULL, xcalloc, xfree));
3987       htab_up visited_not_found (htab_create_alloc (10, htab_hash_pointer,
3988                                                     htab_eq_pointer,
3989                                                     NULL, xcalloc, xfree));
3990
3991       /* The rule is CUs specify all the files, including those used by
3992          any TU, so there's no need to scan TUs here.  */
3993
3994       for (i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
3995         {
3996           int j;
3997           struct dwarf2_per_cu_data *per_cu = dw2_get_cu (i);
3998           struct quick_file_names *file_data;
3999           void **slot;
4000
4001           QUIT;
4002
4003           per_cu->v.quick->mark = 0;
4004
4005           /* We only need to look at symtabs not already expanded.  */
4006           if (per_cu->v.quick->compunit_symtab)
4007             continue;
4008
4009           file_data = dw2_get_file_names (per_cu);
4010           if (file_data == NULL)
4011             continue;
4012
4013           if (htab_find (visited_not_found.get (), file_data) != NULL)
4014             continue;
4015           else if (htab_find (visited_found.get (), file_data) != NULL)
4016             {
4017               per_cu->v.quick->mark = 1;
4018               continue;
4019             }
4020
4021           for (j = 0; j < file_data->num_file_names; ++j)
4022             {
4023               const char *this_real_name;
4024
4025               if (file_matcher (file_data->file_names[j], false))
4026                 {
4027                   per_cu->v.quick->mark = 1;
4028                   break;
4029                 }
4030
4031               /* Before we invoke realpath, which can get expensive when many
4032                  files are involved, do a quick comparison of the basenames.  */
4033               if (!basenames_may_differ
4034                   && !file_matcher (lbasename (file_data->file_names[j]),
4035                                     true))
4036                 continue;
4037
4038               this_real_name = dw2_get_real_path (objfile, file_data, j);
4039               if (file_matcher (this_real_name, false))
4040                 {
4041                   per_cu->v.quick->mark = 1;
4042                   break;
4043                 }
4044             }
4045
4046           slot = htab_find_slot (per_cu->v.quick->mark
4047                                  ? visited_found.get ()
4048                                  : visited_not_found.get (),
4049                                  file_data, INSERT);
4050           *slot = file_data;
4051         }
4052     }
4053
4054   for (iter = 0; iter < index->symbol_table_slots; ++iter)
4055     {
4056       offset_type idx = 2 * iter;
4057       const char *name;
4058       offset_type *vec, vec_len, vec_idx;
4059       int global_seen = 0;
4060
4061       QUIT;
4062
4063       if (index->symbol_table[idx] == 0 && index->symbol_table[idx + 1] == 0)
4064         continue;
4065
4066       name = index->constant_pool + MAYBE_SWAP (index->symbol_table[idx]);
4067
4068       if (!symbol_matcher (name))
4069         continue;
4070
4071       /* The name was matched, now expand corresponding CUs that were
4072          marked.  */
4073       vec = (offset_type *) (index->constant_pool
4074                              + MAYBE_SWAP (index->symbol_table[idx + 1]));
4075       vec_len = MAYBE_SWAP (vec[0]);
4076       for (vec_idx = 0; vec_idx < vec_len; ++vec_idx)
4077         {
4078           struct dwarf2_per_cu_data *per_cu;
4079           offset_type cu_index_and_attrs = MAYBE_SWAP (vec[vec_idx + 1]);
4080           /* This value is only valid for index versions >= 7.  */
4081           int is_static = GDB_INDEX_SYMBOL_STATIC_VALUE (cu_index_and_attrs);
4082           gdb_index_symbol_kind symbol_kind =
4083             GDB_INDEX_SYMBOL_KIND_VALUE (cu_index_and_attrs);
4084           int cu_index = GDB_INDEX_CU_VALUE (cu_index_and_attrs);
4085           /* Only check the symbol attributes if they're present.
4086              Indices prior to version 7 don't record them,
4087              and indices >= 7 may elide them for certain symbols
4088              (gold does this).  */
4089           int attrs_valid =
4090             (index->version >= 7
4091              && symbol_kind != GDB_INDEX_SYMBOL_KIND_NONE);
4092
4093           /* Work around gold/15646.  */
4094           if (attrs_valid)
4095             {
4096               if (!is_static && global_seen)
4097                 continue;
4098               if (!is_static)
4099                 global_seen = 1;
4100             }
4101
4102           /* Only check the symbol's kind if it has one.  */
4103           if (attrs_valid)
4104             {
4105               switch (kind)
4106                 {
4107                 case VARIABLES_DOMAIN:
4108                   if (symbol_kind != GDB_INDEX_SYMBOL_KIND_VARIABLE)
4109                     continue;
4110                   break;
4111                 case FUNCTIONS_DOMAIN:
4112                   if (symbol_kind != GDB_INDEX_SYMBOL_KIND_FUNCTION)
4113                     continue;
4114                   break;
4115                 case TYPES_DOMAIN:
4116                   if (symbol_kind != GDB_INDEX_SYMBOL_KIND_TYPE)
4117                     continue;
4118                   break;
4119                 default:
4120                   break;
4121                 }
4122             }
4123
4124           /* Don't crash on bad data.  */
4125           if (cu_index >= (dwarf2_per_objfile->n_comp_units
4126                            + dwarf2_per_objfile->n_type_units))
4127             {
4128               complaint (&symfile_complaints,
4129                          _(".gdb_index entry has bad CU index"
4130                            " [in module %s]"), objfile_name (objfile));
4131               continue;
4132             }
4133
4134           per_cu = dw2_get_cutu (cu_index);
4135           if (file_matcher == NULL || per_cu->v.quick->mark)
4136             {
4137               int symtab_was_null =
4138                 (per_cu->v.quick->compunit_symtab == NULL);
4139
4140               dw2_instantiate_symtab (per_cu);
4141
4142               if (expansion_notify != NULL
4143                   && symtab_was_null
4144                   && per_cu->v.quick->compunit_symtab != NULL)
4145                 {
4146                   expansion_notify (per_cu->v.quick->compunit_symtab);
4147                 }
4148             }
4149         }
4150     }
4151 }
4152
4153 /* A helper for dw2_find_pc_sect_compunit_symtab which finds the most specific
4154    symtab.  */
4155
4156 static struct compunit_symtab *
4157 recursively_find_pc_sect_compunit_symtab (struct compunit_symtab *cust,
4158                                           CORE_ADDR pc)
4159 {
4160   int i;
4161
4162   if (COMPUNIT_BLOCKVECTOR (cust) != NULL
4163       && blockvector_contains_pc (COMPUNIT_BLOCKVECTOR (cust), pc))
4164     return cust;
4165
4166   if (cust->includes == NULL)
4167     return NULL;
4168
4169   for (i = 0; cust->includes[i]; ++i)
4170     {
4171       struct compunit_symtab *s = cust->includes[i];
4172
4173       s = recursively_find_pc_sect_compunit_symtab (s, pc);
4174       if (s != NULL)
4175         return s;
4176     }
4177
4178   return NULL;
4179 }
4180
4181 static struct compunit_symtab *
4182 dw2_find_pc_sect_compunit_symtab (struct objfile *objfile,
4183                                   struct bound_minimal_symbol msymbol,
4184                                   CORE_ADDR pc,
4185                                   struct obj_section *section,
4186                                   int warn_if_readin)
4187 {
4188   struct dwarf2_per_cu_data *data;
4189   struct compunit_symtab *result;
4190
4191   dw2_setup (objfile);
4192
4193   if (!objfile->psymtabs_addrmap)
4194     return NULL;
4195
4196   data = (struct dwarf2_per_cu_data *) addrmap_find (objfile->psymtabs_addrmap,
4197                                                      pc);
4198   if (!data)
4199     return NULL;
4200
4201   if (warn_if_readin && data->v.quick->compunit_symtab)
4202     warning (_("(Internal error: pc %s in read in CU, but not in symtab.)"),
4203              paddress (get_objfile_arch (objfile), pc));
4204
4205   result
4206     = recursively_find_pc_sect_compunit_symtab (dw2_instantiate_symtab (data),
4207                                                 pc);
4208   gdb_assert (result != NULL);
4209   return result;
4210 }
4211
4212 static void
4213 dw2_map_symbol_filenames (struct objfile *objfile, symbol_filename_ftype *fun,
4214                           void *data, int need_fullname)
4215 {
4216   int i;
4217   htab_up visited (htab_create_alloc (10, htab_hash_pointer, htab_eq_pointer,
4218                                       NULL, xcalloc, xfree));
4219
4220   dw2_setup (objfile);
4221
4222   /* The rule is CUs specify all the files, including those used by
4223      any TU, so there's no need to scan TUs here.
4224      We can ignore file names coming from already-expanded CUs.  */
4225
4226   for (i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
4227     {
4228       struct dwarf2_per_cu_data *per_cu = dw2_get_cutu (i);
4229
4230       if (per_cu->v.quick->compunit_symtab)
4231         {
4232           void **slot = htab_find_slot (visited.get (),
4233                                         per_cu->v.quick->file_names,
4234                                         INSERT);
4235
4236           *slot = per_cu->v.quick->file_names;
4237         }
4238     }
4239
4240   for (i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
4241     {
4242       int j;
4243       struct dwarf2_per_cu_data *per_cu = dw2_get_cu (i);
4244       struct quick_file_names *file_data;
4245       void **slot;
4246
4247       /* We only need to look at symtabs not already expanded.  */
4248       if (per_cu->v.quick->compunit_symtab)
4249         continue;
4250
4251       file_data = dw2_get_file_names (per_cu);
4252       if (file_data == NULL)
4253         continue;
4254
4255       slot = htab_find_slot (visited.get (), file_data, INSERT);
4256       if (*slot)
4257         {
4258           /* Already visited.  */
4259           continue;
4260         }
4261       *slot = file_data;
4262
4263       for (j = 0; j < file_data->num_file_names; ++j)
4264         {
4265           const char *this_real_name;
4266
4267           if (need_fullname)
4268             this_real_name = dw2_get_real_path (objfile, file_data, j);
4269           else
4270             this_real_name = NULL;
4271           (*fun) (file_data->file_names[j], this_real_name, data);
4272         }
4273     }
4274 }
4275
4276 static int
4277 dw2_has_symbols (struct objfile *objfile)
4278 {
4279   return 1;
4280 }
4281
4282 const struct quick_symbol_functions dwarf2_gdb_index_functions =
4283 {
4284   dw2_has_symbols,
4285   dw2_find_last_source_symtab,
4286   dw2_forget_cached_source_info,
4287   dw2_map_symtabs_matching_filename,
4288   dw2_lookup_symbol,
4289   dw2_print_stats,
4290   dw2_dump,
4291   dw2_relocate,
4292   dw2_expand_symtabs_for_function,
4293   dw2_expand_all_symtabs,
4294   dw2_expand_symtabs_with_fullname,
4295   dw2_map_matching_symbols,
4296   dw2_expand_symtabs_matching,
4297   dw2_find_pc_sect_compunit_symtab,
4298   dw2_map_symbol_filenames
4299 };
4300
4301 /* Initialize for reading DWARF for this objfile.  Return 0 if this
4302    file will use psymtabs, or 1 if using the GNU index.  */
4303
4304 int
4305 dwarf2_initialize_objfile (struct objfile *objfile)
4306 {
4307   /* If we're about to read full symbols, don't bother with the
4308      indices.  In this case we also don't care if some other debug
4309      format is making psymtabs, because they are all about to be
4310      expanded anyway.  */
4311   if ((objfile->flags & OBJF_READNOW))
4312     {
4313       int i;
4314
4315       dwarf2_per_objfile->using_index = 1;
4316       create_all_comp_units (objfile);
4317       create_all_type_units (objfile);
4318       dwarf2_per_objfile->quick_file_names_table =
4319         create_quick_file_names_table (dwarf2_per_objfile->n_comp_units);
4320
4321       for (i = 0; i < (dwarf2_per_objfile->n_comp_units
4322                        + dwarf2_per_objfile->n_type_units); ++i)
4323         {
4324           struct dwarf2_per_cu_data *per_cu = dw2_get_cutu (i);
4325
4326           per_cu->v.quick = OBSTACK_ZALLOC (&objfile->objfile_obstack,
4327                                             struct dwarf2_per_cu_quick_data);
4328         }
4329
4330       /* Return 1 so that gdb sees the "quick" functions.  However,
4331          these functions will be no-ops because we will have expanded
4332          all symtabs.  */
4333       return 1;
4334     }
4335
4336   if (dwarf2_read_index (objfile))
4337     return 1;
4338
4339   return 0;
4340 }
4341
4342 \f
4343
4344 /* Build a partial symbol table.  */
4345
4346 void
4347 dwarf2_build_psymtabs (struct objfile *objfile)
4348 {
4349
4350   if (objfile->global_psymbols.size == 0 && objfile->static_psymbols.size == 0)
4351     {
4352       init_psymbol_list (objfile, 1024);
4353     }
4354
4355   TRY
4356     {
4357       /* This isn't really ideal: all the data we allocate on the
4358          objfile's obstack is still uselessly kept around.  However,
4359          freeing it seems unsafe.  */
4360       psymtab_discarder psymtabs (objfile);
4361       dwarf2_build_psymtabs_hard (objfile);
4362       psymtabs.keep ();
4363     }
4364   CATCH (except, RETURN_MASK_ERROR)
4365     {
4366       exception_print (gdb_stderr, except);
4367     }
4368   END_CATCH
4369 }
4370
4371 /* Return the total length of the CU described by HEADER.  */
4372
4373 static unsigned int
4374 get_cu_length (const struct comp_unit_head *header)
4375 {
4376   return header->initial_length_size + header->length;
4377 }
4378
4379 /* Return TRUE if OFFSET is within CU_HEADER.  */
4380
4381 static inline int
4382 offset_in_cu_p (const struct comp_unit_head *cu_header, sect_offset offset)
4383 {
4384   sect_offset bottom = { cu_header->offset.sect_off };
4385   sect_offset top = { cu_header->offset.sect_off + get_cu_length (cu_header) };
4386
4387   return (offset.sect_off >= bottom.sect_off && offset.sect_off < top.sect_off);
4388 }
4389
4390 /* Find the base address of the compilation unit for range lists and
4391    location lists.  It will normally be specified by DW_AT_low_pc.
4392    In DWARF-3 draft 4, the base address could be overridden by
4393    DW_AT_entry_pc.  It's been removed, but GCC still uses this for
4394    compilation units with discontinuous ranges.  */
4395
4396 static void
4397 dwarf2_find_base_address (struct die_info *die, struct dwarf2_cu *cu)
4398 {
4399   struct attribute *attr;
4400
4401   cu->base_known = 0;
4402   cu->base_address = 0;
4403
4404   attr = dwarf2_attr (die, DW_AT_entry_pc, cu);
4405   if (attr)
4406     {
4407       cu->base_address = attr_value_as_address (attr);
4408       cu->base_known = 1;
4409     }
4410   else
4411     {
4412       attr = dwarf2_attr (die, DW_AT_low_pc, cu);
4413       if (attr)
4414         {
4415           cu->base_address = attr_value_as_address (attr);
4416           cu->base_known = 1;
4417         }
4418     }
4419 }
4420
4421 /* Read in the comp unit header information from the debug_info at info_ptr.
4422    Use rcuh_kind::COMPILE as the default type if not known by the caller.
4423    NOTE: This leaves members offset, first_die_offset to be filled in
4424    by the caller.  */
4425
4426 static const gdb_byte *
4427 read_comp_unit_head (struct comp_unit_head *cu_header,
4428                      const gdb_byte *info_ptr,
4429                      struct dwarf2_section_info *section,
4430                      rcuh_kind section_kind)
4431 {
4432   int signed_addr;
4433   unsigned int bytes_read;
4434   const char *filename = get_section_file_name (section);
4435   bfd *abfd = get_section_bfd_owner (section);
4436
4437   cu_header->length = read_initial_length (abfd, info_ptr, &bytes_read);
4438   cu_header->initial_length_size = bytes_read;
4439   cu_header->offset_size = (bytes_read == 4) ? 4 : 8;
4440   info_ptr += bytes_read;
4441   cu_header->version = read_2_bytes (abfd, info_ptr);
4442   info_ptr += 2;
4443   if (cu_header->version < 5)
4444     switch (section_kind)
4445       {
4446       case rcuh_kind::COMPILE:
4447         cu_header->unit_type = DW_UT_compile;
4448         break;
4449       case rcuh_kind::TYPE:
4450         cu_header->unit_type = DW_UT_type;
4451         break;
4452       default:
4453         internal_error (__FILE__, __LINE__,
4454                         _("read_comp_unit_head: invalid section_kind"));
4455       }
4456   else
4457     {
4458       cu_header->unit_type = static_cast<enum dwarf_unit_type>
4459                                                  (read_1_byte (abfd, info_ptr));
4460       info_ptr += 1;
4461       switch (cu_header->unit_type)
4462         {
4463         case DW_UT_compile:
4464           if (section_kind != rcuh_kind::COMPILE)
4465             error (_("Dwarf Error: wrong unit_type in compilation unit header "
4466                    "(is DW_UT_compile, should be DW_UT_type) [in module %s]"),
4467                    filename);
4468           break;
4469         case DW_UT_type:
4470           section_kind = rcuh_kind::TYPE;
4471           break;
4472         default:
4473           error (_("Dwarf Error: wrong unit_type in compilation unit header "
4474                  "(is %d, should be %d or %d) [in module %s]"),
4475                  cu_header->unit_type, DW_UT_compile, DW_UT_type, filename);
4476         }
4477
4478       cu_header->addr_size = read_1_byte (abfd, info_ptr);
4479       info_ptr += 1;
4480     }
4481   cu_header->abbrev_offset.sect_off = read_offset (abfd, info_ptr, cu_header,
4482                                              &bytes_read);
4483   info_ptr += bytes_read;
4484   if (cu_header->version < 5)
4485     {
4486       cu_header->addr_size = read_1_byte (abfd, info_ptr);
4487       info_ptr += 1;
4488     }
4489   signed_addr = bfd_get_sign_extend_vma (abfd);
4490   if (signed_addr < 0)
4491     internal_error (__FILE__, __LINE__,
4492                     _("read_comp_unit_head: dwarf from non elf file"));
4493   cu_header->signed_addr_p = signed_addr;
4494
4495   if (section_kind == rcuh_kind::TYPE)
4496     {
4497       LONGEST type_offset;
4498
4499       cu_header->signature = read_8_bytes (abfd, info_ptr);
4500       info_ptr += 8;
4501
4502       type_offset = read_offset (abfd, info_ptr, cu_header, &bytes_read);
4503       info_ptr += bytes_read;
4504       cu_header->type_offset_in_tu.cu_off = type_offset;
4505       if (cu_header->type_offset_in_tu.cu_off != type_offset)
4506         error (_("Dwarf Error: Too big type_offset in compilation unit "
4507                "header (is %s) [in module %s]"), plongest (type_offset),
4508                filename);
4509     }
4510
4511   return info_ptr;
4512 }
4513
4514 /* Helper function that returns the proper abbrev section for
4515    THIS_CU.  */
4516
4517 static struct dwarf2_section_info *
4518 get_abbrev_section_for_cu (struct dwarf2_per_cu_data *this_cu)
4519 {
4520   struct dwarf2_section_info *abbrev;
4521
4522   if (this_cu->is_dwz)
4523     abbrev = &dwarf2_get_dwz_file ()->abbrev;
4524   else
4525     abbrev = &dwarf2_per_objfile->abbrev;
4526
4527   return abbrev;
4528 }
4529
4530 /* Subroutine of read_and_check_comp_unit_head and
4531    read_and_check_type_unit_head to simplify them.
4532    Perform various error checking on the header.  */
4533
4534 static void
4535 error_check_comp_unit_head (struct comp_unit_head *header,
4536                             struct dwarf2_section_info *section,
4537                             struct dwarf2_section_info *abbrev_section)
4538 {
4539   const char *filename = get_section_file_name (section);
4540
4541   if (header->version < 2 || header->version > 5)
4542     error (_("Dwarf Error: wrong version in compilation unit header "
4543            "(is %d, should be 2, 3, 4 or 5) [in module %s]"), header->version,
4544            filename);
4545
4546   if (header->abbrev_offset.sect_off
4547       >= dwarf2_section_size (dwarf2_per_objfile->objfile, abbrev_section))
4548     error (_("Dwarf Error: bad offset (0x%lx) in compilation unit header "
4549            "(offset 0x%lx + 6) [in module %s]"),
4550            (long) header->abbrev_offset.sect_off, (long) header->offset.sect_off,
4551            filename);
4552
4553   /* Cast to unsigned long to use 64-bit arithmetic when possible to
4554      avoid potential 32-bit overflow.  */
4555   if (((unsigned long) header->offset.sect_off + get_cu_length (header))
4556       > section->size)
4557     error (_("Dwarf Error: bad length (0x%lx) in compilation unit header "
4558            "(offset 0x%lx + 0) [in module %s]"),
4559            (long) header->length, (long) header->offset.sect_off,
4560            filename);
4561 }
4562
4563 /* Read in a CU/TU header and perform some basic error checking.
4564    The contents of the header are stored in HEADER.
4565    The result is a pointer to the start of the first DIE.  */
4566
4567 static const gdb_byte *
4568 read_and_check_comp_unit_head (struct comp_unit_head *header,
4569                                struct dwarf2_section_info *section,
4570                                struct dwarf2_section_info *abbrev_section,
4571                                const gdb_byte *info_ptr,
4572                                rcuh_kind section_kind)
4573 {
4574   const gdb_byte *beg_of_comp_unit = info_ptr;
4575   bfd *abfd = get_section_bfd_owner (section);
4576
4577   header->offset.sect_off = beg_of_comp_unit - section->buffer;
4578
4579   info_ptr = read_comp_unit_head (header, info_ptr, section, section_kind);
4580
4581   header->first_die_offset.cu_off = info_ptr - beg_of_comp_unit;
4582
4583   error_check_comp_unit_head (header, section, abbrev_section);
4584
4585   return info_ptr;
4586 }
4587
4588 /* Fetch the abbreviation table offset from a comp or type unit header.  */
4589
4590 static sect_offset
4591 read_abbrev_offset (struct dwarf2_section_info *section,
4592                     sect_offset offset)
4593 {
4594   bfd *abfd = get_section_bfd_owner (section);
4595   const gdb_byte *info_ptr;
4596   unsigned int initial_length_size, offset_size;
4597   sect_offset abbrev_offset;
4598   uint16_t version;
4599
4600   dwarf2_read_section (dwarf2_per_objfile->objfile, section);
4601   info_ptr = section->buffer + offset.sect_off;
4602   read_initial_length (abfd, info_ptr, &initial_length_size);
4603   offset_size = initial_length_size == 4 ? 4 : 8;
4604   info_ptr += initial_length_size;
4605
4606   version = read_2_bytes (abfd, info_ptr);
4607   info_ptr += 2;
4608   if (version >= 5)
4609     {
4610       /* Skip unit type and address size.  */
4611       info_ptr += 2;
4612     }
4613
4614   abbrev_offset.sect_off = read_offset_1 (abfd, info_ptr, offset_size);
4615   return abbrev_offset;
4616 }
4617
4618 /* Allocate a new partial symtab for file named NAME and mark this new
4619    partial symtab as being an include of PST.  */
4620
4621 static void
4622 dwarf2_create_include_psymtab (const char *name, struct partial_symtab *pst,
4623                                struct objfile *objfile)
4624 {
4625   struct partial_symtab *subpst = allocate_psymtab (name, objfile);
4626
4627   if (!IS_ABSOLUTE_PATH (subpst->filename))
4628     {
4629       /* It shares objfile->objfile_obstack.  */
4630       subpst->dirname = pst->dirname;
4631     }
4632
4633   subpst->textlow = 0;
4634   subpst->texthigh = 0;
4635
4636   subpst->dependencies
4637     = XOBNEW (&objfile->objfile_obstack, struct partial_symtab *);
4638   subpst->dependencies[0] = pst;
4639   subpst->number_of_dependencies = 1;
4640
4641   subpst->globals_offset = 0;
4642   subpst->n_global_syms = 0;
4643   subpst->statics_offset = 0;
4644   subpst->n_static_syms = 0;
4645   subpst->compunit_symtab = NULL;
4646   subpst->read_symtab = pst->read_symtab;
4647   subpst->readin = 0;
4648
4649   /* No private part is necessary for include psymtabs.  This property
4650      can be used to differentiate between such include psymtabs and
4651      the regular ones.  */
4652   subpst->read_symtab_private = NULL;
4653 }
4654
4655 /* Read the Line Number Program data and extract the list of files
4656    included by the source file represented by PST.  Build an include
4657    partial symtab for each of these included files.  */
4658
4659 static void
4660 dwarf2_build_include_psymtabs (struct dwarf2_cu *cu,
4661                                struct die_info *die,
4662                                struct partial_symtab *pst)
4663 {
4664   struct line_header *lh = NULL;
4665   struct attribute *attr;
4666
4667   attr = dwarf2_attr (die, DW_AT_stmt_list, cu);
4668   if (attr)
4669     lh = dwarf_decode_line_header (DW_UNSND (attr), cu);
4670   if (lh == NULL)
4671     return;  /* No linetable, so no includes.  */
4672
4673   /* NOTE: pst->dirname is DW_AT_comp_dir (if present).  */
4674   dwarf_decode_lines (lh, pst->dirname, cu, pst, pst->textlow, 1);
4675
4676   free_line_header (lh);
4677 }
4678
4679 static hashval_t
4680 hash_signatured_type (const void *item)
4681 {
4682   const struct signatured_type *sig_type
4683     = (const struct signatured_type *) item;
4684
4685   /* This drops the top 32 bits of the signature, but is ok for a hash.  */
4686   return sig_type->signature;
4687 }
4688
4689 static int
4690 eq_signatured_type (const void *item_lhs, const void *item_rhs)
4691 {
4692   const struct signatured_type *lhs = (const struct signatured_type *) item_lhs;
4693   const struct signatured_type *rhs = (const struct signatured_type *) item_rhs;
4694
4695   return lhs->signature == rhs->signature;
4696 }
4697
4698 /* Allocate a hash table for signatured types.  */
4699
4700 static htab_t
4701 allocate_signatured_type_table (struct objfile *objfile)
4702 {
4703   return htab_create_alloc_ex (41,
4704                                hash_signatured_type,
4705                                eq_signatured_type,
4706                                NULL,
4707                                &objfile->objfile_obstack,
4708                                hashtab_obstack_allocate,
4709                                dummy_obstack_deallocate);
4710 }
4711
4712 /* A helper function to add a signatured type CU to a table.  */
4713
4714 static int
4715 add_signatured_type_cu_to_table (void **slot, void *datum)
4716 {
4717   struct signatured_type *sigt = (struct signatured_type *) *slot;
4718   struct signatured_type ***datap = (struct signatured_type ***) datum;
4719
4720   **datap = sigt;
4721   ++*datap;
4722
4723   return 1;
4724 }
4725
4726 /* A helper for create_debug_types_hash_table.  Read types from SECTION
4727    and fill them into TYPES_HTAB.  It will process only type units,
4728    therefore DW_UT_type.  */
4729
4730 static void
4731 create_debug_type_hash_table (struct dwo_file *dwo_file,
4732                               dwarf2_section_info *section, htab_t &types_htab,
4733                               rcuh_kind section_kind)
4734 {
4735   struct objfile *objfile = dwarf2_per_objfile->objfile;
4736   struct dwarf2_section_info *abbrev_section;
4737   bfd *abfd;
4738   const gdb_byte *info_ptr, *end_ptr;
4739
4740   abbrev_section = (dwo_file != NULL
4741                     ? &dwo_file->sections.abbrev
4742                     : &dwarf2_per_objfile->abbrev);
4743
4744   if (dwarf_read_debug)
4745     fprintf_unfiltered (gdb_stdlog, "Reading %s for %s:\n",
4746                         get_section_name (section),
4747                         get_section_file_name (abbrev_section));
4748
4749   dwarf2_read_section (objfile, section);
4750   info_ptr = section->buffer;
4751
4752   if (info_ptr == NULL)
4753     return;
4754
4755   /* We can't set abfd until now because the section may be empty or
4756      not present, in which case the bfd is unknown.  */
4757   abfd = get_section_bfd_owner (section);
4758
4759   /* We don't use init_cutu_and_read_dies_simple, or some such, here
4760      because we don't need to read any dies: the signature is in the
4761      header.  */
4762
4763   end_ptr = info_ptr + section->size;
4764   while (info_ptr < end_ptr)
4765     {
4766       sect_offset offset;
4767       struct signatured_type *sig_type;
4768       struct dwo_unit *dwo_tu;
4769       void **slot;
4770       const gdb_byte *ptr = info_ptr;
4771       struct comp_unit_head header;
4772       unsigned int length;
4773
4774       offset.sect_off = ptr - section->buffer;
4775
4776       /* Initialize it due to a false compiler warning.  */
4777       header.signature = -1;
4778       header.type_offset_in_tu.cu_off = -1;
4779
4780       /* We need to read the type's signature in order to build the hash
4781          table, but we don't need anything else just yet.  */
4782
4783       ptr = read_and_check_comp_unit_head (&header, section,
4784                                            abbrev_section, ptr, section_kind);
4785
4786       length = get_cu_length (&header);
4787
4788       /* Skip dummy type units.  */
4789       if (ptr >= info_ptr + length
4790           || peek_abbrev_code (abfd, ptr) == 0
4791           || header.unit_type != DW_UT_type)
4792         {
4793           info_ptr += length;
4794           continue;
4795         }
4796
4797       if (types_htab == NULL)
4798         {
4799           if (dwo_file)
4800             types_htab = allocate_dwo_unit_table (objfile);
4801           else
4802             types_htab = allocate_signatured_type_table (objfile);
4803         }
4804
4805       if (dwo_file)
4806         {
4807           sig_type = NULL;
4808           dwo_tu = OBSTACK_ZALLOC (&objfile->objfile_obstack,
4809                                    struct dwo_unit);
4810           dwo_tu->dwo_file = dwo_file;
4811           dwo_tu->signature = header.signature;
4812           dwo_tu->type_offset_in_tu = header.type_offset_in_tu;
4813           dwo_tu->section = section;
4814           dwo_tu->offset = offset;
4815           dwo_tu->length = length;
4816         }
4817       else
4818         {
4819           /* N.B.: type_offset is not usable if this type uses a DWO file.
4820              The real type_offset is in the DWO file.  */
4821           dwo_tu = NULL;
4822           sig_type = OBSTACK_ZALLOC (&objfile->objfile_obstack,
4823                                      struct signatured_type);
4824           sig_type->signature = header.signature;
4825           sig_type->type_offset_in_tu = header.type_offset_in_tu;
4826           sig_type->per_cu.objfile = objfile;
4827           sig_type->per_cu.is_debug_types = 1;
4828           sig_type->per_cu.section = section;
4829           sig_type->per_cu.offset = offset;
4830           sig_type->per_cu.length = length;
4831         }
4832
4833       slot = htab_find_slot (types_htab,
4834                              dwo_file ? (void*) dwo_tu : (void *) sig_type,
4835                              INSERT);
4836       gdb_assert (slot != NULL);
4837       if (*slot != NULL)
4838         {
4839           sect_offset dup_offset;
4840
4841           if (dwo_file)
4842             {
4843               const struct dwo_unit *dup_tu
4844                 = (const struct dwo_unit *) *slot;
4845
4846               dup_offset = dup_tu->offset;
4847             }
4848           else
4849             {
4850               const struct signatured_type *dup_tu
4851                 = (const struct signatured_type *) *slot;
4852
4853               dup_offset = dup_tu->per_cu.offset;
4854             }
4855
4856           complaint (&symfile_complaints,
4857                      _("debug type entry at offset 0x%x is duplicate to"
4858                        " the entry at offset 0x%x, signature %s"),
4859                      offset.sect_off, dup_offset.sect_off,
4860                      hex_string (header.signature));
4861         }
4862       *slot = dwo_file ? (void *) dwo_tu : (void *) sig_type;
4863
4864       if (dwarf_read_debug > 1)
4865         fprintf_unfiltered (gdb_stdlog, "  offset 0x%x, signature %s\n",
4866                             offset.sect_off,
4867                             hex_string (header.signature));
4868
4869       info_ptr += length;
4870     }
4871 }
4872
4873 /* Create the hash table of all entries in the .debug_types
4874    (or .debug_types.dwo) section(s).
4875    If reading a DWO file, then DWO_FILE is a pointer to the DWO file object,
4876    otherwise it is NULL.
4877
4878    The result is a pointer to the hash table or NULL if there are no types.
4879
4880    Note: This function processes DWO files only, not DWP files.  */
4881
4882 static void
4883 create_debug_types_hash_table (struct dwo_file *dwo_file,
4884                                VEC (dwarf2_section_info_def) *types,
4885                                htab_t &types_htab)
4886 {
4887   int ix;
4888   struct dwarf2_section_info *section;
4889
4890   if (VEC_empty (dwarf2_section_info_def, types))
4891     return;
4892
4893   for (ix = 0;
4894        VEC_iterate (dwarf2_section_info_def, types, ix, section);
4895        ++ix)
4896     create_debug_type_hash_table (dwo_file, section, types_htab,
4897                                   rcuh_kind::TYPE);
4898 }
4899
4900 /* Create the hash table of all entries in the .debug_types section,
4901    and initialize all_type_units.
4902    The result is zero if there is an error (e.g. missing .debug_types section),
4903    otherwise non-zero.  */
4904
4905 static int
4906 create_all_type_units (struct objfile *objfile)
4907 {
4908   htab_t types_htab = NULL;
4909   struct signatured_type **iter;
4910
4911   create_debug_type_hash_table (NULL, &dwarf2_per_objfile->info, types_htab,
4912                                 rcuh_kind::COMPILE);
4913   create_debug_types_hash_table (NULL, dwarf2_per_objfile->types, types_htab);
4914   if (types_htab == NULL)
4915     {
4916       dwarf2_per_objfile->signatured_types = NULL;
4917       return 0;
4918     }
4919
4920   dwarf2_per_objfile->signatured_types = types_htab;
4921
4922   dwarf2_per_objfile->n_type_units
4923     = dwarf2_per_objfile->n_allocated_type_units
4924     = htab_elements (types_htab);
4925   dwarf2_per_objfile->all_type_units =
4926     XNEWVEC (struct signatured_type *, dwarf2_per_objfile->n_type_units);
4927   iter = &dwarf2_per_objfile->all_type_units[0];
4928   htab_traverse_noresize (types_htab, add_signatured_type_cu_to_table, &iter);
4929   gdb_assert (iter - &dwarf2_per_objfile->all_type_units[0]
4930               == dwarf2_per_objfile->n_type_units);
4931
4932   return 1;
4933 }
4934
4935 /* Add an entry for signature SIG to dwarf2_per_objfile->signatured_types.
4936    If SLOT is non-NULL, it is the entry to use in the hash table.
4937    Otherwise we find one.  */
4938
4939 static struct signatured_type *
4940 add_type_unit (ULONGEST sig, void **slot)
4941 {
4942   struct objfile *objfile = dwarf2_per_objfile->objfile;
4943   int n_type_units = dwarf2_per_objfile->n_type_units;
4944   struct signatured_type *sig_type;
4945
4946   gdb_assert (n_type_units <= dwarf2_per_objfile->n_allocated_type_units);
4947   ++n_type_units;
4948   if (n_type_units > dwarf2_per_objfile->n_allocated_type_units)
4949     {
4950       if (dwarf2_per_objfile->n_allocated_type_units == 0)
4951         dwarf2_per_objfile->n_allocated_type_units = 1;
4952       dwarf2_per_objfile->n_allocated_type_units *= 2;
4953       dwarf2_per_objfile->all_type_units
4954         = XRESIZEVEC (struct signatured_type *,
4955                       dwarf2_per_objfile->all_type_units,
4956                       dwarf2_per_objfile->n_allocated_type_units);
4957       ++dwarf2_per_objfile->tu_stats.nr_all_type_units_reallocs;
4958     }
4959   dwarf2_per_objfile->n_type_units = n_type_units;
4960
4961   sig_type = OBSTACK_ZALLOC (&objfile->objfile_obstack,
4962                              struct signatured_type);
4963   dwarf2_per_objfile->all_type_units[n_type_units - 1] = sig_type;
4964   sig_type->signature = sig;
4965   sig_type->per_cu.is_debug_types = 1;
4966   if (dwarf2_per_objfile->using_index)
4967     {
4968       sig_type->per_cu.v.quick =
4969         OBSTACK_ZALLOC (&objfile->objfile_obstack,
4970                         struct dwarf2_per_cu_quick_data);
4971     }
4972
4973   if (slot == NULL)
4974     {
4975       slot = htab_find_slot (dwarf2_per_objfile->signatured_types,
4976                              sig_type, INSERT);
4977     }
4978   gdb_assert (*slot == NULL);
4979   *slot = sig_type;
4980   /* The rest of sig_type must be filled in by the caller.  */
4981   return sig_type;
4982 }
4983
4984 /* Subroutine of lookup_dwo_signatured_type and lookup_dwp_signatured_type.
4985    Fill in SIG_ENTRY with DWO_ENTRY.  */
4986
4987 static void
4988 fill_in_sig_entry_from_dwo_entry (struct objfile *objfile,
4989                                   struct signatured_type *sig_entry,
4990                                   struct dwo_unit *dwo_entry)
4991 {
4992   /* Make sure we're not clobbering something we don't expect to.  */
4993   gdb_assert (! sig_entry->per_cu.queued);
4994   gdb_assert (sig_entry->per_cu.cu == NULL);
4995   if (dwarf2_per_objfile->using_index)
4996     {
4997       gdb_assert (sig_entry->per_cu.v.quick != NULL);
4998       gdb_assert (sig_entry->per_cu.v.quick->compunit_symtab == NULL);
4999     }
5000   else
5001       gdb_assert (sig_entry->per_cu.v.psymtab == NULL);
5002   gdb_assert (sig_entry->signature == dwo_entry->signature);
5003   gdb_assert (sig_entry->type_offset_in_section.sect_off == 0);
5004   gdb_assert (sig_entry->type_unit_group == NULL);
5005   gdb_assert (sig_entry->dwo_unit == NULL);
5006
5007   sig_entry->per_cu.section = dwo_entry->section;
5008   sig_entry->per_cu.offset = dwo_entry->offset;
5009   sig_entry->per_cu.length = dwo_entry->length;
5010   sig_entry->per_cu.reading_dwo_directly = 1;
5011   sig_entry->per_cu.objfile = objfile;
5012   sig_entry->type_offset_in_tu = dwo_entry->type_offset_in_tu;
5013   sig_entry->dwo_unit = dwo_entry;
5014 }
5015
5016 /* Subroutine of lookup_signatured_type.
5017    If we haven't read the TU yet, create the signatured_type data structure
5018    for a TU to be read in directly from a DWO file, bypassing the stub.
5019    This is the "Stay in DWO Optimization": When there is no DWP file and we're
5020    using .gdb_index, then when reading a CU we want to stay in the DWO file
5021    containing that CU.  Otherwise we could end up reading several other DWO
5022    files (due to comdat folding) to process the transitive closure of all the
5023    mentioned TUs, and that can be slow.  The current DWO file will have every
5024    type signature that it needs.
5025    We only do this for .gdb_index because in the psymtab case we already have
5026    to read all the DWOs to build the type unit groups.  */
5027
5028 static struct signatured_type *
5029 lookup_dwo_signatured_type (struct dwarf2_cu *cu, ULONGEST sig)
5030 {
5031   struct objfile *objfile = dwarf2_per_objfile->objfile;
5032   struct dwo_file *dwo_file;
5033   struct dwo_unit find_dwo_entry, *dwo_entry;
5034   struct signatured_type find_sig_entry, *sig_entry;
5035   void **slot;
5036
5037   gdb_assert (cu->dwo_unit && dwarf2_per_objfile->using_index);
5038
5039   /* If TU skeletons have been removed then we may not have read in any
5040      TUs yet.  */
5041   if (dwarf2_per_objfile->signatured_types == NULL)
5042     {
5043       dwarf2_per_objfile->signatured_types
5044         = allocate_signatured_type_table (objfile);
5045     }
5046
5047   /* We only ever need to read in one copy of a signatured type.
5048      Use the global signatured_types array to do our own comdat-folding
5049      of types.  If this is the first time we're reading this TU, and
5050      the TU has an entry in .gdb_index, replace the recorded data from
5051      .gdb_index with this TU.  */
5052
5053   find_sig_entry.signature = sig;
5054   slot = htab_find_slot (dwarf2_per_objfile->signatured_types,
5055                          &find_sig_entry, INSERT);
5056   sig_entry = (struct signatured_type *) *slot;
5057
5058   /* We can get here with the TU already read, *or* in the process of being
5059      read.  Don't reassign the global entry to point to this DWO if that's
5060      the case.  Also note that if the TU is already being read, it may not
5061      have come from a DWO, the program may be a mix of Fission-compiled
5062      code and non-Fission-compiled code.  */
5063
5064   /* Have we already tried to read this TU?
5065      Note: sig_entry can be NULL if the skeleton TU was removed (thus it
5066      needn't exist in the global table yet).  */
5067   if (sig_entry != NULL && sig_entry->per_cu.tu_read)
5068     return sig_entry;
5069
5070   /* Note: cu->dwo_unit is the dwo_unit that references this TU, not the
5071      dwo_unit of the TU itself.  */
5072   dwo_file = cu->dwo_unit->dwo_file;
5073
5074   /* Ok, this is the first time we're reading this TU.  */
5075   if (dwo_file->tus == NULL)
5076     return NULL;
5077   find_dwo_entry.signature = sig;
5078   dwo_entry = (struct dwo_unit *) htab_find (dwo_file->tus, &find_dwo_entry);
5079   if (dwo_entry == NULL)
5080     return NULL;
5081
5082   /* If the global table doesn't have an entry for this TU, add one.  */
5083   if (sig_entry == NULL)
5084     sig_entry = add_type_unit (sig, slot);
5085
5086   fill_in_sig_entry_from_dwo_entry (objfile, sig_entry, dwo_entry);
5087   sig_entry->per_cu.tu_read = 1;
5088   return sig_entry;
5089 }
5090
5091 /* Subroutine of lookup_signatured_type.
5092    Look up the type for signature SIG, and if we can't find SIG in .gdb_index
5093    then try the DWP file.  If the TU stub (skeleton) has been removed then
5094    it won't be in .gdb_index.  */
5095
5096 static struct signatured_type *
5097 lookup_dwp_signatured_type (struct dwarf2_cu *cu, ULONGEST sig)
5098 {
5099   struct objfile *objfile = dwarf2_per_objfile->objfile;
5100   struct dwp_file *dwp_file = get_dwp_file ();
5101   struct dwo_unit *dwo_entry;
5102   struct signatured_type find_sig_entry, *sig_entry;
5103   void **slot;
5104
5105   gdb_assert (cu->dwo_unit && dwarf2_per_objfile->using_index);
5106   gdb_assert (dwp_file != NULL);
5107
5108   /* If TU skeletons have been removed then we may not have read in any
5109      TUs yet.  */
5110   if (dwarf2_per_objfile->signatured_types == NULL)
5111     {
5112       dwarf2_per_objfile->signatured_types
5113         = allocate_signatured_type_table (objfile);
5114     }
5115
5116   find_sig_entry.signature = sig;
5117   slot = htab_find_slot (dwarf2_per_objfile->signatured_types,
5118                          &find_sig_entry, INSERT);
5119   sig_entry = (struct signatured_type *) *slot;
5120
5121   /* Have we already tried to read this TU?
5122      Note: sig_entry can be NULL if the skeleton TU was removed (thus it
5123      needn't exist in the global table yet).  */
5124   if (sig_entry != NULL)
5125     return sig_entry;
5126
5127   if (dwp_file->tus == NULL)
5128     return NULL;
5129   dwo_entry = lookup_dwo_unit_in_dwp (dwp_file, NULL,
5130                                       sig, 1 /* is_debug_types */);
5131   if (dwo_entry == NULL)
5132     return NULL;
5133
5134   sig_entry = add_type_unit (sig, slot);
5135   fill_in_sig_entry_from_dwo_entry (objfile, sig_entry, dwo_entry);
5136
5137   return sig_entry;
5138 }
5139
5140 /* Lookup a signature based type for DW_FORM_ref_sig8.
5141    Returns NULL if signature SIG is not present in the table.
5142    It is up to the caller to complain about this.  */
5143
5144 static struct signatured_type *
5145 lookup_signatured_type (struct dwarf2_cu *cu, ULONGEST sig)
5146 {
5147   if (cu->dwo_unit
5148       && dwarf2_per_objfile->using_index)
5149     {
5150       /* We're in a DWO/DWP file, and we're using .gdb_index.
5151          These cases require special processing.  */
5152       if (get_dwp_file () == NULL)
5153         return lookup_dwo_signatured_type (cu, sig);
5154       else
5155         return lookup_dwp_signatured_type (cu, sig);
5156     }
5157   else
5158     {
5159       struct signatured_type find_entry, *entry;
5160
5161       if (dwarf2_per_objfile->signatured_types == NULL)
5162         return NULL;
5163       find_entry.signature = sig;
5164       entry = ((struct signatured_type *)
5165                htab_find (dwarf2_per_objfile->signatured_types, &find_entry));
5166       return entry;
5167     }
5168 }
5169 \f
5170 /* Low level DIE reading support.  */
5171
5172 /* Initialize a die_reader_specs struct from a dwarf2_cu struct.  */
5173
5174 static void
5175 init_cu_die_reader (struct die_reader_specs *reader,
5176                     struct dwarf2_cu *cu,
5177                     struct dwarf2_section_info *section,
5178                     struct dwo_file *dwo_file)
5179 {
5180   gdb_assert (section->readin && section->buffer != NULL);
5181   reader->abfd = get_section_bfd_owner (section);
5182   reader->cu = cu;
5183   reader->dwo_file = dwo_file;
5184   reader->die_section = section;
5185   reader->buffer = section->buffer;
5186   reader->buffer_end = section->buffer + section->size;
5187   reader->comp_dir = NULL;
5188 }
5189
5190 /* Subroutine of init_cutu_and_read_dies to simplify it.
5191    Read in the rest of a CU/TU top level DIE from DWO_UNIT.
5192    There's just a lot of work to do, and init_cutu_and_read_dies is big enough
5193    already.
5194
5195    STUB_COMP_UNIT_DIE is for the stub DIE, we copy over certain attributes
5196    from it to the DIE in the DWO.  If NULL we are skipping the stub.
5197    STUB_COMP_DIR is similar to STUB_COMP_UNIT_DIE: When reading a TU directly
5198    from the DWO file, bypassing the stub, it contains the DW_AT_comp_dir
5199    attribute of the referencing CU.  At most one of STUB_COMP_UNIT_DIE and
5200    STUB_COMP_DIR may be non-NULL.
5201    *RESULT_READER,*RESULT_INFO_PTR,*RESULT_COMP_UNIT_DIE,*RESULT_HAS_CHILDREN
5202    are filled in with the info of the DIE from the DWO file.
5203    ABBREV_TABLE_PROVIDED is non-zero if the caller of init_cutu_and_read_dies
5204    provided an abbrev table to use.
5205    The result is non-zero if a valid (non-dummy) DIE was found.  */
5206
5207 static int
5208 read_cutu_die_from_dwo (struct dwarf2_per_cu_data *this_cu,
5209                         struct dwo_unit *dwo_unit,
5210                         int abbrev_table_provided,
5211                         struct die_info *stub_comp_unit_die,
5212                         const char *stub_comp_dir,
5213                         struct die_reader_specs *result_reader,
5214                         const gdb_byte **result_info_ptr,
5215                         struct die_info **result_comp_unit_die,
5216                         int *result_has_children)
5217 {
5218   struct objfile *objfile = dwarf2_per_objfile->objfile;
5219   struct dwarf2_cu *cu = this_cu->cu;
5220   struct dwarf2_section_info *section;
5221   bfd *abfd;
5222   const gdb_byte *begin_info_ptr, *info_ptr;
5223   ULONGEST signature; /* Or dwo_id.  */
5224   struct attribute *comp_dir, *stmt_list, *low_pc, *high_pc, *ranges;
5225   int i,num_extra_attrs;
5226   struct dwarf2_section_info *dwo_abbrev_section;
5227   struct attribute *attr;
5228   struct die_info *comp_unit_die;
5229
5230   /* At most one of these may be provided.  */
5231   gdb_assert ((stub_comp_unit_die != NULL) + (stub_comp_dir != NULL) <= 1);
5232
5233   /* These attributes aren't processed until later:
5234      DW_AT_stmt_list, DW_AT_low_pc, DW_AT_high_pc, DW_AT_ranges.
5235      DW_AT_comp_dir is used now, to find the DWO file, but it is also
5236      referenced later.  However, these attributes are found in the stub
5237      which we won't have later.  In order to not impose this complication
5238      on the rest of the code, we read them here and copy them to the
5239      DWO CU/TU die.  */
5240
5241   stmt_list = NULL;
5242   low_pc = NULL;
5243   high_pc = NULL;
5244   ranges = NULL;
5245   comp_dir = NULL;
5246
5247   if (stub_comp_unit_die != NULL)
5248     {
5249       /* For TUs in DWO files, the DW_AT_stmt_list attribute lives in the
5250          DWO file.  */
5251       if (! this_cu->is_debug_types)
5252         stmt_list = dwarf2_attr (stub_comp_unit_die, DW_AT_stmt_list, cu);
5253       low_pc = dwarf2_attr (stub_comp_unit_die, DW_AT_low_pc, cu);
5254       high_pc = dwarf2_attr (stub_comp_unit_die, DW_AT_high_pc, cu);
5255       ranges = dwarf2_attr (stub_comp_unit_die, DW_AT_ranges, cu);
5256       comp_dir = dwarf2_attr (stub_comp_unit_die, DW_AT_comp_dir, cu);
5257
5258       /* There should be a DW_AT_addr_base attribute here (if needed).
5259          We need the value before we can process DW_FORM_GNU_addr_index.  */
5260       cu->addr_base = 0;
5261       attr = dwarf2_attr (stub_comp_unit_die, DW_AT_GNU_addr_base, cu);
5262       if (attr)
5263         cu->addr_base = DW_UNSND (attr);
5264
5265       /* There should be a DW_AT_ranges_base attribute here (if needed).
5266          We need the value before we can process DW_AT_ranges.  */
5267       cu->ranges_base = 0;
5268       attr = dwarf2_attr (stub_comp_unit_die, DW_AT_GNU_ranges_base, cu);
5269       if (attr)
5270         cu->ranges_base = DW_UNSND (attr);
5271     }
5272   else if (stub_comp_dir != NULL)
5273     {
5274       /* Reconstruct the comp_dir attribute to simplify the code below.  */
5275       comp_dir = XOBNEW (&cu->comp_unit_obstack, struct attribute);
5276       comp_dir->name = DW_AT_comp_dir;
5277       comp_dir->form = DW_FORM_string;
5278       DW_STRING_IS_CANONICAL (comp_dir) = 0;
5279       DW_STRING (comp_dir) = stub_comp_dir;
5280     }
5281
5282   /* Set up for reading the DWO CU/TU.  */
5283   cu->dwo_unit = dwo_unit;
5284   section = dwo_unit->section;
5285   dwarf2_read_section (objfile, section);
5286   abfd = get_section_bfd_owner (section);
5287   begin_info_ptr = info_ptr = section->buffer + dwo_unit->offset.sect_off;
5288   dwo_abbrev_section = &dwo_unit->dwo_file->sections.abbrev;
5289   init_cu_die_reader (result_reader, cu, section, dwo_unit->dwo_file);
5290
5291   if (this_cu->is_debug_types)
5292     {
5293       struct signatured_type *sig_type = (struct signatured_type *) this_cu;
5294
5295       info_ptr = read_and_check_comp_unit_head (&cu->header, section,
5296                                                 dwo_abbrev_section,
5297                                                 info_ptr, rcuh_kind::TYPE);
5298       /* This is not an assert because it can be caused by bad debug info.  */
5299       if (sig_type->signature != cu->header.signature)
5300         {
5301           error (_("Dwarf Error: signature mismatch %s vs %s while reading"
5302                    " TU at offset 0x%x [in module %s]"),
5303                  hex_string (sig_type->signature),
5304                  hex_string (cu->header.signature),
5305                  dwo_unit->offset.sect_off,
5306                  bfd_get_filename (abfd));
5307         }
5308       gdb_assert (dwo_unit->offset.sect_off == cu->header.offset.sect_off);
5309       /* For DWOs coming from DWP files, we don't know the CU length
5310          nor the type's offset in the TU until now.  */
5311       dwo_unit->length = get_cu_length (&cu->header);
5312       dwo_unit->type_offset_in_tu = cu->header.type_offset_in_tu;
5313
5314       /* Establish the type offset that can be used to lookup the type.
5315          For DWO files, we don't know it until now.  */
5316       sig_type->type_offset_in_section.sect_off =
5317         dwo_unit->offset.sect_off + dwo_unit->type_offset_in_tu.cu_off;
5318     }
5319   else
5320     {
5321       info_ptr = read_and_check_comp_unit_head (&cu->header, section,
5322                                                 dwo_abbrev_section,
5323                                                 info_ptr, rcuh_kind::COMPILE);
5324       gdb_assert (dwo_unit->offset.sect_off == cu->header.offset.sect_off);
5325       /* For DWOs coming from DWP files, we don't know the CU length
5326          until now.  */
5327       dwo_unit->length = get_cu_length (&cu->header);
5328     }
5329
5330   /* Replace the CU's original abbrev table with the DWO's.
5331      Reminder: We can't read the abbrev table until we've read the header.  */
5332   if (abbrev_table_provided)
5333     {
5334       /* Don't free the provided abbrev table, the caller of
5335          init_cutu_and_read_dies owns it.  */
5336       dwarf2_read_abbrevs (cu, dwo_abbrev_section);
5337       /* Ensure the DWO abbrev table gets freed.  */
5338       make_cleanup (dwarf2_free_abbrev_table, cu);
5339     }
5340   else
5341     {
5342       dwarf2_free_abbrev_table (cu);
5343       dwarf2_read_abbrevs (cu, dwo_abbrev_section);
5344       /* Leave any existing abbrev table cleanup as is.  */
5345     }
5346
5347   /* Read in the die, but leave space to copy over the attributes
5348      from the stub.  This has the benefit of simplifying the rest of
5349      the code - all the work to maintain the illusion of a single
5350      DW_TAG_{compile,type}_unit DIE is done here.  */
5351   num_extra_attrs = ((stmt_list != NULL)
5352                      + (low_pc != NULL)
5353                      + (high_pc != NULL)
5354                      + (ranges != NULL)
5355                      + (comp_dir != NULL));
5356   info_ptr = read_full_die_1 (result_reader, result_comp_unit_die, info_ptr,
5357                               result_has_children, num_extra_attrs);
5358
5359   /* Copy over the attributes from the stub to the DIE we just read in.  */
5360   comp_unit_die = *result_comp_unit_die;
5361   i = comp_unit_die->num_attrs;
5362   if (stmt_list != NULL)
5363     comp_unit_die->attrs[i++] = *stmt_list;
5364   if (low_pc != NULL)
5365     comp_unit_die->attrs[i++] = *low_pc;
5366   if (high_pc != NULL)
5367     comp_unit_die->attrs[i++] = *high_pc;
5368   if (ranges != NULL)
5369     comp_unit_die->attrs[i++] = *ranges;
5370   if (comp_dir != NULL)
5371     comp_unit_die->attrs[i++] = *comp_dir;
5372   comp_unit_die->num_attrs += num_extra_attrs;
5373
5374   if (dwarf_die_debug)
5375     {
5376       fprintf_unfiltered (gdb_stdlog,
5377                           "Read die from %s@0x%x of %s:\n",
5378                           get_section_name (section),
5379                           (unsigned) (begin_info_ptr - section->buffer),
5380                           bfd_get_filename (abfd));
5381       dump_die (comp_unit_die, dwarf_die_debug);
5382     }
5383
5384   /* Save the comp_dir attribute.  If there is no DWP file then we'll read
5385      TUs by skipping the stub and going directly to the entry in the DWO file.
5386      However, skipping the stub means we won't get DW_AT_comp_dir, so we have
5387      to get it via circuitous means.  Blech.  */
5388   if (comp_dir != NULL)
5389     result_reader->comp_dir = DW_STRING (comp_dir);
5390
5391   /* Skip dummy compilation units.  */
5392   if (info_ptr >= begin_info_ptr + dwo_unit->length
5393       || peek_abbrev_code (abfd, info_ptr) == 0)
5394     return 0;
5395
5396   *result_info_ptr = info_ptr;
5397   return 1;
5398 }
5399
5400 /* Subroutine of init_cutu_and_read_dies to simplify it.
5401    Look up the DWO unit specified by COMP_UNIT_DIE of THIS_CU.
5402    Returns NULL if the specified DWO unit cannot be found.  */
5403
5404 static struct dwo_unit *
5405 lookup_dwo_unit (struct dwarf2_per_cu_data *this_cu,
5406                  struct die_info *comp_unit_die)
5407 {
5408   struct dwarf2_cu *cu = this_cu->cu;
5409   struct attribute *attr;
5410   ULONGEST signature;
5411   struct dwo_unit *dwo_unit;
5412   const char *comp_dir, *dwo_name;
5413
5414   gdb_assert (cu != NULL);
5415
5416   /* Yeah, we look dwo_name up again, but it simplifies the code.  */
5417   dwo_name = dwarf2_string_attr (comp_unit_die, DW_AT_GNU_dwo_name, cu);
5418   comp_dir = dwarf2_string_attr (comp_unit_die, DW_AT_comp_dir, cu);
5419
5420   if (this_cu->is_debug_types)
5421     {
5422       struct signatured_type *sig_type;
5423
5424       /* Since this_cu is the first member of struct signatured_type,
5425          we can go from a pointer to one to a pointer to the other.  */
5426       sig_type = (struct signatured_type *) this_cu;
5427       signature = sig_type->signature;
5428       dwo_unit = lookup_dwo_type_unit (sig_type, dwo_name, comp_dir);
5429     }
5430   else
5431     {
5432       struct attribute *attr;
5433
5434       attr = dwarf2_attr (comp_unit_die, DW_AT_GNU_dwo_id, cu);
5435       if (! attr)
5436         error (_("Dwarf Error: missing dwo_id for dwo_name %s"
5437                  " [in module %s]"),
5438                dwo_name, objfile_name (this_cu->objfile));
5439       signature = DW_UNSND (attr);
5440       dwo_unit = lookup_dwo_comp_unit (this_cu, dwo_name, comp_dir,
5441                                        signature);
5442     }
5443
5444   return dwo_unit;
5445 }
5446
5447 /* Subroutine of init_cutu_and_read_dies to simplify it.
5448    See it for a description of the parameters.
5449    Read a TU directly from a DWO file, bypassing the stub.
5450
5451    Note: This function could be a little bit simpler if we shared cleanups
5452    with our caller, init_cutu_and_read_dies.  That's generally a fragile thing
5453    to do, so we keep this function self-contained.  Or we could move this
5454    into our caller, but it's complex enough already.  */
5455
5456 static void
5457 init_tu_and_read_dwo_dies (struct dwarf2_per_cu_data *this_cu,
5458                            int use_existing_cu, int keep,
5459                            die_reader_func_ftype *die_reader_func,
5460                            void *data)
5461 {
5462   struct dwarf2_cu *cu;
5463   struct signatured_type *sig_type;
5464   struct cleanup *cleanups, *free_cu_cleanup = NULL;
5465   struct die_reader_specs reader;
5466   const gdb_byte *info_ptr;
5467   struct die_info *comp_unit_die;
5468   int has_children;
5469
5470   /* Verify we can do the following downcast, and that we have the
5471      data we need.  */
5472   gdb_assert (this_cu->is_debug_types && this_cu->reading_dwo_directly);
5473   sig_type = (struct signatured_type *) this_cu;
5474   gdb_assert (sig_type->dwo_unit != NULL);
5475
5476   cleanups = make_cleanup (null_cleanup, NULL);
5477
5478   if (use_existing_cu && this_cu->cu != NULL)
5479     {
5480       gdb_assert (this_cu->cu->dwo_unit == sig_type->dwo_unit);
5481       cu = this_cu->cu;
5482       /* There's no need to do the rereading_dwo_cu handling that
5483          init_cutu_and_read_dies does since we don't read the stub.  */
5484     }
5485   else
5486     {
5487       /* If !use_existing_cu, this_cu->cu must be NULL.  */
5488       gdb_assert (this_cu->cu == NULL);
5489       cu = XNEW (struct dwarf2_cu);
5490       init_one_comp_unit (cu, this_cu);
5491       /* If an error occurs while loading, release our storage.  */
5492       free_cu_cleanup = make_cleanup (free_heap_comp_unit, cu);
5493     }
5494
5495   /* A future optimization, if needed, would be to use an existing
5496      abbrev table.  When reading DWOs with skeletonless TUs, all the TUs
5497      could share abbrev tables.  */
5498
5499   if (read_cutu_die_from_dwo (this_cu, sig_type->dwo_unit,
5500                               0 /* abbrev_table_provided */,
5501                               NULL /* stub_comp_unit_die */,
5502                               sig_type->dwo_unit->dwo_file->comp_dir,
5503                               &reader, &info_ptr,
5504                               &comp_unit_die, &has_children) == 0)
5505     {
5506       /* Dummy die.  */
5507       do_cleanups (cleanups);
5508       return;
5509     }
5510
5511   /* All the "real" work is done here.  */
5512   die_reader_func (&reader, info_ptr, comp_unit_die, has_children, data);
5513
5514   /* This duplicates the code in init_cutu_and_read_dies,
5515      but the alternative is making the latter more complex.
5516      This function is only for the special case of using DWO files directly:
5517      no point in overly complicating the general case just to handle this.  */
5518   if (free_cu_cleanup != NULL)
5519     {
5520       if (keep)
5521         {
5522           /* We've successfully allocated this compilation unit.  Let our
5523              caller clean it up when finished with it.  */
5524           discard_cleanups (free_cu_cleanup);
5525
5526           /* We can only discard free_cu_cleanup and all subsequent cleanups.
5527              So we have to manually free the abbrev table.  */
5528           dwarf2_free_abbrev_table (cu);
5529
5530           /* Link this CU into read_in_chain.  */
5531           this_cu->cu->read_in_chain = dwarf2_per_objfile->read_in_chain;
5532           dwarf2_per_objfile->read_in_chain = this_cu;
5533         }
5534       else
5535         do_cleanups (free_cu_cleanup);
5536     }
5537
5538   do_cleanups (cleanups);
5539 }
5540
5541 /* Initialize a CU (or TU) and read its DIEs.
5542    If the CU defers to a DWO file, read the DWO file as well.
5543
5544    ABBREV_TABLE, if non-NULL, is the abbreviation table to use.
5545    Otherwise the table specified in the comp unit header is read in and used.
5546    This is an optimization for when we already have the abbrev table.
5547
5548    If USE_EXISTING_CU is non-zero, and THIS_CU->cu is non-NULL, then use it.
5549    Otherwise, a new CU is allocated with xmalloc.
5550
5551    If KEEP is non-zero, then if we allocated a dwarf2_cu we add it to
5552    read_in_chain.  Otherwise the dwarf2_cu data is freed at the end.
5553
5554    WARNING: If THIS_CU is a "dummy CU" (used as filler by the incremental
5555    linker) then DIE_READER_FUNC will not get called.  */
5556
5557 static void
5558 init_cutu_and_read_dies (struct dwarf2_per_cu_data *this_cu,
5559                          struct abbrev_table *abbrev_table,
5560                          int use_existing_cu, int keep,
5561                          die_reader_func_ftype *die_reader_func,
5562                          void *data)
5563 {
5564   struct objfile *objfile = dwarf2_per_objfile->objfile;
5565   struct dwarf2_section_info *section = this_cu->section;
5566   bfd *abfd = get_section_bfd_owner (section);
5567   struct dwarf2_cu *cu;
5568   const gdb_byte *begin_info_ptr, *info_ptr;
5569   struct die_reader_specs reader;
5570   struct die_info *comp_unit_die;
5571   int has_children;
5572   struct attribute *attr;
5573   struct cleanup *cleanups, *free_cu_cleanup = NULL;
5574   struct signatured_type *sig_type = NULL;
5575   struct dwarf2_section_info *abbrev_section;
5576   /* Non-zero if CU currently points to a DWO file and we need to
5577      reread it.  When this happens we need to reread the skeleton die
5578      before we can reread the DWO file (this only applies to CUs, not TUs).  */
5579   int rereading_dwo_cu = 0;
5580
5581   if (dwarf_die_debug)
5582     fprintf_unfiltered (gdb_stdlog, "Reading %s unit at offset 0x%x\n",
5583                         this_cu->is_debug_types ? "type" : "comp",
5584                         this_cu->offset.sect_off);
5585
5586   if (use_existing_cu)
5587     gdb_assert (keep);
5588
5589   /* If we're reading a TU directly from a DWO file, including a virtual DWO
5590      file (instead of going through the stub), short-circuit all of this.  */
5591   if (this_cu->reading_dwo_directly)
5592     {
5593       /* Narrow down the scope of possibilities to have to understand.  */
5594       gdb_assert (this_cu->is_debug_types);
5595       gdb_assert (abbrev_table == NULL);
5596       init_tu_and_read_dwo_dies (this_cu, use_existing_cu, keep,
5597                                  die_reader_func, data);
5598       return;
5599     }
5600
5601   cleanups = make_cleanup (null_cleanup, NULL);
5602
5603   /* This is cheap if the section is already read in.  */
5604   dwarf2_read_section (objfile, section);
5605
5606   begin_info_ptr = info_ptr = section->buffer + this_cu->offset.sect_off;
5607
5608   abbrev_section = get_abbrev_section_for_cu (this_cu);
5609
5610   if (use_existing_cu && this_cu->cu != NULL)
5611     {
5612       cu = this_cu->cu;
5613       /* If this CU is from a DWO file we need to start over, we need to
5614          refetch the attributes from the skeleton CU.
5615          This could be optimized by retrieving those attributes from when we
5616          were here the first time: the previous comp_unit_die was stored in
5617          comp_unit_obstack.  But there's no data yet that we need this
5618          optimization.  */
5619       if (cu->dwo_unit != NULL)
5620         rereading_dwo_cu = 1;
5621     }
5622   else
5623     {
5624       /* If !use_existing_cu, this_cu->cu must be NULL.  */
5625       gdb_assert (this_cu->cu == NULL);
5626       cu = XNEW (struct dwarf2_cu);
5627       init_one_comp_unit (cu, this_cu);
5628       /* If an error occurs while loading, release our storage.  */
5629       free_cu_cleanup = make_cleanup (free_heap_comp_unit, cu);
5630     }
5631
5632   /* Get the header.  */
5633   if (cu->header.first_die_offset.cu_off != 0 && ! rereading_dwo_cu)
5634     {
5635       /* We already have the header, there's no need to read it in again.  */
5636       info_ptr += cu->header.first_die_offset.cu_off;
5637     }
5638   else
5639     {
5640       if (this_cu->is_debug_types)
5641         {
5642           info_ptr = read_and_check_comp_unit_head (&cu->header, section,
5643                                                     abbrev_section, info_ptr,
5644                                                     rcuh_kind::TYPE);
5645
5646           /* Since per_cu is the first member of struct signatured_type,
5647              we can go from a pointer to one to a pointer to the other.  */
5648           sig_type = (struct signatured_type *) this_cu;
5649           gdb_assert (sig_type->signature == cu->header.signature);
5650           gdb_assert (sig_type->type_offset_in_tu.cu_off
5651                       == cu->header.type_offset_in_tu.cu_off);
5652           gdb_assert (this_cu->offset.sect_off == cu->header.offset.sect_off);
5653
5654           /* LENGTH has not been set yet for type units if we're
5655              using .gdb_index.  */
5656           this_cu->length = get_cu_length (&cu->header);
5657
5658           /* Establish the type offset that can be used to lookup the type.  */
5659           sig_type->type_offset_in_section.sect_off =
5660             this_cu->offset.sect_off + sig_type->type_offset_in_tu.cu_off;
5661
5662           this_cu->dwarf_version = cu->header.version;
5663         }
5664       else
5665         {
5666           info_ptr = read_and_check_comp_unit_head (&cu->header, section,
5667                                                     abbrev_section,
5668                                                     info_ptr,
5669                                                     rcuh_kind::COMPILE);
5670
5671           gdb_assert (this_cu->offset.sect_off == cu->header.offset.sect_off);
5672           gdb_assert (this_cu->length == get_cu_length (&cu->header));
5673           this_cu->dwarf_version = cu->header.version;
5674         }
5675     }
5676
5677   /* Skip dummy compilation units.  */
5678   if (info_ptr >= begin_info_ptr + this_cu->length
5679       || peek_abbrev_code (abfd, info_ptr) == 0)
5680     {
5681       do_cleanups (cleanups);
5682       return;
5683     }
5684
5685   /* If we don't have them yet, read the abbrevs for this compilation unit.
5686      And if we need to read them now, make sure they're freed when we're
5687      done.  Note that it's important that if the CU had an abbrev table
5688      on entry we don't free it when we're done: Somewhere up the call stack
5689      it may be in use.  */
5690   if (abbrev_table != NULL)
5691     {
5692       gdb_assert (cu->abbrev_table == NULL);
5693       gdb_assert (cu->header.abbrev_offset.sect_off
5694                   == abbrev_table->offset.sect_off);
5695       cu->abbrev_table = abbrev_table;
5696     }
5697   else if (cu->abbrev_table == NULL)
5698     {
5699       dwarf2_read_abbrevs (cu, abbrev_section);
5700       make_cleanup (dwarf2_free_abbrev_table, cu);
5701     }
5702   else if (rereading_dwo_cu)
5703     {
5704       dwarf2_free_abbrev_table (cu);
5705       dwarf2_read_abbrevs (cu, abbrev_section);
5706     }
5707
5708   /* Read the top level CU/TU die.  */
5709   init_cu_die_reader (&reader, cu, section, NULL);
5710   info_ptr = read_full_die (&reader, &comp_unit_die, info_ptr, &has_children);
5711
5712   /* If we are in a DWO stub, process it and then read in the "real" CU/TU
5713      from the DWO file.
5714      Note that if USE_EXISTING_OK != 0, and THIS_CU->cu already contains a
5715      DWO CU, that this test will fail (the attribute will not be present).  */
5716   attr = dwarf2_attr (comp_unit_die, DW_AT_GNU_dwo_name, cu);
5717   if (attr)
5718     {
5719       struct dwo_unit *dwo_unit;
5720       struct die_info *dwo_comp_unit_die;
5721
5722       if (has_children)
5723         {
5724           complaint (&symfile_complaints,
5725                      _("compilation unit with DW_AT_GNU_dwo_name"
5726                        " has children (offset 0x%x) [in module %s]"),
5727                      this_cu->offset.sect_off, bfd_get_filename (abfd));
5728         }
5729       dwo_unit = lookup_dwo_unit (this_cu, comp_unit_die);
5730       if (dwo_unit != NULL)
5731         {
5732           if (read_cutu_die_from_dwo (this_cu, dwo_unit,
5733                                       abbrev_table != NULL,
5734                                       comp_unit_die, NULL,
5735                                       &reader, &info_ptr,
5736                                       &dwo_comp_unit_die, &has_children) == 0)
5737             {
5738               /* Dummy die.  */
5739               do_cleanups (cleanups);
5740               return;
5741             }
5742           comp_unit_die = dwo_comp_unit_die;
5743         }
5744       else
5745         {
5746           /* Yikes, we couldn't find the rest of the DIE, we only have
5747              the stub.  A complaint has already been logged.  There's
5748              not much more we can do except pass on the stub DIE to
5749              die_reader_func.  We don't want to throw an error on bad
5750              debug info.  */
5751         }
5752     }
5753
5754   /* All of the above is setup for this call.  Yikes.  */
5755   die_reader_func (&reader, info_ptr, comp_unit_die, has_children, data);
5756
5757   /* Done, clean up.  */
5758   if (free_cu_cleanup != NULL)
5759     {
5760       if (keep)
5761         {
5762           /* We've successfully allocated this compilation unit.  Let our
5763              caller clean it up when finished with it.  */
5764           discard_cleanups (free_cu_cleanup);
5765
5766           /* We can only discard free_cu_cleanup and all subsequent cleanups.
5767              So we have to manually free the abbrev table.  */
5768           dwarf2_free_abbrev_table (cu);
5769
5770           /* Link this CU into read_in_chain.  */
5771           this_cu->cu->read_in_chain = dwarf2_per_objfile->read_in_chain;
5772           dwarf2_per_objfile->read_in_chain = this_cu;
5773         }
5774       else
5775         do_cleanups (free_cu_cleanup);
5776     }
5777
5778   do_cleanups (cleanups);
5779 }
5780
5781 /* Read CU/TU THIS_CU but do not follow DW_AT_GNU_dwo_name if present.
5782    DWO_FILE, if non-NULL, is the DWO file to read (the caller is assumed
5783    to have already done the lookup to find the DWO file).
5784
5785    The caller is required to fill in THIS_CU->section, THIS_CU->offset, and
5786    THIS_CU->is_debug_types, but nothing else.
5787
5788    We fill in THIS_CU->length.
5789
5790    WARNING: If THIS_CU is a "dummy CU" (used as filler by the incremental
5791    linker) then DIE_READER_FUNC will not get called.
5792
5793    THIS_CU->cu is always freed when done.
5794    This is done in order to not leave THIS_CU->cu in a state where we have
5795    to care whether it refers to the "main" CU or the DWO CU.  */
5796
5797 static void
5798 init_cutu_and_read_dies_no_follow (struct dwarf2_per_cu_data *this_cu,
5799                                    struct dwo_file *dwo_file,
5800                                    die_reader_func_ftype *die_reader_func,
5801                                    void *data)
5802 {
5803   struct objfile *objfile = dwarf2_per_objfile->objfile;
5804   struct dwarf2_section_info *section = this_cu->section;
5805   bfd *abfd = get_section_bfd_owner (section);
5806   struct dwarf2_section_info *abbrev_section;
5807   struct dwarf2_cu cu;
5808   const gdb_byte *begin_info_ptr, *info_ptr;
5809   struct die_reader_specs reader;
5810   struct cleanup *cleanups;
5811   struct die_info *comp_unit_die;
5812   int has_children;
5813
5814   if (dwarf_die_debug)
5815     fprintf_unfiltered (gdb_stdlog, "Reading %s unit at offset 0x%x\n",
5816                         this_cu->is_debug_types ? "type" : "comp",
5817                         this_cu->offset.sect_off);
5818
5819   gdb_assert (this_cu->cu == NULL);
5820
5821   abbrev_section = (dwo_file != NULL
5822                     ? &dwo_file->sections.abbrev
5823                     : get_abbrev_section_for_cu (this_cu));
5824
5825   /* This is cheap if the section is already read in.  */
5826   dwarf2_read_section (objfile, section);
5827
5828   init_one_comp_unit (&cu, this_cu);
5829
5830   cleanups = make_cleanup (free_stack_comp_unit, &cu);
5831
5832   begin_info_ptr = info_ptr = section->buffer + this_cu->offset.sect_off;
5833   info_ptr = read_and_check_comp_unit_head (&cu.header, section,
5834                                             abbrev_section, info_ptr,
5835                                             (this_cu->is_debug_types
5836                                              ? rcuh_kind::TYPE
5837                                              : rcuh_kind::COMPILE));
5838
5839   this_cu->length = get_cu_length (&cu.header);
5840
5841   /* Skip dummy compilation units.  */
5842   if (info_ptr >= begin_info_ptr + this_cu->length
5843       || peek_abbrev_code (abfd, info_ptr) == 0)
5844     {
5845       do_cleanups (cleanups);
5846       return;
5847     }
5848
5849   dwarf2_read_abbrevs (&cu, abbrev_section);
5850   make_cleanup (dwarf2_free_abbrev_table, &cu);
5851
5852   init_cu_die_reader (&reader, &cu, section, dwo_file);
5853   info_ptr = read_full_die (&reader, &comp_unit_die, info_ptr, &has_children);
5854
5855   die_reader_func (&reader, info_ptr, comp_unit_die, has_children, data);
5856
5857   do_cleanups (cleanups);
5858 }
5859
5860 /* Read a CU/TU, except that this does not look for DW_AT_GNU_dwo_name and
5861    does not lookup the specified DWO file.
5862    This cannot be used to read DWO files.
5863
5864    THIS_CU->cu is always freed when done.
5865    This is done in order to not leave THIS_CU->cu in a state where we have
5866    to care whether it refers to the "main" CU or the DWO CU.
5867    We can revisit this if the data shows there's a performance issue.  */
5868
5869 static void
5870 init_cutu_and_read_dies_simple (struct dwarf2_per_cu_data *this_cu,
5871                                 die_reader_func_ftype *die_reader_func,
5872                                 void *data)
5873 {
5874   init_cutu_and_read_dies_no_follow (this_cu, NULL, die_reader_func, data);
5875 }
5876 \f
5877 /* Type Unit Groups.
5878
5879    Type Unit Groups are a way to collapse the set of all TUs (type units) into
5880    a more manageable set.  The grouping is done by DW_AT_stmt_list entry
5881    so that all types coming from the same compilation (.o file) are grouped
5882    together.  A future step could be to put the types in the same symtab as
5883    the CU the types ultimately came from.  */
5884
5885 static hashval_t
5886 hash_type_unit_group (const void *item)
5887 {
5888   const struct type_unit_group *tu_group
5889     = (const struct type_unit_group *) item;
5890
5891   return hash_stmt_list_entry (&tu_group->hash);
5892 }
5893
5894 static int
5895 eq_type_unit_group (const void *item_lhs, const void *item_rhs)
5896 {
5897   const struct type_unit_group *lhs = (const struct type_unit_group *) item_lhs;
5898   const struct type_unit_group *rhs = (const struct type_unit_group *) item_rhs;
5899
5900   return eq_stmt_list_entry (&lhs->hash, &rhs->hash);
5901 }
5902
5903 /* Allocate a hash table for type unit groups.  */
5904
5905 static htab_t
5906 allocate_type_unit_groups_table (void)
5907 {
5908   return htab_create_alloc_ex (3,
5909                                hash_type_unit_group,
5910                                eq_type_unit_group,
5911                                NULL,
5912                                &dwarf2_per_objfile->objfile->objfile_obstack,
5913                                hashtab_obstack_allocate,
5914                                dummy_obstack_deallocate);
5915 }
5916
5917 /* Type units that don't have DW_AT_stmt_list are grouped into their own
5918    partial symtabs.  We combine several TUs per psymtab to not let the size
5919    of any one psymtab grow too big.  */
5920 #define NO_STMT_LIST_TYPE_UNIT_PSYMTAB (1 << 31)
5921 #define NO_STMT_LIST_TYPE_UNIT_PSYMTAB_SIZE 10
5922
5923 /* Helper routine for get_type_unit_group.
5924    Create the type_unit_group object used to hold one or more TUs.  */
5925
5926 static struct type_unit_group *
5927 create_type_unit_group (struct dwarf2_cu *cu, sect_offset line_offset_struct)
5928 {
5929   struct objfile *objfile = dwarf2_per_objfile->objfile;
5930   struct dwarf2_per_cu_data *per_cu;
5931   struct type_unit_group *tu_group;
5932
5933   tu_group = OBSTACK_ZALLOC (&objfile->objfile_obstack,
5934                              struct type_unit_group);
5935   per_cu = &tu_group->per_cu;
5936   per_cu->objfile = objfile;
5937
5938   if (dwarf2_per_objfile->using_index)
5939     {
5940       per_cu->v.quick = OBSTACK_ZALLOC (&objfile->objfile_obstack,
5941                                         struct dwarf2_per_cu_quick_data);
5942     }
5943   else
5944     {
5945       unsigned int line_offset = line_offset_struct.sect_off;
5946       struct partial_symtab *pst;
5947       char *name;
5948
5949       /* Give the symtab a useful name for debug purposes.  */
5950       if ((line_offset & NO_STMT_LIST_TYPE_UNIT_PSYMTAB) != 0)
5951         name = xstrprintf ("<type_units_%d>",
5952                            (line_offset & ~NO_STMT_LIST_TYPE_UNIT_PSYMTAB));
5953       else
5954         name = xstrprintf ("<type_units_at_0x%x>", line_offset);
5955
5956       pst = create_partial_symtab (per_cu, name);
5957       pst->anonymous = 1;
5958
5959       xfree (name);
5960     }
5961
5962   tu_group->hash.dwo_unit = cu->dwo_unit;
5963   tu_group->hash.line_offset = line_offset_struct;
5964
5965   return tu_group;
5966 }
5967
5968 /* Look up the type_unit_group for type unit CU, and create it if necessary.
5969    STMT_LIST is a DW_AT_stmt_list attribute.  */
5970
5971 static struct type_unit_group *
5972 get_type_unit_group (struct dwarf2_cu *cu, const struct attribute *stmt_list)
5973 {
5974   struct tu_stats *tu_stats = &dwarf2_per_objfile->tu_stats;
5975   struct type_unit_group *tu_group;
5976   void **slot;
5977   unsigned int line_offset;
5978   struct type_unit_group type_unit_group_for_lookup;
5979
5980   if (dwarf2_per_objfile->type_unit_groups == NULL)
5981     {
5982       dwarf2_per_objfile->type_unit_groups =
5983         allocate_type_unit_groups_table ();
5984     }
5985
5986   /* Do we need to create a new group, or can we use an existing one?  */
5987
5988   if (stmt_list)
5989     {
5990       line_offset = DW_UNSND (stmt_list);
5991       ++tu_stats->nr_symtab_sharers;
5992     }
5993   else
5994     {
5995       /* Ugh, no stmt_list.  Rare, but we have to handle it.
5996          We can do various things here like create one group per TU or
5997          spread them over multiple groups to split up the expansion work.
5998          To avoid worst case scenarios (too many groups or too large groups)
5999          we, umm, group them in bunches.  */
6000       line_offset = (NO_STMT_LIST_TYPE_UNIT_PSYMTAB
6001                      | (tu_stats->nr_stmt_less_type_units
6002                         / NO_STMT_LIST_TYPE_UNIT_PSYMTAB_SIZE));
6003       ++tu_stats->nr_stmt_less_type_units;
6004     }
6005
6006   type_unit_group_for_lookup.hash.dwo_unit = cu->dwo_unit;
6007   type_unit_group_for_lookup.hash.line_offset.sect_off = line_offset;
6008   slot = htab_find_slot (dwarf2_per_objfile->type_unit_groups,
6009                          &type_unit_group_for_lookup, INSERT);
6010   if (*slot != NULL)
6011     {
6012       tu_group = (struct type_unit_group *) *slot;
6013       gdb_assert (tu_group != NULL);
6014     }
6015   else
6016     {
6017       sect_offset line_offset_struct;
6018
6019       line_offset_struct.sect_off = line_offset;
6020       tu_group = create_type_unit_group (cu, line_offset_struct);
6021       *slot = tu_group;
6022       ++tu_stats->nr_symtabs;
6023     }
6024
6025   return tu_group;
6026 }
6027 \f
6028 /* Partial symbol tables.  */
6029
6030 /* Create a psymtab named NAME and assign it to PER_CU.
6031
6032    The caller must fill in the following details:
6033    dirname, textlow, texthigh.  */
6034
6035 static struct partial_symtab *
6036 create_partial_symtab (struct dwarf2_per_cu_data *per_cu, const char *name)
6037 {
6038   struct objfile *objfile = per_cu->objfile;
6039   struct partial_symtab *pst;
6040
6041   pst = start_psymtab_common (objfile, name, 0,
6042                               objfile->global_psymbols.next,
6043                               objfile->static_psymbols.next);
6044
6045   pst->psymtabs_addrmap_supported = 1;
6046
6047   /* This is the glue that links PST into GDB's symbol API.  */
6048   pst->read_symtab_private = per_cu;
6049   pst->read_symtab = dwarf2_read_symtab;
6050   per_cu->v.psymtab = pst;
6051
6052   return pst;
6053 }
6054
6055 /* The DATA object passed to process_psymtab_comp_unit_reader has this
6056    type.  */
6057
6058 struct process_psymtab_comp_unit_data
6059 {
6060   /* True if we are reading a DW_TAG_partial_unit.  */
6061
6062   int want_partial_unit;
6063
6064   /* The "pretend" language that is used if the CU doesn't declare a
6065      language.  */
6066
6067   enum language pretend_language;
6068 };
6069
6070 /* die_reader_func for process_psymtab_comp_unit.  */
6071
6072 static void
6073 process_psymtab_comp_unit_reader (const struct die_reader_specs *reader,
6074                                   const gdb_byte *info_ptr,
6075                                   struct die_info *comp_unit_die,
6076                                   int has_children,
6077                                   void *data)
6078 {
6079   struct dwarf2_cu *cu = reader->cu;
6080   struct objfile *objfile = cu->objfile;
6081   struct gdbarch *gdbarch = get_objfile_arch (objfile);
6082   struct dwarf2_per_cu_data *per_cu = cu->per_cu;
6083   CORE_ADDR baseaddr;
6084   CORE_ADDR best_lowpc = 0, best_highpc = 0;
6085   struct partial_symtab *pst;
6086   enum pc_bounds_kind cu_bounds_kind;
6087   const char *filename;
6088   struct process_psymtab_comp_unit_data *info
6089     = (struct process_psymtab_comp_unit_data *) data;
6090
6091   if (comp_unit_die->tag == DW_TAG_partial_unit && !info->want_partial_unit)
6092     return;
6093
6094   gdb_assert (! per_cu->is_debug_types);
6095
6096   prepare_one_comp_unit (cu, comp_unit_die, info->pretend_language);
6097
6098   cu->list_in_scope = &file_symbols;
6099
6100   /* Allocate a new partial symbol table structure.  */
6101   filename = dwarf2_string_attr (comp_unit_die, DW_AT_name, cu);
6102   if (filename == NULL)
6103     filename = "";
6104
6105   pst = create_partial_symtab (per_cu, filename);
6106
6107   /* This must be done before calling dwarf2_build_include_psymtabs.  */
6108   pst->dirname = dwarf2_string_attr (comp_unit_die, DW_AT_comp_dir, cu);
6109
6110   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
6111
6112   dwarf2_find_base_address (comp_unit_die, cu);
6113
6114   /* Possibly set the default values of LOWPC and HIGHPC from
6115      `DW_AT_ranges'.  */
6116   cu_bounds_kind = dwarf2_get_pc_bounds (comp_unit_die, &best_lowpc,
6117                                          &best_highpc, cu, pst);
6118   if (cu_bounds_kind == PC_BOUNDS_HIGH_LOW && best_lowpc < best_highpc)
6119     /* Store the contiguous range if it is not empty; it can be empty for
6120        CUs with no code.  */
6121     addrmap_set_empty (objfile->psymtabs_addrmap,
6122                        gdbarch_adjust_dwarf2_addr (gdbarch,
6123                                                    best_lowpc + baseaddr),
6124                        gdbarch_adjust_dwarf2_addr (gdbarch,
6125                                                    best_highpc + baseaddr) - 1,
6126                        pst);
6127
6128   /* Check if comp unit has_children.
6129      If so, read the rest of the partial symbols from this comp unit.
6130      If not, there's no more debug_info for this comp unit.  */
6131   if (has_children)
6132     {
6133       struct partial_die_info *first_die;
6134       CORE_ADDR lowpc, highpc;
6135
6136       lowpc = ((CORE_ADDR) -1);
6137       highpc = ((CORE_ADDR) 0);
6138
6139       first_die = load_partial_dies (reader, info_ptr, 1);
6140
6141       scan_partial_symbols (first_die, &lowpc, &highpc,
6142                             cu_bounds_kind <= PC_BOUNDS_INVALID, cu);
6143
6144       /* If we didn't find a lowpc, set it to highpc to avoid
6145          complaints from `maint check'.  */
6146       if (lowpc == ((CORE_ADDR) -1))
6147         lowpc = highpc;
6148
6149       /* If the compilation unit didn't have an explicit address range,
6150          then use the information extracted from its child dies.  */
6151       if (cu_bounds_kind <= PC_BOUNDS_INVALID)
6152         {
6153           best_lowpc = lowpc;
6154           best_highpc = highpc;
6155         }
6156     }
6157   pst->textlow = gdbarch_adjust_dwarf2_addr (gdbarch, best_lowpc + baseaddr);
6158   pst->texthigh = gdbarch_adjust_dwarf2_addr (gdbarch, best_highpc + baseaddr);
6159
6160   end_psymtab_common (objfile, pst);
6161
6162   if (!VEC_empty (dwarf2_per_cu_ptr, cu->per_cu->imported_symtabs))
6163     {
6164       int i;
6165       int len = VEC_length (dwarf2_per_cu_ptr, cu->per_cu->imported_symtabs);
6166       struct dwarf2_per_cu_data *iter;
6167
6168       /* Fill in 'dependencies' here; we fill in 'users' in a
6169          post-pass.  */
6170       pst->number_of_dependencies = len;
6171       pst->dependencies =
6172         XOBNEWVEC (&objfile->objfile_obstack, struct partial_symtab *, len);
6173       for (i = 0;
6174            VEC_iterate (dwarf2_per_cu_ptr, cu->per_cu->imported_symtabs,
6175                         i, iter);
6176            ++i)
6177         pst->dependencies[i] = iter->v.psymtab;
6178
6179       VEC_free (dwarf2_per_cu_ptr, cu->per_cu->imported_symtabs);
6180     }
6181
6182   /* Get the list of files included in the current compilation unit,
6183      and build a psymtab for each of them.  */
6184   dwarf2_build_include_psymtabs (cu, comp_unit_die, pst);
6185
6186   if (dwarf_read_debug)
6187     {
6188       struct gdbarch *gdbarch = get_objfile_arch (objfile);
6189
6190       fprintf_unfiltered (gdb_stdlog,
6191                           "Psymtab for %s unit @0x%x: %s - %s"
6192                           ", %d global, %d static syms\n",
6193                           per_cu->is_debug_types ? "type" : "comp",
6194                           per_cu->offset.sect_off,
6195                           paddress (gdbarch, pst->textlow),
6196                           paddress (gdbarch, pst->texthigh),
6197                           pst->n_global_syms, pst->n_static_syms);
6198     }
6199 }
6200
6201 /* Subroutine of dwarf2_build_psymtabs_hard to simplify it.
6202    Process compilation unit THIS_CU for a psymtab.  */
6203
6204 static void
6205 process_psymtab_comp_unit (struct dwarf2_per_cu_data *this_cu,
6206                            int want_partial_unit,
6207                            enum language pretend_language)
6208 {
6209   struct process_psymtab_comp_unit_data info;
6210
6211   /* If this compilation unit was already read in, free the
6212      cached copy in order to read it in again.  This is
6213      necessary because we skipped some symbols when we first
6214      read in the compilation unit (see load_partial_dies).
6215      This problem could be avoided, but the benefit is unclear.  */
6216   if (this_cu->cu != NULL)
6217     free_one_cached_comp_unit (this_cu);
6218
6219   gdb_assert (! this_cu->is_debug_types);
6220   info.want_partial_unit = want_partial_unit;
6221   info.pretend_language = pretend_language;
6222   init_cutu_and_read_dies (this_cu, NULL, 0, 0,
6223                            process_psymtab_comp_unit_reader,
6224                            &info);
6225
6226   /* Age out any secondary CUs.  */
6227   age_cached_comp_units ();
6228 }
6229
6230 /* Reader function for build_type_psymtabs.  */
6231
6232 static void
6233 build_type_psymtabs_reader (const struct die_reader_specs *reader,
6234                             const gdb_byte *info_ptr,
6235                             struct die_info *type_unit_die,
6236                             int has_children,
6237                             void *data)
6238 {
6239   struct objfile *objfile = dwarf2_per_objfile->objfile;
6240   struct dwarf2_cu *cu = reader->cu;
6241   struct dwarf2_per_cu_data *per_cu = cu->per_cu;
6242   struct signatured_type *sig_type;
6243   struct type_unit_group *tu_group;
6244   struct attribute *attr;
6245   struct partial_die_info *first_die;
6246   CORE_ADDR lowpc, highpc;
6247   struct partial_symtab *pst;
6248
6249   gdb_assert (data == NULL);
6250   gdb_assert (per_cu->is_debug_types);
6251   sig_type = (struct signatured_type *) per_cu;
6252
6253   if (! has_children)
6254     return;
6255
6256   attr = dwarf2_attr_no_follow (type_unit_die, DW_AT_stmt_list);
6257   tu_group = get_type_unit_group (cu, attr);
6258
6259   VEC_safe_push (sig_type_ptr, tu_group->tus, sig_type);
6260
6261   prepare_one_comp_unit (cu, type_unit_die, language_minimal);
6262   cu->list_in_scope = &file_symbols;
6263   pst = create_partial_symtab (per_cu, "");
6264   pst->anonymous = 1;
6265
6266   first_die = load_partial_dies (reader, info_ptr, 1);
6267
6268   lowpc = (CORE_ADDR) -1;
6269   highpc = (CORE_ADDR) 0;
6270   scan_partial_symbols (first_die, &lowpc, &highpc, 0, cu);
6271
6272   end_psymtab_common (objfile, pst);
6273 }
6274
6275 /* Struct used to sort TUs by their abbreviation table offset.  */
6276
6277 struct tu_abbrev_offset
6278 {
6279   struct signatured_type *sig_type;
6280   sect_offset abbrev_offset;
6281 };
6282
6283 /* Helper routine for build_type_psymtabs_1, passed to qsort.  */
6284
6285 static int
6286 sort_tu_by_abbrev_offset (const void *ap, const void *bp)
6287 {
6288   const struct tu_abbrev_offset * const *a
6289     = (const struct tu_abbrev_offset * const*) ap;
6290   const struct tu_abbrev_offset * const *b
6291     = (const struct tu_abbrev_offset * const*) bp;
6292   unsigned int aoff = (*a)->abbrev_offset.sect_off;
6293   unsigned int boff = (*b)->abbrev_offset.sect_off;
6294
6295   return (aoff > boff) - (aoff < boff);
6296 }
6297
6298 /* Efficiently read all the type units.
6299    This does the bulk of the work for build_type_psymtabs.
6300
6301    The efficiency is because we sort TUs by the abbrev table they use and
6302    only read each abbrev table once.  In one program there are 200K TUs
6303    sharing 8K abbrev tables.
6304
6305    The main purpose of this function is to support building the
6306    dwarf2_per_objfile->type_unit_groups table.
6307    TUs typically share the DW_AT_stmt_list of the CU they came from, so we
6308    can collapse the search space by grouping them by stmt_list.
6309    The savings can be significant, in the same program from above the 200K TUs
6310    share 8K stmt_list tables.
6311
6312    FUNC is expected to call get_type_unit_group, which will create the
6313    struct type_unit_group if necessary and add it to
6314    dwarf2_per_objfile->type_unit_groups.  */
6315
6316 static void
6317 build_type_psymtabs_1 (void)
6318 {
6319   struct tu_stats *tu_stats = &dwarf2_per_objfile->tu_stats;
6320   struct cleanup *cleanups;
6321   struct abbrev_table *abbrev_table;
6322   sect_offset abbrev_offset;
6323   struct tu_abbrev_offset *sorted_by_abbrev;
6324   int i;
6325
6326   /* It's up to the caller to not call us multiple times.  */
6327   gdb_assert (dwarf2_per_objfile->type_unit_groups == NULL);
6328
6329   if (dwarf2_per_objfile->n_type_units == 0)
6330     return;
6331
6332   /* TUs typically share abbrev tables, and there can be way more TUs than
6333      abbrev tables.  Sort by abbrev table to reduce the number of times we
6334      read each abbrev table in.
6335      Alternatives are to punt or to maintain a cache of abbrev tables.
6336      This is simpler and efficient enough for now.
6337
6338      Later we group TUs by their DW_AT_stmt_list value (as this defines the
6339      symtab to use).  Typically TUs with the same abbrev offset have the same
6340      stmt_list value too so in practice this should work well.
6341
6342      The basic algorithm here is:
6343
6344       sort TUs by abbrev table
6345       for each TU with same abbrev table:
6346         read abbrev table if first user
6347         read TU top level DIE
6348           [IWBN if DWO skeletons had DW_AT_stmt_list]
6349         call FUNC  */
6350
6351   if (dwarf_read_debug)
6352     fprintf_unfiltered (gdb_stdlog, "Building type unit groups ...\n");
6353
6354   /* Sort in a separate table to maintain the order of all_type_units
6355      for .gdb_index: TU indices directly index all_type_units.  */
6356   sorted_by_abbrev = XNEWVEC (struct tu_abbrev_offset,
6357                               dwarf2_per_objfile->n_type_units);
6358   for (i = 0; i < dwarf2_per_objfile->n_type_units; ++i)
6359     {
6360       struct signatured_type *sig_type = dwarf2_per_objfile->all_type_units[i];
6361
6362       sorted_by_abbrev[i].sig_type = sig_type;
6363       sorted_by_abbrev[i].abbrev_offset =
6364         read_abbrev_offset (sig_type->per_cu.section,
6365                             sig_type->per_cu.offset);
6366     }
6367   cleanups = make_cleanup (xfree, sorted_by_abbrev);
6368   qsort (sorted_by_abbrev, dwarf2_per_objfile->n_type_units,
6369          sizeof (struct tu_abbrev_offset), sort_tu_by_abbrev_offset);
6370
6371   abbrev_offset.sect_off = ~(unsigned) 0;
6372   abbrev_table = NULL;
6373   make_cleanup (abbrev_table_free_cleanup, &abbrev_table);
6374
6375   for (i = 0; i < dwarf2_per_objfile->n_type_units; ++i)
6376     {
6377       const struct tu_abbrev_offset *tu = &sorted_by_abbrev[i];
6378
6379       /* Switch to the next abbrev table if necessary.  */
6380       if (abbrev_table == NULL
6381           || tu->abbrev_offset.sect_off != abbrev_offset.sect_off)
6382         {
6383           if (abbrev_table != NULL)
6384             {
6385               abbrev_table_free (abbrev_table);
6386               /* Reset to NULL in case abbrev_table_read_table throws
6387                  an error: abbrev_table_free_cleanup will get called.  */
6388               abbrev_table = NULL;
6389             }
6390           abbrev_offset = tu->abbrev_offset;
6391           abbrev_table =
6392             abbrev_table_read_table (&dwarf2_per_objfile->abbrev,
6393                                      abbrev_offset);
6394           ++tu_stats->nr_uniq_abbrev_tables;
6395         }
6396
6397       init_cutu_and_read_dies (&tu->sig_type->per_cu, abbrev_table, 0, 0,
6398                                build_type_psymtabs_reader, NULL);
6399     }
6400
6401   do_cleanups (cleanups);
6402 }
6403
6404 /* Print collected type unit statistics.  */
6405
6406 static void
6407 print_tu_stats (void)
6408 {
6409   struct tu_stats *tu_stats = &dwarf2_per_objfile->tu_stats;
6410
6411   fprintf_unfiltered (gdb_stdlog, "Type unit statistics:\n");
6412   fprintf_unfiltered (gdb_stdlog, "  %d TUs\n",
6413                       dwarf2_per_objfile->n_type_units);
6414   fprintf_unfiltered (gdb_stdlog, "  %d uniq abbrev tables\n",
6415                       tu_stats->nr_uniq_abbrev_tables);
6416   fprintf_unfiltered (gdb_stdlog, "  %d symtabs from stmt_list entries\n",
6417                       tu_stats->nr_symtabs);
6418   fprintf_unfiltered (gdb_stdlog, "  %d symtab sharers\n",
6419                       tu_stats->nr_symtab_sharers);
6420   fprintf_unfiltered (gdb_stdlog, "  %d type units without a stmt_list\n",
6421                       tu_stats->nr_stmt_less_type_units);
6422   fprintf_unfiltered (gdb_stdlog, "  %d all_type_units reallocs\n",
6423                       tu_stats->nr_all_type_units_reallocs);
6424 }
6425
6426 /* Traversal function for build_type_psymtabs.  */
6427
6428 static int
6429 build_type_psymtab_dependencies (void **slot, void *info)
6430 {
6431   struct objfile *objfile = dwarf2_per_objfile->objfile;
6432   struct type_unit_group *tu_group = (struct type_unit_group *) *slot;
6433   struct dwarf2_per_cu_data *per_cu = &tu_group->per_cu;
6434   struct partial_symtab *pst = per_cu->v.psymtab;
6435   int len = VEC_length (sig_type_ptr, tu_group->tus);
6436   struct signatured_type *iter;
6437   int i;
6438
6439   gdb_assert (len > 0);
6440   gdb_assert (IS_TYPE_UNIT_GROUP (per_cu));
6441
6442   pst->number_of_dependencies = len;
6443   pst->dependencies =
6444     XOBNEWVEC (&objfile->objfile_obstack, struct partial_symtab *, len);
6445   for (i = 0;
6446        VEC_iterate (sig_type_ptr, tu_group->tus, i, iter);
6447        ++i)
6448     {
6449       gdb_assert (iter->per_cu.is_debug_types);
6450       pst->dependencies[i] = iter->per_cu.v.psymtab;
6451       iter->type_unit_group = tu_group;
6452     }
6453
6454   VEC_free (sig_type_ptr, tu_group->tus);
6455
6456   return 1;
6457 }
6458
6459 /* Subroutine of dwarf2_build_psymtabs_hard to simplify it.
6460    Build partial symbol tables for the .debug_types comp-units.  */
6461
6462 static void
6463 build_type_psymtabs (struct objfile *objfile)
6464 {
6465   if (! create_all_type_units (objfile))
6466     return;
6467
6468   build_type_psymtabs_1 ();
6469 }
6470
6471 /* Traversal function for process_skeletonless_type_unit.
6472    Read a TU in a DWO file and build partial symbols for it.  */
6473
6474 static int
6475 process_skeletonless_type_unit (void **slot, void *info)
6476 {
6477   struct dwo_unit *dwo_unit = (struct dwo_unit *) *slot;
6478   struct objfile *objfile = (struct objfile *) info;
6479   struct signatured_type find_entry, *entry;
6480
6481   /* If this TU doesn't exist in the global table, add it and read it in.  */
6482
6483   if (dwarf2_per_objfile->signatured_types == NULL)
6484     {
6485       dwarf2_per_objfile->signatured_types
6486         = allocate_signatured_type_table (objfile);
6487     }
6488
6489   find_entry.signature = dwo_unit->signature;
6490   slot = htab_find_slot (dwarf2_per_objfile->signatured_types, &find_entry,
6491                          INSERT);
6492   /* If we've already seen this type there's nothing to do.  What's happening
6493      is we're doing our own version of comdat-folding here.  */
6494   if (*slot != NULL)
6495     return 1;
6496
6497   /* This does the job that create_all_type_units would have done for
6498      this TU.  */
6499   entry = add_type_unit (dwo_unit->signature, slot);
6500   fill_in_sig_entry_from_dwo_entry (objfile, entry, dwo_unit);
6501   *slot = entry;
6502
6503   /* This does the job that build_type_psymtabs_1 would have done.  */
6504   init_cutu_and_read_dies (&entry->per_cu, NULL, 0, 0,
6505                            build_type_psymtabs_reader, NULL);
6506
6507   return 1;
6508 }
6509
6510 /* Traversal function for process_skeletonless_type_units.  */
6511
6512 static int
6513 process_dwo_file_for_skeletonless_type_units (void **slot, void *info)
6514 {
6515   struct dwo_file *dwo_file = (struct dwo_file *) *slot;
6516
6517   if (dwo_file->tus != NULL)
6518     {
6519       htab_traverse_noresize (dwo_file->tus,
6520                               process_skeletonless_type_unit, info);
6521     }
6522
6523   return 1;
6524 }
6525
6526 /* Scan all TUs of DWO files, verifying we've processed them.
6527    This is needed in case a TU was emitted without its skeleton.
6528    Note: This can't be done until we know what all the DWO files are.  */
6529
6530 static void
6531 process_skeletonless_type_units (struct objfile *objfile)
6532 {
6533   /* Skeletonless TUs in DWP files without .gdb_index is not supported yet.  */
6534   if (get_dwp_file () == NULL
6535       && dwarf2_per_objfile->dwo_files != NULL)
6536     {
6537       htab_traverse_noresize (dwarf2_per_objfile->dwo_files,
6538                               process_dwo_file_for_skeletonless_type_units,
6539                               objfile);
6540     }
6541 }
6542
6543 /* A cleanup function that clears objfile's psymtabs_addrmap field.  */
6544
6545 static void
6546 psymtabs_addrmap_cleanup (void *o)
6547 {
6548   struct objfile *objfile = (struct objfile *) o;
6549
6550   objfile->psymtabs_addrmap = NULL;
6551 }
6552
6553 /* Compute the 'user' field for each psymtab in OBJFILE.  */
6554
6555 static void
6556 set_partial_user (struct objfile *objfile)
6557 {
6558   int i;
6559
6560   for (i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
6561     {
6562       struct dwarf2_per_cu_data *per_cu = dw2_get_cutu (i);
6563       struct partial_symtab *pst = per_cu->v.psymtab;
6564       int j;
6565
6566       if (pst == NULL)
6567         continue;
6568
6569       for (j = 0; j < pst->number_of_dependencies; ++j)
6570         {
6571           /* Set the 'user' field only if it is not already set.  */
6572           if (pst->dependencies[j]->user == NULL)
6573             pst->dependencies[j]->user = pst;
6574         }
6575     }
6576 }
6577
6578 /* Build the partial symbol table by doing a quick pass through the
6579    .debug_info and .debug_abbrev sections.  */
6580
6581 static void
6582 dwarf2_build_psymtabs_hard (struct objfile *objfile)
6583 {
6584   struct cleanup *back_to, *addrmap_cleanup;
6585   struct obstack temp_obstack;
6586   int i;
6587
6588   if (dwarf_read_debug)
6589     {
6590       fprintf_unfiltered (gdb_stdlog, "Building psymtabs of objfile %s ...\n",
6591                           objfile_name (objfile));
6592     }
6593
6594   dwarf2_per_objfile->reading_partial_symbols = 1;
6595
6596   dwarf2_read_section (objfile, &dwarf2_per_objfile->info);
6597
6598   /* Any cached compilation units will be linked by the per-objfile
6599      read_in_chain.  Make sure to free them when we're done.  */
6600   back_to = make_cleanup (free_cached_comp_units, NULL);
6601
6602   build_type_psymtabs (objfile);
6603
6604   create_all_comp_units (objfile);
6605
6606   /* Create a temporary address map on a temporary obstack.  We later
6607      copy this to the final obstack.  */
6608   obstack_init (&temp_obstack);
6609   make_cleanup_obstack_free (&temp_obstack);
6610   objfile->psymtabs_addrmap = addrmap_create_mutable (&temp_obstack);
6611   addrmap_cleanup = make_cleanup (psymtabs_addrmap_cleanup, objfile);
6612
6613   for (i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
6614     {
6615       struct dwarf2_per_cu_data *per_cu = dw2_get_cutu (i);
6616
6617       process_psymtab_comp_unit (per_cu, 0, language_minimal);
6618     }
6619
6620   /* This has to wait until we read the CUs, we need the list of DWOs.  */
6621   process_skeletonless_type_units (objfile);
6622
6623   /* Now that all TUs have been processed we can fill in the dependencies.  */
6624   if (dwarf2_per_objfile->type_unit_groups != NULL)
6625     {
6626       htab_traverse_noresize (dwarf2_per_objfile->type_unit_groups,
6627                               build_type_psymtab_dependencies, NULL);
6628     }
6629
6630   if (dwarf_read_debug)
6631     print_tu_stats ();
6632
6633   set_partial_user (objfile);
6634
6635   objfile->psymtabs_addrmap = addrmap_create_fixed (objfile->psymtabs_addrmap,
6636                                                     &objfile->objfile_obstack);
6637   discard_cleanups (addrmap_cleanup);
6638
6639   do_cleanups (back_to);
6640
6641   if (dwarf_read_debug)
6642     fprintf_unfiltered (gdb_stdlog, "Done building psymtabs of %s\n",
6643                         objfile_name (objfile));
6644 }
6645
6646 /* die_reader_func for load_partial_comp_unit.  */
6647
6648 static void
6649 load_partial_comp_unit_reader (const struct die_reader_specs *reader,
6650                                const gdb_byte *info_ptr,
6651                                struct die_info *comp_unit_die,
6652                                int has_children,
6653                                void *data)
6654 {
6655   struct dwarf2_cu *cu = reader->cu;
6656
6657   prepare_one_comp_unit (cu, comp_unit_die, language_minimal);
6658
6659   /* Check if comp unit has_children.
6660      If so, read the rest of the partial symbols from this comp unit.
6661      If not, there's no more debug_info for this comp unit.  */
6662   if (has_children)
6663     load_partial_dies (reader, info_ptr, 0);
6664 }
6665
6666 /* Load the partial DIEs for a secondary CU into memory.
6667    This is also used when rereading a primary CU with load_all_dies.  */
6668
6669 static void
6670 load_partial_comp_unit (struct dwarf2_per_cu_data *this_cu)
6671 {
6672   init_cutu_and_read_dies (this_cu, NULL, 1, 1,
6673                            load_partial_comp_unit_reader, NULL);
6674 }
6675
6676 static void
6677 read_comp_units_from_section (struct objfile *objfile,
6678                               struct dwarf2_section_info *section,
6679                               unsigned int is_dwz,
6680                               int *n_allocated,
6681                               int *n_comp_units,
6682                               struct dwarf2_per_cu_data ***all_comp_units)
6683 {
6684   const gdb_byte *info_ptr;
6685   bfd *abfd = get_section_bfd_owner (section);
6686
6687   if (dwarf_read_debug)
6688     fprintf_unfiltered (gdb_stdlog, "Reading %s for %s\n",
6689                         get_section_name (section),
6690                         get_section_file_name (section));
6691
6692   dwarf2_read_section (objfile, section);
6693
6694   info_ptr = section->buffer;
6695
6696   while (info_ptr < section->buffer + section->size)
6697     {
6698       unsigned int length, initial_length_size;
6699       struct dwarf2_per_cu_data *this_cu;
6700       sect_offset offset;
6701
6702       offset.sect_off = info_ptr - section->buffer;
6703
6704       /* Read just enough information to find out where the next
6705          compilation unit is.  */
6706       length = read_initial_length (abfd, info_ptr, &initial_length_size);
6707
6708       /* Save the compilation unit for later lookup.  */
6709       this_cu = XOBNEW (&objfile->objfile_obstack, struct dwarf2_per_cu_data);
6710       memset (this_cu, 0, sizeof (*this_cu));
6711       this_cu->offset = offset;
6712       this_cu->length = length + initial_length_size;
6713       this_cu->is_dwz = is_dwz;
6714       this_cu->objfile = objfile;
6715       this_cu->section = section;
6716
6717       if (*n_comp_units == *n_allocated)
6718         {
6719           *n_allocated *= 2;
6720           *all_comp_units = XRESIZEVEC (struct dwarf2_per_cu_data *,
6721                                         *all_comp_units, *n_allocated);
6722         }
6723       (*all_comp_units)[*n_comp_units] = this_cu;
6724       ++*n_comp_units;
6725
6726       info_ptr = info_ptr + this_cu->length;
6727     }
6728 }
6729
6730 /* Create a list of all compilation units in OBJFILE.
6731    This is only done for -readnow and building partial symtabs.  */
6732
6733 static void
6734 create_all_comp_units (struct objfile *objfile)
6735 {
6736   int n_allocated;
6737   int n_comp_units;
6738   struct dwarf2_per_cu_data **all_comp_units;
6739   struct dwz_file *dwz;
6740
6741   n_comp_units = 0;
6742   n_allocated = 10;
6743   all_comp_units = XNEWVEC (struct dwarf2_per_cu_data *, n_allocated);
6744
6745   read_comp_units_from_section (objfile, &dwarf2_per_objfile->info, 0,
6746                                 &n_allocated, &n_comp_units, &all_comp_units);
6747
6748   dwz = dwarf2_get_dwz_file ();
6749   if (dwz != NULL)
6750     read_comp_units_from_section (objfile, &dwz->info, 1,
6751                                   &n_allocated, &n_comp_units,
6752                                   &all_comp_units);
6753
6754   dwarf2_per_objfile->all_comp_units = XOBNEWVEC (&objfile->objfile_obstack,
6755                                                   struct dwarf2_per_cu_data *,
6756                                                   n_comp_units);
6757   memcpy (dwarf2_per_objfile->all_comp_units, all_comp_units,
6758           n_comp_units * sizeof (struct dwarf2_per_cu_data *));
6759   xfree (all_comp_units);
6760   dwarf2_per_objfile->n_comp_units = n_comp_units;
6761 }
6762
6763 /* Process all loaded DIEs for compilation unit CU, starting at
6764    FIRST_DIE.  The caller should pass SET_ADDRMAP == 1 if the compilation
6765    unit DIE did not have PC info (DW_AT_low_pc and DW_AT_high_pc, or
6766    DW_AT_ranges).  See the comments of add_partial_subprogram on how
6767    SET_ADDRMAP is used and how *LOWPC and *HIGHPC are updated.  */
6768
6769 static void
6770 scan_partial_symbols (struct partial_die_info *first_die, CORE_ADDR *lowpc,
6771                       CORE_ADDR *highpc, int set_addrmap,
6772                       struct dwarf2_cu *cu)
6773 {
6774   struct partial_die_info *pdi;
6775
6776   /* Now, march along the PDI's, descending into ones which have
6777      interesting children but skipping the children of the other ones,
6778      until we reach the end of the compilation unit.  */
6779
6780   pdi = first_die;
6781
6782   while (pdi != NULL)
6783     {
6784       fixup_partial_die (pdi, cu);
6785
6786       /* Anonymous namespaces or modules have no name but have interesting
6787          children, so we need to look at them.  Ditto for anonymous
6788          enums.  */
6789
6790       if (pdi->name != NULL || pdi->tag == DW_TAG_namespace
6791           || pdi->tag == DW_TAG_module || pdi->tag == DW_TAG_enumeration_type
6792           || pdi->tag == DW_TAG_imported_unit)
6793         {
6794           switch (pdi->tag)
6795             {
6796             case DW_TAG_subprogram:
6797               add_partial_subprogram (pdi, lowpc, highpc, set_addrmap, cu);
6798               break;
6799             case DW_TAG_constant:
6800             case DW_TAG_variable:
6801             case DW_TAG_typedef:
6802             case DW_TAG_union_type:
6803               if (!pdi->is_declaration)
6804                 {
6805                   add_partial_symbol (pdi, cu);
6806                 }
6807               break;
6808             case DW_TAG_class_type:
6809             case DW_TAG_interface_type:
6810             case DW_TAG_structure_type:
6811               if (!pdi->is_declaration)
6812                 {
6813                   add_partial_symbol (pdi, cu);
6814                 }
6815               if (cu->language == language_rust && pdi->has_children)
6816                 scan_partial_symbols (pdi->die_child, lowpc, highpc,
6817                                       set_addrmap, cu);
6818               break;
6819             case DW_TAG_enumeration_type:
6820               if (!pdi->is_declaration)
6821                 add_partial_enumeration (pdi, cu);
6822               break;
6823             case DW_TAG_base_type:
6824             case DW_TAG_subrange_type:
6825               /* File scope base type definitions are added to the partial
6826                  symbol table.  */
6827               add_partial_symbol (pdi, cu);
6828               break;
6829             case DW_TAG_namespace:
6830               add_partial_namespace (pdi, lowpc, highpc, set_addrmap, cu);
6831               break;
6832             case DW_TAG_module:
6833               add_partial_module (pdi, lowpc, highpc, set_addrmap, cu);
6834               break;
6835             case DW_TAG_imported_unit:
6836               {
6837                 struct dwarf2_per_cu_data *per_cu;
6838
6839                 /* For now we don't handle imported units in type units.  */
6840                 if (cu->per_cu->is_debug_types)
6841                   {
6842                     error (_("Dwarf Error: DW_TAG_imported_unit is not"
6843                              " supported in type units [in module %s]"),
6844                            objfile_name (cu->objfile));
6845                   }
6846
6847                 per_cu = dwarf2_find_containing_comp_unit (pdi->d.offset,
6848                                                            pdi->is_dwz,
6849                                                            cu->objfile);
6850
6851                 /* Go read the partial unit, if needed.  */
6852                 if (per_cu->v.psymtab == NULL)
6853                   process_psymtab_comp_unit (per_cu, 1, cu->language);
6854
6855                 VEC_safe_push (dwarf2_per_cu_ptr,
6856                                cu->per_cu->imported_symtabs, per_cu);
6857               }
6858               break;
6859             case DW_TAG_imported_declaration:
6860               add_partial_symbol (pdi, cu);
6861               break;
6862             default:
6863               break;
6864             }
6865         }
6866
6867       /* If the die has a sibling, skip to the sibling.  */
6868
6869       pdi = pdi->die_sibling;
6870     }
6871 }
6872
6873 /* Functions used to compute the fully scoped name of a partial DIE.
6874
6875    Normally, this is simple.  For C++, the parent DIE's fully scoped
6876    name is concatenated with "::" and the partial DIE's name.
6877    Enumerators are an exception; they use the scope of their parent
6878    enumeration type, i.e. the name of the enumeration type is not
6879    prepended to the enumerator.
6880
6881    There are two complexities.  One is DW_AT_specification; in this
6882    case "parent" means the parent of the target of the specification,
6883    instead of the direct parent of the DIE.  The other is compilers
6884    which do not emit DW_TAG_namespace; in this case we try to guess
6885    the fully qualified name of structure types from their members'
6886    linkage names.  This must be done using the DIE's children rather
6887    than the children of any DW_AT_specification target.  We only need
6888    to do this for structures at the top level, i.e. if the target of
6889    any DW_AT_specification (if any; otherwise the DIE itself) does not
6890    have a parent.  */
6891
6892 /* Compute the scope prefix associated with PDI's parent, in
6893    compilation unit CU.  The result will be allocated on CU's
6894    comp_unit_obstack, or a copy of the already allocated PDI->NAME
6895    field.  NULL is returned if no prefix is necessary.  */
6896 static const char *
6897 partial_die_parent_scope (struct partial_die_info *pdi,
6898                           struct dwarf2_cu *cu)
6899 {
6900   const char *grandparent_scope;
6901   struct partial_die_info *parent, *real_pdi;
6902
6903   /* We need to look at our parent DIE; if we have a DW_AT_specification,
6904      then this means the parent of the specification DIE.  */
6905
6906   real_pdi = pdi;
6907   while (real_pdi->has_specification)
6908     real_pdi = find_partial_die (real_pdi->spec_offset,
6909                                  real_pdi->spec_is_dwz, cu);
6910
6911   parent = real_pdi->die_parent;
6912   if (parent == NULL)
6913     return NULL;
6914
6915   if (parent->scope_set)
6916     return parent->scope;
6917
6918   fixup_partial_die (parent, cu);
6919
6920   grandparent_scope = partial_die_parent_scope (parent, cu);
6921
6922   /* GCC 4.0 and 4.1 had a bug (PR c++/28460) where they generated bogus
6923      DW_TAG_namespace DIEs with a name of "::" for the global namespace.
6924      Work around this problem here.  */
6925   if (cu->language == language_cplus
6926       && parent->tag == DW_TAG_namespace
6927       && strcmp (parent->name, "::") == 0
6928       && grandparent_scope == NULL)
6929     {
6930       parent->scope = NULL;
6931       parent->scope_set = 1;
6932       return NULL;
6933     }
6934
6935   if (pdi->tag == DW_TAG_enumerator)
6936     /* Enumerators should not get the name of the enumeration as a prefix.  */
6937     parent->scope = grandparent_scope;
6938   else if (parent->tag == DW_TAG_namespace
6939       || parent->tag == DW_TAG_module
6940       || parent->tag == DW_TAG_structure_type
6941       || parent->tag == DW_TAG_class_type
6942       || parent->tag == DW_TAG_interface_type
6943       || parent->tag == DW_TAG_union_type
6944       || parent->tag == DW_TAG_enumeration_type)
6945     {
6946       if (grandparent_scope == NULL)
6947         parent->scope = parent->name;
6948       else
6949         parent->scope = typename_concat (&cu->comp_unit_obstack,
6950                                          grandparent_scope,
6951                                          parent->name, 0, cu);
6952     }
6953   else
6954     {
6955       /* FIXME drow/2004-04-01: What should we be doing with
6956          function-local names?  For partial symbols, we should probably be
6957          ignoring them.  */
6958       complaint (&symfile_complaints,
6959                  _("unhandled containing DIE tag %d for DIE at %d"),
6960                  parent->tag, pdi->offset.sect_off);
6961       parent->scope = grandparent_scope;
6962     }
6963
6964   parent->scope_set = 1;
6965   return parent->scope;
6966 }
6967
6968 /* Return the fully scoped name associated with PDI, from compilation unit
6969    CU.  The result will be allocated with malloc.  */
6970
6971 static char *
6972 partial_die_full_name (struct partial_die_info *pdi,
6973                        struct dwarf2_cu *cu)
6974 {
6975   const char *parent_scope;
6976
6977   /* If this is a template instantiation, we can not work out the
6978      template arguments from partial DIEs.  So, unfortunately, we have
6979      to go through the full DIEs.  At least any work we do building
6980      types here will be reused if full symbols are loaded later.  */
6981   if (pdi->has_template_arguments)
6982     {
6983       fixup_partial_die (pdi, cu);
6984
6985       if (pdi->name != NULL && strchr (pdi->name, '<') == NULL)
6986         {
6987           struct die_info *die;
6988           struct attribute attr;
6989           struct dwarf2_cu *ref_cu = cu;
6990
6991           /* DW_FORM_ref_addr is using section offset.  */
6992           attr.name = (enum dwarf_attribute) 0;
6993           attr.form = DW_FORM_ref_addr;
6994           attr.u.unsnd = pdi->offset.sect_off;
6995           die = follow_die_ref (NULL, &attr, &ref_cu);
6996
6997           return xstrdup (dwarf2_full_name (NULL, die, ref_cu));
6998         }
6999     }
7000
7001   parent_scope = partial_die_parent_scope (pdi, cu);
7002   if (parent_scope == NULL)
7003     return NULL;
7004   else
7005     return typename_concat (NULL, parent_scope, pdi->name, 0, cu);
7006 }
7007
7008 static void
7009 add_partial_symbol (struct partial_die_info *pdi, struct dwarf2_cu *cu)
7010 {
7011   struct objfile *objfile = cu->objfile;
7012   struct gdbarch *gdbarch = get_objfile_arch (objfile);
7013   CORE_ADDR addr = 0;
7014   const char *actual_name = NULL;
7015   CORE_ADDR baseaddr;
7016   char *built_actual_name;
7017
7018   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
7019
7020   built_actual_name = partial_die_full_name (pdi, cu);
7021   if (built_actual_name != NULL)
7022     actual_name = built_actual_name;
7023
7024   if (actual_name == NULL)
7025     actual_name = pdi->name;
7026
7027   switch (pdi->tag)
7028     {
7029     case DW_TAG_subprogram:
7030       addr = gdbarch_adjust_dwarf2_addr (gdbarch, pdi->lowpc + baseaddr);
7031       if (pdi->is_external || cu->language == language_ada)
7032         {
7033           /* brobecker/2007-12-26: Normally, only "external" DIEs are part
7034              of the global scope.  But in Ada, we want to be able to access
7035              nested procedures globally.  So all Ada subprograms are stored
7036              in the global scope.  */
7037           add_psymbol_to_list (actual_name, strlen (actual_name),
7038                                built_actual_name != NULL,
7039                                VAR_DOMAIN, LOC_BLOCK,
7040                                &objfile->global_psymbols,
7041                                addr, cu->language, objfile);
7042         }
7043       else
7044         {
7045           add_psymbol_to_list (actual_name, strlen (actual_name),
7046                                built_actual_name != NULL,
7047                                VAR_DOMAIN, LOC_BLOCK,
7048                                &objfile->static_psymbols,
7049                                addr, cu->language, objfile);
7050         }
7051
7052       if (pdi->main_subprogram && actual_name != NULL)
7053         set_objfile_main_name (objfile, actual_name, cu->language);
7054       break;
7055     case DW_TAG_constant:
7056       {
7057         struct psymbol_allocation_list *list;
7058
7059         if (pdi->is_external)
7060           list = &objfile->global_psymbols;
7061         else
7062           list = &objfile->static_psymbols;
7063         add_psymbol_to_list (actual_name, strlen (actual_name),
7064                              built_actual_name != NULL, VAR_DOMAIN, LOC_STATIC,
7065                              list, 0, cu->language, objfile);
7066       }
7067       break;
7068     case DW_TAG_variable:
7069       if (pdi->d.locdesc)
7070         addr = decode_locdesc (pdi->d.locdesc, cu);
7071
7072       if (pdi->d.locdesc
7073           && addr == 0
7074           && !dwarf2_per_objfile->has_section_at_zero)
7075         {
7076           /* A global or static variable may also have been stripped
7077              out by the linker if unused, in which case its address
7078              will be nullified; do not add such variables into partial
7079              symbol table then.  */
7080         }
7081       else if (pdi->is_external)
7082         {
7083           /* Global Variable.
7084              Don't enter into the minimal symbol tables as there is
7085              a minimal symbol table entry from the ELF symbols already.
7086              Enter into partial symbol table if it has a location
7087              descriptor or a type.
7088              If the location descriptor is missing, new_symbol will create
7089              a LOC_UNRESOLVED symbol, the address of the variable will then
7090              be determined from the minimal symbol table whenever the variable
7091              is referenced.
7092              The address for the partial symbol table entry is not
7093              used by GDB, but it comes in handy for debugging partial symbol
7094              table building.  */
7095
7096           if (pdi->d.locdesc || pdi->has_type)
7097             add_psymbol_to_list (actual_name, strlen (actual_name),
7098                                  built_actual_name != NULL,
7099                                  VAR_DOMAIN, LOC_STATIC,
7100                                  &objfile->global_psymbols,
7101                                  addr + baseaddr,
7102                                  cu->language, objfile);
7103         }
7104       else
7105         {
7106           int has_loc = pdi->d.locdesc != NULL;
7107
7108           /* Static Variable.  Skip symbols whose value we cannot know (those
7109              without location descriptors or constant values).  */
7110           if (!has_loc && !pdi->has_const_value)
7111             {
7112               xfree (built_actual_name);
7113               return;
7114             }
7115
7116           add_psymbol_to_list (actual_name, strlen (actual_name),
7117                                built_actual_name != NULL,
7118                                VAR_DOMAIN, LOC_STATIC,
7119                                &objfile->static_psymbols,
7120                                has_loc ? addr + baseaddr : (CORE_ADDR) 0,
7121                                cu->language, objfile);
7122         }
7123       break;
7124     case DW_TAG_typedef:
7125     case DW_TAG_base_type:
7126     case DW_TAG_subrange_type:
7127       add_psymbol_to_list (actual_name, strlen (actual_name),
7128                            built_actual_name != NULL,
7129                            VAR_DOMAIN, LOC_TYPEDEF,
7130                            &objfile->static_psymbols,
7131                            0, cu->language, objfile);
7132       break;
7133     case DW_TAG_imported_declaration:
7134     case DW_TAG_namespace:
7135       add_psymbol_to_list (actual_name, strlen (actual_name),
7136                            built_actual_name != NULL,
7137                            VAR_DOMAIN, LOC_TYPEDEF,
7138                            &objfile->global_psymbols,
7139                            0, cu->language, objfile);
7140       break;
7141     case DW_TAG_module:
7142       add_psymbol_to_list (actual_name, strlen (actual_name),
7143                            built_actual_name != NULL,
7144                            MODULE_DOMAIN, LOC_TYPEDEF,
7145                            &objfile->global_psymbols,
7146                            0, cu->language, objfile);
7147       break;
7148     case DW_TAG_class_type:
7149     case DW_TAG_interface_type:
7150     case DW_TAG_structure_type:
7151     case DW_TAG_union_type:
7152     case DW_TAG_enumeration_type:
7153       /* Skip external references.  The DWARF standard says in the section
7154          about "Structure, Union, and Class Type Entries": "An incomplete
7155          structure, union or class type is represented by a structure,
7156          union or class entry that does not have a byte size attribute
7157          and that has a DW_AT_declaration attribute."  */
7158       if (!pdi->has_byte_size && pdi->is_declaration)
7159         {
7160           xfree (built_actual_name);
7161           return;
7162         }
7163
7164       /* NOTE: carlton/2003-10-07: See comment in new_symbol about
7165          static vs. global.  */
7166       add_psymbol_to_list (actual_name, strlen (actual_name),
7167                            built_actual_name != NULL,
7168                            STRUCT_DOMAIN, LOC_TYPEDEF,
7169                            cu->language == language_cplus
7170                            ? &objfile->global_psymbols
7171                            : &objfile->static_psymbols,
7172                            0, cu->language, objfile);
7173
7174       break;
7175     case DW_TAG_enumerator:
7176       add_psymbol_to_list (actual_name, strlen (actual_name),
7177                            built_actual_name != NULL,
7178                            VAR_DOMAIN, LOC_CONST,
7179                            cu->language == language_cplus
7180                            ? &objfile->global_psymbols
7181                            : &objfile->static_psymbols,
7182                            0, cu->language, objfile);
7183       break;
7184     default:
7185       break;
7186     }
7187
7188   xfree (built_actual_name);
7189 }
7190
7191 /* Read a partial die corresponding to a namespace; also, add a symbol
7192    corresponding to that namespace to the symbol table.  NAMESPACE is
7193    the name of the enclosing namespace.  */
7194
7195 static void
7196 add_partial_namespace (struct partial_die_info *pdi,
7197                        CORE_ADDR *lowpc, CORE_ADDR *highpc,
7198                        int set_addrmap, struct dwarf2_cu *cu)
7199 {
7200   /* Add a symbol for the namespace.  */
7201
7202   add_partial_symbol (pdi, cu);
7203
7204   /* Now scan partial symbols in that namespace.  */
7205
7206   if (pdi->has_children)
7207     scan_partial_symbols (pdi->die_child, lowpc, highpc, set_addrmap, cu);
7208 }
7209
7210 /* Read a partial die corresponding to a Fortran module.  */
7211
7212 static void
7213 add_partial_module (struct partial_die_info *pdi, CORE_ADDR *lowpc,
7214                     CORE_ADDR *highpc, int set_addrmap, struct dwarf2_cu *cu)
7215 {
7216   /* Add a symbol for the namespace.  */
7217
7218   add_partial_symbol (pdi, cu);
7219
7220   /* Now scan partial symbols in that module.  */
7221
7222   if (pdi->has_children)
7223     scan_partial_symbols (pdi->die_child, lowpc, highpc, set_addrmap, cu);
7224 }
7225
7226 /* Read a partial die corresponding to a subprogram and create a partial
7227    symbol for that subprogram.  When the CU language allows it, this
7228    routine also defines a partial symbol for each nested subprogram
7229    that this subprogram contains.  If SET_ADDRMAP is true, record the
7230    covered ranges in the addrmap.  Set *LOWPC and *HIGHPC to the lowest
7231    and highest PC values found in PDI.
7232
7233    PDI may also be a lexical block, in which case we simply search
7234    recursively for subprograms defined inside that lexical block.
7235    Again, this is only performed when the CU language allows this
7236    type of definitions.  */
7237
7238 static void
7239 add_partial_subprogram (struct partial_die_info *pdi,
7240                         CORE_ADDR *lowpc, CORE_ADDR *highpc,
7241                         int set_addrmap, struct dwarf2_cu *cu)
7242 {
7243   if (pdi->tag == DW_TAG_subprogram)
7244     {
7245       if (pdi->has_pc_info)
7246         {
7247           if (pdi->lowpc < *lowpc)
7248             *lowpc = pdi->lowpc;
7249           if (pdi->highpc > *highpc)
7250             *highpc = pdi->highpc;
7251           if (set_addrmap)
7252             {
7253               struct objfile *objfile = cu->objfile;
7254               struct gdbarch *gdbarch = get_objfile_arch (objfile);
7255               CORE_ADDR baseaddr;
7256               CORE_ADDR highpc;
7257               CORE_ADDR lowpc;
7258
7259               baseaddr = ANOFFSET (objfile->section_offsets,
7260                                    SECT_OFF_TEXT (objfile));
7261               lowpc = gdbarch_adjust_dwarf2_addr (gdbarch,
7262                                                   pdi->lowpc + baseaddr);
7263               highpc = gdbarch_adjust_dwarf2_addr (gdbarch,
7264                                                    pdi->highpc + baseaddr);
7265               addrmap_set_empty (objfile->psymtabs_addrmap, lowpc, highpc - 1,
7266                                  cu->per_cu->v.psymtab);
7267             }
7268         }
7269
7270       if (pdi->has_pc_info || (!pdi->is_external && pdi->may_be_inlined))
7271         {
7272           if (!pdi->is_declaration)
7273             /* Ignore subprogram DIEs that do not have a name, they are
7274                illegal.  Do not emit a complaint at this point, we will
7275                do so when we convert this psymtab into a symtab.  */
7276             if (pdi->name)
7277               add_partial_symbol (pdi, cu);
7278         }
7279     }
7280
7281   if (! pdi->has_children)
7282     return;
7283
7284   if (cu->language == language_ada)
7285     {
7286       pdi = pdi->die_child;
7287       while (pdi != NULL)
7288         {
7289           fixup_partial_die (pdi, cu);
7290           if (pdi->tag == DW_TAG_subprogram
7291               || pdi->tag == DW_TAG_lexical_block)
7292             add_partial_subprogram (pdi, lowpc, highpc, set_addrmap, cu);
7293           pdi = pdi->die_sibling;
7294         }
7295     }
7296 }
7297
7298 /* Read a partial die corresponding to an enumeration type.  */
7299
7300 static void
7301 add_partial_enumeration (struct partial_die_info *enum_pdi,
7302                          struct dwarf2_cu *cu)
7303 {
7304   struct partial_die_info *pdi;
7305
7306   if (enum_pdi->name != NULL)
7307     add_partial_symbol (enum_pdi, cu);
7308
7309   pdi = enum_pdi->die_child;
7310   while (pdi)
7311     {
7312       if (pdi->tag != DW_TAG_enumerator || pdi->name == NULL)
7313         complaint (&symfile_complaints, _("malformed enumerator DIE ignored"));
7314       else
7315         add_partial_symbol (pdi, cu);
7316       pdi = pdi->die_sibling;
7317     }
7318 }
7319
7320 /* Return the initial uleb128 in the die at INFO_PTR.  */
7321
7322 static unsigned int
7323 peek_abbrev_code (bfd *abfd, const gdb_byte *info_ptr)
7324 {
7325   unsigned int bytes_read;
7326
7327   return read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
7328 }
7329
7330 /* Read the initial uleb128 in the die at INFO_PTR in compilation unit CU.
7331    Return the corresponding abbrev, or NULL if the number is zero (indicating
7332    an empty DIE).  In either case *BYTES_READ will be set to the length of
7333    the initial number.  */
7334
7335 static struct abbrev_info *
7336 peek_die_abbrev (const gdb_byte *info_ptr, unsigned int *bytes_read,
7337                  struct dwarf2_cu *cu)
7338 {
7339   bfd *abfd = cu->objfile->obfd;
7340   unsigned int abbrev_number;
7341   struct abbrev_info *abbrev;
7342
7343   abbrev_number = read_unsigned_leb128 (abfd, info_ptr, bytes_read);
7344
7345   if (abbrev_number == 0)
7346     return NULL;
7347
7348   abbrev = abbrev_table_lookup_abbrev (cu->abbrev_table, abbrev_number);
7349   if (!abbrev)
7350     {
7351       error (_("Dwarf Error: Could not find abbrev number %d in %s"
7352                " at offset 0x%x [in module %s]"),
7353              abbrev_number, cu->per_cu->is_debug_types ? "TU" : "CU",
7354              cu->header.offset.sect_off, bfd_get_filename (abfd));
7355     }
7356
7357   return abbrev;
7358 }
7359
7360 /* Scan the debug information for CU starting at INFO_PTR in buffer BUFFER.
7361    Returns a pointer to the end of a series of DIEs, terminated by an empty
7362    DIE.  Any children of the skipped DIEs will also be skipped.  */
7363
7364 static const gdb_byte *
7365 skip_children (const struct die_reader_specs *reader, const gdb_byte *info_ptr)
7366 {
7367   struct dwarf2_cu *cu = reader->cu;
7368   struct abbrev_info *abbrev;
7369   unsigned int bytes_read;
7370
7371   while (1)
7372     {
7373       abbrev = peek_die_abbrev (info_ptr, &bytes_read, cu);
7374       if (abbrev == NULL)
7375         return info_ptr + bytes_read;
7376       else
7377         info_ptr = skip_one_die (reader, info_ptr + bytes_read, abbrev);
7378     }
7379 }
7380
7381 /* Scan the debug information for CU starting at INFO_PTR in buffer BUFFER.
7382    INFO_PTR should point just after the initial uleb128 of a DIE, and the
7383    abbrev corresponding to that skipped uleb128 should be passed in
7384    ABBREV.  Returns a pointer to this DIE's sibling, skipping any
7385    children.  */
7386
7387 static const gdb_byte *
7388 skip_one_die (const struct die_reader_specs *reader, const gdb_byte *info_ptr,
7389               struct abbrev_info *abbrev)
7390 {
7391   unsigned int bytes_read;
7392   struct attribute attr;
7393   bfd *abfd = reader->abfd;
7394   struct dwarf2_cu *cu = reader->cu;
7395   const gdb_byte *buffer = reader->buffer;
7396   const gdb_byte *buffer_end = reader->buffer_end;
7397   unsigned int form, i;
7398
7399   for (i = 0; i < abbrev->num_attrs; i++)
7400     {
7401       /* The only abbrev we care about is DW_AT_sibling.  */
7402       if (abbrev->attrs[i].name == DW_AT_sibling)
7403         {
7404           read_attribute (reader, &attr, &abbrev->attrs[i], info_ptr);
7405           if (attr.form == DW_FORM_ref_addr)
7406             complaint (&symfile_complaints,
7407                        _("ignoring absolute DW_AT_sibling"));
7408           else
7409             {
7410               unsigned int off = dwarf2_get_ref_die_offset (&attr).sect_off;
7411               const gdb_byte *sibling_ptr = buffer + off;
7412
7413               if (sibling_ptr < info_ptr)
7414                 complaint (&symfile_complaints,
7415                            _("DW_AT_sibling points backwards"));
7416               else if (sibling_ptr > reader->buffer_end)
7417                 dwarf2_section_buffer_overflow_complaint (reader->die_section);
7418               else
7419                 return sibling_ptr;
7420             }
7421         }
7422
7423       /* If it isn't DW_AT_sibling, skip this attribute.  */
7424       form = abbrev->attrs[i].form;
7425     skip_attribute:
7426       switch (form)
7427         {
7428         case DW_FORM_ref_addr:
7429           /* In DWARF 2, DW_FORM_ref_addr is address sized; in DWARF 3
7430              and later it is offset sized.  */
7431           if (cu->header.version == 2)
7432             info_ptr += cu->header.addr_size;
7433           else
7434             info_ptr += cu->header.offset_size;
7435           break;
7436         case DW_FORM_GNU_ref_alt:
7437           info_ptr += cu->header.offset_size;
7438           break;
7439         case DW_FORM_addr:
7440           info_ptr += cu->header.addr_size;
7441           break;
7442         case DW_FORM_data1:
7443         case DW_FORM_ref1:
7444         case DW_FORM_flag:
7445           info_ptr += 1;
7446           break;
7447         case DW_FORM_flag_present:
7448         case DW_FORM_implicit_const:
7449           break;
7450         case DW_FORM_data2:
7451         case DW_FORM_ref2:
7452           info_ptr += 2;
7453           break;
7454         case DW_FORM_data4:
7455         case DW_FORM_ref4:
7456           info_ptr += 4;
7457           break;
7458         case DW_FORM_data8:
7459         case DW_FORM_ref8:
7460         case DW_FORM_ref_sig8:
7461           info_ptr += 8;
7462           break;
7463         case DW_FORM_data16:
7464           info_ptr += 16;
7465           break;
7466         case DW_FORM_string:
7467           read_direct_string (abfd, info_ptr, &bytes_read);
7468           info_ptr += bytes_read;
7469           break;
7470         case DW_FORM_sec_offset:
7471         case DW_FORM_strp:
7472         case DW_FORM_GNU_strp_alt:
7473           info_ptr += cu->header.offset_size;
7474           break;
7475         case DW_FORM_exprloc:
7476         case DW_FORM_block:
7477           info_ptr += read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
7478           info_ptr += bytes_read;
7479           break;
7480         case DW_FORM_block1:
7481           info_ptr += 1 + read_1_byte (abfd, info_ptr);
7482           break;
7483         case DW_FORM_block2:
7484           info_ptr += 2 + read_2_bytes (abfd, info_ptr);
7485           break;
7486         case DW_FORM_block4:
7487           info_ptr += 4 + read_4_bytes (abfd, info_ptr);
7488           break;
7489         case DW_FORM_sdata:
7490         case DW_FORM_udata:
7491         case DW_FORM_ref_udata:
7492         case DW_FORM_GNU_addr_index:
7493         case DW_FORM_GNU_str_index:
7494           info_ptr = safe_skip_leb128 (info_ptr, buffer_end);
7495           break;
7496         case DW_FORM_indirect:
7497           form = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
7498           info_ptr += bytes_read;
7499           /* We need to continue parsing from here, so just go back to
7500              the top.  */
7501           goto skip_attribute;
7502
7503         default:
7504           error (_("Dwarf Error: Cannot handle %s "
7505                    "in DWARF reader [in module %s]"),
7506                  dwarf_form_name (form),
7507                  bfd_get_filename (abfd));
7508         }
7509     }
7510
7511   if (abbrev->has_children)
7512     return skip_children (reader, info_ptr);
7513   else
7514     return info_ptr;
7515 }
7516
7517 /* Locate ORIG_PDI's sibling.
7518    INFO_PTR should point to the start of the next DIE after ORIG_PDI.  */
7519
7520 static const gdb_byte *
7521 locate_pdi_sibling (const struct die_reader_specs *reader,
7522                     struct partial_die_info *orig_pdi,
7523                     const gdb_byte *info_ptr)
7524 {
7525   /* Do we know the sibling already?  */
7526
7527   if (orig_pdi->sibling)
7528     return orig_pdi->sibling;
7529
7530   /* Are there any children to deal with?  */
7531
7532   if (!orig_pdi->has_children)
7533     return info_ptr;
7534
7535   /* Skip the children the long way.  */
7536
7537   return skip_children (reader, info_ptr);
7538 }
7539
7540 /* Expand this partial symbol table into a full symbol table.  SELF is
7541    not NULL.  */
7542
7543 static void
7544 dwarf2_read_symtab (struct partial_symtab *self,
7545                     struct objfile *objfile)
7546 {
7547   if (self->readin)
7548     {
7549       warning (_("bug: psymtab for %s is already read in."),
7550                self->filename);
7551     }
7552   else
7553     {
7554       if (info_verbose)
7555         {
7556           printf_filtered (_("Reading in symbols for %s..."),
7557                            self->filename);
7558           gdb_flush (gdb_stdout);
7559         }
7560
7561       /* Restore our global data.  */
7562       dwarf2_per_objfile
7563         = (struct dwarf2_per_objfile *) objfile_data (objfile,
7564                                                       dwarf2_objfile_data_key);
7565
7566       /* If this psymtab is constructed from a debug-only objfile, the
7567          has_section_at_zero flag will not necessarily be correct.  We
7568          can get the correct value for this flag by looking at the data
7569          associated with the (presumably stripped) associated objfile.  */
7570       if (objfile->separate_debug_objfile_backlink)
7571         {
7572           struct dwarf2_per_objfile *dpo_backlink
7573             = ((struct dwarf2_per_objfile *)
7574                objfile_data (objfile->separate_debug_objfile_backlink,
7575                              dwarf2_objfile_data_key));
7576
7577           dwarf2_per_objfile->has_section_at_zero
7578             = dpo_backlink->has_section_at_zero;
7579         }
7580
7581       dwarf2_per_objfile->reading_partial_symbols = 0;
7582
7583       psymtab_to_symtab_1 (self);
7584
7585       /* Finish up the debug error message.  */
7586       if (info_verbose)
7587         printf_filtered (_("done.\n"));
7588     }
7589
7590   process_cu_includes ();
7591 }
7592 \f
7593 /* Reading in full CUs.  */
7594
7595 /* Add PER_CU to the queue.  */
7596
7597 static void
7598 queue_comp_unit (struct dwarf2_per_cu_data *per_cu,
7599                  enum language pretend_language)
7600 {
7601   struct dwarf2_queue_item *item;
7602
7603   per_cu->queued = 1;
7604   item = XNEW (struct dwarf2_queue_item);
7605   item->per_cu = per_cu;
7606   item->pretend_language = pretend_language;
7607   item->next = NULL;
7608
7609   if (dwarf2_queue == NULL)
7610     dwarf2_queue = item;
7611   else
7612     dwarf2_queue_tail->next = item;
7613
7614   dwarf2_queue_tail = item;
7615 }
7616
7617 /* If PER_CU is not yet queued, add it to the queue.
7618    If DEPENDENT_CU is non-NULL, it has a reference to PER_CU so add a
7619    dependency.
7620    The result is non-zero if PER_CU was queued, otherwise the result is zero
7621    meaning either PER_CU is already queued or it is already loaded.
7622
7623    N.B. There is an invariant here that if a CU is queued then it is loaded.
7624    The caller is required to load PER_CU if we return non-zero.  */
7625
7626 static int
7627 maybe_queue_comp_unit (struct dwarf2_cu *dependent_cu,
7628                        struct dwarf2_per_cu_data *per_cu,
7629                        enum language pretend_language)
7630 {
7631   /* We may arrive here during partial symbol reading, if we need full
7632      DIEs to process an unusual case (e.g. template arguments).  Do
7633      not queue PER_CU, just tell our caller to load its DIEs.  */
7634   if (dwarf2_per_objfile->reading_partial_symbols)
7635     {
7636       if (per_cu->cu == NULL || per_cu->cu->dies == NULL)
7637         return 1;
7638       return 0;
7639     }
7640
7641   /* Mark the dependence relation so that we don't flush PER_CU
7642      too early.  */
7643   if (dependent_cu != NULL)
7644     dwarf2_add_dependence (dependent_cu, per_cu);
7645
7646   /* If it's already on the queue, we have nothing to do.  */
7647   if (per_cu->queued)
7648     return 0;
7649
7650   /* If the compilation unit is already loaded, just mark it as
7651      used.  */
7652   if (per_cu->cu != NULL)
7653     {
7654       per_cu->cu->last_used = 0;
7655       return 0;
7656     }
7657
7658   /* Add it to the queue.  */
7659   queue_comp_unit (per_cu, pretend_language);
7660
7661   return 1;
7662 }
7663
7664 /* Process the queue.  */
7665
7666 static void
7667 process_queue (void)
7668 {
7669   struct dwarf2_queue_item *item, *next_item;
7670
7671   if (dwarf_read_debug)
7672     {
7673       fprintf_unfiltered (gdb_stdlog,
7674                           "Expanding one or more symtabs of objfile %s ...\n",
7675                           objfile_name (dwarf2_per_objfile->objfile));
7676     }
7677
7678   /* The queue starts out with one item, but following a DIE reference
7679      may load a new CU, adding it to the end of the queue.  */
7680   for (item = dwarf2_queue; item != NULL; dwarf2_queue = item = next_item)
7681     {
7682       if ((dwarf2_per_objfile->using_index
7683            ? !item->per_cu->v.quick->compunit_symtab
7684            : (item->per_cu->v.psymtab && !item->per_cu->v.psymtab->readin))
7685           /* Skip dummy CUs.  */
7686           && item->per_cu->cu != NULL)
7687         {
7688           struct dwarf2_per_cu_data *per_cu = item->per_cu;
7689           unsigned int debug_print_threshold;
7690           char buf[100];
7691
7692           if (per_cu->is_debug_types)
7693             {
7694               struct signatured_type *sig_type =
7695                 (struct signatured_type *) per_cu;
7696
7697               sprintf (buf, "TU %s at offset 0x%x",
7698                        hex_string (sig_type->signature),
7699                        per_cu->offset.sect_off);
7700               /* There can be 100s of TUs.
7701                  Only print them in verbose mode.  */
7702               debug_print_threshold = 2;
7703             }
7704           else
7705             {
7706               sprintf (buf, "CU at offset 0x%x", per_cu->offset.sect_off);
7707               debug_print_threshold = 1;
7708             }
7709
7710           if (dwarf_read_debug >= debug_print_threshold)
7711             fprintf_unfiltered (gdb_stdlog, "Expanding symtab of %s\n", buf);
7712
7713           if (per_cu->is_debug_types)
7714             process_full_type_unit (per_cu, item->pretend_language);
7715           else
7716             process_full_comp_unit (per_cu, item->pretend_language);
7717
7718           if (dwarf_read_debug >= debug_print_threshold)
7719             fprintf_unfiltered (gdb_stdlog, "Done expanding %s\n", buf);
7720         }
7721
7722       item->per_cu->queued = 0;
7723       next_item = item->next;
7724       xfree (item);
7725     }
7726
7727   dwarf2_queue_tail = NULL;
7728
7729   if (dwarf_read_debug)
7730     {
7731       fprintf_unfiltered (gdb_stdlog, "Done expanding symtabs of %s.\n",
7732                           objfile_name (dwarf2_per_objfile->objfile));
7733     }
7734 }
7735
7736 /* Free all allocated queue entries.  This function only releases anything if
7737    an error was thrown; if the queue was processed then it would have been
7738    freed as we went along.  */
7739
7740 static void
7741 dwarf2_release_queue (void *dummy)
7742 {
7743   struct dwarf2_queue_item *item, *last;
7744
7745   item = dwarf2_queue;
7746   while (item)
7747     {
7748       /* Anything still marked queued is likely to be in an
7749          inconsistent state, so discard it.  */
7750       if (item->per_cu->queued)
7751         {
7752           if (item->per_cu->cu != NULL)
7753             free_one_cached_comp_unit (item->per_cu);
7754           item->per_cu->queued = 0;
7755         }
7756
7757       last = item;
7758       item = item->next;
7759       xfree (last);
7760     }
7761
7762   dwarf2_queue = dwarf2_queue_tail = NULL;
7763 }
7764
7765 /* Read in full symbols for PST, and anything it depends on.  */
7766
7767 static void
7768 psymtab_to_symtab_1 (struct partial_symtab *pst)
7769 {
7770   struct dwarf2_per_cu_data *per_cu;
7771   int i;
7772
7773   if (pst->readin)
7774     return;
7775
7776   for (i = 0; i < pst->number_of_dependencies; i++)
7777     if (!pst->dependencies[i]->readin
7778         && pst->dependencies[i]->user == NULL)
7779       {
7780         /* Inform about additional files that need to be read in.  */
7781         if (info_verbose)
7782           {
7783             /* FIXME: i18n: Need to make this a single string.  */
7784             fputs_filtered (" ", gdb_stdout);
7785             wrap_here ("");
7786             fputs_filtered ("and ", gdb_stdout);
7787             wrap_here ("");
7788             printf_filtered ("%s...", pst->dependencies[i]->filename);
7789             wrap_here ("");     /* Flush output.  */
7790             gdb_flush (gdb_stdout);
7791           }
7792         psymtab_to_symtab_1 (pst->dependencies[i]);
7793       }
7794
7795   per_cu = (struct dwarf2_per_cu_data *) pst->read_symtab_private;
7796
7797   if (per_cu == NULL)
7798     {
7799       /* It's an include file, no symbols to read for it.
7800          Everything is in the parent symtab.  */
7801       pst->readin = 1;
7802       return;
7803     }
7804
7805   dw2_do_instantiate_symtab (per_cu);
7806 }
7807
7808 /* Trivial hash function for die_info: the hash value of a DIE
7809    is its offset in .debug_info for this objfile.  */
7810
7811 static hashval_t
7812 die_hash (const void *item)
7813 {
7814   const struct die_info *die = (const struct die_info *) item;
7815
7816   return die->offset.sect_off;
7817 }
7818
7819 /* Trivial comparison function for die_info structures: two DIEs
7820    are equal if they have the same offset.  */
7821
7822 static int
7823 die_eq (const void *item_lhs, const void *item_rhs)
7824 {
7825   const struct die_info *die_lhs = (const struct die_info *) item_lhs;
7826   const struct die_info *die_rhs = (const struct die_info *) item_rhs;
7827
7828   return die_lhs->offset.sect_off == die_rhs->offset.sect_off;
7829 }
7830
7831 /* die_reader_func for load_full_comp_unit.
7832    This is identical to read_signatured_type_reader,
7833    but is kept separate for now.  */
7834
7835 static void
7836 load_full_comp_unit_reader (const struct die_reader_specs *reader,
7837                             const gdb_byte *info_ptr,
7838                             struct die_info *comp_unit_die,
7839                             int has_children,
7840                             void *data)
7841 {
7842   struct dwarf2_cu *cu = reader->cu;
7843   enum language *language_ptr = (enum language *) data;
7844
7845   gdb_assert (cu->die_hash == NULL);
7846   cu->die_hash =
7847     htab_create_alloc_ex (cu->header.length / 12,
7848                           die_hash,
7849                           die_eq,
7850                           NULL,
7851                           &cu->comp_unit_obstack,
7852                           hashtab_obstack_allocate,
7853                           dummy_obstack_deallocate);
7854
7855   if (has_children)
7856     comp_unit_die->child = read_die_and_siblings (reader, info_ptr,
7857                                                   &info_ptr, comp_unit_die);
7858   cu->dies = comp_unit_die;
7859   /* comp_unit_die is not stored in die_hash, no need.  */
7860
7861   /* We try not to read any attributes in this function, because not
7862      all CUs needed for references have been loaded yet, and symbol
7863      table processing isn't initialized.  But we have to set the CU language,
7864      or we won't be able to build types correctly.
7865      Similarly, if we do not read the producer, we can not apply
7866      producer-specific interpretation.  */
7867   prepare_one_comp_unit (cu, cu->dies, *language_ptr);
7868 }
7869
7870 /* Load the DIEs associated with PER_CU into memory.  */
7871
7872 static void
7873 load_full_comp_unit (struct dwarf2_per_cu_data *this_cu,
7874                      enum language pretend_language)
7875 {
7876   gdb_assert (! this_cu->is_debug_types);
7877
7878   init_cutu_and_read_dies (this_cu, NULL, 1, 1,
7879                            load_full_comp_unit_reader, &pretend_language);
7880 }
7881
7882 /* Add a DIE to the delayed physname list.  */
7883
7884 static void
7885 add_to_method_list (struct type *type, int fnfield_index, int index,
7886                     const char *name, struct die_info *die,
7887                     struct dwarf2_cu *cu)
7888 {
7889   struct delayed_method_info mi;
7890   mi.type = type;
7891   mi.fnfield_index = fnfield_index;
7892   mi.index = index;
7893   mi.name = name;
7894   mi.die = die;
7895   VEC_safe_push (delayed_method_info, cu->method_list, &mi);
7896 }
7897
7898 /* A cleanup for freeing the delayed method list.  */
7899
7900 static void
7901 free_delayed_list (void *ptr)
7902 {
7903   struct dwarf2_cu *cu = (struct dwarf2_cu *) ptr;
7904   if (cu->method_list != NULL)
7905     {
7906       VEC_free (delayed_method_info, cu->method_list);
7907       cu->method_list = NULL;
7908     }
7909 }
7910
7911 /* Compute the physnames of any methods on the CU's method list.
7912
7913    The computation of method physnames is delayed in order to avoid the
7914    (bad) condition that one of the method's formal parameters is of an as yet
7915    incomplete type.  */
7916
7917 static void
7918 compute_delayed_physnames (struct dwarf2_cu *cu)
7919 {
7920   int i;
7921   struct delayed_method_info *mi;
7922   for (i = 0; VEC_iterate (delayed_method_info, cu->method_list, i, mi) ; ++i)
7923     {
7924       const char *physname;
7925       struct fn_fieldlist *fn_flp
7926         = &TYPE_FN_FIELDLIST (mi->type, mi->fnfield_index);
7927       physname = dwarf2_physname (mi->name, mi->die, cu);
7928       TYPE_FN_FIELD_PHYSNAME (fn_flp->fn_fields, mi->index)
7929         = physname ? physname : "";
7930     }
7931 }
7932
7933 /* Go objects should be embedded in a DW_TAG_module DIE,
7934    and it's not clear if/how imported objects will appear.
7935    To keep Go support simple until that's worked out,
7936    go back through what we've read and create something usable.
7937    We could do this while processing each DIE, and feels kinda cleaner,
7938    but that way is more invasive.
7939    This is to, for example, allow the user to type "p var" or "b main"
7940    without having to specify the package name, and allow lookups
7941    of module.object to work in contexts that use the expression
7942    parser.  */
7943
7944 static void
7945 fixup_go_packaging (struct dwarf2_cu *cu)
7946 {
7947   char *package_name = NULL;
7948   struct pending *list;
7949   int i;
7950
7951   for (list = global_symbols; list != NULL; list = list->next)
7952     {
7953       for (i = 0; i < list->nsyms; ++i)
7954         {
7955           struct symbol *sym = list->symbol[i];
7956
7957           if (SYMBOL_LANGUAGE (sym) == language_go
7958               && SYMBOL_CLASS (sym) == LOC_BLOCK)
7959             {
7960               char *this_package_name = go_symbol_package_name (sym);
7961
7962               if (this_package_name == NULL)
7963                 continue;
7964               if (package_name == NULL)
7965                 package_name = this_package_name;
7966               else
7967                 {
7968                   if (strcmp (package_name, this_package_name) != 0)
7969                     complaint (&symfile_complaints,
7970                                _("Symtab %s has objects from two different Go packages: %s and %s"),
7971                                (symbol_symtab (sym) != NULL
7972                                 ? symtab_to_filename_for_display
7973                                     (symbol_symtab (sym))
7974                                 : objfile_name (cu->objfile)),
7975                                this_package_name, package_name);
7976                   xfree (this_package_name);
7977                 }
7978             }
7979         }
7980     }
7981
7982   if (package_name != NULL)
7983     {
7984       struct objfile *objfile = cu->objfile;
7985       const char *saved_package_name
7986         = (const char *) obstack_copy0 (&objfile->per_bfd->storage_obstack,
7987                                         package_name,
7988                                         strlen (package_name));
7989       struct type *type = init_type (objfile, TYPE_CODE_MODULE, 0,
7990                                      saved_package_name);
7991       struct symbol *sym;
7992
7993       TYPE_TAG_NAME (type) = TYPE_NAME (type);
7994
7995       sym = allocate_symbol (objfile);
7996       SYMBOL_SET_LANGUAGE (sym, language_go, &objfile->objfile_obstack);
7997       SYMBOL_SET_NAMES (sym, saved_package_name,
7998                         strlen (saved_package_name), 0, objfile);
7999       /* This is not VAR_DOMAIN because we want a way to ensure a lookup of,
8000          e.g., "main" finds the "main" module and not C's main().  */
8001       SYMBOL_DOMAIN (sym) = STRUCT_DOMAIN;
8002       SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
8003       SYMBOL_TYPE (sym) = type;
8004
8005       add_symbol_to_list (sym, &global_symbols);
8006
8007       xfree (package_name);
8008     }
8009 }
8010
8011 /* Return the symtab for PER_CU.  This works properly regardless of
8012    whether we're using the index or psymtabs.  */
8013
8014 static struct compunit_symtab *
8015 get_compunit_symtab (struct dwarf2_per_cu_data *per_cu)
8016 {
8017   return (dwarf2_per_objfile->using_index
8018           ? per_cu->v.quick->compunit_symtab
8019           : per_cu->v.psymtab->compunit_symtab);
8020 }
8021
8022 /* A helper function for computing the list of all symbol tables
8023    included by PER_CU.  */
8024
8025 static void
8026 recursively_compute_inclusions (VEC (compunit_symtab_ptr) **result,
8027                                 htab_t all_children, htab_t all_type_symtabs,
8028                                 struct dwarf2_per_cu_data *per_cu,
8029                                 struct compunit_symtab *immediate_parent)
8030 {
8031   void **slot;
8032   int ix;
8033   struct compunit_symtab *cust;
8034   struct dwarf2_per_cu_data *iter;
8035
8036   slot = htab_find_slot (all_children, per_cu, INSERT);
8037   if (*slot != NULL)
8038     {
8039       /* This inclusion and its children have been processed.  */
8040       return;
8041     }
8042
8043   *slot = per_cu;
8044   /* Only add a CU if it has a symbol table.  */
8045   cust = get_compunit_symtab (per_cu);
8046   if (cust != NULL)
8047     {
8048       /* If this is a type unit only add its symbol table if we haven't
8049          seen it yet (type unit per_cu's can share symtabs).  */
8050       if (per_cu->is_debug_types)
8051         {
8052           slot = htab_find_slot (all_type_symtabs, cust, INSERT);
8053           if (*slot == NULL)
8054             {
8055               *slot = cust;
8056               VEC_safe_push (compunit_symtab_ptr, *result, cust);
8057               if (cust->user == NULL)
8058                 cust->user = immediate_parent;
8059             }
8060         }
8061       else
8062         {
8063           VEC_safe_push (compunit_symtab_ptr, *result, cust);
8064           if (cust->user == NULL)
8065             cust->user = immediate_parent;
8066         }
8067     }
8068
8069   for (ix = 0;
8070        VEC_iterate (dwarf2_per_cu_ptr, per_cu->imported_symtabs, ix, iter);
8071        ++ix)
8072     {
8073       recursively_compute_inclusions (result, all_children,
8074                                       all_type_symtabs, iter, cust);
8075     }
8076 }
8077
8078 /* Compute the compunit_symtab 'includes' fields for the compunit_symtab of
8079    PER_CU.  */
8080
8081 static void
8082 compute_compunit_symtab_includes (struct dwarf2_per_cu_data *per_cu)
8083 {
8084   gdb_assert (! per_cu->is_debug_types);
8085
8086   if (!VEC_empty (dwarf2_per_cu_ptr, per_cu->imported_symtabs))
8087     {
8088       int ix, len;
8089       struct dwarf2_per_cu_data *per_cu_iter;
8090       struct compunit_symtab *compunit_symtab_iter;
8091       VEC (compunit_symtab_ptr) *result_symtabs = NULL;
8092       htab_t all_children, all_type_symtabs;
8093       struct compunit_symtab *cust = get_compunit_symtab (per_cu);
8094
8095       /* If we don't have a symtab, we can just skip this case.  */
8096       if (cust == NULL)
8097         return;
8098
8099       all_children = htab_create_alloc (1, htab_hash_pointer, htab_eq_pointer,
8100                                         NULL, xcalloc, xfree);
8101       all_type_symtabs = htab_create_alloc (1, htab_hash_pointer, htab_eq_pointer,
8102                                             NULL, xcalloc, xfree);
8103
8104       for (ix = 0;
8105            VEC_iterate (dwarf2_per_cu_ptr, per_cu->imported_symtabs,
8106                         ix, per_cu_iter);
8107            ++ix)
8108         {
8109           recursively_compute_inclusions (&result_symtabs, all_children,
8110                                           all_type_symtabs, per_cu_iter,
8111                                           cust);
8112         }
8113
8114       /* Now we have a transitive closure of all the included symtabs.  */
8115       len = VEC_length (compunit_symtab_ptr, result_symtabs);
8116       cust->includes
8117         = XOBNEWVEC (&dwarf2_per_objfile->objfile->objfile_obstack,
8118                      struct compunit_symtab *, len + 1);
8119       for (ix = 0;
8120            VEC_iterate (compunit_symtab_ptr, result_symtabs, ix,
8121                         compunit_symtab_iter);
8122            ++ix)
8123         cust->includes[ix] = compunit_symtab_iter;
8124       cust->includes[len] = NULL;
8125
8126       VEC_free (compunit_symtab_ptr, result_symtabs);
8127       htab_delete (all_children);
8128       htab_delete (all_type_symtabs);
8129     }
8130 }
8131
8132 /* Compute the 'includes' field for the symtabs of all the CUs we just
8133    read.  */
8134
8135 static void
8136 process_cu_includes (void)
8137 {
8138   int ix;
8139   struct dwarf2_per_cu_data *iter;
8140
8141   for (ix = 0;
8142        VEC_iterate (dwarf2_per_cu_ptr, dwarf2_per_objfile->just_read_cus,
8143                     ix, iter);
8144        ++ix)
8145     {
8146       if (! iter->is_debug_types)
8147         compute_compunit_symtab_includes (iter);
8148     }
8149
8150   VEC_free (dwarf2_per_cu_ptr, dwarf2_per_objfile->just_read_cus);
8151 }
8152
8153 /* Generate full symbol information for PER_CU, whose DIEs have
8154    already been loaded into memory.  */
8155
8156 static void
8157 process_full_comp_unit (struct dwarf2_per_cu_data *per_cu,
8158                         enum language pretend_language)
8159 {
8160   struct dwarf2_cu *cu = per_cu->cu;
8161   struct objfile *objfile = per_cu->objfile;
8162   struct gdbarch *gdbarch = get_objfile_arch (objfile);
8163   CORE_ADDR lowpc, highpc;
8164   struct compunit_symtab *cust;
8165   struct cleanup *back_to, *delayed_list_cleanup;
8166   CORE_ADDR baseaddr;
8167   struct block *static_block;
8168   CORE_ADDR addr;
8169
8170   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
8171
8172   buildsym_init ();
8173   back_to = make_cleanup (really_free_pendings, NULL);
8174   delayed_list_cleanup = make_cleanup (free_delayed_list, cu);
8175
8176   cu->list_in_scope = &file_symbols;
8177
8178   cu->language = pretend_language;
8179   cu->language_defn = language_def (cu->language);
8180
8181   /* Do line number decoding in read_file_scope () */
8182   process_die (cu->dies, cu);
8183
8184   /* For now fudge the Go package.  */
8185   if (cu->language == language_go)
8186     fixup_go_packaging (cu);
8187
8188   /* Now that we have processed all the DIEs in the CU, all the types 
8189      should be complete, and it should now be safe to compute all of the
8190      physnames.  */
8191   compute_delayed_physnames (cu);
8192   do_cleanups (delayed_list_cleanup);
8193
8194   /* Some compilers don't define a DW_AT_high_pc attribute for the
8195      compilation unit.  If the DW_AT_high_pc is missing, synthesize
8196      it, by scanning the DIE's below the compilation unit.  */
8197   get_scope_pc_bounds (cu->dies, &lowpc, &highpc, cu);
8198
8199   addr = gdbarch_adjust_dwarf2_addr (gdbarch, highpc + baseaddr);
8200   static_block = end_symtab_get_static_block (addr, 0, 1);
8201
8202   /* If the comp unit has DW_AT_ranges, it may have discontiguous ranges.
8203      Also, DW_AT_ranges may record ranges not belonging to any child DIEs
8204      (such as virtual method tables).  Record the ranges in STATIC_BLOCK's
8205      addrmap to help ensure it has an accurate map of pc values belonging to
8206      this comp unit.  */
8207   dwarf2_record_block_ranges (cu->dies, static_block, baseaddr, cu);
8208
8209   cust = end_symtab_from_static_block (static_block,
8210                                        SECT_OFF_TEXT (objfile), 0);
8211
8212   if (cust != NULL)
8213     {
8214       int gcc_4_minor = producer_is_gcc_ge_4 (cu->producer);
8215
8216       /* Set symtab language to language from DW_AT_language.  If the
8217          compilation is from a C file generated by language preprocessors, do
8218          not set the language if it was already deduced by start_subfile.  */
8219       if (!(cu->language == language_c
8220             && COMPUNIT_FILETABS (cust)->language != language_unknown))
8221         COMPUNIT_FILETABS (cust)->language = cu->language;
8222
8223       /* GCC-4.0 has started to support -fvar-tracking.  GCC-3.x still can
8224          produce DW_AT_location with location lists but it can be possibly
8225          invalid without -fvar-tracking.  Still up to GCC-4.4.x incl. 4.4.0
8226          there were bugs in prologue debug info, fixed later in GCC-4.5
8227          by "unwind info for epilogues" patch (which is not directly related).
8228
8229          For -gdwarf-4 type units LOCATIONS_VALID indication is fortunately not
8230          needed, it would be wrong due to missing DW_AT_producer there.
8231
8232          Still one can confuse GDB by using non-standard GCC compilation
8233          options - this waits on GCC PR other/32998 (-frecord-gcc-switches).
8234          */ 
8235       if (cu->has_loclist && gcc_4_minor >= 5)
8236         cust->locations_valid = 1;
8237
8238       if (gcc_4_minor >= 5)
8239         cust->epilogue_unwind_valid = 1;
8240
8241       cust->call_site_htab = cu->call_site_htab;
8242     }
8243
8244   if (dwarf2_per_objfile->using_index)
8245     per_cu->v.quick->compunit_symtab = cust;
8246   else
8247     {
8248       struct partial_symtab *pst = per_cu->v.psymtab;
8249       pst->compunit_symtab = cust;
8250       pst->readin = 1;
8251     }
8252
8253   /* Push it for inclusion processing later.  */
8254   VEC_safe_push (dwarf2_per_cu_ptr, dwarf2_per_objfile->just_read_cus, per_cu);
8255
8256   do_cleanups (back_to);
8257 }
8258
8259 /* Generate full symbol information for type unit PER_CU, whose DIEs have
8260    already been loaded into memory.  */
8261
8262 static void
8263 process_full_type_unit (struct dwarf2_per_cu_data *per_cu,
8264                         enum language pretend_language)
8265 {
8266   struct dwarf2_cu *cu = per_cu->cu;
8267   struct objfile *objfile = per_cu->objfile;
8268   struct compunit_symtab *cust;
8269   struct cleanup *back_to, *delayed_list_cleanup;
8270   struct signatured_type *sig_type;
8271
8272   gdb_assert (per_cu->is_debug_types);
8273   sig_type = (struct signatured_type *) per_cu;
8274
8275   buildsym_init ();
8276   back_to = make_cleanup (really_free_pendings, NULL);
8277   delayed_list_cleanup = make_cleanup (free_delayed_list, cu);
8278
8279   cu->list_in_scope = &file_symbols;
8280
8281   cu->language = pretend_language;
8282   cu->language_defn = language_def (cu->language);
8283
8284   /* The symbol tables are set up in read_type_unit_scope.  */
8285   process_die (cu->dies, cu);
8286
8287   /* For now fudge the Go package.  */
8288   if (cu->language == language_go)
8289     fixup_go_packaging (cu);
8290
8291   /* Now that we have processed all the DIEs in the CU, all the types 
8292      should be complete, and it should now be safe to compute all of the
8293      physnames.  */
8294   compute_delayed_physnames (cu);
8295   do_cleanups (delayed_list_cleanup);
8296
8297   /* TUs share symbol tables.
8298      If this is the first TU to use this symtab, complete the construction
8299      of it with end_expandable_symtab.  Otherwise, complete the addition of
8300      this TU's symbols to the existing symtab.  */
8301   if (sig_type->type_unit_group->compunit_symtab == NULL)
8302     {
8303       cust = end_expandable_symtab (0, SECT_OFF_TEXT (objfile));
8304       sig_type->type_unit_group->compunit_symtab = cust;
8305
8306       if (cust != NULL)
8307         {
8308           /* Set symtab language to language from DW_AT_language.  If the
8309              compilation is from a C file generated by language preprocessors,
8310              do not set the language if it was already deduced by
8311              start_subfile.  */
8312           if (!(cu->language == language_c
8313                 && COMPUNIT_FILETABS (cust)->language != language_c))
8314             COMPUNIT_FILETABS (cust)->language = cu->language;
8315         }
8316     }
8317   else
8318     {
8319       augment_type_symtab ();
8320       cust = sig_type->type_unit_group->compunit_symtab;
8321     }
8322
8323   if (dwarf2_per_objfile->using_index)
8324     per_cu->v.quick->compunit_symtab = cust;
8325   else
8326     {
8327       struct partial_symtab *pst = per_cu->v.psymtab;
8328       pst->compunit_symtab = cust;
8329       pst->readin = 1;
8330     }
8331
8332   do_cleanups (back_to);
8333 }
8334
8335 /* Process an imported unit DIE.  */
8336
8337 static void
8338 process_imported_unit_die (struct die_info *die, struct dwarf2_cu *cu)
8339 {
8340   struct attribute *attr;
8341
8342   /* For now we don't handle imported units in type units.  */
8343   if (cu->per_cu->is_debug_types)
8344     {
8345       error (_("Dwarf Error: DW_TAG_imported_unit is not"
8346                " supported in type units [in module %s]"),
8347              objfile_name (cu->objfile));
8348     }
8349
8350   attr = dwarf2_attr (die, DW_AT_import, cu);
8351   if (attr != NULL)
8352     {
8353       struct dwarf2_per_cu_data *per_cu;
8354       sect_offset offset;
8355       int is_dwz;
8356
8357       offset = dwarf2_get_ref_die_offset (attr);
8358       is_dwz = (attr->form == DW_FORM_GNU_ref_alt || cu->per_cu->is_dwz);
8359       per_cu = dwarf2_find_containing_comp_unit (offset, is_dwz, cu->objfile);
8360
8361       /* If necessary, add it to the queue and load its DIEs.  */
8362       if (maybe_queue_comp_unit (cu, per_cu, cu->language))
8363         load_full_comp_unit (per_cu, cu->language);
8364
8365       VEC_safe_push (dwarf2_per_cu_ptr, cu->per_cu->imported_symtabs,
8366                      per_cu);
8367     }
8368 }
8369
8370 /* Reset the in_process bit of a die.  */
8371
8372 static void
8373 reset_die_in_process (void *arg)
8374 {
8375   struct die_info *die = (struct die_info *) arg;
8376
8377   die->in_process = 0;
8378 }
8379
8380 /* Process a die and its children.  */
8381
8382 static void
8383 process_die (struct die_info *die, struct dwarf2_cu *cu)
8384 {
8385   struct cleanup *in_process;
8386
8387   /* We should only be processing those not already in process.  */
8388   gdb_assert (!die->in_process);
8389
8390   die->in_process = 1;
8391   in_process = make_cleanup (reset_die_in_process,die);
8392
8393   switch (die->tag)
8394     {
8395     case DW_TAG_padding:
8396       break;
8397     case DW_TAG_compile_unit:
8398     case DW_TAG_partial_unit:
8399       read_file_scope (die, cu);
8400       break;
8401     case DW_TAG_type_unit:
8402       read_type_unit_scope (die, cu);
8403       break;
8404     case DW_TAG_subprogram:
8405     case DW_TAG_inlined_subroutine:
8406       read_func_scope (die, cu);
8407       break;
8408     case DW_TAG_lexical_block:
8409     case DW_TAG_try_block:
8410     case DW_TAG_catch_block:
8411       read_lexical_block_scope (die, cu);
8412       break;
8413     case DW_TAG_call_site:
8414     case DW_TAG_GNU_call_site:
8415       read_call_site_scope (die, cu);
8416       break;
8417     case DW_TAG_class_type:
8418     case DW_TAG_interface_type:
8419     case DW_TAG_structure_type:
8420     case DW_TAG_union_type:
8421       process_structure_scope (die, cu);
8422       break;
8423     case DW_TAG_enumeration_type:
8424       process_enumeration_scope (die, cu);
8425       break;
8426
8427     /* These dies have a type, but processing them does not create
8428        a symbol or recurse to process the children.  Therefore we can
8429        read them on-demand through read_type_die.  */
8430     case DW_TAG_subroutine_type:
8431     case DW_TAG_set_type:
8432     case DW_TAG_array_type:
8433     case DW_TAG_pointer_type:
8434     case DW_TAG_ptr_to_member_type:
8435     case DW_TAG_reference_type:
8436     case DW_TAG_rvalue_reference_type:
8437     case DW_TAG_string_type:
8438       break;
8439
8440     case DW_TAG_base_type:
8441     case DW_TAG_subrange_type:
8442     case DW_TAG_typedef:
8443       /* Add a typedef symbol for the type definition, if it has a
8444          DW_AT_name.  */
8445       new_symbol (die, read_type_die (die, cu), cu);
8446       break;
8447     case DW_TAG_common_block:
8448       read_common_block (die, cu);
8449       break;
8450     case DW_TAG_common_inclusion:
8451       break;
8452     case DW_TAG_namespace:
8453       cu->processing_has_namespace_info = 1;
8454       read_namespace (die, cu);
8455       break;
8456     case DW_TAG_module:
8457       cu->processing_has_namespace_info = 1;
8458       read_module (die, cu);
8459       break;
8460     case DW_TAG_imported_declaration:
8461       cu->processing_has_namespace_info = 1;
8462       if (read_namespace_alias (die, cu))
8463         break;
8464       /* The declaration is not a global namespace alias: fall through.  */
8465     case DW_TAG_imported_module:
8466       cu->processing_has_namespace_info = 1;
8467       if (die->child != NULL && (die->tag == DW_TAG_imported_declaration
8468                                  || cu->language != language_fortran))
8469         complaint (&symfile_complaints, _("Tag '%s' has unexpected children"),
8470                    dwarf_tag_name (die->tag));
8471       read_import_statement (die, cu);
8472       break;
8473
8474     case DW_TAG_imported_unit:
8475       process_imported_unit_die (die, cu);
8476       break;
8477
8478     default:
8479       new_symbol (die, NULL, cu);
8480       break;
8481     }
8482
8483   do_cleanups (in_process);
8484 }
8485 \f
8486 /* DWARF name computation.  */
8487
8488 /* A helper function for dwarf2_compute_name which determines whether DIE
8489    needs to have the name of the scope prepended to the name listed in the
8490    die.  */
8491
8492 static int
8493 die_needs_namespace (struct die_info *die, struct dwarf2_cu *cu)
8494 {
8495   struct attribute *attr;
8496
8497   switch (die->tag)
8498     {
8499     case DW_TAG_namespace:
8500     case DW_TAG_typedef:
8501     case DW_TAG_class_type:
8502     case DW_TAG_interface_type:
8503     case DW_TAG_structure_type:
8504     case DW_TAG_union_type:
8505     case DW_TAG_enumeration_type:
8506     case DW_TAG_enumerator:
8507     case DW_TAG_subprogram:
8508     case DW_TAG_inlined_subroutine:
8509     case DW_TAG_member:
8510     case DW_TAG_imported_declaration:
8511       return 1;
8512
8513     case DW_TAG_variable:
8514     case DW_TAG_constant:
8515       /* We only need to prefix "globally" visible variables.  These include
8516          any variable marked with DW_AT_external or any variable that
8517          lives in a namespace.  [Variables in anonymous namespaces
8518          require prefixing, but they are not DW_AT_external.]  */
8519
8520       if (dwarf2_attr (die, DW_AT_specification, cu))
8521         {
8522           struct dwarf2_cu *spec_cu = cu;
8523
8524           return die_needs_namespace (die_specification (die, &spec_cu),
8525                                       spec_cu);
8526         }
8527
8528       attr = dwarf2_attr (die, DW_AT_external, cu);
8529       if (attr == NULL && die->parent->tag != DW_TAG_namespace
8530           && die->parent->tag != DW_TAG_module)
8531         return 0;
8532       /* A variable in a lexical block of some kind does not need a
8533          namespace, even though in C++ such variables may be external
8534          and have a mangled name.  */
8535       if (die->parent->tag ==  DW_TAG_lexical_block
8536           || die->parent->tag ==  DW_TAG_try_block
8537           || die->parent->tag ==  DW_TAG_catch_block
8538           || die->parent->tag == DW_TAG_subprogram)
8539         return 0;
8540       return 1;
8541
8542     default:
8543       return 0;
8544     }
8545 }
8546
8547 /* Compute the fully qualified name of DIE in CU.  If PHYSNAME is nonzero,
8548    compute the physname for the object, which include a method's:
8549    - formal parameters (C++),
8550    - receiver type (Go),
8551
8552    The term "physname" is a bit confusing.
8553    For C++, for example, it is the demangled name.
8554    For Go, for example, it's the mangled name.
8555
8556    For Ada, return the DIE's linkage name rather than the fully qualified
8557    name.  PHYSNAME is ignored..
8558
8559    The result is allocated on the objfile_obstack and canonicalized.  */
8560
8561 static const char *
8562 dwarf2_compute_name (const char *name,
8563                      struct die_info *die, struct dwarf2_cu *cu,
8564                      int physname)
8565 {
8566   struct objfile *objfile = cu->objfile;
8567
8568   if (name == NULL)
8569     name = dwarf2_name (die, cu);
8570
8571   /* For Fortran GDB prefers DW_AT_*linkage_name for the physname if present
8572      but otherwise compute it by typename_concat inside GDB.
8573      FIXME: Actually this is not really true, or at least not always true.
8574      It's all very confusing.  SYMBOL_SET_NAMES doesn't try to demangle
8575      Fortran names because there is no mangling standard.  So new_symbol_full
8576      will set the demangled name to the result of dwarf2_full_name, and it is
8577      the demangled name that GDB uses if it exists.  */
8578   if (cu->language == language_ada
8579       || (cu->language == language_fortran && physname))
8580     {
8581       /* For Ada unit, we prefer the linkage name over the name, as
8582          the former contains the exported name, which the user expects
8583          to be able to reference.  Ideally, we want the user to be able
8584          to reference this entity using either natural or linkage name,
8585          but we haven't started looking at this enhancement yet.  */
8586       const char *linkage_name;
8587
8588       linkage_name = dwarf2_string_attr (die, DW_AT_linkage_name, cu);
8589       if (linkage_name == NULL)
8590         linkage_name = dwarf2_string_attr (die, DW_AT_MIPS_linkage_name, cu);
8591       if (linkage_name != NULL)
8592         return linkage_name;
8593     }
8594
8595   /* These are the only languages we know how to qualify names in.  */
8596   if (name != NULL
8597       && (cu->language == language_cplus
8598           || cu->language == language_fortran || cu->language == language_d
8599           || cu->language == language_rust))
8600     {
8601       if (die_needs_namespace (die, cu))
8602         {
8603           long length;
8604           const char *prefix;
8605           const char *canonical_name = NULL;
8606
8607           string_file buf;
8608
8609           prefix = determine_prefix (die, cu);
8610           if (*prefix != '\0')
8611             {
8612               char *prefixed_name = typename_concat (NULL, prefix, name,
8613                                                      physname, cu);
8614
8615               buf.puts (prefixed_name);
8616               xfree (prefixed_name);
8617             }
8618           else
8619             buf.puts (name);
8620
8621           /* Template parameters may be specified in the DIE's DW_AT_name, or
8622              as children with DW_TAG_template_type_param or
8623              DW_TAG_value_type_param.  If the latter, add them to the name
8624              here.  If the name already has template parameters, then
8625              skip this step; some versions of GCC emit both, and
8626              it is more efficient to use the pre-computed name.
8627
8628              Something to keep in mind about this process: it is very
8629              unlikely, or in some cases downright impossible, to produce
8630              something that will match the mangled name of a function.
8631              If the definition of the function has the same debug info,
8632              we should be able to match up with it anyway.  But fallbacks
8633              using the minimal symbol, for instance to find a method
8634              implemented in a stripped copy of libstdc++, will not work.
8635              If we do not have debug info for the definition, we will have to
8636              match them up some other way.
8637
8638              When we do name matching there is a related problem with function
8639              templates; two instantiated function templates are allowed to
8640              differ only by their return types, which we do not add here.  */
8641
8642           if (cu->language == language_cplus && strchr (name, '<') == NULL)
8643             {
8644               struct attribute *attr;
8645               struct die_info *child;
8646               int first = 1;
8647
8648               die->building_fullname = 1;
8649
8650               for (child = die->child; child != NULL; child = child->sibling)
8651                 {
8652                   struct type *type;
8653                   LONGEST value;
8654                   const gdb_byte *bytes;
8655                   struct dwarf2_locexpr_baton *baton;
8656                   struct value *v;
8657
8658                   if (child->tag != DW_TAG_template_type_param
8659                       && child->tag != DW_TAG_template_value_param)
8660                     continue;
8661
8662                   if (first)
8663                     {
8664                       buf.puts ("<");
8665                       first = 0;
8666                     }
8667                   else
8668                     buf.puts (", ");
8669
8670                   attr = dwarf2_attr (child, DW_AT_type, cu);
8671                   if (attr == NULL)
8672                     {
8673                       complaint (&symfile_complaints,
8674                                  _("template parameter missing DW_AT_type"));
8675                       buf.puts ("UNKNOWN_TYPE");
8676                       continue;
8677                     }
8678                   type = die_type (child, cu);
8679
8680                   if (child->tag == DW_TAG_template_type_param)
8681                     {
8682                       c_print_type (type, "", &buf, -1, 0, &type_print_raw_options);
8683                       continue;
8684                     }
8685
8686                   attr = dwarf2_attr (child, DW_AT_const_value, cu);
8687                   if (attr == NULL)
8688                     {
8689                       complaint (&symfile_complaints,
8690                                  _("template parameter missing "
8691                                    "DW_AT_const_value"));
8692                       buf.puts ("UNKNOWN_VALUE");
8693                       continue;
8694                     }
8695
8696                   dwarf2_const_value_attr (attr, type, name,
8697                                            &cu->comp_unit_obstack, cu,
8698                                            &value, &bytes, &baton);
8699
8700                   if (TYPE_NOSIGN (type))
8701                     /* GDB prints characters as NUMBER 'CHAR'.  If that's
8702                        changed, this can use value_print instead.  */
8703                     c_printchar (value, type, &buf);
8704                   else
8705                     {
8706                       struct value_print_options opts;
8707
8708                       if (baton != NULL)
8709                         v = dwarf2_evaluate_loc_desc (type, NULL,
8710                                                       baton->data,
8711                                                       baton->size,
8712                                                       baton->per_cu);
8713                       else if (bytes != NULL)
8714                         {
8715                           v = allocate_value (type);
8716                           memcpy (value_contents_writeable (v), bytes,
8717                                   TYPE_LENGTH (type));
8718                         }
8719                       else
8720                         v = value_from_longest (type, value);
8721
8722                       /* Specify decimal so that we do not depend on
8723                          the radix.  */
8724                       get_formatted_print_options (&opts, 'd');
8725                       opts.raw = 1;
8726                       value_print (v, &buf, &opts);
8727                       release_value (v);
8728                       value_free (v);
8729                     }
8730                 }
8731
8732               die->building_fullname = 0;
8733
8734               if (!first)
8735                 {
8736                   /* Close the argument list, with a space if necessary
8737                      (nested templates).  */
8738                   if (!buf.empty () && buf.string ().back () == '>')
8739                     buf.puts (" >");
8740                   else
8741                     buf.puts (">");
8742                 }
8743             }
8744
8745           /* For C++ methods, append formal parameter type
8746              information, if PHYSNAME.  */
8747
8748           if (physname && die->tag == DW_TAG_subprogram
8749               && cu->language == language_cplus)
8750             {
8751               struct type *type = read_type_die (die, cu);
8752
8753               c_type_print_args (type, &buf, 1, cu->language,
8754                                  &type_print_raw_options);
8755
8756               if (cu->language == language_cplus)
8757                 {
8758                   /* Assume that an artificial first parameter is
8759                      "this", but do not crash if it is not.  RealView
8760                      marks unnamed (and thus unused) parameters as
8761                      artificial; there is no way to differentiate
8762                      the two cases.  */
8763                   if (TYPE_NFIELDS (type) > 0
8764                       && TYPE_FIELD_ARTIFICIAL (type, 0)
8765                       && TYPE_CODE (TYPE_FIELD_TYPE (type, 0)) == TYPE_CODE_PTR
8766                       && TYPE_CONST (TYPE_TARGET_TYPE (TYPE_FIELD_TYPE (type,
8767                                                                         0))))
8768                     buf.puts (" const");
8769                 }
8770             }
8771
8772           const std::string &intermediate_name = buf.string ();
8773
8774           if (cu->language == language_cplus)
8775             canonical_name
8776               = dwarf2_canonicalize_name (intermediate_name.c_str (), cu,
8777                                           &objfile->per_bfd->storage_obstack);
8778
8779           /* If we only computed INTERMEDIATE_NAME, or if
8780              INTERMEDIATE_NAME is already canonical, then we need to
8781              copy it to the appropriate obstack.  */
8782           if (canonical_name == NULL || canonical_name == intermediate_name.c_str ())
8783             name = ((const char *)
8784                     obstack_copy0 (&objfile->per_bfd->storage_obstack,
8785                                    intermediate_name.c_str (),
8786                                    intermediate_name.length ()));
8787           else
8788             name = canonical_name;
8789         }
8790     }
8791
8792   return name;
8793 }
8794
8795 /* Return the fully qualified name of DIE, based on its DW_AT_name.
8796    If scope qualifiers are appropriate they will be added.  The result
8797    will be allocated on the storage_obstack, or NULL if the DIE does
8798    not have a name.  NAME may either be from a previous call to
8799    dwarf2_name or NULL.
8800
8801    The output string will be canonicalized (if C++).  */
8802
8803 static const char *
8804 dwarf2_full_name (const char *name, struct die_info *die, struct dwarf2_cu *cu)
8805 {
8806   return dwarf2_compute_name (name, die, cu, 0);
8807 }
8808
8809 /* Construct a physname for the given DIE in CU.  NAME may either be
8810    from a previous call to dwarf2_name or NULL.  The result will be
8811    allocated on the objfile_objstack or NULL if the DIE does not have a
8812    name.
8813
8814    The output string will be canonicalized (if C++).  */
8815
8816 static const char *
8817 dwarf2_physname (const char *name, struct die_info *die, struct dwarf2_cu *cu)
8818 {
8819   struct objfile *objfile = cu->objfile;
8820   const char *retval, *mangled = NULL, *canon = NULL;
8821   struct cleanup *back_to;
8822   int need_copy = 1;
8823
8824   /* In this case dwarf2_compute_name is just a shortcut not building anything
8825      on its own.  */
8826   if (!die_needs_namespace (die, cu))
8827     return dwarf2_compute_name (name, die, cu, 1);
8828
8829   back_to = make_cleanup (null_cleanup, NULL);
8830
8831   mangled = dwarf2_string_attr (die, DW_AT_linkage_name, cu);
8832   if (mangled == NULL)
8833     mangled = dwarf2_string_attr (die, DW_AT_MIPS_linkage_name, cu);
8834
8835   /* rustc emits invalid values for DW_AT_linkage_name.  Ignore these.
8836      See https://github.com/rust-lang/rust/issues/32925.  */
8837   if (cu->language == language_rust && mangled != NULL
8838       && strchr (mangled, '{') != NULL)
8839     mangled = NULL;
8840
8841   /* DW_AT_linkage_name is missing in some cases - depend on what GDB
8842      has computed.  */
8843   if (mangled != NULL)
8844     {
8845       char *demangled;
8846
8847       /* Use DMGL_RET_DROP for C++ template functions to suppress their return
8848          type.  It is easier for GDB users to search for such functions as
8849          `name(params)' than `long name(params)'.  In such case the minimal
8850          symbol names do not match the full symbol names but for template
8851          functions there is never a need to look up their definition from their
8852          declaration so the only disadvantage remains the minimal symbol
8853          variant `long name(params)' does not have the proper inferior type.
8854          */
8855
8856       if (cu->language == language_go)
8857         {
8858           /* This is a lie, but we already lie to the caller new_symbol_full.
8859              new_symbol_full assumes we return the mangled name.
8860              This just undoes that lie until things are cleaned up.  */
8861           demangled = NULL;
8862         }
8863       else
8864         {
8865           demangled = gdb_demangle (mangled,
8866                                     (DMGL_PARAMS | DMGL_ANSI | DMGL_RET_DROP));
8867         }
8868       if (demangled)
8869         {
8870           make_cleanup (xfree, demangled);
8871           canon = demangled;
8872         }
8873       else
8874         {
8875           canon = mangled;
8876           need_copy = 0;
8877         }
8878     }
8879
8880   if (canon == NULL || check_physname)
8881     {
8882       const char *physname = dwarf2_compute_name (name, die, cu, 1);
8883
8884       if (canon != NULL && strcmp (physname, canon) != 0)
8885         {
8886           /* It may not mean a bug in GDB.  The compiler could also
8887              compute DW_AT_linkage_name incorrectly.  But in such case
8888              GDB would need to be bug-to-bug compatible.  */
8889
8890           complaint (&symfile_complaints,
8891                      _("Computed physname <%s> does not match demangled <%s> "
8892                        "(from linkage <%s>) - DIE at 0x%x [in module %s]"),
8893                      physname, canon, mangled, die->offset.sect_off,
8894                      objfile_name (objfile));
8895
8896           /* Prefer DW_AT_linkage_name (in the CANON form) - when it
8897              is available here - over computed PHYSNAME.  It is safer
8898              against both buggy GDB and buggy compilers.  */
8899
8900           retval = canon;
8901         }
8902       else
8903         {
8904           retval = physname;
8905           need_copy = 0;
8906         }
8907     }
8908   else
8909     retval = canon;
8910
8911   if (need_copy)
8912     retval = ((const char *)
8913               obstack_copy0 (&objfile->per_bfd->storage_obstack,
8914                              retval, strlen (retval)));
8915
8916   do_cleanups (back_to);
8917   return retval;
8918 }
8919
8920 /* Inspect DIE in CU for a namespace alias.  If one exists, record
8921    a new symbol for it.
8922
8923    Returns 1 if a namespace alias was recorded, 0 otherwise.  */
8924
8925 static int
8926 read_namespace_alias (struct die_info *die, struct dwarf2_cu *cu)
8927 {
8928   struct attribute *attr;
8929
8930   /* If the die does not have a name, this is not a namespace
8931      alias.  */
8932   attr = dwarf2_attr (die, DW_AT_name, cu);
8933   if (attr != NULL)
8934     {
8935       int num;
8936       struct die_info *d = die;
8937       struct dwarf2_cu *imported_cu = cu;
8938
8939       /* If the compiler has nested DW_AT_imported_declaration DIEs,
8940          keep inspecting DIEs until we hit the underlying import.  */
8941 #define MAX_NESTED_IMPORTED_DECLARATIONS 100
8942       for (num = 0; num  < MAX_NESTED_IMPORTED_DECLARATIONS; ++num)
8943         {
8944           attr = dwarf2_attr (d, DW_AT_import, cu);
8945           if (attr == NULL)
8946             break;
8947
8948           d = follow_die_ref (d, attr, &imported_cu);
8949           if (d->tag != DW_TAG_imported_declaration)
8950             break;
8951         }
8952
8953       if (num == MAX_NESTED_IMPORTED_DECLARATIONS)
8954         {
8955           complaint (&symfile_complaints,
8956                      _("DIE at 0x%x has too many recursively imported "
8957                        "declarations"), d->offset.sect_off);
8958           return 0;
8959         }
8960
8961       if (attr != NULL)
8962         {
8963           struct type *type;
8964           sect_offset offset = dwarf2_get_ref_die_offset (attr);
8965
8966           type = get_die_type_at_offset (offset, cu->per_cu);
8967           if (type != NULL && TYPE_CODE (type) == TYPE_CODE_NAMESPACE)
8968             {
8969               /* This declaration is a global namespace alias.  Add
8970                  a symbol for it whose type is the aliased namespace.  */
8971               new_symbol (die, type, cu);
8972               return 1;
8973             }
8974         }
8975     }
8976
8977   return 0;
8978 }
8979
8980 /* Return the using directives repository (global or local?) to use in the
8981    current context for LANGUAGE.
8982
8983    For Ada, imported declarations can materialize renamings, which *may* be
8984    global.  However it is impossible (for now?) in DWARF to distinguish
8985    "external" imported declarations and "static" ones.  As all imported
8986    declarations seem to be static in all other languages, make them all CU-wide
8987    global only in Ada.  */
8988
8989 static struct using_direct **
8990 using_directives (enum language language)
8991 {
8992   if (language == language_ada && context_stack_depth == 0)
8993     return &global_using_directives;
8994   else
8995     return &local_using_directives;
8996 }
8997
8998 /* Read the import statement specified by the given die and record it.  */
8999
9000 static void
9001 read_import_statement (struct die_info *die, struct dwarf2_cu *cu)
9002 {
9003   struct objfile *objfile = cu->objfile;
9004   struct attribute *import_attr;
9005   struct die_info *imported_die, *child_die;
9006   struct dwarf2_cu *imported_cu;
9007   const char *imported_name;
9008   const char *imported_name_prefix;
9009   const char *canonical_name;
9010   const char *import_alias;
9011   const char *imported_declaration = NULL;
9012   const char *import_prefix;
9013   VEC (const_char_ptr) *excludes = NULL;
9014   struct cleanup *cleanups;
9015
9016   import_attr = dwarf2_attr (die, DW_AT_import, cu);
9017   if (import_attr == NULL)
9018     {
9019       complaint (&symfile_complaints, _("Tag '%s' has no DW_AT_import"),
9020                  dwarf_tag_name (die->tag));
9021       return;
9022     }
9023
9024   imported_cu = cu;
9025   imported_die = follow_die_ref_or_sig (die, import_attr, &imported_cu);
9026   imported_name = dwarf2_name (imported_die, imported_cu);
9027   if (imported_name == NULL)
9028     {
9029       /* GCC bug: https://bugzilla.redhat.com/show_bug.cgi?id=506524
9030
9031         The import in the following code:
9032         namespace A
9033           {
9034             typedef int B;
9035           }
9036
9037         int main ()
9038           {
9039             using A::B;
9040             B b;
9041             return b;
9042           }
9043
9044         ...
9045          <2><51>: Abbrev Number: 3 (DW_TAG_imported_declaration)
9046             <52>   DW_AT_decl_file   : 1
9047             <53>   DW_AT_decl_line   : 6
9048             <54>   DW_AT_import      : <0x75>
9049          <2><58>: Abbrev Number: 4 (DW_TAG_typedef)
9050             <59>   DW_AT_name        : B
9051             <5b>   DW_AT_decl_file   : 1
9052             <5c>   DW_AT_decl_line   : 2
9053             <5d>   DW_AT_type        : <0x6e>
9054         ...
9055          <1><75>: Abbrev Number: 7 (DW_TAG_base_type)
9056             <76>   DW_AT_byte_size   : 4
9057             <77>   DW_AT_encoding    : 5        (signed)
9058
9059         imports the wrong die ( 0x75 instead of 0x58 ).
9060         This case will be ignored until the gcc bug is fixed.  */
9061       return;
9062     }
9063
9064   /* Figure out the local name after import.  */
9065   import_alias = dwarf2_name (die, cu);
9066
9067   /* Figure out where the statement is being imported to.  */
9068   import_prefix = determine_prefix (die, cu);
9069
9070   /* Figure out what the scope of the imported die is and prepend it
9071      to the name of the imported die.  */
9072   imported_name_prefix = determine_prefix (imported_die, imported_cu);
9073
9074   if (imported_die->tag != DW_TAG_namespace
9075       && imported_die->tag != DW_TAG_module)
9076     {
9077       imported_declaration = imported_name;
9078       canonical_name = imported_name_prefix;
9079     }
9080   else if (strlen (imported_name_prefix) > 0)
9081     canonical_name = obconcat (&objfile->objfile_obstack,
9082                                imported_name_prefix,
9083                                (cu->language == language_d ? "." : "::"),
9084                                imported_name, (char *) NULL);
9085   else
9086     canonical_name = imported_name;
9087
9088   cleanups = make_cleanup (VEC_cleanup (const_char_ptr), &excludes);
9089
9090   if (die->tag == DW_TAG_imported_module && cu->language == language_fortran)
9091     for (child_die = die->child; child_die && child_die->tag;
9092          child_die = sibling_die (child_die))
9093       {
9094         /* DWARF-4: A Fortran use statement with a “rename list” may be
9095            represented by an imported module entry with an import attribute
9096            referring to the module and owned entries corresponding to those
9097            entities that are renamed as part of being imported.  */
9098
9099         if (child_die->tag != DW_TAG_imported_declaration)
9100           {
9101             complaint (&symfile_complaints,
9102                        _("child DW_TAG_imported_declaration expected "
9103                          "- DIE at 0x%x [in module %s]"),
9104                        child_die->offset.sect_off, objfile_name (objfile));
9105             continue;
9106           }
9107
9108         import_attr = dwarf2_attr (child_die, DW_AT_import, cu);
9109         if (import_attr == NULL)
9110           {
9111             complaint (&symfile_complaints, _("Tag '%s' has no DW_AT_import"),
9112                        dwarf_tag_name (child_die->tag));
9113             continue;
9114           }
9115
9116         imported_cu = cu;
9117         imported_die = follow_die_ref_or_sig (child_die, import_attr,
9118                                               &imported_cu);
9119         imported_name = dwarf2_name (imported_die, imported_cu);
9120         if (imported_name == NULL)
9121           {
9122             complaint (&symfile_complaints,
9123                        _("child DW_TAG_imported_declaration has unknown "
9124                          "imported name - DIE at 0x%x [in module %s]"),
9125                        child_die->offset.sect_off, objfile_name (objfile));
9126             continue;
9127           }
9128
9129         VEC_safe_push (const_char_ptr, excludes, imported_name);
9130
9131         process_die (child_die, cu);
9132       }
9133
9134   add_using_directive (using_directives (cu->language),
9135                        import_prefix,
9136                        canonical_name,
9137                        import_alias,
9138                        imported_declaration,
9139                        excludes,
9140                        0,
9141                        &objfile->objfile_obstack);
9142
9143   do_cleanups (cleanups);
9144 }
9145
9146 /* Cleanup function for handle_DW_AT_stmt_list.  */
9147
9148 static void
9149 free_cu_line_header (void *arg)
9150 {
9151   struct dwarf2_cu *cu = (struct dwarf2_cu *) arg;
9152
9153   free_line_header (cu->line_header);
9154   cu->line_header = NULL;
9155 }
9156
9157 /* Check for possibly missing DW_AT_comp_dir with relative .debug_line
9158    directory paths.  GCC SVN r127613 (new option -fdebug-prefix-map) fixed
9159    this, it was first present in GCC release 4.3.0.  */
9160
9161 static int
9162 producer_is_gcc_lt_4_3 (struct dwarf2_cu *cu)
9163 {
9164   if (!cu->checked_producer)
9165     check_producer (cu);
9166
9167   return cu->producer_is_gcc_lt_4_3;
9168 }
9169
9170 static file_and_directory
9171 find_file_and_directory (struct die_info *die, struct dwarf2_cu *cu)
9172 {
9173   file_and_directory res;
9174
9175   /* Find the filename.  Do not use dwarf2_name here, since the filename
9176      is not a source language identifier.  */
9177   res.name = dwarf2_string_attr (die, DW_AT_name, cu);
9178   res.comp_dir = dwarf2_string_attr (die, DW_AT_comp_dir, cu);
9179
9180   if (res.comp_dir == NULL
9181       && producer_is_gcc_lt_4_3 (cu) && res.name != NULL
9182       && IS_ABSOLUTE_PATH (res.name))
9183     {
9184       res.comp_dir_storage = ldirname (res.name);
9185       if (!res.comp_dir_storage.empty ())
9186         res.comp_dir = res.comp_dir_storage.c_str ();
9187     }
9188   if (res.comp_dir != NULL)
9189     {
9190       /* Irix 6.2 native cc prepends <machine>.: to the compilation
9191          directory, get rid of it.  */
9192       const char *cp = strchr (res.comp_dir, ':');
9193
9194       if (cp && cp != res.comp_dir && cp[-1] == '.' && cp[1] == '/')
9195         res.comp_dir = cp + 1;
9196     }
9197
9198   if (res.name == NULL)
9199     res.name = "<unknown>";
9200
9201   return res;
9202 }
9203
9204 /* Handle DW_AT_stmt_list for a compilation unit.
9205    DIE is the DW_TAG_compile_unit die for CU.
9206    COMP_DIR is the compilation directory.  LOWPC is passed to
9207    dwarf_decode_lines.  See dwarf_decode_lines comments about it.  */
9208
9209 static void
9210 handle_DW_AT_stmt_list (struct die_info *die, struct dwarf2_cu *cu,
9211                         const char *comp_dir, CORE_ADDR lowpc) /* ARI: editCase function */
9212 {
9213   struct objfile *objfile = dwarf2_per_objfile->objfile;
9214   struct attribute *attr;
9215   unsigned int line_offset;
9216   struct line_header line_header_local;
9217   hashval_t line_header_local_hash;
9218   unsigned u;
9219   void **slot;
9220   int decode_mapping;
9221
9222   gdb_assert (! cu->per_cu->is_debug_types);
9223
9224   attr = dwarf2_attr (die, DW_AT_stmt_list, cu);
9225   if (attr == NULL)
9226     return;
9227
9228   line_offset = DW_UNSND (attr);
9229
9230   /* The line header hash table is only created if needed (it exists to
9231      prevent redundant reading of the line table for partial_units).
9232      If we're given a partial_unit, we'll need it.  If we're given a
9233      compile_unit, then use the line header hash table if it's already
9234      created, but don't create one just yet.  */
9235
9236   if (dwarf2_per_objfile->line_header_hash == NULL
9237       && die->tag == DW_TAG_partial_unit)
9238     {
9239       dwarf2_per_objfile->line_header_hash
9240         = htab_create_alloc_ex (127, line_header_hash_voidp,
9241                                 line_header_eq_voidp,
9242                                 free_line_header_voidp,
9243                                 &objfile->objfile_obstack,
9244                                 hashtab_obstack_allocate,
9245                                 dummy_obstack_deallocate);
9246     }
9247
9248   line_header_local.offset.sect_off = line_offset;
9249   line_header_local.offset_in_dwz = cu->per_cu->is_dwz;
9250   line_header_local_hash = line_header_hash (&line_header_local);
9251   if (dwarf2_per_objfile->line_header_hash != NULL)
9252     {
9253       slot = htab_find_slot_with_hash (dwarf2_per_objfile->line_header_hash,
9254                                        &line_header_local,
9255                                        line_header_local_hash, NO_INSERT);
9256
9257       /* For DW_TAG_compile_unit we need info like symtab::linetable which
9258          is not present in *SLOT (since if there is something in *SLOT then
9259          it will be for a partial_unit).  */
9260       if (die->tag == DW_TAG_partial_unit && slot != NULL)
9261         {
9262           gdb_assert (*slot != NULL);
9263           cu->line_header = (struct line_header *) *slot;
9264           return;
9265         }
9266     }
9267
9268   /* dwarf_decode_line_header does not yet provide sufficient information.
9269      We always have to call also dwarf_decode_lines for it.  */
9270   cu->line_header = dwarf_decode_line_header (line_offset, cu);
9271   if (cu->line_header == NULL)
9272     return;
9273
9274   if (dwarf2_per_objfile->line_header_hash == NULL)
9275     slot = NULL;
9276   else
9277     {
9278       slot = htab_find_slot_with_hash (dwarf2_per_objfile->line_header_hash,
9279                                        &line_header_local,
9280                                        line_header_local_hash, INSERT);
9281       gdb_assert (slot != NULL);
9282     }
9283   if (slot != NULL && *slot == NULL)
9284     {
9285       /* This newly decoded line number information unit will be owned
9286          by line_header_hash hash table.  */
9287       *slot = cu->line_header;
9288     }
9289   else
9290     {
9291       /* We cannot free any current entry in (*slot) as that struct line_header
9292          may be already used by multiple CUs.  Create only temporary decoded
9293          line_header for this CU - it may happen at most once for each line
9294          number information unit.  And if we're not using line_header_hash
9295          then this is what we want as well.  */
9296       gdb_assert (die->tag != DW_TAG_partial_unit);
9297       make_cleanup (free_cu_line_header, cu);
9298     }
9299   decode_mapping = (die->tag != DW_TAG_partial_unit);
9300   dwarf_decode_lines (cu->line_header, comp_dir, cu, NULL, lowpc,
9301                       decode_mapping);
9302 }
9303
9304 /* Process DW_TAG_compile_unit or DW_TAG_partial_unit.  */
9305
9306 static void
9307 read_file_scope (struct die_info *die, struct dwarf2_cu *cu)
9308 {
9309   struct objfile *objfile = dwarf2_per_objfile->objfile;
9310   struct gdbarch *gdbarch = get_objfile_arch (objfile);
9311   CORE_ADDR lowpc = ((CORE_ADDR) -1);
9312   CORE_ADDR highpc = ((CORE_ADDR) 0);
9313   struct attribute *attr;
9314   struct die_info *child_die;
9315   CORE_ADDR baseaddr;
9316
9317   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
9318
9319   get_scope_pc_bounds (die, &lowpc, &highpc, cu);
9320
9321   /* If we didn't find a lowpc, set it to highpc to avoid complaints
9322      from finish_block.  */
9323   if (lowpc == ((CORE_ADDR) -1))
9324     lowpc = highpc;
9325   lowpc = gdbarch_adjust_dwarf2_addr (gdbarch, lowpc + baseaddr);
9326
9327   file_and_directory fnd = find_file_and_directory (die, cu);
9328
9329   prepare_one_comp_unit (cu, die, cu->language);
9330
9331   /* The XLCL doesn't generate DW_LANG_OpenCL because this attribute is not
9332      standardised yet.  As a workaround for the language detection we fall
9333      back to the DW_AT_producer string.  */
9334   if (cu->producer && strstr (cu->producer, "IBM XL C for OpenCL") != NULL)
9335     cu->language = language_opencl;
9336
9337   /* Similar hack for Go.  */
9338   if (cu->producer && strstr (cu->producer, "GNU Go ") != NULL)
9339     set_cu_language (DW_LANG_Go, cu);
9340
9341   dwarf2_start_symtab (cu, fnd.name, fnd.comp_dir, lowpc);
9342
9343   /* Decode line number information if present.  We do this before
9344      processing child DIEs, so that the line header table is available
9345      for DW_AT_decl_file.  */
9346   handle_DW_AT_stmt_list (die, cu, fnd.comp_dir, lowpc);
9347
9348   /* Process all dies in compilation unit.  */
9349   if (die->child != NULL)
9350     {
9351       child_die = die->child;
9352       while (child_die && child_die->tag)
9353         {
9354           process_die (child_die, cu);
9355           child_die = sibling_die (child_die);
9356         }
9357     }
9358
9359   /* Decode macro information, if present.  Dwarf 2 macro information
9360      refers to information in the line number info statement program
9361      header, so we can only read it if we've read the header
9362      successfully.  */
9363   attr = dwarf2_attr (die, DW_AT_macros, cu);
9364   if (attr == NULL)
9365     attr = dwarf2_attr (die, DW_AT_GNU_macros, cu);
9366   if (attr && cu->line_header)
9367     {
9368       if (dwarf2_attr (die, DW_AT_macro_info, cu))
9369         complaint (&symfile_complaints,
9370                    _("CU refers to both DW_AT_macros and DW_AT_macro_info"));
9371
9372       dwarf_decode_macros (cu, DW_UNSND (attr), 1);
9373     }
9374   else
9375     {
9376       attr = dwarf2_attr (die, DW_AT_macro_info, cu);
9377       if (attr && cu->line_header)
9378         {
9379           unsigned int macro_offset = DW_UNSND (attr);
9380
9381           dwarf_decode_macros (cu, macro_offset, 0);
9382         }
9383     }
9384 }
9385
9386 /* TU version of handle_DW_AT_stmt_list for read_type_unit_scope.
9387    Create the set of symtabs used by this TU, or if this TU is sharing
9388    symtabs with another TU and the symtabs have already been created
9389    then restore those symtabs in the line header.
9390    We don't need the pc/line-number mapping for type units.  */
9391
9392 static void
9393 setup_type_unit_groups (struct die_info *die, struct dwarf2_cu *cu)
9394 {
9395   struct dwarf2_per_cu_data *per_cu = cu->per_cu;
9396   struct type_unit_group *tu_group;
9397   int first_time;
9398   struct line_header *lh;
9399   struct attribute *attr;
9400   unsigned int i, line_offset;
9401   struct signatured_type *sig_type;
9402
9403   gdb_assert (per_cu->is_debug_types);
9404   sig_type = (struct signatured_type *) per_cu;
9405
9406   attr = dwarf2_attr (die, DW_AT_stmt_list, cu);
9407
9408   /* If we're using .gdb_index (includes -readnow) then
9409      per_cu->type_unit_group may not have been set up yet.  */
9410   if (sig_type->type_unit_group == NULL)
9411     sig_type->type_unit_group = get_type_unit_group (cu, attr);
9412   tu_group = sig_type->type_unit_group;
9413
9414   /* If we've already processed this stmt_list there's no real need to
9415      do it again, we could fake it and just recreate the part we need
9416      (file name,index -> symtab mapping).  If data shows this optimization
9417      is useful we can do it then.  */
9418   first_time = tu_group->compunit_symtab == NULL;
9419
9420   /* We have to handle the case of both a missing DW_AT_stmt_list or bad
9421      debug info.  */
9422   lh = NULL;
9423   if (attr != NULL)
9424     {
9425       line_offset = DW_UNSND (attr);
9426       lh = dwarf_decode_line_header (line_offset, cu);
9427     }
9428   if (lh == NULL)
9429     {
9430       if (first_time)
9431         dwarf2_start_symtab (cu, "", NULL, 0);
9432       else
9433         {
9434           gdb_assert (tu_group->symtabs == NULL);
9435           restart_symtab (tu_group->compunit_symtab, "", 0);
9436         }
9437       return;
9438     }
9439
9440   cu->line_header = lh;
9441   make_cleanup (free_cu_line_header, cu);
9442
9443   if (first_time)
9444     {
9445       struct compunit_symtab *cust = dwarf2_start_symtab (cu, "", NULL, 0);
9446
9447       /* Note: We don't assign tu_group->compunit_symtab yet because we're
9448          still initializing it, and our caller (a few levels up)
9449          process_full_type_unit still needs to know if this is the first
9450          time.  */
9451
9452       tu_group->num_symtabs = lh->num_file_names;
9453       tu_group->symtabs = XNEWVEC (struct symtab *, lh->num_file_names);
9454
9455       for (i = 0; i < lh->num_file_names; ++i)
9456         {
9457           file_entry &fe = lh->file_names[i];
9458
9459           dwarf2_start_subfile (fe.name, fe.include_dir (lh));
9460
9461           if (current_subfile->symtab == NULL)
9462             {
9463               /* NOTE: start_subfile will recognize when it's been passed
9464                  a file it has already seen.  So we can't assume there's a
9465                  simple mapping from lh->file_names to subfiles, plus
9466                  lh->file_names may contain dups.  */
9467               current_subfile->symtab
9468                 = allocate_symtab (cust, current_subfile->name);
9469             }
9470
9471           fe.symtab = current_subfile->symtab;
9472           tu_group->symtabs[i] = fe.symtab;
9473         }
9474     }
9475   else
9476     {
9477       restart_symtab (tu_group->compunit_symtab, "", 0);
9478
9479       for (i = 0; i < lh->num_file_names; ++i)
9480         {
9481           struct file_entry *fe = &lh->file_names[i];
9482
9483           fe->symtab = tu_group->symtabs[i];
9484         }
9485     }
9486
9487   /* The main symtab is allocated last.  Type units don't have DW_AT_name
9488      so they don't have a "real" (so to speak) symtab anyway.
9489      There is later code that will assign the main symtab to all symbols
9490      that don't have one.  We need to handle the case of a symbol with a
9491      missing symtab (DW_AT_decl_file) anyway.  */
9492 }
9493
9494 /* Process DW_TAG_type_unit.
9495    For TUs we want to skip the first top level sibling if it's not the
9496    actual type being defined by this TU.  In this case the first top
9497    level sibling is there to provide context only.  */
9498
9499 static void
9500 read_type_unit_scope (struct die_info *die, struct dwarf2_cu *cu)
9501 {
9502   struct die_info *child_die;
9503
9504   prepare_one_comp_unit (cu, die, language_minimal);
9505
9506   /* Initialize (or reinitialize) the machinery for building symtabs.
9507      We do this before processing child DIEs, so that the line header table
9508      is available for DW_AT_decl_file.  */
9509   setup_type_unit_groups (die, cu);
9510
9511   if (die->child != NULL)
9512     {
9513       child_die = die->child;
9514       while (child_die && child_die->tag)
9515         {
9516           process_die (child_die, cu);
9517           child_die = sibling_die (child_die);
9518         }
9519     }
9520 }
9521 \f
9522 /* DWO/DWP files.
9523
9524    http://gcc.gnu.org/wiki/DebugFission
9525    http://gcc.gnu.org/wiki/DebugFissionDWP
9526
9527    To simplify handling of both DWO files ("object" files with the DWARF info)
9528    and DWP files (a file with the DWOs packaged up into one file), we treat
9529    DWP files as having a collection of virtual DWO files.  */
9530
9531 static hashval_t
9532 hash_dwo_file (const void *item)
9533 {
9534   const struct dwo_file *dwo_file = (const struct dwo_file *) item;
9535   hashval_t hash;
9536
9537   hash = htab_hash_string (dwo_file->dwo_name);
9538   if (dwo_file->comp_dir != NULL)
9539     hash += htab_hash_string (dwo_file->comp_dir);
9540   return hash;
9541 }
9542
9543 static int
9544 eq_dwo_file (const void *item_lhs, const void *item_rhs)
9545 {
9546   const struct dwo_file *lhs = (const struct dwo_file *) item_lhs;
9547   const struct dwo_file *rhs = (const struct dwo_file *) item_rhs;
9548
9549   if (strcmp (lhs->dwo_name, rhs->dwo_name) != 0)
9550     return 0;
9551   if (lhs->comp_dir == NULL || rhs->comp_dir == NULL)
9552     return lhs->comp_dir == rhs->comp_dir;
9553   return strcmp (lhs->comp_dir, rhs->comp_dir) == 0;
9554 }
9555
9556 /* Allocate a hash table for DWO files.  */
9557
9558 static htab_t
9559 allocate_dwo_file_hash_table (void)
9560 {
9561   struct objfile *objfile = dwarf2_per_objfile->objfile;
9562
9563   return htab_create_alloc_ex (41,
9564                                hash_dwo_file,
9565                                eq_dwo_file,
9566                                NULL,
9567                                &objfile->objfile_obstack,
9568                                hashtab_obstack_allocate,
9569                                dummy_obstack_deallocate);
9570 }
9571
9572 /* Lookup DWO file DWO_NAME.  */
9573
9574 static void **
9575 lookup_dwo_file_slot (const char *dwo_name, const char *comp_dir)
9576 {
9577   struct dwo_file find_entry;
9578   void **slot;
9579
9580   if (dwarf2_per_objfile->dwo_files == NULL)
9581     dwarf2_per_objfile->dwo_files = allocate_dwo_file_hash_table ();
9582
9583   memset (&find_entry, 0, sizeof (find_entry));
9584   find_entry.dwo_name = dwo_name;
9585   find_entry.comp_dir = comp_dir;
9586   slot = htab_find_slot (dwarf2_per_objfile->dwo_files, &find_entry, INSERT);
9587
9588   return slot;
9589 }
9590
9591 static hashval_t
9592 hash_dwo_unit (const void *item)
9593 {
9594   const struct dwo_unit *dwo_unit = (const struct dwo_unit *) item;
9595
9596   /* This drops the top 32 bits of the id, but is ok for a hash.  */
9597   return dwo_unit->signature;
9598 }
9599
9600 static int
9601 eq_dwo_unit (const void *item_lhs, const void *item_rhs)
9602 {
9603   const struct dwo_unit *lhs = (const struct dwo_unit *) item_lhs;
9604   const struct dwo_unit *rhs = (const struct dwo_unit *) item_rhs;
9605
9606   /* The signature is assumed to be unique within the DWO file.
9607      So while object file CU dwo_id's always have the value zero,
9608      that's OK, assuming each object file DWO file has only one CU,
9609      and that's the rule for now.  */
9610   return lhs->signature == rhs->signature;
9611 }
9612
9613 /* Allocate a hash table for DWO CUs,TUs.
9614    There is one of these tables for each of CUs,TUs for each DWO file.  */
9615
9616 static htab_t
9617 allocate_dwo_unit_table (struct objfile *objfile)
9618 {
9619   /* Start out with a pretty small number.
9620      Generally DWO files contain only one CU and maybe some TUs.  */
9621   return htab_create_alloc_ex (3,
9622                                hash_dwo_unit,
9623                                eq_dwo_unit,
9624                                NULL,
9625                                &objfile->objfile_obstack,
9626                                hashtab_obstack_allocate,
9627                                dummy_obstack_deallocate);
9628 }
9629
9630 /* Structure used to pass data to create_dwo_debug_info_hash_table_reader.  */
9631
9632 struct create_dwo_cu_data
9633 {
9634   struct dwo_file *dwo_file;
9635   struct dwo_unit dwo_unit;
9636 };
9637
9638 /* die_reader_func for create_dwo_cu.  */
9639
9640 static void
9641 create_dwo_cu_reader (const struct die_reader_specs *reader,
9642                       const gdb_byte *info_ptr,
9643                       struct die_info *comp_unit_die,
9644                       int has_children,
9645                       void *datap)
9646 {
9647   struct dwarf2_cu *cu = reader->cu;
9648   sect_offset offset = cu->per_cu->offset;
9649   struct dwarf2_section_info *section = cu->per_cu->section;
9650   struct create_dwo_cu_data *data = (struct create_dwo_cu_data *) datap;
9651   struct dwo_file *dwo_file = data->dwo_file;
9652   struct dwo_unit *dwo_unit = &data->dwo_unit;
9653   struct attribute *attr;
9654
9655   attr = dwarf2_attr (comp_unit_die, DW_AT_GNU_dwo_id, cu);
9656   if (attr == NULL)
9657     {
9658       complaint (&symfile_complaints,
9659                  _("Dwarf Error: debug entry at offset 0x%x is missing"
9660                    " its dwo_id [in module %s]"),
9661                  offset.sect_off, dwo_file->dwo_name);
9662       return;
9663     }
9664
9665   dwo_unit->dwo_file = dwo_file;
9666   dwo_unit->signature = DW_UNSND (attr);
9667   dwo_unit->section = section;
9668   dwo_unit->offset = offset;
9669   dwo_unit->length = cu->per_cu->length;
9670
9671   if (dwarf_read_debug)
9672     fprintf_unfiltered (gdb_stdlog, "  offset 0x%x, dwo_id %s\n",
9673                         offset.sect_off, hex_string (dwo_unit->signature));
9674 }
9675
9676 /* Create the dwo_unit for the lone CU in DWO_FILE.
9677    Note: This function processes DWO files only, not DWP files.  */
9678
9679 static struct dwo_unit *
9680 create_dwo_cu (struct dwo_file *dwo_file)
9681 {
9682   struct objfile *objfile = dwarf2_per_objfile->objfile;
9683   struct dwarf2_section_info *section = &dwo_file->sections.info;
9684   const gdb_byte *info_ptr, *end_ptr;
9685   struct create_dwo_cu_data create_dwo_cu_data;
9686   struct dwo_unit *dwo_unit;
9687
9688   dwarf2_read_section (objfile, section);
9689   info_ptr = section->buffer;
9690
9691   if (info_ptr == NULL)
9692     return NULL;
9693
9694   if (dwarf_read_debug)
9695     {
9696       fprintf_unfiltered (gdb_stdlog, "Reading %s for %s:\n",
9697                           get_section_name (section),
9698                           get_section_file_name (section));
9699     }
9700
9701   create_dwo_cu_data.dwo_file = dwo_file;
9702   dwo_unit = NULL;
9703
9704   end_ptr = info_ptr + section->size;
9705   while (info_ptr < end_ptr)
9706     {
9707       struct dwarf2_per_cu_data per_cu;
9708
9709       memset (&create_dwo_cu_data.dwo_unit, 0,
9710               sizeof (create_dwo_cu_data.dwo_unit));
9711       memset (&per_cu, 0, sizeof (per_cu));
9712       per_cu.objfile = objfile;
9713       per_cu.is_debug_types = 0;
9714       per_cu.offset.sect_off = info_ptr - section->buffer;
9715       per_cu.section = section;
9716
9717       init_cutu_and_read_dies_no_follow (&per_cu, dwo_file,
9718                                          create_dwo_cu_reader,
9719                                          &create_dwo_cu_data);
9720
9721       if (create_dwo_cu_data.dwo_unit.dwo_file != NULL)
9722         {
9723           /* If we've already found one, complain.  We only support one
9724              because having more than one requires hacking the dwo_name of
9725              each to match, which is highly unlikely to happen.  */
9726           if (dwo_unit != NULL)
9727             {
9728               complaint (&symfile_complaints,
9729                          _("Multiple CUs in DWO file %s [in module %s]"),
9730                          dwo_file->dwo_name, objfile_name (objfile));
9731               break;
9732             }
9733
9734           dwo_unit = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_unit);
9735           *dwo_unit = create_dwo_cu_data.dwo_unit;
9736         }
9737
9738       info_ptr += per_cu.length;
9739     }
9740
9741   return dwo_unit;
9742 }
9743
9744 /* DWP file .debug_{cu,tu}_index section format:
9745    [ref: http://gcc.gnu.org/wiki/DebugFissionDWP]
9746
9747    DWP Version 1:
9748
9749    Both index sections have the same format, and serve to map a 64-bit
9750    signature to a set of section numbers.  Each section begins with a header,
9751    followed by a hash table of 64-bit signatures, a parallel table of 32-bit
9752    indexes, and a pool of 32-bit section numbers.  The index sections will be
9753    aligned at 8-byte boundaries in the file.
9754
9755    The index section header consists of:
9756
9757     V, 32 bit version number
9758     -, 32 bits unused
9759     N, 32 bit number of compilation units or type units in the index
9760     M, 32 bit number of slots in the hash table
9761
9762    Numbers are recorded using the byte order of the application binary.
9763
9764    The hash table begins at offset 16 in the section, and consists of an array
9765    of M 64-bit slots.  Each slot contains a 64-bit signature (using the byte
9766    order of the application binary).  Unused slots in the hash table are 0.
9767    (We rely on the extreme unlikeliness of a signature being exactly 0.)
9768
9769    The parallel table begins immediately after the hash table
9770    (at offset 16 + 8 * M from the beginning of the section), and consists of an
9771    array of 32-bit indexes (using the byte order of the application binary),
9772    corresponding 1-1 with slots in the hash table.  Each entry in the parallel
9773    table contains a 32-bit index into the pool of section numbers.  For unused
9774    hash table slots, the corresponding entry in the parallel table will be 0.
9775
9776    The pool of section numbers begins immediately following the hash table
9777    (at offset 16 + 12 * M from the beginning of the section).  The pool of
9778    section numbers consists of an array of 32-bit words (using the byte order
9779    of the application binary).  Each item in the array is indexed starting
9780    from 0.  The hash table entry provides the index of the first section
9781    number in the set.  Additional section numbers in the set follow, and the
9782    set is terminated by a 0 entry (section number 0 is not used in ELF).
9783
9784    In each set of section numbers, the .debug_info.dwo or .debug_types.dwo
9785    section must be the first entry in the set, and the .debug_abbrev.dwo must
9786    be the second entry. Other members of the set may follow in any order.
9787
9788    ---
9789
9790    DWP Version 2:
9791
9792    DWP Version 2 combines all the .debug_info, etc. sections into one,
9793    and the entries in the index tables are now offsets into these sections.
9794    CU offsets begin at 0.  TU offsets begin at the size of the .debug_info
9795    section.
9796
9797    Index Section Contents:
9798     Header
9799     Hash Table of Signatures   dwp_hash_table.hash_table
9800     Parallel Table of Indices  dwp_hash_table.unit_table
9801     Table of Section Offsets   dwp_hash_table.v2.{section_ids,offsets}
9802     Table of Section Sizes     dwp_hash_table.v2.sizes
9803
9804    The index section header consists of:
9805
9806     V, 32 bit version number
9807     L, 32 bit number of columns in the table of section offsets
9808     N, 32 bit number of compilation units or type units in the index
9809     M, 32 bit number of slots in the hash table
9810
9811    Numbers are recorded using the byte order of the application binary.
9812
9813    The hash table has the same format as version 1.
9814    The parallel table of indices has the same format as version 1,
9815    except that the entries are origin-1 indices into the table of sections
9816    offsets and the table of section sizes.
9817
9818    The table of offsets begins immediately following the parallel table
9819    (at offset 16 + 12 * M from the beginning of the section).  The table is
9820    a two-dimensional array of 32-bit words (using the byte order of the
9821    application binary), with L columns and N+1 rows, in row-major order.
9822    Each row in the array is indexed starting from 0.  The first row provides
9823    a key to the remaining rows: each column in this row provides an identifier
9824    for a debug section, and the offsets in the same column of subsequent rows
9825    refer to that section.  The section identifiers are:
9826
9827     DW_SECT_INFO         1  .debug_info.dwo
9828     DW_SECT_TYPES        2  .debug_types.dwo
9829     DW_SECT_ABBREV       3  .debug_abbrev.dwo
9830     DW_SECT_LINE         4  .debug_line.dwo
9831     DW_SECT_LOC          5  .debug_loc.dwo
9832     DW_SECT_STR_OFFSETS  6  .debug_str_offsets.dwo
9833     DW_SECT_MACINFO      7  .debug_macinfo.dwo
9834     DW_SECT_MACRO        8  .debug_macro.dwo
9835
9836    The offsets provided by the CU and TU index sections are the base offsets
9837    for the contributions made by each CU or TU to the corresponding section
9838    in the package file.  Each CU and TU header contains an abbrev_offset
9839    field, used to find the abbreviations table for that CU or TU within the
9840    contribution to the .debug_abbrev.dwo section for that CU or TU, and should
9841    be interpreted as relative to the base offset given in the index section.
9842    Likewise, offsets into .debug_line.dwo from DW_AT_stmt_list attributes
9843    should be interpreted as relative to the base offset for .debug_line.dwo,
9844    and offsets into other debug sections obtained from DWARF attributes should
9845    also be interpreted as relative to the corresponding base offset.
9846
9847    The table of sizes begins immediately following the table of offsets.
9848    Like the table of offsets, it is a two-dimensional array of 32-bit words,
9849    with L columns and N rows, in row-major order.  Each row in the array is
9850    indexed starting from 1 (row 0 is shared by the two tables).
9851
9852    ---
9853
9854    Hash table lookup is handled the same in version 1 and 2:
9855
9856    We assume that N and M will not exceed 2^32 - 1.
9857    The size of the hash table, M, must be 2^k such that 2^k > 3*N/2.
9858
9859    Given a 64-bit compilation unit signature or a type signature S, an entry
9860    in the hash table is located as follows:
9861
9862    1) Calculate a primary hash H = S & MASK(k), where MASK(k) is a mask with
9863       the low-order k bits all set to 1.
9864
9865    2) Calculate a secondary hash H' = (((S >> 32) & MASK(k)) | 1).
9866
9867    3) If the hash table entry at index H matches the signature, use that
9868       entry.  If the hash table entry at index H is unused (all zeroes),
9869       terminate the search: the signature is not present in the table.
9870
9871    4) Let H = (H + H') modulo M. Repeat at Step 3.
9872
9873    Because M > N and H' and M are relatively prime, the search is guaranteed
9874    to stop at an unused slot or find the match.  */
9875
9876 /* Create a hash table to map DWO IDs to their CU/TU entry in
9877    .debug_{info,types}.dwo in DWP_FILE.
9878    Returns NULL if there isn't one.
9879    Note: This function processes DWP files only, not DWO files.  */
9880
9881 static struct dwp_hash_table *
9882 create_dwp_hash_table (struct dwp_file *dwp_file, int is_debug_types)
9883 {
9884   struct objfile *objfile = dwarf2_per_objfile->objfile;
9885   bfd *dbfd = dwp_file->dbfd;
9886   const gdb_byte *index_ptr, *index_end;
9887   struct dwarf2_section_info *index;
9888   uint32_t version, nr_columns, nr_units, nr_slots;
9889   struct dwp_hash_table *htab;
9890
9891   if (is_debug_types)
9892     index = &dwp_file->sections.tu_index;
9893   else
9894     index = &dwp_file->sections.cu_index;
9895
9896   if (dwarf2_section_empty_p (index))
9897     return NULL;
9898   dwarf2_read_section (objfile, index);
9899
9900   index_ptr = index->buffer;
9901   index_end = index_ptr + index->size;
9902
9903   version = read_4_bytes (dbfd, index_ptr);
9904   index_ptr += 4;
9905   if (version == 2)
9906     nr_columns = read_4_bytes (dbfd, index_ptr);
9907   else
9908     nr_columns = 0;
9909   index_ptr += 4;
9910   nr_units = read_4_bytes (dbfd, index_ptr);
9911   index_ptr += 4;
9912   nr_slots = read_4_bytes (dbfd, index_ptr);
9913   index_ptr += 4;
9914
9915   if (version != 1 && version != 2)
9916     {
9917       error (_("Dwarf Error: unsupported DWP file version (%s)"
9918                " [in module %s]"),
9919              pulongest (version), dwp_file->name);
9920     }
9921   if (nr_slots != (nr_slots & -nr_slots))
9922     {
9923       error (_("Dwarf Error: number of slots in DWP hash table (%s)"
9924                " is not power of 2 [in module %s]"),
9925              pulongest (nr_slots), dwp_file->name);
9926     }
9927
9928   htab = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwp_hash_table);
9929   htab->version = version;
9930   htab->nr_columns = nr_columns;
9931   htab->nr_units = nr_units;
9932   htab->nr_slots = nr_slots;
9933   htab->hash_table = index_ptr;
9934   htab->unit_table = htab->hash_table + sizeof (uint64_t) * nr_slots;
9935
9936   /* Exit early if the table is empty.  */
9937   if (nr_slots == 0 || nr_units == 0
9938       || (version == 2 && nr_columns == 0))
9939     {
9940       /* All must be zero.  */
9941       if (nr_slots != 0 || nr_units != 0
9942           || (version == 2 && nr_columns != 0))
9943         {
9944           complaint (&symfile_complaints,
9945                      _("Empty DWP but nr_slots,nr_units,nr_columns not"
9946                        " all zero [in modules %s]"),
9947                      dwp_file->name);
9948         }
9949       return htab;
9950     }
9951
9952   if (version == 1)
9953     {
9954       htab->section_pool.v1.indices =
9955         htab->unit_table + sizeof (uint32_t) * nr_slots;
9956       /* It's harder to decide whether the section is too small in v1.
9957          V1 is deprecated anyway so we punt.  */
9958     }
9959   else
9960     {
9961       const gdb_byte *ids_ptr = htab->unit_table + sizeof (uint32_t) * nr_slots;
9962       int *ids = htab->section_pool.v2.section_ids;
9963       /* Reverse map for error checking.  */
9964       int ids_seen[DW_SECT_MAX + 1];
9965       int i;
9966
9967       if (nr_columns < 2)
9968         {
9969           error (_("Dwarf Error: bad DWP hash table, too few columns"
9970                    " in section table [in module %s]"),
9971                  dwp_file->name);
9972         }
9973       if (nr_columns > MAX_NR_V2_DWO_SECTIONS)
9974         {
9975           error (_("Dwarf Error: bad DWP hash table, too many columns"
9976                    " in section table [in module %s]"),
9977                  dwp_file->name);
9978         }
9979       memset (ids, 255, (DW_SECT_MAX + 1) * sizeof (int32_t));
9980       memset (ids_seen, 255, (DW_SECT_MAX + 1) * sizeof (int32_t));
9981       for (i = 0; i < nr_columns; ++i)
9982         {
9983           int id = read_4_bytes (dbfd, ids_ptr + i * sizeof (uint32_t));
9984
9985           if (id < DW_SECT_MIN || id > DW_SECT_MAX)
9986             {
9987               error (_("Dwarf Error: bad DWP hash table, bad section id %d"
9988                        " in section table [in module %s]"),
9989                      id, dwp_file->name);
9990             }
9991           if (ids_seen[id] != -1)
9992             {
9993               error (_("Dwarf Error: bad DWP hash table, duplicate section"
9994                        " id %d in section table [in module %s]"),
9995                      id, dwp_file->name);
9996             }
9997           ids_seen[id] = i;
9998           ids[i] = id;
9999         }
10000       /* Must have exactly one info or types section.  */
10001       if (((ids_seen[DW_SECT_INFO] != -1)
10002            + (ids_seen[DW_SECT_TYPES] != -1))
10003           != 1)
10004         {
10005           error (_("Dwarf Error: bad DWP hash table, missing/duplicate"
10006                    " DWO info/types section [in module %s]"),
10007                  dwp_file->name);
10008         }
10009       /* Must have an abbrev section.  */
10010       if (ids_seen[DW_SECT_ABBREV] == -1)
10011         {
10012           error (_("Dwarf Error: bad DWP hash table, missing DWO abbrev"
10013                    " section [in module %s]"),
10014                  dwp_file->name);
10015         }
10016       htab->section_pool.v2.offsets = ids_ptr + sizeof (uint32_t) * nr_columns;
10017       htab->section_pool.v2.sizes =
10018         htab->section_pool.v2.offsets + (sizeof (uint32_t)
10019                                          * nr_units * nr_columns);
10020       if ((htab->section_pool.v2.sizes + (sizeof (uint32_t)
10021                                           * nr_units * nr_columns))
10022           > index_end)
10023         {
10024           error (_("Dwarf Error: DWP index section is corrupt (too small)"
10025                    " [in module %s]"),
10026                  dwp_file->name);
10027         }
10028     }
10029
10030   return htab;
10031 }
10032
10033 /* Update SECTIONS with the data from SECTP.
10034
10035    This function is like the other "locate" section routines that are
10036    passed to bfd_map_over_sections, but in this context the sections to
10037    read comes from the DWP V1 hash table, not the full ELF section table.
10038
10039    The result is non-zero for success, or zero if an error was found.  */
10040
10041 static int
10042 locate_v1_virtual_dwo_sections (asection *sectp,
10043                                 struct virtual_v1_dwo_sections *sections)
10044 {
10045   const struct dwop_section_names *names = &dwop_section_names;
10046
10047   if (section_is_p (sectp->name, &names->abbrev_dwo))
10048     {
10049       /* There can be only one.  */
10050       if (sections->abbrev.s.section != NULL)
10051         return 0;
10052       sections->abbrev.s.section = sectp;
10053       sections->abbrev.size = bfd_get_section_size (sectp);
10054     }
10055   else if (section_is_p (sectp->name, &names->info_dwo)
10056            || section_is_p (sectp->name, &names->types_dwo))
10057     {
10058       /* There can be only one.  */
10059       if (sections->info_or_types.s.section != NULL)
10060         return 0;
10061       sections->info_or_types.s.section = sectp;
10062       sections->info_or_types.size = bfd_get_section_size (sectp);
10063     }
10064   else if (section_is_p (sectp->name, &names->line_dwo))
10065     {
10066       /* There can be only one.  */
10067       if (sections->line.s.section != NULL)
10068         return 0;
10069       sections->line.s.section = sectp;
10070       sections->line.size = bfd_get_section_size (sectp);
10071     }
10072   else if (section_is_p (sectp->name, &names->loc_dwo))
10073     {
10074       /* There can be only one.  */
10075       if (sections->loc.s.section != NULL)
10076         return 0;
10077       sections->loc.s.section = sectp;
10078       sections->loc.size = bfd_get_section_size (sectp);
10079     }
10080   else if (section_is_p (sectp->name, &names->macinfo_dwo))
10081     {
10082       /* There can be only one.  */
10083       if (sections->macinfo.s.section != NULL)
10084         return 0;
10085       sections->macinfo.s.section = sectp;
10086       sections->macinfo.size = bfd_get_section_size (sectp);
10087     }
10088   else if (section_is_p (sectp->name, &names->macro_dwo))
10089     {
10090       /* There can be only one.  */
10091       if (sections->macro.s.section != NULL)
10092         return 0;
10093       sections->macro.s.section = sectp;
10094       sections->macro.size = bfd_get_section_size (sectp);
10095     }
10096   else if (section_is_p (sectp->name, &names->str_offsets_dwo))
10097     {
10098       /* There can be only one.  */
10099       if (sections->str_offsets.s.section != NULL)
10100         return 0;
10101       sections->str_offsets.s.section = sectp;
10102       sections->str_offsets.size = bfd_get_section_size (sectp);
10103     }
10104   else
10105     {
10106       /* No other kind of section is valid.  */
10107       return 0;
10108     }
10109
10110   return 1;
10111 }
10112
10113 /* Create a dwo_unit object for the DWO unit with signature SIGNATURE.
10114    UNIT_INDEX is the index of the DWO unit in the DWP hash table.
10115    COMP_DIR is the DW_AT_comp_dir attribute of the referencing CU.
10116    This is for DWP version 1 files.  */
10117
10118 static struct dwo_unit *
10119 create_dwo_unit_in_dwp_v1 (struct dwp_file *dwp_file,
10120                            uint32_t unit_index,
10121                            const char *comp_dir,
10122                            ULONGEST signature, int is_debug_types)
10123 {
10124   struct objfile *objfile = dwarf2_per_objfile->objfile;
10125   const struct dwp_hash_table *dwp_htab =
10126     is_debug_types ? dwp_file->tus : dwp_file->cus;
10127   bfd *dbfd = dwp_file->dbfd;
10128   const char *kind = is_debug_types ? "TU" : "CU";
10129   struct dwo_file *dwo_file;
10130   struct dwo_unit *dwo_unit;
10131   struct virtual_v1_dwo_sections sections;
10132   void **dwo_file_slot;
10133   char *virtual_dwo_name;
10134   struct cleanup *cleanups;
10135   int i;
10136
10137   gdb_assert (dwp_file->version == 1);
10138
10139   if (dwarf_read_debug)
10140     {
10141       fprintf_unfiltered (gdb_stdlog, "Reading %s %s/%s in DWP V1 file: %s\n",
10142                           kind,
10143                           pulongest (unit_index), hex_string (signature),
10144                           dwp_file->name);
10145     }
10146
10147   /* Fetch the sections of this DWO unit.
10148      Put a limit on the number of sections we look for so that bad data
10149      doesn't cause us to loop forever.  */
10150
10151 #define MAX_NR_V1_DWO_SECTIONS \
10152   (1 /* .debug_info or .debug_types */ \
10153    + 1 /* .debug_abbrev */ \
10154    + 1 /* .debug_line */ \
10155    + 1 /* .debug_loc */ \
10156    + 1 /* .debug_str_offsets */ \
10157    + 1 /* .debug_macro or .debug_macinfo */ \
10158    + 1 /* trailing zero */)
10159
10160   memset (&sections, 0, sizeof (sections));
10161   cleanups = make_cleanup (null_cleanup, 0);
10162
10163   for (i = 0; i < MAX_NR_V1_DWO_SECTIONS; ++i)
10164     {
10165       asection *sectp;
10166       uint32_t section_nr =
10167         read_4_bytes (dbfd,
10168                       dwp_htab->section_pool.v1.indices
10169                       + (unit_index + i) * sizeof (uint32_t));
10170
10171       if (section_nr == 0)
10172         break;
10173       if (section_nr >= dwp_file->num_sections)
10174         {
10175           error (_("Dwarf Error: bad DWP hash table, section number too large"
10176                    " [in module %s]"),
10177                  dwp_file->name);
10178         }
10179
10180       sectp = dwp_file->elf_sections[section_nr];
10181       if (! locate_v1_virtual_dwo_sections (sectp, &sections))
10182         {
10183           error (_("Dwarf Error: bad DWP hash table, invalid section found"
10184                    " [in module %s]"),
10185                  dwp_file->name);
10186         }
10187     }
10188
10189   if (i < 2
10190       || dwarf2_section_empty_p (&sections.info_or_types)
10191       || dwarf2_section_empty_p (&sections.abbrev))
10192     {
10193       error (_("Dwarf Error: bad DWP hash table, missing DWO sections"
10194                " [in module %s]"),
10195              dwp_file->name);
10196     }
10197   if (i == MAX_NR_V1_DWO_SECTIONS)
10198     {
10199       error (_("Dwarf Error: bad DWP hash table, too many DWO sections"
10200                " [in module %s]"),
10201              dwp_file->name);
10202     }
10203
10204   /* It's easier for the rest of the code if we fake a struct dwo_file and
10205      have dwo_unit "live" in that.  At least for now.
10206
10207      The DWP file can be made up of a random collection of CUs and TUs.
10208      However, for each CU + set of TUs that came from the same original DWO
10209      file, we can combine them back into a virtual DWO file to save space
10210      (fewer struct dwo_file objects to allocate).  Remember that for really
10211      large apps there can be on the order of 8K CUs and 200K TUs, or more.  */
10212
10213   virtual_dwo_name =
10214     xstrprintf ("virtual-dwo/%d-%d-%d-%d",
10215                 get_section_id (&sections.abbrev),
10216                 get_section_id (&sections.line),
10217                 get_section_id (&sections.loc),
10218                 get_section_id (&sections.str_offsets));
10219   make_cleanup (xfree, virtual_dwo_name);
10220   /* Can we use an existing virtual DWO file?  */
10221   dwo_file_slot = lookup_dwo_file_slot (virtual_dwo_name, comp_dir);
10222   /* Create one if necessary.  */
10223   if (*dwo_file_slot == NULL)
10224     {
10225       if (dwarf_read_debug)
10226         {
10227           fprintf_unfiltered (gdb_stdlog, "Creating virtual DWO: %s\n",
10228                               virtual_dwo_name);
10229         }
10230       dwo_file = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_file);
10231       dwo_file->dwo_name
10232         = (const char *) obstack_copy0 (&objfile->objfile_obstack,
10233                                         virtual_dwo_name,
10234                                         strlen (virtual_dwo_name));
10235       dwo_file->comp_dir = comp_dir;
10236       dwo_file->sections.abbrev = sections.abbrev;
10237       dwo_file->sections.line = sections.line;
10238       dwo_file->sections.loc = sections.loc;
10239       dwo_file->sections.macinfo = sections.macinfo;
10240       dwo_file->sections.macro = sections.macro;
10241       dwo_file->sections.str_offsets = sections.str_offsets;
10242       /* The "str" section is global to the entire DWP file.  */
10243       dwo_file->sections.str = dwp_file->sections.str;
10244       /* The info or types section is assigned below to dwo_unit,
10245          there's no need to record it in dwo_file.
10246          Also, we can't simply record type sections in dwo_file because
10247          we record a pointer into the vector in dwo_unit.  As we collect more
10248          types we'll grow the vector and eventually have to reallocate space
10249          for it, invalidating all copies of pointers into the previous
10250          contents.  */
10251       *dwo_file_slot = dwo_file;
10252     }
10253   else
10254     {
10255       if (dwarf_read_debug)
10256         {
10257           fprintf_unfiltered (gdb_stdlog, "Using existing virtual DWO: %s\n",
10258                               virtual_dwo_name);
10259         }
10260       dwo_file = (struct dwo_file *) *dwo_file_slot;
10261     }
10262   do_cleanups (cleanups);
10263
10264   dwo_unit = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_unit);
10265   dwo_unit->dwo_file = dwo_file;
10266   dwo_unit->signature = signature;
10267   dwo_unit->section =
10268     XOBNEW (&objfile->objfile_obstack, struct dwarf2_section_info);
10269   *dwo_unit->section = sections.info_or_types;
10270   /* dwo_unit->{offset,length,type_offset_in_tu} are set later.  */
10271
10272   return dwo_unit;
10273 }
10274
10275 /* Subroutine of create_dwo_unit_in_dwp_v2 to simplify it.
10276    Given a pointer to the containing section SECTION, and OFFSET,SIZE of the
10277    piece within that section used by a TU/CU, return a virtual section
10278    of just that piece.  */
10279
10280 static struct dwarf2_section_info
10281 create_dwp_v2_section (struct dwarf2_section_info *section,
10282                        bfd_size_type offset, bfd_size_type size)
10283 {
10284   struct dwarf2_section_info result;
10285   asection *sectp;
10286
10287   gdb_assert (section != NULL);
10288   gdb_assert (!section->is_virtual);
10289
10290   memset (&result, 0, sizeof (result));
10291   result.s.containing_section = section;
10292   result.is_virtual = 1;
10293
10294   if (size == 0)
10295     return result;
10296
10297   sectp = get_section_bfd_section (section);
10298
10299   /* Flag an error if the piece denoted by OFFSET,SIZE is outside the
10300      bounds of the real section.  This is a pretty-rare event, so just
10301      flag an error (easier) instead of a warning and trying to cope.  */
10302   if (sectp == NULL
10303       || offset + size > bfd_get_section_size (sectp))
10304     {
10305       bfd *abfd = sectp->owner;
10306
10307       error (_("Dwarf Error: Bad DWP V2 section info, doesn't fit"
10308                " in section %s [in module %s]"),
10309              sectp ? bfd_section_name (abfd, sectp) : "<unknown>",
10310              objfile_name (dwarf2_per_objfile->objfile));
10311     }
10312
10313   result.virtual_offset = offset;
10314   result.size = size;
10315   return result;
10316 }
10317
10318 /* Create a dwo_unit object for the DWO unit with signature SIGNATURE.
10319    UNIT_INDEX is the index of the DWO unit in the DWP hash table.
10320    COMP_DIR is the DW_AT_comp_dir attribute of the referencing CU.
10321    This is for DWP version 2 files.  */
10322
10323 static struct dwo_unit *
10324 create_dwo_unit_in_dwp_v2 (struct dwp_file *dwp_file,
10325                            uint32_t unit_index,
10326                            const char *comp_dir,
10327                            ULONGEST signature, int is_debug_types)
10328 {
10329   struct objfile *objfile = dwarf2_per_objfile->objfile;
10330   const struct dwp_hash_table *dwp_htab =
10331     is_debug_types ? dwp_file->tus : dwp_file->cus;
10332   bfd *dbfd = dwp_file->dbfd;
10333   const char *kind = is_debug_types ? "TU" : "CU";
10334   struct dwo_file *dwo_file;
10335   struct dwo_unit *dwo_unit;
10336   struct virtual_v2_dwo_sections sections;
10337   void **dwo_file_slot;
10338   char *virtual_dwo_name;
10339   struct cleanup *cleanups;
10340   int i;
10341
10342   gdb_assert (dwp_file->version == 2);
10343
10344   if (dwarf_read_debug)
10345     {
10346       fprintf_unfiltered (gdb_stdlog, "Reading %s %s/%s in DWP V2 file: %s\n",
10347                           kind,
10348                           pulongest (unit_index), hex_string (signature),
10349                           dwp_file->name);
10350     }
10351
10352   /* Fetch the section offsets of this DWO unit.  */
10353
10354   memset (&sections, 0, sizeof (sections));
10355   cleanups = make_cleanup (null_cleanup, 0);
10356
10357   for (i = 0; i < dwp_htab->nr_columns; ++i)
10358     {
10359       uint32_t offset = read_4_bytes (dbfd,
10360                                       dwp_htab->section_pool.v2.offsets
10361                                       + (((unit_index - 1) * dwp_htab->nr_columns
10362                                           + i)
10363                                          * sizeof (uint32_t)));
10364       uint32_t size = read_4_bytes (dbfd,
10365                                     dwp_htab->section_pool.v2.sizes
10366                                     + (((unit_index - 1) * dwp_htab->nr_columns
10367                                         + i)
10368                                        * sizeof (uint32_t)));
10369
10370       switch (dwp_htab->section_pool.v2.section_ids[i])
10371         {
10372         case DW_SECT_INFO:
10373         case DW_SECT_TYPES:
10374           sections.info_or_types_offset = offset;
10375           sections.info_or_types_size = size;
10376           break;
10377         case DW_SECT_ABBREV:
10378           sections.abbrev_offset = offset;
10379           sections.abbrev_size = size;
10380           break;
10381         case DW_SECT_LINE:
10382           sections.line_offset = offset;
10383           sections.line_size = size;
10384           break;
10385         case DW_SECT_LOC:
10386           sections.loc_offset = offset;
10387           sections.loc_size = size;
10388           break;
10389         case DW_SECT_STR_OFFSETS:
10390           sections.str_offsets_offset = offset;
10391           sections.str_offsets_size = size;
10392           break;
10393         case DW_SECT_MACINFO:
10394           sections.macinfo_offset = offset;
10395           sections.macinfo_size = size;
10396           break;
10397         case DW_SECT_MACRO:
10398           sections.macro_offset = offset;
10399           sections.macro_size = size;
10400           break;
10401         }
10402     }
10403
10404   /* It's easier for the rest of the code if we fake a struct dwo_file and
10405      have dwo_unit "live" in that.  At least for now.
10406
10407      The DWP file can be made up of a random collection of CUs and TUs.
10408      However, for each CU + set of TUs that came from the same original DWO
10409      file, we can combine them back into a virtual DWO file to save space
10410      (fewer struct dwo_file objects to allocate).  Remember that for really
10411      large apps there can be on the order of 8K CUs and 200K TUs, or more.  */
10412
10413   virtual_dwo_name =
10414     xstrprintf ("virtual-dwo/%ld-%ld-%ld-%ld",
10415                 (long) (sections.abbrev_size ? sections.abbrev_offset : 0),
10416                 (long) (sections.line_size ? sections.line_offset : 0),
10417                 (long) (sections.loc_size ? sections.loc_offset : 0),
10418                 (long) (sections.str_offsets_size
10419                         ? sections.str_offsets_offset : 0));
10420   make_cleanup (xfree, virtual_dwo_name);
10421   /* Can we use an existing virtual DWO file?  */
10422   dwo_file_slot = lookup_dwo_file_slot (virtual_dwo_name, comp_dir);
10423   /* Create one if necessary.  */
10424   if (*dwo_file_slot == NULL)
10425     {
10426       if (dwarf_read_debug)
10427         {
10428           fprintf_unfiltered (gdb_stdlog, "Creating virtual DWO: %s\n",
10429                               virtual_dwo_name);
10430         }
10431       dwo_file = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_file);
10432       dwo_file->dwo_name
10433         = (const char *) obstack_copy0 (&objfile->objfile_obstack,
10434                                         virtual_dwo_name,
10435                                         strlen (virtual_dwo_name));
10436       dwo_file->comp_dir = comp_dir;
10437       dwo_file->sections.abbrev =
10438         create_dwp_v2_section (&dwp_file->sections.abbrev,
10439                                sections.abbrev_offset, sections.abbrev_size);
10440       dwo_file->sections.line =
10441         create_dwp_v2_section (&dwp_file->sections.line,
10442                                sections.line_offset, sections.line_size);
10443       dwo_file->sections.loc =
10444         create_dwp_v2_section (&dwp_file->sections.loc,
10445                                sections.loc_offset, sections.loc_size);
10446       dwo_file->sections.macinfo =
10447         create_dwp_v2_section (&dwp_file->sections.macinfo,
10448                                sections.macinfo_offset, sections.macinfo_size);
10449       dwo_file->sections.macro =
10450         create_dwp_v2_section (&dwp_file->sections.macro,
10451                                sections.macro_offset, sections.macro_size);
10452       dwo_file->sections.str_offsets =
10453         create_dwp_v2_section (&dwp_file->sections.str_offsets,
10454                                sections.str_offsets_offset,
10455                                sections.str_offsets_size);
10456       /* The "str" section is global to the entire DWP file.  */
10457       dwo_file->sections.str = dwp_file->sections.str;
10458       /* The info or types section is assigned below to dwo_unit,
10459          there's no need to record it in dwo_file.
10460          Also, we can't simply record type sections in dwo_file because
10461          we record a pointer into the vector in dwo_unit.  As we collect more
10462          types we'll grow the vector and eventually have to reallocate space
10463          for it, invalidating all copies of pointers into the previous
10464          contents.  */
10465       *dwo_file_slot = dwo_file;
10466     }
10467   else
10468     {
10469       if (dwarf_read_debug)
10470         {
10471           fprintf_unfiltered (gdb_stdlog, "Using existing virtual DWO: %s\n",
10472                               virtual_dwo_name);
10473         }
10474       dwo_file = (struct dwo_file *) *dwo_file_slot;
10475     }
10476   do_cleanups (cleanups);
10477
10478   dwo_unit = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_unit);
10479   dwo_unit->dwo_file = dwo_file;
10480   dwo_unit->signature = signature;
10481   dwo_unit->section =
10482     XOBNEW (&objfile->objfile_obstack, struct dwarf2_section_info);
10483   *dwo_unit->section = create_dwp_v2_section (is_debug_types
10484                                               ? &dwp_file->sections.types
10485                                               : &dwp_file->sections.info,
10486                                               sections.info_or_types_offset,
10487                                               sections.info_or_types_size);
10488   /* dwo_unit->{offset,length,type_offset_in_tu} are set later.  */
10489
10490   return dwo_unit;
10491 }
10492
10493 /* Lookup the DWO unit with SIGNATURE in DWP_FILE.
10494    Returns NULL if the signature isn't found.  */
10495
10496 static struct dwo_unit *
10497 lookup_dwo_unit_in_dwp (struct dwp_file *dwp_file, const char *comp_dir,
10498                         ULONGEST signature, int is_debug_types)
10499 {
10500   const struct dwp_hash_table *dwp_htab =
10501     is_debug_types ? dwp_file->tus : dwp_file->cus;
10502   bfd *dbfd = dwp_file->dbfd;
10503   uint32_t mask = dwp_htab->nr_slots - 1;
10504   uint32_t hash = signature & mask;
10505   uint32_t hash2 = ((signature >> 32) & mask) | 1;
10506   unsigned int i;
10507   void **slot;
10508   struct dwo_unit find_dwo_cu;
10509
10510   memset (&find_dwo_cu, 0, sizeof (find_dwo_cu));
10511   find_dwo_cu.signature = signature;
10512   slot = htab_find_slot (is_debug_types
10513                          ? dwp_file->loaded_tus
10514                          : dwp_file->loaded_cus,
10515                          &find_dwo_cu, INSERT);
10516
10517   if (*slot != NULL)
10518     return (struct dwo_unit *) *slot;
10519
10520   /* Use a for loop so that we don't loop forever on bad debug info.  */
10521   for (i = 0; i < dwp_htab->nr_slots; ++i)
10522     {
10523       ULONGEST signature_in_table;
10524
10525       signature_in_table =
10526         read_8_bytes (dbfd, dwp_htab->hash_table + hash * sizeof (uint64_t));
10527       if (signature_in_table == signature)
10528         {
10529           uint32_t unit_index =
10530             read_4_bytes (dbfd,
10531                           dwp_htab->unit_table + hash * sizeof (uint32_t));
10532
10533           if (dwp_file->version == 1)
10534             {
10535               *slot = create_dwo_unit_in_dwp_v1 (dwp_file, unit_index,
10536                                                  comp_dir, signature,
10537                                                  is_debug_types);
10538             }
10539           else
10540             {
10541               *slot = create_dwo_unit_in_dwp_v2 (dwp_file, unit_index,
10542                                                  comp_dir, signature,
10543                                                  is_debug_types);
10544             }
10545           return (struct dwo_unit *) *slot;
10546         }
10547       if (signature_in_table == 0)
10548         return NULL;
10549       hash = (hash + hash2) & mask;
10550     }
10551
10552   error (_("Dwarf Error: bad DWP hash table, lookup didn't terminate"
10553            " [in module %s]"),
10554          dwp_file->name);
10555 }
10556
10557 /* Subroutine of open_dwo_file,open_dwp_file to simplify them.
10558    Open the file specified by FILE_NAME and hand it off to BFD for
10559    preliminary analysis.  Return a newly initialized bfd *, which
10560    includes a canonicalized copy of FILE_NAME.
10561    If IS_DWP is TRUE, we're opening a DWP file, otherwise a DWO file.
10562    SEARCH_CWD is true if the current directory is to be searched.
10563    It will be searched before debug-file-directory.
10564    If successful, the file is added to the bfd include table of the
10565    objfile's bfd (see gdb_bfd_record_inclusion).
10566    If unable to find/open the file, return NULL.
10567    NOTE: This function is derived from symfile_bfd_open.  */
10568
10569 static gdb_bfd_ref_ptr
10570 try_open_dwop_file (const char *file_name, int is_dwp, int search_cwd)
10571 {
10572   int desc, flags;
10573   char *absolute_name;
10574   /* Blech.  OPF_TRY_CWD_FIRST also disables searching the path list if
10575      FILE_NAME contains a '/'.  So we can't use it.  Instead prepend "."
10576      to debug_file_directory.  */
10577   char *search_path;
10578   static const char dirname_separator_string[] = { DIRNAME_SEPARATOR, '\0' };
10579
10580   if (search_cwd)
10581     {
10582       if (*debug_file_directory != '\0')
10583         search_path = concat (".", dirname_separator_string,
10584                               debug_file_directory, (char *) NULL);
10585       else
10586         search_path = xstrdup (".");
10587     }
10588   else
10589     search_path = xstrdup (debug_file_directory);
10590
10591   flags = OPF_RETURN_REALPATH;
10592   if (is_dwp)
10593     flags |= OPF_SEARCH_IN_PATH;
10594   desc = openp (search_path, flags, file_name,
10595                 O_RDONLY | O_BINARY, &absolute_name);
10596   xfree (search_path);
10597   if (desc < 0)
10598     return NULL;
10599
10600   gdb_bfd_ref_ptr sym_bfd (gdb_bfd_open (absolute_name, gnutarget, desc));
10601   xfree (absolute_name);
10602   if (sym_bfd == NULL)
10603     return NULL;
10604   bfd_set_cacheable (sym_bfd.get (), 1);
10605
10606   if (!bfd_check_format (sym_bfd.get (), bfd_object))
10607     return NULL;
10608
10609   /* Success.  Record the bfd as having been included by the objfile's bfd.
10610      This is important because things like demangled_names_hash lives in the
10611      objfile's per_bfd space and may have references to things like symbol
10612      names that live in the DWO/DWP file's per_bfd space.  PR 16426.  */
10613   gdb_bfd_record_inclusion (dwarf2_per_objfile->objfile->obfd, sym_bfd.get ());
10614
10615   return sym_bfd;
10616 }
10617
10618 /* Try to open DWO file FILE_NAME.
10619    COMP_DIR is the DW_AT_comp_dir attribute.
10620    The result is the bfd handle of the file.
10621    If there is a problem finding or opening the file, return NULL.
10622    Upon success, the canonicalized path of the file is stored in the bfd,
10623    same as symfile_bfd_open.  */
10624
10625 static gdb_bfd_ref_ptr
10626 open_dwo_file (const char *file_name, const char *comp_dir)
10627 {
10628   if (IS_ABSOLUTE_PATH (file_name))
10629     return try_open_dwop_file (file_name, 0 /*is_dwp*/, 0 /*search_cwd*/);
10630
10631   /* Before trying the search path, try DWO_NAME in COMP_DIR.  */
10632
10633   if (comp_dir != NULL)
10634     {
10635       char *path_to_try = concat (comp_dir, SLASH_STRING,
10636                                   file_name, (char *) NULL);
10637
10638       /* NOTE: If comp_dir is a relative path, this will also try the
10639          search path, which seems useful.  */
10640       gdb_bfd_ref_ptr abfd (try_open_dwop_file (path_to_try, 0 /*is_dwp*/,
10641                                                 1 /*search_cwd*/));
10642       xfree (path_to_try);
10643       if (abfd != NULL)
10644         return abfd;
10645     }
10646
10647   /* That didn't work, try debug-file-directory, which, despite its name,
10648      is a list of paths.  */
10649
10650   if (*debug_file_directory == '\0')
10651     return NULL;
10652
10653   return try_open_dwop_file (file_name, 0 /*is_dwp*/, 1 /*search_cwd*/);
10654 }
10655
10656 /* This function is mapped across the sections and remembers the offset and
10657    size of each of the DWO debugging sections we are interested in.  */
10658
10659 static void
10660 dwarf2_locate_dwo_sections (bfd *abfd, asection *sectp, void *dwo_sections_ptr)
10661 {
10662   struct dwo_sections *dwo_sections = (struct dwo_sections *) dwo_sections_ptr;
10663   const struct dwop_section_names *names = &dwop_section_names;
10664
10665   if (section_is_p (sectp->name, &names->abbrev_dwo))
10666     {
10667       dwo_sections->abbrev.s.section = sectp;
10668       dwo_sections->abbrev.size = bfd_get_section_size (sectp);
10669     }
10670   else if (section_is_p (sectp->name, &names->info_dwo))
10671     {
10672       dwo_sections->info.s.section = sectp;
10673       dwo_sections->info.size = bfd_get_section_size (sectp);
10674     }
10675   else if (section_is_p (sectp->name, &names->line_dwo))
10676     {
10677       dwo_sections->line.s.section = sectp;
10678       dwo_sections->line.size = bfd_get_section_size (sectp);
10679     }
10680   else if (section_is_p (sectp->name, &names->loc_dwo))
10681     {
10682       dwo_sections->loc.s.section = sectp;
10683       dwo_sections->loc.size = bfd_get_section_size (sectp);
10684     }
10685   else if (section_is_p (sectp->name, &names->macinfo_dwo))
10686     {
10687       dwo_sections->macinfo.s.section = sectp;
10688       dwo_sections->macinfo.size = bfd_get_section_size (sectp);
10689     }
10690   else if (section_is_p (sectp->name, &names->macro_dwo))
10691     {
10692       dwo_sections->macro.s.section = sectp;
10693       dwo_sections->macro.size = bfd_get_section_size (sectp);
10694     }
10695   else if (section_is_p (sectp->name, &names->str_dwo))
10696     {
10697       dwo_sections->str.s.section = sectp;
10698       dwo_sections->str.size = bfd_get_section_size (sectp);
10699     }
10700   else if (section_is_p (sectp->name, &names->str_offsets_dwo))
10701     {
10702       dwo_sections->str_offsets.s.section = sectp;
10703       dwo_sections->str_offsets.size = bfd_get_section_size (sectp);
10704     }
10705   else if (section_is_p (sectp->name, &names->types_dwo))
10706     {
10707       struct dwarf2_section_info type_section;
10708
10709       memset (&type_section, 0, sizeof (type_section));
10710       type_section.s.section = sectp;
10711       type_section.size = bfd_get_section_size (sectp);
10712       VEC_safe_push (dwarf2_section_info_def, dwo_sections->types,
10713                      &type_section);
10714     }
10715 }
10716
10717 /* Initialize the use of the DWO file specified by DWO_NAME and referenced
10718    by PER_CU.  This is for the non-DWP case.
10719    The result is NULL if DWO_NAME can't be found.  */
10720
10721 static struct dwo_file *
10722 open_and_init_dwo_file (struct dwarf2_per_cu_data *per_cu,
10723                         const char *dwo_name, const char *comp_dir)
10724 {
10725   struct objfile *objfile = dwarf2_per_objfile->objfile;
10726   struct dwo_file *dwo_file;
10727   struct cleanup *cleanups;
10728
10729   gdb_bfd_ref_ptr dbfd (open_dwo_file (dwo_name, comp_dir));
10730   if (dbfd == NULL)
10731     {
10732       if (dwarf_read_debug)
10733         fprintf_unfiltered (gdb_stdlog, "DWO file not found: %s\n", dwo_name);
10734       return NULL;
10735     }
10736   dwo_file = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_file);
10737   dwo_file->dwo_name = dwo_name;
10738   dwo_file->comp_dir = comp_dir;
10739   dwo_file->dbfd = dbfd.release ();
10740
10741   cleanups = make_cleanup (free_dwo_file_cleanup, dwo_file);
10742
10743   bfd_map_over_sections (dwo_file->dbfd, dwarf2_locate_dwo_sections,
10744                          &dwo_file->sections);
10745
10746   dwo_file->cu = create_dwo_cu (dwo_file);
10747
10748   create_debug_types_hash_table (dwo_file, dwo_file->sections.types,
10749                                  dwo_file->tus);
10750
10751   discard_cleanups (cleanups);
10752
10753   if (dwarf_read_debug)
10754     fprintf_unfiltered (gdb_stdlog, "DWO file found: %s\n", dwo_name);
10755
10756   return dwo_file;
10757 }
10758
10759 /* This function is mapped across the sections and remembers the offset and
10760    size of each of the DWP debugging sections common to version 1 and 2 that
10761    we are interested in.  */
10762
10763 static void
10764 dwarf2_locate_common_dwp_sections (bfd *abfd, asection *sectp,
10765                                    void *dwp_file_ptr)
10766 {
10767   struct dwp_file *dwp_file = (struct dwp_file *) dwp_file_ptr;
10768   const struct dwop_section_names *names = &dwop_section_names;
10769   unsigned int elf_section_nr = elf_section_data (sectp)->this_idx;
10770
10771   /* Record the ELF section number for later lookup: this is what the
10772      .debug_cu_index,.debug_tu_index tables use in DWP V1.  */
10773   gdb_assert (elf_section_nr < dwp_file->num_sections);
10774   dwp_file->elf_sections[elf_section_nr] = sectp;
10775
10776   /* Look for specific sections that we need.  */
10777   if (section_is_p (sectp->name, &names->str_dwo))
10778     {
10779       dwp_file->sections.str.s.section = sectp;
10780       dwp_file->sections.str.size = bfd_get_section_size (sectp);
10781     }
10782   else if (section_is_p (sectp->name, &names->cu_index))
10783     {
10784       dwp_file->sections.cu_index.s.section = sectp;
10785       dwp_file->sections.cu_index.size = bfd_get_section_size (sectp);
10786     }
10787   else if (section_is_p (sectp->name, &names->tu_index))
10788     {
10789       dwp_file->sections.tu_index.s.section = sectp;
10790       dwp_file->sections.tu_index.size = bfd_get_section_size (sectp);
10791     }
10792 }
10793
10794 /* This function is mapped across the sections and remembers the offset and
10795    size of each of the DWP version 2 debugging sections that we are interested
10796    in.  This is split into a separate function because we don't know if we
10797    have version 1 or 2 until we parse the cu_index/tu_index sections.  */
10798
10799 static void
10800 dwarf2_locate_v2_dwp_sections (bfd *abfd, asection *sectp, void *dwp_file_ptr)
10801 {
10802   struct dwp_file *dwp_file = (struct dwp_file *) dwp_file_ptr;
10803   const struct dwop_section_names *names = &dwop_section_names;
10804   unsigned int elf_section_nr = elf_section_data (sectp)->this_idx;
10805
10806   /* Record the ELF section number for later lookup: this is what the
10807      .debug_cu_index,.debug_tu_index tables use in DWP V1.  */
10808   gdb_assert (elf_section_nr < dwp_file->num_sections);
10809   dwp_file->elf_sections[elf_section_nr] = sectp;
10810
10811   /* Look for specific sections that we need.  */
10812   if (section_is_p (sectp->name, &names->abbrev_dwo))
10813     {
10814       dwp_file->sections.abbrev.s.section = sectp;
10815       dwp_file->sections.abbrev.size = bfd_get_section_size (sectp);
10816     }
10817   else if (section_is_p (sectp->name, &names->info_dwo))
10818     {
10819       dwp_file->sections.info.s.section = sectp;
10820       dwp_file->sections.info.size = bfd_get_section_size (sectp);
10821     }
10822   else if (section_is_p (sectp->name, &names->line_dwo))
10823     {
10824       dwp_file->sections.line.s.section = sectp;
10825       dwp_file->sections.line.size = bfd_get_section_size (sectp);
10826     }
10827   else if (section_is_p (sectp->name, &names->loc_dwo))
10828     {
10829       dwp_file->sections.loc.s.section = sectp;
10830       dwp_file->sections.loc.size = bfd_get_section_size (sectp);
10831     }
10832   else if (section_is_p (sectp->name, &names->macinfo_dwo))
10833     {
10834       dwp_file->sections.macinfo.s.section = sectp;
10835       dwp_file->sections.macinfo.size = bfd_get_section_size (sectp);
10836     }
10837   else if (section_is_p (sectp->name, &names->macro_dwo))
10838     {
10839       dwp_file->sections.macro.s.section = sectp;
10840       dwp_file->sections.macro.size = bfd_get_section_size (sectp);
10841     }
10842   else if (section_is_p (sectp->name, &names->str_offsets_dwo))
10843     {
10844       dwp_file->sections.str_offsets.s.section = sectp;
10845       dwp_file->sections.str_offsets.size = bfd_get_section_size (sectp);
10846     }
10847   else if (section_is_p (sectp->name, &names->types_dwo))
10848     {
10849       dwp_file->sections.types.s.section = sectp;
10850       dwp_file->sections.types.size = bfd_get_section_size (sectp);
10851     }
10852 }
10853
10854 /* Hash function for dwp_file loaded CUs/TUs.  */
10855
10856 static hashval_t
10857 hash_dwp_loaded_cutus (const void *item)
10858 {
10859   const struct dwo_unit *dwo_unit = (const struct dwo_unit *) item;
10860
10861   /* This drops the top 32 bits of the signature, but is ok for a hash.  */
10862   return dwo_unit->signature;
10863 }
10864
10865 /* Equality function for dwp_file loaded CUs/TUs.  */
10866
10867 static int
10868 eq_dwp_loaded_cutus (const void *a, const void *b)
10869 {
10870   const struct dwo_unit *dua = (const struct dwo_unit *) a;
10871   const struct dwo_unit *dub = (const struct dwo_unit *) b;
10872
10873   return dua->signature == dub->signature;
10874 }
10875
10876 /* Allocate a hash table for dwp_file loaded CUs/TUs.  */
10877
10878 static htab_t
10879 allocate_dwp_loaded_cutus_table (struct objfile *objfile)
10880 {
10881   return htab_create_alloc_ex (3,
10882                                hash_dwp_loaded_cutus,
10883                                eq_dwp_loaded_cutus,
10884                                NULL,
10885                                &objfile->objfile_obstack,
10886                                hashtab_obstack_allocate,
10887                                dummy_obstack_deallocate);
10888 }
10889
10890 /* Try to open DWP file FILE_NAME.
10891    The result is the bfd handle of the file.
10892    If there is a problem finding or opening the file, return NULL.
10893    Upon success, the canonicalized path of the file is stored in the bfd,
10894    same as symfile_bfd_open.  */
10895
10896 static gdb_bfd_ref_ptr
10897 open_dwp_file (const char *file_name)
10898 {
10899   gdb_bfd_ref_ptr abfd (try_open_dwop_file (file_name, 1 /*is_dwp*/,
10900                                             1 /*search_cwd*/));
10901   if (abfd != NULL)
10902     return abfd;
10903
10904   /* Work around upstream bug 15652.
10905      http://sourceware.org/bugzilla/show_bug.cgi?id=15652
10906      [Whether that's a "bug" is debatable, but it is getting in our way.]
10907      We have no real idea where the dwp file is, because gdb's realpath-ing
10908      of the executable's path may have discarded the needed info.
10909      [IWBN if the dwp file name was recorded in the executable, akin to
10910      .gnu_debuglink, but that doesn't exist yet.]
10911      Strip the directory from FILE_NAME and search again.  */
10912   if (*debug_file_directory != '\0')
10913     {
10914       /* Don't implicitly search the current directory here.
10915          If the user wants to search "." to handle this case,
10916          it must be added to debug-file-directory.  */
10917       return try_open_dwop_file (lbasename (file_name), 1 /*is_dwp*/,
10918                                  0 /*search_cwd*/);
10919     }
10920
10921   return NULL;
10922 }
10923
10924 /* Initialize the use of the DWP file for the current objfile.
10925    By convention the name of the DWP file is ${objfile}.dwp.
10926    The result is NULL if it can't be found.  */
10927
10928 static struct dwp_file *
10929 open_and_init_dwp_file (void)
10930 {
10931   struct objfile *objfile = dwarf2_per_objfile->objfile;
10932   struct dwp_file *dwp_file;
10933
10934   /* Try to find first .dwp for the binary file before any symbolic links
10935      resolving.  */
10936
10937   /* If the objfile is a debug file, find the name of the real binary
10938      file and get the name of dwp file from there.  */
10939   std::string dwp_name;
10940   if (objfile->separate_debug_objfile_backlink != NULL)
10941     {
10942       struct objfile *backlink = objfile->separate_debug_objfile_backlink;
10943       const char *backlink_basename = lbasename (backlink->original_name);
10944
10945       dwp_name = ldirname (objfile->original_name) + SLASH_STRING + backlink_basename;
10946     }
10947   else
10948     dwp_name = objfile->original_name;
10949
10950   dwp_name += ".dwp";
10951
10952   gdb_bfd_ref_ptr dbfd (open_dwp_file (dwp_name.c_str ()));
10953   if (dbfd == NULL
10954       && strcmp (objfile->original_name, objfile_name (objfile)) != 0)
10955     {
10956       /* Try to find .dwp for the binary file after gdb_realpath resolving.  */
10957       dwp_name = objfile_name (objfile);
10958       dwp_name += ".dwp";
10959       dbfd = open_dwp_file (dwp_name.c_str ());
10960     }
10961
10962   if (dbfd == NULL)
10963     {
10964       if (dwarf_read_debug)
10965         fprintf_unfiltered (gdb_stdlog, "DWP file not found: %s\n", dwp_name.c_str ());
10966       return NULL;
10967     }
10968   dwp_file = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwp_file);
10969   dwp_file->name = bfd_get_filename (dbfd.get ());
10970   dwp_file->dbfd = dbfd.release ();
10971
10972   /* +1: section 0 is unused */
10973   dwp_file->num_sections = bfd_count_sections (dwp_file->dbfd) + 1;
10974   dwp_file->elf_sections =
10975     OBSTACK_CALLOC (&objfile->objfile_obstack,
10976                     dwp_file->num_sections, asection *);
10977
10978   bfd_map_over_sections (dwp_file->dbfd, dwarf2_locate_common_dwp_sections,
10979                          dwp_file);
10980
10981   dwp_file->cus = create_dwp_hash_table (dwp_file, 0);
10982
10983   dwp_file->tus = create_dwp_hash_table (dwp_file, 1);
10984
10985   /* The DWP file version is stored in the hash table.  Oh well.  */
10986   if (dwp_file->cus->version != dwp_file->tus->version)
10987     {
10988       /* Technically speaking, we should try to limp along, but this is
10989          pretty bizarre.  We use pulongest here because that's the established
10990          portability solution (e.g, we cannot use %u for uint32_t).  */
10991       error (_("Dwarf Error: DWP file CU version %s doesn't match"
10992                " TU version %s [in DWP file %s]"),
10993              pulongest (dwp_file->cus->version),
10994              pulongest (dwp_file->tus->version), dwp_name.c_str ());
10995     }
10996   dwp_file->version = dwp_file->cus->version;
10997
10998   if (dwp_file->version == 2)
10999     bfd_map_over_sections (dwp_file->dbfd, dwarf2_locate_v2_dwp_sections,
11000                            dwp_file);
11001
11002   dwp_file->loaded_cus = allocate_dwp_loaded_cutus_table (objfile);
11003   dwp_file->loaded_tus = allocate_dwp_loaded_cutus_table (objfile);
11004
11005   if (dwarf_read_debug)
11006     {
11007       fprintf_unfiltered (gdb_stdlog, "DWP file found: %s\n", dwp_file->name);
11008       fprintf_unfiltered (gdb_stdlog,
11009                           "    %s CUs, %s TUs\n",
11010                           pulongest (dwp_file->cus ? dwp_file->cus->nr_units : 0),
11011                           pulongest (dwp_file->tus ? dwp_file->tus->nr_units : 0));
11012     }
11013
11014   return dwp_file;
11015 }
11016
11017 /* Wrapper around open_and_init_dwp_file, only open it once.  */
11018
11019 static struct dwp_file *
11020 get_dwp_file (void)
11021 {
11022   if (! dwarf2_per_objfile->dwp_checked)
11023     {
11024       dwarf2_per_objfile->dwp_file = open_and_init_dwp_file ();
11025       dwarf2_per_objfile->dwp_checked = 1;
11026     }
11027   return dwarf2_per_objfile->dwp_file;
11028 }
11029
11030 /* Subroutine of lookup_dwo_comp_unit, lookup_dwo_type_unit.
11031    Look up the CU/TU with signature SIGNATURE, either in DWO file DWO_NAME
11032    or in the DWP file for the objfile, referenced by THIS_UNIT.
11033    If non-NULL, comp_dir is the DW_AT_comp_dir attribute.
11034    IS_DEBUG_TYPES is non-zero if reading a TU, otherwise read a CU.
11035
11036    This is called, for example, when wanting to read a variable with a
11037    complex location.  Therefore we don't want to do file i/o for every call.
11038    Therefore we don't want to look for a DWO file on every call.
11039    Therefore we first see if we've already seen SIGNATURE in a DWP file,
11040    then we check if we've already seen DWO_NAME, and only THEN do we check
11041    for a DWO file.
11042
11043    The result is a pointer to the dwo_unit object or NULL if we didn't find it
11044    (dwo_id mismatch or couldn't find the DWO/DWP file).  */
11045
11046 static struct dwo_unit *
11047 lookup_dwo_cutu (struct dwarf2_per_cu_data *this_unit,
11048                  const char *dwo_name, const char *comp_dir,
11049                  ULONGEST signature, int is_debug_types)
11050 {
11051   struct objfile *objfile = dwarf2_per_objfile->objfile;
11052   const char *kind = is_debug_types ? "TU" : "CU";
11053   void **dwo_file_slot;
11054   struct dwo_file *dwo_file;
11055   struct dwp_file *dwp_file;
11056
11057   /* First see if there's a DWP file.
11058      If we have a DWP file but didn't find the DWO inside it, don't
11059      look for the original DWO file.  It makes gdb behave differently
11060      depending on whether one is debugging in the build tree.  */
11061
11062   dwp_file = get_dwp_file ();
11063   if (dwp_file != NULL)
11064     {
11065       const struct dwp_hash_table *dwp_htab =
11066         is_debug_types ? dwp_file->tus : dwp_file->cus;
11067
11068       if (dwp_htab != NULL)
11069         {
11070           struct dwo_unit *dwo_cutu =
11071             lookup_dwo_unit_in_dwp (dwp_file, comp_dir,
11072                                     signature, is_debug_types);
11073
11074           if (dwo_cutu != NULL)
11075             {
11076               if (dwarf_read_debug)
11077                 {
11078                   fprintf_unfiltered (gdb_stdlog,
11079                                       "Virtual DWO %s %s found: @%s\n",
11080                                       kind, hex_string (signature),
11081                                       host_address_to_string (dwo_cutu));
11082                 }
11083               return dwo_cutu;
11084             }
11085         }
11086     }
11087   else
11088     {
11089       /* No DWP file, look for the DWO file.  */
11090
11091       dwo_file_slot = lookup_dwo_file_slot (dwo_name, comp_dir);
11092       if (*dwo_file_slot == NULL)
11093         {
11094           /* Read in the file and build a table of the CUs/TUs it contains.  */
11095           *dwo_file_slot = open_and_init_dwo_file (this_unit, dwo_name, comp_dir);
11096         }
11097       /* NOTE: This will be NULL if unable to open the file.  */
11098       dwo_file = (struct dwo_file *) *dwo_file_slot;
11099
11100       if (dwo_file != NULL)
11101         {
11102           struct dwo_unit *dwo_cutu = NULL;
11103
11104           if (is_debug_types && dwo_file->tus)
11105             {
11106               struct dwo_unit find_dwo_cutu;
11107
11108               memset (&find_dwo_cutu, 0, sizeof (find_dwo_cutu));
11109               find_dwo_cutu.signature = signature;
11110               dwo_cutu
11111                 = (struct dwo_unit *) htab_find (dwo_file->tus, &find_dwo_cutu);
11112             }
11113           else if (!is_debug_types && dwo_file->cu)
11114             {
11115               if (signature == dwo_file->cu->signature)
11116                 dwo_cutu = dwo_file->cu;
11117             }
11118
11119           if (dwo_cutu != NULL)
11120             {
11121               if (dwarf_read_debug)
11122                 {
11123                   fprintf_unfiltered (gdb_stdlog, "DWO %s %s(%s) found: @%s\n",
11124                                       kind, dwo_name, hex_string (signature),
11125                                       host_address_to_string (dwo_cutu));
11126                 }
11127               return dwo_cutu;
11128             }
11129         }
11130     }
11131
11132   /* We didn't find it.  This could mean a dwo_id mismatch, or
11133      someone deleted the DWO/DWP file, or the search path isn't set up
11134      correctly to find the file.  */
11135
11136   if (dwarf_read_debug)
11137     {
11138       fprintf_unfiltered (gdb_stdlog, "DWO %s %s(%s) not found\n",
11139                           kind, dwo_name, hex_string (signature));
11140     }
11141
11142   /* This is a warning and not a complaint because it can be caused by
11143      pilot error (e.g., user accidentally deleting the DWO).  */
11144   {
11145     /* Print the name of the DWP file if we looked there, helps the user
11146        better diagnose the problem.  */
11147     char *dwp_text = NULL;
11148     struct cleanup *cleanups;
11149
11150     if (dwp_file != NULL)
11151       dwp_text = xstrprintf (" [in DWP file %s]", lbasename (dwp_file->name));
11152     cleanups = make_cleanup (xfree, dwp_text);
11153
11154     warning (_("Could not find DWO %s %s(%s)%s referenced by %s at offset 0x%x"
11155                " [in module %s]"),
11156              kind, dwo_name, hex_string (signature),
11157              dwp_text != NULL ? dwp_text : "",
11158              this_unit->is_debug_types ? "TU" : "CU",
11159              this_unit->offset.sect_off, objfile_name (objfile));
11160
11161     do_cleanups (cleanups);
11162   }
11163   return NULL;
11164 }
11165
11166 /* Lookup the DWO CU DWO_NAME/SIGNATURE referenced from THIS_CU.
11167    See lookup_dwo_cutu_unit for details.  */
11168
11169 static struct dwo_unit *
11170 lookup_dwo_comp_unit (struct dwarf2_per_cu_data *this_cu,
11171                       const char *dwo_name, const char *comp_dir,
11172                       ULONGEST signature)
11173 {
11174   return lookup_dwo_cutu (this_cu, dwo_name, comp_dir, signature, 0);
11175 }
11176
11177 /* Lookup the DWO TU DWO_NAME/SIGNATURE referenced from THIS_TU.
11178    See lookup_dwo_cutu_unit for details.  */
11179
11180 static struct dwo_unit *
11181 lookup_dwo_type_unit (struct signatured_type *this_tu,
11182                       const char *dwo_name, const char *comp_dir)
11183 {
11184   return lookup_dwo_cutu (&this_tu->per_cu, dwo_name, comp_dir, this_tu->signature, 1);
11185 }
11186
11187 /* Traversal function for queue_and_load_all_dwo_tus.  */
11188
11189 static int
11190 queue_and_load_dwo_tu (void **slot, void *info)
11191 {
11192   struct dwo_unit *dwo_unit = (struct dwo_unit *) *slot;
11193   struct dwarf2_per_cu_data *per_cu = (struct dwarf2_per_cu_data *) info;
11194   ULONGEST signature = dwo_unit->signature;
11195   struct signatured_type *sig_type =
11196     lookup_dwo_signatured_type (per_cu->cu, signature);
11197
11198   if (sig_type != NULL)
11199     {
11200       struct dwarf2_per_cu_data *sig_cu = &sig_type->per_cu;
11201
11202       /* We pass NULL for DEPENDENT_CU because we don't yet know if there's
11203          a real dependency of PER_CU on SIG_TYPE.  That is detected later
11204          while processing PER_CU.  */
11205       if (maybe_queue_comp_unit (NULL, sig_cu, per_cu->cu->language))
11206         load_full_type_unit (sig_cu);
11207       VEC_safe_push (dwarf2_per_cu_ptr, per_cu->imported_symtabs, sig_cu);
11208     }
11209
11210   return 1;
11211 }
11212
11213 /* Queue all TUs contained in the DWO of PER_CU to be read in.
11214    The DWO may have the only definition of the type, though it may not be
11215    referenced anywhere in PER_CU.  Thus we have to load *all* its TUs.
11216    http://sourceware.org/bugzilla/show_bug.cgi?id=15021  */
11217
11218 static void
11219 queue_and_load_all_dwo_tus (struct dwarf2_per_cu_data *per_cu)
11220 {
11221   struct dwo_unit *dwo_unit;
11222   struct dwo_file *dwo_file;
11223
11224   gdb_assert (!per_cu->is_debug_types);
11225   gdb_assert (get_dwp_file () == NULL);
11226   gdb_assert (per_cu->cu != NULL);
11227
11228   dwo_unit = per_cu->cu->dwo_unit;
11229   gdb_assert (dwo_unit != NULL);
11230
11231   dwo_file = dwo_unit->dwo_file;
11232   if (dwo_file->tus != NULL)
11233     htab_traverse_noresize (dwo_file->tus, queue_and_load_dwo_tu, per_cu);
11234 }
11235
11236 /* Free all resources associated with DWO_FILE.
11237    Close the DWO file and munmap the sections.
11238    All memory should be on the objfile obstack.  */
11239
11240 static void
11241 free_dwo_file (struct dwo_file *dwo_file, struct objfile *objfile)
11242 {
11243
11244   /* Note: dbfd is NULL for virtual DWO files.  */
11245   gdb_bfd_unref (dwo_file->dbfd);
11246
11247   VEC_free (dwarf2_section_info_def, dwo_file->sections.types);
11248 }
11249
11250 /* Wrapper for free_dwo_file for use in cleanups.  */
11251
11252 static void
11253 free_dwo_file_cleanup (void *arg)
11254 {
11255   struct dwo_file *dwo_file = (struct dwo_file *) arg;
11256   struct objfile *objfile = dwarf2_per_objfile->objfile;
11257
11258   free_dwo_file (dwo_file, objfile);
11259 }
11260
11261 /* Traversal function for free_dwo_files.  */
11262
11263 static int
11264 free_dwo_file_from_slot (void **slot, void *info)
11265 {
11266   struct dwo_file *dwo_file = (struct dwo_file *) *slot;
11267   struct objfile *objfile = (struct objfile *) info;
11268
11269   free_dwo_file (dwo_file, objfile);
11270
11271   return 1;
11272 }
11273
11274 /* Free all resources associated with DWO_FILES.  */
11275
11276 static void
11277 free_dwo_files (htab_t dwo_files, struct objfile *objfile)
11278 {
11279   htab_traverse_noresize (dwo_files, free_dwo_file_from_slot, objfile);
11280 }
11281 \f
11282 /* Read in various DIEs.  */
11283
11284 /* qsort helper for inherit_abstract_dies.  */
11285
11286 static int
11287 unsigned_int_compar (const void *ap, const void *bp)
11288 {
11289   unsigned int a = *(unsigned int *) ap;
11290   unsigned int b = *(unsigned int *) bp;
11291
11292   return (a > b) - (b > a);
11293 }
11294
11295 /* DW_AT_abstract_origin inherits whole DIEs (not just their attributes).
11296    Inherit only the children of the DW_AT_abstract_origin DIE not being
11297    already referenced by DW_AT_abstract_origin from the children of the
11298    current DIE.  */
11299
11300 static void
11301 inherit_abstract_dies (struct die_info *die, struct dwarf2_cu *cu)
11302 {
11303   struct die_info *child_die;
11304   unsigned die_children_count;
11305   /* CU offsets which were referenced by children of the current DIE.  */
11306   sect_offset *offsets;
11307   sect_offset *offsets_end, *offsetp;
11308   /* Parent of DIE - referenced by DW_AT_abstract_origin.  */
11309   struct die_info *origin_die;
11310   /* Iterator of the ORIGIN_DIE children.  */
11311   struct die_info *origin_child_die;
11312   struct cleanup *cleanups;
11313   struct attribute *attr;
11314   struct dwarf2_cu *origin_cu;
11315   struct pending **origin_previous_list_in_scope;
11316
11317   attr = dwarf2_attr (die, DW_AT_abstract_origin, cu);
11318   if (!attr)
11319     return;
11320
11321   /* Note that following die references may follow to a die in a
11322      different cu.  */
11323
11324   origin_cu = cu;
11325   origin_die = follow_die_ref (die, attr, &origin_cu);
11326
11327   /* We're inheriting ORIGIN's children into the scope we'd put DIE's
11328      symbols in.  */
11329   origin_previous_list_in_scope = origin_cu->list_in_scope;
11330   origin_cu->list_in_scope = cu->list_in_scope;
11331
11332   if (die->tag != origin_die->tag
11333       && !(die->tag == DW_TAG_inlined_subroutine
11334            && origin_die->tag == DW_TAG_subprogram))
11335     complaint (&symfile_complaints,
11336                _("DIE 0x%x and its abstract origin 0x%x have different tags"),
11337                die->offset.sect_off, origin_die->offset.sect_off);
11338
11339   child_die = die->child;
11340   die_children_count = 0;
11341   while (child_die && child_die->tag)
11342     {
11343       child_die = sibling_die (child_die);
11344       die_children_count++;
11345     }
11346   offsets = XNEWVEC (sect_offset, die_children_count);
11347   cleanups = make_cleanup (xfree, offsets);
11348
11349   offsets_end = offsets;
11350   for (child_die = die->child;
11351        child_die && child_die->tag;
11352        child_die = sibling_die (child_die))
11353     {
11354       struct die_info *child_origin_die;
11355       struct dwarf2_cu *child_origin_cu;
11356
11357       /* We are trying to process concrete instance entries:
11358          DW_TAG_call_site DIEs indeed have a DW_AT_abstract_origin tag, but
11359          it's not relevant to our analysis here. i.e. detecting DIEs that are
11360          present in the abstract instance but not referenced in the concrete
11361          one.  */
11362       if (child_die->tag == DW_TAG_call_site
11363           || child_die->tag == DW_TAG_GNU_call_site)
11364         continue;
11365
11366       /* For each CHILD_DIE, find the corresponding child of
11367          ORIGIN_DIE.  If there is more than one layer of
11368          DW_AT_abstract_origin, follow them all; there shouldn't be,
11369          but GCC versions at least through 4.4 generate this (GCC PR
11370          40573).  */
11371       child_origin_die = child_die;
11372       child_origin_cu = cu;
11373       while (1)
11374         {
11375           attr = dwarf2_attr (child_origin_die, DW_AT_abstract_origin,
11376                               child_origin_cu);
11377           if (attr == NULL)
11378             break;
11379           child_origin_die = follow_die_ref (child_origin_die, attr,
11380                                              &child_origin_cu);
11381         }
11382
11383       /* According to DWARF3 3.3.8.2 #3 new entries without their abstract
11384          counterpart may exist.  */
11385       if (child_origin_die != child_die)
11386         {
11387           if (child_die->tag != child_origin_die->tag
11388               && !(child_die->tag == DW_TAG_inlined_subroutine
11389                    && child_origin_die->tag == DW_TAG_subprogram))
11390             complaint (&symfile_complaints,
11391                        _("Child DIE 0x%x and its abstract origin 0x%x have "
11392                          "different tags"), child_die->offset.sect_off,
11393                        child_origin_die->offset.sect_off);
11394           if (child_origin_die->parent != origin_die)
11395             complaint (&symfile_complaints,
11396                        _("Child DIE 0x%x and its abstract origin 0x%x have "
11397                          "different parents"), child_die->offset.sect_off,
11398                        child_origin_die->offset.sect_off);
11399           else
11400             *offsets_end++ = child_origin_die->offset;
11401         }
11402     }
11403   qsort (offsets, offsets_end - offsets, sizeof (*offsets),
11404          unsigned_int_compar);
11405   for (offsetp = offsets + 1; offsetp < offsets_end; offsetp++)
11406     if (offsetp[-1].sect_off == offsetp->sect_off)
11407       complaint (&symfile_complaints,
11408                  _("Multiple children of DIE 0x%x refer "
11409                    "to DIE 0x%x as their abstract origin"),
11410                  die->offset.sect_off, offsetp->sect_off);
11411
11412   offsetp = offsets;
11413   origin_child_die = origin_die->child;
11414   while (origin_child_die && origin_child_die->tag)
11415     {
11416       /* Is ORIGIN_CHILD_DIE referenced by any of the DIE children?  */
11417       while (offsetp < offsets_end
11418              && offsetp->sect_off < origin_child_die->offset.sect_off)
11419         offsetp++;
11420       if (offsetp >= offsets_end
11421           || offsetp->sect_off > origin_child_die->offset.sect_off)
11422         {
11423           /* Found that ORIGIN_CHILD_DIE is really not referenced.
11424              Check whether we're already processing ORIGIN_CHILD_DIE.
11425              This can happen with mutually referenced abstract_origins.
11426              PR 16581.  */
11427           if (!origin_child_die->in_process)
11428             process_die (origin_child_die, origin_cu);
11429         }
11430       origin_child_die = sibling_die (origin_child_die);
11431     }
11432   origin_cu->list_in_scope = origin_previous_list_in_scope;
11433
11434   do_cleanups (cleanups);
11435 }
11436
11437 static void
11438 read_func_scope (struct die_info *die, struct dwarf2_cu *cu)
11439 {
11440   struct objfile *objfile = cu->objfile;
11441   struct gdbarch *gdbarch = get_objfile_arch (objfile);
11442   struct context_stack *newobj;
11443   CORE_ADDR lowpc;
11444   CORE_ADDR highpc;
11445   struct die_info *child_die;
11446   struct attribute *attr, *call_line, *call_file;
11447   const char *name;
11448   CORE_ADDR baseaddr;
11449   struct block *block;
11450   int inlined_func = (die->tag == DW_TAG_inlined_subroutine);
11451   VEC (symbolp) *template_args = NULL;
11452   struct template_symbol *templ_func = NULL;
11453
11454   if (inlined_func)
11455     {
11456       /* If we do not have call site information, we can't show the
11457          caller of this inlined function.  That's too confusing, so
11458          only use the scope for local variables.  */
11459       call_line = dwarf2_attr (die, DW_AT_call_line, cu);
11460       call_file = dwarf2_attr (die, DW_AT_call_file, cu);
11461       if (call_line == NULL || call_file == NULL)
11462         {
11463           read_lexical_block_scope (die, cu);
11464           return;
11465         }
11466     }
11467
11468   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
11469
11470   name = dwarf2_name (die, cu);
11471
11472   /* Ignore functions with missing or empty names.  These are actually
11473      illegal according to the DWARF standard.  */
11474   if (name == NULL)
11475     {
11476       complaint (&symfile_complaints,
11477                  _("missing name for subprogram DIE at %d"),
11478                  die->offset.sect_off);
11479       return;
11480     }
11481
11482   /* Ignore functions with missing or invalid low and high pc attributes.  */
11483   if (dwarf2_get_pc_bounds (die, &lowpc, &highpc, cu, NULL)
11484       <= PC_BOUNDS_INVALID)
11485     {
11486       attr = dwarf2_attr (die, DW_AT_external, cu);
11487       if (!attr || !DW_UNSND (attr))
11488         complaint (&symfile_complaints,
11489                    _("cannot get low and high bounds "
11490                      "for subprogram DIE at %d"),
11491                    die->offset.sect_off);
11492       return;
11493     }
11494
11495   lowpc = gdbarch_adjust_dwarf2_addr (gdbarch, lowpc + baseaddr);
11496   highpc = gdbarch_adjust_dwarf2_addr (gdbarch, highpc + baseaddr);
11497
11498   /* If we have any template arguments, then we must allocate a
11499      different sort of symbol.  */
11500   for (child_die = die->child; child_die; child_die = sibling_die (child_die))
11501     {
11502       if (child_die->tag == DW_TAG_template_type_param
11503           || child_die->tag == DW_TAG_template_value_param)
11504         {
11505           templ_func = allocate_template_symbol (objfile);
11506           templ_func->base.is_cplus_template_function = 1;
11507           break;
11508         }
11509     }
11510
11511   newobj = push_context (0, lowpc);
11512   newobj->name = new_symbol_full (die, read_type_die (die, cu), cu,
11513                                (struct symbol *) templ_func);
11514
11515   /* If there is a location expression for DW_AT_frame_base, record
11516      it.  */
11517   attr = dwarf2_attr (die, DW_AT_frame_base, cu);
11518   if (attr)
11519     dwarf2_symbol_mark_computed (attr, newobj->name, cu, 1);
11520
11521   /* If there is a location for the static link, record it.  */
11522   newobj->static_link = NULL;
11523   attr = dwarf2_attr (die, DW_AT_static_link, cu);
11524   if (attr)
11525     {
11526       newobj->static_link
11527         = XOBNEW (&objfile->objfile_obstack, struct dynamic_prop);
11528       attr_to_dynamic_prop (attr, die, cu, newobj->static_link);
11529     }
11530
11531   cu->list_in_scope = &local_symbols;
11532
11533   if (die->child != NULL)
11534     {
11535       child_die = die->child;
11536       while (child_die && child_die->tag)
11537         {
11538           if (child_die->tag == DW_TAG_template_type_param
11539               || child_die->tag == DW_TAG_template_value_param)
11540             {
11541               struct symbol *arg = new_symbol (child_die, NULL, cu);
11542
11543               if (arg != NULL)
11544                 VEC_safe_push (symbolp, template_args, arg);
11545             }
11546           else
11547             process_die (child_die, cu);
11548           child_die = sibling_die (child_die);
11549         }
11550     }
11551
11552   inherit_abstract_dies (die, cu);
11553
11554   /* If we have a DW_AT_specification, we might need to import using
11555      directives from the context of the specification DIE.  See the
11556      comment in determine_prefix.  */
11557   if (cu->language == language_cplus
11558       && dwarf2_attr (die, DW_AT_specification, cu))
11559     {
11560       struct dwarf2_cu *spec_cu = cu;
11561       struct die_info *spec_die = die_specification (die, &spec_cu);
11562
11563       while (spec_die)
11564         {
11565           child_die = spec_die->child;
11566           while (child_die && child_die->tag)
11567             {
11568               if (child_die->tag == DW_TAG_imported_module)
11569                 process_die (child_die, spec_cu);
11570               child_die = sibling_die (child_die);
11571             }
11572
11573           /* In some cases, GCC generates specification DIEs that
11574              themselves contain DW_AT_specification attributes.  */
11575           spec_die = die_specification (spec_die, &spec_cu);
11576         }
11577     }
11578
11579   newobj = pop_context ();
11580   /* Make a block for the local symbols within.  */
11581   block = finish_block (newobj->name, &local_symbols, newobj->old_blocks,
11582                         newobj->static_link, lowpc, highpc);
11583
11584   /* For C++, set the block's scope.  */
11585   if ((cu->language == language_cplus
11586        || cu->language == language_fortran
11587        || cu->language == language_d
11588        || cu->language == language_rust)
11589       && cu->processing_has_namespace_info)
11590     block_set_scope (block, determine_prefix (die, cu),
11591                      &objfile->objfile_obstack);
11592
11593   /* If we have address ranges, record them.  */
11594   dwarf2_record_block_ranges (die, block, baseaddr, cu);
11595
11596   gdbarch_make_symbol_special (gdbarch, newobj->name, objfile);
11597
11598   /* Attach template arguments to function.  */
11599   if (! VEC_empty (symbolp, template_args))
11600     {
11601       gdb_assert (templ_func != NULL);
11602
11603       templ_func->n_template_arguments = VEC_length (symbolp, template_args);
11604       templ_func->template_arguments
11605         = XOBNEWVEC (&objfile->objfile_obstack, struct symbol *,
11606                      templ_func->n_template_arguments);
11607       memcpy (templ_func->template_arguments,
11608               VEC_address (symbolp, template_args),
11609               (templ_func->n_template_arguments * sizeof (struct symbol *)));
11610       VEC_free (symbolp, template_args);
11611     }
11612
11613   /* In C++, we can have functions nested inside functions (e.g., when
11614      a function declares a class that has methods).  This means that
11615      when we finish processing a function scope, we may need to go
11616      back to building a containing block's symbol lists.  */
11617   local_symbols = newobj->locals;
11618   local_using_directives = newobj->local_using_directives;
11619
11620   /* If we've finished processing a top-level function, subsequent
11621      symbols go in the file symbol list.  */
11622   if (outermost_context_p ())
11623     cu->list_in_scope = &file_symbols;
11624 }
11625
11626 /* Process all the DIES contained within a lexical block scope.  Start
11627    a new scope, process the dies, and then close the scope.  */
11628
11629 static void
11630 read_lexical_block_scope (struct die_info *die, struct dwarf2_cu *cu)
11631 {
11632   struct objfile *objfile = cu->objfile;
11633   struct gdbarch *gdbarch = get_objfile_arch (objfile);
11634   struct context_stack *newobj;
11635   CORE_ADDR lowpc, highpc;
11636   struct die_info *child_die;
11637   CORE_ADDR baseaddr;
11638
11639   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
11640
11641   /* Ignore blocks with missing or invalid low and high pc attributes.  */
11642   /* ??? Perhaps consider discontiguous blocks defined by DW_AT_ranges
11643      as multiple lexical blocks?  Handling children in a sane way would
11644      be nasty.  Might be easier to properly extend generic blocks to
11645      describe ranges.  */
11646   switch (dwarf2_get_pc_bounds (die, &lowpc, &highpc, cu, NULL))
11647     {
11648     case PC_BOUNDS_NOT_PRESENT:
11649       /* DW_TAG_lexical_block has no attributes, process its children as if
11650          there was no wrapping by that DW_TAG_lexical_block.
11651          GCC does no longer produces such DWARF since GCC r224161.  */
11652       for (child_die = die->child;
11653            child_die != NULL && child_die->tag;
11654            child_die = sibling_die (child_die))
11655         process_die (child_die, cu);
11656       return;
11657     case PC_BOUNDS_INVALID:
11658       return;
11659     }
11660   lowpc = gdbarch_adjust_dwarf2_addr (gdbarch, lowpc + baseaddr);
11661   highpc = gdbarch_adjust_dwarf2_addr (gdbarch, highpc + baseaddr);
11662
11663   push_context (0, lowpc);
11664   if (die->child != NULL)
11665     {
11666       child_die = die->child;
11667       while (child_die && child_die->tag)
11668         {
11669           process_die (child_die, cu);
11670           child_die = sibling_die (child_die);
11671         }
11672     }
11673   inherit_abstract_dies (die, cu);
11674   newobj = pop_context ();
11675
11676   if (local_symbols != NULL || local_using_directives != NULL)
11677     {
11678       struct block *block
11679         = finish_block (0, &local_symbols, newobj->old_blocks, NULL,
11680                         newobj->start_addr, highpc);
11681
11682       /* Note that recording ranges after traversing children, as we
11683          do here, means that recording a parent's ranges entails
11684          walking across all its children's ranges as they appear in
11685          the address map, which is quadratic behavior.
11686
11687          It would be nicer to record the parent's ranges before
11688          traversing its children, simply overriding whatever you find
11689          there.  But since we don't even decide whether to create a
11690          block until after we've traversed its children, that's hard
11691          to do.  */
11692       dwarf2_record_block_ranges (die, block, baseaddr, cu);
11693     }
11694   local_symbols = newobj->locals;
11695   local_using_directives = newobj->local_using_directives;
11696 }
11697
11698 /* Read in DW_TAG_call_site and insert it to CU->call_site_htab.  */
11699
11700 static void
11701 read_call_site_scope (struct die_info *die, struct dwarf2_cu *cu)
11702 {
11703   struct objfile *objfile = cu->objfile;
11704   struct gdbarch *gdbarch = get_objfile_arch (objfile);
11705   CORE_ADDR pc, baseaddr;
11706   struct attribute *attr;
11707   struct call_site *call_site, call_site_local;
11708   void **slot;
11709   int nparams;
11710   struct die_info *child_die;
11711
11712   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
11713
11714   attr = dwarf2_attr (die, DW_AT_call_return_pc, cu);
11715   if (attr == NULL)
11716     {
11717       /* This was a pre-DWARF-5 GNU extension alias
11718          for DW_AT_call_return_pc.  */
11719       attr = dwarf2_attr (die, DW_AT_low_pc, cu);
11720     }
11721   if (!attr)
11722     {
11723       complaint (&symfile_complaints,
11724                  _("missing DW_AT_call_return_pc for DW_TAG_call_site "
11725                    "DIE 0x%x [in module %s]"),
11726                  die->offset.sect_off, objfile_name (objfile));
11727       return;
11728     }
11729   pc = attr_value_as_address (attr) + baseaddr;
11730   pc = gdbarch_adjust_dwarf2_addr (gdbarch, pc);
11731
11732   if (cu->call_site_htab == NULL)
11733     cu->call_site_htab = htab_create_alloc_ex (16, core_addr_hash, core_addr_eq,
11734                                                NULL, &objfile->objfile_obstack,
11735                                                hashtab_obstack_allocate, NULL);
11736   call_site_local.pc = pc;
11737   slot = htab_find_slot (cu->call_site_htab, &call_site_local, INSERT);
11738   if (*slot != NULL)
11739     {
11740       complaint (&symfile_complaints,
11741                  _("Duplicate PC %s for DW_TAG_call_site "
11742                    "DIE 0x%x [in module %s]"),
11743                  paddress (gdbarch, pc), die->offset.sect_off,
11744                  objfile_name (objfile));
11745       return;
11746     }
11747
11748   /* Count parameters at the caller.  */
11749
11750   nparams = 0;
11751   for (child_die = die->child; child_die && child_die->tag;
11752        child_die = sibling_die (child_die))
11753     {
11754       if (child_die->tag != DW_TAG_call_site_parameter
11755           && child_die->tag != DW_TAG_GNU_call_site_parameter)
11756         {
11757           complaint (&symfile_complaints,
11758                      _("Tag %d is not DW_TAG_call_site_parameter in "
11759                        "DW_TAG_call_site child DIE 0x%x [in module %s]"),
11760                      child_die->tag, child_die->offset.sect_off,
11761                      objfile_name (objfile));
11762           continue;
11763         }
11764
11765       nparams++;
11766     }
11767
11768   call_site
11769     = ((struct call_site *)
11770        obstack_alloc (&objfile->objfile_obstack,
11771                       sizeof (*call_site)
11772                       + (sizeof (*call_site->parameter) * (nparams - 1))));
11773   *slot = call_site;
11774   memset (call_site, 0, sizeof (*call_site) - sizeof (*call_site->parameter));
11775   call_site->pc = pc;
11776
11777   if (dwarf2_flag_true_p (die, DW_AT_call_tail_call, cu)
11778       || dwarf2_flag_true_p (die, DW_AT_GNU_tail_call, cu))
11779     {
11780       struct die_info *func_die;
11781
11782       /* Skip also over DW_TAG_inlined_subroutine.  */
11783       for (func_die = die->parent;
11784            func_die && func_die->tag != DW_TAG_subprogram
11785            && func_die->tag != DW_TAG_subroutine_type;
11786            func_die = func_die->parent);
11787
11788       /* DW_AT_call_all_calls is a superset
11789          of DW_AT_call_all_tail_calls.  */
11790       if (func_die
11791           && !dwarf2_flag_true_p (func_die, DW_AT_call_all_calls, cu)
11792           && !dwarf2_flag_true_p (func_die, DW_AT_GNU_all_call_sites, cu)
11793           && !dwarf2_flag_true_p (func_die, DW_AT_call_all_tail_calls, cu)
11794           && !dwarf2_flag_true_p (func_die, DW_AT_GNU_all_tail_call_sites, cu))
11795         {
11796           /* TYPE_TAIL_CALL_LIST is not interesting in functions where it is
11797              not complete.  But keep CALL_SITE for look ups via call_site_htab,
11798              both the initial caller containing the real return address PC and
11799              the final callee containing the current PC of a chain of tail
11800              calls do not need to have the tail call list complete.  But any
11801              function candidate for a virtual tail call frame searched via
11802              TYPE_TAIL_CALL_LIST must have the tail call list complete to be
11803              determined unambiguously.  */
11804         }
11805       else
11806         {
11807           struct type *func_type = NULL;
11808
11809           if (func_die)
11810             func_type = get_die_type (func_die, cu);
11811           if (func_type != NULL)
11812             {
11813               gdb_assert (TYPE_CODE (func_type) == TYPE_CODE_FUNC);
11814
11815               /* Enlist this call site to the function.  */
11816               call_site->tail_call_next = TYPE_TAIL_CALL_LIST (func_type);
11817               TYPE_TAIL_CALL_LIST (func_type) = call_site;
11818             }
11819           else
11820             complaint (&symfile_complaints,
11821                        _("Cannot find function owning DW_TAG_call_site "
11822                          "DIE 0x%x [in module %s]"),
11823                        die->offset.sect_off, objfile_name (objfile));
11824         }
11825     }
11826
11827   attr = dwarf2_attr (die, DW_AT_call_target, cu);
11828   if (attr == NULL)
11829     attr = dwarf2_attr (die, DW_AT_GNU_call_site_target, cu);
11830   if (attr == NULL)
11831     attr = dwarf2_attr (die, DW_AT_call_origin, cu);
11832   if (attr == NULL)
11833     {
11834       /* This was a pre-DWARF-5 GNU extension alias for DW_AT_call_origin.  */
11835       attr = dwarf2_attr (die, DW_AT_abstract_origin, cu);
11836     }
11837   SET_FIELD_DWARF_BLOCK (call_site->target, NULL);
11838   if (!attr || (attr_form_is_block (attr) && DW_BLOCK (attr)->size == 0))
11839     /* Keep NULL DWARF_BLOCK.  */;
11840   else if (attr_form_is_block (attr))
11841     {
11842       struct dwarf2_locexpr_baton *dlbaton;
11843
11844       dlbaton = XOBNEW (&objfile->objfile_obstack, struct dwarf2_locexpr_baton);
11845       dlbaton->data = DW_BLOCK (attr)->data;
11846       dlbaton->size = DW_BLOCK (attr)->size;
11847       dlbaton->per_cu = cu->per_cu;
11848
11849       SET_FIELD_DWARF_BLOCK (call_site->target, dlbaton);
11850     }
11851   else if (attr_form_is_ref (attr))
11852     {
11853       struct dwarf2_cu *target_cu = cu;
11854       struct die_info *target_die;
11855
11856       target_die = follow_die_ref (die, attr, &target_cu);
11857       gdb_assert (target_cu->objfile == objfile);
11858       if (die_is_declaration (target_die, target_cu))
11859         {
11860           const char *target_physname;
11861
11862           /* Prefer the mangled name; otherwise compute the demangled one.  */
11863           target_physname = dwarf2_string_attr (target_die,
11864                                                 DW_AT_linkage_name,
11865                                                 target_cu);
11866           if (target_physname == NULL)
11867             target_physname = dwarf2_string_attr (target_die,
11868                                                  DW_AT_MIPS_linkage_name,
11869                                                  target_cu);
11870           if (target_physname == NULL)
11871             target_physname = dwarf2_physname (NULL, target_die, target_cu);
11872           if (target_physname == NULL)
11873             complaint (&symfile_complaints,
11874                        _("DW_AT_call_target target DIE has invalid "
11875                          "physname, for referencing DIE 0x%x [in module %s]"),
11876                        die->offset.sect_off, objfile_name (objfile));
11877           else
11878             SET_FIELD_PHYSNAME (call_site->target, target_physname);
11879         }
11880       else
11881         {
11882           CORE_ADDR lowpc;
11883
11884           /* DW_AT_entry_pc should be preferred.  */
11885           if (dwarf2_get_pc_bounds (target_die, &lowpc, NULL, target_cu, NULL)
11886               <= PC_BOUNDS_INVALID)
11887             complaint (&symfile_complaints,
11888                        _("DW_AT_call_target target DIE has invalid "
11889                          "low pc, for referencing DIE 0x%x [in module %s]"),
11890                        die->offset.sect_off, objfile_name (objfile));
11891           else
11892             {
11893               lowpc = gdbarch_adjust_dwarf2_addr (gdbarch, lowpc + baseaddr);
11894               SET_FIELD_PHYSADDR (call_site->target, lowpc);
11895             }
11896         }
11897     }
11898   else
11899     complaint (&symfile_complaints,
11900                _("DW_TAG_call_site DW_AT_call_target is neither "
11901                  "block nor reference, for DIE 0x%x [in module %s]"),
11902                die->offset.sect_off, objfile_name (objfile));
11903
11904   call_site->per_cu = cu->per_cu;
11905
11906   for (child_die = die->child;
11907        child_die && child_die->tag;
11908        child_die = sibling_die (child_die))
11909     {
11910       struct call_site_parameter *parameter;
11911       struct attribute *loc, *origin;
11912
11913       if (child_die->tag != DW_TAG_call_site_parameter
11914           && child_die->tag != DW_TAG_GNU_call_site_parameter)
11915         {
11916           /* Already printed the complaint above.  */
11917           continue;
11918         }
11919
11920       gdb_assert (call_site->parameter_count < nparams);
11921       parameter = &call_site->parameter[call_site->parameter_count];
11922
11923       /* DW_AT_location specifies the register number or DW_AT_abstract_origin
11924          specifies DW_TAG_formal_parameter.  Value of the data assumed for the
11925          register is contained in DW_AT_call_value.  */
11926
11927       loc = dwarf2_attr (child_die, DW_AT_location, cu);
11928       origin = dwarf2_attr (child_die, DW_AT_call_parameter, cu);
11929       if (origin == NULL)
11930         {
11931           /* This was a pre-DWARF-5 GNU extension alias
11932              for DW_AT_call_parameter.  */
11933           origin = dwarf2_attr (child_die, DW_AT_abstract_origin, cu);
11934         }
11935       if (loc == NULL && origin != NULL && attr_form_is_ref (origin))
11936         {
11937           sect_offset offset;
11938
11939           parameter->kind = CALL_SITE_PARAMETER_PARAM_OFFSET;
11940           offset = dwarf2_get_ref_die_offset (origin);
11941           if (!offset_in_cu_p (&cu->header, offset))
11942             {
11943               /* As DW_OP_GNU_parameter_ref uses CU-relative offset this
11944                  binding can be done only inside one CU.  Such referenced DIE
11945                  therefore cannot be even moved to DW_TAG_partial_unit.  */
11946               complaint (&symfile_complaints,
11947                          _("DW_AT_call_parameter offset is not in CU for "
11948                            "DW_TAG_call_site child DIE 0x%x [in module %s]"),
11949                          child_die->offset.sect_off, objfile_name (objfile));
11950               continue;
11951             }
11952           parameter->u.param_offset.cu_off = (offset.sect_off
11953                                               - cu->header.offset.sect_off);
11954         }
11955       else if (loc == NULL || origin != NULL || !attr_form_is_block (loc))
11956         {
11957           complaint (&symfile_complaints,
11958                      _("No DW_FORM_block* DW_AT_location for "
11959                        "DW_TAG_call_site child DIE 0x%x [in module %s]"),
11960                      child_die->offset.sect_off, objfile_name (objfile));
11961           continue;
11962         }
11963       else
11964         {
11965           parameter->u.dwarf_reg = dwarf_block_to_dwarf_reg
11966             (DW_BLOCK (loc)->data, &DW_BLOCK (loc)->data[DW_BLOCK (loc)->size]);
11967           if (parameter->u.dwarf_reg != -1)
11968             parameter->kind = CALL_SITE_PARAMETER_DWARF_REG;
11969           else if (dwarf_block_to_sp_offset (gdbarch, DW_BLOCK (loc)->data,
11970                                     &DW_BLOCK (loc)->data[DW_BLOCK (loc)->size],
11971                                              &parameter->u.fb_offset))
11972             parameter->kind = CALL_SITE_PARAMETER_FB_OFFSET;
11973           else
11974             {
11975               complaint (&symfile_complaints,
11976                          _("Only single DW_OP_reg or DW_OP_fbreg is supported "
11977                            "for DW_FORM_block* DW_AT_location is supported for "
11978                            "DW_TAG_call_site child DIE 0x%x "
11979                            "[in module %s]"),
11980                          child_die->offset.sect_off, objfile_name (objfile));
11981               continue;
11982             }
11983         }
11984
11985       attr = dwarf2_attr (child_die, DW_AT_call_value, cu);
11986       if (attr == NULL)
11987         attr = dwarf2_attr (child_die, DW_AT_GNU_call_site_value, cu);
11988       if (!attr_form_is_block (attr))
11989         {
11990           complaint (&symfile_complaints,
11991                      _("No DW_FORM_block* DW_AT_call_value for "
11992                        "DW_TAG_call_site child DIE 0x%x [in module %s]"),
11993                      child_die->offset.sect_off, objfile_name (objfile));
11994           continue;
11995         }
11996       parameter->value = DW_BLOCK (attr)->data;
11997       parameter->value_size = DW_BLOCK (attr)->size;
11998
11999       /* Parameters are not pre-cleared by memset above.  */
12000       parameter->data_value = NULL;
12001       parameter->data_value_size = 0;
12002       call_site->parameter_count++;
12003
12004       attr = dwarf2_attr (child_die, DW_AT_call_data_value, cu);
12005       if (attr == NULL)
12006         attr = dwarf2_attr (child_die, DW_AT_GNU_call_site_data_value, cu);
12007       if (attr)
12008         {
12009           if (!attr_form_is_block (attr))
12010             complaint (&symfile_complaints,
12011                        _("No DW_FORM_block* DW_AT_call_data_value for "
12012                          "DW_TAG_call_site child DIE 0x%x [in module %s]"),
12013                        child_die->offset.sect_off, objfile_name (objfile));
12014           else
12015             {
12016               parameter->data_value = DW_BLOCK (attr)->data;
12017               parameter->data_value_size = DW_BLOCK (attr)->size;
12018             }
12019         }
12020     }
12021 }
12022
12023 /* Call CALLBACK from DW_AT_ranges attribute value OFFSET
12024    reading .debug_rnglists.
12025    Callback's type should be:
12026     void (CORE_ADDR range_beginning, CORE_ADDR range_end)
12027    Return true if the attributes are present and valid, otherwise,
12028    return false.  */
12029
12030 template <typename Callback>
12031 static bool
12032 dwarf2_rnglists_process (unsigned offset, struct dwarf2_cu *cu,
12033                          Callback &&callback)
12034 {
12035   struct objfile *objfile = cu->objfile;
12036   struct gdbarch *gdbarch = get_objfile_arch (objfile);
12037   struct comp_unit_head *cu_header = &cu->header;
12038   bfd *obfd = objfile->obfd;
12039   unsigned int addr_size = cu_header->addr_size;
12040   CORE_ADDR mask = ~(~(CORE_ADDR)1 << (addr_size * 8 - 1));
12041   /* Base address selection entry.  */
12042   CORE_ADDR base;
12043   int found_base;
12044   unsigned int dummy;
12045   const gdb_byte *buffer;
12046   CORE_ADDR low = 0;
12047   CORE_ADDR high = 0;
12048   CORE_ADDR baseaddr;
12049   bool overflow = false;
12050
12051   found_base = cu->base_known;
12052   base = cu->base_address;
12053
12054   dwarf2_read_section (objfile, &dwarf2_per_objfile->rnglists);
12055   if (offset >= dwarf2_per_objfile->rnglists.size)
12056     {
12057       complaint (&symfile_complaints,
12058                  _("Offset %d out of bounds for DW_AT_ranges attribute"),
12059                  offset);
12060       return false;
12061     }
12062   buffer = dwarf2_per_objfile->rnglists.buffer + offset;
12063
12064   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
12065
12066   while (1)
12067     {
12068       /* Initialize it due to a false compiler warning.  */
12069       CORE_ADDR range_beginning = 0, range_end = 0;
12070       const gdb_byte *buf_end = (dwarf2_per_objfile->rnglists.buffer
12071                                  + dwarf2_per_objfile->rnglists.size);
12072       unsigned int bytes_read;
12073
12074       if (buffer == buf_end)
12075         {
12076           overflow = true;
12077           break;
12078         }
12079       const auto rlet = static_cast<enum dwarf_range_list_entry>(*buffer++);
12080       switch (rlet)
12081         {
12082         case DW_RLE_end_of_list:
12083           break;
12084         case DW_RLE_base_address:
12085           if (buffer + cu->header.addr_size > buf_end)
12086             {
12087               overflow = true;
12088               break;
12089             }
12090           base = read_address (obfd, buffer, cu, &bytes_read);
12091           found_base = 1;
12092           buffer += bytes_read;
12093           break;
12094         case DW_RLE_start_length:
12095           if (buffer + cu->header.addr_size > buf_end)
12096             {
12097               overflow = true;
12098               break;
12099             }
12100           range_beginning = read_address (obfd, buffer, cu, &bytes_read);
12101           buffer += bytes_read;
12102           range_end = (range_beginning
12103                        + read_unsigned_leb128 (obfd, buffer, &bytes_read));
12104           buffer += bytes_read;
12105           if (buffer > buf_end)
12106             {
12107               overflow = true;
12108               break;
12109             }
12110           break;
12111         case DW_RLE_offset_pair:
12112           range_beginning = read_unsigned_leb128 (obfd, buffer, &bytes_read);
12113           buffer += bytes_read;
12114           if (buffer > buf_end)
12115             {
12116               overflow = true;
12117               break;
12118             }
12119           range_end = read_unsigned_leb128 (obfd, buffer, &bytes_read);
12120           buffer += bytes_read;
12121           if (buffer > buf_end)
12122             {
12123               overflow = true;
12124               break;
12125             }
12126           break;
12127         case DW_RLE_start_end:
12128           if (buffer + 2 * cu->header.addr_size > buf_end)
12129             {
12130               overflow = true;
12131               break;
12132             }
12133           range_beginning = read_address (obfd, buffer, cu, &bytes_read);
12134           buffer += bytes_read;
12135           range_end = read_address (obfd, buffer, cu, &bytes_read);
12136           buffer += bytes_read;
12137           break;
12138         default:
12139           complaint (&symfile_complaints,
12140                      _("Invalid .debug_rnglists data (no base address)"));
12141           return false;
12142         }
12143       if (rlet == DW_RLE_end_of_list || overflow)
12144         break;
12145       if (rlet == DW_RLE_base_address)
12146         continue;
12147
12148       if (!found_base)
12149         {
12150           /* We have no valid base address for the ranges
12151              data.  */
12152           complaint (&symfile_complaints,
12153                      _("Invalid .debug_rnglists data (no base address)"));
12154           return false;
12155         }
12156
12157       if (range_beginning > range_end)
12158         {
12159           /* Inverted range entries are invalid.  */
12160           complaint (&symfile_complaints,
12161                      _("Invalid .debug_rnglists data (inverted range)"));
12162           return false;
12163         }
12164
12165       /* Empty range entries have no effect.  */
12166       if (range_beginning == range_end)
12167         continue;
12168
12169       range_beginning += base;
12170       range_end += base;
12171
12172       /* A not-uncommon case of bad debug info.
12173          Don't pollute the addrmap with bad data.  */
12174       if (range_beginning + baseaddr == 0
12175           && !dwarf2_per_objfile->has_section_at_zero)
12176         {
12177           complaint (&symfile_complaints,
12178                      _(".debug_rnglists entry has start address of zero"
12179                        " [in module %s]"), objfile_name (objfile));
12180           continue;
12181         }
12182
12183       callback (range_beginning, range_end);
12184     }
12185
12186   if (overflow)
12187     {
12188       complaint (&symfile_complaints,
12189                  _("Offset %d is not terminated "
12190                    "for DW_AT_ranges attribute"),
12191                  offset);
12192       return false;
12193     }
12194
12195   return true;
12196 }
12197
12198 /* Call CALLBACK from DW_AT_ranges attribute value OFFSET reading .debug_ranges.
12199    Callback's type should be:
12200     void (CORE_ADDR range_beginning, CORE_ADDR range_end)
12201    Return 1 if the attributes are present and valid, otherwise, return 0.  */
12202
12203 template <typename Callback>
12204 static int
12205 dwarf2_ranges_process (unsigned offset, struct dwarf2_cu *cu,
12206                        Callback &&callback)
12207 {
12208   struct objfile *objfile = cu->objfile;
12209   struct gdbarch *gdbarch = get_objfile_arch (objfile);
12210   struct comp_unit_head *cu_header = &cu->header;
12211   bfd *obfd = objfile->obfd;
12212   unsigned int addr_size = cu_header->addr_size;
12213   CORE_ADDR mask = ~(~(CORE_ADDR)1 << (addr_size * 8 - 1));
12214   /* Base address selection entry.  */
12215   CORE_ADDR base;
12216   int found_base;
12217   unsigned int dummy;
12218   const gdb_byte *buffer;
12219   CORE_ADDR baseaddr;
12220
12221   if (cu_header->version >= 5)
12222     return dwarf2_rnglists_process (offset, cu, callback);
12223
12224   found_base = cu->base_known;
12225   base = cu->base_address;
12226
12227   dwarf2_read_section (objfile, &dwarf2_per_objfile->ranges);
12228   if (offset >= dwarf2_per_objfile->ranges.size)
12229     {
12230       complaint (&symfile_complaints,
12231                  _("Offset %d out of bounds for DW_AT_ranges attribute"),
12232                  offset);
12233       return 0;
12234     }
12235   buffer = dwarf2_per_objfile->ranges.buffer + offset;
12236
12237   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
12238
12239   while (1)
12240     {
12241       CORE_ADDR range_beginning, range_end;
12242
12243       range_beginning = read_address (obfd, buffer, cu, &dummy);
12244       buffer += addr_size;
12245       range_end = read_address (obfd, buffer, cu, &dummy);
12246       buffer += addr_size;
12247       offset += 2 * addr_size;
12248
12249       /* An end of list marker is a pair of zero addresses.  */
12250       if (range_beginning == 0 && range_end == 0)
12251         /* Found the end of list entry.  */
12252         break;
12253
12254       /* Each base address selection entry is a pair of 2 values.
12255          The first is the largest possible address, the second is
12256          the base address.  Check for a base address here.  */
12257       if ((range_beginning & mask) == mask)
12258         {
12259           /* If we found the largest possible address, then we already
12260              have the base address in range_end.  */
12261           base = range_end;
12262           found_base = 1;
12263           continue;
12264         }
12265
12266       if (!found_base)
12267         {
12268           /* We have no valid base address for the ranges
12269              data.  */
12270           complaint (&symfile_complaints,
12271                      _("Invalid .debug_ranges data (no base address)"));
12272           return 0;
12273         }
12274
12275       if (range_beginning > range_end)
12276         {
12277           /* Inverted range entries are invalid.  */
12278           complaint (&symfile_complaints,
12279                      _("Invalid .debug_ranges data (inverted range)"));
12280           return 0;
12281         }
12282
12283       /* Empty range entries have no effect.  */
12284       if (range_beginning == range_end)
12285         continue;
12286
12287       range_beginning += base;
12288       range_end += base;
12289
12290       /* A not-uncommon case of bad debug info.
12291          Don't pollute the addrmap with bad data.  */
12292       if (range_beginning + baseaddr == 0
12293           && !dwarf2_per_objfile->has_section_at_zero)
12294         {
12295           complaint (&symfile_complaints,
12296                      _(".debug_ranges entry has start address of zero"
12297                        " [in module %s]"), objfile_name (objfile));
12298           continue;
12299         }
12300
12301       callback (range_beginning, range_end);
12302     }
12303
12304   return 1;
12305 }
12306
12307 /* Get low and high pc attributes from DW_AT_ranges attribute value OFFSET.
12308    Return 1 if the attributes are present and valid, otherwise, return 0.
12309    If RANGES_PST is not NULL we should setup `objfile->psymtabs_addrmap'.  */
12310
12311 static int
12312 dwarf2_ranges_read (unsigned offset, CORE_ADDR *low_return,
12313                     CORE_ADDR *high_return, struct dwarf2_cu *cu,
12314                     struct partial_symtab *ranges_pst)
12315 {
12316   struct objfile *objfile = cu->objfile;
12317   struct gdbarch *gdbarch = get_objfile_arch (objfile);
12318   const CORE_ADDR baseaddr = ANOFFSET (objfile->section_offsets,
12319                                        SECT_OFF_TEXT (objfile));
12320   int low_set = 0;
12321   CORE_ADDR low = 0;
12322   CORE_ADDR high = 0;
12323   int retval;
12324
12325   retval = dwarf2_ranges_process (offset, cu,
12326     [&] (CORE_ADDR range_beginning, CORE_ADDR range_end)
12327     {
12328       if (ranges_pst != NULL)
12329         {
12330           CORE_ADDR lowpc;
12331           CORE_ADDR highpc;
12332
12333           lowpc = gdbarch_adjust_dwarf2_addr (gdbarch,
12334                                               range_beginning + baseaddr);
12335           highpc = gdbarch_adjust_dwarf2_addr (gdbarch,
12336                                                range_end + baseaddr);
12337           addrmap_set_empty (objfile->psymtabs_addrmap, lowpc, highpc - 1,
12338                              ranges_pst);
12339         }
12340
12341       /* FIXME: This is recording everything as a low-high
12342          segment of consecutive addresses.  We should have a
12343          data structure for discontiguous block ranges
12344          instead.  */
12345       if (! low_set)
12346         {
12347           low = range_beginning;
12348           high = range_end;
12349           low_set = 1;
12350         }
12351       else
12352         {
12353           if (range_beginning < low)
12354             low = range_beginning;
12355           if (range_end > high)
12356             high = range_end;
12357         }
12358     });
12359   if (!retval)
12360     return 0;
12361
12362   if (! low_set)
12363     /* If the first entry is an end-of-list marker, the range
12364        describes an empty scope, i.e. no instructions.  */
12365     return 0;
12366
12367   if (low_return)
12368     *low_return = low;
12369   if (high_return)
12370     *high_return = high;
12371   return 1;
12372 }
12373
12374 /* Get low and high pc attributes from a die.  See enum pc_bounds_kind
12375    definition for the return value.  *LOWPC and *HIGHPC are set iff
12376    neither PC_BOUNDS_NOT_PRESENT nor PC_BOUNDS_INVALID are returned.  */
12377
12378 static enum pc_bounds_kind
12379 dwarf2_get_pc_bounds (struct die_info *die, CORE_ADDR *lowpc,
12380                       CORE_ADDR *highpc, struct dwarf2_cu *cu,
12381                       struct partial_symtab *pst)
12382 {
12383   struct attribute *attr;
12384   struct attribute *attr_high;
12385   CORE_ADDR low = 0;
12386   CORE_ADDR high = 0;
12387   enum pc_bounds_kind ret;
12388
12389   attr_high = dwarf2_attr (die, DW_AT_high_pc, cu);
12390   if (attr_high)
12391     {
12392       attr = dwarf2_attr (die, DW_AT_low_pc, cu);
12393       if (attr)
12394         {
12395           low = attr_value_as_address (attr);
12396           high = attr_value_as_address (attr_high);
12397           if (cu->header.version >= 4 && attr_form_is_constant (attr_high))
12398             high += low;
12399         }
12400       else
12401         /* Found high w/o low attribute.  */
12402         return PC_BOUNDS_INVALID;
12403
12404       /* Found consecutive range of addresses.  */
12405       ret = PC_BOUNDS_HIGH_LOW;
12406     }
12407   else
12408     {
12409       attr = dwarf2_attr (die, DW_AT_ranges, cu);
12410       if (attr != NULL)
12411         {
12412           /* DW_AT_ranges_base does not apply to DIEs from the DWO skeleton.
12413              We take advantage of the fact that DW_AT_ranges does not appear
12414              in DW_TAG_compile_unit of DWO files.  */
12415           int need_ranges_base = die->tag != DW_TAG_compile_unit;
12416           unsigned int ranges_offset = (DW_UNSND (attr)
12417                                         + (need_ranges_base
12418                                            ? cu->ranges_base
12419                                            : 0));
12420
12421           /* Value of the DW_AT_ranges attribute is the offset in the
12422              .debug_ranges section.  */
12423           if (!dwarf2_ranges_read (ranges_offset, &low, &high, cu, pst))
12424             return PC_BOUNDS_INVALID;
12425           /* Found discontinuous range of addresses.  */
12426           ret = PC_BOUNDS_RANGES;
12427         }
12428       else
12429         return PC_BOUNDS_NOT_PRESENT;
12430     }
12431
12432   /* read_partial_die has also the strict LOW < HIGH requirement.  */
12433   if (high <= low)
12434     return PC_BOUNDS_INVALID;
12435
12436   /* When using the GNU linker, .gnu.linkonce. sections are used to
12437      eliminate duplicate copies of functions and vtables and such.
12438      The linker will arbitrarily choose one and discard the others.
12439      The AT_*_pc values for such functions refer to local labels in
12440      these sections.  If the section from that file was discarded, the
12441      labels are not in the output, so the relocs get a value of 0.
12442      If this is a discarded function, mark the pc bounds as invalid,
12443      so that GDB will ignore it.  */
12444   if (low == 0 && !dwarf2_per_objfile->has_section_at_zero)
12445     return PC_BOUNDS_INVALID;
12446
12447   *lowpc = low;
12448   if (highpc)
12449     *highpc = high;
12450   return ret;
12451 }
12452
12453 /* Assuming that DIE represents a subprogram DIE or a lexical block, get
12454    its low and high PC addresses.  Do nothing if these addresses could not
12455    be determined.  Otherwise, set LOWPC to the low address if it is smaller,
12456    and HIGHPC to the high address if greater than HIGHPC.  */
12457
12458 static void
12459 dwarf2_get_subprogram_pc_bounds (struct die_info *die,
12460                                  CORE_ADDR *lowpc, CORE_ADDR *highpc,
12461                                  struct dwarf2_cu *cu)
12462 {
12463   CORE_ADDR low, high;
12464   struct die_info *child = die->child;
12465
12466   if (dwarf2_get_pc_bounds (die, &low, &high, cu, NULL) >= PC_BOUNDS_RANGES)
12467     {
12468       *lowpc = std::min (*lowpc, low);
12469       *highpc = std::max (*highpc, high);
12470     }
12471
12472   /* If the language does not allow nested subprograms (either inside
12473      subprograms or lexical blocks), we're done.  */
12474   if (cu->language != language_ada)
12475     return;
12476
12477   /* Check all the children of the given DIE.  If it contains nested
12478      subprograms, then check their pc bounds.  Likewise, we need to
12479      check lexical blocks as well, as they may also contain subprogram
12480      definitions.  */
12481   while (child && child->tag)
12482     {
12483       if (child->tag == DW_TAG_subprogram
12484           || child->tag == DW_TAG_lexical_block)
12485         dwarf2_get_subprogram_pc_bounds (child, lowpc, highpc, cu);
12486       child = sibling_die (child);
12487     }
12488 }
12489
12490 /* Get the low and high pc's represented by the scope DIE, and store
12491    them in *LOWPC and *HIGHPC.  If the correct values can't be
12492    determined, set *LOWPC to -1 and *HIGHPC to 0.  */
12493
12494 static void
12495 get_scope_pc_bounds (struct die_info *die,
12496                      CORE_ADDR *lowpc, CORE_ADDR *highpc,
12497                      struct dwarf2_cu *cu)
12498 {
12499   CORE_ADDR best_low = (CORE_ADDR) -1;
12500   CORE_ADDR best_high = (CORE_ADDR) 0;
12501   CORE_ADDR current_low, current_high;
12502
12503   if (dwarf2_get_pc_bounds (die, &current_low, &current_high, cu, NULL)
12504       >= PC_BOUNDS_RANGES)
12505     {
12506       best_low = current_low;
12507       best_high = current_high;
12508     }
12509   else
12510     {
12511       struct die_info *child = die->child;
12512
12513       while (child && child->tag)
12514         {
12515           switch (child->tag) {
12516           case DW_TAG_subprogram:
12517             dwarf2_get_subprogram_pc_bounds (child, &best_low, &best_high, cu);
12518             break;
12519           case DW_TAG_namespace:
12520           case DW_TAG_module:
12521             /* FIXME: carlton/2004-01-16: Should we do this for
12522                DW_TAG_class_type/DW_TAG_structure_type, too?  I think
12523                that current GCC's always emit the DIEs corresponding
12524                to definitions of methods of classes as children of a
12525                DW_TAG_compile_unit or DW_TAG_namespace (as opposed to
12526                the DIEs giving the declarations, which could be
12527                anywhere).  But I don't see any reason why the
12528                standards says that they have to be there.  */
12529             get_scope_pc_bounds (child, &current_low, &current_high, cu);
12530
12531             if (current_low != ((CORE_ADDR) -1))
12532               {
12533                 best_low = std::min (best_low, current_low);
12534                 best_high = std::max (best_high, current_high);
12535               }
12536             break;
12537           default:
12538             /* Ignore.  */
12539             break;
12540           }
12541
12542           child = sibling_die (child);
12543         }
12544     }
12545
12546   *lowpc = best_low;
12547   *highpc = best_high;
12548 }
12549
12550 /* Record the address ranges for BLOCK, offset by BASEADDR, as given
12551    in DIE.  */
12552
12553 static void
12554 dwarf2_record_block_ranges (struct die_info *die, struct block *block,
12555                             CORE_ADDR baseaddr, struct dwarf2_cu *cu)
12556 {
12557   struct objfile *objfile = cu->objfile;
12558   struct gdbarch *gdbarch = get_objfile_arch (objfile);
12559   struct attribute *attr;
12560   struct attribute *attr_high;
12561
12562   attr_high = dwarf2_attr (die, DW_AT_high_pc, cu);
12563   if (attr_high)
12564     {
12565       attr = dwarf2_attr (die, DW_AT_low_pc, cu);
12566       if (attr)
12567         {
12568           CORE_ADDR low = attr_value_as_address (attr);
12569           CORE_ADDR high = attr_value_as_address (attr_high);
12570
12571           if (cu->header.version >= 4 && attr_form_is_constant (attr_high))
12572             high += low;
12573
12574           low = gdbarch_adjust_dwarf2_addr (gdbarch, low + baseaddr);
12575           high = gdbarch_adjust_dwarf2_addr (gdbarch, high + baseaddr);
12576           record_block_range (block, low, high - 1);
12577         }
12578     }
12579
12580   attr = dwarf2_attr (die, DW_AT_ranges, cu);
12581   if (attr)
12582     {
12583       bfd *obfd = objfile->obfd;
12584       /* DW_AT_ranges_base does not apply to DIEs from the DWO skeleton.
12585          We take advantage of the fact that DW_AT_ranges does not appear
12586          in DW_TAG_compile_unit of DWO files.  */
12587       int need_ranges_base = die->tag != DW_TAG_compile_unit;
12588
12589       /* The value of the DW_AT_ranges attribute is the offset of the
12590          address range list in the .debug_ranges section.  */
12591       unsigned long offset = (DW_UNSND (attr)
12592                               + (need_ranges_base ? cu->ranges_base : 0));
12593       const gdb_byte *buffer;
12594
12595       /* For some target architectures, but not others, the
12596          read_address function sign-extends the addresses it returns.
12597          To recognize base address selection entries, we need a
12598          mask.  */
12599       unsigned int addr_size = cu->header.addr_size;
12600       CORE_ADDR base_select_mask = ~(~(CORE_ADDR)1 << (addr_size * 8 - 1));
12601
12602       /* The base address, to which the next pair is relative.  Note
12603          that this 'base' is a DWARF concept: most entries in a range
12604          list are relative, to reduce the number of relocs against the
12605          debugging information.  This is separate from this function's
12606          'baseaddr' argument, which GDB uses to relocate debugging
12607          information from a shared library based on the address at
12608          which the library was loaded.  */
12609       CORE_ADDR base = cu->base_address;
12610       int base_known = cu->base_known;
12611
12612       dwarf2_ranges_process (offset, cu,
12613         [&] (CORE_ADDR start, CORE_ADDR end)
12614         {
12615           start += baseaddr;
12616           end += baseaddr;
12617           start = gdbarch_adjust_dwarf2_addr (gdbarch, start);
12618           end = gdbarch_adjust_dwarf2_addr (gdbarch, end);
12619           record_block_range (block, start, end - 1);
12620         });
12621     }
12622 }
12623
12624 /* Check whether the producer field indicates either of GCC < 4.6, or the
12625    Intel C/C++ compiler, and cache the result in CU.  */
12626
12627 static void
12628 check_producer (struct dwarf2_cu *cu)
12629 {
12630   int major, minor;
12631
12632   if (cu->producer == NULL)
12633     {
12634       /* For unknown compilers expect their behavior is DWARF version
12635          compliant.
12636
12637          GCC started to support .debug_types sections by -gdwarf-4 since
12638          gcc-4.5.x.  As the .debug_types sections are missing DW_AT_producer
12639          for their space efficiency GDB cannot workaround gcc-4.5.x -gdwarf-4
12640          combination.  gcc-4.5.x -gdwarf-4 binaries have DW_AT_accessibility
12641          interpreted incorrectly by GDB now - GCC PR debug/48229.  */
12642     }
12643   else if (producer_is_gcc (cu->producer, &major, &minor))
12644     {
12645       cu->producer_is_gxx_lt_4_6 = major < 4 || (major == 4 && minor < 6);
12646       cu->producer_is_gcc_lt_4_3 = major < 4 || (major == 4 && minor < 3);
12647     }
12648   else if (startswith (cu->producer, "Intel(R) C"))
12649     cu->producer_is_icc = 1;
12650   else
12651     {
12652       /* For other non-GCC compilers, expect their behavior is DWARF version
12653          compliant.  */
12654     }
12655
12656   cu->checked_producer = 1;
12657 }
12658
12659 /* Check for GCC PR debug/45124 fix which is not present in any G++ version up
12660    to 4.5.any while it is present already in G++ 4.6.0 - the PR has been fixed
12661    during 4.6.0 experimental.  */
12662
12663 static int
12664 producer_is_gxx_lt_4_6 (struct dwarf2_cu *cu)
12665 {
12666   if (!cu->checked_producer)
12667     check_producer (cu);
12668
12669   return cu->producer_is_gxx_lt_4_6;
12670 }
12671
12672 /* Return the default accessibility type if it is not overriden by
12673    DW_AT_accessibility.  */
12674
12675 static enum dwarf_access_attribute
12676 dwarf2_default_access_attribute (struct die_info *die, struct dwarf2_cu *cu)
12677 {
12678   if (cu->header.version < 3 || producer_is_gxx_lt_4_6 (cu))
12679     {
12680       /* The default DWARF 2 accessibility for members is public, the default
12681          accessibility for inheritance is private.  */
12682
12683       if (die->tag != DW_TAG_inheritance)
12684         return DW_ACCESS_public;
12685       else
12686         return DW_ACCESS_private;
12687     }
12688   else
12689     {
12690       /* DWARF 3+ defines the default accessibility a different way.  The same
12691          rules apply now for DW_TAG_inheritance as for the members and it only
12692          depends on the container kind.  */
12693
12694       if (die->parent->tag == DW_TAG_class_type)
12695         return DW_ACCESS_private;
12696       else
12697         return DW_ACCESS_public;
12698     }
12699 }
12700
12701 /* Look for DW_AT_data_member_location.  Set *OFFSET to the byte
12702    offset.  If the attribute was not found return 0, otherwise return
12703    1.  If it was found but could not properly be handled, set *OFFSET
12704    to 0.  */
12705
12706 static int
12707 handle_data_member_location (struct die_info *die, struct dwarf2_cu *cu,
12708                              LONGEST *offset)
12709 {
12710   struct attribute *attr;
12711
12712   attr = dwarf2_attr (die, DW_AT_data_member_location, cu);
12713   if (attr != NULL)
12714     {
12715       *offset = 0;
12716
12717       /* Note that we do not check for a section offset first here.
12718          This is because DW_AT_data_member_location is new in DWARF 4,
12719          so if we see it, we can assume that a constant form is really
12720          a constant and not a section offset.  */
12721       if (attr_form_is_constant (attr))
12722         *offset = dwarf2_get_attr_constant_value (attr, 0);
12723       else if (attr_form_is_section_offset (attr))
12724         dwarf2_complex_location_expr_complaint ();
12725       else if (attr_form_is_block (attr))
12726         *offset = decode_locdesc (DW_BLOCK (attr), cu);
12727       else
12728         dwarf2_complex_location_expr_complaint ();
12729
12730       return 1;
12731     }
12732
12733   return 0;
12734 }
12735
12736 /* Add an aggregate field to the field list.  */
12737
12738 static void
12739 dwarf2_add_field (struct field_info *fip, struct die_info *die,
12740                   struct dwarf2_cu *cu)
12741 {
12742   struct objfile *objfile = cu->objfile;
12743   struct gdbarch *gdbarch = get_objfile_arch (objfile);
12744   struct nextfield *new_field;
12745   struct attribute *attr;
12746   struct field *fp;
12747   const char *fieldname = "";
12748
12749   /* Allocate a new field list entry and link it in.  */
12750   new_field = XNEW (struct nextfield);
12751   make_cleanup (xfree, new_field);
12752   memset (new_field, 0, sizeof (struct nextfield));
12753
12754   if (die->tag == DW_TAG_inheritance)
12755     {
12756       new_field->next = fip->baseclasses;
12757       fip->baseclasses = new_field;
12758     }
12759   else
12760     {
12761       new_field->next = fip->fields;
12762       fip->fields = new_field;
12763     }
12764   fip->nfields++;
12765
12766   attr = dwarf2_attr (die, DW_AT_accessibility, cu);
12767   if (attr)
12768     new_field->accessibility = DW_UNSND (attr);
12769   else
12770     new_field->accessibility = dwarf2_default_access_attribute (die, cu);
12771   if (new_field->accessibility != DW_ACCESS_public)
12772     fip->non_public_fields = 1;
12773
12774   attr = dwarf2_attr (die, DW_AT_virtuality, cu);
12775   if (attr)
12776     new_field->virtuality = DW_UNSND (attr);
12777   else
12778     new_field->virtuality = DW_VIRTUALITY_none;
12779
12780   fp = &new_field->field;
12781
12782   if (die->tag == DW_TAG_member && ! die_is_declaration (die, cu))
12783     {
12784       LONGEST offset;
12785
12786       /* Data member other than a C++ static data member.  */
12787
12788       /* Get type of field.  */
12789       fp->type = die_type (die, cu);
12790
12791       SET_FIELD_BITPOS (*fp, 0);
12792
12793       /* Get bit size of field (zero if none).  */
12794       attr = dwarf2_attr (die, DW_AT_bit_size, cu);
12795       if (attr)
12796         {
12797           FIELD_BITSIZE (*fp) = DW_UNSND (attr);
12798         }
12799       else
12800         {
12801           FIELD_BITSIZE (*fp) = 0;
12802         }
12803
12804       /* Get bit offset of field.  */
12805       if (handle_data_member_location (die, cu, &offset))
12806         SET_FIELD_BITPOS (*fp, offset * bits_per_byte);
12807       attr = dwarf2_attr (die, DW_AT_bit_offset, cu);
12808       if (attr)
12809         {
12810           if (gdbarch_bits_big_endian (gdbarch))
12811             {
12812               /* For big endian bits, the DW_AT_bit_offset gives the
12813                  additional bit offset from the MSB of the containing
12814                  anonymous object to the MSB of the field.  We don't
12815                  have to do anything special since we don't need to
12816                  know the size of the anonymous object.  */
12817               SET_FIELD_BITPOS (*fp, FIELD_BITPOS (*fp) + DW_UNSND (attr));
12818             }
12819           else
12820             {
12821               /* For little endian bits, compute the bit offset to the
12822                  MSB of the anonymous object, subtract off the number of
12823                  bits from the MSB of the field to the MSB of the
12824                  object, and then subtract off the number of bits of
12825                  the field itself.  The result is the bit offset of
12826                  the LSB of the field.  */
12827               int anonymous_size;
12828               int bit_offset = DW_UNSND (attr);
12829
12830               attr = dwarf2_attr (die, DW_AT_byte_size, cu);
12831               if (attr)
12832                 {
12833                   /* The size of the anonymous object containing
12834                      the bit field is explicit, so use the
12835                      indicated size (in bytes).  */
12836                   anonymous_size = DW_UNSND (attr);
12837                 }
12838               else
12839                 {
12840                   /* The size of the anonymous object containing
12841                      the bit field must be inferred from the type
12842                      attribute of the data member containing the
12843                      bit field.  */
12844                   anonymous_size = TYPE_LENGTH (fp->type);
12845                 }
12846               SET_FIELD_BITPOS (*fp,
12847                                 (FIELD_BITPOS (*fp)
12848                                  + anonymous_size * bits_per_byte
12849                                  - bit_offset - FIELD_BITSIZE (*fp)));
12850             }
12851         }
12852       attr = dwarf2_attr (die, DW_AT_data_bit_offset, cu);
12853       if (attr != NULL)
12854         SET_FIELD_BITPOS (*fp, (FIELD_BITPOS (*fp)
12855                                 + dwarf2_get_attr_constant_value (attr, 0)));
12856
12857       /* Get name of field.  */
12858       fieldname = dwarf2_name (die, cu);
12859       if (fieldname == NULL)
12860         fieldname = "";
12861
12862       /* The name is already allocated along with this objfile, so we don't
12863          need to duplicate it for the type.  */
12864       fp->name = fieldname;
12865
12866       /* Change accessibility for artificial fields (e.g. virtual table
12867          pointer or virtual base class pointer) to private.  */
12868       if (dwarf2_attr (die, DW_AT_artificial, cu))
12869         {
12870           FIELD_ARTIFICIAL (*fp) = 1;
12871           new_field->accessibility = DW_ACCESS_private;
12872           fip->non_public_fields = 1;
12873         }
12874     }
12875   else if (die->tag == DW_TAG_member || die->tag == DW_TAG_variable)
12876     {
12877       /* C++ static member.  */
12878
12879       /* NOTE: carlton/2002-11-05: It should be a DW_TAG_member that
12880          is a declaration, but all versions of G++ as of this writing
12881          (so through at least 3.2.1) incorrectly generate
12882          DW_TAG_variable tags.  */
12883
12884       const char *physname;
12885
12886       /* Get name of field.  */
12887       fieldname = dwarf2_name (die, cu);
12888       if (fieldname == NULL)
12889         return;
12890
12891       attr = dwarf2_attr (die, DW_AT_const_value, cu);
12892       if (attr
12893           /* Only create a symbol if this is an external value.
12894              new_symbol checks this and puts the value in the global symbol
12895              table, which we want.  If it is not external, new_symbol
12896              will try to put the value in cu->list_in_scope which is wrong.  */
12897           && dwarf2_flag_true_p (die, DW_AT_external, cu))
12898         {
12899           /* A static const member, not much different than an enum as far as
12900              we're concerned, except that we can support more types.  */
12901           new_symbol (die, NULL, cu);
12902         }
12903
12904       /* Get physical name.  */
12905       physname = dwarf2_physname (fieldname, die, cu);
12906
12907       /* The name is already allocated along with this objfile, so we don't
12908          need to duplicate it for the type.  */
12909       SET_FIELD_PHYSNAME (*fp, physname ? physname : "");
12910       FIELD_TYPE (*fp) = die_type (die, cu);
12911       FIELD_NAME (*fp) = fieldname;
12912     }
12913   else if (die->tag == DW_TAG_inheritance)
12914     {
12915       LONGEST offset;
12916
12917       /* C++ base class field.  */
12918       if (handle_data_member_location (die, cu, &offset))
12919         SET_FIELD_BITPOS (*fp, offset * bits_per_byte);
12920       FIELD_BITSIZE (*fp) = 0;
12921       FIELD_TYPE (*fp) = die_type (die, cu);
12922       FIELD_NAME (*fp) = type_name_no_tag (fp->type);
12923       fip->nbaseclasses++;
12924     }
12925 }
12926
12927 /* Add a typedef defined in the scope of the FIP's class.  */
12928
12929 static void
12930 dwarf2_add_typedef (struct field_info *fip, struct die_info *die,
12931                     struct dwarf2_cu *cu)
12932 {
12933   struct typedef_field_list *new_field;
12934   struct typedef_field *fp;
12935
12936   /* Allocate a new field list entry and link it in.  */
12937   new_field = XCNEW (struct typedef_field_list);
12938   make_cleanup (xfree, new_field);
12939
12940   gdb_assert (die->tag == DW_TAG_typedef);
12941
12942   fp = &new_field->field;
12943
12944   /* Get name of field.  */
12945   fp->name = dwarf2_name (die, cu);
12946   if (fp->name == NULL)
12947     return;
12948
12949   fp->type = read_type_die (die, cu);
12950
12951   new_field->next = fip->typedef_field_list;
12952   fip->typedef_field_list = new_field;
12953   fip->typedef_field_list_count++;
12954 }
12955
12956 /* Create the vector of fields, and attach it to the type.  */
12957
12958 static void
12959 dwarf2_attach_fields_to_type (struct field_info *fip, struct type *type,
12960                               struct dwarf2_cu *cu)
12961 {
12962   int nfields = fip->nfields;
12963
12964   /* Record the field count, allocate space for the array of fields,
12965      and create blank accessibility bitfields if necessary.  */
12966   TYPE_NFIELDS (type) = nfields;
12967   TYPE_FIELDS (type) = (struct field *)
12968     TYPE_ALLOC (type, sizeof (struct field) * nfields);
12969   memset (TYPE_FIELDS (type), 0, sizeof (struct field) * nfields);
12970
12971   if (fip->non_public_fields && cu->language != language_ada)
12972     {
12973       ALLOCATE_CPLUS_STRUCT_TYPE (type);
12974
12975       TYPE_FIELD_PRIVATE_BITS (type) =
12976         (B_TYPE *) TYPE_ALLOC (type, B_BYTES (nfields));
12977       B_CLRALL (TYPE_FIELD_PRIVATE_BITS (type), nfields);
12978
12979       TYPE_FIELD_PROTECTED_BITS (type) =
12980         (B_TYPE *) TYPE_ALLOC (type, B_BYTES (nfields));
12981       B_CLRALL (TYPE_FIELD_PROTECTED_BITS (type), nfields);
12982
12983       TYPE_FIELD_IGNORE_BITS (type) =
12984         (B_TYPE *) TYPE_ALLOC (type, B_BYTES (nfields));
12985       B_CLRALL (TYPE_FIELD_IGNORE_BITS (type), nfields);
12986     }
12987
12988   /* If the type has baseclasses, allocate and clear a bit vector for
12989      TYPE_FIELD_VIRTUAL_BITS.  */
12990   if (fip->nbaseclasses && cu->language != language_ada)
12991     {
12992       int num_bytes = B_BYTES (fip->nbaseclasses);
12993       unsigned char *pointer;
12994
12995       ALLOCATE_CPLUS_STRUCT_TYPE (type);
12996       pointer = (unsigned char *) TYPE_ALLOC (type, num_bytes);
12997       TYPE_FIELD_VIRTUAL_BITS (type) = pointer;
12998       B_CLRALL (TYPE_FIELD_VIRTUAL_BITS (type), fip->nbaseclasses);
12999       TYPE_N_BASECLASSES (type) = fip->nbaseclasses;
13000     }
13001
13002   /* Copy the saved-up fields into the field vector.  Start from the head of
13003      the list, adding to the tail of the field array, so that they end up in
13004      the same order in the array in which they were added to the list.  */
13005   while (nfields-- > 0)
13006     {
13007       struct nextfield *fieldp;
13008
13009       if (fip->fields)
13010         {
13011           fieldp = fip->fields;
13012           fip->fields = fieldp->next;
13013         }
13014       else
13015         {
13016           fieldp = fip->baseclasses;
13017           fip->baseclasses = fieldp->next;
13018         }
13019
13020       TYPE_FIELD (type, nfields) = fieldp->field;
13021       switch (fieldp->accessibility)
13022         {
13023         case DW_ACCESS_private:
13024           if (cu->language != language_ada)
13025             SET_TYPE_FIELD_PRIVATE (type, nfields);
13026           break;
13027
13028         case DW_ACCESS_protected:
13029           if (cu->language != language_ada)
13030             SET_TYPE_FIELD_PROTECTED (type, nfields);
13031           break;
13032
13033         case DW_ACCESS_public:
13034           break;
13035
13036         default:
13037           /* Unknown accessibility.  Complain and treat it as public.  */
13038           {
13039             complaint (&symfile_complaints, _("unsupported accessibility %d"),
13040                        fieldp->accessibility);
13041           }
13042           break;
13043         }
13044       if (nfields < fip->nbaseclasses)
13045         {
13046           switch (fieldp->virtuality)
13047             {
13048             case DW_VIRTUALITY_virtual:
13049             case DW_VIRTUALITY_pure_virtual:
13050               if (cu->language == language_ada)
13051                 error (_("unexpected virtuality in component of Ada type"));
13052               SET_TYPE_FIELD_VIRTUAL (type, nfields);
13053               break;
13054             }
13055         }
13056     }
13057 }
13058
13059 /* Return true if this member function is a constructor, false
13060    otherwise.  */
13061
13062 static int
13063 dwarf2_is_constructor (struct die_info *die, struct dwarf2_cu *cu)
13064 {
13065   const char *fieldname;
13066   const char *type_name;
13067   int len;
13068
13069   if (die->parent == NULL)
13070     return 0;
13071
13072   if (die->parent->tag != DW_TAG_structure_type
13073       && die->parent->tag != DW_TAG_union_type
13074       && die->parent->tag != DW_TAG_class_type)
13075     return 0;
13076
13077   fieldname = dwarf2_name (die, cu);
13078   type_name = dwarf2_name (die->parent, cu);
13079   if (fieldname == NULL || type_name == NULL)
13080     return 0;
13081
13082   len = strlen (fieldname);
13083   return (strncmp (fieldname, type_name, len) == 0
13084           && (type_name[len] == '\0' || type_name[len] == '<'));
13085 }
13086
13087 /* Add a member function to the proper fieldlist.  */
13088
13089 static void
13090 dwarf2_add_member_fn (struct field_info *fip, struct die_info *die,
13091                       struct type *type, struct dwarf2_cu *cu)
13092 {
13093   struct objfile *objfile = cu->objfile;
13094   struct attribute *attr;
13095   struct fnfieldlist *flp;
13096   int i;
13097   struct fn_field *fnp;
13098   const char *fieldname;
13099   struct nextfnfield *new_fnfield;
13100   struct type *this_type;
13101   enum dwarf_access_attribute accessibility;
13102
13103   if (cu->language == language_ada)
13104     error (_("unexpected member function in Ada type"));
13105
13106   /* Get name of member function.  */
13107   fieldname = dwarf2_name (die, cu);
13108   if (fieldname == NULL)
13109     return;
13110
13111   /* Look up member function name in fieldlist.  */
13112   for (i = 0; i < fip->nfnfields; i++)
13113     {
13114       if (strcmp (fip->fnfieldlists[i].name, fieldname) == 0)
13115         break;
13116     }
13117
13118   /* Create new list element if necessary.  */
13119   if (i < fip->nfnfields)
13120     flp = &fip->fnfieldlists[i];
13121   else
13122     {
13123       if ((fip->nfnfields % DW_FIELD_ALLOC_CHUNK) == 0)
13124         {
13125           fip->fnfieldlists = (struct fnfieldlist *)
13126             xrealloc (fip->fnfieldlists,
13127                       (fip->nfnfields + DW_FIELD_ALLOC_CHUNK)
13128                       * sizeof (struct fnfieldlist));
13129           if (fip->nfnfields == 0)
13130             make_cleanup (free_current_contents, &fip->fnfieldlists);
13131         }
13132       flp = &fip->fnfieldlists[fip->nfnfields];
13133       flp->name = fieldname;
13134       flp->length = 0;
13135       flp->head = NULL;
13136       i = fip->nfnfields++;
13137     }
13138
13139   /* Create a new member function field and chain it to the field list
13140      entry.  */
13141   new_fnfield = XNEW (struct nextfnfield);
13142   make_cleanup (xfree, new_fnfield);
13143   memset (new_fnfield, 0, sizeof (struct nextfnfield));
13144   new_fnfield->next = flp->head;
13145   flp->head = new_fnfield;
13146   flp->length++;
13147
13148   /* Fill in the member function field info.  */
13149   fnp = &new_fnfield->fnfield;
13150
13151   /* Delay processing of the physname until later.  */
13152   if (cu->language == language_cplus)
13153     {
13154       add_to_method_list (type, i, flp->length - 1, fieldname,
13155                           die, cu);
13156     }
13157   else
13158     {
13159       const char *physname = dwarf2_physname (fieldname, die, cu);
13160       fnp->physname = physname ? physname : "";
13161     }
13162
13163   fnp->type = alloc_type (objfile);
13164   this_type = read_type_die (die, cu);
13165   if (this_type && TYPE_CODE (this_type) == TYPE_CODE_FUNC)
13166     {
13167       int nparams = TYPE_NFIELDS (this_type);
13168
13169       /* TYPE is the domain of this method, and THIS_TYPE is the type
13170            of the method itself (TYPE_CODE_METHOD).  */
13171       smash_to_method_type (fnp->type, type,
13172                             TYPE_TARGET_TYPE (this_type),
13173                             TYPE_FIELDS (this_type),
13174                             TYPE_NFIELDS (this_type),
13175                             TYPE_VARARGS (this_type));
13176
13177       /* Handle static member functions.
13178          Dwarf2 has no clean way to discern C++ static and non-static
13179          member functions.  G++ helps GDB by marking the first
13180          parameter for non-static member functions (which is the this
13181          pointer) as artificial.  We obtain this information from
13182          read_subroutine_type via TYPE_FIELD_ARTIFICIAL.  */
13183       if (nparams == 0 || TYPE_FIELD_ARTIFICIAL (this_type, 0) == 0)
13184         fnp->voffset = VOFFSET_STATIC;
13185     }
13186   else
13187     complaint (&symfile_complaints, _("member function type missing for '%s'"),
13188                dwarf2_full_name (fieldname, die, cu));
13189
13190   /* Get fcontext from DW_AT_containing_type if present.  */
13191   if (dwarf2_attr (die, DW_AT_containing_type, cu) != NULL)
13192     fnp->fcontext = die_containing_type (die, cu);
13193
13194   /* dwarf2 doesn't have stubbed physical names, so the setting of is_const and
13195      is_volatile is irrelevant, as it is needed by gdb_mangle_name only.  */
13196
13197   /* Get accessibility.  */
13198   attr = dwarf2_attr (die, DW_AT_accessibility, cu);
13199   if (attr)
13200     accessibility = (enum dwarf_access_attribute) DW_UNSND (attr);
13201   else
13202     accessibility = dwarf2_default_access_attribute (die, cu);
13203   switch (accessibility)
13204     {
13205     case DW_ACCESS_private:
13206       fnp->is_private = 1;
13207       break;
13208     case DW_ACCESS_protected:
13209       fnp->is_protected = 1;
13210       break;
13211     }
13212
13213   /* Check for artificial methods.  */
13214   attr = dwarf2_attr (die, DW_AT_artificial, cu);
13215   if (attr && DW_UNSND (attr) != 0)
13216     fnp->is_artificial = 1;
13217
13218   fnp->is_constructor = dwarf2_is_constructor (die, cu);
13219
13220   /* Get index in virtual function table if it is a virtual member
13221      function.  For older versions of GCC, this is an offset in the
13222      appropriate virtual table, as specified by DW_AT_containing_type.
13223      For everyone else, it is an expression to be evaluated relative
13224      to the object address.  */
13225
13226   attr = dwarf2_attr (die, DW_AT_vtable_elem_location, cu);
13227   if (attr)
13228     {
13229       if (attr_form_is_block (attr) && DW_BLOCK (attr)->size > 0)
13230         {
13231           if (DW_BLOCK (attr)->data[0] == DW_OP_constu)
13232             {
13233               /* Old-style GCC.  */
13234               fnp->voffset = decode_locdesc (DW_BLOCK (attr), cu) + 2;
13235             }
13236           else if (DW_BLOCK (attr)->data[0] == DW_OP_deref
13237                    || (DW_BLOCK (attr)->size > 1
13238                        && DW_BLOCK (attr)->data[0] == DW_OP_deref_size
13239                        && DW_BLOCK (attr)->data[1] == cu->header.addr_size))
13240             {
13241               fnp->voffset = decode_locdesc (DW_BLOCK (attr), cu);
13242               if ((fnp->voffset % cu->header.addr_size) != 0)
13243                 dwarf2_complex_location_expr_complaint ();
13244               else
13245                 fnp->voffset /= cu->header.addr_size;
13246               fnp->voffset += 2;
13247             }
13248           else
13249             dwarf2_complex_location_expr_complaint ();
13250
13251           if (!fnp->fcontext)
13252             {
13253               /* If there is no `this' field and no DW_AT_containing_type,
13254                  we cannot actually find a base class context for the
13255                  vtable!  */
13256               if (TYPE_NFIELDS (this_type) == 0
13257                   || !TYPE_FIELD_ARTIFICIAL (this_type, 0))
13258                 {
13259                   complaint (&symfile_complaints,
13260                              _("cannot determine context for virtual member "
13261                                "function \"%s\" (offset %d)"),
13262                              fieldname, die->offset.sect_off);
13263                 }
13264               else
13265                 {
13266                   fnp->fcontext
13267                     = TYPE_TARGET_TYPE (TYPE_FIELD_TYPE (this_type, 0));
13268                 }
13269             }
13270         }
13271       else if (attr_form_is_section_offset (attr))
13272         {
13273           dwarf2_complex_location_expr_complaint ();
13274         }
13275       else
13276         {
13277           dwarf2_invalid_attrib_class_complaint ("DW_AT_vtable_elem_location",
13278                                                  fieldname);
13279         }
13280     }
13281   else
13282     {
13283       attr = dwarf2_attr (die, DW_AT_virtuality, cu);
13284       if (attr && DW_UNSND (attr))
13285         {
13286           /* GCC does this, as of 2008-08-25; PR debug/37237.  */
13287           complaint (&symfile_complaints,
13288                      _("Member function \"%s\" (offset %d) is virtual "
13289                        "but the vtable offset is not specified"),
13290                      fieldname, die->offset.sect_off);
13291           ALLOCATE_CPLUS_STRUCT_TYPE (type);
13292           TYPE_CPLUS_DYNAMIC (type) = 1;
13293         }
13294     }
13295 }
13296
13297 /* Create the vector of member function fields, and attach it to the type.  */
13298
13299 static void
13300 dwarf2_attach_fn_fields_to_type (struct field_info *fip, struct type *type,
13301                                  struct dwarf2_cu *cu)
13302 {
13303   struct fnfieldlist *flp;
13304   int i;
13305
13306   if (cu->language == language_ada)
13307     error (_("unexpected member functions in Ada type"));
13308
13309   ALLOCATE_CPLUS_STRUCT_TYPE (type);
13310   TYPE_FN_FIELDLISTS (type) = (struct fn_fieldlist *)
13311     TYPE_ALLOC (type, sizeof (struct fn_fieldlist) * fip->nfnfields);
13312
13313   for (i = 0, flp = fip->fnfieldlists; i < fip->nfnfields; i++, flp++)
13314     {
13315       struct nextfnfield *nfp = flp->head;
13316       struct fn_fieldlist *fn_flp = &TYPE_FN_FIELDLIST (type, i);
13317       int k;
13318
13319       TYPE_FN_FIELDLIST_NAME (type, i) = flp->name;
13320       TYPE_FN_FIELDLIST_LENGTH (type, i) = flp->length;
13321       fn_flp->fn_fields = (struct fn_field *)
13322         TYPE_ALLOC (type, sizeof (struct fn_field) * flp->length);
13323       for (k = flp->length; (k--, nfp); nfp = nfp->next)
13324         fn_flp->fn_fields[k] = nfp->fnfield;
13325     }
13326
13327   TYPE_NFN_FIELDS (type) = fip->nfnfields;
13328 }
13329
13330 /* Returns non-zero if NAME is the name of a vtable member in CU's
13331    language, zero otherwise.  */
13332 static int
13333 is_vtable_name (const char *name, struct dwarf2_cu *cu)
13334 {
13335   static const char vptr[] = "_vptr";
13336   static const char vtable[] = "vtable";
13337
13338   /* Look for the C++ form of the vtable.  */
13339   if (startswith (name, vptr) && is_cplus_marker (name[sizeof (vptr) - 1]))
13340     return 1;
13341
13342   return 0;
13343 }
13344
13345 /* GCC outputs unnamed structures that are really pointers to member
13346    functions, with the ABI-specified layout.  If TYPE describes
13347    such a structure, smash it into a member function type.
13348
13349    GCC shouldn't do this; it should just output pointer to member DIEs.
13350    This is GCC PR debug/28767.  */
13351
13352 static void
13353 quirk_gcc_member_function_pointer (struct type *type, struct objfile *objfile)
13354 {
13355   struct type *pfn_type, *self_type, *new_type;
13356
13357   /* Check for a structure with no name and two children.  */
13358   if (TYPE_CODE (type) != TYPE_CODE_STRUCT || TYPE_NFIELDS (type) != 2)
13359     return;
13360
13361   /* Check for __pfn and __delta members.  */
13362   if (TYPE_FIELD_NAME (type, 0) == NULL
13363       || strcmp (TYPE_FIELD_NAME (type, 0), "__pfn") != 0
13364       || TYPE_FIELD_NAME (type, 1) == NULL
13365       || strcmp (TYPE_FIELD_NAME (type, 1), "__delta") != 0)
13366     return;
13367
13368   /* Find the type of the method.  */
13369   pfn_type = TYPE_FIELD_TYPE (type, 0);
13370   if (pfn_type == NULL
13371       || TYPE_CODE (pfn_type) != TYPE_CODE_PTR
13372       || TYPE_CODE (TYPE_TARGET_TYPE (pfn_type)) != TYPE_CODE_FUNC)
13373     return;
13374
13375   /* Look for the "this" argument.  */
13376   pfn_type = TYPE_TARGET_TYPE (pfn_type);
13377   if (TYPE_NFIELDS (pfn_type) == 0
13378       /* || TYPE_FIELD_TYPE (pfn_type, 0) == NULL */
13379       || TYPE_CODE (TYPE_FIELD_TYPE (pfn_type, 0)) != TYPE_CODE_PTR)
13380     return;
13381
13382   self_type = TYPE_TARGET_TYPE (TYPE_FIELD_TYPE (pfn_type, 0));
13383   new_type = alloc_type (objfile);
13384   smash_to_method_type (new_type, self_type, TYPE_TARGET_TYPE (pfn_type),
13385                         TYPE_FIELDS (pfn_type), TYPE_NFIELDS (pfn_type),
13386                         TYPE_VARARGS (pfn_type));
13387   smash_to_methodptr_type (type, new_type);
13388 }
13389
13390 /* Return non-zero if the CU's PRODUCER string matches the Intel C/C++ compiler
13391    (icc).  */
13392
13393 static int
13394 producer_is_icc (struct dwarf2_cu *cu)
13395 {
13396   if (!cu->checked_producer)
13397     check_producer (cu);
13398
13399   return cu->producer_is_icc;
13400 }
13401
13402 /* Called when we find the DIE that starts a structure or union scope
13403    (definition) to create a type for the structure or union.  Fill in
13404    the type's name and general properties; the members will not be
13405    processed until process_structure_scope.  A symbol table entry for
13406    the type will also not be done until process_structure_scope (assuming
13407    the type has a name).
13408
13409    NOTE: we need to call these functions regardless of whether or not the
13410    DIE has a DW_AT_name attribute, since it might be an anonymous
13411    structure or union.  This gets the type entered into our set of
13412    user defined types.  */
13413
13414 static struct type *
13415 read_structure_type (struct die_info *die, struct dwarf2_cu *cu)
13416 {
13417   struct objfile *objfile = cu->objfile;
13418   struct type *type;
13419   struct attribute *attr;
13420   const char *name;
13421
13422   /* If the definition of this type lives in .debug_types, read that type.
13423      Don't follow DW_AT_specification though, that will take us back up
13424      the chain and we want to go down.  */
13425   attr = dwarf2_attr_no_follow (die, DW_AT_signature);
13426   if (attr)
13427     {
13428       type = get_DW_AT_signature_type (die, attr, cu);
13429
13430       /* The type's CU may not be the same as CU.
13431          Ensure TYPE is recorded with CU in die_type_hash.  */
13432       return set_die_type (die, type, cu);
13433     }
13434
13435   type = alloc_type (objfile);
13436   INIT_CPLUS_SPECIFIC (type);
13437
13438   name = dwarf2_name (die, cu);
13439   if (name != NULL)
13440     {
13441       if (cu->language == language_cplus
13442           || cu->language == language_d
13443           || cu->language == language_rust)
13444         {
13445           const char *full_name = dwarf2_full_name (name, die, cu);
13446
13447           /* dwarf2_full_name might have already finished building the DIE's
13448              type.  If so, there is no need to continue.  */
13449           if (get_die_type (die, cu) != NULL)
13450             return get_die_type (die, cu);
13451
13452           TYPE_TAG_NAME (type) = full_name;
13453           if (die->tag == DW_TAG_structure_type
13454               || die->tag == DW_TAG_class_type)
13455             TYPE_NAME (type) = TYPE_TAG_NAME (type);
13456         }
13457       else
13458         {
13459           /* The name is already allocated along with this objfile, so
13460              we don't need to duplicate it for the type.  */
13461           TYPE_TAG_NAME (type) = name;
13462           if (die->tag == DW_TAG_class_type)
13463             TYPE_NAME (type) = TYPE_TAG_NAME (type);
13464         }
13465     }
13466
13467   if (die->tag == DW_TAG_structure_type)
13468     {
13469       TYPE_CODE (type) = TYPE_CODE_STRUCT;
13470     }
13471   else if (die->tag == DW_TAG_union_type)
13472     {
13473       TYPE_CODE (type) = TYPE_CODE_UNION;
13474     }
13475   else
13476     {
13477       TYPE_CODE (type) = TYPE_CODE_STRUCT;
13478     }
13479
13480   if (cu->language == language_cplus && die->tag == DW_TAG_class_type)
13481     TYPE_DECLARED_CLASS (type) = 1;
13482
13483   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
13484   if (attr)
13485     {
13486       if (attr_form_is_constant (attr))
13487         TYPE_LENGTH (type) = DW_UNSND (attr);
13488       else
13489         {
13490           /* For the moment, dynamic type sizes are not supported
13491              by GDB's struct type.  The actual size is determined
13492              on-demand when resolving the type of a given object,
13493              so set the type's length to zero for now.  Otherwise,
13494              we record an expression as the length, and that expression
13495              could lead to a very large value, which could eventually
13496              lead to us trying to allocate that much memory when creating
13497              a value of that type.  */
13498           TYPE_LENGTH (type) = 0;
13499         }
13500     }
13501   else
13502     {
13503       TYPE_LENGTH (type) = 0;
13504     }
13505
13506   if (producer_is_icc (cu) && (TYPE_LENGTH (type) == 0))
13507     {
13508       /* ICC does not output the required DW_AT_declaration
13509          on incomplete types, but gives them a size of zero.  */
13510       TYPE_STUB (type) = 1;
13511     }
13512   else
13513     TYPE_STUB_SUPPORTED (type) = 1;
13514
13515   if (die_is_declaration (die, cu))
13516     TYPE_STUB (type) = 1;
13517   else if (attr == NULL && die->child == NULL
13518            && producer_is_realview (cu->producer))
13519     /* RealView does not output the required DW_AT_declaration
13520        on incomplete types.  */
13521     TYPE_STUB (type) = 1;
13522
13523   /* We need to add the type field to the die immediately so we don't
13524      infinitely recurse when dealing with pointers to the structure
13525      type within the structure itself.  */
13526   set_die_type (die, type, cu);
13527
13528   /* set_die_type should be already done.  */
13529   set_descriptive_type (type, die, cu);
13530
13531   return type;
13532 }
13533
13534 /* Finish creating a structure or union type, including filling in
13535    its members and creating a symbol for it.  */
13536
13537 static void
13538 process_structure_scope (struct die_info *die, struct dwarf2_cu *cu)
13539 {
13540   struct objfile *objfile = cu->objfile;
13541   struct die_info *child_die;
13542   struct type *type;
13543
13544   type = get_die_type (die, cu);
13545   if (type == NULL)
13546     type = read_structure_type (die, cu);
13547
13548   if (die->child != NULL && ! die_is_declaration (die, cu))
13549     {
13550       struct field_info fi;
13551       VEC (symbolp) *template_args = NULL;
13552       struct cleanup *back_to = make_cleanup (null_cleanup, 0);
13553
13554       memset (&fi, 0, sizeof (struct field_info));
13555
13556       child_die = die->child;
13557
13558       while (child_die && child_die->tag)
13559         {
13560           if (child_die->tag == DW_TAG_member
13561               || child_die->tag == DW_TAG_variable)
13562             {
13563               /* NOTE: carlton/2002-11-05: A C++ static data member
13564                  should be a DW_TAG_member that is a declaration, but
13565                  all versions of G++ as of this writing (so through at
13566                  least 3.2.1) incorrectly generate DW_TAG_variable
13567                  tags for them instead.  */
13568               dwarf2_add_field (&fi, child_die, cu);
13569             }
13570           else if (child_die->tag == DW_TAG_subprogram)
13571             {
13572               /* Rust doesn't have member functions in the C++ sense.
13573                  However, it does emit ordinary functions as children
13574                  of a struct DIE.  */
13575               if (cu->language == language_rust)
13576                 read_func_scope (child_die, cu);
13577               else
13578                 {
13579                   /* C++ member function.  */
13580                   dwarf2_add_member_fn (&fi, child_die, type, cu);
13581                 }
13582             }
13583           else if (child_die->tag == DW_TAG_inheritance)
13584             {
13585               /* C++ base class field.  */
13586               dwarf2_add_field (&fi, child_die, cu);
13587             }
13588           else if (child_die->tag == DW_TAG_typedef)
13589             dwarf2_add_typedef (&fi, child_die, cu);
13590           else if (child_die->tag == DW_TAG_template_type_param
13591                    || child_die->tag == DW_TAG_template_value_param)
13592             {
13593               struct symbol *arg = new_symbol (child_die, NULL, cu);
13594
13595               if (arg != NULL)
13596                 VEC_safe_push (symbolp, template_args, arg);
13597             }
13598
13599           child_die = sibling_die (child_die);
13600         }
13601
13602       /* Attach template arguments to type.  */
13603       if (! VEC_empty (symbolp, template_args))
13604         {
13605           ALLOCATE_CPLUS_STRUCT_TYPE (type);
13606           TYPE_N_TEMPLATE_ARGUMENTS (type)
13607             = VEC_length (symbolp, template_args);
13608           TYPE_TEMPLATE_ARGUMENTS (type)
13609             = XOBNEWVEC (&objfile->objfile_obstack,
13610                          struct symbol *,
13611                          TYPE_N_TEMPLATE_ARGUMENTS (type));
13612           memcpy (TYPE_TEMPLATE_ARGUMENTS (type),
13613                   VEC_address (symbolp, template_args),
13614                   (TYPE_N_TEMPLATE_ARGUMENTS (type)
13615                    * sizeof (struct symbol *)));
13616           VEC_free (symbolp, template_args);
13617         }
13618
13619       /* Attach fields and member functions to the type.  */
13620       if (fi.nfields)
13621         dwarf2_attach_fields_to_type (&fi, type, cu);
13622       if (fi.nfnfields)
13623         {
13624           dwarf2_attach_fn_fields_to_type (&fi, type, cu);
13625
13626           /* Get the type which refers to the base class (possibly this
13627              class itself) which contains the vtable pointer for the current
13628              class from the DW_AT_containing_type attribute.  This use of
13629              DW_AT_containing_type is a GNU extension.  */
13630
13631           if (dwarf2_attr (die, DW_AT_containing_type, cu) != NULL)
13632             {
13633               struct type *t = die_containing_type (die, cu);
13634
13635               set_type_vptr_basetype (type, t);
13636               if (type == t)
13637                 {
13638                   int i;
13639
13640                   /* Our own class provides vtbl ptr.  */
13641                   for (i = TYPE_NFIELDS (t) - 1;
13642                        i >= TYPE_N_BASECLASSES (t);
13643                        --i)
13644                     {
13645                       const char *fieldname = TYPE_FIELD_NAME (t, i);
13646
13647                       if (is_vtable_name (fieldname, cu))
13648                         {
13649                           set_type_vptr_fieldno (type, i);
13650                           break;
13651                         }
13652                     }
13653
13654                   /* Complain if virtual function table field not found.  */
13655                   if (i < TYPE_N_BASECLASSES (t))
13656                     complaint (&symfile_complaints,
13657                                _("virtual function table pointer "
13658                                  "not found when defining class '%s'"),
13659                                TYPE_TAG_NAME (type) ? TYPE_TAG_NAME (type) :
13660                                "");
13661                 }
13662               else
13663                 {
13664                   set_type_vptr_fieldno (type, TYPE_VPTR_FIELDNO (t));
13665                 }
13666             }
13667           else if (cu->producer
13668                    && startswith (cu->producer, "IBM(R) XL C/C++ Advanced Edition"))
13669             {
13670               /* The IBM XLC compiler does not provide direct indication
13671                  of the containing type, but the vtable pointer is
13672                  always named __vfp.  */
13673
13674               int i;
13675
13676               for (i = TYPE_NFIELDS (type) - 1;
13677                    i >= TYPE_N_BASECLASSES (type);
13678                    --i)
13679                 {
13680                   if (strcmp (TYPE_FIELD_NAME (type, i), "__vfp") == 0)
13681                     {
13682                       set_type_vptr_fieldno (type, i);
13683                       set_type_vptr_basetype (type, type);
13684                       break;
13685                     }
13686                 }
13687             }
13688         }
13689
13690       /* Copy fi.typedef_field_list linked list elements content into the
13691          allocated array TYPE_TYPEDEF_FIELD_ARRAY (type).  */
13692       if (fi.typedef_field_list)
13693         {
13694           int i = fi.typedef_field_list_count;
13695
13696           ALLOCATE_CPLUS_STRUCT_TYPE (type);
13697           TYPE_TYPEDEF_FIELD_ARRAY (type)
13698             = ((struct typedef_field *)
13699                TYPE_ALLOC (type, sizeof (TYPE_TYPEDEF_FIELD (type, 0)) * i));
13700           TYPE_TYPEDEF_FIELD_COUNT (type) = i;
13701
13702           /* Reverse the list order to keep the debug info elements order.  */
13703           while (--i >= 0)
13704             {
13705               struct typedef_field *dest, *src;
13706
13707               dest = &TYPE_TYPEDEF_FIELD (type, i);
13708               src = &fi.typedef_field_list->field;
13709               fi.typedef_field_list = fi.typedef_field_list->next;
13710               *dest = *src;
13711             }
13712         }
13713
13714       do_cleanups (back_to);
13715     }
13716
13717   quirk_gcc_member_function_pointer (type, objfile);
13718
13719   /* NOTE: carlton/2004-03-16: GCC 3.4 (or at least one of its
13720      snapshots) has been known to create a die giving a declaration
13721      for a class that has, as a child, a die giving a definition for a
13722      nested class.  So we have to process our children even if the
13723      current die is a declaration.  Normally, of course, a declaration
13724      won't have any children at all.  */
13725
13726   child_die = die->child;
13727
13728   while (child_die != NULL && child_die->tag)
13729     {
13730       if (child_die->tag == DW_TAG_member
13731           || child_die->tag == DW_TAG_variable
13732           || child_die->tag == DW_TAG_inheritance
13733           || child_die->tag == DW_TAG_template_value_param
13734           || child_die->tag == DW_TAG_template_type_param)
13735         {
13736           /* Do nothing.  */
13737         }
13738       else
13739         process_die (child_die, cu);
13740
13741       child_die = sibling_die (child_die);
13742     }
13743
13744   /* Do not consider external references.  According to the DWARF standard,
13745      these DIEs are identified by the fact that they have no byte_size
13746      attribute, and a declaration attribute.  */
13747   if (dwarf2_attr (die, DW_AT_byte_size, cu) != NULL
13748       || !die_is_declaration (die, cu))
13749     new_symbol (die, type, cu);
13750 }
13751
13752 /* Assuming DIE is an enumeration type, and TYPE is its associated type,
13753    update TYPE using some information only available in DIE's children.  */
13754
13755 static void
13756 update_enumeration_type_from_children (struct die_info *die,
13757                                        struct type *type,
13758                                        struct dwarf2_cu *cu)
13759 {
13760   struct obstack obstack;
13761   struct die_info *child_die;
13762   int unsigned_enum = 1;
13763   int flag_enum = 1;
13764   ULONGEST mask = 0;
13765   struct cleanup *old_chain;
13766
13767   obstack_init (&obstack);
13768   old_chain = make_cleanup_obstack_free (&obstack);
13769
13770   for (child_die = die->child;
13771        child_die != NULL && child_die->tag;
13772        child_die = sibling_die (child_die))
13773     {
13774       struct attribute *attr;
13775       LONGEST value;
13776       const gdb_byte *bytes;
13777       struct dwarf2_locexpr_baton *baton;
13778       const char *name;
13779
13780       if (child_die->tag != DW_TAG_enumerator)
13781         continue;
13782
13783       attr = dwarf2_attr (child_die, DW_AT_const_value, cu);
13784       if (attr == NULL)
13785         continue;
13786
13787       name = dwarf2_name (child_die, cu);
13788       if (name == NULL)
13789         name = "<anonymous enumerator>";
13790
13791       dwarf2_const_value_attr (attr, type, name, &obstack, cu,
13792                                &value, &bytes, &baton);
13793       if (value < 0)
13794         {
13795           unsigned_enum = 0;
13796           flag_enum = 0;
13797         }
13798       else if ((mask & value) != 0)
13799         flag_enum = 0;
13800       else
13801         mask |= value;
13802
13803       /* If we already know that the enum type is neither unsigned, nor
13804          a flag type, no need to look at the rest of the enumerates.  */
13805       if (!unsigned_enum && !flag_enum)
13806         break;
13807     }
13808
13809   if (unsigned_enum)
13810     TYPE_UNSIGNED (type) = 1;
13811   if (flag_enum)
13812     TYPE_FLAG_ENUM (type) = 1;
13813
13814   do_cleanups (old_chain);
13815 }
13816
13817 /* Given a DW_AT_enumeration_type die, set its type.  We do not
13818    complete the type's fields yet, or create any symbols.  */
13819
13820 static struct type *
13821 read_enumeration_type (struct die_info *die, struct dwarf2_cu *cu)
13822 {
13823   struct objfile *objfile = cu->objfile;
13824   struct type *type;
13825   struct attribute *attr;
13826   const char *name;
13827
13828   /* If the definition of this type lives in .debug_types, read that type.
13829      Don't follow DW_AT_specification though, that will take us back up
13830      the chain and we want to go down.  */
13831   attr = dwarf2_attr_no_follow (die, DW_AT_signature);
13832   if (attr)
13833     {
13834       type = get_DW_AT_signature_type (die, attr, cu);
13835
13836       /* The type's CU may not be the same as CU.
13837          Ensure TYPE is recorded with CU in die_type_hash.  */
13838       return set_die_type (die, type, cu);
13839     }
13840
13841   type = alloc_type (objfile);
13842
13843   TYPE_CODE (type) = TYPE_CODE_ENUM;
13844   name = dwarf2_full_name (NULL, die, cu);
13845   if (name != NULL)
13846     TYPE_TAG_NAME (type) = name;
13847
13848   attr = dwarf2_attr (die, DW_AT_type, cu);
13849   if (attr != NULL)
13850     {
13851       struct type *underlying_type = die_type (die, cu);
13852
13853       TYPE_TARGET_TYPE (type) = underlying_type;
13854     }
13855
13856   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
13857   if (attr)
13858     {
13859       TYPE_LENGTH (type) = DW_UNSND (attr);
13860     }
13861   else
13862     {
13863       TYPE_LENGTH (type) = 0;
13864     }
13865
13866   /* The enumeration DIE can be incomplete.  In Ada, any type can be
13867      declared as private in the package spec, and then defined only
13868      inside the package body.  Such types are known as Taft Amendment
13869      Types.  When another package uses such a type, an incomplete DIE
13870      may be generated by the compiler.  */
13871   if (die_is_declaration (die, cu))
13872     TYPE_STUB (type) = 1;
13873
13874   /* Finish the creation of this type by using the enum's children.
13875      We must call this even when the underlying type has been provided
13876      so that we can determine if we're looking at a "flag" enum.  */
13877   update_enumeration_type_from_children (die, type, cu);
13878
13879   /* If this type has an underlying type that is not a stub, then we
13880      may use its attributes.  We always use the "unsigned" attribute
13881      in this situation, because ordinarily we guess whether the type
13882      is unsigned -- but the guess can be wrong and the underlying type
13883      can tell us the reality.  However, we defer to a local size
13884      attribute if one exists, because this lets the compiler override
13885      the underlying type if needed.  */
13886   if (TYPE_TARGET_TYPE (type) != NULL && !TYPE_STUB (TYPE_TARGET_TYPE (type)))
13887     {
13888       TYPE_UNSIGNED (type) = TYPE_UNSIGNED (TYPE_TARGET_TYPE (type));
13889       if (TYPE_LENGTH (type) == 0)
13890         TYPE_LENGTH (type) = TYPE_LENGTH (TYPE_TARGET_TYPE (type));
13891     }
13892
13893   TYPE_DECLARED_CLASS (type) = dwarf2_flag_true_p (die, DW_AT_enum_class, cu);
13894
13895   return set_die_type (die, type, cu);
13896 }
13897
13898 /* Given a pointer to a die which begins an enumeration, process all
13899    the dies that define the members of the enumeration, and create the
13900    symbol for the enumeration type.
13901
13902    NOTE: We reverse the order of the element list.  */
13903
13904 static void
13905 process_enumeration_scope (struct die_info *die, struct dwarf2_cu *cu)
13906 {
13907   struct type *this_type;
13908
13909   this_type = get_die_type (die, cu);
13910   if (this_type == NULL)
13911     this_type = read_enumeration_type (die, cu);
13912
13913   if (die->child != NULL)
13914     {
13915       struct die_info *child_die;
13916       struct symbol *sym;
13917       struct field *fields = NULL;
13918       int num_fields = 0;
13919       const char *name;
13920
13921       child_die = die->child;
13922       while (child_die && child_die->tag)
13923         {
13924           if (child_die->tag != DW_TAG_enumerator)
13925             {
13926               process_die (child_die, cu);
13927             }
13928           else
13929             {
13930               name = dwarf2_name (child_die, cu);
13931               if (name)
13932                 {
13933                   sym = new_symbol (child_die, this_type, cu);
13934
13935                   if ((num_fields % DW_FIELD_ALLOC_CHUNK) == 0)
13936                     {
13937                       fields = (struct field *)
13938                         xrealloc (fields,
13939                                   (num_fields + DW_FIELD_ALLOC_CHUNK)
13940                                   * sizeof (struct field));
13941                     }
13942
13943                   FIELD_NAME (fields[num_fields]) = SYMBOL_LINKAGE_NAME (sym);
13944                   FIELD_TYPE (fields[num_fields]) = NULL;
13945                   SET_FIELD_ENUMVAL (fields[num_fields], SYMBOL_VALUE (sym));
13946                   FIELD_BITSIZE (fields[num_fields]) = 0;
13947
13948                   num_fields++;
13949                 }
13950             }
13951
13952           child_die = sibling_die (child_die);
13953         }
13954
13955       if (num_fields)
13956         {
13957           TYPE_NFIELDS (this_type) = num_fields;
13958           TYPE_FIELDS (this_type) = (struct field *)
13959             TYPE_ALLOC (this_type, sizeof (struct field) * num_fields);
13960           memcpy (TYPE_FIELDS (this_type), fields,
13961                   sizeof (struct field) * num_fields);
13962           xfree (fields);
13963         }
13964     }
13965
13966   /* If we are reading an enum from a .debug_types unit, and the enum
13967      is a declaration, and the enum is not the signatured type in the
13968      unit, then we do not want to add a symbol for it.  Adding a
13969      symbol would in some cases obscure the true definition of the
13970      enum, giving users an incomplete type when the definition is
13971      actually available.  Note that we do not want to do this for all
13972      enums which are just declarations, because C++0x allows forward
13973      enum declarations.  */
13974   if (cu->per_cu->is_debug_types
13975       && die_is_declaration (die, cu))
13976     {
13977       struct signatured_type *sig_type;
13978
13979       sig_type = (struct signatured_type *) cu->per_cu;
13980       gdb_assert (sig_type->type_offset_in_section.sect_off != 0);
13981       if (sig_type->type_offset_in_section.sect_off != die->offset.sect_off)
13982         return;
13983     }
13984
13985   new_symbol (die, this_type, cu);
13986 }
13987
13988 /* Extract all information from a DW_TAG_array_type DIE and put it in
13989    the DIE's type field.  For now, this only handles one dimensional
13990    arrays.  */
13991
13992 static struct type *
13993 read_array_type (struct die_info *die, struct dwarf2_cu *cu)
13994 {
13995   struct objfile *objfile = cu->objfile;
13996   struct die_info *child_die;
13997   struct type *type;
13998   struct type *element_type, *range_type, *index_type;
13999   struct type **range_types = NULL;
14000   struct attribute *attr;
14001   int ndim = 0;
14002   struct cleanup *back_to;
14003   const char *name;
14004   unsigned int bit_stride = 0;
14005
14006   element_type = die_type (die, cu);
14007
14008   /* The die_type call above may have already set the type for this DIE.  */
14009   type = get_die_type (die, cu);
14010   if (type)
14011     return type;
14012
14013   attr = dwarf2_attr (die, DW_AT_byte_stride, cu);
14014   if (attr != NULL)
14015     bit_stride = DW_UNSND (attr) * 8;
14016
14017   attr = dwarf2_attr (die, DW_AT_bit_stride, cu);
14018   if (attr != NULL)
14019     bit_stride = DW_UNSND (attr);
14020
14021   /* Irix 6.2 native cc creates array types without children for
14022      arrays with unspecified length.  */
14023   if (die->child == NULL)
14024     {
14025       index_type = objfile_type (objfile)->builtin_int;
14026       range_type = create_static_range_type (NULL, index_type, 0, -1);
14027       type = create_array_type_with_stride (NULL, element_type, range_type,
14028                                             bit_stride);
14029       return set_die_type (die, type, cu);
14030     }
14031
14032   back_to = make_cleanup (null_cleanup, NULL);
14033   child_die = die->child;
14034   while (child_die && child_die->tag)
14035     {
14036       if (child_die->tag == DW_TAG_subrange_type)
14037         {
14038           struct type *child_type = read_type_die (child_die, cu);
14039
14040           if (child_type != NULL)
14041             {
14042               /* The range type was succesfully read.  Save it for the
14043                  array type creation.  */
14044               if ((ndim % DW_FIELD_ALLOC_CHUNK) == 0)
14045                 {
14046                   range_types = (struct type **)
14047                     xrealloc (range_types, (ndim + DW_FIELD_ALLOC_CHUNK)
14048                               * sizeof (struct type *));
14049                   if (ndim == 0)
14050                     make_cleanup (free_current_contents, &range_types);
14051                 }
14052               range_types[ndim++] = child_type;
14053             }
14054         }
14055       child_die = sibling_die (child_die);
14056     }
14057
14058   /* Dwarf2 dimensions are output from left to right, create the
14059      necessary array types in backwards order.  */
14060
14061   type = element_type;
14062
14063   if (read_array_order (die, cu) == DW_ORD_col_major)
14064     {
14065       int i = 0;
14066
14067       while (i < ndim)
14068         type = create_array_type_with_stride (NULL, type, range_types[i++],
14069                                               bit_stride);
14070     }
14071   else
14072     {
14073       while (ndim-- > 0)
14074         type = create_array_type_with_stride (NULL, type, range_types[ndim],
14075                                               bit_stride);
14076     }
14077
14078   /* Understand Dwarf2 support for vector types (like they occur on
14079      the PowerPC w/ AltiVec).  Gcc just adds another attribute to the
14080      array type.  This is not part of the Dwarf2/3 standard yet, but a
14081      custom vendor extension.  The main difference between a regular
14082      array and the vector variant is that vectors are passed by value
14083      to functions.  */
14084   attr = dwarf2_attr (die, DW_AT_GNU_vector, cu);
14085   if (attr)
14086     make_vector_type (type);
14087
14088   /* The DIE may have DW_AT_byte_size set.  For example an OpenCL
14089      implementation may choose to implement triple vectors using this
14090      attribute.  */
14091   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
14092   if (attr)
14093     {
14094       if (DW_UNSND (attr) >= TYPE_LENGTH (type))
14095         TYPE_LENGTH (type) = DW_UNSND (attr);
14096       else
14097         complaint (&symfile_complaints,
14098                    _("DW_AT_byte_size for array type smaller "
14099                      "than the total size of elements"));
14100     }
14101
14102   name = dwarf2_name (die, cu);
14103   if (name)
14104     TYPE_NAME (type) = name;
14105
14106   /* Install the type in the die.  */
14107   set_die_type (die, type, cu);
14108
14109   /* set_die_type should be already done.  */
14110   set_descriptive_type (type, die, cu);
14111
14112   do_cleanups (back_to);
14113
14114   return type;
14115 }
14116
14117 static enum dwarf_array_dim_ordering
14118 read_array_order (struct die_info *die, struct dwarf2_cu *cu)
14119 {
14120   struct attribute *attr;
14121
14122   attr = dwarf2_attr (die, DW_AT_ordering, cu);
14123
14124   if (attr)
14125     return (enum dwarf_array_dim_ordering) DW_SND (attr);
14126
14127   /* GNU F77 is a special case, as at 08/2004 array type info is the
14128      opposite order to the dwarf2 specification, but data is still
14129      laid out as per normal fortran.
14130
14131      FIXME: dsl/2004-8-20: If G77 is ever fixed, this will also need
14132      version checking.  */
14133
14134   if (cu->language == language_fortran
14135       && cu->producer && strstr (cu->producer, "GNU F77"))
14136     {
14137       return DW_ORD_row_major;
14138     }
14139
14140   switch (cu->language_defn->la_array_ordering)
14141     {
14142     case array_column_major:
14143       return DW_ORD_col_major;
14144     case array_row_major:
14145     default:
14146       return DW_ORD_row_major;
14147     };
14148 }
14149
14150 /* Extract all information from a DW_TAG_set_type DIE and put it in
14151    the DIE's type field.  */
14152
14153 static struct type *
14154 read_set_type (struct die_info *die, struct dwarf2_cu *cu)
14155 {
14156   struct type *domain_type, *set_type;
14157   struct attribute *attr;
14158
14159   domain_type = die_type (die, cu);
14160
14161   /* The die_type call above may have already set the type for this DIE.  */
14162   set_type = get_die_type (die, cu);
14163   if (set_type)
14164     return set_type;
14165
14166   set_type = create_set_type (NULL, domain_type);
14167
14168   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
14169   if (attr)
14170     TYPE_LENGTH (set_type) = DW_UNSND (attr);
14171
14172   return set_die_type (die, set_type, cu);
14173 }
14174
14175 /* A helper for read_common_block that creates a locexpr baton.
14176    SYM is the symbol which we are marking as computed.
14177    COMMON_DIE is the DIE for the common block.
14178    COMMON_LOC is the location expression attribute for the common
14179    block itself.
14180    MEMBER_LOC is the location expression attribute for the particular
14181    member of the common block that we are processing.
14182    CU is the CU from which the above come.  */
14183
14184 static void
14185 mark_common_block_symbol_computed (struct symbol *sym,
14186                                    struct die_info *common_die,
14187                                    struct attribute *common_loc,
14188                                    struct attribute *member_loc,
14189                                    struct dwarf2_cu *cu)
14190 {
14191   struct objfile *objfile = dwarf2_per_objfile->objfile;
14192   struct dwarf2_locexpr_baton *baton;
14193   gdb_byte *ptr;
14194   unsigned int cu_off;
14195   enum bfd_endian byte_order = gdbarch_byte_order (get_objfile_arch (objfile));
14196   LONGEST offset = 0;
14197
14198   gdb_assert (common_loc && member_loc);
14199   gdb_assert (attr_form_is_block (common_loc));
14200   gdb_assert (attr_form_is_block (member_loc)
14201               || attr_form_is_constant (member_loc));
14202
14203   baton = XOBNEW (&objfile->objfile_obstack, struct dwarf2_locexpr_baton);
14204   baton->per_cu = cu->per_cu;
14205   gdb_assert (baton->per_cu);
14206
14207   baton->size = 5 /* DW_OP_call4 */ + 1 /* DW_OP_plus */;
14208
14209   if (attr_form_is_constant (member_loc))
14210     {
14211       offset = dwarf2_get_attr_constant_value (member_loc, 0);
14212       baton->size += 1 /* DW_OP_addr */ + cu->header.addr_size;
14213     }
14214   else
14215     baton->size += DW_BLOCK (member_loc)->size;
14216
14217   ptr = (gdb_byte *) obstack_alloc (&objfile->objfile_obstack, baton->size);
14218   baton->data = ptr;
14219
14220   *ptr++ = DW_OP_call4;
14221   cu_off = common_die->offset.sect_off - cu->per_cu->offset.sect_off;
14222   store_unsigned_integer (ptr, 4, byte_order, cu_off);
14223   ptr += 4;
14224
14225   if (attr_form_is_constant (member_loc))
14226     {
14227       *ptr++ = DW_OP_addr;
14228       store_unsigned_integer (ptr, cu->header.addr_size, byte_order, offset);
14229       ptr += cu->header.addr_size;
14230     }
14231   else
14232     {
14233       /* We have to copy the data here, because DW_OP_call4 will only
14234          use a DW_AT_location attribute.  */
14235       memcpy (ptr, DW_BLOCK (member_loc)->data, DW_BLOCK (member_loc)->size);
14236       ptr += DW_BLOCK (member_loc)->size;
14237     }
14238
14239   *ptr++ = DW_OP_plus;
14240   gdb_assert (ptr - baton->data == baton->size);
14241
14242   SYMBOL_LOCATION_BATON (sym) = baton;
14243   SYMBOL_ACLASS_INDEX (sym) = dwarf2_locexpr_index;
14244 }
14245
14246 /* Create appropriate locally-scoped variables for all the
14247    DW_TAG_common_block entries.  Also create a struct common_block
14248    listing all such variables for `info common'.  COMMON_BLOCK_DOMAIN
14249    is used to sepate the common blocks name namespace from regular
14250    variable names.  */
14251
14252 static void
14253 read_common_block (struct die_info *die, struct dwarf2_cu *cu)
14254 {
14255   struct attribute *attr;
14256
14257   attr = dwarf2_attr (die, DW_AT_location, cu);
14258   if (attr)
14259     {
14260       /* Support the .debug_loc offsets.  */
14261       if (attr_form_is_block (attr))
14262         {
14263           /* Ok.  */
14264         }
14265       else if (attr_form_is_section_offset (attr))
14266         {
14267           dwarf2_complex_location_expr_complaint ();
14268           attr = NULL;
14269         }
14270       else
14271         {
14272           dwarf2_invalid_attrib_class_complaint ("DW_AT_location",
14273                                                  "common block member");
14274           attr = NULL;
14275         }
14276     }
14277
14278   if (die->child != NULL)
14279     {
14280       struct objfile *objfile = cu->objfile;
14281       struct die_info *child_die;
14282       size_t n_entries = 0, size;
14283       struct common_block *common_block;
14284       struct symbol *sym;
14285
14286       for (child_die = die->child;
14287            child_die && child_die->tag;
14288            child_die = sibling_die (child_die))
14289         ++n_entries;
14290
14291       size = (sizeof (struct common_block)
14292               + (n_entries - 1) * sizeof (struct symbol *));
14293       common_block
14294         = (struct common_block *) obstack_alloc (&objfile->objfile_obstack,
14295                                                  size);
14296       memset (common_block->contents, 0, n_entries * sizeof (struct symbol *));
14297       common_block->n_entries = 0;
14298
14299       for (child_die = die->child;
14300            child_die && child_die->tag;
14301            child_die = sibling_die (child_die))
14302         {
14303           /* Create the symbol in the DW_TAG_common_block block in the current
14304              symbol scope.  */
14305           sym = new_symbol (child_die, NULL, cu);
14306           if (sym != NULL)
14307             {
14308               struct attribute *member_loc;
14309
14310               common_block->contents[common_block->n_entries++] = sym;
14311
14312               member_loc = dwarf2_attr (child_die, DW_AT_data_member_location,
14313                                         cu);
14314               if (member_loc)
14315                 {
14316                   /* GDB has handled this for a long time, but it is
14317                      not specified by DWARF.  It seems to have been
14318                      emitted by gfortran at least as recently as:
14319                      http://gcc.gnu.org/bugzilla/show_bug.cgi?id=23057.  */
14320                   complaint (&symfile_complaints,
14321                              _("Variable in common block has "
14322                                "DW_AT_data_member_location "
14323                                "- DIE at 0x%x [in module %s]"),
14324                              child_die->offset.sect_off,
14325                              objfile_name (cu->objfile));
14326
14327                   if (attr_form_is_section_offset (member_loc))
14328                     dwarf2_complex_location_expr_complaint ();
14329                   else if (attr_form_is_constant (member_loc)
14330                            || attr_form_is_block (member_loc))
14331                     {
14332                       if (attr)
14333                         mark_common_block_symbol_computed (sym, die, attr,
14334                                                            member_loc, cu);
14335                     }
14336                   else
14337                     dwarf2_complex_location_expr_complaint ();
14338                 }
14339             }
14340         }
14341
14342       sym = new_symbol (die, objfile_type (objfile)->builtin_void, cu);
14343       SYMBOL_VALUE_COMMON_BLOCK (sym) = common_block;
14344     }
14345 }
14346
14347 /* Create a type for a C++ namespace.  */
14348
14349 static struct type *
14350 read_namespace_type (struct die_info *die, struct dwarf2_cu *cu)
14351 {
14352   struct objfile *objfile = cu->objfile;
14353   const char *previous_prefix, *name;
14354   int is_anonymous;
14355   struct type *type;
14356
14357   /* For extensions, reuse the type of the original namespace.  */
14358   if (dwarf2_attr (die, DW_AT_extension, cu) != NULL)
14359     {
14360       struct die_info *ext_die;
14361       struct dwarf2_cu *ext_cu = cu;
14362
14363       ext_die = dwarf2_extension (die, &ext_cu);
14364       type = read_type_die (ext_die, ext_cu);
14365
14366       /* EXT_CU may not be the same as CU.
14367          Ensure TYPE is recorded with CU in die_type_hash.  */
14368       return set_die_type (die, type, cu);
14369     }
14370
14371   name = namespace_name (die, &is_anonymous, cu);
14372
14373   /* Now build the name of the current namespace.  */
14374
14375   previous_prefix = determine_prefix (die, cu);
14376   if (previous_prefix[0] != '\0')
14377     name = typename_concat (&objfile->objfile_obstack,
14378                             previous_prefix, name, 0, cu);
14379
14380   /* Create the type.  */
14381   type = init_type (objfile, TYPE_CODE_NAMESPACE, 0, name);
14382   TYPE_TAG_NAME (type) = TYPE_NAME (type);
14383
14384   return set_die_type (die, type, cu);
14385 }
14386
14387 /* Read a namespace scope.  */
14388
14389 static void
14390 read_namespace (struct die_info *die, struct dwarf2_cu *cu)
14391 {
14392   struct objfile *objfile = cu->objfile;
14393   int is_anonymous;
14394
14395   /* Add a symbol associated to this if we haven't seen the namespace
14396      before.  Also, add a using directive if it's an anonymous
14397      namespace.  */
14398
14399   if (dwarf2_attr (die, DW_AT_extension, cu) == NULL)
14400     {
14401       struct type *type;
14402
14403       type = read_type_die (die, cu);
14404       new_symbol (die, type, cu);
14405
14406       namespace_name (die, &is_anonymous, cu);
14407       if (is_anonymous)
14408         {
14409           const char *previous_prefix = determine_prefix (die, cu);
14410
14411           add_using_directive (using_directives (cu->language),
14412                                previous_prefix, TYPE_NAME (type), NULL,
14413                                NULL, NULL, 0, &objfile->objfile_obstack);
14414         }
14415     }
14416
14417   if (die->child != NULL)
14418     {
14419       struct die_info *child_die = die->child;
14420
14421       while (child_die && child_die->tag)
14422         {
14423           process_die (child_die, cu);
14424           child_die = sibling_die (child_die);
14425         }
14426     }
14427 }
14428
14429 /* Read a Fortran module as type.  This DIE can be only a declaration used for
14430    imported module.  Still we need that type as local Fortran "use ... only"
14431    declaration imports depend on the created type in determine_prefix.  */
14432
14433 static struct type *
14434 read_module_type (struct die_info *die, struct dwarf2_cu *cu)
14435 {
14436   struct objfile *objfile = cu->objfile;
14437   const char *module_name;
14438   struct type *type;
14439
14440   module_name = dwarf2_name (die, cu);
14441   if (!module_name)
14442     complaint (&symfile_complaints,
14443                _("DW_TAG_module has no name, offset 0x%x"),
14444                die->offset.sect_off);
14445   type = init_type (objfile, TYPE_CODE_MODULE, 0, module_name);
14446
14447   /* determine_prefix uses TYPE_TAG_NAME.  */
14448   TYPE_TAG_NAME (type) = TYPE_NAME (type);
14449
14450   return set_die_type (die, type, cu);
14451 }
14452
14453 /* Read a Fortran module.  */
14454
14455 static void
14456 read_module (struct die_info *die, struct dwarf2_cu *cu)
14457 {
14458   struct die_info *child_die = die->child;
14459   struct type *type;
14460
14461   type = read_type_die (die, cu);
14462   new_symbol (die, type, cu);
14463
14464   while (child_die && child_die->tag)
14465     {
14466       process_die (child_die, cu);
14467       child_die = sibling_die (child_die);
14468     }
14469 }
14470
14471 /* Return the name of the namespace represented by DIE.  Set
14472    *IS_ANONYMOUS to tell whether or not the namespace is an anonymous
14473    namespace.  */
14474
14475 static const char *
14476 namespace_name (struct die_info *die, int *is_anonymous, struct dwarf2_cu *cu)
14477 {
14478   struct die_info *current_die;
14479   const char *name = NULL;
14480
14481   /* Loop through the extensions until we find a name.  */
14482
14483   for (current_die = die;
14484        current_die != NULL;
14485        current_die = dwarf2_extension (die, &cu))
14486     {
14487       /* We don't use dwarf2_name here so that we can detect the absence
14488          of a name -> anonymous namespace.  */
14489       name = dwarf2_string_attr (die, DW_AT_name, cu);
14490
14491       if (name != NULL)
14492         break;
14493     }
14494
14495   /* Is it an anonymous namespace?  */
14496
14497   *is_anonymous = (name == NULL);
14498   if (*is_anonymous)
14499     name = CP_ANONYMOUS_NAMESPACE_STR;
14500
14501   return name;
14502 }
14503
14504 /* Extract all information from a DW_TAG_pointer_type DIE and add to
14505    the user defined type vector.  */
14506
14507 static struct type *
14508 read_tag_pointer_type (struct die_info *die, struct dwarf2_cu *cu)
14509 {
14510   struct gdbarch *gdbarch = get_objfile_arch (cu->objfile);
14511   struct comp_unit_head *cu_header = &cu->header;
14512   struct type *type;
14513   struct attribute *attr_byte_size;
14514   struct attribute *attr_address_class;
14515   int byte_size, addr_class;
14516   struct type *target_type;
14517
14518   target_type = die_type (die, cu);
14519
14520   /* The die_type call above may have already set the type for this DIE.  */
14521   type = get_die_type (die, cu);
14522   if (type)
14523     return type;
14524
14525   type = lookup_pointer_type (target_type);
14526
14527   attr_byte_size = dwarf2_attr (die, DW_AT_byte_size, cu);
14528   if (attr_byte_size)
14529     byte_size = DW_UNSND (attr_byte_size);
14530   else
14531     byte_size = cu_header->addr_size;
14532
14533   attr_address_class = dwarf2_attr (die, DW_AT_address_class, cu);
14534   if (attr_address_class)
14535     addr_class = DW_UNSND (attr_address_class);
14536   else
14537     addr_class = DW_ADDR_none;
14538
14539   /* If the pointer size or address class is different than the
14540      default, create a type variant marked as such and set the
14541      length accordingly.  */
14542   if (TYPE_LENGTH (type) != byte_size || addr_class != DW_ADDR_none)
14543     {
14544       if (gdbarch_address_class_type_flags_p (gdbarch))
14545         {
14546           int type_flags;
14547
14548           type_flags = gdbarch_address_class_type_flags
14549                          (gdbarch, byte_size, addr_class);
14550           gdb_assert ((type_flags & ~TYPE_INSTANCE_FLAG_ADDRESS_CLASS_ALL)
14551                       == 0);
14552           type = make_type_with_address_space (type, type_flags);
14553         }
14554       else if (TYPE_LENGTH (type) != byte_size)
14555         {
14556           complaint (&symfile_complaints,
14557                      _("invalid pointer size %d"), byte_size);
14558         }
14559       else
14560         {
14561           /* Should we also complain about unhandled address classes?  */
14562         }
14563     }
14564
14565   TYPE_LENGTH (type) = byte_size;
14566   return set_die_type (die, type, cu);
14567 }
14568
14569 /* Extract all information from a DW_TAG_ptr_to_member_type DIE and add to
14570    the user defined type vector.  */
14571
14572 static struct type *
14573 read_tag_ptr_to_member_type (struct die_info *die, struct dwarf2_cu *cu)
14574 {
14575   struct type *type;
14576   struct type *to_type;
14577   struct type *domain;
14578
14579   to_type = die_type (die, cu);
14580   domain = die_containing_type (die, cu);
14581
14582   /* The calls above may have already set the type for this DIE.  */
14583   type = get_die_type (die, cu);
14584   if (type)
14585     return type;
14586
14587   if (TYPE_CODE (check_typedef (to_type)) == TYPE_CODE_METHOD)
14588     type = lookup_methodptr_type (to_type);
14589   else if (TYPE_CODE (check_typedef (to_type)) == TYPE_CODE_FUNC)
14590     {
14591       struct type *new_type = alloc_type (cu->objfile);
14592
14593       smash_to_method_type (new_type, domain, TYPE_TARGET_TYPE (to_type),
14594                             TYPE_FIELDS (to_type), TYPE_NFIELDS (to_type),
14595                             TYPE_VARARGS (to_type));
14596       type = lookup_methodptr_type (new_type);
14597     }
14598   else
14599     type = lookup_memberptr_type (to_type, domain);
14600
14601   return set_die_type (die, type, cu);
14602 }
14603
14604 /* Extract all information from a DW_TAG_{rvalue_,}reference_type DIE and add to
14605    the user defined type vector.  */
14606
14607 static struct type *
14608 read_tag_reference_type (struct die_info *die, struct dwarf2_cu *cu,
14609                           enum type_code refcode)
14610 {
14611   struct comp_unit_head *cu_header = &cu->header;
14612   struct type *type, *target_type;
14613   struct attribute *attr;
14614
14615   gdb_assert (refcode == TYPE_CODE_REF || refcode == TYPE_CODE_RVALUE_REF);
14616
14617   target_type = die_type (die, cu);
14618
14619   /* The die_type call above may have already set the type for this DIE.  */
14620   type = get_die_type (die, cu);
14621   if (type)
14622     return type;
14623
14624   type = lookup_reference_type (target_type, refcode);
14625   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
14626   if (attr)
14627     {
14628       TYPE_LENGTH (type) = DW_UNSND (attr);
14629     }
14630   else
14631     {
14632       TYPE_LENGTH (type) = cu_header->addr_size;
14633     }
14634   return set_die_type (die, type, cu);
14635 }
14636
14637 /* Add the given cv-qualifiers to the element type of the array.  GCC
14638    outputs DWARF type qualifiers that apply to an array, not the
14639    element type.  But GDB relies on the array element type to carry
14640    the cv-qualifiers.  This mimics section 6.7.3 of the C99
14641    specification.  */
14642
14643 static struct type *
14644 add_array_cv_type (struct die_info *die, struct dwarf2_cu *cu,
14645                    struct type *base_type, int cnst, int voltl)
14646 {
14647   struct type *el_type, *inner_array;
14648
14649   base_type = copy_type (base_type);
14650   inner_array = base_type;
14651
14652   while (TYPE_CODE (TYPE_TARGET_TYPE (inner_array)) == TYPE_CODE_ARRAY)
14653     {
14654       TYPE_TARGET_TYPE (inner_array) =
14655         copy_type (TYPE_TARGET_TYPE (inner_array));
14656       inner_array = TYPE_TARGET_TYPE (inner_array);
14657     }
14658
14659   el_type = TYPE_TARGET_TYPE (inner_array);
14660   cnst |= TYPE_CONST (el_type);
14661   voltl |= TYPE_VOLATILE (el_type);
14662   TYPE_TARGET_TYPE (inner_array) = make_cv_type (cnst, voltl, el_type, NULL);
14663
14664   return set_die_type (die, base_type, cu);
14665 }
14666
14667 static struct type *
14668 read_tag_const_type (struct die_info *die, struct dwarf2_cu *cu)
14669 {
14670   struct type *base_type, *cv_type;
14671
14672   base_type = die_type (die, cu);
14673
14674   /* The die_type call above may have already set the type for this DIE.  */
14675   cv_type = get_die_type (die, cu);
14676   if (cv_type)
14677     return cv_type;
14678
14679   /* In case the const qualifier is applied to an array type, the element type
14680      is so qualified, not the array type (section 6.7.3 of C99).  */
14681   if (TYPE_CODE (base_type) == TYPE_CODE_ARRAY)
14682     return add_array_cv_type (die, cu, base_type, 1, 0);
14683
14684   cv_type = make_cv_type (1, TYPE_VOLATILE (base_type), base_type, 0);
14685   return set_die_type (die, cv_type, cu);
14686 }
14687
14688 static struct type *
14689 read_tag_volatile_type (struct die_info *die, struct dwarf2_cu *cu)
14690 {
14691   struct type *base_type, *cv_type;
14692
14693   base_type = die_type (die, cu);
14694
14695   /* The die_type call above may have already set the type for this DIE.  */
14696   cv_type = get_die_type (die, cu);
14697   if (cv_type)
14698     return cv_type;
14699
14700   /* In case the volatile qualifier is applied to an array type, the
14701      element type is so qualified, not the array type (section 6.7.3
14702      of C99).  */
14703   if (TYPE_CODE (base_type) == TYPE_CODE_ARRAY)
14704     return add_array_cv_type (die, cu, base_type, 0, 1);
14705
14706   cv_type = make_cv_type (TYPE_CONST (base_type), 1, base_type, 0);
14707   return set_die_type (die, cv_type, cu);
14708 }
14709
14710 /* Handle DW_TAG_restrict_type.  */
14711
14712 static struct type *
14713 read_tag_restrict_type (struct die_info *die, struct dwarf2_cu *cu)
14714 {
14715   struct type *base_type, *cv_type;
14716
14717   base_type = die_type (die, cu);
14718
14719   /* The die_type call above may have already set the type for this DIE.  */
14720   cv_type = get_die_type (die, cu);
14721   if (cv_type)
14722     return cv_type;
14723
14724   cv_type = make_restrict_type (base_type);
14725   return set_die_type (die, cv_type, cu);
14726 }
14727
14728 /* Handle DW_TAG_atomic_type.  */
14729
14730 static struct type *
14731 read_tag_atomic_type (struct die_info *die, struct dwarf2_cu *cu)
14732 {
14733   struct type *base_type, *cv_type;
14734
14735   base_type = die_type (die, cu);
14736
14737   /* The die_type call above may have already set the type for this DIE.  */
14738   cv_type = get_die_type (die, cu);
14739   if (cv_type)
14740     return cv_type;
14741
14742   cv_type = make_atomic_type (base_type);
14743   return set_die_type (die, cv_type, cu);
14744 }
14745
14746 /* Extract all information from a DW_TAG_string_type DIE and add to
14747    the user defined type vector.  It isn't really a user defined type,
14748    but it behaves like one, with other DIE's using an AT_user_def_type
14749    attribute to reference it.  */
14750
14751 static struct type *
14752 read_tag_string_type (struct die_info *die, struct dwarf2_cu *cu)
14753 {
14754   struct objfile *objfile = cu->objfile;
14755   struct gdbarch *gdbarch = get_objfile_arch (objfile);
14756   struct type *type, *range_type, *index_type, *char_type;
14757   struct attribute *attr;
14758   unsigned int length;
14759
14760   attr = dwarf2_attr (die, DW_AT_string_length, cu);
14761   if (attr)
14762     {
14763       length = DW_UNSND (attr);
14764     }
14765   else
14766     {
14767       /* Check for the DW_AT_byte_size attribute.  */
14768       attr = dwarf2_attr (die, DW_AT_byte_size, cu);
14769       if (attr)
14770         {
14771           length = DW_UNSND (attr);
14772         }
14773       else
14774         {
14775           length = 1;
14776         }
14777     }
14778
14779   index_type = objfile_type (objfile)->builtin_int;
14780   range_type = create_static_range_type (NULL, index_type, 1, length);
14781   char_type = language_string_char_type (cu->language_defn, gdbarch);
14782   type = create_string_type (NULL, char_type, range_type);
14783
14784   return set_die_type (die, type, cu);
14785 }
14786
14787 /* Assuming that DIE corresponds to a function, returns nonzero
14788    if the function is prototyped.  */
14789
14790 static int
14791 prototyped_function_p (struct die_info *die, struct dwarf2_cu *cu)
14792 {
14793   struct attribute *attr;
14794
14795   attr = dwarf2_attr (die, DW_AT_prototyped, cu);
14796   if (attr && (DW_UNSND (attr) != 0))
14797     return 1;
14798
14799   /* The DWARF standard implies that the DW_AT_prototyped attribute
14800      is only meaninful for C, but the concept also extends to other
14801      languages that allow unprototyped functions (Eg: Objective C).
14802      For all other languages, assume that functions are always
14803      prototyped.  */
14804   if (cu->language != language_c
14805       && cu->language != language_objc
14806       && cu->language != language_opencl)
14807     return 1;
14808
14809   /* RealView does not emit DW_AT_prototyped.  We can not distinguish
14810      prototyped and unprototyped functions; default to prototyped,
14811      since that is more common in modern code (and RealView warns
14812      about unprototyped functions).  */
14813   if (producer_is_realview (cu->producer))
14814     return 1;
14815
14816   return 0;
14817 }
14818
14819 /* Handle DIES due to C code like:
14820
14821    struct foo
14822    {
14823    int (*funcp)(int a, long l);
14824    int b;
14825    };
14826
14827    ('funcp' generates a DW_TAG_subroutine_type DIE).  */
14828
14829 static struct type *
14830 read_subroutine_type (struct die_info *die, struct dwarf2_cu *cu)
14831 {
14832   struct objfile *objfile = cu->objfile;
14833   struct type *type;            /* Type that this function returns.  */
14834   struct type *ftype;           /* Function that returns above type.  */
14835   struct attribute *attr;
14836
14837   type = die_type (die, cu);
14838
14839   /* The die_type call above may have already set the type for this DIE.  */
14840   ftype = get_die_type (die, cu);
14841   if (ftype)
14842     return ftype;
14843
14844   ftype = lookup_function_type (type);
14845
14846   if (prototyped_function_p (die, cu))
14847     TYPE_PROTOTYPED (ftype) = 1;
14848
14849   /* Store the calling convention in the type if it's available in
14850      the subroutine die.  Otherwise set the calling convention to
14851      the default value DW_CC_normal.  */
14852   attr = dwarf2_attr (die, DW_AT_calling_convention, cu);
14853   if (attr)
14854     TYPE_CALLING_CONVENTION (ftype) = DW_UNSND (attr);
14855   else if (cu->producer && strstr (cu->producer, "IBM XL C for OpenCL"))
14856     TYPE_CALLING_CONVENTION (ftype) = DW_CC_GDB_IBM_OpenCL;
14857   else
14858     TYPE_CALLING_CONVENTION (ftype) = DW_CC_normal;
14859
14860   /* Record whether the function returns normally to its caller or not
14861      if the DWARF producer set that information.  */
14862   attr = dwarf2_attr (die, DW_AT_noreturn, cu);
14863   if (attr && (DW_UNSND (attr) != 0))
14864     TYPE_NO_RETURN (ftype) = 1;
14865
14866   /* We need to add the subroutine type to the die immediately so
14867      we don't infinitely recurse when dealing with parameters
14868      declared as the same subroutine type.  */
14869   set_die_type (die, ftype, cu);
14870
14871   if (die->child != NULL)
14872     {
14873       struct type *void_type = objfile_type (objfile)->builtin_void;
14874       struct die_info *child_die;
14875       int nparams, iparams;
14876
14877       /* Count the number of parameters.
14878          FIXME: GDB currently ignores vararg functions, but knows about
14879          vararg member functions.  */
14880       nparams = 0;
14881       child_die = die->child;
14882       while (child_die && child_die->tag)
14883         {
14884           if (child_die->tag == DW_TAG_formal_parameter)
14885             nparams++;
14886           else if (child_die->tag == DW_TAG_unspecified_parameters)
14887             TYPE_VARARGS (ftype) = 1;
14888           child_die = sibling_die (child_die);
14889         }
14890
14891       /* Allocate storage for parameters and fill them in.  */
14892       TYPE_NFIELDS (ftype) = nparams;
14893       TYPE_FIELDS (ftype) = (struct field *)
14894         TYPE_ZALLOC (ftype, nparams * sizeof (struct field));
14895
14896       /* TYPE_FIELD_TYPE must never be NULL.  Pre-fill the array to ensure it
14897          even if we error out during the parameters reading below.  */
14898       for (iparams = 0; iparams < nparams; iparams++)
14899         TYPE_FIELD_TYPE (ftype, iparams) = void_type;
14900
14901       iparams = 0;
14902       child_die = die->child;
14903       while (child_die && child_die->tag)
14904         {
14905           if (child_die->tag == DW_TAG_formal_parameter)
14906             {
14907               struct type *arg_type;
14908
14909               /* DWARF version 2 has no clean way to discern C++
14910                  static and non-static member functions.  G++ helps
14911                  GDB by marking the first parameter for non-static
14912                  member functions (which is the this pointer) as
14913                  artificial.  We pass this information to
14914                  dwarf2_add_member_fn via TYPE_FIELD_ARTIFICIAL.
14915
14916                  DWARF version 3 added DW_AT_object_pointer, which GCC
14917                  4.5 does not yet generate.  */
14918               attr = dwarf2_attr (child_die, DW_AT_artificial, cu);
14919               if (attr)
14920                 TYPE_FIELD_ARTIFICIAL (ftype, iparams) = DW_UNSND (attr);
14921               else
14922                 TYPE_FIELD_ARTIFICIAL (ftype, iparams) = 0;
14923               arg_type = die_type (child_die, cu);
14924
14925               /* RealView does not mark THIS as const, which the testsuite
14926                  expects.  GCC marks THIS as const in method definitions,
14927                  but not in the class specifications (GCC PR 43053).  */
14928               if (cu->language == language_cplus && !TYPE_CONST (arg_type)
14929                   && TYPE_FIELD_ARTIFICIAL (ftype, iparams))
14930                 {
14931                   int is_this = 0;
14932                   struct dwarf2_cu *arg_cu = cu;
14933                   const char *name = dwarf2_name (child_die, cu);
14934
14935                   attr = dwarf2_attr (die, DW_AT_object_pointer, cu);
14936                   if (attr)
14937                     {
14938                       /* If the compiler emits this, use it.  */
14939                       if (follow_die_ref (die, attr, &arg_cu) == child_die)
14940                         is_this = 1;
14941                     }
14942                   else if (name && strcmp (name, "this") == 0)
14943                     /* Function definitions will have the argument names.  */
14944                     is_this = 1;
14945                   else if (name == NULL && iparams == 0)
14946                     /* Declarations may not have the names, so like
14947                        elsewhere in GDB, assume an artificial first
14948                        argument is "this".  */
14949                     is_this = 1;
14950
14951                   if (is_this)
14952                     arg_type = make_cv_type (1, TYPE_VOLATILE (arg_type),
14953                                              arg_type, 0);
14954                 }
14955
14956               TYPE_FIELD_TYPE (ftype, iparams) = arg_type;
14957               iparams++;
14958             }
14959           child_die = sibling_die (child_die);
14960         }
14961     }
14962
14963   return ftype;
14964 }
14965
14966 static struct type *
14967 read_typedef (struct die_info *die, struct dwarf2_cu *cu)
14968 {
14969   struct objfile *objfile = cu->objfile;
14970   const char *name = NULL;
14971   struct type *this_type, *target_type;
14972
14973   name = dwarf2_full_name (NULL, die, cu);
14974   this_type = init_type (objfile, TYPE_CODE_TYPEDEF, 0, name);
14975   TYPE_TARGET_STUB (this_type) = 1;
14976   set_die_type (die, this_type, cu);
14977   target_type = die_type (die, cu);
14978   if (target_type != this_type)
14979     TYPE_TARGET_TYPE (this_type) = target_type;
14980   else
14981     {
14982       /* Self-referential typedefs are, it seems, not allowed by the DWARF
14983          spec and cause infinite loops in GDB.  */
14984       complaint (&symfile_complaints,
14985                  _("Self-referential DW_TAG_typedef "
14986                    "- DIE at 0x%x [in module %s]"),
14987                  die->offset.sect_off, objfile_name (objfile));
14988       TYPE_TARGET_TYPE (this_type) = NULL;
14989     }
14990   return this_type;
14991 }
14992
14993 /* Allocate a floating-point type of size BITS and name NAME.  Pass NAME_HINT
14994    (which may be different from NAME) to the architecture back-end to allow
14995    it to guess the correct format if necessary.  */
14996
14997 static struct type *
14998 dwarf2_init_float_type (struct objfile *objfile, int bits, const char *name,
14999                         const char *name_hint)
15000 {
15001   struct gdbarch *gdbarch = get_objfile_arch (objfile);
15002   const struct floatformat **format;
15003   struct type *type;
15004
15005   format = gdbarch_floatformat_for_type (gdbarch, name_hint, bits);
15006   if (format)
15007     type = init_float_type (objfile, bits, name, format);
15008   else
15009     type = init_type (objfile, TYPE_CODE_ERROR, bits / TARGET_CHAR_BIT, name);
15010
15011   return type;
15012 }
15013
15014 /* Find a representation of a given base type and install
15015    it in the TYPE field of the die.  */
15016
15017 static struct type *
15018 read_base_type (struct die_info *die, struct dwarf2_cu *cu)
15019 {
15020   struct objfile *objfile = cu->objfile;
15021   struct type *type;
15022   struct attribute *attr;
15023   int encoding = 0, bits = 0;
15024   const char *name;
15025
15026   attr = dwarf2_attr (die, DW_AT_encoding, cu);
15027   if (attr)
15028     {
15029       encoding = DW_UNSND (attr);
15030     }
15031   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
15032   if (attr)
15033     {
15034       bits = DW_UNSND (attr) * TARGET_CHAR_BIT;
15035     }
15036   name = dwarf2_name (die, cu);
15037   if (!name)
15038     {
15039       complaint (&symfile_complaints,
15040                  _("DW_AT_name missing from DW_TAG_base_type"));
15041     }
15042
15043   switch (encoding)
15044     {
15045       case DW_ATE_address:
15046         /* Turn DW_ATE_address into a void * pointer.  */
15047         type = init_type (objfile, TYPE_CODE_VOID, 1, NULL);
15048         type = init_pointer_type (objfile, bits, name, type);
15049         break;
15050       case DW_ATE_boolean:
15051         type = init_boolean_type (objfile, bits, 1, name);
15052         break;
15053       case DW_ATE_complex_float:
15054         type = dwarf2_init_float_type (objfile, bits / 2, NULL, name);
15055         type = init_complex_type (objfile, name, type);
15056         break;
15057       case DW_ATE_decimal_float:
15058         type = init_decfloat_type (objfile, bits, name);
15059         break;
15060       case DW_ATE_float:
15061         type = dwarf2_init_float_type (objfile, bits, name, name);
15062         break;
15063       case DW_ATE_signed:
15064         type = init_integer_type (objfile, bits, 0, name);
15065         break;
15066       case DW_ATE_unsigned:
15067         if (cu->language == language_fortran
15068             && name
15069             && startswith (name, "character("))
15070           type = init_character_type (objfile, bits, 1, name);
15071         else
15072           type = init_integer_type (objfile, bits, 1, name);
15073         break;
15074       case DW_ATE_signed_char:
15075         if (cu->language == language_ada || cu->language == language_m2
15076             || cu->language == language_pascal
15077             || cu->language == language_fortran)
15078           type = init_character_type (objfile, bits, 0, name);
15079         else
15080           type = init_integer_type (objfile, bits, 0, name);
15081         break;
15082       case DW_ATE_unsigned_char:
15083         if (cu->language == language_ada || cu->language == language_m2
15084             || cu->language == language_pascal
15085             || cu->language == language_fortran
15086             || cu->language == language_rust)
15087           type = init_character_type (objfile, bits, 1, name);
15088         else
15089           type = init_integer_type (objfile, bits, 1, name);
15090         break;
15091       case DW_ATE_UTF:
15092         /* We just treat this as an integer and then recognize the
15093            type by name elsewhere.  */
15094         type = init_integer_type (objfile, bits, 0, name);
15095         break;
15096
15097       default:
15098         complaint (&symfile_complaints, _("unsupported DW_AT_encoding: '%s'"),
15099                    dwarf_type_encoding_name (encoding));
15100         type = init_type (objfile, TYPE_CODE_ERROR,
15101                           bits / TARGET_CHAR_BIT, name);
15102         break;
15103     }
15104
15105   if (name && strcmp (name, "char") == 0)
15106     TYPE_NOSIGN (type) = 1;
15107
15108   return set_die_type (die, type, cu);
15109 }
15110
15111 /* Parse dwarf attribute if it's a block, reference or constant and put the
15112    resulting value of the attribute into struct bound_prop.
15113    Returns 1 if ATTR could be resolved into PROP, 0 otherwise.  */
15114
15115 static int
15116 attr_to_dynamic_prop (const struct attribute *attr, struct die_info *die,
15117                       struct dwarf2_cu *cu, struct dynamic_prop *prop)
15118 {
15119   struct dwarf2_property_baton *baton;
15120   struct obstack *obstack = &cu->objfile->objfile_obstack;
15121
15122   if (attr == NULL || prop == NULL)
15123     return 0;
15124
15125   if (attr_form_is_block (attr))
15126     {
15127       baton = XOBNEW (obstack, struct dwarf2_property_baton);
15128       baton->referenced_type = NULL;
15129       baton->locexpr.per_cu = cu->per_cu;
15130       baton->locexpr.size = DW_BLOCK (attr)->size;
15131       baton->locexpr.data = DW_BLOCK (attr)->data;
15132       prop->data.baton = baton;
15133       prop->kind = PROP_LOCEXPR;
15134       gdb_assert (prop->data.baton != NULL);
15135     }
15136   else if (attr_form_is_ref (attr))
15137     {
15138       struct dwarf2_cu *target_cu = cu;
15139       struct die_info *target_die;
15140       struct attribute *target_attr;
15141
15142       target_die = follow_die_ref (die, attr, &target_cu);
15143       target_attr = dwarf2_attr (target_die, DW_AT_location, target_cu);
15144       if (target_attr == NULL)
15145         target_attr = dwarf2_attr (target_die, DW_AT_data_member_location,
15146                                    target_cu);
15147       if (target_attr == NULL)
15148         return 0;
15149
15150       switch (target_attr->name)
15151         {
15152           case DW_AT_location:
15153             if (attr_form_is_section_offset (target_attr))
15154               {
15155                 baton = XOBNEW (obstack, struct dwarf2_property_baton);
15156                 baton->referenced_type = die_type (target_die, target_cu);
15157                 fill_in_loclist_baton (cu, &baton->loclist, target_attr);
15158                 prop->data.baton = baton;
15159                 prop->kind = PROP_LOCLIST;
15160                 gdb_assert (prop->data.baton != NULL);
15161               }
15162             else if (attr_form_is_block (target_attr))
15163               {
15164                 baton = XOBNEW (obstack, struct dwarf2_property_baton);
15165                 baton->referenced_type = die_type (target_die, target_cu);
15166                 baton->locexpr.per_cu = cu->per_cu;
15167                 baton->locexpr.size = DW_BLOCK (target_attr)->size;
15168                 baton->locexpr.data = DW_BLOCK (target_attr)->data;
15169                 prop->data.baton = baton;
15170                 prop->kind = PROP_LOCEXPR;
15171                 gdb_assert (prop->data.baton != NULL);
15172               }
15173             else
15174               {
15175                 dwarf2_invalid_attrib_class_complaint ("DW_AT_location",
15176                                                        "dynamic property");
15177                 return 0;
15178               }
15179             break;
15180           case DW_AT_data_member_location:
15181             {
15182               LONGEST offset;
15183
15184               if (!handle_data_member_location (target_die, target_cu,
15185                                                 &offset))
15186                 return 0;
15187
15188               baton = XOBNEW (obstack, struct dwarf2_property_baton);
15189               baton->referenced_type = read_type_die (target_die->parent,
15190                                                       target_cu);
15191               baton->offset_info.offset = offset;
15192               baton->offset_info.type = die_type (target_die, target_cu);
15193               prop->data.baton = baton;
15194               prop->kind = PROP_ADDR_OFFSET;
15195               break;
15196             }
15197         }
15198     }
15199   else if (attr_form_is_constant (attr))
15200     {
15201       prop->data.const_val = dwarf2_get_attr_constant_value (attr, 0);
15202       prop->kind = PROP_CONST;
15203     }
15204   else
15205     {
15206       dwarf2_invalid_attrib_class_complaint (dwarf_form_name (attr->form),
15207                                              dwarf2_name (die, cu));
15208       return 0;
15209     }
15210
15211   return 1;
15212 }
15213
15214 /* Read the given DW_AT_subrange DIE.  */
15215
15216 static struct type *
15217 read_subrange_type (struct die_info *die, struct dwarf2_cu *cu)
15218 {
15219   struct type *base_type, *orig_base_type;
15220   struct type *range_type;
15221   struct attribute *attr;
15222   struct dynamic_prop low, high;
15223   int low_default_is_valid;
15224   int high_bound_is_count = 0;
15225   const char *name;
15226   LONGEST negative_mask;
15227
15228   orig_base_type = die_type (die, cu);
15229   /* If ORIG_BASE_TYPE is a typedef, it will not be TYPE_UNSIGNED,
15230      whereas the real type might be.  So, we use ORIG_BASE_TYPE when
15231      creating the range type, but we use the result of check_typedef
15232      when examining properties of the type.  */
15233   base_type = check_typedef (orig_base_type);
15234
15235   /* The die_type call above may have already set the type for this DIE.  */
15236   range_type = get_die_type (die, cu);
15237   if (range_type)
15238     return range_type;
15239
15240   low.kind = PROP_CONST;
15241   high.kind = PROP_CONST;
15242   high.data.const_val = 0;
15243
15244   /* Set LOW_DEFAULT_IS_VALID if current language and DWARF version allow
15245      omitting DW_AT_lower_bound.  */
15246   switch (cu->language)
15247     {
15248     case language_c:
15249     case language_cplus:
15250       low.data.const_val = 0;
15251       low_default_is_valid = 1;
15252       break;
15253     case language_fortran:
15254       low.data.const_val = 1;
15255       low_default_is_valid = 1;
15256       break;
15257     case language_d:
15258     case language_objc:
15259     case language_rust:
15260       low.data.const_val = 0;
15261       low_default_is_valid = (cu->header.version >= 4);
15262       break;
15263     case language_ada:
15264     case language_m2:
15265     case language_pascal:
15266       low.data.const_val = 1;
15267       low_default_is_valid = (cu->header.version >= 4);
15268       break;
15269     default:
15270       low.data.const_val = 0;
15271       low_default_is_valid = 0;
15272       break;
15273     }
15274
15275   attr = dwarf2_attr (die, DW_AT_lower_bound, cu);
15276   if (attr)
15277     attr_to_dynamic_prop (attr, die, cu, &low);
15278   else if (!low_default_is_valid)
15279     complaint (&symfile_complaints, _("Missing DW_AT_lower_bound "
15280                                       "- DIE at 0x%x [in module %s]"),
15281                die->offset.sect_off, objfile_name (cu->objfile));
15282
15283   attr = dwarf2_attr (die, DW_AT_upper_bound, cu);
15284   if (!attr_to_dynamic_prop (attr, die, cu, &high))
15285     {
15286       attr = dwarf2_attr (die, DW_AT_count, cu);
15287       if (attr_to_dynamic_prop (attr, die, cu, &high))
15288         {
15289           /* If bounds are constant do the final calculation here.  */
15290           if (low.kind == PROP_CONST && high.kind == PROP_CONST)
15291             high.data.const_val = low.data.const_val + high.data.const_val - 1;
15292           else
15293             high_bound_is_count = 1;
15294         }
15295     }
15296
15297   /* Dwarf-2 specifications explicitly allows to create subrange types
15298      without specifying a base type.
15299      In that case, the base type must be set to the type of
15300      the lower bound, upper bound or count, in that order, if any of these
15301      three attributes references an object that has a type.
15302      If no base type is found, the Dwarf-2 specifications say that
15303      a signed integer type of size equal to the size of an address should
15304      be used.
15305      For the following C code: `extern char gdb_int [];'
15306      GCC produces an empty range DIE.
15307      FIXME: muller/2010-05-28: Possible references to object for low bound,
15308      high bound or count are not yet handled by this code.  */
15309   if (TYPE_CODE (base_type) == TYPE_CODE_VOID)
15310     {
15311       struct objfile *objfile = cu->objfile;
15312       struct gdbarch *gdbarch = get_objfile_arch (objfile);
15313       int addr_size = gdbarch_addr_bit (gdbarch) /8;
15314       struct type *int_type = objfile_type (objfile)->builtin_int;
15315
15316       /* Test "int", "long int", and "long long int" objfile types,
15317          and select the first one having a size above or equal to the
15318          architecture address size.  */
15319       if (int_type && TYPE_LENGTH (int_type) >= addr_size)
15320         base_type = int_type;
15321       else
15322         {
15323           int_type = objfile_type (objfile)->builtin_long;
15324           if (int_type && TYPE_LENGTH (int_type) >= addr_size)
15325             base_type = int_type;
15326           else
15327             {
15328               int_type = objfile_type (objfile)->builtin_long_long;
15329               if (int_type && TYPE_LENGTH (int_type) >= addr_size)
15330                 base_type = int_type;
15331             }
15332         }
15333     }
15334
15335   /* Normally, the DWARF producers are expected to use a signed
15336      constant form (Eg. DW_FORM_sdata) to express negative bounds.
15337      But this is unfortunately not always the case, as witnessed
15338      with GCC, for instance, where the ambiguous DW_FORM_dataN form
15339      is used instead.  To work around that ambiguity, we treat
15340      the bounds as signed, and thus sign-extend their values, when
15341      the base type is signed.  */
15342   negative_mask =
15343     -((LONGEST) 1 << (TYPE_LENGTH (base_type) * TARGET_CHAR_BIT - 1));
15344   if (low.kind == PROP_CONST
15345       && !TYPE_UNSIGNED (base_type) && (low.data.const_val & negative_mask))
15346     low.data.const_val |= negative_mask;
15347   if (high.kind == PROP_CONST
15348       && !TYPE_UNSIGNED (base_type) && (high.data.const_val & negative_mask))
15349     high.data.const_val |= negative_mask;
15350
15351   range_type = create_range_type (NULL, orig_base_type, &low, &high);
15352
15353   if (high_bound_is_count)
15354     TYPE_RANGE_DATA (range_type)->flag_upper_bound_is_count = 1;
15355
15356   /* Ada expects an empty array on no boundary attributes.  */
15357   if (attr == NULL && cu->language != language_ada)
15358     TYPE_HIGH_BOUND_KIND (range_type) = PROP_UNDEFINED;
15359
15360   name = dwarf2_name (die, cu);
15361   if (name)
15362     TYPE_NAME (range_type) = name;
15363
15364   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
15365   if (attr)
15366     TYPE_LENGTH (range_type) = DW_UNSND (attr);
15367
15368   set_die_type (die, range_type, cu);
15369
15370   /* set_die_type should be already done.  */
15371   set_descriptive_type (range_type, die, cu);
15372
15373   return range_type;
15374 }
15375
15376 static struct type *
15377 read_unspecified_type (struct die_info *die, struct dwarf2_cu *cu)
15378 {
15379   struct type *type;
15380
15381   /* For now, we only support the C meaning of an unspecified type: void.  */
15382
15383   type = init_type (cu->objfile, TYPE_CODE_VOID, 0, NULL);
15384   TYPE_NAME (type) = dwarf2_name (die, cu);
15385
15386   return set_die_type (die, type, cu);
15387 }
15388
15389 /* Read a single die and all its descendents.  Set the die's sibling
15390    field to NULL; set other fields in the die correctly, and set all
15391    of the descendents' fields correctly.  Set *NEW_INFO_PTR to the
15392    location of the info_ptr after reading all of those dies.  PARENT
15393    is the parent of the die in question.  */
15394
15395 static struct die_info *
15396 read_die_and_children (const struct die_reader_specs *reader,
15397                        const gdb_byte *info_ptr,
15398                        const gdb_byte **new_info_ptr,
15399                        struct die_info *parent)
15400 {
15401   struct die_info *die;
15402   const gdb_byte *cur_ptr;
15403   int has_children;
15404
15405   cur_ptr = read_full_die_1 (reader, &die, info_ptr, &has_children, 0);
15406   if (die == NULL)
15407     {
15408       *new_info_ptr = cur_ptr;
15409       return NULL;
15410     }
15411   store_in_ref_table (die, reader->cu);
15412
15413   if (has_children)
15414     die->child = read_die_and_siblings_1 (reader, cur_ptr, new_info_ptr, die);
15415   else
15416     {
15417       die->child = NULL;
15418       *new_info_ptr = cur_ptr;
15419     }
15420
15421   die->sibling = NULL;
15422   die->parent = parent;
15423   return die;
15424 }
15425
15426 /* Read a die, all of its descendents, and all of its siblings; set
15427    all of the fields of all of the dies correctly.  Arguments are as
15428    in read_die_and_children.  */
15429
15430 static struct die_info *
15431 read_die_and_siblings_1 (const struct die_reader_specs *reader,
15432                          const gdb_byte *info_ptr,
15433                          const gdb_byte **new_info_ptr,
15434                          struct die_info *parent)
15435 {
15436   struct die_info *first_die, *last_sibling;
15437   const gdb_byte *cur_ptr;
15438
15439   cur_ptr = info_ptr;
15440   first_die = last_sibling = NULL;
15441
15442   while (1)
15443     {
15444       struct die_info *die
15445         = read_die_and_children (reader, cur_ptr, &cur_ptr, parent);
15446
15447       if (die == NULL)
15448         {
15449           *new_info_ptr = cur_ptr;
15450           return first_die;
15451         }
15452
15453       if (!first_die)
15454         first_die = die;
15455       else
15456         last_sibling->sibling = die;
15457
15458       last_sibling = die;
15459     }
15460 }
15461
15462 /* Read a die, all of its descendents, and all of its siblings; set
15463    all of the fields of all of the dies correctly.  Arguments are as
15464    in read_die_and_children.
15465    This the main entry point for reading a DIE and all its children.  */
15466
15467 static struct die_info *
15468 read_die_and_siblings (const struct die_reader_specs *reader,
15469                        const gdb_byte *info_ptr,
15470                        const gdb_byte **new_info_ptr,
15471                        struct die_info *parent)
15472 {
15473   struct die_info *die = read_die_and_siblings_1 (reader, info_ptr,
15474                                                   new_info_ptr, parent);
15475
15476   if (dwarf_die_debug)
15477     {
15478       fprintf_unfiltered (gdb_stdlog,
15479                           "Read die from %s@0x%x of %s:\n",
15480                           get_section_name (reader->die_section),
15481                           (unsigned) (info_ptr - reader->die_section->buffer),
15482                           bfd_get_filename (reader->abfd));
15483       dump_die (die, dwarf_die_debug);
15484     }
15485
15486   return die;
15487 }
15488
15489 /* Read a die and all its attributes, leave space for NUM_EXTRA_ATTRS
15490    attributes.
15491    The caller is responsible for filling in the extra attributes
15492    and updating (*DIEP)->num_attrs.
15493    Set DIEP to point to a newly allocated die with its information,
15494    except for its child, sibling, and parent fields.
15495    Set HAS_CHILDREN to tell whether the die has children or not.  */
15496
15497 static const gdb_byte *
15498 read_full_die_1 (const struct die_reader_specs *reader,
15499                  struct die_info **diep, const gdb_byte *info_ptr,
15500                  int *has_children, int num_extra_attrs)
15501 {
15502   unsigned int abbrev_number, bytes_read, i;
15503   sect_offset offset;
15504   struct abbrev_info *abbrev;
15505   struct die_info *die;
15506   struct dwarf2_cu *cu = reader->cu;
15507   bfd *abfd = reader->abfd;
15508
15509   offset.sect_off = info_ptr - reader->buffer;
15510   abbrev_number = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
15511   info_ptr += bytes_read;
15512   if (!abbrev_number)
15513     {
15514       *diep = NULL;
15515       *has_children = 0;
15516       return info_ptr;
15517     }
15518
15519   abbrev = abbrev_table_lookup_abbrev (cu->abbrev_table, abbrev_number);
15520   if (!abbrev)
15521     error (_("Dwarf Error: could not find abbrev number %d [in module %s]"),
15522            abbrev_number,
15523            bfd_get_filename (abfd));
15524
15525   die = dwarf_alloc_die (cu, abbrev->num_attrs + num_extra_attrs);
15526   die->offset = offset;
15527   die->tag = abbrev->tag;
15528   die->abbrev = abbrev_number;
15529
15530   /* Make the result usable.
15531      The caller needs to update num_attrs after adding the extra
15532      attributes.  */
15533   die->num_attrs = abbrev->num_attrs;
15534
15535   for (i = 0; i < abbrev->num_attrs; ++i)
15536     info_ptr = read_attribute (reader, &die->attrs[i], &abbrev->attrs[i],
15537                                info_ptr);
15538
15539   *diep = die;
15540   *has_children = abbrev->has_children;
15541   return info_ptr;
15542 }
15543
15544 /* Read a die and all its attributes.
15545    Set DIEP to point to a newly allocated die with its information,
15546    except for its child, sibling, and parent fields.
15547    Set HAS_CHILDREN to tell whether the die has children or not.  */
15548
15549 static const gdb_byte *
15550 read_full_die (const struct die_reader_specs *reader,
15551                struct die_info **diep, const gdb_byte *info_ptr,
15552                int *has_children)
15553 {
15554   const gdb_byte *result;
15555
15556   result = read_full_die_1 (reader, diep, info_ptr, has_children, 0);
15557
15558   if (dwarf_die_debug)
15559     {
15560       fprintf_unfiltered (gdb_stdlog,
15561                           "Read die from %s@0x%x of %s:\n",
15562                           get_section_name (reader->die_section),
15563                           (unsigned) (info_ptr - reader->die_section->buffer),
15564                           bfd_get_filename (reader->abfd));
15565       dump_die (*diep, dwarf_die_debug);
15566     }
15567
15568   return result;
15569 }
15570 \f
15571 /* Abbreviation tables.
15572
15573    In DWARF version 2, the description of the debugging information is
15574    stored in a separate .debug_abbrev section.  Before we read any
15575    dies from a section we read in all abbreviations and install them
15576    in a hash table.  */
15577
15578 /* Allocate space for a struct abbrev_info object in ABBREV_TABLE.  */
15579
15580 static struct abbrev_info *
15581 abbrev_table_alloc_abbrev (struct abbrev_table *abbrev_table)
15582 {
15583   struct abbrev_info *abbrev;
15584
15585   abbrev = XOBNEW (&abbrev_table->abbrev_obstack, struct abbrev_info);
15586   memset (abbrev, 0, sizeof (struct abbrev_info));
15587
15588   return abbrev;
15589 }
15590
15591 /* Add an abbreviation to the table.  */
15592
15593 static void
15594 abbrev_table_add_abbrev (struct abbrev_table *abbrev_table,
15595                          unsigned int abbrev_number,
15596                          struct abbrev_info *abbrev)
15597 {
15598   unsigned int hash_number;
15599
15600   hash_number = abbrev_number % ABBREV_HASH_SIZE;
15601   abbrev->next = abbrev_table->abbrevs[hash_number];
15602   abbrev_table->abbrevs[hash_number] = abbrev;
15603 }
15604
15605 /* Look up an abbrev in the table.
15606    Returns NULL if the abbrev is not found.  */
15607
15608 static struct abbrev_info *
15609 abbrev_table_lookup_abbrev (const struct abbrev_table *abbrev_table,
15610                             unsigned int abbrev_number)
15611 {
15612   unsigned int hash_number;
15613   struct abbrev_info *abbrev;
15614
15615   hash_number = abbrev_number % ABBREV_HASH_SIZE;
15616   abbrev = abbrev_table->abbrevs[hash_number];
15617
15618   while (abbrev)
15619     {
15620       if (abbrev->number == abbrev_number)
15621         return abbrev;
15622       abbrev = abbrev->next;
15623     }
15624   return NULL;
15625 }
15626
15627 /* Read in an abbrev table.  */
15628
15629 static struct abbrev_table *
15630 abbrev_table_read_table (struct dwarf2_section_info *section,
15631                          sect_offset offset)
15632 {
15633   struct objfile *objfile = dwarf2_per_objfile->objfile;
15634   bfd *abfd = get_section_bfd_owner (section);
15635   struct abbrev_table *abbrev_table;
15636   const gdb_byte *abbrev_ptr;
15637   struct abbrev_info *cur_abbrev;
15638   unsigned int abbrev_number, bytes_read, abbrev_name;
15639   unsigned int abbrev_form;
15640   struct attr_abbrev *cur_attrs;
15641   unsigned int allocated_attrs;
15642
15643   abbrev_table = XNEW (struct abbrev_table);
15644   abbrev_table->offset = offset;
15645   obstack_init (&abbrev_table->abbrev_obstack);
15646   abbrev_table->abbrevs =
15647     XOBNEWVEC (&abbrev_table->abbrev_obstack, struct abbrev_info *,
15648                ABBREV_HASH_SIZE);
15649   memset (abbrev_table->abbrevs, 0,
15650           ABBREV_HASH_SIZE * sizeof (struct abbrev_info *));
15651
15652   dwarf2_read_section (objfile, section);
15653   abbrev_ptr = section->buffer + offset.sect_off;
15654   abbrev_number = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
15655   abbrev_ptr += bytes_read;
15656
15657   allocated_attrs = ATTR_ALLOC_CHUNK;
15658   cur_attrs = XNEWVEC (struct attr_abbrev, allocated_attrs);
15659
15660   /* Loop until we reach an abbrev number of 0.  */
15661   while (abbrev_number)
15662     {
15663       cur_abbrev = abbrev_table_alloc_abbrev (abbrev_table);
15664
15665       /* read in abbrev header */
15666       cur_abbrev->number = abbrev_number;
15667       cur_abbrev->tag
15668         = (enum dwarf_tag) read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
15669       abbrev_ptr += bytes_read;
15670       cur_abbrev->has_children = read_1_byte (abfd, abbrev_ptr);
15671       abbrev_ptr += 1;
15672
15673       /* now read in declarations */
15674       for (;;)
15675         {
15676           LONGEST implicit_const;
15677
15678           abbrev_name = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
15679           abbrev_ptr += bytes_read;
15680           abbrev_form = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
15681           abbrev_ptr += bytes_read;
15682           if (abbrev_form == DW_FORM_implicit_const)
15683             {
15684               implicit_const = read_signed_leb128 (abfd, abbrev_ptr,
15685                                                    &bytes_read);
15686               abbrev_ptr += bytes_read;
15687             }
15688           else
15689             {
15690               /* Initialize it due to a false compiler warning.  */
15691               implicit_const = -1;
15692             }
15693
15694           if (abbrev_name == 0)
15695             break;
15696
15697           if (cur_abbrev->num_attrs == allocated_attrs)
15698             {
15699               allocated_attrs += ATTR_ALLOC_CHUNK;
15700               cur_attrs
15701                 = XRESIZEVEC (struct attr_abbrev, cur_attrs, allocated_attrs);
15702             }
15703
15704           cur_attrs[cur_abbrev->num_attrs].name
15705             = (enum dwarf_attribute) abbrev_name;
15706           cur_attrs[cur_abbrev->num_attrs].form
15707             = (enum dwarf_form) abbrev_form;
15708           cur_attrs[cur_abbrev->num_attrs].implicit_const = implicit_const;
15709           ++cur_abbrev->num_attrs;
15710         }
15711
15712       cur_abbrev->attrs =
15713         XOBNEWVEC (&abbrev_table->abbrev_obstack, struct attr_abbrev,
15714                    cur_abbrev->num_attrs);
15715       memcpy (cur_abbrev->attrs, cur_attrs,
15716               cur_abbrev->num_attrs * sizeof (struct attr_abbrev));
15717
15718       abbrev_table_add_abbrev (abbrev_table, abbrev_number, cur_abbrev);
15719
15720       /* Get next abbreviation.
15721          Under Irix6 the abbreviations for a compilation unit are not
15722          always properly terminated with an abbrev number of 0.
15723          Exit loop if we encounter an abbreviation which we have
15724          already read (which means we are about to read the abbreviations
15725          for the next compile unit) or if the end of the abbreviation
15726          table is reached.  */
15727       if ((unsigned int) (abbrev_ptr - section->buffer) >= section->size)
15728         break;
15729       abbrev_number = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
15730       abbrev_ptr += bytes_read;
15731       if (abbrev_table_lookup_abbrev (abbrev_table, abbrev_number) != NULL)
15732         break;
15733     }
15734
15735   xfree (cur_attrs);
15736   return abbrev_table;
15737 }
15738
15739 /* Free the resources held by ABBREV_TABLE.  */
15740
15741 static void
15742 abbrev_table_free (struct abbrev_table *abbrev_table)
15743 {
15744   obstack_free (&abbrev_table->abbrev_obstack, NULL);
15745   xfree (abbrev_table);
15746 }
15747
15748 /* Same as abbrev_table_free but as a cleanup.
15749    We pass in a pointer to the pointer to the table so that we can
15750    set the pointer to NULL when we're done.  It also simplifies
15751    build_type_psymtabs_1.  */
15752
15753 static void
15754 abbrev_table_free_cleanup (void *table_ptr)
15755 {
15756   struct abbrev_table **abbrev_table_ptr = (struct abbrev_table **) table_ptr;
15757
15758   if (*abbrev_table_ptr != NULL)
15759     abbrev_table_free (*abbrev_table_ptr);
15760   *abbrev_table_ptr = NULL;
15761 }
15762
15763 /* Read the abbrev table for CU from ABBREV_SECTION.  */
15764
15765 static void
15766 dwarf2_read_abbrevs (struct dwarf2_cu *cu,
15767                      struct dwarf2_section_info *abbrev_section)
15768 {
15769   cu->abbrev_table =
15770     abbrev_table_read_table (abbrev_section, cu->header.abbrev_offset);
15771 }
15772
15773 /* Release the memory used by the abbrev table for a compilation unit.  */
15774
15775 static void
15776 dwarf2_free_abbrev_table (void *ptr_to_cu)
15777 {
15778   struct dwarf2_cu *cu = (struct dwarf2_cu *) ptr_to_cu;
15779
15780   if (cu->abbrev_table != NULL)
15781     abbrev_table_free (cu->abbrev_table);
15782   /* Set this to NULL so that we SEGV if we try to read it later,
15783      and also because free_comp_unit verifies this is NULL.  */
15784   cu->abbrev_table = NULL;
15785 }
15786 \f
15787 /* Returns nonzero if TAG represents a type that we might generate a partial
15788    symbol for.  */
15789
15790 static int
15791 is_type_tag_for_partial (int tag)
15792 {
15793   switch (tag)
15794     {
15795 #if 0
15796     /* Some types that would be reasonable to generate partial symbols for,
15797        that we don't at present.  */
15798     case DW_TAG_array_type:
15799     case DW_TAG_file_type:
15800     case DW_TAG_ptr_to_member_type:
15801     case DW_TAG_set_type:
15802     case DW_TAG_string_type:
15803     case DW_TAG_subroutine_type:
15804 #endif
15805     case DW_TAG_base_type:
15806     case DW_TAG_class_type:
15807     case DW_TAG_interface_type:
15808     case DW_TAG_enumeration_type:
15809     case DW_TAG_structure_type:
15810     case DW_TAG_subrange_type:
15811     case DW_TAG_typedef:
15812     case DW_TAG_union_type:
15813       return 1;
15814     default:
15815       return 0;
15816     }
15817 }
15818
15819 /* Load all DIEs that are interesting for partial symbols into memory.  */
15820
15821 static struct partial_die_info *
15822 load_partial_dies (const struct die_reader_specs *reader,
15823                    const gdb_byte *info_ptr, int building_psymtab)
15824 {
15825   struct dwarf2_cu *cu = reader->cu;
15826   struct objfile *objfile = cu->objfile;
15827   struct partial_die_info *part_die;
15828   struct partial_die_info *parent_die, *last_die, *first_die = NULL;
15829   struct abbrev_info *abbrev;
15830   unsigned int bytes_read;
15831   unsigned int load_all = 0;
15832   int nesting_level = 1;
15833
15834   parent_die = NULL;
15835   last_die = NULL;
15836
15837   gdb_assert (cu->per_cu != NULL);
15838   if (cu->per_cu->load_all_dies)
15839     load_all = 1;
15840
15841   cu->partial_dies
15842     = htab_create_alloc_ex (cu->header.length / 12,
15843                             partial_die_hash,
15844                             partial_die_eq,
15845                             NULL,
15846                             &cu->comp_unit_obstack,
15847                             hashtab_obstack_allocate,
15848                             dummy_obstack_deallocate);
15849
15850   part_die = XOBNEW (&cu->comp_unit_obstack, struct partial_die_info);
15851
15852   while (1)
15853     {
15854       abbrev = peek_die_abbrev (info_ptr, &bytes_read, cu);
15855
15856       /* A NULL abbrev means the end of a series of children.  */
15857       if (abbrev == NULL)
15858         {
15859           if (--nesting_level == 0)
15860             {
15861               /* PART_DIE was probably the last thing allocated on the
15862                  comp_unit_obstack, so we could call obstack_free
15863                  here.  We don't do that because the waste is small,
15864                  and will be cleaned up when we're done with this
15865                  compilation unit.  This way, we're also more robust
15866                  against other users of the comp_unit_obstack.  */
15867               return first_die;
15868             }
15869           info_ptr += bytes_read;
15870           last_die = parent_die;
15871           parent_die = parent_die->die_parent;
15872           continue;
15873         }
15874
15875       /* Check for template arguments.  We never save these; if
15876          they're seen, we just mark the parent, and go on our way.  */
15877       if (parent_die != NULL
15878           && cu->language == language_cplus
15879           && (abbrev->tag == DW_TAG_template_type_param
15880               || abbrev->tag == DW_TAG_template_value_param))
15881         {
15882           parent_die->has_template_arguments = 1;
15883
15884           if (!load_all)
15885             {
15886               /* We don't need a partial DIE for the template argument.  */
15887               info_ptr = skip_one_die (reader, info_ptr + bytes_read, abbrev);
15888               continue;
15889             }
15890         }
15891
15892       /* We only recurse into c++ subprograms looking for template arguments.
15893          Skip their other children.  */
15894       if (!load_all
15895           && cu->language == language_cplus
15896           && parent_die != NULL
15897           && parent_die->tag == DW_TAG_subprogram)
15898         {
15899           info_ptr = skip_one_die (reader, info_ptr + bytes_read, abbrev);
15900           continue;
15901         }
15902
15903       /* Check whether this DIE is interesting enough to save.  Normally
15904          we would not be interested in members here, but there may be
15905          later variables referencing them via DW_AT_specification (for
15906          static members).  */
15907       if (!load_all
15908           && !is_type_tag_for_partial (abbrev->tag)
15909           && abbrev->tag != DW_TAG_constant
15910           && abbrev->tag != DW_TAG_enumerator
15911           && abbrev->tag != DW_TAG_subprogram
15912           && abbrev->tag != DW_TAG_lexical_block
15913           && abbrev->tag != DW_TAG_variable
15914           && abbrev->tag != DW_TAG_namespace
15915           && abbrev->tag != DW_TAG_module
15916           && abbrev->tag != DW_TAG_member
15917           && abbrev->tag != DW_TAG_imported_unit
15918           && abbrev->tag != DW_TAG_imported_declaration)
15919         {
15920           /* Otherwise we skip to the next sibling, if any.  */
15921           info_ptr = skip_one_die (reader, info_ptr + bytes_read, abbrev);
15922           continue;
15923         }
15924
15925       info_ptr = read_partial_die (reader, part_die, abbrev, bytes_read,
15926                                    info_ptr);
15927
15928       /* This two-pass algorithm for processing partial symbols has a
15929          high cost in cache pressure.  Thus, handle some simple cases
15930          here which cover the majority of C partial symbols.  DIEs
15931          which neither have specification tags in them, nor could have
15932          specification tags elsewhere pointing at them, can simply be
15933          processed and discarded.
15934
15935          This segment is also optional; scan_partial_symbols and
15936          add_partial_symbol will handle these DIEs if we chain
15937          them in normally.  When compilers which do not emit large
15938          quantities of duplicate debug information are more common,
15939          this code can probably be removed.  */
15940
15941       /* Any complete simple types at the top level (pretty much all
15942          of them, for a language without namespaces), can be processed
15943          directly.  */
15944       if (parent_die == NULL
15945           && part_die->has_specification == 0
15946           && part_die->is_declaration == 0
15947           && ((part_die->tag == DW_TAG_typedef && !part_die->has_children)
15948               || part_die->tag == DW_TAG_base_type
15949               || part_die->tag == DW_TAG_subrange_type))
15950         {
15951           if (building_psymtab && part_die->name != NULL)
15952             add_psymbol_to_list (part_die->name, strlen (part_die->name), 0,
15953                                  VAR_DOMAIN, LOC_TYPEDEF,
15954                                  &objfile->static_psymbols,
15955                                  0, cu->language, objfile);
15956           info_ptr = locate_pdi_sibling (reader, part_die, info_ptr);
15957           continue;
15958         }
15959
15960       /* The exception for DW_TAG_typedef with has_children above is
15961          a workaround of GCC PR debug/47510.  In the case of this complaint
15962          type_name_no_tag_or_error will error on such types later.
15963
15964          GDB skipped children of DW_TAG_typedef by the shortcut above and then
15965          it could not find the child DIEs referenced later, this is checked
15966          above.  In correct DWARF DW_TAG_typedef should have no children.  */
15967
15968       if (part_die->tag == DW_TAG_typedef && part_die->has_children)
15969         complaint (&symfile_complaints,
15970                    _("DW_TAG_typedef has childen - GCC PR debug/47510 bug "
15971                      "- DIE at 0x%x [in module %s]"),
15972                    part_die->offset.sect_off, objfile_name (objfile));
15973
15974       /* If we're at the second level, and we're an enumerator, and
15975          our parent has no specification (meaning possibly lives in a
15976          namespace elsewhere), then we can add the partial symbol now
15977          instead of queueing it.  */
15978       if (part_die->tag == DW_TAG_enumerator
15979           && parent_die != NULL
15980           && parent_die->die_parent == NULL
15981           && parent_die->tag == DW_TAG_enumeration_type
15982           && parent_die->has_specification == 0)
15983         {
15984           if (part_die->name == NULL)
15985             complaint (&symfile_complaints,
15986                        _("malformed enumerator DIE ignored"));
15987           else if (building_psymtab)
15988             add_psymbol_to_list (part_die->name, strlen (part_die->name), 0,
15989                                  VAR_DOMAIN, LOC_CONST,
15990                                  cu->language == language_cplus
15991                                  ? &objfile->global_psymbols
15992                                  : &objfile->static_psymbols,
15993                                  0, cu->language, objfile);
15994
15995           info_ptr = locate_pdi_sibling (reader, part_die, info_ptr);
15996           continue;
15997         }
15998
15999       /* We'll save this DIE so link it in.  */
16000       part_die->die_parent = parent_die;
16001       part_die->die_sibling = NULL;
16002       part_die->die_child = NULL;
16003
16004       if (last_die && last_die == parent_die)
16005         last_die->die_child = part_die;
16006       else if (last_die)
16007         last_die->die_sibling = part_die;
16008
16009       last_die = part_die;
16010
16011       if (first_die == NULL)
16012         first_die = part_die;
16013
16014       /* Maybe add the DIE to the hash table.  Not all DIEs that we
16015          find interesting need to be in the hash table, because we
16016          also have the parent/sibling/child chains; only those that we
16017          might refer to by offset later during partial symbol reading.
16018
16019          For now this means things that might have be the target of a
16020          DW_AT_specification, DW_AT_abstract_origin, or
16021          DW_AT_extension.  DW_AT_extension will refer only to
16022          namespaces; DW_AT_abstract_origin refers to functions (and
16023          many things under the function DIE, but we do not recurse
16024          into function DIEs during partial symbol reading) and
16025          possibly variables as well; DW_AT_specification refers to
16026          declarations.  Declarations ought to have the DW_AT_declaration
16027          flag.  It happens that GCC forgets to put it in sometimes, but
16028          only for functions, not for types.
16029
16030          Adding more things than necessary to the hash table is harmless
16031          except for the performance cost.  Adding too few will result in
16032          wasted time in find_partial_die, when we reread the compilation
16033          unit with load_all_dies set.  */
16034
16035       if (load_all
16036           || abbrev->tag == DW_TAG_constant
16037           || abbrev->tag == DW_TAG_subprogram
16038           || abbrev->tag == DW_TAG_variable
16039           || abbrev->tag == DW_TAG_namespace
16040           || part_die->is_declaration)
16041         {
16042           void **slot;
16043
16044           slot = htab_find_slot_with_hash (cu->partial_dies, part_die,
16045                                            part_die->offset.sect_off, INSERT);
16046           *slot = part_die;
16047         }
16048
16049       part_die = XOBNEW (&cu->comp_unit_obstack, struct partial_die_info);
16050
16051       /* For some DIEs we want to follow their children (if any).  For C
16052          we have no reason to follow the children of structures; for other
16053          languages we have to, so that we can get at method physnames
16054          to infer fully qualified class names, for DW_AT_specification,
16055          and for C++ template arguments.  For C++, we also look one level
16056          inside functions to find template arguments (if the name of the
16057          function does not already contain the template arguments).
16058
16059          For Ada, we need to scan the children of subprograms and lexical
16060          blocks as well because Ada allows the definition of nested
16061          entities that could be interesting for the debugger, such as
16062          nested subprograms for instance.  */
16063       if (last_die->has_children
16064           && (load_all
16065               || last_die->tag == DW_TAG_namespace
16066               || last_die->tag == DW_TAG_module
16067               || last_die->tag == DW_TAG_enumeration_type
16068               || (cu->language == language_cplus
16069                   && last_die->tag == DW_TAG_subprogram
16070                   && (last_die->name == NULL
16071                       || strchr (last_die->name, '<') == NULL))
16072               || (cu->language != language_c
16073                   && (last_die->tag == DW_TAG_class_type
16074                       || last_die->tag == DW_TAG_interface_type
16075                       || last_die->tag == DW_TAG_structure_type
16076                       || last_die->tag == DW_TAG_union_type))
16077               || (cu->language == language_ada
16078                   && (last_die->tag == DW_TAG_subprogram
16079                       || last_die->tag == DW_TAG_lexical_block))))
16080         {
16081           nesting_level++;
16082           parent_die = last_die;
16083           continue;
16084         }
16085
16086       /* Otherwise we skip to the next sibling, if any.  */
16087       info_ptr = locate_pdi_sibling (reader, last_die, info_ptr);
16088
16089       /* Back to the top, do it again.  */
16090     }
16091 }
16092
16093 /* Read a minimal amount of information into the minimal die structure.  */
16094
16095 static const gdb_byte *
16096 read_partial_die (const struct die_reader_specs *reader,
16097                   struct partial_die_info *part_die,
16098                   struct abbrev_info *abbrev, unsigned int abbrev_len,
16099                   const gdb_byte *info_ptr)
16100 {
16101   struct dwarf2_cu *cu = reader->cu;
16102   struct objfile *objfile = cu->objfile;
16103   const gdb_byte *buffer = reader->buffer;
16104   unsigned int i;
16105   struct attribute attr;
16106   int has_low_pc_attr = 0;
16107   int has_high_pc_attr = 0;
16108   int high_pc_relative = 0;
16109
16110   memset (part_die, 0, sizeof (struct partial_die_info));
16111
16112   part_die->offset.sect_off = info_ptr - buffer;
16113
16114   info_ptr += abbrev_len;
16115
16116   if (abbrev == NULL)
16117     return info_ptr;
16118
16119   part_die->tag = abbrev->tag;
16120   part_die->has_children = abbrev->has_children;
16121
16122   for (i = 0; i < abbrev->num_attrs; ++i)
16123     {
16124       info_ptr = read_attribute (reader, &attr, &abbrev->attrs[i], info_ptr);
16125
16126       /* Store the data if it is of an attribute we want to keep in a
16127          partial symbol table.  */
16128       switch (attr.name)
16129         {
16130         case DW_AT_name:
16131           switch (part_die->tag)
16132             {
16133             case DW_TAG_compile_unit:
16134             case DW_TAG_partial_unit:
16135             case DW_TAG_type_unit:
16136               /* Compilation units have a DW_AT_name that is a filename, not
16137                  a source language identifier.  */
16138             case DW_TAG_enumeration_type:
16139             case DW_TAG_enumerator:
16140               /* These tags always have simple identifiers already; no need
16141                  to canonicalize them.  */
16142               part_die->name = DW_STRING (&attr);
16143               break;
16144             default:
16145               part_die->name
16146                 = dwarf2_canonicalize_name (DW_STRING (&attr), cu,
16147                                             &objfile->per_bfd->storage_obstack);
16148               break;
16149             }
16150           break;
16151         case DW_AT_linkage_name:
16152         case DW_AT_MIPS_linkage_name:
16153           /* Note that both forms of linkage name might appear.  We
16154              assume they will be the same, and we only store the last
16155              one we see.  */
16156           if (cu->language == language_ada)
16157             part_die->name = DW_STRING (&attr);
16158           part_die->linkage_name = DW_STRING (&attr);
16159           break;
16160         case DW_AT_low_pc:
16161           has_low_pc_attr = 1;
16162           part_die->lowpc = attr_value_as_address (&attr);
16163           break;
16164         case DW_AT_high_pc:
16165           has_high_pc_attr = 1;
16166           part_die->highpc = attr_value_as_address (&attr);
16167           if (cu->header.version >= 4 && attr_form_is_constant (&attr))
16168                 high_pc_relative = 1;
16169           break;
16170         case DW_AT_location:
16171           /* Support the .debug_loc offsets.  */
16172           if (attr_form_is_block (&attr))
16173             {
16174                part_die->d.locdesc = DW_BLOCK (&attr);
16175             }
16176           else if (attr_form_is_section_offset (&attr))
16177             {
16178               dwarf2_complex_location_expr_complaint ();
16179             }
16180           else
16181             {
16182               dwarf2_invalid_attrib_class_complaint ("DW_AT_location",
16183                                                      "partial symbol information");
16184             }
16185           break;
16186         case DW_AT_external:
16187           part_die->is_external = DW_UNSND (&attr);
16188           break;
16189         case DW_AT_declaration:
16190           part_die->is_declaration = DW_UNSND (&attr);
16191           break;
16192         case DW_AT_type:
16193           part_die->has_type = 1;
16194           break;
16195         case DW_AT_abstract_origin:
16196         case DW_AT_specification:
16197         case DW_AT_extension:
16198           part_die->has_specification = 1;
16199           part_die->spec_offset = dwarf2_get_ref_die_offset (&attr);
16200           part_die->spec_is_dwz = (attr.form == DW_FORM_GNU_ref_alt
16201                                    || cu->per_cu->is_dwz);
16202           break;
16203         case DW_AT_sibling:
16204           /* Ignore absolute siblings, they might point outside of
16205              the current compile unit.  */
16206           if (attr.form == DW_FORM_ref_addr)
16207             complaint (&symfile_complaints,
16208                        _("ignoring absolute DW_AT_sibling"));
16209           else
16210             {
16211               unsigned int off = dwarf2_get_ref_die_offset (&attr).sect_off;
16212               const gdb_byte *sibling_ptr = buffer + off;
16213
16214               if (sibling_ptr < info_ptr)
16215                 complaint (&symfile_complaints,
16216                            _("DW_AT_sibling points backwards"));
16217               else if (sibling_ptr > reader->buffer_end)
16218                 dwarf2_section_buffer_overflow_complaint (reader->die_section);
16219               else
16220                 part_die->sibling = sibling_ptr;
16221             }
16222           break;
16223         case DW_AT_byte_size:
16224           part_die->has_byte_size = 1;
16225           break;
16226         case DW_AT_const_value:
16227           part_die->has_const_value = 1;
16228           break;
16229         case DW_AT_calling_convention:
16230           /* DWARF doesn't provide a way to identify a program's source-level
16231              entry point.  DW_AT_calling_convention attributes are only meant
16232              to describe functions' calling conventions.
16233
16234              However, because it's a necessary piece of information in
16235              Fortran, and before DWARF 4 DW_CC_program was the only
16236              piece of debugging information whose definition refers to
16237              a 'main program' at all, several compilers marked Fortran
16238              main programs with DW_CC_program --- even when those
16239              functions use the standard calling conventions.
16240
16241              Although DWARF now specifies a way to provide this
16242              information, we support this practice for backward
16243              compatibility.  */
16244           if (DW_UNSND (&attr) == DW_CC_program
16245               && cu->language == language_fortran)
16246             part_die->main_subprogram = 1;
16247           break;
16248         case DW_AT_inline:
16249           if (DW_UNSND (&attr) == DW_INL_inlined
16250               || DW_UNSND (&attr) == DW_INL_declared_inlined)
16251             part_die->may_be_inlined = 1;
16252           break;
16253
16254         case DW_AT_import:
16255           if (part_die->tag == DW_TAG_imported_unit)
16256             {
16257               part_die->d.offset = dwarf2_get_ref_die_offset (&attr);
16258               part_die->is_dwz = (attr.form == DW_FORM_GNU_ref_alt
16259                                   || cu->per_cu->is_dwz);
16260             }
16261           break;
16262
16263         case DW_AT_main_subprogram:
16264           part_die->main_subprogram = DW_UNSND (&attr);
16265           break;
16266
16267         default:
16268           break;
16269         }
16270     }
16271
16272   if (high_pc_relative)
16273     part_die->highpc += part_die->lowpc;
16274
16275   if (has_low_pc_attr && has_high_pc_attr)
16276     {
16277       /* When using the GNU linker, .gnu.linkonce. sections are used to
16278          eliminate duplicate copies of functions and vtables and such.
16279          The linker will arbitrarily choose one and discard the others.
16280          The AT_*_pc values for such functions refer to local labels in
16281          these sections.  If the section from that file was discarded, the
16282          labels are not in the output, so the relocs get a value of 0.
16283          If this is a discarded function, mark the pc bounds as invalid,
16284          so that GDB will ignore it.  */
16285       if (part_die->lowpc == 0 && !dwarf2_per_objfile->has_section_at_zero)
16286         {
16287           struct gdbarch *gdbarch = get_objfile_arch (objfile);
16288
16289           complaint (&symfile_complaints,
16290                      _("DW_AT_low_pc %s is zero "
16291                        "for DIE at 0x%x [in module %s]"),
16292                      paddress (gdbarch, part_die->lowpc),
16293                      part_die->offset.sect_off, objfile_name (objfile));
16294         }
16295       /* dwarf2_get_pc_bounds has also the strict low < high requirement.  */
16296       else if (part_die->lowpc >= part_die->highpc)
16297         {
16298           struct gdbarch *gdbarch = get_objfile_arch (objfile);
16299
16300           complaint (&symfile_complaints,
16301                      _("DW_AT_low_pc %s is not < DW_AT_high_pc %s "
16302                        "for DIE at 0x%x [in module %s]"),
16303                      paddress (gdbarch, part_die->lowpc),
16304                      paddress (gdbarch, part_die->highpc),
16305                      part_die->offset.sect_off, objfile_name (objfile));
16306         }
16307       else
16308         part_die->has_pc_info = 1;
16309     }
16310
16311   return info_ptr;
16312 }
16313
16314 /* Find a cached partial DIE at OFFSET in CU.  */
16315
16316 static struct partial_die_info *
16317 find_partial_die_in_comp_unit (sect_offset offset, struct dwarf2_cu *cu)
16318 {
16319   struct partial_die_info *lookup_die = NULL;
16320   struct partial_die_info part_die;
16321
16322   part_die.offset = offset;
16323   lookup_die = ((struct partial_die_info *)
16324                 htab_find_with_hash (cu->partial_dies, &part_die,
16325                                      offset.sect_off));
16326
16327   return lookup_die;
16328 }
16329
16330 /* Find a partial DIE at OFFSET, which may or may not be in CU,
16331    except in the case of .debug_types DIEs which do not reference
16332    outside their CU (they do however referencing other types via
16333    DW_FORM_ref_sig8).  */
16334
16335 static struct partial_die_info *
16336 find_partial_die (sect_offset offset, int offset_in_dwz, struct dwarf2_cu *cu)
16337 {
16338   struct objfile *objfile = cu->objfile;
16339   struct dwarf2_per_cu_data *per_cu = NULL;
16340   struct partial_die_info *pd = NULL;
16341
16342   if (offset_in_dwz == cu->per_cu->is_dwz
16343       && offset_in_cu_p (&cu->header, offset))
16344     {
16345       pd = find_partial_die_in_comp_unit (offset, cu);
16346       if (pd != NULL)
16347         return pd;
16348       /* We missed recording what we needed.
16349          Load all dies and try again.  */
16350       per_cu = cu->per_cu;
16351     }
16352   else
16353     {
16354       /* TUs don't reference other CUs/TUs (except via type signatures).  */
16355       if (cu->per_cu->is_debug_types)
16356         {
16357           error (_("Dwarf Error: Type Unit at offset 0x%lx contains"
16358                    " external reference to offset 0x%lx [in module %s].\n"),
16359                  (long) cu->header.offset.sect_off, (long) offset.sect_off,
16360                  bfd_get_filename (objfile->obfd));
16361         }
16362       per_cu = dwarf2_find_containing_comp_unit (offset, offset_in_dwz,
16363                                                  objfile);
16364
16365       if (per_cu->cu == NULL || per_cu->cu->partial_dies == NULL)
16366         load_partial_comp_unit (per_cu);
16367
16368       per_cu->cu->last_used = 0;
16369       pd = find_partial_die_in_comp_unit (offset, per_cu->cu);
16370     }
16371
16372   /* If we didn't find it, and not all dies have been loaded,
16373      load them all and try again.  */
16374
16375   if (pd == NULL && per_cu->load_all_dies == 0)
16376     {
16377       per_cu->load_all_dies = 1;
16378
16379       /* This is nasty.  When we reread the DIEs, somewhere up the call chain
16380          THIS_CU->cu may already be in use.  So we can't just free it and
16381          replace its DIEs with the ones we read in.  Instead, we leave those
16382          DIEs alone (which can still be in use, e.g. in scan_partial_symbols),
16383          and clobber THIS_CU->cu->partial_dies with the hash table for the new
16384          set.  */
16385       load_partial_comp_unit (per_cu);
16386
16387       pd = find_partial_die_in_comp_unit (offset, per_cu->cu);
16388     }
16389
16390   if (pd == NULL)
16391     internal_error (__FILE__, __LINE__,
16392                     _("could not find partial DIE 0x%x "
16393                       "in cache [from module %s]\n"),
16394                     offset.sect_off, bfd_get_filename (objfile->obfd));
16395   return pd;
16396 }
16397
16398 /* See if we can figure out if the class lives in a namespace.  We do
16399    this by looking for a member function; its demangled name will
16400    contain namespace info, if there is any.  */
16401
16402 static void
16403 guess_partial_die_structure_name (struct partial_die_info *struct_pdi,
16404                                   struct dwarf2_cu *cu)
16405 {
16406   /* NOTE: carlton/2003-10-07: Getting the info this way changes
16407      what template types look like, because the demangler
16408      frequently doesn't give the same name as the debug info.  We
16409      could fix this by only using the demangled name to get the
16410      prefix (but see comment in read_structure_type).  */
16411
16412   struct partial_die_info *real_pdi;
16413   struct partial_die_info *child_pdi;
16414
16415   /* If this DIE (this DIE's specification, if any) has a parent, then
16416      we should not do this.  We'll prepend the parent's fully qualified
16417      name when we create the partial symbol.  */
16418
16419   real_pdi = struct_pdi;
16420   while (real_pdi->has_specification)
16421     real_pdi = find_partial_die (real_pdi->spec_offset,
16422                                  real_pdi->spec_is_dwz, cu);
16423
16424   if (real_pdi->die_parent != NULL)
16425     return;
16426
16427   for (child_pdi = struct_pdi->die_child;
16428        child_pdi != NULL;
16429        child_pdi = child_pdi->die_sibling)
16430     {
16431       if (child_pdi->tag == DW_TAG_subprogram
16432           && child_pdi->linkage_name != NULL)
16433         {
16434           char *actual_class_name
16435             = language_class_name_from_physname (cu->language_defn,
16436                                                  child_pdi->linkage_name);
16437           if (actual_class_name != NULL)
16438             {
16439               struct_pdi->name
16440                 = ((const char *)
16441                    obstack_copy0 (&cu->objfile->per_bfd->storage_obstack,
16442                                   actual_class_name,
16443                                   strlen (actual_class_name)));
16444               xfree (actual_class_name);
16445             }
16446           break;
16447         }
16448     }
16449 }
16450
16451 /* Adjust PART_DIE before generating a symbol for it.  This function
16452    may set the is_external flag or change the DIE's name.  */
16453
16454 static void
16455 fixup_partial_die (struct partial_die_info *part_die,
16456                    struct dwarf2_cu *cu)
16457 {
16458   /* Once we've fixed up a die, there's no point in doing so again.
16459      This also avoids a memory leak if we were to call
16460      guess_partial_die_structure_name multiple times.  */
16461   if (part_die->fixup_called)
16462     return;
16463
16464   /* If we found a reference attribute and the DIE has no name, try
16465      to find a name in the referred to DIE.  */
16466
16467   if (part_die->name == NULL && part_die->has_specification)
16468     {
16469       struct partial_die_info *spec_die;
16470
16471       spec_die = find_partial_die (part_die->spec_offset,
16472                                    part_die->spec_is_dwz, cu);
16473
16474       fixup_partial_die (spec_die, cu);
16475
16476       if (spec_die->name)
16477         {
16478           part_die->name = spec_die->name;
16479
16480           /* Copy DW_AT_external attribute if it is set.  */
16481           if (spec_die->is_external)
16482             part_die->is_external = spec_die->is_external;
16483         }
16484     }
16485
16486   /* Set default names for some unnamed DIEs.  */
16487
16488   if (part_die->name == NULL && part_die->tag == DW_TAG_namespace)
16489     part_die->name = CP_ANONYMOUS_NAMESPACE_STR;
16490
16491   /* If there is no parent die to provide a namespace, and there are
16492      children, see if we can determine the namespace from their linkage
16493      name.  */
16494   if (cu->language == language_cplus
16495       && !VEC_empty (dwarf2_section_info_def, dwarf2_per_objfile->types)
16496       && part_die->die_parent == NULL
16497       && part_die->has_children
16498       && (part_die->tag == DW_TAG_class_type
16499           || part_die->tag == DW_TAG_structure_type
16500           || part_die->tag == DW_TAG_union_type))
16501     guess_partial_die_structure_name (part_die, cu);
16502
16503   /* GCC might emit a nameless struct or union that has a linkage
16504      name.  See http://gcc.gnu.org/bugzilla/show_bug.cgi?id=47510.  */
16505   if (part_die->name == NULL
16506       && (part_die->tag == DW_TAG_class_type
16507           || part_die->tag == DW_TAG_interface_type
16508           || part_die->tag == DW_TAG_structure_type
16509           || part_die->tag == DW_TAG_union_type)
16510       && part_die->linkage_name != NULL)
16511     {
16512       char *demangled;
16513
16514       demangled = gdb_demangle (part_die->linkage_name, DMGL_TYPES);
16515       if (demangled)
16516         {
16517           const char *base;
16518
16519           /* Strip any leading namespaces/classes, keep only the base name.
16520              DW_AT_name for named DIEs does not contain the prefixes.  */
16521           base = strrchr (demangled, ':');
16522           if (base && base > demangled && base[-1] == ':')
16523             base++;
16524           else
16525             base = demangled;
16526
16527           part_die->name
16528             = ((const char *)
16529                obstack_copy0 (&cu->objfile->per_bfd->storage_obstack,
16530                               base, strlen (base)));
16531           xfree (demangled);
16532         }
16533     }
16534
16535   part_die->fixup_called = 1;
16536 }
16537
16538 /* Read an attribute value described by an attribute form.  */
16539
16540 static const gdb_byte *
16541 read_attribute_value (const struct die_reader_specs *reader,
16542                       struct attribute *attr, unsigned form,
16543                       LONGEST implicit_const, const gdb_byte *info_ptr)
16544 {
16545   struct dwarf2_cu *cu = reader->cu;
16546   struct objfile *objfile = cu->objfile;
16547   struct gdbarch *gdbarch = get_objfile_arch (objfile);
16548   bfd *abfd = reader->abfd;
16549   struct comp_unit_head *cu_header = &cu->header;
16550   unsigned int bytes_read;
16551   struct dwarf_block *blk;
16552
16553   attr->form = (enum dwarf_form) form;
16554   switch (form)
16555     {
16556     case DW_FORM_ref_addr:
16557       if (cu->header.version == 2)
16558         DW_UNSND (attr) = read_address (abfd, info_ptr, cu, &bytes_read);
16559       else
16560         DW_UNSND (attr) = read_offset (abfd, info_ptr,
16561                                        &cu->header, &bytes_read);
16562       info_ptr += bytes_read;
16563       break;
16564     case DW_FORM_GNU_ref_alt:
16565       DW_UNSND (attr) = read_offset (abfd, info_ptr, &cu->header, &bytes_read);
16566       info_ptr += bytes_read;
16567       break;
16568     case DW_FORM_addr:
16569       DW_ADDR (attr) = read_address (abfd, info_ptr, cu, &bytes_read);
16570       DW_ADDR (attr) = gdbarch_adjust_dwarf2_addr (gdbarch, DW_ADDR (attr));
16571       info_ptr += bytes_read;
16572       break;
16573     case DW_FORM_block2:
16574       blk = dwarf_alloc_block (cu);
16575       blk->size = read_2_bytes (abfd, info_ptr);
16576       info_ptr += 2;
16577       blk->data = read_n_bytes (abfd, info_ptr, blk->size);
16578       info_ptr += blk->size;
16579       DW_BLOCK (attr) = blk;
16580       break;
16581     case DW_FORM_block4:
16582       blk = dwarf_alloc_block (cu);
16583       blk->size = read_4_bytes (abfd, info_ptr);
16584       info_ptr += 4;
16585       blk->data = read_n_bytes (abfd, info_ptr, blk->size);
16586       info_ptr += blk->size;
16587       DW_BLOCK (attr) = blk;
16588       break;
16589     case DW_FORM_data2:
16590       DW_UNSND (attr) = read_2_bytes (abfd, info_ptr);
16591       info_ptr += 2;
16592       break;
16593     case DW_FORM_data4:
16594       DW_UNSND (attr) = read_4_bytes (abfd, info_ptr);
16595       info_ptr += 4;
16596       break;
16597     case DW_FORM_data8:
16598       DW_UNSND (attr) = read_8_bytes (abfd, info_ptr);
16599       info_ptr += 8;
16600       break;
16601     case DW_FORM_data16:
16602       blk = dwarf_alloc_block (cu);
16603       blk->size = 16;
16604       blk->data = read_n_bytes (abfd, info_ptr, 16);
16605       info_ptr += 16;
16606       DW_BLOCK (attr) = blk;
16607       break;
16608     case DW_FORM_sec_offset:
16609       DW_UNSND (attr) = read_offset (abfd, info_ptr, &cu->header, &bytes_read);
16610       info_ptr += bytes_read;
16611       break;
16612     case DW_FORM_string:
16613       DW_STRING (attr) = read_direct_string (abfd, info_ptr, &bytes_read);
16614       DW_STRING_IS_CANONICAL (attr) = 0;
16615       info_ptr += bytes_read;
16616       break;
16617     case DW_FORM_strp:
16618       if (!cu->per_cu->is_dwz)
16619         {
16620           DW_STRING (attr) = read_indirect_string (abfd, info_ptr, cu_header,
16621                                                    &bytes_read);
16622           DW_STRING_IS_CANONICAL (attr) = 0;
16623           info_ptr += bytes_read;
16624           break;
16625         }
16626       /* FALLTHROUGH */
16627     case DW_FORM_line_strp:
16628       if (!cu->per_cu->is_dwz)
16629         {
16630           DW_STRING (attr) = read_indirect_line_string (abfd, info_ptr,
16631                                                         cu_header, &bytes_read);
16632           DW_STRING_IS_CANONICAL (attr) = 0;
16633           info_ptr += bytes_read;
16634           break;
16635         }
16636       /* FALLTHROUGH */
16637     case DW_FORM_GNU_strp_alt:
16638       {
16639         struct dwz_file *dwz = dwarf2_get_dwz_file ();
16640         LONGEST str_offset = read_offset (abfd, info_ptr, cu_header,
16641                                           &bytes_read);
16642
16643         DW_STRING (attr) = read_indirect_string_from_dwz (dwz, str_offset);
16644         DW_STRING_IS_CANONICAL (attr) = 0;
16645         info_ptr += bytes_read;
16646       }
16647       break;
16648     case DW_FORM_exprloc:
16649     case DW_FORM_block:
16650       blk = dwarf_alloc_block (cu);
16651       blk->size = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
16652       info_ptr += bytes_read;
16653       blk->data = read_n_bytes (abfd, info_ptr, blk->size);
16654       info_ptr += blk->size;
16655       DW_BLOCK (attr) = blk;
16656       break;
16657     case DW_FORM_block1:
16658       blk = dwarf_alloc_block (cu);
16659       blk->size = read_1_byte (abfd, info_ptr);
16660       info_ptr += 1;
16661       blk->data = read_n_bytes (abfd, info_ptr, blk->size);
16662       info_ptr += blk->size;
16663       DW_BLOCK (attr) = blk;
16664       break;
16665     case DW_FORM_data1:
16666       DW_UNSND (attr) = read_1_byte (abfd, info_ptr);
16667       info_ptr += 1;
16668       break;
16669     case DW_FORM_flag:
16670       DW_UNSND (attr) = read_1_byte (abfd, info_ptr);
16671       info_ptr += 1;
16672       break;
16673     case DW_FORM_flag_present:
16674       DW_UNSND (attr) = 1;
16675       break;
16676     case DW_FORM_sdata:
16677       DW_SND (attr) = read_signed_leb128 (abfd, info_ptr, &bytes_read);
16678       info_ptr += bytes_read;
16679       break;
16680     case DW_FORM_udata:
16681       DW_UNSND (attr) = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
16682       info_ptr += bytes_read;
16683       break;
16684     case DW_FORM_ref1:
16685       DW_UNSND (attr) = (cu->header.offset.sect_off
16686                          + read_1_byte (abfd, info_ptr));
16687       info_ptr += 1;
16688       break;
16689     case DW_FORM_ref2:
16690       DW_UNSND (attr) = (cu->header.offset.sect_off
16691                          + read_2_bytes (abfd, info_ptr));
16692       info_ptr += 2;
16693       break;
16694     case DW_FORM_ref4:
16695       DW_UNSND (attr) = (cu->header.offset.sect_off
16696                          + read_4_bytes (abfd, info_ptr));
16697       info_ptr += 4;
16698       break;
16699     case DW_FORM_ref8:
16700       DW_UNSND (attr) = (cu->header.offset.sect_off
16701                          + read_8_bytes (abfd, info_ptr));
16702       info_ptr += 8;
16703       break;
16704     case DW_FORM_ref_sig8:
16705       DW_SIGNATURE (attr) = read_8_bytes (abfd, info_ptr);
16706       info_ptr += 8;
16707       break;
16708     case DW_FORM_ref_udata:
16709       DW_UNSND (attr) = (cu->header.offset.sect_off
16710                          + read_unsigned_leb128 (abfd, info_ptr, &bytes_read));
16711       info_ptr += bytes_read;
16712       break;
16713     case DW_FORM_indirect:
16714       form = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
16715       info_ptr += bytes_read;
16716       if (form == DW_FORM_implicit_const)
16717         {
16718           implicit_const = read_signed_leb128 (abfd, info_ptr, &bytes_read);
16719           info_ptr += bytes_read;
16720         }
16721       info_ptr = read_attribute_value (reader, attr, form, implicit_const,
16722                                        info_ptr);
16723       break;
16724     case DW_FORM_implicit_const:
16725       DW_SND (attr) = implicit_const;
16726       break;
16727     case DW_FORM_GNU_addr_index:
16728       if (reader->dwo_file == NULL)
16729         {
16730           /* For now flag a hard error.
16731              Later we can turn this into a complaint.  */
16732           error (_("Dwarf Error: %s found in non-DWO CU [in module %s]"),
16733                  dwarf_form_name (form),
16734                  bfd_get_filename (abfd));
16735         }
16736       DW_ADDR (attr) = read_addr_index_from_leb128 (cu, info_ptr, &bytes_read);
16737       info_ptr += bytes_read;
16738       break;
16739     case DW_FORM_GNU_str_index:
16740       if (reader->dwo_file == NULL)
16741         {
16742           /* For now flag a hard error.
16743              Later we can turn this into a complaint if warranted.  */
16744           error (_("Dwarf Error: %s found in non-DWO CU [in module %s]"),
16745                  dwarf_form_name (form),
16746                  bfd_get_filename (abfd));
16747         }
16748       {
16749         ULONGEST str_index =
16750           read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
16751
16752         DW_STRING (attr) = read_str_index (reader, str_index);
16753         DW_STRING_IS_CANONICAL (attr) = 0;
16754         info_ptr += bytes_read;
16755       }
16756       break;
16757     default:
16758       error (_("Dwarf Error: Cannot handle %s in DWARF reader [in module %s]"),
16759              dwarf_form_name (form),
16760              bfd_get_filename (abfd));
16761     }
16762
16763   /* Super hack.  */
16764   if (cu->per_cu->is_dwz && attr_form_is_ref (attr))
16765     attr->form = DW_FORM_GNU_ref_alt;
16766
16767   /* We have seen instances where the compiler tried to emit a byte
16768      size attribute of -1 which ended up being encoded as an unsigned
16769      0xffffffff.  Although 0xffffffff is technically a valid size value,
16770      an object of this size seems pretty unlikely so we can relatively
16771      safely treat these cases as if the size attribute was invalid and
16772      treat them as zero by default.  */
16773   if (attr->name == DW_AT_byte_size
16774       && form == DW_FORM_data4
16775       && DW_UNSND (attr) >= 0xffffffff)
16776     {
16777       complaint
16778         (&symfile_complaints,
16779          _("Suspicious DW_AT_byte_size value treated as zero instead of %s"),
16780          hex_string (DW_UNSND (attr)));
16781       DW_UNSND (attr) = 0;
16782     }
16783
16784   return info_ptr;
16785 }
16786
16787 /* Read an attribute described by an abbreviated attribute.  */
16788
16789 static const gdb_byte *
16790 read_attribute (const struct die_reader_specs *reader,
16791                 struct attribute *attr, struct attr_abbrev *abbrev,
16792                 const gdb_byte *info_ptr)
16793 {
16794   attr->name = abbrev->name;
16795   return read_attribute_value (reader, attr, abbrev->form,
16796                                abbrev->implicit_const, info_ptr);
16797 }
16798
16799 /* Read dwarf information from a buffer.  */
16800
16801 static unsigned int
16802 read_1_byte (bfd *abfd, const gdb_byte *buf)
16803 {
16804   return bfd_get_8 (abfd, buf);
16805 }
16806
16807 static int
16808 read_1_signed_byte (bfd *abfd, const gdb_byte *buf)
16809 {
16810   return bfd_get_signed_8 (abfd, buf);
16811 }
16812
16813 static unsigned int
16814 read_2_bytes (bfd *abfd, const gdb_byte *buf)
16815 {
16816   return bfd_get_16 (abfd, buf);
16817 }
16818
16819 static int
16820 read_2_signed_bytes (bfd *abfd, const gdb_byte *buf)
16821 {
16822   return bfd_get_signed_16 (abfd, buf);
16823 }
16824
16825 static unsigned int
16826 read_4_bytes (bfd *abfd, const gdb_byte *buf)
16827 {
16828   return bfd_get_32 (abfd, buf);
16829 }
16830
16831 static int
16832 read_4_signed_bytes (bfd *abfd, const gdb_byte *buf)
16833 {
16834   return bfd_get_signed_32 (abfd, buf);
16835 }
16836
16837 static ULONGEST
16838 read_8_bytes (bfd *abfd, const gdb_byte *buf)
16839 {
16840   return bfd_get_64 (abfd, buf);
16841 }
16842
16843 static CORE_ADDR
16844 read_address (bfd *abfd, const gdb_byte *buf, struct dwarf2_cu *cu,
16845               unsigned int *bytes_read)
16846 {
16847   struct comp_unit_head *cu_header = &cu->header;
16848   CORE_ADDR retval = 0;
16849
16850   if (cu_header->signed_addr_p)
16851     {
16852       switch (cu_header->addr_size)
16853         {
16854         case 2:
16855           retval = bfd_get_signed_16 (abfd, buf);
16856           break;
16857         case 4:
16858           retval = bfd_get_signed_32 (abfd, buf);
16859           break;
16860         case 8:
16861           retval = bfd_get_signed_64 (abfd, buf);
16862           break;
16863         default:
16864           internal_error (__FILE__, __LINE__,
16865                           _("read_address: bad switch, signed [in module %s]"),
16866                           bfd_get_filename (abfd));
16867         }
16868     }
16869   else
16870     {
16871       switch (cu_header->addr_size)
16872         {
16873         case 2:
16874           retval = bfd_get_16 (abfd, buf);
16875           break;
16876         case 4:
16877           retval = bfd_get_32 (abfd, buf);
16878           break;
16879         case 8:
16880           retval = bfd_get_64 (abfd, buf);
16881           break;
16882         default:
16883           internal_error (__FILE__, __LINE__,
16884                           _("read_address: bad switch, "
16885                             "unsigned [in module %s]"),
16886                           bfd_get_filename (abfd));
16887         }
16888     }
16889
16890   *bytes_read = cu_header->addr_size;
16891   return retval;
16892 }
16893
16894 /* Read the initial length from a section.  The (draft) DWARF 3
16895    specification allows the initial length to take up either 4 bytes
16896    or 12 bytes.  If the first 4 bytes are 0xffffffff, then the next 8
16897    bytes describe the length and all offsets will be 8 bytes in length
16898    instead of 4.
16899
16900    An older, non-standard 64-bit format is also handled by this
16901    function.  The older format in question stores the initial length
16902    as an 8-byte quantity without an escape value.  Lengths greater
16903    than 2^32 aren't very common which means that the initial 4 bytes
16904    is almost always zero.  Since a length value of zero doesn't make
16905    sense for the 32-bit format, this initial zero can be considered to
16906    be an escape value which indicates the presence of the older 64-bit
16907    format.  As written, the code can't detect (old format) lengths
16908    greater than 4GB.  If it becomes necessary to handle lengths
16909    somewhat larger than 4GB, we could allow other small values (such
16910    as the non-sensical values of 1, 2, and 3) to also be used as
16911    escape values indicating the presence of the old format.
16912
16913    The value returned via bytes_read should be used to increment the
16914    relevant pointer after calling read_initial_length().
16915
16916    [ Note:  read_initial_length() and read_offset() are based on the
16917      document entitled "DWARF Debugging Information Format", revision
16918      3, draft 8, dated November 19, 2001.  This document was obtained
16919      from:
16920
16921         http://reality.sgiweb.org/davea/dwarf3-draft8-011125.pdf
16922
16923      This document is only a draft and is subject to change.  (So beware.)
16924
16925      Details regarding the older, non-standard 64-bit format were
16926      determined empirically by examining 64-bit ELF files produced by
16927      the SGI toolchain on an IRIX 6.5 machine.
16928
16929      - Kevin, July 16, 2002
16930    ] */
16931
16932 static LONGEST
16933 read_initial_length (bfd *abfd, const gdb_byte *buf, unsigned int *bytes_read)
16934 {
16935   LONGEST length = bfd_get_32 (abfd, buf);
16936
16937   if (length == 0xffffffff)
16938     {
16939       length = bfd_get_64 (abfd, buf + 4);
16940       *bytes_read = 12;
16941     }
16942   else if (length == 0)
16943     {
16944       /* Handle the (non-standard) 64-bit DWARF2 format used by IRIX.  */
16945       length = bfd_get_64 (abfd, buf);
16946       *bytes_read = 8;
16947     }
16948   else
16949     {
16950       *bytes_read = 4;
16951     }
16952
16953   return length;
16954 }
16955
16956 /* Cover function for read_initial_length.
16957    Returns the length of the object at BUF, and stores the size of the
16958    initial length in *BYTES_READ and stores the size that offsets will be in
16959    *OFFSET_SIZE.
16960    If the initial length size is not equivalent to that specified in
16961    CU_HEADER then issue a complaint.
16962    This is useful when reading non-comp-unit headers.  */
16963
16964 static LONGEST
16965 read_checked_initial_length_and_offset (bfd *abfd, const gdb_byte *buf,
16966                                         const struct comp_unit_head *cu_header,
16967                                         unsigned int *bytes_read,
16968                                         unsigned int *offset_size)
16969 {
16970   LONGEST length = read_initial_length (abfd, buf, bytes_read);
16971
16972   gdb_assert (cu_header->initial_length_size == 4
16973               || cu_header->initial_length_size == 8
16974               || cu_header->initial_length_size == 12);
16975
16976   if (cu_header->initial_length_size != *bytes_read)
16977     complaint (&symfile_complaints,
16978                _("intermixed 32-bit and 64-bit DWARF sections"));
16979
16980   *offset_size = (*bytes_read == 4) ? 4 : 8;
16981   return length;
16982 }
16983
16984 /* Read an offset from the data stream.  The size of the offset is
16985    given by cu_header->offset_size.  */
16986
16987 static LONGEST
16988 read_offset (bfd *abfd, const gdb_byte *buf,
16989              const struct comp_unit_head *cu_header,
16990              unsigned int *bytes_read)
16991 {
16992   LONGEST offset = read_offset_1 (abfd, buf, cu_header->offset_size);
16993
16994   *bytes_read = cu_header->offset_size;
16995   return offset;
16996 }
16997
16998 /* Read an offset from the data stream.  */
16999
17000 static LONGEST
17001 read_offset_1 (bfd *abfd, const gdb_byte *buf, unsigned int offset_size)
17002 {
17003   LONGEST retval = 0;
17004
17005   switch (offset_size)
17006     {
17007     case 4:
17008       retval = bfd_get_32 (abfd, buf);
17009       break;
17010     case 8:
17011       retval = bfd_get_64 (abfd, buf);
17012       break;
17013     default:
17014       internal_error (__FILE__, __LINE__,
17015                       _("read_offset_1: bad switch [in module %s]"),
17016                       bfd_get_filename (abfd));
17017     }
17018
17019   return retval;
17020 }
17021
17022 static const gdb_byte *
17023 read_n_bytes (bfd *abfd, const gdb_byte *buf, unsigned int size)
17024 {
17025   /* If the size of a host char is 8 bits, we can return a pointer
17026      to the buffer, otherwise we have to copy the data to a buffer
17027      allocated on the temporary obstack.  */
17028   gdb_assert (HOST_CHAR_BIT == 8);
17029   return buf;
17030 }
17031
17032 static const char *
17033 read_direct_string (bfd *abfd, const gdb_byte *buf,
17034                     unsigned int *bytes_read_ptr)
17035 {
17036   /* If the size of a host char is 8 bits, we can return a pointer
17037      to the string, otherwise we have to copy the string to a buffer
17038      allocated on the temporary obstack.  */
17039   gdb_assert (HOST_CHAR_BIT == 8);
17040   if (*buf == '\0')
17041     {
17042       *bytes_read_ptr = 1;
17043       return NULL;
17044     }
17045   *bytes_read_ptr = strlen ((const char *) buf) + 1;
17046   return (const char *) buf;
17047 }
17048
17049 /* Return pointer to string at section SECT offset STR_OFFSET with error
17050    reporting strings FORM_NAME and SECT_NAME.  */
17051
17052 static const char *
17053 read_indirect_string_at_offset_from (bfd *abfd, LONGEST str_offset,
17054                                      struct dwarf2_section_info *sect,
17055                                      const char *form_name,
17056                                      const char *sect_name)
17057 {
17058   dwarf2_read_section (dwarf2_per_objfile->objfile, sect);
17059   if (sect->buffer == NULL)
17060     error (_("%s used without %s section [in module %s]"),
17061            form_name, sect_name, bfd_get_filename (abfd));
17062   if (str_offset >= sect->size)
17063     error (_("%s pointing outside of %s section [in module %s]"),
17064            form_name, sect_name, bfd_get_filename (abfd));
17065   gdb_assert (HOST_CHAR_BIT == 8);
17066   if (sect->buffer[str_offset] == '\0')
17067     return NULL;
17068   return (const char *) (sect->buffer + str_offset);
17069 }
17070
17071 /* Return pointer to string at .debug_str offset STR_OFFSET.  */
17072
17073 static const char *
17074 read_indirect_string_at_offset (bfd *abfd, LONGEST str_offset)
17075 {
17076   return read_indirect_string_at_offset_from (abfd, str_offset,
17077                                               &dwarf2_per_objfile->str,
17078                                               "DW_FORM_strp", ".debug_str");
17079 }
17080
17081 /* Return pointer to string at .debug_line_str offset STR_OFFSET.  */
17082
17083 static const char *
17084 read_indirect_line_string_at_offset (bfd *abfd, LONGEST str_offset)
17085 {
17086   return read_indirect_string_at_offset_from (abfd, str_offset,
17087                                               &dwarf2_per_objfile->line_str,
17088                                               "DW_FORM_line_strp",
17089                                               ".debug_line_str");
17090 }
17091
17092 /* Read a string at offset STR_OFFSET in the .debug_str section from
17093    the .dwz file DWZ.  Throw an error if the offset is too large.  If
17094    the string consists of a single NUL byte, return NULL; otherwise
17095    return a pointer to the string.  */
17096
17097 static const char *
17098 read_indirect_string_from_dwz (struct dwz_file *dwz, LONGEST str_offset)
17099 {
17100   dwarf2_read_section (dwarf2_per_objfile->objfile, &dwz->str);
17101
17102   if (dwz->str.buffer == NULL)
17103     error (_("DW_FORM_GNU_strp_alt used without .debug_str "
17104              "section [in module %s]"),
17105            bfd_get_filename (dwz->dwz_bfd));
17106   if (str_offset >= dwz->str.size)
17107     error (_("DW_FORM_GNU_strp_alt pointing outside of "
17108              ".debug_str section [in module %s]"),
17109            bfd_get_filename (dwz->dwz_bfd));
17110   gdb_assert (HOST_CHAR_BIT == 8);
17111   if (dwz->str.buffer[str_offset] == '\0')
17112     return NULL;
17113   return (const char *) (dwz->str.buffer + str_offset);
17114 }
17115
17116 /* Return pointer to string at .debug_str offset as read from BUF.
17117    BUF is assumed to be in a compilation unit described by CU_HEADER.
17118    Return *BYTES_READ_PTR count of bytes read from BUF.  */
17119
17120 static const char *
17121 read_indirect_string (bfd *abfd, const gdb_byte *buf,
17122                       const struct comp_unit_head *cu_header,
17123                       unsigned int *bytes_read_ptr)
17124 {
17125   LONGEST str_offset = read_offset (abfd, buf, cu_header, bytes_read_ptr);
17126
17127   return read_indirect_string_at_offset (abfd, str_offset);
17128 }
17129
17130 /* Return pointer to string at .debug_line_str offset as read from BUF.
17131    BUF is assumed to be in a compilation unit described by CU_HEADER.
17132    Return *BYTES_READ_PTR count of bytes read from BUF.  */
17133
17134 static const char *
17135 read_indirect_line_string (bfd *abfd, const gdb_byte *buf,
17136                            const struct comp_unit_head *cu_header,
17137                            unsigned int *bytes_read_ptr)
17138 {
17139   LONGEST str_offset = read_offset (abfd, buf, cu_header, bytes_read_ptr);
17140
17141   return read_indirect_line_string_at_offset (abfd, str_offset);
17142 }
17143
17144 ULONGEST
17145 read_unsigned_leb128 (bfd *abfd, const gdb_byte *buf,
17146                           unsigned int *bytes_read_ptr)
17147 {
17148   ULONGEST result;
17149   unsigned int num_read;
17150   int shift;
17151   unsigned char byte;
17152
17153   result = 0;
17154   shift = 0;
17155   num_read = 0;
17156   while (1)
17157     {
17158       byte = bfd_get_8 (abfd, buf);
17159       buf++;
17160       num_read++;
17161       result |= ((ULONGEST) (byte & 127) << shift);
17162       if ((byte & 128) == 0)
17163         {
17164           break;
17165         }
17166       shift += 7;
17167     }
17168   *bytes_read_ptr = num_read;
17169   return result;
17170 }
17171
17172 static LONGEST
17173 read_signed_leb128 (bfd *abfd, const gdb_byte *buf,
17174                     unsigned int *bytes_read_ptr)
17175 {
17176   LONGEST result;
17177   int shift, num_read;
17178   unsigned char byte;
17179
17180   result = 0;
17181   shift = 0;
17182   num_read = 0;
17183   while (1)
17184     {
17185       byte = bfd_get_8 (abfd, buf);
17186       buf++;
17187       num_read++;
17188       result |= ((LONGEST) (byte & 127) << shift);
17189       shift += 7;
17190       if ((byte & 128) == 0)
17191         {
17192           break;
17193         }
17194     }
17195   if ((shift < 8 * sizeof (result)) && (byte & 0x40))
17196     result |= -(((LONGEST) 1) << shift);
17197   *bytes_read_ptr = num_read;
17198   return result;
17199 }
17200
17201 /* Given index ADDR_INDEX in .debug_addr, fetch the value.
17202    ADDR_BASE is the DW_AT_GNU_addr_base attribute or zero.
17203    ADDR_SIZE is the size of addresses from the CU header.  */
17204
17205 static CORE_ADDR
17206 read_addr_index_1 (unsigned int addr_index, ULONGEST addr_base, int addr_size)
17207 {
17208   struct objfile *objfile = dwarf2_per_objfile->objfile;
17209   bfd *abfd = objfile->obfd;
17210   const gdb_byte *info_ptr;
17211
17212   dwarf2_read_section (objfile, &dwarf2_per_objfile->addr);
17213   if (dwarf2_per_objfile->addr.buffer == NULL)
17214     error (_("DW_FORM_addr_index used without .debug_addr section [in module %s]"),
17215            objfile_name (objfile));
17216   if (addr_base + addr_index * addr_size >= dwarf2_per_objfile->addr.size)
17217     error (_("DW_FORM_addr_index pointing outside of "
17218              ".debug_addr section [in module %s]"),
17219            objfile_name (objfile));
17220   info_ptr = (dwarf2_per_objfile->addr.buffer
17221               + addr_base + addr_index * addr_size);
17222   if (addr_size == 4)
17223     return bfd_get_32 (abfd, info_ptr);
17224   else
17225     return bfd_get_64 (abfd, info_ptr);
17226 }
17227
17228 /* Given index ADDR_INDEX in .debug_addr, fetch the value.  */
17229
17230 static CORE_ADDR
17231 read_addr_index (struct dwarf2_cu *cu, unsigned int addr_index)
17232 {
17233   return read_addr_index_1 (addr_index, cu->addr_base, cu->header.addr_size);
17234 }
17235
17236 /* Given a pointer to an leb128 value, fetch the value from .debug_addr.  */
17237
17238 static CORE_ADDR
17239 read_addr_index_from_leb128 (struct dwarf2_cu *cu, const gdb_byte *info_ptr,
17240                              unsigned int *bytes_read)
17241 {
17242   bfd *abfd = cu->objfile->obfd;
17243   unsigned int addr_index = read_unsigned_leb128 (abfd, info_ptr, bytes_read);
17244
17245   return read_addr_index (cu, addr_index);
17246 }
17247
17248 /* Data structure to pass results from dwarf2_read_addr_index_reader
17249    back to dwarf2_read_addr_index.  */
17250
17251 struct dwarf2_read_addr_index_data
17252 {
17253   ULONGEST addr_base;
17254   int addr_size;
17255 };
17256
17257 /* die_reader_func for dwarf2_read_addr_index.  */
17258
17259 static void
17260 dwarf2_read_addr_index_reader (const struct die_reader_specs *reader,
17261                                const gdb_byte *info_ptr,
17262                                struct die_info *comp_unit_die,
17263                                int has_children,
17264                                void *data)
17265 {
17266   struct dwarf2_cu *cu = reader->cu;
17267   struct dwarf2_read_addr_index_data *aidata =
17268     (struct dwarf2_read_addr_index_data *) data;
17269
17270   aidata->addr_base = cu->addr_base;
17271   aidata->addr_size = cu->header.addr_size;
17272 }
17273
17274 /* Given an index in .debug_addr, fetch the value.
17275    NOTE: This can be called during dwarf expression evaluation,
17276    long after the debug information has been read, and thus per_cu->cu
17277    may no longer exist.  */
17278
17279 CORE_ADDR
17280 dwarf2_read_addr_index (struct dwarf2_per_cu_data *per_cu,
17281                         unsigned int addr_index)
17282 {
17283   struct objfile *objfile = per_cu->objfile;
17284   struct dwarf2_cu *cu = per_cu->cu;
17285   ULONGEST addr_base;
17286   int addr_size;
17287
17288   /* This is intended to be called from outside this file.  */
17289   dw2_setup (objfile);
17290
17291   /* We need addr_base and addr_size.
17292      If we don't have PER_CU->cu, we have to get it.
17293      Nasty, but the alternative is storing the needed info in PER_CU,
17294      which at this point doesn't seem justified: it's not clear how frequently
17295      it would get used and it would increase the size of every PER_CU.
17296      Entry points like dwarf2_per_cu_addr_size do a similar thing
17297      so we're not in uncharted territory here.
17298      Alas we need to be a bit more complicated as addr_base is contained
17299      in the DIE.
17300
17301      We don't need to read the entire CU(/TU).
17302      We just need the header and top level die.
17303
17304      IWBN to use the aging mechanism to let us lazily later discard the CU.
17305      For now we skip this optimization.  */
17306
17307   if (cu != NULL)
17308     {
17309       addr_base = cu->addr_base;
17310       addr_size = cu->header.addr_size;
17311     }
17312   else
17313     {
17314       struct dwarf2_read_addr_index_data aidata;
17315
17316       /* Note: We can't use init_cutu_and_read_dies_simple here,
17317          we need addr_base.  */
17318       init_cutu_and_read_dies (per_cu, NULL, 0, 0,
17319                                dwarf2_read_addr_index_reader, &aidata);
17320       addr_base = aidata.addr_base;
17321       addr_size = aidata.addr_size;
17322     }
17323
17324   return read_addr_index_1 (addr_index, addr_base, addr_size);
17325 }
17326
17327 /* Given a DW_FORM_GNU_str_index, fetch the string.
17328    This is only used by the Fission support.  */
17329
17330 static const char *
17331 read_str_index (const struct die_reader_specs *reader, ULONGEST str_index)
17332 {
17333   struct objfile *objfile = dwarf2_per_objfile->objfile;
17334   const char *objf_name = objfile_name (objfile);
17335   bfd *abfd = objfile->obfd;
17336   struct dwarf2_cu *cu = reader->cu;
17337   struct dwarf2_section_info *str_section = &reader->dwo_file->sections.str;
17338   struct dwarf2_section_info *str_offsets_section =
17339     &reader->dwo_file->sections.str_offsets;
17340   const gdb_byte *info_ptr;
17341   ULONGEST str_offset;
17342   static const char form_name[] = "DW_FORM_GNU_str_index";
17343
17344   dwarf2_read_section (objfile, str_section);
17345   dwarf2_read_section (objfile, str_offsets_section);
17346   if (str_section->buffer == NULL)
17347     error (_("%s used without .debug_str.dwo section"
17348              " in CU at offset 0x%lx [in module %s]"),
17349            form_name, (long) cu->header.offset.sect_off, objf_name);
17350   if (str_offsets_section->buffer == NULL)
17351     error (_("%s used without .debug_str_offsets.dwo section"
17352              " in CU at offset 0x%lx [in module %s]"),
17353            form_name, (long) cu->header.offset.sect_off, objf_name);
17354   if (str_index * cu->header.offset_size >= str_offsets_section->size)
17355     error (_("%s pointing outside of .debug_str_offsets.dwo"
17356              " section in CU at offset 0x%lx [in module %s]"),
17357            form_name, (long) cu->header.offset.sect_off, objf_name);
17358   info_ptr = (str_offsets_section->buffer
17359               + str_index * cu->header.offset_size);
17360   if (cu->header.offset_size == 4)
17361     str_offset = bfd_get_32 (abfd, info_ptr);
17362   else
17363     str_offset = bfd_get_64 (abfd, info_ptr);
17364   if (str_offset >= str_section->size)
17365     error (_("Offset from %s pointing outside of"
17366              " .debug_str.dwo section in CU at offset 0x%lx [in module %s]"),
17367            form_name, (long) cu->header.offset.sect_off, objf_name);
17368   return (const char *) (str_section->buffer + str_offset);
17369 }
17370
17371 /* Return the length of an LEB128 number in BUF.  */
17372
17373 static int
17374 leb128_size (const gdb_byte *buf)
17375 {
17376   const gdb_byte *begin = buf;
17377   gdb_byte byte;
17378
17379   while (1)
17380     {
17381       byte = *buf++;
17382       if ((byte & 128) == 0)
17383         return buf - begin;
17384     }
17385 }
17386
17387 static void
17388 set_cu_language (unsigned int lang, struct dwarf2_cu *cu)
17389 {
17390   switch (lang)
17391     {
17392     case DW_LANG_C89:
17393     case DW_LANG_C99:
17394     case DW_LANG_C11:
17395     case DW_LANG_C:
17396     case DW_LANG_UPC:
17397       cu->language = language_c;
17398       break;
17399     case DW_LANG_Java:
17400     case DW_LANG_C_plus_plus:
17401     case DW_LANG_C_plus_plus_11:
17402     case DW_LANG_C_plus_plus_14:
17403       cu->language = language_cplus;
17404       break;
17405     case DW_LANG_D:
17406       cu->language = language_d;
17407       break;
17408     case DW_LANG_Fortran77:
17409     case DW_LANG_Fortran90:
17410     case DW_LANG_Fortran95:
17411     case DW_LANG_Fortran03:
17412     case DW_LANG_Fortran08:
17413       cu->language = language_fortran;
17414       break;
17415     case DW_LANG_Go:
17416       cu->language = language_go;
17417       break;
17418     case DW_LANG_Mips_Assembler:
17419       cu->language = language_asm;
17420       break;
17421     case DW_LANG_Ada83:
17422     case DW_LANG_Ada95:
17423       cu->language = language_ada;
17424       break;
17425     case DW_LANG_Modula2:
17426       cu->language = language_m2;
17427       break;
17428     case DW_LANG_Pascal83:
17429       cu->language = language_pascal;
17430       break;
17431     case DW_LANG_ObjC:
17432       cu->language = language_objc;
17433       break;
17434     case DW_LANG_Rust:
17435     case DW_LANG_Rust_old:
17436       cu->language = language_rust;
17437       break;
17438     case DW_LANG_Cobol74:
17439     case DW_LANG_Cobol85:
17440     default:
17441       cu->language = language_minimal;
17442       break;
17443     }
17444   cu->language_defn = language_def (cu->language);
17445 }
17446
17447 /* Return the named attribute or NULL if not there.  */
17448
17449 static struct attribute *
17450 dwarf2_attr (struct die_info *die, unsigned int name, struct dwarf2_cu *cu)
17451 {
17452   for (;;)
17453     {
17454       unsigned int i;
17455       struct attribute *spec = NULL;
17456
17457       for (i = 0; i < die->num_attrs; ++i)
17458         {
17459           if (die->attrs[i].name == name)
17460             return &die->attrs[i];
17461           if (die->attrs[i].name == DW_AT_specification
17462               || die->attrs[i].name == DW_AT_abstract_origin)
17463             spec = &die->attrs[i];
17464         }
17465
17466       if (!spec)
17467         break;
17468
17469       die = follow_die_ref (die, spec, &cu);
17470     }
17471
17472   return NULL;
17473 }
17474
17475 /* Return the named attribute or NULL if not there,
17476    but do not follow DW_AT_specification, etc.
17477    This is for use in contexts where we're reading .debug_types dies.
17478    Following DW_AT_specification, DW_AT_abstract_origin will take us
17479    back up the chain, and we want to go down.  */
17480
17481 static struct attribute *
17482 dwarf2_attr_no_follow (struct die_info *die, unsigned int name)
17483 {
17484   unsigned int i;
17485
17486   for (i = 0; i < die->num_attrs; ++i)
17487     if (die->attrs[i].name == name)
17488       return &die->attrs[i];
17489
17490   return NULL;
17491 }
17492
17493 /* Return the string associated with a string-typed attribute, or NULL if it
17494    is either not found or is of an incorrect type.  */
17495
17496 static const char *
17497 dwarf2_string_attr (struct die_info *die, unsigned int name, struct dwarf2_cu *cu)
17498 {
17499   struct attribute *attr;
17500   const char *str = NULL;
17501
17502   attr = dwarf2_attr (die, name, cu);
17503
17504   if (attr != NULL)
17505     {
17506       if (attr->form == DW_FORM_strp || attr->form == DW_FORM_line_strp
17507           || attr->form == DW_FORM_string || attr->form == DW_FORM_GNU_strp_alt)
17508         str = DW_STRING (attr);
17509       else
17510         complaint (&symfile_complaints,
17511                    _("string type expected for attribute %s for "
17512                      "DIE at 0x%x in module %s"),
17513                    dwarf_attr_name (name), die->offset.sect_off,
17514                    objfile_name (cu->objfile));
17515     }
17516
17517   return str;
17518 }
17519
17520 /* Return non-zero iff the attribute NAME is defined for the given DIE,
17521    and holds a non-zero value.  This function should only be used for
17522    DW_FORM_flag or DW_FORM_flag_present attributes.  */
17523
17524 static int
17525 dwarf2_flag_true_p (struct die_info *die, unsigned name, struct dwarf2_cu *cu)
17526 {
17527   struct attribute *attr = dwarf2_attr (die, name, cu);
17528
17529   return (attr && DW_UNSND (attr));
17530 }
17531
17532 static int
17533 die_is_declaration (struct die_info *die, struct dwarf2_cu *cu)
17534 {
17535   /* A DIE is a declaration if it has a DW_AT_declaration attribute
17536      which value is non-zero.  However, we have to be careful with
17537      DIEs having a DW_AT_specification attribute, because dwarf2_attr()
17538      (via dwarf2_flag_true_p) follows this attribute.  So we may
17539      end up accidently finding a declaration attribute that belongs
17540      to a different DIE referenced by the specification attribute,
17541      even though the given DIE does not have a declaration attribute.  */
17542   return (dwarf2_flag_true_p (die, DW_AT_declaration, cu)
17543           && dwarf2_attr (die, DW_AT_specification, cu) == NULL);
17544 }
17545
17546 /* Return the die giving the specification for DIE, if there is
17547    one.  *SPEC_CU is the CU containing DIE on input, and the CU
17548    containing the return value on output.  If there is no
17549    specification, but there is an abstract origin, that is
17550    returned.  */
17551
17552 static struct die_info *
17553 die_specification (struct die_info *die, struct dwarf2_cu **spec_cu)
17554 {
17555   struct attribute *spec_attr = dwarf2_attr (die, DW_AT_specification,
17556                                              *spec_cu);
17557
17558   if (spec_attr == NULL)
17559     spec_attr = dwarf2_attr (die, DW_AT_abstract_origin, *spec_cu);
17560
17561   if (spec_attr == NULL)
17562     return NULL;
17563   else
17564     return follow_die_ref (die, spec_attr, spec_cu);
17565 }
17566
17567 /* Free the line_header structure *LH, and any arrays and strings it
17568    refers to.
17569    NOTE: This is also used as a "cleanup" function.  */
17570
17571 static void
17572 free_line_header (struct line_header *lh)
17573 {
17574   if (lh->standard_opcode_lengths)
17575     xfree (lh->standard_opcode_lengths);
17576
17577   /* Remember that all the lh->file_names[i].name pointers are
17578      pointers into debug_line_buffer, and don't need to be freed.  */
17579   if (lh->file_names)
17580     xfree (lh->file_names);
17581
17582   /* Similarly for the include directory names.  */
17583   if (lh->include_dirs)
17584     xfree (lh->include_dirs);
17585
17586   xfree (lh);
17587 }
17588
17589 /* Stub for free_line_header to match void * callback types.  */
17590
17591 static void
17592 free_line_header_voidp (void *arg)
17593 {
17594   struct line_header *lh = (struct line_header *) arg;
17595
17596   free_line_header (lh);
17597 }
17598
17599 /* Add an entry to LH's include directory table.  */
17600
17601 static void
17602 add_include_dir (struct line_header *lh, const char *include_dir)
17603 {
17604   if (dwarf_line_debug >= 2)
17605     fprintf_unfiltered (gdb_stdlog, "Adding dir %u: %s\n",
17606                         lh->num_include_dirs + 1, include_dir);
17607
17608   /* Grow the array if necessary.  */
17609   if (lh->include_dirs_size == 0)
17610     {
17611       lh->include_dirs_size = 1; /* for testing */
17612       lh->include_dirs = XNEWVEC (const char *, lh->include_dirs_size);
17613     }
17614   else if (lh->num_include_dirs >= lh->include_dirs_size)
17615     {
17616       lh->include_dirs_size *= 2;
17617       lh->include_dirs = XRESIZEVEC (const char *, lh->include_dirs,
17618                                      lh->include_dirs_size);
17619     }
17620
17621   lh->include_dirs[lh->num_include_dirs++] = include_dir;
17622 }
17623
17624 /* Add an entry to LH's file name table.  */
17625
17626 static void
17627 add_file_name (struct line_header *lh,
17628                const char *name,
17629                unsigned int dir_index,
17630                unsigned int mod_time,
17631                unsigned int length)
17632 {
17633   struct file_entry *fe;
17634
17635   if (dwarf_line_debug >= 2)
17636     fprintf_unfiltered (gdb_stdlog, "Adding file %u: %s\n",
17637                         lh->num_file_names + 1, name);
17638
17639   /* Grow the array if necessary.  */
17640   if (lh->file_names_size == 0)
17641     {
17642       lh->file_names_size = 1; /* for testing */
17643       lh->file_names = XNEWVEC (struct file_entry, lh->file_names_size);
17644     }
17645   else if (lh->num_file_names >= lh->file_names_size)
17646     {
17647       lh->file_names_size *= 2;
17648       lh->file_names
17649         = XRESIZEVEC (struct file_entry, lh->file_names, lh->file_names_size);
17650     }
17651
17652   fe = &lh->file_names[lh->num_file_names++];
17653   fe->name = name;
17654   fe->dir_index = dir_index;
17655   fe->mod_time = mod_time;
17656   fe->length = length;
17657   fe->included_p = 0;
17658   fe->symtab = NULL;
17659 }
17660
17661 /* A convenience function to find the proper .debug_line section for a CU.  */
17662
17663 static struct dwarf2_section_info *
17664 get_debug_line_section (struct dwarf2_cu *cu)
17665 {
17666   struct dwarf2_section_info *section;
17667
17668   /* For TUs in DWO files, the DW_AT_stmt_list attribute lives in the
17669      DWO file.  */
17670   if (cu->dwo_unit && cu->per_cu->is_debug_types)
17671     section = &cu->dwo_unit->dwo_file->sections.line;
17672   else if (cu->per_cu->is_dwz)
17673     {
17674       struct dwz_file *dwz = dwarf2_get_dwz_file ();
17675
17676       section = &dwz->line;
17677     }
17678   else
17679     section = &dwarf2_per_objfile->line;
17680
17681   return section;
17682 }
17683
17684 /* Forwarding function for read_formatted_entries.  */
17685
17686 static void
17687 add_include_dir_stub (struct line_header *lh, const char *name,
17688                       unsigned int dir_index, unsigned int mod_time,
17689                       unsigned int length)
17690 {
17691   add_include_dir (lh, name);
17692 }
17693
17694 /* Read directory or file name entry format, starting with byte of
17695    format count entries, ULEB128 pairs of entry formats, ULEB128 of
17696    entries count and the entries themselves in the described entry
17697    format.  */
17698
17699 static void
17700 read_formatted_entries (bfd *abfd, const gdb_byte **bufp,
17701                         struct line_header *lh,
17702                         const struct comp_unit_head *cu_header,
17703                         void (*callback) (struct line_header *lh,
17704                                           const char *name,
17705                                           unsigned int dir_index,
17706                                           unsigned int mod_time,
17707                                           unsigned int length))
17708 {
17709   gdb_byte format_count, formati;
17710   ULONGEST data_count, datai;
17711   const gdb_byte *buf = *bufp;
17712   const gdb_byte *format_header_data;
17713   int i;
17714   unsigned int bytes_read;
17715
17716   format_count = read_1_byte (abfd, buf);
17717   buf += 1;
17718   format_header_data = buf;
17719   for (formati = 0; formati < format_count; formati++)
17720     {
17721       read_unsigned_leb128 (abfd, buf, &bytes_read);
17722       buf += bytes_read;
17723       read_unsigned_leb128 (abfd, buf, &bytes_read);
17724       buf += bytes_read;
17725     }
17726
17727   data_count = read_unsigned_leb128 (abfd, buf, &bytes_read);
17728   buf += bytes_read;
17729   for (datai = 0; datai < data_count; datai++)
17730     {
17731       const gdb_byte *format = format_header_data;
17732       struct file_entry fe;
17733
17734       memset (&fe, 0, sizeof (fe));
17735
17736       for (formati = 0; formati < format_count; formati++)
17737         {
17738           ULONGEST content_type, form;
17739           const char *string_trash;
17740           const char **stringp = &string_trash;
17741           unsigned int uint_trash, *uintp = &uint_trash;
17742
17743           content_type = read_unsigned_leb128 (abfd, format, &bytes_read);
17744           format += bytes_read;
17745           switch (content_type)
17746             {
17747             case DW_LNCT_path:
17748               stringp = &fe.name;
17749               break;
17750             case DW_LNCT_directory_index:
17751               uintp = &fe.dir_index;
17752               break;
17753             case DW_LNCT_timestamp:
17754               uintp = &fe.mod_time;
17755               break;
17756             case DW_LNCT_size:
17757               uintp = &fe.length;
17758               break;
17759             case DW_LNCT_MD5:
17760               break;
17761             default:
17762               complaint (&symfile_complaints,
17763                          _("Unknown format content type %s"),
17764                          pulongest (content_type));
17765             }
17766
17767           form = read_unsigned_leb128 (abfd, format, &bytes_read);
17768           format += bytes_read;
17769           switch (form)
17770             {
17771             case DW_FORM_string:
17772               *stringp = read_direct_string (abfd, buf, &bytes_read);
17773               buf += bytes_read;
17774               break;
17775
17776             case DW_FORM_line_strp:
17777               *stringp = read_indirect_line_string (abfd, buf, cu_header, &bytes_read);
17778               buf += bytes_read;
17779               break;
17780
17781             case DW_FORM_data1:
17782               *uintp = read_1_byte (abfd, buf);
17783               buf += 1;
17784               break;
17785
17786             case DW_FORM_data2:
17787               *uintp = read_2_bytes (abfd, buf);
17788               buf += 2;
17789               break;
17790
17791             case DW_FORM_data4:
17792               *uintp = read_4_bytes (abfd, buf);
17793               buf += 4;
17794               break;
17795
17796             case DW_FORM_data8:
17797               *uintp = read_8_bytes (abfd, buf);
17798               buf += 8;
17799               break;
17800
17801             case DW_FORM_udata:
17802               *uintp = read_unsigned_leb128 (abfd, buf, &bytes_read);
17803               buf += bytes_read;
17804               break;
17805
17806             case DW_FORM_block:
17807               /* It is valid only for DW_LNCT_timestamp which is ignored by
17808                  current GDB.  */
17809               break;
17810             }
17811         }
17812
17813       callback (lh, fe.name, fe.dir_index, fe.mod_time, fe.length);
17814     }
17815
17816   *bufp = buf;
17817 }
17818
17819 /* Read the statement program header starting at OFFSET in
17820    .debug_line, or .debug_line.dwo.  Return a pointer
17821    to a struct line_header, allocated using xmalloc.
17822    Returns NULL if there is a problem reading the header, e.g., if it
17823    has a version we don't understand.
17824
17825    NOTE: the strings in the include directory and file name tables of
17826    the returned object point into the dwarf line section buffer,
17827    and must not be freed.  */
17828
17829 static struct line_header *
17830 dwarf_decode_line_header (unsigned int offset, struct dwarf2_cu *cu)
17831 {
17832   struct cleanup *back_to;
17833   struct line_header *lh;
17834   const gdb_byte *line_ptr;
17835   unsigned int bytes_read, offset_size;
17836   int i;
17837   const char *cur_dir, *cur_file;
17838   struct dwarf2_section_info *section;
17839   bfd *abfd;
17840
17841   section = get_debug_line_section (cu);
17842   dwarf2_read_section (dwarf2_per_objfile->objfile, section);
17843   if (section->buffer == NULL)
17844     {
17845       if (cu->dwo_unit && cu->per_cu->is_debug_types)
17846         complaint (&symfile_complaints, _("missing .debug_line.dwo section"));
17847       else
17848         complaint (&symfile_complaints, _("missing .debug_line section"));
17849       return 0;
17850     }
17851
17852   /* We can't do this until we know the section is non-empty.
17853      Only then do we know we have such a section.  */
17854   abfd = get_section_bfd_owner (section);
17855
17856   /* Make sure that at least there's room for the total_length field.
17857      That could be 12 bytes long, but we're just going to fudge that.  */
17858   if (offset + 4 >= section->size)
17859     {
17860       dwarf2_statement_list_fits_in_line_number_section_complaint ();
17861       return 0;
17862     }
17863
17864   lh = XNEW (struct line_header);
17865   memset (lh, 0, sizeof (*lh));
17866   back_to = make_cleanup ((make_cleanup_ftype *) free_line_header,
17867                           (void *) lh);
17868
17869   lh->offset.sect_off = offset;
17870   lh->offset_in_dwz = cu->per_cu->is_dwz;
17871
17872   line_ptr = section->buffer + offset;
17873
17874   /* Read in the header.  */
17875   lh->total_length =
17876     read_checked_initial_length_and_offset (abfd, line_ptr, &cu->header,
17877                                             &bytes_read, &offset_size);
17878   line_ptr += bytes_read;
17879   if (line_ptr + lh->total_length > (section->buffer + section->size))
17880     {
17881       dwarf2_statement_list_fits_in_line_number_section_complaint ();
17882       do_cleanups (back_to);
17883       return 0;
17884     }
17885   lh->statement_program_end = line_ptr + lh->total_length;
17886   lh->version = read_2_bytes (abfd, line_ptr);
17887   line_ptr += 2;
17888   if (lh->version > 5)
17889     {
17890       /* This is a version we don't understand.  The format could have
17891          changed in ways we don't handle properly so just punt.  */
17892       complaint (&symfile_complaints,
17893                  _("unsupported version in .debug_line section"));
17894       return NULL;
17895     }
17896   if (lh->version >= 5)
17897     {
17898       gdb_byte segment_selector_size;
17899
17900       /* Skip address size.  */
17901       read_1_byte (abfd, line_ptr);
17902       line_ptr += 1;
17903
17904       segment_selector_size = read_1_byte (abfd, line_ptr);
17905       line_ptr += 1;
17906       if (segment_selector_size != 0)
17907         {
17908           complaint (&symfile_complaints,
17909                      _("unsupported segment selector size %u "
17910                        "in .debug_line section"),
17911                      segment_selector_size);
17912           return NULL;
17913         }
17914     }
17915   lh->header_length = read_offset_1 (abfd, line_ptr, offset_size);
17916   line_ptr += offset_size;
17917   lh->minimum_instruction_length = read_1_byte (abfd, line_ptr);
17918   line_ptr += 1;
17919   if (lh->version >= 4)
17920     {
17921       lh->maximum_ops_per_instruction = read_1_byte (abfd, line_ptr);
17922       line_ptr += 1;
17923     }
17924   else
17925     lh->maximum_ops_per_instruction = 1;
17926
17927   if (lh->maximum_ops_per_instruction == 0)
17928     {
17929       lh->maximum_ops_per_instruction = 1;
17930       complaint (&symfile_complaints,
17931                  _("invalid maximum_ops_per_instruction "
17932                    "in `.debug_line' section"));
17933     }
17934
17935   lh->default_is_stmt = read_1_byte (abfd, line_ptr);
17936   line_ptr += 1;
17937   lh->line_base = read_1_signed_byte (abfd, line_ptr);
17938   line_ptr += 1;
17939   lh->line_range = read_1_byte (abfd, line_ptr);
17940   line_ptr += 1;
17941   lh->opcode_base = read_1_byte (abfd, line_ptr);
17942   line_ptr += 1;
17943   lh->standard_opcode_lengths = XNEWVEC (unsigned char, lh->opcode_base);
17944
17945   lh->standard_opcode_lengths[0] = 1;  /* This should never be used anyway.  */
17946   for (i = 1; i < lh->opcode_base; ++i)
17947     {
17948       lh->standard_opcode_lengths[i] = read_1_byte (abfd, line_ptr);
17949       line_ptr += 1;
17950     }
17951
17952   if (lh->version >= 5)
17953     {
17954       /* Read directory table.  */
17955       read_formatted_entries (abfd, &line_ptr, lh, &cu->header,
17956                               add_include_dir_stub);
17957
17958       /* Read file name table.  */
17959       read_formatted_entries (abfd, &line_ptr, lh, &cu->header, add_file_name);
17960     }
17961   else
17962     {
17963       /* Read directory table.  */
17964       while ((cur_dir = read_direct_string (abfd, line_ptr, &bytes_read)) != NULL)
17965         {
17966           line_ptr += bytes_read;
17967           add_include_dir (lh, cur_dir);
17968         }
17969       line_ptr += bytes_read;
17970
17971       /* Read file name table.  */
17972       while ((cur_file = read_direct_string (abfd, line_ptr, &bytes_read)) != NULL)
17973         {
17974           unsigned int dir_index, mod_time, length;
17975
17976           line_ptr += bytes_read;
17977           dir_index = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
17978           line_ptr += bytes_read;
17979           mod_time = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
17980           line_ptr += bytes_read;
17981           length = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
17982           line_ptr += bytes_read;
17983
17984           add_file_name (lh, cur_file, dir_index, mod_time, length);
17985         }
17986       line_ptr += bytes_read;
17987     }
17988   lh->statement_program_start = line_ptr;
17989
17990   if (line_ptr > (section->buffer + section->size))
17991     complaint (&symfile_complaints,
17992                _("line number info header doesn't "
17993                  "fit in `.debug_line' section"));
17994
17995   discard_cleanups (back_to);
17996   return lh;
17997 }
17998
17999 /* Subroutine of dwarf_decode_lines to simplify it.
18000    Return the file name of the psymtab for included file FILE_INDEX
18001    in line header LH of PST.
18002    COMP_DIR is the compilation directory (DW_AT_comp_dir) or NULL if unknown.
18003    If space for the result is malloc'd, it will be freed by a cleanup.
18004    Returns NULL if FILE_INDEX should be ignored, i.e., it is pst->filename.
18005
18006    The function creates dangling cleanup registration.  */
18007
18008 static const char *
18009 psymtab_include_file_name (const struct line_header *lh, int file_index,
18010                            const struct partial_symtab *pst,
18011                            const char *comp_dir)
18012 {
18013   const file_entry &fe = lh->file_names[file_index];
18014   const char *include_name = fe.name;
18015   const char *include_name_to_compare = include_name;
18016   const char *pst_filename;
18017   char *copied_name = NULL;
18018   int file_is_pst;
18019
18020   const char *dir_name = fe.include_dir (lh);
18021
18022   if (!IS_ABSOLUTE_PATH (include_name)
18023       && (dir_name != NULL || comp_dir != NULL))
18024     {
18025       /* Avoid creating a duplicate psymtab for PST.
18026          We do this by comparing INCLUDE_NAME and PST_FILENAME.
18027          Before we do the comparison, however, we need to account
18028          for DIR_NAME and COMP_DIR.
18029          First prepend dir_name (if non-NULL).  If we still don't
18030          have an absolute path prepend comp_dir (if non-NULL).
18031          However, the directory we record in the include-file's
18032          psymtab does not contain COMP_DIR (to match the
18033          corresponding symtab(s)).
18034
18035          Example:
18036
18037          bash$ cd /tmp
18038          bash$ gcc -g ./hello.c
18039          include_name = "hello.c"
18040          dir_name = "."
18041          DW_AT_comp_dir = comp_dir = "/tmp"
18042          DW_AT_name = "./hello.c"
18043
18044       */
18045
18046       if (dir_name != NULL)
18047         {
18048           char *tem = concat (dir_name, SLASH_STRING,
18049                               include_name, (char *)NULL);
18050
18051           make_cleanup (xfree, tem);
18052           include_name = tem;
18053           include_name_to_compare = include_name;
18054         }
18055       if (!IS_ABSOLUTE_PATH (include_name) && comp_dir != NULL)
18056         {
18057           char *tem = concat (comp_dir, SLASH_STRING,
18058                               include_name, (char *)NULL);
18059
18060           make_cleanup (xfree, tem);
18061           include_name_to_compare = tem;
18062         }
18063     }
18064
18065   pst_filename = pst->filename;
18066   if (!IS_ABSOLUTE_PATH (pst_filename) && pst->dirname != NULL)
18067     {
18068       copied_name = concat (pst->dirname, SLASH_STRING,
18069                             pst_filename, (char *)NULL);
18070       pst_filename = copied_name;
18071     }
18072
18073   file_is_pst = FILENAME_CMP (include_name_to_compare, pst_filename) == 0;
18074
18075   if (copied_name != NULL)
18076     xfree (copied_name);
18077
18078   if (file_is_pst)
18079     return NULL;
18080   return include_name;
18081 }
18082
18083 /* State machine to track the state of the line number program.  */
18084
18085 struct lnp_state_machine
18086 {
18087   file_entry *current_file ()
18088   {
18089     /* lh->file_names is 0-based, but the file name numbers in the
18090        statement program are 1-based.  */
18091     return the_line_header->file_name_at (file - 1);
18092   }
18093
18094   /* The line number header.  */
18095   line_header *the_line_header;
18096
18097   /* These are part of the standard DWARF line number state machine.  */
18098
18099   unsigned char op_index;
18100   /* The line table index (1-based) of the current file.  */
18101   unsigned int file;
18102   unsigned int line;
18103   CORE_ADDR address;
18104   int is_stmt;
18105   unsigned int discriminator;
18106
18107   /* Additional bits of state we need to track.  */
18108
18109   /* The last file that we called dwarf2_start_subfile for.
18110      This is only used for TLLs.  */
18111   unsigned int last_file;
18112   /* The last file a line number was recorded for.  */
18113   struct subfile *last_subfile;
18114
18115   /* The function to call to record a line.  */
18116   record_line_ftype *record_line;
18117
18118   /* The last line number that was recorded, used to coalesce
18119      consecutive entries for the same line.  This can happen, for
18120      example, when discriminators are present.  PR 17276.  */
18121   unsigned int last_line;
18122   int line_has_non_zero_discriminator;
18123 };
18124
18125 /* There's a lot of static state to pass to dwarf_record_line.
18126    This keeps it all together.  */
18127
18128 typedef struct
18129 {
18130   /* The gdbarch.  */
18131   struct gdbarch *gdbarch;
18132
18133   /* The line number header.  */
18134   struct line_header *line_header;
18135
18136   /* Non-zero if we're recording lines.
18137      Otherwise we're building partial symtabs and are just interested in
18138      finding include files mentioned by the line number program.  */
18139   int record_lines_p;
18140 } lnp_reader_state;
18141
18142 /* Ignore this record_line request.  */
18143
18144 static void
18145 noop_record_line (struct subfile *subfile, int line, CORE_ADDR pc)
18146 {
18147   return;
18148 }
18149
18150 /* Return non-zero if we should add LINE to the line number table.
18151    LINE is the line to add, LAST_LINE is the last line that was added,
18152    LAST_SUBFILE is the subfile for LAST_LINE.
18153    LINE_HAS_NON_ZERO_DISCRIMINATOR is non-zero if LINE has ever
18154    had a non-zero discriminator.
18155
18156    We have to be careful in the presence of discriminators.
18157    E.g., for this line:
18158
18159      for (i = 0; i < 100000; i++);
18160
18161    clang can emit four line number entries for that one line,
18162    each with a different discriminator.
18163    See gdb.dwarf2/dw2-single-line-discriminators.exp for an example.
18164
18165    However, we want gdb to coalesce all four entries into one.
18166    Otherwise the user could stepi into the middle of the line and
18167    gdb would get confused about whether the pc really was in the
18168    middle of the line.
18169
18170    Things are further complicated by the fact that two consecutive
18171    line number entries for the same line is a heuristic used by gcc
18172    to denote the end of the prologue.  So we can't just discard duplicate
18173    entries, we have to be selective about it.  The heuristic we use is
18174    that we only collapse consecutive entries for the same line if at least
18175    one of those entries has a non-zero discriminator.  PR 17276.
18176
18177    Note: Addresses in the line number state machine can never go backwards
18178    within one sequence, thus this coalescing is ok.  */
18179
18180 static int
18181 dwarf_record_line_p (unsigned int line, unsigned int last_line,
18182                      int line_has_non_zero_discriminator,
18183                      struct subfile *last_subfile)
18184 {
18185   if (current_subfile != last_subfile)
18186     return 1;
18187   if (line != last_line)
18188     return 1;
18189   /* Same line for the same file that we've seen already.
18190      As a last check, for pr 17276, only record the line if the line
18191      has never had a non-zero discriminator.  */
18192   if (!line_has_non_zero_discriminator)
18193     return 1;
18194   return 0;
18195 }
18196
18197 /* Use P_RECORD_LINE to record line number LINE beginning at address ADDRESS
18198    in the line table of subfile SUBFILE.  */
18199
18200 static void
18201 dwarf_record_line_1 (struct gdbarch *gdbarch, struct subfile *subfile,
18202                      unsigned int line, CORE_ADDR address,
18203                      record_line_ftype p_record_line)
18204 {
18205   CORE_ADDR addr = gdbarch_addr_bits_remove (gdbarch, address);
18206
18207   if (dwarf_line_debug)
18208     {
18209       fprintf_unfiltered (gdb_stdlog,
18210                           "Recording line %u, file %s, address %s\n",
18211                           line, lbasename (subfile->name),
18212                           paddress (gdbarch, address));
18213     }
18214
18215   (*p_record_line) (subfile, line, addr);
18216 }
18217
18218 /* Subroutine of dwarf_decode_lines_1 to simplify it.
18219    Mark the end of a set of line number records.
18220    The arguments are the same as for dwarf_record_line_1.
18221    If SUBFILE is NULL the request is ignored.  */
18222
18223 static void
18224 dwarf_finish_line (struct gdbarch *gdbarch, struct subfile *subfile,
18225                    CORE_ADDR address, record_line_ftype p_record_line)
18226 {
18227   if (subfile == NULL)
18228     return;
18229
18230   if (dwarf_line_debug)
18231     {
18232       fprintf_unfiltered (gdb_stdlog,
18233                           "Finishing current line, file %s, address %s\n",
18234                           lbasename (subfile->name),
18235                           paddress (gdbarch, address));
18236     }
18237
18238   dwarf_record_line_1 (gdbarch, subfile, 0, address, p_record_line);
18239 }
18240
18241 /* Record the line in STATE.
18242    END_SEQUENCE is non-zero if we're processing the end of a sequence.  */
18243
18244 static void
18245 dwarf_record_line (lnp_reader_state *reader, lnp_state_machine *state,
18246                    int end_sequence)
18247 {
18248   const struct line_header *lh = reader->line_header;
18249   unsigned int line, discriminator;
18250   int is_stmt;
18251
18252   line = state->line;
18253   is_stmt = state->is_stmt;
18254   discriminator = state->discriminator;
18255
18256   if (dwarf_line_debug)
18257     {
18258       fprintf_unfiltered (gdb_stdlog,
18259                           "Processing actual line %u: file %u,"
18260                           " address %s, is_stmt %u, discrim %u\n",
18261                           line, state->file,
18262                           paddress (reader->gdbarch, state->address),
18263                           is_stmt, discriminator);
18264     }
18265
18266   file_entry *fe = state->current_file ();
18267
18268   if (fe == NULL)
18269     dwarf2_debug_line_missing_file_complaint ();
18270   /* For now we ignore lines not starting on an instruction boundary.
18271      But not when processing end_sequence for compatibility with the
18272      previous version of the code.  */
18273   else if (state->op_index == 0 || end_sequence)
18274     {
18275       fe->included_p = 1;
18276       if (reader->record_lines_p && is_stmt)
18277         {
18278           if (state->last_subfile != current_subfile || end_sequence)
18279             {
18280               dwarf_finish_line (reader->gdbarch, state->last_subfile,
18281                                  state->address, state->record_line);
18282             }
18283
18284           if (!end_sequence)
18285             {
18286               if (dwarf_record_line_p (line, state->last_line,
18287                                        state->line_has_non_zero_discriminator,
18288                                        state->last_subfile))
18289                 {
18290                   dwarf_record_line_1 (reader->gdbarch, current_subfile,
18291                                        line, state->address,
18292                                        state->record_line);
18293                 }
18294               state->last_subfile = current_subfile;
18295               state->last_line = line;
18296             }
18297         }
18298     }
18299 }
18300
18301 /* Initialize STATE for the start of a line number program.  */
18302
18303 static void
18304 init_lnp_state_machine (lnp_state_machine *state,
18305                         const lnp_reader_state *reader)
18306 {
18307   memset (state, 0, sizeof (*state));
18308
18309   /* Just starting, there is no "last file".  */
18310   state->last_file = 0;
18311   state->last_subfile = NULL;
18312
18313   state->record_line = record_line;
18314
18315   state->last_line = 0;
18316   state->line_has_non_zero_discriminator = 0;
18317
18318   /* Initialize these according to the DWARF spec.  */
18319   state->op_index = 0;
18320   state->file = 1;
18321   state->line = 1;
18322   /* Call `gdbarch_adjust_dwarf2_line' on the initial 0 address as if there
18323      was a line entry for it so that the backend has a chance to adjust it
18324      and also record it in case it needs it.  This is currently used by MIPS
18325      code, cf. `mips_adjust_dwarf2_line'.  */
18326   state->address = gdbarch_adjust_dwarf2_line (reader->gdbarch, 0, 0);
18327   state->is_stmt = reader->line_header->default_is_stmt;
18328   state->discriminator = 0;
18329   state->the_line_header = reader->line_header;
18330 }
18331
18332 /* Check address and if invalid nop-out the rest of the lines in this
18333    sequence.  */
18334
18335 static void
18336 check_line_address (struct dwarf2_cu *cu, lnp_state_machine *state,
18337                     const gdb_byte *line_ptr,
18338                     CORE_ADDR lowpc, CORE_ADDR address)
18339 {
18340   /* If address < lowpc then it's not a usable value, it's outside the
18341      pc range of the CU.  However, we restrict the test to only address
18342      values of zero to preserve GDB's previous behaviour which is to
18343      handle the specific case of a function being GC'd by the linker.  */
18344
18345   if (address == 0 && address < lowpc)
18346     {
18347       /* This line table is for a function which has been
18348          GCd by the linker.  Ignore it.  PR gdb/12528 */
18349
18350       struct objfile *objfile = cu->objfile;
18351       long line_offset = line_ptr - get_debug_line_section (cu)->buffer;
18352
18353       complaint (&symfile_complaints,
18354                  _(".debug_line address at offset 0x%lx is 0 [in module %s]"),
18355                  line_offset, objfile_name (objfile));
18356       state->record_line = noop_record_line;
18357       /* Note: sm.record_line is left as noop_record_line
18358          until we see DW_LNE_end_sequence.  */
18359     }
18360 }
18361
18362 /* Subroutine of dwarf_decode_lines to simplify it.
18363    Process the line number information in LH.
18364    If DECODE_FOR_PST_P is non-zero, all we do is process the line number
18365    program in order to set included_p for every referenced header.  */
18366
18367 static void
18368 dwarf_decode_lines_1 (struct line_header *lh, struct dwarf2_cu *cu,
18369                       const int decode_for_pst_p, CORE_ADDR lowpc)
18370 {
18371   const gdb_byte *line_ptr, *extended_end;
18372   const gdb_byte *line_end;
18373   unsigned int bytes_read, extended_len;
18374   unsigned char op_code, extended_op;
18375   CORE_ADDR baseaddr;
18376   struct objfile *objfile = cu->objfile;
18377   bfd *abfd = objfile->obfd;
18378   struct gdbarch *gdbarch = get_objfile_arch (objfile);
18379   /* Non-zero if we're recording line info (as opposed to building partial
18380      symtabs).  */
18381   int record_lines_p = !decode_for_pst_p;
18382   /* A collection of things we need to pass to dwarf_record_line.  */
18383   lnp_reader_state reader_state;
18384
18385   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
18386
18387   line_ptr = lh->statement_program_start;
18388   line_end = lh->statement_program_end;
18389
18390   reader_state.gdbarch = gdbarch;
18391   reader_state.line_header = lh;
18392   reader_state.record_lines_p = record_lines_p;
18393
18394   /* Read the statement sequences until there's nothing left.  */
18395   while (line_ptr < line_end)
18396     {
18397       /* The DWARF line number program state machine.  */
18398       lnp_state_machine state_machine;
18399       int end_sequence = 0;
18400
18401       /* Reset the state machine at the start of each sequence.  */
18402       init_lnp_state_machine (&state_machine, &reader_state);
18403
18404       if (record_lines_p)
18405         {
18406           /* Start a subfile for the current file of the state
18407              machine.  */
18408           const file_entry *fe = state_machine.current_file ();
18409
18410           if (fe != NULL)
18411             dwarf2_start_subfile (fe->name, fe->include_dir (lh));
18412         }
18413
18414       /* Decode the table.  */
18415       while (line_ptr < line_end && !end_sequence)
18416         {
18417           op_code = read_1_byte (abfd, line_ptr);
18418           line_ptr += 1;
18419
18420           if (op_code >= lh->opcode_base)
18421             {
18422               /* Special opcode.  */
18423               unsigned char adj_opcode;
18424               CORE_ADDR addr_adj;
18425               int line_delta;
18426
18427               adj_opcode = op_code - lh->opcode_base;
18428               addr_adj = (((state_machine.op_index
18429                             + (adj_opcode / lh->line_range))
18430                            / lh->maximum_ops_per_instruction)
18431                           * lh->minimum_instruction_length);
18432               state_machine.address
18433                 += gdbarch_adjust_dwarf2_line (gdbarch, addr_adj, 1);
18434               state_machine.op_index = ((state_machine.op_index
18435                                          + (adj_opcode / lh->line_range))
18436                                         % lh->maximum_ops_per_instruction);
18437               line_delta = lh->line_base + (adj_opcode % lh->line_range);
18438               state_machine.line += line_delta;
18439               if (line_delta != 0)
18440                 state_machine.line_has_non_zero_discriminator
18441                   = state_machine.discriminator != 0;
18442
18443               dwarf_record_line (&reader_state, &state_machine, 0);
18444               state_machine.discriminator = 0;
18445             }
18446           else switch (op_code)
18447             {
18448             case DW_LNS_extended_op:
18449               extended_len = read_unsigned_leb128 (abfd, line_ptr,
18450                                                    &bytes_read);
18451               line_ptr += bytes_read;
18452               extended_end = line_ptr + extended_len;
18453               extended_op = read_1_byte (abfd, line_ptr);
18454               line_ptr += 1;
18455               switch (extended_op)
18456                 {
18457                 case DW_LNE_end_sequence:
18458                   state_machine.record_line = record_line;
18459                   end_sequence = 1;
18460                   break;
18461                 case DW_LNE_set_address:
18462                   {
18463                     CORE_ADDR address
18464                       = read_address (abfd, line_ptr, cu, &bytes_read);
18465
18466                     line_ptr += bytes_read;
18467                     check_line_address (cu, &state_machine, line_ptr,
18468                                         lowpc, address);
18469                     state_machine.op_index = 0;
18470                     address += baseaddr;
18471                     state_machine.address
18472                       = gdbarch_adjust_dwarf2_line (gdbarch, address, 0);
18473                   }
18474                   break;
18475                 case DW_LNE_define_file:
18476                   {
18477                     const char *cur_file;
18478                     unsigned int dir_index, mod_time, length;
18479
18480                     cur_file = read_direct_string (abfd, line_ptr,
18481                                                    &bytes_read);
18482                     line_ptr += bytes_read;
18483                     dir_index =
18484                       read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
18485                     line_ptr += bytes_read;
18486                     mod_time =
18487                       read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
18488                     line_ptr += bytes_read;
18489                     length =
18490                       read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
18491                     line_ptr += bytes_read;
18492                     add_file_name (lh, cur_file, dir_index, mod_time, length);
18493                   }
18494                   break;
18495                 case DW_LNE_set_discriminator:
18496                   /* The discriminator is not interesting to the debugger;
18497                      just ignore it.  We still need to check its value though:
18498                      if there are consecutive entries for the same
18499                      (non-prologue) line we want to coalesce them.
18500                      PR 17276.  */
18501                   state_machine.discriminator
18502                     = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
18503                   state_machine.line_has_non_zero_discriminator
18504                     |= state_machine.discriminator != 0;
18505                   line_ptr += bytes_read;
18506                   break;
18507                 default:
18508                   complaint (&symfile_complaints,
18509                              _("mangled .debug_line section"));
18510                   return;
18511                 }
18512               /* Make sure that we parsed the extended op correctly.  If e.g.
18513                  we expected a different address size than the producer used,
18514                  we may have read the wrong number of bytes.  */
18515               if (line_ptr != extended_end)
18516                 {
18517                   complaint (&symfile_complaints,
18518                              _("mangled .debug_line section"));
18519                   return;
18520                 }
18521               break;
18522             case DW_LNS_copy:
18523               dwarf_record_line (&reader_state, &state_machine, 0);
18524               state_machine.discriminator = 0;
18525               break;
18526             case DW_LNS_advance_pc:
18527               {
18528                 CORE_ADDR adjust
18529                   = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
18530                 CORE_ADDR addr_adj;
18531
18532                 addr_adj = (((state_machine.op_index + adjust)
18533                              / lh->maximum_ops_per_instruction)
18534                             * lh->minimum_instruction_length);
18535                 state_machine.address
18536                   += gdbarch_adjust_dwarf2_line (gdbarch, addr_adj, 1);
18537                 state_machine.op_index = ((state_machine.op_index + adjust)
18538                                           % lh->maximum_ops_per_instruction);
18539                 line_ptr += bytes_read;
18540               }
18541               break;
18542             case DW_LNS_advance_line:
18543               {
18544                 int line_delta
18545                   = read_signed_leb128 (abfd, line_ptr, &bytes_read);
18546
18547                 state_machine.line += line_delta;
18548                 if (line_delta != 0)
18549                   state_machine.line_has_non_zero_discriminator
18550                     = state_machine.discriminator != 0;
18551                 line_ptr += bytes_read;
18552               }
18553               break;
18554             case DW_LNS_set_file:
18555               {
18556                 state_machine.file = read_unsigned_leb128 (abfd, line_ptr,
18557                                                            &bytes_read);
18558                 line_ptr += bytes_read;
18559
18560                 const file_entry *fe = state_machine.current_file ();
18561                 if (fe == NULL)
18562                   dwarf2_debug_line_missing_file_complaint ();
18563                 else
18564                   {
18565                     if (record_lines_p)
18566                       {
18567                         const char *dir = fe->include_dir (lh);
18568
18569                         state_machine.last_subfile = current_subfile;
18570                         state_machine.line_has_non_zero_discriminator
18571                           = state_machine.discriminator != 0;
18572                         dwarf2_start_subfile (fe->name, dir);
18573                       }
18574                   }
18575               }
18576               break;
18577             case DW_LNS_set_column:
18578               (void) read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
18579               line_ptr += bytes_read;
18580               break;
18581             case DW_LNS_negate_stmt:
18582               state_machine.is_stmt = (!state_machine.is_stmt);
18583               break;
18584             case DW_LNS_set_basic_block:
18585               break;
18586             /* Add to the address register of the state machine the
18587                address increment value corresponding to special opcode
18588                255.  I.e., this value is scaled by the minimum
18589                instruction length since special opcode 255 would have
18590                scaled the increment.  */
18591             case DW_LNS_const_add_pc:
18592               {
18593                 CORE_ADDR adjust = (255 - lh->opcode_base) / lh->line_range;
18594                 CORE_ADDR addr_adj;
18595
18596                 addr_adj = (((state_machine.op_index + adjust)
18597                              / lh->maximum_ops_per_instruction)
18598                             * lh->minimum_instruction_length);
18599                 state_machine.address
18600                   += gdbarch_adjust_dwarf2_line (gdbarch, addr_adj, 1);
18601                 state_machine.op_index = ((state_machine.op_index + adjust)
18602                                           % lh->maximum_ops_per_instruction);
18603               }
18604               break;
18605             case DW_LNS_fixed_advance_pc:
18606               {
18607                 CORE_ADDR addr_adj;
18608
18609                 addr_adj = read_2_bytes (abfd, line_ptr);
18610                 state_machine.address
18611                   += gdbarch_adjust_dwarf2_line (gdbarch, addr_adj, 1);
18612                 state_machine.op_index = 0;
18613                 line_ptr += 2;
18614               }
18615               break;
18616             default:
18617               {
18618                 /* Unknown standard opcode, ignore it.  */
18619                 int i;
18620
18621                 for (i = 0; i < lh->standard_opcode_lengths[op_code]; i++)
18622                   {
18623                     (void) read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
18624                     line_ptr += bytes_read;
18625                   }
18626               }
18627             }
18628         }
18629
18630       if (!end_sequence)
18631         dwarf2_debug_line_missing_end_sequence_complaint ();
18632
18633       /* We got a DW_LNE_end_sequence (or we ran off the end of the buffer,
18634          in which case we still finish recording the last line).  */
18635       dwarf_record_line (&reader_state, &state_machine, 1);
18636     }
18637 }
18638
18639 /* Decode the Line Number Program (LNP) for the given line_header
18640    structure and CU.  The actual information extracted and the type
18641    of structures created from the LNP depends on the value of PST.
18642
18643    1. If PST is NULL, then this procedure uses the data from the program
18644       to create all necessary symbol tables, and their linetables.
18645
18646    2. If PST is not NULL, this procedure reads the program to determine
18647       the list of files included by the unit represented by PST, and
18648       builds all the associated partial symbol tables.
18649
18650    COMP_DIR is the compilation directory (DW_AT_comp_dir) or NULL if unknown.
18651    It is used for relative paths in the line table.
18652    NOTE: When processing partial symtabs (pst != NULL),
18653    comp_dir == pst->dirname.
18654
18655    NOTE: It is important that psymtabs have the same file name (via strcmp)
18656    as the corresponding symtab.  Since COMP_DIR is not used in the name of the
18657    symtab we don't use it in the name of the psymtabs we create.
18658    E.g. expand_line_sal requires this when finding psymtabs to expand.
18659    A good testcase for this is mb-inline.exp.
18660
18661    LOWPC is the lowest address in CU (or 0 if not known).
18662
18663    Boolean DECODE_MAPPING specifies we need to fully decode .debug_line
18664    for its PC<->lines mapping information.  Otherwise only the filename
18665    table is read in.  */
18666
18667 static void
18668 dwarf_decode_lines (struct line_header *lh, const char *comp_dir,
18669                     struct dwarf2_cu *cu, struct partial_symtab *pst,
18670                     CORE_ADDR lowpc, int decode_mapping)
18671 {
18672   struct objfile *objfile = cu->objfile;
18673   const int decode_for_pst_p = (pst != NULL);
18674
18675   if (decode_mapping)
18676     dwarf_decode_lines_1 (lh, cu, decode_for_pst_p, lowpc);
18677
18678   if (decode_for_pst_p)
18679     {
18680       int file_index;
18681
18682       /* Now that we're done scanning the Line Header Program, we can
18683          create the psymtab of each included file.  */
18684       for (file_index = 0; file_index < lh->num_file_names; file_index++)
18685         if (lh->file_names[file_index].included_p == 1)
18686           {
18687             const char *include_name =
18688               psymtab_include_file_name (lh, file_index, pst, comp_dir);
18689             if (include_name != NULL)
18690               dwarf2_create_include_psymtab (include_name, pst, objfile);
18691           }
18692     }
18693   else
18694     {
18695       /* Make sure a symtab is created for every file, even files
18696          which contain only variables (i.e. no code with associated
18697          line numbers).  */
18698       struct compunit_symtab *cust = buildsym_compunit_symtab ();
18699       int i;
18700
18701       for (i = 0; i < lh->num_file_names; i++)
18702         {
18703           file_entry &fe = lh->file_names[i];
18704
18705           dwarf2_start_subfile (fe.name, fe.include_dir (lh));
18706
18707           if (current_subfile->symtab == NULL)
18708             {
18709               current_subfile->symtab
18710                 = allocate_symtab (cust, current_subfile->name);
18711             }
18712           fe.symtab = current_subfile->symtab;
18713         }
18714     }
18715 }
18716
18717 /* Start a subfile for DWARF.  FILENAME is the name of the file and
18718    DIRNAME the name of the source directory which contains FILENAME
18719    or NULL if not known.
18720    This routine tries to keep line numbers from identical absolute and
18721    relative file names in a common subfile.
18722
18723    Using the `list' example from the GDB testsuite, which resides in
18724    /srcdir and compiling it with Irix6.2 cc in /compdir using a filename
18725    of /srcdir/list0.c yields the following debugging information for list0.c:
18726
18727    DW_AT_name:          /srcdir/list0.c
18728    DW_AT_comp_dir:      /compdir
18729    files.files[0].name: list0.h
18730    files.files[0].dir:  /srcdir
18731    files.files[1].name: list0.c
18732    files.files[1].dir:  /srcdir
18733
18734    The line number information for list0.c has to end up in a single
18735    subfile, so that `break /srcdir/list0.c:1' works as expected.
18736    start_subfile will ensure that this happens provided that we pass the
18737    concatenation of files.files[1].dir and files.files[1].name as the
18738    subfile's name.  */
18739
18740 static void
18741 dwarf2_start_subfile (const char *filename, const char *dirname)
18742 {
18743   char *copy = NULL;
18744
18745   /* In order not to lose the line information directory,
18746      we concatenate it to the filename when it makes sense.
18747      Note that the Dwarf3 standard says (speaking of filenames in line
18748      information): ``The directory index is ignored for file names
18749      that represent full path names''.  Thus ignoring dirname in the
18750      `else' branch below isn't an issue.  */
18751
18752   if (!IS_ABSOLUTE_PATH (filename) && dirname != NULL)
18753     {
18754       copy = concat (dirname, SLASH_STRING, filename, (char *)NULL);
18755       filename = copy;
18756     }
18757
18758   start_subfile (filename);
18759
18760   if (copy != NULL)
18761     xfree (copy);
18762 }
18763
18764 /* Start a symtab for DWARF.
18765    NAME, COMP_DIR, LOW_PC are passed to start_symtab.  */
18766
18767 static struct compunit_symtab *
18768 dwarf2_start_symtab (struct dwarf2_cu *cu,
18769                      const char *name, const char *comp_dir, CORE_ADDR low_pc)
18770 {
18771   struct compunit_symtab *cust
18772     = start_symtab (cu->objfile, name, comp_dir, low_pc);
18773
18774   record_debugformat ("DWARF 2");
18775   record_producer (cu->producer);
18776
18777   /* We assume that we're processing GCC output.  */
18778   processing_gcc_compilation = 2;
18779
18780   cu->processing_has_namespace_info = 0;
18781
18782   return cust;
18783 }
18784
18785 static void
18786 var_decode_location (struct attribute *attr, struct symbol *sym,
18787                      struct dwarf2_cu *cu)
18788 {
18789   struct objfile *objfile = cu->objfile;
18790   struct comp_unit_head *cu_header = &cu->header;
18791
18792   /* NOTE drow/2003-01-30: There used to be a comment and some special
18793      code here to turn a symbol with DW_AT_external and a
18794      SYMBOL_VALUE_ADDRESS of 0 into a LOC_UNRESOLVED symbol.  This was
18795      necessary for platforms (maybe Alpha, certainly PowerPC GNU/Linux
18796      with some versions of binutils) where shared libraries could have
18797      relocations against symbols in their debug information - the
18798      minimal symbol would have the right address, but the debug info
18799      would not.  It's no longer necessary, because we will explicitly
18800      apply relocations when we read in the debug information now.  */
18801
18802   /* A DW_AT_location attribute with no contents indicates that a
18803      variable has been optimized away.  */
18804   if (attr_form_is_block (attr) && DW_BLOCK (attr)->size == 0)
18805     {
18806       SYMBOL_ACLASS_INDEX (sym) = LOC_OPTIMIZED_OUT;
18807       return;
18808     }
18809
18810   /* Handle one degenerate form of location expression specially, to
18811      preserve GDB's previous behavior when section offsets are
18812      specified.  If this is just a DW_OP_addr or DW_OP_GNU_addr_index
18813      then mark this symbol as LOC_STATIC.  */
18814
18815   if (attr_form_is_block (attr)
18816       && ((DW_BLOCK (attr)->data[0] == DW_OP_addr
18817            && DW_BLOCK (attr)->size == 1 + cu_header->addr_size)
18818           || (DW_BLOCK (attr)->data[0] == DW_OP_GNU_addr_index
18819               && (DW_BLOCK (attr)->size
18820                   == 1 + leb128_size (&DW_BLOCK (attr)->data[1])))))
18821     {
18822       unsigned int dummy;
18823
18824       if (DW_BLOCK (attr)->data[0] == DW_OP_addr)
18825         SYMBOL_VALUE_ADDRESS (sym) =
18826           read_address (objfile->obfd, DW_BLOCK (attr)->data + 1, cu, &dummy);
18827       else
18828         SYMBOL_VALUE_ADDRESS (sym) =
18829           read_addr_index_from_leb128 (cu, DW_BLOCK (attr)->data + 1, &dummy);
18830       SYMBOL_ACLASS_INDEX (sym) = LOC_STATIC;
18831       fixup_symbol_section (sym, objfile);
18832       SYMBOL_VALUE_ADDRESS (sym) += ANOFFSET (objfile->section_offsets,
18833                                               SYMBOL_SECTION (sym));
18834       return;
18835     }
18836
18837   /* NOTE drow/2002-01-30: It might be worthwhile to have a static
18838      expression evaluator, and use LOC_COMPUTED only when necessary
18839      (i.e. when the value of a register or memory location is
18840      referenced, or a thread-local block, etc.).  Then again, it might
18841      not be worthwhile.  I'm assuming that it isn't unless performance
18842      or memory numbers show me otherwise.  */
18843
18844   dwarf2_symbol_mark_computed (attr, sym, cu, 0);
18845
18846   if (SYMBOL_COMPUTED_OPS (sym)->location_has_loclist)
18847     cu->has_loclist = 1;
18848 }
18849
18850 /* Given a pointer to a DWARF information entry, figure out if we need
18851    to make a symbol table entry for it, and if so, create a new entry
18852    and return a pointer to it.
18853    If TYPE is NULL, determine symbol type from the die, otherwise
18854    used the passed type.
18855    If SPACE is not NULL, use it to hold the new symbol.  If it is
18856    NULL, allocate a new symbol on the objfile's obstack.  */
18857
18858 static struct symbol *
18859 new_symbol_full (struct die_info *die, struct type *type, struct dwarf2_cu *cu,
18860                  struct symbol *space)
18861 {
18862   struct objfile *objfile = cu->objfile;
18863   struct gdbarch *gdbarch = get_objfile_arch (objfile);
18864   struct symbol *sym = NULL;
18865   const char *name;
18866   struct attribute *attr = NULL;
18867   struct attribute *attr2 = NULL;
18868   CORE_ADDR baseaddr;
18869   struct pending **list_to_add = NULL;
18870
18871   int inlined_func = (die->tag == DW_TAG_inlined_subroutine);
18872
18873   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
18874
18875   name = dwarf2_name (die, cu);
18876   if (name)
18877     {
18878       const char *linkagename;
18879       int suppress_add = 0;
18880
18881       if (space)
18882         sym = space;
18883       else
18884         sym = allocate_symbol (objfile);
18885       OBJSTAT (objfile, n_syms++);
18886
18887       /* Cache this symbol's name and the name's demangled form (if any).  */
18888       SYMBOL_SET_LANGUAGE (sym, cu->language, &objfile->objfile_obstack);
18889       linkagename = dwarf2_physname (name, die, cu);
18890       SYMBOL_SET_NAMES (sym, linkagename, strlen (linkagename), 0, objfile);
18891
18892       /* Fortran does not have mangling standard and the mangling does differ
18893          between gfortran, iFort etc.  */
18894       if (cu->language == language_fortran
18895           && symbol_get_demangled_name (&(sym->ginfo)) == NULL)
18896         symbol_set_demangled_name (&(sym->ginfo),
18897                                    dwarf2_full_name (name, die, cu),
18898                                    NULL);
18899
18900       /* Default assumptions.
18901          Use the passed type or decode it from the die.  */
18902       SYMBOL_DOMAIN (sym) = VAR_DOMAIN;
18903       SYMBOL_ACLASS_INDEX (sym) = LOC_OPTIMIZED_OUT;
18904       if (type != NULL)
18905         SYMBOL_TYPE (sym) = type;
18906       else
18907         SYMBOL_TYPE (sym) = die_type (die, cu);
18908       attr = dwarf2_attr (die,
18909                           inlined_func ? DW_AT_call_line : DW_AT_decl_line,
18910                           cu);
18911       if (attr)
18912         {
18913           SYMBOL_LINE (sym) = DW_UNSND (attr);
18914         }
18915
18916       attr = dwarf2_attr (die,
18917                           inlined_func ? DW_AT_call_file : DW_AT_decl_file,
18918                           cu);
18919       if (attr)
18920         {
18921           unsigned int file_index = DW_UNSND (attr);
18922           struct file_entry *fe;
18923
18924           if (cu->line_header != NULL && file_index > 0)
18925             fe = cu->line_header->file_name_at (file_index - 1);
18926           else
18927             fe = NULL;
18928
18929           if (fe == NULL)
18930             complaint (&symfile_complaints,
18931                        _("file index out of range"));
18932           else
18933             symbol_set_symtab (sym, fe->symtab);
18934         }
18935
18936       switch (die->tag)
18937         {
18938         case DW_TAG_label:
18939           attr = dwarf2_attr (die, DW_AT_low_pc, cu);
18940           if (attr)
18941             {
18942               CORE_ADDR addr;
18943
18944               addr = attr_value_as_address (attr);
18945               addr = gdbarch_adjust_dwarf2_addr (gdbarch, addr + baseaddr);
18946               SYMBOL_VALUE_ADDRESS (sym) = addr;
18947             }
18948           SYMBOL_TYPE (sym) = objfile_type (objfile)->builtin_core_addr;
18949           SYMBOL_DOMAIN (sym) = LABEL_DOMAIN;
18950           SYMBOL_ACLASS_INDEX (sym) = LOC_LABEL;
18951           add_symbol_to_list (sym, cu->list_in_scope);
18952           break;
18953         case DW_TAG_subprogram:
18954           /* SYMBOL_BLOCK_VALUE (sym) will be filled in later by
18955              finish_block.  */
18956           SYMBOL_ACLASS_INDEX (sym) = LOC_BLOCK;
18957           attr2 = dwarf2_attr (die, DW_AT_external, cu);
18958           if ((attr2 && (DW_UNSND (attr2) != 0))
18959               || cu->language == language_ada)
18960             {
18961               /* Subprograms marked external are stored as a global symbol.
18962                  Ada subprograms, whether marked external or not, are always
18963                  stored as a global symbol, because we want to be able to
18964                  access them globally.  For instance, we want to be able
18965                  to break on a nested subprogram without having to
18966                  specify the context.  */
18967               list_to_add = &global_symbols;
18968             }
18969           else
18970             {
18971               list_to_add = cu->list_in_scope;
18972             }
18973           break;
18974         case DW_TAG_inlined_subroutine:
18975           /* SYMBOL_BLOCK_VALUE (sym) will be filled in later by
18976              finish_block.  */
18977           SYMBOL_ACLASS_INDEX (sym) = LOC_BLOCK;
18978           SYMBOL_INLINED (sym) = 1;
18979           list_to_add = cu->list_in_scope;
18980           break;
18981         case DW_TAG_template_value_param:
18982           suppress_add = 1;
18983           /* Fall through.  */
18984         case DW_TAG_constant:
18985         case DW_TAG_variable:
18986         case DW_TAG_member:
18987           /* Compilation with minimal debug info may result in
18988              variables with missing type entries.  Change the
18989              misleading `void' type to something sensible.  */
18990           if (TYPE_CODE (SYMBOL_TYPE (sym)) == TYPE_CODE_VOID)
18991             SYMBOL_TYPE (sym)
18992               = objfile_type (objfile)->nodebug_data_symbol;
18993
18994           attr = dwarf2_attr (die, DW_AT_const_value, cu);
18995           /* In the case of DW_TAG_member, we should only be called for
18996              static const members.  */
18997           if (die->tag == DW_TAG_member)
18998             {
18999               /* dwarf2_add_field uses die_is_declaration,
19000                  so we do the same.  */
19001               gdb_assert (die_is_declaration (die, cu));
19002               gdb_assert (attr);
19003             }
19004           if (attr)
19005             {
19006               dwarf2_const_value (attr, sym, cu);
19007               attr2 = dwarf2_attr (die, DW_AT_external, cu);
19008               if (!suppress_add)
19009                 {
19010                   if (attr2 && (DW_UNSND (attr2) != 0))
19011                     list_to_add = &global_symbols;
19012                   else
19013                     list_to_add = cu->list_in_scope;
19014                 }
19015               break;
19016             }
19017           attr = dwarf2_attr (die, DW_AT_location, cu);
19018           if (attr)
19019             {
19020               var_decode_location (attr, sym, cu);
19021               attr2 = dwarf2_attr (die, DW_AT_external, cu);
19022
19023               /* Fortran explicitly imports any global symbols to the local
19024                  scope by DW_TAG_common_block.  */
19025               if (cu->language == language_fortran && die->parent
19026                   && die->parent->tag == DW_TAG_common_block)
19027                 attr2 = NULL;
19028
19029               if (SYMBOL_CLASS (sym) == LOC_STATIC
19030                   && SYMBOL_VALUE_ADDRESS (sym) == 0
19031                   && !dwarf2_per_objfile->has_section_at_zero)
19032                 {
19033                   /* When a static variable is eliminated by the linker,
19034                      the corresponding debug information is not stripped
19035                      out, but the variable address is set to null;
19036                      do not add such variables into symbol table.  */
19037                 }
19038               else if (attr2 && (DW_UNSND (attr2) != 0))
19039                 {
19040                   /* Workaround gfortran PR debug/40040 - it uses
19041                      DW_AT_location for variables in -fPIC libraries which may
19042                      get overriden by other libraries/executable and get
19043                      a different address.  Resolve it by the minimal symbol
19044                      which may come from inferior's executable using copy
19045                      relocation.  Make this workaround only for gfortran as for
19046                      other compilers GDB cannot guess the minimal symbol
19047                      Fortran mangling kind.  */
19048                   if (cu->language == language_fortran && die->parent
19049                       && die->parent->tag == DW_TAG_module
19050                       && cu->producer
19051                       && startswith (cu->producer, "GNU Fortran"))
19052                     SYMBOL_ACLASS_INDEX (sym) = LOC_UNRESOLVED;
19053
19054                   /* A variable with DW_AT_external is never static,
19055                      but it may be block-scoped.  */
19056                   list_to_add = (cu->list_in_scope == &file_symbols
19057                                  ? &global_symbols : cu->list_in_scope);
19058                 }
19059               else
19060                 list_to_add = cu->list_in_scope;
19061             }
19062           else
19063             {
19064               /* We do not know the address of this symbol.
19065                  If it is an external symbol and we have type information
19066                  for it, enter the symbol as a LOC_UNRESOLVED symbol.
19067                  The address of the variable will then be determined from
19068                  the minimal symbol table whenever the variable is
19069                  referenced.  */
19070               attr2 = dwarf2_attr (die, DW_AT_external, cu);
19071
19072               /* Fortran explicitly imports any global symbols to the local
19073                  scope by DW_TAG_common_block.  */
19074               if (cu->language == language_fortran && die->parent
19075                   && die->parent->tag == DW_TAG_common_block)
19076                 {
19077                   /* SYMBOL_CLASS doesn't matter here because
19078                      read_common_block is going to reset it.  */
19079                   if (!suppress_add)
19080                     list_to_add = cu->list_in_scope;
19081                 }
19082               else if (attr2 && (DW_UNSND (attr2) != 0)
19083                        && dwarf2_attr (die, DW_AT_type, cu) != NULL)
19084                 {
19085                   /* A variable with DW_AT_external is never static, but it
19086                      may be block-scoped.  */
19087                   list_to_add = (cu->list_in_scope == &file_symbols
19088                                  ? &global_symbols : cu->list_in_scope);
19089
19090                   SYMBOL_ACLASS_INDEX (sym) = LOC_UNRESOLVED;
19091                 }
19092               else if (!die_is_declaration (die, cu))
19093                 {
19094                   /* Use the default LOC_OPTIMIZED_OUT class.  */
19095                   gdb_assert (SYMBOL_CLASS (sym) == LOC_OPTIMIZED_OUT);
19096                   if (!suppress_add)
19097                     list_to_add = cu->list_in_scope;
19098                 }
19099             }
19100           break;
19101         case DW_TAG_formal_parameter:
19102           /* If we are inside a function, mark this as an argument.  If
19103              not, we might be looking at an argument to an inlined function
19104              when we do not have enough information to show inlined frames;
19105              pretend it's a local variable in that case so that the user can
19106              still see it.  */
19107           if (context_stack_depth > 0
19108               && context_stack[context_stack_depth - 1].name != NULL)
19109             SYMBOL_IS_ARGUMENT (sym) = 1;
19110           attr = dwarf2_attr (die, DW_AT_location, cu);
19111           if (attr)
19112             {
19113               var_decode_location (attr, sym, cu);
19114             }
19115           attr = dwarf2_attr (die, DW_AT_const_value, cu);
19116           if (attr)
19117             {
19118               dwarf2_const_value (attr, sym, cu);
19119             }
19120
19121           list_to_add = cu->list_in_scope;
19122           break;
19123         case DW_TAG_unspecified_parameters:
19124           /* From varargs functions; gdb doesn't seem to have any
19125              interest in this information, so just ignore it for now.
19126              (FIXME?) */
19127           break;
19128         case DW_TAG_template_type_param:
19129           suppress_add = 1;
19130           /* Fall through.  */
19131         case DW_TAG_class_type:
19132         case DW_TAG_interface_type:
19133         case DW_TAG_structure_type:
19134         case DW_TAG_union_type:
19135         case DW_TAG_set_type:
19136         case DW_TAG_enumeration_type:
19137           SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
19138           SYMBOL_DOMAIN (sym) = STRUCT_DOMAIN;
19139
19140           {
19141             /* NOTE: carlton/2003-11-10: C++ class symbols shouldn't
19142                really ever be static objects: otherwise, if you try
19143                to, say, break of a class's method and you're in a file
19144                which doesn't mention that class, it won't work unless
19145                the check for all static symbols in lookup_symbol_aux
19146                saves you.  See the OtherFileClass tests in
19147                gdb.c++/namespace.exp.  */
19148
19149             if (!suppress_add)
19150               {
19151                 list_to_add = (cu->list_in_scope == &file_symbols
19152                                && cu->language == language_cplus
19153                                ? &global_symbols : cu->list_in_scope);
19154
19155                 /* The semantics of C++ state that "struct foo {
19156                    ... }" also defines a typedef for "foo".  */
19157                 if (cu->language == language_cplus
19158                     || cu->language == language_ada
19159                     || cu->language == language_d
19160                     || cu->language == language_rust)
19161                   {
19162                     /* The symbol's name is already allocated along
19163                        with this objfile, so we don't need to
19164                        duplicate it for the type.  */
19165                     if (TYPE_NAME (SYMBOL_TYPE (sym)) == 0)
19166                       TYPE_NAME (SYMBOL_TYPE (sym)) = SYMBOL_SEARCH_NAME (sym);
19167                   }
19168               }
19169           }
19170           break;
19171         case DW_TAG_typedef:
19172           SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
19173           SYMBOL_DOMAIN (sym) = VAR_DOMAIN;
19174           list_to_add = cu->list_in_scope;
19175           break;
19176         case DW_TAG_base_type:
19177         case DW_TAG_subrange_type:
19178           SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
19179           SYMBOL_DOMAIN (sym) = VAR_DOMAIN;
19180           list_to_add = cu->list_in_scope;
19181           break;
19182         case DW_TAG_enumerator:
19183           attr = dwarf2_attr (die, DW_AT_const_value, cu);
19184           if (attr)
19185             {
19186               dwarf2_const_value (attr, sym, cu);
19187             }
19188           {
19189             /* NOTE: carlton/2003-11-10: See comment above in the
19190                DW_TAG_class_type, etc. block.  */
19191
19192             list_to_add = (cu->list_in_scope == &file_symbols
19193                            && cu->language == language_cplus
19194                            ? &global_symbols : cu->list_in_scope);
19195           }
19196           break;
19197         case DW_TAG_imported_declaration:
19198         case DW_TAG_namespace:
19199           SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
19200           list_to_add = &global_symbols;
19201           break;
19202         case DW_TAG_module:
19203           SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
19204           SYMBOL_DOMAIN (sym) = MODULE_DOMAIN;
19205           list_to_add = &global_symbols;
19206           break;
19207         case DW_TAG_common_block:
19208           SYMBOL_ACLASS_INDEX (sym) = LOC_COMMON_BLOCK;
19209           SYMBOL_DOMAIN (sym) = COMMON_BLOCK_DOMAIN;
19210           add_symbol_to_list (sym, cu->list_in_scope);
19211           break;
19212         default:
19213           /* Not a tag we recognize.  Hopefully we aren't processing
19214              trash data, but since we must specifically ignore things
19215              we don't recognize, there is nothing else we should do at
19216              this point.  */
19217           complaint (&symfile_complaints, _("unsupported tag: '%s'"),
19218                      dwarf_tag_name (die->tag));
19219           break;
19220         }
19221
19222       if (suppress_add)
19223         {
19224           sym->hash_next = objfile->template_symbols;
19225           objfile->template_symbols = sym;
19226           list_to_add = NULL;
19227         }
19228
19229       if (list_to_add != NULL)
19230         add_symbol_to_list (sym, list_to_add);
19231
19232       /* For the benefit of old versions of GCC, check for anonymous
19233          namespaces based on the demangled name.  */
19234       if (!cu->processing_has_namespace_info
19235           && cu->language == language_cplus)
19236         cp_scan_for_anonymous_namespaces (sym, objfile);
19237     }
19238   return (sym);
19239 }
19240
19241 /* A wrapper for new_symbol_full that always allocates a new symbol.  */
19242
19243 static struct symbol *
19244 new_symbol (struct die_info *die, struct type *type, struct dwarf2_cu *cu)
19245 {
19246   return new_symbol_full (die, type, cu, NULL);
19247 }
19248
19249 /* Given an attr with a DW_FORM_dataN value in host byte order,
19250    zero-extend it as appropriate for the symbol's type.  The DWARF
19251    standard (v4) is not entirely clear about the meaning of using
19252    DW_FORM_dataN for a constant with a signed type, where the type is
19253    wider than the data.  The conclusion of a discussion on the DWARF
19254    list was that this is unspecified.  We choose to always zero-extend
19255    because that is the interpretation long in use by GCC.  */
19256
19257 static gdb_byte *
19258 dwarf2_const_value_data (const struct attribute *attr, struct obstack *obstack,
19259                          struct dwarf2_cu *cu, LONGEST *value, int bits)
19260 {
19261   struct objfile *objfile = cu->objfile;
19262   enum bfd_endian byte_order = bfd_big_endian (objfile->obfd) ?
19263                                 BFD_ENDIAN_BIG : BFD_ENDIAN_LITTLE;
19264   LONGEST l = DW_UNSND (attr);
19265
19266   if (bits < sizeof (*value) * 8)
19267     {
19268       l &= ((LONGEST) 1 << bits) - 1;
19269       *value = l;
19270     }
19271   else if (bits == sizeof (*value) * 8)
19272     *value = l;
19273   else
19274     {
19275       gdb_byte *bytes = (gdb_byte *) obstack_alloc (obstack, bits / 8);
19276       store_unsigned_integer (bytes, bits / 8, byte_order, l);
19277       return bytes;
19278     }
19279
19280   return NULL;
19281 }
19282
19283 /* Read a constant value from an attribute.  Either set *VALUE, or if
19284    the value does not fit in *VALUE, set *BYTES - either already
19285    allocated on the objfile obstack, or newly allocated on OBSTACK,
19286    or, set *BATON, if we translated the constant to a location
19287    expression.  */
19288
19289 static void
19290 dwarf2_const_value_attr (const struct attribute *attr, struct type *type,
19291                          const char *name, struct obstack *obstack,
19292                          struct dwarf2_cu *cu,
19293                          LONGEST *value, const gdb_byte **bytes,
19294                          struct dwarf2_locexpr_baton **baton)
19295 {
19296   struct objfile *objfile = cu->objfile;
19297   struct comp_unit_head *cu_header = &cu->header;
19298   struct dwarf_block *blk;
19299   enum bfd_endian byte_order = (bfd_big_endian (objfile->obfd) ?
19300                                 BFD_ENDIAN_BIG : BFD_ENDIAN_LITTLE);
19301
19302   *value = 0;
19303   *bytes = NULL;
19304   *baton = NULL;
19305
19306   switch (attr->form)
19307     {
19308     case DW_FORM_addr:
19309     case DW_FORM_GNU_addr_index:
19310       {
19311         gdb_byte *data;
19312
19313         if (TYPE_LENGTH (type) != cu_header->addr_size)
19314           dwarf2_const_value_length_mismatch_complaint (name,
19315                                                         cu_header->addr_size,
19316                                                         TYPE_LENGTH (type));
19317         /* Symbols of this form are reasonably rare, so we just
19318            piggyback on the existing location code rather than writing
19319            a new implementation of symbol_computed_ops.  */
19320         *baton = XOBNEW (obstack, struct dwarf2_locexpr_baton);
19321         (*baton)->per_cu = cu->per_cu;
19322         gdb_assert ((*baton)->per_cu);
19323
19324         (*baton)->size = 2 + cu_header->addr_size;
19325         data = (gdb_byte *) obstack_alloc (obstack, (*baton)->size);
19326         (*baton)->data = data;
19327
19328         data[0] = DW_OP_addr;
19329         store_unsigned_integer (&data[1], cu_header->addr_size,
19330                                 byte_order, DW_ADDR (attr));
19331         data[cu_header->addr_size + 1] = DW_OP_stack_value;
19332       }
19333       break;
19334     case DW_FORM_string:
19335     case DW_FORM_strp:
19336     case DW_FORM_GNU_str_index:
19337     case DW_FORM_GNU_strp_alt:
19338       /* DW_STRING is already allocated on the objfile obstack, point
19339          directly to it.  */
19340       *bytes = (const gdb_byte *) DW_STRING (attr);
19341       break;
19342     case DW_FORM_block1:
19343     case DW_FORM_block2:
19344     case DW_FORM_block4:
19345     case DW_FORM_block:
19346     case DW_FORM_exprloc:
19347     case DW_FORM_data16:
19348       blk = DW_BLOCK (attr);
19349       if (TYPE_LENGTH (type) != blk->size)
19350         dwarf2_const_value_length_mismatch_complaint (name, blk->size,
19351                                                       TYPE_LENGTH (type));
19352       *bytes = blk->data;
19353       break;
19354
19355       /* The DW_AT_const_value attributes are supposed to carry the
19356          symbol's value "represented as it would be on the target
19357          architecture."  By the time we get here, it's already been
19358          converted to host endianness, so we just need to sign- or
19359          zero-extend it as appropriate.  */
19360     case DW_FORM_data1:
19361       *bytes = dwarf2_const_value_data (attr, obstack, cu, value, 8);
19362       break;
19363     case DW_FORM_data2:
19364       *bytes = dwarf2_const_value_data (attr, obstack, cu, value, 16);
19365       break;
19366     case DW_FORM_data4:
19367       *bytes = dwarf2_const_value_data (attr, obstack, cu, value, 32);
19368       break;
19369     case DW_FORM_data8:
19370       *bytes = dwarf2_const_value_data (attr, obstack, cu, value, 64);
19371       break;
19372
19373     case DW_FORM_sdata:
19374       *value = DW_SND (attr);
19375       break;
19376
19377     case DW_FORM_udata:
19378       *value = DW_UNSND (attr);
19379       break;
19380
19381     default:
19382       complaint (&symfile_complaints,
19383                  _("unsupported const value attribute form: '%s'"),
19384                  dwarf_form_name (attr->form));
19385       *value = 0;
19386       break;
19387     }
19388 }
19389
19390
19391 /* Copy constant value from an attribute to a symbol.  */
19392
19393 static void
19394 dwarf2_const_value (const struct attribute *attr, struct symbol *sym,
19395                     struct dwarf2_cu *cu)
19396 {
19397   struct objfile *objfile = cu->objfile;
19398   LONGEST value;
19399   const gdb_byte *bytes;
19400   struct dwarf2_locexpr_baton *baton;
19401
19402   dwarf2_const_value_attr (attr, SYMBOL_TYPE (sym),
19403                            SYMBOL_PRINT_NAME (sym),
19404                            &objfile->objfile_obstack, cu,
19405                            &value, &bytes, &baton);
19406
19407   if (baton != NULL)
19408     {
19409       SYMBOL_LOCATION_BATON (sym) = baton;
19410       SYMBOL_ACLASS_INDEX (sym) = dwarf2_locexpr_index;
19411     }
19412   else if (bytes != NULL)
19413      {
19414       SYMBOL_VALUE_BYTES (sym) = bytes;
19415       SYMBOL_ACLASS_INDEX (sym) = LOC_CONST_BYTES;
19416     }
19417   else
19418     {
19419       SYMBOL_VALUE (sym) = value;
19420       SYMBOL_ACLASS_INDEX (sym) = LOC_CONST;
19421     }
19422 }
19423
19424 /* Return the type of the die in question using its DW_AT_type attribute.  */
19425
19426 static struct type *
19427 die_type (struct die_info *die, struct dwarf2_cu *cu)
19428 {
19429   struct attribute *type_attr;
19430
19431   type_attr = dwarf2_attr (die, DW_AT_type, cu);
19432   if (!type_attr)
19433     {
19434       /* A missing DW_AT_type represents a void type.  */
19435       return objfile_type (cu->objfile)->builtin_void;
19436     }
19437
19438   return lookup_die_type (die, type_attr, cu);
19439 }
19440
19441 /* True iff CU's producer generates GNAT Ada auxiliary information
19442    that allows to find parallel types through that information instead
19443    of having to do expensive parallel lookups by type name.  */
19444
19445 static int
19446 need_gnat_info (struct dwarf2_cu *cu)
19447 {
19448   /* FIXME: brobecker/2010-10-12: As of now, only the AdaCore version
19449      of GNAT produces this auxiliary information, without any indication
19450      that it is produced.  Part of enhancing the FSF version of GNAT
19451      to produce that information will be to put in place an indicator
19452      that we can use in order to determine whether the descriptive type
19453      info is available or not.  One suggestion that has been made is
19454      to use a new attribute, attached to the CU die.  For now, assume
19455      that the descriptive type info is not available.  */
19456   return 0;
19457 }
19458
19459 /* Return the auxiliary type of the die in question using its
19460    DW_AT_GNAT_descriptive_type attribute.  Returns NULL if the
19461    attribute is not present.  */
19462
19463 static struct type *
19464 die_descriptive_type (struct die_info *die, struct dwarf2_cu *cu)
19465 {
19466   struct attribute *type_attr;
19467
19468   type_attr = dwarf2_attr (die, DW_AT_GNAT_descriptive_type, cu);
19469   if (!type_attr)
19470     return NULL;
19471
19472   return lookup_die_type (die, type_attr, cu);
19473 }
19474
19475 /* If DIE has a descriptive_type attribute, then set the TYPE's
19476    descriptive type accordingly.  */
19477
19478 static void
19479 set_descriptive_type (struct type *type, struct die_info *die,
19480                       struct dwarf2_cu *cu)
19481 {
19482   struct type *descriptive_type = die_descriptive_type (die, cu);
19483
19484   if (descriptive_type)
19485     {
19486       ALLOCATE_GNAT_AUX_TYPE (type);
19487       TYPE_DESCRIPTIVE_TYPE (type) = descriptive_type;
19488     }
19489 }
19490
19491 /* Return the containing type of the die in question using its
19492    DW_AT_containing_type attribute.  */
19493
19494 static struct type *
19495 die_containing_type (struct die_info *die, struct dwarf2_cu *cu)
19496 {
19497   struct attribute *type_attr;
19498
19499   type_attr = dwarf2_attr (die, DW_AT_containing_type, cu);
19500   if (!type_attr)
19501     error (_("Dwarf Error: Problem turning containing type into gdb type "
19502              "[in module %s]"), objfile_name (cu->objfile));
19503
19504   return lookup_die_type (die, type_attr, cu);
19505 }
19506
19507 /* Return an error marker type to use for the ill formed type in DIE/CU.  */
19508
19509 static struct type *
19510 build_error_marker_type (struct dwarf2_cu *cu, struct die_info *die)
19511 {
19512   struct objfile *objfile = dwarf2_per_objfile->objfile;
19513   char *message, *saved;
19514
19515   message = xstrprintf (_("<unknown type in %s, CU 0x%x, DIE 0x%x>"),
19516                         objfile_name (objfile),
19517                         cu->header.offset.sect_off,
19518                         die->offset.sect_off);
19519   saved = (char *) obstack_copy0 (&objfile->objfile_obstack,
19520                                   message, strlen (message));
19521   xfree (message);
19522
19523   return init_type (objfile, TYPE_CODE_ERROR, 0, saved);
19524 }
19525
19526 /* Look up the type of DIE in CU using its type attribute ATTR.
19527    ATTR must be one of: DW_AT_type, DW_AT_GNAT_descriptive_type,
19528    DW_AT_containing_type.
19529    If there is no type substitute an error marker.  */
19530
19531 static struct type *
19532 lookup_die_type (struct die_info *die, const struct attribute *attr,
19533                  struct dwarf2_cu *cu)
19534 {
19535   struct objfile *objfile = cu->objfile;
19536   struct type *this_type;
19537
19538   gdb_assert (attr->name == DW_AT_type
19539               || attr->name == DW_AT_GNAT_descriptive_type
19540               || attr->name == DW_AT_containing_type);
19541
19542   /* First see if we have it cached.  */
19543
19544   if (attr->form == DW_FORM_GNU_ref_alt)
19545     {
19546       struct dwarf2_per_cu_data *per_cu;
19547       sect_offset offset = dwarf2_get_ref_die_offset (attr);
19548
19549       per_cu = dwarf2_find_containing_comp_unit (offset, 1, cu->objfile);
19550       this_type = get_die_type_at_offset (offset, per_cu);
19551     }
19552   else if (attr_form_is_ref (attr))
19553     {
19554       sect_offset offset = dwarf2_get_ref_die_offset (attr);
19555
19556       this_type = get_die_type_at_offset (offset, cu->per_cu);
19557     }
19558   else if (attr->form == DW_FORM_ref_sig8)
19559     {
19560       ULONGEST signature = DW_SIGNATURE (attr);
19561
19562       return get_signatured_type (die, signature, cu);
19563     }
19564   else
19565     {
19566       complaint (&symfile_complaints,
19567                  _("Dwarf Error: Bad type attribute %s in DIE"
19568                    " at 0x%x [in module %s]"),
19569                  dwarf_attr_name (attr->name), die->offset.sect_off,
19570                  objfile_name (objfile));
19571       return build_error_marker_type (cu, die);
19572     }
19573
19574   /* If not cached we need to read it in.  */
19575
19576   if (this_type == NULL)
19577     {
19578       struct die_info *type_die = NULL;
19579       struct dwarf2_cu *type_cu = cu;
19580
19581       if (attr_form_is_ref (attr))
19582         type_die = follow_die_ref (die, attr, &type_cu);
19583       if (type_die == NULL)
19584         return build_error_marker_type (cu, die);
19585       /* If we find the type now, it's probably because the type came
19586          from an inter-CU reference and the type's CU got expanded before
19587          ours.  */
19588       this_type = read_type_die (type_die, type_cu);
19589     }
19590
19591   /* If we still don't have a type use an error marker.  */
19592
19593   if (this_type == NULL)
19594     return build_error_marker_type (cu, die);
19595
19596   return this_type;
19597 }
19598
19599 /* Return the type in DIE, CU.
19600    Returns NULL for invalid types.
19601
19602    This first does a lookup in die_type_hash,
19603    and only reads the die in if necessary.
19604
19605    NOTE: This can be called when reading in partial or full symbols.  */
19606
19607 static struct type *
19608 read_type_die (struct die_info *die, struct dwarf2_cu *cu)
19609 {
19610   struct type *this_type;
19611
19612   this_type = get_die_type (die, cu);
19613   if (this_type)
19614     return this_type;
19615
19616   return read_type_die_1 (die, cu);
19617 }
19618
19619 /* Read the type in DIE, CU.
19620    Returns NULL for invalid types.  */
19621
19622 static struct type *
19623 read_type_die_1 (struct die_info *die, struct dwarf2_cu *cu)
19624 {
19625   struct type *this_type = NULL;
19626
19627   switch (die->tag)
19628     {
19629     case DW_TAG_class_type:
19630     case DW_TAG_interface_type:
19631     case DW_TAG_structure_type:
19632     case DW_TAG_union_type:
19633       this_type = read_structure_type (die, cu);
19634       break;
19635     case DW_TAG_enumeration_type:
19636       this_type = read_enumeration_type (die, cu);
19637       break;
19638     case DW_TAG_subprogram:
19639     case DW_TAG_subroutine_type:
19640     case DW_TAG_inlined_subroutine:
19641       this_type = read_subroutine_type (die, cu);
19642       break;
19643     case DW_TAG_array_type:
19644       this_type = read_array_type (die, cu);
19645       break;
19646     case DW_TAG_set_type:
19647       this_type = read_set_type (die, cu);
19648       break;
19649     case DW_TAG_pointer_type:
19650       this_type = read_tag_pointer_type (die, cu);
19651       break;
19652     case DW_TAG_ptr_to_member_type:
19653       this_type = read_tag_ptr_to_member_type (die, cu);
19654       break;
19655     case DW_TAG_reference_type:
19656       this_type = read_tag_reference_type (die, cu, TYPE_CODE_REF);
19657       break;
19658     case DW_TAG_rvalue_reference_type:
19659       this_type = read_tag_reference_type (die, cu, TYPE_CODE_RVALUE_REF);
19660       break;
19661     case DW_TAG_const_type:
19662       this_type = read_tag_const_type (die, cu);
19663       break;
19664     case DW_TAG_volatile_type:
19665       this_type = read_tag_volatile_type (die, cu);
19666       break;
19667     case DW_TAG_restrict_type:
19668       this_type = read_tag_restrict_type (die, cu);
19669       break;
19670     case DW_TAG_string_type:
19671       this_type = read_tag_string_type (die, cu);
19672       break;
19673     case DW_TAG_typedef:
19674       this_type = read_typedef (die, cu);
19675       break;
19676     case DW_TAG_subrange_type:
19677       this_type = read_subrange_type (die, cu);
19678       break;
19679     case DW_TAG_base_type:
19680       this_type = read_base_type (die, cu);
19681       break;
19682     case DW_TAG_unspecified_type:
19683       this_type = read_unspecified_type (die, cu);
19684       break;
19685     case DW_TAG_namespace:
19686       this_type = read_namespace_type (die, cu);
19687       break;
19688     case DW_TAG_module:
19689       this_type = read_module_type (die, cu);
19690       break;
19691     case DW_TAG_atomic_type:
19692       this_type = read_tag_atomic_type (die, cu);
19693       break;
19694     default:
19695       complaint (&symfile_complaints,
19696                  _("unexpected tag in read_type_die: '%s'"),
19697                  dwarf_tag_name (die->tag));
19698       break;
19699     }
19700
19701   return this_type;
19702 }
19703
19704 /* See if we can figure out if the class lives in a namespace.  We do
19705    this by looking for a member function; its demangled name will
19706    contain namespace info, if there is any.
19707    Return the computed name or NULL.
19708    Space for the result is allocated on the objfile's obstack.
19709    This is the full-die version of guess_partial_die_structure_name.
19710    In this case we know DIE has no useful parent.  */
19711
19712 static char *
19713 guess_full_die_structure_name (struct die_info *die, struct dwarf2_cu *cu)
19714 {
19715   struct die_info *spec_die;
19716   struct dwarf2_cu *spec_cu;
19717   struct die_info *child;
19718
19719   spec_cu = cu;
19720   spec_die = die_specification (die, &spec_cu);
19721   if (spec_die != NULL)
19722     {
19723       die = spec_die;
19724       cu = spec_cu;
19725     }
19726
19727   for (child = die->child;
19728        child != NULL;
19729        child = child->sibling)
19730     {
19731       if (child->tag == DW_TAG_subprogram)
19732         {
19733           const char *linkage_name;
19734
19735           linkage_name = dwarf2_string_attr (child, DW_AT_linkage_name, cu);
19736           if (linkage_name == NULL)
19737             linkage_name = dwarf2_string_attr (child, DW_AT_MIPS_linkage_name,
19738                                                cu);
19739           if (linkage_name != NULL)
19740             {
19741               char *actual_name
19742                 = language_class_name_from_physname (cu->language_defn,
19743                                                      linkage_name);
19744               char *name = NULL;
19745
19746               if (actual_name != NULL)
19747                 {
19748                   const char *die_name = dwarf2_name (die, cu);
19749
19750                   if (die_name != NULL
19751                       && strcmp (die_name, actual_name) != 0)
19752                     {
19753                       /* Strip off the class name from the full name.
19754                          We want the prefix.  */
19755                       int die_name_len = strlen (die_name);
19756                       int actual_name_len = strlen (actual_name);
19757
19758                       /* Test for '::' as a sanity check.  */
19759                       if (actual_name_len > die_name_len + 2
19760                           && actual_name[actual_name_len
19761                                          - die_name_len - 1] == ':')
19762                         name = (char *) obstack_copy0 (
19763                           &cu->objfile->per_bfd->storage_obstack,
19764                           actual_name, actual_name_len - die_name_len - 2);
19765                     }
19766                 }
19767               xfree (actual_name);
19768               return name;
19769             }
19770         }
19771     }
19772
19773   return NULL;
19774 }
19775
19776 /* GCC might emit a nameless typedef that has a linkage name.  Determine the
19777    prefix part in such case.  See
19778    http://gcc.gnu.org/bugzilla/show_bug.cgi?id=47510.  */
19779
19780 static char *
19781 anonymous_struct_prefix (struct die_info *die, struct dwarf2_cu *cu)
19782 {
19783   struct attribute *attr;
19784   const char *base;
19785
19786   if (die->tag != DW_TAG_class_type && die->tag != DW_TAG_interface_type
19787       && die->tag != DW_TAG_structure_type && die->tag != DW_TAG_union_type)
19788     return NULL;
19789
19790   if (dwarf2_string_attr (die, DW_AT_name, cu) != NULL)
19791     return NULL;
19792
19793   attr = dwarf2_attr (die, DW_AT_linkage_name, cu);
19794   if (attr == NULL)
19795     attr = dwarf2_attr (die, DW_AT_MIPS_linkage_name, cu);
19796   if (attr == NULL || DW_STRING (attr) == NULL)
19797     return NULL;
19798
19799   /* dwarf2_name had to be already called.  */
19800   gdb_assert (DW_STRING_IS_CANONICAL (attr));
19801
19802   /* Strip the base name, keep any leading namespaces/classes.  */
19803   base = strrchr (DW_STRING (attr), ':');
19804   if (base == NULL || base == DW_STRING (attr) || base[-1] != ':')
19805     return "";
19806
19807   return (char *) obstack_copy0 (&cu->objfile->per_bfd->storage_obstack,
19808                                  DW_STRING (attr),
19809                                  &base[-1] - DW_STRING (attr));
19810 }
19811
19812 /* Return the name of the namespace/class that DIE is defined within,
19813    or "" if we can't tell.  The caller should not xfree the result.
19814
19815    For example, if we're within the method foo() in the following
19816    code:
19817
19818    namespace N {
19819      class C {
19820        void foo () {
19821        }
19822      };
19823    }
19824
19825    then determine_prefix on foo's die will return "N::C".  */
19826
19827 static const char *
19828 determine_prefix (struct die_info *die, struct dwarf2_cu *cu)
19829 {
19830   struct die_info *parent, *spec_die;
19831   struct dwarf2_cu *spec_cu;
19832   struct type *parent_type;
19833   char *retval;
19834
19835   if (cu->language != language_cplus
19836       && cu->language != language_fortran && cu->language != language_d
19837       && cu->language != language_rust)
19838     return "";
19839
19840   retval = anonymous_struct_prefix (die, cu);
19841   if (retval)
19842     return retval;
19843
19844   /* We have to be careful in the presence of DW_AT_specification.
19845      For example, with GCC 3.4, given the code
19846
19847      namespace N {
19848        void foo() {
19849          // Definition of N::foo.
19850        }
19851      }
19852
19853      then we'll have a tree of DIEs like this:
19854
19855      1: DW_TAG_compile_unit
19856        2: DW_TAG_namespace        // N
19857          3: DW_TAG_subprogram     // declaration of N::foo
19858        4: DW_TAG_subprogram       // definition of N::foo
19859             DW_AT_specification   // refers to die #3
19860
19861      Thus, when processing die #4, we have to pretend that we're in
19862      the context of its DW_AT_specification, namely the contex of die
19863      #3.  */
19864   spec_cu = cu;
19865   spec_die = die_specification (die, &spec_cu);
19866   if (spec_die == NULL)
19867     parent = die->parent;
19868   else
19869     {
19870       parent = spec_die->parent;
19871       cu = spec_cu;
19872     }
19873
19874   if (parent == NULL)
19875     return "";
19876   else if (parent->building_fullname)
19877     {
19878       const char *name;
19879       const char *parent_name;
19880
19881       /* It has been seen on RealView 2.2 built binaries,
19882          DW_TAG_template_type_param types actually _defined_ as
19883          children of the parent class:
19884
19885          enum E {};
19886          template class <class Enum> Class{};
19887          Class<enum E> class_e;
19888
19889          1: DW_TAG_class_type (Class)
19890            2: DW_TAG_enumeration_type (E)
19891              3: DW_TAG_enumerator (enum1:0)
19892              3: DW_TAG_enumerator (enum2:1)
19893              ...
19894            2: DW_TAG_template_type_param
19895               DW_AT_type  DW_FORM_ref_udata (E)
19896
19897          Besides being broken debug info, it can put GDB into an
19898          infinite loop.  Consider:
19899
19900          When we're building the full name for Class<E>, we'll start
19901          at Class, and go look over its template type parameters,
19902          finding E.  We'll then try to build the full name of E, and
19903          reach here.  We're now trying to build the full name of E,
19904          and look over the parent DIE for containing scope.  In the
19905          broken case, if we followed the parent DIE of E, we'd again
19906          find Class, and once again go look at its template type
19907          arguments, etc., etc.  Simply don't consider such parent die
19908          as source-level parent of this die (it can't be, the language
19909          doesn't allow it), and break the loop here.  */
19910       name = dwarf2_name (die, cu);
19911       parent_name = dwarf2_name (parent, cu);
19912       complaint (&symfile_complaints,
19913                  _("template param type '%s' defined within parent '%s'"),
19914                  name ? name : "<unknown>",
19915                  parent_name ? parent_name : "<unknown>");
19916       return "";
19917     }
19918   else
19919     switch (parent->tag)
19920       {
19921       case DW_TAG_namespace:
19922         parent_type = read_type_die (parent, cu);
19923         /* GCC 4.0 and 4.1 had a bug (PR c++/28460) where they generated bogus
19924            DW_TAG_namespace DIEs with a name of "::" for the global namespace.
19925            Work around this problem here.  */
19926         if (cu->language == language_cplus
19927             && strcmp (TYPE_TAG_NAME (parent_type), "::") == 0)
19928           return "";
19929         /* We give a name to even anonymous namespaces.  */
19930         return TYPE_TAG_NAME (parent_type);
19931       case DW_TAG_class_type:
19932       case DW_TAG_interface_type:
19933       case DW_TAG_structure_type:
19934       case DW_TAG_union_type:
19935       case DW_TAG_module:
19936         parent_type = read_type_die (parent, cu);
19937         if (TYPE_TAG_NAME (parent_type) != NULL)
19938           return TYPE_TAG_NAME (parent_type);
19939         else
19940           /* An anonymous structure is only allowed non-static data
19941              members; no typedefs, no member functions, et cetera.
19942              So it does not need a prefix.  */
19943           return "";
19944       case DW_TAG_compile_unit:
19945       case DW_TAG_partial_unit:
19946         /* gcc-4.5 -gdwarf-4 can drop the enclosing namespace.  Cope.  */
19947         if (cu->language == language_cplus
19948             && !VEC_empty (dwarf2_section_info_def, dwarf2_per_objfile->types)
19949             && die->child != NULL
19950             && (die->tag == DW_TAG_class_type
19951                 || die->tag == DW_TAG_structure_type
19952                 || die->tag == DW_TAG_union_type))
19953           {
19954             char *name = guess_full_die_structure_name (die, cu);
19955             if (name != NULL)
19956               return name;
19957           }
19958         return "";
19959       case DW_TAG_enumeration_type:
19960         parent_type = read_type_die (parent, cu);
19961         if (TYPE_DECLARED_CLASS (parent_type))
19962           {
19963             if (TYPE_TAG_NAME (parent_type) != NULL)
19964               return TYPE_TAG_NAME (parent_type);
19965             return "";
19966           }
19967         /* Fall through.  */
19968       default:
19969         return determine_prefix (parent, cu);
19970       }
19971 }
19972
19973 /* Return a newly-allocated string formed by concatenating PREFIX and SUFFIX
19974    with appropriate separator.  If PREFIX or SUFFIX is NULL or empty, then
19975    simply copy the SUFFIX or PREFIX, respectively.  If OBS is non-null, perform
19976    an obconcat, otherwise allocate storage for the result.  The CU argument is
19977    used to determine the language and hence, the appropriate separator.  */
19978
19979 #define MAX_SEP_LEN 7  /* strlen ("__") + strlen ("_MOD_")  */
19980
19981 static char *
19982 typename_concat (struct obstack *obs, const char *prefix, const char *suffix,
19983                  int physname, struct dwarf2_cu *cu)
19984 {
19985   const char *lead = "";
19986   const char *sep;
19987
19988   if (suffix == NULL || suffix[0] == '\0'
19989       || prefix == NULL || prefix[0] == '\0')
19990     sep = "";
19991   else if (cu->language == language_d)
19992     {
19993       /* For D, the 'main' function could be defined in any module, but it
19994          should never be prefixed.  */
19995       if (strcmp (suffix, "D main") == 0)
19996         {
19997           prefix = "";
19998           sep = "";
19999         }
20000       else
20001         sep = ".";
20002     }
20003   else if (cu->language == language_fortran && physname)
20004     {
20005       /* This is gfortran specific mangling.  Normally DW_AT_linkage_name or
20006          DW_AT_MIPS_linkage_name is preferred and used instead.  */
20007
20008       lead = "__";
20009       sep = "_MOD_";
20010     }
20011   else
20012     sep = "::";
20013
20014   if (prefix == NULL)
20015     prefix = "";
20016   if (suffix == NULL)
20017     suffix = "";
20018
20019   if (obs == NULL)
20020     {
20021       char *retval
20022         = ((char *)
20023            xmalloc (strlen (prefix) + MAX_SEP_LEN + strlen (suffix) + 1));
20024
20025       strcpy (retval, lead);
20026       strcat (retval, prefix);
20027       strcat (retval, sep);
20028       strcat (retval, suffix);
20029       return retval;
20030     }
20031   else
20032     {
20033       /* We have an obstack.  */
20034       return obconcat (obs, lead, prefix, sep, suffix, (char *) NULL);
20035     }
20036 }
20037
20038 /* Return sibling of die, NULL if no sibling.  */
20039
20040 static struct die_info *
20041 sibling_die (struct die_info *die)
20042 {
20043   return die->sibling;
20044 }
20045
20046 /* Get name of a die, return NULL if not found.  */
20047
20048 static const char *
20049 dwarf2_canonicalize_name (const char *name, struct dwarf2_cu *cu,
20050                           struct obstack *obstack)
20051 {
20052   if (name && cu->language == language_cplus)
20053     {
20054       std::string canon_name = cp_canonicalize_string (name);
20055
20056       if (!canon_name.empty ())
20057         {
20058           if (canon_name != name)
20059             name = (const char *) obstack_copy0 (obstack,
20060                                                  canon_name.c_str (),
20061                                                  canon_name.length ());
20062         }
20063     }
20064
20065   return name;
20066 }
20067
20068 /* Get name of a die, return NULL if not found.
20069    Anonymous namespaces are converted to their magic string.  */
20070
20071 static const char *
20072 dwarf2_name (struct die_info *die, struct dwarf2_cu *cu)
20073 {
20074   struct attribute *attr;
20075
20076   attr = dwarf2_attr (die, DW_AT_name, cu);
20077   if ((!attr || !DW_STRING (attr))
20078       && die->tag != DW_TAG_namespace
20079       && die->tag != DW_TAG_class_type
20080       && die->tag != DW_TAG_interface_type
20081       && die->tag != DW_TAG_structure_type
20082       && die->tag != DW_TAG_union_type)
20083     return NULL;
20084
20085   switch (die->tag)
20086     {
20087     case DW_TAG_compile_unit:
20088     case DW_TAG_partial_unit:
20089       /* Compilation units have a DW_AT_name that is a filename, not
20090          a source language identifier.  */
20091     case DW_TAG_enumeration_type:
20092     case DW_TAG_enumerator:
20093       /* These tags always have simple identifiers already; no need
20094          to canonicalize them.  */
20095       return DW_STRING (attr);
20096
20097     case DW_TAG_namespace:
20098       if (attr != NULL && DW_STRING (attr) != NULL)
20099         return DW_STRING (attr);
20100       return CP_ANONYMOUS_NAMESPACE_STR;
20101
20102     case DW_TAG_class_type:
20103     case DW_TAG_interface_type:
20104     case DW_TAG_structure_type:
20105     case DW_TAG_union_type:
20106       /* Some GCC versions emit spurious DW_AT_name attributes for unnamed
20107          structures or unions.  These were of the form "._%d" in GCC 4.1,
20108          or simply "<anonymous struct>" or "<anonymous union>" in GCC 4.3
20109          and GCC 4.4.  We work around this problem by ignoring these.  */
20110       if (attr && DW_STRING (attr)
20111           && (startswith (DW_STRING (attr), "._")
20112               || startswith (DW_STRING (attr), "<anonymous")))
20113         return NULL;
20114
20115       /* GCC might emit a nameless typedef that has a linkage name.  See
20116          http://gcc.gnu.org/bugzilla/show_bug.cgi?id=47510.  */
20117       if (!attr || DW_STRING (attr) == NULL)
20118         {
20119           char *demangled = NULL;
20120
20121           attr = dwarf2_attr (die, DW_AT_linkage_name, cu);
20122           if (attr == NULL)
20123             attr = dwarf2_attr (die, DW_AT_MIPS_linkage_name, cu);
20124
20125           if (attr == NULL || DW_STRING (attr) == NULL)
20126             return NULL;
20127
20128           /* Avoid demangling DW_STRING (attr) the second time on a second
20129              call for the same DIE.  */
20130           if (!DW_STRING_IS_CANONICAL (attr))
20131             demangled = gdb_demangle (DW_STRING (attr), DMGL_TYPES);
20132
20133           if (demangled)
20134             {
20135               const char *base;
20136
20137               /* FIXME: we already did this for the partial symbol... */
20138               DW_STRING (attr)
20139                 = ((const char *)
20140                    obstack_copy0 (&cu->objfile->per_bfd->storage_obstack,
20141                                   demangled, strlen (demangled)));
20142               DW_STRING_IS_CANONICAL (attr) = 1;
20143               xfree (demangled);
20144
20145               /* Strip any leading namespaces/classes, keep only the base name.
20146                  DW_AT_name for named DIEs does not contain the prefixes.  */
20147               base = strrchr (DW_STRING (attr), ':');
20148               if (base && base > DW_STRING (attr) && base[-1] == ':')
20149                 return &base[1];
20150               else
20151                 return DW_STRING (attr);
20152             }
20153         }
20154       break;
20155
20156     default:
20157       break;
20158     }
20159
20160   if (!DW_STRING_IS_CANONICAL (attr))
20161     {
20162       DW_STRING (attr)
20163         = dwarf2_canonicalize_name (DW_STRING (attr), cu,
20164                                     &cu->objfile->per_bfd->storage_obstack);
20165       DW_STRING_IS_CANONICAL (attr) = 1;
20166     }
20167   return DW_STRING (attr);
20168 }
20169
20170 /* Return the die that this die in an extension of, or NULL if there
20171    is none.  *EXT_CU is the CU containing DIE on input, and the CU
20172    containing the return value on output.  */
20173
20174 static struct die_info *
20175 dwarf2_extension (struct die_info *die, struct dwarf2_cu **ext_cu)
20176 {
20177   struct attribute *attr;
20178
20179   attr = dwarf2_attr (die, DW_AT_extension, *ext_cu);
20180   if (attr == NULL)
20181     return NULL;
20182
20183   return follow_die_ref (die, attr, ext_cu);
20184 }
20185
20186 /* Convert a DIE tag into its string name.  */
20187
20188 static const char *
20189 dwarf_tag_name (unsigned tag)
20190 {
20191   const char *name = get_DW_TAG_name (tag);
20192
20193   if (name == NULL)
20194     return "DW_TAG_<unknown>";
20195
20196   return name;
20197 }
20198
20199 /* Convert a DWARF attribute code into its string name.  */
20200
20201 static const char *
20202 dwarf_attr_name (unsigned attr)
20203 {
20204   const char *name;
20205
20206 #ifdef MIPS /* collides with DW_AT_HP_block_index */
20207   if (attr == DW_AT_MIPS_fde)
20208     return "DW_AT_MIPS_fde";
20209 #else
20210   if (attr == DW_AT_HP_block_index)
20211     return "DW_AT_HP_block_index";
20212 #endif
20213
20214   name = get_DW_AT_name (attr);
20215
20216   if (name == NULL)
20217     return "DW_AT_<unknown>";
20218
20219   return name;
20220 }
20221
20222 /* Convert a DWARF value form code into its string name.  */
20223
20224 static const char *
20225 dwarf_form_name (unsigned form)
20226 {
20227   const char *name = get_DW_FORM_name (form);
20228
20229   if (name == NULL)
20230     return "DW_FORM_<unknown>";
20231
20232   return name;
20233 }
20234
20235 static char *
20236 dwarf_bool_name (unsigned mybool)
20237 {
20238   if (mybool)
20239     return "TRUE";
20240   else
20241     return "FALSE";
20242 }
20243
20244 /* Convert a DWARF type code into its string name.  */
20245
20246 static const char *
20247 dwarf_type_encoding_name (unsigned enc)
20248 {
20249   const char *name = get_DW_ATE_name (enc);
20250
20251   if (name == NULL)
20252     return "DW_ATE_<unknown>";
20253
20254   return name;
20255 }
20256
20257 static void
20258 dump_die_shallow (struct ui_file *f, int indent, struct die_info *die)
20259 {
20260   unsigned int i;
20261
20262   print_spaces (indent, f);
20263   fprintf_unfiltered (f, "Die: %s (abbrev %d, offset 0x%x)\n",
20264            dwarf_tag_name (die->tag), die->abbrev, die->offset.sect_off);
20265
20266   if (die->parent != NULL)
20267     {
20268       print_spaces (indent, f);
20269       fprintf_unfiltered (f, "  parent at offset: 0x%x\n",
20270                           die->parent->offset.sect_off);
20271     }
20272
20273   print_spaces (indent, f);
20274   fprintf_unfiltered (f, "  has children: %s\n",
20275            dwarf_bool_name (die->child != NULL));
20276
20277   print_spaces (indent, f);
20278   fprintf_unfiltered (f, "  attributes:\n");
20279
20280   for (i = 0; i < die->num_attrs; ++i)
20281     {
20282       print_spaces (indent, f);
20283       fprintf_unfiltered (f, "    %s (%s) ",
20284                dwarf_attr_name (die->attrs[i].name),
20285                dwarf_form_name (die->attrs[i].form));
20286
20287       switch (die->attrs[i].form)
20288         {
20289         case DW_FORM_addr:
20290         case DW_FORM_GNU_addr_index:
20291           fprintf_unfiltered (f, "address: ");
20292           fputs_filtered (hex_string (DW_ADDR (&die->attrs[i])), f);
20293           break;
20294         case DW_FORM_block2:
20295         case DW_FORM_block4:
20296         case DW_FORM_block:
20297         case DW_FORM_block1:
20298           fprintf_unfiltered (f, "block: size %s",
20299                               pulongest (DW_BLOCK (&die->attrs[i])->size));
20300           break;
20301         case DW_FORM_exprloc:
20302           fprintf_unfiltered (f, "expression: size %s",
20303                               pulongest (DW_BLOCK (&die->attrs[i])->size));
20304           break;
20305         case DW_FORM_data16:
20306           fprintf_unfiltered (f, "constant of 16 bytes");
20307           break;
20308         case DW_FORM_ref_addr:
20309           fprintf_unfiltered (f, "ref address: ");
20310           fputs_filtered (hex_string (DW_UNSND (&die->attrs[i])), f);
20311           break;
20312         case DW_FORM_GNU_ref_alt:
20313           fprintf_unfiltered (f, "alt ref address: ");
20314           fputs_filtered (hex_string (DW_UNSND (&die->attrs[i])), f);
20315           break;
20316         case DW_FORM_ref1:
20317         case DW_FORM_ref2:
20318         case DW_FORM_ref4:
20319         case DW_FORM_ref8:
20320         case DW_FORM_ref_udata:
20321           fprintf_unfiltered (f, "constant ref: 0x%lx (adjusted)",
20322                               (long) (DW_UNSND (&die->attrs[i])));
20323           break;
20324         case DW_FORM_data1:
20325         case DW_FORM_data2:
20326         case DW_FORM_data4:
20327         case DW_FORM_data8:
20328         case DW_FORM_udata:
20329         case DW_FORM_sdata:
20330           fprintf_unfiltered (f, "constant: %s",
20331                               pulongest (DW_UNSND (&die->attrs[i])));
20332           break;
20333         case DW_FORM_sec_offset:
20334           fprintf_unfiltered (f, "section offset: %s",
20335                               pulongest (DW_UNSND (&die->attrs[i])));
20336           break;
20337         case DW_FORM_ref_sig8:
20338           fprintf_unfiltered (f, "signature: %s",
20339                               hex_string (DW_SIGNATURE (&die->attrs[i])));
20340           break;
20341         case DW_FORM_string:
20342         case DW_FORM_strp:
20343         case DW_FORM_line_strp:
20344         case DW_FORM_GNU_str_index:
20345         case DW_FORM_GNU_strp_alt:
20346           fprintf_unfiltered (f, "string: \"%s\" (%s canonicalized)",
20347                    DW_STRING (&die->attrs[i])
20348                    ? DW_STRING (&die->attrs[i]) : "",
20349                    DW_STRING_IS_CANONICAL (&die->attrs[i]) ? "is" : "not");
20350           break;
20351         case DW_FORM_flag:
20352           if (DW_UNSND (&die->attrs[i]))
20353             fprintf_unfiltered (f, "flag: TRUE");
20354           else
20355             fprintf_unfiltered (f, "flag: FALSE");
20356           break;
20357         case DW_FORM_flag_present:
20358           fprintf_unfiltered (f, "flag: TRUE");
20359           break;
20360         case DW_FORM_indirect:
20361           /* The reader will have reduced the indirect form to
20362              the "base form" so this form should not occur.  */
20363           fprintf_unfiltered (f, 
20364                               "unexpected attribute form: DW_FORM_indirect");
20365           break;
20366         default:
20367           fprintf_unfiltered (f, "unsupported attribute form: %d.",
20368                    die->attrs[i].form);
20369           break;
20370         }
20371       fprintf_unfiltered (f, "\n");
20372     }
20373 }
20374
20375 static void
20376 dump_die_for_error (struct die_info *die)
20377 {
20378   dump_die_shallow (gdb_stderr, 0, die);
20379 }
20380
20381 static void
20382 dump_die_1 (struct ui_file *f, int level, int max_level, struct die_info *die)
20383 {
20384   int indent = level * 4;
20385
20386   gdb_assert (die != NULL);
20387
20388   if (level >= max_level)
20389     return;
20390
20391   dump_die_shallow (f, indent, die);
20392
20393   if (die->child != NULL)
20394     {
20395       print_spaces (indent, f);
20396       fprintf_unfiltered (f, "  Children:");
20397       if (level + 1 < max_level)
20398         {
20399           fprintf_unfiltered (f, "\n");
20400           dump_die_1 (f, level + 1, max_level, die->child);
20401         }
20402       else
20403         {
20404           fprintf_unfiltered (f,
20405                               " [not printed, max nesting level reached]\n");
20406         }
20407     }
20408
20409   if (die->sibling != NULL && level > 0)
20410     {
20411       dump_die_1 (f, level, max_level, die->sibling);
20412     }
20413 }
20414
20415 /* This is called from the pdie macro in gdbinit.in.
20416    It's not static so gcc will keep a copy callable from gdb.  */
20417
20418 void
20419 dump_die (struct die_info *die, int max_level)
20420 {
20421   dump_die_1 (gdb_stdlog, 0, max_level, die);
20422 }
20423
20424 static void
20425 store_in_ref_table (struct die_info *die, struct dwarf2_cu *cu)
20426 {
20427   void **slot;
20428
20429   slot = htab_find_slot_with_hash (cu->die_hash, die, die->offset.sect_off,
20430                                    INSERT);
20431
20432   *slot = die;
20433 }
20434
20435 /* Return DIE offset of ATTR.  Return 0 with complaint if ATTR is not of the
20436    required kind.  */
20437
20438 static sect_offset
20439 dwarf2_get_ref_die_offset (const struct attribute *attr)
20440 {
20441   sect_offset retval = { DW_UNSND (attr) };
20442
20443   if (attr_form_is_ref (attr))
20444     return retval;
20445
20446   retval.sect_off = 0;
20447   complaint (&symfile_complaints,
20448              _("unsupported die ref attribute form: '%s'"),
20449              dwarf_form_name (attr->form));
20450   return retval;
20451 }
20452
20453 /* Return the constant value held by ATTR.  Return DEFAULT_VALUE if
20454  * the value held by the attribute is not constant.  */
20455
20456 static LONGEST
20457 dwarf2_get_attr_constant_value (const struct attribute *attr, int default_value)
20458 {
20459   if (attr->form == DW_FORM_sdata)
20460     return DW_SND (attr);
20461   else if (attr->form == DW_FORM_udata
20462            || attr->form == DW_FORM_data1
20463            || attr->form == DW_FORM_data2
20464            || attr->form == DW_FORM_data4
20465            || attr->form == DW_FORM_data8)
20466     return DW_UNSND (attr);
20467   else
20468     {
20469       /* For DW_FORM_data16 see attr_form_is_constant.  */
20470       complaint (&symfile_complaints,
20471                  _("Attribute value is not a constant (%s)"),
20472                  dwarf_form_name (attr->form));
20473       return default_value;
20474     }
20475 }
20476
20477 /* Follow reference or signature attribute ATTR of SRC_DIE.
20478    On entry *REF_CU is the CU of SRC_DIE.
20479    On exit *REF_CU is the CU of the result.  */
20480
20481 static struct die_info *
20482 follow_die_ref_or_sig (struct die_info *src_die, const struct attribute *attr,
20483                        struct dwarf2_cu **ref_cu)
20484 {
20485   struct die_info *die;
20486
20487   if (attr_form_is_ref (attr))
20488     die = follow_die_ref (src_die, attr, ref_cu);
20489   else if (attr->form == DW_FORM_ref_sig8)
20490     die = follow_die_sig (src_die, attr, ref_cu);
20491   else
20492     {
20493       dump_die_for_error (src_die);
20494       error (_("Dwarf Error: Expected reference attribute [in module %s]"),
20495              objfile_name ((*ref_cu)->objfile));
20496     }
20497
20498   return die;
20499 }
20500
20501 /* Follow reference OFFSET.
20502    On entry *REF_CU is the CU of the source die referencing OFFSET.
20503    On exit *REF_CU is the CU of the result.
20504    Returns NULL if OFFSET is invalid.  */
20505
20506 static struct die_info *
20507 follow_die_offset (sect_offset offset, int offset_in_dwz,
20508                    struct dwarf2_cu **ref_cu)
20509 {
20510   struct die_info temp_die;
20511   struct dwarf2_cu *target_cu, *cu = *ref_cu;
20512
20513   gdb_assert (cu->per_cu != NULL);
20514
20515   target_cu = cu;
20516
20517   if (cu->per_cu->is_debug_types)
20518     {
20519       /* .debug_types CUs cannot reference anything outside their CU.
20520          If they need to, they have to reference a signatured type via
20521          DW_FORM_ref_sig8.  */
20522       if (! offset_in_cu_p (&cu->header, offset))
20523         return NULL;
20524     }
20525   else if (offset_in_dwz != cu->per_cu->is_dwz
20526            || ! offset_in_cu_p (&cu->header, offset))
20527     {
20528       struct dwarf2_per_cu_data *per_cu;
20529
20530       per_cu = dwarf2_find_containing_comp_unit (offset, offset_in_dwz,
20531                                                  cu->objfile);
20532
20533       /* If necessary, add it to the queue and load its DIEs.  */
20534       if (maybe_queue_comp_unit (cu, per_cu, cu->language))
20535         load_full_comp_unit (per_cu, cu->language);
20536
20537       target_cu = per_cu->cu;
20538     }
20539   else if (cu->dies == NULL)
20540     {
20541       /* We're loading full DIEs during partial symbol reading.  */
20542       gdb_assert (dwarf2_per_objfile->reading_partial_symbols);
20543       load_full_comp_unit (cu->per_cu, language_minimal);
20544     }
20545
20546   *ref_cu = target_cu;
20547   temp_die.offset = offset;
20548   return (struct die_info *) htab_find_with_hash (target_cu->die_hash,
20549                                                   &temp_die, offset.sect_off);
20550 }
20551
20552 /* Follow reference attribute ATTR of SRC_DIE.
20553    On entry *REF_CU is the CU of SRC_DIE.
20554    On exit *REF_CU is the CU of the result.  */
20555
20556 static struct die_info *
20557 follow_die_ref (struct die_info *src_die, const struct attribute *attr,
20558                 struct dwarf2_cu **ref_cu)
20559 {
20560   sect_offset offset = dwarf2_get_ref_die_offset (attr);
20561   struct dwarf2_cu *cu = *ref_cu;
20562   struct die_info *die;
20563
20564   die = follow_die_offset (offset,
20565                            (attr->form == DW_FORM_GNU_ref_alt
20566                             || cu->per_cu->is_dwz),
20567                            ref_cu);
20568   if (!die)
20569     error (_("Dwarf Error: Cannot find DIE at 0x%x referenced from DIE "
20570            "at 0x%x [in module %s]"),
20571            offset.sect_off, src_die->offset.sect_off,
20572            objfile_name (cu->objfile));
20573
20574   return die;
20575 }
20576
20577 /* Return DWARF block referenced by DW_AT_location of DIE at OFFSET at PER_CU.
20578    Returned value is intended for DW_OP_call*.  Returned
20579    dwarf2_locexpr_baton->data has lifetime of PER_CU->OBJFILE.  */
20580
20581 struct dwarf2_locexpr_baton
20582 dwarf2_fetch_die_loc_sect_off (sect_offset offset,
20583                                struct dwarf2_per_cu_data *per_cu,
20584                                CORE_ADDR (*get_frame_pc) (void *baton),
20585                                void *baton)
20586 {
20587   struct dwarf2_cu *cu;
20588   struct die_info *die;
20589   struct attribute *attr;
20590   struct dwarf2_locexpr_baton retval;
20591
20592   dw2_setup (per_cu->objfile);
20593
20594   if (per_cu->cu == NULL)
20595     load_cu (per_cu);
20596   cu = per_cu->cu;
20597   if (cu == NULL)
20598     {
20599       /* We shouldn't get here for a dummy CU, but don't crash on the user.
20600          Instead just throw an error, not much else we can do.  */
20601       error (_("Dwarf Error: Dummy CU at 0x%x referenced in module %s"),
20602              offset.sect_off, objfile_name (per_cu->objfile));
20603     }
20604
20605   die = follow_die_offset (offset, per_cu->is_dwz, &cu);
20606   if (!die)
20607     error (_("Dwarf Error: Cannot find DIE at 0x%x referenced in module %s"),
20608            offset.sect_off, objfile_name (per_cu->objfile));
20609
20610   attr = dwarf2_attr (die, DW_AT_location, cu);
20611   if (!attr)
20612     {
20613       /* DWARF: "If there is no such attribute, then there is no effect.".
20614          DATA is ignored if SIZE is 0.  */
20615
20616       retval.data = NULL;
20617       retval.size = 0;
20618     }
20619   else if (attr_form_is_section_offset (attr))
20620     {
20621       struct dwarf2_loclist_baton loclist_baton;
20622       CORE_ADDR pc = (*get_frame_pc) (baton);
20623       size_t size;
20624
20625       fill_in_loclist_baton (cu, &loclist_baton, attr);
20626
20627       retval.data = dwarf2_find_location_expression (&loclist_baton,
20628                                                      &size, pc);
20629       retval.size = size;
20630     }
20631   else
20632     {
20633       if (!attr_form_is_block (attr))
20634         error (_("Dwarf Error: DIE at 0x%x referenced in module %s "
20635                  "is neither DW_FORM_block* nor DW_FORM_exprloc"),
20636                offset.sect_off, objfile_name (per_cu->objfile));
20637
20638       retval.data = DW_BLOCK (attr)->data;
20639       retval.size = DW_BLOCK (attr)->size;
20640     }
20641   retval.per_cu = cu->per_cu;
20642
20643   age_cached_comp_units ();
20644
20645   return retval;
20646 }
20647
20648 /* Like dwarf2_fetch_die_loc_sect_off, but take a CU
20649    offset.  */
20650
20651 struct dwarf2_locexpr_baton
20652 dwarf2_fetch_die_loc_cu_off (cu_offset offset_in_cu,
20653                              struct dwarf2_per_cu_data *per_cu,
20654                              CORE_ADDR (*get_frame_pc) (void *baton),
20655                              void *baton)
20656 {
20657   sect_offset offset = { per_cu->offset.sect_off + offset_in_cu.cu_off };
20658
20659   return dwarf2_fetch_die_loc_sect_off (offset, per_cu, get_frame_pc, baton);
20660 }
20661
20662 /* Write a constant of a given type as target-ordered bytes into
20663    OBSTACK.  */
20664
20665 static const gdb_byte *
20666 write_constant_as_bytes (struct obstack *obstack,
20667                          enum bfd_endian byte_order,
20668                          struct type *type,
20669                          ULONGEST value,
20670                          LONGEST *len)
20671 {
20672   gdb_byte *result;
20673
20674   *len = TYPE_LENGTH (type);
20675   result = (gdb_byte *) obstack_alloc (obstack, *len);
20676   store_unsigned_integer (result, *len, byte_order, value);
20677
20678   return result;
20679 }
20680
20681 /* If the DIE at OFFSET in PER_CU has a DW_AT_const_value, return a
20682    pointer to the constant bytes and set LEN to the length of the
20683    data.  If memory is needed, allocate it on OBSTACK.  If the DIE
20684    does not have a DW_AT_const_value, return NULL.  */
20685
20686 const gdb_byte *
20687 dwarf2_fetch_constant_bytes (sect_offset offset,
20688                              struct dwarf2_per_cu_data *per_cu,
20689                              struct obstack *obstack,
20690                              LONGEST *len)
20691 {
20692   struct dwarf2_cu *cu;
20693   struct die_info *die;
20694   struct attribute *attr;
20695   const gdb_byte *result = NULL;
20696   struct type *type;
20697   LONGEST value;
20698   enum bfd_endian byte_order;
20699
20700   dw2_setup (per_cu->objfile);
20701
20702   if (per_cu->cu == NULL)
20703     load_cu (per_cu);
20704   cu = per_cu->cu;
20705   if (cu == NULL)
20706     {
20707       /* We shouldn't get here for a dummy CU, but don't crash on the user.
20708          Instead just throw an error, not much else we can do.  */
20709       error (_("Dwarf Error: Dummy CU at 0x%x referenced in module %s"),
20710              offset.sect_off, objfile_name (per_cu->objfile));
20711     }
20712
20713   die = follow_die_offset (offset, per_cu->is_dwz, &cu);
20714   if (!die)
20715     error (_("Dwarf Error: Cannot find DIE at 0x%x referenced in module %s"),
20716            offset.sect_off, objfile_name (per_cu->objfile));
20717
20718
20719   attr = dwarf2_attr (die, DW_AT_const_value, cu);
20720   if (attr == NULL)
20721     return NULL;
20722
20723   byte_order = (bfd_big_endian (per_cu->objfile->obfd)
20724                 ? BFD_ENDIAN_BIG : BFD_ENDIAN_LITTLE);
20725
20726   switch (attr->form)
20727     {
20728     case DW_FORM_addr:
20729     case DW_FORM_GNU_addr_index:
20730       {
20731         gdb_byte *tem;
20732
20733         *len = cu->header.addr_size;
20734         tem = (gdb_byte *) obstack_alloc (obstack, *len);
20735         store_unsigned_integer (tem, *len, byte_order, DW_ADDR (attr));
20736         result = tem;
20737       }
20738       break;
20739     case DW_FORM_string:
20740     case DW_FORM_strp:
20741     case DW_FORM_GNU_str_index:
20742     case DW_FORM_GNU_strp_alt:
20743       /* DW_STRING is already allocated on the objfile obstack, point
20744          directly to it.  */
20745       result = (const gdb_byte *) DW_STRING (attr);
20746       *len = strlen (DW_STRING (attr));
20747       break;
20748     case DW_FORM_block1:
20749     case DW_FORM_block2:
20750     case DW_FORM_block4:
20751     case DW_FORM_block:
20752     case DW_FORM_exprloc:
20753     case DW_FORM_data16:
20754       result = DW_BLOCK (attr)->data;
20755       *len = DW_BLOCK (attr)->size;
20756       break;
20757
20758       /* The DW_AT_const_value attributes are supposed to carry the
20759          symbol's value "represented as it would be on the target
20760          architecture."  By the time we get here, it's already been
20761          converted to host endianness, so we just need to sign- or
20762          zero-extend it as appropriate.  */
20763     case DW_FORM_data1:
20764       type = die_type (die, cu);
20765       result = dwarf2_const_value_data (attr, obstack, cu, &value, 8);
20766       if (result == NULL)
20767         result = write_constant_as_bytes (obstack, byte_order,
20768                                           type, value, len);
20769       break;
20770     case DW_FORM_data2:
20771       type = die_type (die, cu);
20772       result = dwarf2_const_value_data (attr, obstack, cu, &value, 16);
20773       if (result == NULL)
20774         result = write_constant_as_bytes (obstack, byte_order,
20775                                           type, value, len);
20776       break;
20777     case DW_FORM_data4:
20778       type = die_type (die, cu);
20779       result = dwarf2_const_value_data (attr, obstack, cu, &value, 32);
20780       if (result == NULL)
20781         result = write_constant_as_bytes (obstack, byte_order,
20782                                           type, value, len);
20783       break;
20784     case DW_FORM_data8:
20785       type = die_type (die, cu);
20786       result = dwarf2_const_value_data (attr, obstack, cu, &value, 64);
20787       if (result == NULL)
20788         result = write_constant_as_bytes (obstack, byte_order,
20789                                           type, value, len);
20790       break;
20791
20792     case DW_FORM_sdata:
20793       type = die_type (die, cu);
20794       result = write_constant_as_bytes (obstack, byte_order,
20795                                         type, DW_SND (attr), len);
20796       break;
20797
20798     case DW_FORM_udata:
20799       type = die_type (die, cu);
20800       result = write_constant_as_bytes (obstack, byte_order,
20801                                         type, DW_UNSND (attr), len);
20802       break;
20803
20804     default:
20805       complaint (&symfile_complaints,
20806                  _("unsupported const value attribute form: '%s'"),
20807                  dwarf_form_name (attr->form));
20808       break;
20809     }
20810
20811   return result;
20812 }
20813
20814 /* Return the type of the die at OFFSET in PER_CU.  Return NULL if no
20815    valid type for this die is found.  */
20816
20817 struct type *
20818 dwarf2_fetch_die_type_sect_off (sect_offset offset,
20819                                 struct dwarf2_per_cu_data *per_cu)
20820 {
20821   struct dwarf2_cu *cu;
20822   struct die_info *die;
20823
20824   dw2_setup (per_cu->objfile);
20825
20826   if (per_cu->cu == NULL)
20827     load_cu (per_cu);
20828   cu = per_cu->cu;
20829   if (!cu)
20830     return NULL;
20831
20832   die = follow_die_offset (offset, per_cu->is_dwz, &cu);
20833   if (!die)
20834     return NULL;
20835
20836   return die_type (die, cu);
20837 }
20838
20839 /* Return the type of the DIE at DIE_OFFSET in the CU named by
20840    PER_CU.  */
20841
20842 struct type *
20843 dwarf2_get_die_type (cu_offset die_offset,
20844                      struct dwarf2_per_cu_data *per_cu)
20845 {
20846   sect_offset die_offset_sect;
20847
20848   dw2_setup (per_cu->objfile);
20849
20850   die_offset_sect.sect_off = per_cu->offset.sect_off + die_offset.cu_off;
20851   return get_die_type_at_offset (die_offset_sect, per_cu);
20852 }
20853
20854 /* Follow type unit SIG_TYPE referenced by SRC_DIE.
20855    On entry *REF_CU is the CU of SRC_DIE.
20856    On exit *REF_CU is the CU of the result.
20857    Returns NULL if the referenced DIE isn't found.  */
20858
20859 static struct die_info *
20860 follow_die_sig_1 (struct die_info *src_die, struct signatured_type *sig_type,
20861                   struct dwarf2_cu **ref_cu)
20862 {
20863   struct die_info temp_die;
20864   struct dwarf2_cu *sig_cu;
20865   struct die_info *die;
20866
20867   /* While it might be nice to assert sig_type->type == NULL here,
20868      we can get here for DW_AT_imported_declaration where we need
20869      the DIE not the type.  */
20870
20871   /* If necessary, add it to the queue and load its DIEs.  */
20872
20873   if (maybe_queue_comp_unit (*ref_cu, &sig_type->per_cu, language_minimal))
20874     read_signatured_type (sig_type);
20875
20876   sig_cu = sig_type->per_cu.cu;
20877   gdb_assert (sig_cu != NULL);
20878   gdb_assert (sig_type->type_offset_in_section.sect_off != 0);
20879   temp_die.offset = sig_type->type_offset_in_section;
20880   die = (struct die_info *) htab_find_with_hash (sig_cu->die_hash, &temp_die,
20881                                                  temp_die.offset.sect_off);
20882   if (die)
20883     {
20884       /* For .gdb_index version 7 keep track of included TUs.
20885          http://sourceware.org/bugzilla/show_bug.cgi?id=15021.  */
20886       if (dwarf2_per_objfile->index_table != NULL
20887           && dwarf2_per_objfile->index_table->version <= 7)
20888         {
20889           VEC_safe_push (dwarf2_per_cu_ptr,
20890                          (*ref_cu)->per_cu->imported_symtabs,
20891                          sig_cu->per_cu);
20892         }
20893
20894       *ref_cu = sig_cu;
20895       return die;
20896     }
20897
20898   return NULL;
20899 }
20900
20901 /* Follow signatured type referenced by ATTR in SRC_DIE.
20902    On entry *REF_CU is the CU of SRC_DIE.
20903    On exit *REF_CU is the CU of the result.
20904    The result is the DIE of the type.
20905    If the referenced type cannot be found an error is thrown.  */
20906
20907 static struct die_info *
20908 follow_die_sig (struct die_info *src_die, const struct attribute *attr,
20909                 struct dwarf2_cu **ref_cu)
20910 {
20911   ULONGEST signature = DW_SIGNATURE (attr);
20912   struct signatured_type *sig_type;
20913   struct die_info *die;
20914
20915   gdb_assert (attr->form == DW_FORM_ref_sig8);
20916
20917   sig_type = lookup_signatured_type (*ref_cu, signature);
20918   /* sig_type will be NULL if the signatured type is missing from
20919      the debug info.  */
20920   if (sig_type == NULL)
20921     {
20922       error (_("Dwarf Error: Cannot find signatured DIE %s referenced"
20923                " from DIE at 0x%x [in module %s]"),
20924              hex_string (signature), src_die->offset.sect_off,
20925              objfile_name ((*ref_cu)->objfile));
20926     }
20927
20928   die = follow_die_sig_1 (src_die, sig_type, ref_cu);
20929   if (die == NULL)
20930     {
20931       dump_die_for_error (src_die);
20932       error (_("Dwarf Error: Problem reading signatured DIE %s referenced"
20933                " from DIE at 0x%x [in module %s]"),
20934              hex_string (signature), src_die->offset.sect_off,
20935              objfile_name ((*ref_cu)->objfile));
20936     }
20937
20938   return die;
20939 }
20940
20941 /* Get the type specified by SIGNATURE referenced in DIE/CU,
20942    reading in and processing the type unit if necessary.  */
20943
20944 static struct type *
20945 get_signatured_type (struct die_info *die, ULONGEST signature,
20946                      struct dwarf2_cu *cu)
20947 {
20948   struct signatured_type *sig_type;
20949   struct dwarf2_cu *type_cu;
20950   struct die_info *type_die;
20951   struct type *type;
20952
20953   sig_type = lookup_signatured_type (cu, signature);
20954   /* sig_type will be NULL if the signatured type is missing from
20955      the debug info.  */
20956   if (sig_type == NULL)
20957     {
20958       complaint (&symfile_complaints,
20959                  _("Dwarf Error: Cannot find signatured DIE %s referenced"
20960                    " from DIE at 0x%x [in module %s]"),
20961                  hex_string (signature), die->offset.sect_off,
20962                  objfile_name (dwarf2_per_objfile->objfile));
20963       return build_error_marker_type (cu, die);
20964     }
20965
20966   /* If we already know the type we're done.  */
20967   if (sig_type->type != NULL)
20968     return sig_type->type;
20969
20970   type_cu = cu;
20971   type_die = follow_die_sig_1 (die, sig_type, &type_cu);
20972   if (type_die != NULL)
20973     {
20974       /* N.B. We need to call get_die_type to ensure only one type for this DIE
20975          is created.  This is important, for example, because for c++ classes
20976          we need TYPE_NAME set which is only done by new_symbol.  Blech.  */
20977       type = read_type_die (type_die, type_cu);
20978       if (type == NULL)
20979         {
20980           complaint (&symfile_complaints,
20981                      _("Dwarf Error: Cannot build signatured type %s"
20982                        " referenced from DIE at 0x%x [in module %s]"),
20983                      hex_string (signature), die->offset.sect_off,
20984                      objfile_name (dwarf2_per_objfile->objfile));
20985           type = build_error_marker_type (cu, die);
20986         }
20987     }
20988   else
20989     {
20990       complaint (&symfile_complaints,
20991                  _("Dwarf Error: Problem reading signatured DIE %s referenced"
20992                    " from DIE at 0x%x [in module %s]"),
20993                  hex_string (signature), die->offset.sect_off,
20994                  objfile_name (dwarf2_per_objfile->objfile));
20995       type = build_error_marker_type (cu, die);
20996     }
20997   sig_type->type = type;
20998
20999   return type;
21000 }
21001
21002 /* Get the type specified by the DW_AT_signature ATTR in DIE/CU,
21003    reading in and processing the type unit if necessary.  */
21004
21005 static struct type *
21006 get_DW_AT_signature_type (struct die_info *die, const struct attribute *attr,
21007                           struct dwarf2_cu *cu) /* ARI: editCase function */
21008 {
21009   /* Yes, DW_AT_signature can use a non-ref_sig8 reference.  */
21010   if (attr_form_is_ref (attr))
21011     {
21012       struct dwarf2_cu *type_cu = cu;
21013       struct die_info *type_die = follow_die_ref (die, attr, &type_cu);
21014
21015       return read_type_die (type_die, type_cu);
21016     }
21017   else if (attr->form == DW_FORM_ref_sig8)
21018     {
21019       return get_signatured_type (die, DW_SIGNATURE (attr), cu);
21020     }
21021   else
21022     {
21023       complaint (&symfile_complaints,
21024                  _("Dwarf Error: DW_AT_signature has bad form %s in DIE"
21025                    " at 0x%x [in module %s]"),
21026                  dwarf_form_name (attr->form), die->offset.sect_off,
21027                  objfile_name (dwarf2_per_objfile->objfile));
21028       return build_error_marker_type (cu, die);
21029     }
21030 }
21031
21032 /* Load the DIEs associated with type unit PER_CU into memory.  */
21033
21034 static void
21035 load_full_type_unit (struct dwarf2_per_cu_data *per_cu)
21036 {
21037   struct signatured_type *sig_type;
21038
21039   /* Caller is responsible for ensuring type_unit_groups don't get here.  */
21040   gdb_assert (! IS_TYPE_UNIT_GROUP (per_cu));
21041
21042   /* We have the per_cu, but we need the signatured_type.
21043      Fortunately this is an easy translation.  */
21044   gdb_assert (per_cu->is_debug_types);
21045   sig_type = (struct signatured_type *) per_cu;
21046
21047   gdb_assert (per_cu->cu == NULL);
21048
21049   read_signatured_type (sig_type);
21050
21051   gdb_assert (per_cu->cu != NULL);
21052 }
21053
21054 /* die_reader_func for read_signatured_type.
21055    This is identical to load_full_comp_unit_reader,
21056    but is kept separate for now.  */
21057
21058 static void
21059 read_signatured_type_reader (const struct die_reader_specs *reader,
21060                              const gdb_byte *info_ptr,
21061                              struct die_info *comp_unit_die,
21062                              int has_children,
21063                              void *data)
21064 {
21065   struct dwarf2_cu *cu = reader->cu;
21066
21067   gdb_assert (cu->die_hash == NULL);
21068   cu->die_hash =
21069     htab_create_alloc_ex (cu->header.length / 12,
21070                           die_hash,
21071                           die_eq,
21072                           NULL,
21073                           &cu->comp_unit_obstack,
21074                           hashtab_obstack_allocate,
21075                           dummy_obstack_deallocate);
21076
21077   if (has_children)
21078     comp_unit_die->child = read_die_and_siblings (reader, info_ptr,
21079                                                   &info_ptr, comp_unit_die);
21080   cu->dies = comp_unit_die;
21081   /* comp_unit_die is not stored in die_hash, no need.  */
21082
21083   /* We try not to read any attributes in this function, because not
21084      all CUs needed for references have been loaded yet, and symbol
21085      table processing isn't initialized.  But we have to set the CU language,
21086      or we won't be able to build types correctly.
21087      Similarly, if we do not read the producer, we can not apply
21088      producer-specific interpretation.  */
21089   prepare_one_comp_unit (cu, cu->dies, language_minimal);
21090 }
21091
21092 /* Read in a signatured type and build its CU and DIEs.
21093    If the type is a stub for the real type in a DWO file,
21094    read in the real type from the DWO file as well.  */
21095
21096 static void
21097 read_signatured_type (struct signatured_type *sig_type)
21098 {
21099   struct dwarf2_per_cu_data *per_cu = &sig_type->per_cu;
21100
21101   gdb_assert (per_cu->is_debug_types);
21102   gdb_assert (per_cu->cu == NULL);
21103
21104   init_cutu_and_read_dies (per_cu, NULL, 0, 1,
21105                            read_signatured_type_reader, NULL);
21106   sig_type->per_cu.tu_read = 1;
21107 }
21108
21109 /* Decode simple location descriptions.
21110    Given a pointer to a dwarf block that defines a location, compute
21111    the location and return the value.
21112
21113    NOTE drow/2003-11-18: This function is called in two situations
21114    now: for the address of static or global variables (partial symbols
21115    only) and for offsets into structures which are expected to be
21116    (more or less) constant.  The partial symbol case should go away,
21117    and only the constant case should remain.  That will let this
21118    function complain more accurately.  A few special modes are allowed
21119    without complaint for global variables (for instance, global
21120    register values and thread-local values).
21121
21122    A location description containing no operations indicates that the
21123    object is optimized out.  The return value is 0 for that case.
21124    FIXME drow/2003-11-16: No callers check for this case any more; soon all
21125    callers will only want a very basic result and this can become a
21126    complaint.
21127
21128    Note that stack[0] is unused except as a default error return.  */
21129
21130 static CORE_ADDR
21131 decode_locdesc (struct dwarf_block *blk, struct dwarf2_cu *cu)
21132 {
21133   struct objfile *objfile = cu->objfile;
21134   size_t i;
21135   size_t size = blk->size;
21136   const gdb_byte *data = blk->data;
21137   CORE_ADDR stack[64];
21138   int stacki;
21139   unsigned int bytes_read, unsnd;
21140   gdb_byte op;
21141
21142   i = 0;
21143   stacki = 0;
21144   stack[stacki] = 0;
21145   stack[++stacki] = 0;
21146
21147   while (i < size)
21148     {
21149       op = data[i++];
21150       switch (op)
21151         {
21152         case DW_OP_lit0:
21153         case DW_OP_lit1:
21154         case DW_OP_lit2:
21155         case DW_OP_lit3:
21156         case DW_OP_lit4:
21157         case DW_OP_lit5:
21158         case DW_OP_lit6:
21159         case DW_OP_lit7:
21160         case DW_OP_lit8:
21161         case DW_OP_lit9:
21162         case DW_OP_lit10:
21163         case DW_OP_lit11:
21164         case DW_OP_lit12:
21165         case DW_OP_lit13:
21166         case DW_OP_lit14:
21167         case DW_OP_lit15:
21168         case DW_OP_lit16:
21169         case DW_OP_lit17:
21170         case DW_OP_lit18:
21171         case DW_OP_lit19:
21172         case DW_OP_lit20:
21173         case DW_OP_lit21:
21174         case DW_OP_lit22:
21175         case DW_OP_lit23:
21176         case DW_OP_lit24:
21177         case DW_OP_lit25:
21178         case DW_OP_lit26:
21179         case DW_OP_lit27:
21180         case DW_OP_lit28:
21181         case DW_OP_lit29:
21182         case DW_OP_lit30:
21183         case DW_OP_lit31:
21184           stack[++stacki] = op - DW_OP_lit0;
21185           break;
21186
21187         case DW_OP_reg0:
21188         case DW_OP_reg1:
21189         case DW_OP_reg2:
21190         case DW_OP_reg3:
21191         case DW_OP_reg4:
21192         case DW_OP_reg5:
21193         case DW_OP_reg6:
21194         case DW_OP_reg7:
21195         case DW_OP_reg8:
21196         case DW_OP_reg9:
21197         case DW_OP_reg10:
21198         case DW_OP_reg11:
21199         case DW_OP_reg12:
21200         case DW_OP_reg13:
21201         case DW_OP_reg14:
21202         case DW_OP_reg15:
21203         case DW_OP_reg16:
21204         case DW_OP_reg17:
21205         case DW_OP_reg18:
21206         case DW_OP_reg19:
21207         case DW_OP_reg20:
21208         case DW_OP_reg21:
21209         case DW_OP_reg22:
21210         case DW_OP_reg23:
21211         case DW_OP_reg24:
21212         case DW_OP_reg25:
21213         case DW_OP_reg26:
21214         case DW_OP_reg27:
21215         case DW_OP_reg28:
21216         case DW_OP_reg29:
21217         case DW_OP_reg30:
21218         case DW_OP_reg31:
21219           stack[++stacki] = op - DW_OP_reg0;
21220           if (i < size)
21221             dwarf2_complex_location_expr_complaint ();
21222           break;
21223
21224         case DW_OP_regx:
21225           unsnd = read_unsigned_leb128 (NULL, (data + i), &bytes_read);
21226           i += bytes_read;
21227           stack[++stacki] = unsnd;
21228           if (i < size)
21229             dwarf2_complex_location_expr_complaint ();
21230           break;
21231
21232         case DW_OP_addr:
21233           stack[++stacki] = read_address (objfile->obfd, &data[i],
21234                                           cu, &bytes_read);
21235           i += bytes_read;
21236           break;
21237
21238         case DW_OP_const1u:
21239           stack[++stacki] = read_1_byte (objfile->obfd, &data[i]);
21240           i += 1;
21241           break;
21242
21243         case DW_OP_const1s:
21244           stack[++stacki] = read_1_signed_byte (objfile->obfd, &data[i]);
21245           i += 1;
21246           break;
21247
21248         case DW_OP_const2u:
21249           stack[++stacki] = read_2_bytes (objfile->obfd, &data[i]);
21250           i += 2;
21251           break;
21252
21253         case DW_OP_const2s:
21254           stack[++stacki] = read_2_signed_bytes (objfile->obfd, &data[i]);
21255           i += 2;
21256           break;
21257
21258         case DW_OP_const4u:
21259           stack[++stacki] = read_4_bytes (objfile->obfd, &data[i]);
21260           i += 4;
21261           break;
21262
21263         case DW_OP_const4s:
21264           stack[++stacki] = read_4_signed_bytes (objfile->obfd, &data[i]);
21265           i += 4;
21266           break;
21267
21268         case DW_OP_const8u:
21269           stack[++stacki] = read_8_bytes (objfile->obfd, &data[i]);
21270           i += 8;
21271           break;
21272
21273         case DW_OP_constu:
21274           stack[++stacki] = read_unsigned_leb128 (NULL, (data + i),
21275                                                   &bytes_read);
21276           i += bytes_read;
21277           break;
21278
21279         case DW_OP_consts:
21280           stack[++stacki] = read_signed_leb128 (NULL, (data + i), &bytes_read);
21281           i += bytes_read;
21282           break;
21283
21284         case DW_OP_dup:
21285           stack[stacki + 1] = stack[stacki];
21286           stacki++;
21287           break;
21288
21289         case DW_OP_plus:
21290           stack[stacki - 1] += stack[stacki];
21291           stacki--;
21292           break;
21293
21294         case DW_OP_plus_uconst:
21295           stack[stacki] += read_unsigned_leb128 (NULL, (data + i),
21296                                                  &bytes_read);
21297           i += bytes_read;
21298           break;
21299
21300         case DW_OP_minus:
21301           stack[stacki - 1] -= stack[stacki];
21302           stacki--;
21303           break;
21304
21305         case DW_OP_deref:
21306           /* If we're not the last op, then we definitely can't encode
21307              this using GDB's address_class enum.  This is valid for partial
21308              global symbols, although the variable's address will be bogus
21309              in the psymtab.  */
21310           if (i < size)
21311             dwarf2_complex_location_expr_complaint ();
21312           break;
21313
21314         case DW_OP_GNU_push_tls_address:
21315         case DW_OP_form_tls_address:
21316           /* The top of the stack has the offset from the beginning
21317              of the thread control block at which the variable is located.  */
21318           /* Nothing should follow this operator, so the top of stack would
21319              be returned.  */
21320           /* This is valid for partial global symbols, but the variable's
21321              address will be bogus in the psymtab.  Make it always at least
21322              non-zero to not look as a variable garbage collected by linker
21323              which have DW_OP_addr 0.  */
21324           if (i < size)
21325             dwarf2_complex_location_expr_complaint ();
21326           stack[stacki]++;
21327           break;
21328
21329         case DW_OP_GNU_uninit:
21330           break;
21331
21332         case DW_OP_GNU_addr_index:
21333         case DW_OP_GNU_const_index:
21334           stack[++stacki] = read_addr_index_from_leb128 (cu, &data[i],
21335                                                          &bytes_read);
21336           i += bytes_read;
21337           break;
21338
21339         default:
21340           {
21341             const char *name = get_DW_OP_name (op);
21342
21343             if (name)
21344               complaint (&symfile_complaints, _("unsupported stack op: '%s'"),
21345                          name);
21346             else
21347               complaint (&symfile_complaints, _("unsupported stack op: '%02x'"),
21348                          op);
21349           }
21350
21351           return (stack[stacki]);
21352         }
21353
21354       /* Enforce maximum stack depth of SIZE-1 to avoid writing
21355          outside of the allocated space.  Also enforce minimum>0.  */
21356       if (stacki >= ARRAY_SIZE (stack) - 1)
21357         {
21358           complaint (&symfile_complaints,
21359                      _("location description stack overflow"));
21360           return 0;
21361         }
21362
21363       if (stacki <= 0)
21364         {
21365           complaint (&symfile_complaints,
21366                      _("location description stack underflow"));
21367           return 0;
21368         }
21369     }
21370   return (stack[stacki]);
21371 }
21372
21373 /* memory allocation interface */
21374
21375 static struct dwarf_block *
21376 dwarf_alloc_block (struct dwarf2_cu *cu)
21377 {
21378   return XOBNEW (&cu->comp_unit_obstack, struct dwarf_block);
21379 }
21380
21381 static struct die_info *
21382 dwarf_alloc_die (struct dwarf2_cu *cu, int num_attrs)
21383 {
21384   struct die_info *die;
21385   size_t size = sizeof (struct die_info);
21386
21387   if (num_attrs > 1)
21388     size += (num_attrs - 1) * sizeof (struct attribute);
21389
21390   die = (struct die_info *) obstack_alloc (&cu->comp_unit_obstack, size);
21391   memset (die, 0, sizeof (struct die_info));
21392   return (die);
21393 }
21394
21395 \f
21396 /* Macro support.  */
21397
21398 /* Return file name relative to the compilation directory of file number I in
21399    *LH's file name table.  The result is allocated using xmalloc; the caller is
21400    responsible for freeing it.  */
21401
21402 static char *
21403 file_file_name (int file, struct line_header *lh)
21404 {
21405   /* Is the file number a valid index into the line header's file name
21406      table?  Remember that file numbers start with one, not zero.  */
21407   if (1 <= file && file <= lh->num_file_names)
21408     {
21409       const file_entry &fe = lh->file_names[file - 1];
21410
21411       if (!IS_ABSOLUTE_PATH (fe.name))
21412         {
21413           const char *dir = fe.include_dir (lh);
21414           if (dir != NULL)
21415             return concat (dir, SLASH_STRING, fe.name, (char *) NULL);
21416         }
21417       return xstrdup (fe.name);
21418     }
21419   else
21420     {
21421       /* The compiler produced a bogus file number.  We can at least
21422          record the macro definitions made in the file, even if we
21423          won't be able to find the file by name.  */
21424       char fake_name[80];
21425
21426       xsnprintf (fake_name, sizeof (fake_name),
21427                  "<bad macro file number %d>", file);
21428
21429       complaint (&symfile_complaints,
21430                  _("bad file number in macro information (%d)"),
21431                  file);
21432
21433       return xstrdup (fake_name);
21434     }
21435 }
21436
21437 /* Return the full name of file number I in *LH's file name table.
21438    Use COMP_DIR as the name of the current directory of the
21439    compilation.  The result is allocated using xmalloc; the caller is
21440    responsible for freeing it.  */
21441 static char *
21442 file_full_name (int file, struct line_header *lh, const char *comp_dir)
21443 {
21444   /* Is the file number a valid index into the line header's file name
21445      table?  Remember that file numbers start with one, not zero.  */
21446   if (1 <= file && file <= lh->num_file_names)
21447     {
21448       char *relative = file_file_name (file, lh);
21449
21450       if (IS_ABSOLUTE_PATH (relative) || comp_dir == NULL)
21451         return relative;
21452       return reconcat (relative, comp_dir, SLASH_STRING,
21453                        relative, (char *) NULL);
21454     }
21455   else
21456     return file_file_name (file, lh);
21457 }
21458
21459
21460 static struct macro_source_file *
21461 macro_start_file (int file, int line,
21462                   struct macro_source_file *current_file,
21463                   struct line_header *lh)
21464 {
21465   /* File name relative to the compilation directory of this source file.  */
21466   char *file_name = file_file_name (file, lh);
21467
21468   if (! current_file)
21469     {
21470       /* Note: We don't create a macro table for this compilation unit
21471          at all until we actually get a filename.  */
21472       struct macro_table *macro_table = get_macro_table ();
21473
21474       /* If we have no current file, then this must be the start_file
21475          directive for the compilation unit's main source file.  */
21476       current_file = macro_set_main (macro_table, file_name);
21477       macro_define_special (macro_table);
21478     }
21479   else
21480     current_file = macro_include (current_file, line, file_name);
21481
21482   xfree (file_name);
21483
21484   return current_file;
21485 }
21486
21487
21488 /* Copy the LEN characters at BUF to a xmalloc'ed block of memory,
21489    followed by a null byte.  */
21490 static char *
21491 copy_string (const char *buf, int len)
21492 {
21493   char *s = (char *) xmalloc (len + 1);
21494
21495   memcpy (s, buf, len);
21496   s[len] = '\0';
21497   return s;
21498 }
21499
21500
21501 static const char *
21502 consume_improper_spaces (const char *p, const char *body)
21503 {
21504   if (*p == ' ')
21505     {
21506       complaint (&symfile_complaints,
21507                  _("macro definition contains spaces "
21508                    "in formal argument list:\n`%s'"),
21509                  body);
21510
21511       while (*p == ' ')
21512         p++;
21513     }
21514
21515   return p;
21516 }
21517
21518
21519 static void
21520 parse_macro_definition (struct macro_source_file *file, int line,
21521                         const char *body)
21522 {
21523   const char *p;
21524
21525   /* The body string takes one of two forms.  For object-like macro
21526      definitions, it should be:
21527
21528         <macro name> " " <definition>
21529
21530      For function-like macro definitions, it should be:
21531
21532         <macro name> "() " <definition>
21533      or
21534         <macro name> "(" <arg name> ( "," <arg name> ) * ") " <definition>
21535
21536      Spaces may appear only where explicitly indicated, and in the
21537      <definition>.
21538
21539      The Dwarf 2 spec says that an object-like macro's name is always
21540      followed by a space, but versions of GCC around March 2002 omit
21541      the space when the macro's definition is the empty string.
21542
21543      The Dwarf 2 spec says that there should be no spaces between the
21544      formal arguments in a function-like macro's formal argument list,
21545      but versions of GCC around March 2002 include spaces after the
21546      commas.  */
21547
21548
21549   /* Find the extent of the macro name.  The macro name is terminated
21550      by either a space or null character (for an object-like macro) or
21551      an opening paren (for a function-like macro).  */
21552   for (p = body; *p; p++)
21553     if (*p == ' ' || *p == '(')
21554       break;
21555
21556   if (*p == ' ' || *p == '\0')
21557     {
21558       /* It's an object-like macro.  */
21559       int name_len = p - body;
21560       char *name = copy_string (body, name_len);
21561       const char *replacement;
21562
21563       if (*p == ' ')
21564         replacement = body + name_len + 1;
21565       else
21566         {
21567           dwarf2_macro_malformed_definition_complaint (body);
21568           replacement = body + name_len;
21569         }
21570
21571       macro_define_object (file, line, name, replacement);
21572
21573       xfree (name);
21574     }
21575   else if (*p == '(')
21576     {
21577       /* It's a function-like macro.  */
21578       char *name = copy_string (body, p - body);
21579       int argc = 0;
21580       int argv_size = 1;
21581       char **argv = XNEWVEC (char *, argv_size);
21582
21583       p++;
21584
21585       p = consume_improper_spaces (p, body);
21586
21587       /* Parse the formal argument list.  */
21588       while (*p && *p != ')')
21589         {
21590           /* Find the extent of the current argument name.  */
21591           const char *arg_start = p;
21592
21593           while (*p && *p != ',' && *p != ')' && *p != ' ')
21594             p++;
21595
21596           if (! *p || p == arg_start)
21597             dwarf2_macro_malformed_definition_complaint (body);
21598           else
21599             {
21600               /* Make sure argv has room for the new argument.  */
21601               if (argc >= argv_size)
21602                 {
21603                   argv_size *= 2;
21604                   argv = XRESIZEVEC (char *, argv, argv_size);
21605                 }
21606
21607               argv[argc++] = copy_string (arg_start, p - arg_start);
21608             }
21609
21610           p = consume_improper_spaces (p, body);
21611
21612           /* Consume the comma, if present.  */
21613           if (*p == ',')
21614             {
21615               p++;
21616
21617               p = consume_improper_spaces (p, body);
21618             }
21619         }
21620
21621       if (*p == ')')
21622         {
21623           p++;
21624
21625           if (*p == ' ')
21626             /* Perfectly formed definition, no complaints.  */
21627             macro_define_function (file, line, name,
21628                                    argc, (const char **) argv,
21629                                    p + 1);
21630           else if (*p == '\0')
21631             {
21632               /* Complain, but do define it.  */
21633               dwarf2_macro_malformed_definition_complaint (body);
21634               macro_define_function (file, line, name,
21635                                      argc, (const char **) argv,
21636                                      p);
21637             }
21638           else
21639             /* Just complain.  */
21640             dwarf2_macro_malformed_definition_complaint (body);
21641         }
21642       else
21643         /* Just complain.  */
21644         dwarf2_macro_malformed_definition_complaint (body);
21645
21646       xfree (name);
21647       {
21648         int i;
21649
21650         for (i = 0; i < argc; i++)
21651           xfree (argv[i]);
21652       }
21653       xfree (argv);
21654     }
21655   else
21656     dwarf2_macro_malformed_definition_complaint (body);
21657 }
21658
21659 /* Skip some bytes from BYTES according to the form given in FORM.
21660    Returns the new pointer.  */
21661
21662 static const gdb_byte *
21663 skip_form_bytes (bfd *abfd, const gdb_byte *bytes, const gdb_byte *buffer_end,
21664                  enum dwarf_form form,
21665                  unsigned int offset_size,
21666                  struct dwarf2_section_info *section)
21667 {
21668   unsigned int bytes_read;
21669
21670   switch (form)
21671     {
21672     case DW_FORM_data1:
21673     case DW_FORM_flag:
21674       ++bytes;
21675       break;
21676
21677     case DW_FORM_data2:
21678       bytes += 2;
21679       break;
21680
21681     case DW_FORM_data4:
21682       bytes += 4;
21683       break;
21684
21685     case DW_FORM_data8:
21686       bytes += 8;
21687       break;
21688
21689     case DW_FORM_data16:
21690       bytes += 16;
21691       break;
21692
21693     case DW_FORM_string:
21694       read_direct_string (abfd, bytes, &bytes_read);
21695       bytes += bytes_read;
21696       break;
21697
21698     case DW_FORM_sec_offset:
21699     case DW_FORM_strp:
21700     case DW_FORM_GNU_strp_alt:
21701       bytes += offset_size;
21702       break;
21703
21704     case DW_FORM_block:
21705       bytes += read_unsigned_leb128 (abfd, bytes, &bytes_read);
21706       bytes += bytes_read;
21707       break;
21708
21709     case DW_FORM_block1:
21710       bytes += 1 + read_1_byte (abfd, bytes);
21711       break;
21712     case DW_FORM_block2:
21713       bytes += 2 + read_2_bytes (abfd, bytes);
21714       break;
21715     case DW_FORM_block4:
21716       bytes += 4 + read_4_bytes (abfd, bytes);
21717       break;
21718
21719     case DW_FORM_sdata:
21720     case DW_FORM_udata:
21721     case DW_FORM_GNU_addr_index:
21722     case DW_FORM_GNU_str_index:
21723       bytes = gdb_skip_leb128 (bytes, buffer_end);
21724       if (bytes == NULL)
21725         {
21726           dwarf2_section_buffer_overflow_complaint (section);
21727           return NULL;
21728         }
21729       break;
21730
21731     default:
21732       {
21733       complain:
21734         complaint (&symfile_complaints,
21735                    _("invalid form 0x%x in `%s'"),
21736                    form, get_section_name (section));
21737         return NULL;
21738       }
21739     }
21740
21741   return bytes;
21742 }
21743
21744 /* A helper for dwarf_decode_macros that handles skipping an unknown
21745    opcode.  Returns an updated pointer to the macro data buffer; or,
21746    on error, issues a complaint and returns NULL.  */
21747
21748 static const gdb_byte *
21749 skip_unknown_opcode (unsigned int opcode,
21750                      const gdb_byte **opcode_definitions,
21751                      const gdb_byte *mac_ptr, const gdb_byte *mac_end,
21752                      bfd *abfd,
21753                      unsigned int offset_size,
21754                      struct dwarf2_section_info *section)
21755 {
21756   unsigned int bytes_read, i;
21757   unsigned long arg;
21758   const gdb_byte *defn;
21759
21760   if (opcode_definitions[opcode] == NULL)
21761     {
21762       complaint (&symfile_complaints,
21763                  _("unrecognized DW_MACFINO opcode 0x%x"),
21764                  opcode);
21765       return NULL;
21766     }
21767
21768   defn = opcode_definitions[opcode];
21769   arg = read_unsigned_leb128 (abfd, defn, &bytes_read);
21770   defn += bytes_read;
21771
21772   for (i = 0; i < arg; ++i)
21773     {
21774       mac_ptr = skip_form_bytes (abfd, mac_ptr, mac_end,
21775                                  (enum dwarf_form) defn[i], offset_size,
21776                                  section);
21777       if (mac_ptr == NULL)
21778         {
21779           /* skip_form_bytes already issued the complaint.  */
21780           return NULL;
21781         }
21782     }
21783
21784   return mac_ptr;
21785 }
21786
21787 /* A helper function which parses the header of a macro section.
21788    If the macro section is the extended (for now called "GNU") type,
21789    then this updates *OFFSET_SIZE.  Returns a pointer to just after
21790    the header, or issues a complaint and returns NULL on error.  */
21791
21792 static const gdb_byte *
21793 dwarf_parse_macro_header (const gdb_byte **opcode_definitions,
21794                           bfd *abfd,
21795                           const gdb_byte *mac_ptr,
21796                           unsigned int *offset_size,
21797                           int section_is_gnu)
21798 {
21799   memset (opcode_definitions, 0, 256 * sizeof (gdb_byte *));
21800
21801   if (section_is_gnu)
21802     {
21803       unsigned int version, flags;
21804
21805       version = read_2_bytes (abfd, mac_ptr);
21806       if (version != 4 && version != 5)
21807         {
21808           complaint (&symfile_complaints,
21809                      _("unrecognized version `%d' in .debug_macro section"),
21810                      version);
21811           return NULL;
21812         }
21813       mac_ptr += 2;
21814
21815       flags = read_1_byte (abfd, mac_ptr);
21816       ++mac_ptr;
21817       *offset_size = (flags & 1) ? 8 : 4;
21818
21819       if ((flags & 2) != 0)
21820         /* We don't need the line table offset.  */
21821         mac_ptr += *offset_size;
21822
21823       /* Vendor opcode descriptions.  */
21824       if ((flags & 4) != 0)
21825         {
21826           unsigned int i, count;
21827
21828           count = read_1_byte (abfd, mac_ptr);
21829           ++mac_ptr;
21830           for (i = 0; i < count; ++i)
21831             {
21832               unsigned int opcode, bytes_read;
21833               unsigned long arg;
21834
21835               opcode = read_1_byte (abfd, mac_ptr);
21836               ++mac_ptr;
21837               opcode_definitions[opcode] = mac_ptr;
21838               arg = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
21839               mac_ptr += bytes_read;
21840               mac_ptr += arg;
21841             }
21842         }
21843     }
21844
21845   return mac_ptr;
21846 }
21847
21848 /* A helper for dwarf_decode_macros that handles the GNU extensions,
21849    including DW_MACRO_import.  */
21850
21851 static void
21852 dwarf_decode_macro_bytes (bfd *abfd,
21853                           const gdb_byte *mac_ptr, const gdb_byte *mac_end,
21854                           struct macro_source_file *current_file,
21855                           struct line_header *lh,
21856                           struct dwarf2_section_info *section,
21857                           int section_is_gnu, int section_is_dwz,
21858                           unsigned int offset_size,
21859                           htab_t include_hash)
21860 {
21861   struct objfile *objfile = dwarf2_per_objfile->objfile;
21862   enum dwarf_macro_record_type macinfo_type;
21863   int at_commandline;
21864   const gdb_byte *opcode_definitions[256];
21865
21866   mac_ptr = dwarf_parse_macro_header (opcode_definitions, abfd, mac_ptr,
21867                                       &offset_size, section_is_gnu);
21868   if (mac_ptr == NULL)
21869     {
21870       /* We already issued a complaint.  */
21871       return;
21872     }
21873
21874   /* Determines if GDB is still before first DW_MACINFO_start_file.  If true
21875      GDB is still reading the definitions from command line.  First
21876      DW_MACINFO_start_file will need to be ignored as it was already executed
21877      to create CURRENT_FILE for the main source holding also the command line
21878      definitions.  On first met DW_MACINFO_start_file this flag is reset to
21879      normally execute all the remaining DW_MACINFO_start_file macinfos.  */
21880
21881   at_commandline = 1;
21882
21883   do
21884     {
21885       /* Do we at least have room for a macinfo type byte?  */
21886       if (mac_ptr >= mac_end)
21887         {
21888           dwarf2_section_buffer_overflow_complaint (section);
21889           break;
21890         }
21891
21892       macinfo_type = (enum dwarf_macro_record_type) read_1_byte (abfd, mac_ptr);
21893       mac_ptr++;
21894
21895       /* Note that we rely on the fact that the corresponding GNU and
21896          DWARF constants are the same.  */
21897       switch (macinfo_type)
21898         {
21899           /* A zero macinfo type indicates the end of the macro
21900              information.  */
21901         case 0:
21902           break;
21903
21904         case DW_MACRO_define:
21905         case DW_MACRO_undef:
21906         case DW_MACRO_define_strp:
21907         case DW_MACRO_undef_strp:
21908         case DW_MACRO_define_sup:
21909         case DW_MACRO_undef_sup:
21910           {
21911             unsigned int bytes_read;
21912             int line;
21913             const char *body;
21914             int is_define;
21915
21916             line = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
21917             mac_ptr += bytes_read;
21918
21919             if (macinfo_type == DW_MACRO_define
21920                 || macinfo_type == DW_MACRO_undef)
21921               {
21922                 body = read_direct_string (abfd, mac_ptr, &bytes_read);
21923                 mac_ptr += bytes_read;
21924               }
21925             else
21926               {
21927                 LONGEST str_offset;
21928
21929                 str_offset = read_offset_1 (abfd, mac_ptr, offset_size);
21930                 mac_ptr += offset_size;
21931
21932                 if (macinfo_type == DW_MACRO_define_sup
21933                     || macinfo_type == DW_MACRO_undef_sup
21934                     || section_is_dwz)
21935                   {
21936                     struct dwz_file *dwz = dwarf2_get_dwz_file ();
21937
21938                     body = read_indirect_string_from_dwz (dwz, str_offset);
21939                   }
21940                 else
21941                   body = read_indirect_string_at_offset (abfd, str_offset);
21942               }
21943
21944             is_define = (macinfo_type == DW_MACRO_define
21945                          || macinfo_type == DW_MACRO_define_strp
21946                          || macinfo_type == DW_MACRO_define_sup);
21947             if (! current_file)
21948               {
21949                 /* DWARF violation as no main source is present.  */
21950                 complaint (&symfile_complaints,
21951                            _("debug info with no main source gives macro %s "
21952                              "on line %d: %s"),
21953                            is_define ? _("definition") : _("undefinition"),
21954                            line, body);
21955                 break;
21956               }
21957             if ((line == 0 && !at_commandline)
21958                 || (line != 0 && at_commandline))
21959               complaint (&symfile_complaints,
21960                          _("debug info gives %s macro %s with %s line %d: %s"),
21961                          at_commandline ? _("command-line") : _("in-file"),
21962                          is_define ? _("definition") : _("undefinition"),
21963                          line == 0 ? _("zero") : _("non-zero"), line, body);
21964
21965             if (is_define)
21966               parse_macro_definition (current_file, line, body);
21967             else
21968               {
21969                 gdb_assert (macinfo_type == DW_MACRO_undef
21970                             || macinfo_type == DW_MACRO_undef_strp
21971                             || macinfo_type == DW_MACRO_undef_sup);
21972                 macro_undef (current_file, line, body);
21973               }
21974           }
21975           break;
21976
21977         case DW_MACRO_start_file:
21978           {
21979             unsigned int bytes_read;
21980             int line, file;
21981
21982             line = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
21983             mac_ptr += bytes_read;
21984             file = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
21985             mac_ptr += bytes_read;
21986
21987             if ((line == 0 && !at_commandline)
21988                 || (line != 0 && at_commandline))
21989               complaint (&symfile_complaints,
21990                          _("debug info gives source %d included "
21991                            "from %s at %s line %d"),
21992                          file, at_commandline ? _("command-line") : _("file"),
21993                          line == 0 ? _("zero") : _("non-zero"), line);
21994
21995             if (at_commandline)
21996               {
21997                 /* This DW_MACRO_start_file was executed in the
21998                    pass one.  */
21999                 at_commandline = 0;
22000               }
22001             else
22002               current_file = macro_start_file (file, line, current_file, lh);
22003           }
22004           break;
22005
22006         case DW_MACRO_end_file:
22007           if (! current_file)
22008             complaint (&symfile_complaints,
22009                        _("macro debug info has an unmatched "
22010                          "`close_file' directive"));
22011           else
22012             {
22013               current_file = current_file->included_by;
22014               if (! current_file)
22015                 {
22016                   enum dwarf_macro_record_type next_type;
22017
22018                   /* GCC circa March 2002 doesn't produce the zero
22019                      type byte marking the end of the compilation
22020                      unit.  Complain if it's not there, but exit no
22021                      matter what.  */
22022
22023                   /* Do we at least have room for a macinfo type byte?  */
22024                   if (mac_ptr >= mac_end)
22025                     {
22026                       dwarf2_section_buffer_overflow_complaint (section);
22027                       return;
22028                     }
22029
22030                   /* We don't increment mac_ptr here, so this is just
22031                      a look-ahead.  */
22032                   next_type
22033                     = (enum dwarf_macro_record_type) read_1_byte (abfd,
22034                                                                   mac_ptr);
22035                   if (next_type != 0)
22036                     complaint (&symfile_complaints,
22037                                _("no terminating 0-type entry for "
22038                                  "macros in `.debug_macinfo' section"));
22039
22040                   return;
22041                 }
22042             }
22043           break;
22044
22045         case DW_MACRO_import:
22046         case DW_MACRO_import_sup:
22047           {
22048             LONGEST offset;
22049             void **slot;
22050             bfd *include_bfd = abfd;
22051             struct dwarf2_section_info *include_section = section;
22052             const gdb_byte *include_mac_end = mac_end;
22053             int is_dwz = section_is_dwz;
22054             const gdb_byte *new_mac_ptr;
22055
22056             offset = read_offset_1 (abfd, mac_ptr, offset_size);
22057             mac_ptr += offset_size;
22058
22059             if (macinfo_type == DW_MACRO_import_sup)
22060               {
22061                 struct dwz_file *dwz = dwarf2_get_dwz_file ();
22062
22063                 dwarf2_read_section (objfile, &dwz->macro);
22064
22065                 include_section = &dwz->macro;
22066                 include_bfd = get_section_bfd_owner (include_section);
22067                 include_mac_end = dwz->macro.buffer + dwz->macro.size;
22068                 is_dwz = 1;
22069               }
22070
22071             new_mac_ptr = include_section->buffer + offset;
22072             slot = htab_find_slot (include_hash, new_mac_ptr, INSERT);
22073
22074             if (*slot != NULL)
22075               {
22076                 /* This has actually happened; see
22077                    http://sourceware.org/bugzilla/show_bug.cgi?id=13568.  */
22078                 complaint (&symfile_complaints,
22079                            _("recursive DW_MACRO_import in "
22080                              ".debug_macro section"));
22081               }
22082             else
22083               {
22084                 *slot = (void *) new_mac_ptr;
22085
22086                 dwarf_decode_macro_bytes (include_bfd, new_mac_ptr,
22087                                           include_mac_end, current_file, lh,
22088                                           section, section_is_gnu, is_dwz,
22089                                           offset_size, include_hash);
22090
22091                 htab_remove_elt (include_hash, (void *) new_mac_ptr);
22092               }
22093           }
22094           break;
22095
22096         case DW_MACINFO_vendor_ext:
22097           if (!section_is_gnu)
22098             {
22099               unsigned int bytes_read;
22100
22101               /* This reads the constant, but since we don't recognize
22102                  any vendor extensions, we ignore it.  */
22103               read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
22104               mac_ptr += bytes_read;
22105               read_direct_string (abfd, mac_ptr, &bytes_read);
22106               mac_ptr += bytes_read;
22107
22108               /* We don't recognize any vendor extensions.  */
22109               break;
22110             }
22111           /* FALLTHROUGH */
22112
22113         default:
22114           mac_ptr = skip_unknown_opcode (macinfo_type, opcode_definitions,
22115                                          mac_ptr, mac_end, abfd, offset_size,
22116                                          section);
22117           if (mac_ptr == NULL)
22118             return;
22119           break;
22120         }
22121     } while (macinfo_type != 0);
22122 }
22123
22124 static void
22125 dwarf_decode_macros (struct dwarf2_cu *cu, unsigned int offset,
22126                      int section_is_gnu)
22127 {
22128   struct objfile *objfile = dwarf2_per_objfile->objfile;
22129   struct line_header *lh = cu->line_header;
22130   bfd *abfd;
22131   const gdb_byte *mac_ptr, *mac_end;
22132   struct macro_source_file *current_file = 0;
22133   enum dwarf_macro_record_type macinfo_type;
22134   unsigned int offset_size = cu->header.offset_size;
22135   const gdb_byte *opcode_definitions[256];
22136   struct cleanup *cleanup;
22137   void **slot;
22138   struct dwarf2_section_info *section;
22139   const char *section_name;
22140
22141   if (cu->dwo_unit != NULL)
22142     {
22143       if (section_is_gnu)
22144         {
22145           section = &cu->dwo_unit->dwo_file->sections.macro;
22146           section_name = ".debug_macro.dwo";
22147         }
22148       else
22149         {
22150           section = &cu->dwo_unit->dwo_file->sections.macinfo;
22151           section_name = ".debug_macinfo.dwo";
22152         }
22153     }
22154   else
22155     {
22156       if (section_is_gnu)
22157         {
22158           section = &dwarf2_per_objfile->macro;
22159           section_name = ".debug_macro";
22160         }
22161       else
22162         {
22163           section = &dwarf2_per_objfile->macinfo;
22164           section_name = ".debug_macinfo";
22165         }
22166     }
22167
22168   dwarf2_read_section (objfile, section);
22169   if (section->buffer == NULL)
22170     {
22171       complaint (&symfile_complaints, _("missing %s section"), section_name);
22172       return;
22173     }
22174   abfd = get_section_bfd_owner (section);
22175
22176   /* First pass: Find the name of the base filename.
22177      This filename is needed in order to process all macros whose definition
22178      (or undefinition) comes from the command line.  These macros are defined
22179      before the first DW_MACINFO_start_file entry, and yet still need to be
22180      associated to the base file.
22181
22182      To determine the base file name, we scan the macro definitions until we
22183      reach the first DW_MACINFO_start_file entry.  We then initialize
22184      CURRENT_FILE accordingly so that any macro definition found before the
22185      first DW_MACINFO_start_file can still be associated to the base file.  */
22186
22187   mac_ptr = section->buffer + offset;
22188   mac_end = section->buffer + section->size;
22189
22190   mac_ptr = dwarf_parse_macro_header (opcode_definitions, abfd, mac_ptr,
22191                                       &offset_size, section_is_gnu);
22192   if (mac_ptr == NULL)
22193     {
22194       /* We already issued a complaint.  */
22195       return;
22196     }
22197
22198   do
22199     {
22200       /* Do we at least have room for a macinfo type byte?  */
22201       if (mac_ptr >= mac_end)
22202         {
22203           /* Complaint is printed during the second pass as GDB will probably
22204              stop the first pass earlier upon finding
22205              DW_MACINFO_start_file.  */
22206           break;
22207         }
22208
22209       macinfo_type = (enum dwarf_macro_record_type) read_1_byte (abfd, mac_ptr);
22210       mac_ptr++;
22211
22212       /* Note that we rely on the fact that the corresponding GNU and
22213          DWARF constants are the same.  */
22214       switch (macinfo_type)
22215         {
22216           /* A zero macinfo type indicates the end of the macro
22217              information.  */
22218         case 0:
22219           break;
22220
22221         case DW_MACRO_define:
22222         case DW_MACRO_undef:
22223           /* Only skip the data by MAC_PTR.  */
22224           {
22225             unsigned int bytes_read;
22226
22227             read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
22228             mac_ptr += bytes_read;
22229             read_direct_string (abfd, mac_ptr, &bytes_read);
22230             mac_ptr += bytes_read;
22231           }
22232           break;
22233
22234         case DW_MACRO_start_file:
22235           {
22236             unsigned int bytes_read;
22237             int line, file;
22238
22239             line = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
22240             mac_ptr += bytes_read;
22241             file = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
22242             mac_ptr += bytes_read;
22243
22244             current_file = macro_start_file (file, line, current_file, lh);
22245           }
22246           break;
22247
22248         case DW_MACRO_end_file:
22249           /* No data to skip by MAC_PTR.  */
22250           break;
22251
22252         case DW_MACRO_define_strp:
22253         case DW_MACRO_undef_strp:
22254         case DW_MACRO_define_sup:
22255         case DW_MACRO_undef_sup:
22256           {
22257             unsigned int bytes_read;
22258
22259             read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
22260             mac_ptr += bytes_read;
22261             mac_ptr += offset_size;
22262           }
22263           break;
22264
22265         case DW_MACRO_import:
22266         case DW_MACRO_import_sup:
22267           /* Note that, according to the spec, a transparent include
22268              chain cannot call DW_MACRO_start_file.  So, we can just
22269              skip this opcode.  */
22270           mac_ptr += offset_size;
22271           break;
22272
22273         case DW_MACINFO_vendor_ext:
22274           /* Only skip the data by MAC_PTR.  */
22275           if (!section_is_gnu)
22276             {
22277               unsigned int bytes_read;
22278
22279               read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
22280               mac_ptr += bytes_read;
22281               read_direct_string (abfd, mac_ptr, &bytes_read);
22282               mac_ptr += bytes_read;
22283             }
22284           /* FALLTHROUGH */
22285
22286         default:
22287           mac_ptr = skip_unknown_opcode (macinfo_type, opcode_definitions,
22288                                          mac_ptr, mac_end, abfd, offset_size,
22289                                          section);
22290           if (mac_ptr == NULL)
22291             return;
22292           break;
22293         }
22294     } while (macinfo_type != 0 && current_file == NULL);
22295
22296   /* Second pass: Process all entries.
22297
22298      Use the AT_COMMAND_LINE flag to determine whether we are still processing
22299      command-line macro definitions/undefinitions.  This flag is unset when we
22300      reach the first DW_MACINFO_start_file entry.  */
22301
22302   htab_up include_hash (htab_create_alloc (1, htab_hash_pointer,
22303                                            htab_eq_pointer,
22304                                            NULL, xcalloc, xfree));
22305   mac_ptr = section->buffer + offset;
22306   slot = htab_find_slot (include_hash.get (), mac_ptr, INSERT);
22307   *slot = (void *) mac_ptr;
22308   dwarf_decode_macro_bytes (abfd, mac_ptr, mac_end,
22309                             current_file, lh, section,
22310                             section_is_gnu, 0, offset_size,
22311                             include_hash.get ());
22312 }
22313
22314 /* Check if the attribute's form is a DW_FORM_block*
22315    if so return true else false.  */
22316
22317 static int
22318 attr_form_is_block (const struct attribute *attr)
22319 {
22320   return (attr == NULL ? 0 :
22321       attr->form == DW_FORM_block1
22322       || attr->form == DW_FORM_block2
22323       || attr->form == DW_FORM_block4
22324       || attr->form == DW_FORM_block
22325       || attr->form == DW_FORM_exprloc);
22326 }
22327
22328 /* Return non-zero if ATTR's value is a section offset --- classes
22329    lineptr, loclistptr, macptr or rangelistptr --- or zero, otherwise.
22330    You may use DW_UNSND (attr) to retrieve such offsets.
22331
22332    Section 7.5.4, "Attribute Encodings", explains that no attribute
22333    may have a value that belongs to more than one of these classes; it
22334    would be ambiguous if we did, because we use the same forms for all
22335    of them.  */
22336
22337 static int
22338 attr_form_is_section_offset (const struct attribute *attr)
22339 {
22340   return (attr->form == DW_FORM_data4
22341           || attr->form == DW_FORM_data8
22342           || attr->form == DW_FORM_sec_offset);
22343 }
22344
22345 /* Return non-zero if ATTR's value falls in the 'constant' class, or
22346    zero otherwise.  When this function returns true, you can apply
22347    dwarf2_get_attr_constant_value to it.
22348
22349    However, note that for some attributes you must check
22350    attr_form_is_section_offset before using this test.  DW_FORM_data4
22351    and DW_FORM_data8 are members of both the constant class, and of
22352    the classes that contain offsets into other debug sections
22353    (lineptr, loclistptr, macptr or rangelistptr).  The DWARF spec says
22354    that, if an attribute's can be either a constant or one of the
22355    section offset classes, DW_FORM_data4 and DW_FORM_data8 should be
22356    taken as section offsets, not constants.
22357
22358    DW_FORM_data16 is not considered as dwarf2_get_attr_constant_value
22359    cannot handle that.  */
22360
22361 static int
22362 attr_form_is_constant (const struct attribute *attr)
22363 {
22364   switch (attr->form)
22365     {
22366     case DW_FORM_sdata:
22367     case DW_FORM_udata:
22368     case DW_FORM_data1:
22369     case DW_FORM_data2:
22370     case DW_FORM_data4:
22371     case DW_FORM_data8:
22372       return 1;
22373     default:
22374       return 0;
22375     }
22376 }
22377
22378
22379 /* DW_ADDR is always stored already as sect_offset; despite for the forms
22380    besides DW_FORM_ref_addr it is stored as cu_offset in the DWARF file.  */
22381
22382 static int
22383 attr_form_is_ref (const struct attribute *attr)
22384 {
22385   switch (attr->form)
22386     {
22387     case DW_FORM_ref_addr:
22388     case DW_FORM_ref1:
22389     case DW_FORM_ref2:
22390     case DW_FORM_ref4:
22391     case DW_FORM_ref8:
22392     case DW_FORM_ref_udata:
22393     case DW_FORM_GNU_ref_alt:
22394       return 1;
22395     default:
22396       return 0;
22397     }
22398 }
22399
22400 /* Return the .debug_loc section to use for CU.
22401    For DWO files use .debug_loc.dwo.  */
22402
22403 static struct dwarf2_section_info *
22404 cu_debug_loc_section (struct dwarf2_cu *cu)
22405 {
22406   if (cu->dwo_unit)
22407     {
22408       struct dwo_sections *sections = &cu->dwo_unit->dwo_file->sections;
22409       
22410       return cu->header.version >= 5 ? &sections->loclists : &sections->loc;
22411     }
22412   return (cu->header.version >= 5 ? &dwarf2_per_objfile->loclists
22413                                   : &dwarf2_per_objfile->loc);
22414 }
22415
22416 /* A helper function that fills in a dwarf2_loclist_baton.  */
22417
22418 static void
22419 fill_in_loclist_baton (struct dwarf2_cu *cu,
22420                        struct dwarf2_loclist_baton *baton,
22421                        const struct attribute *attr)
22422 {
22423   struct dwarf2_section_info *section = cu_debug_loc_section (cu);
22424
22425   dwarf2_read_section (dwarf2_per_objfile->objfile, section);
22426
22427   baton->per_cu = cu->per_cu;
22428   gdb_assert (baton->per_cu);
22429   /* We don't know how long the location list is, but make sure we
22430      don't run off the edge of the section.  */
22431   baton->size = section->size - DW_UNSND (attr);
22432   baton->data = section->buffer + DW_UNSND (attr);
22433   baton->base_address = cu->base_address;
22434   baton->from_dwo = cu->dwo_unit != NULL;
22435 }
22436
22437 static void
22438 dwarf2_symbol_mark_computed (const struct attribute *attr, struct symbol *sym,
22439                              struct dwarf2_cu *cu, int is_block)
22440 {
22441   struct objfile *objfile = dwarf2_per_objfile->objfile;
22442   struct dwarf2_section_info *section = cu_debug_loc_section (cu);
22443
22444   if (attr_form_is_section_offset (attr)
22445       /* .debug_loc{,.dwo} may not exist at all, or the offset may be outside
22446          the section.  If so, fall through to the complaint in the
22447          other branch.  */
22448       && DW_UNSND (attr) < dwarf2_section_size (objfile, section))
22449     {
22450       struct dwarf2_loclist_baton *baton;
22451
22452       baton = XOBNEW (&objfile->objfile_obstack, struct dwarf2_loclist_baton);
22453
22454       fill_in_loclist_baton (cu, baton, attr);
22455
22456       if (cu->base_known == 0)
22457         complaint (&symfile_complaints,
22458                    _("Location list used without "
22459                      "specifying the CU base address."));
22460
22461       SYMBOL_ACLASS_INDEX (sym) = (is_block
22462                                    ? dwarf2_loclist_block_index
22463                                    : dwarf2_loclist_index);
22464       SYMBOL_LOCATION_BATON (sym) = baton;
22465     }
22466   else
22467     {
22468       struct dwarf2_locexpr_baton *baton;
22469
22470       baton = XOBNEW (&objfile->objfile_obstack, struct dwarf2_locexpr_baton);
22471       baton->per_cu = cu->per_cu;
22472       gdb_assert (baton->per_cu);
22473
22474       if (attr_form_is_block (attr))
22475         {
22476           /* Note that we're just copying the block's data pointer
22477              here, not the actual data.  We're still pointing into the
22478              info_buffer for SYM's objfile; right now we never release
22479              that buffer, but when we do clean up properly this may
22480              need to change.  */
22481           baton->size = DW_BLOCK (attr)->size;
22482           baton->data = DW_BLOCK (attr)->data;
22483         }
22484       else
22485         {
22486           dwarf2_invalid_attrib_class_complaint ("location description",
22487                                                  SYMBOL_NATURAL_NAME (sym));
22488           baton->size = 0;
22489         }
22490
22491       SYMBOL_ACLASS_INDEX (sym) = (is_block
22492                                    ? dwarf2_locexpr_block_index
22493                                    : dwarf2_locexpr_index);
22494       SYMBOL_LOCATION_BATON (sym) = baton;
22495     }
22496 }
22497
22498 /* Return the OBJFILE associated with the compilation unit CU.  If CU
22499    came from a separate debuginfo file, then the master objfile is
22500    returned.  */
22501
22502 struct objfile *
22503 dwarf2_per_cu_objfile (struct dwarf2_per_cu_data *per_cu)
22504 {
22505   struct objfile *objfile = per_cu->objfile;
22506
22507   /* Return the master objfile, so that we can report and look up the
22508      correct file containing this variable.  */
22509   if (objfile->separate_debug_objfile_backlink)
22510     objfile = objfile->separate_debug_objfile_backlink;
22511
22512   return objfile;
22513 }
22514
22515 /* Return comp_unit_head for PER_CU, either already available in PER_CU->CU
22516    (CU_HEADERP is unused in such case) or prepare a temporary copy at
22517    CU_HEADERP first.  */
22518
22519 static const struct comp_unit_head *
22520 per_cu_header_read_in (struct comp_unit_head *cu_headerp,
22521                        struct dwarf2_per_cu_data *per_cu)
22522 {
22523   const gdb_byte *info_ptr;
22524
22525   if (per_cu->cu)
22526     return &per_cu->cu->header;
22527
22528   info_ptr = per_cu->section->buffer + per_cu->offset.sect_off;
22529
22530   memset (cu_headerp, 0, sizeof (*cu_headerp));
22531   read_comp_unit_head (cu_headerp, info_ptr, per_cu->section,
22532                        rcuh_kind::COMPILE);
22533
22534   return cu_headerp;
22535 }
22536
22537 /* Return the address size given in the compilation unit header for CU.  */
22538
22539 int
22540 dwarf2_per_cu_addr_size (struct dwarf2_per_cu_data *per_cu)
22541 {
22542   struct comp_unit_head cu_header_local;
22543   const struct comp_unit_head *cu_headerp;
22544
22545   cu_headerp = per_cu_header_read_in (&cu_header_local, per_cu);
22546
22547   return cu_headerp->addr_size;
22548 }
22549
22550 /* Return the offset size given in the compilation unit header for CU.  */
22551
22552 int
22553 dwarf2_per_cu_offset_size (struct dwarf2_per_cu_data *per_cu)
22554 {
22555   struct comp_unit_head cu_header_local;
22556   const struct comp_unit_head *cu_headerp;
22557
22558   cu_headerp = per_cu_header_read_in (&cu_header_local, per_cu);
22559
22560   return cu_headerp->offset_size;
22561 }
22562
22563 /* See its dwarf2loc.h declaration.  */
22564
22565 int
22566 dwarf2_per_cu_ref_addr_size (struct dwarf2_per_cu_data *per_cu)
22567 {
22568   struct comp_unit_head cu_header_local;
22569   const struct comp_unit_head *cu_headerp;
22570
22571   cu_headerp = per_cu_header_read_in (&cu_header_local, per_cu);
22572
22573   if (cu_headerp->version == 2)
22574     return cu_headerp->addr_size;
22575   else
22576     return cu_headerp->offset_size;
22577 }
22578
22579 /* Return the text offset of the CU.  The returned offset comes from
22580    this CU's objfile.  If this objfile came from a separate debuginfo
22581    file, then the offset may be different from the corresponding
22582    offset in the parent objfile.  */
22583
22584 CORE_ADDR
22585 dwarf2_per_cu_text_offset (struct dwarf2_per_cu_data *per_cu)
22586 {
22587   struct objfile *objfile = per_cu->objfile;
22588
22589   return ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
22590 }
22591
22592 /* Return DWARF version number of PER_CU.  */
22593
22594 short
22595 dwarf2_version (struct dwarf2_per_cu_data *per_cu)
22596 {
22597   return per_cu->dwarf_version;
22598 }
22599
22600 /* Locate the .debug_info compilation unit from CU's objfile which contains
22601    the DIE at OFFSET.  Raises an error on failure.  */
22602
22603 static struct dwarf2_per_cu_data *
22604 dwarf2_find_containing_comp_unit (sect_offset offset,
22605                                   unsigned int offset_in_dwz,
22606                                   struct objfile *objfile)
22607 {
22608   struct dwarf2_per_cu_data *this_cu;
22609   int low, high;
22610   const sect_offset *cu_off;
22611
22612   low = 0;
22613   high = dwarf2_per_objfile->n_comp_units - 1;
22614   while (high > low)
22615     {
22616       struct dwarf2_per_cu_data *mid_cu;
22617       int mid = low + (high - low) / 2;
22618
22619       mid_cu = dwarf2_per_objfile->all_comp_units[mid];
22620       cu_off = &mid_cu->offset;
22621       if (mid_cu->is_dwz > offset_in_dwz
22622           || (mid_cu->is_dwz == offset_in_dwz
22623               && cu_off->sect_off >= offset.sect_off))
22624         high = mid;
22625       else
22626         low = mid + 1;
22627     }
22628   gdb_assert (low == high);
22629   this_cu = dwarf2_per_objfile->all_comp_units[low];
22630   cu_off = &this_cu->offset;
22631   if (this_cu->is_dwz != offset_in_dwz || cu_off->sect_off > offset.sect_off)
22632     {
22633       if (low == 0 || this_cu->is_dwz != offset_in_dwz)
22634         error (_("Dwarf Error: could not find partial DIE containing "
22635                "offset 0x%lx [in module %s]"),
22636                (long) offset.sect_off, bfd_get_filename (objfile->obfd));
22637
22638       gdb_assert (dwarf2_per_objfile->all_comp_units[low-1]->offset.sect_off
22639                   <= offset.sect_off);
22640       return dwarf2_per_objfile->all_comp_units[low-1];
22641     }
22642   else
22643     {
22644       this_cu = dwarf2_per_objfile->all_comp_units[low];
22645       if (low == dwarf2_per_objfile->n_comp_units - 1
22646           && offset.sect_off >= this_cu->offset.sect_off + this_cu->length)
22647         error (_("invalid dwarf2 offset %u"), offset.sect_off);
22648       gdb_assert (offset.sect_off < this_cu->offset.sect_off + this_cu->length);
22649       return this_cu;
22650     }
22651 }
22652
22653 /* Initialize dwarf2_cu CU, owned by PER_CU.  */
22654
22655 static void
22656 init_one_comp_unit (struct dwarf2_cu *cu, struct dwarf2_per_cu_data *per_cu)
22657 {
22658   memset (cu, 0, sizeof (*cu));
22659   per_cu->cu = cu;
22660   cu->per_cu = per_cu;
22661   cu->objfile = per_cu->objfile;
22662   obstack_init (&cu->comp_unit_obstack);
22663 }
22664
22665 /* Initialize basic fields of dwarf_cu CU according to DIE COMP_UNIT_DIE.  */
22666
22667 static void
22668 prepare_one_comp_unit (struct dwarf2_cu *cu, struct die_info *comp_unit_die,
22669                        enum language pretend_language)
22670 {
22671   struct attribute *attr;
22672
22673   /* Set the language we're debugging.  */
22674   attr = dwarf2_attr (comp_unit_die, DW_AT_language, cu);
22675   if (attr)
22676     set_cu_language (DW_UNSND (attr), cu);
22677   else
22678     {
22679       cu->language = pretend_language;
22680       cu->language_defn = language_def (cu->language);
22681     }
22682
22683   cu->producer = dwarf2_string_attr (comp_unit_die, DW_AT_producer, cu);
22684 }
22685
22686 /* Release one cached compilation unit, CU.  We unlink it from the tree
22687    of compilation units, but we don't remove it from the read_in_chain;
22688    the caller is responsible for that.
22689    NOTE: DATA is a void * because this function is also used as a
22690    cleanup routine.  */
22691
22692 static void
22693 free_heap_comp_unit (void *data)
22694 {
22695   struct dwarf2_cu *cu = (struct dwarf2_cu *) data;
22696
22697   gdb_assert (cu->per_cu != NULL);
22698   cu->per_cu->cu = NULL;
22699   cu->per_cu = NULL;
22700
22701   obstack_free (&cu->comp_unit_obstack, NULL);
22702
22703   xfree (cu);
22704 }
22705
22706 /* This cleanup function is passed the address of a dwarf2_cu on the stack
22707    when we're finished with it.  We can't free the pointer itself, but be
22708    sure to unlink it from the cache.  Also release any associated storage.  */
22709
22710 static void
22711 free_stack_comp_unit (void *data)
22712 {
22713   struct dwarf2_cu *cu = (struct dwarf2_cu *) data;
22714
22715   gdb_assert (cu->per_cu != NULL);
22716   cu->per_cu->cu = NULL;
22717   cu->per_cu = NULL;
22718
22719   obstack_free (&cu->comp_unit_obstack, NULL);
22720   cu->partial_dies = NULL;
22721 }
22722
22723 /* Free all cached compilation units.  */
22724
22725 static void
22726 free_cached_comp_units (void *data)
22727 {
22728   struct dwarf2_per_cu_data *per_cu, **last_chain;
22729
22730   per_cu = dwarf2_per_objfile->read_in_chain;
22731   last_chain = &dwarf2_per_objfile->read_in_chain;
22732   while (per_cu != NULL)
22733     {
22734       struct dwarf2_per_cu_data *next_cu;
22735
22736       next_cu = per_cu->cu->read_in_chain;
22737
22738       free_heap_comp_unit (per_cu->cu);
22739       *last_chain = next_cu;
22740
22741       per_cu = next_cu;
22742     }
22743 }
22744
22745 /* Increase the age counter on each cached compilation unit, and free
22746    any that are too old.  */
22747
22748 static void
22749 age_cached_comp_units (void)
22750 {
22751   struct dwarf2_per_cu_data *per_cu, **last_chain;
22752
22753   dwarf2_clear_marks (dwarf2_per_objfile->read_in_chain);
22754   per_cu = dwarf2_per_objfile->read_in_chain;
22755   while (per_cu != NULL)
22756     {
22757       per_cu->cu->last_used ++;
22758       if (per_cu->cu->last_used <= dwarf_max_cache_age)
22759         dwarf2_mark (per_cu->cu);
22760       per_cu = per_cu->cu->read_in_chain;
22761     }
22762
22763   per_cu = dwarf2_per_objfile->read_in_chain;
22764   last_chain = &dwarf2_per_objfile->read_in_chain;
22765   while (per_cu != NULL)
22766     {
22767       struct dwarf2_per_cu_data *next_cu;
22768
22769       next_cu = per_cu->cu->read_in_chain;
22770
22771       if (!per_cu->cu->mark)
22772         {
22773           free_heap_comp_unit (per_cu->cu);
22774           *last_chain = next_cu;
22775         }
22776       else
22777         last_chain = &per_cu->cu->read_in_chain;
22778
22779       per_cu = next_cu;
22780     }
22781 }
22782
22783 /* Remove a single compilation unit from the cache.  */
22784
22785 static void
22786 free_one_cached_comp_unit (struct dwarf2_per_cu_data *target_per_cu)
22787 {
22788   struct dwarf2_per_cu_data *per_cu, **last_chain;
22789
22790   per_cu = dwarf2_per_objfile->read_in_chain;
22791   last_chain = &dwarf2_per_objfile->read_in_chain;
22792   while (per_cu != NULL)
22793     {
22794       struct dwarf2_per_cu_data *next_cu;
22795
22796       next_cu = per_cu->cu->read_in_chain;
22797
22798       if (per_cu == target_per_cu)
22799         {
22800           free_heap_comp_unit (per_cu->cu);
22801           per_cu->cu = NULL;
22802           *last_chain = next_cu;
22803           break;
22804         }
22805       else
22806         last_chain = &per_cu->cu->read_in_chain;
22807
22808       per_cu = next_cu;
22809     }
22810 }
22811
22812 /* Release all extra memory associated with OBJFILE.  */
22813
22814 void
22815 dwarf2_free_objfile (struct objfile *objfile)
22816 {
22817   dwarf2_per_objfile
22818     = (struct dwarf2_per_objfile *) objfile_data (objfile,
22819                                                   dwarf2_objfile_data_key);
22820
22821   if (dwarf2_per_objfile == NULL)
22822     return;
22823
22824   /* Cached DIE trees use xmalloc and the comp_unit_obstack.  */
22825   free_cached_comp_units (NULL);
22826
22827   if (dwarf2_per_objfile->quick_file_names_table)
22828     htab_delete (dwarf2_per_objfile->quick_file_names_table);
22829
22830   if (dwarf2_per_objfile->line_header_hash)
22831     htab_delete (dwarf2_per_objfile->line_header_hash);
22832
22833   /* Everything else should be on the objfile obstack.  */
22834 }
22835
22836 /* A set of CU "per_cu" pointer, DIE offset, and GDB type pointer.
22837    We store these in a hash table separate from the DIEs, and preserve them
22838    when the DIEs are flushed out of cache.
22839
22840    The CU "per_cu" pointer is needed because offset alone is not enough to
22841    uniquely identify the type.  A file may have multiple .debug_types sections,
22842    or the type may come from a DWO file.  Furthermore, while it's more logical
22843    to use per_cu->section+offset, with Fission the section with the data is in
22844    the DWO file but we don't know that section at the point we need it.
22845    We have to use something in dwarf2_per_cu_data (or the pointer to it)
22846    because we can enter the lookup routine, get_die_type_at_offset, from
22847    outside this file, and thus won't necessarily have PER_CU->cu.
22848    Fortunately, PER_CU is stable for the life of the objfile.  */
22849
22850 struct dwarf2_per_cu_offset_and_type
22851 {
22852   const struct dwarf2_per_cu_data *per_cu;
22853   sect_offset offset;
22854   struct type *type;
22855 };
22856
22857 /* Hash function for a dwarf2_per_cu_offset_and_type.  */
22858
22859 static hashval_t
22860 per_cu_offset_and_type_hash (const void *item)
22861 {
22862   const struct dwarf2_per_cu_offset_and_type *ofs
22863     = (const struct dwarf2_per_cu_offset_and_type *) item;
22864
22865   return (uintptr_t) ofs->per_cu + ofs->offset.sect_off;
22866 }
22867
22868 /* Equality function for a dwarf2_per_cu_offset_and_type.  */
22869
22870 static int
22871 per_cu_offset_and_type_eq (const void *item_lhs, const void *item_rhs)
22872 {
22873   const struct dwarf2_per_cu_offset_and_type *ofs_lhs
22874     = (const struct dwarf2_per_cu_offset_and_type *) item_lhs;
22875   const struct dwarf2_per_cu_offset_and_type *ofs_rhs
22876     = (const struct dwarf2_per_cu_offset_and_type *) item_rhs;
22877
22878   return (ofs_lhs->per_cu == ofs_rhs->per_cu
22879           && ofs_lhs->offset.sect_off == ofs_rhs->offset.sect_off);
22880 }
22881
22882 /* Set the type associated with DIE to TYPE.  Save it in CU's hash
22883    table if necessary.  For convenience, return TYPE.
22884
22885    The DIEs reading must have careful ordering to:
22886     * Not cause infite loops trying to read in DIEs as a prerequisite for
22887       reading current DIE.
22888     * Not trying to dereference contents of still incompletely read in types
22889       while reading in other DIEs.
22890     * Enable referencing still incompletely read in types just by a pointer to
22891       the type without accessing its fields.
22892
22893    Therefore caller should follow these rules:
22894      * Try to fetch any prerequisite types we may need to build this DIE type
22895        before building the type and calling set_die_type.
22896      * After building type call set_die_type for current DIE as soon as
22897        possible before fetching more types to complete the current type.
22898      * Make the type as complete as possible before fetching more types.  */
22899
22900 static struct type *
22901 set_die_type (struct die_info *die, struct type *type, struct dwarf2_cu *cu)
22902 {
22903   struct dwarf2_per_cu_offset_and_type **slot, ofs;
22904   struct objfile *objfile = cu->objfile;
22905   struct attribute *attr;
22906   struct dynamic_prop prop;
22907
22908   /* For Ada types, make sure that the gnat-specific data is always
22909      initialized (if not already set).  There are a few types where
22910      we should not be doing so, because the type-specific area is
22911      already used to hold some other piece of info (eg: TYPE_CODE_FLT
22912      where the type-specific area is used to store the floatformat).
22913      But this is not a problem, because the gnat-specific information
22914      is actually not needed for these types.  */
22915   if (need_gnat_info (cu)
22916       && TYPE_CODE (type) != TYPE_CODE_FUNC
22917       && TYPE_CODE (type) != TYPE_CODE_FLT
22918       && TYPE_CODE (type) != TYPE_CODE_METHODPTR
22919       && TYPE_CODE (type) != TYPE_CODE_MEMBERPTR
22920       && TYPE_CODE (type) != TYPE_CODE_METHOD
22921       && !HAVE_GNAT_AUX_INFO (type))
22922     INIT_GNAT_SPECIFIC (type);
22923
22924   /* Read DW_AT_allocated and set in type.  */
22925   attr = dwarf2_attr (die, DW_AT_allocated, cu);
22926   if (attr_form_is_block (attr))
22927     {
22928       if (attr_to_dynamic_prop (attr, die, cu, &prop))
22929         add_dyn_prop (DYN_PROP_ALLOCATED, prop, type, objfile);
22930     }
22931   else if (attr != NULL)
22932     {
22933       complaint (&symfile_complaints,
22934                 _("DW_AT_allocated has the wrong form (%s) at DIE 0x%x"),
22935                 (attr != NULL ? dwarf_form_name (attr->form) : "n/a"),
22936                 die->offset.sect_off);
22937     }
22938
22939   /* Read DW_AT_associated and set in type.  */
22940   attr = dwarf2_attr (die, DW_AT_associated, cu);
22941   if (attr_form_is_block (attr))
22942     {
22943       if (attr_to_dynamic_prop (attr, die, cu, &prop))
22944         add_dyn_prop (DYN_PROP_ASSOCIATED, prop, type, objfile);
22945     }
22946   else if (attr != NULL)
22947     {
22948       complaint (&symfile_complaints,
22949                 _("DW_AT_associated has the wrong form (%s) at DIE 0x%x"),
22950                 (attr != NULL ? dwarf_form_name (attr->form) : "n/a"),
22951                 die->offset.sect_off);
22952     }
22953
22954   /* Read DW_AT_data_location and set in type.  */
22955   attr = dwarf2_attr (die, DW_AT_data_location, cu);
22956   if (attr_to_dynamic_prop (attr, die, cu, &prop))
22957     add_dyn_prop (DYN_PROP_DATA_LOCATION, prop, type, objfile);
22958
22959   if (dwarf2_per_objfile->die_type_hash == NULL)
22960     {
22961       dwarf2_per_objfile->die_type_hash =
22962         htab_create_alloc_ex (127,
22963                               per_cu_offset_and_type_hash,
22964                               per_cu_offset_and_type_eq,
22965                               NULL,
22966                               &objfile->objfile_obstack,
22967                               hashtab_obstack_allocate,
22968                               dummy_obstack_deallocate);
22969     }
22970
22971   ofs.per_cu = cu->per_cu;
22972   ofs.offset = die->offset;
22973   ofs.type = type;
22974   slot = (struct dwarf2_per_cu_offset_and_type **)
22975     htab_find_slot (dwarf2_per_objfile->die_type_hash, &ofs, INSERT);
22976   if (*slot)
22977     complaint (&symfile_complaints,
22978                _("A problem internal to GDB: DIE 0x%x has type already set"),
22979                die->offset.sect_off);
22980   *slot = XOBNEW (&objfile->objfile_obstack,
22981                   struct dwarf2_per_cu_offset_and_type);
22982   **slot = ofs;
22983   return type;
22984 }
22985
22986 /* Look up the type for the die at OFFSET in PER_CU in die_type_hash,
22987    or return NULL if the die does not have a saved type.  */
22988
22989 static struct type *
22990 get_die_type_at_offset (sect_offset offset,
22991                         struct dwarf2_per_cu_data *per_cu)
22992 {
22993   struct dwarf2_per_cu_offset_and_type *slot, ofs;
22994
22995   if (dwarf2_per_objfile->die_type_hash == NULL)
22996     return NULL;
22997
22998   ofs.per_cu = per_cu;
22999   ofs.offset = offset;
23000   slot = ((struct dwarf2_per_cu_offset_and_type *)
23001           htab_find (dwarf2_per_objfile->die_type_hash, &ofs));
23002   if (slot)
23003     return slot->type;
23004   else
23005     return NULL;
23006 }
23007
23008 /* Look up the type for DIE in CU in die_type_hash,
23009    or return NULL if DIE does not have a saved type.  */
23010
23011 static struct type *
23012 get_die_type (struct die_info *die, struct dwarf2_cu *cu)
23013 {
23014   return get_die_type_at_offset (die->offset, cu->per_cu);
23015 }
23016
23017 /* Add a dependence relationship from CU to REF_PER_CU.  */
23018
23019 static void
23020 dwarf2_add_dependence (struct dwarf2_cu *cu,
23021                        struct dwarf2_per_cu_data *ref_per_cu)
23022 {
23023   void **slot;
23024
23025   if (cu->dependencies == NULL)
23026     cu->dependencies
23027       = htab_create_alloc_ex (5, htab_hash_pointer, htab_eq_pointer,
23028                               NULL, &cu->comp_unit_obstack,
23029                               hashtab_obstack_allocate,
23030                               dummy_obstack_deallocate);
23031
23032   slot = htab_find_slot (cu->dependencies, ref_per_cu, INSERT);
23033   if (*slot == NULL)
23034     *slot = ref_per_cu;
23035 }
23036
23037 /* Subroutine of dwarf2_mark to pass to htab_traverse.
23038    Set the mark field in every compilation unit in the
23039    cache that we must keep because we are keeping CU.  */
23040
23041 static int
23042 dwarf2_mark_helper (void **slot, void *data)
23043 {
23044   struct dwarf2_per_cu_data *per_cu;
23045
23046   per_cu = (struct dwarf2_per_cu_data *) *slot;
23047
23048   /* cu->dependencies references may not yet have been ever read if QUIT aborts
23049      reading of the chain.  As such dependencies remain valid it is not much
23050      useful to track and undo them during QUIT cleanups.  */
23051   if (per_cu->cu == NULL)
23052     return 1;
23053
23054   if (per_cu->cu->mark)
23055     return 1;
23056   per_cu->cu->mark = 1;
23057
23058   if (per_cu->cu->dependencies != NULL)
23059     htab_traverse (per_cu->cu->dependencies, dwarf2_mark_helper, NULL);
23060
23061   return 1;
23062 }
23063
23064 /* Set the mark field in CU and in every other compilation unit in the
23065    cache that we must keep because we are keeping CU.  */
23066
23067 static void
23068 dwarf2_mark (struct dwarf2_cu *cu)
23069 {
23070   if (cu->mark)
23071     return;
23072   cu->mark = 1;
23073   if (cu->dependencies != NULL)
23074     htab_traverse (cu->dependencies, dwarf2_mark_helper, NULL);
23075 }
23076
23077 static void
23078 dwarf2_clear_marks (struct dwarf2_per_cu_data *per_cu)
23079 {
23080   while (per_cu)
23081     {
23082       per_cu->cu->mark = 0;
23083       per_cu = per_cu->cu->read_in_chain;
23084     }
23085 }
23086
23087 /* Trivial hash function for partial_die_info: the hash value of a DIE
23088    is its offset in .debug_info for this objfile.  */
23089
23090 static hashval_t
23091 partial_die_hash (const void *item)
23092 {
23093   const struct partial_die_info *part_die
23094     = (const struct partial_die_info *) item;
23095
23096   return part_die->offset.sect_off;
23097 }
23098
23099 /* Trivial comparison function for partial_die_info structures: two DIEs
23100    are equal if they have the same offset.  */
23101
23102 static int
23103 partial_die_eq (const void *item_lhs, const void *item_rhs)
23104 {
23105   const struct partial_die_info *part_die_lhs
23106     = (const struct partial_die_info *) item_lhs;
23107   const struct partial_die_info *part_die_rhs
23108     = (const struct partial_die_info *) item_rhs;
23109
23110   return part_die_lhs->offset.sect_off == part_die_rhs->offset.sect_off;
23111 }
23112
23113 static struct cmd_list_element *set_dwarf_cmdlist;
23114 static struct cmd_list_element *show_dwarf_cmdlist;
23115
23116 static void
23117 set_dwarf_cmd (char *args, int from_tty)
23118 {
23119   help_list (set_dwarf_cmdlist, "maintenance set dwarf ", all_commands,
23120              gdb_stdout);
23121 }
23122
23123 static void
23124 show_dwarf_cmd (char *args, int from_tty)
23125 {
23126   cmd_show_list (show_dwarf_cmdlist, from_tty, "");
23127 }
23128
23129 /* Free data associated with OBJFILE, if necessary.  */
23130
23131 static void
23132 dwarf2_per_objfile_free (struct objfile *objfile, void *d)
23133 {
23134   struct dwarf2_per_objfile *data = (struct dwarf2_per_objfile *) d;
23135   int ix;
23136
23137   /* Make sure we don't accidentally use dwarf2_per_objfile while
23138      cleaning up.  */
23139   dwarf2_per_objfile = NULL;
23140
23141   for (ix = 0; ix < data->n_comp_units; ++ix)
23142    VEC_free (dwarf2_per_cu_ptr, data->all_comp_units[ix]->imported_symtabs);
23143
23144   for (ix = 0; ix < data->n_type_units; ++ix)
23145     VEC_free (dwarf2_per_cu_ptr,
23146               data->all_type_units[ix]->per_cu.imported_symtabs);
23147   xfree (data->all_type_units);
23148
23149   VEC_free (dwarf2_section_info_def, data->types);
23150
23151   if (data->dwo_files)
23152     free_dwo_files (data->dwo_files, objfile);
23153   if (data->dwp_file)
23154     gdb_bfd_unref (data->dwp_file->dbfd);
23155
23156   if (data->dwz_file && data->dwz_file->dwz_bfd)
23157     gdb_bfd_unref (data->dwz_file->dwz_bfd);
23158 }
23159
23160 \f
23161 /* The "save gdb-index" command.  */
23162
23163 /* The contents of the hash table we create when building the string
23164    table.  */
23165 struct strtab_entry
23166 {
23167   offset_type offset;
23168   const char *str;
23169 };
23170
23171 /* Hash function for a strtab_entry.
23172
23173    Function is used only during write_hash_table so no index format backward
23174    compatibility is needed.  */
23175
23176 static hashval_t
23177 hash_strtab_entry (const void *e)
23178 {
23179   const struct strtab_entry *entry = (const struct strtab_entry *) e;
23180   return mapped_index_string_hash (INT_MAX, entry->str);
23181 }
23182
23183 /* Equality function for a strtab_entry.  */
23184
23185 static int
23186 eq_strtab_entry (const void *a, const void *b)
23187 {
23188   const struct strtab_entry *ea = (const struct strtab_entry *) a;
23189   const struct strtab_entry *eb = (const struct strtab_entry *) b;
23190   return !strcmp (ea->str, eb->str);
23191 }
23192
23193 /* Create a strtab_entry hash table.  */
23194
23195 static htab_t
23196 create_strtab (void)
23197 {
23198   return htab_create_alloc (100, hash_strtab_entry, eq_strtab_entry,
23199                             xfree, xcalloc, xfree);
23200 }
23201
23202 /* Add a string to the constant pool.  Return the string's offset in
23203    host order.  */
23204
23205 static offset_type
23206 add_string (htab_t table, struct obstack *cpool, const char *str)
23207 {
23208   void **slot;
23209   struct strtab_entry entry;
23210   struct strtab_entry *result;
23211
23212   entry.str = str;
23213   slot = htab_find_slot (table, &entry, INSERT);
23214   if (*slot)
23215     result = (struct strtab_entry *) *slot;
23216   else
23217     {
23218       result = XNEW (struct strtab_entry);
23219       result->offset = obstack_object_size (cpool);
23220       result->str = str;
23221       obstack_grow_str0 (cpool, str);
23222       *slot = result;
23223     }
23224   return result->offset;
23225 }
23226
23227 /* An entry in the symbol table.  */
23228 struct symtab_index_entry
23229 {
23230   /* The name of the symbol.  */
23231   const char *name;
23232   /* The offset of the name in the constant pool.  */
23233   offset_type index_offset;
23234   /* A sorted vector of the indices of all the CUs that hold an object
23235      of this name.  */
23236   VEC (offset_type) *cu_indices;
23237 };
23238
23239 /* The symbol table.  This is a power-of-2-sized hash table.  */
23240 struct mapped_symtab
23241 {
23242   offset_type n_elements;
23243   offset_type size;
23244   struct symtab_index_entry **data;
23245 };
23246
23247 /* Hash function for a symtab_index_entry.  */
23248
23249 static hashval_t
23250 hash_symtab_entry (const void *e)
23251 {
23252   const struct symtab_index_entry *entry
23253     = (const struct symtab_index_entry *) e;
23254   return iterative_hash (VEC_address (offset_type, entry->cu_indices),
23255                          sizeof (offset_type) * VEC_length (offset_type,
23256                                                             entry->cu_indices),
23257                          0);
23258 }
23259
23260 /* Equality function for a symtab_index_entry.  */
23261
23262 static int
23263 eq_symtab_entry (const void *a, const void *b)
23264 {
23265   const struct symtab_index_entry *ea = (const struct symtab_index_entry *) a;
23266   const struct symtab_index_entry *eb = (const struct symtab_index_entry *) b;
23267   int len = VEC_length (offset_type, ea->cu_indices);
23268   if (len != VEC_length (offset_type, eb->cu_indices))
23269     return 0;
23270   return !memcmp (VEC_address (offset_type, ea->cu_indices),
23271                   VEC_address (offset_type, eb->cu_indices),
23272                   sizeof (offset_type) * len);
23273 }
23274
23275 /* Destroy a symtab_index_entry.  */
23276
23277 static void
23278 delete_symtab_entry (void *p)
23279 {
23280   struct symtab_index_entry *entry = (struct symtab_index_entry *) p;
23281   VEC_free (offset_type, entry->cu_indices);
23282   xfree (entry);
23283 }
23284
23285 /* Create a hash table holding symtab_index_entry objects.  */
23286
23287 static htab_t
23288 create_symbol_hash_table (void)
23289 {
23290   return htab_create_alloc (100, hash_symtab_entry, eq_symtab_entry,
23291                             delete_symtab_entry, xcalloc, xfree);
23292 }
23293
23294 /* Create a new mapped symtab object.  */
23295
23296 static struct mapped_symtab *
23297 create_mapped_symtab (void)
23298 {
23299   struct mapped_symtab *symtab = XNEW (struct mapped_symtab);
23300   symtab->n_elements = 0;
23301   symtab->size = 1024;
23302   symtab->data = XCNEWVEC (struct symtab_index_entry *, symtab->size);
23303   return symtab;
23304 }
23305
23306 /* Destroy a mapped_symtab.  */
23307
23308 static void
23309 cleanup_mapped_symtab (void *p)
23310 {
23311   struct mapped_symtab *symtab = (struct mapped_symtab *) p;
23312   /* The contents of the array are freed when the other hash table is
23313      destroyed.  */
23314   xfree (symtab->data);
23315   xfree (symtab);
23316 }
23317
23318 /* Find a slot in SYMTAB for the symbol NAME.  Returns a pointer to
23319    the slot.
23320    
23321    Function is used only during write_hash_table so no index format backward
23322    compatibility is needed.  */
23323
23324 static struct symtab_index_entry **
23325 find_slot (struct mapped_symtab *symtab, const char *name)
23326 {
23327   offset_type index, step, hash = mapped_index_string_hash (INT_MAX, name);
23328
23329   index = hash & (symtab->size - 1);
23330   step = ((hash * 17) & (symtab->size - 1)) | 1;
23331
23332   for (;;)
23333     {
23334       if (!symtab->data[index] || !strcmp (name, symtab->data[index]->name))
23335         return &symtab->data[index];
23336       index = (index + step) & (symtab->size - 1);
23337     }
23338 }
23339
23340 /* Expand SYMTAB's hash table.  */
23341
23342 static void
23343 hash_expand (struct mapped_symtab *symtab)
23344 {
23345   offset_type old_size = symtab->size;
23346   offset_type i;
23347   struct symtab_index_entry **old_entries = symtab->data;
23348
23349   symtab->size *= 2;
23350   symtab->data = XCNEWVEC (struct symtab_index_entry *, symtab->size);
23351
23352   for (i = 0; i < old_size; ++i)
23353     {
23354       if (old_entries[i])
23355         {
23356           struct symtab_index_entry **slot = find_slot (symtab,
23357                                                         old_entries[i]->name);
23358           *slot = old_entries[i];
23359         }
23360     }
23361
23362   xfree (old_entries);
23363 }
23364
23365 /* Add an entry to SYMTAB.  NAME is the name of the symbol.
23366    CU_INDEX is the index of the CU in which the symbol appears.
23367    IS_STATIC is one if the symbol is static, otherwise zero (global).  */
23368
23369 static void
23370 add_index_entry (struct mapped_symtab *symtab, const char *name,
23371                  int is_static, gdb_index_symbol_kind kind,
23372                  offset_type cu_index)
23373 {
23374   struct symtab_index_entry **slot;
23375   offset_type cu_index_and_attrs;
23376
23377   ++symtab->n_elements;
23378   if (4 * symtab->n_elements / 3 >= symtab->size)
23379     hash_expand (symtab);
23380
23381   slot = find_slot (symtab, name);
23382   if (!*slot)
23383     {
23384       *slot = XNEW (struct symtab_index_entry);
23385       (*slot)->name = name;
23386       /* index_offset is set later.  */
23387       (*slot)->cu_indices = NULL;
23388     }
23389
23390   cu_index_and_attrs = 0;
23391   DW2_GDB_INDEX_CU_SET_VALUE (cu_index_and_attrs, cu_index);
23392   DW2_GDB_INDEX_SYMBOL_STATIC_SET_VALUE (cu_index_and_attrs, is_static);
23393   DW2_GDB_INDEX_SYMBOL_KIND_SET_VALUE (cu_index_and_attrs, kind);
23394
23395   /* We don't want to record an index value twice as we want to avoid the
23396      duplication.
23397      We process all global symbols and then all static symbols
23398      (which would allow us to avoid the duplication by only having to check
23399      the last entry pushed), but a symbol could have multiple kinds in one CU.
23400      To keep things simple we don't worry about the duplication here and
23401      sort and uniqufy the list after we've processed all symbols.  */
23402   VEC_safe_push (offset_type, (*slot)->cu_indices, cu_index_and_attrs);
23403 }
23404
23405 /* qsort helper routine for uniquify_cu_indices.  */
23406
23407 static int
23408 offset_type_compare (const void *ap, const void *bp)
23409 {
23410   offset_type a = *(offset_type *) ap;
23411   offset_type b = *(offset_type *) bp;
23412
23413   return (a > b) - (b > a);
23414 }
23415
23416 /* Sort and remove duplicates of all symbols' cu_indices lists.  */
23417
23418 static void
23419 uniquify_cu_indices (struct mapped_symtab *symtab)
23420 {
23421   int i;
23422
23423   for (i = 0; i < symtab->size; ++i)
23424     {
23425       struct symtab_index_entry *entry = symtab->data[i];
23426
23427       if (entry
23428           && entry->cu_indices != NULL)
23429         {
23430           unsigned int next_to_insert, next_to_check;
23431           offset_type last_value;
23432
23433           qsort (VEC_address (offset_type, entry->cu_indices),
23434                  VEC_length (offset_type, entry->cu_indices),
23435                  sizeof (offset_type), offset_type_compare);
23436
23437           last_value = VEC_index (offset_type, entry->cu_indices, 0);
23438           next_to_insert = 1;
23439           for (next_to_check = 1;
23440                next_to_check < VEC_length (offset_type, entry->cu_indices);
23441                ++next_to_check)
23442             {
23443               if (VEC_index (offset_type, entry->cu_indices, next_to_check)
23444                   != last_value)
23445                 {
23446                   last_value = VEC_index (offset_type, entry->cu_indices,
23447                                           next_to_check);
23448                   VEC_replace (offset_type, entry->cu_indices, next_to_insert,
23449                                last_value);
23450                   ++next_to_insert;
23451                 }
23452             }
23453           VEC_truncate (offset_type, entry->cu_indices, next_to_insert);
23454         }
23455     }
23456 }
23457
23458 /* Add a vector of indices to the constant pool.  */
23459
23460 static offset_type
23461 add_indices_to_cpool (htab_t symbol_hash_table, struct obstack *cpool,
23462                       struct symtab_index_entry *entry)
23463 {
23464   void **slot;
23465
23466   slot = htab_find_slot (symbol_hash_table, entry, INSERT);
23467   if (!*slot)
23468     {
23469       offset_type len = VEC_length (offset_type, entry->cu_indices);
23470       offset_type val = MAYBE_SWAP (len);
23471       offset_type iter;
23472       int i;
23473
23474       *slot = entry;
23475       entry->index_offset = obstack_object_size (cpool);
23476
23477       obstack_grow (cpool, &val, sizeof (val));
23478       for (i = 0;
23479            VEC_iterate (offset_type, entry->cu_indices, i, iter);
23480            ++i)
23481         {
23482           val = MAYBE_SWAP (iter);
23483           obstack_grow (cpool, &val, sizeof (val));
23484         }
23485     }
23486   else
23487     {
23488       struct symtab_index_entry *old_entry
23489         = (struct symtab_index_entry *) *slot;
23490       entry->index_offset = old_entry->index_offset;
23491       entry = old_entry;
23492     }
23493   return entry->index_offset;
23494 }
23495
23496 /* Write the mapped hash table SYMTAB to the obstack OUTPUT, with
23497    constant pool entries going into the obstack CPOOL.  */
23498
23499 static void
23500 write_hash_table (struct mapped_symtab *symtab,
23501                   struct obstack *output, struct obstack *cpool)
23502 {
23503   offset_type i;
23504   htab_t symbol_hash_table;
23505   htab_t str_table;
23506
23507   symbol_hash_table = create_symbol_hash_table ();
23508   str_table = create_strtab ();
23509
23510   /* We add all the index vectors to the constant pool first, to
23511      ensure alignment is ok.  */
23512   for (i = 0; i < symtab->size; ++i)
23513     {
23514       if (symtab->data[i])
23515         add_indices_to_cpool (symbol_hash_table, cpool, symtab->data[i]);
23516     }
23517
23518   /* Now write out the hash table.  */
23519   for (i = 0; i < symtab->size; ++i)
23520     {
23521       offset_type str_off, vec_off;
23522
23523       if (symtab->data[i])
23524         {
23525           str_off = add_string (str_table, cpool, symtab->data[i]->name);
23526           vec_off = symtab->data[i]->index_offset;
23527         }
23528       else
23529         {
23530           /* While 0 is a valid constant pool index, it is not valid
23531              to have 0 for both offsets.  */
23532           str_off = 0;
23533           vec_off = 0;
23534         }
23535
23536       str_off = MAYBE_SWAP (str_off);
23537       vec_off = MAYBE_SWAP (vec_off);
23538
23539       obstack_grow (output, &str_off, sizeof (str_off));
23540       obstack_grow (output, &vec_off, sizeof (vec_off));
23541     }
23542
23543   htab_delete (str_table);
23544   htab_delete (symbol_hash_table);
23545 }
23546
23547 /* Struct to map psymtab to CU index in the index file.  */
23548 struct psymtab_cu_index_map
23549 {
23550   struct partial_symtab *psymtab;
23551   unsigned int cu_index;
23552 };
23553
23554 static hashval_t
23555 hash_psymtab_cu_index (const void *item)
23556 {
23557   const struct psymtab_cu_index_map *map
23558     = (const struct psymtab_cu_index_map *) item;
23559
23560   return htab_hash_pointer (map->psymtab);
23561 }
23562
23563 static int
23564 eq_psymtab_cu_index (const void *item_lhs, const void *item_rhs)
23565 {
23566   const struct psymtab_cu_index_map *lhs
23567     = (const struct psymtab_cu_index_map *) item_lhs;
23568   const struct psymtab_cu_index_map *rhs
23569     = (const struct psymtab_cu_index_map *) item_rhs;
23570
23571   return lhs->psymtab == rhs->psymtab;
23572 }
23573
23574 /* Helper struct for building the address table.  */
23575 struct addrmap_index_data
23576 {
23577   struct objfile *objfile;
23578   struct obstack *addr_obstack;
23579   htab_t cu_index_htab;
23580
23581   /* Non-zero if the previous_* fields are valid.
23582      We can't write an entry until we see the next entry (since it is only then
23583      that we know the end of the entry).  */
23584   int previous_valid;
23585   /* Index of the CU in the table of all CUs in the index file.  */
23586   unsigned int previous_cu_index;
23587   /* Start address of the CU.  */
23588   CORE_ADDR previous_cu_start;
23589 };
23590
23591 /* Write an address entry to OBSTACK.  */
23592
23593 static void
23594 add_address_entry (struct objfile *objfile, struct obstack *obstack,
23595                    CORE_ADDR start, CORE_ADDR end, unsigned int cu_index)
23596 {
23597   offset_type cu_index_to_write;
23598   gdb_byte addr[8];
23599   CORE_ADDR baseaddr;
23600
23601   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
23602
23603   store_unsigned_integer (addr, 8, BFD_ENDIAN_LITTLE, start - baseaddr);
23604   obstack_grow (obstack, addr, 8);
23605   store_unsigned_integer (addr, 8, BFD_ENDIAN_LITTLE, end - baseaddr);
23606   obstack_grow (obstack, addr, 8);
23607   cu_index_to_write = MAYBE_SWAP (cu_index);
23608   obstack_grow (obstack, &cu_index_to_write, sizeof (offset_type));
23609 }
23610
23611 /* Worker function for traversing an addrmap to build the address table.  */
23612
23613 static int
23614 add_address_entry_worker (void *datap, CORE_ADDR start_addr, void *obj)
23615 {
23616   struct addrmap_index_data *data = (struct addrmap_index_data *) datap;
23617   struct partial_symtab *pst = (struct partial_symtab *) obj;
23618
23619   if (data->previous_valid)
23620     add_address_entry (data->objfile, data->addr_obstack,
23621                        data->previous_cu_start, start_addr,
23622                        data->previous_cu_index);
23623
23624   data->previous_cu_start = start_addr;
23625   if (pst != NULL)
23626     {
23627       struct psymtab_cu_index_map find_map, *map;
23628       find_map.psymtab = pst;
23629       map = ((struct psymtab_cu_index_map *)
23630              htab_find (data->cu_index_htab, &find_map));
23631       gdb_assert (map != NULL);
23632       data->previous_cu_index = map->cu_index;
23633       data->previous_valid = 1;
23634     }
23635   else
23636       data->previous_valid = 0;
23637
23638   return 0;
23639 }
23640
23641 /* Write OBJFILE's address map to OBSTACK.
23642    CU_INDEX_HTAB is used to map addrmap entries to their CU indices
23643    in the index file.  */
23644
23645 static void
23646 write_address_map (struct objfile *objfile, struct obstack *obstack,
23647                    htab_t cu_index_htab)
23648 {
23649   struct addrmap_index_data addrmap_index_data;
23650
23651   /* When writing the address table, we have to cope with the fact that
23652      the addrmap iterator only provides the start of a region; we have to
23653      wait until the next invocation to get the start of the next region.  */
23654
23655   addrmap_index_data.objfile = objfile;
23656   addrmap_index_data.addr_obstack = obstack;
23657   addrmap_index_data.cu_index_htab = cu_index_htab;
23658   addrmap_index_data.previous_valid = 0;
23659
23660   addrmap_foreach (objfile->psymtabs_addrmap, add_address_entry_worker,
23661                    &addrmap_index_data);
23662
23663   /* It's highly unlikely the last entry (end address = 0xff...ff)
23664      is valid, but we should still handle it.
23665      The end address is recorded as the start of the next region, but that
23666      doesn't work here.  To cope we pass 0xff...ff, this is a rare situation
23667      anyway.  */
23668   if (addrmap_index_data.previous_valid)
23669     add_address_entry (objfile, obstack,
23670                        addrmap_index_data.previous_cu_start, (CORE_ADDR) -1,
23671                        addrmap_index_data.previous_cu_index);
23672 }
23673
23674 /* Return the symbol kind of PSYM.  */
23675
23676 static gdb_index_symbol_kind
23677 symbol_kind (struct partial_symbol *psym)
23678 {
23679   domain_enum domain = PSYMBOL_DOMAIN (psym);
23680   enum address_class aclass = PSYMBOL_CLASS (psym);
23681
23682   switch (domain)
23683     {
23684     case VAR_DOMAIN:
23685       switch (aclass)
23686         {
23687         case LOC_BLOCK:
23688           return GDB_INDEX_SYMBOL_KIND_FUNCTION;
23689         case LOC_TYPEDEF:
23690           return GDB_INDEX_SYMBOL_KIND_TYPE;
23691         case LOC_COMPUTED:
23692         case LOC_CONST_BYTES:
23693         case LOC_OPTIMIZED_OUT:
23694         case LOC_STATIC:
23695           return GDB_INDEX_SYMBOL_KIND_VARIABLE;
23696         case LOC_CONST:
23697           /* Note: It's currently impossible to recognize psyms as enum values
23698              short of reading the type info.  For now punt.  */
23699           return GDB_INDEX_SYMBOL_KIND_VARIABLE;
23700         default:
23701           /* There are other LOC_FOO values that one might want to classify
23702              as variables, but dwarf2read.c doesn't currently use them.  */
23703           return GDB_INDEX_SYMBOL_KIND_OTHER;
23704         }
23705     case STRUCT_DOMAIN:
23706       return GDB_INDEX_SYMBOL_KIND_TYPE;
23707     default:
23708       return GDB_INDEX_SYMBOL_KIND_OTHER;
23709     }
23710 }
23711
23712 /* Add a list of partial symbols to SYMTAB.  */
23713
23714 static void
23715 write_psymbols (struct mapped_symtab *symtab,
23716                 htab_t psyms_seen,
23717                 struct partial_symbol **psymp,
23718                 int count,
23719                 offset_type cu_index,
23720                 int is_static)
23721 {
23722   for (; count-- > 0; ++psymp)
23723     {
23724       struct partial_symbol *psym = *psymp;
23725       void **slot;
23726
23727       if (SYMBOL_LANGUAGE (psym) == language_ada)
23728         error (_("Ada is not currently supported by the index"));
23729
23730       /* Only add a given psymbol once.  */
23731       slot = htab_find_slot (psyms_seen, psym, INSERT);
23732       if (!*slot)
23733         {
23734           gdb_index_symbol_kind kind = symbol_kind (psym);
23735
23736           *slot = psym;
23737           add_index_entry (symtab, SYMBOL_SEARCH_NAME (psym),
23738                            is_static, kind, cu_index);
23739         }
23740     }
23741 }
23742
23743 /* Write the contents of an ("unfinished") obstack to FILE.  Throw an
23744    exception if there is an error.  */
23745
23746 static void
23747 write_obstack (FILE *file, struct obstack *obstack)
23748 {
23749   if (fwrite (obstack_base (obstack), 1, obstack_object_size (obstack),
23750               file)
23751       != obstack_object_size (obstack))
23752     error (_("couldn't data write to file"));
23753 }
23754
23755 /* A helper struct used when iterating over debug_types.  */
23756 struct signatured_type_index_data
23757 {
23758   struct objfile *objfile;
23759   struct mapped_symtab *symtab;
23760   struct obstack *types_list;
23761   htab_t psyms_seen;
23762   int cu_index;
23763 };
23764
23765 /* A helper function that writes a single signatured_type to an
23766    obstack.  */
23767
23768 static int
23769 write_one_signatured_type (void **slot, void *d)
23770 {
23771   struct signatured_type_index_data *info
23772     = (struct signatured_type_index_data *) d;
23773   struct signatured_type *entry = (struct signatured_type *) *slot;
23774   struct partial_symtab *psymtab = entry->per_cu.v.psymtab;
23775   gdb_byte val[8];
23776
23777   write_psymbols (info->symtab,
23778                   info->psyms_seen,
23779                   info->objfile->global_psymbols.list
23780                   + psymtab->globals_offset,
23781                   psymtab->n_global_syms, info->cu_index,
23782                   0);
23783   write_psymbols (info->symtab,
23784                   info->psyms_seen,
23785                   info->objfile->static_psymbols.list
23786                   + psymtab->statics_offset,
23787                   psymtab->n_static_syms, info->cu_index,
23788                   1);
23789
23790   store_unsigned_integer (val, 8, BFD_ENDIAN_LITTLE,
23791                           entry->per_cu.offset.sect_off);
23792   obstack_grow (info->types_list, val, 8);
23793   store_unsigned_integer (val, 8, BFD_ENDIAN_LITTLE,
23794                           entry->type_offset_in_tu.cu_off);
23795   obstack_grow (info->types_list, val, 8);
23796   store_unsigned_integer (val, 8, BFD_ENDIAN_LITTLE, entry->signature);
23797   obstack_grow (info->types_list, val, 8);
23798
23799   ++info->cu_index;
23800
23801   return 1;
23802 }
23803
23804 /* Recurse into all "included" dependencies and write their symbols as
23805    if they appeared in this psymtab.  */
23806
23807 static void
23808 recursively_write_psymbols (struct objfile *objfile,
23809                             struct partial_symtab *psymtab,
23810                             struct mapped_symtab *symtab,
23811                             htab_t psyms_seen,
23812                             offset_type cu_index)
23813 {
23814   int i;
23815
23816   for (i = 0; i < psymtab->number_of_dependencies; ++i)
23817     if (psymtab->dependencies[i]->user != NULL)
23818       recursively_write_psymbols (objfile, psymtab->dependencies[i],
23819                                   symtab, psyms_seen, cu_index);
23820
23821   write_psymbols (symtab,
23822                   psyms_seen,
23823                   objfile->global_psymbols.list + psymtab->globals_offset,
23824                   psymtab->n_global_syms, cu_index,
23825                   0);
23826   write_psymbols (symtab,
23827                   psyms_seen,
23828                   objfile->static_psymbols.list + psymtab->statics_offset,
23829                   psymtab->n_static_syms, cu_index,
23830                   1);
23831 }
23832
23833 /* Create an index file for OBJFILE in the directory DIR.  */
23834
23835 static void
23836 write_psymtabs_to_index (struct objfile *objfile, const char *dir)
23837 {
23838   struct cleanup *cleanup;
23839   char *filename;
23840   struct obstack contents, addr_obstack, constant_pool, symtab_obstack;
23841   struct obstack cu_list, types_cu_list;
23842   int i;
23843   FILE *out_file;
23844   struct mapped_symtab *symtab;
23845   offset_type val, size_of_contents, total_len;
23846   struct stat st;
23847   struct psymtab_cu_index_map *psymtab_cu_index_map;
23848
23849   if (dwarf2_per_objfile->using_index)
23850     error (_("Cannot use an index to create the index"));
23851
23852   if (VEC_length (dwarf2_section_info_def, dwarf2_per_objfile->types) > 1)
23853     error (_("Cannot make an index when the file has multiple .debug_types sections"));
23854
23855   if (!objfile->psymtabs || !objfile->psymtabs_addrmap)
23856     return;
23857
23858   if (stat (objfile_name (objfile), &st) < 0)
23859     perror_with_name (objfile_name (objfile));
23860
23861   filename = concat (dir, SLASH_STRING, lbasename (objfile_name (objfile)),
23862                      INDEX_SUFFIX, (char *) NULL);
23863   cleanup = make_cleanup (xfree, filename);
23864
23865   out_file = gdb_fopen_cloexec (filename, "wb");
23866   if (!out_file)
23867     error (_("Can't open `%s' for writing"), filename);
23868
23869   gdb::unlinker unlink_file (filename);
23870
23871   symtab = create_mapped_symtab ();
23872   make_cleanup (cleanup_mapped_symtab, symtab);
23873
23874   obstack_init (&addr_obstack);
23875   make_cleanup_obstack_free (&addr_obstack);
23876
23877   obstack_init (&cu_list);
23878   make_cleanup_obstack_free (&cu_list);
23879
23880   obstack_init (&types_cu_list);
23881   make_cleanup_obstack_free (&types_cu_list);
23882
23883   htab_up psyms_seen (htab_create_alloc (100, htab_hash_pointer,
23884                                          htab_eq_pointer,
23885                                          NULL, xcalloc, xfree));
23886
23887   /* While we're scanning CU's create a table that maps a psymtab pointer
23888      (which is what addrmap records) to its index (which is what is recorded
23889      in the index file).  This will later be needed to write the address
23890      table.  */
23891   htab_up cu_index_htab (htab_create_alloc (100,
23892                                             hash_psymtab_cu_index,
23893                                             eq_psymtab_cu_index,
23894                                             NULL, xcalloc, xfree));
23895   psymtab_cu_index_map = XNEWVEC (struct psymtab_cu_index_map,
23896                                   dwarf2_per_objfile->n_comp_units);
23897   make_cleanup (xfree, psymtab_cu_index_map);
23898
23899   /* The CU list is already sorted, so we don't need to do additional
23900      work here.  Also, the debug_types entries do not appear in
23901      all_comp_units, but only in their own hash table.  */
23902   for (i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
23903     {
23904       struct dwarf2_per_cu_data *per_cu
23905         = dwarf2_per_objfile->all_comp_units[i];
23906       struct partial_symtab *psymtab = per_cu->v.psymtab;
23907       gdb_byte val[8];
23908       struct psymtab_cu_index_map *map;
23909       void **slot;
23910
23911       /* CU of a shared file from 'dwz -m' may be unused by this main file.
23912          It may be referenced from a local scope but in such case it does not
23913          need to be present in .gdb_index.  */
23914       if (psymtab == NULL)
23915         continue;
23916
23917       if (psymtab->user == NULL)
23918         recursively_write_psymbols (objfile, psymtab, symtab,
23919                                     psyms_seen.get (), i);
23920
23921       map = &psymtab_cu_index_map[i];
23922       map->psymtab = psymtab;
23923       map->cu_index = i;
23924       slot = htab_find_slot (cu_index_htab.get (), map, INSERT);
23925       gdb_assert (slot != NULL);
23926       gdb_assert (*slot == NULL);
23927       *slot = map;
23928
23929       store_unsigned_integer (val, 8, BFD_ENDIAN_LITTLE,
23930                               per_cu->offset.sect_off);
23931       obstack_grow (&cu_list, val, 8);
23932       store_unsigned_integer (val, 8, BFD_ENDIAN_LITTLE, per_cu->length);
23933       obstack_grow (&cu_list, val, 8);
23934     }
23935
23936   /* Dump the address map.  */
23937   write_address_map (objfile, &addr_obstack, cu_index_htab.get ());
23938
23939   /* Write out the .debug_type entries, if any.  */
23940   if (dwarf2_per_objfile->signatured_types)
23941     {
23942       struct signatured_type_index_data sig_data;
23943
23944       sig_data.objfile = objfile;
23945       sig_data.symtab = symtab;
23946       sig_data.types_list = &types_cu_list;
23947       sig_data.psyms_seen = psyms_seen.get ();
23948       sig_data.cu_index = dwarf2_per_objfile->n_comp_units;
23949       htab_traverse_noresize (dwarf2_per_objfile->signatured_types,
23950                               write_one_signatured_type, &sig_data);
23951     }
23952
23953   /* Now that we've processed all symbols we can shrink their cu_indices
23954      lists.  */
23955   uniquify_cu_indices (symtab);
23956
23957   obstack_init (&constant_pool);
23958   make_cleanup_obstack_free (&constant_pool);
23959   obstack_init (&symtab_obstack);
23960   make_cleanup_obstack_free (&symtab_obstack);
23961   write_hash_table (symtab, &symtab_obstack, &constant_pool);
23962
23963   obstack_init (&contents);
23964   make_cleanup_obstack_free (&contents);
23965   size_of_contents = 6 * sizeof (offset_type);
23966   total_len = size_of_contents;
23967
23968   /* The version number.  */
23969   val = MAYBE_SWAP (8);
23970   obstack_grow (&contents, &val, sizeof (val));
23971
23972   /* The offset of the CU list from the start of the file.  */
23973   val = MAYBE_SWAP (total_len);
23974   obstack_grow (&contents, &val, sizeof (val));
23975   total_len += obstack_object_size (&cu_list);
23976
23977   /* The offset of the types CU list from the start of the file.  */
23978   val = MAYBE_SWAP (total_len);
23979   obstack_grow (&contents, &val, sizeof (val));
23980   total_len += obstack_object_size (&types_cu_list);
23981
23982   /* The offset of the address table from the start of the file.  */
23983   val = MAYBE_SWAP (total_len);
23984   obstack_grow (&contents, &val, sizeof (val));
23985   total_len += obstack_object_size (&addr_obstack);
23986
23987   /* The offset of the symbol table from the start of the file.  */
23988   val = MAYBE_SWAP (total_len);
23989   obstack_grow (&contents, &val, sizeof (val));
23990   total_len += obstack_object_size (&symtab_obstack);
23991
23992   /* The offset of the constant pool from the start of the file.  */
23993   val = MAYBE_SWAP (total_len);
23994   obstack_grow (&contents, &val, sizeof (val));
23995   total_len += obstack_object_size (&constant_pool);
23996
23997   gdb_assert (obstack_object_size (&contents) == size_of_contents);
23998
23999   write_obstack (out_file, &contents);
24000   write_obstack (out_file, &cu_list);
24001   write_obstack (out_file, &types_cu_list);
24002   write_obstack (out_file, &addr_obstack);
24003   write_obstack (out_file, &symtab_obstack);
24004   write_obstack (out_file, &constant_pool);
24005
24006   fclose (out_file);
24007
24008   /* We want to keep the file.  */
24009   unlink_file.keep ();
24010
24011   do_cleanups (cleanup);
24012 }
24013
24014 /* Implementation of the `save gdb-index' command.
24015    
24016    Note that the file format used by this command is documented in the
24017    GDB manual.  Any changes here must be documented there.  */
24018
24019 static void
24020 save_gdb_index_command (char *arg, int from_tty)
24021 {
24022   struct objfile *objfile;
24023
24024   if (!arg || !*arg)
24025     error (_("usage: save gdb-index DIRECTORY"));
24026
24027   ALL_OBJFILES (objfile)
24028   {
24029     struct stat st;
24030
24031     /* If the objfile does not correspond to an actual file, skip it.  */
24032     if (stat (objfile_name (objfile), &st) < 0)
24033       continue;
24034
24035     dwarf2_per_objfile
24036       = (struct dwarf2_per_objfile *) objfile_data (objfile,
24037                                                     dwarf2_objfile_data_key);
24038     if (dwarf2_per_objfile)
24039       {
24040
24041         TRY
24042           {
24043             write_psymtabs_to_index (objfile, arg);
24044           }
24045         CATCH (except, RETURN_MASK_ERROR)
24046           {
24047             exception_fprintf (gdb_stderr, except,
24048                                _("Error while writing index for `%s': "),
24049                                objfile_name (objfile));
24050           }
24051         END_CATCH
24052       }
24053   }
24054 }
24055
24056 \f
24057
24058 int dwarf_always_disassemble;
24059
24060 static void
24061 show_dwarf_always_disassemble (struct ui_file *file, int from_tty,
24062                                struct cmd_list_element *c, const char *value)
24063 {
24064   fprintf_filtered (file,
24065                     _("Whether to always disassemble "
24066                       "DWARF expressions is %s.\n"),
24067                     value);
24068 }
24069
24070 static void
24071 show_check_physname (struct ui_file *file, int from_tty,
24072                      struct cmd_list_element *c, const char *value)
24073 {
24074   fprintf_filtered (file,
24075                     _("Whether to check \"physname\" is %s.\n"),
24076                     value);
24077 }
24078
24079 void _initialize_dwarf2_read (void);
24080
24081 void
24082 _initialize_dwarf2_read (void)
24083 {
24084   struct cmd_list_element *c;
24085
24086   dwarf2_objfile_data_key
24087     = register_objfile_data_with_cleanup (NULL, dwarf2_per_objfile_free);
24088
24089   add_prefix_cmd ("dwarf", class_maintenance, set_dwarf_cmd, _("\
24090 Set DWARF specific variables.\n\
24091 Configure DWARF variables such as the cache size"),
24092                   &set_dwarf_cmdlist, "maintenance set dwarf ",
24093                   0/*allow-unknown*/, &maintenance_set_cmdlist);
24094
24095   add_prefix_cmd ("dwarf", class_maintenance, show_dwarf_cmd, _("\
24096 Show DWARF specific variables\n\
24097 Show DWARF variables such as the cache size"),
24098                   &show_dwarf_cmdlist, "maintenance show dwarf ",
24099                   0/*allow-unknown*/, &maintenance_show_cmdlist);
24100
24101   add_setshow_zinteger_cmd ("max-cache-age", class_obscure,
24102                             &dwarf_max_cache_age, _("\
24103 Set the upper bound on the age of cached DWARF compilation units."), _("\
24104 Show the upper bound on the age of cached DWARF compilation units."), _("\
24105 A higher limit means that cached compilation units will be stored\n\
24106 in memory longer, and more total memory will be used.  Zero disables\n\
24107 caching, which can slow down startup."),
24108                             NULL,
24109                             show_dwarf_max_cache_age,
24110                             &set_dwarf_cmdlist,
24111                             &show_dwarf_cmdlist);
24112
24113   add_setshow_boolean_cmd ("always-disassemble", class_obscure,
24114                            &dwarf_always_disassemble, _("\
24115 Set whether `info address' always disassembles DWARF expressions."), _("\
24116 Show whether `info address' always disassembles DWARF expressions."), _("\
24117 When enabled, DWARF expressions are always printed in an assembly-like\n\
24118 syntax.  When disabled, expressions will be printed in a more\n\
24119 conversational style, when possible."),
24120                            NULL,
24121                            show_dwarf_always_disassemble,
24122                            &set_dwarf_cmdlist,
24123                            &show_dwarf_cmdlist);
24124
24125   add_setshow_zuinteger_cmd ("dwarf-read", no_class, &dwarf_read_debug, _("\
24126 Set debugging of the DWARF reader."), _("\
24127 Show debugging of the DWARF reader."), _("\
24128 When enabled (non-zero), debugging messages are printed during DWARF\n\
24129 reading and symtab expansion.  A value of 1 (one) provides basic\n\
24130 information.  A value greater than 1 provides more verbose information."),
24131                             NULL,
24132                             NULL,
24133                             &setdebuglist, &showdebuglist);
24134
24135   add_setshow_zuinteger_cmd ("dwarf-die", no_class, &dwarf_die_debug, _("\
24136 Set debugging of the DWARF DIE reader."), _("\
24137 Show debugging of the DWARF DIE reader."), _("\
24138 When enabled (non-zero), DIEs are dumped after they are read in.\n\
24139 The value is the maximum depth to print."),
24140                              NULL,
24141                              NULL,
24142                              &setdebuglist, &showdebuglist);
24143
24144   add_setshow_zuinteger_cmd ("dwarf-line", no_class, &dwarf_line_debug, _("\
24145 Set debugging of the dwarf line reader."), _("\
24146 Show debugging of the dwarf line reader."), _("\
24147 When enabled (non-zero), line number entries are dumped as they are read in.\n\
24148 A value of 1 (one) provides basic information.\n\
24149 A value greater than 1 provides more verbose information."),
24150                              NULL,
24151                              NULL,
24152                              &setdebuglist, &showdebuglist);
24153
24154   add_setshow_boolean_cmd ("check-physname", no_class, &check_physname, _("\
24155 Set cross-checking of \"physname\" code against demangler."), _("\
24156 Show cross-checking of \"physname\" code against demangler."), _("\
24157 When enabled, GDB's internal \"physname\" code is checked against\n\
24158 the demangler."),
24159                            NULL, show_check_physname,
24160                            &setdebuglist, &showdebuglist);
24161
24162   add_setshow_boolean_cmd ("use-deprecated-index-sections",
24163                            no_class, &use_deprecated_index_sections, _("\
24164 Set whether to use deprecated gdb_index sections."), _("\
24165 Show whether to use deprecated gdb_index sections."), _("\
24166 When enabled, deprecated .gdb_index sections are used anyway.\n\
24167 Normally they are ignored either because of a missing feature or\n\
24168 performance issue.\n\
24169 Warning: This option must be enabled before gdb reads the file."),
24170                            NULL,
24171                            NULL,
24172                            &setlist, &showlist);
24173
24174   c = add_cmd ("gdb-index", class_files, save_gdb_index_command,
24175                _("\
24176 Save a gdb-index file.\n\
24177 Usage: save gdb-index DIRECTORY"),
24178                &save_cmdlist);
24179   set_cmd_completer (c, filename_completer);
24180
24181   dwarf2_locexpr_index = register_symbol_computed_impl (LOC_COMPUTED,
24182                                                         &dwarf2_locexpr_funcs);
24183   dwarf2_loclist_index = register_symbol_computed_impl (LOC_COMPUTED,
24184                                                         &dwarf2_loclist_funcs);
24185
24186   dwarf2_locexpr_block_index = register_symbol_block_impl (LOC_BLOCK,
24187                                         &dwarf2_block_frame_base_locexpr_funcs);
24188   dwarf2_loclist_block_index = register_symbol_block_impl (LOC_BLOCK,
24189                                         &dwarf2_block_frame_base_loclist_funcs);
24190 }