* symfile.h (struct quick_symbol_functions): Reorg arg list of
[external/binutils.git] / gdb / dwarf2read.c
1 /* DWARF 2 debugging format support for GDB.
2
3    Copyright (C) 1994-2013 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 "jv-lang.h"
57 #include "psympriv.h"
58 #include "exceptions.h"
59 #include "gdb_stat.h"
60 #include "completer.h"
61 #include "vec.h"
62 #include "c-lang.h"
63 #include "go-lang.h"
64 #include "valprint.h"
65 #include "gdbcore.h" /* for gnutarget */
66 #include "gdb/gdb-index.h"
67 #include <ctype.h>
68 #include "gdb_bfd.h"
69 #include "f-lang.h"
70 #include "source.h"
71 #include "filestuff.h"
72
73 #include <fcntl.h>
74 #include "gdb_string.h"
75 #include "gdb_assert.h"
76 #include <sys/types.h>
77
78 typedef struct symbol *symbolp;
79 DEF_VEC_P (symbolp);
80
81 /* When non-zero, print basic high level tracing messages.
82    This is in contrast to the low level DIE reading of dwarf2_die_debug.  */
83 static int dwarf2_read_debug = 0;
84
85 /* When non-zero, dump DIEs after they are read in.  */
86 static unsigned int dwarf2_die_debug = 0;
87
88 /* When non-zero, cross-check physname against demangler.  */
89 static int check_physname = 0;
90
91 /* When non-zero, do not reject deprecated .gdb_index sections.  */
92 static int use_deprecated_index_sections = 0;
93
94 static const struct objfile_data *dwarf2_objfile_data_key;
95
96 /* The "aclass" indices for various kinds of computed DWARF symbols.  */
97
98 static int dwarf2_locexpr_index;
99 static int dwarf2_loclist_index;
100 static int dwarf2_locexpr_block_index;
101 static int dwarf2_loclist_block_index;
102
103 struct dwarf2_section_info
104 {
105   asection *asection;
106   const gdb_byte *buffer;
107   bfd_size_type size;
108   /* True if we have tried to read this section.  */
109   int readin;
110 };
111
112 typedef struct dwarf2_section_info dwarf2_section_info_def;
113 DEF_VEC_O (dwarf2_section_info_def);
114
115 /* All offsets in the index are of this type.  It must be
116    architecture-independent.  */
117 typedef uint32_t offset_type;
118
119 DEF_VEC_I (offset_type);
120
121 /* Ensure only legit values are used.  */
122 #define DW2_GDB_INDEX_SYMBOL_STATIC_SET_VALUE(cu_index, value) \
123   do { \
124     gdb_assert ((unsigned int) (value) <= 1); \
125     GDB_INDEX_SYMBOL_STATIC_SET_VALUE((cu_index), (value)); \
126   } while (0)
127
128 /* Ensure only legit values are used.  */
129 #define DW2_GDB_INDEX_SYMBOL_KIND_SET_VALUE(cu_index, value) \
130   do { \
131     gdb_assert ((value) >= GDB_INDEX_SYMBOL_KIND_TYPE \
132                 && (value) <= GDB_INDEX_SYMBOL_KIND_OTHER); \
133     GDB_INDEX_SYMBOL_KIND_SET_VALUE((cu_index), (value)); \
134   } while (0)
135
136 /* Ensure we don't use more than the alloted nuber of bits for the CU.  */
137 #define DW2_GDB_INDEX_CU_SET_VALUE(cu_index, value) \
138   do { \
139     gdb_assert (((value) & ~GDB_INDEX_CU_MASK) == 0); \
140     GDB_INDEX_CU_SET_VALUE((cu_index), (value)); \
141   } while (0)
142
143 /* A description of the mapped index.  The file format is described in
144    a comment by the code that writes the index.  */
145 struct mapped_index
146 {
147   /* Index data format version.  */
148   int version;
149
150   /* The total length of the buffer.  */
151   off_t total_size;
152
153   /* A pointer to the address table data.  */
154   const gdb_byte *address_table;
155
156   /* Size of the address table data in bytes.  */
157   offset_type address_table_size;
158
159   /* The symbol table, implemented as a hash table.  */
160   const offset_type *symbol_table;
161
162   /* Size in slots, each slot is 2 offset_types.  */
163   offset_type symbol_table_slots;
164
165   /* A pointer to the constant pool.  */
166   const char *constant_pool;
167 };
168
169 typedef struct dwarf2_per_cu_data *dwarf2_per_cu_ptr;
170 DEF_VEC_P (dwarf2_per_cu_ptr);
171
172 /* Collection of data recorded per objfile.
173    This hangs off of dwarf2_objfile_data_key.  */
174
175 struct dwarf2_per_objfile
176 {
177   struct dwarf2_section_info info;
178   struct dwarf2_section_info abbrev;
179   struct dwarf2_section_info line;
180   struct dwarf2_section_info loc;
181   struct dwarf2_section_info macinfo;
182   struct dwarf2_section_info macro;
183   struct dwarf2_section_info str;
184   struct dwarf2_section_info ranges;
185   struct dwarf2_section_info addr;
186   struct dwarf2_section_info frame;
187   struct dwarf2_section_info eh_frame;
188   struct dwarf2_section_info gdb_index;
189
190   VEC (dwarf2_section_info_def) *types;
191
192   /* Back link.  */
193   struct objfile *objfile;
194
195   /* Table of all the compilation units.  This is used to locate
196      the target compilation unit of a particular reference.  */
197   struct dwarf2_per_cu_data **all_comp_units;
198
199   /* The number of compilation units in ALL_COMP_UNITS.  */
200   int n_comp_units;
201
202   /* The number of .debug_types-related CUs.  */
203   int n_type_units;
204
205   /* The .debug_types-related CUs (TUs).
206      This is stored in malloc space because we may realloc it.  */
207   struct signatured_type **all_type_units;
208
209   /* The number of entries in all_type_unit_groups.  */
210   int n_type_unit_groups;
211
212   /* Table of type unit groups.
213      This exists to make it easy to iterate over all CUs and TU groups.  */
214   struct type_unit_group **all_type_unit_groups;
215
216   /* Table of struct type_unit_group objects.
217      The hash key is the DW_AT_stmt_list value.  */
218   htab_t type_unit_groups;
219
220   /* A table mapping .debug_types signatures to its signatured_type entry.
221      This is NULL if the .debug_types section hasn't been read in yet.  */
222   htab_t signatured_types;
223
224   /* Type unit statistics, to see how well the scaling improvements
225      are doing.  */
226   struct tu_stats
227   {
228     int nr_uniq_abbrev_tables;
229     int nr_symtabs;
230     int nr_symtab_sharers;
231     int nr_stmt_less_type_units;
232   } tu_stats;
233
234   /* A chain of compilation units that are currently read in, so that
235      they can be freed later.  */
236   struct dwarf2_per_cu_data *read_in_chain;
237
238   /* A table mapping DW_AT_dwo_name values to struct dwo_file objects.
239      This is NULL if the table hasn't been allocated yet.  */
240   htab_t dwo_files;
241
242   /* Non-zero if we've check for whether there is a DWP file.  */
243   int dwp_checked;
244
245   /* The DWP file if there is one, or NULL.  */
246   struct dwp_file *dwp_file;
247
248   /* The shared '.dwz' file, if one exists.  This is used when the
249      original data was compressed using 'dwz -m'.  */
250   struct dwz_file *dwz_file;
251
252   /* A flag indicating wether this objfile has a section loaded at a
253      VMA of 0.  */
254   int has_section_at_zero;
255
256   /* True if we are using the mapped index,
257      or we are faking it for OBJF_READNOW's sake.  */
258   unsigned char using_index;
259
260   /* The mapped index, or NULL if .gdb_index is missing or not being used.  */
261   struct mapped_index *index_table;
262
263   /* When using index_table, this keeps track of all quick_file_names entries.
264      TUs typically share line table entries with a CU, so we maintain a
265      separate table of all line table entries to support the sharing.
266      Note that while there can be way more TUs than CUs, we've already
267      sorted all the TUs into "type unit groups", grouped by their
268      DW_AT_stmt_list value.  Therefore the only sharing done here is with a
269      CU and its associated TU group if there is one.  */
270   htab_t quick_file_names_table;
271
272   /* Set during partial symbol reading, to prevent queueing of full
273      symbols.  */
274   int reading_partial_symbols;
275
276   /* Table mapping type DIEs to their struct type *.
277      This is NULL if not allocated yet.
278      The mapping is done via (CU/TU + DIE offset) -> type.  */
279   htab_t die_type_hash;
280
281   /* The CUs we recently read.  */
282   VEC (dwarf2_per_cu_ptr) *just_read_cus;
283 };
284
285 static struct dwarf2_per_objfile *dwarf2_per_objfile;
286
287 /* Default names of the debugging sections.  */
288
289 /* Note that if the debugging section has been compressed, it might
290    have a name like .zdebug_info.  */
291
292 static const struct dwarf2_debug_sections dwarf2_elf_names =
293 {
294   { ".debug_info", ".zdebug_info" },
295   { ".debug_abbrev", ".zdebug_abbrev" },
296   { ".debug_line", ".zdebug_line" },
297   { ".debug_loc", ".zdebug_loc" },
298   { ".debug_macinfo", ".zdebug_macinfo" },
299   { ".debug_macro", ".zdebug_macro" },
300   { ".debug_str", ".zdebug_str" },
301   { ".debug_ranges", ".zdebug_ranges" },
302   { ".debug_types", ".zdebug_types" },
303   { ".debug_addr", ".zdebug_addr" },
304   { ".debug_frame", ".zdebug_frame" },
305   { ".eh_frame", NULL },
306   { ".gdb_index", ".zgdb_index" },
307   23
308 };
309
310 /* List of DWO/DWP sections.  */
311
312 static const struct dwop_section_names
313 {
314   struct dwarf2_section_names abbrev_dwo;
315   struct dwarf2_section_names info_dwo;
316   struct dwarf2_section_names line_dwo;
317   struct dwarf2_section_names loc_dwo;
318   struct dwarf2_section_names macinfo_dwo;
319   struct dwarf2_section_names macro_dwo;
320   struct dwarf2_section_names str_dwo;
321   struct dwarf2_section_names str_offsets_dwo;
322   struct dwarf2_section_names types_dwo;
323   struct dwarf2_section_names cu_index;
324   struct dwarf2_section_names tu_index;
325 }
326 dwop_section_names =
327 {
328   { ".debug_abbrev.dwo", ".zdebug_abbrev.dwo" },
329   { ".debug_info.dwo", ".zdebug_info.dwo" },
330   { ".debug_line.dwo", ".zdebug_line.dwo" },
331   { ".debug_loc.dwo", ".zdebug_loc.dwo" },
332   { ".debug_macinfo.dwo", ".zdebug_macinfo.dwo" },
333   { ".debug_macro.dwo", ".zdebug_macro.dwo" },
334   { ".debug_str.dwo", ".zdebug_str.dwo" },
335   { ".debug_str_offsets.dwo", ".zdebug_str_offsets.dwo" },
336   { ".debug_types.dwo", ".zdebug_types.dwo" },
337   { ".debug_cu_index", ".zdebug_cu_index" },
338   { ".debug_tu_index", ".zdebug_tu_index" },
339 };
340
341 /* local data types */
342
343 /* The data in a compilation unit header, after target2host
344    translation, looks like this.  */
345 struct comp_unit_head
346 {
347   unsigned int length;
348   short version;
349   unsigned char addr_size;
350   unsigned char signed_addr_p;
351   sect_offset abbrev_offset;
352
353   /* Size of file offsets; either 4 or 8.  */
354   unsigned int offset_size;
355
356   /* Size of the length field; either 4 or 12.  */
357   unsigned int initial_length_size;
358
359   /* Offset to the first byte of this compilation unit header in the
360      .debug_info section, for resolving relative reference dies.  */
361   sect_offset offset;
362
363   /* Offset to first die in this cu from the start of the cu.
364      This will be the first byte following the compilation unit header.  */
365   cu_offset first_die_offset;
366 };
367
368 /* Type used for delaying computation of method physnames.
369    See comments for compute_delayed_physnames.  */
370 struct delayed_method_info
371 {
372   /* The type to which the method is attached, i.e., its parent class.  */
373   struct type *type;
374
375   /* The index of the method in the type's function fieldlists.  */
376   int fnfield_index;
377
378   /* The index of the method in the fieldlist.  */
379   int index;
380
381   /* The name of the DIE.  */
382   const char *name;
383
384   /*  The DIE associated with this method.  */
385   struct die_info *die;
386 };
387
388 typedef struct delayed_method_info delayed_method_info;
389 DEF_VEC_O (delayed_method_info);
390
391 /* Internal state when decoding a particular compilation unit.  */
392 struct dwarf2_cu
393 {
394   /* The objfile containing this compilation unit.  */
395   struct objfile *objfile;
396
397   /* The header of the compilation unit.  */
398   struct comp_unit_head header;
399
400   /* Base address of this compilation unit.  */
401   CORE_ADDR base_address;
402
403   /* Non-zero if base_address has been set.  */
404   int base_known;
405
406   /* The language we are debugging.  */
407   enum language language;
408   const struct language_defn *language_defn;
409
410   const char *producer;
411
412   /* The generic symbol table building routines have separate lists for
413      file scope symbols and all all other scopes (local scopes).  So
414      we need to select the right one to pass to add_symbol_to_list().
415      We do it by keeping a pointer to the correct list in list_in_scope.
416
417      FIXME: The original dwarf code just treated the file scope as the
418      first local scope, and all other local scopes as nested local
419      scopes, and worked fine.  Check to see if we really need to
420      distinguish these in buildsym.c.  */
421   struct pending **list_in_scope;
422
423   /* The abbrev table for this CU.
424      Normally this points to the abbrev table in the objfile.
425      But if DWO_UNIT is non-NULL this is the abbrev table in the DWO file.  */
426   struct abbrev_table *abbrev_table;
427
428   /* Hash table holding all the loaded partial DIEs
429      with partial_die->offset.SECT_OFF as hash.  */
430   htab_t partial_dies;
431
432   /* Storage for things with the same lifetime as this read-in compilation
433      unit, including partial DIEs.  */
434   struct obstack comp_unit_obstack;
435
436   /* When multiple dwarf2_cu structures are living in memory, this field
437      chains them all together, so that they can be released efficiently.
438      We will probably also want a generation counter so that most-recently-used
439      compilation units are cached...  */
440   struct dwarf2_per_cu_data *read_in_chain;
441
442   /* Backlink to our per_cu entry.  */
443   struct dwarf2_per_cu_data *per_cu;
444
445   /* How many compilation units ago was this CU last referenced?  */
446   int last_used;
447
448   /* A hash table of DIE cu_offset for following references with
449      die_info->offset.sect_off as hash.  */
450   htab_t die_hash;
451
452   /* Full DIEs if read in.  */
453   struct die_info *dies;
454
455   /* A set of pointers to dwarf2_per_cu_data objects for compilation
456      units referenced by this one.  Only set during full symbol processing;
457      partial symbol tables do not have dependencies.  */
458   htab_t dependencies;
459
460   /* Header data from the line table, during full symbol processing.  */
461   struct line_header *line_header;
462
463   /* A list of methods which need to have physnames computed
464      after all type information has been read.  */
465   VEC (delayed_method_info) *method_list;
466
467   /* To be copied to symtab->call_site_htab.  */
468   htab_t call_site_htab;
469
470   /* Non-NULL if this CU came from a DWO file.
471      There is an invariant here that is important to remember:
472      Except for attributes copied from the top level DIE in the "main"
473      (or "stub") file in preparation for reading the DWO file
474      (e.g., DW_AT_GNU_addr_base), we KISS: there is only *one* CU.
475      Either there isn't a DWO file (in which case this is NULL and the point
476      is moot), or there is and either we're not going to read it (in which
477      case this is NULL) or there is and we are reading it (in which case this
478      is non-NULL).  */
479   struct dwo_unit *dwo_unit;
480
481   /* The DW_AT_addr_base attribute if present, zero otherwise
482      (zero is a valid value though).
483      Note this value comes from the stub CU/TU's DIE.  */
484   ULONGEST addr_base;
485
486   /* The DW_AT_ranges_base attribute if present, zero otherwise
487      (zero is a valid value though).
488      Note this value comes from the stub CU/TU's DIE.
489      Also note that the value is zero in the non-DWO case so this value can
490      be used without needing to know whether DWO files are in use or not.
491      N.B. This does not apply to DW_AT_ranges appearing in
492      DW_TAG_compile_unit dies.  This is a bit of a wart, consider if ever
493      DW_AT_ranges appeared in the DW_TAG_compile_unit of DWO DIEs: then
494      DW_AT_ranges_base *would* have to be applied, and we'd have to care
495      whether the DW_AT_ranges attribute came from the skeleton or DWO.  */
496   ULONGEST ranges_base;
497
498   /* Mark used when releasing cached dies.  */
499   unsigned int mark : 1;
500
501   /* This CU references .debug_loc.  See the symtab->locations_valid field.
502      This test is imperfect as there may exist optimized debug code not using
503      any location list and still facing inlining issues if handled as
504      unoptimized code.  For a future better test see GCC PR other/32998.  */
505   unsigned int has_loclist : 1;
506
507   /* These cache the results for producer_is_* fields.  CHECKED_PRODUCER is set
508      if all the producer_is_* fields are valid.  This information is cached
509      because profiling CU expansion showed excessive time spent in
510      producer_is_gxx_lt_4_6.  */
511   unsigned int checked_producer : 1;
512   unsigned int producer_is_gxx_lt_4_6 : 1;
513   unsigned int producer_is_gcc_lt_4_3 : 1;
514   unsigned int producer_is_icc : 1;
515
516   /* When set, the file that we're processing is known to have
517      debugging info for C++ namespaces.  GCC 3.3.x did not produce
518      this information, but later versions do.  */
519
520   unsigned int processing_has_namespace_info : 1;
521 };
522
523 /* Persistent data held for a compilation unit, even when not
524    processing it.  We put a pointer to this structure in the
525    read_symtab_private field of the psymtab.  */
526
527 struct dwarf2_per_cu_data
528 {
529   /* The start offset and length of this compilation unit.
530      NOTE: Unlike comp_unit_head.length, this length includes
531      initial_length_size.
532      If the DIE refers to a DWO file, this is always of the original die,
533      not the DWO file.  */
534   sect_offset offset;
535   unsigned int length;
536
537   /* Flag indicating this compilation unit will be read in before
538      any of the current compilation units are processed.  */
539   unsigned int queued : 1;
540
541   /* This flag will be set when reading partial DIEs if we need to load
542      absolutely all DIEs for this compilation unit, instead of just the ones
543      we think are interesting.  It gets set if we look for a DIE in the
544      hash table and don't find it.  */
545   unsigned int load_all_dies : 1;
546
547   /* Non-zero if this CU is from .debug_types.
548      Struct dwarf2_per_cu_data is contained in struct signatured_type iff
549      this is non-zero.  */
550   unsigned int is_debug_types : 1;
551
552   /* Non-zero if this CU is from the .dwz file.  */
553   unsigned int is_dwz : 1;
554
555   /* Non-zero if reading a TU directly from a DWO file, bypassing the stub.
556      This flag is only valid if is_debug_types is true.
557      We can't read a CU directly from a DWO file: There are required
558      attributes in the stub.  */
559   unsigned int reading_dwo_directly : 1;
560
561   /* Non-zero if the TU has been read.
562      This is used to assist the "Stay in DWO Optimization" for Fission:
563      When reading a DWO, it's faster to read TUs from the DWO instead of
564      fetching them from random other DWOs (due to comdat folding).
565      If the TU has already been read, the optimization is unnecessary
566      (and unwise - we don't want to change where gdb thinks the TU lives
567      "midflight").
568      This flag is only valid if is_debug_types is true.  */
569   unsigned int tu_read : 1;
570
571   /* The section this CU/TU lives in.
572      If the DIE refers to a DWO file, this is always the original die,
573      not the DWO file.  */
574   struct dwarf2_section_info *section;
575
576   /* Set to non-NULL iff this CU is currently loaded.  When it gets freed out
577      of the CU cache it gets reset to NULL again.  */
578   struct dwarf2_cu *cu;
579
580   /* The corresponding objfile.
581      Normally we can get the objfile from dwarf2_per_objfile.
582      However we can enter this file with just a "per_cu" handle.  */
583   struct objfile *objfile;
584
585   /* When using partial symbol tables, the 'psymtab' field is active.
586      Otherwise the 'quick' field is active.  */
587   union
588   {
589     /* The partial symbol table associated with this compilation unit,
590        or NULL for unread partial units.  */
591     struct partial_symtab *psymtab;
592
593     /* Data needed by the "quick" functions.  */
594     struct dwarf2_per_cu_quick_data *quick;
595   } v;
596
597   /* The CUs we import using DW_TAG_imported_unit.  This is filled in
598      while reading psymtabs, used to compute the psymtab dependencies,
599      and then cleared.  Then it is filled in again while reading full
600      symbols, and only deleted when the objfile is destroyed.
601
602      This is also used to work around a difference between the way gold
603      generates .gdb_index version <=7 and the way gdb does.  Arguably this
604      is a gold bug.  For symbols coming from TUs, gold records in the index
605      the CU that includes the TU instead of the TU itself.  This breaks
606      dw2_lookup_symbol: It assumes that if the index says symbol X lives
607      in CU/TU Y, then one need only expand Y and a subsequent lookup in Y
608      will find X.  Alas TUs live in their own symtab, so after expanding CU Y
609      we need to look in TU Z to find X.  Fortunately, this is akin to
610      DW_TAG_imported_unit, so we just use the same mechanism: For
611      .gdb_index version <=7 this also records the TUs that the CU referred
612      to.  Concurrently with this change gdb was modified to emit version 8
613      indices so we only pay a price for gold generated indices.
614      http://sourceware.org/bugzilla/show_bug.cgi?id=15021.  */
615   VEC (dwarf2_per_cu_ptr) *imported_symtabs;
616 };
617
618 /* Entry in the signatured_types hash table.  */
619
620 struct signatured_type
621 {
622   /* The "per_cu" object of this type.
623      This struct is used iff per_cu.is_debug_types.
624      N.B.: This is the first member so that it's easy to convert pointers
625      between them.  */
626   struct dwarf2_per_cu_data per_cu;
627
628   /* The type's signature.  */
629   ULONGEST signature;
630
631   /* Offset in the TU of the type's DIE, as read from the TU header.
632      If this TU is a DWO stub and the definition lives in a DWO file
633      (specified by DW_AT_GNU_dwo_name), this value is unusable.  */
634   cu_offset type_offset_in_tu;
635
636   /* Offset in the section of the type's DIE.
637      If the definition lives in a DWO file, this is the offset in the
638      .debug_types.dwo section.
639      The value is zero until the actual value is known.
640      Zero is otherwise not a valid section offset.  */
641   sect_offset type_offset_in_section;
642
643   /* Type units are grouped by their DW_AT_stmt_list entry so that they
644      can share them.  This points to the containing symtab.  */
645   struct type_unit_group *type_unit_group;
646
647   /* The type.
648      The first time we encounter this type we fully read it in and install it
649      in the symbol tables.  Subsequent times we only need the type.  */
650   struct type *type;
651
652   /* Containing DWO unit.
653      This field is valid iff per_cu.reading_dwo_directly.  */
654   struct dwo_unit *dwo_unit;
655 };
656
657 typedef struct signatured_type *sig_type_ptr;
658 DEF_VEC_P (sig_type_ptr);
659
660 /* A struct that can be used as a hash key for tables based on DW_AT_stmt_list.
661    This includes type_unit_group and quick_file_names.  */
662
663 struct stmt_list_hash
664 {
665   /* The DWO unit this table is from or NULL if there is none.  */
666   struct dwo_unit *dwo_unit;
667
668   /* Offset in .debug_line or .debug_line.dwo.  */
669   sect_offset line_offset;
670 };
671
672 /* Each element of dwarf2_per_objfile->type_unit_groups is a pointer to
673    an object of this type.  */
674
675 struct type_unit_group
676 {
677   /* dwarf2read.c's main "handle" on a TU symtab.
678      To simplify things we create an artificial CU that "includes" all the
679      type units using this stmt_list so that the rest of the code still has
680      a "per_cu" handle on the symtab.
681      This PER_CU is recognized by having no section.  */
682 #define IS_TYPE_UNIT_GROUP(per_cu) ((per_cu)->section == NULL)
683   struct dwarf2_per_cu_data per_cu;
684
685   /* The TUs that share this DW_AT_stmt_list entry.
686      This is added to while parsing type units to build partial symtabs,
687      and is deleted afterwards and not used again.  */
688   VEC (sig_type_ptr) *tus;
689
690   /* The primary symtab.
691      Type units in a group needn't all be defined in the same source file,
692      so we create an essentially anonymous symtab as the primary symtab.  */
693   struct symtab *primary_symtab;
694
695   /* The data used to construct the hash key.  */
696   struct stmt_list_hash hash;
697
698   /* The number of symtabs from the line header.
699      The value here must match line_header.num_file_names.  */
700   unsigned int num_symtabs;
701
702   /* The symbol tables for this TU (obtained from the files listed in
703      DW_AT_stmt_list).
704      WARNING: The order of entries here must match the order of entries
705      in the line header.  After the first TU using this type_unit_group, the
706      line header for the subsequent TUs is recreated from this.  This is done
707      because we need to use the same symtabs for each TU using the same
708      DW_AT_stmt_list value.  Also note that symtabs may be repeated here,
709      there's no guarantee the line header doesn't have duplicate entries.  */
710   struct symtab **symtabs;
711 };
712
713 /* These sections are what may appear in a DWO file.  */
714
715 struct dwo_sections
716 {
717   struct dwarf2_section_info abbrev;
718   struct dwarf2_section_info line;
719   struct dwarf2_section_info loc;
720   struct dwarf2_section_info macinfo;
721   struct dwarf2_section_info macro;
722   struct dwarf2_section_info str;
723   struct dwarf2_section_info str_offsets;
724   /* In the case of a virtual DWO file, these two are unused.  */
725   struct dwarf2_section_info info;
726   VEC (dwarf2_section_info_def) *types;
727 };
728
729 /* CUs/TUs in DWP/DWO files.  */
730
731 struct dwo_unit
732 {
733   /* Backlink to the containing struct dwo_file.  */
734   struct dwo_file *dwo_file;
735
736   /* The "id" that distinguishes this CU/TU.
737      .debug_info calls this "dwo_id", .debug_types calls this "signature".
738      Since signatures came first, we stick with it for consistency.  */
739   ULONGEST signature;
740
741   /* The section this CU/TU lives in, in the DWO file.  */
742   struct dwarf2_section_info *section;
743
744   /* Same as dwarf2_per_cu_data:{offset,length} but for the DWO section.  */
745   sect_offset offset;
746   unsigned int length;
747
748   /* For types, offset in the type's DIE of the type defined by this TU.  */
749   cu_offset type_offset_in_tu;
750 };
751
752 /* Data for one DWO file.
753    This includes virtual DWO files that have been packaged into a
754    DWP file.  */
755
756 struct dwo_file
757 {
758   /* The DW_AT_GNU_dwo_name attribute.
759      For virtual DWO files the name is constructed from the section offsets
760      of abbrev,line,loc,str_offsets so that we combine virtual DWO files
761      from related CU+TUs.  */
762   const char *dwo_name;
763
764   /* The DW_AT_comp_dir attribute.  */
765   const char *comp_dir;
766
767   /* The bfd, when the file is open.  Otherwise this is NULL.
768      This is unused(NULL) for virtual DWO files where we use dwp_file.dbfd.  */
769   bfd *dbfd;
770
771   /* Section info for this file.  */
772   struct dwo_sections sections;
773
774   /* The CU in the file.
775      We only support one because having more than one requires hacking the
776      dwo_name of each to match, which is highly unlikely to happen.
777      Doing this means all TUs can share comp_dir: We also assume that
778      DW_AT_comp_dir across all TUs in a DWO file will be identical.  */
779   struct dwo_unit *cu;
780
781   /* Table of TUs in the file.
782      Each element is a struct dwo_unit.  */
783   htab_t tus;
784 };
785
786 /* These sections are what may appear in a DWP file.  */
787
788 struct dwp_sections
789 {
790   struct dwarf2_section_info str;
791   struct dwarf2_section_info cu_index;
792   struct dwarf2_section_info tu_index;
793   /* The .debug_info.dwo, .debug_types.dwo, and other sections are referenced
794      by section number.  We don't need to record them here.  */
795 };
796
797 /* These sections are what may appear in a virtual DWO file.  */
798
799 struct virtual_dwo_sections
800 {
801   struct dwarf2_section_info abbrev;
802   struct dwarf2_section_info line;
803   struct dwarf2_section_info loc;
804   struct dwarf2_section_info macinfo;
805   struct dwarf2_section_info macro;
806   struct dwarf2_section_info str_offsets;
807   /* Each DWP hash table entry records one CU or one TU.
808      That is recorded here, and copied to dwo_unit.section.  */
809   struct dwarf2_section_info info_or_types;
810 };
811
812 /* Contents of DWP hash tables.  */
813
814 struct dwp_hash_table
815 {
816   uint32_t nr_units, nr_slots;
817   const gdb_byte *hash_table, *unit_table, *section_pool;
818 };
819
820 /* Data for one DWP file.  */
821
822 struct dwp_file
823 {
824   /* Name of the file.  */
825   const char *name;
826
827   /* The bfd.  */
828   bfd *dbfd;
829
830   /* Section info for this file.  */
831   struct dwp_sections sections;
832
833   /* Table of CUs in the file. */
834   const struct dwp_hash_table *cus;
835
836   /* Table of TUs in the file.  */
837   const struct dwp_hash_table *tus;
838
839   /* Table of loaded CUs/TUs.  Each entry is a struct dwo_unit *.  */
840   htab_t loaded_cutus;
841
842   /* Table to map ELF section numbers to their sections.  */
843   unsigned int num_sections;
844   asection **elf_sections;
845 };
846
847 /* This represents a '.dwz' file.  */
848
849 struct dwz_file
850 {
851   /* A dwz file can only contain a few sections.  */
852   struct dwarf2_section_info abbrev;
853   struct dwarf2_section_info info;
854   struct dwarf2_section_info str;
855   struct dwarf2_section_info line;
856   struct dwarf2_section_info macro;
857   struct dwarf2_section_info gdb_index;
858
859   /* The dwz's BFD.  */
860   bfd *dwz_bfd;
861 };
862
863 /* Struct used to pass misc. parameters to read_die_and_children, et
864    al.  which are used for both .debug_info and .debug_types dies.
865    All parameters here are unchanging for the life of the call.  This
866    struct exists to abstract away the constant parameters of die reading.  */
867
868 struct die_reader_specs
869 {
870   /* die_section->asection->owner.  */
871   bfd* abfd;
872
873   /* The CU of the DIE we are parsing.  */
874   struct dwarf2_cu *cu;
875
876   /* Non-NULL if reading a DWO file (including one packaged into a DWP).  */
877   struct dwo_file *dwo_file;
878
879   /* The section the die comes from.
880      This is either .debug_info or .debug_types, or the .dwo variants.  */
881   struct dwarf2_section_info *die_section;
882
883   /* die_section->buffer.  */
884   const gdb_byte *buffer;
885
886   /* The end of the buffer.  */
887   const gdb_byte *buffer_end;
888
889   /* The value of the DW_AT_comp_dir attribute.  */
890   const char *comp_dir;
891 };
892
893 /* Type of function passed to init_cutu_and_read_dies, et.al.  */
894 typedef void (die_reader_func_ftype) (const struct die_reader_specs *reader,
895                                       const gdb_byte *info_ptr,
896                                       struct die_info *comp_unit_die,
897                                       int has_children,
898                                       void *data);
899
900 /* The line number information for a compilation unit (found in the
901    .debug_line section) begins with a "statement program header",
902    which contains the following information.  */
903 struct line_header
904 {
905   unsigned int total_length;
906   unsigned short version;
907   unsigned int header_length;
908   unsigned char minimum_instruction_length;
909   unsigned char maximum_ops_per_instruction;
910   unsigned char default_is_stmt;
911   int line_base;
912   unsigned char line_range;
913   unsigned char opcode_base;
914
915   /* standard_opcode_lengths[i] is the number of operands for the
916      standard opcode whose value is i.  This means that
917      standard_opcode_lengths[0] is unused, and the last meaningful
918      element is standard_opcode_lengths[opcode_base - 1].  */
919   unsigned char *standard_opcode_lengths;
920
921   /* The include_directories table.  NOTE!  These strings are not
922      allocated with xmalloc; instead, they are pointers into
923      debug_line_buffer.  If you try to free them, `free' will get
924      indigestion.  */
925   unsigned int num_include_dirs, include_dirs_size;
926   const char **include_dirs;
927
928   /* The file_names table.  NOTE!  These strings are not allocated
929      with xmalloc; instead, they are pointers into debug_line_buffer.
930      Don't try to free them directly.  */
931   unsigned int num_file_names, file_names_size;
932   struct file_entry
933   {
934     const char *name;
935     unsigned int dir_index;
936     unsigned int mod_time;
937     unsigned int length;
938     int included_p; /* Non-zero if referenced by the Line Number Program.  */
939     struct symtab *symtab; /* The associated symbol table, if any.  */
940   } *file_names;
941
942   /* The start and end of the statement program following this
943      header.  These point into dwarf2_per_objfile->line_buffer.  */
944   const gdb_byte *statement_program_start, *statement_program_end;
945 };
946
947 /* When we construct a partial symbol table entry we only
948    need this much information.  */
949 struct partial_die_info
950   {
951     /* Offset of this DIE.  */
952     sect_offset offset;
953
954     /* DWARF-2 tag for this DIE.  */
955     ENUM_BITFIELD(dwarf_tag) tag : 16;
956
957     /* Assorted flags describing the data found in this DIE.  */
958     unsigned int has_children : 1;
959     unsigned int is_external : 1;
960     unsigned int is_declaration : 1;
961     unsigned int has_type : 1;
962     unsigned int has_specification : 1;
963     unsigned int has_pc_info : 1;
964     unsigned int may_be_inlined : 1;
965
966     /* Flag set if the SCOPE field of this structure has been
967        computed.  */
968     unsigned int scope_set : 1;
969
970     /* Flag set if the DIE has a byte_size attribute.  */
971     unsigned int has_byte_size : 1;
972
973     /* Flag set if any of the DIE's children are template arguments.  */
974     unsigned int has_template_arguments : 1;
975
976     /* Flag set if fixup_partial_die has been called on this die.  */
977     unsigned int fixup_called : 1;
978
979     /* Flag set if DW_TAG_imported_unit uses DW_FORM_GNU_ref_alt.  */
980     unsigned int is_dwz : 1;
981
982     /* Flag set if spec_offset uses DW_FORM_GNU_ref_alt.  */
983     unsigned int spec_is_dwz : 1;
984
985     /* The name of this DIE.  Normally the value of DW_AT_name, but
986        sometimes a default name for unnamed DIEs.  */
987     const char *name;
988
989     /* The linkage name, if present.  */
990     const char *linkage_name;
991
992     /* The scope to prepend to our children.  This is generally
993        allocated on the comp_unit_obstack, so will disappear
994        when this compilation unit leaves the cache.  */
995     const char *scope;
996
997     /* Some data associated with the partial DIE.  The tag determines
998        which field is live.  */
999     union
1000     {
1001       /* The location description associated with this DIE, if any.  */
1002       struct dwarf_block *locdesc;
1003       /* The offset of an import, for DW_TAG_imported_unit.  */
1004       sect_offset offset;
1005     } d;
1006
1007     /* If HAS_PC_INFO, the PC range associated with this DIE.  */
1008     CORE_ADDR lowpc;
1009     CORE_ADDR highpc;
1010
1011     /* Pointer into the info_buffer (or types_buffer) pointing at the target of
1012        DW_AT_sibling, if any.  */
1013     /* NOTE: This member isn't strictly necessary, read_partial_die could
1014        return DW_AT_sibling values to its caller load_partial_dies.  */
1015     const gdb_byte *sibling;
1016
1017     /* If HAS_SPECIFICATION, the offset of the DIE referred to by
1018        DW_AT_specification (or DW_AT_abstract_origin or
1019        DW_AT_extension).  */
1020     sect_offset spec_offset;
1021
1022     /* Pointers to this DIE's parent, first child, and next sibling,
1023        if any.  */
1024     struct partial_die_info *die_parent, *die_child, *die_sibling;
1025   };
1026
1027 /* This data structure holds the information of an abbrev.  */
1028 struct abbrev_info
1029   {
1030     unsigned int number;        /* number identifying abbrev */
1031     enum dwarf_tag tag;         /* dwarf tag */
1032     unsigned short has_children;                /* boolean */
1033     unsigned short num_attrs;   /* number of attributes */
1034     struct attr_abbrev *attrs;  /* an array of attribute descriptions */
1035     struct abbrev_info *next;   /* next in chain */
1036   };
1037
1038 struct attr_abbrev
1039   {
1040     ENUM_BITFIELD(dwarf_attribute) name : 16;
1041     ENUM_BITFIELD(dwarf_form) form : 16;
1042   };
1043
1044 /* Size of abbrev_table.abbrev_hash_table.  */
1045 #define ABBREV_HASH_SIZE 121
1046
1047 /* Top level data structure to contain an abbreviation table.  */
1048
1049 struct abbrev_table
1050 {
1051   /* Where the abbrev table came from.
1052      This is used as a sanity check when the table is used.  */
1053   sect_offset offset;
1054
1055   /* Storage for the abbrev table.  */
1056   struct obstack abbrev_obstack;
1057
1058   /* Hash table of abbrevs.
1059      This is an array of size ABBREV_HASH_SIZE allocated in abbrev_obstack.
1060      It could be statically allocated, but the previous code didn't so we
1061      don't either.  */
1062   struct abbrev_info **abbrevs;
1063 };
1064
1065 /* Attributes have a name and a value.  */
1066 struct attribute
1067   {
1068     ENUM_BITFIELD(dwarf_attribute) name : 16;
1069     ENUM_BITFIELD(dwarf_form) form : 15;
1070
1071     /* Has DW_STRING already been updated by dwarf2_canonicalize_name?  This
1072        field should be in u.str (existing only for DW_STRING) but it is kept
1073        here for better struct attribute alignment.  */
1074     unsigned int string_is_canonical : 1;
1075
1076     union
1077       {
1078         const char *str;
1079         struct dwarf_block *blk;
1080         ULONGEST unsnd;
1081         LONGEST snd;
1082         CORE_ADDR addr;
1083         ULONGEST signature;
1084       }
1085     u;
1086   };
1087
1088 /* This data structure holds a complete die structure.  */
1089 struct die_info
1090   {
1091     /* DWARF-2 tag for this DIE.  */
1092     ENUM_BITFIELD(dwarf_tag) tag : 16;
1093
1094     /* Number of attributes */
1095     unsigned char num_attrs;
1096
1097     /* True if we're presently building the full type name for the
1098        type derived from this DIE.  */
1099     unsigned char building_fullname : 1;
1100
1101     /* Abbrev number */
1102     unsigned int abbrev;
1103
1104     /* Offset in .debug_info or .debug_types section.  */
1105     sect_offset offset;
1106
1107     /* The dies in a compilation unit form an n-ary tree.  PARENT
1108        points to this die's parent; CHILD points to the first child of
1109        this node; and all the children of a given node are chained
1110        together via their SIBLING fields.  */
1111     struct die_info *child;     /* Its first child, if any.  */
1112     struct die_info *sibling;   /* Its next sibling, if any.  */
1113     struct die_info *parent;    /* Its parent, if any.  */
1114
1115     /* An array of attributes, with NUM_ATTRS elements.  There may be
1116        zero, but it's not common and zero-sized arrays are not
1117        sufficiently portable C.  */
1118     struct attribute attrs[1];
1119   };
1120
1121 /* Get at parts of an attribute structure.  */
1122
1123 #define DW_STRING(attr)    ((attr)->u.str)
1124 #define DW_STRING_IS_CANONICAL(attr) ((attr)->string_is_canonical)
1125 #define DW_UNSND(attr)     ((attr)->u.unsnd)
1126 #define DW_BLOCK(attr)     ((attr)->u.blk)
1127 #define DW_SND(attr)       ((attr)->u.snd)
1128 #define DW_ADDR(attr)      ((attr)->u.addr)
1129 #define DW_SIGNATURE(attr) ((attr)->u.signature)
1130
1131 /* Blocks are a bunch of untyped bytes.  */
1132 struct dwarf_block
1133   {
1134     size_t size;
1135
1136     /* Valid only if SIZE is not zero.  */
1137     const gdb_byte *data;
1138   };
1139
1140 #ifndef ATTR_ALLOC_CHUNK
1141 #define ATTR_ALLOC_CHUNK 4
1142 #endif
1143
1144 /* Allocate fields for structs, unions and enums in this size.  */
1145 #ifndef DW_FIELD_ALLOC_CHUNK
1146 #define DW_FIELD_ALLOC_CHUNK 4
1147 #endif
1148
1149 /* FIXME: We might want to set this from BFD via bfd_arch_bits_per_byte,
1150    but this would require a corresponding change in unpack_field_as_long
1151    and friends.  */
1152 static int bits_per_byte = 8;
1153
1154 /* The routines that read and process dies for a C struct or C++ class
1155    pass lists of data member fields and lists of member function fields
1156    in an instance of a field_info structure, as defined below.  */
1157 struct field_info
1158   {
1159     /* List of data member and baseclasses fields.  */
1160     struct nextfield
1161       {
1162         struct nextfield *next;
1163         int accessibility;
1164         int virtuality;
1165         struct field field;
1166       }
1167      *fields, *baseclasses;
1168
1169     /* Number of fields (including baseclasses).  */
1170     int nfields;
1171
1172     /* Number of baseclasses.  */
1173     int nbaseclasses;
1174
1175     /* Set if the accesibility of one of the fields is not public.  */
1176     int non_public_fields;
1177
1178     /* Member function fields array, entries are allocated in the order they
1179        are encountered in the object file.  */
1180     struct nextfnfield
1181       {
1182         struct nextfnfield *next;
1183         struct fn_field fnfield;
1184       }
1185      *fnfields;
1186
1187     /* Member function fieldlist array, contains name of possibly overloaded
1188        member function, number of overloaded member functions and a pointer
1189        to the head of the member function field chain.  */
1190     struct fnfieldlist
1191       {
1192         const char *name;
1193         int length;
1194         struct nextfnfield *head;
1195       }
1196      *fnfieldlists;
1197
1198     /* Number of entries in the fnfieldlists array.  */
1199     int nfnfields;
1200
1201     /* typedefs defined inside this class.  TYPEDEF_FIELD_LIST contains head of
1202        a NULL terminated list of TYPEDEF_FIELD_LIST_COUNT elements.  */
1203     struct typedef_field_list
1204       {
1205         struct typedef_field field;
1206         struct typedef_field_list *next;
1207       }
1208     *typedef_field_list;
1209     unsigned typedef_field_list_count;
1210   };
1211
1212 /* One item on the queue of compilation units to read in full symbols
1213    for.  */
1214 struct dwarf2_queue_item
1215 {
1216   struct dwarf2_per_cu_data *per_cu;
1217   enum language pretend_language;
1218   struct dwarf2_queue_item *next;
1219 };
1220
1221 /* The current queue.  */
1222 static struct dwarf2_queue_item *dwarf2_queue, *dwarf2_queue_tail;
1223
1224 /* Loaded secondary compilation units are kept in memory until they
1225    have not been referenced for the processing of this many
1226    compilation units.  Set this to zero to disable caching.  Cache
1227    sizes of up to at least twenty will improve startup time for
1228    typical inter-CU-reference binaries, at an obvious memory cost.  */
1229 static int dwarf2_max_cache_age = 5;
1230 static void
1231 show_dwarf2_max_cache_age (struct ui_file *file, int from_tty,
1232                            struct cmd_list_element *c, const char *value)
1233 {
1234   fprintf_filtered (file, _("The upper bound on the age of cached "
1235                             "dwarf2 compilation units is %s.\n"),
1236                     value);
1237 }
1238 \f
1239 /* local function prototypes */
1240
1241 static void dwarf2_locate_sections (bfd *, asection *, void *);
1242
1243 static void dwarf2_find_base_address (struct die_info *die,
1244                                       struct dwarf2_cu *cu);
1245
1246 static struct partial_symtab *create_partial_symtab
1247   (struct dwarf2_per_cu_data *per_cu, const char *name);
1248
1249 static void dwarf2_build_psymtabs_hard (struct objfile *);
1250
1251 static void scan_partial_symbols (struct partial_die_info *,
1252                                   CORE_ADDR *, CORE_ADDR *,
1253                                   int, struct dwarf2_cu *);
1254
1255 static void add_partial_symbol (struct partial_die_info *,
1256                                 struct dwarf2_cu *);
1257
1258 static void add_partial_namespace (struct partial_die_info *pdi,
1259                                    CORE_ADDR *lowpc, CORE_ADDR *highpc,
1260                                    int need_pc, struct dwarf2_cu *cu);
1261
1262 static void add_partial_module (struct partial_die_info *pdi, CORE_ADDR *lowpc,
1263                                 CORE_ADDR *highpc, int need_pc,
1264                                 struct dwarf2_cu *cu);
1265
1266 static void add_partial_enumeration (struct partial_die_info *enum_pdi,
1267                                      struct dwarf2_cu *cu);
1268
1269 static void add_partial_subprogram (struct partial_die_info *pdi,
1270                                     CORE_ADDR *lowpc, CORE_ADDR *highpc,
1271                                     int need_pc, struct dwarf2_cu *cu);
1272
1273 static void dwarf2_read_symtab (struct partial_symtab *,
1274                                 struct objfile *);
1275
1276 static void psymtab_to_symtab_1 (struct partial_symtab *);
1277
1278 static struct abbrev_info *abbrev_table_lookup_abbrev
1279   (const struct abbrev_table *, unsigned int);
1280
1281 static struct abbrev_table *abbrev_table_read_table
1282   (struct dwarf2_section_info *, sect_offset);
1283
1284 static void abbrev_table_free (struct abbrev_table *);
1285
1286 static void abbrev_table_free_cleanup (void *);
1287
1288 static void dwarf2_read_abbrevs (struct dwarf2_cu *,
1289                                  struct dwarf2_section_info *);
1290
1291 static void dwarf2_free_abbrev_table (void *);
1292
1293 static unsigned int peek_abbrev_code (bfd *, const gdb_byte *);
1294
1295 static struct partial_die_info *load_partial_dies
1296   (const struct die_reader_specs *, const gdb_byte *, int);
1297
1298 static const gdb_byte *read_partial_die (const struct die_reader_specs *,
1299                                          struct partial_die_info *,
1300                                          struct abbrev_info *,
1301                                          unsigned int,
1302                                          const gdb_byte *);
1303
1304 static struct partial_die_info *find_partial_die (sect_offset, int,
1305                                                   struct dwarf2_cu *);
1306
1307 static void fixup_partial_die (struct partial_die_info *,
1308                                struct dwarf2_cu *);
1309
1310 static const gdb_byte *read_attribute (const struct die_reader_specs *,
1311                                        struct attribute *, struct attr_abbrev *,
1312                                        const gdb_byte *);
1313
1314 static unsigned int read_1_byte (bfd *, const gdb_byte *);
1315
1316 static int read_1_signed_byte (bfd *, const gdb_byte *);
1317
1318 static unsigned int read_2_bytes (bfd *, const gdb_byte *);
1319
1320 static unsigned int read_4_bytes (bfd *, const gdb_byte *);
1321
1322 static ULONGEST read_8_bytes (bfd *, const gdb_byte *);
1323
1324 static CORE_ADDR read_address (bfd *, const gdb_byte *ptr, struct dwarf2_cu *,
1325                                unsigned int *);
1326
1327 static LONGEST read_initial_length (bfd *, const gdb_byte *, unsigned int *);
1328
1329 static LONGEST read_checked_initial_length_and_offset
1330   (bfd *, const gdb_byte *, const struct comp_unit_head *,
1331    unsigned int *, unsigned int *);
1332
1333 static LONGEST read_offset (bfd *, const gdb_byte *,
1334                             const struct comp_unit_head *,
1335                             unsigned int *);
1336
1337 static LONGEST read_offset_1 (bfd *, const gdb_byte *, unsigned int);
1338
1339 static sect_offset read_abbrev_offset (struct dwarf2_section_info *,
1340                                        sect_offset);
1341
1342 static const gdb_byte *read_n_bytes (bfd *, const gdb_byte *, unsigned int);
1343
1344 static const char *read_direct_string (bfd *, const gdb_byte *, unsigned int *);
1345
1346 static const char *read_indirect_string (bfd *, const gdb_byte *,
1347                                          const struct comp_unit_head *,
1348                                          unsigned int *);
1349
1350 static const char *read_indirect_string_from_dwz (struct dwz_file *, LONGEST);
1351
1352 static ULONGEST read_unsigned_leb128 (bfd *, const gdb_byte *, unsigned int *);
1353
1354 static LONGEST read_signed_leb128 (bfd *, const gdb_byte *, unsigned int *);
1355
1356 static CORE_ADDR read_addr_index_from_leb128 (struct dwarf2_cu *,
1357                                               const gdb_byte *,
1358                                               unsigned int *);
1359
1360 static const char *read_str_index (const struct die_reader_specs *reader,
1361                                    struct dwarf2_cu *cu, ULONGEST str_index);
1362
1363 static void set_cu_language (unsigned int, struct dwarf2_cu *);
1364
1365 static struct attribute *dwarf2_attr (struct die_info *, unsigned int,
1366                                       struct dwarf2_cu *);
1367
1368 static struct attribute *dwarf2_attr_no_follow (struct die_info *,
1369                                                 unsigned int);
1370
1371 static int dwarf2_flag_true_p (struct die_info *die, unsigned name,
1372                                struct dwarf2_cu *cu);
1373
1374 static int die_is_declaration (struct die_info *, struct dwarf2_cu *cu);
1375
1376 static struct die_info *die_specification (struct die_info *die,
1377                                            struct dwarf2_cu **);
1378
1379 static void free_line_header (struct line_header *lh);
1380
1381 static struct line_header *dwarf_decode_line_header (unsigned int offset,
1382                                                      struct dwarf2_cu *cu);
1383
1384 static void dwarf_decode_lines (struct line_header *, const char *,
1385                                 struct dwarf2_cu *, struct partial_symtab *,
1386                                 int);
1387
1388 static void dwarf2_start_subfile (const char *, const char *, const char *);
1389
1390 static void dwarf2_start_symtab (struct dwarf2_cu *,
1391                                  const char *, const char *, CORE_ADDR);
1392
1393 static struct symbol *new_symbol (struct die_info *, struct type *,
1394                                   struct dwarf2_cu *);
1395
1396 static struct symbol *new_symbol_full (struct die_info *, struct type *,
1397                                        struct dwarf2_cu *, struct symbol *);
1398
1399 static void dwarf2_const_value (const struct attribute *, struct symbol *,
1400                                 struct dwarf2_cu *);
1401
1402 static void dwarf2_const_value_attr (const struct attribute *attr,
1403                                      struct type *type,
1404                                      const char *name,
1405                                      struct obstack *obstack,
1406                                      struct dwarf2_cu *cu, LONGEST *value,
1407                                      const gdb_byte **bytes,
1408                                      struct dwarf2_locexpr_baton **baton);
1409
1410 static struct type *die_type (struct die_info *, struct dwarf2_cu *);
1411
1412 static int need_gnat_info (struct dwarf2_cu *);
1413
1414 static struct type *die_descriptive_type (struct die_info *,
1415                                           struct dwarf2_cu *);
1416
1417 static void set_descriptive_type (struct type *, struct die_info *,
1418                                   struct dwarf2_cu *);
1419
1420 static struct type *die_containing_type (struct die_info *,
1421                                          struct dwarf2_cu *);
1422
1423 static struct type *lookup_die_type (struct die_info *, const struct attribute *,
1424                                      struct dwarf2_cu *);
1425
1426 static struct type *read_type_die (struct die_info *, struct dwarf2_cu *);
1427
1428 static struct type *read_type_die_1 (struct die_info *, struct dwarf2_cu *);
1429
1430 static const char *determine_prefix (struct die_info *die, struct dwarf2_cu *);
1431
1432 static char *typename_concat (struct obstack *obs, const char *prefix,
1433                               const char *suffix, int physname,
1434                               struct dwarf2_cu *cu);
1435
1436 static void read_file_scope (struct die_info *, struct dwarf2_cu *);
1437
1438 static void read_type_unit_scope (struct die_info *, struct dwarf2_cu *);
1439
1440 static void read_func_scope (struct die_info *, struct dwarf2_cu *);
1441
1442 static void read_lexical_block_scope (struct die_info *, struct dwarf2_cu *);
1443
1444 static void read_call_site_scope (struct die_info *die, struct dwarf2_cu *cu);
1445
1446 static int dwarf2_ranges_read (unsigned, CORE_ADDR *, CORE_ADDR *,
1447                                struct dwarf2_cu *, struct partial_symtab *);
1448
1449 static int dwarf2_get_pc_bounds (struct die_info *,
1450                                  CORE_ADDR *, CORE_ADDR *, struct dwarf2_cu *,
1451                                  struct partial_symtab *);
1452
1453 static void get_scope_pc_bounds (struct die_info *,
1454                                  CORE_ADDR *, CORE_ADDR *,
1455                                  struct dwarf2_cu *);
1456
1457 static void dwarf2_record_block_ranges (struct die_info *, struct block *,
1458                                         CORE_ADDR, struct dwarf2_cu *);
1459
1460 static void dwarf2_add_field (struct field_info *, struct die_info *,
1461                               struct dwarf2_cu *);
1462
1463 static void dwarf2_attach_fields_to_type (struct field_info *,
1464                                           struct type *, struct dwarf2_cu *);
1465
1466 static void dwarf2_add_member_fn (struct field_info *,
1467                                   struct die_info *, struct type *,
1468                                   struct dwarf2_cu *);
1469
1470 static void dwarf2_attach_fn_fields_to_type (struct field_info *,
1471                                              struct type *,
1472                                              struct dwarf2_cu *);
1473
1474 static void process_structure_scope (struct die_info *, struct dwarf2_cu *);
1475
1476 static void read_common_block (struct die_info *, struct dwarf2_cu *);
1477
1478 static void read_namespace (struct die_info *die, struct dwarf2_cu *);
1479
1480 static void read_module (struct die_info *die, struct dwarf2_cu *cu);
1481
1482 static void read_import_statement (struct die_info *die, struct dwarf2_cu *);
1483
1484 static struct type *read_module_type (struct die_info *die,
1485                                       struct dwarf2_cu *cu);
1486
1487 static const char *namespace_name (struct die_info *die,
1488                                    int *is_anonymous, struct dwarf2_cu *);
1489
1490 static void process_enumeration_scope (struct die_info *, struct dwarf2_cu *);
1491
1492 static CORE_ADDR decode_locdesc (struct dwarf_block *, struct dwarf2_cu *);
1493
1494 static enum dwarf_array_dim_ordering read_array_order (struct die_info *,
1495                                                        struct dwarf2_cu *);
1496
1497 static struct die_info *read_die_and_siblings_1
1498   (const struct die_reader_specs *, const gdb_byte *, const gdb_byte **,
1499    struct die_info *);
1500
1501 static struct die_info *read_die_and_siblings (const struct die_reader_specs *,
1502                                                const gdb_byte *info_ptr,
1503                                                const gdb_byte **new_info_ptr,
1504                                                struct die_info *parent);
1505
1506 static const gdb_byte *read_full_die_1 (const struct die_reader_specs *,
1507                                         struct die_info **, const gdb_byte *,
1508                                         int *, int);
1509
1510 static const gdb_byte *read_full_die (const struct die_reader_specs *,
1511                                       struct die_info **, const gdb_byte *,
1512                                       int *);
1513
1514 static void process_die (struct die_info *, struct dwarf2_cu *);
1515
1516 static const char *dwarf2_canonicalize_name (const char *, struct dwarf2_cu *,
1517                                              struct obstack *);
1518
1519 static const char *dwarf2_name (struct die_info *die, struct dwarf2_cu *);
1520
1521 static const char *dwarf2_full_name (const char *name,
1522                                      struct die_info *die,
1523                                      struct dwarf2_cu *cu);
1524
1525 static const char *dwarf2_physname (const char *name, struct die_info *die,
1526                                     struct dwarf2_cu *cu);
1527
1528 static struct die_info *dwarf2_extension (struct die_info *die,
1529                                           struct dwarf2_cu **);
1530
1531 static const char *dwarf_tag_name (unsigned int);
1532
1533 static const char *dwarf_attr_name (unsigned int);
1534
1535 static const char *dwarf_form_name (unsigned int);
1536
1537 static char *dwarf_bool_name (unsigned int);
1538
1539 static const char *dwarf_type_encoding_name (unsigned int);
1540
1541 static struct die_info *sibling_die (struct die_info *);
1542
1543 static void dump_die_shallow (struct ui_file *, int indent, struct die_info *);
1544
1545 static void dump_die_for_error (struct die_info *);
1546
1547 static void dump_die_1 (struct ui_file *, int level, int max_level,
1548                         struct die_info *);
1549
1550 /*static*/ void dump_die (struct die_info *, int max_level);
1551
1552 static void store_in_ref_table (struct die_info *,
1553                                 struct dwarf2_cu *);
1554
1555 static sect_offset dwarf2_get_ref_die_offset (const struct attribute *);
1556
1557 static LONGEST dwarf2_get_attr_constant_value (const struct attribute *, int);
1558
1559 static struct die_info *follow_die_ref_or_sig (struct die_info *,
1560                                                const struct attribute *,
1561                                                struct dwarf2_cu **);
1562
1563 static struct die_info *follow_die_ref (struct die_info *,
1564                                         const struct attribute *,
1565                                         struct dwarf2_cu **);
1566
1567 static struct die_info *follow_die_sig (struct die_info *,
1568                                         const struct attribute *,
1569                                         struct dwarf2_cu **);
1570
1571 static struct type *get_signatured_type (struct die_info *, ULONGEST,
1572                                          struct dwarf2_cu *);
1573
1574 static struct type *get_DW_AT_signature_type (struct die_info *,
1575                                               const struct attribute *,
1576                                               struct dwarf2_cu *);
1577
1578 static void load_full_type_unit (struct dwarf2_per_cu_data *per_cu);
1579
1580 static void read_signatured_type (struct signatured_type *);
1581
1582 static struct type_unit_group *get_type_unit_group
1583     (struct dwarf2_cu *, const struct attribute *);
1584
1585 static void build_type_unit_groups (die_reader_func_ftype *, void *);
1586
1587 /* memory allocation interface */
1588
1589 static struct dwarf_block *dwarf_alloc_block (struct dwarf2_cu *);
1590
1591 static struct die_info *dwarf_alloc_die (struct dwarf2_cu *, int);
1592
1593 static void dwarf_decode_macros (struct dwarf2_cu *, unsigned int,
1594                                  const char *, int);
1595
1596 static int attr_form_is_block (const struct attribute *);
1597
1598 static int attr_form_is_section_offset (const struct attribute *);
1599
1600 static int attr_form_is_constant (const struct attribute *);
1601
1602 static int attr_form_is_ref (const struct attribute *);
1603
1604 static void fill_in_loclist_baton (struct dwarf2_cu *cu,
1605                                    struct dwarf2_loclist_baton *baton,
1606                                    const struct attribute *attr);
1607
1608 static void dwarf2_symbol_mark_computed (const struct attribute *attr,
1609                                          struct symbol *sym,
1610                                          struct dwarf2_cu *cu,
1611                                          int is_block);
1612
1613 static const gdb_byte *skip_one_die (const struct die_reader_specs *reader,
1614                                      const gdb_byte *info_ptr,
1615                                      struct abbrev_info *abbrev);
1616
1617 static void free_stack_comp_unit (void *);
1618
1619 static hashval_t partial_die_hash (const void *item);
1620
1621 static int partial_die_eq (const void *item_lhs, const void *item_rhs);
1622
1623 static struct dwarf2_per_cu_data *dwarf2_find_containing_comp_unit
1624   (sect_offset offset, unsigned int offset_in_dwz, struct objfile *objfile);
1625
1626 static void init_one_comp_unit (struct dwarf2_cu *cu,
1627                                 struct dwarf2_per_cu_data *per_cu);
1628
1629 static void prepare_one_comp_unit (struct dwarf2_cu *cu,
1630                                    struct die_info *comp_unit_die,
1631                                    enum language pretend_language);
1632
1633 static void free_heap_comp_unit (void *);
1634
1635 static void free_cached_comp_units (void *);
1636
1637 static void age_cached_comp_units (void);
1638
1639 static void free_one_cached_comp_unit (struct dwarf2_per_cu_data *);
1640
1641 static struct type *set_die_type (struct die_info *, struct type *,
1642                                   struct dwarf2_cu *);
1643
1644 static void create_all_comp_units (struct objfile *);
1645
1646 static int create_all_type_units (struct objfile *);
1647
1648 static void load_full_comp_unit (struct dwarf2_per_cu_data *,
1649                                  enum language);
1650
1651 static void process_full_comp_unit (struct dwarf2_per_cu_data *,
1652                                     enum language);
1653
1654 static void process_full_type_unit (struct dwarf2_per_cu_data *,
1655                                     enum language);
1656
1657 static void dwarf2_add_dependence (struct dwarf2_cu *,
1658                                    struct dwarf2_per_cu_data *);
1659
1660 static void dwarf2_mark (struct dwarf2_cu *);
1661
1662 static void dwarf2_clear_marks (struct dwarf2_per_cu_data *);
1663
1664 static struct type *get_die_type_at_offset (sect_offset,
1665                                             struct dwarf2_per_cu_data *);
1666
1667 static struct type *get_die_type (struct die_info *die, struct dwarf2_cu *cu);
1668
1669 static void dwarf2_release_queue (void *dummy);
1670
1671 static void queue_comp_unit (struct dwarf2_per_cu_data *per_cu,
1672                              enum language pretend_language);
1673
1674 static void process_queue (void);
1675
1676 static void find_file_and_directory (struct die_info *die,
1677                                      struct dwarf2_cu *cu,
1678                                      const char **name, const char **comp_dir);
1679
1680 static char *file_full_name (int file, struct line_header *lh,
1681                              const char *comp_dir);
1682
1683 static const gdb_byte *read_and_check_comp_unit_head
1684   (struct comp_unit_head *header,
1685    struct dwarf2_section_info *section,
1686    struct dwarf2_section_info *abbrev_section, const gdb_byte *info_ptr,
1687    int is_debug_types_section);
1688
1689 static void init_cutu_and_read_dies
1690   (struct dwarf2_per_cu_data *this_cu, struct abbrev_table *abbrev_table,
1691    int use_existing_cu, int keep,
1692    die_reader_func_ftype *die_reader_func, void *data);
1693
1694 static void init_cutu_and_read_dies_simple
1695   (struct dwarf2_per_cu_data *this_cu,
1696    die_reader_func_ftype *die_reader_func, void *data);
1697
1698 static htab_t allocate_signatured_type_table (struct objfile *objfile);
1699
1700 static htab_t allocate_dwo_unit_table (struct objfile *objfile);
1701
1702 static struct dwo_unit *lookup_dwo_in_dwp
1703   (struct dwp_file *dwp_file, const struct dwp_hash_table *htab,
1704    const char *comp_dir, ULONGEST signature, int is_debug_types);
1705
1706 static struct dwp_file *get_dwp_file (void);
1707
1708 static struct dwo_unit *lookup_dwo_comp_unit
1709   (struct dwarf2_per_cu_data *, const char *, const char *, ULONGEST);
1710
1711 static struct dwo_unit *lookup_dwo_type_unit
1712   (struct signatured_type *, const char *, const char *);
1713
1714 static void queue_and_load_all_dwo_tus (struct dwarf2_per_cu_data *);
1715
1716 static void free_dwo_file_cleanup (void *);
1717
1718 static void process_cu_includes (void);
1719
1720 static void check_producer (struct dwarf2_cu *cu);
1721 \f
1722 /* Various complaints about symbol reading that don't abort the process.  */
1723
1724 static void
1725 dwarf2_statement_list_fits_in_line_number_section_complaint (void)
1726 {
1727   complaint (&symfile_complaints,
1728              _("statement list doesn't fit in .debug_line section"));
1729 }
1730
1731 static void
1732 dwarf2_debug_line_missing_file_complaint (void)
1733 {
1734   complaint (&symfile_complaints,
1735              _(".debug_line section has line data without a file"));
1736 }
1737
1738 static void
1739 dwarf2_debug_line_missing_end_sequence_complaint (void)
1740 {
1741   complaint (&symfile_complaints,
1742              _(".debug_line section has line "
1743                "program sequence without an end"));
1744 }
1745
1746 static void
1747 dwarf2_complex_location_expr_complaint (void)
1748 {
1749   complaint (&symfile_complaints, _("location expression too complex"));
1750 }
1751
1752 static void
1753 dwarf2_const_value_length_mismatch_complaint (const char *arg1, int arg2,
1754                                               int arg3)
1755 {
1756   complaint (&symfile_complaints,
1757              _("const value length mismatch for '%s', got %d, expected %d"),
1758              arg1, arg2, arg3);
1759 }
1760
1761 static void
1762 dwarf2_section_buffer_overflow_complaint (struct dwarf2_section_info *section)
1763 {
1764   complaint (&symfile_complaints,
1765              _("debug info runs off end of %s section"
1766                " [in module %s]"),
1767              section->asection->name,
1768              bfd_get_filename (section->asection->owner));
1769 }
1770
1771 static void
1772 dwarf2_macro_malformed_definition_complaint (const char *arg1)
1773 {
1774   complaint (&symfile_complaints,
1775              _("macro debug info contains a "
1776                "malformed macro definition:\n`%s'"),
1777              arg1);
1778 }
1779
1780 static void
1781 dwarf2_invalid_attrib_class_complaint (const char *arg1, const char *arg2)
1782 {
1783   complaint (&symfile_complaints,
1784              _("invalid attribute class or form for '%s' in '%s'"),
1785              arg1, arg2);
1786 }
1787 \f
1788 #if WORDS_BIGENDIAN
1789
1790 /* Convert VALUE between big- and little-endian.  */
1791 static offset_type
1792 byte_swap (offset_type value)
1793 {
1794   offset_type result;
1795
1796   result = (value & 0xff) << 24;
1797   result |= (value & 0xff00) << 8;
1798   result |= (value & 0xff0000) >> 8;
1799   result |= (value & 0xff000000) >> 24;
1800   return result;
1801 }
1802
1803 #define MAYBE_SWAP(V)  byte_swap (V)
1804
1805 #else
1806 #define MAYBE_SWAP(V) (V)
1807 #endif /* WORDS_BIGENDIAN */
1808
1809 /* The suffix for an index file.  */
1810 #define INDEX_SUFFIX ".gdb-index"
1811
1812 /* Try to locate the sections we need for DWARF 2 debugging
1813    information and return true if we have enough to do something.
1814    NAMES points to the dwarf2 section names, or is NULL if the standard
1815    ELF names are used.  */
1816
1817 int
1818 dwarf2_has_info (struct objfile *objfile,
1819                  const struct dwarf2_debug_sections *names)
1820 {
1821   dwarf2_per_objfile = objfile_data (objfile, dwarf2_objfile_data_key);
1822   if (!dwarf2_per_objfile)
1823     {
1824       /* Initialize per-objfile state.  */
1825       struct dwarf2_per_objfile *data
1826         = obstack_alloc (&objfile->objfile_obstack, sizeof (*data));
1827
1828       memset (data, 0, sizeof (*data));
1829       set_objfile_data (objfile, dwarf2_objfile_data_key, data);
1830       dwarf2_per_objfile = data;
1831
1832       bfd_map_over_sections (objfile->obfd, dwarf2_locate_sections,
1833                              (void *) names);
1834       dwarf2_per_objfile->objfile = objfile;
1835     }
1836   return (dwarf2_per_objfile->info.asection != NULL
1837           && dwarf2_per_objfile->abbrev.asection != NULL);
1838 }
1839
1840 /* When loading sections, we look either for uncompressed section or for
1841    compressed section names.  */
1842
1843 static int
1844 section_is_p (const char *section_name,
1845               const struct dwarf2_section_names *names)
1846 {
1847   if (names->normal != NULL
1848       && strcmp (section_name, names->normal) == 0)
1849     return 1;
1850   if (names->compressed != NULL
1851       && strcmp (section_name, names->compressed) == 0)
1852     return 1;
1853   return 0;
1854 }
1855
1856 /* This function is mapped across the sections and remembers the
1857    offset and size of each of the debugging sections we are interested
1858    in.  */
1859
1860 static void
1861 dwarf2_locate_sections (bfd *abfd, asection *sectp, void *vnames)
1862 {
1863   const struct dwarf2_debug_sections *names;
1864   flagword aflag = bfd_get_section_flags (abfd, sectp);
1865
1866   if (vnames == NULL)
1867     names = &dwarf2_elf_names;
1868   else
1869     names = (const struct dwarf2_debug_sections *) vnames;
1870
1871   if ((aflag & SEC_HAS_CONTENTS) == 0)
1872     {
1873     }
1874   else if (section_is_p (sectp->name, &names->info))
1875     {
1876       dwarf2_per_objfile->info.asection = sectp;
1877       dwarf2_per_objfile->info.size = bfd_get_section_size (sectp);
1878     }
1879   else if (section_is_p (sectp->name, &names->abbrev))
1880     {
1881       dwarf2_per_objfile->abbrev.asection = sectp;
1882       dwarf2_per_objfile->abbrev.size = bfd_get_section_size (sectp);
1883     }
1884   else if (section_is_p (sectp->name, &names->line))
1885     {
1886       dwarf2_per_objfile->line.asection = sectp;
1887       dwarf2_per_objfile->line.size = bfd_get_section_size (sectp);
1888     }
1889   else if (section_is_p (sectp->name, &names->loc))
1890     {
1891       dwarf2_per_objfile->loc.asection = sectp;
1892       dwarf2_per_objfile->loc.size = bfd_get_section_size (sectp);
1893     }
1894   else if (section_is_p (sectp->name, &names->macinfo))
1895     {
1896       dwarf2_per_objfile->macinfo.asection = sectp;
1897       dwarf2_per_objfile->macinfo.size = bfd_get_section_size (sectp);
1898     }
1899   else if (section_is_p (sectp->name, &names->macro))
1900     {
1901       dwarf2_per_objfile->macro.asection = sectp;
1902       dwarf2_per_objfile->macro.size = bfd_get_section_size (sectp);
1903     }
1904   else if (section_is_p (sectp->name, &names->str))
1905     {
1906       dwarf2_per_objfile->str.asection = sectp;
1907       dwarf2_per_objfile->str.size = bfd_get_section_size (sectp);
1908     }
1909   else if (section_is_p (sectp->name, &names->addr))
1910     {
1911       dwarf2_per_objfile->addr.asection = sectp;
1912       dwarf2_per_objfile->addr.size = bfd_get_section_size (sectp);
1913     }
1914   else if (section_is_p (sectp->name, &names->frame))
1915     {
1916       dwarf2_per_objfile->frame.asection = sectp;
1917       dwarf2_per_objfile->frame.size = bfd_get_section_size (sectp);
1918     }
1919   else if (section_is_p (sectp->name, &names->eh_frame))
1920     {
1921       dwarf2_per_objfile->eh_frame.asection = sectp;
1922       dwarf2_per_objfile->eh_frame.size = bfd_get_section_size (sectp);
1923     }
1924   else if (section_is_p (sectp->name, &names->ranges))
1925     {
1926       dwarf2_per_objfile->ranges.asection = sectp;
1927       dwarf2_per_objfile->ranges.size = bfd_get_section_size (sectp);
1928     }
1929   else if (section_is_p (sectp->name, &names->types))
1930     {
1931       struct dwarf2_section_info type_section;
1932
1933       memset (&type_section, 0, sizeof (type_section));
1934       type_section.asection = sectp;
1935       type_section.size = bfd_get_section_size (sectp);
1936
1937       VEC_safe_push (dwarf2_section_info_def, dwarf2_per_objfile->types,
1938                      &type_section);
1939     }
1940   else if (section_is_p (sectp->name, &names->gdb_index))
1941     {
1942       dwarf2_per_objfile->gdb_index.asection = sectp;
1943       dwarf2_per_objfile->gdb_index.size = bfd_get_section_size (sectp);
1944     }
1945
1946   if ((bfd_get_section_flags (abfd, sectp) & SEC_LOAD)
1947       && bfd_section_vma (abfd, sectp) == 0)
1948     dwarf2_per_objfile->has_section_at_zero = 1;
1949 }
1950
1951 /* A helper function that decides whether a section is empty,
1952    or not present.  */
1953
1954 static int
1955 dwarf2_section_empty_p (struct dwarf2_section_info *info)
1956 {
1957   return info->asection == NULL || info->size == 0;
1958 }
1959
1960 /* Read the contents of the section INFO.
1961    OBJFILE is the main object file, but not necessarily the file where
1962    the section comes from.  E.g., for DWO files INFO->asection->owner
1963    is the bfd of the DWO file.
1964    If the section is compressed, uncompress it before returning.  */
1965
1966 static void
1967 dwarf2_read_section (struct objfile *objfile, struct dwarf2_section_info *info)
1968 {
1969   asection *sectp = info->asection;
1970   bfd *abfd;
1971   gdb_byte *buf, *retbuf;
1972   unsigned char header[4];
1973
1974   if (info->readin)
1975     return;
1976   info->buffer = NULL;
1977   info->readin = 1;
1978
1979   if (dwarf2_section_empty_p (info))
1980     return;
1981
1982   abfd = sectp->owner;
1983
1984   /* If the section has relocations, we must read it ourselves.
1985      Otherwise we attach it to the BFD.  */
1986   if ((sectp->flags & SEC_RELOC) == 0)
1987     {
1988       info->buffer = gdb_bfd_map_section (sectp, &info->size);
1989       return;
1990     }
1991
1992   buf = obstack_alloc (&objfile->objfile_obstack, info->size);
1993   info->buffer = buf;
1994
1995   /* When debugging .o files, we may need to apply relocations; see
1996      http://sourceware.org/ml/gdb-patches/2002-04/msg00136.html .
1997      We never compress sections in .o files, so we only need to
1998      try this when the section is not compressed.  */
1999   retbuf = symfile_relocate_debug_section (objfile, sectp, buf);
2000   if (retbuf != NULL)
2001     {
2002       info->buffer = retbuf;
2003       return;
2004     }
2005
2006   if (bfd_seek (abfd, sectp->filepos, SEEK_SET) != 0
2007       || bfd_bread (buf, info->size, abfd) != info->size)
2008     error (_("Dwarf Error: Can't read DWARF data from '%s'"),
2009            bfd_get_filename (abfd));
2010 }
2011
2012 /* A helper function that returns the size of a section in a safe way.
2013    If you are positive that the section has been read before using the
2014    size, then it is safe to refer to the dwarf2_section_info object's
2015    "size" field directly.  In other cases, you must call this
2016    function, because for compressed sections the size field is not set
2017    correctly until the section has been read.  */
2018
2019 static bfd_size_type
2020 dwarf2_section_size (struct objfile *objfile,
2021                      struct dwarf2_section_info *info)
2022 {
2023   if (!info->readin)
2024     dwarf2_read_section (objfile, info);
2025   return info->size;
2026 }
2027
2028 /* Fill in SECTP, BUFP and SIZEP with section info, given OBJFILE and
2029    SECTION_NAME.  */
2030
2031 void
2032 dwarf2_get_section_info (struct objfile *objfile,
2033                          enum dwarf2_section_enum sect,
2034                          asection **sectp, const gdb_byte **bufp,
2035                          bfd_size_type *sizep)
2036 {
2037   struct dwarf2_per_objfile *data
2038     = objfile_data (objfile, dwarf2_objfile_data_key);
2039   struct dwarf2_section_info *info;
2040
2041   /* We may see an objfile without any DWARF, in which case we just
2042      return nothing.  */
2043   if (data == NULL)
2044     {
2045       *sectp = NULL;
2046       *bufp = NULL;
2047       *sizep = 0;
2048       return;
2049     }
2050   switch (sect)
2051     {
2052     case DWARF2_DEBUG_FRAME:
2053       info = &data->frame;
2054       break;
2055     case DWARF2_EH_FRAME:
2056       info = &data->eh_frame;
2057       break;
2058     default:
2059       gdb_assert_not_reached ("unexpected section");
2060     }
2061
2062   dwarf2_read_section (objfile, info);
2063
2064   *sectp = info->asection;
2065   *bufp = info->buffer;
2066   *sizep = info->size;
2067 }
2068
2069 /* A helper function to find the sections for a .dwz file.  */
2070
2071 static void
2072 locate_dwz_sections (bfd *abfd, asection *sectp, void *arg)
2073 {
2074   struct dwz_file *dwz_file = arg;
2075
2076   /* Note that we only support the standard ELF names, because .dwz
2077      is ELF-only (at the time of writing).  */
2078   if (section_is_p (sectp->name, &dwarf2_elf_names.abbrev))
2079     {
2080       dwz_file->abbrev.asection = sectp;
2081       dwz_file->abbrev.size = bfd_get_section_size (sectp);
2082     }
2083   else if (section_is_p (sectp->name, &dwarf2_elf_names.info))
2084     {
2085       dwz_file->info.asection = sectp;
2086       dwz_file->info.size = bfd_get_section_size (sectp);
2087     }
2088   else if (section_is_p (sectp->name, &dwarf2_elf_names.str))
2089     {
2090       dwz_file->str.asection = sectp;
2091       dwz_file->str.size = bfd_get_section_size (sectp);
2092     }
2093   else if (section_is_p (sectp->name, &dwarf2_elf_names.line))
2094     {
2095       dwz_file->line.asection = sectp;
2096       dwz_file->line.size = bfd_get_section_size (sectp);
2097     }
2098   else if (section_is_p (sectp->name, &dwarf2_elf_names.macro))
2099     {
2100       dwz_file->macro.asection = sectp;
2101       dwz_file->macro.size = bfd_get_section_size (sectp);
2102     }
2103   else if (section_is_p (sectp->name, &dwarf2_elf_names.gdb_index))
2104     {
2105       dwz_file->gdb_index.asection = sectp;
2106       dwz_file->gdb_index.size = bfd_get_section_size (sectp);
2107     }
2108 }
2109
2110 /* Open the separate '.dwz' debug file, if needed.  Return NULL if
2111    there is no .gnu_debugaltlink section in the file.  Error if there
2112    is such a section but the file cannot be found.  */
2113
2114 static struct dwz_file *
2115 dwarf2_get_dwz_file (void)
2116 {
2117   bfd *dwz_bfd;
2118   char *data;
2119   struct cleanup *cleanup;
2120   const char *filename;
2121   struct dwz_file *result;
2122   unsigned long buildid;
2123
2124   if (dwarf2_per_objfile->dwz_file != NULL)
2125     return dwarf2_per_objfile->dwz_file;
2126
2127   bfd_set_error (bfd_error_no_error);
2128   data = bfd_get_alt_debug_link_info (dwarf2_per_objfile->objfile->obfd,
2129                                       &buildid);
2130   if (data == NULL)
2131     {
2132       if (bfd_get_error () == bfd_error_no_error)
2133         return NULL;
2134       error (_("could not read '.gnu_debugaltlink' section: %s"),
2135              bfd_errmsg (bfd_get_error ()));
2136     }
2137   cleanup = make_cleanup (xfree, data);
2138
2139   filename = (const char *) data;
2140   if (!IS_ABSOLUTE_PATH (filename))
2141     {
2142       char *abs = gdb_realpath (objfile_name (dwarf2_per_objfile->objfile));
2143       char *rel;
2144
2145       make_cleanup (xfree, abs);
2146       abs = ldirname (abs);
2147       make_cleanup (xfree, abs);
2148
2149       rel = concat (abs, SLASH_STRING, filename, (char *) NULL);
2150       make_cleanup (xfree, rel);
2151       filename = rel;
2152     }
2153
2154   /* The format is just a NUL-terminated file name, followed by the
2155      build-id.  For now, though, we ignore the build-id.  */
2156   dwz_bfd = gdb_bfd_open (filename, gnutarget, -1);
2157   if (dwz_bfd == NULL)
2158     error (_("could not read '%s': %s"), filename,
2159            bfd_errmsg (bfd_get_error ()));
2160
2161   if (!bfd_check_format (dwz_bfd, bfd_object))
2162     {
2163       gdb_bfd_unref (dwz_bfd);
2164       error (_("file '%s' was not usable: %s"), filename,
2165              bfd_errmsg (bfd_get_error ()));
2166     }
2167
2168   result = OBSTACK_ZALLOC (&dwarf2_per_objfile->objfile->objfile_obstack,
2169                            struct dwz_file);
2170   result->dwz_bfd = dwz_bfd;
2171
2172   bfd_map_over_sections (dwz_bfd, locate_dwz_sections, result);
2173
2174   do_cleanups (cleanup);
2175
2176   dwarf2_per_objfile->dwz_file = result;
2177   return result;
2178 }
2179 \f
2180 /* DWARF quick_symbols_functions support.  */
2181
2182 /* TUs can share .debug_line entries, and there can be a lot more TUs than
2183    unique line tables, so we maintain a separate table of all .debug_line
2184    derived entries to support the sharing.
2185    All the quick functions need is the list of file names.  We discard the
2186    line_header when we're done and don't need to record it here.  */
2187 struct quick_file_names
2188 {
2189   /* The data used to construct the hash key.  */
2190   struct stmt_list_hash hash;
2191
2192   /* The number of entries in file_names, real_names.  */
2193   unsigned int num_file_names;
2194
2195   /* The file names from the line table, after being run through
2196      file_full_name.  */
2197   const char **file_names;
2198
2199   /* The file names from the line table after being run through
2200      gdb_realpath.  These are computed lazily.  */
2201   const char **real_names;
2202 };
2203
2204 /* When using the index (and thus not using psymtabs), each CU has an
2205    object of this type.  This is used to hold information needed by
2206    the various "quick" methods.  */
2207 struct dwarf2_per_cu_quick_data
2208 {
2209   /* The file table.  This can be NULL if there was no file table
2210      or it's currently not read in.
2211      NOTE: This points into dwarf2_per_objfile->quick_file_names_table.  */
2212   struct quick_file_names *file_names;
2213
2214   /* The corresponding symbol table.  This is NULL if symbols for this
2215      CU have not yet been read.  */
2216   struct symtab *symtab;
2217
2218   /* A temporary mark bit used when iterating over all CUs in
2219      expand_symtabs_matching.  */
2220   unsigned int mark : 1;
2221
2222   /* True if we've tried to read the file table and found there isn't one.
2223      There will be no point in trying to read it again next time.  */
2224   unsigned int no_file_data : 1;
2225 };
2226
2227 /* Utility hash function for a stmt_list_hash.  */
2228
2229 static hashval_t
2230 hash_stmt_list_entry (const struct stmt_list_hash *stmt_list_hash)
2231 {
2232   hashval_t v = 0;
2233
2234   if (stmt_list_hash->dwo_unit != NULL)
2235     v += (uintptr_t) stmt_list_hash->dwo_unit->dwo_file;
2236   v += stmt_list_hash->line_offset.sect_off;
2237   return v;
2238 }
2239
2240 /* Utility equality function for a stmt_list_hash.  */
2241
2242 static int
2243 eq_stmt_list_entry (const struct stmt_list_hash *lhs,
2244                     const struct stmt_list_hash *rhs)
2245 {
2246   if ((lhs->dwo_unit != NULL) != (rhs->dwo_unit != NULL))
2247     return 0;
2248   if (lhs->dwo_unit != NULL
2249       && lhs->dwo_unit->dwo_file != rhs->dwo_unit->dwo_file)
2250     return 0;
2251
2252   return lhs->line_offset.sect_off == rhs->line_offset.sect_off;
2253 }
2254
2255 /* Hash function for a quick_file_names.  */
2256
2257 static hashval_t
2258 hash_file_name_entry (const void *e)
2259 {
2260   const struct quick_file_names *file_data = e;
2261
2262   return hash_stmt_list_entry (&file_data->hash);
2263 }
2264
2265 /* Equality function for a quick_file_names.  */
2266
2267 static int
2268 eq_file_name_entry (const void *a, const void *b)
2269 {
2270   const struct quick_file_names *ea = a;
2271   const struct quick_file_names *eb = b;
2272
2273   return eq_stmt_list_entry (&ea->hash, &eb->hash);
2274 }
2275
2276 /* Delete function for a quick_file_names.  */
2277
2278 static void
2279 delete_file_name_entry (void *e)
2280 {
2281   struct quick_file_names *file_data = e;
2282   int i;
2283
2284   for (i = 0; i < file_data->num_file_names; ++i)
2285     {
2286       xfree ((void*) file_data->file_names[i]);
2287       if (file_data->real_names)
2288         xfree ((void*) file_data->real_names[i]);
2289     }
2290
2291   /* The space for the struct itself lives on objfile_obstack,
2292      so we don't free it here.  */
2293 }
2294
2295 /* Create a quick_file_names hash table.  */
2296
2297 static htab_t
2298 create_quick_file_names_table (unsigned int nr_initial_entries)
2299 {
2300   return htab_create_alloc (nr_initial_entries,
2301                             hash_file_name_entry, eq_file_name_entry,
2302                             delete_file_name_entry, xcalloc, xfree);
2303 }
2304
2305 /* Read in PER_CU->CU.  This function is unrelated to symtabs, symtab would
2306    have to be created afterwards.  You should call age_cached_comp_units after
2307    processing PER_CU->CU.  dw2_setup must have been already called.  */
2308
2309 static void
2310 load_cu (struct dwarf2_per_cu_data *per_cu)
2311 {
2312   if (per_cu->is_debug_types)
2313     load_full_type_unit (per_cu);
2314   else
2315     load_full_comp_unit (per_cu, language_minimal);
2316
2317   gdb_assert (per_cu->cu != NULL);
2318
2319   dwarf2_find_base_address (per_cu->cu->dies, per_cu->cu);
2320 }
2321
2322 /* Read in the symbols for PER_CU.  */
2323
2324 static void
2325 dw2_do_instantiate_symtab (struct dwarf2_per_cu_data *per_cu)
2326 {
2327   struct cleanup *back_to;
2328
2329   /* Skip type_unit_groups, reading the type units they contain
2330      is handled elsewhere.  */
2331   if (IS_TYPE_UNIT_GROUP (per_cu))
2332     return;
2333
2334   back_to = make_cleanup (dwarf2_release_queue, NULL);
2335
2336   if (dwarf2_per_objfile->using_index
2337       ? per_cu->v.quick->symtab == NULL
2338       : (per_cu->v.psymtab == NULL || !per_cu->v.psymtab->readin))
2339     {
2340       queue_comp_unit (per_cu, language_minimal);
2341       load_cu (per_cu);
2342
2343       /* If we just loaded a CU from a DWO, and we're working with an index
2344          that may badly handle TUs, load all the TUs in that DWO as well.
2345          http://sourceware.org/bugzilla/show_bug.cgi?id=15021  */
2346       if (!per_cu->is_debug_types
2347           && per_cu->cu->dwo_unit != NULL
2348           && dwarf2_per_objfile->index_table != NULL
2349           && dwarf2_per_objfile->index_table->version <= 7
2350           /* DWP files aren't supported yet.  */
2351           && get_dwp_file () == NULL)
2352         queue_and_load_all_dwo_tus (per_cu);
2353     }
2354
2355   process_queue ();
2356
2357   /* Age the cache, releasing compilation units that have not
2358      been used recently.  */
2359   age_cached_comp_units ();
2360
2361   do_cleanups (back_to);
2362 }
2363
2364 /* Ensure that the symbols for PER_CU have been read in.  OBJFILE is
2365    the objfile from which this CU came.  Returns the resulting symbol
2366    table.  */
2367
2368 static struct symtab *
2369 dw2_instantiate_symtab (struct dwarf2_per_cu_data *per_cu)
2370 {
2371   gdb_assert (dwarf2_per_objfile->using_index);
2372   if (!per_cu->v.quick->symtab)
2373     {
2374       struct cleanup *back_to = make_cleanup (free_cached_comp_units, NULL);
2375       increment_reading_symtab ();
2376       dw2_do_instantiate_symtab (per_cu);
2377       process_cu_includes ();
2378       do_cleanups (back_to);
2379     }
2380   return per_cu->v.quick->symtab;
2381 }
2382
2383 /* Return the CU given its index.
2384
2385    This is intended for loops like:
2386
2387    for (i = 0; i < (dwarf2_per_objfile->n_comp_units
2388                     + dwarf2_per_objfile->n_type_units); ++i)
2389      {
2390        struct dwarf2_per_cu_data *per_cu = dw2_get_cu (i);
2391
2392        ...;
2393      }
2394 */
2395
2396 static struct dwarf2_per_cu_data *
2397 dw2_get_cu (int index)
2398 {
2399   if (index >= dwarf2_per_objfile->n_comp_units)
2400     {
2401       index -= dwarf2_per_objfile->n_comp_units;
2402       gdb_assert (index < dwarf2_per_objfile->n_type_units);
2403       return &dwarf2_per_objfile->all_type_units[index]->per_cu;
2404     }
2405
2406   return dwarf2_per_objfile->all_comp_units[index];
2407 }
2408
2409 /* Return the primary CU given its index.
2410    The difference between this function and dw2_get_cu is in the handling
2411    of type units (TUs).  Here we return the type_unit_group object.
2412
2413    This is intended for loops like:
2414
2415    for (i = 0; i < (dwarf2_per_objfile->n_comp_units
2416                     + dwarf2_per_objfile->n_type_unit_groups); ++i)
2417      {
2418        struct dwarf2_per_cu_data *per_cu = dw2_get_primary_cu (i);
2419
2420        ...;
2421      }
2422 */
2423
2424 static struct dwarf2_per_cu_data *
2425 dw2_get_primary_cu (int index)
2426 {
2427   if (index >= dwarf2_per_objfile->n_comp_units)
2428     {
2429       index -= dwarf2_per_objfile->n_comp_units;
2430       gdb_assert (index < dwarf2_per_objfile->n_type_unit_groups);
2431       return &dwarf2_per_objfile->all_type_unit_groups[index]->per_cu;
2432     }
2433
2434   return dwarf2_per_objfile->all_comp_units[index];
2435 }
2436
2437 /* A helper for create_cus_from_index that handles a given list of
2438    CUs.  */
2439
2440 static void
2441 create_cus_from_index_list (struct objfile *objfile,
2442                             const gdb_byte *cu_list, offset_type n_elements,
2443                             struct dwarf2_section_info *section,
2444                             int is_dwz,
2445                             int base_offset)
2446 {
2447   offset_type i;
2448
2449   for (i = 0; i < n_elements; i += 2)
2450     {
2451       struct dwarf2_per_cu_data *the_cu;
2452       ULONGEST offset, length;
2453
2454       gdb_static_assert (sizeof (ULONGEST) >= 8);
2455       offset = extract_unsigned_integer (cu_list, 8, BFD_ENDIAN_LITTLE);
2456       length = extract_unsigned_integer (cu_list + 8, 8, BFD_ENDIAN_LITTLE);
2457       cu_list += 2 * 8;
2458
2459       the_cu = OBSTACK_ZALLOC (&objfile->objfile_obstack,
2460                                struct dwarf2_per_cu_data);
2461       the_cu->offset.sect_off = offset;
2462       the_cu->length = length;
2463       the_cu->objfile = objfile;
2464       the_cu->section = section;
2465       the_cu->v.quick = OBSTACK_ZALLOC (&objfile->objfile_obstack,
2466                                         struct dwarf2_per_cu_quick_data);
2467       the_cu->is_dwz = is_dwz;
2468       dwarf2_per_objfile->all_comp_units[base_offset + i / 2] = the_cu;
2469     }
2470 }
2471
2472 /* Read the CU list from the mapped index, and use it to create all
2473    the CU objects for this objfile.  */
2474
2475 static void
2476 create_cus_from_index (struct objfile *objfile,
2477                        const gdb_byte *cu_list, offset_type cu_list_elements,
2478                        const gdb_byte *dwz_list, offset_type dwz_elements)
2479 {
2480   struct dwz_file *dwz;
2481
2482   dwarf2_per_objfile->n_comp_units = (cu_list_elements + dwz_elements) / 2;
2483   dwarf2_per_objfile->all_comp_units
2484     = obstack_alloc (&objfile->objfile_obstack,
2485                      dwarf2_per_objfile->n_comp_units
2486                      * sizeof (struct dwarf2_per_cu_data *));
2487
2488   create_cus_from_index_list (objfile, cu_list, cu_list_elements,
2489                               &dwarf2_per_objfile->info, 0, 0);
2490
2491   if (dwz_elements == 0)
2492     return;
2493
2494   dwz = dwarf2_get_dwz_file ();
2495   create_cus_from_index_list (objfile, dwz_list, dwz_elements, &dwz->info, 1,
2496                               cu_list_elements / 2);
2497 }
2498
2499 /* Create the signatured type hash table from the index.  */
2500
2501 static void
2502 create_signatured_type_table_from_index (struct objfile *objfile,
2503                                          struct dwarf2_section_info *section,
2504                                          const gdb_byte *bytes,
2505                                          offset_type elements)
2506 {
2507   offset_type i;
2508   htab_t sig_types_hash;
2509
2510   dwarf2_per_objfile->n_type_units = elements / 3;
2511   dwarf2_per_objfile->all_type_units
2512     = xmalloc (dwarf2_per_objfile->n_type_units
2513                * sizeof (struct signatured_type *));
2514
2515   sig_types_hash = allocate_signatured_type_table (objfile);
2516
2517   for (i = 0; i < elements; i += 3)
2518     {
2519       struct signatured_type *sig_type;
2520       ULONGEST offset, type_offset_in_tu, signature;
2521       void **slot;
2522
2523       gdb_static_assert (sizeof (ULONGEST) >= 8);
2524       offset = extract_unsigned_integer (bytes, 8, BFD_ENDIAN_LITTLE);
2525       type_offset_in_tu = extract_unsigned_integer (bytes + 8, 8,
2526                                                     BFD_ENDIAN_LITTLE);
2527       signature = extract_unsigned_integer (bytes + 16, 8, BFD_ENDIAN_LITTLE);
2528       bytes += 3 * 8;
2529
2530       sig_type = OBSTACK_ZALLOC (&objfile->objfile_obstack,
2531                                  struct signatured_type);
2532       sig_type->signature = signature;
2533       sig_type->type_offset_in_tu.cu_off = type_offset_in_tu;
2534       sig_type->per_cu.is_debug_types = 1;
2535       sig_type->per_cu.section = section;
2536       sig_type->per_cu.offset.sect_off = offset;
2537       sig_type->per_cu.objfile = objfile;
2538       sig_type->per_cu.v.quick
2539         = OBSTACK_ZALLOC (&objfile->objfile_obstack,
2540                           struct dwarf2_per_cu_quick_data);
2541
2542       slot = htab_find_slot (sig_types_hash, sig_type, INSERT);
2543       *slot = sig_type;
2544
2545       dwarf2_per_objfile->all_type_units[i / 3] = sig_type;
2546     }
2547
2548   dwarf2_per_objfile->signatured_types = sig_types_hash;
2549 }
2550
2551 /* Read the address map data from the mapped index, and use it to
2552    populate the objfile's psymtabs_addrmap.  */
2553
2554 static void
2555 create_addrmap_from_index (struct objfile *objfile, struct mapped_index *index)
2556 {
2557   const gdb_byte *iter, *end;
2558   struct obstack temp_obstack;
2559   struct addrmap *mutable_map;
2560   struct cleanup *cleanup;
2561   CORE_ADDR baseaddr;
2562
2563   obstack_init (&temp_obstack);
2564   cleanup = make_cleanup_obstack_free (&temp_obstack);
2565   mutable_map = addrmap_create_mutable (&temp_obstack);
2566
2567   iter = index->address_table;
2568   end = iter + index->address_table_size;
2569
2570   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
2571
2572   while (iter < end)
2573     {
2574       ULONGEST hi, lo, cu_index;
2575       lo = extract_unsigned_integer (iter, 8, BFD_ENDIAN_LITTLE);
2576       iter += 8;
2577       hi = extract_unsigned_integer (iter, 8, BFD_ENDIAN_LITTLE);
2578       iter += 8;
2579       cu_index = extract_unsigned_integer (iter, 4, BFD_ENDIAN_LITTLE);
2580       iter += 4;
2581
2582       if (lo > hi)
2583         {
2584           complaint (&symfile_complaints,
2585                      _(".gdb_index address table has invalid range (%s - %s)"),
2586                      hex_string (lo), hex_string (hi));
2587           continue;
2588         }
2589
2590       if (cu_index >= dwarf2_per_objfile->n_comp_units)
2591         {
2592           complaint (&symfile_complaints,
2593                      _(".gdb_index address table has invalid CU number %u"),
2594                      (unsigned) cu_index);
2595           continue;
2596         }
2597
2598       addrmap_set_empty (mutable_map, lo + baseaddr, hi + baseaddr - 1,
2599                          dw2_get_cu (cu_index));
2600     }
2601
2602   objfile->psymtabs_addrmap = addrmap_create_fixed (mutable_map,
2603                                                     &objfile->objfile_obstack);
2604   do_cleanups (cleanup);
2605 }
2606
2607 /* The hash function for strings in the mapped index.  This is the same as
2608    SYMBOL_HASH_NEXT, but we keep a separate copy to maintain control over the
2609    implementation.  This is necessary because the hash function is tied to the
2610    format of the mapped index file.  The hash values do not have to match with
2611    SYMBOL_HASH_NEXT.
2612    
2613    Use INT_MAX for INDEX_VERSION if you generate the current index format.  */
2614
2615 static hashval_t
2616 mapped_index_string_hash (int index_version, const void *p)
2617 {
2618   const unsigned char *str = (const unsigned char *) p;
2619   hashval_t r = 0;
2620   unsigned char c;
2621
2622   while ((c = *str++) != 0)
2623     {
2624       if (index_version >= 5)
2625         c = tolower (c);
2626       r = r * 67 + c - 113;
2627     }
2628
2629   return r;
2630 }
2631
2632 /* Find a slot in the mapped index INDEX for the object named NAME.
2633    If NAME is found, set *VEC_OUT to point to the CU vector in the
2634    constant pool and return 1.  If NAME cannot be found, return 0.  */
2635
2636 static int
2637 find_slot_in_mapped_hash (struct mapped_index *index, const char *name,
2638                           offset_type **vec_out)
2639 {
2640   struct cleanup *back_to = make_cleanup (null_cleanup, 0);
2641   offset_type hash;
2642   offset_type slot, step;
2643   int (*cmp) (const char *, const char *);
2644
2645   if (current_language->la_language == language_cplus
2646       || current_language->la_language == language_java
2647       || current_language->la_language == language_fortran)
2648     {
2649       /* NAME is already canonical.  Drop any qualifiers as .gdb_index does
2650          not contain any.  */
2651       const char *paren = strchr (name, '(');
2652
2653       if (paren)
2654         {
2655           char *dup;
2656
2657           dup = xmalloc (paren - name + 1);
2658           memcpy (dup, name, paren - name);
2659           dup[paren - name] = 0;
2660
2661           make_cleanup (xfree, dup);
2662           name = dup;
2663         }
2664     }
2665
2666   /* Index version 4 did not support case insensitive searches.  But the
2667      indices for case insensitive languages are built in lowercase, therefore
2668      simulate our NAME being searched is also lowercased.  */
2669   hash = mapped_index_string_hash ((index->version == 4
2670                                     && case_sensitivity == case_sensitive_off
2671                                     ? 5 : index->version),
2672                                    name);
2673
2674   slot = hash & (index->symbol_table_slots - 1);
2675   step = ((hash * 17) & (index->symbol_table_slots - 1)) | 1;
2676   cmp = (case_sensitivity == case_sensitive_on ? strcmp : strcasecmp);
2677
2678   for (;;)
2679     {
2680       /* Convert a slot number to an offset into the table.  */
2681       offset_type i = 2 * slot;
2682       const char *str;
2683       if (index->symbol_table[i] == 0 && index->symbol_table[i + 1] == 0)
2684         {
2685           do_cleanups (back_to);
2686           return 0;
2687         }
2688
2689       str = index->constant_pool + MAYBE_SWAP (index->symbol_table[i]);
2690       if (!cmp (name, str))
2691         {
2692           *vec_out = (offset_type *) (index->constant_pool
2693                                       + MAYBE_SWAP (index->symbol_table[i + 1]));
2694           do_cleanups (back_to);
2695           return 1;
2696         }
2697
2698       slot = (slot + step) & (index->symbol_table_slots - 1);
2699     }
2700 }
2701
2702 /* A helper function that reads the .gdb_index from SECTION and fills
2703    in MAP.  FILENAME is the name of the file containing the section;
2704    it is used for error reporting.  DEPRECATED_OK is nonzero if it is
2705    ok to use deprecated sections.
2706
2707    CU_LIST, CU_LIST_ELEMENTS, TYPES_LIST, and TYPES_LIST_ELEMENTS are
2708    out parameters that are filled in with information about the CU and
2709    TU lists in the section.
2710
2711    Returns 1 if all went well, 0 otherwise.  */
2712
2713 static int
2714 read_index_from_section (struct objfile *objfile,
2715                          const char *filename,
2716                          int deprecated_ok,
2717                          struct dwarf2_section_info *section,
2718                          struct mapped_index *map,
2719                          const gdb_byte **cu_list,
2720                          offset_type *cu_list_elements,
2721                          const gdb_byte **types_list,
2722                          offset_type *types_list_elements)
2723 {
2724   const gdb_byte *addr;
2725   offset_type version;
2726   offset_type *metadata;
2727   int i;
2728
2729   if (dwarf2_section_empty_p (section))
2730     return 0;
2731
2732   /* Older elfutils strip versions could keep the section in the main
2733      executable while splitting it for the separate debug info file.  */
2734   if ((bfd_get_file_flags (section->asection) & SEC_HAS_CONTENTS) == 0)
2735     return 0;
2736
2737   dwarf2_read_section (objfile, section);
2738
2739   addr = section->buffer;
2740   /* Version check.  */
2741   version = MAYBE_SWAP (*(offset_type *) addr);
2742   /* Versions earlier than 3 emitted every copy of a psymbol.  This
2743      causes the index to behave very poorly for certain requests.  Version 3
2744      contained incomplete addrmap.  So, it seems better to just ignore such
2745      indices.  */
2746   if (version < 4)
2747     {
2748       static int warning_printed = 0;
2749       if (!warning_printed)
2750         {
2751           warning (_("Skipping obsolete .gdb_index section in %s."),
2752                    filename);
2753           warning_printed = 1;
2754         }
2755       return 0;
2756     }
2757   /* Index version 4 uses a different hash function than index version
2758      5 and later.
2759
2760      Versions earlier than 6 did not emit psymbols for inlined
2761      functions.  Using these files will cause GDB not to be able to
2762      set breakpoints on inlined functions by name, so we ignore these
2763      indices unless the user has done
2764      "set use-deprecated-index-sections on".  */
2765   if (version < 6 && !deprecated_ok)
2766     {
2767       static int warning_printed = 0;
2768       if (!warning_printed)
2769         {
2770           warning (_("\
2771 Skipping deprecated .gdb_index section in %s.\n\
2772 Do \"set use-deprecated-index-sections on\" before the file is read\n\
2773 to use the section anyway."),
2774                    filename);
2775           warning_printed = 1;
2776         }
2777       return 0;
2778     }
2779   /* Version 7 indices generated by gold refer to the CU for a symbol instead
2780      of the TU (for symbols coming from TUs).  It's just a performance bug, and
2781      we can't distinguish gdb-generated indices from gold-generated ones, so
2782      nothing to do here.  */
2783
2784   /* Indexes with higher version than the one supported by GDB may be no
2785      longer backward compatible.  */
2786   if (version > 8)
2787     return 0;
2788
2789   map->version = version;
2790   map->total_size = section->size;
2791
2792   metadata = (offset_type *) (addr + sizeof (offset_type));
2793
2794   i = 0;
2795   *cu_list = addr + MAYBE_SWAP (metadata[i]);
2796   *cu_list_elements = ((MAYBE_SWAP (metadata[i + 1]) - MAYBE_SWAP (metadata[i]))
2797                        / 8);
2798   ++i;
2799
2800   *types_list = addr + MAYBE_SWAP (metadata[i]);
2801   *types_list_elements = ((MAYBE_SWAP (metadata[i + 1])
2802                            - MAYBE_SWAP (metadata[i]))
2803                           / 8);
2804   ++i;
2805
2806   map->address_table = addr + MAYBE_SWAP (metadata[i]);
2807   map->address_table_size = (MAYBE_SWAP (metadata[i + 1])
2808                              - MAYBE_SWAP (metadata[i]));
2809   ++i;
2810
2811   map->symbol_table = (offset_type *) (addr + MAYBE_SWAP (metadata[i]));
2812   map->symbol_table_slots = ((MAYBE_SWAP (metadata[i + 1])
2813                               - MAYBE_SWAP (metadata[i]))
2814                              / (2 * sizeof (offset_type)));
2815   ++i;
2816
2817   map->constant_pool = (char *) (addr + MAYBE_SWAP (metadata[i]));
2818
2819   return 1;
2820 }
2821
2822
2823 /* Read the index file.  If everything went ok, initialize the "quick"
2824    elements of all the CUs and return 1.  Otherwise, return 0.  */
2825
2826 static int
2827 dwarf2_read_index (struct objfile *objfile)
2828 {
2829   struct mapped_index local_map, *map;
2830   const gdb_byte *cu_list, *types_list, *dwz_list = NULL;
2831   offset_type cu_list_elements, types_list_elements, dwz_list_elements = 0;
2832   struct dwz_file *dwz;
2833
2834   if (!read_index_from_section (objfile, objfile_name (objfile),
2835                                 use_deprecated_index_sections,
2836                                 &dwarf2_per_objfile->gdb_index, &local_map,
2837                                 &cu_list, &cu_list_elements,
2838                                 &types_list, &types_list_elements))
2839     return 0;
2840
2841   /* Don't use the index if it's empty.  */
2842   if (local_map.symbol_table_slots == 0)
2843     return 0;
2844
2845   /* If there is a .dwz file, read it so we can get its CU list as
2846      well.  */
2847   dwz = dwarf2_get_dwz_file ();
2848   if (dwz != NULL)
2849     {
2850       struct mapped_index dwz_map;
2851       const gdb_byte *dwz_types_ignore;
2852       offset_type dwz_types_elements_ignore;
2853
2854       if (!read_index_from_section (objfile, bfd_get_filename (dwz->dwz_bfd),
2855                                     1,
2856                                     &dwz->gdb_index, &dwz_map,
2857                                     &dwz_list, &dwz_list_elements,
2858                                     &dwz_types_ignore,
2859                                     &dwz_types_elements_ignore))
2860         {
2861           warning (_("could not read '.gdb_index' section from %s; skipping"),
2862                    bfd_get_filename (dwz->dwz_bfd));
2863           return 0;
2864         }
2865     }
2866
2867   create_cus_from_index (objfile, cu_list, cu_list_elements, dwz_list,
2868                          dwz_list_elements);
2869
2870   if (types_list_elements)
2871     {
2872       struct dwarf2_section_info *section;
2873
2874       /* We can only handle a single .debug_types when we have an
2875          index.  */
2876       if (VEC_length (dwarf2_section_info_def, dwarf2_per_objfile->types) != 1)
2877         return 0;
2878
2879       section = VEC_index (dwarf2_section_info_def,
2880                            dwarf2_per_objfile->types, 0);
2881
2882       create_signatured_type_table_from_index (objfile, section, types_list,
2883                                                types_list_elements);
2884     }
2885
2886   create_addrmap_from_index (objfile, &local_map);
2887
2888   map = obstack_alloc (&objfile->objfile_obstack, sizeof (struct mapped_index));
2889   *map = local_map;
2890
2891   dwarf2_per_objfile->index_table = map;
2892   dwarf2_per_objfile->using_index = 1;
2893   dwarf2_per_objfile->quick_file_names_table =
2894     create_quick_file_names_table (dwarf2_per_objfile->n_comp_units);
2895
2896   return 1;
2897 }
2898
2899 /* A helper for the "quick" functions which sets the global
2900    dwarf2_per_objfile according to OBJFILE.  */
2901
2902 static void
2903 dw2_setup (struct objfile *objfile)
2904 {
2905   dwarf2_per_objfile = objfile_data (objfile, dwarf2_objfile_data_key);
2906   gdb_assert (dwarf2_per_objfile);
2907 }
2908
2909 /* die_reader_func for dw2_get_file_names.  */
2910
2911 static void
2912 dw2_get_file_names_reader (const struct die_reader_specs *reader,
2913                            const gdb_byte *info_ptr,
2914                            struct die_info *comp_unit_die,
2915                            int has_children,
2916                            void *data)
2917 {
2918   struct dwarf2_cu *cu = reader->cu;
2919   struct dwarf2_per_cu_data *this_cu = cu->per_cu;  
2920   struct objfile *objfile = dwarf2_per_objfile->objfile;
2921   struct dwarf2_per_cu_data *lh_cu;
2922   struct line_header *lh;
2923   struct attribute *attr;
2924   int i;
2925   const char *name, *comp_dir;
2926   void **slot;
2927   struct quick_file_names *qfn;
2928   unsigned int line_offset;
2929
2930   gdb_assert (! this_cu->is_debug_types);
2931
2932   /* Our callers never want to match partial units -- instead they
2933      will match the enclosing full CU.  */
2934   if (comp_unit_die->tag == DW_TAG_partial_unit)
2935     {
2936       this_cu->v.quick->no_file_data = 1;
2937       return;
2938     }
2939
2940   lh_cu = this_cu;
2941   lh = NULL;
2942   slot = NULL;
2943   line_offset = 0;
2944
2945   attr = dwarf2_attr (comp_unit_die, DW_AT_stmt_list, cu);
2946   if (attr)
2947     {
2948       struct quick_file_names find_entry;
2949
2950       line_offset = DW_UNSND (attr);
2951
2952       /* We may have already read in this line header (TU line header sharing).
2953          If we have we're done.  */
2954       find_entry.hash.dwo_unit = cu->dwo_unit;
2955       find_entry.hash.line_offset.sect_off = line_offset;
2956       slot = htab_find_slot (dwarf2_per_objfile->quick_file_names_table,
2957                              &find_entry, INSERT);
2958       if (*slot != NULL)
2959         {
2960           lh_cu->v.quick->file_names = *slot;
2961           return;
2962         }
2963
2964       lh = dwarf_decode_line_header (line_offset, cu);
2965     }
2966   if (lh == NULL)
2967     {
2968       lh_cu->v.quick->no_file_data = 1;
2969       return;
2970     }
2971
2972   qfn = obstack_alloc (&objfile->objfile_obstack, sizeof (*qfn));
2973   qfn->hash.dwo_unit = cu->dwo_unit;
2974   qfn->hash.line_offset.sect_off = line_offset;
2975   gdb_assert (slot != NULL);
2976   *slot = qfn;
2977
2978   find_file_and_directory (comp_unit_die, cu, &name, &comp_dir);
2979
2980   qfn->num_file_names = lh->num_file_names;
2981   qfn->file_names = obstack_alloc (&objfile->objfile_obstack,
2982                                    lh->num_file_names * sizeof (char *));
2983   for (i = 0; i < lh->num_file_names; ++i)
2984     qfn->file_names[i] = file_full_name (i + 1, lh, comp_dir);
2985   qfn->real_names = NULL;
2986
2987   free_line_header (lh);
2988
2989   lh_cu->v.quick->file_names = qfn;
2990 }
2991
2992 /* A helper for the "quick" functions which attempts to read the line
2993    table for THIS_CU.  */
2994
2995 static struct quick_file_names *
2996 dw2_get_file_names (struct dwarf2_per_cu_data *this_cu)
2997 {
2998   /* This should never be called for TUs.  */
2999   gdb_assert (! this_cu->is_debug_types);
3000   /* Nor type unit groups.  */
3001   gdb_assert (! IS_TYPE_UNIT_GROUP (this_cu));
3002
3003   if (this_cu->v.quick->file_names != NULL)
3004     return this_cu->v.quick->file_names;
3005   /* If we know there is no line data, no point in looking again.  */
3006   if (this_cu->v.quick->no_file_data)
3007     return NULL;
3008
3009   init_cutu_and_read_dies_simple (this_cu, dw2_get_file_names_reader, NULL);
3010
3011   if (this_cu->v.quick->no_file_data)
3012     return NULL;
3013   return this_cu->v.quick->file_names;
3014 }
3015
3016 /* A helper for the "quick" functions which computes and caches the
3017    real path for a given file name from the line table.  */
3018
3019 static const char *
3020 dw2_get_real_path (struct objfile *objfile,
3021                    struct quick_file_names *qfn, int index)
3022 {
3023   if (qfn->real_names == NULL)
3024     qfn->real_names = OBSTACK_CALLOC (&objfile->objfile_obstack,
3025                                       qfn->num_file_names, sizeof (char *));
3026
3027   if (qfn->real_names[index] == NULL)
3028     qfn->real_names[index] = gdb_realpath (qfn->file_names[index]);
3029
3030   return qfn->real_names[index];
3031 }
3032
3033 static struct symtab *
3034 dw2_find_last_source_symtab (struct objfile *objfile)
3035 {
3036   int index;
3037
3038   dw2_setup (objfile);
3039   index = dwarf2_per_objfile->n_comp_units - 1;
3040   return dw2_instantiate_symtab (dw2_get_cu (index));
3041 }
3042
3043 /* Traversal function for dw2_forget_cached_source_info.  */
3044
3045 static int
3046 dw2_free_cached_file_names (void **slot, void *info)
3047 {
3048   struct quick_file_names *file_data = (struct quick_file_names *) *slot;
3049
3050   if (file_data->real_names)
3051     {
3052       int i;
3053
3054       for (i = 0; i < file_data->num_file_names; ++i)
3055         {
3056           xfree ((void*) file_data->real_names[i]);
3057           file_data->real_names[i] = NULL;
3058         }
3059     }
3060
3061   return 1;
3062 }
3063
3064 static void
3065 dw2_forget_cached_source_info (struct objfile *objfile)
3066 {
3067   dw2_setup (objfile);
3068
3069   htab_traverse_noresize (dwarf2_per_objfile->quick_file_names_table,
3070                           dw2_free_cached_file_names, NULL);
3071 }
3072
3073 /* Helper function for dw2_map_symtabs_matching_filename that expands
3074    the symtabs and calls the iterator.  */
3075
3076 static int
3077 dw2_map_expand_apply (struct objfile *objfile,
3078                       struct dwarf2_per_cu_data *per_cu,
3079                       const char *name, const char *real_path,
3080                       int (*callback) (struct symtab *, void *),
3081                       void *data)
3082 {
3083   struct symtab *last_made = objfile->symtabs;
3084
3085   /* Don't visit already-expanded CUs.  */
3086   if (per_cu->v.quick->symtab)
3087     return 0;
3088
3089   /* This may expand more than one symtab, and we want to iterate over
3090      all of them.  */
3091   dw2_instantiate_symtab (per_cu);
3092
3093   return iterate_over_some_symtabs (name, real_path, callback, data,
3094                                     objfile->symtabs, last_made);
3095 }
3096
3097 /* Implementation of the map_symtabs_matching_filename method.  */
3098
3099 static int
3100 dw2_map_symtabs_matching_filename (struct objfile *objfile, const char *name,
3101                                    const char *real_path,
3102                                    int (*callback) (struct symtab *, void *),
3103                                    void *data)
3104 {
3105   int i;
3106   const char *name_basename = lbasename (name);
3107
3108   dw2_setup (objfile);
3109
3110   /* The rule is CUs specify all the files, including those used by
3111      any TU, so there's no need to scan TUs here.  */
3112
3113   for (i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
3114     {
3115       int j;
3116       struct dwarf2_per_cu_data *per_cu = dw2_get_primary_cu (i);
3117       struct quick_file_names *file_data;
3118
3119       /* We only need to look at symtabs not already expanded.  */
3120       if (per_cu->v.quick->symtab)
3121         continue;
3122
3123       file_data = dw2_get_file_names (per_cu);
3124       if (file_data == NULL)
3125         continue;
3126
3127       for (j = 0; j < file_data->num_file_names; ++j)
3128         {
3129           const char *this_name = file_data->file_names[j];
3130           const char *this_real_name;
3131
3132           if (compare_filenames_for_search (this_name, name))
3133             {
3134               if (dw2_map_expand_apply (objfile, per_cu, name, real_path,
3135                                         callback, data))
3136                 return 1;
3137               continue;
3138             }
3139
3140           /* Before we invoke realpath, which can get expensive when many
3141              files are involved, do a quick comparison of the basenames.  */
3142           if (! basenames_may_differ
3143               && FILENAME_CMP (lbasename (this_name), name_basename) != 0)
3144             continue;
3145
3146           this_real_name = dw2_get_real_path (objfile, file_data, j);
3147           if (compare_filenames_for_search (this_real_name, name))
3148             {
3149               if (dw2_map_expand_apply (objfile, per_cu, name, real_path,
3150                                         callback, data))
3151                 return 1;
3152               continue;
3153             }
3154
3155           if (real_path != NULL)
3156             {
3157               gdb_assert (IS_ABSOLUTE_PATH (real_path));
3158               gdb_assert (IS_ABSOLUTE_PATH (name));
3159               if (this_real_name != NULL
3160                   && FILENAME_CMP (real_path, this_real_name) == 0)
3161                 {
3162                   if (dw2_map_expand_apply (objfile, per_cu, name, real_path,
3163                                             callback, data))
3164                     return 1;
3165                   continue;
3166                 }
3167             }
3168         }
3169     }
3170
3171   return 0;
3172 }
3173
3174 /* Struct used to manage iterating over all CUs looking for a symbol.  */
3175
3176 struct dw2_symtab_iterator
3177 {
3178   /* The internalized form of .gdb_index.  */
3179   struct mapped_index *index;
3180   /* If non-zero, only look for symbols that match BLOCK_INDEX.  */
3181   int want_specific_block;
3182   /* One of GLOBAL_BLOCK or STATIC_BLOCK.
3183      Unused if !WANT_SPECIFIC_BLOCK.  */
3184   int block_index;
3185   /* The kind of symbol we're looking for.  */
3186   domain_enum domain;
3187   /* The list of CUs from the index entry of the symbol,
3188      or NULL if not found.  */
3189   offset_type *vec;
3190   /* The next element in VEC to look at.  */
3191   int next;
3192   /* The number of elements in VEC, or zero if there is no match.  */
3193   int length;
3194 };
3195
3196 /* Initialize the index symtab iterator ITER.
3197    If WANT_SPECIFIC_BLOCK is non-zero, only look for symbols
3198    in block BLOCK_INDEX.  Otherwise BLOCK_INDEX is ignored.  */
3199
3200 static void
3201 dw2_symtab_iter_init (struct dw2_symtab_iterator *iter,
3202                       struct mapped_index *index,
3203                       int want_specific_block,
3204                       int block_index,
3205                       domain_enum domain,
3206                       const char *name)
3207 {
3208   iter->index = index;
3209   iter->want_specific_block = want_specific_block;
3210   iter->block_index = block_index;
3211   iter->domain = domain;
3212   iter->next = 0;
3213
3214   if (find_slot_in_mapped_hash (index, name, &iter->vec))
3215     iter->length = MAYBE_SWAP (*iter->vec);
3216   else
3217     {
3218       iter->vec = NULL;
3219       iter->length = 0;
3220     }
3221 }
3222
3223 /* Return the next matching CU or NULL if there are no more.  */
3224
3225 static struct dwarf2_per_cu_data *
3226 dw2_symtab_iter_next (struct dw2_symtab_iterator *iter)
3227 {
3228   for ( ; iter->next < iter->length; ++iter->next)
3229     {
3230       offset_type cu_index_and_attrs =
3231         MAYBE_SWAP (iter->vec[iter->next + 1]);
3232       offset_type cu_index = GDB_INDEX_CU_VALUE (cu_index_and_attrs);
3233       struct dwarf2_per_cu_data *per_cu;
3234       int want_static = iter->block_index != GLOBAL_BLOCK;
3235       /* This value is only valid for index versions >= 7.  */
3236       int is_static = GDB_INDEX_SYMBOL_STATIC_VALUE (cu_index_and_attrs);
3237       gdb_index_symbol_kind symbol_kind =
3238         GDB_INDEX_SYMBOL_KIND_VALUE (cu_index_and_attrs);
3239       /* Only check the symbol attributes if they're present.
3240          Indices prior to version 7 don't record them,
3241          and indices >= 7 may elide them for certain symbols
3242          (gold does this).  */
3243       int attrs_valid =
3244         (iter->index->version >= 7
3245          && symbol_kind != GDB_INDEX_SYMBOL_KIND_NONE);
3246
3247       /* Don't crash on bad data.  */
3248       if (cu_index >= (dwarf2_per_objfile->n_comp_units
3249                        + dwarf2_per_objfile->n_type_units))
3250         {
3251           complaint (&symfile_complaints,
3252                      _(".gdb_index entry has bad CU index"
3253                        " [in module %s]"),
3254                      objfile_name (dwarf2_per_objfile->objfile));
3255           continue;
3256         }
3257
3258       per_cu = dw2_get_cu (cu_index);
3259
3260       /* Skip if already read in.  */
3261       if (per_cu->v.quick->symtab)
3262         continue;
3263
3264       if (attrs_valid
3265           && iter->want_specific_block
3266           && want_static != is_static)
3267         continue;
3268
3269       /* Only check the symbol's kind if it has one.  */
3270       if (attrs_valid)
3271         {
3272           switch (iter->domain)
3273             {
3274             case VAR_DOMAIN:
3275               if (symbol_kind != GDB_INDEX_SYMBOL_KIND_VARIABLE
3276                   && symbol_kind != GDB_INDEX_SYMBOL_KIND_FUNCTION
3277                   /* Some types are also in VAR_DOMAIN.  */
3278                   && symbol_kind != GDB_INDEX_SYMBOL_KIND_TYPE)
3279                 continue;
3280               break;
3281             case STRUCT_DOMAIN:
3282               if (symbol_kind != GDB_INDEX_SYMBOL_KIND_TYPE)
3283                 continue;
3284               break;
3285             case LABEL_DOMAIN:
3286               if (symbol_kind != GDB_INDEX_SYMBOL_KIND_OTHER)
3287                 continue;
3288               break;
3289             default:
3290               break;
3291             }
3292         }
3293
3294       ++iter->next;
3295       return per_cu;
3296     }
3297
3298   return NULL;
3299 }
3300
3301 static struct symtab *
3302 dw2_lookup_symbol (struct objfile *objfile, int block_index,
3303                    const char *name, domain_enum domain)
3304 {
3305   struct symtab *stab_best = NULL;
3306   struct mapped_index *index;
3307
3308   dw2_setup (objfile);
3309
3310   index = dwarf2_per_objfile->index_table;
3311
3312   /* index is NULL if OBJF_READNOW.  */
3313   if (index)
3314     {
3315       struct dw2_symtab_iterator iter;
3316       struct dwarf2_per_cu_data *per_cu;
3317
3318       dw2_symtab_iter_init (&iter, index, 1, block_index, domain, name);
3319
3320       while ((per_cu = dw2_symtab_iter_next (&iter)) != NULL)
3321         {
3322           struct symbol *sym = NULL;
3323           struct symtab *stab = dw2_instantiate_symtab (per_cu);
3324
3325           /* Some caution must be observed with overloaded functions
3326              and methods, since the index will not contain any overload
3327              information (but NAME might contain it).  */
3328           if (stab->primary)
3329             {
3330               struct blockvector *bv = BLOCKVECTOR (stab);
3331               struct block *block = BLOCKVECTOR_BLOCK (bv, block_index);
3332
3333               sym = lookup_block_symbol (block, name, domain);
3334             }
3335
3336           if (sym && strcmp_iw (SYMBOL_SEARCH_NAME (sym), name) == 0)
3337             {
3338               if (!TYPE_IS_OPAQUE (SYMBOL_TYPE (sym)))
3339                 return stab;
3340
3341               stab_best = stab;
3342             }
3343
3344           /* Keep looking through other CUs.  */
3345         }
3346     }
3347
3348   return stab_best;
3349 }
3350
3351 static void
3352 dw2_print_stats (struct objfile *objfile)
3353 {
3354   int i, total, count;
3355
3356   dw2_setup (objfile);
3357   total = dwarf2_per_objfile->n_comp_units + dwarf2_per_objfile->n_type_units;
3358   count = 0;
3359   for (i = 0; i < total; ++i)
3360     {
3361       struct dwarf2_per_cu_data *per_cu = dw2_get_cu (i);
3362
3363       if (!per_cu->v.quick->symtab)
3364         ++count;
3365     }
3366   printf_filtered (_("  Number of read CUs: %d\n"), total - count);
3367   printf_filtered (_("  Number of unread CUs: %d\n"), count);
3368 }
3369
3370 /* This dumps minimal information about the index.
3371    It is called via "mt print objfiles".
3372    One use is to verify .gdb_index has been loaded by the
3373    gdb.dwarf2/gdb-index.exp testcase.  */
3374
3375 static void
3376 dw2_dump (struct objfile *objfile)
3377 {
3378   dw2_setup (objfile);
3379   gdb_assert (dwarf2_per_objfile->using_index);
3380   printf_filtered (".gdb_index:");
3381   if (dwarf2_per_objfile->index_table != NULL)
3382     {
3383       printf_filtered (" version %d\n",
3384                        dwarf2_per_objfile->index_table->version);
3385     }
3386   else
3387     printf_filtered (" faked for \"readnow\"\n");
3388   printf_filtered ("\n");
3389 }
3390
3391 static void
3392 dw2_relocate (struct objfile *objfile,
3393               const struct section_offsets *new_offsets,
3394               const struct section_offsets *delta)
3395 {
3396   /* There's nothing to relocate here.  */
3397 }
3398
3399 static void
3400 dw2_expand_symtabs_for_function (struct objfile *objfile,
3401                                  const char *func_name)
3402 {
3403   struct mapped_index *index;
3404
3405   dw2_setup (objfile);
3406
3407   index = dwarf2_per_objfile->index_table;
3408
3409   /* index is NULL if OBJF_READNOW.  */
3410   if (index)
3411     {
3412       struct dw2_symtab_iterator iter;
3413       struct dwarf2_per_cu_data *per_cu;
3414
3415       /* Note: It doesn't matter what we pass for block_index here.  */
3416       dw2_symtab_iter_init (&iter, index, 0, GLOBAL_BLOCK, VAR_DOMAIN,
3417                             func_name);
3418
3419       while ((per_cu = dw2_symtab_iter_next (&iter)) != NULL)
3420         dw2_instantiate_symtab (per_cu);
3421     }
3422 }
3423
3424 static void
3425 dw2_expand_all_symtabs (struct objfile *objfile)
3426 {
3427   int i;
3428
3429   dw2_setup (objfile);
3430
3431   for (i = 0; i < (dwarf2_per_objfile->n_comp_units
3432                    + dwarf2_per_objfile->n_type_units); ++i)
3433     {
3434       struct dwarf2_per_cu_data *per_cu = dw2_get_cu (i);
3435
3436       dw2_instantiate_symtab (per_cu);
3437     }
3438 }
3439
3440 static void
3441 dw2_expand_symtabs_with_fullname (struct objfile *objfile,
3442                                   const char *fullname)
3443 {
3444   int i;
3445
3446   dw2_setup (objfile);
3447
3448   /* We don't need to consider type units here.
3449      This is only called for examining code, e.g. expand_line_sal.
3450      There can be an order of magnitude (or more) more type units
3451      than comp units, and we avoid them if we can.  */
3452
3453   for (i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
3454     {
3455       int j;
3456       struct dwarf2_per_cu_data *per_cu = dw2_get_cu (i);
3457       struct quick_file_names *file_data;
3458
3459       /* We only need to look at symtabs not already expanded.  */
3460       if (per_cu->v.quick->symtab)
3461         continue;
3462
3463       file_data = dw2_get_file_names (per_cu);
3464       if (file_data == NULL)
3465         continue;
3466
3467       for (j = 0; j < file_data->num_file_names; ++j)
3468         {
3469           const char *this_fullname = file_data->file_names[j];
3470
3471           if (filename_cmp (this_fullname, fullname) == 0)
3472             {
3473               dw2_instantiate_symtab (per_cu);
3474               break;
3475             }
3476         }
3477     }
3478 }
3479
3480 static void
3481 dw2_map_matching_symbols (struct objfile *objfile,
3482                           const char * name, domain_enum namespace,
3483                           int global,
3484                           int (*callback) (struct block *,
3485                                            struct symbol *, void *),
3486                           void *data, symbol_compare_ftype *match,
3487                           symbol_compare_ftype *ordered_compare)
3488 {
3489   /* Currently unimplemented; used for Ada.  The function can be called if the
3490      current language is Ada for a non-Ada objfile using GNU index.  As Ada
3491      does not look for non-Ada symbols this function should just return.  */
3492 }
3493
3494 static void
3495 dw2_expand_symtabs_matching
3496   (struct objfile *objfile,
3497    int (*file_matcher) (const char *, void *, int basenames),
3498    int (*name_matcher) (const char *, void *),
3499    enum search_domain kind,
3500    void *data)
3501 {
3502   int i;
3503   offset_type iter;
3504   struct mapped_index *index;
3505
3506   dw2_setup (objfile);
3507
3508   /* index_table is NULL if OBJF_READNOW.  */
3509   if (!dwarf2_per_objfile->index_table)
3510     return;
3511   index = dwarf2_per_objfile->index_table;
3512
3513   if (file_matcher != NULL)
3514     {
3515       struct cleanup *cleanup;
3516       htab_t visited_found, visited_not_found;
3517
3518       visited_found = htab_create_alloc (10,
3519                                          htab_hash_pointer, htab_eq_pointer,
3520                                          NULL, xcalloc, xfree);
3521       cleanup = make_cleanup_htab_delete (visited_found);
3522       visited_not_found = htab_create_alloc (10,
3523                                              htab_hash_pointer, htab_eq_pointer,
3524                                              NULL, xcalloc, xfree);
3525       make_cleanup_htab_delete (visited_not_found);
3526
3527       /* The rule is CUs specify all the files, including those used by
3528          any TU, so there's no need to scan TUs here.  */
3529
3530       for (i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
3531         {
3532           int j;
3533           struct dwarf2_per_cu_data *per_cu = dw2_get_primary_cu (i);
3534           struct quick_file_names *file_data;
3535           void **slot;
3536
3537           per_cu->v.quick->mark = 0;
3538
3539           /* We only need to look at symtabs not already expanded.  */
3540           if (per_cu->v.quick->symtab)
3541             continue;
3542
3543           file_data = dw2_get_file_names (per_cu);
3544           if (file_data == NULL)
3545             continue;
3546
3547           if (htab_find (visited_not_found, file_data) != NULL)
3548             continue;
3549           else if (htab_find (visited_found, file_data) != NULL)
3550             {
3551               per_cu->v.quick->mark = 1;
3552               continue;
3553             }
3554
3555           for (j = 0; j < file_data->num_file_names; ++j)
3556             {
3557               const char *this_real_name;
3558
3559               if (file_matcher (file_data->file_names[j], data, 0))
3560                 {
3561                   per_cu->v.quick->mark = 1;
3562                   break;
3563                 }
3564
3565               /* Before we invoke realpath, which can get expensive when many
3566                  files are involved, do a quick comparison of the basenames.  */
3567               if (!basenames_may_differ
3568                   && !file_matcher (lbasename (file_data->file_names[j]),
3569                                     data, 1))
3570                 continue;
3571
3572               this_real_name = dw2_get_real_path (objfile, file_data, j);
3573               if (file_matcher (this_real_name, data, 0))
3574                 {
3575                   per_cu->v.quick->mark = 1;
3576                   break;
3577                 }
3578             }
3579
3580           slot = htab_find_slot (per_cu->v.quick->mark
3581                                  ? visited_found
3582                                  : visited_not_found,
3583                                  file_data, INSERT);
3584           *slot = file_data;
3585         }
3586
3587       do_cleanups (cleanup);
3588     }
3589
3590   for (iter = 0; iter < index->symbol_table_slots; ++iter)
3591     {
3592       offset_type idx = 2 * iter;
3593       const char *name;
3594       offset_type *vec, vec_len, vec_idx;
3595
3596       if (index->symbol_table[idx] == 0 && index->symbol_table[idx + 1] == 0)
3597         continue;
3598
3599       name = index->constant_pool + MAYBE_SWAP (index->symbol_table[idx]);
3600
3601       if (! (*name_matcher) (name, data))
3602         continue;
3603
3604       /* The name was matched, now expand corresponding CUs that were
3605          marked.  */
3606       vec = (offset_type *) (index->constant_pool
3607                              + MAYBE_SWAP (index->symbol_table[idx + 1]));
3608       vec_len = MAYBE_SWAP (vec[0]);
3609       for (vec_idx = 0; vec_idx < vec_len; ++vec_idx)
3610         {
3611           struct dwarf2_per_cu_data *per_cu;
3612           offset_type cu_index_and_attrs = MAYBE_SWAP (vec[vec_idx + 1]);
3613           gdb_index_symbol_kind symbol_kind =
3614             GDB_INDEX_SYMBOL_KIND_VALUE (cu_index_and_attrs);
3615           int cu_index = GDB_INDEX_CU_VALUE (cu_index_and_attrs);
3616           /* Only check the symbol attributes if they're present.
3617              Indices prior to version 7 don't record them,
3618              and indices >= 7 may elide them for certain symbols
3619              (gold does this).  */
3620           int attrs_valid =
3621             (index->version >= 7
3622              && symbol_kind != GDB_INDEX_SYMBOL_KIND_NONE);
3623
3624           /* Only check the symbol's kind if it has one.  */
3625           if (attrs_valid)
3626             {
3627               switch (kind)
3628                 {
3629                 case VARIABLES_DOMAIN:
3630                   if (symbol_kind != GDB_INDEX_SYMBOL_KIND_VARIABLE)
3631                     continue;
3632                   break;
3633                 case FUNCTIONS_DOMAIN:
3634                   if (symbol_kind != GDB_INDEX_SYMBOL_KIND_FUNCTION)
3635                     continue;
3636                   break;
3637                 case TYPES_DOMAIN:
3638                   if (symbol_kind != GDB_INDEX_SYMBOL_KIND_TYPE)
3639                     continue;
3640                   break;
3641                 default:
3642                   break;
3643                 }
3644             }
3645
3646           /* Don't crash on bad data.  */
3647           if (cu_index >= (dwarf2_per_objfile->n_comp_units
3648                            + dwarf2_per_objfile->n_type_units))
3649             {
3650               complaint (&symfile_complaints,
3651                          _(".gdb_index entry has bad CU index"
3652                            " [in module %s]"), objfile_name (objfile));
3653               continue;
3654             }
3655
3656           per_cu = dw2_get_cu (cu_index);
3657           if (file_matcher == NULL || per_cu->v.quick->mark)
3658             dw2_instantiate_symtab (per_cu);
3659         }
3660     }
3661 }
3662
3663 /* A helper for dw2_find_pc_sect_symtab which finds the most specific
3664    symtab.  */
3665
3666 static struct symtab *
3667 recursively_find_pc_sect_symtab (struct symtab *symtab, CORE_ADDR pc)
3668 {
3669   int i;
3670
3671   if (BLOCKVECTOR (symtab) != NULL
3672       && blockvector_contains_pc (BLOCKVECTOR (symtab), pc))
3673     return symtab;
3674
3675   if (symtab->includes == NULL)
3676     return NULL;
3677
3678   for (i = 0; symtab->includes[i]; ++i)
3679     {
3680       struct symtab *s = symtab->includes[i];
3681
3682       s = recursively_find_pc_sect_symtab (s, pc);
3683       if (s != NULL)
3684         return s;
3685     }
3686
3687   return NULL;
3688 }
3689
3690 static struct symtab *
3691 dw2_find_pc_sect_symtab (struct objfile *objfile,
3692                          struct minimal_symbol *msymbol,
3693                          CORE_ADDR pc,
3694                          struct obj_section *section,
3695                          int warn_if_readin)
3696 {
3697   struct dwarf2_per_cu_data *data;
3698   struct symtab *result;
3699
3700   dw2_setup (objfile);
3701
3702   if (!objfile->psymtabs_addrmap)
3703     return NULL;
3704
3705   data = addrmap_find (objfile->psymtabs_addrmap, pc);
3706   if (!data)
3707     return NULL;
3708
3709   if (warn_if_readin && data->v.quick->symtab)
3710     warning (_("(Internal error: pc %s in read in CU, but not in symtab.)"),
3711              paddress (get_objfile_arch (objfile), pc));
3712
3713   result = recursively_find_pc_sect_symtab (dw2_instantiate_symtab (data), pc);
3714   gdb_assert (result != NULL);
3715   return result;
3716 }
3717
3718 static void
3719 dw2_map_symbol_filenames (struct objfile *objfile, symbol_filename_ftype *fun,
3720                           void *data, int need_fullname)
3721 {
3722   int i;
3723   struct cleanup *cleanup;
3724   htab_t visited = htab_create_alloc (10, htab_hash_pointer, htab_eq_pointer,
3725                                       NULL, xcalloc, xfree);
3726
3727   cleanup = make_cleanup_htab_delete (visited);
3728   dw2_setup (objfile);
3729
3730   /* The rule is CUs specify all the files, including those used by
3731      any TU, so there's no need to scan TUs here.
3732      We can ignore file names coming from already-expanded CUs.  */
3733
3734   for (i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
3735     {
3736       struct dwarf2_per_cu_data *per_cu = dw2_get_cu (i);
3737
3738       if (per_cu->v.quick->symtab)
3739         {
3740           void **slot = htab_find_slot (visited, per_cu->v.quick->file_names,
3741                                         INSERT);
3742
3743           *slot = per_cu->v.quick->file_names;
3744         }
3745     }
3746
3747   for (i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
3748     {
3749       int j;
3750       struct dwarf2_per_cu_data *per_cu = dw2_get_primary_cu (i);
3751       struct quick_file_names *file_data;
3752       void **slot;
3753
3754       /* We only need to look at symtabs not already expanded.  */
3755       if (per_cu->v.quick->symtab)
3756         continue;
3757
3758       file_data = dw2_get_file_names (per_cu);
3759       if (file_data == NULL)
3760         continue;
3761
3762       slot = htab_find_slot (visited, file_data, INSERT);
3763       if (*slot)
3764         {
3765           /* Already visited.  */
3766           continue;
3767         }
3768       *slot = file_data;
3769
3770       for (j = 0; j < file_data->num_file_names; ++j)
3771         {
3772           const char *this_real_name;
3773
3774           if (need_fullname)
3775             this_real_name = dw2_get_real_path (objfile, file_data, j);
3776           else
3777             this_real_name = NULL;
3778           (*fun) (file_data->file_names[j], this_real_name, data);
3779         }
3780     }
3781
3782   do_cleanups (cleanup);
3783 }
3784
3785 static int
3786 dw2_has_symbols (struct objfile *objfile)
3787 {
3788   return 1;
3789 }
3790
3791 const struct quick_symbol_functions dwarf2_gdb_index_functions =
3792 {
3793   dw2_has_symbols,
3794   dw2_find_last_source_symtab,
3795   dw2_forget_cached_source_info,
3796   dw2_map_symtabs_matching_filename,
3797   dw2_lookup_symbol,
3798   dw2_print_stats,
3799   dw2_dump,
3800   dw2_relocate,
3801   dw2_expand_symtabs_for_function,
3802   dw2_expand_all_symtabs,
3803   dw2_expand_symtabs_with_fullname,
3804   dw2_map_matching_symbols,
3805   dw2_expand_symtabs_matching,
3806   dw2_find_pc_sect_symtab,
3807   dw2_map_symbol_filenames
3808 };
3809
3810 /* Initialize for reading DWARF for this objfile.  Return 0 if this
3811    file will use psymtabs, or 1 if using the GNU index.  */
3812
3813 int
3814 dwarf2_initialize_objfile (struct objfile *objfile)
3815 {
3816   /* If we're about to read full symbols, don't bother with the
3817      indices.  In this case we also don't care if some other debug
3818      format is making psymtabs, because they are all about to be
3819      expanded anyway.  */
3820   if ((objfile->flags & OBJF_READNOW))
3821     {
3822       int i;
3823
3824       dwarf2_per_objfile->using_index = 1;
3825       create_all_comp_units (objfile);
3826       create_all_type_units (objfile);
3827       dwarf2_per_objfile->quick_file_names_table =
3828         create_quick_file_names_table (dwarf2_per_objfile->n_comp_units);
3829
3830       for (i = 0; i < (dwarf2_per_objfile->n_comp_units
3831                        + dwarf2_per_objfile->n_type_units); ++i)
3832         {
3833           struct dwarf2_per_cu_data *per_cu = dw2_get_cu (i);
3834
3835           per_cu->v.quick = OBSTACK_ZALLOC (&objfile->objfile_obstack,
3836                                             struct dwarf2_per_cu_quick_data);
3837         }
3838
3839       /* Return 1 so that gdb sees the "quick" functions.  However,
3840          these functions will be no-ops because we will have expanded
3841          all symtabs.  */
3842       return 1;
3843     }
3844
3845   if (dwarf2_read_index (objfile))
3846     return 1;
3847
3848   return 0;
3849 }
3850
3851 \f
3852
3853 /* Build a partial symbol table.  */
3854
3855 void
3856 dwarf2_build_psymtabs (struct objfile *objfile)
3857 {
3858   volatile struct gdb_exception except;
3859
3860   if (objfile->global_psymbols.size == 0 && objfile->static_psymbols.size == 0)
3861     {
3862       init_psymbol_list (objfile, 1024);
3863     }
3864
3865   TRY_CATCH (except, RETURN_MASK_ERROR)
3866     {
3867       /* This isn't really ideal: all the data we allocate on the
3868          objfile's obstack is still uselessly kept around.  However,
3869          freeing it seems unsafe.  */
3870       struct cleanup *cleanups = make_cleanup_discard_psymtabs (objfile);
3871
3872       dwarf2_build_psymtabs_hard (objfile);
3873       discard_cleanups (cleanups);
3874     }
3875   if (except.reason < 0)
3876     exception_print (gdb_stderr, except);
3877 }
3878
3879 /* Return the total length of the CU described by HEADER.  */
3880
3881 static unsigned int
3882 get_cu_length (const struct comp_unit_head *header)
3883 {
3884   return header->initial_length_size + header->length;
3885 }
3886
3887 /* Return TRUE if OFFSET is within CU_HEADER.  */
3888
3889 static inline int
3890 offset_in_cu_p (const struct comp_unit_head *cu_header, sect_offset offset)
3891 {
3892   sect_offset bottom = { cu_header->offset.sect_off };
3893   sect_offset top = { cu_header->offset.sect_off + get_cu_length (cu_header) };
3894
3895   return (offset.sect_off >= bottom.sect_off && offset.sect_off < top.sect_off);
3896 }
3897
3898 /* Find the base address of the compilation unit for range lists and
3899    location lists.  It will normally be specified by DW_AT_low_pc.
3900    In DWARF-3 draft 4, the base address could be overridden by
3901    DW_AT_entry_pc.  It's been removed, but GCC still uses this for
3902    compilation units with discontinuous ranges.  */
3903
3904 static void
3905 dwarf2_find_base_address (struct die_info *die, struct dwarf2_cu *cu)
3906 {
3907   struct attribute *attr;
3908
3909   cu->base_known = 0;
3910   cu->base_address = 0;
3911
3912   attr = dwarf2_attr (die, DW_AT_entry_pc, cu);
3913   if (attr)
3914     {
3915       cu->base_address = DW_ADDR (attr);
3916       cu->base_known = 1;
3917     }
3918   else
3919     {
3920       attr = dwarf2_attr (die, DW_AT_low_pc, cu);
3921       if (attr)
3922         {
3923           cu->base_address = DW_ADDR (attr);
3924           cu->base_known = 1;
3925         }
3926     }
3927 }
3928
3929 /* Read in the comp unit header information from the debug_info at info_ptr.
3930    NOTE: This leaves members offset, first_die_offset to be filled in
3931    by the caller.  */
3932
3933 static const gdb_byte *
3934 read_comp_unit_head (struct comp_unit_head *cu_header,
3935                      const gdb_byte *info_ptr, bfd *abfd)
3936 {
3937   int signed_addr;
3938   unsigned int bytes_read;
3939
3940   cu_header->length = read_initial_length (abfd, info_ptr, &bytes_read);
3941   cu_header->initial_length_size = bytes_read;
3942   cu_header->offset_size = (bytes_read == 4) ? 4 : 8;
3943   info_ptr += bytes_read;
3944   cu_header->version = read_2_bytes (abfd, info_ptr);
3945   info_ptr += 2;
3946   cu_header->abbrev_offset.sect_off = read_offset (abfd, info_ptr, cu_header,
3947                                              &bytes_read);
3948   info_ptr += bytes_read;
3949   cu_header->addr_size = read_1_byte (abfd, info_ptr);
3950   info_ptr += 1;
3951   signed_addr = bfd_get_sign_extend_vma (abfd);
3952   if (signed_addr < 0)
3953     internal_error (__FILE__, __LINE__,
3954                     _("read_comp_unit_head: dwarf from non elf file"));
3955   cu_header->signed_addr_p = signed_addr;
3956
3957   return info_ptr;
3958 }
3959
3960 /* Helper function that returns the proper abbrev section for
3961    THIS_CU.  */
3962
3963 static struct dwarf2_section_info *
3964 get_abbrev_section_for_cu (struct dwarf2_per_cu_data *this_cu)
3965 {
3966   struct dwarf2_section_info *abbrev;
3967
3968   if (this_cu->is_dwz)
3969     abbrev = &dwarf2_get_dwz_file ()->abbrev;
3970   else
3971     abbrev = &dwarf2_per_objfile->abbrev;
3972
3973   return abbrev;
3974 }
3975
3976 /* Subroutine of read_and_check_comp_unit_head and
3977    read_and_check_type_unit_head to simplify them.
3978    Perform various error checking on the header.  */
3979
3980 static void
3981 error_check_comp_unit_head (struct comp_unit_head *header,
3982                             struct dwarf2_section_info *section,
3983                             struct dwarf2_section_info *abbrev_section)
3984 {
3985   bfd *abfd = section->asection->owner;
3986   const char *filename = bfd_get_filename (abfd);
3987
3988   if (header->version != 2 && header->version != 3 && header->version != 4)
3989     error (_("Dwarf Error: wrong version in compilation unit header "
3990            "(is %d, should be 2, 3, or 4) [in module %s]"), header->version,
3991            filename);
3992
3993   if (header->abbrev_offset.sect_off
3994       >= dwarf2_section_size (dwarf2_per_objfile->objfile, abbrev_section))
3995     error (_("Dwarf Error: bad offset (0x%lx) in compilation unit header "
3996            "(offset 0x%lx + 6) [in module %s]"),
3997            (long) header->abbrev_offset.sect_off, (long) header->offset.sect_off,
3998            filename);
3999
4000   /* Cast to unsigned long to use 64-bit arithmetic when possible to
4001      avoid potential 32-bit overflow.  */
4002   if (((unsigned long) header->offset.sect_off + get_cu_length (header))
4003       > section->size)
4004     error (_("Dwarf Error: bad length (0x%lx) in compilation unit header "
4005            "(offset 0x%lx + 0) [in module %s]"),
4006            (long) header->length, (long) header->offset.sect_off,
4007            filename);
4008 }
4009
4010 /* Read in a CU/TU header and perform some basic error checking.
4011    The contents of the header are stored in HEADER.
4012    The result is a pointer to the start of the first DIE.  */
4013
4014 static const gdb_byte *
4015 read_and_check_comp_unit_head (struct comp_unit_head *header,
4016                                struct dwarf2_section_info *section,
4017                                struct dwarf2_section_info *abbrev_section,
4018                                const gdb_byte *info_ptr,
4019                                int is_debug_types_section)
4020 {
4021   const gdb_byte *beg_of_comp_unit = info_ptr;
4022   bfd *abfd = section->asection->owner;
4023
4024   header->offset.sect_off = beg_of_comp_unit - section->buffer;
4025
4026   info_ptr = read_comp_unit_head (header, info_ptr, abfd);
4027
4028   /* If we're reading a type unit, skip over the signature and
4029      type_offset fields.  */
4030   if (is_debug_types_section)
4031     info_ptr += 8 /*signature*/ + header->offset_size;
4032
4033   header->first_die_offset.cu_off = info_ptr - beg_of_comp_unit;
4034
4035   error_check_comp_unit_head (header, section, abbrev_section);
4036
4037   return info_ptr;
4038 }
4039
4040 /* Read in the types comp unit header information from .debug_types entry at
4041    types_ptr.  The result is a pointer to one past the end of the header.  */
4042
4043 static const gdb_byte *
4044 read_and_check_type_unit_head (struct comp_unit_head *header,
4045                                struct dwarf2_section_info *section,
4046                                struct dwarf2_section_info *abbrev_section,
4047                                const gdb_byte *info_ptr,
4048                                ULONGEST *signature,
4049                                cu_offset *type_offset_in_tu)
4050 {
4051   const gdb_byte *beg_of_comp_unit = info_ptr;
4052   bfd *abfd = section->asection->owner;
4053
4054   header->offset.sect_off = beg_of_comp_unit - section->buffer;
4055
4056   info_ptr = read_comp_unit_head (header, info_ptr, abfd);
4057
4058   /* If we're reading a type unit, skip over the signature and
4059      type_offset fields.  */
4060   if (signature != NULL)
4061     *signature = read_8_bytes (abfd, info_ptr);
4062   info_ptr += 8;
4063   if (type_offset_in_tu != NULL)
4064     type_offset_in_tu->cu_off = read_offset_1 (abfd, info_ptr,
4065                                                header->offset_size);
4066   info_ptr += header->offset_size;
4067
4068   header->first_die_offset.cu_off = info_ptr - beg_of_comp_unit;
4069
4070   error_check_comp_unit_head (header, section, abbrev_section);
4071
4072   return info_ptr;
4073 }
4074
4075 /* Fetch the abbreviation table offset from a comp or type unit header.  */
4076
4077 static sect_offset
4078 read_abbrev_offset (struct dwarf2_section_info *section,
4079                     sect_offset offset)
4080 {
4081   bfd *abfd = section->asection->owner;
4082   const gdb_byte *info_ptr;
4083   unsigned int length, initial_length_size, offset_size;
4084   sect_offset abbrev_offset;
4085
4086   dwarf2_read_section (dwarf2_per_objfile->objfile, section);
4087   info_ptr = section->buffer + offset.sect_off;
4088   length = read_initial_length (abfd, info_ptr, &initial_length_size);
4089   offset_size = initial_length_size == 4 ? 4 : 8;
4090   info_ptr += initial_length_size + 2 /*version*/;
4091   abbrev_offset.sect_off = read_offset_1 (abfd, info_ptr, offset_size);
4092   return abbrev_offset;
4093 }
4094
4095 /* Allocate a new partial symtab for file named NAME and mark this new
4096    partial symtab as being an include of PST.  */
4097
4098 static void
4099 dwarf2_create_include_psymtab (const char *name, struct partial_symtab *pst,
4100                                struct objfile *objfile)
4101 {
4102   struct partial_symtab *subpst = allocate_psymtab (name, objfile);
4103
4104   if (!IS_ABSOLUTE_PATH (subpst->filename))
4105     {
4106       /* It shares objfile->objfile_obstack.  */
4107       subpst->dirname = pst->dirname;
4108     }
4109
4110   subpst->section_offsets = pst->section_offsets;
4111   subpst->textlow = 0;
4112   subpst->texthigh = 0;
4113
4114   subpst->dependencies = (struct partial_symtab **)
4115     obstack_alloc (&objfile->objfile_obstack,
4116                    sizeof (struct partial_symtab *));
4117   subpst->dependencies[0] = pst;
4118   subpst->number_of_dependencies = 1;
4119
4120   subpst->globals_offset = 0;
4121   subpst->n_global_syms = 0;
4122   subpst->statics_offset = 0;
4123   subpst->n_static_syms = 0;
4124   subpst->symtab = NULL;
4125   subpst->read_symtab = pst->read_symtab;
4126   subpst->readin = 0;
4127
4128   /* No private part is necessary for include psymtabs.  This property
4129      can be used to differentiate between such include psymtabs and
4130      the regular ones.  */
4131   subpst->read_symtab_private = NULL;
4132 }
4133
4134 /* Read the Line Number Program data and extract the list of files
4135    included by the source file represented by PST.  Build an include
4136    partial symtab for each of these included files.  */
4137
4138 static void
4139 dwarf2_build_include_psymtabs (struct dwarf2_cu *cu,
4140                                struct die_info *die,
4141                                struct partial_symtab *pst)
4142 {
4143   struct line_header *lh = NULL;
4144   struct attribute *attr;
4145
4146   attr = dwarf2_attr (die, DW_AT_stmt_list, cu);
4147   if (attr)
4148     lh = dwarf_decode_line_header (DW_UNSND (attr), cu);
4149   if (lh == NULL)
4150     return;  /* No linetable, so no includes.  */
4151
4152   /* NOTE: pst->dirname is DW_AT_comp_dir (if present).  */
4153   dwarf_decode_lines (lh, pst->dirname, cu, pst, 1);
4154
4155   free_line_header (lh);
4156 }
4157
4158 static hashval_t
4159 hash_signatured_type (const void *item)
4160 {
4161   const struct signatured_type *sig_type = item;
4162
4163   /* This drops the top 32 bits of the signature, but is ok for a hash.  */
4164   return sig_type->signature;
4165 }
4166
4167 static int
4168 eq_signatured_type (const void *item_lhs, const void *item_rhs)
4169 {
4170   const struct signatured_type *lhs = item_lhs;
4171   const struct signatured_type *rhs = item_rhs;
4172
4173   return lhs->signature == rhs->signature;
4174 }
4175
4176 /* Allocate a hash table for signatured types.  */
4177
4178 static htab_t
4179 allocate_signatured_type_table (struct objfile *objfile)
4180 {
4181   return htab_create_alloc_ex (41,
4182                                hash_signatured_type,
4183                                eq_signatured_type,
4184                                NULL,
4185                                &objfile->objfile_obstack,
4186                                hashtab_obstack_allocate,
4187                                dummy_obstack_deallocate);
4188 }
4189
4190 /* A helper function to add a signatured type CU to a table.  */
4191
4192 static int
4193 add_signatured_type_cu_to_table (void **slot, void *datum)
4194 {
4195   struct signatured_type *sigt = *slot;
4196   struct signatured_type ***datap = datum;
4197
4198   **datap = sigt;
4199   ++*datap;
4200
4201   return 1;
4202 }
4203
4204 /* Create the hash table of all entries in the .debug_types
4205    (or .debug_types.dwo) section(s).
4206    If reading a DWO file, then DWO_FILE is a pointer to the DWO file object,
4207    otherwise it is NULL.
4208
4209    The result is a pointer to the hash table or NULL if there are no types.
4210
4211    Note: This function processes DWO files only, not DWP files.  */
4212
4213 static htab_t
4214 create_debug_types_hash_table (struct dwo_file *dwo_file,
4215                                VEC (dwarf2_section_info_def) *types)
4216 {
4217   struct objfile *objfile = dwarf2_per_objfile->objfile;
4218   htab_t types_htab = NULL;
4219   int ix;
4220   struct dwarf2_section_info *section;
4221   struct dwarf2_section_info *abbrev_section;
4222
4223   if (VEC_empty (dwarf2_section_info_def, types))
4224     return NULL;
4225
4226   abbrev_section = (dwo_file != NULL
4227                     ? &dwo_file->sections.abbrev
4228                     : &dwarf2_per_objfile->abbrev);
4229
4230   if (dwarf2_read_debug)
4231     fprintf_unfiltered (gdb_stdlog, "Reading .debug_types%s for %s:\n",
4232                         dwo_file ? ".dwo" : "",
4233                         bfd_get_filename (abbrev_section->asection->owner));
4234
4235   for (ix = 0;
4236        VEC_iterate (dwarf2_section_info_def, types, ix, section);
4237        ++ix)
4238     {
4239       bfd *abfd;
4240       const gdb_byte *info_ptr, *end_ptr;
4241       struct dwarf2_section_info *abbrev_section;
4242
4243       dwarf2_read_section (objfile, section);
4244       info_ptr = section->buffer;
4245
4246       if (info_ptr == NULL)
4247         continue;
4248
4249       /* We can't set abfd until now because the section may be empty or
4250          not present, in which case section->asection will be NULL.  */
4251       abfd = section->asection->owner;
4252
4253       if (dwo_file)
4254         abbrev_section = &dwo_file->sections.abbrev;
4255       else
4256         abbrev_section = &dwarf2_per_objfile->abbrev;
4257
4258       /* We don't use init_cutu_and_read_dies_simple, or some such, here
4259          because we don't need to read any dies: the signature is in the
4260          header.  */
4261
4262       end_ptr = info_ptr + section->size;
4263       while (info_ptr < end_ptr)
4264         {
4265           sect_offset offset;
4266           cu_offset type_offset_in_tu;
4267           ULONGEST signature;
4268           struct signatured_type *sig_type;
4269           struct dwo_unit *dwo_tu;
4270           void **slot;
4271           const gdb_byte *ptr = info_ptr;
4272           struct comp_unit_head header;
4273           unsigned int length;
4274
4275           offset.sect_off = ptr - section->buffer;
4276
4277           /* We need to read the type's signature in order to build the hash
4278              table, but we don't need anything else just yet.  */
4279
4280           ptr = read_and_check_type_unit_head (&header, section,
4281                                                abbrev_section, ptr,
4282                                                &signature, &type_offset_in_tu);
4283
4284           length = get_cu_length (&header);
4285
4286           /* Skip dummy type units.  */
4287           if (ptr >= info_ptr + length
4288               || peek_abbrev_code (abfd, ptr) == 0)
4289             {
4290               info_ptr += length;
4291               continue;
4292             }
4293
4294           if (types_htab == NULL)
4295             {
4296               if (dwo_file)
4297                 types_htab = allocate_dwo_unit_table (objfile);
4298               else
4299                 types_htab = allocate_signatured_type_table (objfile);
4300             }
4301
4302           if (dwo_file)
4303             {
4304               sig_type = NULL;
4305               dwo_tu = OBSTACK_ZALLOC (&objfile->objfile_obstack,
4306                                        struct dwo_unit);
4307               dwo_tu->dwo_file = dwo_file;
4308               dwo_tu->signature = signature;
4309               dwo_tu->type_offset_in_tu = type_offset_in_tu;
4310               dwo_tu->section = section;
4311               dwo_tu->offset = offset;
4312               dwo_tu->length = length;
4313             }
4314           else
4315             {
4316               /* N.B.: type_offset is not usable if this type uses a DWO file.
4317                  The real type_offset is in the DWO file.  */
4318               dwo_tu = NULL;
4319               sig_type = OBSTACK_ZALLOC (&objfile->objfile_obstack,
4320                                          struct signatured_type);
4321               sig_type->signature = signature;
4322               sig_type->type_offset_in_tu = type_offset_in_tu;
4323               sig_type->per_cu.objfile = objfile;
4324               sig_type->per_cu.is_debug_types = 1;
4325               sig_type->per_cu.section = section;
4326               sig_type->per_cu.offset = offset;
4327               sig_type->per_cu.length = length;
4328             }
4329
4330           slot = htab_find_slot (types_htab,
4331                                  dwo_file ? (void*) dwo_tu : (void *) sig_type,
4332                                  INSERT);
4333           gdb_assert (slot != NULL);
4334           if (*slot != NULL)
4335             {
4336               sect_offset dup_offset;
4337
4338               if (dwo_file)
4339                 {
4340                   const struct dwo_unit *dup_tu = *slot;
4341
4342                   dup_offset = dup_tu->offset;
4343                 }
4344               else
4345                 {
4346                   const struct signatured_type *dup_tu = *slot;
4347
4348                   dup_offset = dup_tu->per_cu.offset;
4349                 }
4350
4351               complaint (&symfile_complaints,
4352                          _("debug type entry at offset 0x%x is duplicate to"
4353                            " the entry at offset 0x%x, signature %s"),
4354                          offset.sect_off, dup_offset.sect_off,
4355                          hex_string (signature));
4356             }
4357           *slot = dwo_file ? (void *) dwo_tu : (void *) sig_type;
4358
4359           if (dwarf2_read_debug)
4360             fprintf_unfiltered (gdb_stdlog, "  offset 0x%x, signature %s\n",
4361                                 offset.sect_off,
4362                                 hex_string (signature));
4363
4364           info_ptr += length;
4365         }
4366     }
4367
4368   return types_htab;
4369 }
4370
4371 /* Create the hash table of all entries in the .debug_types section,
4372    and initialize all_type_units.
4373    The result is zero if there is an error (e.g. missing .debug_types section),
4374    otherwise non-zero.  */
4375
4376 static int
4377 create_all_type_units (struct objfile *objfile)
4378 {
4379   htab_t types_htab;
4380   struct signatured_type **iter;
4381
4382   types_htab = create_debug_types_hash_table (NULL, dwarf2_per_objfile->types);
4383   if (types_htab == NULL)
4384     {
4385       dwarf2_per_objfile->signatured_types = NULL;
4386       return 0;
4387     }
4388
4389   dwarf2_per_objfile->signatured_types = types_htab;
4390
4391   dwarf2_per_objfile->n_type_units = htab_elements (types_htab);
4392   dwarf2_per_objfile->all_type_units
4393     = xmalloc (dwarf2_per_objfile->n_type_units
4394                * sizeof (struct signatured_type *));
4395   iter = &dwarf2_per_objfile->all_type_units[0];
4396   htab_traverse_noresize (types_htab, add_signatured_type_cu_to_table, &iter);
4397   gdb_assert (iter - &dwarf2_per_objfile->all_type_units[0]
4398               == dwarf2_per_objfile->n_type_units);
4399
4400   return 1;
4401 }
4402
4403 /* Subroutine of lookup_dwo_signatured_type and lookup_dwp_signatured_type.
4404    Fill in SIG_ENTRY with DWO_ENTRY.  */
4405
4406 static void
4407 fill_in_sig_entry_from_dwo_entry (struct objfile *objfile,
4408                                   struct signatured_type *sig_entry,
4409                                   struct dwo_unit *dwo_entry)
4410 {
4411   /* Make sure we're not clobbering something we don't expect to.  */
4412   gdb_assert (! sig_entry->per_cu.queued);
4413   gdb_assert (sig_entry->per_cu.cu == NULL);
4414   gdb_assert (sig_entry->per_cu.v.quick != NULL);
4415   gdb_assert (sig_entry->per_cu.v.quick->symtab == NULL);
4416   gdb_assert (sig_entry->signature == dwo_entry->signature);
4417   gdb_assert (sig_entry->type_offset_in_section.sect_off == 0);
4418   gdb_assert (sig_entry->type_unit_group == NULL);
4419   gdb_assert (sig_entry->dwo_unit == NULL);
4420
4421   sig_entry->per_cu.section = dwo_entry->section;
4422   sig_entry->per_cu.offset = dwo_entry->offset;
4423   sig_entry->per_cu.length = dwo_entry->length;
4424   sig_entry->per_cu.reading_dwo_directly = 1;
4425   sig_entry->per_cu.objfile = objfile;
4426   sig_entry->type_offset_in_tu = dwo_entry->type_offset_in_tu;
4427   sig_entry->dwo_unit = dwo_entry;
4428 }
4429
4430 /* Subroutine of lookup_signatured_type.
4431    If we haven't read the TU yet, create the signatured_type data structure
4432    for a TU to be read in directly from a DWO file, bypassing the stub.
4433    This is the "Stay in DWO Optimization": When there is no DWP file and we're
4434    using .gdb_index, then when reading a CU we want to stay in the DWO file
4435    containing that CU.  Otherwise we could end up reading several other DWO
4436    files (due to comdat folding) to process the transitive closure of all the
4437    mentioned TUs, and that can be slow.  The current DWO file will have every
4438    type signature that it needs.
4439    We only do this for .gdb_index because in the psymtab case we already have
4440    to read all the DWOs to build the type unit groups.  */
4441
4442 static struct signatured_type *
4443 lookup_dwo_signatured_type (struct dwarf2_cu *cu, ULONGEST sig)
4444 {
4445   struct objfile *objfile = dwarf2_per_objfile->objfile;
4446   struct dwo_file *dwo_file;
4447   struct dwo_unit find_dwo_entry, *dwo_entry;
4448   struct signatured_type find_sig_entry, *sig_entry;
4449
4450   gdb_assert (cu->dwo_unit && dwarf2_per_objfile->using_index);
4451
4452   /* Note: cu->dwo_unit is the dwo_unit that references this TU, not the
4453      dwo_unit of the TU itself.  */
4454   dwo_file = cu->dwo_unit->dwo_file;
4455
4456   /* We only ever need to read in one copy of a signatured type.
4457      Just use the global signatured_types array.  If this is the first time
4458      we're reading this type, replace the recorded data from .gdb_index with
4459      this TU.  */
4460
4461   if (dwarf2_per_objfile->signatured_types == NULL)
4462     return NULL;
4463   find_sig_entry.signature = sig;
4464   sig_entry = htab_find (dwarf2_per_objfile->signatured_types, &find_sig_entry);
4465   if (sig_entry == NULL)
4466     return NULL;
4467
4468   /* We can get here with the TU already read, *or* in the process of being
4469      read.  Don't reassign it if that's the case.  Also note that if the TU is
4470      already being read, it may not have come from a DWO, the program may be
4471      a mix of Fission-compiled code and non-Fission-compiled code.  */
4472   /* Have we already tried to read this TU?  */
4473   if (sig_entry->per_cu.tu_read)
4474     return sig_entry;
4475
4476   /* Ok, this is the first time we're reading this TU.  */
4477   if (dwo_file->tus == NULL)
4478     return NULL;
4479   find_dwo_entry.signature = sig;
4480   dwo_entry = htab_find (dwo_file->tus, &find_dwo_entry);
4481   if (dwo_entry == NULL)
4482     return NULL;
4483
4484   fill_in_sig_entry_from_dwo_entry (objfile, sig_entry, dwo_entry);
4485   sig_entry->per_cu.tu_read = 1;
4486   return sig_entry;
4487 }
4488
4489 /* Subroutine of lookup_dwp_signatured_type.
4490    Add an entry for signature SIG to dwarf2_per_objfile->signatured_types.  */
4491
4492 static struct signatured_type *
4493 add_type_unit (ULONGEST sig)
4494 {
4495   struct objfile *objfile = dwarf2_per_objfile->objfile;
4496   int n_type_units = dwarf2_per_objfile->n_type_units;
4497   struct signatured_type *sig_type;
4498   void **slot;
4499
4500   ++n_type_units;
4501   dwarf2_per_objfile->all_type_units =
4502     xrealloc (dwarf2_per_objfile->all_type_units,
4503               n_type_units * sizeof (struct signatured_type *));
4504   dwarf2_per_objfile->n_type_units = n_type_units;
4505   sig_type = OBSTACK_ZALLOC (&objfile->objfile_obstack,
4506                              struct signatured_type);
4507   dwarf2_per_objfile->all_type_units[n_type_units - 1] = sig_type;
4508   sig_type->signature = sig;
4509   sig_type->per_cu.is_debug_types = 1;
4510   sig_type->per_cu.v.quick =
4511     OBSTACK_ZALLOC (&objfile->objfile_obstack,
4512                     struct dwarf2_per_cu_quick_data);
4513   slot = htab_find_slot (dwarf2_per_objfile->signatured_types,
4514                          sig_type, INSERT);
4515   gdb_assert (*slot == NULL);
4516   *slot = sig_type;
4517   /* The rest of sig_type must be filled in by the caller.  */
4518   return sig_type;
4519 }
4520
4521 /* Subroutine of lookup_signatured_type.
4522    Look up the type for signature SIG, and if we can't find SIG in .gdb_index
4523    then try the DWP file.
4524    Normally this "can't happen", but if there's a bug in signature
4525    generation and/or the DWP file is built incorrectly, it can happen.
4526    Using the type directly from the DWP file means we don't have the stub
4527    which has some useful attributes (e.g., DW_AT_comp_dir), but they're
4528    not critical.  [Eventually the stub may go away for type units anyway.]  */
4529
4530 static struct signatured_type *
4531 lookup_dwp_signatured_type (struct dwarf2_cu *cu, ULONGEST sig)
4532 {
4533   struct objfile *objfile = dwarf2_per_objfile->objfile;
4534   struct dwp_file *dwp_file = get_dwp_file ();
4535   struct dwo_unit *dwo_entry;
4536   struct signatured_type find_sig_entry, *sig_entry;
4537
4538   gdb_assert (cu->dwo_unit && dwarf2_per_objfile->using_index);
4539   gdb_assert (dwp_file != NULL);
4540
4541   if (dwarf2_per_objfile->signatured_types != NULL)
4542     {
4543       find_sig_entry.signature = sig;
4544       sig_entry = htab_find (dwarf2_per_objfile->signatured_types,
4545                              &find_sig_entry);
4546       if (sig_entry != NULL)
4547         return sig_entry;
4548     }
4549
4550   /* This is the "shouldn't happen" case.
4551      Try the DWP file and hope for the best.  */
4552   if (dwp_file->tus == NULL)
4553     return NULL;
4554   dwo_entry = lookup_dwo_in_dwp (dwp_file, dwp_file->tus, NULL,
4555                                  sig, 1 /* is_debug_types */);
4556   if (dwo_entry == NULL)
4557     return NULL;
4558
4559   sig_entry = add_type_unit (sig);
4560   fill_in_sig_entry_from_dwo_entry (objfile, sig_entry, dwo_entry);
4561
4562   /* The caller will signal a complaint if we return NULL.
4563      Here we don't return NULL but we still want to complain.  */
4564   complaint (&symfile_complaints,
4565              _("Bad type signature %s referenced by %s at 0x%x,"
4566                " coping by using copy in DWP [in module %s]"),
4567              hex_string (sig),
4568              cu->per_cu->is_debug_types ? "TU" : "CU",
4569              cu->per_cu->offset.sect_off,
4570              objfile_name (objfile));
4571
4572   return sig_entry;
4573 }
4574
4575 /* Lookup a signature based type for DW_FORM_ref_sig8.
4576    Returns NULL if signature SIG is not present in the table.
4577    It is up to the caller to complain about this.  */
4578
4579 static struct signatured_type *
4580 lookup_signatured_type (struct dwarf2_cu *cu, ULONGEST sig)
4581 {
4582   if (cu->dwo_unit
4583       && dwarf2_per_objfile->using_index)
4584     {
4585       /* We're in a DWO/DWP file, and we're using .gdb_index.
4586          These cases require special processing.  */
4587       if (get_dwp_file () == NULL)
4588         return lookup_dwo_signatured_type (cu, sig);
4589       else
4590         return lookup_dwp_signatured_type (cu, sig);
4591     }
4592   else
4593     {
4594       struct signatured_type find_entry, *entry;
4595
4596       if (dwarf2_per_objfile->signatured_types == NULL)
4597         return NULL;
4598       find_entry.signature = sig;
4599       entry = htab_find (dwarf2_per_objfile->signatured_types, &find_entry);
4600       return entry;
4601     }
4602 }
4603 \f
4604 /* Low level DIE reading support.  */
4605
4606 /* Initialize a die_reader_specs struct from a dwarf2_cu struct.  */
4607
4608 static void
4609 init_cu_die_reader (struct die_reader_specs *reader,
4610                     struct dwarf2_cu *cu,
4611                     struct dwarf2_section_info *section,
4612                     struct dwo_file *dwo_file)
4613 {
4614   gdb_assert (section->readin && section->buffer != NULL);
4615   reader->abfd = section->asection->owner;
4616   reader->cu = cu;
4617   reader->dwo_file = dwo_file;
4618   reader->die_section = section;
4619   reader->buffer = section->buffer;
4620   reader->buffer_end = section->buffer + section->size;
4621   reader->comp_dir = NULL;
4622 }
4623
4624 /* Subroutine of init_cutu_and_read_dies to simplify it.
4625    Read in the rest of a CU/TU top level DIE from DWO_UNIT.
4626    There's just a lot of work to do, and init_cutu_and_read_dies is big enough
4627    already.
4628
4629    STUB_COMP_UNIT_DIE is for the stub DIE, we copy over certain attributes
4630    from it to the DIE in the DWO.  If NULL we are skipping the stub.
4631    STUB_COMP_DIR is similar to STUB_COMP_UNIT_DIE: When reading a TU directly
4632    from the DWO file, bypassing the stub, it contains the DW_AT_comp_dir
4633    attribute of the referencing CU.  Exactly one of STUB_COMP_UNIT_DIE and
4634    COMP_DIR must be non-NULL.
4635    *RESULT_READER,*RESULT_INFO_PTR,*RESULT_COMP_UNIT_DIE,*RESULT_HAS_CHILDREN
4636    are filled in with the info of the DIE from the DWO file.
4637    ABBREV_TABLE_PROVIDED is non-zero if the caller of init_cutu_and_read_dies
4638    provided an abbrev table to use.
4639    The result is non-zero if a valid (non-dummy) DIE was found.  */
4640
4641 static int
4642 read_cutu_die_from_dwo (struct dwarf2_per_cu_data *this_cu,
4643                         struct dwo_unit *dwo_unit,
4644                         int abbrev_table_provided,
4645                         struct die_info *stub_comp_unit_die,
4646                         const char *stub_comp_dir,
4647                         struct die_reader_specs *result_reader,
4648                         const gdb_byte **result_info_ptr,
4649                         struct die_info **result_comp_unit_die,
4650                         int *result_has_children)
4651 {
4652   struct objfile *objfile = dwarf2_per_objfile->objfile;
4653   struct dwarf2_cu *cu = this_cu->cu;
4654   struct dwarf2_section_info *section;
4655   bfd *abfd;
4656   const gdb_byte *begin_info_ptr, *info_ptr;
4657   const char *comp_dir_string;
4658   ULONGEST signature; /* Or dwo_id.  */
4659   struct attribute *comp_dir, *stmt_list, *low_pc, *high_pc, *ranges;
4660   int i,num_extra_attrs;
4661   struct dwarf2_section_info *dwo_abbrev_section;
4662   struct attribute *attr;
4663   struct attribute comp_dir_attr;
4664   struct die_info *comp_unit_die;
4665
4666   /* Both can't be provided.  */
4667   gdb_assert (! (stub_comp_unit_die && stub_comp_dir));
4668
4669   /* These attributes aren't processed until later:
4670      DW_AT_stmt_list, DW_AT_low_pc, DW_AT_high_pc, DW_AT_ranges.
4671      However, the attribute is found in the stub which we won't have later.
4672      In order to not impose this complication on the rest of the code,
4673      we read them here and copy them to the DWO CU/TU die.  */
4674
4675   stmt_list = NULL;
4676   low_pc = NULL;
4677   high_pc = NULL;
4678   ranges = NULL;
4679   comp_dir = NULL;
4680
4681   if (stub_comp_unit_die != NULL)
4682     {
4683       /* For TUs in DWO files, the DW_AT_stmt_list attribute lives in the
4684          DWO file.  */
4685       if (! this_cu->is_debug_types)
4686         stmt_list = dwarf2_attr (stub_comp_unit_die, DW_AT_stmt_list, cu);
4687       low_pc = dwarf2_attr (stub_comp_unit_die, DW_AT_low_pc, cu);
4688       high_pc = dwarf2_attr (stub_comp_unit_die, DW_AT_high_pc, cu);
4689       ranges = dwarf2_attr (stub_comp_unit_die, DW_AT_ranges, cu);
4690       comp_dir = dwarf2_attr (stub_comp_unit_die, DW_AT_comp_dir, cu);
4691
4692       /* There should be a DW_AT_addr_base attribute here (if needed).
4693          We need the value before we can process DW_FORM_GNU_addr_index.  */
4694       cu->addr_base = 0;
4695       attr = dwarf2_attr (stub_comp_unit_die, DW_AT_GNU_addr_base, cu);
4696       if (attr)
4697         cu->addr_base = DW_UNSND (attr);
4698
4699       /* There should be a DW_AT_ranges_base attribute here (if needed).
4700          We need the value before we can process DW_AT_ranges.  */
4701       cu->ranges_base = 0;
4702       attr = dwarf2_attr (stub_comp_unit_die, DW_AT_GNU_ranges_base, cu);
4703       if (attr)
4704         cu->ranges_base = DW_UNSND (attr);
4705     }
4706   else if (stub_comp_dir != NULL)
4707     {
4708       /* Reconstruct the comp_dir attribute to simplify the code below.  */
4709       comp_dir = (struct attribute *)
4710         obstack_alloc (&cu->comp_unit_obstack, sizeof (*comp_dir));
4711       comp_dir->name = DW_AT_comp_dir;
4712       comp_dir->form = DW_FORM_string;
4713       DW_STRING_IS_CANONICAL (comp_dir) = 0;
4714       DW_STRING (comp_dir) = stub_comp_dir;
4715     }
4716
4717   /* Set up for reading the DWO CU/TU.  */
4718   cu->dwo_unit = dwo_unit;
4719   section = dwo_unit->section;
4720   dwarf2_read_section (objfile, section);
4721   abfd = section->asection->owner;
4722   begin_info_ptr = info_ptr = section->buffer + dwo_unit->offset.sect_off;
4723   dwo_abbrev_section = &dwo_unit->dwo_file->sections.abbrev;
4724   init_cu_die_reader (result_reader, cu, section, dwo_unit->dwo_file);
4725
4726   if (this_cu->is_debug_types)
4727     {
4728       ULONGEST header_signature;
4729       cu_offset type_offset_in_tu;
4730       struct signatured_type *sig_type = (struct signatured_type *) this_cu;
4731
4732       info_ptr = read_and_check_type_unit_head (&cu->header, section,
4733                                                 dwo_abbrev_section,
4734                                                 info_ptr,
4735                                                 &header_signature,
4736                                                 &type_offset_in_tu);
4737       /* This is not an assert because it can be caused by bad debug info.  */
4738       if (sig_type->signature != header_signature)
4739         {
4740           error (_("Dwarf Error: signature mismatch %s vs %s while reading"
4741                    " TU at offset 0x%x [in module %s]"),
4742                  hex_string (sig_type->signature),
4743                  hex_string (header_signature),
4744                  dwo_unit->offset.sect_off,
4745                  bfd_get_filename (abfd));
4746         }
4747       gdb_assert (dwo_unit->offset.sect_off == cu->header.offset.sect_off);
4748       /* For DWOs coming from DWP files, we don't know the CU length
4749          nor the type's offset in the TU until now.  */
4750       dwo_unit->length = get_cu_length (&cu->header);
4751       dwo_unit->type_offset_in_tu = type_offset_in_tu;
4752
4753       /* Establish the type offset that can be used to lookup the type.
4754          For DWO files, we don't know it until now.  */
4755       sig_type->type_offset_in_section.sect_off =
4756         dwo_unit->offset.sect_off + dwo_unit->type_offset_in_tu.cu_off;
4757     }
4758   else
4759     {
4760       info_ptr = read_and_check_comp_unit_head (&cu->header, section,
4761                                                 dwo_abbrev_section,
4762                                                 info_ptr, 0);
4763       gdb_assert (dwo_unit->offset.sect_off == cu->header.offset.sect_off);
4764       /* For DWOs coming from DWP files, we don't know the CU length
4765          until now.  */
4766       dwo_unit->length = get_cu_length (&cu->header);
4767     }
4768
4769   /* Replace the CU's original abbrev table with the DWO's.
4770      Reminder: We can't read the abbrev table until we've read the header.  */
4771   if (abbrev_table_provided)
4772     {
4773       /* Don't free the provided abbrev table, the caller of
4774          init_cutu_and_read_dies owns it.  */
4775       dwarf2_read_abbrevs (cu, dwo_abbrev_section);
4776       /* Ensure the DWO abbrev table gets freed.  */
4777       make_cleanup (dwarf2_free_abbrev_table, cu);
4778     }
4779   else
4780     {
4781       dwarf2_free_abbrev_table (cu);
4782       dwarf2_read_abbrevs (cu, dwo_abbrev_section);
4783       /* Leave any existing abbrev table cleanup as is.  */
4784     }
4785
4786   /* Read in the die, but leave space to copy over the attributes
4787      from the stub.  This has the benefit of simplifying the rest of
4788      the code - all the work to maintain the illusion of a single
4789      DW_TAG_{compile,type}_unit DIE is done here.  */
4790   num_extra_attrs = ((stmt_list != NULL)
4791                      + (low_pc != NULL)
4792                      + (high_pc != NULL)
4793                      + (ranges != NULL)
4794                      + (comp_dir != NULL));
4795   info_ptr = read_full_die_1 (result_reader, result_comp_unit_die, info_ptr,
4796                               result_has_children, num_extra_attrs);
4797
4798   /* Copy over the attributes from the stub to the DIE we just read in.  */
4799   comp_unit_die = *result_comp_unit_die;
4800   i = comp_unit_die->num_attrs;
4801   if (stmt_list != NULL)
4802     comp_unit_die->attrs[i++] = *stmt_list;
4803   if (low_pc != NULL)
4804     comp_unit_die->attrs[i++] = *low_pc;
4805   if (high_pc != NULL)
4806     comp_unit_die->attrs[i++] = *high_pc;
4807   if (ranges != NULL)
4808     comp_unit_die->attrs[i++] = *ranges;
4809   if (comp_dir != NULL)
4810     comp_unit_die->attrs[i++] = *comp_dir;
4811   comp_unit_die->num_attrs += num_extra_attrs;
4812
4813   if (dwarf2_die_debug)
4814     {
4815       fprintf_unfiltered (gdb_stdlog,
4816                           "Read die from %s@0x%x of %s:\n",
4817                           bfd_section_name (abfd, section->asection),
4818                           (unsigned) (begin_info_ptr - section->buffer),
4819                           bfd_get_filename (abfd));
4820       dump_die (comp_unit_die, dwarf2_die_debug);
4821     }
4822
4823   /* Save the comp_dir attribute.  If there is no DWP file then we'll read
4824      TUs by skipping the stub and going directly to the entry in the DWO file.
4825      However, skipping the stub means we won't get DW_AT_comp_dir, so we have
4826      to get it via circuitous means.  Blech.  */
4827   if (comp_dir != NULL)
4828     result_reader->comp_dir = DW_STRING (comp_dir);
4829
4830   /* Skip dummy compilation units.  */
4831   if (info_ptr >= begin_info_ptr + dwo_unit->length
4832       || peek_abbrev_code (abfd, info_ptr) == 0)
4833     return 0;
4834
4835   *result_info_ptr = info_ptr;
4836   return 1;
4837 }
4838
4839 /* Subroutine of init_cutu_and_read_dies to simplify it.
4840    Look up the DWO unit specified by COMP_UNIT_DIE of THIS_CU.
4841    Returns NULL if the specified DWO unit cannot be found.  */
4842
4843 static struct dwo_unit *
4844 lookup_dwo_unit (struct dwarf2_per_cu_data *this_cu,
4845                  struct die_info *comp_unit_die)
4846 {
4847   struct dwarf2_cu *cu = this_cu->cu;
4848   struct attribute *attr;
4849   ULONGEST signature;
4850   struct dwo_unit *dwo_unit;
4851   const char *comp_dir, *dwo_name;
4852
4853   gdb_assert (cu != NULL);
4854
4855   /* Yeah, we look dwo_name up again, but it simplifies the code.  */
4856   attr = dwarf2_attr (comp_unit_die, DW_AT_GNU_dwo_name, cu);
4857   gdb_assert (attr != NULL);
4858   dwo_name = DW_STRING (attr);
4859   comp_dir = NULL;
4860   attr = dwarf2_attr (comp_unit_die, DW_AT_comp_dir, cu);
4861   if (attr)
4862     comp_dir = DW_STRING (attr);
4863
4864   if (this_cu->is_debug_types)
4865     {
4866       struct signatured_type *sig_type;
4867
4868       /* Since this_cu is the first member of struct signatured_type,
4869          we can go from a pointer to one to a pointer to the other.  */
4870       sig_type = (struct signatured_type *) this_cu;
4871       signature = sig_type->signature;
4872       dwo_unit = lookup_dwo_type_unit (sig_type, dwo_name, comp_dir);
4873     }
4874   else
4875     {
4876       struct attribute *attr;
4877
4878       attr = dwarf2_attr (comp_unit_die, DW_AT_GNU_dwo_id, cu);
4879       if (! attr)
4880         error (_("Dwarf Error: missing dwo_id for dwo_name %s"
4881                  " [in module %s]"),
4882                dwo_name, objfile_name (this_cu->objfile));
4883       signature = DW_UNSND (attr);
4884       dwo_unit = lookup_dwo_comp_unit (this_cu, dwo_name, comp_dir,
4885                                        signature);
4886     }
4887
4888   return dwo_unit;
4889 }
4890
4891 /* Subroutine of init_cutu_and_read_dies to simplify it.
4892    Read a TU directly from a DWO file, bypassing the stub.  */
4893
4894 static void
4895 init_tu_and_read_dwo_dies (struct dwarf2_per_cu_data *this_cu, int keep,
4896                            die_reader_func_ftype *die_reader_func,
4897                            void *data)
4898 {
4899   struct dwarf2_cu *cu;
4900   struct signatured_type *sig_type;
4901   struct cleanup *cleanups, *free_cu_cleanup;
4902   struct die_reader_specs reader;
4903   const gdb_byte *info_ptr;
4904   struct die_info *comp_unit_die;
4905   int has_children;
4906
4907   /* Verify we can do the following downcast, and that we have the
4908      data we need.  */
4909   gdb_assert (this_cu->is_debug_types && this_cu->reading_dwo_directly);
4910   sig_type = (struct signatured_type *) this_cu;
4911   gdb_assert (sig_type->dwo_unit != NULL);
4912
4913   cleanups = make_cleanup (null_cleanup, NULL);
4914
4915   gdb_assert (this_cu->cu == NULL);
4916   cu = xmalloc (sizeof (*cu));
4917   init_one_comp_unit (cu, this_cu);
4918   /* If an error occurs while loading, release our storage.  */
4919   free_cu_cleanup = make_cleanup (free_heap_comp_unit, cu);
4920
4921   if (read_cutu_die_from_dwo (this_cu, sig_type->dwo_unit,
4922                               0 /* abbrev_table_provided */,
4923                               NULL /* stub_comp_unit_die */,
4924                               sig_type->dwo_unit->dwo_file->comp_dir,
4925                               &reader, &info_ptr,
4926                               &comp_unit_die, &has_children) == 0)
4927     {
4928       /* Dummy die.  */
4929       do_cleanups (cleanups);
4930       return;
4931     }
4932
4933   /* All the "real" work is done here.  */
4934   die_reader_func (&reader, info_ptr, comp_unit_die, has_children, data);
4935
4936   /* This duplicates some code in init_cutu_and_read_dies,
4937      but the alternative is making the latter more complex.
4938      This function is only for the special case of using DWO files directly:
4939      no point in overly complicating the general case just to handle this.  */
4940   if (keep)
4941     {
4942       /* We've successfully allocated this compilation unit.  Let our
4943          caller clean it up when finished with it.  */
4944       discard_cleanups (free_cu_cleanup);
4945
4946       /* We can only discard free_cu_cleanup and all subsequent cleanups.
4947          So we have to manually free the abbrev table.  */
4948       dwarf2_free_abbrev_table (cu);
4949
4950       /* Link this CU into read_in_chain.  */
4951       this_cu->cu->read_in_chain = dwarf2_per_objfile->read_in_chain;
4952       dwarf2_per_objfile->read_in_chain = this_cu;
4953     }
4954   else
4955     do_cleanups (free_cu_cleanup);
4956
4957   do_cleanups (cleanups);
4958 }
4959
4960 /* Initialize a CU (or TU) and read its DIEs.
4961    If the CU defers to a DWO file, read the DWO file as well.
4962
4963    ABBREV_TABLE, if non-NULL, is the abbreviation table to use.
4964    Otherwise the table specified in the comp unit header is read in and used.
4965    This is an optimization for when we already have the abbrev table.
4966
4967    If USE_EXISTING_CU is non-zero, and THIS_CU->cu is non-NULL, then use it.
4968    Otherwise, a new CU is allocated with xmalloc.
4969
4970    If KEEP is non-zero, then if we allocated a dwarf2_cu we add it to
4971    read_in_chain.  Otherwise the dwarf2_cu data is freed at the end.
4972
4973    WARNING: If THIS_CU is a "dummy CU" (used as filler by the incremental
4974    linker) then DIE_READER_FUNC will not get called.  */
4975
4976 static void
4977 init_cutu_and_read_dies (struct dwarf2_per_cu_data *this_cu,
4978                          struct abbrev_table *abbrev_table,
4979                          int use_existing_cu, int keep,
4980                          die_reader_func_ftype *die_reader_func,
4981                          void *data)
4982 {
4983   struct objfile *objfile = dwarf2_per_objfile->objfile;
4984   struct dwarf2_section_info *section = this_cu->section;
4985   bfd *abfd = section->asection->owner;
4986   struct dwarf2_cu *cu;
4987   const gdb_byte *begin_info_ptr, *info_ptr;
4988   struct die_reader_specs reader;
4989   struct die_info *comp_unit_die;
4990   int has_children;
4991   struct attribute *attr;
4992   struct cleanup *cleanups, *free_cu_cleanup = NULL;
4993   struct signatured_type *sig_type = NULL;
4994   struct dwarf2_section_info *abbrev_section;
4995   /* Non-zero if CU currently points to a DWO file and we need to
4996      reread it.  When this happens we need to reread the skeleton die
4997      before we can reread the DWO file (this only applies to CUs, not TUs).  */
4998   int rereading_dwo_cu = 0;
4999
5000   if (dwarf2_die_debug)
5001     fprintf_unfiltered (gdb_stdlog, "Reading %s unit at offset 0x%x\n",
5002                         this_cu->is_debug_types ? "type" : "comp",
5003                         this_cu->offset.sect_off);
5004
5005   if (use_existing_cu)
5006     gdb_assert (keep);
5007
5008   /* If we're reading a TU directly from a DWO file, including a virtual DWO
5009      file (instead of going through the stub), short-circuit all of this.  */
5010   if (this_cu->reading_dwo_directly)
5011     {
5012       /* Narrow down the scope of possibilities to have to understand.  */
5013       gdb_assert (this_cu->is_debug_types);
5014       gdb_assert (abbrev_table == NULL);
5015       gdb_assert (!use_existing_cu);
5016       init_tu_and_read_dwo_dies (this_cu, keep, die_reader_func, data);
5017       return;
5018     }
5019
5020   cleanups = make_cleanup (null_cleanup, NULL);
5021
5022   /* This is cheap if the section is already read in.  */
5023   dwarf2_read_section (objfile, section);
5024
5025   begin_info_ptr = info_ptr = section->buffer + this_cu->offset.sect_off;
5026
5027   abbrev_section = get_abbrev_section_for_cu (this_cu);
5028
5029   if (use_existing_cu && this_cu->cu != NULL)
5030     {
5031       cu = this_cu->cu;
5032
5033       /* If this CU is from a DWO file we need to start over, we need to
5034          refetch the attributes from the skeleton CU.
5035          This could be optimized by retrieving those attributes from when we
5036          were here the first time: the previous comp_unit_die was stored in
5037          comp_unit_obstack.  But there's no data yet that we need this
5038          optimization.  */
5039       if (cu->dwo_unit != NULL)
5040         rereading_dwo_cu = 1;
5041     }
5042   else
5043     {
5044       /* If !use_existing_cu, this_cu->cu must be NULL.  */
5045       gdb_assert (this_cu->cu == NULL);
5046
5047       cu = xmalloc (sizeof (*cu));
5048       init_one_comp_unit (cu, this_cu);
5049
5050       /* If an error occurs while loading, release our storage.  */
5051       free_cu_cleanup = make_cleanup (free_heap_comp_unit, cu);
5052     }
5053
5054   /* Get the header.  */
5055   if (cu->header.first_die_offset.cu_off != 0 && ! rereading_dwo_cu)
5056     {
5057       /* We already have the header, there's no need to read it in again.  */
5058       info_ptr += cu->header.first_die_offset.cu_off;
5059     }
5060   else
5061     {
5062       if (this_cu->is_debug_types)
5063         {
5064           ULONGEST signature;
5065           cu_offset type_offset_in_tu;
5066
5067           info_ptr = read_and_check_type_unit_head (&cu->header, section,
5068                                                     abbrev_section, info_ptr,
5069                                                     &signature,
5070                                                     &type_offset_in_tu);
5071
5072           /* Since per_cu is the first member of struct signatured_type,
5073              we can go from a pointer to one to a pointer to the other.  */
5074           sig_type = (struct signatured_type *) this_cu;
5075           gdb_assert (sig_type->signature == signature);
5076           gdb_assert (sig_type->type_offset_in_tu.cu_off
5077                       == type_offset_in_tu.cu_off);
5078           gdb_assert (this_cu->offset.sect_off == cu->header.offset.sect_off);
5079
5080           /* LENGTH has not been set yet for type units if we're
5081              using .gdb_index.  */
5082           this_cu->length = get_cu_length (&cu->header);
5083
5084           /* Establish the type offset that can be used to lookup the type.  */
5085           sig_type->type_offset_in_section.sect_off =
5086             this_cu->offset.sect_off + sig_type->type_offset_in_tu.cu_off;
5087         }
5088       else
5089         {
5090           info_ptr = read_and_check_comp_unit_head (&cu->header, section,
5091                                                     abbrev_section,
5092                                                     info_ptr, 0);
5093
5094           gdb_assert (this_cu->offset.sect_off == cu->header.offset.sect_off);
5095           gdb_assert (this_cu->length == get_cu_length (&cu->header));
5096         }
5097     }
5098
5099   /* Skip dummy compilation units.  */
5100   if (info_ptr >= begin_info_ptr + this_cu->length
5101       || peek_abbrev_code (abfd, info_ptr) == 0)
5102     {
5103       do_cleanups (cleanups);
5104       return;
5105     }
5106
5107   /* If we don't have them yet, read the abbrevs for this compilation unit.
5108      And if we need to read them now, make sure they're freed when we're
5109      done.  Note that it's important that if the CU had an abbrev table
5110      on entry we don't free it when we're done: Somewhere up the call stack
5111      it may be in use.  */
5112   if (abbrev_table != NULL)
5113     {
5114       gdb_assert (cu->abbrev_table == NULL);
5115       gdb_assert (cu->header.abbrev_offset.sect_off
5116                   == abbrev_table->offset.sect_off);
5117       cu->abbrev_table = abbrev_table;
5118     }
5119   else if (cu->abbrev_table == NULL)
5120     {
5121       dwarf2_read_abbrevs (cu, abbrev_section);
5122       make_cleanup (dwarf2_free_abbrev_table, cu);
5123     }
5124   else if (rereading_dwo_cu)
5125     {
5126       dwarf2_free_abbrev_table (cu);
5127       dwarf2_read_abbrevs (cu, abbrev_section);
5128     }
5129
5130   /* Read the top level CU/TU die.  */
5131   init_cu_die_reader (&reader, cu, section, NULL);
5132   info_ptr = read_full_die (&reader, &comp_unit_die, info_ptr, &has_children);
5133
5134   /* If we are in a DWO stub, process it and then read in the "real" CU/TU
5135      from the DWO file.
5136      Note that if USE_EXISTING_OK != 0, and THIS_CU->cu already contains a
5137      DWO CU, that this test will fail (the attribute will not be present).  */
5138   attr = dwarf2_attr (comp_unit_die, DW_AT_GNU_dwo_name, cu);
5139   if (attr)
5140     {
5141       struct dwo_unit *dwo_unit;
5142       struct die_info *dwo_comp_unit_die;
5143
5144       if (has_children)
5145         {
5146           complaint (&symfile_complaints,
5147                      _("compilation unit with DW_AT_GNU_dwo_name"
5148                        " has children (offset 0x%x) [in module %s]"),
5149                      this_cu->offset.sect_off, bfd_get_filename (abfd));
5150         }
5151       dwo_unit = lookup_dwo_unit (this_cu, comp_unit_die);
5152       if (dwo_unit != NULL)
5153         {
5154           if (read_cutu_die_from_dwo (this_cu, dwo_unit,
5155                                       abbrev_table != NULL,
5156                                       comp_unit_die, NULL,
5157                                       &reader, &info_ptr,
5158                                       &dwo_comp_unit_die, &has_children) == 0)
5159             {
5160               /* Dummy die.  */
5161               do_cleanups (cleanups);
5162               return;
5163             }
5164           comp_unit_die = dwo_comp_unit_die;
5165         }
5166       else
5167         {
5168           /* Yikes, we couldn't find the rest of the DIE, we only have
5169              the stub.  A complaint has already been logged.  There's
5170              not much more we can do except pass on the stub DIE to
5171              die_reader_func.  We don't want to throw an error on bad
5172              debug info.  */
5173         }
5174     }
5175
5176   /* All of the above is setup for this call.  Yikes.  */
5177   die_reader_func (&reader, info_ptr, comp_unit_die, has_children, data);
5178
5179   /* Done, clean up.  */
5180   if (free_cu_cleanup != NULL)
5181     {
5182       if (keep)
5183         {
5184           /* We've successfully allocated this compilation unit.  Let our
5185              caller clean it up when finished with it.  */
5186           discard_cleanups (free_cu_cleanup);
5187
5188           /* We can only discard free_cu_cleanup and all subsequent cleanups.
5189              So we have to manually free the abbrev table.  */
5190           dwarf2_free_abbrev_table (cu);
5191
5192           /* Link this CU into read_in_chain.  */
5193           this_cu->cu->read_in_chain = dwarf2_per_objfile->read_in_chain;
5194           dwarf2_per_objfile->read_in_chain = this_cu;
5195         }
5196       else
5197         do_cleanups (free_cu_cleanup);
5198     }
5199
5200   do_cleanups (cleanups);
5201 }
5202
5203 /* Read CU/TU THIS_CU in section SECTION,
5204    but do not follow DW_AT_GNU_dwo_name if present.
5205    DWOP_FILE, if non-NULL, is the DWO/DWP file to read (the caller is assumed
5206    to have already done the lookup to find the DWO/DWP file).
5207
5208    The caller is required to fill in THIS_CU->section, THIS_CU->offset, and
5209    THIS_CU->is_debug_types, but nothing else.
5210
5211    We fill in THIS_CU->length.
5212
5213    WARNING: If THIS_CU is a "dummy CU" (used as filler by the incremental
5214    linker) then DIE_READER_FUNC will not get called.
5215
5216    THIS_CU->cu is always freed when done.
5217    This is done in order to not leave THIS_CU->cu in a state where we have
5218    to care whether it refers to the "main" CU or the DWO CU.  */
5219
5220 static void
5221 init_cutu_and_read_dies_no_follow (struct dwarf2_per_cu_data *this_cu,
5222                                    struct dwarf2_section_info *abbrev_section,
5223                                    struct dwo_file *dwo_file,
5224                                    die_reader_func_ftype *die_reader_func,
5225                                    void *data)
5226 {
5227   struct objfile *objfile = dwarf2_per_objfile->objfile;
5228   struct dwarf2_section_info *section = this_cu->section;
5229   bfd *abfd = section->asection->owner;
5230   struct dwarf2_cu cu;
5231   const gdb_byte *begin_info_ptr, *info_ptr;
5232   struct die_reader_specs reader;
5233   struct cleanup *cleanups;
5234   struct die_info *comp_unit_die;
5235   int has_children;
5236
5237   if (dwarf2_die_debug)
5238     fprintf_unfiltered (gdb_stdlog, "Reading %s unit at offset 0x%x\n",
5239                         this_cu->is_debug_types ? "type" : "comp",
5240                         this_cu->offset.sect_off);
5241
5242   gdb_assert (this_cu->cu == NULL);
5243
5244   /* This is cheap if the section is already read in.  */
5245   dwarf2_read_section (objfile, section);
5246
5247   init_one_comp_unit (&cu, this_cu);
5248
5249   cleanups = make_cleanup (free_stack_comp_unit, &cu);
5250
5251   begin_info_ptr = info_ptr = section->buffer + this_cu->offset.sect_off;
5252   info_ptr = read_and_check_comp_unit_head (&cu.header, section,
5253                                             abbrev_section, info_ptr,
5254                                             this_cu->is_debug_types);
5255
5256   this_cu->length = get_cu_length (&cu.header);
5257
5258   /* Skip dummy compilation units.  */
5259   if (info_ptr >= begin_info_ptr + this_cu->length
5260       || peek_abbrev_code (abfd, info_ptr) == 0)
5261     {
5262       do_cleanups (cleanups);
5263       return;
5264     }
5265
5266   dwarf2_read_abbrevs (&cu, abbrev_section);
5267   make_cleanup (dwarf2_free_abbrev_table, &cu);
5268
5269   init_cu_die_reader (&reader, &cu, section, dwo_file);
5270   info_ptr = read_full_die (&reader, &comp_unit_die, info_ptr, &has_children);
5271
5272   die_reader_func (&reader, info_ptr, comp_unit_die, has_children, data);
5273
5274   do_cleanups (cleanups);
5275 }
5276
5277 /* Read a CU/TU, except that this does not look for DW_AT_GNU_dwo_name and
5278    does not lookup the specified DWO file.
5279    This cannot be used to read DWO files.
5280
5281    THIS_CU->cu is always freed when done.
5282    This is done in order to not leave THIS_CU->cu in a state where we have
5283    to care whether it refers to the "main" CU or the DWO CU.
5284    We can revisit this if the data shows there's a performance issue.  */
5285
5286 static void
5287 init_cutu_and_read_dies_simple (struct dwarf2_per_cu_data *this_cu,
5288                                 die_reader_func_ftype *die_reader_func,
5289                                 void *data)
5290 {
5291   init_cutu_and_read_dies_no_follow (this_cu,
5292                                      get_abbrev_section_for_cu (this_cu),
5293                                      NULL,
5294                                      die_reader_func, data);
5295 }
5296 \f
5297 /* Type Unit Groups.
5298
5299    Type Unit Groups are a way to collapse the set of all TUs (type units) into
5300    a more manageable set.  The grouping is done by DW_AT_stmt_list entry
5301    so that all types coming from the same compilation (.o file) are grouped
5302    together.  A future step could be to put the types in the same symtab as
5303    the CU the types ultimately came from.  */
5304
5305 static hashval_t
5306 hash_type_unit_group (const void *item)
5307 {
5308   const struct type_unit_group *tu_group = item;
5309
5310   return hash_stmt_list_entry (&tu_group->hash);
5311 }
5312
5313 static int
5314 eq_type_unit_group (const void *item_lhs, const void *item_rhs)
5315 {
5316   const struct type_unit_group *lhs = item_lhs;
5317   const struct type_unit_group *rhs = item_rhs;
5318
5319   return eq_stmt_list_entry (&lhs->hash, &rhs->hash);
5320 }
5321
5322 /* Allocate a hash table for type unit groups.  */
5323
5324 static htab_t
5325 allocate_type_unit_groups_table (void)
5326 {
5327   return htab_create_alloc_ex (3,
5328                                hash_type_unit_group,
5329                                eq_type_unit_group,
5330                                NULL,
5331                                &dwarf2_per_objfile->objfile->objfile_obstack,
5332                                hashtab_obstack_allocate,
5333                                dummy_obstack_deallocate);
5334 }
5335
5336 /* Type units that don't have DW_AT_stmt_list are grouped into their own
5337    partial symtabs.  We combine several TUs per psymtab to not let the size
5338    of any one psymtab grow too big.  */
5339 #define NO_STMT_LIST_TYPE_UNIT_PSYMTAB (1 << 31)
5340 #define NO_STMT_LIST_TYPE_UNIT_PSYMTAB_SIZE 10
5341
5342 /* Helper routine for get_type_unit_group.
5343    Create the type_unit_group object used to hold one or more TUs.  */
5344
5345 static struct type_unit_group *
5346 create_type_unit_group (struct dwarf2_cu *cu, sect_offset line_offset_struct)
5347 {
5348   struct objfile *objfile = dwarf2_per_objfile->objfile;
5349   struct dwarf2_per_cu_data *per_cu;
5350   struct type_unit_group *tu_group;
5351
5352   tu_group = OBSTACK_ZALLOC (&objfile->objfile_obstack,
5353                              struct type_unit_group);
5354   per_cu = &tu_group->per_cu;
5355   per_cu->objfile = objfile;
5356
5357   if (dwarf2_per_objfile->using_index)
5358     {
5359       per_cu->v.quick = OBSTACK_ZALLOC (&objfile->objfile_obstack,
5360                                         struct dwarf2_per_cu_quick_data);
5361     }
5362   else
5363     {
5364       unsigned int line_offset = line_offset_struct.sect_off;
5365       struct partial_symtab *pst;
5366       char *name;
5367
5368       /* Give the symtab a useful name for debug purposes.  */
5369       if ((line_offset & NO_STMT_LIST_TYPE_UNIT_PSYMTAB) != 0)
5370         name = xstrprintf ("<type_units_%d>",
5371                            (line_offset & ~NO_STMT_LIST_TYPE_UNIT_PSYMTAB));
5372       else
5373         name = xstrprintf ("<type_units_at_0x%x>", line_offset);
5374
5375       pst = create_partial_symtab (per_cu, name);
5376       pst->anonymous = 1;
5377
5378       xfree (name);
5379     }
5380
5381   tu_group->hash.dwo_unit = cu->dwo_unit;
5382   tu_group->hash.line_offset = line_offset_struct;
5383
5384   return tu_group;
5385 }
5386
5387 /* Look up the type_unit_group for type unit CU, and create it if necessary.
5388    STMT_LIST is a DW_AT_stmt_list attribute.  */
5389
5390 static struct type_unit_group *
5391 get_type_unit_group (struct dwarf2_cu *cu, const struct attribute *stmt_list)
5392 {
5393   struct tu_stats *tu_stats = &dwarf2_per_objfile->tu_stats;
5394   struct type_unit_group *tu_group;
5395   void **slot;
5396   unsigned int line_offset;
5397   struct type_unit_group type_unit_group_for_lookup;
5398
5399   if (dwarf2_per_objfile->type_unit_groups == NULL)
5400     {
5401       dwarf2_per_objfile->type_unit_groups =
5402         allocate_type_unit_groups_table ();
5403     }
5404
5405   /* Do we need to create a new group, or can we use an existing one?  */
5406
5407   if (stmt_list)
5408     {
5409       line_offset = DW_UNSND (stmt_list);
5410       ++tu_stats->nr_symtab_sharers;
5411     }
5412   else
5413     {
5414       /* Ugh, no stmt_list.  Rare, but we have to handle it.
5415          We can do various things here like create one group per TU or
5416          spread them over multiple groups to split up the expansion work.
5417          To avoid worst case scenarios (too many groups or too large groups)
5418          we, umm, group them in bunches.  */
5419       line_offset = (NO_STMT_LIST_TYPE_UNIT_PSYMTAB
5420                      | (tu_stats->nr_stmt_less_type_units
5421                         / NO_STMT_LIST_TYPE_UNIT_PSYMTAB_SIZE));
5422       ++tu_stats->nr_stmt_less_type_units;
5423     }
5424
5425   type_unit_group_for_lookup.hash.dwo_unit = cu->dwo_unit;
5426   type_unit_group_for_lookup.hash.line_offset.sect_off = line_offset;
5427   slot = htab_find_slot (dwarf2_per_objfile->type_unit_groups,
5428                          &type_unit_group_for_lookup, INSERT);
5429   if (*slot != NULL)
5430     {
5431       tu_group = *slot;
5432       gdb_assert (tu_group != NULL);
5433     }
5434   else
5435     {
5436       sect_offset line_offset_struct;
5437
5438       line_offset_struct.sect_off = line_offset;
5439       tu_group = create_type_unit_group (cu, line_offset_struct);
5440       *slot = tu_group;
5441       ++tu_stats->nr_symtabs;
5442     }
5443
5444   return tu_group;
5445 }
5446
5447 /* Struct used to sort TUs by their abbreviation table offset.  */
5448
5449 struct tu_abbrev_offset
5450 {
5451   struct signatured_type *sig_type;
5452   sect_offset abbrev_offset;
5453 };
5454
5455 /* Helper routine for build_type_unit_groups, passed to qsort.  */
5456
5457 static int
5458 sort_tu_by_abbrev_offset (const void *ap, const void *bp)
5459 {
5460   const struct tu_abbrev_offset * const *a = ap;
5461   const struct tu_abbrev_offset * const *b = bp;
5462   unsigned int aoff = (*a)->abbrev_offset.sect_off;
5463   unsigned int boff = (*b)->abbrev_offset.sect_off;
5464
5465   return (aoff > boff) - (aoff < boff);
5466 }
5467
5468 /* A helper function to add a type_unit_group to a table.  */
5469
5470 static int
5471 add_type_unit_group_to_table (void **slot, void *datum)
5472 {
5473   struct type_unit_group *tu_group = *slot;
5474   struct type_unit_group ***datap = datum;
5475
5476   **datap = tu_group;
5477   ++*datap;
5478
5479   return 1;
5480 }
5481
5482 /* Efficiently read all the type units, calling init_cutu_and_read_dies on
5483    each one passing FUNC,DATA.
5484
5485    The efficiency is because we sort TUs by the abbrev table they use and
5486    only read each abbrev table once.  In one program there are 200K TUs
5487    sharing 8K abbrev tables.
5488
5489    The main purpose of this function is to support building the
5490    dwarf2_per_objfile->type_unit_groups table.
5491    TUs typically share the DW_AT_stmt_list of the CU they came from, so we
5492    can collapse the search space by grouping them by stmt_list.
5493    The savings can be significant, in the same program from above the 200K TUs
5494    share 8K stmt_list tables.
5495
5496    FUNC is expected to call get_type_unit_group, which will create the
5497    struct type_unit_group if necessary and add it to
5498    dwarf2_per_objfile->type_unit_groups.  */
5499
5500 static void
5501 build_type_unit_groups (die_reader_func_ftype *func, void *data)
5502 {
5503   struct objfile *objfile = dwarf2_per_objfile->objfile;
5504   struct tu_stats *tu_stats = &dwarf2_per_objfile->tu_stats;
5505   struct cleanup *cleanups;
5506   struct abbrev_table *abbrev_table;
5507   sect_offset abbrev_offset;
5508   struct tu_abbrev_offset *sorted_by_abbrev;
5509   struct type_unit_group **iter;
5510   int i;
5511
5512   /* It's up to the caller to not call us multiple times.  */
5513   gdb_assert (dwarf2_per_objfile->type_unit_groups == NULL);
5514
5515   if (dwarf2_per_objfile->n_type_units == 0)
5516     return;
5517
5518   /* TUs typically share abbrev tables, and there can be way more TUs than
5519      abbrev tables.  Sort by abbrev table to reduce the number of times we
5520      read each abbrev table in.
5521      Alternatives are to punt or to maintain a cache of abbrev tables.
5522      This is simpler and efficient enough for now.
5523
5524      Later we group TUs by their DW_AT_stmt_list value (as this defines the
5525      symtab to use).  Typically TUs with the same abbrev offset have the same
5526      stmt_list value too so in practice this should work well.
5527
5528      The basic algorithm here is:
5529
5530       sort TUs by abbrev table
5531       for each TU with same abbrev table:
5532         read abbrev table if first user
5533         read TU top level DIE
5534           [IWBN if DWO skeletons had DW_AT_stmt_list]
5535         call FUNC  */
5536
5537   if (dwarf2_read_debug)
5538     fprintf_unfiltered (gdb_stdlog, "Building type unit groups ...\n");
5539
5540   /* Sort in a separate table to maintain the order of all_type_units
5541      for .gdb_index: TU indices directly index all_type_units.  */
5542   sorted_by_abbrev = XNEWVEC (struct tu_abbrev_offset,
5543                               dwarf2_per_objfile->n_type_units);
5544   for (i = 0; i < dwarf2_per_objfile->n_type_units; ++i)
5545     {
5546       struct signatured_type *sig_type = dwarf2_per_objfile->all_type_units[i];
5547
5548       sorted_by_abbrev[i].sig_type = sig_type;
5549       sorted_by_abbrev[i].abbrev_offset =
5550         read_abbrev_offset (sig_type->per_cu.section,
5551                             sig_type->per_cu.offset);
5552     }
5553   cleanups = make_cleanup (xfree, sorted_by_abbrev);
5554   qsort (sorted_by_abbrev, dwarf2_per_objfile->n_type_units,
5555          sizeof (struct tu_abbrev_offset), sort_tu_by_abbrev_offset);
5556
5557   /* Note: In the .gdb_index case, get_type_unit_group may have already been
5558      called any number of times, so we don't reset tu_stats here.  */
5559
5560   abbrev_offset.sect_off = ~(unsigned) 0;
5561   abbrev_table = NULL;
5562   make_cleanup (abbrev_table_free_cleanup, &abbrev_table);
5563
5564   for (i = 0; i < dwarf2_per_objfile->n_type_units; ++i)
5565     {
5566       const struct tu_abbrev_offset *tu = &sorted_by_abbrev[i];
5567
5568       /* Switch to the next abbrev table if necessary.  */
5569       if (abbrev_table == NULL
5570           || tu->abbrev_offset.sect_off != abbrev_offset.sect_off)
5571         {
5572           if (abbrev_table != NULL)
5573             {
5574               abbrev_table_free (abbrev_table);
5575               /* Reset to NULL in case abbrev_table_read_table throws
5576                  an error: abbrev_table_free_cleanup will get called.  */
5577               abbrev_table = NULL;
5578             }
5579           abbrev_offset = tu->abbrev_offset;
5580           abbrev_table =
5581             abbrev_table_read_table (&dwarf2_per_objfile->abbrev,
5582                                      abbrev_offset);
5583           ++tu_stats->nr_uniq_abbrev_tables;
5584         }
5585
5586       init_cutu_and_read_dies (&tu->sig_type->per_cu, abbrev_table, 0, 0,
5587                                func, data);
5588     }
5589
5590   /* type_unit_groups can be NULL if there is an error in the debug info.
5591      Just create an empty table so the rest of gdb doesn't have to watch
5592      for this error case.  */
5593   if (dwarf2_per_objfile->type_unit_groups == NULL)
5594     {
5595       dwarf2_per_objfile->type_unit_groups =
5596         allocate_type_unit_groups_table ();
5597       dwarf2_per_objfile->n_type_unit_groups = 0;
5598     }
5599
5600   /* Create a vector of pointers to primary type units to make it easy to
5601      iterate over them and CUs.  See dw2_get_primary_cu.  */
5602   dwarf2_per_objfile->n_type_unit_groups =
5603     htab_elements (dwarf2_per_objfile->type_unit_groups);
5604   dwarf2_per_objfile->all_type_unit_groups =
5605     obstack_alloc (&objfile->objfile_obstack,
5606                    dwarf2_per_objfile->n_type_unit_groups
5607                    * sizeof (struct type_unit_group *));
5608   iter = &dwarf2_per_objfile->all_type_unit_groups[0];
5609   htab_traverse_noresize (dwarf2_per_objfile->type_unit_groups,
5610                           add_type_unit_group_to_table, &iter);
5611   gdb_assert (iter - &dwarf2_per_objfile->all_type_unit_groups[0]
5612               == dwarf2_per_objfile->n_type_unit_groups);
5613
5614   do_cleanups (cleanups);
5615
5616   if (dwarf2_read_debug)
5617     {
5618       fprintf_unfiltered (gdb_stdlog, "Done building type unit groups:\n");
5619       fprintf_unfiltered (gdb_stdlog, "  %d TUs\n",
5620                           dwarf2_per_objfile->n_type_units);
5621       fprintf_unfiltered (gdb_stdlog, "  %d uniq abbrev tables\n",
5622                           tu_stats->nr_uniq_abbrev_tables);
5623       fprintf_unfiltered (gdb_stdlog, "  %d symtabs from stmt_list entries\n",
5624                           tu_stats->nr_symtabs);
5625       fprintf_unfiltered (gdb_stdlog, "  %d symtab sharers\n",
5626                           tu_stats->nr_symtab_sharers);
5627       fprintf_unfiltered (gdb_stdlog, "  %d type units without a stmt_list\n",
5628                           tu_stats->nr_stmt_less_type_units);
5629     }
5630 }
5631 \f
5632 /* Partial symbol tables.  */
5633
5634 /* Create a psymtab named NAME and assign it to PER_CU.
5635
5636    The caller must fill in the following details:
5637    dirname, textlow, texthigh.  */
5638
5639 static struct partial_symtab *
5640 create_partial_symtab (struct dwarf2_per_cu_data *per_cu, const char *name)
5641 {
5642   struct objfile *objfile = per_cu->objfile;
5643   struct partial_symtab *pst;
5644
5645   pst = start_psymtab_common (objfile, objfile->section_offsets,
5646                               name, 0,
5647                               objfile->global_psymbols.next,
5648                               objfile->static_psymbols.next);
5649
5650   pst->psymtabs_addrmap_supported = 1;
5651
5652   /* This is the glue that links PST into GDB's symbol API.  */
5653   pst->read_symtab_private = per_cu;
5654   pst->read_symtab = dwarf2_read_symtab;
5655   per_cu->v.psymtab = pst;
5656
5657   return pst;
5658 }
5659
5660 /* The DATA object passed to process_psymtab_comp_unit_reader has this
5661    type.  */
5662
5663 struct process_psymtab_comp_unit_data
5664 {
5665   /* True if we are reading a DW_TAG_partial_unit.  */
5666
5667   int want_partial_unit;
5668
5669   /* The "pretend" language that is used if the CU doesn't declare a
5670      language.  */
5671
5672   enum language pretend_language;
5673 };
5674
5675 /* die_reader_func for process_psymtab_comp_unit.  */
5676
5677 static void
5678 process_psymtab_comp_unit_reader (const struct die_reader_specs *reader,
5679                                   const gdb_byte *info_ptr,
5680                                   struct die_info *comp_unit_die,
5681                                   int has_children,
5682                                   void *data)
5683 {
5684   struct dwarf2_cu *cu = reader->cu;
5685   struct objfile *objfile = cu->objfile;
5686   struct dwarf2_per_cu_data *per_cu = cu->per_cu;
5687   struct attribute *attr;
5688   CORE_ADDR baseaddr;
5689   CORE_ADDR best_lowpc = 0, best_highpc = 0;
5690   struct partial_symtab *pst;
5691   int has_pc_info;
5692   const char *filename;
5693   struct process_psymtab_comp_unit_data *info = data;
5694
5695   if (comp_unit_die->tag == DW_TAG_partial_unit && !info->want_partial_unit)
5696     return;
5697
5698   gdb_assert (! per_cu->is_debug_types);
5699
5700   prepare_one_comp_unit (cu, comp_unit_die, info->pretend_language);
5701
5702   cu->list_in_scope = &file_symbols;
5703
5704   /* Allocate a new partial symbol table structure.  */
5705   attr = dwarf2_attr (comp_unit_die, DW_AT_name, cu);
5706   if (attr == NULL || !DW_STRING (attr))
5707     filename = "";
5708   else
5709     filename = DW_STRING (attr);
5710
5711   pst = create_partial_symtab (per_cu, filename);
5712
5713   /* This must be done before calling dwarf2_build_include_psymtabs.  */
5714   attr = dwarf2_attr (comp_unit_die, DW_AT_comp_dir, cu);
5715   if (attr != NULL)
5716     pst->dirname = DW_STRING (attr);
5717
5718   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
5719
5720   dwarf2_find_base_address (comp_unit_die, cu);
5721
5722   /* Possibly set the default values of LOWPC and HIGHPC from
5723      `DW_AT_ranges'.  */
5724   has_pc_info = dwarf2_get_pc_bounds (comp_unit_die, &best_lowpc,
5725                                       &best_highpc, cu, pst);
5726   if (has_pc_info == 1 && best_lowpc < best_highpc)
5727     /* Store the contiguous range if it is not empty; it can be empty for
5728        CUs with no code.  */
5729     addrmap_set_empty (objfile->psymtabs_addrmap,
5730                        best_lowpc + baseaddr,
5731                        best_highpc + baseaddr - 1, pst);
5732
5733   /* Check if comp unit has_children.
5734      If so, read the rest of the partial symbols from this comp unit.
5735      If not, there's no more debug_info for this comp unit.  */
5736   if (has_children)
5737     {
5738       struct partial_die_info *first_die;
5739       CORE_ADDR lowpc, highpc;
5740
5741       lowpc = ((CORE_ADDR) -1);
5742       highpc = ((CORE_ADDR) 0);
5743
5744       first_die = load_partial_dies (reader, info_ptr, 1);
5745
5746       scan_partial_symbols (first_die, &lowpc, &highpc,
5747                             ! has_pc_info, cu);
5748
5749       /* If we didn't find a lowpc, set it to highpc to avoid
5750          complaints from `maint check'.  */
5751       if (lowpc == ((CORE_ADDR) -1))
5752         lowpc = highpc;
5753
5754       /* If the compilation unit didn't have an explicit address range,
5755          then use the information extracted from its child dies.  */
5756       if (! has_pc_info)
5757         {
5758           best_lowpc = lowpc;
5759           best_highpc = highpc;
5760         }
5761     }
5762   pst->textlow = best_lowpc + baseaddr;
5763   pst->texthigh = best_highpc + baseaddr;
5764
5765   pst->n_global_syms = objfile->global_psymbols.next -
5766     (objfile->global_psymbols.list + pst->globals_offset);
5767   pst->n_static_syms = objfile->static_psymbols.next -
5768     (objfile->static_psymbols.list + pst->statics_offset);
5769   sort_pst_symbols (objfile, pst);
5770
5771   if (!VEC_empty (dwarf2_per_cu_ptr, cu->per_cu->imported_symtabs))
5772     {
5773       int i;
5774       int len = VEC_length (dwarf2_per_cu_ptr, cu->per_cu->imported_symtabs);
5775       struct dwarf2_per_cu_data *iter;
5776
5777       /* Fill in 'dependencies' here; we fill in 'users' in a
5778          post-pass.  */
5779       pst->number_of_dependencies = len;
5780       pst->dependencies = obstack_alloc (&objfile->objfile_obstack,
5781                                          len * sizeof (struct symtab *));
5782       for (i = 0;
5783            VEC_iterate (dwarf2_per_cu_ptr, cu->per_cu->imported_symtabs,
5784                         i, iter);
5785            ++i)
5786         pst->dependencies[i] = iter->v.psymtab;
5787
5788       VEC_free (dwarf2_per_cu_ptr, cu->per_cu->imported_symtabs);
5789     }
5790
5791   /* Get the list of files included in the current compilation unit,
5792      and build a psymtab for each of them.  */
5793   dwarf2_build_include_psymtabs (cu, comp_unit_die, pst);
5794
5795   if (dwarf2_read_debug)
5796     {
5797       struct gdbarch *gdbarch = get_objfile_arch (objfile);
5798
5799       fprintf_unfiltered (gdb_stdlog,
5800                           "Psymtab for %s unit @0x%x: %s - %s"
5801                           ", %d global, %d static syms\n",
5802                           per_cu->is_debug_types ? "type" : "comp",
5803                           per_cu->offset.sect_off,
5804                           paddress (gdbarch, pst->textlow),
5805                           paddress (gdbarch, pst->texthigh),
5806                           pst->n_global_syms, pst->n_static_syms);
5807     }
5808 }
5809
5810 /* Subroutine of dwarf2_build_psymtabs_hard to simplify it.
5811    Process compilation unit THIS_CU for a psymtab.  */
5812
5813 static void
5814 process_psymtab_comp_unit (struct dwarf2_per_cu_data *this_cu,
5815                            int want_partial_unit,
5816                            enum language pretend_language)
5817 {
5818   struct process_psymtab_comp_unit_data info;
5819
5820   /* If this compilation unit was already read in, free the
5821      cached copy in order to read it in again.  This is
5822      necessary because we skipped some symbols when we first
5823      read in the compilation unit (see load_partial_dies).
5824      This problem could be avoided, but the benefit is unclear.  */
5825   if (this_cu->cu != NULL)
5826     free_one_cached_comp_unit (this_cu);
5827
5828   gdb_assert (! this_cu->is_debug_types);
5829   info.want_partial_unit = want_partial_unit;
5830   info.pretend_language = pretend_language;
5831   init_cutu_and_read_dies (this_cu, NULL, 0, 0,
5832                            process_psymtab_comp_unit_reader,
5833                            &info);
5834
5835   /* Age out any secondary CUs.  */
5836   age_cached_comp_units ();
5837 }
5838
5839 /* Reader function for build_type_psymtabs.  */
5840
5841 static void
5842 build_type_psymtabs_reader (const struct die_reader_specs *reader,
5843                             const gdb_byte *info_ptr,
5844                             struct die_info *type_unit_die,
5845                             int has_children,
5846                             void *data)
5847 {
5848   struct objfile *objfile = dwarf2_per_objfile->objfile;
5849   struct dwarf2_cu *cu = reader->cu;
5850   struct dwarf2_per_cu_data *per_cu = cu->per_cu;
5851   struct signatured_type *sig_type;
5852   struct type_unit_group *tu_group;
5853   struct attribute *attr;
5854   struct partial_die_info *first_die;
5855   CORE_ADDR lowpc, highpc;
5856   struct partial_symtab *pst;
5857
5858   gdb_assert (data == NULL);
5859   gdb_assert (per_cu->is_debug_types);
5860   sig_type = (struct signatured_type *) per_cu;
5861
5862   if (! has_children)
5863     return;
5864
5865   attr = dwarf2_attr_no_follow (type_unit_die, DW_AT_stmt_list);
5866   tu_group = get_type_unit_group (cu, attr);
5867
5868   VEC_safe_push (sig_type_ptr, tu_group->tus, sig_type);
5869
5870   prepare_one_comp_unit (cu, type_unit_die, language_minimal);
5871   cu->list_in_scope = &file_symbols;
5872   pst = create_partial_symtab (per_cu, "");
5873   pst->anonymous = 1;
5874
5875   first_die = load_partial_dies (reader, info_ptr, 1);
5876
5877   lowpc = (CORE_ADDR) -1;
5878   highpc = (CORE_ADDR) 0;
5879   scan_partial_symbols (first_die, &lowpc, &highpc, 0, cu);
5880
5881   pst->n_global_syms = objfile->global_psymbols.next -
5882     (objfile->global_psymbols.list + pst->globals_offset);
5883   pst->n_static_syms = objfile->static_psymbols.next -
5884     (objfile->static_psymbols.list + pst->statics_offset);
5885   sort_pst_symbols (objfile, pst);
5886 }
5887
5888 /* Traversal function for build_type_psymtabs.  */
5889
5890 static int
5891 build_type_psymtab_dependencies (void **slot, void *info)
5892 {
5893   struct objfile *objfile = dwarf2_per_objfile->objfile;
5894   struct type_unit_group *tu_group = (struct type_unit_group *) *slot;
5895   struct dwarf2_per_cu_data *per_cu = &tu_group->per_cu;
5896   struct partial_symtab *pst = per_cu->v.psymtab;
5897   int len = VEC_length (sig_type_ptr, tu_group->tus);
5898   struct signatured_type *iter;
5899   int i;
5900
5901   gdb_assert (len > 0);
5902   gdb_assert (IS_TYPE_UNIT_GROUP (per_cu));
5903
5904   pst->number_of_dependencies = len;
5905   pst->dependencies = obstack_alloc (&objfile->objfile_obstack,
5906                                      len * sizeof (struct psymtab *));
5907   for (i = 0;
5908        VEC_iterate (sig_type_ptr, tu_group->tus, i, iter);
5909        ++i)
5910     {
5911       gdb_assert (iter->per_cu.is_debug_types);
5912       pst->dependencies[i] = iter->per_cu.v.psymtab;
5913       iter->type_unit_group = tu_group;
5914     }
5915
5916   VEC_free (sig_type_ptr, tu_group->tus);
5917
5918   return 1;
5919 }
5920
5921 /* Subroutine of dwarf2_build_psymtabs_hard to simplify it.
5922    Build partial symbol tables for the .debug_types comp-units.  */
5923
5924 static void
5925 build_type_psymtabs (struct objfile *objfile)
5926 {
5927   if (! create_all_type_units (objfile))
5928     return;
5929
5930   build_type_unit_groups (build_type_psymtabs_reader, NULL);
5931
5932   /* Now that all TUs have been processed we can fill in the dependencies.  */
5933   htab_traverse_noresize (dwarf2_per_objfile->type_unit_groups,
5934                           build_type_psymtab_dependencies, NULL);
5935 }
5936
5937 /* A cleanup function that clears objfile's psymtabs_addrmap field.  */
5938
5939 static void
5940 psymtabs_addrmap_cleanup (void *o)
5941 {
5942   struct objfile *objfile = o;
5943
5944   objfile->psymtabs_addrmap = NULL;
5945 }
5946
5947 /* Compute the 'user' field for each psymtab in OBJFILE.  */
5948
5949 static void
5950 set_partial_user (struct objfile *objfile)
5951 {
5952   int i;
5953
5954   for (i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
5955     {
5956       struct dwarf2_per_cu_data *per_cu = dw2_get_cu (i);
5957       struct partial_symtab *pst = per_cu->v.psymtab;
5958       int j;
5959
5960       if (pst == NULL)
5961         continue;
5962
5963       for (j = 0; j < pst->number_of_dependencies; ++j)
5964         {
5965           /* Set the 'user' field only if it is not already set.  */
5966           if (pst->dependencies[j]->user == NULL)
5967             pst->dependencies[j]->user = pst;
5968         }
5969     }
5970 }
5971
5972 /* Build the partial symbol table by doing a quick pass through the
5973    .debug_info and .debug_abbrev sections.  */
5974
5975 static void
5976 dwarf2_build_psymtabs_hard (struct objfile *objfile)
5977 {
5978   struct cleanup *back_to, *addrmap_cleanup;
5979   struct obstack temp_obstack;
5980   int i;
5981
5982   if (dwarf2_read_debug)
5983     {
5984       fprintf_unfiltered (gdb_stdlog, "Building psymtabs of objfile %s ...\n",
5985                           objfile_name (objfile));
5986     }
5987
5988   dwarf2_per_objfile->reading_partial_symbols = 1;
5989
5990   dwarf2_read_section (objfile, &dwarf2_per_objfile->info);
5991
5992   /* Any cached compilation units will be linked by the per-objfile
5993      read_in_chain.  Make sure to free them when we're done.  */
5994   back_to = make_cleanup (free_cached_comp_units, NULL);
5995
5996   build_type_psymtabs (objfile);
5997
5998   create_all_comp_units (objfile);
5999
6000   /* Create a temporary address map on a temporary obstack.  We later
6001      copy this to the final obstack.  */
6002   obstack_init (&temp_obstack);
6003   make_cleanup_obstack_free (&temp_obstack);
6004   objfile->psymtabs_addrmap = addrmap_create_mutable (&temp_obstack);
6005   addrmap_cleanup = make_cleanup (psymtabs_addrmap_cleanup, objfile);
6006
6007   for (i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
6008     {
6009       struct dwarf2_per_cu_data *per_cu = dw2_get_cu (i);
6010
6011       process_psymtab_comp_unit (per_cu, 0, language_minimal);
6012     }
6013
6014   set_partial_user (objfile);
6015
6016   objfile->psymtabs_addrmap = addrmap_create_fixed (objfile->psymtabs_addrmap,
6017                                                     &objfile->objfile_obstack);
6018   discard_cleanups (addrmap_cleanup);
6019
6020   do_cleanups (back_to);
6021
6022   if (dwarf2_read_debug)
6023     fprintf_unfiltered (gdb_stdlog, "Done building psymtabs of %s\n",
6024                         objfile_name (objfile));
6025 }
6026
6027 /* die_reader_func for load_partial_comp_unit.  */
6028
6029 static void
6030 load_partial_comp_unit_reader (const struct die_reader_specs *reader,
6031                                const gdb_byte *info_ptr,
6032                                struct die_info *comp_unit_die,
6033                                int has_children,
6034                                void *data)
6035 {
6036   struct dwarf2_cu *cu = reader->cu;
6037
6038   prepare_one_comp_unit (cu, comp_unit_die, language_minimal);
6039
6040   /* Check if comp unit has_children.
6041      If so, read the rest of the partial symbols from this comp unit.
6042      If not, there's no more debug_info for this comp unit.  */
6043   if (has_children)
6044     load_partial_dies (reader, info_ptr, 0);
6045 }
6046
6047 /* Load the partial DIEs for a secondary CU into memory.
6048    This is also used when rereading a primary CU with load_all_dies.  */
6049
6050 static void
6051 load_partial_comp_unit (struct dwarf2_per_cu_data *this_cu)
6052 {
6053   init_cutu_and_read_dies (this_cu, NULL, 1, 1,
6054                            load_partial_comp_unit_reader, NULL);
6055 }
6056
6057 static void
6058 read_comp_units_from_section (struct objfile *objfile,
6059                               struct dwarf2_section_info *section,
6060                               unsigned int is_dwz,
6061                               int *n_allocated,
6062                               int *n_comp_units,
6063                               struct dwarf2_per_cu_data ***all_comp_units)
6064 {
6065   const gdb_byte *info_ptr;
6066   bfd *abfd = section->asection->owner;
6067
6068   if (dwarf2_read_debug)
6069     fprintf_unfiltered (gdb_stdlog, "Reading %s for %s\n",
6070                         section->asection->name, bfd_get_filename (abfd));
6071
6072   dwarf2_read_section (objfile, section);
6073
6074   info_ptr = section->buffer;
6075
6076   while (info_ptr < section->buffer + section->size)
6077     {
6078       unsigned int length, initial_length_size;
6079       struct dwarf2_per_cu_data *this_cu;
6080       sect_offset offset;
6081
6082       offset.sect_off = info_ptr - section->buffer;
6083
6084       /* Read just enough information to find out where the next
6085          compilation unit is.  */
6086       length = read_initial_length (abfd, info_ptr, &initial_length_size);
6087
6088       /* Save the compilation unit for later lookup.  */
6089       this_cu = obstack_alloc (&objfile->objfile_obstack,
6090                                sizeof (struct dwarf2_per_cu_data));
6091       memset (this_cu, 0, sizeof (*this_cu));
6092       this_cu->offset = offset;
6093       this_cu->length = length + initial_length_size;
6094       this_cu->is_dwz = is_dwz;
6095       this_cu->objfile = objfile;
6096       this_cu->section = section;
6097
6098       if (*n_comp_units == *n_allocated)
6099         {
6100           *n_allocated *= 2;
6101           *all_comp_units = xrealloc (*all_comp_units,
6102                                       *n_allocated
6103                                       * sizeof (struct dwarf2_per_cu_data *));
6104         }
6105       (*all_comp_units)[*n_comp_units] = this_cu;
6106       ++*n_comp_units;
6107
6108       info_ptr = info_ptr + this_cu->length;
6109     }
6110 }
6111
6112 /* Create a list of all compilation units in OBJFILE.
6113    This is only done for -readnow and building partial symtabs.  */
6114
6115 static void
6116 create_all_comp_units (struct objfile *objfile)
6117 {
6118   int n_allocated;
6119   int n_comp_units;
6120   struct dwarf2_per_cu_data **all_comp_units;
6121   struct dwz_file *dwz;
6122
6123   n_comp_units = 0;
6124   n_allocated = 10;
6125   all_comp_units = xmalloc (n_allocated
6126                             * sizeof (struct dwarf2_per_cu_data *));
6127
6128   read_comp_units_from_section (objfile, &dwarf2_per_objfile->info, 0,
6129                                 &n_allocated, &n_comp_units, &all_comp_units);
6130
6131   dwz = dwarf2_get_dwz_file ();
6132   if (dwz != NULL)
6133     read_comp_units_from_section (objfile, &dwz->info, 1,
6134                                   &n_allocated, &n_comp_units,
6135                                   &all_comp_units);
6136
6137   dwarf2_per_objfile->all_comp_units
6138     = obstack_alloc (&objfile->objfile_obstack,
6139                      n_comp_units * sizeof (struct dwarf2_per_cu_data *));
6140   memcpy (dwarf2_per_objfile->all_comp_units, all_comp_units,
6141           n_comp_units * sizeof (struct dwarf2_per_cu_data *));
6142   xfree (all_comp_units);
6143   dwarf2_per_objfile->n_comp_units = n_comp_units;
6144 }
6145
6146 /* Process all loaded DIEs for compilation unit CU, starting at
6147    FIRST_DIE.  The caller should pass NEED_PC == 1 if the compilation
6148    unit DIE did not have PC info (DW_AT_low_pc and DW_AT_high_pc, or
6149    DW_AT_ranges).  If NEED_PC is set, then this function will set
6150    *LOWPC and *HIGHPC to the lowest and highest PC values found in CU
6151    and record the covered ranges in the addrmap.  */
6152
6153 static void
6154 scan_partial_symbols (struct partial_die_info *first_die, CORE_ADDR *lowpc,
6155                       CORE_ADDR *highpc, int need_pc, struct dwarf2_cu *cu)
6156 {
6157   struct partial_die_info *pdi;
6158
6159   /* Now, march along the PDI's, descending into ones which have
6160      interesting children but skipping the children of the other ones,
6161      until we reach the end of the compilation unit.  */
6162
6163   pdi = first_die;
6164
6165   while (pdi != NULL)
6166     {
6167       fixup_partial_die (pdi, cu);
6168
6169       /* Anonymous namespaces or modules have no name but have interesting
6170          children, so we need to look at them.  Ditto for anonymous
6171          enums.  */
6172
6173       if (pdi->name != NULL || pdi->tag == DW_TAG_namespace
6174           || pdi->tag == DW_TAG_module || pdi->tag == DW_TAG_enumeration_type
6175           || pdi->tag == DW_TAG_imported_unit)
6176         {
6177           switch (pdi->tag)
6178             {
6179             case DW_TAG_subprogram:
6180               add_partial_subprogram (pdi, lowpc, highpc, need_pc, cu);
6181               break;
6182             case DW_TAG_constant:
6183             case DW_TAG_variable:
6184             case DW_TAG_typedef:
6185             case DW_TAG_union_type:
6186               if (!pdi->is_declaration)
6187                 {
6188                   add_partial_symbol (pdi, cu);
6189                 }
6190               break;
6191             case DW_TAG_class_type:
6192             case DW_TAG_interface_type:
6193             case DW_TAG_structure_type:
6194               if (!pdi->is_declaration)
6195                 {
6196                   add_partial_symbol (pdi, cu);
6197                 }
6198               break;
6199             case DW_TAG_enumeration_type:
6200               if (!pdi->is_declaration)
6201                 add_partial_enumeration (pdi, cu);
6202               break;
6203             case DW_TAG_base_type:
6204             case DW_TAG_subrange_type:
6205               /* File scope base type definitions are added to the partial
6206                  symbol table.  */
6207               add_partial_symbol (pdi, cu);
6208               break;
6209             case DW_TAG_namespace:
6210               add_partial_namespace (pdi, lowpc, highpc, need_pc, cu);
6211               break;
6212             case DW_TAG_module:
6213               add_partial_module (pdi, lowpc, highpc, need_pc, cu);
6214               break;
6215             case DW_TAG_imported_unit:
6216               {
6217                 struct dwarf2_per_cu_data *per_cu;
6218
6219                 /* For now we don't handle imported units in type units.  */
6220                 if (cu->per_cu->is_debug_types)
6221                   {
6222                     error (_("Dwarf Error: DW_TAG_imported_unit is not"
6223                              " supported in type units [in module %s]"),
6224                            objfile_name (cu->objfile));
6225                   }
6226
6227                 per_cu = dwarf2_find_containing_comp_unit (pdi->d.offset,
6228                                                            pdi->is_dwz,
6229                                                            cu->objfile);
6230
6231                 /* Go read the partial unit, if needed.  */
6232                 if (per_cu->v.psymtab == NULL)
6233                   process_psymtab_comp_unit (per_cu, 1, cu->language);
6234
6235                 VEC_safe_push (dwarf2_per_cu_ptr,
6236                                cu->per_cu->imported_symtabs, per_cu);
6237               }
6238               break;
6239             default:
6240               break;
6241             }
6242         }
6243
6244       /* If the die has a sibling, skip to the sibling.  */
6245
6246       pdi = pdi->die_sibling;
6247     }
6248 }
6249
6250 /* Functions used to compute the fully scoped name of a partial DIE.
6251
6252    Normally, this is simple.  For C++, the parent DIE's fully scoped
6253    name is concatenated with "::" and the partial DIE's name.  For
6254    Java, the same thing occurs except that "." is used instead of "::".
6255    Enumerators are an exception; they use the scope of their parent
6256    enumeration type, i.e. the name of the enumeration type is not
6257    prepended to the enumerator.
6258
6259    There are two complexities.  One is DW_AT_specification; in this
6260    case "parent" means the parent of the target of the specification,
6261    instead of the direct parent of the DIE.  The other is compilers
6262    which do not emit DW_TAG_namespace; in this case we try to guess
6263    the fully qualified name of structure types from their members'
6264    linkage names.  This must be done using the DIE's children rather
6265    than the children of any DW_AT_specification target.  We only need
6266    to do this for structures at the top level, i.e. if the target of
6267    any DW_AT_specification (if any; otherwise the DIE itself) does not
6268    have a parent.  */
6269
6270 /* Compute the scope prefix associated with PDI's parent, in
6271    compilation unit CU.  The result will be allocated on CU's
6272    comp_unit_obstack, or a copy of the already allocated PDI->NAME
6273    field.  NULL is returned if no prefix is necessary.  */
6274 static const char *
6275 partial_die_parent_scope (struct partial_die_info *pdi,
6276                           struct dwarf2_cu *cu)
6277 {
6278   const char *grandparent_scope;
6279   struct partial_die_info *parent, *real_pdi;
6280
6281   /* We need to look at our parent DIE; if we have a DW_AT_specification,
6282      then this means the parent of the specification DIE.  */
6283
6284   real_pdi = pdi;
6285   while (real_pdi->has_specification)
6286     real_pdi = find_partial_die (real_pdi->spec_offset,
6287                                  real_pdi->spec_is_dwz, cu);
6288
6289   parent = real_pdi->die_parent;
6290   if (parent == NULL)
6291     return NULL;
6292
6293   if (parent->scope_set)
6294     return parent->scope;
6295
6296   fixup_partial_die (parent, cu);
6297
6298   grandparent_scope = partial_die_parent_scope (parent, cu);
6299
6300   /* GCC 4.0 and 4.1 had a bug (PR c++/28460) where they generated bogus
6301      DW_TAG_namespace DIEs with a name of "::" for the global namespace.
6302      Work around this problem here.  */
6303   if (cu->language == language_cplus
6304       && parent->tag == DW_TAG_namespace
6305       && strcmp (parent->name, "::") == 0
6306       && grandparent_scope == NULL)
6307     {
6308       parent->scope = NULL;
6309       parent->scope_set = 1;
6310       return NULL;
6311     }
6312
6313   if (pdi->tag == DW_TAG_enumerator)
6314     /* Enumerators should not get the name of the enumeration as a prefix.  */
6315     parent->scope = grandparent_scope;
6316   else if (parent->tag == DW_TAG_namespace
6317       || parent->tag == DW_TAG_module
6318       || parent->tag == DW_TAG_structure_type
6319       || parent->tag == DW_TAG_class_type
6320       || parent->tag == DW_TAG_interface_type
6321       || parent->tag == DW_TAG_union_type
6322       || parent->tag == DW_TAG_enumeration_type)
6323     {
6324       if (grandparent_scope == NULL)
6325         parent->scope = parent->name;
6326       else
6327         parent->scope = typename_concat (&cu->comp_unit_obstack,
6328                                          grandparent_scope,
6329                                          parent->name, 0, cu);
6330     }
6331   else
6332     {
6333       /* FIXME drow/2004-04-01: What should we be doing with
6334          function-local names?  For partial symbols, we should probably be
6335          ignoring them.  */
6336       complaint (&symfile_complaints,
6337                  _("unhandled containing DIE tag %d for DIE at %d"),
6338                  parent->tag, pdi->offset.sect_off);
6339       parent->scope = grandparent_scope;
6340     }
6341
6342   parent->scope_set = 1;
6343   return parent->scope;
6344 }
6345
6346 /* Return the fully scoped name associated with PDI, from compilation unit
6347    CU.  The result will be allocated with malloc.  */
6348
6349 static char *
6350 partial_die_full_name (struct partial_die_info *pdi,
6351                        struct dwarf2_cu *cu)
6352 {
6353   const char *parent_scope;
6354
6355   /* If this is a template instantiation, we can not work out the
6356      template arguments from partial DIEs.  So, unfortunately, we have
6357      to go through the full DIEs.  At least any work we do building
6358      types here will be reused if full symbols are loaded later.  */
6359   if (pdi->has_template_arguments)
6360     {
6361       fixup_partial_die (pdi, cu);
6362
6363       if (pdi->name != NULL && strchr (pdi->name, '<') == NULL)
6364         {
6365           struct die_info *die;
6366           struct attribute attr;
6367           struct dwarf2_cu *ref_cu = cu;
6368
6369           /* DW_FORM_ref_addr is using section offset.  */
6370           attr.name = 0;
6371           attr.form = DW_FORM_ref_addr;
6372           attr.u.unsnd = pdi->offset.sect_off;
6373           die = follow_die_ref (NULL, &attr, &ref_cu);
6374
6375           return xstrdup (dwarf2_full_name (NULL, die, ref_cu));
6376         }
6377     }
6378
6379   parent_scope = partial_die_parent_scope (pdi, cu);
6380   if (parent_scope == NULL)
6381     return NULL;
6382   else
6383     return typename_concat (NULL, parent_scope, pdi->name, 0, cu);
6384 }
6385
6386 static void
6387 add_partial_symbol (struct partial_die_info *pdi, struct dwarf2_cu *cu)
6388 {
6389   struct objfile *objfile = cu->objfile;
6390   CORE_ADDR addr = 0;
6391   const char *actual_name = NULL;
6392   CORE_ADDR baseaddr;
6393   char *built_actual_name;
6394
6395   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
6396
6397   built_actual_name = partial_die_full_name (pdi, cu);
6398   if (built_actual_name != NULL)
6399     actual_name = built_actual_name;
6400
6401   if (actual_name == NULL)
6402     actual_name = pdi->name;
6403
6404   switch (pdi->tag)
6405     {
6406     case DW_TAG_subprogram:
6407       if (pdi->is_external || cu->language == language_ada)
6408         {
6409           /* brobecker/2007-12-26: Normally, only "external" DIEs are part
6410              of the global scope.  But in Ada, we want to be able to access
6411              nested procedures globally.  So all Ada subprograms are stored
6412              in the global scope.  */
6413           /* prim_record_minimal_symbol (actual_name, pdi->lowpc + baseaddr,
6414              mst_text, objfile); */
6415           add_psymbol_to_list (actual_name, strlen (actual_name),
6416                                built_actual_name != NULL,
6417                                VAR_DOMAIN, LOC_BLOCK,
6418                                &objfile->global_psymbols,
6419                                0, pdi->lowpc + baseaddr,
6420                                cu->language, objfile);
6421         }
6422       else
6423         {
6424           /* prim_record_minimal_symbol (actual_name, pdi->lowpc + baseaddr,
6425              mst_file_text, objfile); */
6426           add_psymbol_to_list (actual_name, strlen (actual_name),
6427                                built_actual_name != NULL,
6428                                VAR_DOMAIN, LOC_BLOCK,
6429                                &objfile->static_psymbols,
6430                                0, pdi->lowpc + baseaddr,
6431                                cu->language, objfile);
6432         }
6433       break;
6434     case DW_TAG_constant:
6435       {
6436         struct psymbol_allocation_list *list;
6437
6438         if (pdi->is_external)
6439           list = &objfile->global_psymbols;
6440         else
6441           list = &objfile->static_psymbols;
6442         add_psymbol_to_list (actual_name, strlen (actual_name),
6443                              built_actual_name != NULL, VAR_DOMAIN, LOC_STATIC,
6444                              list, 0, 0, cu->language, objfile);
6445       }
6446       break;
6447     case DW_TAG_variable:
6448       if (pdi->d.locdesc)
6449         addr = decode_locdesc (pdi->d.locdesc, cu);
6450
6451       if (pdi->d.locdesc
6452           && addr == 0
6453           && !dwarf2_per_objfile->has_section_at_zero)
6454         {
6455           /* A global or static variable may also have been stripped
6456              out by the linker if unused, in which case its address
6457              will be nullified; do not add such variables into partial
6458              symbol table then.  */
6459         }
6460       else if (pdi->is_external)
6461         {
6462           /* Global Variable.
6463              Don't enter into the minimal symbol tables as there is
6464              a minimal symbol table entry from the ELF symbols already.
6465              Enter into partial symbol table if it has a location
6466              descriptor or a type.
6467              If the location descriptor is missing, new_symbol will create
6468              a LOC_UNRESOLVED symbol, the address of the variable will then
6469              be determined from the minimal symbol table whenever the variable
6470              is referenced.
6471              The address for the partial symbol table entry is not
6472              used by GDB, but it comes in handy for debugging partial symbol
6473              table building.  */
6474
6475           if (pdi->d.locdesc || pdi->has_type)
6476             add_psymbol_to_list (actual_name, strlen (actual_name),
6477                                  built_actual_name != NULL,
6478                                  VAR_DOMAIN, LOC_STATIC,
6479                                  &objfile->global_psymbols,
6480                                  0, addr + baseaddr,
6481                                  cu->language, objfile);
6482         }
6483       else
6484         {
6485           /* Static Variable.  Skip symbols without location descriptors.  */
6486           if (pdi->d.locdesc == NULL)
6487             {
6488               xfree (built_actual_name);
6489               return;
6490             }
6491           /* prim_record_minimal_symbol (actual_name, addr + baseaddr,
6492              mst_file_data, objfile); */
6493           add_psymbol_to_list (actual_name, strlen (actual_name),
6494                                built_actual_name != NULL,
6495                                VAR_DOMAIN, LOC_STATIC,
6496                                &objfile->static_psymbols,
6497                                0, addr + baseaddr,
6498                                cu->language, objfile);
6499         }
6500       break;
6501     case DW_TAG_typedef:
6502     case DW_TAG_base_type:
6503     case DW_TAG_subrange_type:
6504       add_psymbol_to_list (actual_name, strlen (actual_name),
6505                            built_actual_name != NULL,
6506                            VAR_DOMAIN, LOC_TYPEDEF,
6507                            &objfile->static_psymbols,
6508                            0, (CORE_ADDR) 0, cu->language, objfile);
6509       break;
6510     case DW_TAG_namespace:
6511       add_psymbol_to_list (actual_name, strlen (actual_name),
6512                            built_actual_name != NULL,
6513                            VAR_DOMAIN, LOC_TYPEDEF,
6514                            &objfile->global_psymbols,
6515                            0, (CORE_ADDR) 0, cu->language, objfile);
6516       break;
6517     case DW_TAG_class_type:
6518     case DW_TAG_interface_type:
6519     case DW_TAG_structure_type:
6520     case DW_TAG_union_type:
6521     case DW_TAG_enumeration_type:
6522       /* Skip external references.  The DWARF standard says in the section
6523          about "Structure, Union, and Class Type Entries": "An incomplete
6524          structure, union or class type is represented by a structure,
6525          union or class entry that does not have a byte size attribute
6526          and that has a DW_AT_declaration attribute."  */
6527       if (!pdi->has_byte_size && pdi->is_declaration)
6528         {
6529           xfree (built_actual_name);
6530           return;
6531         }
6532
6533       /* NOTE: carlton/2003-10-07: See comment in new_symbol about
6534          static vs. global.  */
6535       add_psymbol_to_list (actual_name, strlen (actual_name),
6536                            built_actual_name != NULL,
6537                            STRUCT_DOMAIN, LOC_TYPEDEF,
6538                            (cu->language == language_cplus
6539                             || cu->language == language_java)
6540                            ? &objfile->global_psymbols
6541                            : &objfile->static_psymbols,
6542                            0, (CORE_ADDR) 0, cu->language, objfile);
6543
6544       break;
6545     case DW_TAG_enumerator:
6546       add_psymbol_to_list (actual_name, strlen (actual_name),
6547                            built_actual_name != NULL,
6548                            VAR_DOMAIN, LOC_CONST,
6549                            (cu->language == language_cplus
6550                             || cu->language == language_java)
6551                            ? &objfile->global_psymbols
6552                            : &objfile->static_psymbols,
6553                            0, (CORE_ADDR) 0, cu->language, objfile);
6554       break;
6555     default:
6556       break;
6557     }
6558
6559   xfree (built_actual_name);
6560 }
6561
6562 /* Read a partial die corresponding to a namespace; also, add a symbol
6563    corresponding to that namespace to the symbol table.  NAMESPACE is
6564    the name of the enclosing namespace.  */
6565
6566 static void
6567 add_partial_namespace (struct partial_die_info *pdi,
6568                        CORE_ADDR *lowpc, CORE_ADDR *highpc,
6569                        int need_pc, struct dwarf2_cu *cu)
6570 {
6571   /* Add a symbol for the namespace.  */
6572
6573   add_partial_symbol (pdi, cu);
6574
6575   /* Now scan partial symbols in that namespace.  */
6576
6577   if (pdi->has_children)
6578     scan_partial_symbols (pdi->die_child, lowpc, highpc, need_pc, cu);
6579 }
6580
6581 /* Read a partial die corresponding to a Fortran module.  */
6582
6583 static void
6584 add_partial_module (struct partial_die_info *pdi, CORE_ADDR *lowpc,
6585                     CORE_ADDR *highpc, int need_pc, struct dwarf2_cu *cu)
6586 {
6587   /* Now scan partial symbols in that module.  */
6588
6589   if (pdi->has_children)
6590     scan_partial_symbols (pdi->die_child, lowpc, highpc, need_pc, cu);
6591 }
6592
6593 /* Read a partial die corresponding to a subprogram and create a partial
6594    symbol for that subprogram.  When the CU language allows it, this
6595    routine also defines a partial symbol for each nested subprogram
6596    that this subprogram contains.
6597
6598    DIE my also be a lexical block, in which case we simply search
6599    recursively for suprograms defined inside that lexical block.
6600    Again, this is only performed when the CU language allows this
6601    type of definitions.  */
6602
6603 static void
6604 add_partial_subprogram (struct partial_die_info *pdi,
6605                         CORE_ADDR *lowpc, CORE_ADDR *highpc,
6606                         int need_pc, struct dwarf2_cu *cu)
6607 {
6608   if (pdi->tag == DW_TAG_subprogram)
6609     {
6610       if (pdi->has_pc_info)
6611         {
6612           if (pdi->lowpc < *lowpc)
6613             *lowpc = pdi->lowpc;
6614           if (pdi->highpc > *highpc)
6615             *highpc = pdi->highpc;
6616           if (need_pc)
6617             {
6618               CORE_ADDR baseaddr;
6619               struct objfile *objfile = cu->objfile;
6620
6621               baseaddr = ANOFFSET (objfile->section_offsets,
6622                                    SECT_OFF_TEXT (objfile));
6623               addrmap_set_empty (objfile->psymtabs_addrmap,
6624                                  pdi->lowpc + baseaddr,
6625                                  pdi->highpc - 1 + baseaddr,
6626                                  cu->per_cu->v.psymtab);
6627             }
6628         }
6629
6630       if (pdi->has_pc_info || (!pdi->is_external && pdi->may_be_inlined))
6631         {
6632           if (!pdi->is_declaration)
6633             /* Ignore subprogram DIEs that do not have a name, they are
6634                illegal.  Do not emit a complaint at this point, we will
6635                do so when we convert this psymtab into a symtab.  */
6636             if (pdi->name)
6637               add_partial_symbol (pdi, cu);
6638         }
6639     }
6640
6641   if (! pdi->has_children)
6642     return;
6643
6644   if (cu->language == language_ada)
6645     {
6646       pdi = pdi->die_child;
6647       while (pdi != NULL)
6648         {
6649           fixup_partial_die (pdi, cu);
6650           if (pdi->tag == DW_TAG_subprogram
6651               || pdi->tag == DW_TAG_lexical_block)
6652             add_partial_subprogram (pdi, lowpc, highpc, need_pc, cu);
6653           pdi = pdi->die_sibling;
6654         }
6655     }
6656 }
6657
6658 /* Read a partial die corresponding to an enumeration type.  */
6659
6660 static void
6661 add_partial_enumeration (struct partial_die_info *enum_pdi,
6662                          struct dwarf2_cu *cu)
6663 {
6664   struct partial_die_info *pdi;
6665
6666   if (enum_pdi->name != NULL)
6667     add_partial_symbol (enum_pdi, cu);
6668
6669   pdi = enum_pdi->die_child;
6670   while (pdi)
6671     {
6672       if (pdi->tag != DW_TAG_enumerator || pdi->name == NULL)
6673         complaint (&symfile_complaints, _("malformed enumerator DIE ignored"));
6674       else
6675         add_partial_symbol (pdi, cu);
6676       pdi = pdi->die_sibling;
6677     }
6678 }
6679
6680 /* Return the initial uleb128 in the die at INFO_PTR.  */
6681
6682 static unsigned int
6683 peek_abbrev_code (bfd *abfd, const gdb_byte *info_ptr)
6684 {
6685   unsigned int bytes_read;
6686
6687   return read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
6688 }
6689
6690 /* Read the initial uleb128 in the die at INFO_PTR in compilation unit CU.
6691    Return the corresponding abbrev, or NULL if the number is zero (indicating
6692    an empty DIE).  In either case *BYTES_READ will be set to the length of
6693    the initial number.  */
6694
6695 static struct abbrev_info *
6696 peek_die_abbrev (const gdb_byte *info_ptr, unsigned int *bytes_read,
6697                  struct dwarf2_cu *cu)
6698 {
6699   bfd *abfd = cu->objfile->obfd;
6700   unsigned int abbrev_number;
6701   struct abbrev_info *abbrev;
6702
6703   abbrev_number = read_unsigned_leb128 (abfd, info_ptr, bytes_read);
6704
6705   if (abbrev_number == 0)
6706     return NULL;
6707
6708   abbrev = abbrev_table_lookup_abbrev (cu->abbrev_table, abbrev_number);
6709   if (!abbrev)
6710     {
6711       error (_("Dwarf Error: Could not find abbrev number %d [in module %s]"),
6712              abbrev_number, bfd_get_filename (abfd));
6713     }
6714
6715   return abbrev;
6716 }
6717
6718 /* Scan the debug information for CU starting at INFO_PTR in buffer BUFFER.
6719    Returns a pointer to the end of a series of DIEs, terminated by an empty
6720    DIE.  Any children of the skipped DIEs will also be skipped.  */
6721
6722 static const gdb_byte *
6723 skip_children (const struct die_reader_specs *reader, const gdb_byte *info_ptr)
6724 {
6725   struct dwarf2_cu *cu = reader->cu;
6726   struct abbrev_info *abbrev;
6727   unsigned int bytes_read;
6728
6729   while (1)
6730     {
6731       abbrev = peek_die_abbrev (info_ptr, &bytes_read, cu);
6732       if (abbrev == NULL)
6733         return info_ptr + bytes_read;
6734       else
6735         info_ptr = skip_one_die (reader, info_ptr + bytes_read, abbrev);
6736     }
6737 }
6738
6739 /* Scan the debug information for CU starting at INFO_PTR in buffer BUFFER.
6740    INFO_PTR should point just after the initial uleb128 of a DIE, and the
6741    abbrev corresponding to that skipped uleb128 should be passed in
6742    ABBREV.  Returns a pointer to this DIE's sibling, skipping any
6743    children.  */
6744
6745 static const gdb_byte *
6746 skip_one_die (const struct die_reader_specs *reader, const gdb_byte *info_ptr,
6747               struct abbrev_info *abbrev)
6748 {
6749   unsigned int bytes_read;
6750   struct attribute attr;
6751   bfd *abfd = reader->abfd;
6752   struct dwarf2_cu *cu = reader->cu;
6753   const gdb_byte *buffer = reader->buffer;
6754   const gdb_byte *buffer_end = reader->buffer_end;
6755   const gdb_byte *start_info_ptr = info_ptr;
6756   unsigned int form, i;
6757
6758   for (i = 0; i < abbrev->num_attrs; i++)
6759     {
6760       /* The only abbrev we care about is DW_AT_sibling.  */
6761       if (abbrev->attrs[i].name == DW_AT_sibling)
6762         {
6763           read_attribute (reader, &attr, &abbrev->attrs[i], info_ptr);
6764           if (attr.form == DW_FORM_ref_addr)
6765             complaint (&symfile_complaints,
6766                        _("ignoring absolute DW_AT_sibling"));
6767           else
6768             return buffer + dwarf2_get_ref_die_offset (&attr).sect_off;
6769         }
6770
6771       /* If it isn't DW_AT_sibling, skip this attribute.  */
6772       form = abbrev->attrs[i].form;
6773     skip_attribute:
6774       switch (form)
6775         {
6776         case DW_FORM_ref_addr:
6777           /* In DWARF 2, DW_FORM_ref_addr is address sized; in DWARF 3
6778              and later it is offset sized.  */
6779           if (cu->header.version == 2)
6780             info_ptr += cu->header.addr_size;
6781           else
6782             info_ptr += cu->header.offset_size;
6783           break;
6784         case DW_FORM_GNU_ref_alt:
6785           info_ptr += cu->header.offset_size;
6786           break;
6787         case DW_FORM_addr:
6788           info_ptr += cu->header.addr_size;
6789           break;
6790         case DW_FORM_data1:
6791         case DW_FORM_ref1:
6792         case DW_FORM_flag:
6793           info_ptr += 1;
6794           break;
6795         case DW_FORM_flag_present:
6796           break;
6797         case DW_FORM_data2:
6798         case DW_FORM_ref2:
6799           info_ptr += 2;
6800           break;
6801         case DW_FORM_data4:
6802         case DW_FORM_ref4:
6803           info_ptr += 4;
6804           break;
6805         case DW_FORM_data8:
6806         case DW_FORM_ref8:
6807         case DW_FORM_ref_sig8:
6808           info_ptr += 8;
6809           break;
6810         case DW_FORM_string:
6811           read_direct_string (abfd, info_ptr, &bytes_read);
6812           info_ptr += bytes_read;
6813           break;
6814         case DW_FORM_sec_offset:
6815         case DW_FORM_strp:
6816         case DW_FORM_GNU_strp_alt:
6817           info_ptr += cu->header.offset_size;
6818           break;
6819         case DW_FORM_exprloc:
6820         case DW_FORM_block:
6821           info_ptr += read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
6822           info_ptr += bytes_read;
6823           break;
6824         case DW_FORM_block1:
6825           info_ptr += 1 + read_1_byte (abfd, info_ptr);
6826           break;
6827         case DW_FORM_block2:
6828           info_ptr += 2 + read_2_bytes (abfd, info_ptr);
6829           break;
6830         case DW_FORM_block4:
6831           info_ptr += 4 + read_4_bytes (abfd, info_ptr);
6832           break;
6833         case DW_FORM_sdata:
6834         case DW_FORM_udata:
6835         case DW_FORM_ref_udata:
6836         case DW_FORM_GNU_addr_index:
6837         case DW_FORM_GNU_str_index:
6838           info_ptr = safe_skip_leb128 (info_ptr, buffer_end);
6839           break;
6840         case DW_FORM_indirect:
6841           form = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
6842           info_ptr += bytes_read;
6843           /* We need to continue parsing from here, so just go back to
6844              the top.  */
6845           goto skip_attribute;
6846
6847         default:
6848           error (_("Dwarf Error: Cannot handle %s "
6849                    "in DWARF reader [in module %s]"),
6850                  dwarf_form_name (form),
6851                  bfd_get_filename (abfd));
6852         }
6853     }
6854
6855   if (abbrev->has_children)
6856     return skip_children (reader, info_ptr);
6857   else
6858     return info_ptr;
6859 }
6860
6861 /* Locate ORIG_PDI's sibling.
6862    INFO_PTR should point to the start of the next DIE after ORIG_PDI.  */
6863
6864 static const gdb_byte *
6865 locate_pdi_sibling (const struct die_reader_specs *reader,
6866                     struct partial_die_info *orig_pdi,
6867                     const gdb_byte *info_ptr)
6868 {
6869   /* Do we know the sibling already?  */
6870
6871   if (orig_pdi->sibling)
6872     return orig_pdi->sibling;
6873
6874   /* Are there any children to deal with?  */
6875
6876   if (!orig_pdi->has_children)
6877     return info_ptr;
6878
6879   /* Skip the children the long way.  */
6880
6881   return skip_children (reader, info_ptr);
6882 }
6883
6884 /* Expand this partial symbol table into a full symbol table.  SELF is
6885    not NULL.  */
6886
6887 static void
6888 dwarf2_read_symtab (struct partial_symtab *self,
6889                     struct objfile *objfile)
6890 {
6891   if (self->readin)
6892     {
6893       warning (_("bug: psymtab for %s is already read in."),
6894                self->filename);
6895     }
6896   else
6897     {
6898       if (info_verbose)
6899         {
6900           printf_filtered (_("Reading in symbols for %s..."),
6901                            self->filename);
6902           gdb_flush (gdb_stdout);
6903         }
6904
6905       /* Restore our global data.  */
6906       dwarf2_per_objfile = objfile_data (objfile, dwarf2_objfile_data_key);
6907
6908       /* If this psymtab is constructed from a debug-only objfile, the
6909          has_section_at_zero flag will not necessarily be correct.  We
6910          can get the correct value for this flag by looking at the data
6911          associated with the (presumably stripped) associated objfile.  */
6912       if (objfile->separate_debug_objfile_backlink)
6913         {
6914           struct dwarf2_per_objfile *dpo_backlink
6915             = objfile_data (objfile->separate_debug_objfile_backlink,
6916                             dwarf2_objfile_data_key);
6917
6918           dwarf2_per_objfile->has_section_at_zero
6919             = dpo_backlink->has_section_at_zero;
6920         }
6921
6922       dwarf2_per_objfile->reading_partial_symbols = 0;
6923
6924       psymtab_to_symtab_1 (self);
6925
6926       /* Finish up the debug error message.  */
6927       if (info_verbose)
6928         printf_filtered (_("done.\n"));
6929     }
6930
6931   process_cu_includes ();
6932 }
6933 \f
6934 /* Reading in full CUs.  */
6935
6936 /* Add PER_CU to the queue.  */
6937
6938 static void
6939 queue_comp_unit (struct dwarf2_per_cu_data *per_cu,
6940                  enum language pretend_language)
6941 {
6942   struct dwarf2_queue_item *item;
6943
6944   per_cu->queued = 1;
6945   item = xmalloc (sizeof (*item));
6946   item->per_cu = per_cu;
6947   item->pretend_language = pretend_language;
6948   item->next = NULL;
6949
6950   if (dwarf2_queue == NULL)
6951     dwarf2_queue = item;
6952   else
6953     dwarf2_queue_tail->next = item;
6954
6955   dwarf2_queue_tail = item;
6956 }
6957
6958 /* If PER_CU is not yet queued, add it to the queue.
6959    If DEPENDENT_CU is non-NULL, it has a reference to PER_CU so add a
6960    dependency.
6961    The result is non-zero if PER_CU was queued, otherwise the result is zero
6962    meaning either PER_CU is already queued or it is already loaded.
6963
6964    N.B. There is an invariant here that if a CU is queued then it is loaded.
6965    The caller is required to load PER_CU if we return non-zero.  */
6966
6967 static int
6968 maybe_queue_comp_unit (struct dwarf2_cu *dependent_cu,
6969                        struct dwarf2_per_cu_data *per_cu,
6970                        enum language pretend_language)
6971 {
6972   /* We may arrive here during partial symbol reading, if we need full
6973      DIEs to process an unusual case (e.g. template arguments).  Do
6974      not queue PER_CU, just tell our caller to load its DIEs.  */
6975   if (dwarf2_per_objfile->reading_partial_symbols)
6976     {
6977       if (per_cu->cu == NULL || per_cu->cu->dies == NULL)
6978         return 1;
6979       return 0;
6980     }
6981
6982   /* Mark the dependence relation so that we don't flush PER_CU
6983      too early.  */
6984   if (dependent_cu != NULL)
6985     dwarf2_add_dependence (dependent_cu, per_cu);
6986
6987   /* If it's already on the queue, we have nothing to do.  */
6988   if (per_cu->queued)
6989     return 0;
6990
6991   /* If the compilation unit is already loaded, just mark it as
6992      used.  */
6993   if (per_cu->cu != NULL)
6994     {
6995       per_cu->cu->last_used = 0;
6996       return 0;
6997     }
6998
6999   /* Add it to the queue.  */
7000   queue_comp_unit (per_cu, pretend_language);
7001
7002   return 1;
7003 }
7004
7005 /* Process the queue.  */
7006
7007 static void
7008 process_queue (void)
7009 {
7010   struct dwarf2_queue_item *item, *next_item;
7011
7012   if (dwarf2_read_debug)
7013     {
7014       fprintf_unfiltered (gdb_stdlog,
7015                           "Expanding one or more symtabs of objfile %s ...\n",
7016                           objfile_name (dwarf2_per_objfile->objfile));
7017     }
7018
7019   /* The queue starts out with one item, but following a DIE reference
7020      may load a new CU, adding it to the end of the queue.  */
7021   for (item = dwarf2_queue; item != NULL; dwarf2_queue = item = next_item)
7022     {
7023       if (dwarf2_per_objfile->using_index
7024           ? !item->per_cu->v.quick->symtab
7025           : (item->per_cu->v.psymtab && !item->per_cu->v.psymtab->readin))
7026         {
7027           struct dwarf2_per_cu_data *per_cu = item->per_cu;
7028           char buf[100];
7029
7030           if (per_cu->is_debug_types)
7031             {
7032               struct signatured_type *sig_type =
7033                 (struct signatured_type *) per_cu;
7034
7035               sprintf (buf, "TU %s at offset 0x%x",
7036                        hex_string (sig_type->signature), per_cu->offset.sect_off);
7037             }
7038           else
7039             sprintf (buf, "CU at offset 0x%x", per_cu->offset.sect_off);
7040
7041           if (dwarf2_read_debug)
7042             fprintf_unfiltered (gdb_stdlog, "Expanding symtab of %s\n", buf);
7043
7044           if (per_cu->is_debug_types)
7045             process_full_type_unit (per_cu, item->pretend_language);
7046           else
7047             process_full_comp_unit (per_cu, item->pretend_language);
7048
7049           if (dwarf2_read_debug)
7050             fprintf_unfiltered (gdb_stdlog, "Done expanding %s\n", buf);
7051         }
7052
7053       item->per_cu->queued = 0;
7054       next_item = item->next;
7055       xfree (item);
7056     }
7057
7058   dwarf2_queue_tail = NULL;
7059
7060   if (dwarf2_read_debug)
7061     {
7062       fprintf_unfiltered (gdb_stdlog, "Done expanding symtabs of %s.\n",
7063                           objfile_name (dwarf2_per_objfile->objfile));
7064     }
7065 }
7066
7067 /* Free all allocated queue entries.  This function only releases anything if
7068    an error was thrown; if the queue was processed then it would have been
7069    freed as we went along.  */
7070
7071 static void
7072 dwarf2_release_queue (void *dummy)
7073 {
7074   struct dwarf2_queue_item *item, *last;
7075
7076   item = dwarf2_queue;
7077   while (item)
7078     {
7079       /* Anything still marked queued is likely to be in an
7080          inconsistent state, so discard it.  */
7081       if (item->per_cu->queued)
7082         {
7083           if (item->per_cu->cu != NULL)
7084             free_one_cached_comp_unit (item->per_cu);
7085           item->per_cu->queued = 0;
7086         }
7087
7088       last = item;
7089       item = item->next;
7090       xfree (last);
7091     }
7092
7093   dwarf2_queue = dwarf2_queue_tail = NULL;
7094 }
7095
7096 /* Read in full symbols for PST, and anything it depends on.  */
7097
7098 static void
7099 psymtab_to_symtab_1 (struct partial_symtab *pst)
7100 {
7101   struct dwarf2_per_cu_data *per_cu;
7102   int i;
7103
7104   if (pst->readin)
7105     return;
7106
7107   for (i = 0; i < pst->number_of_dependencies; i++)
7108     if (!pst->dependencies[i]->readin
7109         && pst->dependencies[i]->user == NULL)
7110       {
7111         /* Inform about additional files that need to be read in.  */
7112         if (info_verbose)
7113           {
7114             /* FIXME: i18n: Need to make this a single string.  */
7115             fputs_filtered (" ", gdb_stdout);
7116             wrap_here ("");
7117             fputs_filtered ("and ", gdb_stdout);
7118             wrap_here ("");
7119             printf_filtered ("%s...", pst->dependencies[i]->filename);
7120             wrap_here ("");     /* Flush output.  */
7121             gdb_flush (gdb_stdout);
7122           }
7123         psymtab_to_symtab_1 (pst->dependencies[i]);
7124       }
7125
7126   per_cu = pst->read_symtab_private;
7127
7128   if (per_cu == NULL)
7129     {
7130       /* It's an include file, no symbols to read for it.
7131          Everything is in the parent symtab.  */
7132       pst->readin = 1;
7133       return;
7134     }
7135
7136   dw2_do_instantiate_symtab (per_cu);
7137 }
7138
7139 /* Trivial hash function for die_info: the hash value of a DIE
7140    is its offset in .debug_info for this objfile.  */
7141
7142 static hashval_t
7143 die_hash (const void *item)
7144 {
7145   const struct die_info *die = item;
7146
7147   return die->offset.sect_off;
7148 }
7149
7150 /* Trivial comparison function for die_info structures: two DIEs
7151    are equal if they have the same offset.  */
7152
7153 static int
7154 die_eq (const void *item_lhs, const void *item_rhs)
7155 {
7156   const struct die_info *die_lhs = item_lhs;
7157   const struct die_info *die_rhs = item_rhs;
7158
7159   return die_lhs->offset.sect_off == die_rhs->offset.sect_off;
7160 }
7161
7162 /* die_reader_func for load_full_comp_unit.
7163    This is identical to read_signatured_type_reader,
7164    but is kept separate for now.  */
7165
7166 static void
7167 load_full_comp_unit_reader (const struct die_reader_specs *reader,
7168                             const gdb_byte *info_ptr,
7169                             struct die_info *comp_unit_die,
7170                             int has_children,
7171                             void *data)
7172 {
7173   struct dwarf2_cu *cu = reader->cu;
7174   enum language *language_ptr = data;
7175
7176   gdb_assert (cu->die_hash == NULL);
7177   cu->die_hash =
7178     htab_create_alloc_ex (cu->header.length / 12,
7179                           die_hash,
7180                           die_eq,
7181                           NULL,
7182                           &cu->comp_unit_obstack,
7183                           hashtab_obstack_allocate,
7184                           dummy_obstack_deallocate);
7185
7186   if (has_children)
7187     comp_unit_die->child = read_die_and_siblings (reader, info_ptr,
7188                                                   &info_ptr, comp_unit_die);
7189   cu->dies = comp_unit_die;
7190   /* comp_unit_die is not stored in die_hash, no need.  */
7191
7192   /* We try not to read any attributes in this function, because not
7193      all CUs needed for references have been loaded yet, and symbol
7194      table processing isn't initialized.  But we have to set the CU language,
7195      or we won't be able to build types correctly.
7196      Similarly, if we do not read the producer, we can not apply
7197      producer-specific interpretation.  */
7198   prepare_one_comp_unit (cu, cu->dies, *language_ptr);
7199 }
7200
7201 /* Load the DIEs associated with PER_CU into memory.  */
7202
7203 static void
7204 load_full_comp_unit (struct dwarf2_per_cu_data *this_cu,
7205                      enum language pretend_language)
7206 {
7207   gdb_assert (! this_cu->is_debug_types);
7208
7209   init_cutu_and_read_dies (this_cu, NULL, 1, 1,
7210                            load_full_comp_unit_reader, &pretend_language);
7211 }
7212
7213 /* Add a DIE to the delayed physname list.  */
7214
7215 static void
7216 add_to_method_list (struct type *type, int fnfield_index, int index,
7217                     const char *name, struct die_info *die,
7218                     struct dwarf2_cu *cu)
7219 {
7220   struct delayed_method_info mi;
7221   mi.type = type;
7222   mi.fnfield_index = fnfield_index;
7223   mi.index = index;
7224   mi.name = name;
7225   mi.die = die;
7226   VEC_safe_push (delayed_method_info, cu->method_list, &mi);
7227 }
7228
7229 /* A cleanup for freeing the delayed method list.  */
7230
7231 static void
7232 free_delayed_list (void *ptr)
7233 {
7234   struct dwarf2_cu *cu = (struct dwarf2_cu *) ptr;
7235   if (cu->method_list != NULL)
7236     {
7237       VEC_free (delayed_method_info, cu->method_list);
7238       cu->method_list = NULL;
7239     }
7240 }
7241
7242 /* Compute the physnames of any methods on the CU's method list.
7243
7244    The computation of method physnames is delayed in order to avoid the
7245    (bad) condition that one of the method's formal parameters is of an as yet
7246    incomplete type.  */
7247
7248 static void
7249 compute_delayed_physnames (struct dwarf2_cu *cu)
7250 {
7251   int i;
7252   struct delayed_method_info *mi;
7253   for (i = 0; VEC_iterate (delayed_method_info, cu->method_list, i, mi) ; ++i)
7254     {
7255       const char *physname;
7256       struct fn_fieldlist *fn_flp
7257         = &TYPE_FN_FIELDLIST (mi->type, mi->fnfield_index);
7258       physname = dwarf2_physname (mi->name, mi->die, cu);
7259       fn_flp->fn_fields[mi->index].physname = physname ? physname : "";
7260     }
7261 }
7262
7263 /* Go objects should be embedded in a DW_TAG_module DIE,
7264    and it's not clear if/how imported objects will appear.
7265    To keep Go support simple until that's worked out,
7266    go back through what we've read and create something usable.
7267    We could do this while processing each DIE, and feels kinda cleaner,
7268    but that way is more invasive.
7269    This is to, for example, allow the user to type "p var" or "b main"
7270    without having to specify the package name, and allow lookups
7271    of module.object to work in contexts that use the expression
7272    parser.  */
7273
7274 static void
7275 fixup_go_packaging (struct dwarf2_cu *cu)
7276 {
7277   char *package_name = NULL;
7278   struct pending *list;
7279   int i;
7280
7281   for (list = global_symbols; list != NULL; list = list->next)
7282     {
7283       for (i = 0; i < list->nsyms; ++i)
7284         {
7285           struct symbol *sym = list->symbol[i];
7286
7287           if (SYMBOL_LANGUAGE (sym) == language_go
7288               && SYMBOL_CLASS (sym) == LOC_BLOCK)
7289             {
7290               char *this_package_name = go_symbol_package_name (sym);
7291
7292               if (this_package_name == NULL)
7293                 continue;
7294               if (package_name == NULL)
7295                 package_name = this_package_name;
7296               else
7297                 {
7298                   if (strcmp (package_name, this_package_name) != 0)
7299                     complaint (&symfile_complaints,
7300                                _("Symtab %s has objects from two different Go packages: %s and %s"),
7301                                (SYMBOL_SYMTAB (sym)
7302                           ? symtab_to_filename_for_display (SYMBOL_SYMTAB (sym))
7303                                 : objfile_name (cu->objfile)),
7304                                this_package_name, package_name);
7305                   xfree (this_package_name);
7306                 }
7307             }
7308         }
7309     }
7310
7311   if (package_name != NULL)
7312     {
7313       struct objfile *objfile = cu->objfile;
7314       const char *saved_package_name = obstack_copy0 (&objfile->objfile_obstack,
7315                                                       package_name,
7316                                                       strlen (package_name));
7317       struct type *type = init_type (TYPE_CODE_MODULE, 0, 0,
7318                                      saved_package_name, objfile);
7319       struct symbol *sym;
7320
7321       TYPE_TAG_NAME (type) = TYPE_NAME (type);
7322
7323       sym = allocate_symbol (objfile);
7324       SYMBOL_SET_LANGUAGE (sym, language_go, &objfile->objfile_obstack);
7325       SYMBOL_SET_NAMES (sym, saved_package_name,
7326                         strlen (saved_package_name), 0, objfile);
7327       /* This is not VAR_DOMAIN because we want a way to ensure a lookup of,
7328          e.g., "main" finds the "main" module and not C's main().  */
7329       SYMBOL_DOMAIN (sym) = STRUCT_DOMAIN;
7330       SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
7331       SYMBOL_TYPE (sym) = type;
7332
7333       add_symbol_to_list (sym, &global_symbols);
7334
7335       xfree (package_name);
7336     }
7337 }
7338
7339 /* Return the symtab for PER_CU.  This works properly regardless of
7340    whether we're using the index or psymtabs.  */
7341
7342 static struct symtab *
7343 get_symtab (struct dwarf2_per_cu_data *per_cu)
7344 {
7345   return (dwarf2_per_objfile->using_index
7346           ? per_cu->v.quick->symtab
7347           : per_cu->v.psymtab->symtab);
7348 }
7349
7350 /* A helper function for computing the list of all symbol tables
7351    included by PER_CU.  */
7352
7353 static void
7354 recursively_compute_inclusions (VEC (symtab_ptr) **result,
7355                                 htab_t all_children, htab_t all_type_symtabs,
7356                                 struct dwarf2_per_cu_data *per_cu,
7357                                 struct symtab *immediate_parent)
7358 {
7359   void **slot;
7360   int ix;
7361   struct symtab *symtab;
7362   struct dwarf2_per_cu_data *iter;
7363
7364   slot = htab_find_slot (all_children, per_cu, INSERT);
7365   if (*slot != NULL)
7366     {
7367       /* This inclusion and its children have been processed.  */
7368       return;
7369     }
7370
7371   *slot = per_cu;
7372   /* Only add a CU if it has a symbol table.  */
7373   symtab = get_symtab (per_cu);
7374   if (symtab != NULL)
7375     {
7376       /* If this is a type unit only add its symbol table if we haven't
7377          seen it yet (type unit per_cu's can share symtabs).  */
7378       if (per_cu->is_debug_types)
7379         {
7380           slot = htab_find_slot (all_type_symtabs, symtab, INSERT);
7381           if (*slot == NULL)
7382             {
7383               *slot = symtab;
7384               VEC_safe_push (symtab_ptr, *result, symtab);
7385               if (symtab->user == NULL)
7386                 symtab->user = immediate_parent;
7387             }
7388         }
7389       else
7390         {
7391           VEC_safe_push (symtab_ptr, *result, symtab);
7392           if (symtab->user == NULL)
7393             symtab->user = immediate_parent;
7394         }
7395     }
7396
7397   for (ix = 0;
7398        VEC_iterate (dwarf2_per_cu_ptr, per_cu->imported_symtabs, ix, iter);
7399        ++ix)
7400     {
7401       recursively_compute_inclusions (result, all_children,
7402                                       all_type_symtabs, iter, symtab);
7403     }
7404 }
7405
7406 /* Compute the symtab 'includes' fields for the symtab related to
7407    PER_CU.  */
7408
7409 static void
7410 compute_symtab_includes (struct dwarf2_per_cu_data *per_cu)
7411 {
7412   gdb_assert (! per_cu->is_debug_types);
7413
7414   if (!VEC_empty (dwarf2_per_cu_ptr, per_cu->imported_symtabs))
7415     {
7416       int ix, len;
7417       struct dwarf2_per_cu_data *per_cu_iter;
7418       struct symtab *symtab_iter;
7419       VEC (symtab_ptr) *result_symtabs = NULL;
7420       htab_t all_children, all_type_symtabs;
7421       struct symtab *symtab = get_symtab (per_cu);
7422
7423       /* If we don't have a symtab, we can just skip this case.  */
7424       if (symtab == NULL)
7425         return;
7426
7427       all_children = htab_create_alloc (1, htab_hash_pointer, htab_eq_pointer,
7428                                         NULL, xcalloc, xfree);
7429       all_type_symtabs = htab_create_alloc (1, htab_hash_pointer, htab_eq_pointer,
7430                                             NULL, xcalloc, xfree);
7431
7432       for (ix = 0;
7433            VEC_iterate (dwarf2_per_cu_ptr, per_cu->imported_symtabs,
7434                         ix, per_cu_iter);
7435            ++ix)
7436         {
7437           recursively_compute_inclusions (&result_symtabs, all_children,
7438                                           all_type_symtabs, per_cu_iter,
7439                                           symtab);
7440         }
7441
7442       /* Now we have a transitive closure of all the included symtabs.  */
7443       len = VEC_length (symtab_ptr, result_symtabs);
7444       symtab->includes
7445         = obstack_alloc (&dwarf2_per_objfile->objfile->objfile_obstack,
7446                          (len + 1) * sizeof (struct symtab *));
7447       for (ix = 0;
7448            VEC_iterate (symtab_ptr, result_symtabs, ix, symtab_iter);
7449            ++ix)
7450         symtab->includes[ix] = symtab_iter;
7451       symtab->includes[len] = NULL;
7452
7453       VEC_free (symtab_ptr, result_symtabs);
7454       htab_delete (all_children);
7455       htab_delete (all_type_symtabs);
7456     }
7457 }
7458
7459 /* Compute the 'includes' field for the symtabs of all the CUs we just
7460    read.  */
7461
7462 static void
7463 process_cu_includes (void)
7464 {
7465   int ix;
7466   struct dwarf2_per_cu_data *iter;
7467
7468   for (ix = 0;
7469        VEC_iterate (dwarf2_per_cu_ptr, dwarf2_per_objfile->just_read_cus,
7470                     ix, iter);
7471        ++ix)
7472     {
7473       if (! iter->is_debug_types)
7474         compute_symtab_includes (iter);
7475     }
7476
7477   VEC_free (dwarf2_per_cu_ptr, dwarf2_per_objfile->just_read_cus);
7478 }
7479
7480 /* Generate full symbol information for PER_CU, whose DIEs have
7481    already been loaded into memory.  */
7482
7483 static void
7484 process_full_comp_unit (struct dwarf2_per_cu_data *per_cu,
7485                         enum language pretend_language)
7486 {
7487   struct dwarf2_cu *cu = per_cu->cu;
7488   struct objfile *objfile = per_cu->objfile;
7489   CORE_ADDR lowpc, highpc;
7490   struct symtab *symtab;
7491   struct cleanup *back_to, *delayed_list_cleanup;
7492   CORE_ADDR baseaddr;
7493   struct block *static_block;
7494
7495   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
7496
7497   buildsym_init ();
7498   back_to = make_cleanup (really_free_pendings, NULL);
7499   delayed_list_cleanup = make_cleanup (free_delayed_list, cu);
7500
7501   cu->list_in_scope = &file_symbols;
7502
7503   cu->language = pretend_language;
7504   cu->language_defn = language_def (cu->language);
7505
7506   /* Do line number decoding in read_file_scope () */
7507   process_die (cu->dies, cu);
7508
7509   /* For now fudge the Go package.  */
7510   if (cu->language == language_go)
7511     fixup_go_packaging (cu);
7512
7513   /* Now that we have processed all the DIEs in the CU, all the types 
7514      should be complete, and it should now be safe to compute all of the
7515      physnames.  */
7516   compute_delayed_physnames (cu);
7517   do_cleanups (delayed_list_cleanup);
7518
7519   /* Some compilers don't define a DW_AT_high_pc attribute for the
7520      compilation unit.  If the DW_AT_high_pc is missing, synthesize
7521      it, by scanning the DIE's below the compilation unit.  */
7522   get_scope_pc_bounds (cu->dies, &lowpc, &highpc, cu);
7523
7524   static_block
7525     = end_symtab_get_static_block (highpc + baseaddr, objfile, 0, 1);
7526
7527   /* If the comp unit has DW_AT_ranges, it may have discontiguous ranges.
7528      Also, DW_AT_ranges may record ranges not belonging to any child DIEs
7529      (such as virtual method tables).  Record the ranges in STATIC_BLOCK's
7530      addrmap to help ensure it has an accurate map of pc values belonging to
7531      this comp unit.  */
7532   dwarf2_record_block_ranges (cu->dies, static_block, baseaddr, cu);
7533
7534   symtab = end_symtab_from_static_block (static_block, objfile,
7535                                          SECT_OFF_TEXT (objfile), 0);
7536
7537   if (symtab != NULL)
7538     {
7539       int gcc_4_minor = producer_is_gcc_ge_4 (cu->producer);
7540
7541       /* Set symtab language to language from DW_AT_language.  If the
7542          compilation is from a C file generated by language preprocessors, do
7543          not set the language if it was already deduced by start_subfile.  */
7544       if (!(cu->language == language_c && symtab->language != language_c))
7545         symtab->language = cu->language;
7546
7547       /* GCC-4.0 has started to support -fvar-tracking.  GCC-3.x still can
7548          produce DW_AT_location with location lists but it can be possibly
7549          invalid without -fvar-tracking.  Still up to GCC-4.4.x incl. 4.4.0
7550          there were bugs in prologue debug info, fixed later in GCC-4.5
7551          by "unwind info for epilogues" patch (which is not directly related).
7552
7553          For -gdwarf-4 type units LOCATIONS_VALID indication is fortunately not
7554          needed, it would be wrong due to missing DW_AT_producer there.
7555
7556          Still one can confuse GDB by using non-standard GCC compilation
7557          options - this waits on GCC PR other/32998 (-frecord-gcc-switches).
7558          */ 
7559       if (cu->has_loclist && gcc_4_minor >= 5)
7560         symtab->locations_valid = 1;
7561
7562       if (gcc_4_minor >= 5)
7563         symtab->epilogue_unwind_valid = 1;
7564
7565       symtab->call_site_htab = cu->call_site_htab;
7566     }
7567
7568   if (dwarf2_per_objfile->using_index)
7569     per_cu->v.quick->symtab = symtab;
7570   else
7571     {
7572       struct partial_symtab *pst = per_cu->v.psymtab;
7573       pst->symtab = symtab;
7574       pst->readin = 1;
7575     }
7576
7577   /* Push it for inclusion processing later.  */
7578   VEC_safe_push (dwarf2_per_cu_ptr, dwarf2_per_objfile->just_read_cus, per_cu);
7579
7580   do_cleanups (back_to);
7581 }
7582
7583 /* Generate full symbol information for type unit PER_CU, whose DIEs have
7584    already been loaded into memory.  */
7585
7586 static void
7587 process_full_type_unit (struct dwarf2_per_cu_data *per_cu,
7588                         enum language pretend_language)
7589 {
7590   struct dwarf2_cu *cu = per_cu->cu;
7591   struct objfile *objfile = per_cu->objfile;
7592   struct symtab *symtab;
7593   struct cleanup *back_to, *delayed_list_cleanup;
7594   struct signatured_type *sig_type;
7595
7596   gdb_assert (per_cu->is_debug_types);
7597   sig_type = (struct signatured_type *) per_cu;
7598
7599   buildsym_init ();
7600   back_to = make_cleanup (really_free_pendings, NULL);
7601   delayed_list_cleanup = make_cleanup (free_delayed_list, cu);
7602
7603   cu->list_in_scope = &file_symbols;
7604
7605   cu->language = pretend_language;
7606   cu->language_defn = language_def (cu->language);
7607
7608   /* The symbol tables are set up in read_type_unit_scope.  */
7609   process_die (cu->dies, cu);
7610
7611   /* For now fudge the Go package.  */
7612   if (cu->language == language_go)
7613     fixup_go_packaging (cu);
7614
7615   /* Now that we have processed all the DIEs in the CU, all the types 
7616      should be complete, and it should now be safe to compute all of the
7617      physnames.  */
7618   compute_delayed_physnames (cu);
7619   do_cleanups (delayed_list_cleanup);
7620
7621   /* TUs share symbol tables.
7622      If this is the first TU to use this symtab, complete the construction
7623      of it with end_expandable_symtab.  Otherwise, complete the addition of
7624      this TU's symbols to the existing symtab.  */
7625   if (sig_type->type_unit_group->primary_symtab == NULL)
7626     {
7627       symtab = end_expandable_symtab (0, objfile, SECT_OFF_TEXT (objfile));
7628       sig_type->type_unit_group->primary_symtab = symtab;
7629
7630       if (symtab != NULL)
7631         {
7632           /* Set symtab language to language from DW_AT_language.  If the
7633              compilation is from a C file generated by language preprocessors,
7634              do not set the language if it was already deduced by
7635              start_subfile.  */
7636           if (!(cu->language == language_c && symtab->language != language_c))
7637             symtab->language = cu->language;
7638         }
7639     }
7640   else
7641     {
7642       augment_type_symtab (objfile,
7643                            sig_type->type_unit_group->primary_symtab);
7644       symtab = sig_type->type_unit_group->primary_symtab;
7645     }
7646
7647   if (dwarf2_per_objfile->using_index)
7648     per_cu->v.quick->symtab = symtab;
7649   else
7650     {
7651       struct partial_symtab *pst = per_cu->v.psymtab;
7652       pst->symtab = symtab;
7653       pst->readin = 1;
7654     }
7655
7656   do_cleanups (back_to);
7657 }
7658
7659 /* Process an imported unit DIE.  */
7660
7661 static void
7662 process_imported_unit_die (struct die_info *die, struct dwarf2_cu *cu)
7663 {
7664   struct attribute *attr;
7665
7666   /* For now we don't handle imported units in type units.  */
7667   if (cu->per_cu->is_debug_types)
7668     {
7669       error (_("Dwarf Error: DW_TAG_imported_unit is not"
7670                " supported in type units [in module %s]"),
7671              objfile_name (cu->objfile));
7672     }
7673
7674   attr = dwarf2_attr (die, DW_AT_import, cu);
7675   if (attr != NULL)
7676     {
7677       struct dwarf2_per_cu_data *per_cu;
7678       struct symtab *imported_symtab;
7679       sect_offset offset;
7680       int is_dwz;
7681
7682       offset = dwarf2_get_ref_die_offset (attr);
7683       is_dwz = (attr->form == DW_FORM_GNU_ref_alt || cu->per_cu->is_dwz);
7684       per_cu = dwarf2_find_containing_comp_unit (offset, is_dwz, cu->objfile);
7685
7686       /* If necessary, add it to the queue and load its DIEs.  */
7687       if (maybe_queue_comp_unit (cu, per_cu, cu->language))
7688         load_full_comp_unit (per_cu, cu->language);
7689
7690       VEC_safe_push (dwarf2_per_cu_ptr, cu->per_cu->imported_symtabs,
7691                      per_cu);
7692     }
7693 }
7694
7695 /* Process a die and its children.  */
7696
7697 static void
7698 process_die (struct die_info *die, struct dwarf2_cu *cu)
7699 {
7700   switch (die->tag)
7701     {
7702     case DW_TAG_padding:
7703       break;
7704     case DW_TAG_compile_unit:
7705     case DW_TAG_partial_unit:
7706       read_file_scope (die, cu);
7707       break;
7708     case DW_TAG_type_unit:
7709       read_type_unit_scope (die, cu);
7710       break;
7711     case DW_TAG_subprogram:
7712     case DW_TAG_inlined_subroutine:
7713       read_func_scope (die, cu);
7714       break;
7715     case DW_TAG_lexical_block:
7716     case DW_TAG_try_block:
7717     case DW_TAG_catch_block:
7718       read_lexical_block_scope (die, cu);
7719       break;
7720     case DW_TAG_GNU_call_site:
7721       read_call_site_scope (die, cu);
7722       break;
7723     case DW_TAG_class_type:
7724     case DW_TAG_interface_type:
7725     case DW_TAG_structure_type:
7726     case DW_TAG_union_type:
7727       process_structure_scope (die, cu);
7728       break;
7729     case DW_TAG_enumeration_type:
7730       process_enumeration_scope (die, cu);
7731       break;
7732
7733     /* These dies have a type, but processing them does not create
7734        a symbol or recurse to process the children.  Therefore we can
7735        read them on-demand through read_type_die.  */
7736     case DW_TAG_subroutine_type:
7737     case DW_TAG_set_type:
7738     case DW_TAG_array_type:
7739     case DW_TAG_pointer_type:
7740     case DW_TAG_ptr_to_member_type:
7741     case DW_TAG_reference_type:
7742     case DW_TAG_string_type:
7743       break;
7744
7745     case DW_TAG_base_type:
7746     case DW_TAG_subrange_type:
7747     case DW_TAG_typedef:
7748       /* Add a typedef symbol for the type definition, if it has a
7749          DW_AT_name.  */
7750       new_symbol (die, read_type_die (die, cu), cu);
7751       break;
7752     case DW_TAG_common_block:
7753       read_common_block (die, cu);
7754       break;
7755     case DW_TAG_common_inclusion:
7756       break;
7757     case DW_TAG_namespace:
7758       cu->processing_has_namespace_info = 1;
7759       read_namespace (die, cu);
7760       break;
7761     case DW_TAG_module:
7762       cu->processing_has_namespace_info = 1;
7763       read_module (die, cu);
7764       break;
7765     case DW_TAG_imported_declaration:
7766     case DW_TAG_imported_module:
7767       cu->processing_has_namespace_info = 1;
7768       if (die->child != NULL && (die->tag == DW_TAG_imported_declaration
7769                                  || cu->language != language_fortran))
7770         complaint (&symfile_complaints, _("Tag '%s' has unexpected children"),
7771                    dwarf_tag_name (die->tag));
7772       read_import_statement (die, cu);
7773       break;
7774
7775     case DW_TAG_imported_unit:
7776       process_imported_unit_die (die, cu);
7777       break;
7778
7779     default:
7780       new_symbol (die, NULL, cu);
7781       break;
7782     }
7783 }
7784 \f
7785 /* DWARF name computation.  */
7786
7787 /* A helper function for dwarf2_compute_name which determines whether DIE
7788    needs to have the name of the scope prepended to the name listed in the
7789    die.  */
7790
7791 static int
7792 die_needs_namespace (struct die_info *die, struct dwarf2_cu *cu)
7793 {
7794   struct attribute *attr;
7795
7796   switch (die->tag)
7797     {
7798     case DW_TAG_namespace:
7799     case DW_TAG_typedef:
7800     case DW_TAG_class_type:
7801     case DW_TAG_interface_type:
7802     case DW_TAG_structure_type:
7803     case DW_TAG_union_type:
7804     case DW_TAG_enumeration_type:
7805     case DW_TAG_enumerator:
7806     case DW_TAG_subprogram:
7807     case DW_TAG_member:
7808       return 1;
7809
7810     case DW_TAG_variable:
7811     case DW_TAG_constant:
7812       /* We only need to prefix "globally" visible variables.  These include
7813          any variable marked with DW_AT_external or any variable that
7814          lives in a namespace.  [Variables in anonymous namespaces
7815          require prefixing, but they are not DW_AT_external.]  */
7816
7817       if (dwarf2_attr (die, DW_AT_specification, cu))
7818         {
7819           struct dwarf2_cu *spec_cu = cu;
7820
7821           return die_needs_namespace (die_specification (die, &spec_cu),
7822                                       spec_cu);
7823         }
7824
7825       attr = dwarf2_attr (die, DW_AT_external, cu);
7826       if (attr == NULL && die->parent->tag != DW_TAG_namespace
7827           && die->parent->tag != DW_TAG_module)
7828         return 0;
7829       /* A variable in a lexical block of some kind does not need a
7830          namespace, even though in C++ such variables may be external
7831          and have a mangled name.  */
7832       if (die->parent->tag ==  DW_TAG_lexical_block
7833           || die->parent->tag ==  DW_TAG_try_block
7834           || die->parent->tag ==  DW_TAG_catch_block
7835           || die->parent->tag == DW_TAG_subprogram)
7836         return 0;
7837       return 1;
7838
7839     default:
7840       return 0;
7841     }
7842 }
7843
7844 /* Retrieve the last character from a mem_file.  */
7845
7846 static void
7847 do_ui_file_peek_last (void *object, const char *buffer, long length)
7848 {
7849   char *last_char_p = (char *) object;
7850
7851   if (length > 0)
7852     *last_char_p = buffer[length - 1];
7853 }
7854
7855 /* Compute the fully qualified name of DIE in CU.  If PHYSNAME is nonzero,
7856    compute the physname for the object, which include a method's:
7857    - formal parameters (C++/Java),
7858    - receiver type (Go),
7859    - return type (Java).
7860
7861    The term "physname" is a bit confusing.
7862    For C++, for example, it is the demangled name.
7863    For Go, for example, it's the mangled name.
7864
7865    For Ada, return the DIE's linkage name rather than the fully qualified
7866    name.  PHYSNAME is ignored..
7867
7868    The result is allocated on the objfile_obstack and canonicalized.  */
7869
7870 static const char *
7871 dwarf2_compute_name (const char *name,
7872                      struct die_info *die, struct dwarf2_cu *cu,
7873                      int physname)
7874 {
7875   struct objfile *objfile = cu->objfile;
7876
7877   if (name == NULL)
7878     name = dwarf2_name (die, cu);
7879
7880   /* For Fortran GDB prefers DW_AT_*linkage_name if present but otherwise
7881      compute it by typename_concat inside GDB.  */
7882   if (cu->language == language_ada
7883       || (cu->language == language_fortran && physname))
7884     {
7885       /* For Ada unit, we prefer the linkage name over the name, as
7886          the former contains the exported name, which the user expects
7887          to be able to reference.  Ideally, we want the user to be able
7888          to reference this entity using either natural or linkage name,
7889          but we haven't started looking at this enhancement yet.  */
7890       struct attribute *attr;
7891
7892       attr = dwarf2_attr (die, DW_AT_linkage_name, cu);
7893       if (attr == NULL)
7894         attr = dwarf2_attr (die, DW_AT_MIPS_linkage_name, cu);
7895       if (attr && DW_STRING (attr))
7896         return DW_STRING (attr);
7897     }
7898
7899   /* These are the only languages we know how to qualify names in.  */
7900   if (name != NULL
7901       && (cu->language == language_cplus || cu->language == language_java
7902           || cu->language == language_fortran))
7903     {
7904       if (die_needs_namespace (die, cu))
7905         {
7906           long length;
7907           const char *prefix;
7908           struct ui_file *buf;
7909
7910           prefix = determine_prefix (die, cu);
7911           buf = mem_fileopen ();
7912           if (*prefix != '\0')
7913             {
7914               char *prefixed_name = typename_concat (NULL, prefix, name,
7915                                                      physname, cu);
7916
7917               fputs_unfiltered (prefixed_name, buf);
7918               xfree (prefixed_name);
7919             }
7920           else
7921             fputs_unfiltered (name, buf);
7922
7923           /* Template parameters may be specified in the DIE's DW_AT_name, or
7924              as children with DW_TAG_template_type_param or
7925              DW_TAG_value_type_param.  If the latter, add them to the name
7926              here.  If the name already has template parameters, then
7927              skip this step; some versions of GCC emit both, and
7928              it is more efficient to use the pre-computed name.
7929
7930              Something to keep in mind about this process: it is very
7931              unlikely, or in some cases downright impossible, to produce
7932              something that will match the mangled name of a function.
7933              If the definition of the function has the same debug info,
7934              we should be able to match up with it anyway.  But fallbacks
7935              using the minimal symbol, for instance to find a method
7936              implemented in a stripped copy of libstdc++, will not work.
7937              If we do not have debug info for the definition, we will have to
7938              match them up some other way.
7939
7940              When we do name matching there is a related problem with function
7941              templates; two instantiated function templates are allowed to
7942              differ only by their return types, which we do not add here.  */
7943
7944           if (cu->language == language_cplus && strchr (name, '<') == NULL)
7945             {
7946               struct attribute *attr;
7947               struct die_info *child;
7948               int first = 1;
7949
7950               die->building_fullname = 1;
7951
7952               for (child = die->child; child != NULL; child = child->sibling)
7953                 {
7954                   struct type *type;
7955                   LONGEST value;
7956                   const gdb_byte *bytes;
7957                   struct dwarf2_locexpr_baton *baton;
7958                   struct value *v;
7959
7960                   if (child->tag != DW_TAG_template_type_param
7961                       && child->tag != DW_TAG_template_value_param)
7962                     continue;
7963
7964                   if (first)
7965                     {
7966                       fputs_unfiltered ("<", buf);
7967                       first = 0;
7968                     }
7969                   else
7970                     fputs_unfiltered (", ", buf);
7971
7972                   attr = dwarf2_attr (child, DW_AT_type, cu);
7973                   if (attr == NULL)
7974                     {
7975                       complaint (&symfile_complaints,
7976                                  _("template parameter missing DW_AT_type"));
7977                       fputs_unfiltered ("UNKNOWN_TYPE", buf);
7978                       continue;
7979                     }
7980                   type = die_type (child, cu);
7981
7982                   if (child->tag == DW_TAG_template_type_param)
7983                     {
7984                       c_print_type (type, "", buf, -1, 0, &type_print_raw_options);
7985                       continue;
7986                     }
7987
7988                   attr = dwarf2_attr (child, DW_AT_const_value, cu);
7989                   if (attr == NULL)
7990                     {
7991                       complaint (&symfile_complaints,
7992                                  _("template parameter missing "
7993                                    "DW_AT_const_value"));
7994                       fputs_unfiltered ("UNKNOWN_VALUE", buf);
7995                       continue;
7996                     }
7997
7998                   dwarf2_const_value_attr (attr, type, name,
7999                                            &cu->comp_unit_obstack, cu,
8000                                            &value, &bytes, &baton);
8001
8002                   if (TYPE_NOSIGN (type))
8003                     /* GDB prints characters as NUMBER 'CHAR'.  If that's
8004                        changed, this can use value_print instead.  */
8005                     c_printchar (value, type, buf);
8006                   else
8007                     {
8008                       struct value_print_options opts;
8009
8010                       if (baton != NULL)
8011                         v = dwarf2_evaluate_loc_desc (type, NULL,
8012                                                       baton->data,
8013                                                       baton->size,
8014                                                       baton->per_cu);
8015                       else if (bytes != NULL)
8016                         {
8017                           v = allocate_value (type);
8018                           memcpy (value_contents_writeable (v), bytes,
8019                                   TYPE_LENGTH (type));
8020                         }
8021                       else
8022                         v = value_from_longest (type, value);
8023
8024                       /* Specify decimal so that we do not depend on
8025                          the radix.  */
8026                       get_formatted_print_options (&opts, 'd');
8027                       opts.raw = 1;
8028                       value_print (v, buf, &opts);
8029                       release_value (v);
8030                       value_free (v);
8031                     }
8032                 }
8033
8034               die->building_fullname = 0;
8035
8036               if (!first)
8037                 {
8038                   /* Close the argument list, with a space if necessary
8039                      (nested templates).  */
8040                   char last_char = '\0';
8041                   ui_file_put (buf, do_ui_file_peek_last, &last_char);
8042                   if (last_char == '>')
8043                     fputs_unfiltered (" >", buf);
8044                   else
8045                     fputs_unfiltered (">", buf);
8046                 }
8047             }
8048
8049           /* For Java and C++ methods, append formal parameter type
8050              information, if PHYSNAME.  */
8051
8052           if (physname && die->tag == DW_TAG_subprogram
8053               && (cu->language == language_cplus
8054                   || cu->language == language_java))
8055             {
8056               struct type *type = read_type_die (die, cu);
8057
8058               c_type_print_args (type, buf, 1, cu->language,
8059                                  &type_print_raw_options);
8060
8061               if (cu->language == language_java)
8062                 {
8063                   /* For java, we must append the return type to method
8064                      names.  */
8065                   if (die->tag == DW_TAG_subprogram)
8066                     java_print_type (TYPE_TARGET_TYPE (type), "", buf,
8067                                      0, 0, &type_print_raw_options);
8068                 }
8069               else if (cu->language == language_cplus)
8070                 {
8071                   /* Assume that an artificial first parameter is
8072                      "this", but do not crash if it is not.  RealView
8073                      marks unnamed (and thus unused) parameters as
8074                      artificial; there is no way to differentiate
8075                      the two cases.  */
8076                   if (TYPE_NFIELDS (type) > 0
8077                       && TYPE_FIELD_ARTIFICIAL (type, 0)
8078                       && TYPE_CODE (TYPE_FIELD_TYPE (type, 0)) == TYPE_CODE_PTR
8079                       && TYPE_CONST (TYPE_TARGET_TYPE (TYPE_FIELD_TYPE (type,
8080                                                                         0))))
8081                     fputs_unfiltered (" const", buf);
8082                 }
8083             }
8084
8085           name = ui_file_obsavestring (buf, &objfile->objfile_obstack,
8086                                        &length);
8087           ui_file_delete (buf);
8088
8089           if (cu->language == language_cplus)
8090             {
8091               const char *cname
8092                 = dwarf2_canonicalize_name (name, cu,
8093                                             &objfile->objfile_obstack);
8094
8095               if (cname != NULL)
8096                 name = cname;
8097             }
8098         }
8099     }
8100
8101   return name;
8102 }
8103
8104 /* Return the fully qualified name of DIE, based on its DW_AT_name.
8105    If scope qualifiers are appropriate they will be added.  The result
8106    will be allocated on the objfile_obstack, or NULL if the DIE does
8107    not have a name.  NAME may either be from a previous call to
8108    dwarf2_name or NULL.
8109
8110    The output string will be canonicalized (if C++/Java).  */
8111
8112 static const char *
8113 dwarf2_full_name (const char *name, struct die_info *die, struct dwarf2_cu *cu)
8114 {
8115   return dwarf2_compute_name (name, die, cu, 0);
8116 }
8117
8118 /* Construct a physname for the given DIE in CU.  NAME may either be
8119    from a previous call to dwarf2_name or NULL.  The result will be
8120    allocated on the objfile_objstack or NULL if the DIE does not have a
8121    name.
8122
8123    The output string will be canonicalized (if C++/Java).  */
8124
8125 static const char *
8126 dwarf2_physname (const char *name, struct die_info *die, struct dwarf2_cu *cu)
8127 {
8128   struct objfile *objfile = cu->objfile;
8129   struct attribute *attr;
8130   const char *retval, *mangled = NULL, *canon = NULL;
8131   struct cleanup *back_to;
8132   int need_copy = 1;
8133
8134   /* In this case dwarf2_compute_name is just a shortcut not building anything
8135      on its own.  */
8136   if (!die_needs_namespace (die, cu))
8137     return dwarf2_compute_name (name, die, cu, 1);
8138
8139   back_to = make_cleanup (null_cleanup, NULL);
8140
8141   attr = dwarf2_attr (die, DW_AT_linkage_name, cu);
8142   if (!attr)
8143     attr = dwarf2_attr (die, DW_AT_MIPS_linkage_name, cu);
8144
8145   /* DW_AT_linkage_name is missing in some cases - depend on what GDB
8146      has computed.  */
8147   if (attr && DW_STRING (attr))
8148     {
8149       char *demangled;
8150
8151       mangled = DW_STRING (attr);
8152
8153       /* Use DMGL_RET_DROP for C++ template functions to suppress their return
8154          type.  It is easier for GDB users to search for such functions as
8155          `name(params)' than `long name(params)'.  In such case the minimal
8156          symbol names do not match the full symbol names but for template
8157          functions there is never a need to look up their definition from their
8158          declaration so the only disadvantage remains the minimal symbol
8159          variant `long name(params)' does not have the proper inferior type.
8160          */
8161
8162       if (cu->language == language_go)
8163         {
8164           /* This is a lie, but we already lie to the caller new_symbol_full.
8165              new_symbol_full assumes we return the mangled name.
8166              This just undoes that lie until things are cleaned up.  */
8167           demangled = NULL;
8168         }
8169       else
8170         {
8171           demangled = gdb_demangle (mangled,
8172                                     (DMGL_PARAMS | DMGL_ANSI
8173                                      | (cu->language == language_java
8174                                         ? DMGL_JAVA | DMGL_RET_POSTFIX
8175                                         : DMGL_RET_DROP)));
8176         }
8177       if (demangled)
8178         {
8179           make_cleanup (xfree, demangled);
8180           canon = demangled;
8181         }
8182       else
8183         {
8184           canon = mangled;
8185           need_copy = 0;
8186         }
8187     }
8188
8189   if (canon == NULL || check_physname)
8190     {
8191       const char *physname = dwarf2_compute_name (name, die, cu, 1);
8192
8193       if (canon != NULL && strcmp (physname, canon) != 0)
8194         {
8195           /* It may not mean a bug in GDB.  The compiler could also
8196              compute DW_AT_linkage_name incorrectly.  But in such case
8197              GDB would need to be bug-to-bug compatible.  */
8198
8199           complaint (&symfile_complaints,
8200                      _("Computed physname <%s> does not match demangled <%s> "
8201                        "(from linkage <%s>) - DIE at 0x%x [in module %s]"),
8202                      physname, canon, mangled, die->offset.sect_off,
8203                      objfile_name (objfile));
8204
8205           /* Prefer DW_AT_linkage_name (in the CANON form) - when it
8206              is available here - over computed PHYSNAME.  It is safer
8207              against both buggy GDB and buggy compilers.  */
8208
8209           retval = canon;
8210         }
8211       else
8212         {
8213           retval = physname;
8214           need_copy = 0;
8215         }
8216     }
8217   else
8218     retval = canon;
8219
8220   if (need_copy)
8221     retval = obstack_copy0 (&objfile->objfile_obstack, retval, strlen (retval));
8222
8223   do_cleanups (back_to);
8224   return retval;
8225 }
8226
8227 /* Read the import statement specified by the given die and record it.  */
8228
8229 static void
8230 read_import_statement (struct die_info *die, struct dwarf2_cu *cu)
8231 {
8232   struct objfile *objfile = cu->objfile;
8233   struct attribute *import_attr;
8234   struct die_info *imported_die, *child_die;
8235   struct dwarf2_cu *imported_cu;
8236   const char *imported_name;
8237   const char *imported_name_prefix;
8238   const char *canonical_name;
8239   const char *import_alias;
8240   const char *imported_declaration = NULL;
8241   const char *import_prefix;
8242   VEC (const_char_ptr) *excludes = NULL;
8243   struct cleanup *cleanups;
8244
8245   import_attr = dwarf2_attr (die, DW_AT_import, cu);
8246   if (import_attr == NULL)
8247     {
8248       complaint (&symfile_complaints, _("Tag '%s' has no DW_AT_import"),
8249                  dwarf_tag_name (die->tag));
8250       return;
8251     }
8252
8253   imported_cu = cu;
8254   imported_die = follow_die_ref_or_sig (die, import_attr, &imported_cu);
8255   imported_name = dwarf2_name (imported_die, imported_cu);
8256   if (imported_name == NULL)
8257     {
8258       /* GCC bug: https://bugzilla.redhat.com/show_bug.cgi?id=506524
8259
8260         The import in the following code:
8261         namespace A
8262           {
8263             typedef int B;
8264           }
8265
8266         int main ()
8267           {
8268             using A::B;
8269             B b;
8270             return b;
8271           }
8272
8273         ...
8274          <2><51>: Abbrev Number: 3 (DW_TAG_imported_declaration)
8275             <52>   DW_AT_decl_file   : 1
8276             <53>   DW_AT_decl_line   : 6
8277             <54>   DW_AT_import      : <0x75>
8278          <2><58>: Abbrev Number: 4 (DW_TAG_typedef)
8279             <59>   DW_AT_name        : B
8280             <5b>   DW_AT_decl_file   : 1
8281             <5c>   DW_AT_decl_line   : 2
8282             <5d>   DW_AT_type        : <0x6e>
8283         ...
8284          <1><75>: Abbrev Number: 7 (DW_TAG_base_type)
8285             <76>   DW_AT_byte_size   : 4
8286             <77>   DW_AT_encoding    : 5        (signed)
8287
8288         imports the wrong die ( 0x75 instead of 0x58 ).
8289         This case will be ignored until the gcc bug is fixed.  */
8290       return;
8291     }
8292
8293   /* Figure out the local name after import.  */
8294   import_alias = dwarf2_name (die, cu);
8295
8296   /* Figure out where the statement is being imported to.  */
8297   import_prefix = determine_prefix (die, cu);
8298
8299   /* Figure out what the scope of the imported die is and prepend it
8300      to the name of the imported die.  */
8301   imported_name_prefix = determine_prefix (imported_die, imported_cu);
8302
8303   if (imported_die->tag != DW_TAG_namespace
8304       && imported_die->tag != DW_TAG_module)
8305     {
8306       imported_declaration = imported_name;
8307       canonical_name = imported_name_prefix;
8308     }
8309   else if (strlen (imported_name_prefix) > 0)
8310     canonical_name = obconcat (&objfile->objfile_obstack,
8311                                imported_name_prefix, "::", imported_name,
8312                                (char *) NULL);
8313   else
8314     canonical_name = imported_name;
8315
8316   cleanups = make_cleanup (VEC_cleanup (const_char_ptr), &excludes);
8317
8318   if (die->tag == DW_TAG_imported_module && cu->language == language_fortran)
8319     for (child_die = die->child; child_die && child_die->tag;
8320          child_die = sibling_die (child_die))
8321       {
8322         /* DWARF-4: A Fortran use statement with a “rename list” may be
8323            represented by an imported module entry with an import attribute
8324            referring to the module and owned entries corresponding to those
8325            entities that are renamed as part of being imported.  */
8326
8327         if (child_die->tag != DW_TAG_imported_declaration)
8328           {
8329             complaint (&symfile_complaints,
8330                        _("child DW_TAG_imported_declaration expected "
8331                          "- DIE at 0x%x [in module %s]"),
8332                        child_die->offset.sect_off, objfile_name (objfile));
8333             continue;
8334           }
8335
8336         import_attr = dwarf2_attr (child_die, DW_AT_import, cu);
8337         if (import_attr == NULL)
8338           {
8339             complaint (&symfile_complaints, _("Tag '%s' has no DW_AT_import"),
8340                        dwarf_tag_name (child_die->tag));
8341             continue;
8342           }
8343
8344         imported_cu = cu;
8345         imported_die = follow_die_ref_or_sig (child_die, import_attr,
8346                                               &imported_cu);
8347         imported_name = dwarf2_name (imported_die, imported_cu);
8348         if (imported_name == NULL)
8349           {
8350             complaint (&symfile_complaints,
8351                        _("child DW_TAG_imported_declaration has unknown "
8352                          "imported name - DIE at 0x%x [in module %s]"),
8353                        child_die->offset.sect_off, objfile_name (objfile));
8354             continue;
8355           }
8356
8357         VEC_safe_push (const_char_ptr, excludes, imported_name);
8358
8359         process_die (child_die, cu);
8360       }
8361
8362   cp_add_using_directive (import_prefix,
8363                           canonical_name,
8364                           import_alias,
8365                           imported_declaration,
8366                           excludes,
8367                           0,
8368                           &objfile->objfile_obstack);
8369
8370   do_cleanups (cleanups);
8371 }
8372
8373 /* Cleanup function for handle_DW_AT_stmt_list.  */
8374
8375 static void
8376 free_cu_line_header (void *arg)
8377 {
8378   struct dwarf2_cu *cu = arg;
8379
8380   free_line_header (cu->line_header);
8381   cu->line_header = NULL;
8382 }
8383
8384 /* Check for possibly missing DW_AT_comp_dir with relative .debug_line
8385    directory paths.  GCC SVN r127613 (new option -fdebug-prefix-map) fixed
8386    this, it was first present in GCC release 4.3.0.  */
8387
8388 static int
8389 producer_is_gcc_lt_4_3 (struct dwarf2_cu *cu)
8390 {
8391   if (!cu->checked_producer)
8392     check_producer (cu);
8393
8394   return cu->producer_is_gcc_lt_4_3;
8395 }
8396
8397 static void
8398 find_file_and_directory (struct die_info *die, struct dwarf2_cu *cu,
8399                          const char **name, const char **comp_dir)
8400 {
8401   struct attribute *attr;
8402
8403   *name = NULL;
8404   *comp_dir = NULL;
8405
8406   /* Find the filename.  Do not use dwarf2_name here, since the filename
8407      is not a source language identifier.  */
8408   attr = dwarf2_attr (die, DW_AT_name, cu);
8409   if (attr)
8410     {
8411       *name = DW_STRING (attr);
8412     }
8413
8414   attr = dwarf2_attr (die, DW_AT_comp_dir, cu);
8415   if (attr)
8416     *comp_dir = DW_STRING (attr);
8417   else if (producer_is_gcc_lt_4_3 (cu) && *name != NULL
8418            && IS_ABSOLUTE_PATH (*name))
8419     {
8420       char *d = ldirname (*name);
8421
8422       *comp_dir = d;
8423       if (d != NULL)
8424         make_cleanup (xfree, d);
8425     }
8426   if (*comp_dir != NULL)
8427     {
8428       /* Irix 6.2 native cc prepends <machine>.: to the compilation
8429          directory, get rid of it.  */
8430       char *cp = strchr (*comp_dir, ':');
8431
8432       if (cp && cp != *comp_dir && cp[-1] == '.' && cp[1] == '/')
8433         *comp_dir = cp + 1;
8434     }
8435
8436   if (*name == NULL)
8437     *name = "<unknown>";
8438 }
8439
8440 /* Handle DW_AT_stmt_list for a compilation unit.
8441    DIE is the DW_TAG_compile_unit die for CU.
8442    COMP_DIR is the compilation directory.
8443    WANT_LINE_INFO is non-zero if the pc/line-number mapping is needed.  */
8444
8445 static void
8446 handle_DW_AT_stmt_list (struct die_info *die, struct dwarf2_cu *cu,
8447                         const char *comp_dir) /* ARI: editCase function */
8448 {
8449   struct attribute *attr;
8450
8451   gdb_assert (! cu->per_cu->is_debug_types);
8452
8453   attr = dwarf2_attr (die, DW_AT_stmt_list, cu);
8454   if (attr)
8455     {
8456       unsigned int line_offset = DW_UNSND (attr);
8457       struct line_header *line_header
8458         = dwarf_decode_line_header (line_offset, cu);
8459
8460       if (line_header)
8461         {
8462           cu->line_header = line_header;
8463           make_cleanup (free_cu_line_header, cu);
8464           dwarf_decode_lines (line_header, comp_dir, cu, NULL, 1);
8465         }
8466     }
8467 }
8468
8469 /* Process DW_TAG_compile_unit or DW_TAG_partial_unit.  */
8470
8471 static void
8472 read_file_scope (struct die_info *die, struct dwarf2_cu *cu)
8473 {
8474   struct objfile *objfile = dwarf2_per_objfile->objfile;
8475   struct cleanup *back_to = make_cleanup (null_cleanup, 0);
8476   CORE_ADDR lowpc = ((CORE_ADDR) -1);
8477   CORE_ADDR highpc = ((CORE_ADDR) 0);
8478   struct attribute *attr;
8479   const char *name = NULL;
8480   const char *comp_dir = NULL;
8481   struct die_info *child_die;
8482   bfd *abfd = objfile->obfd;
8483   CORE_ADDR baseaddr;
8484
8485   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
8486
8487   get_scope_pc_bounds (die, &lowpc, &highpc, cu);
8488
8489   /* If we didn't find a lowpc, set it to highpc to avoid complaints
8490      from finish_block.  */
8491   if (lowpc == ((CORE_ADDR) -1))
8492     lowpc = highpc;
8493   lowpc += baseaddr;
8494   highpc += baseaddr;
8495
8496   find_file_and_directory (die, cu, &name, &comp_dir);
8497
8498   prepare_one_comp_unit (cu, die, cu->language);
8499
8500   /* The XLCL doesn't generate DW_LANG_OpenCL because this attribute is not
8501      standardised yet.  As a workaround for the language detection we fall
8502      back to the DW_AT_producer string.  */
8503   if (cu->producer && strstr (cu->producer, "IBM XL C for OpenCL") != NULL)
8504     cu->language = language_opencl;
8505
8506   /* Similar hack for Go.  */
8507   if (cu->producer && strstr (cu->producer, "GNU Go ") != NULL)
8508     set_cu_language (DW_LANG_Go, cu);
8509
8510   dwarf2_start_symtab (cu, name, comp_dir, lowpc);
8511
8512   /* Decode line number information if present.  We do this before
8513      processing child DIEs, so that the line header table is available
8514      for DW_AT_decl_file.  */
8515   handle_DW_AT_stmt_list (die, cu, comp_dir);
8516
8517   /* Process all dies in compilation unit.  */
8518   if (die->child != NULL)
8519     {
8520       child_die = die->child;
8521       while (child_die && child_die->tag)
8522         {
8523           process_die (child_die, cu);
8524           child_die = sibling_die (child_die);
8525         }
8526     }
8527
8528   /* Decode macro information, if present.  Dwarf 2 macro information
8529      refers to information in the line number info statement program
8530      header, so we can only read it if we've read the header
8531      successfully.  */
8532   attr = dwarf2_attr (die, DW_AT_GNU_macros, cu);
8533   if (attr && cu->line_header)
8534     {
8535       if (dwarf2_attr (die, DW_AT_macro_info, cu))
8536         complaint (&symfile_complaints,
8537                    _("CU refers to both DW_AT_GNU_macros and DW_AT_macro_info"));
8538
8539       dwarf_decode_macros (cu, DW_UNSND (attr), comp_dir, 1);
8540     }
8541   else
8542     {
8543       attr = dwarf2_attr (die, DW_AT_macro_info, cu);
8544       if (attr && cu->line_header)
8545         {
8546           unsigned int macro_offset = DW_UNSND (attr);
8547
8548           dwarf_decode_macros (cu, macro_offset, comp_dir, 0);
8549         }
8550     }
8551
8552   do_cleanups (back_to);
8553 }
8554
8555 /* TU version of handle_DW_AT_stmt_list for read_type_unit_scope.
8556    Create the set of symtabs used by this TU, or if this TU is sharing
8557    symtabs with another TU and the symtabs have already been created
8558    then restore those symtabs in the line header.
8559    We don't need the pc/line-number mapping for type units.  */
8560
8561 static void
8562 setup_type_unit_groups (struct die_info *die, struct dwarf2_cu *cu)
8563 {
8564   struct objfile *objfile = dwarf2_per_objfile->objfile;
8565   struct dwarf2_per_cu_data *per_cu = cu->per_cu;
8566   struct type_unit_group *tu_group;
8567   int first_time;
8568   struct line_header *lh;
8569   struct attribute *attr;
8570   unsigned int i, line_offset;
8571   struct signatured_type *sig_type;
8572
8573   gdb_assert (per_cu->is_debug_types);
8574   sig_type = (struct signatured_type *) per_cu;
8575
8576   attr = dwarf2_attr (die, DW_AT_stmt_list, cu);
8577
8578   /* If we're using .gdb_index (includes -readnow) then
8579      per_cu->type_unit_group may not have been set up yet.  */
8580   if (sig_type->type_unit_group == NULL)
8581     sig_type->type_unit_group = get_type_unit_group (cu, attr);
8582   tu_group = sig_type->type_unit_group;
8583
8584   /* If we've already processed this stmt_list there's no real need to
8585      do it again, we could fake it and just recreate the part we need
8586      (file name,index -> symtab mapping).  If data shows this optimization
8587      is useful we can do it then.  */
8588   first_time = tu_group->primary_symtab == NULL;
8589
8590   /* We have to handle the case of both a missing DW_AT_stmt_list or bad
8591      debug info.  */
8592   lh = NULL;
8593   if (attr != NULL)
8594     {
8595       line_offset = DW_UNSND (attr);
8596       lh = dwarf_decode_line_header (line_offset, cu);
8597     }
8598   if (lh == NULL)
8599     {
8600       if (first_time)
8601         dwarf2_start_symtab (cu, "", NULL, 0);
8602       else
8603         {
8604           gdb_assert (tu_group->symtabs == NULL);
8605           restart_symtab (0);
8606         }
8607       /* Note: The primary symtab will get allocated at the end.  */
8608       return;
8609     }
8610
8611   cu->line_header = lh;
8612   make_cleanup (free_cu_line_header, cu);
8613
8614   if (first_time)
8615     {
8616       dwarf2_start_symtab (cu, "", NULL, 0);
8617
8618       tu_group->num_symtabs = lh->num_file_names;
8619       tu_group->symtabs = XNEWVEC (struct symtab *, lh->num_file_names);
8620
8621       for (i = 0; i < lh->num_file_names; ++i)
8622         {
8623           const char *dir = NULL;
8624           struct file_entry *fe = &lh->file_names[i];
8625
8626           if (fe->dir_index)
8627             dir = lh->include_dirs[fe->dir_index - 1];
8628           dwarf2_start_subfile (fe->name, dir, NULL);
8629
8630           /* Note: We don't have to watch for the main subfile here, type units
8631              don't have DW_AT_name.  */
8632
8633           if (current_subfile->symtab == NULL)
8634             {
8635               /* NOTE: start_subfile will recognize when it's been passed
8636                  a file it has already seen.  So we can't assume there's a
8637                  simple mapping from lh->file_names to subfiles,
8638                  lh->file_names may contain dups.  */
8639               current_subfile->symtab = allocate_symtab (current_subfile->name,
8640                                                          objfile);
8641             }
8642
8643           fe->symtab = current_subfile->symtab;
8644           tu_group->symtabs[i] = fe->symtab;
8645         }
8646     }
8647   else
8648     {
8649       restart_symtab (0);
8650
8651       for (i = 0; i < lh->num_file_names; ++i)
8652         {
8653           struct file_entry *fe = &lh->file_names[i];
8654
8655           fe->symtab = tu_group->symtabs[i];
8656         }
8657     }
8658
8659   /* The main symtab is allocated last.  Type units don't have DW_AT_name
8660      so they don't have a "real" (so to speak) symtab anyway.
8661      There is later code that will assign the main symtab to all symbols
8662      that don't have one.  We need to handle the case of a symbol with a
8663      missing symtab (DW_AT_decl_file) anyway.  */
8664 }
8665
8666 /* Process DW_TAG_type_unit.
8667    For TUs we want to skip the first top level sibling if it's not the
8668    actual type being defined by this TU.  In this case the first top
8669    level sibling is there to provide context only.  */
8670
8671 static void
8672 read_type_unit_scope (struct die_info *die, struct dwarf2_cu *cu)
8673 {
8674   struct die_info *child_die;
8675
8676   prepare_one_comp_unit (cu, die, language_minimal);
8677
8678   /* Initialize (or reinitialize) the machinery for building symtabs.
8679      We do this before processing child DIEs, so that the line header table
8680      is available for DW_AT_decl_file.  */
8681   setup_type_unit_groups (die, cu);
8682
8683   if (die->child != NULL)
8684     {
8685       child_die = die->child;
8686       while (child_die && child_die->tag)
8687         {
8688           process_die (child_die, cu);
8689           child_die = sibling_die (child_die);
8690         }
8691     }
8692 }
8693 \f
8694 /* DWO/DWP files.
8695
8696    http://gcc.gnu.org/wiki/DebugFission
8697    http://gcc.gnu.org/wiki/DebugFissionDWP
8698
8699    To simplify handling of both DWO files ("object" files with the DWARF info)
8700    and DWP files (a file with the DWOs packaged up into one file), we treat
8701    DWP files as having a collection of virtual DWO files.  */
8702
8703 static hashval_t
8704 hash_dwo_file (const void *item)
8705 {
8706   const struct dwo_file *dwo_file = item;
8707   hashval_t hash;
8708
8709   hash = htab_hash_string (dwo_file->dwo_name);
8710   if (dwo_file->comp_dir != NULL)
8711     hash += htab_hash_string (dwo_file->comp_dir);
8712   return hash;
8713 }
8714
8715 static int
8716 eq_dwo_file (const void *item_lhs, const void *item_rhs)
8717 {
8718   const struct dwo_file *lhs = item_lhs;
8719   const struct dwo_file *rhs = item_rhs;
8720
8721   if (strcmp (lhs->dwo_name, rhs->dwo_name) != 0)
8722     return 0;
8723   if (lhs->comp_dir == NULL || rhs->comp_dir == NULL)
8724     return lhs->comp_dir == rhs->comp_dir;
8725   return strcmp (lhs->comp_dir, rhs->comp_dir) == 0;
8726 }
8727
8728 /* Allocate a hash table for DWO files.  */
8729
8730 static htab_t
8731 allocate_dwo_file_hash_table (void)
8732 {
8733   struct objfile *objfile = dwarf2_per_objfile->objfile;
8734
8735   return htab_create_alloc_ex (41,
8736                                hash_dwo_file,
8737                                eq_dwo_file,
8738                                NULL,
8739                                &objfile->objfile_obstack,
8740                                hashtab_obstack_allocate,
8741                                dummy_obstack_deallocate);
8742 }
8743
8744 /* Lookup DWO file DWO_NAME.  */
8745
8746 static void **
8747 lookup_dwo_file_slot (const char *dwo_name, const char *comp_dir)
8748 {
8749   struct dwo_file find_entry;
8750   void **slot;
8751
8752   if (dwarf2_per_objfile->dwo_files == NULL)
8753     dwarf2_per_objfile->dwo_files = allocate_dwo_file_hash_table ();
8754
8755   memset (&find_entry, 0, sizeof (find_entry));
8756   find_entry.dwo_name = dwo_name;
8757   find_entry.comp_dir = comp_dir;
8758   slot = htab_find_slot (dwarf2_per_objfile->dwo_files, &find_entry, INSERT);
8759
8760   return slot;
8761 }
8762
8763 static hashval_t
8764 hash_dwo_unit (const void *item)
8765 {
8766   const struct dwo_unit *dwo_unit = item;
8767
8768   /* This drops the top 32 bits of the id, but is ok for a hash.  */
8769   return dwo_unit->signature;
8770 }
8771
8772 static int
8773 eq_dwo_unit (const void *item_lhs, const void *item_rhs)
8774 {
8775   const struct dwo_unit *lhs = item_lhs;
8776   const struct dwo_unit *rhs = item_rhs;
8777
8778   /* The signature is assumed to be unique within the DWO file.
8779      So while object file CU dwo_id's always have the value zero,
8780      that's OK, assuming each object file DWO file has only one CU,
8781      and that's the rule for now.  */
8782   return lhs->signature == rhs->signature;
8783 }
8784
8785 /* Allocate a hash table for DWO CUs,TUs.
8786    There is one of these tables for each of CUs,TUs for each DWO file.  */
8787
8788 static htab_t
8789 allocate_dwo_unit_table (struct objfile *objfile)
8790 {
8791   /* Start out with a pretty small number.
8792      Generally DWO files contain only one CU and maybe some TUs.  */
8793   return htab_create_alloc_ex (3,
8794                                hash_dwo_unit,
8795                                eq_dwo_unit,
8796                                NULL,
8797                                &objfile->objfile_obstack,
8798                                hashtab_obstack_allocate,
8799                                dummy_obstack_deallocate);
8800 }
8801
8802 /* Structure used to pass data to create_dwo_debug_info_hash_table_reader.  */
8803
8804 struct create_dwo_cu_data
8805 {
8806   struct dwo_file *dwo_file;
8807   struct dwo_unit dwo_unit;
8808 };
8809
8810 /* die_reader_func for create_dwo_cu.  */
8811
8812 static void
8813 create_dwo_cu_reader (const struct die_reader_specs *reader,
8814                       const gdb_byte *info_ptr,
8815                       struct die_info *comp_unit_die,
8816                       int has_children,
8817                       void *datap)
8818 {
8819   struct dwarf2_cu *cu = reader->cu;
8820   struct objfile *objfile = dwarf2_per_objfile->objfile;
8821   sect_offset offset = cu->per_cu->offset;
8822   struct dwarf2_section_info *section = cu->per_cu->section;
8823   struct create_dwo_cu_data *data = datap;
8824   struct dwo_file *dwo_file = data->dwo_file;
8825   struct dwo_unit *dwo_unit = &data->dwo_unit;
8826   struct attribute *attr;
8827
8828   attr = dwarf2_attr (comp_unit_die, DW_AT_GNU_dwo_id, cu);
8829   if (attr == NULL)
8830     {
8831       complaint (&symfile_complaints,
8832                  _("Dwarf Error: debug entry at offset 0x%x is missing"
8833                    " its dwo_id [in module %s]"),
8834                  offset.sect_off, dwo_file->dwo_name);
8835       return;
8836     }
8837
8838   dwo_unit->dwo_file = dwo_file;
8839   dwo_unit->signature = DW_UNSND (attr);
8840   dwo_unit->section = section;
8841   dwo_unit->offset = offset;
8842   dwo_unit->length = cu->per_cu->length;
8843
8844   if (dwarf2_read_debug)
8845     fprintf_unfiltered (gdb_stdlog, "  offset 0x%x, dwo_id %s\n",
8846                         offset.sect_off, hex_string (dwo_unit->signature));
8847 }
8848
8849 /* Create the dwo_unit for the lone CU in DWO_FILE.
8850    Note: This function processes DWO files only, not DWP files.  */
8851
8852 static struct dwo_unit *
8853 create_dwo_cu (struct dwo_file *dwo_file)
8854 {
8855   struct objfile *objfile = dwarf2_per_objfile->objfile;
8856   struct dwarf2_section_info *section = &dwo_file->sections.info;
8857   bfd *abfd;
8858   htab_t cu_htab;
8859   const gdb_byte *info_ptr, *end_ptr;
8860   struct create_dwo_cu_data create_dwo_cu_data;
8861   struct dwo_unit *dwo_unit;
8862
8863   dwarf2_read_section (objfile, section);
8864   info_ptr = section->buffer;
8865
8866   if (info_ptr == NULL)
8867     return NULL;
8868
8869   /* We can't set abfd until now because the section may be empty or
8870      not present, in which case section->asection will be NULL.  */
8871   abfd = section->asection->owner;
8872
8873   if (dwarf2_read_debug)
8874     {
8875       fprintf_unfiltered (gdb_stdlog, "Reading %s for %s:\n",
8876                           bfd_section_name (abfd, section->asection),
8877                           bfd_get_filename (abfd));
8878     }
8879
8880   create_dwo_cu_data.dwo_file = dwo_file;
8881   dwo_unit = NULL;
8882
8883   end_ptr = info_ptr + section->size;
8884   while (info_ptr < end_ptr)
8885     {
8886       struct dwarf2_per_cu_data per_cu;
8887
8888       memset (&create_dwo_cu_data.dwo_unit, 0,
8889               sizeof (create_dwo_cu_data.dwo_unit));
8890       memset (&per_cu, 0, sizeof (per_cu));
8891       per_cu.objfile = objfile;
8892       per_cu.is_debug_types = 0;
8893       per_cu.offset.sect_off = info_ptr - section->buffer;
8894       per_cu.section = section;
8895
8896       init_cutu_and_read_dies_no_follow (&per_cu,
8897                                          &dwo_file->sections.abbrev,
8898                                          dwo_file,
8899                                          create_dwo_cu_reader,
8900                                          &create_dwo_cu_data);
8901
8902       if (create_dwo_cu_data.dwo_unit.dwo_file != NULL)
8903         {
8904           /* If we've already found one, complain.  We only support one
8905              because having more than one requires hacking the dwo_name of
8906              each to match, which is highly unlikely to happen.  */
8907           if (dwo_unit != NULL)
8908             {
8909               complaint (&symfile_complaints,
8910                          _("Multiple CUs in DWO file %s [in module %s]"),
8911                          dwo_file->dwo_name, objfile_name (objfile));
8912               break;
8913             }
8914
8915           dwo_unit = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_unit);
8916           *dwo_unit = create_dwo_cu_data.dwo_unit;
8917         }
8918
8919       info_ptr += per_cu.length;
8920     }
8921
8922   return dwo_unit;
8923 }
8924
8925 /* DWP file .debug_{cu,tu}_index section format:
8926    [ref: http://gcc.gnu.org/wiki/DebugFissionDWP]
8927
8928    DWP Version 1:
8929
8930    Both index sections have the same format, and serve to map a 64-bit
8931    signature to a set of section numbers.  Each section begins with a header,
8932    followed by a hash table of 64-bit signatures, a parallel table of 32-bit
8933    indexes, and a pool of 32-bit section numbers.  The index sections will be
8934    aligned at 8-byte boundaries in the file.
8935
8936    The index section header consists of:
8937
8938     V, 32 bit version number
8939     -, 32 bits unused
8940     N, 32 bit number of compilation units or type units in the index
8941     M, 32 bit number of slots in the hash table
8942
8943    Numbers are recorded using the byte order of the application binary.
8944
8945    We assume that N and M will not exceed 2^32 - 1.
8946
8947    The size of the hash table, M, must be 2^k such that 2^k > 3*N/2.
8948
8949    The hash table begins at offset 16 in the section, and consists of an array
8950    of M 64-bit slots.  Each slot contains a 64-bit signature (using the byte
8951    order of the application binary).  Unused slots in the hash table are 0.
8952    (We rely on the extreme unlikeliness of a signature being exactly 0.)
8953
8954    The parallel table begins immediately after the hash table
8955    (at offset 16 + 8 * M from the beginning of the section), and consists of an
8956    array of 32-bit indexes (using the byte order of the application binary),
8957    corresponding 1-1 with slots in the hash table.  Each entry in the parallel
8958    table contains a 32-bit index into the pool of section numbers.  For unused
8959    hash table slots, the corresponding entry in the parallel table will be 0.
8960
8961    Given a 64-bit compilation unit signature or a type signature S, an entry
8962    in the hash table is located as follows:
8963
8964    1) Calculate a primary hash H = S & MASK(k), where MASK(k) is a mask with
8965       the low-order k bits all set to 1.
8966
8967    2) Calculate a secondary hash H' = (((S >> 32) & MASK(k)) | 1).
8968
8969    3) If the hash table entry at index H matches the signature, use that
8970       entry.  If the hash table entry at index H is unused (all zeroes),
8971       terminate the search: the signature is not present in the table.
8972
8973    4) Let H = (H + H') modulo M. Repeat at Step 3.
8974
8975    Because M > N and H' and M are relatively prime, the search is guaranteed
8976    to stop at an unused slot or find the match.
8977
8978    The pool of section numbers begins immediately following the hash table
8979    (at offset 16 + 12 * M from the beginning of the section).  The pool of
8980    section numbers consists of an array of 32-bit words (using the byte order
8981    of the application binary).  Each item in the array is indexed starting
8982    from 0.  The hash table entry provides the index of the first section
8983    number in the set.  Additional section numbers in the set follow, and the
8984    set is terminated by a 0 entry (section number 0 is not used in ELF).
8985
8986    In each set of section numbers, the .debug_info.dwo or .debug_types.dwo
8987    section must be the first entry in the set, and the .debug_abbrev.dwo must
8988    be the second entry. Other members of the set may follow in any order.  */
8989
8990 /* Create a hash table to map DWO IDs to their CU/TU entry in
8991    .debug_{info,types}.dwo in DWP_FILE.
8992    Returns NULL if there isn't one.
8993    Note: This function processes DWP files only, not DWO files.  */
8994
8995 static struct dwp_hash_table *
8996 create_dwp_hash_table (struct dwp_file *dwp_file, int is_debug_types)
8997 {
8998   struct objfile *objfile = dwarf2_per_objfile->objfile;
8999   bfd *dbfd = dwp_file->dbfd;
9000   const gdb_byte *index_ptr, *index_end;
9001   struct dwarf2_section_info *index;
9002   uint32_t version, nr_units, nr_slots;
9003   struct dwp_hash_table *htab;
9004
9005   if (is_debug_types)
9006     index = &dwp_file->sections.tu_index;
9007   else
9008     index = &dwp_file->sections.cu_index;
9009
9010   if (dwarf2_section_empty_p (index))
9011     return NULL;
9012   dwarf2_read_section (objfile, index);
9013
9014   index_ptr = index->buffer;
9015   index_end = index_ptr + index->size;
9016
9017   version = read_4_bytes (dbfd, index_ptr);
9018   index_ptr += 8; /* Skip the unused word.  */
9019   nr_units = read_4_bytes (dbfd, index_ptr);
9020   index_ptr += 4;
9021   nr_slots = read_4_bytes (dbfd, index_ptr);
9022   index_ptr += 4;
9023
9024   if (version != 1)
9025     {
9026       error (_("Dwarf Error: unsupported DWP file version (%s)"
9027                " [in module %s]"),
9028              pulongest (version), dwp_file->name);
9029     }
9030   if (nr_slots != (nr_slots & -nr_slots))
9031     {
9032       error (_("Dwarf Error: number of slots in DWP hash table (%s)"
9033                " is not power of 2 [in module %s]"),
9034              pulongest (nr_slots), dwp_file->name);
9035     }
9036
9037   htab = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwp_hash_table);
9038   htab->nr_units = nr_units;
9039   htab->nr_slots = nr_slots;
9040   htab->hash_table = index_ptr;
9041   htab->unit_table = htab->hash_table + sizeof (uint64_t) * nr_slots;
9042   htab->section_pool = htab->unit_table + sizeof (uint32_t) * nr_slots;
9043
9044   return htab;
9045 }
9046
9047 /* Update SECTIONS with the data from SECTP.
9048
9049    This function is like the other "locate" section routines that are
9050    passed to bfd_map_over_sections, but in this context the sections to
9051    read comes from the DWP hash table, not the full ELF section table.
9052
9053    The result is non-zero for success, or zero if an error was found.  */
9054
9055 static int
9056 locate_virtual_dwo_sections (asection *sectp,
9057                              struct virtual_dwo_sections *sections)
9058 {
9059   const struct dwop_section_names *names = &dwop_section_names;
9060
9061   if (section_is_p (sectp->name, &names->abbrev_dwo))
9062     {
9063       /* There can be only one.  */
9064       if (sections->abbrev.asection != NULL)
9065         return 0;
9066       sections->abbrev.asection = sectp;
9067       sections->abbrev.size = bfd_get_section_size (sectp);
9068     }
9069   else if (section_is_p (sectp->name, &names->info_dwo)
9070            || section_is_p (sectp->name, &names->types_dwo))
9071     {
9072       /* There can be only one.  */
9073       if (sections->info_or_types.asection != NULL)
9074         return 0;
9075       sections->info_or_types.asection = sectp;
9076       sections->info_or_types.size = bfd_get_section_size (sectp);
9077     }
9078   else if (section_is_p (sectp->name, &names->line_dwo))
9079     {
9080       /* There can be only one.  */
9081       if (sections->line.asection != NULL)
9082         return 0;
9083       sections->line.asection = sectp;
9084       sections->line.size = bfd_get_section_size (sectp);
9085     }
9086   else if (section_is_p (sectp->name, &names->loc_dwo))
9087     {
9088       /* There can be only one.  */
9089       if (sections->loc.asection != NULL)
9090         return 0;
9091       sections->loc.asection = sectp;
9092       sections->loc.size = bfd_get_section_size (sectp);
9093     }
9094   else if (section_is_p (sectp->name, &names->macinfo_dwo))
9095     {
9096       /* There can be only one.  */
9097       if (sections->macinfo.asection != NULL)
9098         return 0;
9099       sections->macinfo.asection = sectp;
9100       sections->macinfo.size = bfd_get_section_size (sectp);
9101     }
9102   else if (section_is_p (sectp->name, &names->macro_dwo))
9103     {
9104       /* There can be only one.  */
9105       if (sections->macro.asection != NULL)
9106         return 0;
9107       sections->macro.asection = sectp;
9108       sections->macro.size = bfd_get_section_size (sectp);
9109     }
9110   else if (section_is_p (sectp->name, &names->str_offsets_dwo))
9111     {
9112       /* There can be only one.  */
9113       if (sections->str_offsets.asection != NULL)
9114         return 0;
9115       sections->str_offsets.asection = sectp;
9116       sections->str_offsets.size = bfd_get_section_size (sectp);
9117     }
9118   else
9119     {
9120       /* No other kind of section is valid.  */
9121       return 0;
9122     }
9123
9124   return 1;
9125 }
9126
9127 /* Create a dwo_unit object for the DWO with signature SIGNATURE.
9128    HTAB is the hash table from the DWP file.
9129    SECTION_INDEX is the index of the DWO in HTAB.
9130    COMP_DIR is the DW_AT_comp_dir attribute of the referencing CU.  */
9131
9132 static struct dwo_unit *
9133 create_dwo_in_dwp (struct dwp_file *dwp_file,
9134                    const struct dwp_hash_table *htab,
9135                    uint32_t section_index,
9136                    const char *comp_dir,
9137                    ULONGEST signature, int is_debug_types)
9138 {
9139   struct objfile *objfile = dwarf2_per_objfile->objfile;
9140   bfd *dbfd = dwp_file->dbfd;
9141   const char *kind = is_debug_types ? "TU" : "CU";
9142   struct dwo_file *dwo_file;
9143   struct dwo_unit *dwo_unit;
9144   struct virtual_dwo_sections sections;
9145   void **dwo_file_slot;
9146   char *virtual_dwo_name;
9147   struct dwarf2_section_info *cutu;
9148   struct cleanup *cleanups;
9149   int i;
9150
9151   if (dwarf2_read_debug)
9152     {
9153       fprintf_unfiltered (gdb_stdlog, "Reading %s %s/%s in DWP file: %s\n",
9154                           kind,
9155                           pulongest (section_index), hex_string (signature),
9156                           dwp_file->name);
9157     }
9158
9159   /* Fetch the sections of this DWO.
9160      Put a limit on the number of sections we look for so that bad data
9161      doesn't cause us to loop forever.  */
9162
9163 #define MAX_NR_DWO_SECTIONS \
9164   (1 /* .debug_info or .debug_types */ \
9165    + 1 /* .debug_abbrev */ \
9166    + 1 /* .debug_line */ \
9167    + 1 /* .debug_loc */ \
9168    + 1 /* .debug_str_offsets */ \
9169    + 1 /* .debug_macro */ \
9170    + 1 /* .debug_macinfo */ \
9171    + 1 /* trailing zero */)
9172
9173   memset (&sections, 0, sizeof (sections));
9174   cleanups = make_cleanup (null_cleanup, 0);
9175
9176   for (i = 0; i < MAX_NR_DWO_SECTIONS; ++i)
9177     {
9178       asection *sectp;
9179       uint32_t section_nr =
9180         read_4_bytes (dbfd,
9181                       htab->section_pool
9182                       + (section_index + i) * sizeof (uint32_t));
9183
9184       if (section_nr == 0)
9185         break;
9186       if (section_nr >= dwp_file->num_sections)
9187         {
9188           error (_("Dwarf Error: bad DWP hash table, section number too large"
9189                    " [in module %s]"),
9190                  dwp_file->name);
9191         }
9192
9193       sectp = dwp_file->elf_sections[section_nr];
9194       if (! locate_virtual_dwo_sections (sectp, &sections))
9195         {
9196           error (_("Dwarf Error: bad DWP hash table, invalid section found"
9197                    " [in module %s]"),
9198                  dwp_file->name);
9199         }
9200     }
9201
9202   if (i < 2
9203       || sections.info_or_types.asection == NULL
9204       || sections.abbrev.asection == NULL)
9205     {
9206       error (_("Dwarf Error: bad DWP hash table, missing DWO sections"
9207                " [in module %s]"),
9208              dwp_file->name);
9209     }
9210   if (i == MAX_NR_DWO_SECTIONS)
9211     {
9212       error (_("Dwarf Error: bad DWP hash table, too many DWO sections"
9213                " [in module %s]"),
9214              dwp_file->name);
9215     }
9216
9217   /* It's easier for the rest of the code if we fake a struct dwo_file and
9218      have dwo_unit "live" in that.  At least for now.
9219
9220      The DWP file can be made up of a random collection of CUs and TUs.
9221      However, for each CU + set of TUs that came from the same original DWO
9222      file, we want to combine them back into a virtual DWO file to save space
9223      (fewer struct dwo_file objects to allocated).  Remember that for really
9224      large apps there can be on the order of 8K CUs and 200K TUs, or more.  */
9225
9226   virtual_dwo_name =
9227     xstrprintf ("virtual-dwo/%d-%d-%d-%d",
9228                 sections.abbrev.asection ? sections.abbrev.asection->id : 0,
9229                 sections.line.asection ? sections.line.asection->id : 0,
9230                 sections.loc.asection ? sections.loc.asection->id : 0,
9231                 (sections.str_offsets.asection
9232                 ? sections.str_offsets.asection->id
9233                 : 0));
9234   make_cleanup (xfree, virtual_dwo_name);
9235   /* Can we use an existing virtual DWO file?  */
9236   dwo_file_slot = lookup_dwo_file_slot (virtual_dwo_name, comp_dir);
9237   /* Create one if necessary.  */
9238   if (*dwo_file_slot == NULL)
9239     {
9240       if (dwarf2_read_debug)
9241         {
9242           fprintf_unfiltered (gdb_stdlog, "Creating virtual DWO: %s\n",
9243                               virtual_dwo_name);
9244         }
9245       dwo_file = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_file);
9246       dwo_file->dwo_name = obstack_copy0 (&objfile->objfile_obstack,
9247                                           virtual_dwo_name,
9248                                           strlen (virtual_dwo_name));
9249       dwo_file->comp_dir = comp_dir;
9250       dwo_file->sections.abbrev = sections.abbrev;
9251       dwo_file->sections.line = sections.line;
9252       dwo_file->sections.loc = sections.loc;
9253       dwo_file->sections.macinfo = sections.macinfo;
9254       dwo_file->sections.macro = sections.macro;
9255       dwo_file->sections.str_offsets = sections.str_offsets;
9256       /* The "str" section is global to the entire DWP file.  */
9257       dwo_file->sections.str = dwp_file->sections.str;
9258       /* The info or types section is assigned later to dwo_unit,
9259          there's no need to record it in dwo_file.
9260          Also, we can't simply record type sections in dwo_file because
9261          we record a pointer into the vector in dwo_unit.  As we collect more
9262          types we'll grow the vector and eventually have to reallocate space
9263          for it, invalidating all the pointers into the current copy.  */
9264       *dwo_file_slot = dwo_file;
9265     }
9266   else
9267     {
9268       if (dwarf2_read_debug)
9269         {
9270           fprintf_unfiltered (gdb_stdlog, "Using existing virtual DWO: %s\n",
9271                               virtual_dwo_name);
9272         }
9273       dwo_file = *dwo_file_slot;
9274     }
9275   do_cleanups (cleanups);
9276
9277   dwo_unit = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_unit);
9278   dwo_unit->dwo_file = dwo_file;
9279   dwo_unit->signature = signature;
9280   dwo_unit->section = obstack_alloc (&objfile->objfile_obstack,
9281                                      sizeof (struct dwarf2_section_info));
9282   *dwo_unit->section = sections.info_or_types;
9283   /* offset, length, type_offset_in_tu are set later.  */
9284
9285   return dwo_unit;
9286 }
9287
9288 /* Lookup the DWO with SIGNATURE in DWP_FILE.  */
9289
9290 static struct dwo_unit *
9291 lookup_dwo_in_dwp (struct dwp_file *dwp_file,
9292                    const struct dwp_hash_table *htab,
9293                    const char *comp_dir,
9294                    ULONGEST signature, int is_debug_types)
9295 {
9296   bfd *dbfd = dwp_file->dbfd;
9297   uint32_t mask = htab->nr_slots - 1;
9298   uint32_t hash = signature & mask;
9299   uint32_t hash2 = ((signature >> 32) & mask) | 1;
9300   unsigned int i;
9301   void **slot;
9302   struct dwo_unit find_dwo_cu, *dwo_cu;
9303
9304   memset (&find_dwo_cu, 0, sizeof (find_dwo_cu));
9305   find_dwo_cu.signature = signature;
9306   slot = htab_find_slot (dwp_file->loaded_cutus, &find_dwo_cu, INSERT);
9307
9308   if (*slot != NULL)
9309     return *slot;
9310
9311   /* Use a for loop so that we don't loop forever on bad debug info.  */
9312   for (i = 0; i < htab->nr_slots; ++i)
9313     {
9314       ULONGEST signature_in_table;
9315
9316       signature_in_table =
9317         read_8_bytes (dbfd, htab->hash_table + hash * sizeof (uint64_t));
9318       if (signature_in_table == signature)
9319         {
9320           uint32_t section_index =
9321             read_4_bytes (dbfd, htab->unit_table + hash * sizeof (uint32_t));
9322
9323           *slot = create_dwo_in_dwp (dwp_file, htab, section_index,
9324                                      comp_dir, signature, is_debug_types);
9325           return *slot;
9326         }
9327       if (signature_in_table == 0)
9328         return NULL;
9329       hash = (hash + hash2) & mask;
9330     }
9331
9332   error (_("Dwarf Error: bad DWP hash table, lookup didn't terminate"
9333            " [in module %s]"),
9334          dwp_file->name);
9335 }
9336
9337 /* Subroutine of open_dwo_file,open_dwp_file to simplify them.
9338    Open the file specified by FILE_NAME and hand it off to BFD for
9339    preliminary analysis.  Return a newly initialized bfd *, which
9340    includes a canonicalized copy of FILE_NAME.
9341    If IS_DWP is TRUE, we're opening a DWP file, otherwise a DWO file.
9342    SEARCH_CWD is true if the current directory is to be searched.
9343    It will be searched before debug-file-directory.
9344    If unable to find/open the file, return NULL.
9345    NOTE: This function is derived from symfile_bfd_open.  */
9346
9347 static bfd *
9348 try_open_dwop_file (const char *file_name, int is_dwp, int search_cwd)
9349 {
9350   bfd *sym_bfd;
9351   int desc, flags;
9352   char *absolute_name;
9353   /* Blech.  OPF_TRY_CWD_FIRST also disables searching the path list if
9354      FILE_NAME contains a '/'.  So we can't use it.  Instead prepend "."
9355      to debug_file_directory.  */
9356   char *search_path;
9357   static const char dirname_separator_string[] = { DIRNAME_SEPARATOR, '\0' };
9358
9359   if (search_cwd)
9360     {
9361       if (*debug_file_directory != '\0')
9362         search_path = concat (".", dirname_separator_string,
9363                               debug_file_directory, NULL);
9364       else
9365         search_path = xstrdup (".");
9366     }
9367   else
9368     search_path = xstrdup (debug_file_directory);
9369
9370   flags = OPF_RETURN_REALPATH;
9371   if (is_dwp)
9372     flags |= OPF_SEARCH_IN_PATH;
9373   desc = openp (search_path, flags, file_name,
9374                 O_RDONLY | O_BINARY, &absolute_name);
9375   xfree (search_path);
9376   if (desc < 0)
9377     return NULL;
9378
9379   sym_bfd = gdb_bfd_open (absolute_name, gnutarget, desc);
9380   xfree (absolute_name);
9381   if (sym_bfd == NULL)
9382     return NULL;
9383   bfd_set_cacheable (sym_bfd, 1);
9384
9385   if (!bfd_check_format (sym_bfd, bfd_object))
9386     {
9387       gdb_bfd_unref (sym_bfd); /* This also closes desc.  */
9388       return NULL;
9389     }
9390
9391   return sym_bfd;
9392 }
9393
9394 /* Try to open DWO file FILE_NAME.
9395    COMP_DIR is the DW_AT_comp_dir attribute.
9396    The result is the bfd handle of the file.
9397    If there is a problem finding or opening the file, return NULL.
9398    Upon success, the canonicalized path of the file is stored in the bfd,
9399    same as symfile_bfd_open.  */
9400
9401 static bfd *
9402 open_dwo_file (const char *file_name, const char *comp_dir)
9403 {
9404   bfd *abfd;
9405
9406   if (IS_ABSOLUTE_PATH (file_name))
9407     return try_open_dwop_file (file_name, 0 /*is_dwp*/, 0 /*search_cwd*/);
9408
9409   /* Before trying the search path, try DWO_NAME in COMP_DIR.  */
9410
9411   if (comp_dir != NULL)
9412     {
9413       char *path_to_try = concat (comp_dir, SLASH_STRING, file_name, NULL);
9414
9415       /* NOTE: If comp_dir is a relative path, this will also try the
9416          search path, which seems useful.  */
9417       abfd = try_open_dwop_file (path_to_try, 0 /*is_dwp*/, 1 /*search_cwd*/);
9418       xfree (path_to_try);
9419       if (abfd != NULL)
9420         return abfd;
9421     }
9422
9423   /* That didn't work, try debug-file-directory, which, despite its name,
9424      is a list of paths.  */
9425
9426   if (*debug_file_directory == '\0')
9427     return NULL;
9428
9429   return try_open_dwop_file (file_name, 0 /*is_dwp*/, 1 /*search_cwd*/);
9430 }
9431
9432 /* This function is mapped across the sections and remembers the offset and
9433    size of each of the DWO debugging sections we are interested in.  */
9434
9435 static void
9436 dwarf2_locate_dwo_sections (bfd *abfd, asection *sectp, void *dwo_sections_ptr)
9437 {
9438   struct dwo_sections *dwo_sections = dwo_sections_ptr;
9439   const struct dwop_section_names *names = &dwop_section_names;
9440
9441   if (section_is_p (sectp->name, &names->abbrev_dwo))
9442     {
9443       dwo_sections->abbrev.asection = sectp;
9444       dwo_sections->abbrev.size = bfd_get_section_size (sectp);
9445     }
9446   else if (section_is_p (sectp->name, &names->info_dwo))
9447     {
9448       dwo_sections->info.asection = sectp;
9449       dwo_sections->info.size = bfd_get_section_size (sectp);
9450     }
9451   else if (section_is_p (sectp->name, &names->line_dwo))
9452     {
9453       dwo_sections->line.asection = sectp;
9454       dwo_sections->line.size = bfd_get_section_size (sectp);
9455     }
9456   else if (section_is_p (sectp->name, &names->loc_dwo))
9457     {
9458       dwo_sections->loc.asection = sectp;
9459       dwo_sections->loc.size = bfd_get_section_size (sectp);
9460     }
9461   else if (section_is_p (sectp->name, &names->macinfo_dwo))
9462     {
9463       dwo_sections->macinfo.asection = sectp;
9464       dwo_sections->macinfo.size = bfd_get_section_size (sectp);
9465     }
9466   else if (section_is_p (sectp->name, &names->macro_dwo))
9467     {
9468       dwo_sections->macro.asection = sectp;
9469       dwo_sections->macro.size = bfd_get_section_size (sectp);
9470     }
9471   else if (section_is_p (sectp->name, &names->str_dwo))
9472     {
9473       dwo_sections->str.asection = sectp;
9474       dwo_sections->str.size = bfd_get_section_size (sectp);
9475     }
9476   else if (section_is_p (sectp->name, &names->str_offsets_dwo))
9477     {
9478       dwo_sections->str_offsets.asection = sectp;
9479       dwo_sections->str_offsets.size = bfd_get_section_size (sectp);
9480     }
9481   else if (section_is_p (sectp->name, &names->types_dwo))
9482     {
9483       struct dwarf2_section_info type_section;
9484
9485       memset (&type_section, 0, sizeof (type_section));
9486       type_section.asection = sectp;
9487       type_section.size = bfd_get_section_size (sectp);
9488       VEC_safe_push (dwarf2_section_info_def, dwo_sections->types,
9489                      &type_section);
9490     }
9491 }
9492
9493 /* Initialize the use of the DWO file specified by DWO_NAME and referenced
9494    by PER_CU.  This is for the non-DWP case.
9495    The result is NULL if DWO_NAME can't be found.  */
9496
9497 static struct dwo_file *
9498 open_and_init_dwo_file (struct dwarf2_per_cu_data *per_cu,
9499                         const char *dwo_name, const char *comp_dir)
9500 {
9501   struct objfile *objfile = dwarf2_per_objfile->objfile;
9502   struct dwo_file *dwo_file;
9503   bfd *dbfd;
9504   struct cleanup *cleanups;
9505
9506   dbfd = open_dwo_file (dwo_name, comp_dir);
9507   if (dbfd == NULL)
9508     {
9509       if (dwarf2_read_debug)
9510         fprintf_unfiltered (gdb_stdlog, "DWO file not found: %s\n", dwo_name);
9511       return NULL;
9512     }
9513   dwo_file = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_file);
9514   dwo_file->dwo_name = dwo_name;
9515   dwo_file->comp_dir = comp_dir;
9516   dwo_file->dbfd = dbfd;
9517
9518   cleanups = make_cleanup (free_dwo_file_cleanup, dwo_file);
9519
9520   bfd_map_over_sections (dbfd, dwarf2_locate_dwo_sections, &dwo_file->sections);
9521
9522   dwo_file->cu = create_dwo_cu (dwo_file);
9523
9524   dwo_file->tus = create_debug_types_hash_table (dwo_file,
9525                                                  dwo_file->sections.types);
9526
9527   discard_cleanups (cleanups);
9528
9529   if (dwarf2_read_debug)
9530     fprintf_unfiltered (gdb_stdlog, "DWO file found: %s\n", dwo_name);
9531
9532   return dwo_file;
9533 }
9534
9535 /* This function is mapped across the sections and remembers the offset and
9536    size of each of the DWP debugging sections we are interested in.  */
9537
9538 static void
9539 dwarf2_locate_dwp_sections (bfd *abfd, asection *sectp, void *dwp_file_ptr)
9540 {
9541   struct dwp_file *dwp_file = dwp_file_ptr;
9542   const struct dwop_section_names *names = &dwop_section_names;
9543   unsigned int elf_section_nr = elf_section_data (sectp)->this_idx;
9544
9545   /* Record the ELF section number for later lookup: this is what the
9546      .debug_cu_index,.debug_tu_index tables use.  */
9547   gdb_assert (elf_section_nr < dwp_file->num_sections);
9548   dwp_file->elf_sections[elf_section_nr] = sectp;
9549
9550   /* Look for specific sections that we need.  */
9551   if (section_is_p (sectp->name, &names->str_dwo))
9552     {
9553       dwp_file->sections.str.asection = sectp;
9554       dwp_file->sections.str.size = bfd_get_section_size (sectp);
9555     }
9556   else if (section_is_p (sectp->name, &names->cu_index))
9557     {
9558       dwp_file->sections.cu_index.asection = sectp;
9559       dwp_file->sections.cu_index.size = bfd_get_section_size (sectp);
9560     }
9561   else if (section_is_p (sectp->name, &names->tu_index))
9562     {
9563       dwp_file->sections.tu_index.asection = sectp;
9564       dwp_file->sections.tu_index.size = bfd_get_section_size (sectp);
9565     }
9566 }
9567
9568 /* Hash function for dwp_file loaded CUs/TUs.  */
9569
9570 static hashval_t
9571 hash_dwp_loaded_cutus (const void *item)
9572 {
9573   const struct dwo_unit *dwo_unit = item;
9574
9575   /* This drops the top 32 bits of the signature, but is ok for a hash.  */
9576   return dwo_unit->signature;
9577 }
9578
9579 /* Equality function for dwp_file loaded CUs/TUs.  */
9580
9581 static int
9582 eq_dwp_loaded_cutus (const void *a, const void *b)
9583 {
9584   const struct dwo_unit *dua = a;
9585   const struct dwo_unit *dub = b;
9586
9587   return dua->signature == dub->signature;
9588 }
9589
9590 /* Allocate a hash table for dwp_file loaded CUs/TUs.  */
9591
9592 static htab_t
9593 allocate_dwp_loaded_cutus_table (struct objfile *objfile)
9594 {
9595   return htab_create_alloc_ex (3,
9596                                hash_dwp_loaded_cutus,
9597                                eq_dwp_loaded_cutus,
9598                                NULL,
9599                                &objfile->objfile_obstack,
9600                                hashtab_obstack_allocate,
9601                                dummy_obstack_deallocate);
9602 }
9603
9604 /* Try to open DWP file FILE_NAME.
9605    The result is the bfd handle of the file.
9606    If there is a problem finding or opening the file, return NULL.
9607    Upon success, the canonicalized path of the file is stored in the bfd,
9608    same as symfile_bfd_open.  */
9609
9610 static bfd *
9611 open_dwp_file (const char *file_name)
9612 {
9613   bfd *abfd;
9614
9615   abfd = try_open_dwop_file (file_name, 1 /*is_dwp*/, 1 /*search_cwd*/);
9616   if (abfd != NULL)
9617     return abfd;
9618
9619   /* Work around upstream bug 15652.
9620      http://sourceware.org/bugzilla/show_bug.cgi?id=15652
9621      [Whether that's a "bug" is debatable, but it is getting in our way.]
9622      We have no real idea where the dwp file is, because gdb's realpath-ing
9623      of the executable's path may have discarded the needed info.
9624      [IWBN if the dwp file name was recorded in the executable, akin to
9625      .gnu_debuglink, but that doesn't exist yet.]
9626      Strip the directory from FILE_NAME and search again.  */
9627   if (*debug_file_directory != '\0')
9628     {
9629       /* Don't implicitly search the current directory here.
9630          If the user wants to search "." to handle this case,
9631          it must be added to debug-file-directory.  */
9632       return try_open_dwop_file (lbasename (file_name), 1 /*is_dwp*/,
9633                                  0 /*search_cwd*/);
9634     }
9635
9636   return NULL;
9637 }
9638
9639 /* Initialize the use of the DWP file for the current objfile.
9640    By convention the name of the DWP file is ${objfile}.dwp.
9641    The result is NULL if it can't be found.  */
9642
9643 static struct dwp_file *
9644 open_and_init_dwp_file (void)
9645 {
9646   struct objfile *objfile = dwarf2_per_objfile->objfile;
9647   struct dwp_file *dwp_file;
9648   char *dwp_name;
9649   bfd *dbfd;
9650   struct cleanup *cleanups;
9651
9652   /* Try to find first .dwp for the binary file before any symbolic links
9653      resolving.  */
9654   dwp_name = xstrprintf ("%s.dwp", objfile->original_name);
9655   cleanups = make_cleanup (xfree, dwp_name);
9656
9657   dbfd = open_dwp_file (dwp_name);
9658   if (dbfd == NULL
9659       && strcmp (objfile->original_name, objfile_name (objfile)) != 0)
9660     {
9661       /* Try to find .dwp for the binary file after gdb_realpath resolving.  */
9662       dwp_name = xstrprintf ("%s.dwp", objfile_name (objfile));
9663       make_cleanup (xfree, dwp_name);
9664       dbfd = open_dwp_file (dwp_name);
9665     }
9666
9667   if (dbfd == NULL)
9668     {
9669       if (dwarf2_read_debug)
9670         fprintf_unfiltered (gdb_stdlog, "DWP file not found: %s\n", dwp_name);
9671       do_cleanups (cleanups);
9672       return NULL;
9673     }
9674   dwp_file = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwp_file);
9675   dwp_file->name = bfd_get_filename (dbfd);
9676   dwp_file->dbfd = dbfd;
9677   do_cleanups (cleanups);
9678
9679   /* +1: section 0 is unused */
9680   dwp_file->num_sections = bfd_count_sections (dbfd) + 1;
9681   dwp_file->elf_sections =
9682     OBSTACK_CALLOC (&objfile->objfile_obstack,
9683                     dwp_file->num_sections, asection *);
9684
9685   bfd_map_over_sections (dbfd, dwarf2_locate_dwp_sections, dwp_file);
9686
9687   dwp_file->cus = create_dwp_hash_table (dwp_file, 0);
9688
9689   dwp_file->tus = create_dwp_hash_table (dwp_file, 1);
9690
9691   dwp_file->loaded_cutus = allocate_dwp_loaded_cutus_table (objfile);
9692
9693   if (dwarf2_read_debug)
9694     {
9695       fprintf_unfiltered (gdb_stdlog, "DWP file found: %s\n", dwp_file->name);
9696       fprintf_unfiltered (gdb_stdlog,
9697                           "    %s CUs, %s TUs\n",
9698                           pulongest (dwp_file->cus ? dwp_file->cus->nr_units : 0),
9699                           pulongest (dwp_file->tus ? dwp_file->tus->nr_units : 0));
9700     }
9701
9702   return dwp_file;
9703 }
9704
9705 /* Wrapper around open_and_init_dwp_file, only open it once.  */
9706
9707 static struct dwp_file *
9708 get_dwp_file (void)
9709 {
9710   if (! dwarf2_per_objfile->dwp_checked)
9711     {
9712       dwarf2_per_objfile->dwp_file = open_and_init_dwp_file ();
9713       dwarf2_per_objfile->dwp_checked = 1;
9714     }
9715   return dwarf2_per_objfile->dwp_file;
9716 }
9717
9718 /* Subroutine of lookup_dwo_comp_unit, lookup_dwo_type_unit.
9719    Look up the CU/TU with signature SIGNATURE, either in DWO file DWO_NAME
9720    or in the DWP file for the objfile, referenced by THIS_UNIT.
9721    If non-NULL, comp_dir is the DW_AT_comp_dir attribute.
9722    IS_DEBUG_TYPES is non-zero if reading a TU, otherwise read a CU.
9723
9724    This is called, for example, when wanting to read a variable with a
9725    complex location.  Therefore we don't want to do file i/o for every call.
9726    Therefore we don't want to look for a DWO file on every call.
9727    Therefore we first see if we've already seen SIGNATURE in a DWP file,
9728    then we check if we've already seen DWO_NAME, and only THEN do we check
9729    for a DWO file.
9730
9731    The result is a pointer to the dwo_unit object or NULL if we didn't find it
9732    (dwo_id mismatch or couldn't find the DWO/DWP file).  */
9733
9734 static struct dwo_unit *
9735 lookup_dwo_cutu (struct dwarf2_per_cu_data *this_unit,
9736                  const char *dwo_name, const char *comp_dir,
9737                  ULONGEST signature, int is_debug_types)
9738 {
9739   struct objfile *objfile = dwarf2_per_objfile->objfile;
9740   const char *kind = is_debug_types ? "TU" : "CU";
9741   void **dwo_file_slot;
9742   struct dwo_file *dwo_file;
9743   struct dwp_file *dwp_file;
9744
9745   /* First see if there's a DWP file.
9746      If we have a DWP file but didn't find the DWO inside it, don't
9747      look for the original DWO file.  It makes gdb behave differently
9748      depending on whether one is debugging in the build tree.  */
9749
9750   dwp_file = get_dwp_file ();
9751   if (dwp_file != NULL)
9752     {
9753       const struct dwp_hash_table *dwp_htab =
9754         is_debug_types ? dwp_file->tus : dwp_file->cus;
9755
9756       if (dwp_htab != NULL)
9757         {
9758           struct dwo_unit *dwo_cutu =
9759             lookup_dwo_in_dwp (dwp_file, dwp_htab, comp_dir,
9760                                signature, is_debug_types);
9761
9762           if (dwo_cutu != NULL)
9763             {
9764               if (dwarf2_read_debug)
9765                 {
9766                   fprintf_unfiltered (gdb_stdlog,
9767                                       "Virtual DWO %s %s found: @%s\n",
9768                                       kind, hex_string (signature),
9769                                       host_address_to_string (dwo_cutu));
9770                 }
9771               return dwo_cutu;
9772             }
9773         }
9774     }
9775   else
9776     {
9777       /* No DWP file, look for the DWO file.  */
9778
9779       dwo_file_slot = lookup_dwo_file_slot (dwo_name, comp_dir);
9780       if (*dwo_file_slot == NULL)
9781         {
9782           /* Read in the file and build a table of the CUs/TUs it contains.  */
9783           *dwo_file_slot = open_and_init_dwo_file (this_unit, dwo_name, comp_dir);
9784         }
9785       /* NOTE: This will be NULL if unable to open the file.  */
9786       dwo_file = *dwo_file_slot;
9787
9788       if (dwo_file != NULL)
9789         {
9790           struct dwo_unit *dwo_cutu = NULL;
9791
9792           if (is_debug_types && dwo_file->tus)
9793             {
9794               struct dwo_unit find_dwo_cutu;
9795
9796               memset (&find_dwo_cutu, 0, sizeof (find_dwo_cutu));
9797               find_dwo_cutu.signature = signature;
9798               dwo_cutu = htab_find (dwo_file->tus, &find_dwo_cutu);
9799             }
9800           else if (!is_debug_types && dwo_file->cu)
9801             {
9802               if (signature == dwo_file->cu->signature)
9803                 dwo_cutu = dwo_file->cu;
9804             }
9805
9806           if (dwo_cutu != NULL)
9807             {
9808               if (dwarf2_read_debug)
9809                 {
9810                   fprintf_unfiltered (gdb_stdlog, "DWO %s %s(%s) found: @%s\n",
9811                                       kind, dwo_name, hex_string (signature),
9812                                       host_address_to_string (dwo_cutu));
9813                 }
9814               return dwo_cutu;
9815             }
9816         }
9817     }
9818
9819   /* We didn't find it.  This could mean a dwo_id mismatch, or
9820      someone deleted the DWO/DWP file, or the search path isn't set up
9821      correctly to find the file.  */
9822
9823   if (dwarf2_read_debug)
9824     {
9825       fprintf_unfiltered (gdb_stdlog, "DWO %s %s(%s) not found\n",
9826                           kind, dwo_name, hex_string (signature));
9827     }
9828
9829   /* This is a warning and not a complaint because it can be caused by
9830      pilot error (e.g., user accidentally deleting the DWO).  */
9831   warning (_("Could not find DWO %s %s(%s) referenced by %s at offset 0x%x"
9832              " [in module %s]"),
9833            kind, dwo_name, hex_string (signature),
9834            this_unit->is_debug_types ? "TU" : "CU",
9835            this_unit->offset.sect_off, objfile_name (objfile));
9836   return NULL;
9837 }
9838
9839 /* Lookup the DWO CU DWO_NAME/SIGNATURE referenced from THIS_CU.
9840    See lookup_dwo_cutu_unit for details.  */
9841
9842 static struct dwo_unit *
9843 lookup_dwo_comp_unit (struct dwarf2_per_cu_data *this_cu,
9844                       const char *dwo_name, const char *comp_dir,
9845                       ULONGEST signature)
9846 {
9847   return lookup_dwo_cutu (this_cu, dwo_name, comp_dir, signature, 0);
9848 }
9849
9850 /* Lookup the DWO TU DWO_NAME/SIGNATURE referenced from THIS_TU.
9851    See lookup_dwo_cutu_unit for details.  */
9852
9853 static struct dwo_unit *
9854 lookup_dwo_type_unit (struct signatured_type *this_tu,
9855                       const char *dwo_name, const char *comp_dir)
9856 {
9857   return lookup_dwo_cutu (&this_tu->per_cu, dwo_name, comp_dir, this_tu->signature, 1);
9858 }
9859
9860 /* Traversal function for queue_and_load_all_dwo_tus.  */
9861
9862 static int
9863 queue_and_load_dwo_tu (void **slot, void *info)
9864 {
9865   struct dwo_unit *dwo_unit = (struct dwo_unit *) *slot;
9866   struct dwarf2_per_cu_data *per_cu = (struct dwarf2_per_cu_data *) info;
9867   ULONGEST signature = dwo_unit->signature;
9868   struct signatured_type *sig_type =
9869     lookup_dwo_signatured_type (per_cu->cu, signature);
9870
9871   if (sig_type != NULL)
9872     {
9873       struct dwarf2_per_cu_data *sig_cu = &sig_type->per_cu;
9874
9875       /* We pass NULL for DEPENDENT_CU because we don't yet know if there's
9876          a real dependency of PER_CU on SIG_TYPE.  That is detected later
9877          while processing PER_CU.  */
9878       if (maybe_queue_comp_unit (NULL, sig_cu, per_cu->cu->language))
9879         load_full_type_unit (sig_cu);
9880       VEC_safe_push (dwarf2_per_cu_ptr, per_cu->imported_symtabs, sig_cu);
9881     }
9882
9883   return 1;
9884 }
9885
9886 /* Queue all TUs contained in the DWO of PER_CU to be read in.
9887    The DWO may have the only definition of the type, though it may not be
9888    referenced anywhere in PER_CU.  Thus we have to load *all* its TUs.
9889    http://sourceware.org/bugzilla/show_bug.cgi?id=15021  */
9890
9891 static void
9892 queue_and_load_all_dwo_tus (struct dwarf2_per_cu_data *per_cu)
9893 {
9894   struct dwo_unit *dwo_unit;
9895   struct dwo_file *dwo_file;
9896
9897   gdb_assert (!per_cu->is_debug_types);
9898   gdb_assert (get_dwp_file () == NULL);
9899   gdb_assert (per_cu->cu != NULL);
9900
9901   dwo_unit = per_cu->cu->dwo_unit;
9902   gdb_assert (dwo_unit != NULL);
9903
9904   dwo_file = dwo_unit->dwo_file;
9905   if (dwo_file->tus != NULL)
9906     htab_traverse_noresize (dwo_file->tus, queue_and_load_dwo_tu, per_cu);
9907 }
9908
9909 /* Free all resources associated with DWO_FILE.
9910    Close the DWO file and munmap the sections.
9911    All memory should be on the objfile obstack.  */
9912
9913 static void
9914 free_dwo_file (struct dwo_file *dwo_file, struct objfile *objfile)
9915 {
9916   int ix;
9917   struct dwarf2_section_info *section;
9918
9919   /* Note: dbfd is NULL for virtual DWO files.  */
9920   gdb_bfd_unref (dwo_file->dbfd);
9921
9922   VEC_free (dwarf2_section_info_def, dwo_file->sections.types);
9923 }
9924
9925 /* Wrapper for free_dwo_file for use in cleanups.  */
9926
9927 static void
9928 free_dwo_file_cleanup (void *arg)
9929 {
9930   struct dwo_file *dwo_file = (struct dwo_file *) arg;
9931   struct objfile *objfile = dwarf2_per_objfile->objfile;
9932
9933   free_dwo_file (dwo_file, objfile);
9934 }
9935
9936 /* Traversal function for free_dwo_files.  */
9937
9938 static int
9939 free_dwo_file_from_slot (void **slot, void *info)
9940 {
9941   struct dwo_file *dwo_file = (struct dwo_file *) *slot;
9942   struct objfile *objfile = (struct objfile *) info;
9943
9944   free_dwo_file (dwo_file, objfile);
9945
9946   return 1;
9947 }
9948
9949 /* Free all resources associated with DWO_FILES.  */
9950
9951 static void
9952 free_dwo_files (htab_t dwo_files, struct objfile *objfile)
9953 {
9954   htab_traverse_noresize (dwo_files, free_dwo_file_from_slot, objfile);
9955 }
9956 \f
9957 /* Read in various DIEs.  */
9958
9959 /* qsort helper for inherit_abstract_dies.  */
9960
9961 static int
9962 unsigned_int_compar (const void *ap, const void *bp)
9963 {
9964   unsigned int a = *(unsigned int *) ap;
9965   unsigned int b = *(unsigned int *) bp;
9966
9967   return (a > b) - (b > a);
9968 }
9969
9970 /* DW_AT_abstract_origin inherits whole DIEs (not just their attributes).
9971    Inherit only the children of the DW_AT_abstract_origin DIE not being
9972    already referenced by DW_AT_abstract_origin from the children of the
9973    current DIE.  */
9974
9975 static void
9976 inherit_abstract_dies (struct die_info *die, struct dwarf2_cu *cu)
9977 {
9978   struct die_info *child_die;
9979   unsigned die_children_count;
9980   /* CU offsets which were referenced by children of the current DIE.  */
9981   sect_offset *offsets;
9982   sect_offset *offsets_end, *offsetp;
9983   /* Parent of DIE - referenced by DW_AT_abstract_origin.  */
9984   struct die_info *origin_die;
9985   /* Iterator of the ORIGIN_DIE children.  */
9986   struct die_info *origin_child_die;
9987   struct cleanup *cleanups;
9988   struct attribute *attr;
9989   struct dwarf2_cu *origin_cu;
9990   struct pending **origin_previous_list_in_scope;
9991
9992   attr = dwarf2_attr (die, DW_AT_abstract_origin, cu);
9993   if (!attr)
9994     return;
9995
9996   /* Note that following die references may follow to a die in a
9997      different cu.  */
9998
9999   origin_cu = cu;
10000   origin_die = follow_die_ref (die, attr, &origin_cu);
10001
10002   /* We're inheriting ORIGIN's children into the scope we'd put DIE's
10003      symbols in.  */
10004   origin_previous_list_in_scope = origin_cu->list_in_scope;
10005   origin_cu->list_in_scope = cu->list_in_scope;
10006
10007   if (die->tag != origin_die->tag
10008       && !(die->tag == DW_TAG_inlined_subroutine
10009            && origin_die->tag == DW_TAG_subprogram))
10010     complaint (&symfile_complaints,
10011                _("DIE 0x%x and its abstract origin 0x%x have different tags"),
10012                die->offset.sect_off, origin_die->offset.sect_off);
10013
10014   child_die = die->child;
10015   die_children_count = 0;
10016   while (child_die && child_die->tag)
10017     {
10018       child_die = sibling_die (child_die);
10019       die_children_count++;
10020     }
10021   offsets = xmalloc (sizeof (*offsets) * die_children_count);
10022   cleanups = make_cleanup (xfree, offsets);
10023
10024   offsets_end = offsets;
10025   child_die = die->child;
10026   while (child_die && child_die->tag)
10027     {
10028       /* For each CHILD_DIE, find the corresponding child of
10029          ORIGIN_DIE.  If there is more than one layer of
10030          DW_AT_abstract_origin, follow them all; there shouldn't be,
10031          but GCC versions at least through 4.4 generate this (GCC PR
10032          40573).  */
10033       struct die_info *child_origin_die = child_die;
10034       struct dwarf2_cu *child_origin_cu = cu;
10035
10036       while (1)
10037         {
10038           attr = dwarf2_attr (child_origin_die, DW_AT_abstract_origin,
10039                               child_origin_cu);
10040           if (attr == NULL)
10041             break;
10042           child_origin_die = follow_die_ref (child_origin_die, attr,
10043                                              &child_origin_cu);
10044         }
10045
10046       /* According to DWARF3 3.3.8.2 #3 new entries without their abstract
10047          counterpart may exist.  */
10048       if (child_origin_die != child_die)
10049         {
10050           if (child_die->tag != child_origin_die->tag
10051               && !(child_die->tag == DW_TAG_inlined_subroutine
10052                    && child_origin_die->tag == DW_TAG_subprogram))
10053             complaint (&symfile_complaints,
10054                        _("Child DIE 0x%x and its abstract origin 0x%x have "
10055                          "different tags"), child_die->offset.sect_off,
10056                        child_origin_die->offset.sect_off);
10057           if (child_origin_die->parent != origin_die)
10058             complaint (&symfile_complaints,
10059                        _("Child DIE 0x%x and its abstract origin 0x%x have "
10060                          "different parents"), child_die->offset.sect_off,
10061                        child_origin_die->offset.sect_off);
10062           else
10063             *offsets_end++ = child_origin_die->offset;
10064         }
10065       child_die = sibling_die (child_die);
10066     }
10067   qsort (offsets, offsets_end - offsets, sizeof (*offsets),
10068          unsigned_int_compar);
10069   for (offsetp = offsets + 1; offsetp < offsets_end; offsetp++)
10070     if (offsetp[-1].sect_off == offsetp->sect_off)
10071       complaint (&symfile_complaints,
10072                  _("Multiple children of DIE 0x%x refer "
10073                    "to DIE 0x%x as their abstract origin"),
10074                  die->offset.sect_off, offsetp->sect_off);
10075
10076   offsetp = offsets;
10077   origin_child_die = origin_die->child;
10078   while (origin_child_die && origin_child_die->tag)
10079     {
10080       /* Is ORIGIN_CHILD_DIE referenced by any of the DIE children?  */
10081       while (offsetp < offsets_end
10082              && offsetp->sect_off < origin_child_die->offset.sect_off)
10083         offsetp++;
10084       if (offsetp >= offsets_end
10085           || offsetp->sect_off > origin_child_die->offset.sect_off)
10086         {
10087           /* Found that ORIGIN_CHILD_DIE is really not referenced.  */
10088           process_die (origin_child_die, origin_cu);
10089         }
10090       origin_child_die = sibling_die (origin_child_die);
10091     }
10092   origin_cu->list_in_scope = origin_previous_list_in_scope;
10093
10094   do_cleanups (cleanups);
10095 }
10096
10097 static void
10098 read_func_scope (struct die_info *die, struct dwarf2_cu *cu)
10099 {
10100   struct objfile *objfile = cu->objfile;
10101   struct context_stack *new;
10102   CORE_ADDR lowpc;
10103   CORE_ADDR highpc;
10104   struct die_info *child_die;
10105   struct attribute *attr, *call_line, *call_file;
10106   const char *name;
10107   CORE_ADDR baseaddr;
10108   struct block *block;
10109   int inlined_func = (die->tag == DW_TAG_inlined_subroutine);
10110   VEC (symbolp) *template_args = NULL;
10111   struct template_symbol *templ_func = NULL;
10112
10113   if (inlined_func)
10114     {
10115       /* If we do not have call site information, we can't show the
10116          caller of this inlined function.  That's too confusing, so
10117          only use the scope for local variables.  */
10118       call_line = dwarf2_attr (die, DW_AT_call_line, cu);
10119       call_file = dwarf2_attr (die, DW_AT_call_file, cu);
10120       if (call_line == NULL || call_file == NULL)
10121         {
10122           read_lexical_block_scope (die, cu);
10123           return;
10124         }
10125     }
10126
10127   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
10128
10129   name = dwarf2_name (die, cu);
10130
10131   /* Ignore functions with missing or empty names.  These are actually
10132      illegal according to the DWARF standard.  */
10133   if (name == NULL)
10134     {
10135       complaint (&symfile_complaints,
10136                  _("missing name for subprogram DIE at %d"),
10137                  die->offset.sect_off);
10138       return;
10139     }
10140
10141   /* Ignore functions with missing or invalid low and high pc attributes.  */
10142   if (!dwarf2_get_pc_bounds (die, &lowpc, &highpc, cu, NULL))
10143     {
10144       attr = dwarf2_attr (die, DW_AT_external, cu);
10145       if (!attr || !DW_UNSND (attr))
10146         complaint (&symfile_complaints,
10147                    _("cannot get low and high bounds "
10148                      "for subprogram DIE at %d"),
10149                    die->offset.sect_off);
10150       return;
10151     }
10152
10153   lowpc += baseaddr;
10154   highpc += baseaddr;
10155
10156   /* If we have any template arguments, then we must allocate a
10157      different sort of symbol.  */
10158   for (child_die = die->child; child_die; child_die = sibling_die (child_die))
10159     {
10160       if (child_die->tag == DW_TAG_template_type_param
10161           || child_die->tag == DW_TAG_template_value_param)
10162         {
10163           templ_func = allocate_template_symbol (objfile);
10164           templ_func->base.is_cplus_template_function = 1;
10165           break;
10166         }
10167     }
10168
10169   new = push_context (0, lowpc);
10170   new->name = new_symbol_full (die, read_type_die (die, cu), cu,
10171                                (struct symbol *) templ_func);
10172
10173   /* If there is a location expression for DW_AT_frame_base, record
10174      it.  */
10175   attr = dwarf2_attr (die, DW_AT_frame_base, cu);
10176   if (attr)
10177     dwarf2_symbol_mark_computed (attr, new->name, cu, 1);
10178
10179   cu->list_in_scope = &local_symbols;
10180
10181   if (die->child != NULL)
10182     {
10183       child_die = die->child;
10184       while (child_die && child_die->tag)
10185         {
10186           if (child_die->tag == DW_TAG_template_type_param
10187               || child_die->tag == DW_TAG_template_value_param)
10188             {
10189               struct symbol *arg = new_symbol (child_die, NULL, cu);
10190
10191               if (arg != NULL)
10192                 VEC_safe_push (symbolp, template_args, arg);
10193             }
10194           else
10195             process_die (child_die, cu);
10196           child_die = sibling_die (child_die);
10197         }
10198     }
10199
10200   inherit_abstract_dies (die, cu);
10201
10202   /* If we have a DW_AT_specification, we might need to import using
10203      directives from the context of the specification DIE.  See the
10204      comment in determine_prefix.  */
10205   if (cu->language == language_cplus
10206       && dwarf2_attr (die, DW_AT_specification, cu))
10207     {
10208       struct dwarf2_cu *spec_cu = cu;
10209       struct die_info *spec_die = die_specification (die, &spec_cu);
10210
10211       while (spec_die)
10212         {
10213           child_die = spec_die->child;
10214           while (child_die && child_die->tag)
10215             {
10216               if (child_die->tag == DW_TAG_imported_module)
10217                 process_die (child_die, spec_cu);
10218               child_die = sibling_die (child_die);
10219             }
10220
10221           /* In some cases, GCC generates specification DIEs that
10222              themselves contain DW_AT_specification attributes.  */
10223           spec_die = die_specification (spec_die, &spec_cu);
10224         }
10225     }
10226
10227   new = pop_context ();
10228   /* Make a block for the local symbols within.  */
10229   block = finish_block (new->name, &local_symbols, new->old_blocks,
10230                         lowpc, highpc, objfile);
10231
10232   /* For C++, set the block's scope.  */
10233   if ((cu->language == language_cplus || cu->language == language_fortran)
10234       && cu->processing_has_namespace_info)
10235     block_set_scope (block, determine_prefix (die, cu),
10236                      &objfile->objfile_obstack);
10237
10238   /* If we have address ranges, record them.  */
10239   dwarf2_record_block_ranges (die, block, baseaddr, cu);
10240
10241   /* Attach template arguments to function.  */
10242   if (! VEC_empty (symbolp, template_args))
10243     {
10244       gdb_assert (templ_func != NULL);
10245
10246       templ_func->n_template_arguments = VEC_length (symbolp, template_args);
10247       templ_func->template_arguments
10248         = obstack_alloc (&objfile->objfile_obstack,
10249                          (templ_func->n_template_arguments
10250                           * sizeof (struct symbol *)));
10251       memcpy (templ_func->template_arguments,
10252               VEC_address (symbolp, template_args),
10253               (templ_func->n_template_arguments * sizeof (struct symbol *)));
10254       VEC_free (symbolp, template_args);
10255     }
10256
10257   /* In C++, we can have functions nested inside functions (e.g., when
10258      a function declares a class that has methods).  This means that
10259      when we finish processing a function scope, we may need to go
10260      back to building a containing block's symbol lists.  */
10261   local_symbols = new->locals;
10262   using_directives = new->using_directives;
10263
10264   /* If we've finished processing a top-level function, subsequent
10265      symbols go in the file symbol list.  */
10266   if (outermost_context_p ())
10267     cu->list_in_scope = &file_symbols;
10268 }
10269
10270 /* Process all the DIES contained within a lexical block scope.  Start
10271    a new scope, process the dies, and then close the scope.  */
10272
10273 static void
10274 read_lexical_block_scope (struct die_info *die, struct dwarf2_cu *cu)
10275 {
10276   struct objfile *objfile = cu->objfile;
10277   struct context_stack *new;
10278   CORE_ADDR lowpc, highpc;
10279   struct die_info *child_die;
10280   CORE_ADDR baseaddr;
10281
10282   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
10283
10284   /* Ignore blocks with missing or invalid low and high pc attributes.  */
10285   /* ??? Perhaps consider discontiguous blocks defined by DW_AT_ranges
10286      as multiple lexical blocks?  Handling children in a sane way would
10287      be nasty.  Might be easier to properly extend generic blocks to
10288      describe ranges.  */
10289   if (!dwarf2_get_pc_bounds (die, &lowpc, &highpc, cu, NULL))
10290     return;
10291   lowpc += baseaddr;
10292   highpc += baseaddr;
10293
10294   push_context (0, lowpc);
10295   if (die->child != NULL)
10296     {
10297       child_die = die->child;
10298       while (child_die && child_die->tag)
10299         {
10300           process_die (child_die, cu);
10301           child_die = sibling_die (child_die);
10302         }
10303     }
10304   new = pop_context ();
10305
10306   if (local_symbols != NULL || using_directives != NULL)
10307     {
10308       struct block *block
10309         = finish_block (0, &local_symbols, new->old_blocks, new->start_addr,
10310                         highpc, objfile);
10311
10312       /* Note that recording ranges after traversing children, as we
10313          do here, means that recording a parent's ranges entails
10314          walking across all its children's ranges as they appear in
10315          the address map, which is quadratic behavior.
10316
10317          It would be nicer to record the parent's ranges before
10318          traversing its children, simply overriding whatever you find
10319          there.  But since we don't even decide whether to create a
10320          block until after we've traversed its children, that's hard
10321          to do.  */
10322       dwarf2_record_block_ranges (die, block, baseaddr, cu);
10323     }
10324   local_symbols = new->locals;
10325   using_directives = new->using_directives;
10326 }
10327
10328 /* Read in DW_TAG_GNU_call_site and insert it to CU->call_site_htab.  */
10329
10330 static void
10331 read_call_site_scope (struct die_info *die, struct dwarf2_cu *cu)
10332 {
10333   struct objfile *objfile = cu->objfile;
10334   struct gdbarch *gdbarch = get_objfile_arch (objfile);
10335   CORE_ADDR pc, baseaddr;
10336   struct attribute *attr;
10337   struct call_site *call_site, call_site_local;
10338   void **slot;
10339   int nparams;
10340   struct die_info *child_die;
10341
10342   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
10343
10344   attr = dwarf2_attr (die, DW_AT_low_pc, cu);
10345   if (!attr)
10346     {
10347       complaint (&symfile_complaints,
10348                  _("missing DW_AT_low_pc for DW_TAG_GNU_call_site "
10349                    "DIE 0x%x [in module %s]"),
10350                  die->offset.sect_off, objfile_name (objfile));
10351       return;
10352     }
10353   pc = DW_ADDR (attr) + baseaddr;
10354
10355   if (cu->call_site_htab == NULL)
10356     cu->call_site_htab = htab_create_alloc_ex (16, core_addr_hash, core_addr_eq,
10357                                                NULL, &objfile->objfile_obstack,
10358                                                hashtab_obstack_allocate, NULL);
10359   call_site_local.pc = pc;
10360   slot = htab_find_slot (cu->call_site_htab, &call_site_local, INSERT);
10361   if (*slot != NULL)
10362     {
10363       complaint (&symfile_complaints,
10364                  _("Duplicate PC %s for DW_TAG_GNU_call_site "
10365                    "DIE 0x%x [in module %s]"),
10366                  paddress (gdbarch, pc), die->offset.sect_off,
10367                  objfile_name (objfile));
10368       return;
10369     }
10370
10371   /* Count parameters at the caller.  */
10372
10373   nparams = 0;
10374   for (child_die = die->child; child_die && child_die->tag;
10375        child_die = sibling_die (child_die))
10376     {
10377       if (child_die->tag != DW_TAG_GNU_call_site_parameter)
10378         {
10379           complaint (&symfile_complaints,
10380                      _("Tag %d is not DW_TAG_GNU_call_site_parameter in "
10381                        "DW_TAG_GNU_call_site child DIE 0x%x [in module %s]"),
10382                      child_die->tag, child_die->offset.sect_off,
10383                      objfile_name (objfile));
10384           continue;
10385         }
10386
10387       nparams++;
10388     }
10389
10390   call_site = obstack_alloc (&objfile->objfile_obstack,
10391                              (sizeof (*call_site)
10392                               + (sizeof (*call_site->parameter)
10393                                  * (nparams - 1))));
10394   *slot = call_site;
10395   memset (call_site, 0, sizeof (*call_site) - sizeof (*call_site->parameter));
10396   call_site->pc = pc;
10397
10398   if (dwarf2_flag_true_p (die, DW_AT_GNU_tail_call, cu))
10399     {
10400       struct die_info *func_die;
10401
10402       /* Skip also over DW_TAG_inlined_subroutine.  */
10403       for (func_die = die->parent;
10404            func_die && func_die->tag != DW_TAG_subprogram
10405            && func_die->tag != DW_TAG_subroutine_type;
10406            func_die = func_die->parent);
10407
10408       /* DW_AT_GNU_all_call_sites is a superset
10409          of DW_AT_GNU_all_tail_call_sites.  */
10410       if (func_die
10411           && !dwarf2_flag_true_p (func_die, DW_AT_GNU_all_call_sites, cu)
10412           && !dwarf2_flag_true_p (func_die, DW_AT_GNU_all_tail_call_sites, cu))
10413         {
10414           /* TYPE_TAIL_CALL_LIST is not interesting in functions where it is
10415              not complete.  But keep CALL_SITE for look ups via call_site_htab,
10416              both the initial caller containing the real return address PC and
10417              the final callee containing the current PC of a chain of tail
10418              calls do not need to have the tail call list complete.  But any
10419              function candidate for a virtual tail call frame searched via
10420              TYPE_TAIL_CALL_LIST must have the tail call list complete to be
10421              determined unambiguously.  */
10422         }
10423       else
10424         {
10425           struct type *func_type = NULL;
10426
10427           if (func_die)
10428             func_type = get_die_type (func_die, cu);
10429           if (func_type != NULL)
10430             {
10431               gdb_assert (TYPE_CODE (func_type) == TYPE_CODE_FUNC);
10432
10433               /* Enlist this call site to the function.  */
10434               call_site->tail_call_next = TYPE_TAIL_CALL_LIST (func_type);
10435               TYPE_TAIL_CALL_LIST (func_type) = call_site;
10436             }
10437           else
10438             complaint (&symfile_complaints,
10439                        _("Cannot find function owning DW_TAG_GNU_call_site "
10440                          "DIE 0x%x [in module %s]"),
10441                        die->offset.sect_off, objfile_name (objfile));
10442         }
10443     }
10444
10445   attr = dwarf2_attr (die, DW_AT_GNU_call_site_target, cu);
10446   if (attr == NULL)
10447     attr = dwarf2_attr (die, DW_AT_abstract_origin, cu);
10448   SET_FIELD_DWARF_BLOCK (call_site->target, NULL);
10449   if (!attr || (attr_form_is_block (attr) && DW_BLOCK (attr)->size == 0))
10450     /* Keep NULL DWARF_BLOCK.  */;
10451   else if (attr_form_is_block (attr))
10452     {
10453       struct dwarf2_locexpr_baton *dlbaton;
10454
10455       dlbaton = obstack_alloc (&objfile->objfile_obstack, sizeof (*dlbaton));
10456       dlbaton->data = DW_BLOCK (attr)->data;
10457       dlbaton->size = DW_BLOCK (attr)->size;
10458       dlbaton->per_cu = cu->per_cu;
10459
10460       SET_FIELD_DWARF_BLOCK (call_site->target, dlbaton);
10461     }
10462   else if (attr_form_is_ref (attr))
10463     {
10464       struct dwarf2_cu *target_cu = cu;
10465       struct die_info *target_die;
10466
10467       target_die = follow_die_ref (die, attr, &target_cu);
10468       gdb_assert (target_cu->objfile == objfile);
10469       if (die_is_declaration (target_die, target_cu))
10470         {
10471           const char *target_physname = NULL;
10472           struct attribute *target_attr;
10473
10474           /* Prefer the mangled name; otherwise compute the demangled one.  */
10475           target_attr = dwarf2_attr (target_die, DW_AT_linkage_name, target_cu);
10476           if (target_attr == NULL)
10477             target_attr = dwarf2_attr (target_die, DW_AT_MIPS_linkage_name,
10478                                        target_cu);
10479           if (target_attr != NULL && DW_STRING (target_attr) != NULL)
10480             target_physname = DW_STRING (target_attr);
10481           else
10482             target_physname = dwarf2_physname (NULL, target_die, target_cu);
10483           if (target_physname == NULL)
10484             complaint (&symfile_complaints,
10485                        _("DW_AT_GNU_call_site_target target DIE has invalid "
10486                          "physname, for referencing DIE 0x%x [in module %s]"),
10487                        die->offset.sect_off, objfile_name (objfile));
10488           else
10489             SET_FIELD_PHYSNAME (call_site->target, target_physname);
10490         }
10491       else
10492         {
10493           CORE_ADDR lowpc;
10494
10495           /* DW_AT_entry_pc should be preferred.  */
10496           if (!dwarf2_get_pc_bounds (target_die, &lowpc, NULL, target_cu, NULL))
10497             complaint (&symfile_complaints,
10498                        _("DW_AT_GNU_call_site_target target DIE has invalid "
10499                          "low pc, for referencing DIE 0x%x [in module %s]"),
10500                        die->offset.sect_off, objfile_name (objfile));
10501           else
10502             SET_FIELD_PHYSADDR (call_site->target, lowpc + baseaddr);
10503         }
10504     }
10505   else
10506     complaint (&symfile_complaints,
10507                _("DW_TAG_GNU_call_site DW_AT_GNU_call_site_target is neither "
10508                  "block nor reference, for DIE 0x%x [in module %s]"),
10509                die->offset.sect_off, objfile_name (objfile));
10510
10511   call_site->per_cu = cu->per_cu;
10512
10513   for (child_die = die->child;
10514        child_die && child_die->tag;
10515        child_die = sibling_die (child_die))
10516     {
10517       struct call_site_parameter *parameter;
10518       struct attribute *loc, *origin;
10519
10520       if (child_die->tag != DW_TAG_GNU_call_site_parameter)
10521         {
10522           /* Already printed the complaint above.  */
10523           continue;
10524         }
10525
10526       gdb_assert (call_site->parameter_count < nparams);
10527       parameter = &call_site->parameter[call_site->parameter_count];
10528
10529       /* DW_AT_location specifies the register number or DW_AT_abstract_origin
10530          specifies DW_TAG_formal_parameter.  Value of the data assumed for the
10531          register is contained in DW_AT_GNU_call_site_value.  */
10532
10533       loc = dwarf2_attr (child_die, DW_AT_location, cu);
10534       origin = dwarf2_attr (child_die, DW_AT_abstract_origin, cu);
10535       if (loc == NULL && origin != NULL && attr_form_is_ref (origin))
10536         {
10537           sect_offset offset;
10538
10539           parameter->kind = CALL_SITE_PARAMETER_PARAM_OFFSET;
10540           offset = dwarf2_get_ref_die_offset (origin);
10541           if (!offset_in_cu_p (&cu->header, offset))
10542             {
10543               /* As DW_OP_GNU_parameter_ref uses CU-relative offset this
10544                  binding can be done only inside one CU.  Such referenced DIE
10545                  therefore cannot be even moved to DW_TAG_partial_unit.  */
10546               complaint (&symfile_complaints,
10547                          _("DW_AT_abstract_origin offset is not in CU for "
10548                            "DW_TAG_GNU_call_site child DIE 0x%x "
10549                            "[in module %s]"),
10550                          child_die->offset.sect_off, objfile_name (objfile));
10551               continue;
10552             }
10553           parameter->u.param_offset.cu_off = (offset.sect_off
10554                                               - cu->header.offset.sect_off);
10555         }
10556       else if (loc == NULL || origin != NULL || !attr_form_is_block (loc))
10557         {
10558           complaint (&symfile_complaints,
10559                      _("No DW_FORM_block* DW_AT_location for "
10560                        "DW_TAG_GNU_call_site child DIE 0x%x [in module %s]"),
10561                      child_die->offset.sect_off, objfile_name (objfile));
10562           continue;
10563         }
10564       else
10565         {
10566           parameter->u.dwarf_reg = dwarf_block_to_dwarf_reg
10567             (DW_BLOCK (loc)->data, &DW_BLOCK (loc)->data[DW_BLOCK (loc)->size]);
10568           if (parameter->u.dwarf_reg != -1)
10569             parameter->kind = CALL_SITE_PARAMETER_DWARF_REG;
10570           else if (dwarf_block_to_sp_offset (gdbarch, DW_BLOCK (loc)->data,
10571                                     &DW_BLOCK (loc)->data[DW_BLOCK (loc)->size],
10572                                              &parameter->u.fb_offset))
10573             parameter->kind = CALL_SITE_PARAMETER_FB_OFFSET;
10574           else
10575             {
10576               complaint (&symfile_complaints,
10577                          _("Only single DW_OP_reg or DW_OP_fbreg is supported "
10578                            "for DW_FORM_block* DW_AT_location is supported for "
10579                            "DW_TAG_GNU_call_site child DIE 0x%x "
10580                            "[in module %s]"),
10581                          child_die->offset.sect_off, objfile_name (objfile));
10582               continue;
10583             }
10584         }
10585
10586       attr = dwarf2_attr (child_die, DW_AT_GNU_call_site_value, cu);
10587       if (!attr_form_is_block (attr))
10588         {
10589           complaint (&symfile_complaints,
10590                      _("No DW_FORM_block* DW_AT_GNU_call_site_value for "
10591                        "DW_TAG_GNU_call_site child DIE 0x%x [in module %s]"),
10592                      child_die->offset.sect_off, objfile_name (objfile));
10593           continue;
10594         }
10595       parameter->value = DW_BLOCK (attr)->data;
10596       parameter->value_size = DW_BLOCK (attr)->size;
10597
10598       /* Parameters are not pre-cleared by memset above.  */
10599       parameter->data_value = NULL;
10600       parameter->data_value_size = 0;
10601       call_site->parameter_count++;
10602
10603       attr = dwarf2_attr (child_die, DW_AT_GNU_call_site_data_value, cu);
10604       if (attr)
10605         {
10606           if (!attr_form_is_block (attr))
10607             complaint (&symfile_complaints,
10608                        _("No DW_FORM_block* DW_AT_GNU_call_site_data_value for "
10609                          "DW_TAG_GNU_call_site child DIE 0x%x [in module %s]"),
10610                        child_die->offset.sect_off, objfile_name (objfile));
10611           else
10612             {
10613               parameter->data_value = DW_BLOCK (attr)->data;
10614               parameter->data_value_size = DW_BLOCK (attr)->size;
10615             }
10616         }
10617     }
10618 }
10619
10620 /* Get low and high pc attributes from DW_AT_ranges attribute value OFFSET.
10621    Return 1 if the attributes are present and valid, otherwise, return 0.
10622    If RANGES_PST is not NULL we should setup `objfile->psymtabs_addrmap'.  */
10623
10624 static int
10625 dwarf2_ranges_read (unsigned offset, CORE_ADDR *low_return,
10626                     CORE_ADDR *high_return, struct dwarf2_cu *cu,
10627                     struct partial_symtab *ranges_pst)
10628 {
10629   struct objfile *objfile = cu->objfile;
10630   struct comp_unit_head *cu_header = &cu->header;
10631   bfd *obfd = objfile->obfd;
10632   unsigned int addr_size = cu_header->addr_size;
10633   CORE_ADDR mask = ~(~(CORE_ADDR)1 << (addr_size * 8 - 1));
10634   /* Base address selection entry.  */
10635   CORE_ADDR base;
10636   int found_base;
10637   unsigned int dummy;
10638   const gdb_byte *buffer;
10639   CORE_ADDR marker;
10640   int low_set;
10641   CORE_ADDR low = 0;
10642   CORE_ADDR high = 0;
10643   CORE_ADDR baseaddr;
10644
10645   found_base = cu->base_known;
10646   base = cu->base_address;
10647
10648   dwarf2_read_section (objfile, &dwarf2_per_objfile->ranges);
10649   if (offset >= dwarf2_per_objfile->ranges.size)
10650     {
10651       complaint (&symfile_complaints,
10652                  _("Offset %d out of bounds for DW_AT_ranges attribute"),
10653                  offset);
10654       return 0;
10655     }
10656   buffer = dwarf2_per_objfile->ranges.buffer + offset;
10657
10658   /* Read in the largest possible address.  */
10659   marker = read_address (obfd, buffer, cu, &dummy);
10660   if ((marker & mask) == mask)
10661     {
10662       /* If we found the largest possible address, then
10663          read the base address.  */
10664       base = read_address (obfd, buffer + addr_size, cu, &dummy);
10665       buffer += 2 * addr_size;
10666       offset += 2 * addr_size;
10667       found_base = 1;
10668     }
10669
10670   low_set = 0;
10671
10672   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
10673
10674   while (1)
10675     {
10676       CORE_ADDR range_beginning, range_end;
10677
10678       range_beginning = read_address (obfd, buffer, cu, &dummy);
10679       buffer += addr_size;
10680       range_end = read_address (obfd, buffer, cu, &dummy);
10681       buffer += addr_size;
10682       offset += 2 * addr_size;
10683
10684       /* An end of list marker is a pair of zero addresses.  */
10685       if (range_beginning == 0 && range_end == 0)
10686         /* Found the end of list entry.  */
10687         break;
10688
10689       /* Each base address selection entry is a pair of 2 values.
10690          The first is the largest possible address, the second is
10691          the base address.  Check for a base address here.  */
10692       if ((range_beginning & mask) == mask)
10693         {
10694           /* If we found the largest possible address, then
10695              read the base address.  */
10696           base = read_address (obfd, buffer + addr_size, cu, &dummy);
10697           found_base = 1;
10698           continue;
10699         }
10700
10701       if (!found_base)
10702         {
10703           /* We have no valid base address for the ranges
10704              data.  */
10705           complaint (&symfile_complaints,
10706                      _("Invalid .debug_ranges data (no base address)"));
10707           return 0;
10708         }
10709
10710       if (range_beginning > range_end)
10711         {
10712           /* Inverted range entries are invalid.  */
10713           complaint (&symfile_complaints,
10714                      _("Invalid .debug_ranges data (inverted range)"));
10715           return 0;
10716         }
10717
10718       /* Empty range entries have no effect.  */
10719       if (range_beginning == range_end)
10720         continue;
10721
10722       range_beginning += base;
10723       range_end += base;
10724
10725       /* A not-uncommon case of bad debug info.
10726          Don't pollute the addrmap with bad data.  */
10727       if (range_beginning + baseaddr == 0
10728           && !dwarf2_per_objfile->has_section_at_zero)
10729         {
10730           complaint (&symfile_complaints,
10731                      _(".debug_ranges entry has start address of zero"
10732                        " [in module %s]"), objfile_name (objfile));
10733           continue;
10734         }
10735
10736       if (ranges_pst != NULL)
10737         addrmap_set_empty (objfile->psymtabs_addrmap,
10738                            range_beginning + baseaddr,
10739                            range_end - 1 + baseaddr,
10740                            ranges_pst);
10741
10742       /* FIXME: This is recording everything as a low-high
10743          segment of consecutive addresses.  We should have a
10744          data structure for discontiguous block ranges
10745          instead.  */
10746       if (! low_set)
10747         {
10748           low = range_beginning;
10749           high = range_end;
10750           low_set = 1;
10751         }
10752       else
10753         {
10754           if (range_beginning < low)
10755             low = range_beginning;
10756           if (range_end > high)
10757             high = range_end;
10758         }
10759     }
10760
10761   if (! low_set)
10762     /* If the first entry is an end-of-list marker, the range
10763        describes an empty scope, i.e. no instructions.  */
10764     return 0;
10765
10766   if (low_return)
10767     *low_return = low;
10768   if (high_return)
10769     *high_return = high;
10770   return 1;
10771 }
10772
10773 /* Get low and high pc attributes from a die.  Return 1 if the attributes
10774    are present and valid, otherwise, return 0.  Return -1 if the range is
10775    discontinuous, i.e. derived from DW_AT_ranges information.  */
10776
10777 static int
10778 dwarf2_get_pc_bounds (struct die_info *die, CORE_ADDR *lowpc,
10779                       CORE_ADDR *highpc, struct dwarf2_cu *cu,
10780                       struct partial_symtab *pst)
10781 {
10782   struct attribute *attr;
10783   struct attribute *attr_high;
10784   CORE_ADDR low = 0;
10785   CORE_ADDR high = 0;
10786   int ret = 0;
10787
10788   attr_high = dwarf2_attr (die, DW_AT_high_pc, cu);
10789   if (attr_high)
10790     {
10791       attr = dwarf2_attr (die, DW_AT_low_pc, cu);
10792       if (attr)
10793         {
10794           low = DW_ADDR (attr);
10795           if (attr_high->form == DW_FORM_addr
10796               || attr_high->form == DW_FORM_GNU_addr_index)
10797             high = DW_ADDR (attr_high);
10798           else
10799             high = low + DW_UNSND (attr_high);
10800         }
10801       else
10802         /* Found high w/o low attribute.  */
10803         return 0;
10804
10805       /* Found consecutive range of addresses.  */
10806       ret = 1;
10807     }
10808   else
10809     {
10810       attr = dwarf2_attr (die, DW_AT_ranges, cu);
10811       if (attr != NULL)
10812         {
10813           /* DW_AT_ranges_base does not apply to DIEs from the DWO skeleton.
10814              We take advantage of the fact that DW_AT_ranges does not appear
10815              in DW_TAG_compile_unit of DWO files.  */
10816           int need_ranges_base = die->tag != DW_TAG_compile_unit;
10817           unsigned int ranges_offset = (DW_UNSND (attr)
10818                                         + (need_ranges_base
10819                                            ? cu->ranges_base
10820                                            : 0));
10821
10822           /* Value of the DW_AT_ranges attribute is the offset in the
10823              .debug_ranges section.  */
10824           if (!dwarf2_ranges_read (ranges_offset, &low, &high, cu, pst))
10825             return 0;
10826           /* Found discontinuous range of addresses.  */
10827           ret = -1;
10828         }
10829     }
10830
10831   /* read_partial_die has also the strict LOW < HIGH requirement.  */
10832   if (high <= low)
10833     return 0;
10834
10835   /* When using the GNU linker, .gnu.linkonce. sections are used to
10836      eliminate duplicate copies of functions and vtables and such.
10837      The linker will arbitrarily choose one and discard the others.
10838      The AT_*_pc values for such functions refer to local labels in
10839      these sections.  If the section from that file was discarded, the
10840      labels are not in the output, so the relocs get a value of 0.
10841      If this is a discarded function, mark the pc bounds as invalid,
10842      so that GDB will ignore it.  */
10843   if (low == 0 && !dwarf2_per_objfile->has_section_at_zero)
10844     return 0;
10845
10846   *lowpc = low;
10847   if (highpc)
10848     *highpc = high;
10849   return ret;
10850 }
10851
10852 /* Assuming that DIE represents a subprogram DIE or a lexical block, get
10853    its low and high PC addresses.  Do nothing if these addresses could not
10854    be determined.  Otherwise, set LOWPC to the low address if it is smaller,
10855    and HIGHPC to the high address if greater than HIGHPC.  */
10856
10857 static void
10858 dwarf2_get_subprogram_pc_bounds (struct die_info *die,
10859                                  CORE_ADDR *lowpc, CORE_ADDR *highpc,
10860                                  struct dwarf2_cu *cu)
10861 {
10862   CORE_ADDR low, high;
10863   struct die_info *child = die->child;
10864
10865   if (dwarf2_get_pc_bounds (die, &low, &high, cu, NULL))
10866     {
10867       *lowpc = min (*lowpc, low);
10868       *highpc = max (*highpc, high);
10869     }
10870
10871   /* If the language does not allow nested subprograms (either inside
10872      subprograms or lexical blocks), we're done.  */
10873   if (cu->language != language_ada)
10874     return;
10875
10876   /* Check all the children of the given DIE.  If it contains nested
10877      subprograms, then check their pc bounds.  Likewise, we need to
10878      check lexical blocks as well, as they may also contain subprogram
10879      definitions.  */
10880   while (child && child->tag)
10881     {
10882       if (child->tag == DW_TAG_subprogram
10883           || child->tag == DW_TAG_lexical_block)
10884         dwarf2_get_subprogram_pc_bounds (child, lowpc, highpc, cu);
10885       child = sibling_die (child);
10886     }
10887 }
10888
10889 /* Get the low and high pc's represented by the scope DIE, and store
10890    them in *LOWPC and *HIGHPC.  If the correct values can't be
10891    determined, set *LOWPC to -1 and *HIGHPC to 0.  */
10892
10893 static void
10894 get_scope_pc_bounds (struct die_info *die,
10895                      CORE_ADDR *lowpc, CORE_ADDR *highpc,
10896                      struct dwarf2_cu *cu)
10897 {
10898   CORE_ADDR best_low = (CORE_ADDR) -1;
10899   CORE_ADDR best_high = (CORE_ADDR) 0;
10900   CORE_ADDR current_low, current_high;
10901
10902   if (dwarf2_get_pc_bounds (die, &current_low, &current_high, cu, NULL))
10903     {
10904       best_low = current_low;
10905       best_high = current_high;
10906     }
10907   else
10908     {
10909       struct die_info *child = die->child;
10910
10911       while (child && child->tag)
10912         {
10913           switch (child->tag) {
10914           case DW_TAG_subprogram:
10915             dwarf2_get_subprogram_pc_bounds (child, &best_low, &best_high, cu);
10916             break;
10917           case DW_TAG_namespace:
10918           case DW_TAG_module:
10919             /* FIXME: carlton/2004-01-16: Should we do this for
10920                DW_TAG_class_type/DW_TAG_structure_type, too?  I think
10921                that current GCC's always emit the DIEs corresponding
10922                to definitions of methods of classes as children of a
10923                DW_TAG_compile_unit or DW_TAG_namespace (as opposed to
10924                the DIEs giving the declarations, which could be
10925                anywhere).  But I don't see any reason why the
10926                standards says that they have to be there.  */
10927             get_scope_pc_bounds (child, &current_low, &current_high, cu);
10928
10929             if (current_low != ((CORE_ADDR) -1))
10930               {
10931                 best_low = min (best_low, current_low);
10932                 best_high = max (best_high, current_high);
10933               }
10934             break;
10935           default:
10936             /* Ignore.  */
10937             break;
10938           }
10939
10940           child = sibling_die (child);
10941         }
10942     }
10943
10944   *lowpc = best_low;
10945   *highpc = best_high;
10946 }
10947
10948 /* Record the address ranges for BLOCK, offset by BASEADDR, as given
10949    in DIE.  */
10950
10951 static void
10952 dwarf2_record_block_ranges (struct die_info *die, struct block *block,
10953                             CORE_ADDR baseaddr, struct dwarf2_cu *cu)
10954 {
10955   struct objfile *objfile = cu->objfile;
10956   struct attribute *attr;
10957   struct attribute *attr_high;
10958
10959   attr_high = dwarf2_attr (die, DW_AT_high_pc, cu);
10960   if (attr_high)
10961     {
10962       attr = dwarf2_attr (die, DW_AT_low_pc, cu);
10963       if (attr)
10964         {
10965           CORE_ADDR low = DW_ADDR (attr);
10966           CORE_ADDR high;
10967           if (attr_high->form == DW_FORM_addr
10968               || attr_high->form == DW_FORM_GNU_addr_index)
10969             high = DW_ADDR (attr_high);
10970           else
10971             high = low + DW_UNSND (attr_high);
10972
10973           record_block_range (block, baseaddr + low, baseaddr + high - 1);
10974         }
10975     }
10976
10977   attr = dwarf2_attr (die, DW_AT_ranges, cu);
10978   if (attr)
10979     {
10980       bfd *obfd = objfile->obfd;
10981       /* DW_AT_ranges_base does not apply to DIEs from the DWO skeleton.
10982          We take advantage of the fact that DW_AT_ranges does not appear
10983          in DW_TAG_compile_unit of DWO files.  */
10984       int need_ranges_base = die->tag != DW_TAG_compile_unit;
10985
10986       /* The value of the DW_AT_ranges attribute is the offset of the
10987          address range list in the .debug_ranges section.  */
10988       unsigned long offset = (DW_UNSND (attr)
10989                               + (need_ranges_base ? cu->ranges_base : 0));
10990       const gdb_byte *buffer;
10991
10992       /* For some target architectures, but not others, the
10993          read_address function sign-extends the addresses it returns.
10994          To recognize base address selection entries, we need a
10995          mask.  */
10996       unsigned int addr_size = cu->header.addr_size;
10997       CORE_ADDR base_select_mask = ~(~(CORE_ADDR)1 << (addr_size * 8 - 1));
10998
10999       /* The base address, to which the next pair is relative.  Note
11000          that this 'base' is a DWARF concept: most entries in a range
11001          list are relative, to reduce the number of relocs against the
11002          debugging information.  This is separate from this function's
11003          'baseaddr' argument, which GDB uses to relocate debugging
11004          information from a shared library based on the address at
11005          which the library was loaded.  */
11006       CORE_ADDR base = cu->base_address;
11007       int base_known = cu->base_known;
11008
11009       dwarf2_read_section (objfile, &dwarf2_per_objfile->ranges);
11010       if (offset >= dwarf2_per_objfile->ranges.size)
11011         {
11012           complaint (&symfile_complaints,
11013                      _("Offset %lu out of bounds for DW_AT_ranges attribute"),
11014                      offset);
11015           return;
11016         }
11017       buffer = dwarf2_per_objfile->ranges.buffer + offset;
11018
11019       for (;;)
11020         {
11021           unsigned int bytes_read;
11022           CORE_ADDR start, end;
11023
11024           start = read_address (obfd, buffer, cu, &bytes_read);
11025           buffer += bytes_read;
11026           end = read_address (obfd, buffer, cu, &bytes_read);
11027           buffer += bytes_read;
11028
11029           /* Did we find the end of the range list?  */
11030           if (start == 0 && end == 0)
11031             break;
11032
11033           /* Did we find a base address selection entry?  */
11034           else if ((start & base_select_mask) == base_select_mask)
11035             {
11036               base = end;
11037               base_known = 1;
11038             }
11039
11040           /* We found an ordinary address range.  */
11041           else
11042             {
11043               if (!base_known)
11044                 {
11045                   complaint (&symfile_complaints,
11046                              _("Invalid .debug_ranges data "
11047                                "(no base address)"));
11048                   return;
11049                 }
11050
11051               if (start > end)
11052                 {
11053                   /* Inverted range entries are invalid.  */
11054                   complaint (&symfile_complaints,
11055                              _("Invalid .debug_ranges data "
11056                                "(inverted range)"));
11057                   return;
11058                 }
11059
11060               /* Empty range entries have no effect.  */
11061               if (start == end)
11062                 continue;
11063
11064               start += base + baseaddr;
11065               end += base + baseaddr;
11066
11067               /* A not-uncommon case of bad debug info.
11068                  Don't pollute the addrmap with bad data.  */
11069               if (start == 0 && !dwarf2_per_objfile->has_section_at_zero)
11070                 {
11071                   complaint (&symfile_complaints,
11072                              _(".debug_ranges entry has start address of zero"
11073                                " [in module %s]"), objfile_name (objfile));
11074                   continue;
11075                 }
11076
11077               record_block_range (block, start, end - 1);
11078             }
11079         }
11080     }
11081 }
11082
11083 /* Check whether the producer field indicates either of GCC < 4.6, or the
11084    Intel C/C++ compiler, and cache the result in CU.  */
11085
11086 static void
11087 check_producer (struct dwarf2_cu *cu)
11088 {
11089   const char *cs;
11090   int major, minor, release;
11091
11092   if (cu->producer == NULL)
11093     {
11094       /* For unknown compilers expect their behavior is DWARF version
11095          compliant.
11096
11097          GCC started to support .debug_types sections by -gdwarf-4 since
11098          gcc-4.5.x.  As the .debug_types sections are missing DW_AT_producer
11099          for their space efficiency GDB cannot workaround gcc-4.5.x -gdwarf-4
11100          combination.  gcc-4.5.x -gdwarf-4 binaries have DW_AT_accessibility
11101          interpreted incorrectly by GDB now - GCC PR debug/48229.  */
11102     }
11103   else if (strncmp (cu->producer, "GNU ", strlen ("GNU ")) == 0)
11104     {
11105       /* Skip any identifier after "GNU " - such as "C++" or "Java".  */
11106
11107       cs = &cu->producer[strlen ("GNU ")];
11108       while (*cs && !isdigit (*cs))
11109         cs++;
11110       if (sscanf (cs, "%d.%d.%d", &major, &minor, &release) != 3)
11111         {
11112           /* Not recognized as GCC.  */
11113         }
11114       else
11115         {
11116           cu->producer_is_gxx_lt_4_6 = major < 4 || (major == 4 && minor < 6);
11117           cu->producer_is_gcc_lt_4_3 = major < 4 || (major == 4 && minor < 3);
11118         }
11119     }
11120   else if (strncmp (cu->producer, "Intel(R) C", strlen ("Intel(R) C")) == 0)
11121     cu->producer_is_icc = 1;
11122   else
11123     {
11124       /* For other non-GCC compilers, expect their behavior is DWARF version
11125          compliant.  */
11126     }
11127
11128   cu->checked_producer = 1;
11129 }
11130
11131 /* Check for GCC PR debug/45124 fix which is not present in any G++ version up
11132    to 4.5.any while it is present already in G++ 4.6.0 - the PR has been fixed
11133    during 4.6.0 experimental.  */
11134
11135 static int
11136 producer_is_gxx_lt_4_6 (struct dwarf2_cu *cu)
11137 {
11138   if (!cu->checked_producer)
11139     check_producer (cu);
11140
11141   return cu->producer_is_gxx_lt_4_6;
11142 }
11143
11144 /* Return the default accessibility type if it is not overriden by
11145    DW_AT_accessibility.  */
11146
11147 static enum dwarf_access_attribute
11148 dwarf2_default_access_attribute (struct die_info *die, struct dwarf2_cu *cu)
11149 {
11150   if (cu->header.version < 3 || producer_is_gxx_lt_4_6 (cu))
11151     {
11152       /* The default DWARF 2 accessibility for members is public, the default
11153          accessibility for inheritance is private.  */
11154
11155       if (die->tag != DW_TAG_inheritance)
11156         return DW_ACCESS_public;
11157       else
11158         return DW_ACCESS_private;
11159     }
11160   else
11161     {
11162       /* DWARF 3+ defines the default accessibility a different way.  The same
11163          rules apply now for DW_TAG_inheritance as for the members and it only
11164          depends on the container kind.  */
11165
11166       if (die->parent->tag == DW_TAG_class_type)
11167         return DW_ACCESS_private;
11168       else
11169         return DW_ACCESS_public;
11170     }
11171 }
11172
11173 /* Look for DW_AT_data_member_location.  Set *OFFSET to the byte
11174    offset.  If the attribute was not found return 0, otherwise return
11175    1.  If it was found but could not properly be handled, set *OFFSET
11176    to 0.  */
11177
11178 static int
11179 handle_data_member_location (struct die_info *die, struct dwarf2_cu *cu,
11180                              LONGEST *offset)
11181 {
11182   struct attribute *attr;
11183
11184   attr = dwarf2_attr (die, DW_AT_data_member_location, cu);
11185   if (attr != NULL)
11186     {
11187       *offset = 0;
11188
11189       /* Note that we do not check for a section offset first here.
11190          This is because DW_AT_data_member_location is new in DWARF 4,
11191          so if we see it, we can assume that a constant form is really
11192          a constant and not a section offset.  */
11193       if (attr_form_is_constant (attr))
11194         *offset = dwarf2_get_attr_constant_value (attr, 0);
11195       else if (attr_form_is_section_offset (attr))
11196         dwarf2_complex_location_expr_complaint ();
11197       else if (attr_form_is_block (attr))
11198         *offset = decode_locdesc (DW_BLOCK (attr), cu);
11199       else
11200         dwarf2_complex_location_expr_complaint ();
11201
11202       return 1;
11203     }
11204
11205   return 0;
11206 }
11207
11208 /* Add an aggregate field to the field list.  */
11209
11210 static void
11211 dwarf2_add_field (struct field_info *fip, struct die_info *die,
11212                   struct dwarf2_cu *cu)
11213 {
11214   struct objfile *objfile = cu->objfile;
11215   struct gdbarch *gdbarch = get_objfile_arch (objfile);
11216   struct nextfield *new_field;
11217   struct attribute *attr;
11218   struct field *fp;
11219   const char *fieldname = "";
11220
11221   /* Allocate a new field list entry and link it in.  */
11222   new_field = (struct nextfield *) xmalloc (sizeof (struct nextfield));
11223   make_cleanup (xfree, new_field);
11224   memset (new_field, 0, sizeof (struct nextfield));
11225
11226   if (die->tag == DW_TAG_inheritance)
11227     {
11228       new_field->next = fip->baseclasses;
11229       fip->baseclasses = new_field;
11230     }
11231   else
11232     {
11233       new_field->next = fip->fields;
11234       fip->fields = new_field;
11235     }
11236   fip->nfields++;
11237
11238   attr = dwarf2_attr (die, DW_AT_accessibility, cu);
11239   if (attr)
11240     new_field->accessibility = DW_UNSND (attr);
11241   else
11242     new_field->accessibility = dwarf2_default_access_attribute (die, cu);
11243   if (new_field->accessibility != DW_ACCESS_public)
11244     fip->non_public_fields = 1;
11245
11246   attr = dwarf2_attr (die, DW_AT_virtuality, cu);
11247   if (attr)
11248     new_field->virtuality = DW_UNSND (attr);
11249   else
11250     new_field->virtuality = DW_VIRTUALITY_none;
11251
11252   fp = &new_field->field;
11253
11254   if (die->tag == DW_TAG_member && ! die_is_declaration (die, cu))
11255     {
11256       LONGEST offset;
11257
11258       /* Data member other than a C++ static data member.  */
11259
11260       /* Get type of field.  */
11261       fp->type = die_type (die, cu);
11262
11263       SET_FIELD_BITPOS (*fp, 0);
11264
11265       /* Get bit size of field (zero if none).  */
11266       attr = dwarf2_attr (die, DW_AT_bit_size, cu);
11267       if (attr)
11268         {
11269           FIELD_BITSIZE (*fp) = DW_UNSND (attr);
11270         }
11271       else
11272         {
11273           FIELD_BITSIZE (*fp) = 0;
11274         }
11275
11276       /* Get bit offset of field.  */
11277       if (handle_data_member_location (die, cu, &offset))
11278         SET_FIELD_BITPOS (*fp, offset * bits_per_byte);
11279       attr = dwarf2_attr (die, DW_AT_bit_offset, cu);
11280       if (attr)
11281         {
11282           if (gdbarch_bits_big_endian (gdbarch))
11283             {
11284               /* For big endian bits, the DW_AT_bit_offset gives the
11285                  additional bit offset from the MSB of the containing
11286                  anonymous object to the MSB of the field.  We don't
11287                  have to do anything special since we don't need to
11288                  know the size of the anonymous object.  */
11289               SET_FIELD_BITPOS (*fp, FIELD_BITPOS (*fp) + DW_UNSND (attr));
11290             }
11291           else
11292             {
11293               /* For little endian bits, compute the bit offset to the
11294                  MSB of the anonymous object, subtract off the number of
11295                  bits from the MSB of the field to the MSB of the
11296                  object, and then subtract off the number of bits of
11297                  the field itself.  The result is the bit offset of
11298                  the LSB of the field.  */
11299               int anonymous_size;
11300               int bit_offset = DW_UNSND (attr);
11301
11302               attr = dwarf2_attr (die, DW_AT_byte_size, cu);
11303               if (attr)
11304                 {
11305                   /* The size of the anonymous object containing
11306                      the bit field is explicit, so use the
11307                      indicated size (in bytes).  */
11308                   anonymous_size = DW_UNSND (attr);
11309                 }
11310               else
11311                 {
11312                   /* The size of the anonymous object containing
11313                      the bit field must be inferred from the type
11314                      attribute of the data member containing the
11315                      bit field.  */
11316                   anonymous_size = TYPE_LENGTH (fp->type);
11317                 }
11318               SET_FIELD_BITPOS (*fp,
11319                                 (FIELD_BITPOS (*fp)
11320                                  + anonymous_size * bits_per_byte
11321                                  - bit_offset - FIELD_BITSIZE (*fp)));
11322             }
11323         }
11324
11325       /* Get name of field.  */
11326       fieldname = dwarf2_name (die, cu);
11327       if (fieldname == NULL)
11328         fieldname = "";
11329
11330       /* The name is already allocated along with this objfile, so we don't
11331          need to duplicate it for the type.  */
11332       fp->name = fieldname;
11333
11334       /* Change accessibility for artificial fields (e.g. virtual table
11335          pointer or virtual base class pointer) to private.  */
11336       if (dwarf2_attr (die, DW_AT_artificial, cu))
11337         {
11338           FIELD_ARTIFICIAL (*fp) = 1;
11339           new_field->accessibility = DW_ACCESS_private;
11340           fip->non_public_fields = 1;
11341         }
11342     }
11343   else if (die->tag == DW_TAG_member || die->tag == DW_TAG_variable)
11344     {
11345       /* C++ static member.  */
11346
11347       /* NOTE: carlton/2002-11-05: It should be a DW_TAG_member that
11348          is a declaration, but all versions of G++ as of this writing
11349          (so through at least 3.2.1) incorrectly generate
11350          DW_TAG_variable tags.  */
11351
11352       const char *physname;
11353
11354       /* Get name of field.  */
11355       fieldname = dwarf2_name (die, cu);
11356       if (fieldname == NULL)
11357         return;
11358
11359       attr = dwarf2_attr (die, DW_AT_const_value, cu);
11360       if (attr
11361           /* Only create a symbol if this is an external value.
11362              new_symbol checks this and puts the value in the global symbol
11363              table, which we want.  If it is not external, new_symbol
11364              will try to put the value in cu->list_in_scope which is wrong.  */
11365           && dwarf2_flag_true_p (die, DW_AT_external, cu))
11366         {
11367           /* A static const member, not much different than an enum as far as
11368              we're concerned, except that we can support more types.  */
11369           new_symbol (die, NULL, cu);
11370         }
11371
11372       /* Get physical name.  */
11373       physname = dwarf2_physname (fieldname, die, cu);
11374
11375       /* The name is already allocated along with this objfile, so we don't
11376          need to duplicate it for the type.  */
11377       SET_FIELD_PHYSNAME (*fp, physname ? physname : "");
11378       FIELD_TYPE (*fp) = die_type (die, cu);
11379       FIELD_NAME (*fp) = fieldname;
11380     }
11381   else if (die->tag == DW_TAG_inheritance)
11382     {
11383       LONGEST offset;
11384
11385       /* C++ base class field.  */
11386       if (handle_data_member_location (die, cu, &offset))
11387         SET_FIELD_BITPOS (*fp, offset * bits_per_byte);
11388       FIELD_BITSIZE (*fp) = 0;
11389       FIELD_TYPE (*fp) = die_type (die, cu);
11390       FIELD_NAME (*fp) = type_name_no_tag (fp->type);
11391       fip->nbaseclasses++;
11392     }
11393 }
11394
11395 /* Add a typedef defined in the scope of the FIP's class.  */
11396
11397 static void
11398 dwarf2_add_typedef (struct field_info *fip, struct die_info *die,
11399                     struct dwarf2_cu *cu)
11400 {
11401   struct objfile *objfile = cu->objfile;
11402   struct typedef_field_list *new_field;
11403   struct attribute *attr;
11404   struct typedef_field *fp;
11405   char *fieldname = "";
11406
11407   /* Allocate a new field list entry and link it in.  */
11408   new_field = xzalloc (sizeof (*new_field));
11409   make_cleanup (xfree, new_field);
11410
11411   gdb_assert (die->tag == DW_TAG_typedef);
11412
11413   fp = &new_field->field;
11414
11415   /* Get name of field.  */
11416   fp->name = dwarf2_name (die, cu);
11417   if (fp->name == NULL)
11418     return;
11419
11420   fp->type = read_type_die (die, cu);
11421
11422   new_field->next = fip->typedef_field_list;
11423   fip->typedef_field_list = new_field;
11424   fip->typedef_field_list_count++;
11425 }
11426
11427 /* Create the vector of fields, and attach it to the type.  */
11428
11429 static void
11430 dwarf2_attach_fields_to_type (struct field_info *fip, struct type *type,
11431                               struct dwarf2_cu *cu)
11432 {
11433   int nfields = fip->nfields;
11434
11435   /* Record the field count, allocate space for the array of fields,
11436      and create blank accessibility bitfields if necessary.  */
11437   TYPE_NFIELDS (type) = nfields;
11438   TYPE_FIELDS (type) = (struct field *)
11439     TYPE_ALLOC (type, sizeof (struct field) * nfields);
11440   memset (TYPE_FIELDS (type), 0, sizeof (struct field) * nfields);
11441
11442   if (fip->non_public_fields && cu->language != language_ada)
11443     {
11444       ALLOCATE_CPLUS_STRUCT_TYPE (type);
11445
11446       TYPE_FIELD_PRIVATE_BITS (type) =
11447         (B_TYPE *) TYPE_ALLOC (type, B_BYTES (nfields));
11448       B_CLRALL (TYPE_FIELD_PRIVATE_BITS (type), nfields);
11449
11450       TYPE_FIELD_PROTECTED_BITS (type) =
11451         (B_TYPE *) TYPE_ALLOC (type, B_BYTES (nfields));
11452       B_CLRALL (TYPE_FIELD_PROTECTED_BITS (type), nfields);
11453
11454       TYPE_FIELD_IGNORE_BITS (type) =
11455         (B_TYPE *) TYPE_ALLOC (type, B_BYTES (nfields));
11456       B_CLRALL (TYPE_FIELD_IGNORE_BITS (type), nfields);
11457     }
11458
11459   /* If the type has baseclasses, allocate and clear a bit vector for
11460      TYPE_FIELD_VIRTUAL_BITS.  */
11461   if (fip->nbaseclasses && cu->language != language_ada)
11462     {
11463       int num_bytes = B_BYTES (fip->nbaseclasses);
11464       unsigned char *pointer;
11465
11466       ALLOCATE_CPLUS_STRUCT_TYPE (type);
11467       pointer = TYPE_ALLOC (type, num_bytes);
11468       TYPE_FIELD_VIRTUAL_BITS (type) = pointer;
11469       B_CLRALL (TYPE_FIELD_VIRTUAL_BITS (type), fip->nbaseclasses);
11470       TYPE_N_BASECLASSES (type) = fip->nbaseclasses;
11471     }
11472
11473   /* Copy the saved-up fields into the field vector.  Start from the head of
11474      the list, adding to the tail of the field array, so that they end up in
11475      the same order in the array in which they were added to the list.  */
11476   while (nfields-- > 0)
11477     {
11478       struct nextfield *fieldp;
11479
11480       if (fip->fields)
11481         {
11482           fieldp = fip->fields;
11483           fip->fields = fieldp->next;
11484         }
11485       else
11486         {
11487           fieldp = fip->baseclasses;
11488           fip->baseclasses = fieldp->next;
11489         }
11490
11491       TYPE_FIELD (type, nfields) = fieldp->field;
11492       switch (fieldp->accessibility)
11493         {
11494         case DW_ACCESS_private:
11495           if (cu->language != language_ada)
11496             SET_TYPE_FIELD_PRIVATE (type, nfields);
11497           break;
11498
11499         case DW_ACCESS_protected:
11500           if (cu->language != language_ada)
11501             SET_TYPE_FIELD_PROTECTED (type, nfields);
11502           break;
11503
11504         case DW_ACCESS_public:
11505           break;
11506
11507         default:
11508           /* Unknown accessibility.  Complain and treat it as public.  */
11509           {
11510             complaint (&symfile_complaints, _("unsupported accessibility %d"),
11511                        fieldp->accessibility);
11512           }
11513           break;
11514         }
11515       if (nfields < fip->nbaseclasses)
11516         {
11517           switch (fieldp->virtuality)
11518             {
11519             case DW_VIRTUALITY_virtual:
11520             case DW_VIRTUALITY_pure_virtual:
11521               if (cu->language == language_ada)
11522                 error (_("unexpected virtuality in component of Ada type"));
11523               SET_TYPE_FIELD_VIRTUAL (type, nfields);
11524               break;
11525             }
11526         }
11527     }
11528 }
11529
11530 /* Return true if this member function is a constructor, false
11531    otherwise.  */
11532
11533 static int
11534 dwarf2_is_constructor (struct die_info *die, struct dwarf2_cu *cu)
11535 {
11536   const char *fieldname;
11537   const char *typename;
11538   int len;
11539
11540   if (die->parent == NULL)
11541     return 0;
11542
11543   if (die->parent->tag != DW_TAG_structure_type
11544       && die->parent->tag != DW_TAG_union_type
11545       && die->parent->tag != DW_TAG_class_type)
11546     return 0;
11547
11548   fieldname = dwarf2_name (die, cu);
11549   typename = dwarf2_name (die->parent, cu);
11550   if (fieldname == NULL || typename == NULL)
11551     return 0;
11552
11553   len = strlen (fieldname);
11554   return (strncmp (fieldname, typename, len) == 0
11555           && (typename[len] == '\0' || typename[len] == '<'));
11556 }
11557
11558 /* Add a member function to the proper fieldlist.  */
11559
11560 static void
11561 dwarf2_add_member_fn (struct field_info *fip, struct die_info *die,
11562                       struct type *type, struct dwarf2_cu *cu)
11563 {
11564   struct objfile *objfile = cu->objfile;
11565   struct attribute *attr;
11566   struct fnfieldlist *flp;
11567   int i;
11568   struct fn_field *fnp;
11569   const char *fieldname;
11570   struct nextfnfield *new_fnfield;
11571   struct type *this_type;
11572   enum dwarf_access_attribute accessibility;
11573
11574   if (cu->language == language_ada)
11575     error (_("unexpected member function in Ada type"));
11576
11577   /* Get name of member function.  */
11578   fieldname = dwarf2_name (die, cu);
11579   if (fieldname == NULL)
11580     return;
11581
11582   /* Look up member function name in fieldlist.  */
11583   for (i = 0; i < fip->nfnfields; i++)
11584     {
11585       if (strcmp (fip->fnfieldlists[i].name, fieldname) == 0)
11586         break;
11587     }
11588
11589   /* Create new list element if necessary.  */
11590   if (i < fip->nfnfields)
11591     flp = &fip->fnfieldlists[i];
11592   else
11593     {
11594       if ((fip->nfnfields % DW_FIELD_ALLOC_CHUNK) == 0)
11595         {
11596           fip->fnfieldlists = (struct fnfieldlist *)
11597             xrealloc (fip->fnfieldlists,
11598                       (fip->nfnfields + DW_FIELD_ALLOC_CHUNK)
11599                       * sizeof (struct fnfieldlist));
11600           if (fip->nfnfields == 0)
11601             make_cleanup (free_current_contents, &fip->fnfieldlists);
11602         }
11603       flp = &fip->fnfieldlists[fip->nfnfields];
11604       flp->name = fieldname;
11605       flp->length = 0;
11606       flp->head = NULL;
11607       i = fip->nfnfields++;
11608     }
11609
11610   /* Create a new member function field and chain it to the field list
11611      entry.  */
11612   new_fnfield = (struct nextfnfield *) xmalloc (sizeof (struct nextfnfield));
11613   make_cleanup (xfree, new_fnfield);
11614   memset (new_fnfield, 0, sizeof (struct nextfnfield));
11615   new_fnfield->next = flp->head;
11616   flp->head = new_fnfield;
11617   flp->length++;
11618
11619   /* Fill in the member function field info.  */
11620   fnp = &new_fnfield->fnfield;
11621
11622   /* Delay processing of the physname until later.  */
11623   if (cu->language == language_cplus || cu->language == language_java)
11624     {
11625       add_to_method_list (type, i, flp->length - 1, fieldname,
11626                           die, cu);
11627     }
11628   else
11629     {
11630       const char *physname = dwarf2_physname (fieldname, die, cu);
11631       fnp->physname = physname ? physname : "";
11632     }
11633
11634   fnp->type = alloc_type (objfile);
11635   this_type = read_type_die (die, cu);
11636   if (this_type && TYPE_CODE (this_type) == TYPE_CODE_FUNC)
11637     {
11638       int nparams = TYPE_NFIELDS (this_type);
11639
11640       /* TYPE is the domain of this method, and THIS_TYPE is the type
11641            of the method itself (TYPE_CODE_METHOD).  */
11642       smash_to_method_type (fnp->type, type,
11643                             TYPE_TARGET_TYPE (this_type),
11644                             TYPE_FIELDS (this_type),
11645                             TYPE_NFIELDS (this_type),
11646                             TYPE_VARARGS (this_type));
11647
11648       /* Handle static member functions.
11649          Dwarf2 has no clean way to discern C++ static and non-static
11650          member functions.  G++ helps GDB by marking the first
11651          parameter for non-static member functions (which is the this
11652          pointer) as artificial.  We obtain this information from
11653          read_subroutine_type via TYPE_FIELD_ARTIFICIAL.  */
11654       if (nparams == 0 || TYPE_FIELD_ARTIFICIAL (this_type, 0) == 0)
11655         fnp->voffset = VOFFSET_STATIC;
11656     }
11657   else
11658     complaint (&symfile_complaints, _("member function type missing for '%s'"),
11659                dwarf2_full_name (fieldname, die, cu));
11660
11661   /* Get fcontext from DW_AT_containing_type if present.  */
11662   if (dwarf2_attr (die, DW_AT_containing_type, cu) != NULL)
11663     fnp->fcontext = die_containing_type (die, cu);
11664
11665   /* dwarf2 doesn't have stubbed physical names, so the setting of is_const and
11666      is_volatile is irrelevant, as it is needed by gdb_mangle_name only.  */
11667
11668   /* Get accessibility.  */
11669   attr = dwarf2_attr (die, DW_AT_accessibility, cu);
11670   if (attr)
11671     accessibility = DW_UNSND (attr);
11672   else
11673     accessibility = dwarf2_default_access_attribute (die, cu);
11674   switch (accessibility)
11675     {
11676     case DW_ACCESS_private:
11677       fnp->is_private = 1;
11678       break;
11679     case DW_ACCESS_protected:
11680       fnp->is_protected = 1;
11681       break;
11682     }
11683
11684   /* Check for artificial methods.  */
11685   attr = dwarf2_attr (die, DW_AT_artificial, cu);
11686   if (attr && DW_UNSND (attr) != 0)
11687     fnp->is_artificial = 1;
11688
11689   fnp->is_constructor = dwarf2_is_constructor (die, cu);
11690
11691   /* Get index in virtual function table if it is a virtual member
11692      function.  For older versions of GCC, this is an offset in the
11693      appropriate virtual table, as specified by DW_AT_containing_type.
11694      For everyone else, it is an expression to be evaluated relative
11695      to the object address.  */
11696
11697   attr = dwarf2_attr (die, DW_AT_vtable_elem_location, cu);
11698   if (attr)
11699     {
11700       if (attr_form_is_block (attr) && DW_BLOCK (attr)->size > 0)
11701         {
11702           if (DW_BLOCK (attr)->data[0] == DW_OP_constu)
11703             {
11704               /* Old-style GCC.  */
11705               fnp->voffset = decode_locdesc (DW_BLOCK (attr), cu) + 2;
11706             }
11707           else if (DW_BLOCK (attr)->data[0] == DW_OP_deref
11708                    || (DW_BLOCK (attr)->size > 1
11709                        && DW_BLOCK (attr)->data[0] == DW_OP_deref_size
11710                        && DW_BLOCK (attr)->data[1] == cu->header.addr_size))
11711             {
11712               struct dwarf_block blk;
11713               int offset;
11714
11715               offset = (DW_BLOCK (attr)->data[0] == DW_OP_deref
11716                         ? 1 : 2);
11717               blk.size = DW_BLOCK (attr)->size - offset;
11718               blk.data = DW_BLOCK (attr)->data + offset;
11719               fnp->voffset = decode_locdesc (DW_BLOCK (attr), cu);
11720               if ((fnp->voffset % cu->header.addr_size) != 0)
11721                 dwarf2_complex_location_expr_complaint ();
11722               else
11723                 fnp->voffset /= cu->header.addr_size;
11724               fnp->voffset += 2;
11725             }
11726           else
11727             dwarf2_complex_location_expr_complaint ();
11728
11729           if (!fnp->fcontext)
11730             fnp->fcontext = TYPE_TARGET_TYPE (TYPE_FIELD_TYPE (this_type, 0));
11731         }
11732       else if (attr_form_is_section_offset (attr))
11733         {
11734           dwarf2_complex_location_expr_complaint ();
11735         }
11736       else
11737         {
11738           dwarf2_invalid_attrib_class_complaint ("DW_AT_vtable_elem_location",
11739                                                  fieldname);
11740         }
11741     }
11742   else
11743     {
11744       attr = dwarf2_attr (die, DW_AT_virtuality, cu);
11745       if (attr && DW_UNSND (attr))
11746         {
11747           /* GCC does this, as of 2008-08-25; PR debug/37237.  */
11748           complaint (&symfile_complaints,
11749                      _("Member function \"%s\" (offset %d) is virtual "
11750                        "but the vtable offset is not specified"),
11751                      fieldname, die->offset.sect_off);
11752           ALLOCATE_CPLUS_STRUCT_TYPE (type);
11753           TYPE_CPLUS_DYNAMIC (type) = 1;
11754         }
11755     }
11756 }
11757
11758 /* Create the vector of member function fields, and attach it to the type.  */
11759
11760 static void
11761 dwarf2_attach_fn_fields_to_type (struct field_info *fip, struct type *type,
11762                                  struct dwarf2_cu *cu)
11763 {
11764   struct fnfieldlist *flp;
11765   int i;
11766
11767   if (cu->language == language_ada)
11768     error (_("unexpected member functions in Ada type"));
11769
11770   ALLOCATE_CPLUS_STRUCT_TYPE (type);
11771   TYPE_FN_FIELDLISTS (type) = (struct fn_fieldlist *)
11772     TYPE_ALLOC (type, sizeof (struct fn_fieldlist) * fip->nfnfields);
11773
11774   for (i = 0, flp = fip->fnfieldlists; i < fip->nfnfields; i++, flp++)
11775     {
11776       struct nextfnfield *nfp = flp->head;
11777       struct fn_fieldlist *fn_flp = &TYPE_FN_FIELDLIST (type, i);
11778       int k;
11779
11780       TYPE_FN_FIELDLIST_NAME (type, i) = flp->name;
11781       TYPE_FN_FIELDLIST_LENGTH (type, i) = flp->length;
11782       fn_flp->fn_fields = (struct fn_field *)
11783         TYPE_ALLOC (type, sizeof (struct fn_field) * flp->length);
11784       for (k = flp->length; (k--, nfp); nfp = nfp->next)
11785         fn_flp->fn_fields[k] = nfp->fnfield;
11786     }
11787
11788   TYPE_NFN_FIELDS (type) = fip->nfnfields;
11789 }
11790
11791 /* Returns non-zero if NAME is the name of a vtable member in CU's
11792    language, zero otherwise.  */
11793 static int
11794 is_vtable_name (const char *name, struct dwarf2_cu *cu)
11795 {
11796   static const char vptr[] = "_vptr";
11797   static const char vtable[] = "vtable";
11798
11799   /* Look for the C++ and Java forms of the vtable.  */
11800   if ((cu->language == language_java
11801        && strncmp (name, vtable, sizeof (vtable) - 1) == 0)
11802        || (strncmp (name, vptr, sizeof (vptr) - 1) == 0
11803        && is_cplus_marker (name[sizeof (vptr) - 1])))
11804     return 1;
11805
11806   return 0;
11807 }
11808
11809 /* GCC outputs unnamed structures that are really pointers to member
11810    functions, with the ABI-specified layout.  If TYPE describes
11811    such a structure, smash it into a member function type.
11812
11813    GCC shouldn't do this; it should just output pointer to member DIEs.
11814    This is GCC PR debug/28767.  */
11815
11816 static void
11817 quirk_gcc_member_function_pointer (struct type *type, struct objfile *objfile)
11818 {
11819   struct type *pfn_type, *domain_type, *new_type;
11820
11821   /* Check for a structure with no name and two children.  */
11822   if (TYPE_CODE (type) != TYPE_CODE_STRUCT || TYPE_NFIELDS (type) != 2)
11823     return;
11824
11825   /* Check for __pfn and __delta members.  */
11826   if (TYPE_FIELD_NAME (type, 0) == NULL
11827       || strcmp (TYPE_FIELD_NAME (type, 0), "__pfn") != 0
11828       || TYPE_FIELD_NAME (type, 1) == NULL
11829       || strcmp (TYPE_FIELD_NAME (type, 1), "__delta") != 0)
11830     return;
11831
11832   /* Find the type of the method.  */
11833   pfn_type = TYPE_FIELD_TYPE (type, 0);
11834   if (pfn_type == NULL
11835       || TYPE_CODE (pfn_type) != TYPE_CODE_PTR
11836       || TYPE_CODE (TYPE_TARGET_TYPE (pfn_type)) != TYPE_CODE_FUNC)
11837     return;
11838
11839   /* Look for the "this" argument.  */
11840   pfn_type = TYPE_TARGET_TYPE (pfn_type);
11841   if (TYPE_NFIELDS (pfn_type) == 0
11842       /* || TYPE_FIELD_TYPE (pfn_type, 0) == NULL */
11843       || TYPE_CODE (TYPE_FIELD_TYPE (pfn_type, 0)) != TYPE_CODE_PTR)
11844     return;
11845
11846   domain_type = TYPE_TARGET_TYPE (TYPE_FIELD_TYPE (pfn_type, 0));
11847   new_type = alloc_type (objfile);
11848   smash_to_method_type (new_type, domain_type, TYPE_TARGET_TYPE (pfn_type),
11849                         TYPE_FIELDS (pfn_type), TYPE_NFIELDS (pfn_type),
11850                         TYPE_VARARGS (pfn_type));
11851   smash_to_methodptr_type (type, new_type);
11852 }
11853
11854 /* Return non-zero if the CU's PRODUCER string matches the Intel C/C++ compiler
11855    (icc).  */
11856
11857 static int
11858 producer_is_icc (struct dwarf2_cu *cu)
11859 {
11860   if (!cu->checked_producer)
11861     check_producer (cu);
11862
11863   return cu->producer_is_icc;
11864 }
11865
11866 /* Called when we find the DIE that starts a structure or union scope
11867    (definition) to create a type for the structure or union.  Fill in
11868    the type's name and general properties; the members will not be
11869    processed until process_structure_scope.
11870
11871    NOTE: we need to call these functions regardless of whether or not the
11872    DIE has a DW_AT_name attribute, since it might be an anonymous
11873    structure or union.  This gets the type entered into our set of
11874    user defined types.
11875
11876    However, if the structure is incomplete (an opaque struct/union)
11877    then suppress creating a symbol table entry for it since gdb only
11878    wants to find the one with the complete definition.  Note that if
11879    it is complete, we just call new_symbol, which does it's own
11880    checking about whether the struct/union is anonymous or not (and
11881    suppresses creating a symbol table entry itself).  */
11882
11883 static struct type *
11884 read_structure_type (struct die_info *die, struct dwarf2_cu *cu)
11885 {
11886   struct objfile *objfile = cu->objfile;
11887   struct type *type;
11888   struct attribute *attr;
11889   const char *name;
11890
11891   /* If the definition of this type lives in .debug_types, read that type.
11892      Don't follow DW_AT_specification though, that will take us back up
11893      the chain and we want to go down.  */
11894   attr = dwarf2_attr_no_follow (die, DW_AT_signature);
11895   if (attr)
11896     {
11897       type = get_DW_AT_signature_type (die, attr, cu);
11898
11899       /* The type's CU may not be the same as CU.
11900          Ensure TYPE is recorded with CU in die_type_hash.  */
11901       return set_die_type (die, type, cu);
11902     }
11903
11904   type = alloc_type (objfile);
11905   INIT_CPLUS_SPECIFIC (type);
11906
11907   name = dwarf2_name (die, cu);
11908   if (name != NULL)
11909     {
11910       if (cu->language == language_cplus
11911           || cu->language == language_java)
11912         {
11913           const char *full_name = dwarf2_full_name (name, die, cu);
11914
11915           /* dwarf2_full_name might have already finished building the DIE's
11916              type.  If so, there is no need to continue.  */
11917           if (get_die_type (die, cu) != NULL)
11918             return get_die_type (die, cu);
11919
11920           TYPE_TAG_NAME (type) = full_name;
11921           if (die->tag == DW_TAG_structure_type
11922               || die->tag == DW_TAG_class_type)
11923             TYPE_NAME (type) = TYPE_TAG_NAME (type);
11924         }
11925       else
11926         {
11927           /* The name is already allocated along with this objfile, so
11928              we don't need to duplicate it for the type.  */
11929           TYPE_TAG_NAME (type) = name;
11930           if (die->tag == DW_TAG_class_type)
11931             TYPE_NAME (type) = TYPE_TAG_NAME (type);
11932         }
11933     }
11934
11935   if (die->tag == DW_TAG_structure_type)
11936     {
11937       TYPE_CODE (type) = TYPE_CODE_STRUCT;
11938     }
11939   else if (die->tag == DW_TAG_union_type)
11940     {
11941       TYPE_CODE (type) = TYPE_CODE_UNION;
11942     }
11943   else
11944     {
11945       TYPE_CODE (type) = TYPE_CODE_CLASS;
11946     }
11947
11948   if (cu->language == language_cplus && die->tag == DW_TAG_class_type)
11949     TYPE_DECLARED_CLASS (type) = 1;
11950
11951   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
11952   if (attr)
11953     {
11954       TYPE_LENGTH (type) = DW_UNSND (attr);
11955     }
11956   else
11957     {
11958       TYPE_LENGTH (type) = 0;
11959     }
11960
11961   if (producer_is_icc (cu))
11962     {
11963       /* ICC does not output the required DW_AT_declaration
11964          on incomplete types, but gives them a size of zero.  */
11965     }
11966   else
11967     TYPE_STUB_SUPPORTED (type) = 1;
11968
11969   if (die_is_declaration (die, cu))
11970     TYPE_STUB (type) = 1;
11971   else if (attr == NULL && die->child == NULL
11972            && producer_is_realview (cu->producer))
11973     /* RealView does not output the required DW_AT_declaration
11974        on incomplete types.  */
11975     TYPE_STUB (type) = 1;
11976
11977   /* We need to add the type field to the die immediately so we don't
11978      infinitely recurse when dealing with pointers to the structure
11979      type within the structure itself.  */
11980   set_die_type (die, type, cu);
11981
11982   /* set_die_type should be already done.  */
11983   set_descriptive_type (type, die, cu);
11984
11985   return type;
11986 }
11987
11988 /* Finish creating a structure or union type, including filling in
11989    its members and creating a symbol for it.  */
11990
11991 static void
11992 process_structure_scope (struct die_info *die, struct dwarf2_cu *cu)
11993 {
11994   struct objfile *objfile = cu->objfile;
11995   struct die_info *child_die = die->child;
11996   struct type *type;
11997
11998   type = get_die_type (die, cu);
11999   if (type == NULL)
12000     type = read_structure_type (die, cu);
12001
12002   if (die->child != NULL && ! die_is_declaration (die, cu))
12003     {
12004       struct field_info fi;
12005       struct die_info *child_die;
12006       VEC (symbolp) *template_args = NULL;
12007       struct cleanup *back_to = make_cleanup (null_cleanup, 0);
12008
12009       memset (&fi, 0, sizeof (struct field_info));
12010
12011       child_die = die->child;
12012
12013       while (child_die && child_die->tag)
12014         {
12015           if (child_die->tag == DW_TAG_member
12016               || child_die->tag == DW_TAG_variable)
12017             {
12018               /* NOTE: carlton/2002-11-05: A C++ static data member
12019                  should be a DW_TAG_member that is a declaration, but
12020                  all versions of G++ as of this writing (so through at
12021                  least 3.2.1) incorrectly generate DW_TAG_variable
12022                  tags for them instead.  */
12023               dwarf2_add_field (&fi, child_die, cu);
12024             }
12025           else if (child_die->tag == DW_TAG_subprogram)
12026             {
12027               /* C++ member function.  */
12028               dwarf2_add_member_fn (&fi, child_die, type, cu);
12029             }
12030           else if (child_die->tag == DW_TAG_inheritance)
12031             {
12032               /* C++ base class field.  */
12033               dwarf2_add_field (&fi, child_die, cu);
12034             }
12035           else if (child_die->tag == DW_TAG_typedef)
12036             dwarf2_add_typedef (&fi, child_die, cu);
12037           else if (child_die->tag == DW_TAG_template_type_param
12038                    || child_die->tag == DW_TAG_template_value_param)
12039             {
12040               struct symbol *arg = new_symbol (child_die, NULL, cu);
12041
12042               if (arg != NULL)
12043                 VEC_safe_push (symbolp, template_args, arg);
12044             }
12045
12046           child_die = sibling_die (child_die);
12047         }
12048
12049       /* Attach template arguments to type.  */
12050       if (! VEC_empty (symbolp, template_args))
12051         {
12052           ALLOCATE_CPLUS_STRUCT_TYPE (type);
12053           TYPE_N_TEMPLATE_ARGUMENTS (type)
12054             = VEC_length (symbolp, template_args);
12055           TYPE_TEMPLATE_ARGUMENTS (type)
12056             = obstack_alloc (&objfile->objfile_obstack,
12057                              (TYPE_N_TEMPLATE_ARGUMENTS (type)
12058                               * sizeof (struct symbol *)));
12059           memcpy (TYPE_TEMPLATE_ARGUMENTS (type),
12060                   VEC_address (symbolp, template_args),
12061                   (TYPE_N_TEMPLATE_ARGUMENTS (type)
12062                    * sizeof (struct symbol *)));
12063           VEC_free (symbolp, template_args);
12064         }
12065
12066       /* Attach fields and member functions to the type.  */
12067       if (fi.nfields)
12068         dwarf2_attach_fields_to_type (&fi, type, cu);
12069       if (fi.nfnfields)
12070         {
12071           dwarf2_attach_fn_fields_to_type (&fi, type, cu);
12072
12073           /* Get the type which refers to the base class (possibly this
12074              class itself) which contains the vtable pointer for the current
12075              class from the DW_AT_containing_type attribute.  This use of
12076              DW_AT_containing_type is a GNU extension.  */
12077
12078           if (dwarf2_attr (die, DW_AT_containing_type, cu) != NULL)
12079             {
12080               struct type *t = die_containing_type (die, cu);
12081
12082               TYPE_VPTR_BASETYPE (type) = t;
12083               if (type == t)
12084                 {
12085                   int i;
12086
12087                   /* Our own class provides vtbl ptr.  */
12088                   for (i = TYPE_NFIELDS (t) - 1;
12089                        i >= TYPE_N_BASECLASSES (t);
12090                        --i)
12091                     {
12092                       const char *fieldname = TYPE_FIELD_NAME (t, i);
12093
12094                       if (is_vtable_name (fieldname, cu))
12095                         {
12096                           TYPE_VPTR_FIELDNO (type) = i;
12097                           break;
12098                         }
12099                     }
12100
12101                   /* Complain if virtual function table field not found.  */
12102                   if (i < TYPE_N_BASECLASSES (t))
12103                     complaint (&symfile_complaints,
12104                                _("virtual function table pointer "
12105                                  "not found when defining class '%s'"),
12106                                TYPE_TAG_NAME (type) ? TYPE_TAG_NAME (type) :
12107                                "");
12108                 }
12109               else
12110                 {
12111                   TYPE_VPTR_FIELDNO (type) = TYPE_VPTR_FIELDNO (t);
12112                 }
12113             }
12114           else if (cu->producer
12115                    && strncmp (cu->producer,
12116                                "IBM(R) XL C/C++ Advanced Edition", 32) == 0)
12117             {
12118               /* The IBM XLC compiler does not provide direct indication
12119                  of the containing type, but the vtable pointer is
12120                  always named __vfp.  */
12121
12122               int i;
12123
12124               for (i = TYPE_NFIELDS (type) - 1;
12125                    i >= TYPE_N_BASECLASSES (type);
12126                    --i)
12127                 {
12128                   if (strcmp (TYPE_FIELD_NAME (type, i), "__vfp") == 0)
12129                     {
12130                       TYPE_VPTR_FIELDNO (type) = i;
12131                       TYPE_VPTR_BASETYPE (type) = type;
12132                       break;
12133                     }
12134                 }
12135             }
12136         }
12137
12138       /* Copy fi.typedef_field_list linked list elements content into the
12139          allocated array TYPE_TYPEDEF_FIELD_ARRAY (type).  */
12140       if (fi.typedef_field_list)
12141         {
12142           int i = fi.typedef_field_list_count;
12143
12144           ALLOCATE_CPLUS_STRUCT_TYPE (type);
12145           TYPE_TYPEDEF_FIELD_ARRAY (type)
12146             = TYPE_ALLOC (type, sizeof (TYPE_TYPEDEF_FIELD (type, 0)) * i);
12147           TYPE_TYPEDEF_FIELD_COUNT (type) = i;
12148
12149           /* Reverse the list order to keep the debug info elements order.  */
12150           while (--i >= 0)
12151             {
12152               struct typedef_field *dest, *src;
12153
12154               dest = &TYPE_TYPEDEF_FIELD (type, i);
12155               src = &fi.typedef_field_list->field;
12156               fi.typedef_field_list = fi.typedef_field_list->next;
12157               *dest = *src;
12158             }
12159         }
12160
12161       do_cleanups (back_to);
12162
12163       if (HAVE_CPLUS_STRUCT (type))
12164         TYPE_CPLUS_REALLY_JAVA (type) = cu->language == language_java;
12165     }
12166
12167   quirk_gcc_member_function_pointer (type, objfile);
12168
12169   /* NOTE: carlton/2004-03-16: GCC 3.4 (or at least one of its
12170      snapshots) has been known to create a die giving a declaration
12171      for a class that has, as a child, a die giving a definition for a
12172      nested class.  So we have to process our children even if the
12173      current die is a declaration.  Normally, of course, a declaration
12174      won't have any children at all.  */
12175
12176   while (child_die != NULL && child_die->tag)
12177     {
12178       if (child_die->tag == DW_TAG_member
12179           || child_die->tag == DW_TAG_variable
12180           || child_die->tag == DW_TAG_inheritance
12181           || child_die->tag == DW_TAG_template_value_param
12182           || child_die->tag == DW_TAG_template_type_param)
12183         {
12184           /* Do nothing.  */
12185         }
12186       else
12187         process_die (child_die, cu);
12188
12189       child_die = sibling_die (child_die);
12190     }
12191
12192   /* Do not consider external references.  According to the DWARF standard,
12193      these DIEs are identified by the fact that they have no byte_size
12194      attribute, and a declaration attribute.  */
12195   if (dwarf2_attr (die, DW_AT_byte_size, cu) != NULL
12196       || !die_is_declaration (die, cu))
12197     new_symbol (die, type, cu);
12198 }
12199
12200 /* Given a DW_AT_enumeration_type die, set its type.  We do not
12201    complete the type's fields yet, or create any symbols.  */
12202
12203 static struct type *
12204 read_enumeration_type (struct die_info *die, struct dwarf2_cu *cu)
12205 {
12206   struct objfile *objfile = cu->objfile;
12207   struct type *type;
12208   struct attribute *attr;
12209   const char *name;
12210
12211   /* If the definition of this type lives in .debug_types, read that type.
12212      Don't follow DW_AT_specification though, that will take us back up
12213      the chain and we want to go down.  */
12214   attr = dwarf2_attr_no_follow (die, DW_AT_signature);
12215   if (attr)
12216     {
12217       type = get_DW_AT_signature_type (die, attr, cu);
12218
12219       /* The type's CU may not be the same as CU.
12220          Ensure TYPE is recorded with CU in die_type_hash.  */
12221       return set_die_type (die, type, cu);
12222     }
12223
12224   type = alloc_type (objfile);
12225
12226   TYPE_CODE (type) = TYPE_CODE_ENUM;
12227   name = dwarf2_full_name (NULL, die, cu);
12228   if (name != NULL)
12229     TYPE_TAG_NAME (type) = name;
12230
12231   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
12232   if (attr)
12233     {
12234       TYPE_LENGTH (type) = DW_UNSND (attr);
12235     }
12236   else
12237     {
12238       TYPE_LENGTH (type) = 0;
12239     }
12240
12241   /* The enumeration DIE can be incomplete.  In Ada, any type can be
12242      declared as private in the package spec, and then defined only
12243      inside the package body.  Such types are known as Taft Amendment
12244      Types.  When another package uses such a type, an incomplete DIE
12245      may be generated by the compiler.  */
12246   if (die_is_declaration (die, cu))
12247     TYPE_STUB (type) = 1;
12248
12249   return set_die_type (die, type, cu);
12250 }
12251
12252 /* Given a pointer to a die which begins an enumeration, process all
12253    the dies that define the members of the enumeration, and create the
12254    symbol for the enumeration type.
12255
12256    NOTE: We reverse the order of the element list.  */
12257
12258 static void
12259 process_enumeration_scope (struct die_info *die, struct dwarf2_cu *cu)
12260 {
12261   struct type *this_type;
12262
12263   this_type = get_die_type (die, cu);
12264   if (this_type == NULL)
12265     this_type = read_enumeration_type (die, cu);
12266
12267   if (die->child != NULL)
12268     {
12269       struct die_info *child_die;
12270       struct symbol *sym;
12271       struct field *fields = NULL;
12272       int num_fields = 0;
12273       int unsigned_enum = 1;
12274       const char *name;
12275       int flag_enum = 1;
12276       ULONGEST mask = 0;
12277
12278       child_die = die->child;
12279       while (child_die && child_die->tag)
12280         {
12281           if (child_die->tag != DW_TAG_enumerator)
12282             {
12283               process_die (child_die, cu);
12284             }
12285           else
12286             {
12287               name = dwarf2_name (child_die, cu);
12288               if (name)
12289                 {
12290                   sym = new_symbol (child_die, this_type, cu);
12291                   if (SYMBOL_VALUE (sym) < 0)
12292                     {
12293                       unsigned_enum = 0;
12294                       flag_enum = 0;
12295                     }
12296                   else if ((mask & SYMBOL_VALUE (sym)) != 0)
12297                     flag_enum = 0;
12298                   else
12299                     mask |= SYMBOL_VALUE (sym);
12300
12301                   if ((num_fields % DW_FIELD_ALLOC_CHUNK) == 0)
12302                     {
12303                       fields = (struct field *)
12304                         xrealloc (fields,
12305                                   (num_fields + DW_FIELD_ALLOC_CHUNK)
12306                                   * sizeof (struct field));
12307                     }
12308
12309                   FIELD_NAME (fields[num_fields]) = SYMBOL_LINKAGE_NAME (sym);
12310                   FIELD_TYPE (fields[num_fields]) = NULL;
12311                   SET_FIELD_ENUMVAL (fields[num_fields], SYMBOL_VALUE (sym));
12312                   FIELD_BITSIZE (fields[num_fields]) = 0;
12313
12314                   num_fields++;
12315                 }
12316             }
12317
12318           child_die = sibling_die (child_die);
12319         }
12320
12321       if (num_fields)
12322         {
12323           TYPE_NFIELDS (this_type) = num_fields;
12324           TYPE_FIELDS (this_type) = (struct field *)
12325             TYPE_ALLOC (this_type, sizeof (struct field) * num_fields);
12326           memcpy (TYPE_FIELDS (this_type), fields,
12327                   sizeof (struct field) * num_fields);
12328           xfree (fields);
12329         }
12330       if (unsigned_enum)
12331         TYPE_UNSIGNED (this_type) = 1;
12332       if (flag_enum)
12333         TYPE_FLAG_ENUM (this_type) = 1;
12334     }
12335
12336   /* If we are reading an enum from a .debug_types unit, and the enum
12337      is a declaration, and the enum is not the signatured type in the
12338      unit, then we do not want to add a symbol for it.  Adding a
12339      symbol would in some cases obscure the true definition of the
12340      enum, giving users an incomplete type when the definition is
12341      actually available.  Note that we do not want to do this for all
12342      enums which are just declarations, because C++0x allows forward
12343      enum declarations.  */
12344   if (cu->per_cu->is_debug_types
12345       && die_is_declaration (die, cu))
12346     {
12347       struct signatured_type *sig_type;
12348
12349       sig_type = (struct signatured_type *) cu->per_cu;
12350       gdb_assert (sig_type->type_offset_in_section.sect_off != 0);
12351       if (sig_type->type_offset_in_section.sect_off != die->offset.sect_off)
12352         return;
12353     }
12354
12355   new_symbol (die, this_type, cu);
12356 }
12357
12358 /* Extract all information from a DW_TAG_array_type DIE and put it in
12359    the DIE's type field.  For now, this only handles one dimensional
12360    arrays.  */
12361
12362 static struct type *
12363 read_array_type (struct die_info *die, struct dwarf2_cu *cu)
12364 {
12365   struct objfile *objfile = cu->objfile;
12366   struct die_info *child_die;
12367   struct type *type;
12368   struct type *element_type, *range_type, *index_type;
12369   struct type **range_types = NULL;
12370   struct attribute *attr;
12371   int ndim = 0;
12372   struct cleanup *back_to;
12373   const char *name;
12374
12375   element_type = die_type (die, cu);
12376
12377   /* The die_type call above may have already set the type for this DIE.  */
12378   type = get_die_type (die, cu);
12379   if (type)
12380     return type;
12381
12382   /* Irix 6.2 native cc creates array types without children for
12383      arrays with unspecified length.  */
12384   if (die->child == NULL)
12385     {
12386       index_type = objfile_type (objfile)->builtin_int;
12387       range_type = create_range_type (NULL, index_type, 0, -1);
12388       type = create_array_type (NULL, element_type, range_type);
12389       return set_die_type (die, type, cu);
12390     }
12391
12392   back_to = make_cleanup (null_cleanup, NULL);
12393   child_die = die->child;
12394   while (child_die && child_die->tag)
12395     {
12396       if (child_die->tag == DW_TAG_subrange_type)
12397         {
12398           struct type *child_type = read_type_die (child_die, cu);
12399
12400           if (child_type != NULL)
12401             {
12402               /* The range type was succesfully read.  Save it for the
12403                  array type creation.  */
12404               if ((ndim % DW_FIELD_ALLOC_CHUNK) == 0)
12405                 {
12406                   range_types = (struct type **)
12407                     xrealloc (range_types, (ndim + DW_FIELD_ALLOC_CHUNK)
12408                               * sizeof (struct type *));
12409                   if (ndim == 0)
12410                     make_cleanup (free_current_contents, &range_types);
12411                 }
12412               range_types[ndim++] = child_type;
12413             }
12414         }
12415       child_die = sibling_die (child_die);
12416     }
12417
12418   /* Dwarf2 dimensions are output from left to right, create the
12419      necessary array types in backwards order.  */
12420
12421   type = element_type;
12422
12423   if (read_array_order (die, cu) == DW_ORD_col_major)
12424     {
12425       int i = 0;
12426
12427       while (i < ndim)
12428         type = create_array_type (NULL, type, range_types[i++]);
12429     }
12430   else
12431     {
12432       while (ndim-- > 0)
12433         type = create_array_type (NULL, type, range_types[ndim]);
12434     }
12435
12436   /* Understand Dwarf2 support for vector types (like they occur on
12437      the PowerPC w/ AltiVec).  Gcc just adds another attribute to the
12438      array type.  This is not part of the Dwarf2/3 standard yet, but a
12439      custom vendor extension.  The main difference between a regular
12440      array and the vector variant is that vectors are passed by value
12441      to functions.  */
12442   attr = dwarf2_attr (die, DW_AT_GNU_vector, cu);
12443   if (attr)
12444     make_vector_type (type);
12445
12446   /* The DIE may have DW_AT_byte_size set.  For example an OpenCL
12447      implementation may choose to implement triple vectors using this
12448      attribute.  */
12449   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
12450   if (attr)
12451     {
12452       if (DW_UNSND (attr) >= TYPE_LENGTH (type))
12453         TYPE_LENGTH (type) = DW_UNSND (attr);
12454       else
12455         complaint (&symfile_complaints,
12456                    _("DW_AT_byte_size for array type smaller "
12457                      "than the total size of elements"));
12458     }
12459
12460   name = dwarf2_name (die, cu);
12461   if (name)
12462     TYPE_NAME (type) = name;
12463
12464   /* Install the type in the die.  */
12465   set_die_type (die, type, cu);
12466
12467   /* set_die_type should be already done.  */
12468   set_descriptive_type (type, die, cu);
12469
12470   do_cleanups (back_to);
12471
12472   return type;
12473 }
12474
12475 static enum dwarf_array_dim_ordering
12476 read_array_order (struct die_info *die, struct dwarf2_cu *cu)
12477 {
12478   struct attribute *attr;
12479
12480   attr = dwarf2_attr (die, DW_AT_ordering, cu);
12481
12482   if (attr) return DW_SND (attr);
12483
12484   /* GNU F77 is a special case, as at 08/2004 array type info is the
12485      opposite order to the dwarf2 specification, but data is still
12486      laid out as per normal fortran.
12487
12488      FIXME: dsl/2004-8-20: If G77 is ever fixed, this will also need
12489      version checking.  */
12490
12491   if (cu->language == language_fortran
12492       && cu->producer && strstr (cu->producer, "GNU F77"))
12493     {
12494       return DW_ORD_row_major;
12495     }
12496
12497   switch (cu->language_defn->la_array_ordering)
12498     {
12499     case array_column_major:
12500       return DW_ORD_col_major;
12501     case array_row_major:
12502     default:
12503       return DW_ORD_row_major;
12504     };
12505 }
12506
12507 /* Extract all information from a DW_TAG_set_type DIE and put it in
12508    the DIE's type field.  */
12509
12510 static struct type *
12511 read_set_type (struct die_info *die, struct dwarf2_cu *cu)
12512 {
12513   struct type *domain_type, *set_type;
12514   struct attribute *attr;
12515
12516   domain_type = die_type (die, cu);
12517
12518   /* The die_type call above may have already set the type for this DIE.  */
12519   set_type = get_die_type (die, cu);
12520   if (set_type)
12521     return set_type;
12522
12523   set_type = create_set_type (NULL, domain_type);
12524
12525   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
12526   if (attr)
12527     TYPE_LENGTH (set_type) = DW_UNSND (attr);
12528
12529   return set_die_type (die, set_type, cu);
12530 }
12531
12532 /* A helper for read_common_block that creates a locexpr baton.
12533    SYM is the symbol which we are marking as computed.
12534    COMMON_DIE is the DIE for the common block.
12535    COMMON_LOC is the location expression attribute for the common
12536    block itself.
12537    MEMBER_LOC is the location expression attribute for the particular
12538    member of the common block that we are processing.
12539    CU is the CU from which the above come.  */
12540
12541 static void
12542 mark_common_block_symbol_computed (struct symbol *sym,
12543                                    struct die_info *common_die,
12544                                    struct attribute *common_loc,
12545                                    struct attribute *member_loc,
12546                                    struct dwarf2_cu *cu)
12547 {
12548   struct objfile *objfile = dwarf2_per_objfile->objfile;
12549   struct dwarf2_locexpr_baton *baton;
12550   gdb_byte *ptr;
12551   unsigned int cu_off;
12552   enum bfd_endian byte_order = gdbarch_byte_order (get_objfile_arch (objfile));
12553   LONGEST offset = 0;
12554
12555   gdb_assert (common_loc && member_loc);
12556   gdb_assert (attr_form_is_block (common_loc));
12557   gdb_assert (attr_form_is_block (member_loc)
12558               || attr_form_is_constant (member_loc));
12559
12560   baton = obstack_alloc (&objfile->objfile_obstack,
12561                          sizeof (struct dwarf2_locexpr_baton));
12562   baton->per_cu = cu->per_cu;
12563   gdb_assert (baton->per_cu);
12564
12565   baton->size = 5 /* DW_OP_call4 */ + 1 /* DW_OP_plus */;
12566
12567   if (attr_form_is_constant (member_loc))
12568     {
12569       offset = dwarf2_get_attr_constant_value (member_loc, 0);
12570       baton->size += 1 /* DW_OP_addr */ + cu->header.addr_size;
12571     }
12572   else
12573     baton->size += DW_BLOCK (member_loc)->size;
12574
12575   ptr = obstack_alloc (&objfile->objfile_obstack, baton->size);
12576   baton->data = ptr;
12577
12578   *ptr++ = DW_OP_call4;
12579   cu_off = common_die->offset.sect_off - cu->per_cu->offset.sect_off;
12580   store_unsigned_integer (ptr, 4, byte_order, cu_off);
12581   ptr += 4;
12582
12583   if (attr_form_is_constant (member_loc))
12584     {
12585       *ptr++ = DW_OP_addr;
12586       store_unsigned_integer (ptr, cu->header.addr_size, byte_order, offset);
12587       ptr += cu->header.addr_size;
12588     }
12589   else
12590     {
12591       /* We have to copy the data here, because DW_OP_call4 will only
12592          use a DW_AT_location attribute.  */
12593       memcpy (ptr, DW_BLOCK (member_loc)->data, DW_BLOCK (member_loc)->size);
12594       ptr += DW_BLOCK (member_loc)->size;
12595     }
12596
12597   *ptr++ = DW_OP_plus;
12598   gdb_assert (ptr - baton->data == baton->size);
12599
12600   SYMBOL_LOCATION_BATON (sym) = baton;
12601   SYMBOL_ACLASS_INDEX (sym) = dwarf2_locexpr_index;
12602 }
12603
12604 /* Create appropriate locally-scoped variables for all the
12605    DW_TAG_common_block entries.  Also create a struct common_block
12606    listing all such variables for `info common'.  COMMON_BLOCK_DOMAIN
12607    is used to sepate the common blocks name namespace from regular
12608    variable names.  */
12609
12610 static void
12611 read_common_block (struct die_info *die, struct dwarf2_cu *cu)
12612 {
12613   struct attribute *attr;
12614
12615   attr = dwarf2_attr (die, DW_AT_location, cu);
12616   if (attr)
12617     {
12618       /* Support the .debug_loc offsets.  */
12619       if (attr_form_is_block (attr))
12620         {
12621           /* Ok.  */
12622         }
12623       else if (attr_form_is_section_offset (attr))
12624         {
12625           dwarf2_complex_location_expr_complaint ();
12626           attr = NULL;
12627         }
12628       else
12629         {
12630           dwarf2_invalid_attrib_class_complaint ("DW_AT_location",
12631                                                  "common block member");
12632           attr = NULL;
12633         }
12634     }
12635
12636   if (die->child != NULL)
12637     {
12638       struct objfile *objfile = cu->objfile;
12639       struct die_info *child_die;
12640       size_t n_entries = 0, size;
12641       struct common_block *common_block;
12642       struct symbol *sym;
12643
12644       for (child_die = die->child;
12645            child_die && child_die->tag;
12646            child_die = sibling_die (child_die))
12647         ++n_entries;
12648
12649       size = (sizeof (struct common_block)
12650               + (n_entries - 1) * sizeof (struct symbol *));
12651       common_block = obstack_alloc (&objfile->objfile_obstack, size);
12652       memset (common_block->contents, 0, n_entries * sizeof (struct symbol *));
12653       common_block->n_entries = 0;
12654
12655       for (child_die = die->child;
12656            child_die && child_die->tag;
12657            child_die = sibling_die (child_die))
12658         {
12659           /* Create the symbol in the DW_TAG_common_block block in the current
12660              symbol scope.  */
12661           sym = new_symbol (child_die, NULL, cu);
12662           if (sym != NULL)
12663             {
12664               struct attribute *member_loc;
12665
12666               common_block->contents[common_block->n_entries++] = sym;
12667
12668               member_loc = dwarf2_attr (child_die, DW_AT_data_member_location,
12669                                         cu);
12670               if (member_loc)
12671                 {
12672                   /* GDB has handled this for a long time, but it is
12673                      not specified by DWARF.  It seems to have been
12674                      emitted by gfortran at least as recently as:
12675                      http://gcc.gnu.org/bugzilla/show_bug.cgi?id=23057.  */
12676                   complaint (&symfile_complaints,
12677                              _("Variable in common block has "
12678                                "DW_AT_data_member_location "
12679                                "- DIE at 0x%x [in module %s]"),
12680                              child_die->offset.sect_off,
12681                              objfile_name (cu->objfile));
12682
12683                   if (attr_form_is_section_offset (member_loc))
12684                     dwarf2_complex_location_expr_complaint ();
12685                   else if (attr_form_is_constant (member_loc)
12686                            || attr_form_is_block (member_loc))
12687                     {
12688                       if (attr)
12689                         mark_common_block_symbol_computed (sym, die, attr,
12690                                                            member_loc, cu);
12691                     }
12692                   else
12693                     dwarf2_complex_location_expr_complaint ();
12694                 }
12695             }
12696         }
12697
12698       sym = new_symbol (die, objfile_type (objfile)->builtin_void, cu);
12699       SYMBOL_VALUE_COMMON_BLOCK (sym) = common_block;
12700     }
12701 }
12702
12703 /* Create a type for a C++ namespace.  */
12704
12705 static struct type *
12706 read_namespace_type (struct die_info *die, struct dwarf2_cu *cu)
12707 {
12708   struct objfile *objfile = cu->objfile;
12709   const char *previous_prefix, *name;
12710   int is_anonymous;
12711   struct type *type;
12712
12713   /* For extensions, reuse the type of the original namespace.  */
12714   if (dwarf2_attr (die, DW_AT_extension, cu) != NULL)
12715     {
12716       struct die_info *ext_die;
12717       struct dwarf2_cu *ext_cu = cu;
12718
12719       ext_die = dwarf2_extension (die, &ext_cu);
12720       type = read_type_die (ext_die, ext_cu);
12721
12722       /* EXT_CU may not be the same as CU.
12723          Ensure TYPE is recorded with CU in die_type_hash.  */
12724       return set_die_type (die, type, cu);
12725     }
12726
12727   name = namespace_name (die, &is_anonymous, cu);
12728
12729   /* Now build the name of the current namespace.  */
12730
12731   previous_prefix = determine_prefix (die, cu);
12732   if (previous_prefix[0] != '\0')
12733     name = typename_concat (&objfile->objfile_obstack,
12734                             previous_prefix, name, 0, cu);
12735
12736   /* Create the type.  */
12737   type = init_type (TYPE_CODE_NAMESPACE, 0, 0, NULL,
12738                     objfile);
12739   TYPE_NAME (type) = name;
12740   TYPE_TAG_NAME (type) = TYPE_NAME (type);
12741
12742   return set_die_type (die, type, cu);
12743 }
12744
12745 /* Read a C++ namespace.  */
12746
12747 static void
12748 read_namespace (struct die_info *die, struct dwarf2_cu *cu)
12749 {
12750   struct objfile *objfile = cu->objfile;
12751   int is_anonymous;
12752
12753   /* Add a symbol associated to this if we haven't seen the namespace
12754      before.  Also, add a using directive if it's an anonymous
12755      namespace.  */
12756
12757   if (dwarf2_attr (die, DW_AT_extension, cu) == NULL)
12758     {
12759       struct type *type;
12760
12761       type = read_type_die (die, cu);
12762       new_symbol (die, type, cu);
12763
12764       namespace_name (die, &is_anonymous, cu);
12765       if (is_anonymous)
12766         {
12767           const char *previous_prefix = determine_prefix (die, cu);
12768
12769           cp_add_using_directive (previous_prefix, TYPE_NAME (type), NULL,
12770                                   NULL, NULL, 0, &objfile->objfile_obstack);
12771         }
12772     }
12773
12774   if (die->child != NULL)
12775     {
12776       struct die_info *child_die = die->child;
12777
12778       while (child_die && child_die->tag)
12779         {
12780           process_die (child_die, cu);
12781           child_die = sibling_die (child_die);
12782         }
12783     }
12784 }
12785
12786 /* Read a Fortran module as type.  This DIE can be only a declaration used for
12787    imported module.  Still we need that type as local Fortran "use ... only"
12788    declaration imports depend on the created type in determine_prefix.  */
12789
12790 static struct type *
12791 read_module_type (struct die_info *die, struct dwarf2_cu *cu)
12792 {
12793   struct objfile *objfile = cu->objfile;
12794   const char *module_name;
12795   struct type *type;
12796
12797   module_name = dwarf2_name (die, cu);
12798   if (!module_name)
12799     complaint (&symfile_complaints,
12800                _("DW_TAG_module has no name, offset 0x%x"),
12801                die->offset.sect_off);
12802   type = init_type (TYPE_CODE_MODULE, 0, 0, module_name, objfile);
12803
12804   /* determine_prefix uses TYPE_TAG_NAME.  */
12805   TYPE_TAG_NAME (type) = TYPE_NAME (type);
12806
12807   return set_die_type (die, type, cu);
12808 }
12809
12810 /* Read a Fortran module.  */
12811
12812 static void
12813 read_module (struct die_info *die, struct dwarf2_cu *cu)
12814 {
12815   struct die_info *child_die = die->child;
12816
12817   while (child_die && child_die->tag)
12818     {
12819       process_die (child_die, cu);
12820       child_die = sibling_die (child_die);
12821     }
12822 }
12823
12824 /* Return the name of the namespace represented by DIE.  Set
12825    *IS_ANONYMOUS to tell whether or not the namespace is an anonymous
12826    namespace.  */
12827
12828 static const char *
12829 namespace_name (struct die_info *die, int *is_anonymous, struct dwarf2_cu *cu)
12830 {
12831   struct die_info *current_die;
12832   const char *name = NULL;
12833
12834   /* Loop through the extensions until we find a name.  */
12835
12836   for (current_die = die;
12837        current_die != NULL;
12838        current_die = dwarf2_extension (die, &cu))
12839     {
12840       name = dwarf2_name (current_die, cu);
12841       if (name != NULL)
12842         break;
12843     }
12844
12845   /* Is it an anonymous namespace?  */
12846
12847   *is_anonymous = (name == NULL);
12848   if (*is_anonymous)
12849     name = CP_ANONYMOUS_NAMESPACE_STR;
12850
12851   return name;
12852 }
12853
12854 /* Extract all information from a DW_TAG_pointer_type DIE and add to
12855    the user defined type vector.  */
12856
12857 static struct type *
12858 read_tag_pointer_type (struct die_info *die, struct dwarf2_cu *cu)
12859 {
12860   struct gdbarch *gdbarch = get_objfile_arch (cu->objfile);
12861   struct comp_unit_head *cu_header = &cu->header;
12862   struct type *type;
12863   struct attribute *attr_byte_size;
12864   struct attribute *attr_address_class;
12865   int byte_size, addr_class;
12866   struct type *target_type;
12867
12868   target_type = die_type (die, cu);
12869
12870   /* The die_type call above may have already set the type for this DIE.  */
12871   type = get_die_type (die, cu);
12872   if (type)
12873     return type;
12874
12875   type = lookup_pointer_type (target_type);
12876
12877   attr_byte_size = dwarf2_attr (die, DW_AT_byte_size, cu);
12878   if (attr_byte_size)
12879     byte_size = DW_UNSND (attr_byte_size);
12880   else
12881     byte_size = cu_header->addr_size;
12882
12883   attr_address_class = dwarf2_attr (die, DW_AT_address_class, cu);
12884   if (attr_address_class)
12885     addr_class = DW_UNSND (attr_address_class);
12886   else
12887     addr_class = DW_ADDR_none;
12888
12889   /* If the pointer size or address class is different than the
12890      default, create a type variant marked as such and set the
12891      length accordingly.  */
12892   if (TYPE_LENGTH (type) != byte_size || addr_class != DW_ADDR_none)
12893     {
12894       if (gdbarch_address_class_type_flags_p (gdbarch))
12895         {
12896           int type_flags;
12897
12898           type_flags = gdbarch_address_class_type_flags
12899                          (gdbarch, byte_size, addr_class);
12900           gdb_assert ((type_flags & ~TYPE_INSTANCE_FLAG_ADDRESS_CLASS_ALL)
12901                       == 0);
12902           type = make_type_with_address_space (type, type_flags);
12903         }
12904       else if (TYPE_LENGTH (type) != byte_size)
12905         {
12906           complaint (&symfile_complaints,
12907                      _("invalid pointer size %d"), byte_size);
12908         }
12909       else
12910         {
12911           /* Should we also complain about unhandled address classes?  */
12912         }
12913     }
12914
12915   TYPE_LENGTH (type) = byte_size;
12916   return set_die_type (die, type, cu);
12917 }
12918
12919 /* Extract all information from a DW_TAG_ptr_to_member_type DIE and add to
12920    the user defined type vector.  */
12921
12922 static struct type *
12923 read_tag_ptr_to_member_type (struct die_info *die, struct dwarf2_cu *cu)
12924 {
12925   struct type *type;
12926   struct type *to_type;
12927   struct type *domain;
12928
12929   to_type = die_type (die, cu);
12930   domain = die_containing_type (die, cu);
12931
12932   /* The calls above may have already set the type for this DIE.  */
12933   type = get_die_type (die, cu);
12934   if (type)
12935     return type;
12936
12937   if (TYPE_CODE (check_typedef (to_type)) == TYPE_CODE_METHOD)
12938     type = lookup_methodptr_type (to_type);
12939   else if (TYPE_CODE (check_typedef (to_type)) == TYPE_CODE_FUNC)
12940     {
12941       struct type *new_type = alloc_type (cu->objfile);
12942
12943       smash_to_method_type (new_type, domain, TYPE_TARGET_TYPE (to_type),
12944                             TYPE_FIELDS (to_type), TYPE_NFIELDS (to_type),
12945                             TYPE_VARARGS (to_type));
12946       type = lookup_methodptr_type (new_type);
12947     }
12948   else
12949     type = lookup_memberptr_type (to_type, domain);
12950
12951   return set_die_type (die, type, cu);
12952 }
12953
12954 /* Extract all information from a DW_TAG_reference_type DIE and add to
12955    the user defined type vector.  */
12956
12957 static struct type *
12958 read_tag_reference_type (struct die_info *die, struct dwarf2_cu *cu)
12959 {
12960   struct comp_unit_head *cu_header = &cu->header;
12961   struct type *type, *target_type;
12962   struct attribute *attr;
12963
12964   target_type = die_type (die, cu);
12965
12966   /* The die_type call above may have already set the type for this DIE.  */
12967   type = get_die_type (die, cu);
12968   if (type)
12969     return type;
12970
12971   type = lookup_reference_type (target_type);
12972   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
12973   if (attr)
12974     {
12975       TYPE_LENGTH (type) = DW_UNSND (attr);
12976     }
12977   else
12978     {
12979       TYPE_LENGTH (type) = cu_header->addr_size;
12980     }
12981   return set_die_type (die, type, cu);
12982 }
12983
12984 static struct type *
12985 read_tag_const_type (struct die_info *die, struct dwarf2_cu *cu)
12986 {
12987   struct type *base_type, *cv_type;
12988
12989   base_type = die_type (die, cu);
12990
12991   /* The die_type call above may have already set the type for this DIE.  */
12992   cv_type = get_die_type (die, cu);
12993   if (cv_type)
12994     return cv_type;
12995
12996   /* In case the const qualifier is applied to an array type, the element type
12997      is so qualified, not the array type (section 6.7.3 of C99).  */
12998   if (TYPE_CODE (base_type) == TYPE_CODE_ARRAY)
12999     {
13000       struct type *el_type, *inner_array;
13001
13002       base_type = copy_type (base_type);
13003       inner_array = base_type;
13004
13005       while (TYPE_CODE (TYPE_TARGET_TYPE (inner_array)) == TYPE_CODE_ARRAY)
13006         {
13007           TYPE_TARGET_TYPE (inner_array) =
13008             copy_type (TYPE_TARGET_TYPE (inner_array));
13009           inner_array = TYPE_TARGET_TYPE (inner_array);
13010         }
13011
13012       el_type = TYPE_TARGET_TYPE (inner_array);
13013       TYPE_TARGET_TYPE (inner_array) =
13014         make_cv_type (1, TYPE_VOLATILE (el_type), el_type, NULL);
13015
13016       return set_die_type (die, base_type, cu);
13017     }
13018
13019   cv_type = make_cv_type (1, TYPE_VOLATILE (base_type), base_type, 0);
13020   return set_die_type (die, cv_type, cu);
13021 }
13022
13023 static struct type *
13024 read_tag_volatile_type (struct die_info *die, struct dwarf2_cu *cu)
13025 {
13026   struct type *base_type, *cv_type;
13027
13028   base_type = die_type (die, cu);
13029
13030   /* The die_type call above may have already set the type for this DIE.  */
13031   cv_type = get_die_type (die, cu);
13032   if (cv_type)
13033     return cv_type;
13034
13035   cv_type = make_cv_type (TYPE_CONST (base_type), 1, base_type, 0);
13036   return set_die_type (die, cv_type, cu);
13037 }
13038
13039 /* Handle DW_TAG_restrict_type.  */
13040
13041 static struct type *
13042 read_tag_restrict_type (struct die_info *die, struct dwarf2_cu *cu)
13043 {
13044   struct type *base_type, *cv_type;
13045
13046   base_type = die_type (die, cu);
13047
13048   /* The die_type call above may have already set the type for this DIE.  */
13049   cv_type = get_die_type (die, cu);
13050   if (cv_type)
13051     return cv_type;
13052
13053   cv_type = make_restrict_type (base_type);
13054   return set_die_type (die, cv_type, cu);
13055 }
13056
13057 /* Extract all information from a DW_TAG_string_type DIE and add to
13058    the user defined type vector.  It isn't really a user defined type,
13059    but it behaves like one, with other DIE's using an AT_user_def_type
13060    attribute to reference it.  */
13061
13062 static struct type *
13063 read_tag_string_type (struct die_info *die, struct dwarf2_cu *cu)
13064 {
13065   struct objfile *objfile = cu->objfile;
13066   struct gdbarch *gdbarch = get_objfile_arch (objfile);
13067   struct type *type, *range_type, *index_type, *char_type;
13068   struct attribute *attr;
13069   unsigned int length;
13070
13071   attr = dwarf2_attr (die, DW_AT_string_length, cu);
13072   if (attr)
13073     {
13074       length = DW_UNSND (attr);
13075     }
13076   else
13077     {
13078       /* Check for the DW_AT_byte_size attribute.  */
13079       attr = dwarf2_attr (die, DW_AT_byte_size, cu);
13080       if (attr)
13081         {
13082           length = DW_UNSND (attr);
13083         }
13084       else
13085         {
13086           length = 1;
13087         }
13088     }
13089
13090   index_type = objfile_type (objfile)->builtin_int;
13091   range_type = create_range_type (NULL, index_type, 1, length);
13092   char_type = language_string_char_type (cu->language_defn, gdbarch);
13093   type = create_string_type (NULL, char_type, range_type);
13094
13095   return set_die_type (die, type, cu);
13096 }
13097
13098 /* Assuming that DIE corresponds to a function, returns nonzero
13099    if the function is prototyped.  */
13100
13101 static int
13102 prototyped_function_p (struct die_info *die, struct dwarf2_cu *cu)
13103 {
13104   struct attribute *attr;
13105
13106   attr = dwarf2_attr (die, DW_AT_prototyped, cu);
13107   if (attr && (DW_UNSND (attr) != 0))
13108     return 1;
13109
13110   /* The DWARF standard implies that the DW_AT_prototyped attribute
13111      is only meaninful for C, but the concept also extends to other
13112      languages that allow unprototyped functions (Eg: Objective C).
13113      For all other languages, assume that functions are always
13114      prototyped.  */
13115   if (cu->language != language_c
13116       && cu->language != language_objc
13117       && cu->language != language_opencl)
13118     return 1;
13119
13120   /* RealView does not emit DW_AT_prototyped.  We can not distinguish
13121      prototyped and unprototyped functions; default to prototyped,
13122      since that is more common in modern code (and RealView warns
13123      about unprototyped functions).  */
13124   if (producer_is_realview (cu->producer))
13125     return 1;
13126
13127   return 0;
13128 }
13129
13130 /* Handle DIES due to C code like:
13131
13132    struct foo
13133    {
13134    int (*funcp)(int a, long l);
13135    int b;
13136    };
13137
13138    ('funcp' generates a DW_TAG_subroutine_type DIE).  */
13139
13140 static struct type *
13141 read_subroutine_type (struct die_info *die, struct dwarf2_cu *cu)
13142 {
13143   struct objfile *objfile = cu->objfile;
13144   struct type *type;            /* Type that this function returns.  */
13145   struct type *ftype;           /* Function that returns above type.  */
13146   struct attribute *attr;
13147
13148   type = die_type (die, cu);
13149
13150   /* The die_type call above may have already set the type for this DIE.  */
13151   ftype = get_die_type (die, cu);
13152   if (ftype)
13153     return ftype;
13154
13155   ftype = lookup_function_type (type);
13156
13157   if (prototyped_function_p (die, cu))
13158     TYPE_PROTOTYPED (ftype) = 1;
13159
13160   /* Store the calling convention in the type if it's available in
13161      the subroutine die.  Otherwise set the calling convention to
13162      the default value DW_CC_normal.  */
13163   attr = dwarf2_attr (die, DW_AT_calling_convention, cu);
13164   if (attr)
13165     TYPE_CALLING_CONVENTION (ftype) = DW_UNSND (attr);
13166   else if (cu->producer && strstr (cu->producer, "IBM XL C for OpenCL"))
13167     TYPE_CALLING_CONVENTION (ftype) = DW_CC_GDB_IBM_OpenCL;
13168   else
13169     TYPE_CALLING_CONVENTION (ftype) = DW_CC_normal;
13170
13171   /* We need to add the subroutine type to the die immediately so
13172      we don't infinitely recurse when dealing with parameters
13173      declared as the same subroutine type.  */
13174   set_die_type (die, ftype, cu);
13175
13176   if (die->child != NULL)
13177     {
13178       struct type *void_type = objfile_type (objfile)->builtin_void;
13179       struct die_info *child_die;
13180       int nparams, iparams;
13181
13182       /* Count the number of parameters.
13183          FIXME: GDB currently ignores vararg functions, but knows about
13184          vararg member functions.  */
13185       nparams = 0;
13186       child_die = die->child;
13187       while (child_die && child_die->tag)
13188         {
13189           if (child_die->tag == DW_TAG_formal_parameter)
13190             nparams++;
13191           else if (child_die->tag == DW_TAG_unspecified_parameters)
13192             TYPE_VARARGS (ftype) = 1;
13193           child_die = sibling_die (child_die);
13194         }
13195
13196       /* Allocate storage for parameters and fill them in.  */
13197       TYPE_NFIELDS (ftype) = nparams;
13198       TYPE_FIELDS (ftype) = (struct field *)
13199         TYPE_ZALLOC (ftype, nparams * sizeof (struct field));
13200
13201       /* TYPE_FIELD_TYPE must never be NULL.  Pre-fill the array to ensure it
13202          even if we error out during the parameters reading below.  */
13203       for (iparams = 0; iparams < nparams; iparams++)
13204         TYPE_FIELD_TYPE (ftype, iparams) = void_type;
13205
13206       iparams = 0;
13207       child_die = die->child;
13208       while (child_die && child_die->tag)
13209         {
13210           if (child_die->tag == DW_TAG_formal_parameter)
13211             {
13212               struct type *arg_type;
13213
13214               /* DWARF version 2 has no clean way to discern C++
13215                  static and non-static member functions.  G++ helps
13216                  GDB by marking the first parameter for non-static
13217                  member functions (which is the this pointer) as
13218                  artificial.  We pass this information to
13219                  dwarf2_add_member_fn via TYPE_FIELD_ARTIFICIAL.
13220
13221                  DWARF version 3 added DW_AT_object_pointer, which GCC
13222                  4.5 does not yet generate.  */
13223               attr = dwarf2_attr (child_die, DW_AT_artificial, cu);
13224               if (attr)
13225                 TYPE_FIELD_ARTIFICIAL (ftype, iparams) = DW_UNSND (attr);
13226               else
13227                 {
13228                   TYPE_FIELD_ARTIFICIAL (ftype, iparams) = 0;
13229
13230                   /* GCC/43521: In java, the formal parameter
13231                      "this" is sometimes not marked with DW_AT_artificial.  */
13232                   if (cu->language == language_java)
13233                     {
13234                       const char *name = dwarf2_name (child_die, cu);
13235
13236                       if (name && !strcmp (name, "this"))
13237                         TYPE_FIELD_ARTIFICIAL (ftype, iparams) = 1;
13238                     }
13239                 }
13240               arg_type = die_type (child_die, cu);
13241
13242               /* RealView does not mark THIS as const, which the testsuite
13243                  expects.  GCC marks THIS as const in method definitions,
13244                  but not in the class specifications (GCC PR 43053).  */
13245               if (cu->language == language_cplus && !TYPE_CONST (arg_type)
13246                   && TYPE_FIELD_ARTIFICIAL (ftype, iparams))
13247                 {
13248                   int is_this = 0;
13249                   struct dwarf2_cu *arg_cu = cu;
13250                   const char *name = dwarf2_name (child_die, cu);
13251
13252                   attr = dwarf2_attr (die, DW_AT_object_pointer, cu);
13253                   if (attr)
13254                     {
13255                       /* If the compiler emits this, use it.  */
13256                       if (follow_die_ref (die, attr, &arg_cu) == child_die)
13257                         is_this = 1;
13258                     }
13259                   else if (name && strcmp (name, "this") == 0)
13260                     /* Function definitions will have the argument names.  */
13261                     is_this = 1;
13262                   else if (name == NULL && iparams == 0)
13263                     /* Declarations may not have the names, so like
13264                        elsewhere in GDB, assume an artificial first
13265                        argument is "this".  */
13266                     is_this = 1;
13267
13268                   if (is_this)
13269                     arg_type = make_cv_type (1, TYPE_VOLATILE (arg_type),
13270                                              arg_type, 0);
13271                 }
13272
13273               TYPE_FIELD_TYPE (ftype, iparams) = arg_type;
13274               iparams++;
13275             }
13276           child_die = sibling_die (child_die);
13277         }
13278     }
13279
13280   return ftype;
13281 }
13282
13283 static struct type *
13284 read_typedef (struct die_info *die, struct dwarf2_cu *cu)
13285 {
13286   struct objfile *objfile = cu->objfile;
13287   const char *name = NULL;
13288   struct type *this_type, *target_type;
13289
13290   name = dwarf2_full_name (NULL, die, cu);
13291   this_type = init_type (TYPE_CODE_TYPEDEF, 0,
13292                          TYPE_FLAG_TARGET_STUB, NULL, objfile);
13293   TYPE_NAME (this_type) = name;
13294   set_die_type (die, this_type, cu);
13295   target_type = die_type (die, cu);
13296   if (target_type != this_type)
13297     TYPE_TARGET_TYPE (this_type) = target_type;
13298   else
13299     {
13300       /* Self-referential typedefs are, it seems, not allowed by the DWARF
13301          spec and cause infinite loops in GDB.  */
13302       complaint (&symfile_complaints,
13303                  _("Self-referential DW_TAG_typedef "
13304                    "- DIE at 0x%x [in module %s]"),
13305                  die->offset.sect_off, objfile_name (objfile));
13306       TYPE_TARGET_TYPE (this_type) = NULL;
13307     }
13308   return this_type;
13309 }
13310
13311 /* Find a representation of a given base type and install
13312    it in the TYPE field of the die.  */
13313
13314 static struct type *
13315 read_base_type (struct die_info *die, struct dwarf2_cu *cu)
13316 {
13317   struct objfile *objfile = cu->objfile;
13318   struct type *type;
13319   struct attribute *attr;
13320   int encoding = 0, size = 0;
13321   const char *name;
13322   enum type_code code = TYPE_CODE_INT;
13323   int type_flags = 0;
13324   struct type *target_type = NULL;
13325
13326   attr = dwarf2_attr (die, DW_AT_encoding, cu);
13327   if (attr)
13328     {
13329       encoding = DW_UNSND (attr);
13330     }
13331   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
13332   if (attr)
13333     {
13334       size = DW_UNSND (attr);
13335     }
13336   name = dwarf2_name (die, cu);
13337   if (!name)
13338     {
13339       complaint (&symfile_complaints,
13340                  _("DW_AT_name missing from DW_TAG_base_type"));
13341     }
13342
13343   switch (encoding)
13344     {
13345       case DW_ATE_address:
13346         /* Turn DW_ATE_address into a void * pointer.  */
13347         code = TYPE_CODE_PTR;
13348         type_flags |= TYPE_FLAG_UNSIGNED;
13349         target_type = init_type (TYPE_CODE_VOID, 1, 0, NULL, objfile);
13350         break;
13351       case DW_ATE_boolean:
13352         code = TYPE_CODE_BOOL;
13353         type_flags |= TYPE_FLAG_UNSIGNED;
13354         break;
13355       case DW_ATE_complex_float:
13356         code = TYPE_CODE_COMPLEX;
13357         target_type = init_type (TYPE_CODE_FLT, size / 2, 0, NULL, objfile);
13358         break;
13359       case DW_ATE_decimal_float:
13360         code = TYPE_CODE_DECFLOAT;
13361         break;
13362       case DW_ATE_float:
13363         code = TYPE_CODE_FLT;
13364         break;
13365       case DW_ATE_signed:
13366         break;
13367       case DW_ATE_unsigned:
13368         type_flags |= TYPE_FLAG_UNSIGNED;
13369         if (cu->language == language_fortran
13370             && name
13371             && strncmp (name, "character(", sizeof ("character(") - 1) == 0)
13372           code = TYPE_CODE_CHAR;
13373         break;
13374       case DW_ATE_signed_char:
13375         if (cu->language == language_ada || cu->language == language_m2
13376             || cu->language == language_pascal
13377             || cu->language == language_fortran)
13378           code = TYPE_CODE_CHAR;
13379         break;
13380       case DW_ATE_unsigned_char:
13381         if (cu->language == language_ada || cu->language == language_m2
13382             || cu->language == language_pascal
13383             || cu->language == language_fortran)
13384           code = TYPE_CODE_CHAR;
13385         type_flags |= TYPE_FLAG_UNSIGNED;
13386         break;
13387       case DW_ATE_UTF:
13388         /* We just treat this as an integer and then recognize the
13389            type by name elsewhere.  */
13390         break;
13391
13392       default:
13393         complaint (&symfile_complaints, _("unsupported DW_AT_encoding: '%s'"),
13394                    dwarf_type_encoding_name (encoding));
13395         break;
13396     }
13397
13398   type = init_type (code, size, type_flags, NULL, objfile);
13399   TYPE_NAME (type) = name;
13400   TYPE_TARGET_TYPE (type) = target_type;
13401
13402   if (name && strcmp (name, "char") == 0)
13403     TYPE_NOSIGN (type) = 1;
13404
13405   return set_die_type (die, type, cu);
13406 }
13407
13408 /* Read the given DW_AT_subrange DIE.  */
13409
13410 static struct type *
13411 read_subrange_type (struct die_info *die, struct dwarf2_cu *cu)
13412 {
13413   struct type *base_type, *orig_base_type;
13414   struct type *range_type;
13415   struct attribute *attr;
13416   LONGEST low, high;
13417   int low_default_is_valid;
13418   const char *name;
13419   LONGEST negative_mask;
13420
13421   orig_base_type = die_type (die, cu);
13422   /* If ORIG_BASE_TYPE is a typedef, it will not be TYPE_UNSIGNED,
13423      whereas the real type might be.  So, we use ORIG_BASE_TYPE when
13424      creating the range type, but we use the result of check_typedef
13425      when examining properties of the type.  */
13426   base_type = check_typedef (orig_base_type);
13427
13428   /* The die_type call above may have already set the type for this DIE.  */
13429   range_type = get_die_type (die, cu);
13430   if (range_type)
13431     return range_type;
13432
13433   /* Set LOW_DEFAULT_IS_VALID if current language and DWARF version allow
13434      omitting DW_AT_lower_bound.  */
13435   switch (cu->language)
13436     {
13437     case language_c:
13438     case language_cplus:
13439       low = 0;
13440       low_default_is_valid = 1;
13441       break;
13442     case language_fortran:
13443       low = 1;
13444       low_default_is_valid = 1;
13445       break;
13446     case language_d:
13447     case language_java:
13448     case language_objc:
13449       low = 0;
13450       low_default_is_valid = (cu->header.version >= 4);
13451       break;
13452     case language_ada:
13453     case language_m2:
13454     case language_pascal:
13455       low = 1;
13456       low_default_is_valid = (cu->header.version >= 4);
13457       break;
13458     default:
13459       low = 0;
13460       low_default_is_valid = 0;
13461       break;
13462     }
13463
13464   /* FIXME: For variable sized arrays either of these could be
13465      a variable rather than a constant value.  We'll allow it,
13466      but we don't know how to handle it.  */
13467   attr = dwarf2_attr (die, DW_AT_lower_bound, cu);
13468   if (attr)
13469     low = dwarf2_get_attr_constant_value (attr, low);
13470   else if (!low_default_is_valid)
13471     complaint (&symfile_complaints, _("Missing DW_AT_lower_bound "
13472                                       "- DIE at 0x%x [in module %s]"),
13473                die->offset.sect_off, objfile_name (cu->objfile));
13474
13475   attr = dwarf2_attr (die, DW_AT_upper_bound, cu);
13476   if (attr)
13477     {
13478       if (attr_form_is_block (attr) || attr_form_is_ref (attr))
13479         {
13480           /* GCC encodes arrays with unspecified or dynamic length
13481              with a DW_FORM_block1 attribute or a reference attribute.
13482              FIXME: GDB does not yet know how to handle dynamic
13483              arrays properly, treat them as arrays with unspecified
13484              length for now.
13485
13486              FIXME: jimb/2003-09-22: GDB does not really know
13487              how to handle arrays of unspecified length
13488              either; we just represent them as zero-length
13489              arrays.  Choose an appropriate upper bound given
13490              the lower bound we've computed above.  */
13491           high = low - 1;
13492         }
13493       else
13494         high = dwarf2_get_attr_constant_value (attr, 1);
13495     }
13496   else
13497     {
13498       attr = dwarf2_attr (die, DW_AT_count, cu);
13499       if (attr)
13500         {
13501           int count = dwarf2_get_attr_constant_value (attr, 1);
13502           high = low + count - 1;
13503         }
13504       else
13505         {
13506           /* Unspecified array length.  */
13507           high = low - 1;
13508         }
13509     }
13510
13511   /* Dwarf-2 specifications explicitly allows to create subrange types
13512      without specifying a base type.
13513      In that case, the base type must be set to the type of
13514      the lower bound, upper bound or count, in that order, if any of these
13515      three attributes references an object that has a type.
13516      If no base type is found, the Dwarf-2 specifications say that
13517      a signed integer type of size equal to the size of an address should
13518      be used.
13519      For the following C code: `extern char gdb_int [];'
13520      GCC produces an empty range DIE.
13521      FIXME: muller/2010-05-28: Possible references to object for low bound,
13522      high bound or count are not yet handled by this code.  */
13523   if (TYPE_CODE (base_type) == TYPE_CODE_VOID)
13524     {
13525       struct objfile *objfile = cu->objfile;
13526       struct gdbarch *gdbarch = get_objfile_arch (objfile);
13527       int addr_size = gdbarch_addr_bit (gdbarch) /8;
13528       struct type *int_type = objfile_type (objfile)->builtin_int;
13529
13530       /* Test "int", "long int", and "long long int" objfile types,
13531          and select the first one having a size above or equal to the
13532          architecture address size.  */
13533       if (int_type && TYPE_LENGTH (int_type) >= addr_size)
13534         base_type = int_type;
13535       else
13536         {
13537           int_type = objfile_type (objfile)->builtin_long;
13538           if (int_type && TYPE_LENGTH (int_type) >= addr_size)
13539             base_type = int_type;
13540           else
13541             {
13542               int_type = objfile_type (objfile)->builtin_long_long;
13543               if (int_type && TYPE_LENGTH (int_type) >= addr_size)
13544                 base_type = int_type;
13545             }
13546         }
13547     }
13548
13549   negative_mask =
13550     (LONGEST) -1 << (TYPE_LENGTH (base_type) * TARGET_CHAR_BIT - 1);
13551   if (!TYPE_UNSIGNED (base_type) && (low & negative_mask))
13552     low |= negative_mask;
13553   if (!TYPE_UNSIGNED (base_type) && (high & negative_mask))
13554     high |= negative_mask;
13555
13556   range_type = create_range_type (NULL, orig_base_type, low, high);
13557
13558   /* Mark arrays with dynamic length at least as an array of unspecified
13559      length.  GDB could check the boundary but before it gets implemented at
13560      least allow accessing the array elements.  */
13561   if (attr && attr_form_is_block (attr))
13562     TYPE_HIGH_BOUND_UNDEFINED (range_type) = 1;
13563
13564   /* Ada expects an empty array on no boundary attributes.  */
13565   if (attr == NULL && cu->language != language_ada)
13566     TYPE_HIGH_BOUND_UNDEFINED (range_type) = 1;
13567
13568   name = dwarf2_name (die, cu);
13569   if (name)
13570     TYPE_NAME (range_type) = name;
13571
13572   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
13573   if (attr)
13574     TYPE_LENGTH (range_type) = DW_UNSND (attr);
13575
13576   set_die_type (die, range_type, cu);
13577
13578   /* set_die_type should be already done.  */
13579   set_descriptive_type (range_type, die, cu);
13580
13581   return range_type;
13582 }
13583
13584 static struct type *
13585 read_unspecified_type (struct die_info *die, struct dwarf2_cu *cu)
13586 {
13587   struct type *type;
13588
13589   /* For now, we only support the C meaning of an unspecified type: void.  */
13590
13591   type = init_type (TYPE_CODE_VOID, 0, 0, NULL, cu->objfile);
13592   TYPE_NAME (type) = dwarf2_name (die, cu);
13593
13594   return set_die_type (die, type, cu);
13595 }
13596
13597 /* Read a single die and all its descendents.  Set the die's sibling
13598    field to NULL; set other fields in the die correctly, and set all
13599    of the descendents' fields correctly.  Set *NEW_INFO_PTR to the
13600    location of the info_ptr after reading all of those dies.  PARENT
13601    is the parent of the die in question.  */
13602
13603 static struct die_info *
13604 read_die_and_children (const struct die_reader_specs *reader,
13605                        const gdb_byte *info_ptr,
13606                        const gdb_byte **new_info_ptr,
13607                        struct die_info *parent)
13608 {
13609   struct die_info *die;
13610   const gdb_byte *cur_ptr;
13611   int has_children;
13612
13613   cur_ptr = read_full_die_1 (reader, &die, info_ptr, &has_children, 0);
13614   if (die == NULL)
13615     {
13616       *new_info_ptr = cur_ptr;
13617       return NULL;
13618     }
13619   store_in_ref_table (die, reader->cu);
13620
13621   if (has_children)
13622     die->child = read_die_and_siblings_1 (reader, cur_ptr, new_info_ptr, die);
13623   else
13624     {
13625       die->child = NULL;
13626       *new_info_ptr = cur_ptr;
13627     }
13628
13629   die->sibling = NULL;
13630   die->parent = parent;
13631   return die;
13632 }
13633
13634 /* Read a die, all of its descendents, and all of its siblings; set
13635    all of the fields of all of the dies correctly.  Arguments are as
13636    in read_die_and_children.  */
13637
13638 static struct die_info *
13639 read_die_and_siblings_1 (const struct die_reader_specs *reader,
13640                          const gdb_byte *info_ptr,
13641                          const gdb_byte **new_info_ptr,
13642                          struct die_info *parent)
13643 {
13644   struct die_info *first_die, *last_sibling;
13645   const gdb_byte *cur_ptr;
13646
13647   cur_ptr = info_ptr;
13648   first_die = last_sibling = NULL;
13649
13650   while (1)
13651     {
13652       struct die_info *die
13653         = read_die_and_children (reader, cur_ptr, &cur_ptr, parent);
13654
13655       if (die == NULL)
13656         {
13657           *new_info_ptr = cur_ptr;
13658           return first_die;
13659         }
13660
13661       if (!first_die)
13662         first_die = die;
13663       else
13664         last_sibling->sibling = die;
13665
13666       last_sibling = die;
13667     }
13668 }
13669
13670 /* Read a die, all of its descendents, and all of its siblings; set
13671    all of the fields of all of the dies correctly.  Arguments are as
13672    in read_die_and_children.
13673    This the main entry point for reading a DIE and all its children.  */
13674
13675 static struct die_info *
13676 read_die_and_siblings (const struct die_reader_specs *reader,
13677                        const gdb_byte *info_ptr,
13678                        const gdb_byte **new_info_ptr,
13679                        struct die_info *parent)
13680 {
13681   struct die_info *die = read_die_and_siblings_1 (reader, info_ptr,
13682                                                   new_info_ptr, parent);
13683
13684   if (dwarf2_die_debug)
13685     {
13686       fprintf_unfiltered (gdb_stdlog,
13687                           "Read die from %s@0x%x of %s:\n",
13688                           bfd_section_name (reader->abfd,
13689                                             reader->die_section->asection),
13690                           (unsigned) (info_ptr - reader->die_section->buffer),
13691                           bfd_get_filename (reader->abfd));
13692       dump_die (die, dwarf2_die_debug);
13693     }
13694
13695   return die;
13696 }
13697
13698 /* Read a die and all its attributes, leave space for NUM_EXTRA_ATTRS
13699    attributes.
13700    The caller is responsible for filling in the extra attributes
13701    and updating (*DIEP)->num_attrs.
13702    Set DIEP to point to a newly allocated die with its information,
13703    except for its child, sibling, and parent fields.
13704    Set HAS_CHILDREN to tell whether the die has children or not.  */
13705
13706 static const gdb_byte *
13707 read_full_die_1 (const struct die_reader_specs *reader,
13708                  struct die_info **diep, const gdb_byte *info_ptr,
13709                  int *has_children, int num_extra_attrs)
13710 {
13711   unsigned int abbrev_number, bytes_read, i;
13712   sect_offset offset;
13713   struct abbrev_info *abbrev;
13714   struct die_info *die;
13715   struct dwarf2_cu *cu = reader->cu;
13716   bfd *abfd = reader->abfd;
13717
13718   offset.sect_off = info_ptr - reader->buffer;
13719   abbrev_number = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
13720   info_ptr += bytes_read;
13721   if (!abbrev_number)
13722     {
13723       *diep = NULL;
13724       *has_children = 0;
13725       return info_ptr;
13726     }
13727
13728   abbrev = abbrev_table_lookup_abbrev (cu->abbrev_table, abbrev_number);
13729   if (!abbrev)
13730     error (_("Dwarf Error: could not find abbrev number %d [in module %s]"),
13731            abbrev_number,
13732            bfd_get_filename (abfd));
13733
13734   die = dwarf_alloc_die (cu, abbrev->num_attrs + num_extra_attrs);
13735   die->offset = offset;
13736   die->tag = abbrev->tag;
13737   die->abbrev = abbrev_number;
13738
13739   /* Make the result usable.
13740      The caller needs to update num_attrs after adding the extra
13741      attributes.  */
13742   die->num_attrs = abbrev->num_attrs;
13743
13744   for (i = 0; i < abbrev->num_attrs; ++i)
13745     info_ptr = read_attribute (reader, &die->attrs[i], &abbrev->attrs[i],
13746                                info_ptr);
13747
13748   *diep = die;
13749   *has_children = abbrev->has_children;
13750   return info_ptr;
13751 }
13752
13753 /* Read a die and all its attributes.
13754    Set DIEP to point to a newly allocated die with its information,
13755    except for its child, sibling, and parent fields.
13756    Set HAS_CHILDREN to tell whether the die has children or not.  */
13757
13758 static const gdb_byte *
13759 read_full_die (const struct die_reader_specs *reader,
13760                struct die_info **diep, const gdb_byte *info_ptr,
13761                int *has_children)
13762 {
13763   const gdb_byte *result;
13764
13765   result = read_full_die_1 (reader, diep, info_ptr, has_children, 0);
13766
13767   if (dwarf2_die_debug)
13768     {
13769       fprintf_unfiltered (gdb_stdlog,
13770                           "Read die from %s@0x%x of %s:\n",
13771                           bfd_section_name (reader->abfd,
13772                                             reader->die_section->asection),
13773                           (unsigned) (info_ptr - reader->die_section->buffer),
13774                           bfd_get_filename (reader->abfd));
13775       dump_die (*diep, dwarf2_die_debug);
13776     }
13777
13778   return result;
13779 }
13780 \f
13781 /* Abbreviation tables.
13782
13783    In DWARF version 2, the description of the debugging information is
13784    stored in a separate .debug_abbrev section.  Before we read any
13785    dies from a section we read in all abbreviations and install them
13786    in a hash table.  */
13787
13788 /* Allocate space for a struct abbrev_info object in ABBREV_TABLE.  */
13789
13790 static struct abbrev_info *
13791 abbrev_table_alloc_abbrev (struct abbrev_table *abbrev_table)
13792 {
13793   struct abbrev_info *abbrev;
13794
13795   abbrev = (struct abbrev_info *)
13796     obstack_alloc (&abbrev_table->abbrev_obstack, sizeof (struct abbrev_info));
13797   memset (abbrev, 0, sizeof (struct abbrev_info));
13798   return abbrev;
13799 }
13800
13801 /* Add an abbreviation to the table.  */
13802
13803 static void
13804 abbrev_table_add_abbrev (struct abbrev_table *abbrev_table,
13805                          unsigned int abbrev_number,
13806                          struct abbrev_info *abbrev)
13807 {
13808   unsigned int hash_number;
13809
13810   hash_number = abbrev_number % ABBREV_HASH_SIZE;
13811   abbrev->next = abbrev_table->abbrevs[hash_number];
13812   abbrev_table->abbrevs[hash_number] = abbrev;
13813 }
13814
13815 /* Look up an abbrev in the table.
13816    Returns NULL if the abbrev is not found.  */
13817
13818 static struct abbrev_info *
13819 abbrev_table_lookup_abbrev (const struct abbrev_table *abbrev_table,
13820                             unsigned int abbrev_number)
13821 {
13822   unsigned int hash_number;
13823   struct abbrev_info *abbrev;
13824
13825   hash_number = abbrev_number % ABBREV_HASH_SIZE;
13826   abbrev = abbrev_table->abbrevs[hash_number];
13827
13828   while (abbrev)
13829     {
13830       if (abbrev->number == abbrev_number)
13831         return abbrev;
13832       abbrev = abbrev->next;
13833     }
13834   return NULL;
13835 }
13836
13837 /* Read in an abbrev table.  */
13838
13839 static struct abbrev_table *
13840 abbrev_table_read_table (struct dwarf2_section_info *section,
13841                          sect_offset offset)
13842 {
13843   struct objfile *objfile = dwarf2_per_objfile->objfile;
13844   bfd *abfd = section->asection->owner;
13845   struct abbrev_table *abbrev_table;
13846   const gdb_byte *abbrev_ptr;
13847   struct abbrev_info *cur_abbrev;
13848   unsigned int abbrev_number, bytes_read, abbrev_name;
13849   unsigned int abbrev_form;
13850   struct attr_abbrev *cur_attrs;
13851   unsigned int allocated_attrs;
13852
13853   abbrev_table = XMALLOC (struct abbrev_table);
13854   abbrev_table->offset = offset;
13855   obstack_init (&abbrev_table->abbrev_obstack);
13856   abbrev_table->abbrevs = obstack_alloc (&abbrev_table->abbrev_obstack,
13857                                          (ABBREV_HASH_SIZE
13858                                           * sizeof (struct abbrev_info *)));
13859   memset (abbrev_table->abbrevs, 0,
13860           ABBREV_HASH_SIZE * sizeof (struct abbrev_info *));
13861
13862   dwarf2_read_section (objfile, section);
13863   abbrev_ptr = section->buffer + offset.sect_off;
13864   abbrev_number = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
13865   abbrev_ptr += bytes_read;
13866
13867   allocated_attrs = ATTR_ALLOC_CHUNK;
13868   cur_attrs = xmalloc (allocated_attrs * sizeof (struct attr_abbrev));
13869
13870   /* Loop until we reach an abbrev number of 0.  */
13871   while (abbrev_number)
13872     {
13873       cur_abbrev = abbrev_table_alloc_abbrev (abbrev_table);
13874
13875       /* read in abbrev header */
13876       cur_abbrev->number = abbrev_number;
13877       cur_abbrev->tag = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
13878       abbrev_ptr += bytes_read;
13879       cur_abbrev->has_children = read_1_byte (abfd, abbrev_ptr);
13880       abbrev_ptr += 1;
13881
13882       /* now read in declarations */
13883       abbrev_name = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
13884       abbrev_ptr += bytes_read;
13885       abbrev_form = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
13886       abbrev_ptr += bytes_read;
13887       while (abbrev_name)
13888         {
13889           if (cur_abbrev->num_attrs == allocated_attrs)
13890             {
13891               allocated_attrs += ATTR_ALLOC_CHUNK;
13892               cur_attrs
13893                 = xrealloc (cur_attrs, (allocated_attrs
13894                                         * sizeof (struct attr_abbrev)));
13895             }
13896
13897           cur_attrs[cur_abbrev->num_attrs].name = abbrev_name;
13898           cur_attrs[cur_abbrev->num_attrs++].form = abbrev_form;
13899           abbrev_name = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
13900           abbrev_ptr += bytes_read;
13901           abbrev_form = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
13902           abbrev_ptr += bytes_read;
13903         }
13904
13905       cur_abbrev->attrs = obstack_alloc (&abbrev_table->abbrev_obstack,
13906                                          (cur_abbrev->num_attrs
13907                                           * sizeof (struct attr_abbrev)));
13908       memcpy (cur_abbrev->attrs, cur_attrs,
13909               cur_abbrev->num_attrs * sizeof (struct attr_abbrev));
13910
13911       abbrev_table_add_abbrev (abbrev_table, abbrev_number, cur_abbrev);
13912
13913       /* Get next abbreviation.
13914          Under Irix6 the abbreviations for a compilation unit are not
13915          always properly terminated with an abbrev number of 0.
13916          Exit loop if we encounter an abbreviation which we have
13917          already read (which means we are about to read the abbreviations
13918          for the next compile unit) or if the end of the abbreviation
13919          table is reached.  */
13920       if ((unsigned int) (abbrev_ptr - section->buffer) >= section->size)
13921         break;
13922       abbrev_number = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
13923       abbrev_ptr += bytes_read;
13924       if (abbrev_table_lookup_abbrev (abbrev_table, abbrev_number) != NULL)
13925         break;
13926     }
13927
13928   xfree (cur_attrs);
13929   return abbrev_table;
13930 }
13931
13932 /* Free the resources held by ABBREV_TABLE.  */
13933
13934 static void
13935 abbrev_table_free (struct abbrev_table *abbrev_table)
13936 {
13937   obstack_free (&abbrev_table->abbrev_obstack, NULL);
13938   xfree (abbrev_table);
13939 }
13940
13941 /* Same as abbrev_table_free but as a cleanup.
13942    We pass in a pointer to the pointer to the table so that we can
13943    set the pointer to NULL when we're done.  It also simplifies
13944    build_type_unit_groups.  */
13945
13946 static void
13947 abbrev_table_free_cleanup (void *table_ptr)
13948 {
13949   struct abbrev_table **abbrev_table_ptr = table_ptr;
13950
13951   if (*abbrev_table_ptr != NULL)
13952     abbrev_table_free (*abbrev_table_ptr);
13953   *abbrev_table_ptr = NULL;
13954 }
13955
13956 /* Read the abbrev table for CU from ABBREV_SECTION.  */
13957
13958 static void
13959 dwarf2_read_abbrevs (struct dwarf2_cu *cu,
13960                      struct dwarf2_section_info *abbrev_section)
13961 {
13962   cu->abbrev_table =
13963     abbrev_table_read_table (abbrev_section, cu->header.abbrev_offset);
13964 }
13965
13966 /* Release the memory used by the abbrev table for a compilation unit.  */
13967
13968 static void
13969 dwarf2_free_abbrev_table (void *ptr_to_cu)
13970 {
13971   struct dwarf2_cu *cu = ptr_to_cu;
13972
13973   if (cu->abbrev_table != NULL)
13974     abbrev_table_free (cu->abbrev_table);
13975   /* Set this to NULL so that we SEGV if we try to read it later,
13976      and also because free_comp_unit verifies this is NULL.  */
13977   cu->abbrev_table = NULL;
13978 }
13979 \f
13980 /* Returns nonzero if TAG represents a type that we might generate a partial
13981    symbol for.  */
13982
13983 static int
13984 is_type_tag_for_partial (int tag)
13985 {
13986   switch (tag)
13987     {
13988 #if 0
13989     /* Some types that would be reasonable to generate partial symbols for,
13990        that we don't at present.  */
13991     case DW_TAG_array_type:
13992     case DW_TAG_file_type:
13993     case DW_TAG_ptr_to_member_type:
13994     case DW_TAG_set_type:
13995     case DW_TAG_string_type:
13996     case DW_TAG_subroutine_type:
13997 #endif
13998     case DW_TAG_base_type:
13999     case DW_TAG_class_type:
14000     case DW_TAG_interface_type:
14001     case DW_TAG_enumeration_type:
14002     case DW_TAG_structure_type:
14003     case DW_TAG_subrange_type:
14004     case DW_TAG_typedef:
14005     case DW_TAG_union_type:
14006       return 1;
14007     default:
14008       return 0;
14009     }
14010 }
14011
14012 /* Load all DIEs that are interesting for partial symbols into memory.  */
14013
14014 static struct partial_die_info *
14015 load_partial_dies (const struct die_reader_specs *reader,
14016                    const gdb_byte *info_ptr, int building_psymtab)
14017 {
14018   struct dwarf2_cu *cu = reader->cu;
14019   struct objfile *objfile = cu->objfile;
14020   struct partial_die_info *part_die;
14021   struct partial_die_info *parent_die, *last_die, *first_die = NULL;
14022   struct abbrev_info *abbrev;
14023   unsigned int bytes_read;
14024   unsigned int load_all = 0;
14025   int nesting_level = 1;
14026
14027   parent_die = NULL;
14028   last_die = NULL;
14029
14030   gdb_assert (cu->per_cu != NULL);
14031   if (cu->per_cu->load_all_dies)
14032     load_all = 1;
14033
14034   cu->partial_dies
14035     = htab_create_alloc_ex (cu->header.length / 12,
14036                             partial_die_hash,
14037                             partial_die_eq,
14038                             NULL,
14039                             &cu->comp_unit_obstack,
14040                             hashtab_obstack_allocate,
14041                             dummy_obstack_deallocate);
14042
14043   part_die = obstack_alloc (&cu->comp_unit_obstack,
14044                             sizeof (struct partial_die_info));
14045
14046   while (1)
14047     {
14048       abbrev = peek_die_abbrev (info_ptr, &bytes_read, cu);
14049
14050       /* A NULL abbrev means the end of a series of children.  */
14051       if (abbrev == NULL)
14052         {
14053           if (--nesting_level == 0)
14054             {
14055               /* PART_DIE was probably the last thing allocated on the
14056                  comp_unit_obstack, so we could call obstack_free
14057                  here.  We don't do that because the waste is small,
14058                  and will be cleaned up when we're done with this
14059                  compilation unit.  This way, we're also more robust
14060                  against other users of the comp_unit_obstack.  */
14061               return first_die;
14062             }
14063           info_ptr += bytes_read;
14064           last_die = parent_die;
14065           parent_die = parent_die->die_parent;
14066           continue;
14067         }
14068
14069       /* Check for template arguments.  We never save these; if
14070          they're seen, we just mark the parent, and go on our way.  */
14071       if (parent_die != NULL
14072           && cu->language == language_cplus
14073           && (abbrev->tag == DW_TAG_template_type_param
14074               || abbrev->tag == DW_TAG_template_value_param))
14075         {
14076           parent_die->has_template_arguments = 1;
14077
14078           if (!load_all)
14079             {
14080               /* We don't need a partial DIE for the template argument.  */
14081               info_ptr = skip_one_die (reader, info_ptr + bytes_read, abbrev);
14082               continue;
14083             }
14084         }
14085
14086       /* We only recurse into c++ subprograms looking for template arguments.
14087          Skip their other children.  */
14088       if (!load_all
14089           && cu->language == language_cplus
14090           && parent_die != NULL
14091           && parent_die->tag == DW_TAG_subprogram)
14092         {
14093           info_ptr = skip_one_die (reader, info_ptr + bytes_read, abbrev);
14094           continue;
14095         }
14096
14097       /* Check whether this DIE is interesting enough to save.  Normally
14098          we would not be interested in members here, but there may be
14099          later variables referencing them via DW_AT_specification (for
14100          static members).  */
14101       if (!load_all
14102           && !is_type_tag_for_partial (abbrev->tag)
14103           && abbrev->tag != DW_TAG_constant
14104           && abbrev->tag != DW_TAG_enumerator
14105           && abbrev->tag != DW_TAG_subprogram
14106           && abbrev->tag != DW_TAG_lexical_block
14107           && abbrev->tag != DW_TAG_variable
14108           && abbrev->tag != DW_TAG_namespace
14109           && abbrev->tag != DW_TAG_module
14110           && abbrev->tag != DW_TAG_member
14111           && abbrev->tag != DW_TAG_imported_unit)
14112         {
14113           /* Otherwise we skip to the next sibling, if any.  */
14114           info_ptr = skip_one_die (reader, info_ptr + bytes_read, abbrev);
14115           continue;
14116         }
14117
14118       info_ptr = read_partial_die (reader, part_die, abbrev, bytes_read,
14119                                    info_ptr);
14120
14121       /* This two-pass algorithm for processing partial symbols has a
14122          high cost in cache pressure.  Thus, handle some simple cases
14123          here which cover the majority of C partial symbols.  DIEs
14124          which neither have specification tags in them, nor could have
14125          specification tags elsewhere pointing at them, can simply be
14126          processed and discarded.
14127
14128          This segment is also optional; scan_partial_symbols and
14129          add_partial_symbol will handle these DIEs if we chain
14130          them in normally.  When compilers which do not emit large
14131          quantities of duplicate debug information are more common,
14132          this code can probably be removed.  */
14133
14134       /* Any complete simple types at the top level (pretty much all
14135          of them, for a language without namespaces), can be processed
14136          directly.  */
14137       if (parent_die == NULL
14138           && part_die->has_specification == 0
14139           && part_die->is_declaration == 0
14140           && ((part_die->tag == DW_TAG_typedef && !part_die->has_children)
14141               || part_die->tag == DW_TAG_base_type
14142               || part_die->tag == DW_TAG_subrange_type))
14143         {
14144           if (building_psymtab && part_die->name != NULL)
14145             add_psymbol_to_list (part_die->name, strlen (part_die->name), 0,
14146                                  VAR_DOMAIN, LOC_TYPEDEF,
14147                                  &objfile->static_psymbols,
14148                                  0, (CORE_ADDR) 0, cu->language, objfile);
14149           info_ptr = locate_pdi_sibling (reader, part_die, info_ptr);
14150           continue;
14151         }
14152
14153       /* The exception for DW_TAG_typedef with has_children above is
14154          a workaround of GCC PR debug/47510.  In the case of this complaint
14155          type_name_no_tag_or_error will error on such types later.
14156
14157          GDB skipped children of DW_TAG_typedef by the shortcut above and then
14158          it could not find the child DIEs referenced later, this is checked
14159          above.  In correct DWARF DW_TAG_typedef should have no children.  */
14160
14161       if (part_die->tag == DW_TAG_typedef && part_die->has_children)
14162         complaint (&symfile_complaints,
14163                    _("DW_TAG_typedef has childen - GCC PR debug/47510 bug "
14164                      "- DIE at 0x%x [in module %s]"),
14165                    part_die->offset.sect_off, objfile_name (objfile));
14166
14167       /* If we're at the second level, and we're an enumerator, and
14168          our parent has no specification (meaning possibly lives in a
14169          namespace elsewhere), then we can add the partial symbol now
14170          instead of queueing it.  */
14171       if (part_die->tag == DW_TAG_enumerator
14172           && parent_die != NULL
14173           && parent_die->die_parent == NULL
14174           && parent_die->tag == DW_TAG_enumeration_type
14175           && parent_die->has_specification == 0)
14176         {
14177           if (part_die->name == NULL)
14178             complaint (&symfile_complaints,
14179                        _("malformed enumerator DIE ignored"));
14180           else if (building_psymtab)
14181             add_psymbol_to_list (part_die->name, strlen (part_die->name), 0,
14182                                  VAR_DOMAIN, LOC_CONST,
14183                                  (cu->language == language_cplus
14184                                   || cu->language == language_java)
14185                                  ? &objfile->global_psymbols
14186                                  : &objfile->static_psymbols,
14187                                  0, (CORE_ADDR) 0, cu->language, objfile);
14188
14189           info_ptr = locate_pdi_sibling (reader, part_die, info_ptr);
14190           continue;
14191         }
14192
14193       /* We'll save this DIE so link it in.  */
14194       part_die->die_parent = parent_die;
14195       part_die->die_sibling = NULL;
14196       part_die->die_child = NULL;
14197
14198       if (last_die && last_die == parent_die)
14199         last_die->die_child = part_die;
14200       else if (last_die)
14201         last_die->die_sibling = part_die;
14202
14203       last_die = part_die;
14204
14205       if (first_die == NULL)
14206         first_die = part_die;
14207
14208       /* Maybe add the DIE to the hash table.  Not all DIEs that we
14209          find interesting need to be in the hash table, because we
14210          also have the parent/sibling/child chains; only those that we
14211          might refer to by offset later during partial symbol reading.
14212
14213          For now this means things that might have be the target of a
14214          DW_AT_specification, DW_AT_abstract_origin, or
14215          DW_AT_extension.  DW_AT_extension will refer only to
14216          namespaces; DW_AT_abstract_origin refers to functions (and
14217          many things under the function DIE, but we do not recurse
14218          into function DIEs during partial symbol reading) and
14219          possibly variables as well; DW_AT_specification refers to
14220          declarations.  Declarations ought to have the DW_AT_declaration
14221          flag.  It happens that GCC forgets to put it in sometimes, but
14222          only for functions, not for types.
14223
14224          Adding more things than necessary to the hash table is harmless
14225          except for the performance cost.  Adding too few will result in
14226          wasted time in find_partial_die, when we reread the compilation
14227          unit with load_all_dies set.  */
14228
14229       if (load_all
14230           || abbrev->tag == DW_TAG_constant
14231           || abbrev->tag == DW_TAG_subprogram
14232           || abbrev->tag == DW_TAG_variable
14233           || abbrev->tag == DW_TAG_namespace
14234           || part_die->is_declaration)
14235         {
14236           void **slot;
14237
14238           slot = htab_find_slot_with_hash (cu->partial_dies, part_die,
14239                                            part_die->offset.sect_off, INSERT);
14240           *slot = part_die;
14241         }
14242
14243       part_die = obstack_alloc (&cu->comp_unit_obstack,
14244                                 sizeof (struct partial_die_info));
14245
14246       /* For some DIEs we want to follow their children (if any).  For C
14247          we have no reason to follow the children of structures; for other
14248          languages we have to, so that we can get at method physnames
14249          to infer fully qualified class names, for DW_AT_specification,
14250          and for C++ template arguments.  For C++, we also look one level
14251          inside functions to find template arguments (if the name of the
14252          function does not already contain the template arguments).
14253
14254          For Ada, we need to scan the children of subprograms and lexical
14255          blocks as well because Ada allows the definition of nested
14256          entities that could be interesting for the debugger, such as
14257          nested subprograms for instance.  */
14258       if (last_die->has_children
14259           && (load_all
14260               || last_die->tag == DW_TAG_namespace
14261               || last_die->tag == DW_TAG_module
14262               || last_die->tag == DW_TAG_enumeration_type
14263               || (cu->language == language_cplus
14264                   && last_die->tag == DW_TAG_subprogram
14265                   && (last_die->name == NULL
14266                       || strchr (last_die->name, '<') == NULL))
14267               || (cu->language != language_c
14268                   && (last_die->tag == DW_TAG_class_type
14269                       || last_die->tag == DW_TAG_interface_type
14270                       || last_die->tag == DW_TAG_structure_type
14271                       || last_die->tag == DW_TAG_union_type))
14272               || (cu->language == language_ada
14273                   && (last_die->tag == DW_TAG_subprogram
14274                       || last_die->tag == DW_TAG_lexical_block))))
14275         {
14276           nesting_level++;
14277           parent_die = last_die;
14278           continue;
14279         }
14280
14281       /* Otherwise we skip to the next sibling, if any.  */
14282       info_ptr = locate_pdi_sibling (reader, last_die, info_ptr);
14283
14284       /* Back to the top, do it again.  */
14285     }
14286 }
14287
14288 /* Read a minimal amount of information into the minimal die structure.  */
14289
14290 static const gdb_byte *
14291 read_partial_die (const struct die_reader_specs *reader,
14292                   struct partial_die_info *part_die,
14293                   struct abbrev_info *abbrev, unsigned int abbrev_len,
14294                   const gdb_byte *info_ptr)
14295 {
14296   struct dwarf2_cu *cu = reader->cu;
14297   struct objfile *objfile = cu->objfile;
14298   const gdb_byte *buffer = reader->buffer;
14299   unsigned int i;
14300   struct attribute attr;
14301   int has_low_pc_attr = 0;
14302   int has_high_pc_attr = 0;
14303   int high_pc_relative = 0;
14304
14305   memset (part_die, 0, sizeof (struct partial_die_info));
14306
14307   part_die->offset.sect_off = info_ptr - buffer;
14308
14309   info_ptr += abbrev_len;
14310
14311   if (abbrev == NULL)
14312     return info_ptr;
14313
14314   part_die->tag = abbrev->tag;
14315   part_die->has_children = abbrev->has_children;
14316
14317   for (i = 0; i < abbrev->num_attrs; ++i)
14318     {
14319       info_ptr = read_attribute (reader, &attr, &abbrev->attrs[i], info_ptr);
14320
14321       /* Store the data if it is of an attribute we want to keep in a
14322          partial symbol table.  */
14323       switch (attr.name)
14324         {
14325         case DW_AT_name:
14326           switch (part_die->tag)
14327             {
14328             case DW_TAG_compile_unit:
14329             case DW_TAG_partial_unit:
14330             case DW_TAG_type_unit:
14331               /* Compilation units have a DW_AT_name that is a filename, not
14332                  a source language identifier.  */
14333             case DW_TAG_enumeration_type:
14334             case DW_TAG_enumerator:
14335               /* These tags always have simple identifiers already; no need
14336                  to canonicalize them.  */
14337               part_die->name = DW_STRING (&attr);
14338               break;
14339             default:
14340               part_die->name
14341                 = dwarf2_canonicalize_name (DW_STRING (&attr), cu,
14342                                             &objfile->objfile_obstack);
14343               break;
14344             }
14345           break;
14346         case DW_AT_linkage_name:
14347         case DW_AT_MIPS_linkage_name:
14348           /* Note that both forms of linkage name might appear.  We
14349              assume they will be the same, and we only store the last
14350              one we see.  */
14351           if (cu->language == language_ada)
14352             part_die->name = DW_STRING (&attr);
14353           part_die->linkage_name = DW_STRING (&attr);
14354           break;
14355         case DW_AT_low_pc:
14356           has_low_pc_attr = 1;
14357           part_die->lowpc = DW_ADDR (&attr);
14358           break;
14359         case DW_AT_high_pc:
14360           has_high_pc_attr = 1;
14361           if (attr.form == DW_FORM_addr
14362               || attr.form == DW_FORM_GNU_addr_index)
14363             part_die->highpc = DW_ADDR (&attr);
14364           else
14365             {
14366               high_pc_relative = 1;
14367               part_die->highpc = DW_UNSND (&attr);
14368             }
14369           break;
14370         case DW_AT_location:
14371           /* Support the .debug_loc offsets.  */
14372           if (attr_form_is_block (&attr))
14373             {
14374                part_die->d.locdesc = DW_BLOCK (&attr);
14375             }
14376           else if (attr_form_is_section_offset (&attr))
14377             {
14378               dwarf2_complex_location_expr_complaint ();
14379             }
14380           else
14381             {
14382               dwarf2_invalid_attrib_class_complaint ("DW_AT_location",
14383                                                      "partial symbol information");
14384             }
14385           break;
14386         case DW_AT_external:
14387           part_die->is_external = DW_UNSND (&attr);
14388           break;
14389         case DW_AT_declaration:
14390           part_die->is_declaration = DW_UNSND (&attr);
14391           break;
14392         case DW_AT_type:
14393           part_die->has_type = 1;
14394           break;
14395         case DW_AT_abstract_origin:
14396         case DW_AT_specification:
14397         case DW_AT_extension:
14398           part_die->has_specification = 1;
14399           part_die->spec_offset = dwarf2_get_ref_die_offset (&attr);
14400           part_die->spec_is_dwz = (attr.form == DW_FORM_GNU_ref_alt
14401                                    || cu->per_cu->is_dwz);
14402           break;
14403         case DW_AT_sibling:
14404           /* Ignore absolute siblings, they might point outside of
14405              the current compile unit.  */
14406           if (attr.form == DW_FORM_ref_addr)
14407             complaint (&symfile_complaints,
14408                        _("ignoring absolute DW_AT_sibling"));
14409           else
14410             part_die->sibling = buffer + dwarf2_get_ref_die_offset (&attr).sect_off;
14411           break;
14412         case DW_AT_byte_size:
14413           part_die->has_byte_size = 1;
14414           break;
14415         case DW_AT_calling_convention:
14416           /* DWARF doesn't provide a way to identify a program's source-level
14417              entry point.  DW_AT_calling_convention attributes are only meant
14418              to describe functions' calling conventions.
14419
14420              However, because it's a necessary piece of information in
14421              Fortran, and because DW_CC_program is the only piece of debugging
14422              information whose definition refers to a 'main program' at all,
14423              several compilers have begun marking Fortran main programs with
14424              DW_CC_program --- even when those functions use the standard
14425              calling conventions.
14426
14427              So until DWARF specifies a way to provide this information and
14428              compilers pick up the new representation, we'll support this
14429              practice.  */
14430           if (DW_UNSND (&attr) == DW_CC_program
14431               && cu->language == language_fortran)
14432             {
14433               set_main_name (part_die->name);
14434
14435               /* As this DIE has a static linkage the name would be difficult
14436                  to look up later.  */
14437               language_of_main = language_fortran;
14438             }
14439           break;
14440         case DW_AT_inline:
14441           if (DW_UNSND (&attr) == DW_INL_inlined
14442               || DW_UNSND (&attr) == DW_INL_declared_inlined)
14443             part_die->may_be_inlined = 1;
14444           break;
14445
14446         case DW_AT_import:
14447           if (part_die->tag == DW_TAG_imported_unit)
14448             {
14449               part_die->d.offset = dwarf2_get_ref_die_offset (&attr);
14450               part_die->is_dwz = (attr.form == DW_FORM_GNU_ref_alt
14451                                   || cu->per_cu->is_dwz);
14452             }
14453           break;
14454
14455         default:
14456           break;
14457         }
14458     }
14459
14460   if (high_pc_relative)
14461     part_die->highpc += part_die->lowpc;
14462
14463   if (has_low_pc_attr && has_high_pc_attr)
14464     {
14465       /* When using the GNU linker, .gnu.linkonce. sections are used to
14466          eliminate duplicate copies of functions and vtables and such.
14467          The linker will arbitrarily choose one and discard the others.
14468          The AT_*_pc values for such functions refer to local labels in
14469          these sections.  If the section from that file was discarded, the
14470          labels are not in the output, so the relocs get a value of 0.
14471          If this is a discarded function, mark the pc bounds as invalid,
14472          so that GDB will ignore it.  */
14473       if (part_die->lowpc == 0 && !dwarf2_per_objfile->has_section_at_zero)
14474         {
14475           struct gdbarch *gdbarch = get_objfile_arch (objfile);
14476
14477           complaint (&symfile_complaints,
14478                      _("DW_AT_low_pc %s is zero "
14479                        "for DIE at 0x%x [in module %s]"),
14480                      paddress (gdbarch, part_die->lowpc),
14481                      part_die->offset.sect_off, objfile_name (objfile));
14482         }
14483       /* dwarf2_get_pc_bounds has also the strict low < high requirement.  */
14484       else if (part_die->lowpc >= part_die->highpc)
14485         {
14486           struct gdbarch *gdbarch = get_objfile_arch (objfile);
14487
14488           complaint (&symfile_complaints,
14489                      _("DW_AT_low_pc %s is not < DW_AT_high_pc %s "
14490                        "for DIE at 0x%x [in module %s]"),
14491                      paddress (gdbarch, part_die->lowpc),
14492                      paddress (gdbarch, part_die->highpc),
14493                      part_die->offset.sect_off, objfile_name (objfile));
14494         }
14495       else
14496         part_die->has_pc_info = 1;
14497     }
14498
14499   return info_ptr;
14500 }
14501
14502 /* Find a cached partial DIE at OFFSET in CU.  */
14503
14504 static struct partial_die_info *
14505 find_partial_die_in_comp_unit (sect_offset offset, struct dwarf2_cu *cu)
14506 {
14507   struct partial_die_info *lookup_die = NULL;
14508   struct partial_die_info part_die;
14509
14510   part_die.offset = offset;
14511   lookup_die = htab_find_with_hash (cu->partial_dies, &part_die,
14512                                     offset.sect_off);
14513
14514   return lookup_die;
14515 }
14516
14517 /* Find a partial DIE at OFFSET, which may or may not be in CU,
14518    except in the case of .debug_types DIEs which do not reference
14519    outside their CU (they do however referencing other types via
14520    DW_FORM_ref_sig8).  */
14521
14522 static struct partial_die_info *
14523 find_partial_die (sect_offset offset, int offset_in_dwz, struct dwarf2_cu *cu)
14524 {
14525   struct objfile *objfile = cu->objfile;
14526   struct dwarf2_per_cu_data *per_cu = NULL;
14527   struct partial_die_info *pd = NULL;
14528
14529   if (offset_in_dwz == cu->per_cu->is_dwz
14530       && offset_in_cu_p (&cu->header, offset))
14531     {
14532       pd = find_partial_die_in_comp_unit (offset, cu);
14533       if (pd != NULL)
14534         return pd;
14535       /* We missed recording what we needed.
14536          Load all dies and try again.  */
14537       per_cu = cu->per_cu;
14538     }
14539   else
14540     {
14541       /* TUs don't reference other CUs/TUs (except via type signatures).  */
14542       if (cu->per_cu->is_debug_types)
14543         {
14544           error (_("Dwarf Error: Type Unit at offset 0x%lx contains"
14545                    " external reference to offset 0x%lx [in module %s].\n"),
14546                  (long) cu->header.offset.sect_off, (long) offset.sect_off,
14547                  bfd_get_filename (objfile->obfd));
14548         }
14549       per_cu = dwarf2_find_containing_comp_unit (offset, offset_in_dwz,
14550                                                  objfile);
14551
14552       if (per_cu->cu == NULL || per_cu->cu->partial_dies == NULL)
14553         load_partial_comp_unit (per_cu);
14554
14555       per_cu->cu->last_used = 0;
14556       pd = find_partial_die_in_comp_unit (offset, per_cu->cu);
14557     }
14558
14559   /* If we didn't find it, and not all dies have been loaded,
14560      load them all and try again.  */
14561
14562   if (pd == NULL && per_cu->load_all_dies == 0)
14563     {
14564       per_cu->load_all_dies = 1;
14565
14566       /* This is nasty.  When we reread the DIEs, somewhere up the call chain
14567          THIS_CU->cu may already be in use.  So we can't just free it and
14568          replace its DIEs with the ones we read in.  Instead, we leave those
14569          DIEs alone (which can still be in use, e.g. in scan_partial_symbols),
14570          and clobber THIS_CU->cu->partial_dies with the hash table for the new
14571          set.  */
14572       load_partial_comp_unit (per_cu);
14573
14574       pd = find_partial_die_in_comp_unit (offset, per_cu->cu);
14575     }
14576
14577   if (pd == NULL)
14578     internal_error (__FILE__, __LINE__,
14579                     _("could not find partial DIE 0x%x "
14580                       "in cache [from module %s]\n"),
14581                     offset.sect_off, bfd_get_filename (objfile->obfd));
14582   return pd;
14583 }
14584
14585 /* See if we can figure out if the class lives in a namespace.  We do
14586    this by looking for a member function; its demangled name will
14587    contain namespace info, if there is any.  */
14588
14589 static void
14590 guess_partial_die_structure_name (struct partial_die_info *struct_pdi,
14591                                   struct dwarf2_cu *cu)
14592 {
14593   /* NOTE: carlton/2003-10-07: Getting the info this way changes
14594      what template types look like, because the demangler
14595      frequently doesn't give the same name as the debug info.  We
14596      could fix this by only using the demangled name to get the
14597      prefix (but see comment in read_structure_type).  */
14598
14599   struct partial_die_info *real_pdi;
14600   struct partial_die_info *child_pdi;
14601
14602   /* If this DIE (this DIE's specification, if any) has a parent, then
14603      we should not do this.  We'll prepend the parent's fully qualified
14604      name when we create the partial symbol.  */
14605
14606   real_pdi = struct_pdi;
14607   while (real_pdi->has_specification)
14608     real_pdi = find_partial_die (real_pdi->spec_offset,
14609                                  real_pdi->spec_is_dwz, cu);
14610
14611   if (real_pdi->die_parent != NULL)
14612     return;
14613
14614   for (child_pdi = struct_pdi->die_child;
14615        child_pdi != NULL;
14616        child_pdi = child_pdi->die_sibling)
14617     {
14618       if (child_pdi->tag == DW_TAG_subprogram
14619           && child_pdi->linkage_name != NULL)
14620         {
14621           char *actual_class_name
14622             = language_class_name_from_physname (cu->language_defn,
14623                                                  child_pdi->linkage_name);
14624           if (actual_class_name != NULL)
14625             {
14626               struct_pdi->name
14627                 = obstack_copy0 (&cu->objfile->objfile_obstack,
14628                                  actual_class_name,
14629                                  strlen (actual_class_name));
14630               xfree (actual_class_name);
14631             }
14632           break;
14633         }
14634     }
14635 }
14636
14637 /* Adjust PART_DIE before generating a symbol for it.  This function
14638    may set the is_external flag or change the DIE's name.  */
14639
14640 static void
14641 fixup_partial_die (struct partial_die_info *part_die,
14642                    struct dwarf2_cu *cu)
14643 {
14644   /* Once we've fixed up a die, there's no point in doing so again.
14645      This also avoids a memory leak if we were to call
14646      guess_partial_die_structure_name multiple times.  */
14647   if (part_die->fixup_called)
14648     return;
14649
14650   /* If we found a reference attribute and the DIE has no name, try
14651      to find a name in the referred to DIE.  */
14652
14653   if (part_die->name == NULL && part_die->has_specification)
14654     {
14655       struct partial_die_info *spec_die;
14656
14657       spec_die = find_partial_die (part_die->spec_offset,
14658                                    part_die->spec_is_dwz, cu);
14659
14660       fixup_partial_die (spec_die, cu);
14661
14662       if (spec_die->name)
14663         {
14664           part_die->name = spec_die->name;
14665
14666           /* Copy DW_AT_external attribute if it is set.  */
14667           if (spec_die->is_external)
14668             part_die->is_external = spec_die->is_external;
14669         }
14670     }
14671
14672   /* Set default names for some unnamed DIEs.  */
14673
14674   if (part_die->name == NULL && part_die->tag == DW_TAG_namespace)
14675     part_die->name = CP_ANONYMOUS_NAMESPACE_STR;
14676
14677   /* If there is no parent die to provide a namespace, and there are
14678      children, see if we can determine the namespace from their linkage
14679      name.  */
14680   if (cu->language == language_cplus
14681       && !VEC_empty (dwarf2_section_info_def, dwarf2_per_objfile->types)
14682       && part_die->die_parent == NULL
14683       && part_die->has_children
14684       && (part_die->tag == DW_TAG_class_type
14685           || part_die->tag == DW_TAG_structure_type
14686           || part_die->tag == DW_TAG_union_type))
14687     guess_partial_die_structure_name (part_die, cu);
14688
14689   /* GCC might emit a nameless struct or union that has a linkage
14690      name.  See http://gcc.gnu.org/bugzilla/show_bug.cgi?id=47510.  */
14691   if (part_die->name == NULL
14692       && (part_die->tag == DW_TAG_class_type
14693           || part_die->tag == DW_TAG_interface_type
14694           || part_die->tag == DW_TAG_structure_type
14695           || part_die->tag == DW_TAG_union_type)
14696       && part_die->linkage_name != NULL)
14697     {
14698       char *demangled;
14699
14700       demangled = gdb_demangle (part_die->linkage_name, DMGL_TYPES);
14701       if (demangled)
14702         {
14703           const char *base;
14704
14705           /* Strip any leading namespaces/classes, keep only the base name.
14706              DW_AT_name for named DIEs does not contain the prefixes.  */
14707           base = strrchr (demangled, ':');
14708           if (base && base > demangled && base[-1] == ':')
14709             base++;
14710           else
14711             base = demangled;
14712
14713           part_die->name = obstack_copy0 (&cu->objfile->objfile_obstack,
14714                                           base, strlen (base));
14715           xfree (demangled);
14716         }
14717     }
14718
14719   part_die->fixup_called = 1;
14720 }
14721
14722 /* Read an attribute value described by an attribute form.  */
14723
14724 static const gdb_byte *
14725 read_attribute_value (const struct die_reader_specs *reader,
14726                       struct attribute *attr, unsigned form,
14727                       const gdb_byte *info_ptr)
14728 {
14729   struct dwarf2_cu *cu = reader->cu;
14730   bfd *abfd = reader->abfd;
14731   struct comp_unit_head *cu_header = &cu->header;
14732   unsigned int bytes_read;
14733   struct dwarf_block *blk;
14734
14735   attr->form = form;
14736   switch (form)
14737     {
14738     case DW_FORM_ref_addr:
14739       if (cu->header.version == 2)
14740         DW_UNSND (attr) = read_address (abfd, info_ptr, cu, &bytes_read);
14741       else
14742         DW_UNSND (attr) = read_offset (abfd, info_ptr,
14743                                        &cu->header, &bytes_read);
14744       info_ptr += bytes_read;
14745       break;
14746     case DW_FORM_GNU_ref_alt:
14747       DW_UNSND (attr) = read_offset (abfd, info_ptr, &cu->header, &bytes_read);
14748       info_ptr += bytes_read;
14749       break;
14750     case DW_FORM_addr:
14751       DW_ADDR (attr) = read_address (abfd, info_ptr, cu, &bytes_read);
14752       info_ptr += bytes_read;
14753       break;
14754     case DW_FORM_block2:
14755       blk = dwarf_alloc_block (cu);
14756       blk->size = read_2_bytes (abfd, info_ptr);
14757       info_ptr += 2;
14758       blk->data = read_n_bytes (abfd, info_ptr, blk->size);
14759       info_ptr += blk->size;
14760       DW_BLOCK (attr) = blk;
14761       break;
14762     case DW_FORM_block4:
14763       blk = dwarf_alloc_block (cu);
14764       blk->size = read_4_bytes (abfd, info_ptr);
14765       info_ptr += 4;
14766       blk->data = read_n_bytes (abfd, info_ptr, blk->size);
14767       info_ptr += blk->size;
14768       DW_BLOCK (attr) = blk;
14769       break;
14770     case DW_FORM_data2:
14771       DW_UNSND (attr) = read_2_bytes (abfd, info_ptr);
14772       info_ptr += 2;
14773       break;
14774     case DW_FORM_data4:
14775       DW_UNSND (attr) = read_4_bytes (abfd, info_ptr);
14776       info_ptr += 4;
14777       break;
14778     case DW_FORM_data8:
14779       DW_UNSND (attr) = read_8_bytes (abfd, info_ptr);
14780       info_ptr += 8;
14781       break;
14782     case DW_FORM_sec_offset:
14783       DW_UNSND (attr) = read_offset (abfd, info_ptr, &cu->header, &bytes_read);
14784       info_ptr += bytes_read;
14785       break;
14786     case DW_FORM_string:
14787       DW_STRING (attr) = read_direct_string (abfd, info_ptr, &bytes_read);
14788       DW_STRING_IS_CANONICAL (attr) = 0;
14789       info_ptr += bytes_read;
14790       break;
14791     case DW_FORM_strp:
14792       if (!cu->per_cu->is_dwz)
14793         {
14794           DW_STRING (attr) = read_indirect_string (abfd, info_ptr, cu_header,
14795                                                    &bytes_read);
14796           DW_STRING_IS_CANONICAL (attr) = 0;
14797           info_ptr += bytes_read;
14798           break;
14799         }
14800       /* FALLTHROUGH */
14801     case DW_FORM_GNU_strp_alt:
14802       {
14803         struct dwz_file *dwz = dwarf2_get_dwz_file ();
14804         LONGEST str_offset = read_offset (abfd, info_ptr, cu_header,
14805                                           &bytes_read);
14806
14807         DW_STRING (attr) = read_indirect_string_from_dwz (dwz, str_offset);
14808         DW_STRING_IS_CANONICAL (attr) = 0;
14809         info_ptr += bytes_read;
14810       }
14811       break;
14812     case DW_FORM_exprloc:
14813     case DW_FORM_block:
14814       blk = dwarf_alloc_block (cu);
14815       blk->size = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
14816       info_ptr += bytes_read;
14817       blk->data = read_n_bytes (abfd, info_ptr, blk->size);
14818       info_ptr += blk->size;
14819       DW_BLOCK (attr) = blk;
14820       break;
14821     case DW_FORM_block1:
14822       blk = dwarf_alloc_block (cu);
14823       blk->size = read_1_byte (abfd, info_ptr);
14824       info_ptr += 1;
14825       blk->data = read_n_bytes (abfd, info_ptr, blk->size);
14826       info_ptr += blk->size;
14827       DW_BLOCK (attr) = blk;
14828       break;
14829     case DW_FORM_data1:
14830       DW_UNSND (attr) = read_1_byte (abfd, info_ptr);
14831       info_ptr += 1;
14832       break;
14833     case DW_FORM_flag:
14834       DW_UNSND (attr) = read_1_byte (abfd, info_ptr);
14835       info_ptr += 1;
14836       break;
14837     case DW_FORM_flag_present:
14838       DW_UNSND (attr) = 1;
14839       break;
14840     case DW_FORM_sdata:
14841       DW_SND (attr) = read_signed_leb128 (abfd, info_ptr, &bytes_read);
14842       info_ptr += bytes_read;
14843       break;
14844     case DW_FORM_udata:
14845       DW_UNSND (attr) = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
14846       info_ptr += bytes_read;
14847       break;
14848     case DW_FORM_ref1:
14849       DW_UNSND (attr) = (cu->header.offset.sect_off
14850                          + read_1_byte (abfd, info_ptr));
14851       info_ptr += 1;
14852       break;
14853     case DW_FORM_ref2:
14854       DW_UNSND (attr) = (cu->header.offset.sect_off
14855                          + read_2_bytes (abfd, info_ptr));
14856       info_ptr += 2;
14857       break;
14858     case DW_FORM_ref4:
14859       DW_UNSND (attr) = (cu->header.offset.sect_off
14860                          + read_4_bytes (abfd, info_ptr));
14861       info_ptr += 4;
14862       break;
14863     case DW_FORM_ref8:
14864       DW_UNSND (attr) = (cu->header.offset.sect_off
14865                          + read_8_bytes (abfd, info_ptr));
14866       info_ptr += 8;
14867       break;
14868     case DW_FORM_ref_sig8:
14869       DW_SIGNATURE (attr) = read_8_bytes (abfd, info_ptr);
14870       info_ptr += 8;
14871       break;
14872     case DW_FORM_ref_udata:
14873       DW_UNSND (attr) = (cu->header.offset.sect_off
14874                          + read_unsigned_leb128 (abfd, info_ptr, &bytes_read));
14875       info_ptr += bytes_read;
14876       break;
14877     case DW_FORM_indirect:
14878       form = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
14879       info_ptr += bytes_read;
14880       info_ptr = read_attribute_value (reader, attr, form, info_ptr);
14881       break;
14882     case DW_FORM_GNU_addr_index:
14883       if (reader->dwo_file == NULL)
14884         {
14885           /* For now flag a hard error.
14886              Later we can turn this into a complaint.  */
14887           error (_("Dwarf Error: %s found in non-DWO CU [in module %s]"),
14888                  dwarf_form_name (form),
14889                  bfd_get_filename (abfd));
14890         }
14891       DW_ADDR (attr) = read_addr_index_from_leb128 (cu, info_ptr, &bytes_read);
14892       info_ptr += bytes_read;
14893       break;
14894     case DW_FORM_GNU_str_index:
14895       if (reader->dwo_file == NULL)
14896         {
14897           /* For now flag a hard error.
14898              Later we can turn this into a complaint if warranted.  */
14899           error (_("Dwarf Error: %s found in non-DWO CU [in module %s]"),
14900                  dwarf_form_name (form),
14901                  bfd_get_filename (abfd));
14902         }
14903       {
14904         ULONGEST str_index =
14905           read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
14906
14907         DW_STRING (attr) = read_str_index (reader, cu, str_index);
14908         DW_STRING_IS_CANONICAL (attr) = 0;
14909         info_ptr += bytes_read;
14910       }
14911       break;
14912     default:
14913       error (_("Dwarf Error: Cannot handle %s in DWARF reader [in module %s]"),
14914              dwarf_form_name (form),
14915              bfd_get_filename (abfd));
14916     }
14917
14918   /* Super hack.  */
14919   if (cu->per_cu->is_dwz && attr_form_is_ref (attr))
14920     attr->form = DW_FORM_GNU_ref_alt;
14921
14922   /* We have seen instances where the compiler tried to emit a byte
14923      size attribute of -1 which ended up being encoded as an unsigned
14924      0xffffffff.  Although 0xffffffff is technically a valid size value,
14925      an object of this size seems pretty unlikely so we can relatively
14926      safely treat these cases as if the size attribute was invalid and
14927      treat them as zero by default.  */
14928   if (attr->name == DW_AT_byte_size
14929       && form == DW_FORM_data4
14930       && DW_UNSND (attr) >= 0xffffffff)
14931     {
14932       complaint
14933         (&symfile_complaints,
14934          _("Suspicious DW_AT_byte_size value treated as zero instead of %s"),
14935          hex_string (DW_UNSND (attr)));
14936       DW_UNSND (attr) = 0;
14937     }
14938
14939   return info_ptr;
14940 }
14941
14942 /* Read an attribute described by an abbreviated attribute.  */
14943
14944 static const gdb_byte *
14945 read_attribute (const struct die_reader_specs *reader,
14946                 struct attribute *attr, struct attr_abbrev *abbrev,
14947                 const gdb_byte *info_ptr)
14948 {
14949   attr->name = abbrev->name;
14950   return read_attribute_value (reader, attr, abbrev->form, info_ptr);
14951 }
14952
14953 /* Read dwarf information from a buffer.  */
14954
14955 static unsigned int
14956 read_1_byte (bfd *abfd, const gdb_byte *buf)
14957 {
14958   return bfd_get_8 (abfd, buf);
14959 }
14960
14961 static int
14962 read_1_signed_byte (bfd *abfd, const gdb_byte *buf)
14963 {
14964   return bfd_get_signed_8 (abfd, buf);
14965 }
14966
14967 static unsigned int
14968 read_2_bytes (bfd *abfd, const gdb_byte *buf)
14969 {
14970   return bfd_get_16 (abfd, buf);
14971 }
14972
14973 static int
14974 read_2_signed_bytes (bfd *abfd, const gdb_byte *buf)
14975 {
14976   return bfd_get_signed_16 (abfd, buf);
14977 }
14978
14979 static unsigned int
14980 read_4_bytes (bfd *abfd, const gdb_byte *buf)
14981 {
14982   return bfd_get_32 (abfd, buf);
14983 }
14984
14985 static int
14986 read_4_signed_bytes (bfd *abfd, const gdb_byte *buf)
14987 {
14988   return bfd_get_signed_32 (abfd, buf);
14989 }
14990
14991 static ULONGEST
14992 read_8_bytes (bfd *abfd, const gdb_byte *buf)
14993 {
14994   return bfd_get_64 (abfd, buf);
14995 }
14996
14997 static CORE_ADDR
14998 read_address (bfd *abfd, const gdb_byte *buf, struct dwarf2_cu *cu,
14999               unsigned int *bytes_read)
15000 {
15001   struct comp_unit_head *cu_header = &cu->header;
15002   CORE_ADDR retval = 0;
15003
15004   if (cu_header->signed_addr_p)
15005     {
15006       switch (cu_header->addr_size)
15007         {
15008         case 2:
15009           retval = bfd_get_signed_16 (abfd, buf);
15010           break;
15011         case 4:
15012           retval = bfd_get_signed_32 (abfd, buf);
15013           break;
15014         case 8:
15015           retval = bfd_get_signed_64 (abfd, buf);
15016           break;
15017         default:
15018           internal_error (__FILE__, __LINE__,
15019                           _("read_address: bad switch, signed [in module %s]"),
15020                           bfd_get_filename (abfd));
15021         }
15022     }
15023   else
15024     {
15025       switch (cu_header->addr_size)
15026         {
15027         case 2:
15028           retval = bfd_get_16 (abfd, buf);
15029           break;
15030         case 4:
15031           retval = bfd_get_32 (abfd, buf);
15032           break;
15033         case 8:
15034           retval = bfd_get_64 (abfd, buf);
15035           break;
15036         default:
15037           internal_error (__FILE__, __LINE__,
15038                           _("read_address: bad switch, "
15039                             "unsigned [in module %s]"),
15040                           bfd_get_filename (abfd));
15041         }
15042     }
15043
15044   *bytes_read = cu_header->addr_size;
15045   return retval;
15046 }
15047
15048 /* Read the initial length from a section.  The (draft) DWARF 3
15049    specification allows the initial length to take up either 4 bytes
15050    or 12 bytes.  If the first 4 bytes are 0xffffffff, then the next 8
15051    bytes describe the length and all offsets will be 8 bytes in length
15052    instead of 4.
15053
15054    An older, non-standard 64-bit format is also handled by this
15055    function.  The older format in question stores the initial length
15056    as an 8-byte quantity without an escape value.  Lengths greater
15057    than 2^32 aren't very common which means that the initial 4 bytes
15058    is almost always zero.  Since a length value of zero doesn't make
15059    sense for the 32-bit format, this initial zero can be considered to
15060    be an escape value which indicates the presence of the older 64-bit
15061    format.  As written, the code can't detect (old format) lengths
15062    greater than 4GB.  If it becomes necessary to handle lengths
15063    somewhat larger than 4GB, we could allow other small values (such
15064    as the non-sensical values of 1, 2, and 3) to also be used as
15065    escape values indicating the presence of the old format.
15066
15067    The value returned via bytes_read should be used to increment the
15068    relevant pointer after calling read_initial_length().
15069
15070    [ Note:  read_initial_length() and read_offset() are based on the
15071      document entitled "DWARF Debugging Information Format", revision
15072      3, draft 8, dated November 19, 2001.  This document was obtained
15073      from:
15074
15075         http://reality.sgiweb.org/davea/dwarf3-draft8-011125.pdf
15076
15077      This document is only a draft and is subject to change.  (So beware.)
15078
15079      Details regarding the older, non-standard 64-bit format were
15080      determined empirically by examining 64-bit ELF files produced by
15081      the SGI toolchain on an IRIX 6.5 machine.
15082
15083      - Kevin, July 16, 2002
15084    ] */
15085
15086 static LONGEST
15087 read_initial_length (bfd *abfd, const gdb_byte *buf, unsigned int *bytes_read)
15088 {
15089   LONGEST length = bfd_get_32 (abfd, buf);
15090
15091   if (length == 0xffffffff)
15092     {
15093       length = bfd_get_64 (abfd, buf + 4);
15094       *bytes_read = 12;
15095     }
15096   else if (length == 0)
15097     {
15098       /* Handle the (non-standard) 64-bit DWARF2 format used by IRIX.  */
15099       length = bfd_get_64 (abfd, buf);
15100       *bytes_read = 8;
15101     }
15102   else
15103     {
15104       *bytes_read = 4;
15105     }
15106
15107   return length;
15108 }
15109
15110 /* Cover function for read_initial_length.
15111    Returns the length of the object at BUF, and stores the size of the
15112    initial length in *BYTES_READ and stores the size that offsets will be in
15113    *OFFSET_SIZE.
15114    If the initial length size is not equivalent to that specified in
15115    CU_HEADER then issue a complaint.
15116    This is useful when reading non-comp-unit headers.  */
15117
15118 static LONGEST
15119 read_checked_initial_length_and_offset (bfd *abfd, const gdb_byte *buf,
15120                                         const struct comp_unit_head *cu_header,
15121                                         unsigned int *bytes_read,
15122                                         unsigned int *offset_size)
15123 {
15124   LONGEST length = read_initial_length (abfd, buf, bytes_read);
15125
15126   gdb_assert (cu_header->initial_length_size == 4
15127               || cu_header->initial_length_size == 8
15128               || cu_header->initial_length_size == 12);
15129
15130   if (cu_header->initial_length_size != *bytes_read)
15131     complaint (&symfile_complaints,
15132                _("intermixed 32-bit and 64-bit DWARF sections"));
15133
15134   *offset_size = (*bytes_read == 4) ? 4 : 8;
15135   return length;
15136 }
15137
15138 /* Read an offset from the data stream.  The size of the offset is
15139    given by cu_header->offset_size.  */
15140
15141 static LONGEST
15142 read_offset (bfd *abfd, const gdb_byte *buf,
15143              const struct comp_unit_head *cu_header,
15144              unsigned int *bytes_read)
15145 {
15146   LONGEST offset = read_offset_1 (abfd, buf, cu_header->offset_size);
15147
15148   *bytes_read = cu_header->offset_size;
15149   return offset;
15150 }
15151
15152 /* Read an offset from the data stream.  */
15153
15154 static LONGEST
15155 read_offset_1 (bfd *abfd, const gdb_byte *buf, unsigned int offset_size)
15156 {
15157   LONGEST retval = 0;
15158
15159   switch (offset_size)
15160     {
15161     case 4:
15162       retval = bfd_get_32 (abfd, buf);
15163       break;
15164     case 8:
15165       retval = bfd_get_64 (abfd, buf);
15166       break;
15167     default:
15168       internal_error (__FILE__, __LINE__,
15169                       _("read_offset_1: bad switch [in module %s]"),
15170                       bfd_get_filename (abfd));
15171     }
15172
15173   return retval;
15174 }
15175
15176 static const gdb_byte *
15177 read_n_bytes (bfd *abfd, const gdb_byte *buf, unsigned int size)
15178 {
15179   /* If the size of a host char is 8 bits, we can return a pointer
15180      to the buffer, otherwise we have to copy the data to a buffer
15181      allocated on the temporary obstack.  */
15182   gdb_assert (HOST_CHAR_BIT == 8);
15183   return buf;
15184 }
15185
15186 static const char *
15187 read_direct_string (bfd *abfd, const gdb_byte *buf,
15188                     unsigned int *bytes_read_ptr)
15189 {
15190   /* If the size of a host char is 8 bits, we can return a pointer
15191      to the string, otherwise we have to copy the string to a buffer
15192      allocated on the temporary obstack.  */
15193   gdb_assert (HOST_CHAR_BIT == 8);
15194   if (*buf == '\0')
15195     {
15196       *bytes_read_ptr = 1;
15197       return NULL;
15198     }
15199   *bytes_read_ptr = strlen ((const char *) buf) + 1;
15200   return (const char *) buf;
15201 }
15202
15203 static const char *
15204 read_indirect_string_at_offset (bfd *abfd, LONGEST str_offset)
15205 {
15206   dwarf2_read_section (dwarf2_per_objfile->objfile, &dwarf2_per_objfile->str);
15207   if (dwarf2_per_objfile->str.buffer == NULL)
15208     error (_("DW_FORM_strp used without .debug_str section [in module %s]"),
15209            bfd_get_filename (abfd));
15210   if (str_offset >= dwarf2_per_objfile->str.size)
15211     error (_("DW_FORM_strp pointing outside of "
15212              ".debug_str section [in module %s]"),
15213            bfd_get_filename (abfd));
15214   gdb_assert (HOST_CHAR_BIT == 8);
15215   if (dwarf2_per_objfile->str.buffer[str_offset] == '\0')
15216     return NULL;
15217   return (const char *) (dwarf2_per_objfile->str.buffer + str_offset);
15218 }
15219
15220 /* Read a string at offset STR_OFFSET in the .debug_str section from
15221    the .dwz file DWZ.  Throw an error if the offset is too large.  If
15222    the string consists of a single NUL byte, return NULL; otherwise
15223    return a pointer to the string.  */
15224
15225 static const char *
15226 read_indirect_string_from_dwz (struct dwz_file *dwz, LONGEST str_offset)
15227 {
15228   dwarf2_read_section (dwarf2_per_objfile->objfile, &dwz->str);
15229
15230   if (dwz->str.buffer == NULL)
15231     error (_("DW_FORM_GNU_strp_alt used without .debug_str "
15232              "section [in module %s]"),
15233            bfd_get_filename (dwz->dwz_bfd));
15234   if (str_offset >= dwz->str.size)
15235     error (_("DW_FORM_GNU_strp_alt pointing outside of "
15236              ".debug_str section [in module %s]"),
15237            bfd_get_filename (dwz->dwz_bfd));
15238   gdb_assert (HOST_CHAR_BIT == 8);
15239   if (dwz->str.buffer[str_offset] == '\0')
15240     return NULL;
15241   return (const char *) (dwz->str.buffer + str_offset);
15242 }
15243
15244 static const char *
15245 read_indirect_string (bfd *abfd, const gdb_byte *buf,
15246                       const struct comp_unit_head *cu_header,
15247                       unsigned int *bytes_read_ptr)
15248 {
15249   LONGEST str_offset = read_offset (abfd, buf, cu_header, bytes_read_ptr);
15250
15251   return read_indirect_string_at_offset (abfd, str_offset);
15252 }
15253
15254 static ULONGEST
15255 read_unsigned_leb128 (bfd *abfd, const gdb_byte *buf,
15256                       unsigned int *bytes_read_ptr)
15257 {
15258   ULONGEST result;
15259   unsigned int num_read;
15260   int i, shift;
15261   unsigned char byte;
15262
15263   result = 0;
15264   shift = 0;
15265   num_read = 0;
15266   i = 0;
15267   while (1)
15268     {
15269       byte = bfd_get_8 (abfd, buf);
15270       buf++;
15271       num_read++;
15272       result |= ((ULONGEST) (byte & 127) << shift);
15273       if ((byte & 128) == 0)
15274         {
15275           break;
15276         }
15277       shift += 7;
15278     }
15279   *bytes_read_ptr = num_read;
15280   return result;
15281 }
15282
15283 static LONGEST
15284 read_signed_leb128 (bfd *abfd, const gdb_byte *buf,
15285                     unsigned int *bytes_read_ptr)
15286 {
15287   LONGEST result;
15288   int i, shift, num_read;
15289   unsigned char byte;
15290
15291   result = 0;
15292   shift = 0;
15293   num_read = 0;
15294   i = 0;
15295   while (1)
15296     {
15297       byte = bfd_get_8 (abfd, buf);
15298       buf++;
15299       num_read++;
15300       result |= ((LONGEST) (byte & 127) << shift);
15301       shift += 7;
15302       if ((byte & 128) == 0)
15303         {
15304           break;
15305         }
15306     }
15307   if ((shift < 8 * sizeof (result)) && (byte & 0x40))
15308     result |= -(((LONGEST) 1) << shift);
15309   *bytes_read_ptr = num_read;
15310   return result;
15311 }
15312
15313 /* Given index ADDR_INDEX in .debug_addr, fetch the value.
15314    ADDR_BASE is the DW_AT_GNU_addr_base attribute or zero.
15315    ADDR_SIZE is the size of addresses from the CU header.  */
15316
15317 static CORE_ADDR
15318 read_addr_index_1 (unsigned int addr_index, ULONGEST addr_base, int addr_size)
15319 {
15320   struct objfile *objfile = dwarf2_per_objfile->objfile;
15321   bfd *abfd = objfile->obfd;
15322   const gdb_byte *info_ptr;
15323
15324   dwarf2_read_section (objfile, &dwarf2_per_objfile->addr);
15325   if (dwarf2_per_objfile->addr.buffer == NULL)
15326     error (_("DW_FORM_addr_index used without .debug_addr section [in module %s]"),
15327            objfile_name (objfile));
15328   if (addr_base + addr_index * addr_size >= dwarf2_per_objfile->addr.size)
15329     error (_("DW_FORM_addr_index pointing outside of "
15330              ".debug_addr section [in module %s]"),
15331            objfile_name (objfile));
15332   info_ptr = (dwarf2_per_objfile->addr.buffer
15333               + addr_base + addr_index * addr_size);
15334   if (addr_size == 4)
15335     return bfd_get_32 (abfd, info_ptr);
15336   else
15337     return bfd_get_64 (abfd, info_ptr);
15338 }
15339
15340 /* Given index ADDR_INDEX in .debug_addr, fetch the value.  */
15341
15342 static CORE_ADDR
15343 read_addr_index (struct dwarf2_cu *cu, unsigned int addr_index)
15344 {
15345   return read_addr_index_1 (addr_index, cu->addr_base, cu->header.addr_size);
15346 }
15347
15348 /* Given a pointer to an leb128 value, fetch the value from .debug_addr.  */
15349
15350 static CORE_ADDR
15351 read_addr_index_from_leb128 (struct dwarf2_cu *cu, const gdb_byte *info_ptr,
15352                              unsigned int *bytes_read)
15353 {
15354   bfd *abfd = cu->objfile->obfd;
15355   unsigned int addr_index = read_unsigned_leb128 (abfd, info_ptr, bytes_read);
15356
15357   return read_addr_index (cu, addr_index);
15358 }
15359
15360 /* Data structure to pass results from dwarf2_read_addr_index_reader
15361    back to dwarf2_read_addr_index.  */
15362
15363 struct dwarf2_read_addr_index_data
15364 {
15365   ULONGEST addr_base;
15366   int addr_size;
15367 };
15368
15369 /* die_reader_func for dwarf2_read_addr_index.  */
15370
15371 static void
15372 dwarf2_read_addr_index_reader (const struct die_reader_specs *reader,
15373                                const gdb_byte *info_ptr,
15374                                struct die_info *comp_unit_die,
15375                                int has_children,
15376                                void *data)
15377 {
15378   struct dwarf2_cu *cu = reader->cu;
15379   struct dwarf2_read_addr_index_data *aidata =
15380     (struct dwarf2_read_addr_index_data *) data;
15381
15382   aidata->addr_base = cu->addr_base;
15383   aidata->addr_size = cu->header.addr_size;
15384 }
15385
15386 /* Given an index in .debug_addr, fetch the value.
15387    NOTE: This can be called during dwarf expression evaluation,
15388    long after the debug information has been read, and thus per_cu->cu
15389    may no longer exist.  */
15390
15391 CORE_ADDR
15392 dwarf2_read_addr_index (struct dwarf2_per_cu_data *per_cu,
15393                         unsigned int addr_index)
15394 {
15395   struct objfile *objfile = per_cu->objfile;
15396   struct dwarf2_cu *cu = per_cu->cu;
15397   ULONGEST addr_base;
15398   int addr_size;
15399
15400   /* This is intended to be called from outside this file.  */
15401   dw2_setup (objfile);
15402
15403   /* We need addr_base and addr_size.
15404      If we don't have PER_CU->cu, we have to get it.
15405      Nasty, but the alternative is storing the needed info in PER_CU,
15406      which at this point doesn't seem justified: it's not clear how frequently
15407      it would get used and it would increase the size of every PER_CU.
15408      Entry points like dwarf2_per_cu_addr_size do a similar thing
15409      so we're not in uncharted territory here.
15410      Alas we need to be a bit more complicated as addr_base is contained
15411      in the DIE.
15412
15413      We don't need to read the entire CU(/TU).
15414      We just need the header and top level die.
15415
15416      IWBN to use the aging mechanism to let us lazily later discard the CU.
15417      For now we skip this optimization.  */
15418
15419   if (cu != NULL)
15420     {
15421       addr_base = cu->addr_base;
15422       addr_size = cu->header.addr_size;
15423     }
15424   else
15425     {
15426       struct dwarf2_read_addr_index_data aidata;
15427
15428       /* Note: We can't use init_cutu_and_read_dies_simple here,
15429          we need addr_base.  */
15430       init_cutu_and_read_dies (per_cu, NULL, 0, 0,
15431                                dwarf2_read_addr_index_reader, &aidata);
15432       addr_base = aidata.addr_base;
15433       addr_size = aidata.addr_size;
15434     }
15435
15436   return read_addr_index_1 (addr_index, addr_base, addr_size);
15437 }
15438
15439 /* Given a DW_AT_str_index, fetch the string.  */
15440
15441 static const char *
15442 read_str_index (const struct die_reader_specs *reader,
15443                 struct dwarf2_cu *cu, ULONGEST str_index)
15444 {
15445   struct objfile *objfile = dwarf2_per_objfile->objfile;
15446   const char *dwo_name = objfile_name (objfile);
15447   bfd *abfd = objfile->obfd;
15448   struct dwo_sections *sections = &reader->dwo_file->sections;
15449   const gdb_byte *info_ptr;
15450   ULONGEST str_offset;
15451
15452   dwarf2_read_section (objfile, &sections->str);
15453   dwarf2_read_section (objfile, &sections->str_offsets);
15454   if (sections->str.buffer == NULL)
15455     error (_("DW_FORM_str_index used without .debug_str.dwo section"
15456              " in CU at offset 0x%lx [in module %s]"),
15457            (long) cu->header.offset.sect_off, dwo_name);
15458   if (sections->str_offsets.buffer == NULL)
15459     error (_("DW_FORM_str_index used without .debug_str_offsets.dwo section"
15460              " in CU at offset 0x%lx [in module %s]"),
15461            (long) cu->header.offset.sect_off, dwo_name);
15462   if (str_index * cu->header.offset_size >= sections->str_offsets.size)
15463     error (_("DW_FORM_str_index pointing outside of .debug_str_offsets.dwo"
15464              " section in CU at offset 0x%lx [in module %s]"),
15465            (long) cu->header.offset.sect_off, dwo_name);
15466   info_ptr = (sections->str_offsets.buffer
15467               + str_index * cu->header.offset_size);
15468   if (cu->header.offset_size == 4)
15469     str_offset = bfd_get_32 (abfd, info_ptr);
15470   else
15471     str_offset = bfd_get_64 (abfd, info_ptr);
15472   if (str_offset >= sections->str.size)
15473     error (_("Offset from DW_FORM_str_index pointing outside of"
15474              " .debug_str.dwo section in CU at offset 0x%lx [in module %s]"),
15475            (long) cu->header.offset.sect_off, dwo_name);
15476   return (const char *) (sections->str.buffer + str_offset);
15477 }
15478
15479 /* Return the length of an LEB128 number in BUF.  */
15480
15481 static int
15482 leb128_size (const gdb_byte *buf)
15483 {
15484   const gdb_byte *begin = buf;
15485   gdb_byte byte;
15486
15487   while (1)
15488     {
15489       byte = *buf++;
15490       if ((byte & 128) == 0)
15491         return buf - begin;
15492     }
15493 }
15494
15495 static void
15496 set_cu_language (unsigned int lang, struct dwarf2_cu *cu)
15497 {
15498   switch (lang)
15499     {
15500     case DW_LANG_C89:
15501     case DW_LANG_C99:
15502     case DW_LANG_C:
15503     case DW_LANG_UPC:
15504       cu->language = language_c;
15505       break;
15506     case DW_LANG_C_plus_plus:
15507       cu->language = language_cplus;
15508       break;
15509     case DW_LANG_D:
15510       cu->language = language_d;
15511       break;
15512     case DW_LANG_Fortran77:
15513     case DW_LANG_Fortran90:
15514     case DW_LANG_Fortran95:
15515       cu->language = language_fortran;
15516       break;
15517     case DW_LANG_Go:
15518       cu->language = language_go;
15519       break;
15520     case DW_LANG_Mips_Assembler:
15521       cu->language = language_asm;
15522       break;
15523     case DW_LANG_Java:
15524       cu->language = language_java;
15525       break;
15526     case DW_LANG_Ada83:
15527     case DW_LANG_Ada95:
15528       cu->language = language_ada;
15529       break;
15530     case DW_LANG_Modula2:
15531       cu->language = language_m2;
15532       break;
15533     case DW_LANG_Pascal83:
15534       cu->language = language_pascal;
15535       break;
15536     case DW_LANG_ObjC:
15537       cu->language = language_objc;
15538       break;
15539     case DW_LANG_Cobol74:
15540     case DW_LANG_Cobol85:
15541     default:
15542       cu->language = language_minimal;
15543       break;
15544     }
15545   cu->language_defn = language_def (cu->language);
15546 }
15547
15548 /* Return the named attribute or NULL if not there.  */
15549
15550 static struct attribute *
15551 dwarf2_attr (struct die_info *die, unsigned int name, struct dwarf2_cu *cu)
15552 {
15553   for (;;)
15554     {
15555       unsigned int i;
15556       struct attribute *spec = NULL;
15557
15558       for (i = 0; i < die->num_attrs; ++i)
15559         {
15560           if (die->attrs[i].name == name)
15561             return &die->attrs[i];
15562           if (die->attrs[i].name == DW_AT_specification
15563               || die->attrs[i].name == DW_AT_abstract_origin)
15564             spec = &die->attrs[i];
15565         }
15566
15567       if (!spec)
15568         break;
15569
15570       die = follow_die_ref (die, spec, &cu);
15571     }
15572
15573   return NULL;
15574 }
15575
15576 /* Return the named attribute or NULL if not there,
15577    but do not follow DW_AT_specification, etc.
15578    This is for use in contexts where we're reading .debug_types dies.
15579    Following DW_AT_specification, DW_AT_abstract_origin will take us
15580    back up the chain, and we want to go down.  */
15581
15582 static struct attribute *
15583 dwarf2_attr_no_follow (struct die_info *die, unsigned int name)
15584 {
15585   unsigned int i;
15586
15587   for (i = 0; i < die->num_attrs; ++i)
15588     if (die->attrs[i].name == name)
15589       return &die->attrs[i];
15590
15591   return NULL;
15592 }
15593
15594 /* Return non-zero iff the attribute NAME is defined for the given DIE,
15595    and holds a non-zero value.  This function should only be used for
15596    DW_FORM_flag or DW_FORM_flag_present attributes.  */
15597
15598 static int
15599 dwarf2_flag_true_p (struct die_info *die, unsigned name, struct dwarf2_cu *cu)
15600 {
15601   struct attribute *attr = dwarf2_attr (die, name, cu);
15602
15603   return (attr && DW_UNSND (attr));
15604 }
15605
15606 static int
15607 die_is_declaration (struct die_info *die, struct dwarf2_cu *cu)
15608 {
15609   /* A DIE is a declaration if it has a DW_AT_declaration attribute
15610      which value is non-zero.  However, we have to be careful with
15611      DIEs having a DW_AT_specification attribute, because dwarf2_attr()
15612      (via dwarf2_flag_true_p) follows this attribute.  So we may
15613      end up accidently finding a declaration attribute that belongs
15614      to a different DIE referenced by the specification attribute,
15615      even though the given DIE does not have a declaration attribute.  */
15616   return (dwarf2_flag_true_p (die, DW_AT_declaration, cu)
15617           && dwarf2_attr (die, DW_AT_specification, cu) == NULL);
15618 }
15619
15620 /* Return the die giving the specification for DIE, if there is
15621    one.  *SPEC_CU is the CU containing DIE on input, and the CU
15622    containing the return value on output.  If there is no
15623    specification, but there is an abstract origin, that is
15624    returned.  */
15625
15626 static struct die_info *
15627 die_specification (struct die_info *die, struct dwarf2_cu **spec_cu)
15628 {
15629   struct attribute *spec_attr = dwarf2_attr (die, DW_AT_specification,
15630                                              *spec_cu);
15631
15632   if (spec_attr == NULL)
15633     spec_attr = dwarf2_attr (die, DW_AT_abstract_origin, *spec_cu);
15634
15635   if (spec_attr == NULL)
15636     return NULL;
15637   else
15638     return follow_die_ref (die, spec_attr, spec_cu);
15639 }
15640
15641 /* Free the line_header structure *LH, and any arrays and strings it
15642    refers to.
15643    NOTE: This is also used as a "cleanup" function.  */
15644
15645 static void
15646 free_line_header (struct line_header *lh)
15647 {
15648   if (lh->standard_opcode_lengths)
15649     xfree (lh->standard_opcode_lengths);
15650
15651   /* Remember that all the lh->file_names[i].name pointers are
15652      pointers into debug_line_buffer, and don't need to be freed.  */
15653   if (lh->file_names)
15654     xfree (lh->file_names);
15655
15656   /* Similarly for the include directory names.  */
15657   if (lh->include_dirs)
15658     xfree (lh->include_dirs);
15659
15660   xfree (lh);
15661 }
15662
15663 /* Add an entry to LH's include directory table.  */
15664
15665 static void
15666 add_include_dir (struct line_header *lh, const char *include_dir)
15667 {
15668   /* Grow the array if necessary.  */
15669   if (lh->include_dirs_size == 0)
15670     {
15671       lh->include_dirs_size = 1; /* for testing */
15672       lh->include_dirs = xmalloc (lh->include_dirs_size
15673                                   * sizeof (*lh->include_dirs));
15674     }
15675   else if (lh->num_include_dirs >= lh->include_dirs_size)
15676     {
15677       lh->include_dirs_size *= 2;
15678       lh->include_dirs = xrealloc (lh->include_dirs,
15679                                    (lh->include_dirs_size
15680                                     * sizeof (*lh->include_dirs)));
15681     }
15682
15683   lh->include_dirs[lh->num_include_dirs++] = include_dir;
15684 }
15685
15686 /* Add an entry to LH's file name table.  */
15687
15688 static void
15689 add_file_name (struct line_header *lh,
15690                const char *name,
15691                unsigned int dir_index,
15692                unsigned int mod_time,
15693                unsigned int length)
15694 {
15695   struct file_entry *fe;
15696
15697   /* Grow the array if necessary.  */
15698   if (lh->file_names_size == 0)
15699     {
15700       lh->file_names_size = 1; /* for testing */
15701       lh->file_names = xmalloc (lh->file_names_size
15702                                 * sizeof (*lh->file_names));
15703     }
15704   else if (lh->num_file_names >= lh->file_names_size)
15705     {
15706       lh->file_names_size *= 2;
15707       lh->file_names = xrealloc (lh->file_names,
15708                                  (lh->file_names_size
15709                                   * sizeof (*lh->file_names)));
15710     }
15711
15712   fe = &lh->file_names[lh->num_file_names++];
15713   fe->name = name;
15714   fe->dir_index = dir_index;
15715   fe->mod_time = mod_time;
15716   fe->length = length;
15717   fe->included_p = 0;
15718   fe->symtab = NULL;
15719 }
15720
15721 /* A convenience function to find the proper .debug_line section for a
15722    CU.  */
15723
15724 static struct dwarf2_section_info *
15725 get_debug_line_section (struct dwarf2_cu *cu)
15726 {
15727   struct dwarf2_section_info *section;
15728
15729   /* For TUs in DWO files, the DW_AT_stmt_list attribute lives in the
15730      DWO file.  */
15731   if (cu->dwo_unit && cu->per_cu->is_debug_types)
15732     section = &cu->dwo_unit->dwo_file->sections.line;
15733   else if (cu->per_cu->is_dwz)
15734     {
15735       struct dwz_file *dwz = dwarf2_get_dwz_file ();
15736
15737       section = &dwz->line;
15738     }
15739   else
15740     section = &dwarf2_per_objfile->line;
15741
15742   return section;
15743 }
15744
15745 /* Read the statement program header starting at OFFSET in
15746    .debug_line, or .debug_line.dwo.  Return a pointer
15747    to a struct line_header, allocated using xmalloc.
15748
15749    NOTE: the strings in the include directory and file name tables of
15750    the returned object point into the dwarf line section buffer,
15751    and must not be freed.  */
15752
15753 static struct line_header *
15754 dwarf_decode_line_header (unsigned int offset, struct dwarf2_cu *cu)
15755 {
15756   struct cleanup *back_to;
15757   struct line_header *lh;
15758   const gdb_byte *line_ptr;
15759   unsigned int bytes_read, offset_size;
15760   int i;
15761   const char *cur_dir, *cur_file;
15762   struct dwarf2_section_info *section;
15763   bfd *abfd;
15764
15765   section = get_debug_line_section (cu);
15766   dwarf2_read_section (dwarf2_per_objfile->objfile, section);
15767   if (section->buffer == NULL)
15768     {
15769       if (cu->dwo_unit && cu->per_cu->is_debug_types)
15770         complaint (&symfile_complaints, _("missing .debug_line.dwo section"));
15771       else
15772         complaint (&symfile_complaints, _("missing .debug_line section"));
15773       return 0;
15774     }
15775
15776   /* We can't do this until we know the section is non-empty.
15777      Only then do we know we have such a section.  */
15778   abfd = section->asection->owner;
15779
15780   /* Make sure that at least there's room for the total_length field.
15781      That could be 12 bytes long, but we're just going to fudge that.  */
15782   if (offset + 4 >= section->size)
15783     {
15784       dwarf2_statement_list_fits_in_line_number_section_complaint ();
15785       return 0;
15786     }
15787
15788   lh = xmalloc (sizeof (*lh));
15789   memset (lh, 0, sizeof (*lh));
15790   back_to = make_cleanup ((make_cleanup_ftype *) free_line_header,
15791                           (void *) lh);
15792
15793   line_ptr = section->buffer + offset;
15794
15795   /* Read in the header.  */
15796   lh->total_length =
15797     read_checked_initial_length_and_offset (abfd, line_ptr, &cu->header,
15798                                             &bytes_read, &offset_size);
15799   line_ptr += bytes_read;
15800   if (line_ptr + lh->total_length > (section->buffer + section->size))
15801     {
15802       dwarf2_statement_list_fits_in_line_number_section_complaint ();
15803       do_cleanups (back_to);
15804       return 0;
15805     }
15806   lh->statement_program_end = line_ptr + lh->total_length;
15807   lh->version = read_2_bytes (abfd, line_ptr);
15808   line_ptr += 2;
15809   lh->header_length = read_offset_1 (abfd, line_ptr, offset_size);
15810   line_ptr += offset_size;
15811   lh->minimum_instruction_length = read_1_byte (abfd, line_ptr);
15812   line_ptr += 1;
15813   if (lh->version >= 4)
15814     {
15815       lh->maximum_ops_per_instruction = read_1_byte (abfd, line_ptr);
15816       line_ptr += 1;
15817     }
15818   else
15819     lh->maximum_ops_per_instruction = 1;
15820
15821   if (lh->maximum_ops_per_instruction == 0)
15822     {
15823       lh->maximum_ops_per_instruction = 1;
15824       complaint (&symfile_complaints,
15825                  _("invalid maximum_ops_per_instruction "
15826                    "in `.debug_line' section"));
15827     }
15828
15829   lh->default_is_stmt = read_1_byte (abfd, line_ptr);
15830   line_ptr += 1;
15831   lh->line_base = read_1_signed_byte (abfd, line_ptr);
15832   line_ptr += 1;
15833   lh->line_range = read_1_byte (abfd, line_ptr);
15834   line_ptr += 1;
15835   lh->opcode_base = read_1_byte (abfd, line_ptr);
15836   line_ptr += 1;
15837   lh->standard_opcode_lengths
15838     = xmalloc (lh->opcode_base * sizeof (lh->standard_opcode_lengths[0]));
15839
15840   lh->standard_opcode_lengths[0] = 1;  /* This should never be used anyway.  */
15841   for (i = 1; i < lh->opcode_base; ++i)
15842     {
15843       lh->standard_opcode_lengths[i] = read_1_byte (abfd, line_ptr);
15844       line_ptr += 1;
15845     }
15846
15847   /* Read directory table.  */
15848   while ((cur_dir = read_direct_string (abfd, line_ptr, &bytes_read)) != NULL)
15849     {
15850       line_ptr += bytes_read;
15851       add_include_dir (lh, cur_dir);
15852     }
15853   line_ptr += bytes_read;
15854
15855   /* Read file name table.  */
15856   while ((cur_file = read_direct_string (abfd, line_ptr, &bytes_read)) != NULL)
15857     {
15858       unsigned int dir_index, mod_time, length;
15859
15860       line_ptr += bytes_read;
15861       dir_index = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
15862       line_ptr += bytes_read;
15863       mod_time = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
15864       line_ptr += bytes_read;
15865       length = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
15866       line_ptr += bytes_read;
15867
15868       add_file_name (lh, cur_file, dir_index, mod_time, length);
15869     }
15870   line_ptr += bytes_read;
15871   lh->statement_program_start = line_ptr;
15872
15873   if (line_ptr > (section->buffer + section->size))
15874     complaint (&symfile_complaints,
15875                _("line number info header doesn't "
15876                  "fit in `.debug_line' section"));
15877
15878   discard_cleanups (back_to);
15879   return lh;
15880 }
15881
15882 /* Subroutine of dwarf_decode_lines to simplify it.
15883    Return the file name of the psymtab for included file FILE_INDEX
15884    in line header LH of PST.
15885    COMP_DIR is the compilation directory (DW_AT_comp_dir) or NULL if unknown.
15886    If space for the result is malloc'd, it will be freed by a cleanup.
15887    Returns NULL if FILE_INDEX should be ignored, i.e., it is pst->filename.
15888
15889    The function creates dangling cleanup registration.  */
15890
15891 static const char *
15892 psymtab_include_file_name (const struct line_header *lh, int file_index,
15893                            const struct partial_symtab *pst,
15894                            const char *comp_dir)
15895 {
15896   const struct file_entry fe = lh->file_names [file_index];
15897   const char *include_name = fe.name;
15898   const char *include_name_to_compare = include_name;
15899   const char *dir_name = NULL;
15900   const char *pst_filename;
15901   char *copied_name = NULL;
15902   int file_is_pst;
15903
15904   if (fe.dir_index)
15905     dir_name = lh->include_dirs[fe.dir_index - 1];
15906
15907   if (!IS_ABSOLUTE_PATH (include_name)
15908       && (dir_name != NULL || comp_dir != NULL))
15909     {
15910       /* Avoid creating a duplicate psymtab for PST.
15911          We do this by comparing INCLUDE_NAME and PST_FILENAME.
15912          Before we do the comparison, however, we need to account
15913          for DIR_NAME and COMP_DIR.
15914          First prepend dir_name (if non-NULL).  If we still don't
15915          have an absolute path prepend comp_dir (if non-NULL).
15916          However, the directory we record in the include-file's
15917          psymtab does not contain COMP_DIR (to match the
15918          corresponding symtab(s)).
15919
15920          Example:
15921
15922          bash$ cd /tmp
15923          bash$ gcc -g ./hello.c
15924          include_name = "hello.c"
15925          dir_name = "."
15926          DW_AT_comp_dir = comp_dir = "/tmp"
15927          DW_AT_name = "./hello.c"  */
15928
15929       if (dir_name != NULL)
15930         {
15931           char *tem = concat (dir_name, SLASH_STRING,
15932                               include_name, (char *)NULL);
15933
15934           make_cleanup (xfree, tem);
15935           include_name = tem;
15936           include_name_to_compare = include_name;
15937         }
15938       if (!IS_ABSOLUTE_PATH (include_name) && comp_dir != NULL)
15939         {
15940           char *tem = concat (comp_dir, SLASH_STRING,
15941                               include_name, (char *)NULL);
15942
15943           make_cleanup (xfree, tem);
15944           include_name_to_compare = tem;
15945         }
15946     }
15947
15948   pst_filename = pst->filename;
15949   if (!IS_ABSOLUTE_PATH (pst_filename) && pst->dirname != NULL)
15950     {
15951       copied_name = concat (pst->dirname, SLASH_STRING,
15952                             pst_filename, (char *)NULL);
15953       pst_filename = copied_name;
15954     }
15955
15956   file_is_pst = FILENAME_CMP (include_name_to_compare, pst_filename) == 0;
15957
15958   if (copied_name != NULL)
15959     xfree (copied_name);
15960
15961   if (file_is_pst)
15962     return NULL;
15963   return include_name;
15964 }
15965
15966 /* Ignore this record_line request.  */
15967
15968 static void
15969 noop_record_line (struct subfile *subfile, int line, CORE_ADDR pc)
15970 {
15971   return;
15972 }
15973
15974 /* Subroutine of dwarf_decode_lines to simplify it.
15975    Process the line number information in LH.  */
15976
15977 static void
15978 dwarf_decode_lines_1 (struct line_header *lh, const char *comp_dir,
15979                       struct dwarf2_cu *cu, struct partial_symtab *pst)
15980 {
15981   const gdb_byte *line_ptr, *extended_end;
15982   const gdb_byte *line_end;
15983   unsigned int bytes_read, extended_len;
15984   unsigned char op_code, extended_op, adj_opcode;
15985   CORE_ADDR baseaddr;
15986   struct objfile *objfile = cu->objfile;
15987   bfd *abfd = objfile->obfd;
15988   struct gdbarch *gdbarch = get_objfile_arch (objfile);
15989   const int decode_for_pst_p = (pst != NULL);
15990   struct subfile *last_subfile = NULL;
15991   void (*p_record_line) (struct subfile *subfile, int line, CORE_ADDR pc)
15992     = record_line;
15993
15994   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
15995
15996   line_ptr = lh->statement_program_start;
15997   line_end = lh->statement_program_end;
15998
15999   /* Read the statement sequences until there's nothing left.  */
16000   while (line_ptr < line_end)
16001     {
16002       /* state machine registers  */
16003       CORE_ADDR address = 0;
16004       unsigned int file = 1;
16005       unsigned int line = 1;
16006       unsigned int column = 0;
16007       int is_stmt = lh->default_is_stmt;
16008       int basic_block = 0;
16009       int end_sequence = 0;
16010       CORE_ADDR addr;
16011       unsigned char op_index = 0;
16012
16013       if (!decode_for_pst_p && lh->num_file_names >= file)
16014         {
16015           /* Start a subfile for the current file of the state machine.  */
16016           /* lh->include_dirs and lh->file_names are 0-based, but the
16017              directory and file name numbers in the statement program
16018              are 1-based.  */
16019           struct file_entry *fe = &lh->file_names[file - 1];
16020           const char *dir = NULL;
16021
16022           if (fe->dir_index)
16023             dir = lh->include_dirs[fe->dir_index - 1];
16024
16025           dwarf2_start_subfile (fe->name, dir, comp_dir);
16026         }
16027
16028       /* Decode the table.  */
16029       while (!end_sequence)
16030         {
16031           op_code = read_1_byte (abfd, line_ptr);
16032           line_ptr += 1;
16033           if (line_ptr > line_end)
16034             {
16035               dwarf2_debug_line_missing_end_sequence_complaint ();
16036               break;
16037             }
16038
16039           if (op_code >= lh->opcode_base)
16040             {
16041               /* Special operand.  */
16042               adj_opcode = op_code - lh->opcode_base;
16043               address += (((op_index + (adj_opcode / lh->line_range))
16044                            / lh->maximum_ops_per_instruction)
16045                           * lh->minimum_instruction_length);
16046               op_index = ((op_index + (adj_opcode / lh->line_range))
16047                           % lh->maximum_ops_per_instruction);
16048               line += lh->line_base + (adj_opcode % lh->line_range);
16049               if (lh->num_file_names < file || file == 0)
16050                 dwarf2_debug_line_missing_file_complaint ();
16051               /* For now we ignore lines not starting on an
16052                  instruction boundary.  */
16053               else if (op_index == 0)
16054                 {
16055                   lh->file_names[file - 1].included_p = 1;
16056                   if (!decode_for_pst_p && is_stmt)
16057                     {
16058                       if (last_subfile != current_subfile)
16059                         {
16060                           addr = gdbarch_addr_bits_remove (gdbarch, address);
16061                           if (last_subfile)
16062                             (*p_record_line) (last_subfile, 0, addr);
16063                           last_subfile = current_subfile;
16064                         }
16065                       /* Append row to matrix using current values.  */
16066                       addr = gdbarch_addr_bits_remove (gdbarch, address);
16067                       (*p_record_line) (current_subfile, line, addr);
16068                     }
16069                 }
16070               basic_block = 0;
16071             }
16072           else switch (op_code)
16073             {
16074             case DW_LNS_extended_op:
16075               extended_len = read_unsigned_leb128 (abfd, line_ptr,
16076                                                    &bytes_read);
16077               line_ptr += bytes_read;
16078               extended_end = line_ptr + extended_len;
16079               extended_op = read_1_byte (abfd, line_ptr);
16080               line_ptr += 1;
16081               switch (extended_op)
16082                 {
16083                 case DW_LNE_end_sequence:
16084                   p_record_line = record_line;
16085                   end_sequence = 1;
16086                   break;
16087                 case DW_LNE_set_address:
16088                   address = read_address (abfd, line_ptr, cu, &bytes_read);
16089
16090                   if (address == 0 && !dwarf2_per_objfile->has_section_at_zero)
16091                     {
16092                       /* This line table is for a function which has been
16093                          GCd by the linker.  Ignore it.  PR gdb/12528 */
16094
16095                       long line_offset
16096                         = line_ptr - get_debug_line_section (cu)->buffer;
16097
16098                       complaint (&symfile_complaints,
16099                                  _(".debug_line address at offset 0x%lx is 0 "
16100                                    "[in module %s]"),
16101                                  line_offset, objfile_name (objfile));
16102                       p_record_line = noop_record_line;
16103                     }
16104
16105                   op_index = 0;
16106                   line_ptr += bytes_read;
16107                   address += baseaddr;
16108                   break;
16109                 case DW_LNE_define_file:
16110                   {
16111                     const char *cur_file;
16112                     unsigned int dir_index, mod_time, length;
16113
16114                     cur_file = read_direct_string (abfd, line_ptr,
16115                                                    &bytes_read);
16116                     line_ptr += bytes_read;
16117                     dir_index =
16118                       read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
16119                     line_ptr += bytes_read;
16120                     mod_time =
16121                       read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
16122                     line_ptr += bytes_read;
16123                     length =
16124                       read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
16125                     line_ptr += bytes_read;
16126                     add_file_name (lh, cur_file, dir_index, mod_time, length);
16127                   }
16128                   break;
16129                 case DW_LNE_set_discriminator:
16130                   /* The discriminator is not interesting to the debugger;
16131                      just ignore it.  */
16132                   line_ptr = extended_end;
16133                   break;
16134                 default:
16135                   complaint (&symfile_complaints,
16136                              _("mangled .debug_line section"));
16137                   return;
16138                 }
16139               /* Make sure that we parsed the extended op correctly.  If e.g.
16140                  we expected a different address size than the producer used,
16141                  we may have read the wrong number of bytes.  */
16142               if (line_ptr != extended_end)
16143                 {
16144                   complaint (&symfile_complaints,
16145                              _("mangled .debug_line section"));
16146                   return;
16147                 }
16148               break;
16149             case DW_LNS_copy:
16150               if (lh->num_file_names < file || file == 0)
16151                 dwarf2_debug_line_missing_file_complaint ();
16152               else
16153                 {
16154                   lh->file_names[file - 1].included_p = 1;
16155                   if (!decode_for_pst_p && is_stmt)
16156                     {
16157                       if (last_subfile != current_subfile)
16158                         {
16159                           addr = gdbarch_addr_bits_remove (gdbarch, address);
16160                           if (last_subfile)
16161                             (*p_record_line) (last_subfile, 0, addr);
16162                           last_subfile = current_subfile;
16163                         }
16164                       addr = gdbarch_addr_bits_remove (gdbarch, address);
16165                       (*p_record_line) (current_subfile, line, addr);
16166                     }
16167                 }
16168               basic_block = 0;
16169               break;
16170             case DW_LNS_advance_pc:
16171               {
16172                 CORE_ADDR adjust
16173                   = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
16174
16175                 address += (((op_index + adjust)
16176                              / lh->maximum_ops_per_instruction)
16177                             * lh->minimum_instruction_length);
16178                 op_index = ((op_index + adjust)
16179                             % lh->maximum_ops_per_instruction);
16180                 line_ptr += bytes_read;
16181               }
16182               break;
16183             case DW_LNS_advance_line:
16184               line += read_signed_leb128 (abfd, line_ptr, &bytes_read);
16185               line_ptr += bytes_read;
16186               break;
16187             case DW_LNS_set_file:
16188               {
16189                 /* The arrays lh->include_dirs and lh->file_names are
16190                    0-based, but the directory and file name numbers in
16191                    the statement program are 1-based.  */
16192                 struct file_entry *fe;
16193                 const char *dir = NULL;
16194
16195                 file = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
16196                 line_ptr += bytes_read;
16197                 if (lh->num_file_names < file || file == 0)
16198                   dwarf2_debug_line_missing_file_complaint ();
16199                 else
16200                   {
16201                     fe = &lh->file_names[file - 1];
16202                     if (fe->dir_index)
16203                       dir = lh->include_dirs[fe->dir_index - 1];
16204                     if (!decode_for_pst_p)
16205                       {
16206                         last_subfile = current_subfile;
16207                         dwarf2_start_subfile (fe->name, dir, comp_dir);
16208                       }
16209                   }
16210               }
16211               break;
16212             case DW_LNS_set_column:
16213               column = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
16214               line_ptr += bytes_read;
16215               break;
16216             case DW_LNS_negate_stmt:
16217               is_stmt = (!is_stmt);
16218               break;
16219             case DW_LNS_set_basic_block:
16220               basic_block = 1;
16221               break;
16222             /* Add to the address register of the state machine the
16223                address increment value corresponding to special opcode
16224                255.  I.e., this value is scaled by the minimum
16225                instruction length since special opcode 255 would have
16226                scaled the increment.  */
16227             case DW_LNS_const_add_pc:
16228               {
16229                 CORE_ADDR adjust = (255 - lh->opcode_base) / lh->line_range;
16230
16231                 address += (((op_index + adjust)
16232                              / lh->maximum_ops_per_instruction)
16233                             * lh->minimum_instruction_length);
16234                 op_index = ((op_index + adjust)
16235                             % lh->maximum_ops_per_instruction);
16236               }
16237               break;
16238             case DW_LNS_fixed_advance_pc:
16239               address += read_2_bytes (abfd, line_ptr);
16240               op_index = 0;
16241               line_ptr += 2;
16242               break;
16243             default:
16244               {
16245                 /* Unknown standard opcode, ignore it.  */
16246                 int i;
16247
16248                 for (i = 0; i < lh->standard_opcode_lengths[op_code]; i++)
16249                   {
16250                     (void) read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
16251                     line_ptr += bytes_read;
16252                   }
16253               }
16254             }
16255         }
16256       if (lh->num_file_names < file || file == 0)
16257         dwarf2_debug_line_missing_file_complaint ();
16258       else
16259         {
16260           lh->file_names[file - 1].included_p = 1;
16261           if (!decode_for_pst_p)
16262             {
16263               addr = gdbarch_addr_bits_remove (gdbarch, address);
16264               (*p_record_line) (current_subfile, 0, addr);
16265             }
16266         }
16267     }
16268 }
16269
16270 /* Decode the Line Number Program (LNP) for the given line_header
16271    structure and CU.  The actual information extracted and the type
16272    of structures created from the LNP depends on the value of PST.
16273
16274    1. If PST is NULL, then this procedure uses the data from the program
16275       to create all necessary symbol tables, and their linetables.
16276
16277    2. If PST is not NULL, this procedure reads the program to determine
16278       the list of files included by the unit represented by PST, and
16279       builds all the associated partial symbol tables.
16280
16281    COMP_DIR is the compilation directory (DW_AT_comp_dir) or NULL if unknown.
16282    It is used for relative paths in the line table.
16283    NOTE: When processing partial symtabs (pst != NULL),
16284    comp_dir == pst->dirname.
16285
16286    NOTE: It is important that psymtabs have the same file name (via strcmp)
16287    as the corresponding symtab.  Since COMP_DIR is not used in the name of the
16288    symtab we don't use it in the name of the psymtabs we create.
16289    E.g. expand_line_sal requires this when finding psymtabs to expand.
16290    A good testcase for this is mb-inline.exp.  */
16291
16292 static void
16293 dwarf_decode_lines (struct line_header *lh, const char *comp_dir,
16294                     struct dwarf2_cu *cu, struct partial_symtab *pst,
16295                     int want_line_info)
16296 {
16297   struct objfile *objfile = cu->objfile;
16298   const int decode_for_pst_p = (pst != NULL);
16299   struct subfile *first_subfile = current_subfile;
16300
16301   if (want_line_info)
16302     dwarf_decode_lines_1 (lh, comp_dir, cu, pst);
16303
16304   if (decode_for_pst_p)
16305     {
16306       int file_index;
16307
16308       /* Now that we're done scanning the Line Header Program, we can
16309          create the psymtab of each included file.  */
16310       for (file_index = 0; file_index < lh->num_file_names; file_index++)
16311         if (lh->file_names[file_index].included_p == 1)
16312           {
16313             const char *include_name =
16314               psymtab_include_file_name (lh, file_index, pst, comp_dir);
16315             if (include_name != NULL)
16316               dwarf2_create_include_psymtab (include_name, pst, objfile);
16317           }
16318     }
16319   else
16320     {
16321       /* Make sure a symtab is created for every file, even files
16322          which contain only variables (i.e. no code with associated
16323          line numbers).  */
16324       int i;
16325
16326       for (i = 0; i < lh->num_file_names; i++)
16327         {
16328           const char *dir = NULL;
16329           struct file_entry *fe;
16330
16331           fe = &lh->file_names[i];
16332           if (fe->dir_index)
16333             dir = lh->include_dirs[fe->dir_index - 1];
16334           dwarf2_start_subfile (fe->name, dir, comp_dir);
16335
16336           /* Skip the main file; we don't need it, and it must be
16337              allocated last, so that it will show up before the
16338              non-primary symtabs in the objfile's symtab list.  */
16339           if (current_subfile == first_subfile)
16340             continue;
16341
16342           if (current_subfile->symtab == NULL)
16343             current_subfile->symtab = allocate_symtab (current_subfile->name,
16344                                                        objfile);
16345           fe->symtab = current_subfile->symtab;
16346         }
16347     }
16348 }
16349
16350 /* Start a subfile for DWARF.  FILENAME is the name of the file and
16351    DIRNAME the name of the source directory which contains FILENAME
16352    or NULL if not known.  COMP_DIR is the compilation directory for the
16353    linetable's compilation unit or NULL if not known.
16354    This routine tries to keep line numbers from identical absolute and
16355    relative file names in a common subfile.
16356
16357    Using the `list' example from the GDB testsuite, which resides in
16358    /srcdir and compiling it with Irix6.2 cc in /compdir using a filename
16359    of /srcdir/list0.c yields the following debugging information for list0.c:
16360
16361    DW_AT_name:          /srcdir/list0.c
16362    DW_AT_comp_dir:              /compdir
16363    files.files[0].name: list0.h
16364    files.files[0].dir:  /srcdir
16365    files.files[1].name: list0.c
16366    files.files[1].dir:  /srcdir
16367
16368    The line number information for list0.c has to end up in a single
16369    subfile, so that `break /srcdir/list0.c:1' works as expected.
16370    start_subfile will ensure that this happens provided that we pass the
16371    concatenation of files.files[1].dir and files.files[1].name as the
16372    subfile's name.  */
16373
16374 static void
16375 dwarf2_start_subfile (const char *filename, const char *dirname,
16376                       const char *comp_dir)
16377 {
16378   char *copy = NULL;
16379
16380   /* While reading the DIEs, we call start_symtab(DW_AT_name, DW_AT_comp_dir).
16381      `start_symtab' will always pass the contents of DW_AT_comp_dir as
16382      second argument to start_subfile.  To be consistent, we do the
16383      same here.  In order not to lose the line information directory,
16384      we concatenate it to the filename when it makes sense.
16385      Note that the Dwarf3 standard says (speaking of filenames in line
16386      information): ``The directory index is ignored for file names
16387      that represent full path names''.  Thus ignoring dirname in the
16388      `else' branch below isn't an issue.  */
16389
16390   if (!IS_ABSOLUTE_PATH (filename) && dirname != NULL)
16391     {
16392       copy = concat (dirname, SLASH_STRING, filename, (char *)NULL);
16393       filename = copy;
16394     }
16395
16396   start_subfile (filename, comp_dir);
16397
16398   if (copy != NULL)
16399     xfree (copy);
16400 }
16401
16402 /* Start a symtab for DWARF.
16403    NAME, COMP_DIR, LOW_PC are passed to start_symtab.  */
16404
16405 static void
16406 dwarf2_start_symtab (struct dwarf2_cu *cu,
16407                      const char *name, const char *comp_dir, CORE_ADDR low_pc)
16408 {
16409   start_symtab (name, comp_dir, low_pc);
16410   record_debugformat ("DWARF 2");
16411   record_producer (cu->producer);
16412
16413   /* We assume that we're processing GCC output.  */
16414   processing_gcc_compilation = 2;
16415
16416   cu->processing_has_namespace_info = 0;
16417 }
16418
16419 static void
16420 var_decode_location (struct attribute *attr, struct symbol *sym,
16421                      struct dwarf2_cu *cu)
16422 {
16423   struct objfile *objfile = cu->objfile;
16424   struct comp_unit_head *cu_header = &cu->header;
16425
16426   /* NOTE drow/2003-01-30: There used to be a comment and some special
16427      code here to turn a symbol with DW_AT_external and a
16428      SYMBOL_VALUE_ADDRESS of 0 into a LOC_UNRESOLVED symbol.  This was
16429      necessary for platforms (maybe Alpha, certainly PowerPC GNU/Linux
16430      with some versions of binutils) where shared libraries could have
16431      relocations against symbols in their debug information - the
16432      minimal symbol would have the right address, but the debug info
16433      would not.  It's no longer necessary, because we will explicitly
16434      apply relocations when we read in the debug information now.  */
16435
16436   /* A DW_AT_location attribute with no contents indicates that a
16437      variable has been optimized away.  */
16438   if (attr_form_is_block (attr) && DW_BLOCK (attr)->size == 0)
16439     {
16440       SYMBOL_ACLASS_INDEX (sym) = LOC_OPTIMIZED_OUT;
16441       return;
16442     }
16443
16444   /* Handle one degenerate form of location expression specially, to
16445      preserve GDB's previous behavior when section offsets are
16446      specified.  If this is just a DW_OP_addr or DW_OP_GNU_addr_index
16447      then mark this symbol as LOC_STATIC.  */
16448
16449   if (attr_form_is_block (attr)
16450       && ((DW_BLOCK (attr)->data[0] == DW_OP_addr
16451            && DW_BLOCK (attr)->size == 1 + cu_header->addr_size)
16452           || (DW_BLOCK (attr)->data[0] == DW_OP_GNU_addr_index
16453               && (DW_BLOCK (attr)->size
16454                   == 1 + leb128_size (&DW_BLOCK (attr)->data[1])))))
16455     {
16456       unsigned int dummy;
16457
16458       if (DW_BLOCK (attr)->data[0] == DW_OP_addr)
16459         SYMBOL_VALUE_ADDRESS (sym) =
16460           read_address (objfile->obfd, DW_BLOCK (attr)->data + 1, cu, &dummy);
16461       else
16462         SYMBOL_VALUE_ADDRESS (sym) =
16463           read_addr_index_from_leb128 (cu, DW_BLOCK (attr)->data + 1, &dummy);
16464       SYMBOL_ACLASS_INDEX (sym) = LOC_STATIC;
16465       fixup_symbol_section (sym, objfile);
16466       SYMBOL_VALUE_ADDRESS (sym) += ANOFFSET (objfile->section_offsets,
16467                                               SYMBOL_SECTION (sym));
16468       return;
16469     }
16470
16471   /* NOTE drow/2002-01-30: It might be worthwhile to have a static
16472      expression evaluator, and use LOC_COMPUTED only when necessary
16473      (i.e. when the value of a register or memory location is
16474      referenced, or a thread-local block, etc.).  Then again, it might
16475      not be worthwhile.  I'm assuming that it isn't unless performance
16476      or memory numbers show me otherwise.  */
16477
16478   dwarf2_symbol_mark_computed (attr, sym, cu, 0);
16479
16480   if (SYMBOL_COMPUTED_OPS (sym)->location_has_loclist)
16481     cu->has_loclist = 1;
16482 }
16483
16484 /* Given a pointer to a DWARF information entry, figure out if we need
16485    to make a symbol table entry for it, and if so, create a new entry
16486    and return a pointer to it.
16487    If TYPE is NULL, determine symbol type from the die, otherwise
16488    used the passed type.
16489    If SPACE is not NULL, use it to hold the new symbol.  If it is
16490    NULL, allocate a new symbol on the objfile's obstack.  */
16491
16492 static struct symbol *
16493 new_symbol_full (struct die_info *die, struct type *type, struct dwarf2_cu *cu,
16494                  struct symbol *space)
16495 {
16496   struct objfile *objfile = cu->objfile;
16497   struct symbol *sym = NULL;
16498   const char *name;
16499   struct attribute *attr = NULL;
16500   struct attribute *attr2 = NULL;
16501   CORE_ADDR baseaddr;
16502   struct pending **list_to_add = NULL;
16503
16504   int inlined_func = (die->tag == DW_TAG_inlined_subroutine);
16505
16506   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
16507
16508   name = dwarf2_name (die, cu);
16509   if (name)
16510     {
16511       const char *linkagename;
16512       int suppress_add = 0;
16513
16514       if (space)
16515         sym = space;
16516       else
16517         sym = allocate_symbol (objfile);
16518       OBJSTAT (objfile, n_syms++);
16519
16520       /* Cache this symbol's name and the name's demangled form (if any).  */
16521       SYMBOL_SET_LANGUAGE (sym, cu->language, &objfile->objfile_obstack);
16522       linkagename = dwarf2_physname (name, die, cu);
16523       SYMBOL_SET_NAMES (sym, linkagename, strlen (linkagename), 0, objfile);
16524
16525       /* Fortran does not have mangling standard and the mangling does differ
16526          between gfortran, iFort etc.  */
16527       if (cu->language == language_fortran
16528           && symbol_get_demangled_name (&(sym->ginfo)) == NULL)
16529         symbol_set_demangled_name (&(sym->ginfo),
16530                                    dwarf2_full_name (name, die, cu),
16531                                    NULL);
16532
16533       /* Default assumptions.
16534          Use the passed type or decode it from the die.  */
16535       SYMBOL_DOMAIN (sym) = VAR_DOMAIN;
16536       SYMBOL_ACLASS_INDEX (sym) = LOC_OPTIMIZED_OUT;
16537       if (type != NULL)
16538         SYMBOL_TYPE (sym) = type;
16539       else
16540         SYMBOL_TYPE (sym) = die_type (die, cu);
16541       attr = dwarf2_attr (die,
16542                           inlined_func ? DW_AT_call_line : DW_AT_decl_line,
16543                           cu);
16544       if (attr)
16545         {
16546           SYMBOL_LINE (sym) = DW_UNSND (attr);
16547         }
16548
16549       attr = dwarf2_attr (die,
16550                           inlined_func ? DW_AT_call_file : DW_AT_decl_file,
16551                           cu);
16552       if (attr)
16553         {
16554           int file_index = DW_UNSND (attr);
16555
16556           if (cu->line_header == NULL
16557               || file_index > cu->line_header->num_file_names)
16558             complaint (&symfile_complaints,
16559                        _("file index out of range"));
16560           else if (file_index > 0)
16561             {
16562               struct file_entry *fe;
16563
16564               fe = &cu->line_header->file_names[file_index - 1];
16565               SYMBOL_SYMTAB (sym) = fe->symtab;
16566             }
16567         }
16568
16569       switch (die->tag)
16570         {
16571         case DW_TAG_label:
16572           attr = dwarf2_attr (die, DW_AT_low_pc, cu);
16573           if (attr)
16574             {
16575               SYMBOL_VALUE_ADDRESS (sym) = DW_ADDR (attr) + baseaddr;
16576             }
16577           SYMBOL_TYPE (sym) = objfile_type (objfile)->builtin_core_addr;
16578           SYMBOL_DOMAIN (sym) = LABEL_DOMAIN;
16579           SYMBOL_ACLASS_INDEX (sym) = LOC_LABEL;
16580           add_symbol_to_list (sym, cu->list_in_scope);
16581           break;
16582         case DW_TAG_subprogram:
16583           /* SYMBOL_BLOCK_VALUE (sym) will be filled in later by
16584              finish_block.  */
16585           SYMBOL_ACLASS_INDEX (sym) = LOC_BLOCK;
16586           attr2 = dwarf2_attr (die, DW_AT_external, cu);
16587           if ((attr2 && (DW_UNSND (attr2) != 0))
16588               || cu->language == language_ada)
16589             {
16590               /* Subprograms marked external are stored as a global symbol.
16591                  Ada subprograms, whether marked external or not, are always
16592                  stored as a global symbol, because we want to be able to
16593                  access them globally.  For instance, we want to be able
16594                  to break on a nested subprogram without having to
16595                  specify the context.  */
16596               list_to_add = &global_symbols;
16597             }
16598           else
16599             {
16600               list_to_add = cu->list_in_scope;
16601             }
16602           break;
16603         case DW_TAG_inlined_subroutine:
16604           /* SYMBOL_BLOCK_VALUE (sym) will be filled in later by
16605              finish_block.  */
16606           SYMBOL_ACLASS_INDEX (sym) = LOC_BLOCK;
16607           SYMBOL_INLINED (sym) = 1;
16608           list_to_add = cu->list_in_scope;
16609           break;
16610         case DW_TAG_template_value_param:
16611           suppress_add = 1;
16612           /* Fall through.  */
16613         case DW_TAG_constant:
16614         case DW_TAG_variable:
16615         case DW_TAG_member:
16616           /* Compilation with minimal debug info may result in
16617              variables with missing type entries.  Change the
16618              misleading `void' type to something sensible.  */
16619           if (TYPE_CODE (SYMBOL_TYPE (sym)) == TYPE_CODE_VOID)
16620             SYMBOL_TYPE (sym)
16621               = objfile_type (objfile)->nodebug_data_symbol;
16622
16623           attr = dwarf2_attr (die, DW_AT_const_value, cu);
16624           /* In the case of DW_TAG_member, we should only be called for
16625              static const members.  */
16626           if (die->tag == DW_TAG_member)
16627             {
16628               /* dwarf2_add_field uses die_is_declaration,
16629                  so we do the same.  */
16630               gdb_assert (die_is_declaration (die, cu));
16631               gdb_assert (attr);
16632             }
16633           if (attr)
16634             {
16635               dwarf2_const_value (attr, sym, cu);
16636               attr2 = dwarf2_attr (die, DW_AT_external, cu);
16637               if (!suppress_add)
16638                 {
16639                   if (attr2 && (DW_UNSND (attr2) != 0))
16640                     list_to_add = &global_symbols;
16641                   else
16642                     list_to_add = cu->list_in_scope;
16643                 }
16644               break;
16645             }
16646           attr = dwarf2_attr (die, DW_AT_location, cu);
16647           if (attr)
16648             {
16649               var_decode_location (attr, sym, cu);
16650               attr2 = dwarf2_attr (die, DW_AT_external, cu);
16651
16652               /* Fortran explicitly imports any global symbols to the local
16653                  scope by DW_TAG_common_block.  */
16654               if (cu->language == language_fortran && die->parent
16655                   && die->parent->tag == DW_TAG_common_block)
16656                 attr2 = NULL;
16657
16658               if (SYMBOL_CLASS (sym) == LOC_STATIC
16659                   && SYMBOL_VALUE_ADDRESS (sym) == 0
16660                   && !dwarf2_per_objfile->has_section_at_zero)
16661                 {
16662                   /* When a static variable is eliminated by the linker,
16663                      the corresponding debug information is not stripped
16664                      out, but the variable address is set to null;
16665                      do not add such variables into symbol table.  */
16666                 }
16667               else if (attr2 && (DW_UNSND (attr2) != 0))
16668                 {
16669                   /* Workaround gfortran PR debug/40040 - it uses
16670                      DW_AT_location for variables in -fPIC libraries which may
16671                      get overriden by other libraries/executable and get
16672                      a different address.  Resolve it by the minimal symbol
16673                      which may come from inferior's executable using copy
16674                      relocation.  Make this workaround only for gfortran as for
16675                      other compilers GDB cannot guess the minimal symbol
16676                      Fortran mangling kind.  */
16677                   if (cu->language == language_fortran && die->parent
16678                       && die->parent->tag == DW_TAG_module
16679                       && cu->producer
16680                       && strncmp (cu->producer, "GNU Fortran ", 12) == 0)
16681                     SYMBOL_ACLASS_INDEX (sym) = LOC_UNRESOLVED;
16682
16683                   /* A variable with DW_AT_external is never static,
16684                      but it may be block-scoped.  */
16685                   list_to_add = (cu->list_in_scope == &file_symbols
16686                                  ? &global_symbols : cu->list_in_scope);
16687                 }
16688               else
16689                 list_to_add = cu->list_in_scope;
16690             }
16691           else
16692             {
16693               /* We do not know the address of this symbol.
16694                  If it is an external symbol and we have type information
16695                  for it, enter the symbol as a LOC_UNRESOLVED symbol.
16696                  The address of the variable will then be determined from
16697                  the minimal symbol table whenever the variable is
16698                  referenced.  */
16699               attr2 = dwarf2_attr (die, DW_AT_external, cu);
16700
16701               /* Fortran explicitly imports any global symbols to the local
16702                  scope by DW_TAG_common_block.  */
16703               if (cu->language == language_fortran && die->parent
16704                   && die->parent->tag == DW_TAG_common_block)
16705                 {
16706                   /* SYMBOL_CLASS doesn't matter here because
16707                      read_common_block is going to reset it.  */
16708                   if (!suppress_add)
16709                     list_to_add = cu->list_in_scope;
16710                 }
16711               else if (attr2 && (DW_UNSND (attr2) != 0)
16712                        && dwarf2_attr (die, DW_AT_type, cu) != NULL)
16713                 {
16714                   /* A variable with DW_AT_external is never static, but it
16715                      may be block-scoped.  */
16716                   list_to_add = (cu->list_in_scope == &file_symbols
16717                                  ? &global_symbols : cu->list_in_scope);
16718
16719                   SYMBOL_ACLASS_INDEX (sym) = LOC_UNRESOLVED;
16720                 }
16721               else if (!die_is_declaration (die, cu))
16722                 {
16723                   /* Use the default LOC_OPTIMIZED_OUT class.  */
16724                   gdb_assert (SYMBOL_CLASS (sym) == LOC_OPTIMIZED_OUT);
16725                   if (!suppress_add)
16726                     list_to_add = cu->list_in_scope;
16727                 }
16728             }
16729           break;
16730         case DW_TAG_formal_parameter:
16731           /* If we are inside a function, mark this as an argument.  If
16732              not, we might be looking at an argument to an inlined function
16733              when we do not have enough information to show inlined frames;
16734              pretend it's a local variable in that case so that the user can
16735              still see it.  */
16736           if (context_stack_depth > 0
16737               && context_stack[context_stack_depth - 1].name != NULL)
16738             SYMBOL_IS_ARGUMENT (sym) = 1;
16739           attr = dwarf2_attr (die, DW_AT_location, cu);
16740           if (attr)
16741             {
16742               var_decode_location (attr, sym, cu);
16743             }
16744           attr = dwarf2_attr (die, DW_AT_const_value, cu);
16745           if (attr)
16746             {
16747               dwarf2_const_value (attr, sym, cu);
16748             }
16749
16750           list_to_add = cu->list_in_scope;
16751           break;
16752         case DW_TAG_unspecified_parameters:
16753           /* From varargs functions; gdb doesn't seem to have any
16754              interest in this information, so just ignore it for now.
16755              (FIXME?) */
16756           break;
16757         case DW_TAG_template_type_param:
16758           suppress_add = 1;
16759           /* Fall through.  */
16760         case DW_TAG_class_type:
16761         case DW_TAG_interface_type:
16762         case DW_TAG_structure_type:
16763         case DW_TAG_union_type:
16764         case DW_TAG_set_type:
16765         case DW_TAG_enumeration_type:
16766           SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
16767           SYMBOL_DOMAIN (sym) = STRUCT_DOMAIN;
16768
16769           {
16770             /* NOTE: carlton/2003-11-10: C++ and Java class symbols shouldn't
16771                really ever be static objects: otherwise, if you try
16772                to, say, break of a class's method and you're in a file
16773                which doesn't mention that class, it won't work unless
16774                the check for all static symbols in lookup_symbol_aux
16775                saves you.  See the OtherFileClass tests in
16776                gdb.c++/namespace.exp.  */
16777
16778             if (!suppress_add)
16779               {
16780                 list_to_add = (cu->list_in_scope == &file_symbols
16781                                && (cu->language == language_cplus
16782                                    || cu->language == language_java)
16783                                ? &global_symbols : cu->list_in_scope);
16784
16785                 /* The semantics of C++ state that "struct foo {
16786                    ... }" also defines a typedef for "foo".  A Java
16787                    class declaration also defines a typedef for the
16788                    class.  */
16789                 if (cu->language == language_cplus
16790                     || cu->language == language_java
16791                     || cu->language == language_ada)
16792                   {
16793                     /* The symbol's name is already allocated along
16794                        with this objfile, so we don't need to
16795                        duplicate it for the type.  */
16796                     if (TYPE_NAME (SYMBOL_TYPE (sym)) == 0)
16797                       TYPE_NAME (SYMBOL_TYPE (sym)) = SYMBOL_SEARCH_NAME (sym);
16798                   }
16799               }
16800           }
16801           break;
16802         case DW_TAG_typedef:
16803           SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
16804           SYMBOL_DOMAIN (sym) = VAR_DOMAIN;
16805           list_to_add = cu->list_in_scope;
16806           break;
16807         case DW_TAG_base_type:
16808         case DW_TAG_subrange_type:
16809           SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
16810           SYMBOL_DOMAIN (sym) = VAR_DOMAIN;
16811           list_to_add = cu->list_in_scope;
16812           break;
16813         case DW_TAG_enumerator:
16814           attr = dwarf2_attr (die, DW_AT_const_value, cu);
16815           if (attr)
16816             {
16817               dwarf2_const_value (attr, sym, cu);
16818             }
16819           {
16820             /* NOTE: carlton/2003-11-10: See comment above in the
16821                DW_TAG_class_type, etc. block.  */
16822
16823             list_to_add = (cu->list_in_scope == &file_symbols
16824                            && (cu->language == language_cplus
16825                                || cu->language == language_java)
16826                            ? &global_symbols : cu->list_in_scope);
16827           }
16828           break;
16829         case DW_TAG_namespace:
16830           SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
16831           list_to_add = &global_symbols;
16832           break;
16833         case DW_TAG_common_block:
16834           SYMBOL_ACLASS_INDEX (sym) = LOC_COMMON_BLOCK;
16835           SYMBOL_DOMAIN (sym) = COMMON_BLOCK_DOMAIN;
16836           add_symbol_to_list (sym, cu->list_in_scope);
16837           break;
16838         default:
16839           /* Not a tag we recognize.  Hopefully we aren't processing
16840              trash data, but since we must specifically ignore things
16841              we don't recognize, there is nothing else we should do at
16842              this point.  */
16843           complaint (&symfile_complaints, _("unsupported tag: '%s'"),
16844                      dwarf_tag_name (die->tag));
16845           break;
16846         }
16847
16848       if (suppress_add)
16849         {
16850           sym->hash_next = objfile->template_symbols;
16851           objfile->template_symbols = sym;
16852           list_to_add = NULL;
16853         }
16854
16855       if (list_to_add != NULL)
16856         add_symbol_to_list (sym, list_to_add);
16857
16858       /* For the benefit of old versions of GCC, check for anonymous
16859          namespaces based on the demangled name.  */
16860       if (!cu->processing_has_namespace_info
16861           && cu->language == language_cplus)
16862         cp_scan_for_anonymous_namespaces (sym, objfile);
16863     }
16864   return (sym);
16865 }
16866
16867 /* A wrapper for new_symbol_full that always allocates a new symbol.  */
16868
16869 static struct symbol *
16870 new_symbol (struct die_info *die, struct type *type, struct dwarf2_cu *cu)
16871 {
16872   return new_symbol_full (die, type, cu, NULL);
16873 }
16874
16875 /* Given an attr with a DW_FORM_dataN value in host byte order,
16876    zero-extend it as appropriate for the symbol's type.  The DWARF
16877    standard (v4) is not entirely clear about the meaning of using
16878    DW_FORM_dataN for a constant with a signed type, where the type is
16879    wider than the data.  The conclusion of a discussion on the DWARF
16880    list was that this is unspecified.  We choose to always zero-extend
16881    because that is the interpretation long in use by GCC.  */
16882
16883 static gdb_byte *
16884 dwarf2_const_value_data (const struct attribute *attr, struct obstack *obstack,
16885                          struct dwarf2_cu *cu, LONGEST *value, int bits)
16886 {
16887   struct objfile *objfile = cu->objfile;
16888   enum bfd_endian byte_order = bfd_big_endian (objfile->obfd) ?
16889                                 BFD_ENDIAN_BIG : BFD_ENDIAN_LITTLE;
16890   LONGEST l = DW_UNSND (attr);
16891
16892   if (bits < sizeof (*value) * 8)
16893     {
16894       l &= ((LONGEST) 1 << bits) - 1;
16895       *value = l;
16896     }
16897   else if (bits == sizeof (*value) * 8)
16898     *value = l;
16899   else
16900     {
16901       gdb_byte *bytes = obstack_alloc (obstack, bits / 8);
16902       store_unsigned_integer (bytes, bits / 8, byte_order, l);
16903       return bytes;
16904     }
16905
16906   return NULL;
16907 }
16908
16909 /* Read a constant value from an attribute.  Either set *VALUE, or if
16910    the value does not fit in *VALUE, set *BYTES - either already
16911    allocated on the objfile obstack, or newly allocated on OBSTACK,
16912    or, set *BATON, if we translated the constant to a location
16913    expression.  */
16914
16915 static void
16916 dwarf2_const_value_attr (const struct attribute *attr, struct type *type,
16917                          const char *name, struct obstack *obstack,
16918                          struct dwarf2_cu *cu,
16919                          LONGEST *value, const gdb_byte **bytes,
16920                          struct dwarf2_locexpr_baton **baton)
16921 {
16922   struct objfile *objfile = cu->objfile;
16923   struct comp_unit_head *cu_header = &cu->header;
16924   struct dwarf_block *blk;
16925   enum bfd_endian byte_order = (bfd_big_endian (objfile->obfd) ?
16926                                 BFD_ENDIAN_BIG : BFD_ENDIAN_LITTLE);
16927
16928   *value = 0;
16929   *bytes = NULL;
16930   *baton = NULL;
16931
16932   switch (attr->form)
16933     {
16934     case DW_FORM_addr:
16935     case DW_FORM_GNU_addr_index:
16936       {
16937         gdb_byte *data;
16938
16939         if (TYPE_LENGTH (type) != cu_header->addr_size)
16940           dwarf2_const_value_length_mismatch_complaint (name,
16941                                                         cu_header->addr_size,
16942                                                         TYPE_LENGTH (type));
16943         /* Symbols of this form are reasonably rare, so we just
16944            piggyback on the existing location code rather than writing
16945            a new implementation of symbol_computed_ops.  */
16946         *baton = obstack_alloc (obstack, sizeof (struct dwarf2_locexpr_baton));
16947         (*baton)->per_cu = cu->per_cu;
16948         gdb_assert ((*baton)->per_cu);
16949
16950         (*baton)->size = 2 + cu_header->addr_size;
16951         data = obstack_alloc (obstack, (*baton)->size);
16952         (*baton)->data = data;
16953
16954         data[0] = DW_OP_addr;
16955         store_unsigned_integer (&data[1], cu_header->addr_size,
16956                                 byte_order, DW_ADDR (attr));
16957         data[cu_header->addr_size + 1] = DW_OP_stack_value;
16958       }
16959       break;
16960     case DW_FORM_string:
16961     case DW_FORM_strp:
16962     case DW_FORM_GNU_str_index:
16963     case DW_FORM_GNU_strp_alt:
16964       /* DW_STRING is already allocated on the objfile obstack, point
16965          directly to it.  */
16966       *bytes = (const gdb_byte *) DW_STRING (attr);
16967       break;
16968     case DW_FORM_block1:
16969     case DW_FORM_block2:
16970     case DW_FORM_block4:
16971     case DW_FORM_block:
16972     case DW_FORM_exprloc:
16973       blk = DW_BLOCK (attr);
16974       if (TYPE_LENGTH (type) != blk->size)
16975         dwarf2_const_value_length_mismatch_complaint (name, blk->size,
16976                                                       TYPE_LENGTH (type));
16977       *bytes = blk->data;
16978       break;
16979
16980       /* The DW_AT_const_value attributes are supposed to carry the
16981          symbol's value "represented as it would be on the target
16982          architecture."  By the time we get here, it's already been
16983          converted to host endianness, so we just need to sign- or
16984          zero-extend it as appropriate.  */
16985     case DW_FORM_data1:
16986       *bytes = dwarf2_const_value_data (attr, obstack, cu, value, 8);
16987       break;
16988     case DW_FORM_data2:
16989       *bytes = dwarf2_const_value_data (attr, obstack, cu, value, 16);
16990       break;
16991     case DW_FORM_data4:
16992       *bytes = dwarf2_const_value_data (attr, obstack, cu, value, 32);
16993       break;
16994     case DW_FORM_data8:
16995       *bytes = dwarf2_const_value_data (attr, obstack, cu, value, 64);
16996       break;
16997
16998     case DW_FORM_sdata:
16999       *value = DW_SND (attr);
17000       break;
17001
17002     case DW_FORM_udata:
17003       *value = DW_UNSND (attr);
17004       break;
17005
17006     default:
17007       complaint (&symfile_complaints,
17008                  _("unsupported const value attribute form: '%s'"),
17009                  dwarf_form_name (attr->form));
17010       *value = 0;
17011       break;
17012     }
17013 }
17014
17015
17016 /* Copy constant value from an attribute to a symbol.  */
17017
17018 static void
17019 dwarf2_const_value (const struct attribute *attr, struct symbol *sym,
17020                     struct dwarf2_cu *cu)
17021 {
17022   struct objfile *objfile = cu->objfile;
17023   struct comp_unit_head *cu_header = &cu->header;
17024   LONGEST value;
17025   const gdb_byte *bytes;
17026   struct dwarf2_locexpr_baton *baton;
17027
17028   dwarf2_const_value_attr (attr, SYMBOL_TYPE (sym),
17029                            SYMBOL_PRINT_NAME (sym),
17030                            &objfile->objfile_obstack, cu,
17031                            &value, &bytes, &baton);
17032
17033   if (baton != NULL)
17034     {
17035       SYMBOL_LOCATION_BATON (sym) = baton;
17036       SYMBOL_ACLASS_INDEX (sym) = dwarf2_locexpr_index;
17037     }
17038   else if (bytes != NULL)
17039      {
17040       SYMBOL_VALUE_BYTES (sym) = bytes;
17041       SYMBOL_ACLASS_INDEX (sym) = LOC_CONST_BYTES;
17042     }
17043   else
17044     {
17045       SYMBOL_VALUE (sym) = value;
17046       SYMBOL_ACLASS_INDEX (sym) = LOC_CONST;
17047     }
17048 }
17049
17050 /* Return the type of the die in question using its DW_AT_type attribute.  */
17051
17052 static struct type *
17053 die_type (struct die_info *die, struct dwarf2_cu *cu)
17054 {
17055   struct attribute *type_attr;
17056
17057   type_attr = dwarf2_attr (die, DW_AT_type, cu);
17058   if (!type_attr)
17059     {
17060       /* A missing DW_AT_type represents a void type.  */
17061       return objfile_type (cu->objfile)->builtin_void;
17062     }
17063
17064   return lookup_die_type (die, type_attr, cu);
17065 }
17066
17067 /* True iff CU's producer generates GNAT Ada auxiliary information
17068    that allows to find parallel types through that information instead
17069    of having to do expensive parallel lookups by type name.  */
17070
17071 static int
17072 need_gnat_info (struct dwarf2_cu *cu)
17073 {
17074   /* FIXME: brobecker/2010-10-12: As of now, only the AdaCore version
17075      of GNAT produces this auxiliary information, without any indication
17076      that it is produced.  Part of enhancing the FSF version of GNAT
17077      to produce that information will be to put in place an indicator
17078      that we can use in order to determine whether the descriptive type
17079      info is available or not.  One suggestion that has been made is
17080      to use a new attribute, attached to the CU die.  For now, assume
17081      that the descriptive type info is not available.  */
17082   return 0;
17083 }
17084
17085 /* Return the auxiliary type of the die in question using its
17086    DW_AT_GNAT_descriptive_type attribute.  Returns NULL if the
17087    attribute is not present.  */
17088
17089 static struct type *
17090 die_descriptive_type (struct die_info *die, struct dwarf2_cu *cu)
17091 {
17092   struct attribute *type_attr;
17093
17094   type_attr = dwarf2_attr (die, DW_AT_GNAT_descriptive_type, cu);
17095   if (!type_attr)
17096     return NULL;
17097
17098   return lookup_die_type (die, type_attr, cu);
17099 }
17100
17101 /* If DIE has a descriptive_type attribute, then set the TYPE's
17102    descriptive type accordingly.  */
17103
17104 static void
17105 set_descriptive_type (struct type *type, struct die_info *die,
17106                       struct dwarf2_cu *cu)
17107 {
17108   struct type *descriptive_type = die_descriptive_type (die, cu);
17109
17110   if (descriptive_type)
17111     {
17112       ALLOCATE_GNAT_AUX_TYPE (type);
17113       TYPE_DESCRIPTIVE_TYPE (type) = descriptive_type;
17114     }
17115 }
17116
17117 /* Return the containing type of the die in question using its
17118    DW_AT_containing_type attribute.  */
17119
17120 static struct type *
17121 die_containing_type (struct die_info *die, struct dwarf2_cu *cu)
17122 {
17123   struct attribute *type_attr;
17124
17125   type_attr = dwarf2_attr (die, DW_AT_containing_type, cu);
17126   if (!type_attr)
17127     error (_("Dwarf Error: Problem turning containing type into gdb type "
17128              "[in module %s]"), objfile_name (cu->objfile));
17129
17130   return lookup_die_type (die, type_attr, cu);
17131 }
17132
17133 /* Return an error marker type to use for the ill formed type in DIE/CU.  */
17134
17135 static struct type *
17136 build_error_marker_type (struct dwarf2_cu *cu, struct die_info *die)
17137 {
17138   struct objfile *objfile = dwarf2_per_objfile->objfile;
17139   char *message, *saved;
17140
17141   message = xstrprintf (_("<unknown type in %s, CU 0x%x, DIE 0x%x>"),
17142                         objfile_name (objfile),
17143                         cu->header.offset.sect_off,
17144                         die->offset.sect_off);
17145   saved = obstack_copy0 (&objfile->objfile_obstack,
17146                          message, strlen (message));
17147   xfree (message);
17148
17149   return init_type (TYPE_CODE_ERROR, 0, 0, saved, objfile);
17150 }
17151
17152 /* Look up the type of DIE in CU using its type attribute ATTR.
17153    ATTR must be one of: DW_AT_type, DW_AT_GNAT_descriptive_type,
17154    DW_AT_containing_type.
17155    If there is no type substitute an error marker.  */
17156
17157 static struct type *
17158 lookup_die_type (struct die_info *die, const struct attribute *attr,
17159                  struct dwarf2_cu *cu)
17160 {
17161   struct objfile *objfile = cu->objfile;
17162   struct type *this_type;
17163
17164   gdb_assert (attr->name == DW_AT_type
17165               || attr->name == DW_AT_GNAT_descriptive_type
17166               || attr->name == DW_AT_containing_type);
17167
17168   /* First see if we have it cached.  */
17169
17170   if (attr->form == DW_FORM_GNU_ref_alt)
17171     {
17172       struct dwarf2_per_cu_data *per_cu;
17173       sect_offset offset = dwarf2_get_ref_die_offset (attr);
17174
17175       per_cu = dwarf2_find_containing_comp_unit (offset, 1, cu->objfile);
17176       this_type = get_die_type_at_offset (offset, per_cu);
17177     }
17178   else if (attr_form_is_ref (attr))
17179     {
17180       sect_offset offset = dwarf2_get_ref_die_offset (attr);
17181
17182       this_type = get_die_type_at_offset (offset, cu->per_cu);
17183     }
17184   else if (attr->form == DW_FORM_ref_sig8)
17185     {
17186       ULONGEST signature = DW_SIGNATURE (attr);
17187
17188       return get_signatured_type (die, signature, cu);
17189     }
17190   else
17191     {
17192       complaint (&symfile_complaints,
17193                  _("Dwarf Error: Bad type attribute %s in DIE"
17194                    " at 0x%x [in module %s]"),
17195                  dwarf_attr_name (attr->name), die->offset.sect_off,
17196                  objfile_name (objfile));
17197       return build_error_marker_type (cu, die);
17198     }
17199
17200   /* If not cached we need to read it in.  */
17201
17202   if (this_type == NULL)
17203     {
17204       struct die_info *type_die = NULL;
17205       struct dwarf2_cu *type_cu = cu;
17206
17207       if (attr_form_is_ref (attr))
17208         type_die = follow_die_ref (die, attr, &type_cu);
17209       if (type_die == NULL)
17210         return build_error_marker_type (cu, die);
17211       /* If we find the type now, it's probably because the type came
17212          from an inter-CU reference and the type's CU got expanded before
17213          ours.  */
17214       this_type = read_type_die (type_die, type_cu);
17215     }
17216
17217   /* If we still don't have a type use an error marker.  */
17218
17219   if (this_type == NULL)
17220     return build_error_marker_type (cu, die);
17221
17222   return this_type;
17223 }
17224
17225 /* Return the type in DIE, CU.
17226    Returns NULL for invalid types.
17227
17228    This first does a lookup in die_type_hash,
17229    and only reads the die in if necessary.
17230
17231    NOTE: This can be called when reading in partial or full symbols.  */
17232
17233 static struct type *
17234 read_type_die (struct die_info *die, struct dwarf2_cu *cu)
17235 {
17236   struct type *this_type;
17237
17238   this_type = get_die_type (die, cu);
17239   if (this_type)
17240     return this_type;
17241
17242   return read_type_die_1 (die, cu);
17243 }
17244
17245 /* Read the type in DIE, CU.
17246    Returns NULL for invalid types.  */
17247
17248 static struct type *
17249 read_type_die_1 (struct die_info *die, struct dwarf2_cu *cu)
17250 {
17251   struct type *this_type = NULL;
17252
17253   switch (die->tag)
17254     {
17255     case DW_TAG_class_type:
17256     case DW_TAG_interface_type:
17257     case DW_TAG_structure_type:
17258     case DW_TAG_union_type:
17259       this_type = read_structure_type (die, cu);
17260       break;
17261     case DW_TAG_enumeration_type:
17262       this_type = read_enumeration_type (die, cu);
17263       break;
17264     case DW_TAG_subprogram:
17265     case DW_TAG_subroutine_type:
17266     case DW_TAG_inlined_subroutine:
17267       this_type = read_subroutine_type (die, cu);
17268       break;
17269     case DW_TAG_array_type:
17270       this_type = read_array_type (die, cu);
17271       break;
17272     case DW_TAG_set_type:
17273       this_type = read_set_type (die, cu);
17274       break;
17275     case DW_TAG_pointer_type:
17276       this_type = read_tag_pointer_type (die, cu);
17277       break;
17278     case DW_TAG_ptr_to_member_type:
17279       this_type = read_tag_ptr_to_member_type (die, cu);
17280       break;
17281     case DW_TAG_reference_type:
17282       this_type = read_tag_reference_type (die, cu);
17283       break;
17284     case DW_TAG_const_type:
17285       this_type = read_tag_const_type (die, cu);
17286       break;
17287     case DW_TAG_volatile_type:
17288       this_type = read_tag_volatile_type (die, cu);
17289       break;
17290     case DW_TAG_restrict_type:
17291       this_type = read_tag_restrict_type (die, cu);
17292       break;
17293     case DW_TAG_string_type:
17294       this_type = read_tag_string_type (die, cu);
17295       break;
17296     case DW_TAG_typedef:
17297       this_type = read_typedef (die, cu);
17298       break;
17299     case DW_TAG_subrange_type:
17300       this_type = read_subrange_type (die, cu);
17301       break;
17302     case DW_TAG_base_type:
17303       this_type = read_base_type (die, cu);
17304       break;
17305     case DW_TAG_unspecified_type:
17306       this_type = read_unspecified_type (die, cu);
17307       break;
17308     case DW_TAG_namespace:
17309       this_type = read_namespace_type (die, cu);
17310       break;
17311     case DW_TAG_module:
17312       this_type = read_module_type (die, cu);
17313       break;
17314     default:
17315       complaint (&symfile_complaints,
17316                  _("unexpected tag in read_type_die: '%s'"),
17317                  dwarf_tag_name (die->tag));
17318       break;
17319     }
17320
17321   return this_type;
17322 }
17323
17324 /* See if we can figure out if the class lives in a namespace.  We do
17325    this by looking for a member function; its demangled name will
17326    contain namespace info, if there is any.
17327    Return the computed name or NULL.
17328    Space for the result is allocated on the objfile's obstack.
17329    This is the full-die version of guess_partial_die_structure_name.
17330    In this case we know DIE has no useful parent.  */
17331
17332 static char *
17333 guess_full_die_structure_name (struct die_info *die, struct dwarf2_cu *cu)
17334 {
17335   struct die_info *spec_die;
17336   struct dwarf2_cu *spec_cu;
17337   struct die_info *child;
17338
17339   spec_cu = cu;
17340   spec_die = die_specification (die, &spec_cu);
17341   if (spec_die != NULL)
17342     {
17343       die = spec_die;
17344       cu = spec_cu;
17345     }
17346
17347   for (child = die->child;
17348        child != NULL;
17349        child = child->sibling)
17350     {
17351       if (child->tag == DW_TAG_subprogram)
17352         {
17353           struct attribute *attr;
17354
17355           attr = dwarf2_attr (child, DW_AT_linkage_name, cu);
17356           if (attr == NULL)
17357             attr = dwarf2_attr (child, DW_AT_MIPS_linkage_name, cu);
17358           if (attr != NULL)
17359             {
17360               char *actual_name
17361                 = language_class_name_from_physname (cu->language_defn,
17362                                                      DW_STRING (attr));
17363               char *name = NULL;
17364
17365               if (actual_name != NULL)
17366                 {
17367                   const char *die_name = dwarf2_name (die, cu);
17368
17369                   if (die_name != NULL
17370                       && strcmp (die_name, actual_name) != 0)
17371                     {
17372                       /* Strip off the class name from the full name.
17373                          We want the prefix.  */
17374                       int die_name_len = strlen (die_name);
17375                       int actual_name_len = strlen (actual_name);
17376
17377                       /* Test for '::' as a sanity check.  */
17378                       if (actual_name_len > die_name_len + 2
17379                           && actual_name[actual_name_len
17380                                          - die_name_len - 1] == ':')
17381                         name =
17382                           obstack_copy0 (&cu->objfile->objfile_obstack,
17383                                          actual_name,
17384                                          actual_name_len - die_name_len - 2);
17385                     }
17386                 }
17387               xfree (actual_name);
17388               return name;
17389             }
17390         }
17391     }
17392
17393   return NULL;
17394 }
17395
17396 /* GCC might emit a nameless typedef that has a linkage name.  Determine the
17397    prefix part in such case.  See
17398    http://gcc.gnu.org/bugzilla/show_bug.cgi?id=47510.  */
17399
17400 static char *
17401 anonymous_struct_prefix (struct die_info *die, struct dwarf2_cu *cu)
17402 {
17403   struct attribute *attr;
17404   char *base;
17405
17406   if (die->tag != DW_TAG_class_type && die->tag != DW_TAG_interface_type
17407       && die->tag != DW_TAG_structure_type && die->tag != DW_TAG_union_type)
17408     return NULL;
17409
17410   attr = dwarf2_attr (die, DW_AT_name, cu);
17411   if (attr != NULL && DW_STRING (attr) != NULL)
17412     return NULL;
17413
17414   attr = dwarf2_attr (die, DW_AT_linkage_name, cu);
17415   if (attr == NULL)
17416     attr = dwarf2_attr (die, DW_AT_MIPS_linkage_name, cu);
17417   if (attr == NULL || DW_STRING (attr) == NULL)
17418     return NULL;
17419
17420   /* dwarf2_name had to be already called.  */
17421   gdb_assert (DW_STRING_IS_CANONICAL (attr));
17422
17423   /* Strip the base name, keep any leading namespaces/classes.  */
17424   base = strrchr (DW_STRING (attr), ':');
17425   if (base == NULL || base == DW_STRING (attr) || base[-1] != ':')
17426     return "";
17427
17428   return obstack_copy0 (&cu->objfile->objfile_obstack,
17429                         DW_STRING (attr), &base[-1] - DW_STRING (attr));
17430 }
17431
17432 /* Return the name of the namespace/class that DIE is defined within,
17433    or "" if we can't tell.  The caller should not xfree the result.
17434
17435    For example, if we're within the method foo() in the following
17436    code:
17437
17438    namespace N {
17439      class C {
17440        void foo () {
17441        }
17442      };
17443    }
17444
17445    then determine_prefix on foo's die will return "N::C".  */
17446
17447 static const char *
17448 determine_prefix (struct die_info *die, struct dwarf2_cu *cu)
17449 {
17450   struct die_info *parent, *spec_die;
17451   struct dwarf2_cu *spec_cu;
17452   struct type *parent_type;
17453   char *retval;
17454
17455   if (cu->language != language_cplus && cu->language != language_java
17456       && cu->language != language_fortran)
17457     return "";
17458
17459   retval = anonymous_struct_prefix (die, cu);
17460   if (retval)
17461     return retval;
17462
17463   /* We have to be careful in the presence of DW_AT_specification.
17464      For example, with GCC 3.4, given the code
17465
17466      namespace N {
17467        void foo() {
17468          // Definition of N::foo.
17469        }
17470      }
17471
17472      then we'll have a tree of DIEs like this:
17473
17474      1: DW_TAG_compile_unit
17475        2: DW_TAG_namespace        // N
17476          3: DW_TAG_subprogram     // declaration of N::foo
17477        4: DW_TAG_subprogram       // definition of N::foo
17478             DW_AT_specification   // refers to die #3
17479
17480      Thus, when processing die #4, we have to pretend that we're in
17481      the context of its DW_AT_specification, namely the contex of die
17482      #3.  */
17483   spec_cu = cu;
17484   spec_die = die_specification (die, &spec_cu);
17485   if (spec_die == NULL)
17486     parent = die->parent;
17487   else
17488     {
17489       parent = spec_die->parent;
17490       cu = spec_cu;
17491     }
17492
17493   if (parent == NULL)
17494     return "";
17495   else if (parent->building_fullname)
17496     {
17497       const char *name;
17498       const char *parent_name;
17499
17500       /* It has been seen on RealView 2.2 built binaries,
17501          DW_TAG_template_type_param types actually _defined_ as
17502          children of the parent class:
17503
17504          enum E {};
17505          template class <class Enum> Class{};
17506          Class<enum E> class_e;
17507
17508          1: DW_TAG_class_type (Class)
17509            2: DW_TAG_enumeration_type (E)
17510              3: DW_TAG_enumerator (enum1:0)
17511              3: DW_TAG_enumerator (enum2:1)
17512              ...
17513            2: DW_TAG_template_type_param
17514               DW_AT_type  DW_FORM_ref_udata (E)
17515
17516          Besides being broken debug info, it can put GDB into an
17517          infinite loop.  Consider:
17518
17519          When we're building the full name for Class<E>, we'll start
17520          at Class, and go look over its template type parameters,
17521          finding E.  We'll then try to build the full name of E, and
17522          reach here.  We're now trying to build the full name of E,
17523          and look over the parent DIE for containing scope.  In the
17524          broken case, if we followed the parent DIE of E, we'd again
17525          find Class, and once again go look at its template type
17526          arguments, etc., etc.  Simply don't consider such parent die
17527          as source-level parent of this die (it can't be, the language
17528          doesn't allow it), and break the loop here.  */
17529       name = dwarf2_name (die, cu);
17530       parent_name = dwarf2_name (parent, cu);
17531       complaint (&symfile_complaints,
17532                  _("template param type '%s' defined within parent '%s'"),
17533                  name ? name : "<unknown>",
17534                  parent_name ? parent_name : "<unknown>");
17535       return "";
17536     }
17537   else
17538     switch (parent->tag)
17539       {
17540       case DW_TAG_namespace:
17541         parent_type = read_type_die (parent, cu);
17542         /* GCC 4.0 and 4.1 had a bug (PR c++/28460) where they generated bogus
17543            DW_TAG_namespace DIEs with a name of "::" for the global namespace.
17544            Work around this problem here.  */
17545         if (cu->language == language_cplus
17546             && strcmp (TYPE_TAG_NAME (parent_type), "::") == 0)
17547           return "";
17548         /* We give a name to even anonymous namespaces.  */
17549         return TYPE_TAG_NAME (parent_type);
17550       case DW_TAG_class_type:
17551       case DW_TAG_interface_type:
17552       case DW_TAG_structure_type:
17553       case DW_TAG_union_type:
17554       case DW_TAG_module:
17555         parent_type = read_type_die (parent, cu);
17556         if (TYPE_TAG_NAME (parent_type) != NULL)
17557           return TYPE_TAG_NAME (parent_type);
17558         else
17559           /* An anonymous structure is only allowed non-static data
17560              members; no typedefs, no member functions, et cetera.
17561              So it does not need a prefix.  */
17562           return "";
17563       case DW_TAG_compile_unit:
17564       case DW_TAG_partial_unit:
17565         /* gcc-4.5 -gdwarf-4 can drop the enclosing namespace.  Cope.  */
17566         if (cu->language == language_cplus
17567             && !VEC_empty (dwarf2_section_info_def, dwarf2_per_objfile->types)
17568             && die->child != NULL
17569             && (die->tag == DW_TAG_class_type
17570                 || die->tag == DW_TAG_structure_type
17571                 || die->tag == DW_TAG_union_type))
17572           {
17573             char *name = guess_full_die_structure_name (die, cu);
17574             if (name != NULL)
17575               return name;
17576           }
17577         return "";
17578       default:
17579         return determine_prefix (parent, cu);
17580       }
17581 }
17582
17583 /* Return a newly-allocated string formed by concatenating PREFIX and SUFFIX
17584    with appropriate separator.  If PREFIX or SUFFIX is NULL or empty, then
17585    simply copy the SUFFIX or PREFIX, respectively.  If OBS is non-null, perform
17586    an obconcat, otherwise allocate storage for the result.  The CU argument is
17587    used to determine the language and hence, the appropriate separator.  */
17588
17589 #define MAX_SEP_LEN 7  /* strlen ("__") + strlen ("_MOD_")  */
17590
17591 static char *
17592 typename_concat (struct obstack *obs, const char *prefix, const char *suffix,
17593                  int physname, struct dwarf2_cu *cu)
17594 {
17595   const char *lead = "";
17596   const char *sep;
17597
17598   if (suffix == NULL || suffix[0] == '\0'
17599       || prefix == NULL || prefix[0] == '\0')
17600     sep = "";
17601   else if (cu->language == language_java)
17602     sep = ".";
17603   else if (cu->language == language_fortran && physname)
17604     {
17605       /* This is gfortran specific mangling.  Normally DW_AT_linkage_name or
17606          DW_AT_MIPS_linkage_name is preferred and used instead.  */
17607
17608       lead = "__";
17609       sep = "_MOD_";
17610     }
17611   else
17612     sep = "::";
17613
17614   if (prefix == NULL)
17615     prefix = "";
17616   if (suffix == NULL)
17617     suffix = "";
17618
17619   if (obs == NULL)
17620     {
17621       char *retval
17622         = xmalloc (strlen (prefix) + MAX_SEP_LEN + strlen (suffix) + 1);
17623
17624       strcpy (retval, lead);
17625       strcat (retval, prefix);
17626       strcat (retval, sep);
17627       strcat (retval, suffix);
17628       return retval;
17629     }
17630   else
17631     {
17632       /* We have an obstack.  */
17633       return obconcat (obs, lead, prefix, sep, suffix, (char *) NULL);
17634     }
17635 }
17636
17637 /* Return sibling of die, NULL if no sibling.  */
17638
17639 static struct die_info *
17640 sibling_die (struct die_info *die)
17641 {
17642   return die->sibling;
17643 }
17644
17645 /* Get name of a die, return NULL if not found.  */
17646
17647 static const char *
17648 dwarf2_canonicalize_name (const char *name, struct dwarf2_cu *cu,
17649                           struct obstack *obstack)
17650 {
17651   if (name && cu->language == language_cplus)
17652     {
17653       char *canon_name = cp_canonicalize_string (name);
17654
17655       if (canon_name != NULL)
17656         {
17657           if (strcmp (canon_name, name) != 0)
17658             name = obstack_copy0 (obstack, canon_name, strlen (canon_name));
17659           xfree (canon_name);
17660         }
17661     }
17662
17663   return name;
17664 }
17665
17666 /* Get name of a die, return NULL if not found.  */
17667
17668 static const char *
17669 dwarf2_name (struct die_info *die, struct dwarf2_cu *cu)
17670 {
17671   struct attribute *attr;
17672
17673   attr = dwarf2_attr (die, DW_AT_name, cu);
17674   if ((!attr || !DW_STRING (attr))
17675       && die->tag != DW_TAG_class_type
17676       && die->tag != DW_TAG_interface_type
17677       && die->tag != DW_TAG_structure_type
17678       && die->tag != DW_TAG_union_type)
17679     return NULL;
17680
17681   switch (die->tag)
17682     {
17683     case DW_TAG_compile_unit:
17684     case DW_TAG_partial_unit:
17685       /* Compilation units have a DW_AT_name that is a filename, not
17686          a source language identifier.  */
17687     case DW_TAG_enumeration_type:
17688     case DW_TAG_enumerator:
17689       /* These tags always have simple identifiers already; no need
17690          to canonicalize them.  */
17691       return DW_STRING (attr);
17692
17693     case DW_TAG_subprogram:
17694       /* Java constructors will all be named "<init>", so return
17695          the class name when we see this special case.  */
17696       if (cu->language == language_java
17697           && DW_STRING (attr) != NULL
17698           && strcmp (DW_STRING (attr), "<init>") == 0)
17699         {
17700           struct dwarf2_cu *spec_cu = cu;
17701           struct die_info *spec_die;
17702
17703           /* GCJ will output '<init>' for Java constructor names.
17704              For this special case, return the name of the parent class.  */
17705
17706           /* GCJ may output suprogram DIEs with AT_specification set.
17707              If so, use the name of the specified DIE.  */
17708           spec_die = die_specification (die, &spec_cu);
17709           if (spec_die != NULL)
17710             return dwarf2_name (spec_die, spec_cu);
17711
17712           do
17713             {
17714               die = die->parent;
17715               if (die->tag == DW_TAG_class_type)
17716                 return dwarf2_name (die, cu);
17717             }
17718           while (die->tag != DW_TAG_compile_unit
17719                  && die->tag != DW_TAG_partial_unit);
17720         }
17721       break;
17722
17723     case DW_TAG_class_type:
17724     case DW_TAG_interface_type:
17725     case DW_TAG_structure_type:
17726     case DW_TAG_union_type:
17727       /* Some GCC versions emit spurious DW_AT_name attributes for unnamed
17728          structures or unions.  These were of the form "._%d" in GCC 4.1,
17729          or simply "<anonymous struct>" or "<anonymous union>" in GCC 4.3
17730          and GCC 4.4.  We work around this problem by ignoring these.  */
17731       if (attr && DW_STRING (attr)
17732           && (strncmp (DW_STRING (attr), "._", 2) == 0
17733               || strncmp (DW_STRING (attr), "<anonymous", 10) == 0))
17734         return NULL;
17735
17736       /* GCC might emit a nameless typedef that has a linkage name.  See
17737          http://gcc.gnu.org/bugzilla/show_bug.cgi?id=47510.  */
17738       if (!attr || DW_STRING (attr) == NULL)
17739         {
17740           char *demangled = NULL;
17741
17742           attr = dwarf2_attr (die, DW_AT_linkage_name, cu);
17743           if (attr == NULL)
17744             attr = dwarf2_attr (die, DW_AT_MIPS_linkage_name, cu);
17745
17746           if (attr == NULL || DW_STRING (attr) == NULL)
17747             return NULL;
17748
17749           /* Avoid demangling DW_STRING (attr) the second time on a second
17750              call for the same DIE.  */
17751           if (!DW_STRING_IS_CANONICAL (attr))
17752             demangled = gdb_demangle (DW_STRING (attr), DMGL_TYPES);
17753
17754           if (demangled)
17755             {
17756               char *base;
17757
17758               /* FIXME: we already did this for the partial symbol... */
17759               DW_STRING (attr) = obstack_copy0 (&cu->objfile->objfile_obstack,
17760                                                 demangled, strlen (demangled));
17761               DW_STRING_IS_CANONICAL (attr) = 1;
17762               xfree (demangled);
17763
17764               /* Strip any leading namespaces/classes, keep only the base name.
17765                  DW_AT_name for named DIEs does not contain the prefixes.  */
17766               base = strrchr (DW_STRING (attr), ':');
17767               if (base && base > DW_STRING (attr) && base[-1] == ':')
17768                 return &base[1];
17769               else
17770                 return DW_STRING (attr);
17771             }
17772         }
17773       break;
17774
17775     default:
17776       break;
17777     }
17778
17779   if (!DW_STRING_IS_CANONICAL (attr))
17780     {
17781       DW_STRING (attr)
17782         = dwarf2_canonicalize_name (DW_STRING (attr), cu,
17783                                     &cu->objfile->objfile_obstack);
17784       DW_STRING_IS_CANONICAL (attr) = 1;
17785     }
17786   return DW_STRING (attr);
17787 }
17788
17789 /* Return the die that this die in an extension of, or NULL if there
17790    is none.  *EXT_CU is the CU containing DIE on input, and the CU
17791    containing the return value on output.  */
17792
17793 static struct die_info *
17794 dwarf2_extension (struct die_info *die, struct dwarf2_cu **ext_cu)
17795 {
17796   struct attribute *attr;
17797
17798   attr = dwarf2_attr (die, DW_AT_extension, *ext_cu);
17799   if (attr == NULL)
17800     return NULL;
17801
17802   return follow_die_ref (die, attr, ext_cu);
17803 }
17804
17805 /* Convert a DIE tag into its string name.  */
17806
17807 static const char *
17808 dwarf_tag_name (unsigned tag)
17809 {
17810   const char *name = get_DW_TAG_name (tag);
17811
17812   if (name == NULL)
17813     return "DW_TAG_<unknown>";
17814
17815   return name;
17816 }
17817
17818 /* Convert a DWARF attribute code into its string name.  */
17819
17820 static const char *
17821 dwarf_attr_name (unsigned attr)
17822 {
17823   const char *name;
17824
17825 #ifdef MIPS /* collides with DW_AT_HP_block_index */
17826   if (attr == DW_AT_MIPS_fde)
17827     return "DW_AT_MIPS_fde";
17828 #else
17829   if (attr == DW_AT_HP_block_index)
17830     return "DW_AT_HP_block_index";
17831 #endif
17832
17833   name = get_DW_AT_name (attr);
17834
17835   if (name == NULL)
17836     return "DW_AT_<unknown>";
17837
17838   return name;
17839 }
17840
17841 /* Convert a DWARF value form code into its string name.  */
17842
17843 static const char *
17844 dwarf_form_name (unsigned form)
17845 {
17846   const char *name = get_DW_FORM_name (form);
17847
17848   if (name == NULL)
17849     return "DW_FORM_<unknown>";
17850
17851   return name;
17852 }
17853
17854 static char *
17855 dwarf_bool_name (unsigned mybool)
17856 {
17857   if (mybool)
17858     return "TRUE";
17859   else
17860     return "FALSE";
17861 }
17862
17863 /* Convert a DWARF type code into its string name.  */
17864
17865 static const char *
17866 dwarf_type_encoding_name (unsigned enc)
17867 {
17868   const char *name = get_DW_ATE_name (enc);
17869
17870   if (name == NULL)
17871     return "DW_ATE_<unknown>";
17872
17873   return name;
17874 }
17875
17876 static void
17877 dump_die_shallow (struct ui_file *f, int indent, struct die_info *die)
17878 {
17879   unsigned int i;
17880
17881   print_spaces (indent, f);
17882   fprintf_unfiltered (f, "Die: %s (abbrev %d, offset 0x%x)\n",
17883            dwarf_tag_name (die->tag), die->abbrev, die->offset.sect_off);
17884
17885   if (die->parent != NULL)
17886     {
17887       print_spaces (indent, f);
17888       fprintf_unfiltered (f, "  parent at offset: 0x%x\n",
17889                           die->parent->offset.sect_off);
17890     }
17891
17892   print_spaces (indent, f);
17893   fprintf_unfiltered (f, "  has children: %s\n",
17894            dwarf_bool_name (die->child != NULL));
17895
17896   print_spaces (indent, f);
17897   fprintf_unfiltered (f, "  attributes:\n");
17898
17899   for (i = 0; i < die->num_attrs; ++i)
17900     {
17901       print_spaces (indent, f);
17902       fprintf_unfiltered (f, "    %s (%s) ",
17903                dwarf_attr_name (die->attrs[i].name),
17904                dwarf_form_name (die->attrs[i].form));
17905
17906       switch (die->attrs[i].form)
17907         {
17908         case DW_FORM_addr:
17909         case DW_FORM_GNU_addr_index:
17910           fprintf_unfiltered (f, "address: ");
17911           fputs_filtered (hex_string (DW_ADDR (&die->attrs[i])), f);
17912           break;
17913         case DW_FORM_block2:
17914         case DW_FORM_block4:
17915         case DW_FORM_block:
17916         case DW_FORM_block1:
17917           fprintf_unfiltered (f, "block: size %s",
17918                               pulongest (DW_BLOCK (&die->attrs[i])->size));
17919           break;
17920         case DW_FORM_exprloc:
17921           fprintf_unfiltered (f, "expression: size %s",
17922                               pulongest (DW_BLOCK (&die->attrs[i])->size));
17923           break;
17924         case DW_FORM_ref_addr:
17925           fprintf_unfiltered (f, "ref address: ");
17926           fputs_filtered (hex_string (DW_UNSND (&die->attrs[i])), f);
17927           break;
17928         case DW_FORM_GNU_ref_alt:
17929           fprintf_unfiltered (f, "alt ref address: ");
17930           fputs_filtered (hex_string (DW_UNSND (&die->attrs[i])), f);
17931           break;
17932         case DW_FORM_ref1:
17933         case DW_FORM_ref2:
17934         case DW_FORM_ref4:
17935         case DW_FORM_ref8:
17936         case DW_FORM_ref_udata:
17937           fprintf_unfiltered (f, "constant ref: 0x%lx (adjusted)",
17938                               (long) (DW_UNSND (&die->attrs[i])));
17939           break;
17940         case DW_FORM_data1:
17941         case DW_FORM_data2:
17942         case DW_FORM_data4:
17943         case DW_FORM_data8:
17944         case DW_FORM_udata:
17945         case DW_FORM_sdata:
17946           fprintf_unfiltered (f, "constant: %s",
17947                               pulongest (DW_UNSND (&die->attrs[i])));
17948           break;
17949         case DW_FORM_sec_offset:
17950           fprintf_unfiltered (f, "section offset: %s",
17951                               pulongest (DW_UNSND (&die->attrs[i])));
17952           break;
17953         case DW_FORM_ref_sig8:
17954           fprintf_unfiltered (f, "signature: %s",
17955                               hex_string (DW_SIGNATURE (&die->attrs[i])));
17956           break;
17957         case DW_FORM_string:
17958         case DW_FORM_strp:
17959         case DW_FORM_GNU_str_index:
17960         case DW_FORM_GNU_strp_alt:
17961           fprintf_unfiltered (f, "string: \"%s\" (%s canonicalized)",
17962                    DW_STRING (&die->attrs[i])
17963                    ? DW_STRING (&die->attrs[i]) : "",
17964                    DW_STRING_IS_CANONICAL (&die->attrs[i]) ? "is" : "not");
17965           break;
17966         case DW_FORM_flag:
17967           if (DW_UNSND (&die->attrs[i]))
17968             fprintf_unfiltered (f, "flag: TRUE");
17969           else
17970             fprintf_unfiltered (f, "flag: FALSE");
17971           break;
17972         case DW_FORM_flag_present:
17973           fprintf_unfiltered (f, "flag: TRUE");
17974           break;
17975         case DW_FORM_indirect:
17976           /* The reader will have reduced the indirect form to
17977              the "base form" so this form should not occur.  */
17978           fprintf_unfiltered (f, 
17979                               "unexpected attribute form: DW_FORM_indirect");
17980           break;
17981         default:
17982           fprintf_unfiltered (f, "unsupported attribute form: %d.",
17983                    die->attrs[i].form);
17984           break;
17985         }
17986       fprintf_unfiltered (f, "\n");
17987     }
17988 }
17989
17990 static void
17991 dump_die_for_error (struct die_info *die)
17992 {
17993   dump_die_shallow (gdb_stderr, 0, die);
17994 }
17995
17996 static void
17997 dump_die_1 (struct ui_file *f, int level, int max_level, struct die_info *die)
17998 {
17999   int indent = level * 4;
18000
18001   gdb_assert (die != NULL);
18002
18003   if (level >= max_level)
18004     return;
18005
18006   dump_die_shallow (f, indent, die);
18007
18008   if (die->child != NULL)
18009     {
18010       print_spaces (indent, f);
18011       fprintf_unfiltered (f, "  Children:");
18012       if (level + 1 < max_level)
18013         {
18014           fprintf_unfiltered (f, "\n");
18015           dump_die_1 (f, level + 1, max_level, die->child);
18016         }
18017       else
18018         {
18019           fprintf_unfiltered (f,
18020                               " [not printed, max nesting level reached]\n");
18021         }
18022     }
18023
18024   if (die->sibling != NULL && level > 0)
18025     {
18026       dump_die_1 (f, level, max_level, die->sibling);
18027     }
18028 }
18029
18030 /* This is called from the pdie macro in gdbinit.in.
18031    It's not static so gcc will keep a copy callable from gdb.  */
18032
18033 void
18034 dump_die (struct die_info *die, int max_level)
18035 {
18036   dump_die_1 (gdb_stdlog, 0, max_level, die);
18037 }
18038
18039 static void
18040 store_in_ref_table (struct die_info *die, struct dwarf2_cu *cu)
18041 {
18042   void **slot;
18043
18044   slot = htab_find_slot_with_hash (cu->die_hash, die, die->offset.sect_off,
18045                                    INSERT);
18046
18047   *slot = die;
18048 }
18049
18050 /* Return DIE offset of ATTR.  Return 0 with complaint if ATTR is not of the
18051    required kind.  */
18052
18053 static sect_offset
18054 dwarf2_get_ref_die_offset (const struct attribute *attr)
18055 {
18056   sect_offset retval = { DW_UNSND (attr) };
18057
18058   if (attr_form_is_ref (attr))
18059     return retval;
18060
18061   retval.sect_off = 0;
18062   complaint (&symfile_complaints,
18063              _("unsupported die ref attribute form: '%s'"),
18064              dwarf_form_name (attr->form));
18065   return retval;
18066 }
18067
18068 /* Return the constant value held by ATTR.  Return DEFAULT_VALUE if
18069  * the value held by the attribute is not constant.  */
18070
18071 static LONGEST
18072 dwarf2_get_attr_constant_value (const struct attribute *attr, int default_value)
18073 {
18074   if (attr->form == DW_FORM_sdata)
18075     return DW_SND (attr);
18076   else if (attr->form == DW_FORM_udata
18077            || attr->form == DW_FORM_data1
18078            || attr->form == DW_FORM_data2
18079            || attr->form == DW_FORM_data4
18080            || attr->form == DW_FORM_data8)
18081     return DW_UNSND (attr);
18082   else
18083     {
18084       complaint (&symfile_complaints,
18085                  _("Attribute value is not a constant (%s)"),
18086                  dwarf_form_name (attr->form));
18087       return default_value;
18088     }
18089 }
18090
18091 /* Follow reference or signature attribute ATTR of SRC_DIE.
18092    On entry *REF_CU is the CU of SRC_DIE.
18093    On exit *REF_CU is the CU of the result.  */
18094
18095 static struct die_info *
18096 follow_die_ref_or_sig (struct die_info *src_die, const struct attribute *attr,
18097                        struct dwarf2_cu **ref_cu)
18098 {
18099   struct die_info *die;
18100
18101   if (attr_form_is_ref (attr))
18102     die = follow_die_ref (src_die, attr, ref_cu);
18103   else if (attr->form == DW_FORM_ref_sig8)
18104     die = follow_die_sig (src_die, attr, ref_cu);
18105   else
18106     {
18107       dump_die_for_error (src_die);
18108       error (_("Dwarf Error: Expected reference attribute [in module %s]"),
18109              objfile_name ((*ref_cu)->objfile));
18110     }
18111
18112   return die;
18113 }
18114
18115 /* Follow reference OFFSET.
18116    On entry *REF_CU is the CU of the source die referencing OFFSET.
18117    On exit *REF_CU is the CU of the result.
18118    Returns NULL if OFFSET is invalid.  */
18119
18120 static struct die_info *
18121 follow_die_offset (sect_offset offset, int offset_in_dwz,
18122                    struct dwarf2_cu **ref_cu)
18123 {
18124   struct die_info temp_die;
18125   struct dwarf2_cu *target_cu, *cu = *ref_cu;
18126
18127   gdb_assert (cu->per_cu != NULL);
18128
18129   target_cu = cu;
18130
18131   if (cu->per_cu->is_debug_types)
18132     {
18133       /* .debug_types CUs cannot reference anything outside their CU.
18134          If they need to, they have to reference a signatured type via
18135          DW_FORM_ref_sig8.  */
18136       if (! offset_in_cu_p (&cu->header, offset))
18137         return NULL;
18138     }
18139   else if (offset_in_dwz != cu->per_cu->is_dwz
18140            || ! offset_in_cu_p (&cu->header, offset))
18141     {
18142       struct dwarf2_per_cu_data *per_cu;
18143
18144       per_cu = dwarf2_find_containing_comp_unit (offset, offset_in_dwz,
18145                                                  cu->objfile);
18146
18147       /* If necessary, add it to the queue and load its DIEs.  */
18148       if (maybe_queue_comp_unit (cu, per_cu, cu->language))
18149         load_full_comp_unit (per_cu, cu->language);
18150
18151       target_cu = per_cu->cu;
18152     }
18153   else if (cu->dies == NULL)
18154     {
18155       /* We're loading full DIEs during partial symbol reading.  */
18156       gdb_assert (dwarf2_per_objfile->reading_partial_symbols);
18157       load_full_comp_unit (cu->per_cu, language_minimal);
18158     }
18159
18160   *ref_cu = target_cu;
18161   temp_die.offset = offset;
18162   return htab_find_with_hash (target_cu->die_hash, &temp_die, offset.sect_off);
18163 }
18164
18165 /* Follow reference attribute ATTR of SRC_DIE.
18166    On entry *REF_CU is the CU of SRC_DIE.
18167    On exit *REF_CU is the CU of the result.  */
18168
18169 static struct die_info *
18170 follow_die_ref (struct die_info *src_die, const struct attribute *attr,
18171                 struct dwarf2_cu **ref_cu)
18172 {
18173   sect_offset offset = dwarf2_get_ref_die_offset (attr);
18174   struct dwarf2_cu *cu = *ref_cu;
18175   struct die_info *die;
18176
18177   die = follow_die_offset (offset,
18178                            (attr->form == DW_FORM_GNU_ref_alt
18179                             || cu->per_cu->is_dwz),
18180                            ref_cu);
18181   if (!die)
18182     error (_("Dwarf Error: Cannot find DIE at 0x%x referenced from DIE "
18183            "at 0x%x [in module %s]"),
18184            offset.sect_off, src_die->offset.sect_off,
18185            objfile_name (cu->objfile));
18186
18187   return die;
18188 }
18189
18190 /* Return DWARF block referenced by DW_AT_location of DIE at OFFSET at PER_CU.
18191    Returned value is intended for DW_OP_call*.  Returned
18192    dwarf2_locexpr_baton->data has lifetime of PER_CU->OBJFILE.  */
18193
18194 struct dwarf2_locexpr_baton
18195 dwarf2_fetch_die_loc_sect_off (sect_offset offset,
18196                                struct dwarf2_per_cu_data *per_cu,
18197                                CORE_ADDR (*get_frame_pc) (void *baton),
18198                                void *baton)
18199 {
18200   struct dwarf2_cu *cu;
18201   struct die_info *die;
18202   struct attribute *attr;
18203   struct dwarf2_locexpr_baton retval;
18204
18205   dw2_setup (per_cu->objfile);
18206
18207   if (per_cu->cu == NULL)
18208     load_cu (per_cu);
18209   cu = per_cu->cu;
18210
18211   die = follow_die_offset (offset, per_cu->is_dwz, &cu);
18212   if (!die)
18213     error (_("Dwarf Error: Cannot find DIE at 0x%x referenced in module %s"),
18214            offset.sect_off, objfile_name (per_cu->objfile));
18215
18216   attr = dwarf2_attr (die, DW_AT_location, cu);
18217   if (!attr)
18218     {
18219       /* DWARF: "If there is no such attribute, then there is no effect.".
18220          DATA is ignored if SIZE is 0.  */
18221
18222       retval.data = NULL;
18223       retval.size = 0;
18224     }
18225   else if (attr_form_is_section_offset (attr))
18226     {
18227       struct dwarf2_loclist_baton loclist_baton;
18228       CORE_ADDR pc = (*get_frame_pc) (baton);
18229       size_t size;
18230
18231       fill_in_loclist_baton (cu, &loclist_baton, attr);
18232
18233       retval.data = dwarf2_find_location_expression (&loclist_baton,
18234                                                      &size, pc);
18235       retval.size = size;
18236     }
18237   else
18238     {
18239       if (!attr_form_is_block (attr))
18240         error (_("Dwarf Error: DIE at 0x%x referenced in module %s "
18241                  "is neither DW_FORM_block* nor DW_FORM_exprloc"),
18242                offset.sect_off, objfile_name (per_cu->objfile));
18243
18244       retval.data = DW_BLOCK (attr)->data;
18245       retval.size = DW_BLOCK (attr)->size;
18246     }
18247   retval.per_cu = cu->per_cu;
18248
18249   age_cached_comp_units ();
18250
18251   return retval;
18252 }
18253
18254 /* Like dwarf2_fetch_die_loc_sect_off, but take a CU
18255    offset.  */
18256
18257 struct dwarf2_locexpr_baton
18258 dwarf2_fetch_die_loc_cu_off (cu_offset offset_in_cu,
18259                              struct dwarf2_per_cu_data *per_cu,
18260                              CORE_ADDR (*get_frame_pc) (void *baton),
18261                              void *baton)
18262 {
18263   sect_offset offset = { per_cu->offset.sect_off + offset_in_cu.cu_off };
18264
18265   return dwarf2_fetch_die_loc_sect_off (offset, per_cu, get_frame_pc, baton);
18266 }
18267
18268 /* Write a constant of a given type as target-ordered bytes into
18269    OBSTACK.  */
18270
18271 static const gdb_byte *
18272 write_constant_as_bytes (struct obstack *obstack,
18273                          enum bfd_endian byte_order,
18274                          struct type *type,
18275                          ULONGEST value,
18276                          LONGEST *len)
18277 {
18278   gdb_byte *result;
18279
18280   *len = TYPE_LENGTH (type);
18281   result = obstack_alloc (obstack, *len);
18282   store_unsigned_integer (result, *len, byte_order, value);
18283
18284   return result;
18285 }
18286
18287 /* If the DIE at OFFSET in PER_CU has a DW_AT_const_value, return a
18288    pointer to the constant bytes and set LEN to the length of the
18289    data.  If memory is needed, allocate it on OBSTACK.  If the DIE
18290    does not have a DW_AT_const_value, return NULL.  */
18291
18292 const gdb_byte *
18293 dwarf2_fetch_constant_bytes (sect_offset offset,
18294                              struct dwarf2_per_cu_data *per_cu,
18295                              struct obstack *obstack,
18296                              LONGEST *len)
18297 {
18298   struct dwarf2_cu *cu;
18299   struct die_info *die;
18300   struct attribute *attr;
18301   const gdb_byte *result = NULL;
18302   struct type *type;
18303   LONGEST value;
18304   enum bfd_endian byte_order;
18305
18306   dw2_setup (per_cu->objfile);
18307
18308   if (per_cu->cu == NULL)
18309     load_cu (per_cu);
18310   cu = per_cu->cu;
18311
18312   die = follow_die_offset (offset, per_cu->is_dwz, &cu);
18313   if (!die)
18314     error (_("Dwarf Error: Cannot find DIE at 0x%x referenced in module %s"),
18315            offset.sect_off, objfile_name (per_cu->objfile));
18316
18317
18318   attr = dwarf2_attr (die, DW_AT_const_value, cu);
18319   if (attr == NULL)
18320     return NULL;
18321
18322   byte_order = (bfd_big_endian (per_cu->objfile->obfd)
18323                 ? BFD_ENDIAN_BIG : BFD_ENDIAN_LITTLE);
18324
18325   switch (attr->form)
18326     {
18327     case DW_FORM_addr:
18328     case DW_FORM_GNU_addr_index:
18329       {
18330         gdb_byte *tem;
18331
18332         *len = cu->header.addr_size;
18333         tem = obstack_alloc (obstack, *len);
18334         store_unsigned_integer (tem, *len, byte_order, DW_ADDR (attr));
18335         result = tem;
18336       }
18337       break;
18338     case DW_FORM_string:
18339     case DW_FORM_strp:
18340     case DW_FORM_GNU_str_index:
18341     case DW_FORM_GNU_strp_alt:
18342       /* DW_STRING is already allocated on the objfile obstack, point
18343          directly to it.  */
18344       result = (const gdb_byte *) DW_STRING (attr);
18345       *len = strlen (DW_STRING (attr));
18346       break;
18347     case DW_FORM_block1:
18348     case DW_FORM_block2:
18349     case DW_FORM_block4:
18350     case DW_FORM_block:
18351     case DW_FORM_exprloc:
18352       result = DW_BLOCK (attr)->data;
18353       *len = DW_BLOCK (attr)->size;
18354       break;
18355
18356       /* The DW_AT_const_value attributes are supposed to carry the
18357          symbol's value "represented as it would be on the target
18358          architecture."  By the time we get here, it's already been
18359          converted to host endianness, so we just need to sign- or
18360          zero-extend it as appropriate.  */
18361     case DW_FORM_data1:
18362       type = die_type (die, cu);
18363       result = dwarf2_const_value_data (attr, obstack, cu, &value, 8);
18364       if (result == NULL)
18365         result = write_constant_as_bytes (obstack, byte_order,
18366                                           type, value, len);
18367       break;
18368     case DW_FORM_data2:
18369       type = die_type (die, cu);
18370       result = dwarf2_const_value_data (attr, obstack, cu, &value, 16);
18371       if (result == NULL)
18372         result = write_constant_as_bytes (obstack, byte_order,
18373                                           type, value, len);
18374       break;
18375     case DW_FORM_data4:
18376       type = die_type (die, cu);
18377       result = dwarf2_const_value_data (attr, obstack, cu, &value, 32);
18378       if (result == NULL)
18379         result = write_constant_as_bytes (obstack, byte_order,
18380                                           type, value, len);
18381       break;
18382     case DW_FORM_data8:
18383       type = die_type (die, cu);
18384       result = dwarf2_const_value_data (attr, obstack, cu, &value, 64);
18385       if (result == NULL)
18386         result = write_constant_as_bytes (obstack, byte_order,
18387                                           type, value, len);
18388       break;
18389
18390     case DW_FORM_sdata:
18391       type = die_type (die, cu);
18392       result = write_constant_as_bytes (obstack, byte_order,
18393                                         type, DW_SND (attr), len);
18394       break;
18395
18396     case DW_FORM_udata:
18397       type = die_type (die, cu);
18398       result = write_constant_as_bytes (obstack, byte_order,
18399                                         type, DW_UNSND (attr), len);
18400       break;
18401
18402     default:
18403       complaint (&symfile_complaints,
18404                  _("unsupported const value attribute form: '%s'"),
18405                  dwarf_form_name (attr->form));
18406       break;
18407     }
18408
18409   return result;
18410 }
18411
18412 /* Return the type of the DIE at DIE_OFFSET in the CU named by
18413    PER_CU.  */
18414
18415 struct type *
18416 dwarf2_get_die_type (cu_offset die_offset,
18417                      struct dwarf2_per_cu_data *per_cu)
18418 {
18419   sect_offset die_offset_sect;
18420
18421   dw2_setup (per_cu->objfile);
18422
18423   die_offset_sect.sect_off = per_cu->offset.sect_off + die_offset.cu_off;
18424   return get_die_type_at_offset (die_offset_sect, per_cu);
18425 }
18426
18427 /* Follow type unit SIG_TYPE referenced by SRC_DIE.
18428    On entry *REF_CU is the CU of SRC_DIE.
18429    On exit *REF_CU is the CU of the result.
18430    Returns NULL if the referenced DIE isn't found.  */
18431
18432 static struct die_info *
18433 follow_die_sig_1 (struct die_info *src_die, struct signatured_type *sig_type,
18434                   struct dwarf2_cu **ref_cu)
18435 {
18436   struct objfile *objfile = (*ref_cu)->objfile;
18437   struct die_info temp_die;
18438   struct dwarf2_cu *sig_cu;
18439   struct die_info *die;
18440
18441   /* While it might be nice to assert sig_type->type == NULL here,
18442      we can get here for DW_AT_imported_declaration where we need
18443      the DIE not the type.  */
18444
18445   /* If necessary, add it to the queue and load its DIEs.  */
18446
18447   if (maybe_queue_comp_unit (*ref_cu, &sig_type->per_cu, language_minimal))
18448     read_signatured_type (sig_type);
18449
18450   sig_cu = sig_type->per_cu.cu;
18451   gdb_assert (sig_cu != NULL);
18452   gdb_assert (sig_type->type_offset_in_section.sect_off != 0);
18453   temp_die.offset = sig_type->type_offset_in_section;
18454   die = htab_find_with_hash (sig_cu->die_hash, &temp_die,
18455                              temp_die.offset.sect_off);
18456   if (die)
18457     {
18458       /* For .gdb_index version 7 keep track of included TUs.
18459          http://sourceware.org/bugzilla/show_bug.cgi?id=15021.  */
18460       if (dwarf2_per_objfile->index_table != NULL
18461           && dwarf2_per_objfile->index_table->version <= 7)
18462         {
18463           VEC_safe_push (dwarf2_per_cu_ptr,
18464                          (*ref_cu)->per_cu->imported_symtabs,
18465                          sig_cu->per_cu);
18466         }
18467
18468       *ref_cu = sig_cu;
18469       return die;
18470     }
18471
18472   return NULL;
18473 }
18474
18475 /* Follow signatured type referenced by ATTR in SRC_DIE.
18476    On entry *REF_CU is the CU of SRC_DIE.
18477    On exit *REF_CU is the CU of the result.
18478    The result is the DIE of the type.
18479    If the referenced type cannot be found an error is thrown.  */
18480
18481 static struct die_info *
18482 follow_die_sig (struct die_info *src_die, const struct attribute *attr,
18483                 struct dwarf2_cu **ref_cu)
18484 {
18485   ULONGEST signature = DW_SIGNATURE (attr);
18486   struct signatured_type *sig_type;
18487   struct die_info *die;
18488
18489   gdb_assert (attr->form == DW_FORM_ref_sig8);
18490
18491   sig_type = lookup_signatured_type (*ref_cu, signature);
18492   /* sig_type will be NULL if the signatured type is missing from
18493      the debug info.  */
18494   if (sig_type == NULL)
18495     {
18496       error (_("Dwarf Error: Cannot find signatured DIE %s referenced"
18497                " from DIE at 0x%x [in module %s]"),
18498              hex_string (signature), src_die->offset.sect_off,
18499              objfile_name ((*ref_cu)->objfile));
18500     }
18501
18502   die = follow_die_sig_1 (src_die, sig_type, ref_cu);
18503   if (die == NULL)
18504     {
18505       dump_die_for_error (src_die);
18506       error (_("Dwarf Error: Problem reading signatured DIE %s referenced"
18507                " from DIE at 0x%x [in module %s]"),
18508              hex_string (signature), src_die->offset.sect_off,
18509              objfile_name ((*ref_cu)->objfile));
18510     }
18511
18512   return die;
18513 }
18514
18515 /* Get the type specified by SIGNATURE referenced in DIE/CU,
18516    reading in and processing the type unit if necessary.  */
18517
18518 static struct type *
18519 get_signatured_type (struct die_info *die, ULONGEST signature,
18520                      struct dwarf2_cu *cu)
18521 {
18522   struct signatured_type *sig_type;
18523   struct dwarf2_cu *type_cu;
18524   struct die_info *type_die;
18525   struct type *type;
18526
18527   sig_type = lookup_signatured_type (cu, signature);
18528   /* sig_type will be NULL if the signatured type is missing from
18529      the debug info.  */
18530   if (sig_type == NULL)
18531     {
18532       complaint (&symfile_complaints,
18533                  _("Dwarf Error: Cannot find signatured DIE %s referenced"
18534                    " from DIE at 0x%x [in module %s]"),
18535                  hex_string (signature), die->offset.sect_off,
18536                  objfile_name (dwarf2_per_objfile->objfile));
18537       return build_error_marker_type (cu, die);
18538     }
18539
18540   /* If we already know the type we're done.  */
18541   if (sig_type->type != NULL)
18542     return sig_type->type;
18543
18544   type_cu = cu;
18545   type_die = follow_die_sig_1 (die, sig_type, &type_cu);
18546   if (type_die != NULL)
18547     {
18548       /* N.B. We need to call get_die_type to ensure only one type for this DIE
18549          is created.  This is important, for example, because for c++ classes
18550          we need TYPE_NAME set which is only done by new_symbol.  Blech.  */
18551       type = read_type_die (type_die, type_cu);
18552       if (type == NULL)
18553         {
18554           complaint (&symfile_complaints,
18555                      _("Dwarf Error: Cannot build signatured type %s"
18556                        " referenced from DIE at 0x%x [in module %s]"),
18557                      hex_string (signature), die->offset.sect_off,
18558                      objfile_name (dwarf2_per_objfile->objfile));
18559           type = build_error_marker_type (cu, die);
18560         }
18561     }
18562   else
18563     {
18564       complaint (&symfile_complaints,
18565                  _("Dwarf Error: Problem reading signatured DIE %s referenced"
18566                    " from DIE at 0x%x [in module %s]"),
18567                  hex_string (signature), die->offset.sect_off,
18568                  objfile_name (dwarf2_per_objfile->objfile));
18569       type = build_error_marker_type (cu, die);
18570     }
18571   sig_type->type = type;
18572
18573   return type;
18574 }
18575
18576 /* Get the type specified by the DW_AT_signature ATTR in DIE/CU,
18577    reading in and processing the type unit if necessary.  */
18578
18579 static struct type *
18580 get_DW_AT_signature_type (struct die_info *die, const struct attribute *attr,
18581                           struct dwarf2_cu *cu) /* ARI: editCase function */
18582 {
18583   /* Yes, DW_AT_signature can use a non-ref_sig8 reference.  */
18584   if (attr_form_is_ref (attr))
18585     {
18586       struct dwarf2_cu *type_cu = cu;
18587       struct die_info *type_die = follow_die_ref (die, attr, &type_cu);
18588
18589       return read_type_die (type_die, type_cu);
18590     }
18591   else if (attr->form == DW_FORM_ref_sig8)
18592     {
18593       return get_signatured_type (die, DW_SIGNATURE (attr), cu);
18594     }
18595   else
18596     {
18597       complaint (&symfile_complaints,
18598                  _("Dwarf Error: DW_AT_signature has bad form %s in DIE"
18599                    " at 0x%x [in module %s]"),
18600                  dwarf_form_name (attr->form), die->offset.sect_off,
18601                  objfile_name (dwarf2_per_objfile->objfile));
18602       return build_error_marker_type (cu, die);
18603     }
18604 }
18605
18606 /* Load the DIEs associated with type unit PER_CU into memory.  */
18607
18608 static void
18609 load_full_type_unit (struct dwarf2_per_cu_data *per_cu)
18610 {
18611   struct signatured_type *sig_type;
18612
18613   /* Caller is responsible for ensuring type_unit_groups don't get here.  */
18614   gdb_assert (! IS_TYPE_UNIT_GROUP (per_cu));
18615
18616   /* We have the per_cu, but we need the signatured_type.
18617      Fortunately this is an easy translation.  */
18618   gdb_assert (per_cu->is_debug_types);
18619   sig_type = (struct signatured_type *) per_cu;
18620
18621   gdb_assert (per_cu->cu == NULL);
18622
18623   read_signatured_type (sig_type);
18624
18625   gdb_assert (per_cu->cu != NULL);
18626 }
18627
18628 /* die_reader_func for read_signatured_type.
18629    This is identical to load_full_comp_unit_reader,
18630    but is kept separate for now.  */
18631
18632 static void
18633 read_signatured_type_reader (const struct die_reader_specs *reader,
18634                              const gdb_byte *info_ptr,
18635                              struct die_info *comp_unit_die,
18636                              int has_children,
18637                              void *data)
18638 {
18639   struct dwarf2_cu *cu = reader->cu;
18640
18641   gdb_assert (cu->die_hash == NULL);
18642   cu->die_hash =
18643     htab_create_alloc_ex (cu->header.length / 12,
18644                           die_hash,
18645                           die_eq,
18646                           NULL,
18647                           &cu->comp_unit_obstack,
18648                           hashtab_obstack_allocate,
18649                           dummy_obstack_deallocate);
18650
18651   if (has_children)
18652     comp_unit_die->child = read_die_and_siblings (reader, info_ptr,
18653                                                   &info_ptr, comp_unit_die);
18654   cu->dies = comp_unit_die;
18655   /* comp_unit_die is not stored in die_hash, no need.  */
18656
18657   /* We try not to read any attributes in this function, because not
18658      all CUs needed for references have been loaded yet, and symbol
18659      table processing isn't initialized.  But we have to set the CU language,
18660      or we won't be able to build types correctly.
18661      Similarly, if we do not read the producer, we can not apply
18662      producer-specific interpretation.  */
18663   prepare_one_comp_unit (cu, cu->dies, language_minimal);
18664 }
18665
18666 /* Read in a signatured type and build its CU and DIEs.
18667    If the type is a stub for the real type in a DWO file,
18668    read in the real type from the DWO file as well.  */
18669
18670 static void
18671 read_signatured_type (struct signatured_type *sig_type)
18672 {
18673   struct dwarf2_per_cu_data *per_cu = &sig_type->per_cu;
18674
18675   gdb_assert (per_cu->is_debug_types);
18676   gdb_assert (per_cu->cu == NULL);
18677
18678   init_cutu_and_read_dies (per_cu, NULL, 0, 1,
18679                            read_signatured_type_reader, NULL);
18680   sig_type->per_cu.tu_read = 1;
18681 }
18682
18683 /* Decode simple location descriptions.
18684    Given a pointer to a dwarf block that defines a location, compute
18685    the location and return the value.
18686
18687    NOTE drow/2003-11-18: This function is called in two situations
18688    now: for the address of static or global variables (partial symbols
18689    only) and for offsets into structures which are expected to be
18690    (more or less) constant.  The partial symbol case should go away,
18691    and only the constant case should remain.  That will let this
18692    function complain more accurately.  A few special modes are allowed
18693    without complaint for global variables (for instance, global
18694    register values and thread-local values).
18695
18696    A location description containing no operations indicates that the
18697    object is optimized out.  The return value is 0 for that case.
18698    FIXME drow/2003-11-16: No callers check for this case any more; soon all
18699    callers will only want a very basic result and this can become a
18700    complaint.
18701
18702    Note that stack[0] is unused except as a default error return.  */
18703
18704 static CORE_ADDR
18705 decode_locdesc (struct dwarf_block *blk, struct dwarf2_cu *cu)
18706 {
18707   struct objfile *objfile = cu->objfile;
18708   size_t i;
18709   size_t size = blk->size;
18710   const gdb_byte *data = blk->data;
18711   CORE_ADDR stack[64];
18712   int stacki;
18713   unsigned int bytes_read, unsnd;
18714   gdb_byte op;
18715
18716   i = 0;
18717   stacki = 0;
18718   stack[stacki] = 0;
18719   stack[++stacki] = 0;
18720
18721   while (i < size)
18722     {
18723       op = data[i++];
18724       switch (op)
18725         {
18726         case DW_OP_lit0:
18727         case DW_OP_lit1:
18728         case DW_OP_lit2:
18729         case DW_OP_lit3:
18730         case DW_OP_lit4:
18731         case DW_OP_lit5:
18732         case DW_OP_lit6:
18733         case DW_OP_lit7:
18734         case DW_OP_lit8:
18735         case DW_OP_lit9:
18736         case DW_OP_lit10:
18737         case DW_OP_lit11:
18738         case DW_OP_lit12:
18739         case DW_OP_lit13:
18740         case DW_OP_lit14:
18741         case DW_OP_lit15:
18742         case DW_OP_lit16:
18743         case DW_OP_lit17:
18744         case DW_OP_lit18:
18745         case DW_OP_lit19:
18746         case DW_OP_lit20:
18747         case DW_OP_lit21:
18748         case DW_OP_lit22:
18749         case DW_OP_lit23:
18750         case DW_OP_lit24:
18751         case DW_OP_lit25:
18752         case DW_OP_lit26:
18753         case DW_OP_lit27:
18754         case DW_OP_lit28:
18755         case DW_OP_lit29:
18756         case DW_OP_lit30:
18757         case DW_OP_lit31:
18758           stack[++stacki] = op - DW_OP_lit0;
18759           break;
18760
18761         case DW_OP_reg0:
18762         case DW_OP_reg1:
18763         case DW_OP_reg2:
18764         case DW_OP_reg3:
18765         case DW_OP_reg4:
18766         case DW_OP_reg5:
18767         case DW_OP_reg6:
18768         case DW_OP_reg7:
18769         case DW_OP_reg8:
18770         case DW_OP_reg9:
18771         case DW_OP_reg10:
18772         case DW_OP_reg11:
18773         case DW_OP_reg12:
18774         case DW_OP_reg13:
18775         case DW_OP_reg14:
18776         case DW_OP_reg15:
18777         case DW_OP_reg16:
18778         case DW_OP_reg17:
18779         case DW_OP_reg18:
18780         case DW_OP_reg19:
18781         case DW_OP_reg20:
18782         case DW_OP_reg21:
18783         case DW_OP_reg22:
18784         case DW_OP_reg23:
18785         case DW_OP_reg24:
18786         case DW_OP_reg25:
18787         case DW_OP_reg26:
18788         case DW_OP_reg27:
18789         case DW_OP_reg28:
18790         case DW_OP_reg29:
18791         case DW_OP_reg30:
18792         case DW_OP_reg31:
18793           stack[++stacki] = op - DW_OP_reg0;
18794           if (i < size)
18795             dwarf2_complex_location_expr_complaint ();
18796           break;
18797
18798         case DW_OP_regx:
18799           unsnd = read_unsigned_leb128 (NULL, (data + i), &bytes_read);
18800           i += bytes_read;
18801           stack[++stacki] = unsnd;
18802           if (i < size)
18803             dwarf2_complex_location_expr_complaint ();
18804           break;
18805
18806         case DW_OP_addr:
18807           stack[++stacki] = read_address (objfile->obfd, &data[i],
18808                                           cu, &bytes_read);
18809           i += bytes_read;
18810           break;
18811
18812         case DW_OP_const1u:
18813           stack[++stacki] = read_1_byte (objfile->obfd, &data[i]);
18814           i += 1;
18815           break;
18816
18817         case DW_OP_const1s:
18818           stack[++stacki] = read_1_signed_byte (objfile->obfd, &data[i]);
18819           i += 1;
18820           break;
18821
18822         case DW_OP_const2u:
18823           stack[++stacki] = read_2_bytes (objfile->obfd, &data[i]);
18824           i += 2;
18825           break;
18826
18827         case DW_OP_const2s:
18828           stack[++stacki] = read_2_signed_bytes (objfile->obfd, &data[i]);
18829           i += 2;
18830           break;
18831
18832         case DW_OP_const4u:
18833           stack[++stacki] = read_4_bytes (objfile->obfd, &data[i]);
18834           i += 4;
18835           break;
18836
18837         case DW_OP_const4s:
18838           stack[++stacki] = read_4_signed_bytes (objfile->obfd, &data[i]);
18839           i += 4;
18840           break;
18841
18842         case DW_OP_const8u:
18843           stack[++stacki] = read_8_bytes (objfile->obfd, &data[i]);
18844           i += 8;
18845           break;
18846
18847         case DW_OP_constu:
18848           stack[++stacki] = read_unsigned_leb128 (NULL, (data + i),
18849                                                   &bytes_read);
18850           i += bytes_read;
18851           break;
18852
18853         case DW_OP_consts:
18854           stack[++stacki] = read_signed_leb128 (NULL, (data + i), &bytes_read);
18855           i += bytes_read;
18856           break;
18857
18858         case DW_OP_dup:
18859           stack[stacki + 1] = stack[stacki];
18860           stacki++;
18861           break;
18862
18863         case DW_OP_plus:
18864           stack[stacki - 1] += stack[stacki];
18865           stacki--;
18866           break;
18867
18868         case DW_OP_plus_uconst:
18869           stack[stacki] += read_unsigned_leb128 (NULL, (data + i),
18870                                                  &bytes_read);
18871           i += bytes_read;
18872           break;
18873
18874         case DW_OP_minus:
18875           stack[stacki - 1] -= stack[stacki];
18876           stacki--;
18877           break;
18878
18879         case DW_OP_deref:
18880           /* If we're not the last op, then we definitely can't encode
18881              this using GDB's address_class enum.  This is valid for partial
18882              global symbols, although the variable's address will be bogus
18883              in the psymtab.  */
18884           if (i < size)
18885             dwarf2_complex_location_expr_complaint ();
18886           break;
18887
18888         case DW_OP_GNU_push_tls_address:
18889           /* The top of the stack has the offset from the beginning
18890              of the thread control block at which the variable is located.  */
18891           /* Nothing should follow this operator, so the top of stack would
18892              be returned.  */
18893           /* This is valid for partial global symbols, but the variable's
18894              address will be bogus in the psymtab.  Make it always at least
18895              non-zero to not look as a variable garbage collected by linker
18896              which have DW_OP_addr 0.  */
18897           if (i < size)
18898             dwarf2_complex_location_expr_complaint ();
18899           stack[stacki]++;
18900           break;
18901
18902         case DW_OP_GNU_uninit:
18903           break;
18904
18905         case DW_OP_GNU_addr_index:
18906         case DW_OP_GNU_const_index:
18907           stack[++stacki] = read_addr_index_from_leb128 (cu, &data[i],
18908                                                          &bytes_read);
18909           i += bytes_read;
18910           break;
18911
18912         default:
18913           {
18914             const char *name = get_DW_OP_name (op);
18915
18916             if (name)
18917               complaint (&symfile_complaints, _("unsupported stack op: '%s'"),
18918                          name);
18919             else
18920               complaint (&symfile_complaints, _("unsupported stack op: '%02x'"),
18921                          op);
18922           }
18923
18924           return (stack[stacki]);
18925         }
18926
18927       /* Enforce maximum stack depth of SIZE-1 to avoid writing
18928          outside of the allocated space.  Also enforce minimum>0.  */
18929       if (stacki >= ARRAY_SIZE (stack) - 1)
18930         {
18931           complaint (&symfile_complaints,
18932                      _("location description stack overflow"));
18933           return 0;
18934         }
18935
18936       if (stacki <= 0)
18937         {
18938           complaint (&symfile_complaints,
18939                      _("location description stack underflow"));
18940           return 0;
18941         }
18942     }
18943   return (stack[stacki]);
18944 }
18945
18946 /* memory allocation interface */
18947
18948 static struct dwarf_block *
18949 dwarf_alloc_block (struct dwarf2_cu *cu)
18950 {
18951   struct dwarf_block *blk;
18952
18953   blk = (struct dwarf_block *)
18954     obstack_alloc (&cu->comp_unit_obstack, sizeof (struct dwarf_block));
18955   return (blk);
18956 }
18957
18958 static struct die_info *
18959 dwarf_alloc_die (struct dwarf2_cu *cu, int num_attrs)
18960 {
18961   struct die_info *die;
18962   size_t size = sizeof (struct die_info);
18963
18964   if (num_attrs > 1)
18965     size += (num_attrs - 1) * sizeof (struct attribute);
18966
18967   die = (struct die_info *) obstack_alloc (&cu->comp_unit_obstack, size);
18968   memset (die, 0, sizeof (struct die_info));
18969   return (die);
18970 }
18971
18972 \f
18973 /* Macro support.  */
18974
18975 /* Return file name relative to the compilation directory of file number I in
18976    *LH's file name table.  The result is allocated using xmalloc; the caller is
18977    responsible for freeing it.  */
18978
18979 static char *
18980 file_file_name (int file, struct line_header *lh)
18981 {
18982   /* Is the file number a valid index into the line header's file name
18983      table?  Remember that file numbers start with one, not zero.  */
18984   if (1 <= file && file <= lh->num_file_names)
18985     {
18986       struct file_entry *fe = &lh->file_names[file - 1];
18987
18988       if (IS_ABSOLUTE_PATH (fe->name) || fe->dir_index == 0)
18989         return xstrdup (fe->name);
18990       return concat (lh->include_dirs[fe->dir_index - 1], SLASH_STRING,
18991                      fe->name, NULL);
18992     }
18993   else
18994     {
18995       /* The compiler produced a bogus file number.  We can at least
18996          record the macro definitions made in the file, even if we
18997          won't be able to find the file by name.  */
18998       char fake_name[80];
18999
19000       xsnprintf (fake_name, sizeof (fake_name),
19001                  "<bad macro file number %d>", file);
19002
19003       complaint (&symfile_complaints,
19004                  _("bad file number in macro information (%d)"),
19005                  file);
19006
19007       return xstrdup (fake_name);
19008     }
19009 }
19010
19011 /* Return the full name of file number I in *LH's file name table.
19012    Use COMP_DIR as the name of the current directory of the
19013    compilation.  The result is allocated using xmalloc; the caller is
19014    responsible for freeing it.  */
19015 static char *
19016 file_full_name (int file, struct line_header *lh, const char *comp_dir)
19017 {
19018   /* Is the file number a valid index into the line header's file name
19019      table?  Remember that file numbers start with one, not zero.  */
19020   if (1 <= file && file <= lh->num_file_names)
19021     {
19022       char *relative = file_file_name (file, lh);
19023
19024       if (IS_ABSOLUTE_PATH (relative) || comp_dir == NULL)
19025         return relative;
19026       return reconcat (relative, comp_dir, SLASH_STRING, relative, NULL);
19027     }
19028   else
19029     return file_file_name (file, lh);
19030 }
19031
19032
19033 static struct macro_source_file *
19034 macro_start_file (int file, int line,
19035                   struct macro_source_file *current_file,
19036                   const char *comp_dir,
19037                   struct line_header *lh, struct objfile *objfile)
19038 {
19039   /* File name relative to the compilation directory of this source file.  */
19040   char *file_name = file_file_name (file, lh);
19041
19042   if (! current_file)
19043     {
19044       /* Note: We don't create a macro table for this compilation unit
19045          at all until we actually get a filename.  */
19046       struct macro_table *macro_table = get_macro_table (objfile, comp_dir);
19047
19048       /* If we have no current file, then this must be the start_file
19049          directive for the compilation unit's main source file.  */
19050       current_file = macro_set_main (macro_table, file_name);
19051       macro_define_special (macro_table);
19052     }
19053   else
19054     current_file = macro_include (current_file, line, file_name);
19055
19056   xfree (file_name);
19057
19058   return current_file;
19059 }
19060
19061
19062 /* Copy the LEN characters at BUF to a xmalloc'ed block of memory,
19063    followed by a null byte.  */
19064 static char *
19065 copy_string (const char *buf, int len)
19066 {
19067   char *s = xmalloc (len + 1);
19068
19069   memcpy (s, buf, len);
19070   s[len] = '\0';
19071   return s;
19072 }
19073
19074
19075 static const char *
19076 consume_improper_spaces (const char *p, const char *body)
19077 {
19078   if (*p == ' ')
19079     {
19080       complaint (&symfile_complaints,
19081                  _("macro definition contains spaces "
19082                    "in formal argument list:\n`%s'"),
19083                  body);
19084
19085       while (*p == ' ')
19086         p++;
19087     }
19088
19089   return p;
19090 }
19091
19092
19093 static void
19094 parse_macro_definition (struct macro_source_file *file, int line,
19095                         const char *body)
19096 {
19097   const char *p;
19098
19099   /* The body string takes one of two forms.  For object-like macro
19100      definitions, it should be:
19101
19102         <macro name> " " <definition>
19103
19104      For function-like macro definitions, it should be:
19105
19106         <macro name> "() " <definition>
19107      or
19108         <macro name> "(" <arg name> ( "," <arg name> ) * ") " <definition>
19109
19110      Spaces may appear only where explicitly indicated, and in the
19111      <definition>.
19112
19113      The Dwarf 2 spec says that an object-like macro's name is always
19114      followed by a space, but versions of GCC around March 2002 omit
19115      the space when the macro's definition is the empty string.
19116
19117      The Dwarf 2 spec says that there should be no spaces between the
19118      formal arguments in a function-like macro's formal argument list,
19119      but versions of GCC around March 2002 include spaces after the
19120      commas.  */
19121
19122
19123   /* Find the extent of the macro name.  The macro name is terminated
19124      by either a space or null character (for an object-like macro) or
19125      an opening paren (for a function-like macro).  */
19126   for (p = body; *p; p++)
19127     if (*p == ' ' || *p == '(')
19128       break;
19129
19130   if (*p == ' ' || *p == '\0')
19131     {
19132       /* It's an object-like macro.  */
19133       int name_len = p - body;
19134       char *name = copy_string (body, name_len);
19135       const char *replacement;
19136
19137       if (*p == ' ')
19138         replacement = body + name_len + 1;
19139       else
19140         {
19141           dwarf2_macro_malformed_definition_complaint (body);
19142           replacement = body + name_len;
19143         }
19144
19145       macro_define_object (file, line, name, replacement);
19146
19147       xfree (name);
19148     }
19149   else if (*p == '(')
19150     {
19151       /* It's a function-like macro.  */
19152       char *name = copy_string (body, p - body);
19153       int argc = 0;
19154       int argv_size = 1;
19155       char **argv = xmalloc (argv_size * sizeof (*argv));
19156
19157       p++;
19158
19159       p = consume_improper_spaces (p, body);
19160
19161       /* Parse the formal argument list.  */
19162       while (*p && *p != ')')
19163         {
19164           /* Find the extent of the current argument name.  */
19165           const char *arg_start = p;
19166
19167           while (*p && *p != ',' && *p != ')' && *p != ' ')
19168             p++;
19169
19170           if (! *p || p == arg_start)
19171             dwarf2_macro_malformed_definition_complaint (body);
19172           else
19173             {
19174               /* Make sure argv has room for the new argument.  */
19175               if (argc >= argv_size)
19176                 {
19177                   argv_size *= 2;
19178                   argv = xrealloc (argv, argv_size * sizeof (*argv));
19179                 }
19180
19181               argv[argc++] = copy_string (arg_start, p - arg_start);
19182             }
19183
19184           p = consume_improper_spaces (p, body);
19185
19186           /* Consume the comma, if present.  */
19187           if (*p == ',')
19188             {
19189               p++;
19190
19191               p = consume_improper_spaces (p, body);
19192             }
19193         }
19194
19195       if (*p == ')')
19196         {
19197           p++;
19198
19199           if (*p == ' ')
19200             /* Perfectly formed definition, no complaints.  */
19201             macro_define_function (file, line, name,
19202                                    argc, (const char **) argv,
19203                                    p + 1);
19204           else if (*p == '\0')
19205             {
19206               /* Complain, but do define it.  */
19207               dwarf2_macro_malformed_definition_complaint (body);
19208               macro_define_function (file, line, name,
19209                                      argc, (const char **) argv,
19210                                      p);
19211             }
19212           else
19213             /* Just complain.  */
19214             dwarf2_macro_malformed_definition_complaint (body);
19215         }
19216       else
19217         /* Just complain.  */
19218         dwarf2_macro_malformed_definition_complaint (body);
19219
19220       xfree (name);
19221       {
19222         int i;
19223
19224         for (i = 0; i < argc; i++)
19225           xfree (argv[i]);
19226       }
19227       xfree (argv);
19228     }
19229   else
19230     dwarf2_macro_malformed_definition_complaint (body);
19231 }
19232
19233 /* Skip some bytes from BYTES according to the form given in FORM.
19234    Returns the new pointer.  */
19235
19236 static const gdb_byte *
19237 skip_form_bytes (bfd *abfd, const gdb_byte *bytes, const gdb_byte *buffer_end,
19238                  enum dwarf_form form,
19239                  unsigned int offset_size,
19240                  struct dwarf2_section_info *section)
19241 {
19242   unsigned int bytes_read;
19243
19244   switch (form)
19245     {
19246     case DW_FORM_data1:
19247     case DW_FORM_flag:
19248       ++bytes;
19249       break;
19250
19251     case DW_FORM_data2:
19252       bytes += 2;
19253       break;
19254
19255     case DW_FORM_data4:
19256       bytes += 4;
19257       break;
19258
19259     case DW_FORM_data8:
19260       bytes += 8;
19261       break;
19262
19263     case DW_FORM_string:
19264       read_direct_string (abfd, bytes, &bytes_read);
19265       bytes += bytes_read;
19266       break;
19267
19268     case DW_FORM_sec_offset:
19269     case DW_FORM_strp:
19270     case DW_FORM_GNU_strp_alt:
19271       bytes += offset_size;
19272       break;
19273
19274     case DW_FORM_block:
19275       bytes += read_unsigned_leb128 (abfd, bytes, &bytes_read);
19276       bytes += bytes_read;
19277       break;
19278
19279     case DW_FORM_block1:
19280       bytes += 1 + read_1_byte (abfd, bytes);
19281       break;
19282     case DW_FORM_block2:
19283       bytes += 2 + read_2_bytes (abfd, bytes);
19284       break;
19285     case DW_FORM_block4:
19286       bytes += 4 + read_4_bytes (abfd, bytes);
19287       break;
19288
19289     case DW_FORM_sdata:
19290     case DW_FORM_udata:
19291     case DW_FORM_GNU_addr_index:
19292     case DW_FORM_GNU_str_index:
19293       bytes = gdb_skip_leb128 (bytes, buffer_end);
19294       if (bytes == NULL)
19295         {
19296           dwarf2_section_buffer_overflow_complaint (section);
19297           return NULL;
19298         }
19299       break;
19300
19301     default:
19302       {
19303       complain:
19304         complaint (&symfile_complaints,
19305                    _("invalid form 0x%x in `%s'"),
19306                    form,
19307                    section->asection->name);
19308         return NULL;
19309       }
19310     }
19311
19312   return bytes;
19313 }
19314
19315 /* A helper for dwarf_decode_macros that handles skipping an unknown
19316    opcode.  Returns an updated pointer to the macro data buffer; or,
19317    on error, issues a complaint and returns NULL.  */
19318
19319 static const gdb_byte *
19320 skip_unknown_opcode (unsigned int opcode,
19321                      const gdb_byte **opcode_definitions,
19322                      const gdb_byte *mac_ptr, const gdb_byte *mac_end,
19323                      bfd *abfd,
19324                      unsigned int offset_size,
19325                      struct dwarf2_section_info *section)
19326 {
19327   unsigned int bytes_read, i;
19328   unsigned long arg;
19329   const gdb_byte *defn;
19330
19331   if (opcode_definitions[opcode] == NULL)
19332     {
19333       complaint (&symfile_complaints,
19334                  _("unrecognized DW_MACFINO opcode 0x%x"),
19335                  opcode);
19336       return NULL;
19337     }
19338
19339   defn = opcode_definitions[opcode];
19340   arg = read_unsigned_leb128 (abfd, defn, &bytes_read);
19341   defn += bytes_read;
19342
19343   for (i = 0; i < arg; ++i)
19344     {
19345       mac_ptr = skip_form_bytes (abfd, mac_ptr, mac_end, defn[i], offset_size,
19346                                  section);
19347       if (mac_ptr == NULL)
19348         {
19349           /* skip_form_bytes already issued the complaint.  */
19350           return NULL;
19351         }
19352     }
19353
19354   return mac_ptr;
19355 }
19356
19357 /* A helper function which parses the header of a macro section.
19358    If the macro section is the extended (for now called "GNU") type,
19359    then this updates *OFFSET_SIZE.  Returns a pointer to just after
19360    the header, or issues a complaint and returns NULL on error.  */
19361
19362 static const gdb_byte *
19363 dwarf_parse_macro_header (const gdb_byte **opcode_definitions,
19364                           bfd *abfd,
19365                           const gdb_byte *mac_ptr,
19366                           unsigned int *offset_size,
19367                           int section_is_gnu)
19368 {
19369   memset (opcode_definitions, 0, 256 * sizeof (gdb_byte *));
19370
19371   if (section_is_gnu)
19372     {
19373       unsigned int version, flags;
19374
19375       version = read_2_bytes (abfd, mac_ptr);
19376       if (version != 4)
19377         {
19378           complaint (&symfile_complaints,
19379                      _("unrecognized version `%d' in .debug_macro section"),
19380                      version);
19381           return NULL;
19382         }
19383       mac_ptr += 2;
19384
19385       flags = read_1_byte (abfd, mac_ptr);
19386       ++mac_ptr;
19387       *offset_size = (flags & 1) ? 8 : 4;
19388
19389       if ((flags & 2) != 0)
19390         /* We don't need the line table offset.  */
19391         mac_ptr += *offset_size;
19392
19393       /* Vendor opcode descriptions.  */
19394       if ((flags & 4) != 0)
19395         {
19396           unsigned int i, count;
19397
19398           count = read_1_byte (abfd, mac_ptr);
19399           ++mac_ptr;
19400           for (i = 0; i < count; ++i)
19401             {
19402               unsigned int opcode, bytes_read;
19403               unsigned long arg;
19404
19405               opcode = read_1_byte (abfd, mac_ptr);
19406               ++mac_ptr;
19407               opcode_definitions[opcode] = mac_ptr;
19408               arg = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
19409               mac_ptr += bytes_read;
19410               mac_ptr += arg;
19411             }
19412         }
19413     }
19414
19415   return mac_ptr;
19416 }
19417
19418 /* A helper for dwarf_decode_macros that handles the GNU extensions,
19419    including DW_MACRO_GNU_transparent_include.  */
19420
19421 static void
19422 dwarf_decode_macro_bytes (bfd *abfd,
19423                           const gdb_byte *mac_ptr, const gdb_byte *mac_end,
19424                           struct macro_source_file *current_file,
19425                           struct line_header *lh, const char *comp_dir,
19426                           struct dwarf2_section_info *section,
19427                           int section_is_gnu, int section_is_dwz,
19428                           unsigned int offset_size,
19429                           struct objfile *objfile,
19430                           htab_t include_hash)
19431 {
19432   enum dwarf_macro_record_type macinfo_type;
19433   int at_commandline;
19434   const gdb_byte *opcode_definitions[256];
19435
19436   mac_ptr = dwarf_parse_macro_header (opcode_definitions, abfd, mac_ptr,
19437                                       &offset_size, section_is_gnu);
19438   if (mac_ptr == NULL)
19439     {
19440       /* We already issued a complaint.  */
19441       return;
19442     }
19443
19444   /* Determines if GDB is still before first DW_MACINFO_start_file.  If true
19445      GDB is still reading the definitions from command line.  First
19446      DW_MACINFO_start_file will need to be ignored as it was already executed
19447      to create CURRENT_FILE for the main source holding also the command line
19448      definitions.  On first met DW_MACINFO_start_file this flag is reset to
19449      normally execute all the remaining DW_MACINFO_start_file macinfos.  */
19450
19451   at_commandline = 1;
19452
19453   do
19454     {
19455       /* Do we at least have room for a macinfo type byte?  */
19456       if (mac_ptr >= mac_end)
19457         {
19458           dwarf2_section_buffer_overflow_complaint (section);
19459           break;
19460         }
19461
19462       macinfo_type = read_1_byte (abfd, mac_ptr);
19463       mac_ptr++;
19464
19465       /* Note that we rely on the fact that the corresponding GNU and
19466          DWARF constants are the same.  */
19467       switch (macinfo_type)
19468         {
19469           /* A zero macinfo type indicates the end of the macro
19470              information.  */
19471         case 0:
19472           break;
19473
19474         case DW_MACRO_GNU_define:
19475         case DW_MACRO_GNU_undef:
19476         case DW_MACRO_GNU_define_indirect:
19477         case DW_MACRO_GNU_undef_indirect:
19478         case DW_MACRO_GNU_define_indirect_alt:
19479         case DW_MACRO_GNU_undef_indirect_alt:
19480           {
19481             unsigned int bytes_read;
19482             int line;
19483             const char *body;
19484             int is_define;
19485
19486             line = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
19487             mac_ptr += bytes_read;
19488
19489             if (macinfo_type == DW_MACRO_GNU_define
19490                 || macinfo_type == DW_MACRO_GNU_undef)
19491               {
19492                 body = read_direct_string (abfd, mac_ptr, &bytes_read);
19493                 mac_ptr += bytes_read;
19494               }
19495             else
19496               {
19497                 LONGEST str_offset;
19498
19499                 str_offset = read_offset_1 (abfd, mac_ptr, offset_size);
19500                 mac_ptr += offset_size;
19501
19502                 if (macinfo_type == DW_MACRO_GNU_define_indirect_alt
19503                     || macinfo_type == DW_MACRO_GNU_undef_indirect_alt
19504                     || section_is_dwz)
19505                   {
19506                     struct dwz_file *dwz = dwarf2_get_dwz_file ();
19507
19508                     body = read_indirect_string_from_dwz (dwz, str_offset);
19509                   }
19510                 else
19511                   body = read_indirect_string_at_offset (abfd, str_offset);
19512               }
19513
19514             is_define = (macinfo_type == DW_MACRO_GNU_define
19515                          || macinfo_type == DW_MACRO_GNU_define_indirect
19516                          || macinfo_type == DW_MACRO_GNU_define_indirect_alt);
19517             if (! current_file)
19518               {
19519                 /* DWARF violation as no main source is present.  */
19520                 complaint (&symfile_complaints,
19521                            _("debug info with no main source gives macro %s "
19522                              "on line %d: %s"),
19523                            is_define ? _("definition") : _("undefinition"),
19524                            line, body);
19525                 break;
19526               }
19527             if ((line == 0 && !at_commandline)
19528                 || (line != 0 && at_commandline))
19529               complaint (&symfile_complaints,
19530                          _("debug info gives %s macro %s with %s line %d: %s"),
19531                          at_commandline ? _("command-line") : _("in-file"),
19532                          is_define ? _("definition") : _("undefinition"),
19533                          line == 0 ? _("zero") : _("non-zero"), line, body);
19534
19535             if (is_define)
19536               parse_macro_definition (current_file, line, body);
19537             else
19538               {
19539                 gdb_assert (macinfo_type == DW_MACRO_GNU_undef
19540                             || macinfo_type == DW_MACRO_GNU_undef_indirect
19541                             || macinfo_type == DW_MACRO_GNU_undef_indirect_alt);
19542                 macro_undef (current_file, line, body);
19543               }
19544           }
19545           break;
19546
19547         case DW_MACRO_GNU_start_file:
19548           {
19549             unsigned int bytes_read;
19550             int line, file;
19551
19552             line = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
19553             mac_ptr += bytes_read;
19554             file = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
19555             mac_ptr += bytes_read;
19556
19557             if ((line == 0 && !at_commandline)
19558                 || (line != 0 && at_commandline))
19559               complaint (&symfile_complaints,
19560                          _("debug info gives source %d included "
19561                            "from %s at %s line %d"),
19562                          file, at_commandline ? _("command-line") : _("file"),
19563                          line == 0 ? _("zero") : _("non-zero"), line);
19564
19565             if (at_commandline)
19566               {
19567                 /* This DW_MACRO_GNU_start_file was executed in the
19568                    pass one.  */
19569                 at_commandline = 0;
19570               }
19571             else
19572               current_file = macro_start_file (file, line,
19573                                                current_file, comp_dir,
19574                                                lh, objfile);
19575           }
19576           break;
19577
19578         case DW_MACRO_GNU_end_file:
19579           if (! current_file)
19580             complaint (&symfile_complaints,
19581                        _("macro debug info has an unmatched "
19582                          "`close_file' directive"));
19583           else
19584             {
19585               current_file = current_file->included_by;
19586               if (! current_file)
19587                 {
19588                   enum dwarf_macro_record_type next_type;
19589
19590                   /* GCC circa March 2002 doesn't produce the zero
19591                      type byte marking the end of the compilation
19592                      unit.  Complain if it's not there, but exit no
19593                      matter what.  */
19594
19595                   /* Do we at least have room for a macinfo type byte?  */
19596                   if (mac_ptr >= mac_end)
19597                     {
19598                       dwarf2_section_buffer_overflow_complaint (section);
19599                       return;
19600                     }
19601
19602                   /* We don't increment mac_ptr here, so this is just
19603                      a look-ahead.  */
19604                   next_type = read_1_byte (abfd, mac_ptr);
19605                   if (next_type != 0)
19606                     complaint (&symfile_complaints,
19607                                _("no terminating 0-type entry for "
19608                                  "macros in `.debug_macinfo' section"));
19609
19610                   return;
19611                 }
19612             }
19613           break;
19614
19615         case DW_MACRO_GNU_transparent_include:
19616         case DW_MACRO_GNU_transparent_include_alt:
19617           {
19618             LONGEST offset;
19619             void **slot;
19620             bfd *include_bfd = abfd;
19621             struct dwarf2_section_info *include_section = section;
19622             struct dwarf2_section_info alt_section;
19623             const gdb_byte *include_mac_end = mac_end;
19624             int is_dwz = section_is_dwz;
19625             const gdb_byte *new_mac_ptr;
19626
19627             offset = read_offset_1 (abfd, mac_ptr, offset_size);
19628             mac_ptr += offset_size;
19629
19630             if (macinfo_type == DW_MACRO_GNU_transparent_include_alt)
19631               {
19632                 struct dwz_file *dwz = dwarf2_get_dwz_file ();
19633
19634                 dwarf2_read_section (dwarf2_per_objfile->objfile,
19635                                      &dwz->macro);
19636
19637                 include_bfd = dwz->macro.asection->owner;
19638                 include_section = &dwz->macro;
19639                 include_mac_end = dwz->macro.buffer + dwz->macro.size;
19640                 is_dwz = 1;
19641               }
19642
19643             new_mac_ptr = include_section->buffer + offset;
19644             slot = htab_find_slot (include_hash, new_mac_ptr, INSERT);
19645
19646             if (*slot != NULL)
19647               {
19648                 /* This has actually happened; see
19649                    http://sourceware.org/bugzilla/show_bug.cgi?id=13568.  */
19650                 complaint (&symfile_complaints,
19651                            _("recursive DW_MACRO_GNU_transparent_include in "
19652                              ".debug_macro section"));
19653               }
19654             else
19655               {
19656                 *slot = (void *) new_mac_ptr;
19657
19658                 dwarf_decode_macro_bytes (include_bfd, new_mac_ptr,
19659                                           include_mac_end, current_file,
19660                                           lh, comp_dir,
19661                                           section, section_is_gnu, is_dwz,
19662                                           offset_size, objfile, include_hash);
19663
19664                 htab_remove_elt (include_hash, (void *) new_mac_ptr);
19665               }
19666           }
19667           break;
19668
19669         case DW_MACINFO_vendor_ext:
19670           if (!section_is_gnu)
19671             {
19672               unsigned int bytes_read;
19673               int constant;
19674
19675               constant = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
19676               mac_ptr += bytes_read;
19677               read_direct_string (abfd, mac_ptr, &bytes_read);
19678               mac_ptr += bytes_read;
19679
19680               /* We don't recognize any vendor extensions.  */
19681               break;
19682             }
19683           /* FALLTHROUGH */
19684
19685         default:
19686           mac_ptr = skip_unknown_opcode (macinfo_type, opcode_definitions,
19687                                          mac_ptr, mac_end, abfd, offset_size,
19688                                          section);
19689           if (mac_ptr == NULL)
19690             return;
19691           break;
19692         }
19693     } while (macinfo_type != 0);
19694 }
19695
19696 static void
19697 dwarf_decode_macros (struct dwarf2_cu *cu, unsigned int offset,
19698                      const char *comp_dir, int section_is_gnu)
19699 {
19700   struct objfile *objfile = dwarf2_per_objfile->objfile;
19701   struct line_header *lh = cu->line_header;
19702   bfd *abfd;
19703   const gdb_byte *mac_ptr, *mac_end;
19704   struct macro_source_file *current_file = 0;
19705   enum dwarf_macro_record_type macinfo_type;
19706   unsigned int offset_size = cu->header.offset_size;
19707   const gdb_byte *opcode_definitions[256];
19708   struct cleanup *cleanup;
19709   htab_t include_hash;
19710   void **slot;
19711   struct dwarf2_section_info *section;
19712   const char *section_name;
19713
19714   if (cu->dwo_unit != NULL)
19715     {
19716       if (section_is_gnu)
19717         {
19718           section = &cu->dwo_unit->dwo_file->sections.macro;
19719           section_name = ".debug_macro.dwo";
19720         }
19721       else
19722         {
19723           section = &cu->dwo_unit->dwo_file->sections.macinfo;
19724           section_name = ".debug_macinfo.dwo";
19725         }
19726     }
19727   else
19728     {
19729       if (section_is_gnu)
19730         {
19731           section = &dwarf2_per_objfile->macro;
19732           section_name = ".debug_macro";
19733         }
19734       else
19735         {
19736           section = &dwarf2_per_objfile->macinfo;
19737           section_name = ".debug_macinfo";
19738         }
19739     }
19740
19741   dwarf2_read_section (objfile, section);
19742   if (section->buffer == NULL)
19743     {
19744       complaint (&symfile_complaints, _("missing %s section"), section_name);
19745       return;
19746     }
19747   abfd = section->asection->owner;
19748
19749   /* First pass: Find the name of the base filename.
19750      This filename is needed in order to process all macros whose definition
19751      (or undefinition) comes from the command line.  These macros are defined
19752      before the first DW_MACINFO_start_file entry, and yet still need to be
19753      associated to the base file.
19754
19755      To determine the base file name, we scan the macro definitions until we
19756      reach the first DW_MACINFO_start_file entry.  We then initialize
19757      CURRENT_FILE accordingly so that any macro definition found before the
19758      first DW_MACINFO_start_file can still be associated to the base file.  */
19759
19760   mac_ptr = section->buffer + offset;
19761   mac_end = section->buffer + section->size;
19762
19763   mac_ptr = dwarf_parse_macro_header (opcode_definitions, abfd, mac_ptr,
19764                                       &offset_size, section_is_gnu);
19765   if (mac_ptr == NULL)
19766     {
19767       /* We already issued a complaint.  */
19768       return;
19769     }
19770
19771   do
19772     {
19773       /* Do we at least have room for a macinfo type byte?  */
19774       if (mac_ptr >= mac_end)
19775         {
19776           /* Complaint is printed during the second pass as GDB will probably
19777              stop the first pass earlier upon finding
19778              DW_MACINFO_start_file.  */
19779           break;
19780         }
19781
19782       macinfo_type = read_1_byte (abfd, mac_ptr);
19783       mac_ptr++;
19784
19785       /* Note that we rely on the fact that the corresponding GNU and
19786          DWARF constants are the same.  */
19787       switch (macinfo_type)
19788         {
19789           /* A zero macinfo type indicates the end of the macro
19790              information.  */
19791         case 0:
19792           break;
19793
19794         case DW_MACRO_GNU_define:
19795         case DW_MACRO_GNU_undef:
19796           /* Only skip the data by MAC_PTR.  */
19797           {
19798             unsigned int bytes_read;
19799
19800             read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
19801             mac_ptr += bytes_read;
19802             read_direct_string (abfd, mac_ptr, &bytes_read);
19803             mac_ptr += bytes_read;
19804           }
19805           break;
19806
19807         case DW_MACRO_GNU_start_file:
19808           {
19809             unsigned int bytes_read;
19810             int line, file;
19811
19812             line = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
19813             mac_ptr += bytes_read;
19814             file = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
19815             mac_ptr += bytes_read;
19816
19817             current_file = macro_start_file (file, line, current_file,
19818                                              comp_dir, lh, objfile);
19819           }
19820           break;
19821
19822         case DW_MACRO_GNU_end_file:
19823           /* No data to skip by MAC_PTR.  */
19824           break;
19825
19826         case DW_MACRO_GNU_define_indirect:
19827         case DW_MACRO_GNU_undef_indirect:
19828         case DW_MACRO_GNU_define_indirect_alt:
19829         case DW_MACRO_GNU_undef_indirect_alt:
19830           {
19831             unsigned int bytes_read;
19832
19833             read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
19834             mac_ptr += bytes_read;
19835             mac_ptr += offset_size;
19836           }
19837           break;
19838
19839         case DW_MACRO_GNU_transparent_include:
19840         case DW_MACRO_GNU_transparent_include_alt:
19841           /* Note that, according to the spec, a transparent include
19842              chain cannot call DW_MACRO_GNU_start_file.  So, we can just
19843              skip this opcode.  */
19844           mac_ptr += offset_size;
19845           break;
19846
19847         case DW_MACINFO_vendor_ext:
19848           /* Only skip the data by MAC_PTR.  */
19849           if (!section_is_gnu)
19850             {
19851               unsigned int bytes_read;
19852
19853               read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
19854               mac_ptr += bytes_read;
19855               read_direct_string (abfd, mac_ptr, &bytes_read);
19856               mac_ptr += bytes_read;
19857             }
19858           /* FALLTHROUGH */
19859
19860         default:
19861           mac_ptr = skip_unknown_opcode (macinfo_type, opcode_definitions,
19862                                          mac_ptr, mac_end, abfd, offset_size,
19863                                          section);
19864           if (mac_ptr == NULL)
19865             return;
19866           break;
19867         }
19868     } while (macinfo_type != 0 && current_file == NULL);
19869
19870   /* Second pass: Process all entries.
19871
19872      Use the AT_COMMAND_LINE flag to determine whether we are still processing
19873      command-line macro definitions/undefinitions.  This flag is unset when we
19874      reach the first DW_MACINFO_start_file entry.  */
19875
19876   include_hash = htab_create_alloc (1, htab_hash_pointer, htab_eq_pointer,
19877                                     NULL, xcalloc, xfree);
19878   cleanup = make_cleanup_htab_delete (include_hash);
19879   mac_ptr = section->buffer + offset;
19880   slot = htab_find_slot (include_hash, mac_ptr, INSERT);
19881   *slot = (void *) mac_ptr;
19882   dwarf_decode_macro_bytes (abfd, mac_ptr, mac_end,
19883                             current_file, lh, comp_dir, section,
19884                             section_is_gnu, 0,
19885                             offset_size, objfile, include_hash);
19886   do_cleanups (cleanup);
19887 }
19888
19889 /* Check if the attribute's form is a DW_FORM_block*
19890    if so return true else false.  */
19891
19892 static int
19893 attr_form_is_block (const struct attribute *attr)
19894 {
19895   return (attr == NULL ? 0 :
19896       attr->form == DW_FORM_block1
19897       || attr->form == DW_FORM_block2
19898       || attr->form == DW_FORM_block4
19899       || attr->form == DW_FORM_block
19900       || attr->form == DW_FORM_exprloc);
19901 }
19902
19903 /* Return non-zero if ATTR's value is a section offset --- classes
19904    lineptr, loclistptr, macptr or rangelistptr --- or zero, otherwise.
19905    You may use DW_UNSND (attr) to retrieve such offsets.
19906
19907    Section 7.5.4, "Attribute Encodings", explains that no attribute
19908    may have a value that belongs to more than one of these classes; it
19909    would be ambiguous if we did, because we use the same forms for all
19910    of them.  */
19911
19912 static int
19913 attr_form_is_section_offset (const struct attribute *attr)
19914 {
19915   return (attr->form == DW_FORM_data4
19916           || attr->form == DW_FORM_data8
19917           || attr->form == DW_FORM_sec_offset);
19918 }
19919
19920 /* Return non-zero if ATTR's value falls in the 'constant' class, or
19921    zero otherwise.  When this function returns true, you can apply
19922    dwarf2_get_attr_constant_value to it.
19923
19924    However, note that for some attributes you must check
19925    attr_form_is_section_offset before using this test.  DW_FORM_data4
19926    and DW_FORM_data8 are members of both the constant class, and of
19927    the classes that contain offsets into other debug sections
19928    (lineptr, loclistptr, macptr or rangelistptr).  The DWARF spec says
19929    that, if an attribute's can be either a constant or one of the
19930    section offset classes, DW_FORM_data4 and DW_FORM_data8 should be
19931    taken as section offsets, not constants.  */
19932
19933 static int
19934 attr_form_is_constant (const struct attribute *attr)
19935 {
19936   switch (attr->form)
19937     {
19938     case DW_FORM_sdata:
19939     case DW_FORM_udata:
19940     case DW_FORM_data1:
19941     case DW_FORM_data2:
19942     case DW_FORM_data4:
19943     case DW_FORM_data8:
19944       return 1;
19945     default:
19946       return 0;
19947     }
19948 }
19949
19950
19951 /* DW_ADDR is always stored already as sect_offset; despite for the forms
19952    besides DW_FORM_ref_addr it is stored as cu_offset in the DWARF file.  */
19953
19954 static int
19955 attr_form_is_ref (const struct attribute *attr)
19956 {
19957   switch (attr->form)
19958     {
19959     case DW_FORM_ref_addr:
19960     case DW_FORM_ref1:
19961     case DW_FORM_ref2:
19962     case DW_FORM_ref4:
19963     case DW_FORM_ref8:
19964     case DW_FORM_ref_udata:
19965     case DW_FORM_GNU_ref_alt:
19966       return 1;
19967     default:
19968       return 0;
19969     }
19970 }
19971
19972 /* Return the .debug_loc section to use for CU.
19973    For DWO files use .debug_loc.dwo.  */
19974
19975 static struct dwarf2_section_info *
19976 cu_debug_loc_section (struct dwarf2_cu *cu)
19977 {
19978   if (cu->dwo_unit)
19979     return &cu->dwo_unit->dwo_file->sections.loc;
19980   return &dwarf2_per_objfile->loc;
19981 }
19982
19983 /* A helper function that fills in a dwarf2_loclist_baton.  */
19984
19985 static void
19986 fill_in_loclist_baton (struct dwarf2_cu *cu,
19987                        struct dwarf2_loclist_baton *baton,
19988                        const struct attribute *attr)
19989 {
19990   struct dwarf2_section_info *section = cu_debug_loc_section (cu);
19991
19992   dwarf2_read_section (dwarf2_per_objfile->objfile, section);
19993
19994   baton->per_cu = cu->per_cu;
19995   gdb_assert (baton->per_cu);
19996   /* We don't know how long the location list is, but make sure we
19997      don't run off the edge of the section.  */
19998   baton->size = section->size - DW_UNSND (attr);
19999   baton->data = section->buffer + DW_UNSND (attr);
20000   baton->base_address = cu->base_address;
20001   baton->from_dwo = cu->dwo_unit != NULL;
20002 }
20003
20004 static void
20005 dwarf2_symbol_mark_computed (const struct attribute *attr, struct symbol *sym,
20006                              struct dwarf2_cu *cu, int is_block)
20007 {
20008   struct objfile *objfile = dwarf2_per_objfile->objfile;
20009   struct dwarf2_section_info *section = cu_debug_loc_section (cu);
20010
20011   if (attr_form_is_section_offset (attr)
20012       /* .debug_loc{,.dwo} may not exist at all, or the offset may be outside
20013          the section.  If so, fall through to the complaint in the
20014          other branch.  */
20015       && DW_UNSND (attr) < dwarf2_section_size (objfile, section))
20016     {
20017       struct dwarf2_loclist_baton *baton;
20018
20019       baton = obstack_alloc (&objfile->objfile_obstack,
20020                              sizeof (struct dwarf2_loclist_baton));
20021
20022       fill_in_loclist_baton (cu, baton, attr);
20023
20024       if (cu->base_known == 0)
20025         complaint (&symfile_complaints,
20026                    _("Location list used without "
20027                      "specifying the CU base address."));
20028
20029       SYMBOL_ACLASS_INDEX (sym) = (is_block
20030                                    ? dwarf2_loclist_block_index
20031                                    : dwarf2_loclist_index);
20032       SYMBOL_LOCATION_BATON (sym) = baton;
20033     }
20034   else
20035     {
20036       struct dwarf2_locexpr_baton *baton;
20037
20038       baton = obstack_alloc (&objfile->objfile_obstack,
20039                              sizeof (struct dwarf2_locexpr_baton));
20040       baton->per_cu = cu->per_cu;
20041       gdb_assert (baton->per_cu);
20042
20043       if (attr_form_is_block (attr))
20044         {
20045           /* Note that we're just copying the block's data pointer
20046              here, not the actual data.  We're still pointing into the
20047              info_buffer for SYM's objfile; right now we never release
20048              that buffer, but when we do clean up properly this may
20049              need to change.  */
20050           baton->size = DW_BLOCK (attr)->size;
20051           baton->data = DW_BLOCK (attr)->data;
20052         }
20053       else
20054         {
20055           dwarf2_invalid_attrib_class_complaint ("location description",
20056                                                  SYMBOL_NATURAL_NAME (sym));
20057           baton->size = 0;
20058         }
20059
20060       SYMBOL_ACLASS_INDEX (sym) = (is_block
20061                                    ? dwarf2_locexpr_block_index
20062                                    : dwarf2_locexpr_index);
20063       SYMBOL_LOCATION_BATON (sym) = baton;
20064     }
20065 }
20066
20067 /* Return the OBJFILE associated with the compilation unit CU.  If CU
20068    came from a separate debuginfo file, then the master objfile is
20069    returned.  */
20070
20071 struct objfile *
20072 dwarf2_per_cu_objfile (struct dwarf2_per_cu_data *per_cu)
20073 {
20074   struct objfile *objfile = per_cu->objfile;
20075
20076   /* Return the master objfile, so that we can report and look up the
20077      correct file containing this variable.  */
20078   if (objfile->separate_debug_objfile_backlink)
20079     objfile = objfile->separate_debug_objfile_backlink;
20080
20081   return objfile;
20082 }
20083
20084 /* Return comp_unit_head for PER_CU, either already available in PER_CU->CU
20085    (CU_HEADERP is unused in such case) or prepare a temporary copy at
20086    CU_HEADERP first.  */
20087
20088 static const struct comp_unit_head *
20089 per_cu_header_read_in (struct comp_unit_head *cu_headerp,
20090                        struct dwarf2_per_cu_data *per_cu)
20091 {
20092   const gdb_byte *info_ptr;
20093
20094   if (per_cu->cu)
20095     return &per_cu->cu->header;
20096
20097   info_ptr = per_cu->section->buffer + per_cu->offset.sect_off;
20098
20099   memset (cu_headerp, 0, sizeof (*cu_headerp));
20100   read_comp_unit_head (cu_headerp, info_ptr, per_cu->objfile->obfd);
20101
20102   return cu_headerp;
20103 }
20104
20105 /* Return the address size given in the compilation unit header for CU.  */
20106
20107 int
20108 dwarf2_per_cu_addr_size (struct dwarf2_per_cu_data *per_cu)
20109 {
20110   struct comp_unit_head cu_header_local;
20111   const struct comp_unit_head *cu_headerp;
20112
20113   cu_headerp = per_cu_header_read_in (&cu_header_local, per_cu);
20114
20115   return cu_headerp->addr_size;
20116 }
20117
20118 /* Return the offset size given in the compilation unit header for CU.  */
20119
20120 int
20121 dwarf2_per_cu_offset_size (struct dwarf2_per_cu_data *per_cu)
20122 {
20123   struct comp_unit_head cu_header_local;
20124   const struct comp_unit_head *cu_headerp;
20125
20126   cu_headerp = per_cu_header_read_in (&cu_header_local, per_cu);
20127
20128   return cu_headerp->offset_size;
20129 }
20130
20131 /* See its dwarf2loc.h declaration.  */
20132
20133 int
20134 dwarf2_per_cu_ref_addr_size (struct dwarf2_per_cu_data *per_cu)
20135 {
20136   struct comp_unit_head cu_header_local;
20137   const struct comp_unit_head *cu_headerp;
20138
20139   cu_headerp = per_cu_header_read_in (&cu_header_local, per_cu);
20140
20141   if (cu_headerp->version == 2)
20142     return cu_headerp->addr_size;
20143   else
20144     return cu_headerp->offset_size;
20145 }
20146
20147 /* Return the text offset of the CU.  The returned offset comes from
20148    this CU's objfile.  If this objfile came from a separate debuginfo
20149    file, then the offset may be different from the corresponding
20150    offset in the parent objfile.  */
20151
20152 CORE_ADDR
20153 dwarf2_per_cu_text_offset (struct dwarf2_per_cu_data *per_cu)
20154 {
20155   struct objfile *objfile = per_cu->objfile;
20156
20157   return ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
20158 }
20159
20160 /* Locate the .debug_info compilation unit from CU's objfile which contains
20161    the DIE at OFFSET.  Raises an error on failure.  */
20162
20163 static struct dwarf2_per_cu_data *
20164 dwarf2_find_containing_comp_unit (sect_offset offset,
20165                                   unsigned int offset_in_dwz,
20166                                   struct objfile *objfile)
20167 {
20168   struct dwarf2_per_cu_data *this_cu;
20169   int low, high;
20170   const sect_offset *cu_off;
20171
20172   low = 0;
20173   high = dwarf2_per_objfile->n_comp_units - 1;
20174   while (high > low)
20175     {
20176       struct dwarf2_per_cu_data *mid_cu;
20177       int mid = low + (high - low) / 2;
20178
20179       mid_cu = dwarf2_per_objfile->all_comp_units[mid];
20180       cu_off = &mid_cu->offset;
20181       if (mid_cu->is_dwz > offset_in_dwz
20182           || (mid_cu->is_dwz == offset_in_dwz
20183               && cu_off->sect_off >= offset.sect_off))
20184         high = mid;
20185       else
20186         low = mid + 1;
20187     }
20188   gdb_assert (low == high);
20189   this_cu = dwarf2_per_objfile->all_comp_units[low];
20190   cu_off = &this_cu->offset;
20191   if (this_cu->is_dwz != offset_in_dwz || cu_off->sect_off > offset.sect_off)
20192     {
20193       if (low == 0 || this_cu->is_dwz != offset_in_dwz)
20194         error (_("Dwarf Error: could not find partial DIE containing "
20195                "offset 0x%lx [in module %s]"),
20196                (long) offset.sect_off, bfd_get_filename (objfile->obfd));
20197
20198       gdb_assert (dwarf2_per_objfile->all_comp_units[low-1]->offset.sect_off
20199                   <= offset.sect_off);
20200       return dwarf2_per_objfile->all_comp_units[low-1];
20201     }
20202   else
20203     {
20204       this_cu = dwarf2_per_objfile->all_comp_units[low];
20205       if (low == dwarf2_per_objfile->n_comp_units - 1
20206           && offset.sect_off >= this_cu->offset.sect_off + this_cu->length)
20207         error (_("invalid dwarf2 offset %u"), offset.sect_off);
20208       gdb_assert (offset.sect_off < this_cu->offset.sect_off + this_cu->length);
20209       return this_cu;
20210     }
20211 }
20212
20213 /* Initialize dwarf2_cu CU, owned by PER_CU.  */
20214
20215 static void
20216 init_one_comp_unit (struct dwarf2_cu *cu, struct dwarf2_per_cu_data *per_cu)
20217 {
20218   memset (cu, 0, sizeof (*cu));
20219   per_cu->cu = cu;
20220   cu->per_cu = per_cu;
20221   cu->objfile = per_cu->objfile;
20222   obstack_init (&cu->comp_unit_obstack);
20223 }
20224
20225 /* Initialize basic fields of dwarf_cu CU according to DIE COMP_UNIT_DIE.  */
20226
20227 static void
20228 prepare_one_comp_unit (struct dwarf2_cu *cu, struct die_info *comp_unit_die,
20229                        enum language pretend_language)
20230 {
20231   struct attribute *attr;
20232
20233   /* Set the language we're debugging.  */
20234   attr = dwarf2_attr (comp_unit_die, DW_AT_language, cu);
20235   if (attr)
20236     set_cu_language (DW_UNSND (attr), cu);
20237   else
20238     {
20239       cu->language = pretend_language;
20240       cu->language_defn = language_def (cu->language);
20241     }
20242
20243   attr = dwarf2_attr (comp_unit_die, DW_AT_producer, cu);
20244   if (attr)
20245     cu->producer = DW_STRING (attr);
20246 }
20247
20248 /* Release one cached compilation unit, CU.  We unlink it from the tree
20249    of compilation units, but we don't remove it from the read_in_chain;
20250    the caller is responsible for that.
20251    NOTE: DATA is a void * because this function is also used as a
20252    cleanup routine.  */
20253
20254 static void
20255 free_heap_comp_unit (void *data)
20256 {
20257   struct dwarf2_cu *cu = data;
20258
20259   gdb_assert (cu->per_cu != NULL);
20260   cu->per_cu->cu = NULL;
20261   cu->per_cu = NULL;
20262
20263   obstack_free (&cu->comp_unit_obstack, NULL);
20264
20265   xfree (cu);
20266 }
20267
20268 /* This cleanup function is passed the address of a dwarf2_cu on the stack
20269    when we're finished with it.  We can't free the pointer itself, but be
20270    sure to unlink it from the cache.  Also release any associated storage.  */
20271
20272 static void
20273 free_stack_comp_unit (void *data)
20274 {
20275   struct dwarf2_cu *cu = data;
20276
20277   gdb_assert (cu->per_cu != NULL);
20278   cu->per_cu->cu = NULL;
20279   cu->per_cu = NULL;
20280
20281   obstack_free (&cu->comp_unit_obstack, NULL);
20282   cu->partial_dies = NULL;
20283 }
20284
20285 /* Free all cached compilation units.  */
20286
20287 static void
20288 free_cached_comp_units (void *data)
20289 {
20290   struct dwarf2_per_cu_data *per_cu, **last_chain;
20291
20292   per_cu = dwarf2_per_objfile->read_in_chain;
20293   last_chain = &dwarf2_per_objfile->read_in_chain;
20294   while (per_cu != NULL)
20295     {
20296       struct dwarf2_per_cu_data *next_cu;
20297
20298       next_cu = per_cu->cu->read_in_chain;
20299
20300       free_heap_comp_unit (per_cu->cu);
20301       *last_chain = next_cu;
20302
20303       per_cu = next_cu;
20304     }
20305 }
20306
20307 /* Increase the age counter on each cached compilation unit, and free
20308    any that are too old.  */
20309
20310 static void
20311 age_cached_comp_units (void)
20312 {
20313   struct dwarf2_per_cu_data *per_cu, **last_chain;
20314
20315   dwarf2_clear_marks (dwarf2_per_objfile->read_in_chain);
20316   per_cu = dwarf2_per_objfile->read_in_chain;
20317   while (per_cu != NULL)
20318     {
20319       per_cu->cu->last_used ++;
20320       if (per_cu->cu->last_used <= dwarf2_max_cache_age)
20321         dwarf2_mark (per_cu->cu);
20322       per_cu = per_cu->cu->read_in_chain;
20323     }
20324
20325   per_cu = dwarf2_per_objfile->read_in_chain;
20326   last_chain = &dwarf2_per_objfile->read_in_chain;
20327   while (per_cu != NULL)
20328     {
20329       struct dwarf2_per_cu_data *next_cu;
20330
20331       next_cu = per_cu->cu->read_in_chain;
20332
20333       if (!per_cu->cu->mark)
20334         {
20335           free_heap_comp_unit (per_cu->cu);
20336           *last_chain = next_cu;
20337         }
20338       else
20339         last_chain = &per_cu->cu->read_in_chain;
20340
20341       per_cu = next_cu;
20342     }
20343 }
20344
20345 /* Remove a single compilation unit from the cache.  */
20346
20347 static void
20348 free_one_cached_comp_unit (struct dwarf2_per_cu_data *target_per_cu)
20349 {
20350   struct dwarf2_per_cu_data *per_cu, **last_chain;
20351
20352   per_cu = dwarf2_per_objfile->read_in_chain;
20353   last_chain = &dwarf2_per_objfile->read_in_chain;
20354   while (per_cu != NULL)
20355     {
20356       struct dwarf2_per_cu_data *next_cu;
20357
20358       next_cu = per_cu->cu->read_in_chain;
20359
20360       if (per_cu == target_per_cu)
20361         {
20362           free_heap_comp_unit (per_cu->cu);
20363           per_cu->cu = NULL;
20364           *last_chain = next_cu;
20365           break;
20366         }
20367       else
20368         last_chain = &per_cu->cu->read_in_chain;
20369
20370       per_cu = next_cu;
20371     }
20372 }
20373
20374 /* Release all extra memory associated with OBJFILE.  */
20375
20376 void
20377 dwarf2_free_objfile (struct objfile *objfile)
20378 {
20379   dwarf2_per_objfile = objfile_data (objfile, dwarf2_objfile_data_key);
20380
20381   if (dwarf2_per_objfile == NULL)
20382     return;
20383
20384   /* Cached DIE trees use xmalloc and the comp_unit_obstack.  */
20385   free_cached_comp_units (NULL);
20386
20387   if (dwarf2_per_objfile->quick_file_names_table)
20388     htab_delete (dwarf2_per_objfile->quick_file_names_table);
20389
20390   /* Everything else should be on the objfile obstack.  */
20391 }
20392
20393 /* A set of CU "per_cu" pointer, DIE offset, and GDB type pointer.
20394    We store these in a hash table separate from the DIEs, and preserve them
20395    when the DIEs are flushed out of cache.
20396
20397    The CU "per_cu" pointer is needed because offset alone is not enough to
20398    uniquely identify the type.  A file may have multiple .debug_types sections,
20399    or the type may come from a DWO file.  Furthermore, while it's more logical
20400    to use per_cu->section+offset, with Fission the section with the data is in
20401    the DWO file but we don't know that section at the point we need it.
20402    We have to use something in dwarf2_per_cu_data (or the pointer to it)
20403    because we can enter the lookup routine, get_die_type_at_offset, from
20404    outside this file, and thus won't necessarily have PER_CU->cu.
20405    Fortunately, PER_CU is stable for the life of the objfile.  */
20406
20407 struct dwarf2_per_cu_offset_and_type
20408 {
20409   const struct dwarf2_per_cu_data *per_cu;
20410   sect_offset offset;
20411   struct type *type;
20412 };
20413
20414 /* Hash function for a dwarf2_per_cu_offset_and_type.  */
20415
20416 static hashval_t
20417 per_cu_offset_and_type_hash (const void *item)
20418 {
20419   const struct dwarf2_per_cu_offset_and_type *ofs = item;
20420
20421   return (uintptr_t) ofs->per_cu + ofs->offset.sect_off;
20422 }
20423
20424 /* Equality function for a dwarf2_per_cu_offset_and_type.  */
20425
20426 static int
20427 per_cu_offset_and_type_eq (const void *item_lhs, const void *item_rhs)
20428 {
20429   const struct dwarf2_per_cu_offset_and_type *ofs_lhs = item_lhs;
20430   const struct dwarf2_per_cu_offset_and_type *ofs_rhs = item_rhs;
20431
20432   return (ofs_lhs->per_cu == ofs_rhs->per_cu
20433           && ofs_lhs->offset.sect_off == ofs_rhs->offset.sect_off);
20434 }
20435
20436 /* Set the type associated with DIE to TYPE.  Save it in CU's hash
20437    table if necessary.  For convenience, return TYPE.
20438
20439    The DIEs reading must have careful ordering to:
20440     * Not cause infite loops trying to read in DIEs as a prerequisite for
20441       reading current DIE.
20442     * Not trying to dereference contents of still incompletely read in types
20443       while reading in other DIEs.
20444     * Enable referencing still incompletely read in types just by a pointer to
20445       the type without accessing its fields.
20446
20447    Therefore caller should follow these rules:
20448      * Try to fetch any prerequisite types we may need to build this DIE type
20449        before building the type and calling set_die_type.
20450      * After building type call set_die_type for current DIE as soon as
20451        possible before fetching more types to complete the current type.
20452      * Make the type as complete as possible before fetching more types.  */
20453
20454 static struct type *
20455 set_die_type (struct die_info *die, struct type *type, struct dwarf2_cu *cu)
20456 {
20457   struct dwarf2_per_cu_offset_and_type **slot, ofs;
20458   struct objfile *objfile = cu->objfile;
20459
20460   /* For Ada types, make sure that the gnat-specific data is always
20461      initialized (if not already set).  There are a few types where
20462      we should not be doing so, because the type-specific area is
20463      already used to hold some other piece of info (eg: TYPE_CODE_FLT
20464      where the type-specific area is used to store the floatformat).
20465      But this is not a problem, because the gnat-specific information
20466      is actually not needed for these types.  */
20467   if (need_gnat_info (cu)
20468       && TYPE_CODE (type) != TYPE_CODE_FUNC
20469       && TYPE_CODE (type) != TYPE_CODE_FLT
20470       && !HAVE_GNAT_AUX_INFO (type))
20471     INIT_GNAT_SPECIFIC (type);
20472
20473   if (dwarf2_per_objfile->die_type_hash == NULL)
20474     {
20475       dwarf2_per_objfile->die_type_hash =
20476         htab_create_alloc_ex (127,
20477                               per_cu_offset_and_type_hash,
20478                               per_cu_offset_and_type_eq,
20479                               NULL,
20480                               &objfile->objfile_obstack,
20481                               hashtab_obstack_allocate,
20482                               dummy_obstack_deallocate);
20483     }
20484
20485   ofs.per_cu = cu->per_cu;
20486   ofs.offset = die->offset;
20487   ofs.type = type;
20488   slot = (struct dwarf2_per_cu_offset_and_type **)
20489     htab_find_slot (dwarf2_per_objfile->die_type_hash, &ofs, INSERT);
20490   if (*slot)
20491     complaint (&symfile_complaints,
20492                _("A problem internal to GDB: DIE 0x%x has type already set"),
20493                die->offset.sect_off);
20494   *slot = obstack_alloc (&objfile->objfile_obstack, sizeof (**slot));
20495   **slot = ofs;
20496   return type;
20497 }
20498
20499 /* Look up the type for the die at OFFSET in PER_CU in die_type_hash,
20500    or return NULL if the die does not have a saved type.  */
20501
20502 static struct type *
20503 get_die_type_at_offset (sect_offset offset,
20504                         struct dwarf2_per_cu_data *per_cu)
20505 {
20506   struct dwarf2_per_cu_offset_and_type *slot, ofs;
20507
20508   if (dwarf2_per_objfile->die_type_hash == NULL)
20509     return NULL;
20510
20511   ofs.per_cu = per_cu;
20512   ofs.offset = offset;
20513   slot = htab_find (dwarf2_per_objfile->die_type_hash, &ofs);
20514   if (slot)
20515     return slot->type;
20516   else
20517     return NULL;
20518 }
20519
20520 /* Look up the type for DIE in CU in die_type_hash,
20521    or return NULL if DIE does not have a saved type.  */
20522
20523 static struct type *
20524 get_die_type (struct die_info *die, struct dwarf2_cu *cu)
20525 {
20526   return get_die_type_at_offset (die->offset, cu->per_cu);
20527 }
20528
20529 /* Add a dependence relationship from CU to REF_PER_CU.  */
20530
20531 static void
20532 dwarf2_add_dependence (struct dwarf2_cu *cu,
20533                        struct dwarf2_per_cu_data *ref_per_cu)
20534 {
20535   void **slot;
20536
20537   if (cu->dependencies == NULL)
20538     cu->dependencies
20539       = htab_create_alloc_ex (5, htab_hash_pointer, htab_eq_pointer,
20540                               NULL, &cu->comp_unit_obstack,
20541                               hashtab_obstack_allocate,
20542                               dummy_obstack_deallocate);
20543
20544   slot = htab_find_slot (cu->dependencies, ref_per_cu, INSERT);
20545   if (*slot == NULL)
20546     *slot = ref_per_cu;
20547 }
20548
20549 /* Subroutine of dwarf2_mark to pass to htab_traverse.
20550    Set the mark field in every compilation unit in the
20551    cache that we must keep because we are keeping CU.  */
20552
20553 static int
20554 dwarf2_mark_helper (void **slot, void *data)
20555 {
20556   struct dwarf2_per_cu_data *per_cu;
20557
20558   per_cu = (struct dwarf2_per_cu_data *) *slot;
20559
20560   /* cu->dependencies references may not yet have been ever read if QUIT aborts
20561      reading of the chain.  As such dependencies remain valid it is not much
20562      useful to track and undo them during QUIT cleanups.  */
20563   if (per_cu->cu == NULL)
20564     return 1;
20565
20566   if (per_cu->cu->mark)
20567     return 1;
20568   per_cu->cu->mark = 1;
20569
20570   if (per_cu->cu->dependencies != NULL)
20571     htab_traverse (per_cu->cu->dependencies, dwarf2_mark_helper, NULL);
20572
20573   return 1;
20574 }
20575
20576 /* Set the mark field in CU and in every other compilation unit in the
20577    cache that we must keep because we are keeping CU.  */
20578
20579 static void
20580 dwarf2_mark (struct dwarf2_cu *cu)
20581 {
20582   if (cu->mark)
20583     return;
20584   cu->mark = 1;
20585   if (cu->dependencies != NULL)
20586     htab_traverse (cu->dependencies, dwarf2_mark_helper, NULL);
20587 }
20588
20589 static void
20590 dwarf2_clear_marks (struct dwarf2_per_cu_data *per_cu)
20591 {
20592   while (per_cu)
20593     {
20594       per_cu->cu->mark = 0;
20595       per_cu = per_cu->cu->read_in_chain;
20596     }
20597 }
20598
20599 /* Trivial hash function for partial_die_info: the hash value of a DIE
20600    is its offset in .debug_info for this objfile.  */
20601
20602 static hashval_t
20603 partial_die_hash (const void *item)
20604 {
20605   const struct partial_die_info *part_die = item;
20606
20607   return part_die->offset.sect_off;
20608 }
20609
20610 /* Trivial comparison function for partial_die_info structures: two DIEs
20611    are equal if they have the same offset.  */
20612
20613 static int
20614 partial_die_eq (const void *item_lhs, const void *item_rhs)
20615 {
20616   const struct partial_die_info *part_die_lhs = item_lhs;
20617   const struct partial_die_info *part_die_rhs = item_rhs;
20618
20619   return part_die_lhs->offset.sect_off == part_die_rhs->offset.sect_off;
20620 }
20621
20622 static struct cmd_list_element *set_dwarf2_cmdlist;
20623 static struct cmd_list_element *show_dwarf2_cmdlist;
20624
20625 static void
20626 set_dwarf2_cmd (char *args, int from_tty)
20627 {
20628   help_list (set_dwarf2_cmdlist, "maintenance set dwarf2 ", -1, gdb_stdout);
20629 }
20630
20631 static void
20632 show_dwarf2_cmd (char *args, int from_tty)
20633 {
20634   cmd_show_list (show_dwarf2_cmdlist, from_tty, "");
20635 }
20636
20637 /* Free data associated with OBJFILE, if necessary.  */
20638
20639 static void
20640 dwarf2_per_objfile_free (struct objfile *objfile, void *d)
20641 {
20642   struct dwarf2_per_objfile *data = d;
20643   int ix;
20644
20645   /* Make sure we don't accidentally use dwarf2_per_objfile while
20646      cleaning up.  */
20647   dwarf2_per_objfile = NULL;
20648
20649   for (ix = 0; ix < data->n_comp_units; ++ix)
20650    VEC_free (dwarf2_per_cu_ptr, data->all_comp_units[ix]->imported_symtabs);
20651
20652   for (ix = 0; ix < data->n_type_units; ++ix)
20653     VEC_free (dwarf2_per_cu_ptr,
20654               data->all_type_units[ix]->per_cu.imported_symtabs);
20655   xfree (data->all_type_units);
20656
20657   VEC_free (dwarf2_section_info_def, data->types);
20658
20659   if (data->dwo_files)
20660     free_dwo_files (data->dwo_files, objfile);
20661   if (data->dwp_file)
20662     gdb_bfd_unref (data->dwp_file->dbfd);
20663
20664   if (data->dwz_file && data->dwz_file->dwz_bfd)
20665     gdb_bfd_unref (data->dwz_file->dwz_bfd);
20666 }
20667
20668 \f
20669 /* The "save gdb-index" command.  */
20670
20671 /* The contents of the hash table we create when building the string
20672    table.  */
20673 struct strtab_entry
20674 {
20675   offset_type offset;
20676   const char *str;
20677 };
20678
20679 /* Hash function for a strtab_entry.
20680
20681    Function is used only during write_hash_table so no index format backward
20682    compatibility is needed.  */
20683
20684 static hashval_t
20685 hash_strtab_entry (const void *e)
20686 {
20687   const struct strtab_entry *entry = e;
20688   return mapped_index_string_hash (INT_MAX, entry->str);
20689 }
20690
20691 /* Equality function for a strtab_entry.  */
20692
20693 static int
20694 eq_strtab_entry (const void *a, const void *b)
20695 {
20696   const struct strtab_entry *ea = a;
20697   const struct strtab_entry *eb = b;
20698   return !strcmp (ea->str, eb->str);
20699 }
20700
20701 /* Create a strtab_entry hash table.  */
20702
20703 static htab_t
20704 create_strtab (void)
20705 {
20706   return htab_create_alloc (100, hash_strtab_entry, eq_strtab_entry,
20707                             xfree, xcalloc, xfree);
20708 }
20709
20710 /* Add a string to the constant pool.  Return the string's offset in
20711    host order.  */
20712
20713 static offset_type
20714 add_string (htab_t table, struct obstack *cpool, const char *str)
20715 {
20716   void **slot;
20717   struct strtab_entry entry;
20718   struct strtab_entry *result;
20719
20720   entry.str = str;
20721   slot = htab_find_slot (table, &entry, INSERT);
20722   if (*slot)
20723     result = *slot;
20724   else
20725     {
20726       result = XNEW (struct strtab_entry);
20727       result->offset = obstack_object_size (cpool);
20728       result->str = str;
20729       obstack_grow_str0 (cpool, str);
20730       *slot = result;
20731     }
20732   return result->offset;
20733 }
20734
20735 /* An entry in the symbol table.  */
20736 struct symtab_index_entry
20737 {
20738   /* The name of the symbol.  */
20739   const char *name;
20740   /* The offset of the name in the constant pool.  */
20741   offset_type index_offset;
20742   /* A sorted vector of the indices of all the CUs that hold an object
20743      of this name.  */
20744   VEC (offset_type) *cu_indices;
20745 };
20746
20747 /* The symbol table.  This is a power-of-2-sized hash table.  */
20748 struct mapped_symtab
20749 {
20750   offset_type n_elements;
20751   offset_type size;
20752   struct symtab_index_entry **data;
20753 };
20754
20755 /* Hash function for a symtab_index_entry.  */
20756
20757 static hashval_t
20758 hash_symtab_entry (const void *e)
20759 {
20760   const struct symtab_index_entry *entry = e;
20761   return iterative_hash (VEC_address (offset_type, entry->cu_indices),
20762                          sizeof (offset_type) * VEC_length (offset_type,
20763                                                             entry->cu_indices),
20764                          0);
20765 }
20766
20767 /* Equality function for a symtab_index_entry.  */
20768
20769 static int
20770 eq_symtab_entry (const void *a, const void *b)
20771 {
20772   const struct symtab_index_entry *ea = a;
20773   const struct symtab_index_entry *eb = b;
20774   int len = VEC_length (offset_type, ea->cu_indices);
20775   if (len != VEC_length (offset_type, eb->cu_indices))
20776     return 0;
20777   return !memcmp (VEC_address (offset_type, ea->cu_indices),
20778                   VEC_address (offset_type, eb->cu_indices),
20779                   sizeof (offset_type) * len);
20780 }
20781
20782 /* Destroy a symtab_index_entry.  */
20783
20784 static void
20785 delete_symtab_entry (void *p)
20786 {
20787   struct symtab_index_entry *entry = p;
20788   VEC_free (offset_type, entry->cu_indices);
20789   xfree (entry);
20790 }
20791
20792 /* Create a hash table holding symtab_index_entry objects.  */
20793
20794 static htab_t
20795 create_symbol_hash_table (void)
20796 {
20797   return htab_create_alloc (100, hash_symtab_entry, eq_symtab_entry,
20798                             delete_symtab_entry, xcalloc, xfree);
20799 }
20800
20801 /* Create a new mapped symtab object.  */
20802
20803 static struct mapped_symtab *
20804 create_mapped_symtab (void)
20805 {
20806   struct mapped_symtab *symtab = XNEW (struct mapped_symtab);
20807   symtab->n_elements = 0;
20808   symtab->size = 1024;
20809   symtab->data = XCNEWVEC (struct symtab_index_entry *, symtab->size);
20810   return symtab;
20811 }
20812
20813 /* Destroy a mapped_symtab.  */
20814
20815 static void
20816 cleanup_mapped_symtab (void *p)
20817 {
20818   struct mapped_symtab *symtab = p;
20819   /* The contents of the array are freed when the other hash table is
20820      destroyed.  */
20821   xfree (symtab->data);
20822   xfree (symtab);
20823 }
20824
20825 /* Find a slot in SYMTAB for the symbol NAME.  Returns a pointer to
20826    the slot.
20827    
20828    Function is used only during write_hash_table so no index format backward
20829    compatibility is needed.  */
20830
20831 static struct symtab_index_entry **
20832 find_slot (struct mapped_symtab *symtab, const char *name)
20833 {
20834   offset_type index, step, hash = mapped_index_string_hash (INT_MAX, name);
20835
20836   index = hash & (symtab->size - 1);
20837   step = ((hash * 17) & (symtab->size - 1)) | 1;
20838
20839   for (;;)
20840     {
20841       if (!symtab->data[index] || !strcmp (name, symtab->data[index]->name))
20842         return &symtab->data[index];
20843       index = (index + step) & (symtab->size - 1);
20844     }
20845 }
20846
20847 /* Expand SYMTAB's hash table.  */
20848
20849 static void
20850 hash_expand (struct mapped_symtab *symtab)
20851 {
20852   offset_type old_size = symtab->size;
20853   offset_type i;
20854   struct symtab_index_entry **old_entries = symtab->data;
20855
20856   symtab->size *= 2;
20857   symtab->data = XCNEWVEC (struct symtab_index_entry *, symtab->size);
20858
20859   for (i = 0; i < old_size; ++i)
20860     {
20861       if (old_entries[i])
20862         {
20863           struct symtab_index_entry **slot = find_slot (symtab,
20864                                                         old_entries[i]->name);
20865           *slot = old_entries[i];
20866         }
20867     }
20868
20869   xfree (old_entries);
20870 }
20871
20872 /* Add an entry to SYMTAB.  NAME is the name of the symbol.
20873    CU_INDEX is the index of the CU in which the symbol appears.
20874    IS_STATIC is one if the symbol is static, otherwise zero (global).  */
20875
20876 static void
20877 add_index_entry (struct mapped_symtab *symtab, const char *name,
20878                  int is_static, gdb_index_symbol_kind kind,
20879                  offset_type cu_index)
20880 {
20881   struct symtab_index_entry **slot;
20882   offset_type cu_index_and_attrs;
20883
20884   ++symtab->n_elements;
20885   if (4 * symtab->n_elements / 3 >= symtab->size)
20886     hash_expand (symtab);
20887
20888   slot = find_slot (symtab, name);
20889   if (!*slot)
20890     {
20891       *slot = XNEW (struct symtab_index_entry);
20892       (*slot)->name = name;
20893       /* index_offset is set later.  */
20894       (*slot)->cu_indices = NULL;
20895     }
20896
20897   cu_index_and_attrs = 0;
20898   DW2_GDB_INDEX_CU_SET_VALUE (cu_index_and_attrs, cu_index);
20899   DW2_GDB_INDEX_SYMBOL_STATIC_SET_VALUE (cu_index_and_attrs, is_static);
20900   DW2_GDB_INDEX_SYMBOL_KIND_SET_VALUE (cu_index_and_attrs, kind);
20901
20902   /* We don't want to record an index value twice as we want to avoid the
20903      duplication.
20904      We process all global symbols and then all static symbols
20905      (which would allow us to avoid the duplication by only having to check
20906      the last entry pushed), but a symbol could have multiple kinds in one CU.
20907      To keep things simple we don't worry about the duplication here and
20908      sort and uniqufy the list after we've processed all symbols.  */
20909   VEC_safe_push (offset_type, (*slot)->cu_indices, cu_index_and_attrs);
20910 }
20911
20912 /* qsort helper routine for uniquify_cu_indices.  */
20913
20914 static int
20915 offset_type_compare (const void *ap, const void *bp)
20916 {
20917   offset_type a = *(offset_type *) ap;
20918   offset_type b = *(offset_type *) bp;
20919
20920   return (a > b) - (b > a);
20921 }
20922
20923 /* Sort and remove duplicates of all symbols' cu_indices lists.  */
20924
20925 static void
20926 uniquify_cu_indices (struct mapped_symtab *symtab)
20927 {
20928   int i;
20929
20930   for (i = 0; i < symtab->size; ++i)
20931     {
20932       struct symtab_index_entry *entry = symtab->data[i];
20933
20934       if (entry
20935           && entry->cu_indices != NULL)
20936         {
20937           unsigned int next_to_insert, next_to_check;
20938           offset_type last_value;
20939
20940           qsort (VEC_address (offset_type, entry->cu_indices),
20941                  VEC_length (offset_type, entry->cu_indices),
20942                  sizeof (offset_type), offset_type_compare);
20943
20944           last_value = VEC_index (offset_type, entry->cu_indices, 0);
20945           next_to_insert = 1;
20946           for (next_to_check = 1;
20947                next_to_check < VEC_length (offset_type, entry->cu_indices);
20948                ++next_to_check)
20949             {
20950               if (VEC_index (offset_type, entry->cu_indices, next_to_check)
20951                   != last_value)
20952                 {
20953                   last_value = VEC_index (offset_type, entry->cu_indices,
20954                                           next_to_check);
20955                   VEC_replace (offset_type, entry->cu_indices, next_to_insert,
20956                                last_value);
20957                   ++next_to_insert;
20958                 }
20959             }
20960           VEC_truncate (offset_type, entry->cu_indices, next_to_insert);
20961         }
20962     }
20963 }
20964
20965 /* Add a vector of indices to the constant pool.  */
20966
20967 static offset_type
20968 add_indices_to_cpool (htab_t symbol_hash_table, struct obstack *cpool,
20969                       struct symtab_index_entry *entry)
20970 {
20971   void **slot;
20972
20973   slot = htab_find_slot (symbol_hash_table, entry, INSERT);
20974   if (!*slot)
20975     {
20976       offset_type len = VEC_length (offset_type, entry->cu_indices);
20977       offset_type val = MAYBE_SWAP (len);
20978       offset_type iter;
20979       int i;
20980
20981       *slot = entry;
20982       entry->index_offset = obstack_object_size (cpool);
20983
20984       obstack_grow (cpool, &val, sizeof (val));
20985       for (i = 0;
20986            VEC_iterate (offset_type, entry->cu_indices, i, iter);
20987            ++i)
20988         {
20989           val = MAYBE_SWAP (iter);
20990           obstack_grow (cpool, &val, sizeof (val));
20991         }
20992     }
20993   else
20994     {
20995       struct symtab_index_entry *old_entry = *slot;
20996       entry->index_offset = old_entry->index_offset;
20997       entry = old_entry;
20998     }
20999   return entry->index_offset;
21000 }
21001
21002 /* Write the mapped hash table SYMTAB to the obstack OUTPUT, with
21003    constant pool entries going into the obstack CPOOL.  */
21004
21005 static void
21006 write_hash_table (struct mapped_symtab *symtab,
21007                   struct obstack *output, struct obstack *cpool)
21008 {
21009   offset_type i;
21010   htab_t symbol_hash_table;
21011   htab_t str_table;
21012
21013   symbol_hash_table = create_symbol_hash_table ();
21014   str_table = create_strtab ();
21015
21016   /* We add all the index vectors to the constant pool first, to
21017      ensure alignment is ok.  */
21018   for (i = 0; i < symtab->size; ++i)
21019     {
21020       if (symtab->data[i])
21021         add_indices_to_cpool (symbol_hash_table, cpool, symtab->data[i]);
21022     }
21023
21024   /* Now write out the hash table.  */
21025   for (i = 0; i < symtab->size; ++i)
21026     {
21027       offset_type str_off, vec_off;
21028
21029       if (symtab->data[i])
21030         {
21031           str_off = add_string (str_table, cpool, symtab->data[i]->name);
21032           vec_off = symtab->data[i]->index_offset;
21033         }
21034       else
21035         {
21036           /* While 0 is a valid constant pool index, it is not valid
21037              to have 0 for both offsets.  */
21038           str_off = 0;
21039           vec_off = 0;
21040         }
21041
21042       str_off = MAYBE_SWAP (str_off);
21043       vec_off = MAYBE_SWAP (vec_off);
21044
21045       obstack_grow (output, &str_off, sizeof (str_off));
21046       obstack_grow (output, &vec_off, sizeof (vec_off));
21047     }
21048
21049   htab_delete (str_table);
21050   htab_delete (symbol_hash_table);
21051 }
21052
21053 /* Struct to map psymtab to CU index in the index file.  */
21054 struct psymtab_cu_index_map
21055 {
21056   struct partial_symtab *psymtab;
21057   unsigned int cu_index;
21058 };
21059
21060 static hashval_t
21061 hash_psymtab_cu_index (const void *item)
21062 {
21063   const struct psymtab_cu_index_map *map = item;
21064
21065   return htab_hash_pointer (map->psymtab);
21066 }
21067
21068 static int
21069 eq_psymtab_cu_index (const void *item_lhs, const void *item_rhs)
21070 {
21071   const struct psymtab_cu_index_map *lhs = item_lhs;
21072   const struct psymtab_cu_index_map *rhs = item_rhs;
21073
21074   return lhs->psymtab == rhs->psymtab;
21075 }
21076
21077 /* Helper struct for building the address table.  */
21078 struct addrmap_index_data
21079 {
21080   struct objfile *objfile;
21081   struct obstack *addr_obstack;
21082   htab_t cu_index_htab;
21083
21084   /* Non-zero if the previous_* fields are valid.
21085      We can't write an entry until we see the next entry (since it is only then
21086      that we know the end of the entry).  */
21087   int previous_valid;
21088   /* Index of the CU in the table of all CUs in the index file.  */
21089   unsigned int previous_cu_index;
21090   /* Start address of the CU.  */
21091   CORE_ADDR previous_cu_start;
21092 };
21093
21094 /* Write an address entry to OBSTACK.  */
21095
21096 static void
21097 add_address_entry (struct objfile *objfile, struct obstack *obstack,
21098                    CORE_ADDR start, CORE_ADDR end, unsigned int cu_index)
21099 {
21100   offset_type cu_index_to_write;
21101   gdb_byte addr[8];
21102   CORE_ADDR baseaddr;
21103
21104   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
21105
21106   store_unsigned_integer (addr, 8, BFD_ENDIAN_LITTLE, start - baseaddr);
21107   obstack_grow (obstack, addr, 8);
21108   store_unsigned_integer (addr, 8, BFD_ENDIAN_LITTLE, end - baseaddr);
21109   obstack_grow (obstack, addr, 8);
21110   cu_index_to_write = MAYBE_SWAP (cu_index);
21111   obstack_grow (obstack, &cu_index_to_write, sizeof (offset_type));
21112 }
21113
21114 /* Worker function for traversing an addrmap to build the address table.  */
21115
21116 static int
21117 add_address_entry_worker (void *datap, CORE_ADDR start_addr, void *obj)
21118 {
21119   struct addrmap_index_data *data = datap;
21120   struct partial_symtab *pst = obj;
21121
21122   if (data->previous_valid)
21123     add_address_entry (data->objfile, data->addr_obstack,
21124                        data->previous_cu_start, start_addr,
21125                        data->previous_cu_index);
21126
21127   data->previous_cu_start = start_addr;
21128   if (pst != NULL)
21129     {
21130       struct psymtab_cu_index_map find_map, *map;
21131       find_map.psymtab = pst;
21132       map = htab_find (data->cu_index_htab, &find_map);
21133       gdb_assert (map != NULL);
21134       data->previous_cu_index = map->cu_index;
21135       data->previous_valid = 1;
21136     }
21137   else
21138       data->previous_valid = 0;
21139
21140   return 0;
21141 }
21142
21143 /* Write OBJFILE's address map to OBSTACK.
21144    CU_INDEX_HTAB is used to map addrmap entries to their CU indices
21145    in the index file.  */
21146
21147 static void
21148 write_address_map (struct objfile *objfile, struct obstack *obstack,
21149                    htab_t cu_index_htab)
21150 {
21151   struct addrmap_index_data addrmap_index_data;
21152
21153   /* When writing the address table, we have to cope with the fact that
21154      the addrmap iterator only provides the start of a region; we have to
21155      wait until the next invocation to get the start of the next region.  */
21156
21157   addrmap_index_data.objfile = objfile;
21158   addrmap_index_data.addr_obstack = obstack;
21159   addrmap_index_data.cu_index_htab = cu_index_htab;
21160   addrmap_index_data.previous_valid = 0;
21161
21162   addrmap_foreach (objfile->psymtabs_addrmap, add_address_entry_worker,
21163                    &addrmap_index_data);
21164
21165   /* It's highly unlikely the last entry (end address = 0xff...ff)
21166      is valid, but we should still handle it.
21167      The end address is recorded as the start of the next region, but that
21168      doesn't work here.  To cope we pass 0xff...ff, this is a rare situation
21169      anyway.  */
21170   if (addrmap_index_data.previous_valid)
21171     add_address_entry (objfile, obstack,
21172                        addrmap_index_data.previous_cu_start, (CORE_ADDR) -1,
21173                        addrmap_index_data.previous_cu_index);
21174 }
21175
21176 /* Return the symbol kind of PSYM.  */
21177
21178 static gdb_index_symbol_kind
21179 symbol_kind (struct partial_symbol *psym)
21180 {
21181   domain_enum domain = PSYMBOL_DOMAIN (psym);
21182   enum address_class aclass = PSYMBOL_CLASS (psym);
21183
21184   switch (domain)
21185     {
21186     case VAR_DOMAIN:
21187       switch (aclass)
21188         {
21189         case LOC_BLOCK:
21190           return GDB_INDEX_SYMBOL_KIND_FUNCTION;
21191         case LOC_TYPEDEF:
21192           return GDB_INDEX_SYMBOL_KIND_TYPE;
21193         case LOC_COMPUTED:
21194         case LOC_CONST_BYTES:
21195         case LOC_OPTIMIZED_OUT:
21196         case LOC_STATIC:
21197           return GDB_INDEX_SYMBOL_KIND_VARIABLE;
21198         case LOC_CONST:
21199           /* Note: It's currently impossible to recognize psyms as enum values
21200              short of reading the type info.  For now punt.  */
21201           return GDB_INDEX_SYMBOL_KIND_VARIABLE;
21202         default:
21203           /* There are other LOC_FOO values that one might want to classify
21204              as variables, but dwarf2read.c doesn't currently use them.  */
21205           return GDB_INDEX_SYMBOL_KIND_OTHER;
21206         }
21207     case STRUCT_DOMAIN:
21208       return GDB_INDEX_SYMBOL_KIND_TYPE;
21209     default:
21210       return GDB_INDEX_SYMBOL_KIND_OTHER;
21211     }
21212 }
21213
21214 /* Add a list of partial symbols to SYMTAB.  */
21215
21216 static void
21217 write_psymbols (struct mapped_symtab *symtab,
21218                 htab_t psyms_seen,
21219                 struct partial_symbol **psymp,
21220                 int count,
21221                 offset_type cu_index,
21222                 int is_static)
21223 {
21224   for (; count-- > 0; ++psymp)
21225     {
21226       struct partial_symbol *psym = *psymp;
21227       void **slot;
21228
21229       if (SYMBOL_LANGUAGE (psym) == language_ada)
21230         error (_("Ada is not currently supported by the index"));
21231
21232       /* Only add a given psymbol once.  */
21233       slot = htab_find_slot (psyms_seen, psym, INSERT);
21234       if (!*slot)
21235         {
21236           gdb_index_symbol_kind kind = symbol_kind (psym);
21237
21238           *slot = psym;
21239           add_index_entry (symtab, SYMBOL_SEARCH_NAME (psym),
21240                            is_static, kind, cu_index);
21241         }
21242     }
21243 }
21244
21245 /* Write the contents of an ("unfinished") obstack to FILE.  Throw an
21246    exception if there is an error.  */
21247
21248 static void
21249 write_obstack (FILE *file, struct obstack *obstack)
21250 {
21251   if (fwrite (obstack_base (obstack), 1, obstack_object_size (obstack),
21252               file)
21253       != obstack_object_size (obstack))
21254     error (_("couldn't data write to file"));
21255 }
21256
21257 /* Unlink a file if the argument is not NULL.  */
21258
21259 static void
21260 unlink_if_set (void *p)
21261 {
21262   char **filename = p;
21263   if (*filename)
21264     unlink (*filename);
21265 }
21266
21267 /* A helper struct used when iterating over debug_types.  */
21268 struct signatured_type_index_data
21269 {
21270   struct objfile *objfile;
21271   struct mapped_symtab *symtab;
21272   struct obstack *types_list;
21273   htab_t psyms_seen;
21274   int cu_index;
21275 };
21276
21277 /* A helper function that writes a single signatured_type to an
21278    obstack.  */
21279
21280 static int
21281 write_one_signatured_type (void **slot, void *d)
21282 {
21283   struct signatured_type_index_data *info = d;
21284   struct signatured_type *entry = (struct signatured_type *) *slot;
21285   struct partial_symtab *psymtab = entry->per_cu.v.psymtab;
21286   gdb_byte val[8];
21287
21288   write_psymbols (info->symtab,
21289                   info->psyms_seen,
21290                   info->objfile->global_psymbols.list
21291                   + psymtab->globals_offset,
21292                   psymtab->n_global_syms, info->cu_index,
21293                   0);
21294   write_psymbols (info->symtab,
21295                   info->psyms_seen,
21296                   info->objfile->static_psymbols.list
21297                   + psymtab->statics_offset,
21298                   psymtab->n_static_syms, info->cu_index,
21299                   1);
21300
21301   store_unsigned_integer (val, 8, BFD_ENDIAN_LITTLE,
21302                           entry->per_cu.offset.sect_off);
21303   obstack_grow (info->types_list, val, 8);
21304   store_unsigned_integer (val, 8, BFD_ENDIAN_LITTLE,
21305                           entry->type_offset_in_tu.cu_off);
21306   obstack_grow (info->types_list, val, 8);
21307   store_unsigned_integer (val, 8, BFD_ENDIAN_LITTLE, entry->signature);
21308   obstack_grow (info->types_list, val, 8);
21309
21310   ++info->cu_index;
21311
21312   return 1;
21313 }
21314
21315 /* Recurse into all "included" dependencies and write their symbols as
21316    if they appeared in this psymtab.  */
21317
21318 static void
21319 recursively_write_psymbols (struct objfile *objfile,
21320                             struct partial_symtab *psymtab,
21321                             struct mapped_symtab *symtab,
21322                             htab_t psyms_seen,
21323                             offset_type cu_index)
21324 {
21325   int i;
21326
21327   for (i = 0; i < psymtab->number_of_dependencies; ++i)
21328     if (psymtab->dependencies[i]->user != NULL)
21329       recursively_write_psymbols (objfile, psymtab->dependencies[i],
21330                                   symtab, psyms_seen, cu_index);
21331
21332   write_psymbols (symtab,
21333                   psyms_seen,
21334                   objfile->global_psymbols.list + psymtab->globals_offset,
21335                   psymtab->n_global_syms, cu_index,
21336                   0);
21337   write_psymbols (symtab,
21338                   psyms_seen,
21339                   objfile->static_psymbols.list + psymtab->statics_offset,
21340                   psymtab->n_static_syms, cu_index,
21341                   1);
21342 }
21343
21344 /* Create an index file for OBJFILE in the directory DIR.  */
21345
21346 static void
21347 write_psymtabs_to_index (struct objfile *objfile, const char *dir)
21348 {
21349   struct cleanup *cleanup;
21350   char *filename, *cleanup_filename;
21351   struct obstack contents, addr_obstack, constant_pool, symtab_obstack;
21352   struct obstack cu_list, types_cu_list;
21353   int i;
21354   FILE *out_file;
21355   struct mapped_symtab *symtab;
21356   offset_type val, size_of_contents, total_len;
21357   struct stat st;
21358   htab_t psyms_seen;
21359   htab_t cu_index_htab;
21360   struct psymtab_cu_index_map *psymtab_cu_index_map;
21361
21362   if (dwarf2_per_objfile->using_index)
21363     error (_("Cannot use an index to create the index"));
21364
21365   if (VEC_length (dwarf2_section_info_def, dwarf2_per_objfile->types) > 1)
21366     error (_("Cannot make an index when the file has multiple .debug_types sections"));
21367
21368   if (!objfile->psymtabs || !objfile->psymtabs_addrmap)
21369     return;
21370
21371   if (stat (objfile_name (objfile), &st) < 0)
21372     perror_with_name (objfile_name (objfile));
21373
21374   filename = concat (dir, SLASH_STRING, lbasename (objfile_name (objfile)),
21375                      INDEX_SUFFIX, (char *) NULL);
21376   cleanup = make_cleanup (xfree, filename);
21377
21378   out_file = gdb_fopen_cloexec (filename, "wb");
21379   if (!out_file)
21380     error (_("Can't open `%s' for writing"), filename);
21381
21382   cleanup_filename = filename;
21383   make_cleanup (unlink_if_set, &cleanup_filename);
21384
21385   symtab = create_mapped_symtab ();
21386   make_cleanup (cleanup_mapped_symtab, symtab);
21387
21388   obstack_init (&addr_obstack);
21389   make_cleanup_obstack_free (&addr_obstack);
21390
21391   obstack_init (&cu_list);
21392   make_cleanup_obstack_free (&cu_list);
21393
21394   obstack_init (&types_cu_list);
21395   make_cleanup_obstack_free (&types_cu_list);
21396
21397   psyms_seen = htab_create_alloc (100, htab_hash_pointer, htab_eq_pointer,
21398                                   NULL, xcalloc, xfree);
21399   make_cleanup_htab_delete (psyms_seen);
21400
21401   /* While we're scanning CU's create a table that maps a psymtab pointer
21402      (which is what addrmap records) to its index (which is what is recorded
21403      in the index file).  This will later be needed to write the address
21404      table.  */
21405   cu_index_htab = htab_create_alloc (100,
21406                                      hash_psymtab_cu_index,
21407                                      eq_psymtab_cu_index,
21408                                      NULL, xcalloc, xfree);
21409   make_cleanup_htab_delete (cu_index_htab);
21410   psymtab_cu_index_map = (struct psymtab_cu_index_map *)
21411     xmalloc (sizeof (struct psymtab_cu_index_map)
21412              * dwarf2_per_objfile->n_comp_units);
21413   make_cleanup (xfree, psymtab_cu_index_map);
21414
21415   /* The CU list is already sorted, so we don't need to do additional
21416      work here.  Also, the debug_types entries do not appear in
21417      all_comp_units, but only in their own hash table.  */
21418   for (i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
21419     {
21420       struct dwarf2_per_cu_data *per_cu
21421         = dwarf2_per_objfile->all_comp_units[i];
21422       struct partial_symtab *psymtab = per_cu->v.psymtab;
21423       gdb_byte val[8];
21424       struct psymtab_cu_index_map *map;
21425       void **slot;
21426
21427       /* CU of a shared file from 'dwz -m' may be unused by this main file.
21428          It may be referenced from a local scope but in such case it does not
21429          need to be present in .gdb_index.  */
21430       if (psymtab == NULL)
21431         continue;
21432
21433       if (psymtab->user == NULL)
21434         recursively_write_psymbols (objfile, psymtab, symtab, psyms_seen, i);
21435
21436       map = &psymtab_cu_index_map[i];
21437       map->psymtab = psymtab;
21438       map->cu_index = i;
21439       slot = htab_find_slot (cu_index_htab, map, INSERT);
21440       gdb_assert (slot != NULL);
21441       gdb_assert (*slot == NULL);
21442       *slot = map;
21443
21444       store_unsigned_integer (val, 8, BFD_ENDIAN_LITTLE,
21445                               per_cu->offset.sect_off);
21446       obstack_grow (&cu_list, val, 8);
21447       store_unsigned_integer (val, 8, BFD_ENDIAN_LITTLE, per_cu->length);
21448       obstack_grow (&cu_list, val, 8);
21449     }
21450
21451   /* Dump the address map.  */
21452   write_address_map (objfile, &addr_obstack, cu_index_htab);
21453
21454   /* Write out the .debug_type entries, if any.  */
21455   if (dwarf2_per_objfile->signatured_types)
21456     {
21457       struct signatured_type_index_data sig_data;
21458
21459       sig_data.objfile = objfile;
21460       sig_data.symtab = symtab;
21461       sig_data.types_list = &types_cu_list;
21462       sig_data.psyms_seen = psyms_seen;
21463       sig_data.cu_index = dwarf2_per_objfile->n_comp_units;
21464       htab_traverse_noresize (dwarf2_per_objfile->signatured_types,
21465                               write_one_signatured_type, &sig_data);
21466     }
21467
21468   /* Now that we've processed all symbols we can shrink their cu_indices
21469      lists.  */
21470   uniquify_cu_indices (symtab);
21471
21472   obstack_init (&constant_pool);
21473   make_cleanup_obstack_free (&constant_pool);
21474   obstack_init (&symtab_obstack);
21475   make_cleanup_obstack_free (&symtab_obstack);
21476   write_hash_table (symtab, &symtab_obstack, &constant_pool);
21477
21478   obstack_init (&contents);
21479   make_cleanup_obstack_free (&contents);
21480   size_of_contents = 6 * sizeof (offset_type);
21481   total_len = size_of_contents;
21482
21483   /* The version number.  */
21484   val = MAYBE_SWAP (8);
21485   obstack_grow (&contents, &val, sizeof (val));
21486
21487   /* The offset of the CU list from the start of the file.  */
21488   val = MAYBE_SWAP (total_len);
21489   obstack_grow (&contents, &val, sizeof (val));
21490   total_len += obstack_object_size (&cu_list);
21491
21492   /* The offset of the types CU list from the start of the file.  */
21493   val = MAYBE_SWAP (total_len);
21494   obstack_grow (&contents, &val, sizeof (val));
21495   total_len += obstack_object_size (&types_cu_list);
21496
21497   /* The offset of the address table from the start of the file.  */
21498   val = MAYBE_SWAP (total_len);
21499   obstack_grow (&contents, &val, sizeof (val));
21500   total_len += obstack_object_size (&addr_obstack);
21501
21502   /* The offset of the symbol table from the start of the file.  */
21503   val = MAYBE_SWAP (total_len);
21504   obstack_grow (&contents, &val, sizeof (val));
21505   total_len += obstack_object_size (&symtab_obstack);
21506
21507   /* The offset of the constant pool from the start of the file.  */
21508   val = MAYBE_SWAP (total_len);
21509   obstack_grow (&contents, &val, sizeof (val));
21510   total_len += obstack_object_size (&constant_pool);
21511
21512   gdb_assert (obstack_object_size (&contents) == size_of_contents);
21513
21514   write_obstack (out_file, &contents);
21515   write_obstack (out_file, &cu_list);
21516   write_obstack (out_file, &types_cu_list);
21517   write_obstack (out_file, &addr_obstack);
21518   write_obstack (out_file, &symtab_obstack);
21519   write_obstack (out_file, &constant_pool);
21520
21521   fclose (out_file);
21522
21523   /* We want to keep the file, so we set cleanup_filename to NULL
21524      here.  See unlink_if_set.  */
21525   cleanup_filename = NULL;
21526
21527   do_cleanups (cleanup);
21528 }
21529
21530 /* Implementation of the `save gdb-index' command.
21531    
21532    Note that the file format used by this command is documented in the
21533    GDB manual.  Any changes here must be documented there.  */
21534
21535 static void
21536 save_gdb_index_command (char *arg, int from_tty)
21537 {
21538   struct objfile *objfile;
21539
21540   if (!arg || !*arg)
21541     error (_("usage: save gdb-index DIRECTORY"));
21542
21543   ALL_OBJFILES (objfile)
21544   {
21545     struct stat st;
21546
21547     /* If the objfile does not correspond to an actual file, skip it.  */
21548     if (stat (objfile_name (objfile), &st) < 0)
21549       continue;
21550
21551     dwarf2_per_objfile = objfile_data (objfile, dwarf2_objfile_data_key);
21552     if (dwarf2_per_objfile)
21553       {
21554         volatile struct gdb_exception except;
21555
21556         TRY_CATCH (except, RETURN_MASK_ERROR)
21557           {
21558             write_psymtabs_to_index (objfile, arg);
21559           }
21560         if (except.reason < 0)
21561           exception_fprintf (gdb_stderr, except,
21562                              _("Error while writing index for `%s': "),
21563                              objfile_name (objfile));
21564       }
21565   }
21566 }
21567
21568 \f
21569
21570 int dwarf2_always_disassemble;
21571
21572 static void
21573 show_dwarf2_always_disassemble (struct ui_file *file, int from_tty,
21574                                 struct cmd_list_element *c, const char *value)
21575 {
21576   fprintf_filtered (file,
21577                     _("Whether to always disassemble "
21578                       "DWARF expressions is %s.\n"),
21579                     value);
21580 }
21581
21582 static void
21583 show_check_physname (struct ui_file *file, int from_tty,
21584                      struct cmd_list_element *c, const char *value)
21585 {
21586   fprintf_filtered (file,
21587                     _("Whether to check \"physname\" is %s.\n"),
21588                     value);
21589 }
21590
21591 void _initialize_dwarf2_read (void);
21592
21593 void
21594 _initialize_dwarf2_read (void)
21595 {
21596   struct cmd_list_element *c;
21597
21598   dwarf2_objfile_data_key
21599     = register_objfile_data_with_cleanup (NULL, dwarf2_per_objfile_free);
21600
21601   add_prefix_cmd ("dwarf2", class_maintenance, set_dwarf2_cmd, _("\
21602 Set DWARF 2 specific variables.\n\
21603 Configure DWARF 2 variables such as the cache size"),
21604                   &set_dwarf2_cmdlist, "maintenance set dwarf2 ",
21605                   0/*allow-unknown*/, &maintenance_set_cmdlist);
21606
21607   add_prefix_cmd ("dwarf2", class_maintenance, show_dwarf2_cmd, _("\
21608 Show DWARF 2 specific variables\n\
21609 Show DWARF 2 variables such as the cache size"),
21610                   &show_dwarf2_cmdlist, "maintenance show dwarf2 ",
21611                   0/*allow-unknown*/, &maintenance_show_cmdlist);
21612
21613   add_setshow_zinteger_cmd ("max-cache-age", class_obscure,
21614                             &dwarf2_max_cache_age, _("\
21615 Set the upper bound on the age of cached dwarf2 compilation units."), _("\
21616 Show the upper bound on the age of cached dwarf2 compilation units."), _("\
21617 A higher limit means that cached compilation units will be stored\n\
21618 in memory longer, and more total memory will be used.  Zero disables\n\
21619 caching, which can slow down startup."),
21620                             NULL,
21621                             show_dwarf2_max_cache_age,
21622                             &set_dwarf2_cmdlist,
21623                             &show_dwarf2_cmdlist);
21624
21625   add_setshow_boolean_cmd ("always-disassemble", class_obscure,
21626                            &dwarf2_always_disassemble, _("\
21627 Set whether `info address' always disassembles DWARF expressions."), _("\
21628 Show whether `info address' always disassembles DWARF expressions."), _("\
21629 When enabled, DWARF expressions are always printed in an assembly-like\n\
21630 syntax.  When disabled, expressions will be printed in a more\n\
21631 conversational style, when possible."),
21632                            NULL,
21633                            show_dwarf2_always_disassemble,
21634                            &set_dwarf2_cmdlist,
21635                            &show_dwarf2_cmdlist);
21636
21637   add_setshow_boolean_cmd ("dwarf2-read", no_class, &dwarf2_read_debug, _("\
21638 Set debugging of the dwarf2 reader."), _("\
21639 Show debugging of the dwarf2 reader."), _("\
21640 When enabled, debugging messages are printed during dwarf2 reading\n\
21641 and symtab expansion."),
21642                             NULL,
21643                             NULL,
21644                             &setdebuglist, &showdebuglist);
21645
21646   add_setshow_zuinteger_cmd ("dwarf2-die", no_class, &dwarf2_die_debug, _("\
21647 Set debugging of the dwarf2 DIE reader."), _("\
21648 Show debugging of the dwarf2 DIE reader."), _("\
21649 When enabled (non-zero), DIEs are dumped after they are read in.\n\
21650 The value is the maximum depth to print."),
21651                              NULL,
21652                              NULL,
21653                              &setdebuglist, &showdebuglist);
21654
21655   add_setshow_boolean_cmd ("check-physname", no_class, &check_physname, _("\
21656 Set cross-checking of \"physname\" code against demangler."), _("\
21657 Show cross-checking of \"physname\" code against demangler."), _("\
21658 When enabled, GDB's internal \"physname\" code is checked against\n\
21659 the demangler."),
21660                            NULL, show_check_physname,
21661                            &setdebuglist, &showdebuglist);
21662
21663   add_setshow_boolean_cmd ("use-deprecated-index-sections",
21664                            no_class, &use_deprecated_index_sections, _("\
21665 Set whether to use deprecated gdb_index sections."), _("\
21666 Show whether to use deprecated gdb_index sections."), _("\
21667 When enabled, deprecated .gdb_index sections are used anyway.\n\
21668 Normally they are ignored either because of a missing feature or\n\
21669 performance issue.\n\
21670 Warning: This option must be enabled before gdb reads the file."),
21671                            NULL,
21672                            NULL,
21673                            &setlist, &showlist);
21674
21675   c = add_cmd ("gdb-index", class_files, save_gdb_index_command,
21676                _("\
21677 Save a gdb-index file.\n\
21678 Usage: save gdb-index DIRECTORY"),
21679                &save_cmdlist);
21680   set_cmd_completer (c, filename_completer);
21681
21682   dwarf2_locexpr_index = register_symbol_computed_impl (LOC_COMPUTED,
21683                                                         &dwarf2_locexpr_funcs);
21684   dwarf2_loclist_index = register_symbol_computed_impl (LOC_COMPUTED,
21685                                                         &dwarf2_loclist_funcs);
21686
21687   dwarf2_locexpr_block_index = register_symbol_block_impl (LOC_BLOCK,
21688                                         &dwarf2_block_frame_base_locexpr_funcs);
21689   dwarf2_loclist_block_index = register_symbol_block_impl (LOC_BLOCK,
21690                                         &dwarf2_block_frame_base_loclist_funcs);
21691 }