PR symtab/15691
[platform/upstream/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   /* Backchain to our per_cu entry if the tree has been built.  */
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   VEC (dwarf2_per_cu_ptr) *imported_symtabs;
615 };
616
617 /* Entry in the signatured_types hash table.  */
618
619 struct signatured_type
620 {
621   /* The "per_cu" object of this type.
622      This struct is used iff per_cu.is_debug_types.
623      N.B.: This is the first member so that it's easy to convert pointers
624      between them.  */
625   struct dwarf2_per_cu_data per_cu;
626
627   /* The type's signature.  */
628   ULONGEST signature;
629
630   /* Offset in the TU of the type's DIE, as read from the TU header.
631      If this TU is a DWO stub and the definition lives in a DWO file
632      (specified by DW_AT_GNU_dwo_name), this value is unusable.  */
633   cu_offset type_offset_in_tu;
634
635   /* Offset in the section of the type's DIE.
636      If the definition lives in a DWO file, this is the offset in the
637      .debug_types.dwo section.
638      The value is zero until the actual value is known.
639      Zero is otherwise not a valid section offset.  */
640   sect_offset type_offset_in_section;
641
642   /* Type units are grouped by their DW_AT_stmt_list entry so that they
643      can share them.  This points to the containing symtab.  */
644   struct type_unit_group *type_unit_group;
645
646   /* The type.
647      The first time we encounter this type we fully read it in and install it
648      in the symbol tables.  Subsequent times we only need the type.  */
649   struct type *type;
650
651   /* Containing DWO unit.
652      This field is valid iff per_cu.reading_dwo_directly.  */
653   struct dwo_unit *dwo_unit;
654 };
655
656 typedef struct signatured_type *sig_type_ptr;
657 DEF_VEC_P (sig_type_ptr);
658
659 /* A struct that can be used as a hash key for tables based on DW_AT_stmt_list.
660    This includes type_unit_group and quick_file_names.  */
661
662 struct stmt_list_hash
663 {
664   /* The DWO unit this table is from or NULL if there is none.  */
665   struct dwo_unit *dwo_unit;
666
667   /* Offset in .debug_line or .debug_line.dwo.  */
668   sect_offset line_offset;
669 };
670
671 /* Each element of dwarf2_per_objfile->type_unit_groups is a pointer to
672    an object of this type.  */
673
674 struct type_unit_group
675 {
676   /* dwarf2read.c's main "handle" on a TU symtab.
677      To simplify things we create an artificial CU that "includes" all the
678      type units using this stmt_list so that the rest of the code still has
679      a "per_cu" handle on the symtab.
680      This PER_CU is recognized by having no section.  */
681 #define IS_TYPE_UNIT_GROUP(per_cu) ((per_cu)->section == NULL)
682   struct dwarf2_per_cu_data per_cu;
683
684   /* The TUs that share this DW_AT_stmt_list entry.
685      This is added to while parsing type units to build partial symtabs,
686      and is deleted afterwards and not used again.  */
687   VEC (sig_type_ptr) *tus;
688
689   /* The primary symtab.
690      Type units in a group needn't all be defined in the same source file,
691      so we create an essentially anonymous symtab as the primary symtab.  */
692   struct symtab *primary_symtab;
693
694   /* The data used to construct the hash key.  */
695   struct stmt_list_hash hash;
696
697   /* The number of symtabs from the line header.
698      The value here must match line_header.num_file_names.  */
699   unsigned int num_symtabs;
700
701   /* The symbol tables for this TU (obtained from the files listed in
702      DW_AT_stmt_list).
703      WARNING: The order of entries here must match the order of entries
704      in the line header.  After the first TU using this type_unit_group, the
705      line header for the subsequent TUs is recreated from this.  This is done
706      because we need to use the same symtabs for each TU using the same
707      DW_AT_stmt_list value.  Also note that symtabs may be repeated here,
708      there's no guarantee the line header doesn't have duplicate entries.  */
709   struct symtab **symtabs;
710 };
711
712 /* These sections are what may appear in a DWO file.  */
713
714 struct dwo_sections
715 {
716   struct dwarf2_section_info abbrev;
717   struct dwarf2_section_info line;
718   struct dwarf2_section_info loc;
719   struct dwarf2_section_info macinfo;
720   struct dwarf2_section_info macro;
721   struct dwarf2_section_info str;
722   struct dwarf2_section_info str_offsets;
723   /* In the case of a virtual DWO file, these two are unused.  */
724   struct dwarf2_section_info info;
725   VEC (dwarf2_section_info_def) *types;
726 };
727
728 /* CUs/TUs in DWP/DWO files.  */
729
730 struct dwo_unit
731 {
732   /* Backlink to the containing struct dwo_file.  */
733   struct dwo_file *dwo_file;
734
735   /* The "id" that distinguishes this CU/TU.
736      .debug_info calls this "dwo_id", .debug_types calls this "signature".
737      Since signatures came first, we stick with it for consistency.  */
738   ULONGEST signature;
739
740   /* The section this CU/TU lives in, in the DWO file.  */
741   struct dwarf2_section_info *section;
742
743   /* Same as dwarf2_per_cu_data:{offset,length} but for the DWO section.  */
744   sect_offset offset;
745   unsigned int length;
746
747   /* For types, offset in the type's DIE of the type defined by this TU.  */
748   cu_offset type_offset_in_tu;
749 };
750
751 /* Data for one DWO file.
752    This includes virtual DWO files that have been packaged into a
753    DWP file.  */
754
755 struct dwo_file
756 {
757   /* The DW_AT_GNU_dwo_name attribute.
758      For virtual DWO files the name is constructed from the section offsets
759      of abbrev,line,loc,str_offsets so that we combine virtual DWO files
760      from related CU+TUs.  */
761   const char *dwo_name;
762
763   /* The DW_AT_comp_dir attribute.  */
764   const char *comp_dir;
765
766   /* The bfd, when the file is open.  Otherwise this is NULL.
767      This is unused(NULL) for virtual DWO files where we use dwp_file.dbfd.  */
768   bfd *dbfd;
769
770   /* Section info for this file.  */
771   struct dwo_sections sections;
772
773   /* The CU in the file.
774      We only support one because having more than one requires hacking the
775      dwo_name of each to match, which is highly unlikely to happen.
776      Doing this means all TUs can share comp_dir: We also assume that
777      DW_AT_comp_dir across all TUs in a DWO file will be identical.  */
778   struct dwo_unit *cu;
779
780   /* Table of TUs in the file.
781      Each element is a struct dwo_unit.  */
782   htab_t tus;
783 };
784
785 /* These sections are what may appear in a DWP file.  */
786
787 struct dwp_sections
788 {
789   struct dwarf2_section_info str;
790   struct dwarf2_section_info cu_index;
791   struct dwarf2_section_info tu_index;
792   /* The .debug_info.dwo, .debug_types.dwo, and other sections are referenced
793      by section number.  We don't need to record them here.  */
794 };
795
796 /* These sections are what may appear in a virtual DWO file.  */
797
798 struct virtual_dwo_sections
799 {
800   struct dwarf2_section_info abbrev;
801   struct dwarf2_section_info line;
802   struct dwarf2_section_info loc;
803   struct dwarf2_section_info macinfo;
804   struct dwarf2_section_info macro;
805   struct dwarf2_section_info str_offsets;
806   /* Each DWP hash table entry records one CU or one TU.
807      That is recorded here, and copied to dwo_unit.section.  */
808   struct dwarf2_section_info info_or_types;
809 };
810
811 /* Contents of DWP hash tables.  */
812
813 struct dwp_hash_table
814 {
815   uint32_t nr_units, nr_slots;
816   const gdb_byte *hash_table, *unit_table, *section_pool;
817 };
818
819 /* Data for one DWP file.  */
820
821 struct dwp_file
822 {
823   /* Name of the file.  */
824   const char *name;
825
826   /* The bfd.  */
827   bfd *dbfd;
828
829   /* Section info for this file.  */
830   struct dwp_sections sections;
831
832   /* Table of CUs in the file. */
833   const struct dwp_hash_table *cus;
834
835   /* Table of TUs in the file.  */
836   const struct dwp_hash_table *tus;
837
838   /* Table of loaded CUs/TUs.  Each entry is a struct dwo_unit *.  */
839   htab_t loaded_cutus;
840
841   /* Table to map ELF section numbers to their sections.  */
842   unsigned int num_sections;
843   asection **elf_sections;
844 };
845
846 /* This represents a '.dwz' file.  */
847
848 struct dwz_file
849 {
850   /* A dwz file can only contain a few sections.  */
851   struct dwarf2_section_info abbrev;
852   struct dwarf2_section_info info;
853   struct dwarf2_section_info str;
854   struct dwarf2_section_info line;
855   struct dwarf2_section_info macro;
856   struct dwarf2_section_info gdb_index;
857
858   /* The dwz's BFD.  */
859   bfd *dwz_bfd;
860 };
861
862 /* Struct used to pass misc. parameters to read_die_and_children, et
863    al.  which are used for both .debug_info and .debug_types dies.
864    All parameters here are unchanging for the life of the call.  This
865    struct exists to abstract away the constant parameters of die reading.  */
866
867 struct die_reader_specs
868 {
869   /* die_section->asection->owner.  */
870   bfd* abfd;
871
872   /* The CU of the DIE we are parsing.  */
873   struct dwarf2_cu *cu;
874
875   /* Non-NULL if reading a DWO file (including one packaged into a DWP).  */
876   struct dwo_file *dwo_file;
877
878   /* The section the die comes from.
879      This is either .debug_info or .debug_types, or the .dwo variants.  */
880   struct dwarf2_section_info *die_section;
881
882   /* die_section->buffer.  */
883   const gdb_byte *buffer;
884
885   /* The end of the buffer.  */
886   const gdb_byte *buffer_end;
887
888   /* The value of the DW_AT_comp_dir attribute.  */
889   const char *comp_dir;
890 };
891
892 /* Type of function passed to init_cutu_and_read_dies, et.al.  */
893 typedef void (die_reader_func_ftype) (const struct die_reader_specs *reader,
894                                       const gdb_byte *info_ptr,
895                                       struct die_info *comp_unit_die,
896                                       int has_children,
897                                       void *data);
898
899 /* The line number information for a compilation unit (found in the
900    .debug_line section) begins with a "statement program header",
901    which contains the following information.  */
902 struct line_header
903 {
904   unsigned int total_length;
905   unsigned short version;
906   unsigned int header_length;
907   unsigned char minimum_instruction_length;
908   unsigned char maximum_ops_per_instruction;
909   unsigned char default_is_stmt;
910   int line_base;
911   unsigned char line_range;
912   unsigned char opcode_base;
913
914   /* standard_opcode_lengths[i] is the number of operands for the
915      standard opcode whose value is i.  This means that
916      standard_opcode_lengths[0] is unused, and the last meaningful
917      element is standard_opcode_lengths[opcode_base - 1].  */
918   unsigned char *standard_opcode_lengths;
919
920   /* The include_directories table.  NOTE!  These strings are not
921      allocated with xmalloc; instead, they are pointers into
922      debug_line_buffer.  If you try to free them, `free' will get
923      indigestion.  */
924   unsigned int num_include_dirs, include_dirs_size;
925   const char **include_dirs;
926
927   /* The file_names table.  NOTE!  These strings are not allocated
928      with xmalloc; instead, they are pointers into debug_line_buffer.
929      Don't try to free them directly.  */
930   unsigned int num_file_names, file_names_size;
931   struct file_entry
932   {
933     const char *name;
934     unsigned int dir_index;
935     unsigned int mod_time;
936     unsigned int length;
937     int included_p; /* Non-zero if referenced by the Line Number Program.  */
938     struct symtab *symtab; /* The associated symbol table, if any.  */
939   } *file_names;
940
941   /* The start and end of the statement program following this
942      header.  These point into dwarf2_per_objfile->line_buffer.  */
943   const gdb_byte *statement_program_start, *statement_program_end;
944 };
945
946 /* When we construct a partial symbol table entry we only
947    need this much information.  */
948 struct partial_die_info
949   {
950     /* Offset of this DIE.  */
951     sect_offset offset;
952
953     /* DWARF-2 tag for this DIE.  */
954     ENUM_BITFIELD(dwarf_tag) tag : 16;
955
956     /* Assorted flags describing the data found in this DIE.  */
957     unsigned int has_children : 1;
958     unsigned int is_external : 1;
959     unsigned int is_declaration : 1;
960     unsigned int has_type : 1;
961     unsigned int has_specification : 1;
962     unsigned int has_pc_info : 1;
963     unsigned int may_be_inlined : 1;
964
965     /* Flag set if the SCOPE field of this structure has been
966        computed.  */
967     unsigned int scope_set : 1;
968
969     /* Flag set if the DIE has a byte_size attribute.  */
970     unsigned int has_byte_size : 1;
971
972     /* Flag set if any of the DIE's children are template arguments.  */
973     unsigned int has_template_arguments : 1;
974
975     /* Flag set if fixup_partial_die has been called on this die.  */
976     unsigned int fixup_called : 1;
977
978     /* Flag set if DW_TAG_imported_unit uses DW_FORM_GNU_ref_alt.  */
979     unsigned int is_dwz : 1;
980
981     /* Flag set if spec_offset uses DW_FORM_GNU_ref_alt.  */
982     unsigned int spec_is_dwz : 1;
983
984     /* The name of this DIE.  Normally the value of DW_AT_name, but
985        sometimes a default name for unnamed DIEs.  */
986     const char *name;
987
988     /* The linkage name, if present.  */
989     const char *linkage_name;
990
991     /* The scope to prepend to our children.  This is generally
992        allocated on the comp_unit_obstack, so will disappear
993        when this compilation unit leaves the cache.  */
994     const char *scope;
995
996     /* Some data associated with the partial DIE.  The tag determines
997        which field is live.  */
998     union
999     {
1000       /* The location description associated with this DIE, if any.  */
1001       struct dwarf_block *locdesc;
1002       /* The offset of an import, for DW_TAG_imported_unit.  */
1003       sect_offset offset;
1004     } d;
1005
1006     /* If HAS_PC_INFO, the PC range associated with this DIE.  */
1007     CORE_ADDR lowpc;
1008     CORE_ADDR highpc;
1009
1010     /* Pointer into the info_buffer (or types_buffer) pointing at the target of
1011        DW_AT_sibling, if any.  */
1012     /* NOTE: This member isn't strictly necessary, read_partial_die could
1013        return DW_AT_sibling values to its caller load_partial_dies.  */
1014     const gdb_byte *sibling;
1015
1016     /* If HAS_SPECIFICATION, the offset of the DIE referred to by
1017        DW_AT_specification (or DW_AT_abstract_origin or
1018        DW_AT_extension).  */
1019     sect_offset spec_offset;
1020
1021     /* Pointers to this DIE's parent, first child, and next sibling,
1022        if any.  */
1023     struct partial_die_info *die_parent, *die_child, *die_sibling;
1024   };
1025
1026 /* This data structure holds the information of an abbrev.  */
1027 struct abbrev_info
1028   {
1029     unsigned int number;        /* number identifying abbrev */
1030     enum dwarf_tag tag;         /* dwarf tag */
1031     unsigned short has_children;                /* boolean */
1032     unsigned short num_attrs;   /* number of attributes */
1033     struct attr_abbrev *attrs;  /* an array of attribute descriptions */
1034     struct abbrev_info *next;   /* next in chain */
1035   };
1036
1037 struct attr_abbrev
1038   {
1039     ENUM_BITFIELD(dwarf_attribute) name : 16;
1040     ENUM_BITFIELD(dwarf_form) form : 16;
1041   };
1042
1043 /* Size of abbrev_table.abbrev_hash_table.  */
1044 #define ABBREV_HASH_SIZE 121
1045
1046 /* Top level data structure to contain an abbreviation table.  */
1047
1048 struct abbrev_table
1049 {
1050   /* Where the abbrev table came from.
1051      This is used as a sanity check when the table is used.  */
1052   sect_offset offset;
1053
1054   /* Storage for the abbrev table.  */
1055   struct obstack abbrev_obstack;
1056
1057   /* Hash table of abbrevs.
1058      This is an array of size ABBREV_HASH_SIZE allocated in abbrev_obstack.
1059      It could be statically allocated, but the previous code didn't so we
1060      don't either.  */
1061   struct abbrev_info **abbrevs;
1062 };
1063
1064 /* Attributes have a name and a value.  */
1065 struct attribute
1066   {
1067     ENUM_BITFIELD(dwarf_attribute) name : 16;
1068     ENUM_BITFIELD(dwarf_form) form : 15;
1069
1070     /* Has DW_STRING already been updated by dwarf2_canonicalize_name?  This
1071        field should be in u.str (existing only for DW_STRING) but it is kept
1072        here for better struct attribute alignment.  */
1073     unsigned int string_is_canonical : 1;
1074
1075     union
1076       {
1077         const char *str;
1078         struct dwarf_block *blk;
1079         ULONGEST unsnd;
1080         LONGEST snd;
1081         CORE_ADDR addr;
1082         ULONGEST signature;
1083       }
1084     u;
1085   };
1086
1087 /* This data structure holds a complete die structure.  */
1088 struct die_info
1089   {
1090     /* DWARF-2 tag for this DIE.  */
1091     ENUM_BITFIELD(dwarf_tag) tag : 16;
1092
1093     /* Number of attributes */
1094     unsigned char num_attrs;
1095
1096     /* True if we're presently building the full type name for the
1097        type derived from this DIE.  */
1098     unsigned char building_fullname : 1;
1099
1100     /* Abbrev number */
1101     unsigned int abbrev;
1102
1103     /* Offset in .debug_info or .debug_types section.  */
1104     sect_offset offset;
1105
1106     /* The dies in a compilation unit form an n-ary tree.  PARENT
1107        points to this die's parent; CHILD points to the first child of
1108        this node; and all the children of a given node are chained
1109        together via their SIBLING fields.  */
1110     struct die_info *child;     /* Its first child, if any.  */
1111     struct die_info *sibling;   /* Its next sibling, if any.  */
1112     struct die_info *parent;    /* Its parent, if any.  */
1113
1114     /* An array of attributes, with NUM_ATTRS elements.  There may be
1115        zero, but it's not common and zero-sized arrays are not
1116        sufficiently portable C.  */
1117     struct attribute attrs[1];
1118   };
1119
1120 /* Get at parts of an attribute structure.  */
1121
1122 #define DW_STRING(attr)    ((attr)->u.str)
1123 #define DW_STRING_IS_CANONICAL(attr) ((attr)->string_is_canonical)
1124 #define DW_UNSND(attr)     ((attr)->u.unsnd)
1125 #define DW_BLOCK(attr)     ((attr)->u.blk)
1126 #define DW_SND(attr)       ((attr)->u.snd)
1127 #define DW_ADDR(attr)      ((attr)->u.addr)
1128 #define DW_SIGNATURE(attr) ((attr)->u.signature)
1129
1130 /* Blocks are a bunch of untyped bytes.  */
1131 struct dwarf_block
1132   {
1133     size_t size;
1134
1135     /* Valid only if SIZE is not zero.  */
1136     const gdb_byte *data;
1137   };
1138
1139 #ifndef ATTR_ALLOC_CHUNK
1140 #define ATTR_ALLOC_CHUNK 4
1141 #endif
1142
1143 /* Allocate fields for structs, unions and enums in this size.  */
1144 #ifndef DW_FIELD_ALLOC_CHUNK
1145 #define DW_FIELD_ALLOC_CHUNK 4
1146 #endif
1147
1148 /* FIXME: We might want to set this from BFD via bfd_arch_bits_per_byte,
1149    but this would require a corresponding change in unpack_field_as_long
1150    and friends.  */
1151 static int bits_per_byte = 8;
1152
1153 /* The routines that read and process dies for a C struct or C++ class
1154    pass lists of data member fields and lists of member function fields
1155    in an instance of a field_info structure, as defined below.  */
1156 struct field_info
1157   {
1158     /* List of data member and baseclasses fields.  */
1159     struct nextfield
1160       {
1161         struct nextfield *next;
1162         int accessibility;
1163         int virtuality;
1164         struct field field;
1165       }
1166      *fields, *baseclasses;
1167
1168     /* Number of fields (including baseclasses).  */
1169     int nfields;
1170
1171     /* Number of baseclasses.  */
1172     int nbaseclasses;
1173
1174     /* Set if the accesibility of one of the fields is not public.  */
1175     int non_public_fields;
1176
1177     /* Member function fields array, entries are allocated in the order they
1178        are encountered in the object file.  */
1179     struct nextfnfield
1180       {
1181         struct nextfnfield *next;
1182         struct fn_field fnfield;
1183       }
1184      *fnfields;
1185
1186     /* Member function fieldlist array, contains name of possibly overloaded
1187        member function, number of overloaded member functions and a pointer
1188        to the head of the member function field chain.  */
1189     struct fnfieldlist
1190       {
1191         const char *name;
1192         int length;
1193         struct nextfnfield *head;
1194       }
1195      *fnfieldlists;
1196
1197     /* Number of entries in the fnfieldlists array.  */
1198     int nfnfields;
1199
1200     /* typedefs defined inside this class.  TYPEDEF_FIELD_LIST contains head of
1201        a NULL terminated list of TYPEDEF_FIELD_LIST_COUNT elements.  */
1202     struct typedef_field_list
1203       {
1204         struct typedef_field field;
1205         struct typedef_field_list *next;
1206       }
1207     *typedef_field_list;
1208     unsigned typedef_field_list_count;
1209   };
1210
1211 /* One item on the queue of compilation units to read in full symbols
1212    for.  */
1213 struct dwarf2_queue_item
1214 {
1215   struct dwarf2_per_cu_data *per_cu;
1216   enum language pretend_language;
1217   struct dwarf2_queue_item *next;
1218 };
1219
1220 /* The current queue.  */
1221 static struct dwarf2_queue_item *dwarf2_queue, *dwarf2_queue_tail;
1222
1223 /* Loaded secondary compilation units are kept in memory until they
1224    have not been referenced for the processing of this many
1225    compilation units.  Set this to zero to disable caching.  Cache
1226    sizes of up to at least twenty will improve startup time for
1227    typical inter-CU-reference binaries, at an obvious memory cost.  */
1228 static int dwarf2_max_cache_age = 5;
1229 static void
1230 show_dwarf2_max_cache_age (struct ui_file *file, int from_tty,
1231                            struct cmd_list_element *c, const char *value)
1232 {
1233   fprintf_filtered (file, _("The upper bound on the age of cached "
1234                             "dwarf2 compilation units is %s.\n"),
1235                     value);
1236 }
1237
1238
1239 /* Various complaints about symbol reading that don't abort the process.  */
1240
1241 static void
1242 dwarf2_statement_list_fits_in_line_number_section_complaint (void)
1243 {
1244   complaint (&symfile_complaints,
1245              _("statement list doesn't fit in .debug_line section"));
1246 }
1247
1248 static void
1249 dwarf2_debug_line_missing_file_complaint (void)
1250 {
1251   complaint (&symfile_complaints,
1252              _(".debug_line section has line data without a file"));
1253 }
1254
1255 static void
1256 dwarf2_debug_line_missing_end_sequence_complaint (void)
1257 {
1258   complaint (&symfile_complaints,
1259              _(".debug_line section has line "
1260                "program sequence without an end"));
1261 }
1262
1263 static void
1264 dwarf2_complex_location_expr_complaint (void)
1265 {
1266   complaint (&symfile_complaints, _("location expression too complex"));
1267 }
1268
1269 static void
1270 dwarf2_const_value_length_mismatch_complaint (const char *arg1, int arg2,
1271                                               int arg3)
1272 {
1273   complaint (&symfile_complaints,
1274              _("const value length mismatch for '%s', got %d, expected %d"),
1275              arg1, arg2, arg3);
1276 }
1277
1278 static void
1279 dwarf2_section_buffer_overflow_complaint (struct dwarf2_section_info *section)
1280 {
1281   complaint (&symfile_complaints,
1282              _("debug info runs off end of %s section"
1283                " [in module %s]"),
1284              section->asection->name,
1285              bfd_get_filename (section->asection->owner));
1286 }
1287
1288 static void
1289 dwarf2_macro_malformed_definition_complaint (const char *arg1)
1290 {
1291   complaint (&symfile_complaints,
1292              _("macro debug info contains a "
1293                "malformed macro definition:\n`%s'"),
1294              arg1);
1295 }
1296
1297 static void
1298 dwarf2_invalid_attrib_class_complaint (const char *arg1, const char *arg2)
1299 {
1300   complaint (&symfile_complaints,
1301              _("invalid attribute class or form for '%s' in '%s'"),
1302              arg1, arg2);
1303 }
1304
1305 /* local function prototypes */
1306
1307 static void dwarf2_locate_sections (bfd *, asection *, void *);
1308
1309 static void dwarf2_find_base_address (struct die_info *die,
1310                                       struct dwarf2_cu *cu);
1311
1312 static struct partial_symtab *create_partial_symtab
1313   (struct dwarf2_per_cu_data *per_cu, const char *name);
1314
1315 static void dwarf2_build_psymtabs_hard (struct objfile *);
1316
1317 static void scan_partial_symbols (struct partial_die_info *,
1318                                   CORE_ADDR *, CORE_ADDR *,
1319                                   int, struct dwarf2_cu *);
1320
1321 static void add_partial_symbol (struct partial_die_info *,
1322                                 struct dwarf2_cu *);
1323
1324 static void add_partial_namespace (struct partial_die_info *pdi,
1325                                    CORE_ADDR *lowpc, CORE_ADDR *highpc,
1326                                    int need_pc, struct dwarf2_cu *cu);
1327
1328 static void add_partial_module (struct partial_die_info *pdi, CORE_ADDR *lowpc,
1329                                 CORE_ADDR *highpc, int need_pc,
1330                                 struct dwarf2_cu *cu);
1331
1332 static void add_partial_enumeration (struct partial_die_info *enum_pdi,
1333                                      struct dwarf2_cu *cu);
1334
1335 static void add_partial_subprogram (struct partial_die_info *pdi,
1336                                     CORE_ADDR *lowpc, CORE_ADDR *highpc,
1337                                     int need_pc, struct dwarf2_cu *cu);
1338
1339 static void dwarf2_read_symtab (struct partial_symtab *,
1340                                 struct objfile *);
1341
1342 static void psymtab_to_symtab_1 (struct partial_symtab *);
1343
1344 static struct abbrev_info *abbrev_table_lookup_abbrev
1345   (const struct abbrev_table *, unsigned int);
1346
1347 static struct abbrev_table *abbrev_table_read_table
1348   (struct dwarf2_section_info *, sect_offset);
1349
1350 static void abbrev_table_free (struct abbrev_table *);
1351
1352 static void abbrev_table_free_cleanup (void *);
1353
1354 static void dwarf2_read_abbrevs (struct dwarf2_cu *,
1355                                  struct dwarf2_section_info *);
1356
1357 static void dwarf2_free_abbrev_table (void *);
1358
1359 static unsigned int peek_abbrev_code (bfd *, const gdb_byte *);
1360
1361 static struct partial_die_info *load_partial_dies
1362   (const struct die_reader_specs *, const gdb_byte *, int);
1363
1364 static const gdb_byte *read_partial_die (const struct die_reader_specs *,
1365                                          struct partial_die_info *,
1366                                          struct abbrev_info *,
1367                                          unsigned int,
1368                                          const gdb_byte *);
1369
1370 static struct partial_die_info *find_partial_die (sect_offset, int,
1371                                                   struct dwarf2_cu *);
1372
1373 static void fixup_partial_die (struct partial_die_info *,
1374                                struct dwarf2_cu *);
1375
1376 static const gdb_byte *read_attribute (const struct die_reader_specs *,
1377                                        struct attribute *, struct attr_abbrev *,
1378                                        const gdb_byte *);
1379
1380 static unsigned int read_1_byte (bfd *, const gdb_byte *);
1381
1382 static int read_1_signed_byte (bfd *, const gdb_byte *);
1383
1384 static unsigned int read_2_bytes (bfd *, const gdb_byte *);
1385
1386 static unsigned int read_4_bytes (bfd *, const gdb_byte *);
1387
1388 static ULONGEST read_8_bytes (bfd *, const gdb_byte *);
1389
1390 static CORE_ADDR read_address (bfd *, const gdb_byte *ptr, struct dwarf2_cu *,
1391                                unsigned int *);
1392
1393 static LONGEST read_initial_length (bfd *, const gdb_byte *, unsigned int *);
1394
1395 static LONGEST read_checked_initial_length_and_offset
1396   (bfd *, const gdb_byte *, const struct comp_unit_head *,
1397    unsigned int *, unsigned int *);
1398
1399 static LONGEST read_offset (bfd *, const gdb_byte *,
1400                             const struct comp_unit_head *,
1401                             unsigned int *);
1402
1403 static LONGEST read_offset_1 (bfd *, const gdb_byte *, unsigned int);
1404
1405 static sect_offset read_abbrev_offset (struct dwarf2_section_info *,
1406                                        sect_offset);
1407
1408 static const gdb_byte *read_n_bytes (bfd *, const gdb_byte *, unsigned int);
1409
1410 static const char *read_direct_string (bfd *, const gdb_byte *, unsigned int *);
1411
1412 static const char *read_indirect_string (bfd *, const gdb_byte *,
1413                                          const struct comp_unit_head *,
1414                                          unsigned int *);
1415
1416 static const char *read_indirect_string_from_dwz (struct dwz_file *, LONGEST);
1417
1418 static ULONGEST read_unsigned_leb128 (bfd *, const gdb_byte *, unsigned int *);
1419
1420 static LONGEST read_signed_leb128 (bfd *, const gdb_byte *, unsigned int *);
1421
1422 static CORE_ADDR read_addr_index_from_leb128 (struct dwarf2_cu *,
1423                                               const gdb_byte *,
1424                                               unsigned int *);
1425
1426 static const char *read_str_index (const struct die_reader_specs *reader,
1427                                    struct dwarf2_cu *cu, ULONGEST str_index);
1428
1429 static void set_cu_language (unsigned int, struct dwarf2_cu *);
1430
1431 static struct attribute *dwarf2_attr (struct die_info *, unsigned int,
1432                                       struct dwarf2_cu *);
1433
1434 static struct attribute *dwarf2_attr_no_follow (struct die_info *,
1435                                                 unsigned int);
1436
1437 static int dwarf2_flag_true_p (struct die_info *die, unsigned name,
1438                                struct dwarf2_cu *cu);
1439
1440 static int die_is_declaration (struct die_info *, struct dwarf2_cu *cu);
1441
1442 static struct die_info *die_specification (struct die_info *die,
1443                                            struct dwarf2_cu **);
1444
1445 static void free_line_header (struct line_header *lh);
1446
1447 static struct line_header *dwarf_decode_line_header (unsigned int offset,
1448                                                      struct dwarf2_cu *cu);
1449
1450 static void dwarf_decode_lines (struct line_header *, const char *,
1451                                 struct dwarf2_cu *, struct partial_symtab *,
1452                                 int);
1453
1454 static void dwarf2_start_subfile (const char *, const char *, const char *);
1455
1456 static void dwarf2_start_symtab (struct dwarf2_cu *,
1457                                  const char *, const char *, CORE_ADDR);
1458
1459 static struct symbol *new_symbol (struct die_info *, struct type *,
1460                                   struct dwarf2_cu *);
1461
1462 static struct symbol *new_symbol_full (struct die_info *, struct type *,
1463                                        struct dwarf2_cu *, struct symbol *);
1464
1465 static void dwarf2_const_value (const struct attribute *, struct symbol *,
1466                                 struct dwarf2_cu *);
1467
1468 static void dwarf2_const_value_attr (const struct attribute *attr,
1469                                      struct type *type,
1470                                      const char *name,
1471                                      struct obstack *obstack,
1472                                      struct dwarf2_cu *cu, LONGEST *value,
1473                                      const gdb_byte **bytes,
1474                                      struct dwarf2_locexpr_baton **baton);
1475
1476 static struct type *die_type (struct die_info *, struct dwarf2_cu *);
1477
1478 static int need_gnat_info (struct dwarf2_cu *);
1479
1480 static struct type *die_descriptive_type (struct die_info *,
1481                                           struct dwarf2_cu *);
1482
1483 static void set_descriptive_type (struct type *, struct die_info *,
1484                                   struct dwarf2_cu *);
1485
1486 static struct type *die_containing_type (struct die_info *,
1487                                          struct dwarf2_cu *);
1488
1489 static struct type *lookup_die_type (struct die_info *, const struct attribute *,
1490                                      struct dwarf2_cu *);
1491
1492 static struct type *read_type_die (struct die_info *, struct dwarf2_cu *);
1493
1494 static struct type *read_type_die_1 (struct die_info *, struct dwarf2_cu *);
1495
1496 static const char *determine_prefix (struct die_info *die, struct dwarf2_cu *);
1497
1498 static char *typename_concat (struct obstack *obs, const char *prefix,
1499                               const char *suffix, int physname,
1500                               struct dwarf2_cu *cu);
1501
1502 static void read_file_scope (struct die_info *, struct dwarf2_cu *);
1503
1504 static void read_type_unit_scope (struct die_info *, struct dwarf2_cu *);
1505
1506 static void read_func_scope (struct die_info *, struct dwarf2_cu *);
1507
1508 static void read_lexical_block_scope (struct die_info *, struct dwarf2_cu *);
1509
1510 static void read_call_site_scope (struct die_info *die, struct dwarf2_cu *cu);
1511
1512 static int dwarf2_ranges_read (unsigned, CORE_ADDR *, CORE_ADDR *,
1513                                struct dwarf2_cu *, struct partial_symtab *);
1514
1515 static int dwarf2_get_pc_bounds (struct die_info *,
1516                                  CORE_ADDR *, CORE_ADDR *, struct dwarf2_cu *,
1517                                  struct partial_symtab *);
1518
1519 static void get_scope_pc_bounds (struct die_info *,
1520                                  CORE_ADDR *, CORE_ADDR *,
1521                                  struct dwarf2_cu *);
1522
1523 static void dwarf2_record_block_ranges (struct die_info *, struct block *,
1524                                         CORE_ADDR, struct dwarf2_cu *);
1525
1526 static void dwarf2_add_field (struct field_info *, struct die_info *,
1527                               struct dwarf2_cu *);
1528
1529 static void dwarf2_attach_fields_to_type (struct field_info *,
1530                                           struct type *, struct dwarf2_cu *);
1531
1532 static void dwarf2_add_member_fn (struct field_info *,
1533                                   struct die_info *, struct type *,
1534                                   struct dwarf2_cu *);
1535
1536 static void dwarf2_attach_fn_fields_to_type (struct field_info *,
1537                                              struct type *,
1538                                              struct dwarf2_cu *);
1539
1540 static void process_structure_scope (struct die_info *, struct dwarf2_cu *);
1541
1542 static void read_common_block (struct die_info *, struct dwarf2_cu *);
1543
1544 static void read_namespace (struct die_info *die, struct dwarf2_cu *);
1545
1546 static void read_module (struct die_info *die, struct dwarf2_cu *cu);
1547
1548 static void read_import_statement (struct die_info *die, struct dwarf2_cu *);
1549
1550 static struct type *read_module_type (struct die_info *die,
1551                                       struct dwarf2_cu *cu);
1552
1553 static const char *namespace_name (struct die_info *die,
1554                                    int *is_anonymous, struct dwarf2_cu *);
1555
1556 static void process_enumeration_scope (struct die_info *, struct dwarf2_cu *);
1557
1558 static CORE_ADDR decode_locdesc (struct dwarf_block *, struct dwarf2_cu *);
1559
1560 static enum dwarf_array_dim_ordering read_array_order (struct die_info *,
1561                                                        struct dwarf2_cu *);
1562
1563 static struct die_info *read_die_and_siblings_1
1564   (const struct die_reader_specs *, const gdb_byte *, const gdb_byte **,
1565    struct die_info *);
1566
1567 static struct die_info *read_die_and_siblings (const struct die_reader_specs *,
1568                                                const gdb_byte *info_ptr,
1569                                                const gdb_byte **new_info_ptr,
1570                                                struct die_info *parent);
1571
1572 static const gdb_byte *read_full_die_1 (const struct die_reader_specs *,
1573                                         struct die_info **, const gdb_byte *,
1574                                         int *, int);
1575
1576 static const gdb_byte *read_full_die (const struct die_reader_specs *,
1577                                       struct die_info **, const gdb_byte *,
1578                                       int *);
1579
1580 static void process_die (struct die_info *, struct dwarf2_cu *);
1581
1582 static const char *dwarf2_canonicalize_name (const char *, struct dwarf2_cu *,
1583                                              struct obstack *);
1584
1585 static const char *dwarf2_name (struct die_info *die, struct dwarf2_cu *);
1586
1587 static const char *dwarf2_full_name (const char *name,
1588                                      struct die_info *die,
1589                                      struct dwarf2_cu *cu);
1590
1591 static const char *dwarf2_physname (const char *name, struct die_info *die,
1592                                     struct dwarf2_cu *cu);
1593
1594 static struct die_info *dwarf2_extension (struct die_info *die,
1595                                           struct dwarf2_cu **);
1596
1597 static const char *dwarf_tag_name (unsigned int);
1598
1599 static const char *dwarf_attr_name (unsigned int);
1600
1601 static const char *dwarf_form_name (unsigned int);
1602
1603 static char *dwarf_bool_name (unsigned int);
1604
1605 static const char *dwarf_type_encoding_name (unsigned int);
1606
1607 static struct die_info *sibling_die (struct die_info *);
1608
1609 static void dump_die_shallow (struct ui_file *, int indent, struct die_info *);
1610
1611 static void dump_die_for_error (struct die_info *);
1612
1613 static void dump_die_1 (struct ui_file *, int level, int max_level,
1614                         struct die_info *);
1615
1616 /*static*/ void dump_die (struct die_info *, int max_level);
1617
1618 static void store_in_ref_table (struct die_info *,
1619                                 struct dwarf2_cu *);
1620
1621 static sect_offset dwarf2_get_ref_die_offset (const struct attribute *);
1622
1623 static LONGEST dwarf2_get_attr_constant_value (const struct attribute *, int);
1624
1625 static struct die_info *follow_die_ref_or_sig (struct die_info *,
1626                                                const struct attribute *,
1627                                                struct dwarf2_cu **);
1628
1629 static struct die_info *follow_die_ref (struct die_info *,
1630                                         const struct attribute *,
1631                                         struct dwarf2_cu **);
1632
1633 static struct die_info *follow_die_sig (struct die_info *,
1634                                         const struct attribute *,
1635                                         struct dwarf2_cu **);
1636
1637 static struct type *get_signatured_type (struct die_info *, ULONGEST,
1638                                          struct dwarf2_cu *);
1639
1640 static struct type *get_DW_AT_signature_type (struct die_info *,
1641                                               const struct attribute *,
1642                                               struct dwarf2_cu *);
1643
1644 static void load_full_type_unit (struct dwarf2_per_cu_data *per_cu);
1645
1646 static void read_signatured_type (struct signatured_type *);
1647
1648 static struct type_unit_group *get_type_unit_group
1649     (struct dwarf2_cu *, const struct attribute *);
1650
1651 static void build_type_unit_groups (die_reader_func_ftype *, void *);
1652
1653 /* memory allocation interface */
1654
1655 static struct dwarf_block *dwarf_alloc_block (struct dwarf2_cu *);
1656
1657 static struct die_info *dwarf_alloc_die (struct dwarf2_cu *, int);
1658
1659 static void dwarf_decode_macros (struct dwarf2_cu *, unsigned int,
1660                                  const char *, int);
1661
1662 static int attr_form_is_block (const struct attribute *);
1663
1664 static int attr_form_is_section_offset (const struct attribute *);
1665
1666 static int attr_form_is_constant (const struct attribute *);
1667
1668 static int attr_form_is_ref (const struct attribute *);
1669
1670 static void fill_in_loclist_baton (struct dwarf2_cu *cu,
1671                                    struct dwarf2_loclist_baton *baton,
1672                                    const struct attribute *attr);
1673
1674 static void dwarf2_symbol_mark_computed (const struct attribute *attr,
1675                                          struct symbol *sym,
1676                                          struct dwarf2_cu *cu,
1677                                          int is_block);
1678
1679 static const gdb_byte *skip_one_die (const struct die_reader_specs *reader,
1680                                      const gdb_byte *info_ptr,
1681                                      struct abbrev_info *abbrev);
1682
1683 static void free_stack_comp_unit (void *);
1684
1685 static hashval_t partial_die_hash (const void *item);
1686
1687 static int partial_die_eq (const void *item_lhs, const void *item_rhs);
1688
1689 static struct dwarf2_per_cu_data *dwarf2_find_containing_comp_unit
1690   (sect_offset offset, unsigned int offset_in_dwz, struct objfile *objfile);
1691
1692 static void init_one_comp_unit (struct dwarf2_cu *cu,
1693                                 struct dwarf2_per_cu_data *per_cu);
1694
1695 static void prepare_one_comp_unit (struct dwarf2_cu *cu,
1696                                    struct die_info *comp_unit_die,
1697                                    enum language pretend_language);
1698
1699 static void free_heap_comp_unit (void *);
1700
1701 static void free_cached_comp_units (void *);
1702
1703 static void age_cached_comp_units (void);
1704
1705 static void free_one_cached_comp_unit (struct dwarf2_per_cu_data *);
1706
1707 static struct type *set_die_type (struct die_info *, struct type *,
1708                                   struct dwarf2_cu *);
1709
1710 static void create_all_comp_units (struct objfile *);
1711
1712 static int create_all_type_units (struct objfile *);
1713
1714 static void load_full_comp_unit (struct dwarf2_per_cu_data *,
1715                                  enum language);
1716
1717 static void process_full_comp_unit (struct dwarf2_per_cu_data *,
1718                                     enum language);
1719
1720 static void process_full_type_unit (struct dwarf2_per_cu_data *,
1721                                     enum language);
1722
1723 static void dwarf2_add_dependence (struct dwarf2_cu *,
1724                                    struct dwarf2_per_cu_data *);
1725
1726 static void dwarf2_mark (struct dwarf2_cu *);
1727
1728 static void dwarf2_clear_marks (struct dwarf2_per_cu_data *);
1729
1730 static struct type *get_die_type_at_offset (sect_offset,
1731                                             struct dwarf2_per_cu_data *);
1732
1733 static struct type *get_die_type (struct die_info *die, struct dwarf2_cu *cu);
1734
1735 static void dwarf2_release_queue (void *dummy);
1736
1737 static void queue_comp_unit (struct dwarf2_per_cu_data *per_cu,
1738                              enum language pretend_language);
1739
1740 static int maybe_queue_comp_unit (struct dwarf2_cu *this_cu,
1741                                   struct dwarf2_per_cu_data *per_cu,
1742                                   enum language pretend_language);
1743
1744 static void process_queue (void);
1745
1746 static void find_file_and_directory (struct die_info *die,
1747                                      struct dwarf2_cu *cu,
1748                                      const char **name, const char **comp_dir);
1749
1750 static char *file_full_name (int file, struct line_header *lh,
1751                              const char *comp_dir);
1752
1753 static const gdb_byte *read_and_check_comp_unit_head
1754   (struct comp_unit_head *header,
1755    struct dwarf2_section_info *section,
1756    struct dwarf2_section_info *abbrev_section, const gdb_byte *info_ptr,
1757    int is_debug_types_section);
1758
1759 static void init_cutu_and_read_dies
1760   (struct dwarf2_per_cu_data *this_cu, struct abbrev_table *abbrev_table,
1761    int use_existing_cu, int keep,
1762    die_reader_func_ftype *die_reader_func, void *data);
1763
1764 static void init_cutu_and_read_dies_simple
1765   (struct dwarf2_per_cu_data *this_cu,
1766    die_reader_func_ftype *die_reader_func, void *data);
1767
1768 static htab_t allocate_signatured_type_table (struct objfile *objfile);
1769
1770 static htab_t allocate_dwo_unit_table (struct objfile *objfile);
1771
1772 static struct dwo_unit *lookup_dwo_in_dwp
1773   (struct dwp_file *dwp_file, const struct dwp_hash_table *htab,
1774    const char *comp_dir, ULONGEST signature, int is_debug_types);
1775
1776 static struct dwp_file *get_dwp_file (void);
1777
1778 static struct dwo_unit *lookup_dwo_comp_unit
1779   (struct dwarf2_per_cu_data *, const char *, const char *, ULONGEST);
1780
1781 static struct dwo_unit *lookup_dwo_type_unit
1782   (struct signatured_type *, const char *, const char *);
1783
1784 static void free_dwo_file_cleanup (void *);
1785
1786 static void process_cu_includes (void);
1787
1788 static void check_producer (struct dwarf2_cu *cu);
1789
1790 #if WORDS_BIGENDIAN
1791
1792 /* Convert VALUE between big- and little-endian.  */
1793 static offset_type
1794 byte_swap (offset_type value)
1795 {
1796   offset_type result;
1797
1798   result = (value & 0xff) << 24;
1799   result |= (value & 0xff00) << 8;
1800   result |= (value & 0xff0000) >> 8;
1801   result |= (value & 0xff000000) >> 24;
1802   return result;
1803 }
1804
1805 #define MAYBE_SWAP(V)  byte_swap (V)
1806
1807 #else
1808 #define MAYBE_SWAP(V) (V)
1809 #endif /* WORDS_BIGENDIAN */
1810
1811 /* The suffix for an index file.  */
1812 #define INDEX_SUFFIX ".gdb-index"
1813
1814 /* Try to locate the sections we need for DWARF 2 debugging
1815    information and return true if we have enough to do something.
1816    NAMES points to the dwarf2 section names, or is NULL if the standard
1817    ELF names are used.  */
1818
1819 int
1820 dwarf2_has_info (struct objfile *objfile,
1821                  const struct dwarf2_debug_sections *names)
1822 {
1823   dwarf2_per_objfile = objfile_data (objfile, dwarf2_objfile_data_key);
1824   if (!dwarf2_per_objfile)
1825     {
1826       /* Initialize per-objfile state.  */
1827       struct dwarf2_per_objfile *data
1828         = obstack_alloc (&objfile->objfile_obstack, sizeof (*data));
1829
1830       memset (data, 0, sizeof (*data));
1831       set_objfile_data (objfile, dwarf2_objfile_data_key, data);
1832       dwarf2_per_objfile = data;
1833
1834       bfd_map_over_sections (objfile->obfd, dwarf2_locate_sections,
1835                              (void *) names);
1836       dwarf2_per_objfile->objfile = objfile;
1837     }
1838   return (dwarf2_per_objfile->info.asection != NULL
1839           && dwarf2_per_objfile->abbrev.asection != NULL);
1840 }
1841
1842 /* When loading sections, we look either for uncompressed section or for
1843    compressed section names.  */
1844
1845 static int
1846 section_is_p (const char *section_name,
1847               const struct dwarf2_section_names *names)
1848 {
1849   if (names->normal != NULL
1850       && strcmp (section_name, names->normal) == 0)
1851     return 1;
1852   if (names->compressed != NULL
1853       && strcmp (section_name, names->compressed) == 0)
1854     return 1;
1855   return 0;
1856 }
1857
1858 /* This function is mapped across the sections and remembers the
1859    offset and size of each of the debugging sections we are interested
1860    in.  */
1861
1862 static void
1863 dwarf2_locate_sections (bfd *abfd, asection *sectp, void *vnames)
1864 {
1865   const struct dwarf2_debug_sections *names;
1866   flagword aflag = bfd_get_section_flags (abfd, sectp);
1867
1868   if (vnames == NULL)
1869     names = &dwarf2_elf_names;
1870   else
1871     names = (const struct dwarf2_debug_sections *) vnames;
1872
1873   if ((aflag & SEC_HAS_CONTENTS) == 0)
1874     {
1875     }
1876   else if (section_is_p (sectp->name, &names->info))
1877     {
1878       dwarf2_per_objfile->info.asection = sectp;
1879       dwarf2_per_objfile->info.size = bfd_get_section_size (sectp);
1880     }
1881   else if (section_is_p (sectp->name, &names->abbrev))
1882     {
1883       dwarf2_per_objfile->abbrev.asection = sectp;
1884       dwarf2_per_objfile->abbrev.size = bfd_get_section_size (sectp);
1885     }
1886   else if (section_is_p (sectp->name, &names->line))
1887     {
1888       dwarf2_per_objfile->line.asection = sectp;
1889       dwarf2_per_objfile->line.size = bfd_get_section_size (sectp);
1890     }
1891   else if (section_is_p (sectp->name, &names->loc))
1892     {
1893       dwarf2_per_objfile->loc.asection = sectp;
1894       dwarf2_per_objfile->loc.size = bfd_get_section_size (sectp);
1895     }
1896   else if (section_is_p (sectp->name, &names->macinfo))
1897     {
1898       dwarf2_per_objfile->macinfo.asection = sectp;
1899       dwarf2_per_objfile->macinfo.size = bfd_get_section_size (sectp);
1900     }
1901   else if (section_is_p (sectp->name, &names->macro))
1902     {
1903       dwarf2_per_objfile->macro.asection = sectp;
1904       dwarf2_per_objfile->macro.size = bfd_get_section_size (sectp);
1905     }
1906   else if (section_is_p (sectp->name, &names->str))
1907     {
1908       dwarf2_per_objfile->str.asection = sectp;
1909       dwarf2_per_objfile->str.size = bfd_get_section_size (sectp);
1910     }
1911   else if (section_is_p (sectp->name, &names->addr))
1912     {
1913       dwarf2_per_objfile->addr.asection = sectp;
1914       dwarf2_per_objfile->addr.size = bfd_get_section_size (sectp);
1915     }
1916   else if (section_is_p (sectp->name, &names->frame))
1917     {
1918       dwarf2_per_objfile->frame.asection = sectp;
1919       dwarf2_per_objfile->frame.size = bfd_get_section_size (sectp);
1920     }
1921   else if (section_is_p (sectp->name, &names->eh_frame))
1922     {
1923       dwarf2_per_objfile->eh_frame.asection = sectp;
1924       dwarf2_per_objfile->eh_frame.size = bfd_get_section_size (sectp);
1925     }
1926   else if (section_is_p (sectp->name, &names->ranges))
1927     {
1928       dwarf2_per_objfile->ranges.asection = sectp;
1929       dwarf2_per_objfile->ranges.size = bfd_get_section_size (sectp);
1930     }
1931   else if (section_is_p (sectp->name, &names->types))
1932     {
1933       struct dwarf2_section_info type_section;
1934
1935       memset (&type_section, 0, sizeof (type_section));
1936       type_section.asection = sectp;
1937       type_section.size = bfd_get_section_size (sectp);
1938
1939       VEC_safe_push (dwarf2_section_info_def, dwarf2_per_objfile->types,
1940                      &type_section);
1941     }
1942   else if (section_is_p (sectp->name, &names->gdb_index))
1943     {
1944       dwarf2_per_objfile->gdb_index.asection = sectp;
1945       dwarf2_per_objfile->gdb_index.size = bfd_get_section_size (sectp);
1946     }
1947
1948   if ((bfd_get_section_flags (abfd, sectp) & SEC_LOAD)
1949       && bfd_section_vma (abfd, sectp) == 0)
1950     dwarf2_per_objfile->has_section_at_zero = 1;
1951 }
1952
1953 /* A helper function that decides whether a section is empty,
1954    or not present.  */
1955
1956 static int
1957 dwarf2_section_empty_p (struct dwarf2_section_info *info)
1958 {
1959   return info->asection == NULL || info->size == 0;
1960 }
1961
1962 /* Read the contents of the section INFO.
1963    OBJFILE is the main object file, but not necessarily the file where
1964    the section comes from.  E.g., for DWO files INFO->asection->owner
1965    is the bfd of the DWO file.
1966    If the section is compressed, uncompress it before returning.  */
1967
1968 static void
1969 dwarf2_read_section (struct objfile *objfile, struct dwarf2_section_info *info)
1970 {
1971   asection *sectp = info->asection;
1972   bfd *abfd;
1973   gdb_byte *buf, *retbuf;
1974   unsigned char header[4];
1975
1976   if (info->readin)
1977     return;
1978   info->buffer = NULL;
1979   info->readin = 1;
1980
1981   if (dwarf2_section_empty_p (info))
1982     return;
1983
1984   abfd = sectp->owner;
1985
1986   /* If the section has relocations, we must read it ourselves.
1987      Otherwise we attach it to the BFD.  */
1988   if ((sectp->flags & SEC_RELOC) == 0)
1989     {
1990       info->buffer = gdb_bfd_map_section (sectp, &info->size);
1991       return;
1992     }
1993
1994   buf = obstack_alloc (&objfile->objfile_obstack, info->size);
1995   info->buffer = buf;
1996
1997   /* When debugging .o files, we may need to apply relocations; see
1998      http://sourceware.org/ml/gdb-patches/2002-04/msg00136.html .
1999      We never compress sections in .o files, so we only need to
2000      try this when the section is not compressed.  */
2001   retbuf = symfile_relocate_debug_section (objfile, sectp, buf);
2002   if (retbuf != NULL)
2003     {
2004       info->buffer = retbuf;
2005       return;
2006     }
2007
2008   if (bfd_seek (abfd, sectp->filepos, SEEK_SET) != 0
2009       || bfd_bread (buf, info->size, abfd) != info->size)
2010     error (_("Dwarf Error: Can't read DWARF data from '%s'"),
2011            bfd_get_filename (abfd));
2012 }
2013
2014 /* A helper function that returns the size of a section in a safe way.
2015    If you are positive that the section has been read before using the
2016    size, then it is safe to refer to the dwarf2_section_info object's
2017    "size" field directly.  In other cases, you must call this
2018    function, because for compressed sections the size field is not set
2019    correctly until the section has been read.  */
2020
2021 static bfd_size_type
2022 dwarf2_section_size (struct objfile *objfile,
2023                      struct dwarf2_section_info *info)
2024 {
2025   if (!info->readin)
2026     dwarf2_read_section (objfile, info);
2027   return info->size;
2028 }
2029
2030 /* Fill in SECTP, BUFP and SIZEP with section info, given OBJFILE and
2031    SECTION_NAME.  */
2032
2033 void
2034 dwarf2_get_section_info (struct objfile *objfile,
2035                          enum dwarf2_section_enum sect,
2036                          asection **sectp, const gdb_byte **bufp,
2037                          bfd_size_type *sizep)
2038 {
2039   struct dwarf2_per_objfile *data
2040     = objfile_data (objfile, dwarf2_objfile_data_key);
2041   struct dwarf2_section_info *info;
2042
2043   /* We may see an objfile without any DWARF, in which case we just
2044      return nothing.  */
2045   if (data == NULL)
2046     {
2047       *sectp = NULL;
2048       *bufp = NULL;
2049       *sizep = 0;
2050       return;
2051     }
2052   switch (sect)
2053     {
2054     case DWARF2_DEBUG_FRAME:
2055       info = &data->frame;
2056       break;
2057     case DWARF2_EH_FRAME:
2058       info = &data->eh_frame;
2059       break;
2060     default:
2061       gdb_assert_not_reached ("unexpected section");
2062     }
2063
2064   dwarf2_read_section (objfile, info);
2065
2066   *sectp = info->asection;
2067   *bufp = info->buffer;
2068   *sizep = info->size;
2069 }
2070
2071 /* A helper function to find the sections for a .dwz file.  */
2072
2073 static void
2074 locate_dwz_sections (bfd *abfd, asection *sectp, void *arg)
2075 {
2076   struct dwz_file *dwz_file = arg;
2077
2078   /* Note that we only support the standard ELF names, because .dwz
2079      is ELF-only (at the time of writing).  */
2080   if (section_is_p (sectp->name, &dwarf2_elf_names.abbrev))
2081     {
2082       dwz_file->abbrev.asection = sectp;
2083       dwz_file->abbrev.size = bfd_get_section_size (sectp);
2084     }
2085   else if (section_is_p (sectp->name, &dwarf2_elf_names.info))
2086     {
2087       dwz_file->info.asection = sectp;
2088       dwz_file->info.size = bfd_get_section_size (sectp);
2089     }
2090   else if (section_is_p (sectp->name, &dwarf2_elf_names.str))
2091     {
2092       dwz_file->str.asection = sectp;
2093       dwz_file->str.size = bfd_get_section_size (sectp);
2094     }
2095   else if (section_is_p (sectp->name, &dwarf2_elf_names.line))
2096     {
2097       dwz_file->line.asection = sectp;
2098       dwz_file->line.size = bfd_get_section_size (sectp);
2099     }
2100   else if (section_is_p (sectp->name, &dwarf2_elf_names.macro))
2101     {
2102       dwz_file->macro.asection = sectp;
2103       dwz_file->macro.size = bfd_get_section_size (sectp);
2104     }
2105   else if (section_is_p (sectp->name, &dwarf2_elf_names.gdb_index))
2106     {
2107       dwz_file->gdb_index.asection = sectp;
2108       dwz_file->gdb_index.size = bfd_get_section_size (sectp);
2109     }
2110 }
2111
2112 /* Open the separate '.dwz' debug file, if needed.  Return NULL if
2113    there is no .gnu_debugaltlink section in the file.  Error if there
2114    is such a section but the file cannot be found.  */
2115
2116 static struct dwz_file *
2117 dwarf2_get_dwz_file (void)
2118 {
2119   bfd *dwz_bfd;
2120   char *data;
2121   struct cleanup *cleanup;
2122   const char *filename;
2123   struct dwz_file *result;
2124   unsigned long buildid;
2125
2126   if (dwarf2_per_objfile->dwz_file != NULL)
2127     return dwarf2_per_objfile->dwz_file;
2128
2129   bfd_set_error (bfd_error_no_error);
2130   data = bfd_get_alt_debug_link_info (dwarf2_per_objfile->objfile->obfd,
2131                                       &buildid);
2132   if (data == NULL)
2133     {
2134       if (bfd_get_error () == bfd_error_no_error)
2135         return NULL;
2136       error (_("could not read '.gnu_debugaltlink' section: %s"),
2137              bfd_errmsg (bfd_get_error ()));
2138     }
2139   cleanup = make_cleanup (xfree, data);
2140
2141   filename = (const char *) data;
2142   if (!IS_ABSOLUTE_PATH (filename))
2143     {
2144       char *abs = gdb_realpath (dwarf2_per_objfile->objfile->name);
2145       char *rel;
2146
2147       make_cleanup (xfree, abs);
2148       abs = ldirname (abs);
2149       make_cleanup (xfree, abs);
2150
2151       rel = concat (abs, SLASH_STRING, filename, (char *) NULL);
2152       make_cleanup (xfree, rel);
2153       filename = rel;
2154     }
2155
2156   /* The format is just a NUL-terminated file name, followed by the
2157      build-id.  For now, though, we ignore the build-id.  */
2158   dwz_bfd = gdb_bfd_open (filename, gnutarget, -1);
2159   if (dwz_bfd == NULL)
2160     error (_("could not read '%s': %s"), filename,
2161            bfd_errmsg (bfd_get_error ()));
2162
2163   if (!bfd_check_format (dwz_bfd, bfd_object))
2164     {
2165       gdb_bfd_unref (dwz_bfd);
2166       error (_("file '%s' was not usable: %s"), filename,
2167              bfd_errmsg (bfd_get_error ()));
2168     }
2169
2170   result = OBSTACK_ZALLOC (&dwarf2_per_objfile->objfile->objfile_obstack,
2171                            struct dwz_file);
2172   result->dwz_bfd = dwz_bfd;
2173
2174   bfd_map_over_sections (dwz_bfd, locate_dwz_sections, result);
2175
2176   do_cleanups (cleanup);
2177
2178   dwarf2_per_objfile->dwz_file = result;
2179   return result;
2180 }
2181 \f
2182 /* DWARF quick_symbols_functions support.  */
2183
2184 /* TUs can share .debug_line entries, and there can be a lot more TUs than
2185    unique line tables, so we maintain a separate table of all .debug_line
2186    derived entries to support the sharing.
2187    All the quick functions need is the list of file names.  We discard the
2188    line_header when we're done and don't need to record it here.  */
2189 struct quick_file_names
2190 {
2191   /* The data used to construct the hash key.  */
2192   struct stmt_list_hash hash;
2193
2194   /* The number of entries in file_names, real_names.  */
2195   unsigned int num_file_names;
2196
2197   /* The file names from the line table, after being run through
2198      file_full_name.  */
2199   const char **file_names;
2200
2201   /* The file names from the line table after being run through
2202      gdb_realpath.  These are computed lazily.  */
2203   const char **real_names;
2204 };
2205
2206 /* When using the index (and thus not using psymtabs), each CU has an
2207    object of this type.  This is used to hold information needed by
2208    the various "quick" methods.  */
2209 struct dwarf2_per_cu_quick_data
2210 {
2211   /* The file table.  This can be NULL if there was no file table
2212      or it's currently not read in.
2213      NOTE: This points into dwarf2_per_objfile->quick_file_names_table.  */
2214   struct quick_file_names *file_names;
2215
2216   /* The corresponding symbol table.  This is NULL if symbols for this
2217      CU have not yet been read.  */
2218   struct symtab *symtab;
2219
2220   /* A temporary mark bit used when iterating over all CUs in
2221      expand_symtabs_matching.  */
2222   unsigned int mark : 1;
2223
2224   /* True if we've tried to read the file table and found there isn't one.
2225      There will be no point in trying to read it again next time.  */
2226   unsigned int no_file_data : 1;
2227 };
2228
2229 /* Utility hash function for a stmt_list_hash.  */
2230
2231 static hashval_t
2232 hash_stmt_list_entry (const struct stmt_list_hash *stmt_list_hash)
2233 {
2234   hashval_t v = 0;
2235
2236   if (stmt_list_hash->dwo_unit != NULL)
2237     v += (uintptr_t) stmt_list_hash->dwo_unit->dwo_file;
2238   v += stmt_list_hash->line_offset.sect_off;
2239   return v;
2240 }
2241
2242 /* Utility equality function for a stmt_list_hash.  */
2243
2244 static int
2245 eq_stmt_list_entry (const struct stmt_list_hash *lhs,
2246                     const struct stmt_list_hash *rhs)
2247 {
2248   if ((lhs->dwo_unit != NULL) != (rhs->dwo_unit != NULL))
2249     return 0;
2250   if (lhs->dwo_unit != NULL
2251       && lhs->dwo_unit->dwo_file != rhs->dwo_unit->dwo_file)
2252     return 0;
2253
2254   return lhs->line_offset.sect_off == rhs->line_offset.sect_off;
2255 }
2256
2257 /* Hash function for a quick_file_names.  */
2258
2259 static hashval_t
2260 hash_file_name_entry (const void *e)
2261 {
2262   const struct quick_file_names *file_data = e;
2263
2264   return hash_stmt_list_entry (&file_data->hash);
2265 }
2266
2267 /* Equality function for a quick_file_names.  */
2268
2269 static int
2270 eq_file_name_entry (const void *a, const void *b)
2271 {
2272   const struct quick_file_names *ea = a;
2273   const struct quick_file_names *eb = b;
2274
2275   return eq_stmt_list_entry (&ea->hash, &eb->hash);
2276 }
2277
2278 /* Delete function for a quick_file_names.  */
2279
2280 static void
2281 delete_file_name_entry (void *e)
2282 {
2283   struct quick_file_names *file_data = e;
2284   int i;
2285
2286   for (i = 0; i < file_data->num_file_names; ++i)
2287     {
2288       xfree ((void*) file_data->file_names[i]);
2289       if (file_data->real_names)
2290         xfree ((void*) file_data->real_names[i]);
2291     }
2292
2293   /* The space for the struct itself lives on objfile_obstack,
2294      so we don't free it here.  */
2295 }
2296
2297 /* Create a quick_file_names hash table.  */
2298
2299 static htab_t
2300 create_quick_file_names_table (unsigned int nr_initial_entries)
2301 {
2302   return htab_create_alloc (nr_initial_entries,
2303                             hash_file_name_entry, eq_file_name_entry,
2304                             delete_file_name_entry, xcalloc, xfree);
2305 }
2306
2307 /* Read in PER_CU->CU.  This function is unrelated to symtabs, symtab would
2308    have to be created afterwards.  You should call age_cached_comp_units after
2309    processing PER_CU->CU.  dw2_setup must have been already called.  */
2310
2311 static void
2312 load_cu (struct dwarf2_per_cu_data *per_cu)
2313 {
2314   if (per_cu->is_debug_types)
2315     load_full_type_unit (per_cu);
2316   else
2317     load_full_comp_unit (per_cu, language_minimal);
2318
2319   gdb_assert (per_cu->cu != NULL);
2320
2321   dwarf2_find_base_address (per_cu->cu->dies, per_cu->cu);
2322 }
2323
2324 /* Read in the symbols for PER_CU.  */
2325
2326 static void
2327 dw2_do_instantiate_symtab (struct dwarf2_per_cu_data *per_cu)
2328 {
2329   struct cleanup *back_to;
2330
2331   /* Skip type_unit_groups, reading the type units they contain
2332      is handled elsewhere.  */
2333   if (IS_TYPE_UNIT_GROUP (per_cu))
2334     return;
2335
2336   back_to = make_cleanup (dwarf2_release_queue, NULL);
2337
2338   if (dwarf2_per_objfile->using_index
2339       ? per_cu->v.quick->symtab == NULL
2340       : (per_cu->v.psymtab == NULL || !per_cu->v.psymtab->readin))
2341     {
2342       queue_comp_unit (per_cu, language_minimal);
2343       load_cu (per_cu);
2344     }
2345
2346   process_queue ();
2347
2348   /* Age the cache, releasing compilation units that have not
2349      been used recently.  */
2350   age_cached_comp_units ();
2351
2352   do_cleanups (back_to);
2353 }
2354
2355 /* Ensure that the symbols for PER_CU have been read in.  OBJFILE is
2356    the objfile from which this CU came.  Returns the resulting symbol
2357    table.  */
2358
2359 static struct symtab *
2360 dw2_instantiate_symtab (struct dwarf2_per_cu_data *per_cu)
2361 {
2362   gdb_assert (dwarf2_per_objfile->using_index);
2363   if (!per_cu->v.quick->symtab)
2364     {
2365       struct cleanup *back_to = make_cleanup (free_cached_comp_units, NULL);
2366       increment_reading_symtab ();
2367       dw2_do_instantiate_symtab (per_cu);
2368       process_cu_includes ();
2369       do_cleanups (back_to);
2370     }
2371   return per_cu->v.quick->symtab;
2372 }
2373
2374 /* Return the CU given its index.
2375
2376    This is intended for loops like:
2377
2378    for (i = 0; i < (dwarf2_per_objfile->n_comp_units
2379                     + dwarf2_per_objfile->n_type_units); ++i)
2380      {
2381        struct dwarf2_per_cu_data *per_cu = dw2_get_cu (i);
2382
2383        ...;
2384      }
2385 */
2386
2387 static struct dwarf2_per_cu_data *
2388 dw2_get_cu (int index)
2389 {
2390   if (index >= dwarf2_per_objfile->n_comp_units)
2391     {
2392       index -= dwarf2_per_objfile->n_comp_units;
2393       gdb_assert (index < dwarf2_per_objfile->n_type_units);
2394       return &dwarf2_per_objfile->all_type_units[index]->per_cu;
2395     }
2396
2397   return dwarf2_per_objfile->all_comp_units[index];
2398 }
2399
2400 /* Return the primary CU given its index.
2401    The difference between this function and dw2_get_cu is in the handling
2402    of type units (TUs).  Here we return the type_unit_group object.
2403
2404    This is intended for loops like:
2405
2406    for (i = 0; i < (dwarf2_per_objfile->n_comp_units
2407                     + dwarf2_per_objfile->n_type_unit_groups); ++i)
2408      {
2409        struct dwarf2_per_cu_data *per_cu = dw2_get_primary_cu (i);
2410
2411        ...;
2412      }
2413 */
2414
2415 static struct dwarf2_per_cu_data *
2416 dw2_get_primary_cu (int index)
2417 {
2418   if (index >= dwarf2_per_objfile->n_comp_units)
2419     {
2420       index -= dwarf2_per_objfile->n_comp_units;
2421       gdb_assert (index < dwarf2_per_objfile->n_type_unit_groups);
2422       return &dwarf2_per_objfile->all_type_unit_groups[index]->per_cu;
2423     }
2424
2425   return dwarf2_per_objfile->all_comp_units[index];
2426 }
2427
2428 /* A helper for create_cus_from_index that handles a given list of
2429    CUs.  */
2430
2431 static void
2432 create_cus_from_index_list (struct objfile *objfile,
2433                             const gdb_byte *cu_list, offset_type n_elements,
2434                             struct dwarf2_section_info *section,
2435                             int is_dwz,
2436                             int base_offset)
2437 {
2438   offset_type i;
2439
2440   for (i = 0; i < n_elements; i += 2)
2441     {
2442       struct dwarf2_per_cu_data *the_cu;
2443       ULONGEST offset, length;
2444
2445       gdb_static_assert (sizeof (ULONGEST) >= 8);
2446       offset = extract_unsigned_integer (cu_list, 8, BFD_ENDIAN_LITTLE);
2447       length = extract_unsigned_integer (cu_list + 8, 8, BFD_ENDIAN_LITTLE);
2448       cu_list += 2 * 8;
2449
2450       the_cu = OBSTACK_ZALLOC (&objfile->objfile_obstack,
2451                                struct dwarf2_per_cu_data);
2452       the_cu->offset.sect_off = offset;
2453       the_cu->length = length;
2454       the_cu->objfile = objfile;
2455       the_cu->section = section;
2456       the_cu->v.quick = OBSTACK_ZALLOC (&objfile->objfile_obstack,
2457                                         struct dwarf2_per_cu_quick_data);
2458       the_cu->is_dwz = is_dwz;
2459       dwarf2_per_objfile->all_comp_units[base_offset + i / 2] = the_cu;
2460     }
2461 }
2462
2463 /* Read the CU list from the mapped index, and use it to create all
2464    the CU objects for this objfile.  */
2465
2466 static void
2467 create_cus_from_index (struct objfile *objfile,
2468                        const gdb_byte *cu_list, offset_type cu_list_elements,
2469                        const gdb_byte *dwz_list, offset_type dwz_elements)
2470 {
2471   struct dwz_file *dwz;
2472
2473   dwarf2_per_objfile->n_comp_units = (cu_list_elements + dwz_elements) / 2;
2474   dwarf2_per_objfile->all_comp_units
2475     = obstack_alloc (&objfile->objfile_obstack,
2476                      dwarf2_per_objfile->n_comp_units
2477                      * sizeof (struct dwarf2_per_cu_data *));
2478
2479   create_cus_from_index_list (objfile, cu_list, cu_list_elements,
2480                               &dwarf2_per_objfile->info, 0, 0);
2481
2482   if (dwz_elements == 0)
2483     return;
2484
2485   dwz = dwarf2_get_dwz_file ();
2486   create_cus_from_index_list (objfile, dwz_list, dwz_elements, &dwz->info, 1,
2487                               cu_list_elements / 2);
2488 }
2489
2490 /* Create the signatured type hash table from the index.  */
2491
2492 static void
2493 create_signatured_type_table_from_index (struct objfile *objfile,
2494                                          struct dwarf2_section_info *section,
2495                                          const gdb_byte *bytes,
2496                                          offset_type elements)
2497 {
2498   offset_type i;
2499   htab_t sig_types_hash;
2500
2501   dwarf2_per_objfile->n_type_units = elements / 3;
2502   dwarf2_per_objfile->all_type_units
2503     = xmalloc (dwarf2_per_objfile->n_type_units
2504                * sizeof (struct signatured_type *));
2505
2506   sig_types_hash = allocate_signatured_type_table (objfile);
2507
2508   for (i = 0; i < elements; i += 3)
2509     {
2510       struct signatured_type *sig_type;
2511       ULONGEST offset, type_offset_in_tu, signature;
2512       void **slot;
2513
2514       gdb_static_assert (sizeof (ULONGEST) >= 8);
2515       offset = extract_unsigned_integer (bytes, 8, BFD_ENDIAN_LITTLE);
2516       type_offset_in_tu = extract_unsigned_integer (bytes + 8, 8,
2517                                                     BFD_ENDIAN_LITTLE);
2518       signature = extract_unsigned_integer (bytes + 16, 8, BFD_ENDIAN_LITTLE);
2519       bytes += 3 * 8;
2520
2521       sig_type = OBSTACK_ZALLOC (&objfile->objfile_obstack,
2522                                  struct signatured_type);
2523       sig_type->signature = signature;
2524       sig_type->type_offset_in_tu.cu_off = type_offset_in_tu;
2525       sig_type->per_cu.is_debug_types = 1;
2526       sig_type->per_cu.section = section;
2527       sig_type->per_cu.offset.sect_off = offset;
2528       sig_type->per_cu.objfile = objfile;
2529       sig_type->per_cu.v.quick
2530         = OBSTACK_ZALLOC (&objfile->objfile_obstack,
2531                           struct dwarf2_per_cu_quick_data);
2532
2533       slot = htab_find_slot (sig_types_hash, sig_type, INSERT);
2534       *slot = sig_type;
2535
2536       dwarf2_per_objfile->all_type_units[i / 3] = sig_type;
2537     }
2538
2539   dwarf2_per_objfile->signatured_types = sig_types_hash;
2540 }
2541
2542 /* Read the address map data from the mapped index, and use it to
2543    populate the objfile's psymtabs_addrmap.  */
2544
2545 static void
2546 create_addrmap_from_index (struct objfile *objfile, struct mapped_index *index)
2547 {
2548   const gdb_byte *iter, *end;
2549   struct obstack temp_obstack;
2550   struct addrmap *mutable_map;
2551   struct cleanup *cleanup;
2552   CORE_ADDR baseaddr;
2553
2554   obstack_init (&temp_obstack);
2555   cleanup = make_cleanup_obstack_free (&temp_obstack);
2556   mutable_map = addrmap_create_mutable (&temp_obstack);
2557
2558   iter = index->address_table;
2559   end = iter + index->address_table_size;
2560
2561   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
2562
2563   while (iter < end)
2564     {
2565       ULONGEST hi, lo, cu_index;
2566       lo = extract_unsigned_integer (iter, 8, BFD_ENDIAN_LITTLE);
2567       iter += 8;
2568       hi = extract_unsigned_integer (iter, 8, BFD_ENDIAN_LITTLE);
2569       iter += 8;
2570       cu_index = extract_unsigned_integer (iter, 4, BFD_ENDIAN_LITTLE);
2571       iter += 4;
2572
2573       if (cu_index < dwarf2_per_objfile->n_comp_units)
2574         {
2575           addrmap_set_empty (mutable_map, lo + baseaddr, hi + baseaddr - 1,
2576                              dw2_get_cu (cu_index));
2577         }
2578       else
2579         {
2580           complaint (&symfile_complaints,
2581                      _(".gdb_index address table has invalid CU number %u"),
2582                      (unsigned) cu_index);
2583         }
2584     }
2585
2586   objfile->psymtabs_addrmap = addrmap_create_fixed (mutable_map,
2587                                                     &objfile->objfile_obstack);
2588   do_cleanups (cleanup);
2589 }
2590
2591 /* The hash function for strings in the mapped index.  This is the same as
2592    SYMBOL_HASH_NEXT, but we keep a separate copy to maintain control over the
2593    implementation.  This is necessary because the hash function is tied to the
2594    format of the mapped index file.  The hash values do not have to match with
2595    SYMBOL_HASH_NEXT.
2596    
2597    Use INT_MAX for INDEX_VERSION if you generate the current index format.  */
2598
2599 static hashval_t
2600 mapped_index_string_hash (int index_version, const void *p)
2601 {
2602   const unsigned char *str = (const unsigned char *) p;
2603   hashval_t r = 0;
2604   unsigned char c;
2605
2606   while ((c = *str++) != 0)
2607     {
2608       if (index_version >= 5)
2609         c = tolower (c);
2610       r = r * 67 + c - 113;
2611     }
2612
2613   return r;
2614 }
2615
2616 /* Find a slot in the mapped index INDEX for the object named NAME.
2617    If NAME is found, set *VEC_OUT to point to the CU vector in the
2618    constant pool and return 1.  If NAME cannot be found, return 0.  */
2619
2620 static int
2621 find_slot_in_mapped_hash (struct mapped_index *index, const char *name,
2622                           offset_type **vec_out)
2623 {
2624   struct cleanup *back_to = make_cleanup (null_cleanup, 0);
2625   offset_type hash;
2626   offset_type slot, step;
2627   int (*cmp) (const char *, const char *);
2628
2629   if (current_language->la_language == language_cplus
2630       || current_language->la_language == language_java
2631       || current_language->la_language == language_fortran)
2632     {
2633       /* NAME is already canonical.  Drop any qualifiers as .gdb_index does
2634          not contain any.  */
2635       const char *paren = strchr (name, '(');
2636
2637       if (paren)
2638         {
2639           char *dup;
2640
2641           dup = xmalloc (paren - name + 1);
2642           memcpy (dup, name, paren - name);
2643           dup[paren - name] = 0;
2644
2645           make_cleanup (xfree, dup);
2646           name = dup;
2647         }
2648     }
2649
2650   /* Index version 4 did not support case insensitive searches.  But the
2651      indices for case insensitive languages are built in lowercase, therefore
2652      simulate our NAME being searched is also lowercased.  */
2653   hash = mapped_index_string_hash ((index->version == 4
2654                                     && case_sensitivity == case_sensitive_off
2655                                     ? 5 : index->version),
2656                                    name);
2657
2658   slot = hash & (index->symbol_table_slots - 1);
2659   step = ((hash * 17) & (index->symbol_table_slots - 1)) | 1;
2660   cmp = (case_sensitivity == case_sensitive_on ? strcmp : strcasecmp);
2661
2662   for (;;)
2663     {
2664       /* Convert a slot number to an offset into the table.  */
2665       offset_type i = 2 * slot;
2666       const char *str;
2667       if (index->symbol_table[i] == 0 && index->symbol_table[i + 1] == 0)
2668         {
2669           do_cleanups (back_to);
2670           return 0;
2671         }
2672
2673       str = index->constant_pool + MAYBE_SWAP (index->symbol_table[i]);
2674       if (!cmp (name, str))
2675         {
2676           *vec_out = (offset_type *) (index->constant_pool
2677                                       + MAYBE_SWAP (index->symbol_table[i + 1]));
2678           do_cleanups (back_to);
2679           return 1;
2680         }
2681
2682       slot = (slot + step) & (index->symbol_table_slots - 1);
2683     }
2684 }
2685
2686 /* A helper function that reads the .gdb_index from SECTION and fills
2687    in MAP.  FILENAME is the name of the file containing the section;
2688    it is used for error reporting.  DEPRECATED_OK is nonzero if it is
2689    ok to use deprecated sections.
2690
2691    CU_LIST, CU_LIST_ELEMENTS, TYPES_LIST, and TYPES_LIST_ELEMENTS are
2692    out parameters that are filled in with information about the CU and
2693    TU lists in the section.
2694
2695    Returns 1 if all went well, 0 otherwise.  */
2696
2697 static int
2698 read_index_from_section (struct objfile *objfile,
2699                          const char *filename,
2700                          int deprecated_ok,
2701                          struct dwarf2_section_info *section,
2702                          struct mapped_index *map,
2703                          const gdb_byte **cu_list,
2704                          offset_type *cu_list_elements,
2705                          const gdb_byte **types_list,
2706                          offset_type *types_list_elements)
2707 {
2708   const gdb_byte *addr;
2709   offset_type version;
2710   offset_type *metadata;
2711   int i;
2712
2713   if (dwarf2_section_empty_p (section))
2714     return 0;
2715
2716   /* Older elfutils strip versions could keep the section in the main
2717      executable while splitting it for the separate debug info file.  */
2718   if ((bfd_get_file_flags (section->asection) & SEC_HAS_CONTENTS) == 0)
2719     return 0;
2720
2721   dwarf2_read_section (objfile, section);
2722
2723   addr = section->buffer;
2724   /* Version check.  */
2725   version = MAYBE_SWAP (*(offset_type *) addr);
2726   /* Versions earlier than 3 emitted every copy of a psymbol.  This
2727      causes the index to behave very poorly for certain requests.  Version 3
2728      contained incomplete addrmap.  So, it seems better to just ignore such
2729      indices.  */
2730   if (version < 4)
2731     {
2732       static int warning_printed = 0;
2733       if (!warning_printed)
2734         {
2735           warning (_("Skipping obsolete .gdb_index section in %s."),
2736                    filename);
2737           warning_printed = 1;
2738         }
2739       return 0;
2740     }
2741   /* Index version 4 uses a different hash function than index version
2742      5 and later.
2743
2744      Versions earlier than 6 did not emit psymbols for inlined
2745      functions.  Using these files will cause GDB not to be able to
2746      set breakpoints on inlined functions by name, so we ignore these
2747      indices unless the user has done
2748      "set use-deprecated-index-sections on".  */
2749   if (version < 6 && !deprecated_ok)
2750     {
2751       static int warning_printed = 0;
2752       if (!warning_printed)
2753         {
2754           warning (_("\
2755 Skipping deprecated .gdb_index section in %s.\n\
2756 Do \"set use-deprecated-index-sections on\" before the file is read\n\
2757 to use the section anyway."),
2758                    filename);
2759           warning_printed = 1;
2760         }
2761       return 0;
2762     }
2763   /* Version 7 indices generated by gold refer to the CU for a symbol instead
2764      of the TU (for symbols coming from TUs).  It's just a performance bug, and
2765      we can't distinguish gdb-generated indices from gold-generated ones, so
2766      nothing to do here.  */
2767
2768   /* Indexes with higher version than the one supported by GDB may be no
2769      longer backward compatible.  */
2770   if (version > 8)
2771     return 0;
2772
2773   map->version = version;
2774   map->total_size = section->size;
2775
2776   metadata = (offset_type *) (addr + sizeof (offset_type));
2777
2778   i = 0;
2779   *cu_list = addr + MAYBE_SWAP (metadata[i]);
2780   *cu_list_elements = ((MAYBE_SWAP (metadata[i + 1]) - MAYBE_SWAP (metadata[i]))
2781                        / 8);
2782   ++i;
2783
2784   *types_list = addr + MAYBE_SWAP (metadata[i]);
2785   *types_list_elements = ((MAYBE_SWAP (metadata[i + 1])
2786                            - MAYBE_SWAP (metadata[i]))
2787                           / 8);
2788   ++i;
2789
2790   map->address_table = addr + MAYBE_SWAP (metadata[i]);
2791   map->address_table_size = (MAYBE_SWAP (metadata[i + 1])
2792                              - MAYBE_SWAP (metadata[i]));
2793   ++i;
2794
2795   map->symbol_table = (offset_type *) (addr + MAYBE_SWAP (metadata[i]));
2796   map->symbol_table_slots = ((MAYBE_SWAP (metadata[i + 1])
2797                               - MAYBE_SWAP (metadata[i]))
2798                              / (2 * sizeof (offset_type)));
2799   ++i;
2800
2801   map->constant_pool = (char *) (addr + MAYBE_SWAP (metadata[i]));
2802
2803   return 1;
2804 }
2805
2806
2807 /* Read the index file.  If everything went ok, initialize the "quick"
2808    elements of all the CUs and return 1.  Otherwise, return 0.  */
2809
2810 static int
2811 dwarf2_read_index (struct objfile *objfile)
2812 {
2813   struct mapped_index local_map, *map;
2814   const gdb_byte *cu_list, *types_list, *dwz_list = NULL;
2815   offset_type cu_list_elements, types_list_elements, dwz_list_elements = 0;
2816   struct dwz_file *dwz;
2817
2818   if (!read_index_from_section (objfile, objfile->name,
2819                                 use_deprecated_index_sections,
2820                                 &dwarf2_per_objfile->gdb_index, &local_map,
2821                                 &cu_list, &cu_list_elements,
2822                                 &types_list, &types_list_elements))
2823     return 0;
2824
2825   /* Don't use the index if it's empty.  */
2826   if (local_map.symbol_table_slots == 0)
2827     return 0;
2828
2829   /* If there is a .dwz file, read it so we can get its CU list as
2830      well.  */
2831   dwz = dwarf2_get_dwz_file ();
2832   if (dwz != NULL)
2833     {
2834       struct mapped_index dwz_map;
2835       const gdb_byte *dwz_types_ignore;
2836       offset_type dwz_types_elements_ignore;
2837
2838       if (!read_index_from_section (objfile, bfd_get_filename (dwz->dwz_bfd),
2839                                     1,
2840                                     &dwz->gdb_index, &dwz_map,
2841                                     &dwz_list, &dwz_list_elements,
2842                                     &dwz_types_ignore,
2843                                     &dwz_types_elements_ignore))
2844         {
2845           warning (_("could not read '.gdb_index' section from %s; skipping"),
2846                    bfd_get_filename (dwz->dwz_bfd));
2847           return 0;
2848         }
2849     }
2850
2851   create_cus_from_index (objfile, cu_list, cu_list_elements, dwz_list,
2852                          dwz_list_elements);
2853
2854   if (types_list_elements)
2855     {
2856       struct dwarf2_section_info *section;
2857
2858       /* We can only handle a single .debug_types when we have an
2859          index.  */
2860       if (VEC_length (dwarf2_section_info_def, dwarf2_per_objfile->types) != 1)
2861         return 0;
2862
2863       section = VEC_index (dwarf2_section_info_def,
2864                            dwarf2_per_objfile->types, 0);
2865
2866       create_signatured_type_table_from_index (objfile, section, types_list,
2867                                                types_list_elements);
2868     }
2869
2870   create_addrmap_from_index (objfile, &local_map);
2871
2872   map = obstack_alloc (&objfile->objfile_obstack, sizeof (struct mapped_index));
2873   *map = local_map;
2874
2875   dwarf2_per_objfile->index_table = map;
2876   dwarf2_per_objfile->using_index = 1;
2877   dwarf2_per_objfile->quick_file_names_table =
2878     create_quick_file_names_table (dwarf2_per_objfile->n_comp_units);
2879
2880   return 1;
2881 }
2882
2883 /* A helper for the "quick" functions which sets the global
2884    dwarf2_per_objfile according to OBJFILE.  */
2885
2886 static void
2887 dw2_setup (struct objfile *objfile)
2888 {
2889   dwarf2_per_objfile = objfile_data (objfile, dwarf2_objfile_data_key);
2890   gdb_assert (dwarf2_per_objfile);
2891 }
2892
2893 /* die_reader_func for dw2_get_file_names.  */
2894
2895 static void
2896 dw2_get_file_names_reader (const struct die_reader_specs *reader,
2897                            const gdb_byte *info_ptr,
2898                            struct die_info *comp_unit_die,
2899                            int has_children,
2900                            void *data)
2901 {
2902   struct dwarf2_cu *cu = reader->cu;
2903   struct dwarf2_per_cu_data *this_cu = cu->per_cu;  
2904   struct objfile *objfile = dwarf2_per_objfile->objfile;
2905   struct dwarf2_per_cu_data *lh_cu;
2906   struct line_header *lh;
2907   struct attribute *attr;
2908   int i;
2909   const char *name, *comp_dir;
2910   void **slot;
2911   struct quick_file_names *qfn;
2912   unsigned int line_offset;
2913
2914   gdb_assert (! this_cu->is_debug_types);
2915
2916   /* Our callers never want to match partial units -- instead they
2917      will match the enclosing full CU.  */
2918   if (comp_unit_die->tag == DW_TAG_partial_unit)
2919     {
2920       this_cu->v.quick->no_file_data = 1;
2921       return;
2922     }
2923
2924   lh_cu = this_cu;
2925   lh = NULL;
2926   slot = NULL;
2927   line_offset = 0;
2928
2929   attr = dwarf2_attr (comp_unit_die, DW_AT_stmt_list, cu);
2930   if (attr)
2931     {
2932       struct quick_file_names find_entry;
2933
2934       line_offset = DW_UNSND (attr);
2935
2936       /* We may have already read in this line header (TU line header sharing).
2937          If we have we're done.  */
2938       find_entry.hash.dwo_unit = cu->dwo_unit;
2939       find_entry.hash.line_offset.sect_off = line_offset;
2940       slot = htab_find_slot (dwarf2_per_objfile->quick_file_names_table,
2941                              &find_entry, INSERT);
2942       if (*slot != NULL)
2943         {
2944           lh_cu->v.quick->file_names = *slot;
2945           return;
2946         }
2947
2948       lh = dwarf_decode_line_header (line_offset, cu);
2949     }
2950   if (lh == NULL)
2951     {
2952       lh_cu->v.quick->no_file_data = 1;
2953       return;
2954     }
2955
2956   qfn = obstack_alloc (&objfile->objfile_obstack, sizeof (*qfn));
2957   qfn->hash.dwo_unit = cu->dwo_unit;
2958   qfn->hash.line_offset.sect_off = line_offset;
2959   gdb_assert (slot != NULL);
2960   *slot = qfn;
2961
2962   find_file_and_directory (comp_unit_die, cu, &name, &comp_dir);
2963
2964   qfn->num_file_names = lh->num_file_names;
2965   qfn->file_names = obstack_alloc (&objfile->objfile_obstack,
2966                                    lh->num_file_names * sizeof (char *));
2967   for (i = 0; i < lh->num_file_names; ++i)
2968     qfn->file_names[i] = file_full_name (i + 1, lh, comp_dir);
2969   qfn->real_names = NULL;
2970
2971   free_line_header (lh);
2972
2973   lh_cu->v.quick->file_names = qfn;
2974 }
2975
2976 /* A helper for the "quick" functions which attempts to read the line
2977    table for THIS_CU.  */
2978
2979 static struct quick_file_names *
2980 dw2_get_file_names (struct dwarf2_per_cu_data *this_cu)
2981 {
2982   /* This should never be called for TUs.  */
2983   gdb_assert (! this_cu->is_debug_types);
2984   /* Nor type unit groups.  */
2985   gdb_assert (! IS_TYPE_UNIT_GROUP (this_cu));
2986
2987   if (this_cu->v.quick->file_names != NULL)
2988     return this_cu->v.quick->file_names;
2989   /* If we know there is no line data, no point in looking again.  */
2990   if (this_cu->v.quick->no_file_data)
2991     return NULL;
2992
2993   init_cutu_and_read_dies_simple (this_cu, dw2_get_file_names_reader, NULL);
2994
2995   if (this_cu->v.quick->no_file_data)
2996     return NULL;
2997   return this_cu->v.quick->file_names;
2998 }
2999
3000 /* A helper for the "quick" functions which computes and caches the
3001    real path for a given file name from the line table.  */
3002
3003 static const char *
3004 dw2_get_real_path (struct objfile *objfile,
3005                    struct quick_file_names *qfn, int index)
3006 {
3007   if (qfn->real_names == NULL)
3008     qfn->real_names = OBSTACK_CALLOC (&objfile->objfile_obstack,
3009                                       qfn->num_file_names, sizeof (char *));
3010
3011   if (qfn->real_names[index] == NULL)
3012     qfn->real_names[index] = gdb_realpath (qfn->file_names[index]);
3013
3014   return qfn->real_names[index];
3015 }
3016
3017 static struct symtab *
3018 dw2_find_last_source_symtab (struct objfile *objfile)
3019 {
3020   int index;
3021
3022   dw2_setup (objfile);
3023   index = dwarf2_per_objfile->n_comp_units - 1;
3024   return dw2_instantiate_symtab (dw2_get_cu (index));
3025 }
3026
3027 /* Traversal function for dw2_forget_cached_source_info.  */
3028
3029 static int
3030 dw2_free_cached_file_names (void **slot, void *info)
3031 {
3032   struct quick_file_names *file_data = (struct quick_file_names *) *slot;
3033
3034   if (file_data->real_names)
3035     {
3036       int i;
3037
3038       for (i = 0; i < file_data->num_file_names; ++i)
3039         {
3040           xfree ((void*) file_data->real_names[i]);
3041           file_data->real_names[i] = NULL;
3042         }
3043     }
3044
3045   return 1;
3046 }
3047
3048 static void
3049 dw2_forget_cached_source_info (struct objfile *objfile)
3050 {
3051   dw2_setup (objfile);
3052
3053   htab_traverse_noresize (dwarf2_per_objfile->quick_file_names_table,
3054                           dw2_free_cached_file_names, NULL);
3055 }
3056
3057 /* Helper function for dw2_map_symtabs_matching_filename that expands
3058    the symtabs and calls the iterator.  */
3059
3060 static int
3061 dw2_map_expand_apply (struct objfile *objfile,
3062                       struct dwarf2_per_cu_data *per_cu,
3063                       const char *name, const char *real_path,
3064                       int (*callback) (struct symtab *, void *),
3065                       void *data)
3066 {
3067   struct symtab *last_made = objfile->symtabs;
3068
3069   /* Don't visit already-expanded CUs.  */
3070   if (per_cu->v.quick->symtab)
3071     return 0;
3072
3073   /* This may expand more than one symtab, and we want to iterate over
3074      all of them.  */
3075   dw2_instantiate_symtab (per_cu);
3076
3077   return iterate_over_some_symtabs (name, real_path, callback, data,
3078                                     objfile->symtabs, last_made);
3079 }
3080
3081 /* Implementation of the map_symtabs_matching_filename method.  */
3082
3083 static int
3084 dw2_map_symtabs_matching_filename (struct objfile *objfile, const char *name,
3085                                    const char *real_path,
3086                                    int (*callback) (struct symtab *, void *),
3087                                    void *data)
3088 {
3089   int i;
3090   const char *name_basename = lbasename (name);
3091
3092   dw2_setup (objfile);
3093
3094   /* The rule is CUs specify all the files, including those used by
3095      any TU, so there's no need to scan TUs here.  */
3096
3097   for (i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
3098     {
3099       int j;
3100       struct dwarf2_per_cu_data *per_cu = dw2_get_primary_cu (i);
3101       struct quick_file_names *file_data;
3102
3103       /* We only need to look at symtabs not already expanded.  */
3104       if (per_cu->v.quick->symtab)
3105         continue;
3106
3107       file_data = dw2_get_file_names (per_cu);
3108       if (file_data == NULL)
3109         continue;
3110
3111       for (j = 0; j < file_data->num_file_names; ++j)
3112         {
3113           const char *this_name = file_data->file_names[j];
3114           const char *this_real_name;
3115
3116           if (compare_filenames_for_search (this_name, name))
3117             {
3118               if (dw2_map_expand_apply (objfile, per_cu, name, real_path,
3119                                         callback, data))
3120                 return 1;
3121               continue;
3122             }
3123
3124           /* Before we invoke realpath, which can get expensive when many
3125              files are involved, do a quick comparison of the basenames.  */
3126           if (! basenames_may_differ
3127               && FILENAME_CMP (lbasename (this_name), name_basename) != 0)
3128             continue;
3129
3130           this_real_name = dw2_get_real_path (objfile, file_data, j);
3131           if (compare_filenames_for_search (this_real_name, name))
3132             {
3133               if (dw2_map_expand_apply (objfile, per_cu, name, real_path,
3134                                         callback, data))
3135                 return 1;
3136               continue;
3137             }
3138
3139           if (real_path != NULL)
3140             {
3141               gdb_assert (IS_ABSOLUTE_PATH (real_path));
3142               gdb_assert (IS_ABSOLUTE_PATH (name));
3143               if (this_real_name != NULL
3144                   && FILENAME_CMP (real_path, this_real_name) == 0)
3145                 {
3146                   if (dw2_map_expand_apply (objfile, per_cu, name, real_path,
3147                                             callback, data))
3148                     return 1;
3149                   continue;
3150                 }
3151             }
3152         }
3153     }
3154
3155   return 0;
3156 }
3157
3158 /* Struct used to manage iterating over all CUs looking for a symbol.  */
3159
3160 struct dw2_symtab_iterator
3161 {
3162   /* The internalized form of .gdb_index.  */
3163   struct mapped_index *index;
3164   /* If non-zero, only look for symbols that match BLOCK_INDEX.  */
3165   int want_specific_block;
3166   /* One of GLOBAL_BLOCK or STATIC_BLOCK.
3167      Unused if !WANT_SPECIFIC_BLOCK.  */
3168   int block_index;
3169   /* The kind of symbol we're looking for.  */
3170   domain_enum domain;
3171   /* The list of CUs from the index entry of the symbol,
3172      or NULL if not found.  */
3173   offset_type *vec;
3174   /* The next element in VEC to look at.  */
3175   int next;
3176   /* The number of elements in VEC, or zero if there is no match.  */
3177   int length;
3178 };
3179
3180 /* Initialize the index symtab iterator ITER.
3181    If WANT_SPECIFIC_BLOCK is non-zero, only look for symbols
3182    in block BLOCK_INDEX.  Otherwise BLOCK_INDEX is ignored.  */
3183
3184 static void
3185 dw2_symtab_iter_init (struct dw2_symtab_iterator *iter,
3186                       struct mapped_index *index,
3187                       int want_specific_block,
3188                       int block_index,
3189                       domain_enum domain,
3190                       const char *name)
3191 {
3192   iter->index = index;
3193   iter->want_specific_block = want_specific_block;
3194   iter->block_index = block_index;
3195   iter->domain = domain;
3196   iter->next = 0;
3197
3198   if (find_slot_in_mapped_hash (index, name, &iter->vec))
3199     iter->length = MAYBE_SWAP (*iter->vec);
3200   else
3201     {
3202       iter->vec = NULL;
3203       iter->length = 0;
3204     }
3205 }
3206
3207 /* Return the next matching CU or NULL if there are no more.  */
3208
3209 static struct dwarf2_per_cu_data *
3210 dw2_symtab_iter_next (struct dw2_symtab_iterator *iter)
3211 {
3212   for ( ; iter->next < iter->length; ++iter->next)
3213     {
3214       offset_type cu_index_and_attrs =
3215         MAYBE_SWAP (iter->vec[iter->next + 1]);
3216       offset_type cu_index = GDB_INDEX_CU_VALUE (cu_index_and_attrs);
3217       struct dwarf2_per_cu_data *per_cu;
3218       int want_static = iter->block_index != GLOBAL_BLOCK;
3219       /* This value is only valid for index versions >= 7.  */
3220       int is_static = GDB_INDEX_SYMBOL_STATIC_VALUE (cu_index_and_attrs);
3221       gdb_index_symbol_kind symbol_kind =
3222         GDB_INDEX_SYMBOL_KIND_VALUE (cu_index_and_attrs);
3223       /* Only check the symbol attributes if they're present.
3224          Indices prior to version 7 don't record them,
3225          and indices >= 7 may elide them for certain symbols
3226          (gold does this).  */
3227       int attrs_valid =
3228         (iter->index->version >= 7
3229          && symbol_kind != GDB_INDEX_SYMBOL_KIND_NONE);
3230
3231       /* Don't crash on bad data.  */
3232       if (cu_index >= (dwarf2_per_objfile->n_comp_units
3233                        + dwarf2_per_objfile->n_type_units))
3234         {
3235           complaint (&symfile_complaints,
3236                      _(".gdb_index entry has bad CU index"
3237                        " [in module %s]"), dwarf2_per_objfile->objfile->name);
3238           continue;
3239         }
3240
3241       per_cu = dw2_get_cu (cu_index);
3242
3243       /* Skip if already read in.  */
3244       if (per_cu->v.quick->symtab)
3245         continue;
3246
3247       if (attrs_valid
3248           && iter->want_specific_block
3249           && want_static != is_static)
3250         continue;
3251
3252       /* Only check the symbol's kind if it has one.  */
3253       if (attrs_valid)
3254         {
3255           switch (iter->domain)
3256             {
3257             case VAR_DOMAIN:
3258               if (symbol_kind != GDB_INDEX_SYMBOL_KIND_VARIABLE
3259                   && symbol_kind != GDB_INDEX_SYMBOL_KIND_FUNCTION
3260                   /* Some types are also in VAR_DOMAIN.  */
3261                   && symbol_kind != GDB_INDEX_SYMBOL_KIND_TYPE)
3262                 continue;
3263               break;
3264             case STRUCT_DOMAIN:
3265               if (symbol_kind != GDB_INDEX_SYMBOL_KIND_TYPE)
3266                 continue;
3267               break;
3268             case LABEL_DOMAIN:
3269               if (symbol_kind != GDB_INDEX_SYMBOL_KIND_OTHER)
3270                 continue;
3271               break;
3272             default:
3273               break;
3274             }
3275         }
3276
3277       ++iter->next;
3278       return per_cu;
3279     }
3280
3281   return NULL;
3282 }
3283
3284 static struct symtab *
3285 dw2_lookup_symbol (struct objfile *objfile, int block_index,
3286                    const char *name, domain_enum domain)
3287 {
3288   struct symtab *stab_best = NULL;
3289   struct mapped_index *index;
3290
3291   dw2_setup (objfile);
3292
3293   index = dwarf2_per_objfile->index_table;
3294
3295   /* index is NULL if OBJF_READNOW.  */
3296   if (index)
3297     {
3298       struct dw2_symtab_iterator iter;
3299       struct dwarf2_per_cu_data *per_cu;
3300
3301       dw2_symtab_iter_init (&iter, index, 1, block_index, domain, name);
3302
3303       while ((per_cu = dw2_symtab_iter_next (&iter)) != NULL)
3304         {
3305           struct symbol *sym = NULL;
3306           struct symtab *stab = dw2_instantiate_symtab (per_cu);
3307
3308           /* Some caution must be observed with overloaded functions
3309              and methods, since the index will not contain any overload
3310              information (but NAME might contain it).  */
3311           if (stab->primary)
3312             {
3313               struct blockvector *bv = BLOCKVECTOR (stab);
3314               struct block *block = BLOCKVECTOR_BLOCK (bv, block_index);
3315
3316               sym = lookup_block_symbol (block, name, domain);
3317             }
3318
3319           if (sym && strcmp_iw (SYMBOL_SEARCH_NAME (sym), name) == 0)
3320             {
3321               if (!TYPE_IS_OPAQUE (SYMBOL_TYPE (sym)))
3322                 return stab;
3323
3324               stab_best = stab;
3325             }
3326
3327           /* Keep looking through other CUs.  */
3328         }
3329     }
3330
3331   return stab_best;
3332 }
3333
3334 static void
3335 dw2_print_stats (struct objfile *objfile)
3336 {
3337   int i, total, count;
3338
3339   dw2_setup (objfile);
3340   total = dwarf2_per_objfile->n_comp_units + dwarf2_per_objfile->n_type_units;
3341   count = 0;
3342   for (i = 0; i < total; ++i)
3343     {
3344       struct dwarf2_per_cu_data *per_cu = dw2_get_cu (i);
3345
3346       if (!per_cu->v.quick->symtab)
3347         ++count;
3348     }
3349   printf_filtered (_("  Number of read CUs: %d\n"), total - count);
3350   printf_filtered (_("  Number of unread CUs: %d\n"), count);
3351 }
3352
3353 static void
3354 dw2_dump (struct objfile *objfile)
3355 {
3356   /* Nothing worth printing.  */
3357 }
3358
3359 static void
3360 dw2_relocate (struct objfile *objfile,
3361               const struct section_offsets *new_offsets,
3362               const struct section_offsets *delta)
3363 {
3364   /* There's nothing to relocate here.  */
3365 }
3366
3367 static void
3368 dw2_expand_symtabs_for_function (struct objfile *objfile,
3369                                  const char *func_name)
3370 {
3371   struct mapped_index *index;
3372
3373   dw2_setup (objfile);
3374
3375   index = dwarf2_per_objfile->index_table;
3376
3377   /* index is NULL if OBJF_READNOW.  */
3378   if (index)
3379     {
3380       struct dw2_symtab_iterator iter;
3381       struct dwarf2_per_cu_data *per_cu;
3382
3383       /* Note: It doesn't matter what we pass for block_index here.  */
3384       dw2_symtab_iter_init (&iter, index, 0, GLOBAL_BLOCK, VAR_DOMAIN,
3385                             func_name);
3386
3387       while ((per_cu = dw2_symtab_iter_next (&iter)) != NULL)
3388         dw2_instantiate_symtab (per_cu);
3389     }
3390 }
3391
3392 static void
3393 dw2_expand_all_symtabs (struct objfile *objfile)
3394 {
3395   int i;
3396
3397   dw2_setup (objfile);
3398
3399   for (i = 0; i < (dwarf2_per_objfile->n_comp_units
3400                    + dwarf2_per_objfile->n_type_units); ++i)
3401     {
3402       struct dwarf2_per_cu_data *per_cu = dw2_get_cu (i);
3403
3404       dw2_instantiate_symtab (per_cu);
3405     }
3406 }
3407
3408 static void
3409 dw2_expand_symtabs_with_fullname (struct objfile *objfile,
3410                                   const char *fullname)
3411 {
3412   int i;
3413
3414   dw2_setup (objfile);
3415
3416   /* We don't need to consider type units here.
3417      This is only called for examining code, e.g. expand_line_sal.
3418      There can be an order of magnitude (or more) more type units
3419      than comp units, and we avoid them if we can.  */
3420
3421   for (i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
3422     {
3423       int j;
3424       struct dwarf2_per_cu_data *per_cu = dw2_get_cu (i);
3425       struct quick_file_names *file_data;
3426
3427       /* We only need to look at symtabs not already expanded.  */
3428       if (per_cu->v.quick->symtab)
3429         continue;
3430
3431       file_data = dw2_get_file_names (per_cu);
3432       if (file_data == NULL)
3433         continue;
3434
3435       for (j = 0; j < file_data->num_file_names; ++j)
3436         {
3437           const char *this_fullname = file_data->file_names[j];
3438
3439           if (filename_cmp (this_fullname, fullname) == 0)
3440             {
3441               dw2_instantiate_symtab (per_cu);
3442               break;
3443             }
3444         }
3445     }
3446 }
3447
3448 /* A helper function for dw2_find_symbol_file that finds the primary
3449    file name for a given CU.  This is a die_reader_func.  */
3450
3451 static void
3452 dw2_get_primary_filename_reader (const struct die_reader_specs *reader,
3453                                  const gdb_byte *info_ptr,
3454                                  struct die_info *comp_unit_die,
3455                                  int has_children,
3456                                  void *data)
3457 {
3458   const char **result_ptr = data;
3459   struct dwarf2_cu *cu = reader->cu;
3460   struct attribute *attr;
3461
3462   attr = dwarf2_attr (comp_unit_die, DW_AT_name, cu);
3463   if (attr == NULL)
3464     *result_ptr = NULL;
3465   else
3466     *result_ptr = DW_STRING (attr);
3467 }
3468
3469 static const char *
3470 dw2_find_symbol_file (struct objfile *objfile, const char *name)
3471 {
3472   struct dwarf2_per_cu_data *per_cu;
3473   offset_type *vec;
3474   const char *filename;
3475
3476   dw2_setup (objfile);
3477
3478   /* index_table is NULL if OBJF_READNOW.  */
3479   if (!dwarf2_per_objfile->index_table)
3480     {
3481       struct symtab *s;
3482
3483       ALL_OBJFILE_PRIMARY_SYMTABS (objfile, s)
3484         {
3485           struct blockvector *bv = BLOCKVECTOR (s);
3486           const struct block *block = BLOCKVECTOR_BLOCK (bv, GLOBAL_BLOCK);
3487           struct symbol *sym = lookup_block_symbol (block, name, VAR_DOMAIN);
3488
3489           if (sym)
3490             {
3491               /* Only file extension of returned filename is recognized.  */
3492               return SYMBOL_SYMTAB (sym)->filename;
3493             }
3494         }
3495       return NULL;
3496     }
3497
3498   if (!find_slot_in_mapped_hash (dwarf2_per_objfile->index_table,
3499                                  name, &vec))
3500     return NULL;
3501
3502   /* Note that this just looks at the very first one named NAME -- but
3503      actually we are looking for a function.  find_main_filename
3504      should be rewritten so that it doesn't require a custom hook.  It
3505      could just use the ordinary symbol tables.  */
3506   /* vec[0] is the length, which must always be >0.  */
3507   per_cu = dw2_get_cu (GDB_INDEX_CU_VALUE (MAYBE_SWAP (vec[1])));
3508
3509   if (per_cu->v.quick->symtab != NULL)
3510     {
3511       /* Only file extension of returned filename is recognized.  */
3512       return per_cu->v.quick->symtab->filename;
3513     }
3514
3515   /* Initialize filename in case there's a problem reading the DWARF,
3516      dw2_get_primary_filename_reader may not get called.  */
3517   filename = NULL;
3518   init_cutu_and_read_dies (per_cu, NULL, 0, 0,
3519                            dw2_get_primary_filename_reader, &filename);
3520
3521   /* Only file extension of returned filename is recognized.  */
3522   return filename;
3523 }
3524
3525 static void
3526 dw2_map_matching_symbols (const char * name, domain_enum namespace,
3527                           struct objfile *objfile, int global,
3528                           int (*callback) (struct block *,
3529                                            struct symbol *, void *),
3530                           void *data, symbol_compare_ftype *match,
3531                           symbol_compare_ftype *ordered_compare)
3532 {
3533   /* Currently unimplemented; used for Ada.  The function can be called if the
3534      current language is Ada for a non-Ada objfile using GNU index.  As Ada
3535      does not look for non-Ada symbols this function should just return.  */
3536 }
3537
3538 static void
3539 dw2_expand_symtabs_matching
3540   (struct objfile *objfile,
3541    int (*file_matcher) (const char *, void *, int basenames),
3542    int (*name_matcher) (const char *, void *),
3543    enum search_domain kind,
3544    void *data)
3545 {
3546   int i;
3547   offset_type iter;
3548   struct mapped_index *index;
3549
3550   dw2_setup (objfile);
3551
3552   /* index_table is NULL if OBJF_READNOW.  */
3553   if (!dwarf2_per_objfile->index_table)
3554     return;
3555   index = dwarf2_per_objfile->index_table;
3556
3557   if (file_matcher != NULL)
3558     {
3559       struct cleanup *cleanup;
3560       htab_t visited_found, visited_not_found;
3561
3562       visited_found = htab_create_alloc (10,
3563                                          htab_hash_pointer, htab_eq_pointer,
3564                                          NULL, xcalloc, xfree);
3565       cleanup = make_cleanup_htab_delete (visited_found);
3566       visited_not_found = htab_create_alloc (10,
3567                                              htab_hash_pointer, htab_eq_pointer,
3568                                              NULL, xcalloc, xfree);
3569       make_cleanup_htab_delete (visited_not_found);
3570
3571       /* The rule is CUs specify all the files, including those used by
3572          any TU, so there's no need to scan TUs here.  */
3573
3574       for (i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
3575         {
3576           int j;
3577           struct dwarf2_per_cu_data *per_cu = dw2_get_primary_cu (i);
3578           struct quick_file_names *file_data;
3579           void **slot;
3580
3581           per_cu->v.quick->mark = 0;
3582
3583           /* We only need to look at symtabs not already expanded.  */
3584           if (per_cu->v.quick->symtab)
3585             continue;
3586
3587           file_data = dw2_get_file_names (per_cu);
3588           if (file_data == NULL)
3589             continue;
3590
3591           if (htab_find (visited_not_found, file_data) != NULL)
3592             continue;
3593           else if (htab_find (visited_found, file_data) != NULL)
3594             {
3595               per_cu->v.quick->mark = 1;
3596               continue;
3597             }
3598
3599           for (j = 0; j < file_data->num_file_names; ++j)
3600             {
3601               const char *this_real_name;
3602
3603               if (file_matcher (file_data->file_names[j], data, 0))
3604                 {
3605                   per_cu->v.quick->mark = 1;
3606                   break;
3607                 }
3608
3609               /* Before we invoke realpath, which can get expensive when many
3610                  files are involved, do a quick comparison of the basenames.  */
3611               if (!basenames_may_differ
3612                   && !file_matcher (lbasename (file_data->file_names[j]),
3613                                     data, 1))
3614                 continue;
3615
3616               this_real_name = dw2_get_real_path (objfile, file_data, j);
3617               if (file_matcher (this_real_name, data, 0))
3618                 {
3619                   per_cu->v.quick->mark = 1;
3620                   break;
3621                 }
3622             }
3623
3624           slot = htab_find_slot (per_cu->v.quick->mark
3625                                  ? visited_found
3626                                  : visited_not_found,
3627                                  file_data, INSERT);
3628           *slot = file_data;
3629         }
3630
3631       do_cleanups (cleanup);
3632     }
3633
3634   for (iter = 0; iter < index->symbol_table_slots; ++iter)
3635     {
3636       offset_type idx = 2 * iter;
3637       const char *name;
3638       offset_type *vec, vec_len, vec_idx;
3639
3640       if (index->symbol_table[idx] == 0 && index->symbol_table[idx + 1] == 0)
3641         continue;
3642
3643       name = index->constant_pool + MAYBE_SWAP (index->symbol_table[idx]);
3644
3645       if (! (*name_matcher) (name, data))
3646         continue;
3647
3648       /* The name was matched, now expand corresponding CUs that were
3649          marked.  */
3650       vec = (offset_type *) (index->constant_pool
3651                              + MAYBE_SWAP (index->symbol_table[idx + 1]));
3652       vec_len = MAYBE_SWAP (vec[0]);
3653       for (vec_idx = 0; vec_idx < vec_len; ++vec_idx)
3654         {
3655           struct dwarf2_per_cu_data *per_cu;
3656           offset_type cu_index_and_attrs = MAYBE_SWAP (vec[vec_idx + 1]);
3657           gdb_index_symbol_kind symbol_kind =
3658             GDB_INDEX_SYMBOL_KIND_VALUE (cu_index_and_attrs);
3659           int cu_index = GDB_INDEX_CU_VALUE (cu_index_and_attrs);
3660           /* Only check the symbol attributes if they're present.
3661              Indices prior to version 7 don't record them,
3662              and indices >= 7 may elide them for certain symbols
3663              (gold does this).  */
3664           int attrs_valid =
3665             (index->version >= 7
3666              && symbol_kind != GDB_INDEX_SYMBOL_KIND_NONE);
3667
3668           /* Only check the symbol's kind if it has one.  */
3669           if (attrs_valid)
3670             {
3671               switch (kind)
3672                 {
3673                 case VARIABLES_DOMAIN:
3674                   if (symbol_kind != GDB_INDEX_SYMBOL_KIND_VARIABLE)
3675                     continue;
3676                   break;
3677                 case FUNCTIONS_DOMAIN:
3678                   if (symbol_kind != GDB_INDEX_SYMBOL_KIND_FUNCTION)
3679                     continue;
3680                   break;
3681                 case TYPES_DOMAIN:
3682                   if (symbol_kind != GDB_INDEX_SYMBOL_KIND_TYPE)
3683                     continue;
3684                   break;
3685                 default:
3686                   break;
3687                 }
3688             }
3689
3690           /* Don't crash on bad data.  */
3691           if (cu_index >= (dwarf2_per_objfile->n_comp_units
3692                            + dwarf2_per_objfile->n_type_units))
3693             {
3694               complaint (&symfile_complaints,
3695                          _(".gdb_index entry has bad CU index"
3696                            " [in module %s]"), objfile->name);
3697               continue;
3698             }
3699
3700           per_cu = dw2_get_cu (cu_index);
3701           if (file_matcher == NULL || per_cu->v.quick->mark)
3702             dw2_instantiate_symtab (per_cu);
3703         }
3704     }
3705 }
3706
3707 /* A helper for dw2_find_pc_sect_symtab which finds the most specific
3708    symtab.  */
3709
3710 static struct symtab *
3711 recursively_find_pc_sect_symtab (struct symtab *symtab, CORE_ADDR pc)
3712 {
3713   int i;
3714
3715   if (BLOCKVECTOR (symtab) != NULL
3716       && blockvector_contains_pc (BLOCKVECTOR (symtab), pc))
3717     return symtab;
3718
3719   if (symtab->includes == NULL)
3720     return NULL;
3721
3722   for (i = 0; symtab->includes[i]; ++i)
3723     {
3724       struct symtab *s = symtab->includes[i];
3725
3726       s = recursively_find_pc_sect_symtab (s, pc);
3727       if (s != NULL)
3728         return s;
3729     }
3730
3731   return NULL;
3732 }
3733
3734 static struct symtab *
3735 dw2_find_pc_sect_symtab (struct objfile *objfile,
3736                          struct minimal_symbol *msymbol,
3737                          CORE_ADDR pc,
3738                          struct obj_section *section,
3739                          int warn_if_readin)
3740 {
3741   struct dwarf2_per_cu_data *data;
3742   struct symtab *result;
3743
3744   dw2_setup (objfile);
3745
3746   if (!objfile->psymtabs_addrmap)
3747     return NULL;
3748
3749   data = addrmap_find (objfile->psymtabs_addrmap, pc);
3750   if (!data)
3751     return NULL;
3752
3753   if (warn_if_readin && data->v.quick->symtab)
3754     warning (_("(Internal error: pc %s in read in CU, but not in symtab.)"),
3755              paddress (get_objfile_arch (objfile), pc));
3756
3757   result = recursively_find_pc_sect_symtab (dw2_instantiate_symtab (data), pc);
3758   gdb_assert (result != NULL);
3759   return result;
3760 }
3761
3762 static void
3763 dw2_map_symbol_filenames (struct objfile *objfile, symbol_filename_ftype *fun,
3764                           void *data, int need_fullname)
3765 {
3766   int i;
3767   struct cleanup *cleanup;
3768   htab_t visited = htab_create_alloc (10, htab_hash_pointer, htab_eq_pointer,
3769                                       NULL, xcalloc, xfree);
3770
3771   cleanup = make_cleanup_htab_delete (visited);
3772   dw2_setup (objfile);
3773
3774   /* The rule is CUs specify all the files, including those used by
3775      any TU, so there's no need to scan TUs here.
3776      We can ignore file names coming from already-expanded CUs.  */
3777
3778   for (i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
3779     {
3780       struct dwarf2_per_cu_data *per_cu = dw2_get_cu (i);
3781
3782       if (per_cu->v.quick->symtab)
3783         {
3784           void **slot = htab_find_slot (visited, per_cu->v.quick->file_names,
3785                                         INSERT);
3786
3787           *slot = per_cu->v.quick->file_names;
3788         }
3789     }
3790
3791   for (i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
3792     {
3793       int j;
3794       struct dwarf2_per_cu_data *per_cu = dw2_get_primary_cu (i);
3795       struct quick_file_names *file_data;
3796       void **slot;
3797
3798       /* We only need to look at symtabs not already expanded.  */
3799       if (per_cu->v.quick->symtab)
3800         continue;
3801
3802       file_data = dw2_get_file_names (per_cu);
3803       if (file_data == NULL)
3804         continue;
3805
3806       slot = htab_find_slot (visited, file_data, INSERT);
3807       if (*slot)
3808         {
3809           /* Already visited.  */
3810           continue;
3811         }
3812       *slot = file_data;
3813
3814       for (j = 0; j < file_data->num_file_names; ++j)
3815         {
3816           const char *this_real_name;
3817
3818           if (need_fullname)
3819             this_real_name = dw2_get_real_path (objfile, file_data, j);
3820           else
3821             this_real_name = NULL;
3822           (*fun) (file_data->file_names[j], this_real_name, data);
3823         }
3824     }
3825
3826   do_cleanups (cleanup);
3827 }
3828
3829 static int
3830 dw2_has_symbols (struct objfile *objfile)
3831 {
3832   return 1;
3833 }
3834
3835 const struct quick_symbol_functions dwarf2_gdb_index_functions =
3836 {
3837   dw2_has_symbols,
3838   dw2_find_last_source_symtab,
3839   dw2_forget_cached_source_info,
3840   dw2_map_symtabs_matching_filename,
3841   dw2_lookup_symbol,
3842   dw2_print_stats,
3843   dw2_dump,
3844   dw2_relocate,
3845   dw2_expand_symtabs_for_function,
3846   dw2_expand_all_symtabs,
3847   dw2_expand_symtabs_with_fullname,
3848   dw2_find_symbol_file,
3849   dw2_map_matching_symbols,
3850   dw2_expand_symtabs_matching,
3851   dw2_find_pc_sect_symtab,
3852   dw2_map_symbol_filenames
3853 };
3854
3855 /* Initialize for reading DWARF for this objfile.  Return 0 if this
3856    file will use psymtabs, or 1 if using the GNU index.  */
3857
3858 int
3859 dwarf2_initialize_objfile (struct objfile *objfile)
3860 {
3861   /* If we're about to read full symbols, don't bother with the
3862      indices.  In this case we also don't care if some other debug
3863      format is making psymtabs, because they are all about to be
3864      expanded anyway.  */
3865   if ((objfile->flags & OBJF_READNOW))
3866     {
3867       int i;
3868
3869       dwarf2_per_objfile->using_index = 1;
3870       create_all_comp_units (objfile);
3871       create_all_type_units (objfile);
3872       dwarf2_per_objfile->quick_file_names_table =
3873         create_quick_file_names_table (dwarf2_per_objfile->n_comp_units);
3874
3875       for (i = 0; i < (dwarf2_per_objfile->n_comp_units
3876                        + dwarf2_per_objfile->n_type_units); ++i)
3877         {
3878           struct dwarf2_per_cu_data *per_cu = dw2_get_cu (i);
3879
3880           per_cu->v.quick = OBSTACK_ZALLOC (&objfile->objfile_obstack,
3881                                             struct dwarf2_per_cu_quick_data);
3882         }
3883
3884       /* Return 1 so that gdb sees the "quick" functions.  However,
3885          these functions will be no-ops because we will have expanded
3886          all symtabs.  */
3887       return 1;
3888     }
3889
3890   if (dwarf2_read_index (objfile))
3891     return 1;
3892
3893   return 0;
3894 }
3895
3896 \f
3897
3898 /* Build a partial symbol table.  */
3899
3900 void
3901 dwarf2_build_psymtabs (struct objfile *objfile)
3902 {
3903   volatile struct gdb_exception except;
3904
3905   if (objfile->global_psymbols.size == 0 && objfile->static_psymbols.size == 0)
3906     {
3907       init_psymbol_list (objfile, 1024);
3908     }
3909
3910   TRY_CATCH (except, RETURN_MASK_ERROR)
3911     {
3912       /* This isn't really ideal: all the data we allocate on the
3913          objfile's obstack is still uselessly kept around.  However,
3914          freeing it seems unsafe.  */
3915       struct cleanup *cleanups = make_cleanup_discard_psymtabs (objfile);
3916
3917       dwarf2_build_psymtabs_hard (objfile);
3918       discard_cleanups (cleanups);
3919     }
3920   if (except.reason < 0)
3921     exception_print (gdb_stderr, except);
3922 }
3923
3924 /* Return the total length of the CU described by HEADER.  */
3925
3926 static unsigned int
3927 get_cu_length (const struct comp_unit_head *header)
3928 {
3929   return header->initial_length_size + header->length;
3930 }
3931
3932 /* Return TRUE if OFFSET is within CU_HEADER.  */
3933
3934 static inline int
3935 offset_in_cu_p (const struct comp_unit_head *cu_header, sect_offset offset)
3936 {
3937   sect_offset bottom = { cu_header->offset.sect_off };
3938   sect_offset top = { cu_header->offset.sect_off + get_cu_length (cu_header) };
3939
3940   return (offset.sect_off >= bottom.sect_off && offset.sect_off < top.sect_off);
3941 }
3942
3943 /* Find the base address of the compilation unit for range lists and
3944    location lists.  It will normally be specified by DW_AT_low_pc.
3945    In DWARF-3 draft 4, the base address could be overridden by
3946    DW_AT_entry_pc.  It's been removed, but GCC still uses this for
3947    compilation units with discontinuous ranges.  */
3948
3949 static void
3950 dwarf2_find_base_address (struct die_info *die, struct dwarf2_cu *cu)
3951 {
3952   struct attribute *attr;
3953
3954   cu->base_known = 0;
3955   cu->base_address = 0;
3956
3957   attr = dwarf2_attr (die, DW_AT_entry_pc, cu);
3958   if (attr)
3959     {
3960       cu->base_address = DW_ADDR (attr);
3961       cu->base_known = 1;
3962     }
3963   else
3964     {
3965       attr = dwarf2_attr (die, DW_AT_low_pc, cu);
3966       if (attr)
3967         {
3968           cu->base_address = DW_ADDR (attr);
3969           cu->base_known = 1;
3970         }
3971     }
3972 }
3973
3974 /* Read in the comp unit header information from the debug_info at info_ptr.
3975    NOTE: This leaves members offset, first_die_offset to be filled in
3976    by the caller.  */
3977
3978 static const gdb_byte *
3979 read_comp_unit_head (struct comp_unit_head *cu_header,
3980                      const gdb_byte *info_ptr, bfd *abfd)
3981 {
3982   int signed_addr;
3983   unsigned int bytes_read;
3984
3985   cu_header->length = read_initial_length (abfd, info_ptr, &bytes_read);
3986   cu_header->initial_length_size = bytes_read;
3987   cu_header->offset_size = (bytes_read == 4) ? 4 : 8;
3988   info_ptr += bytes_read;
3989   cu_header->version = read_2_bytes (abfd, info_ptr);
3990   info_ptr += 2;
3991   cu_header->abbrev_offset.sect_off = read_offset (abfd, info_ptr, cu_header,
3992                                              &bytes_read);
3993   info_ptr += bytes_read;
3994   cu_header->addr_size = read_1_byte (abfd, info_ptr);
3995   info_ptr += 1;
3996   signed_addr = bfd_get_sign_extend_vma (abfd);
3997   if (signed_addr < 0)
3998     internal_error (__FILE__, __LINE__,
3999                     _("read_comp_unit_head: dwarf from non elf file"));
4000   cu_header->signed_addr_p = signed_addr;
4001
4002   return info_ptr;
4003 }
4004
4005 /* Helper function that returns the proper abbrev section for
4006    THIS_CU.  */
4007
4008 static struct dwarf2_section_info *
4009 get_abbrev_section_for_cu (struct dwarf2_per_cu_data *this_cu)
4010 {
4011   struct dwarf2_section_info *abbrev;
4012
4013   if (this_cu->is_dwz)
4014     abbrev = &dwarf2_get_dwz_file ()->abbrev;
4015   else
4016     abbrev = &dwarf2_per_objfile->abbrev;
4017
4018   return abbrev;
4019 }
4020
4021 /* Subroutine of read_and_check_comp_unit_head and
4022    read_and_check_type_unit_head to simplify them.
4023    Perform various error checking on the header.  */
4024
4025 static void
4026 error_check_comp_unit_head (struct comp_unit_head *header,
4027                             struct dwarf2_section_info *section,
4028                             struct dwarf2_section_info *abbrev_section)
4029 {
4030   bfd *abfd = section->asection->owner;
4031   const char *filename = bfd_get_filename (abfd);
4032
4033   if (header->version != 2 && header->version != 3 && header->version != 4)
4034     error (_("Dwarf Error: wrong version in compilation unit header "
4035            "(is %d, should be 2, 3, or 4) [in module %s]"), header->version,
4036            filename);
4037
4038   if (header->abbrev_offset.sect_off
4039       >= dwarf2_section_size (dwarf2_per_objfile->objfile, abbrev_section))
4040     error (_("Dwarf Error: bad offset (0x%lx) in compilation unit header "
4041            "(offset 0x%lx + 6) [in module %s]"),
4042            (long) header->abbrev_offset.sect_off, (long) header->offset.sect_off,
4043            filename);
4044
4045   /* Cast to unsigned long to use 64-bit arithmetic when possible to
4046      avoid potential 32-bit overflow.  */
4047   if (((unsigned long) header->offset.sect_off + get_cu_length (header))
4048       > section->size)
4049     error (_("Dwarf Error: bad length (0x%lx) in compilation unit header "
4050            "(offset 0x%lx + 0) [in module %s]"),
4051            (long) header->length, (long) header->offset.sect_off,
4052            filename);
4053 }
4054
4055 /* Read in a CU/TU header and perform some basic error checking.
4056    The contents of the header are stored in HEADER.
4057    The result is a pointer to the start of the first DIE.  */
4058
4059 static const gdb_byte *
4060 read_and_check_comp_unit_head (struct comp_unit_head *header,
4061                                struct dwarf2_section_info *section,
4062                                struct dwarf2_section_info *abbrev_section,
4063                                const gdb_byte *info_ptr,
4064                                int is_debug_types_section)
4065 {
4066   const gdb_byte *beg_of_comp_unit = info_ptr;
4067   bfd *abfd = section->asection->owner;
4068
4069   header->offset.sect_off = beg_of_comp_unit - section->buffer;
4070
4071   info_ptr = read_comp_unit_head (header, info_ptr, abfd);
4072
4073   /* If we're reading a type unit, skip over the signature and
4074      type_offset fields.  */
4075   if (is_debug_types_section)
4076     info_ptr += 8 /*signature*/ + header->offset_size;
4077
4078   header->first_die_offset.cu_off = info_ptr - beg_of_comp_unit;
4079
4080   error_check_comp_unit_head (header, section, abbrev_section);
4081
4082   return info_ptr;
4083 }
4084
4085 /* Read in the types comp unit header information from .debug_types entry at
4086    types_ptr.  The result is a pointer to one past the end of the header.  */
4087
4088 static const gdb_byte *
4089 read_and_check_type_unit_head (struct comp_unit_head *header,
4090                                struct dwarf2_section_info *section,
4091                                struct dwarf2_section_info *abbrev_section,
4092                                const gdb_byte *info_ptr,
4093                                ULONGEST *signature,
4094                                cu_offset *type_offset_in_tu)
4095 {
4096   const gdb_byte *beg_of_comp_unit = info_ptr;
4097   bfd *abfd = section->asection->owner;
4098
4099   header->offset.sect_off = beg_of_comp_unit - section->buffer;
4100
4101   info_ptr = read_comp_unit_head (header, info_ptr, abfd);
4102
4103   /* If we're reading a type unit, skip over the signature and
4104      type_offset fields.  */
4105   if (signature != NULL)
4106     *signature = read_8_bytes (abfd, info_ptr);
4107   info_ptr += 8;
4108   if (type_offset_in_tu != NULL)
4109     type_offset_in_tu->cu_off = read_offset_1 (abfd, info_ptr,
4110                                                header->offset_size);
4111   info_ptr += header->offset_size;
4112
4113   header->first_die_offset.cu_off = info_ptr - beg_of_comp_unit;
4114
4115   error_check_comp_unit_head (header, section, abbrev_section);
4116
4117   return info_ptr;
4118 }
4119
4120 /* Fetch the abbreviation table offset from a comp or type unit header.  */
4121
4122 static sect_offset
4123 read_abbrev_offset (struct dwarf2_section_info *section,
4124                     sect_offset offset)
4125 {
4126   bfd *abfd = section->asection->owner;
4127   const gdb_byte *info_ptr;
4128   unsigned int length, initial_length_size, offset_size;
4129   sect_offset abbrev_offset;
4130
4131   dwarf2_read_section (dwarf2_per_objfile->objfile, section);
4132   info_ptr = section->buffer + offset.sect_off;
4133   length = read_initial_length (abfd, info_ptr, &initial_length_size);
4134   offset_size = initial_length_size == 4 ? 4 : 8;
4135   info_ptr += initial_length_size + 2 /*version*/;
4136   abbrev_offset.sect_off = read_offset_1 (abfd, info_ptr, offset_size);
4137   return abbrev_offset;
4138 }
4139
4140 /* Allocate a new partial symtab for file named NAME and mark this new
4141    partial symtab as being an include of PST.  */
4142
4143 static void
4144 dwarf2_create_include_psymtab (const char *name, struct partial_symtab *pst,
4145                                struct objfile *objfile)
4146 {
4147   struct partial_symtab *subpst = allocate_psymtab (name, objfile);
4148
4149   if (!IS_ABSOLUTE_PATH (subpst->filename))
4150     {
4151       /* It shares objfile->objfile_obstack.  */
4152       subpst->dirname = pst->dirname;
4153     }
4154
4155   subpst->section_offsets = pst->section_offsets;
4156   subpst->textlow = 0;
4157   subpst->texthigh = 0;
4158
4159   subpst->dependencies = (struct partial_symtab **)
4160     obstack_alloc (&objfile->objfile_obstack,
4161                    sizeof (struct partial_symtab *));
4162   subpst->dependencies[0] = pst;
4163   subpst->number_of_dependencies = 1;
4164
4165   subpst->globals_offset = 0;
4166   subpst->n_global_syms = 0;
4167   subpst->statics_offset = 0;
4168   subpst->n_static_syms = 0;
4169   subpst->symtab = NULL;
4170   subpst->read_symtab = pst->read_symtab;
4171   subpst->readin = 0;
4172
4173   /* No private part is necessary for include psymtabs.  This property
4174      can be used to differentiate between such include psymtabs and
4175      the regular ones.  */
4176   subpst->read_symtab_private = NULL;
4177 }
4178
4179 /* Read the Line Number Program data and extract the list of files
4180    included by the source file represented by PST.  Build an include
4181    partial symtab for each of these included files.  */
4182
4183 static void
4184 dwarf2_build_include_psymtabs (struct dwarf2_cu *cu,
4185                                struct die_info *die,
4186                                struct partial_symtab *pst)
4187 {
4188   struct line_header *lh = NULL;
4189   struct attribute *attr;
4190
4191   attr = dwarf2_attr (die, DW_AT_stmt_list, cu);
4192   if (attr)
4193     lh = dwarf_decode_line_header (DW_UNSND (attr), cu);
4194   if (lh == NULL)
4195     return;  /* No linetable, so no includes.  */
4196
4197   /* NOTE: pst->dirname is DW_AT_comp_dir (if present).  */
4198   dwarf_decode_lines (lh, pst->dirname, cu, pst, 1);
4199
4200   free_line_header (lh);
4201 }
4202
4203 static hashval_t
4204 hash_signatured_type (const void *item)
4205 {
4206   const struct signatured_type *sig_type = item;
4207
4208   /* This drops the top 32 bits of the signature, but is ok for a hash.  */
4209   return sig_type->signature;
4210 }
4211
4212 static int
4213 eq_signatured_type (const void *item_lhs, const void *item_rhs)
4214 {
4215   const struct signatured_type *lhs = item_lhs;
4216   const struct signatured_type *rhs = item_rhs;
4217
4218   return lhs->signature == rhs->signature;
4219 }
4220
4221 /* Allocate a hash table for signatured types.  */
4222
4223 static htab_t
4224 allocate_signatured_type_table (struct objfile *objfile)
4225 {
4226   return htab_create_alloc_ex (41,
4227                                hash_signatured_type,
4228                                eq_signatured_type,
4229                                NULL,
4230                                &objfile->objfile_obstack,
4231                                hashtab_obstack_allocate,
4232                                dummy_obstack_deallocate);
4233 }
4234
4235 /* A helper function to add a signatured type CU to a table.  */
4236
4237 static int
4238 add_signatured_type_cu_to_table (void **slot, void *datum)
4239 {
4240   struct signatured_type *sigt = *slot;
4241   struct signatured_type ***datap = datum;
4242
4243   **datap = sigt;
4244   ++*datap;
4245
4246   return 1;
4247 }
4248
4249 /* Create the hash table of all entries in the .debug_types
4250    (or .debug_types.dwo) section(s).
4251    If reading a DWO file, then DWO_FILE is a pointer to the DWO file object,
4252    otherwise it is NULL.
4253
4254    The result is a pointer to the hash table or NULL if there are no types.
4255
4256    Note: This function processes DWO files only, not DWP files.  */
4257
4258 static htab_t
4259 create_debug_types_hash_table (struct dwo_file *dwo_file,
4260                                VEC (dwarf2_section_info_def) *types)
4261 {
4262   struct objfile *objfile = dwarf2_per_objfile->objfile;
4263   htab_t types_htab = NULL;
4264   int ix;
4265   struct dwarf2_section_info *section;
4266   struct dwarf2_section_info *abbrev_section;
4267
4268   if (VEC_empty (dwarf2_section_info_def, types))
4269     return NULL;
4270
4271   abbrev_section = (dwo_file != NULL
4272                     ? &dwo_file->sections.abbrev
4273                     : &dwarf2_per_objfile->abbrev);
4274
4275   if (dwarf2_read_debug)
4276     fprintf_unfiltered (gdb_stdlog, "Reading .debug_types%s for %s:\n",
4277                         dwo_file ? ".dwo" : "",
4278                         bfd_get_filename (abbrev_section->asection->owner));
4279
4280   for (ix = 0;
4281        VEC_iterate (dwarf2_section_info_def, types, ix, section);
4282        ++ix)
4283     {
4284       bfd *abfd;
4285       const gdb_byte *info_ptr, *end_ptr;
4286       struct dwarf2_section_info *abbrev_section;
4287
4288       dwarf2_read_section (objfile, section);
4289       info_ptr = section->buffer;
4290
4291       if (info_ptr == NULL)
4292         continue;
4293
4294       /* We can't set abfd until now because the section may be empty or
4295          not present, in which case section->asection will be NULL.  */
4296       abfd = section->asection->owner;
4297
4298       if (dwo_file)
4299         abbrev_section = &dwo_file->sections.abbrev;
4300       else
4301         abbrev_section = &dwarf2_per_objfile->abbrev;
4302
4303       /* We don't use init_cutu_and_read_dies_simple, or some such, here
4304          because we don't need to read any dies: the signature is in the
4305          header.  */
4306
4307       end_ptr = info_ptr + section->size;
4308       while (info_ptr < end_ptr)
4309         {
4310           sect_offset offset;
4311           cu_offset type_offset_in_tu;
4312           ULONGEST signature;
4313           struct signatured_type *sig_type;
4314           struct dwo_unit *dwo_tu;
4315           void **slot;
4316           const gdb_byte *ptr = info_ptr;
4317           struct comp_unit_head header;
4318           unsigned int length;
4319
4320           offset.sect_off = ptr - section->buffer;
4321
4322           /* We need to read the type's signature in order to build the hash
4323              table, but we don't need anything else just yet.  */
4324
4325           ptr = read_and_check_type_unit_head (&header, section,
4326                                                abbrev_section, ptr,
4327                                                &signature, &type_offset_in_tu);
4328
4329           length = get_cu_length (&header);
4330
4331           /* Skip dummy type units.  */
4332           if (ptr >= info_ptr + length
4333               || peek_abbrev_code (abfd, ptr) == 0)
4334             {
4335               info_ptr += length;
4336               continue;
4337             }
4338
4339           if (types_htab == NULL)
4340             {
4341               if (dwo_file)
4342                 types_htab = allocate_dwo_unit_table (objfile);
4343               else
4344                 types_htab = allocate_signatured_type_table (objfile);
4345             }
4346
4347           if (dwo_file)
4348             {
4349               sig_type = NULL;
4350               dwo_tu = OBSTACK_ZALLOC (&objfile->objfile_obstack,
4351                                        struct dwo_unit);
4352               dwo_tu->dwo_file = dwo_file;
4353               dwo_tu->signature = signature;
4354               dwo_tu->type_offset_in_tu = type_offset_in_tu;
4355               dwo_tu->section = section;
4356               dwo_tu->offset = offset;
4357               dwo_tu->length = length;
4358             }
4359           else
4360             {
4361               /* N.B.: type_offset is not usable if this type uses a DWO file.
4362                  The real type_offset is in the DWO file.  */
4363               dwo_tu = NULL;
4364               sig_type = OBSTACK_ZALLOC (&objfile->objfile_obstack,
4365                                          struct signatured_type);
4366               sig_type->signature = signature;
4367               sig_type->type_offset_in_tu = type_offset_in_tu;
4368               sig_type->per_cu.objfile = objfile;
4369               sig_type->per_cu.is_debug_types = 1;
4370               sig_type->per_cu.section = section;
4371               sig_type->per_cu.offset = offset;
4372               sig_type->per_cu.length = length;
4373             }
4374
4375           slot = htab_find_slot (types_htab,
4376                                  dwo_file ? (void*) dwo_tu : (void *) sig_type,
4377                                  INSERT);
4378           gdb_assert (slot != NULL);
4379           if (*slot != NULL)
4380             {
4381               sect_offset dup_offset;
4382
4383               if (dwo_file)
4384                 {
4385                   const struct dwo_unit *dup_tu = *slot;
4386
4387                   dup_offset = dup_tu->offset;
4388                 }
4389               else
4390                 {
4391                   const struct signatured_type *dup_tu = *slot;
4392
4393                   dup_offset = dup_tu->per_cu.offset;
4394                 }
4395
4396               complaint (&symfile_complaints,
4397                          _("debug type entry at offset 0x%x is duplicate to"
4398                            " the entry at offset 0x%x, signature %s"),
4399                          offset.sect_off, dup_offset.sect_off,
4400                          hex_string (signature));
4401             }
4402           *slot = dwo_file ? (void *) dwo_tu : (void *) sig_type;
4403
4404           if (dwarf2_read_debug)
4405             fprintf_unfiltered (gdb_stdlog, "  offset 0x%x, signature %s\n",
4406                                 offset.sect_off,
4407                                 hex_string (signature));
4408
4409           info_ptr += length;
4410         }
4411     }
4412
4413   return types_htab;
4414 }
4415
4416 /* Create the hash table of all entries in the .debug_types section,
4417    and initialize all_type_units.
4418    The result is zero if there is an error (e.g. missing .debug_types section),
4419    otherwise non-zero.  */
4420
4421 static int
4422 create_all_type_units (struct objfile *objfile)
4423 {
4424   htab_t types_htab;
4425   struct signatured_type **iter;
4426
4427   types_htab = create_debug_types_hash_table (NULL, dwarf2_per_objfile->types);
4428   if (types_htab == NULL)
4429     {
4430       dwarf2_per_objfile->signatured_types = NULL;
4431       return 0;
4432     }
4433
4434   dwarf2_per_objfile->signatured_types = types_htab;
4435
4436   dwarf2_per_objfile->n_type_units = htab_elements (types_htab);
4437   dwarf2_per_objfile->all_type_units
4438     = xmalloc (dwarf2_per_objfile->n_type_units
4439                * sizeof (struct signatured_type *));
4440   iter = &dwarf2_per_objfile->all_type_units[0];
4441   htab_traverse_noresize (types_htab, add_signatured_type_cu_to_table, &iter);
4442   gdb_assert (iter - &dwarf2_per_objfile->all_type_units[0]
4443               == dwarf2_per_objfile->n_type_units);
4444
4445   return 1;
4446 }
4447
4448 /* Subroutine of lookup_dwo_signatured_type and lookup_dwp_signatured_type.
4449    Fill in SIG_ENTRY with DWO_ENTRY.  */
4450
4451 static void
4452 fill_in_sig_entry_from_dwo_entry (struct objfile *objfile,
4453                                   struct signatured_type *sig_entry,
4454                                   struct dwo_unit *dwo_entry)
4455 {
4456   /* Make sure we're not clobbering something we don't expect to.  */
4457   gdb_assert (! sig_entry->per_cu.queued);
4458   gdb_assert (sig_entry->per_cu.cu == NULL);
4459   gdb_assert (sig_entry->per_cu.v.quick != NULL);
4460   gdb_assert (sig_entry->per_cu.v.quick->symtab == NULL);
4461   gdb_assert (sig_entry->signature == dwo_entry->signature);
4462   gdb_assert (sig_entry->type_offset_in_section.sect_off == 0);
4463   gdb_assert (sig_entry->type_unit_group == NULL);
4464   gdb_assert (sig_entry->dwo_unit == NULL);
4465
4466   sig_entry->per_cu.section = dwo_entry->section;
4467   sig_entry->per_cu.offset = dwo_entry->offset;
4468   sig_entry->per_cu.length = dwo_entry->length;
4469   sig_entry->per_cu.reading_dwo_directly = 1;
4470   sig_entry->per_cu.objfile = objfile;
4471   sig_entry->type_offset_in_tu = dwo_entry->type_offset_in_tu;
4472   sig_entry->dwo_unit = dwo_entry;
4473 }
4474
4475 /* Subroutine of lookup_signatured_type.
4476    If we haven't read the TU yet, create the signatured_type data structure
4477    for a TU to be read in directly from a DWO file, bypassing the stub.
4478    This is the "Stay in DWO Optimization": When there is no DWP file and we're
4479    using .gdb_index, then when reading a CU we want to stay in the DWO file
4480    containing that CU.  Otherwise we could end up reading several other DWO
4481    files (due to comdat folding) to process the transitive closure of all the
4482    mentioned TUs, and that can be slow.  The current DWO file will have every
4483    type signature that it needs.
4484    We only do this for .gdb_index because in the psymtab case we already have
4485    to read all the DWOs to build the type unit groups.  */
4486
4487 static struct signatured_type *
4488 lookup_dwo_signatured_type (struct dwarf2_cu *cu, ULONGEST sig)
4489 {
4490   struct objfile *objfile = dwarf2_per_objfile->objfile;
4491   struct dwo_file *dwo_file;
4492   struct dwo_unit find_dwo_entry, *dwo_entry;
4493   struct signatured_type find_sig_entry, *sig_entry;
4494
4495   gdb_assert (cu->dwo_unit && dwarf2_per_objfile->using_index);
4496
4497   /* Note: cu->dwo_unit is the dwo_unit that references this TU, not the
4498      dwo_unit of the TU itself.  */
4499   dwo_file = cu->dwo_unit->dwo_file;
4500
4501   /* We only ever need to read in one copy of a signatured type.
4502      Just use the global signatured_types array.  If this is the first time
4503      we're reading this type, replace the recorded data from .gdb_index with
4504      this TU.  */
4505
4506   if (dwarf2_per_objfile->signatured_types == NULL)
4507     return NULL;
4508   find_sig_entry.signature = sig;
4509   sig_entry = htab_find (dwarf2_per_objfile->signatured_types, &find_sig_entry);
4510   if (sig_entry == NULL)
4511     return NULL;
4512
4513   /* We can get here with the TU already read, *or* in the process of being
4514      read.  Don't reassign it if that's the case.  Also note that if the TU is
4515      already being read, it may not have come from a DWO, the program may be
4516      a mix of Fission-compiled code and non-Fission-compiled code.  */
4517   /* Have we already tried to read this TU?  */
4518   if (sig_entry->per_cu.tu_read)
4519     return sig_entry;
4520
4521   /* Ok, this is the first time we're reading this TU.  */
4522   if (dwo_file->tus == NULL)
4523     return NULL;
4524   find_dwo_entry.signature = sig;
4525   dwo_entry = htab_find (dwo_file->tus, &find_dwo_entry);
4526   if (dwo_entry == NULL)
4527     return NULL;
4528
4529   fill_in_sig_entry_from_dwo_entry (objfile, sig_entry, dwo_entry);
4530   return sig_entry;
4531 }
4532
4533 /* Subroutine of lookup_dwp_signatured_type.
4534    Add an entry for signature SIG to dwarf2_per_objfile->signatured_types.  */
4535
4536 static struct signatured_type *
4537 add_type_unit (ULONGEST sig)
4538 {
4539   struct objfile *objfile = dwarf2_per_objfile->objfile;
4540   int n_type_units = dwarf2_per_objfile->n_type_units;
4541   struct signatured_type *sig_type;
4542   void **slot;
4543
4544   ++n_type_units;
4545   dwarf2_per_objfile->all_type_units =
4546     xrealloc (dwarf2_per_objfile->all_type_units,
4547               n_type_units * sizeof (struct signatured_type *));
4548   dwarf2_per_objfile->n_type_units = n_type_units;
4549   sig_type = OBSTACK_ZALLOC (&objfile->objfile_obstack,
4550                              struct signatured_type);
4551   dwarf2_per_objfile->all_type_units[n_type_units - 1] = sig_type;
4552   sig_type->signature = sig;
4553   sig_type->per_cu.is_debug_types = 1;
4554   sig_type->per_cu.v.quick =
4555     OBSTACK_ZALLOC (&objfile->objfile_obstack,
4556                     struct dwarf2_per_cu_quick_data);
4557   slot = htab_find_slot (dwarf2_per_objfile->signatured_types,
4558                          sig_type, INSERT);
4559   gdb_assert (*slot == NULL);
4560   *slot = sig_type;
4561   /* The rest of sig_type must be filled in by the caller.  */
4562   return sig_type;
4563 }
4564
4565 /* Subroutine of lookup_signatured_type.
4566    Look up the type for signature SIG, and if we can't find SIG in .gdb_index
4567    then try the DWP file.
4568    Normally this "can't happen", but if there's a bug in signature
4569    generation and/or the DWP file is built incorrectly, it can happen.
4570    Using the type directly from the DWP file means we don't have the stub
4571    which has some useful attributes (e.g., DW_AT_comp_dir), but they're
4572    not critical.  [Eventually the stub may go away for type units anyway.]  */
4573
4574 static struct signatured_type *
4575 lookup_dwp_signatured_type (struct dwarf2_cu *cu, ULONGEST sig)
4576 {
4577   struct objfile *objfile = dwarf2_per_objfile->objfile;
4578   struct dwp_file *dwp_file = get_dwp_file ();
4579   struct dwo_unit *dwo_entry;
4580   struct signatured_type find_sig_entry, *sig_entry;
4581
4582   gdb_assert (cu->dwo_unit && dwarf2_per_objfile->using_index);
4583   gdb_assert (dwp_file != NULL);
4584
4585   if (dwarf2_per_objfile->signatured_types != NULL)
4586     {
4587       find_sig_entry.signature = sig;
4588       sig_entry = htab_find (dwarf2_per_objfile->signatured_types,
4589                              &find_sig_entry);
4590       if (sig_entry != NULL)
4591         return sig_entry;
4592     }
4593
4594   /* This is the "shouldn't happen" case.
4595      Try the DWP file and hope for the best.  */
4596   if (dwp_file->tus == NULL)
4597     return NULL;
4598   dwo_entry = lookup_dwo_in_dwp (dwp_file, dwp_file->tus, NULL,
4599                                  sig, 1 /* is_debug_types */);
4600   if (dwo_entry == NULL)
4601     return NULL;
4602
4603   sig_entry = add_type_unit (sig);
4604   fill_in_sig_entry_from_dwo_entry (objfile, sig_entry, dwo_entry);
4605
4606   /* The caller will signal a complaint if we return NULL.
4607      Here we don't return NULL but we still want to complain.  */
4608   complaint (&symfile_complaints,
4609              _("Bad type signature %s referenced by %s at 0x%x,"
4610                " coping by using copy in DWP [in module %s]"),
4611              hex_string (sig),
4612              cu->per_cu->is_debug_types ? "TU" : "CU",
4613              cu->per_cu->offset.sect_off,
4614              objfile->name);
4615
4616   return sig_entry;
4617 }
4618
4619 /* Lookup a signature based type for DW_FORM_ref_sig8.
4620    Returns NULL if signature SIG is not present in the table.
4621    It is up to the caller to complain about this.  */
4622
4623 static struct signatured_type *
4624 lookup_signatured_type (struct dwarf2_cu *cu, ULONGEST sig)
4625 {
4626   if (cu->dwo_unit
4627       && dwarf2_per_objfile->using_index)
4628     {
4629       /* We're in a DWO/DWP file, and we're using .gdb_index.
4630          These cases require special processing.  */
4631       if (get_dwp_file () == NULL)
4632         return lookup_dwo_signatured_type (cu, sig);
4633       else
4634         return lookup_dwp_signatured_type (cu, sig);
4635     }
4636   else
4637     {
4638       struct signatured_type find_entry, *entry;
4639
4640       if (dwarf2_per_objfile->signatured_types == NULL)
4641         return NULL;
4642       find_entry.signature = sig;
4643       entry = htab_find (dwarf2_per_objfile->signatured_types, &find_entry);
4644       return entry;
4645     }
4646 }
4647 \f
4648 /* Low level DIE reading support.  */
4649
4650 /* Initialize a die_reader_specs struct from a dwarf2_cu struct.  */
4651
4652 static void
4653 init_cu_die_reader (struct die_reader_specs *reader,
4654                     struct dwarf2_cu *cu,
4655                     struct dwarf2_section_info *section,
4656                     struct dwo_file *dwo_file)
4657 {
4658   gdb_assert (section->readin && section->buffer != NULL);
4659   reader->abfd = section->asection->owner;
4660   reader->cu = cu;
4661   reader->dwo_file = dwo_file;
4662   reader->die_section = section;
4663   reader->buffer = section->buffer;
4664   reader->buffer_end = section->buffer + section->size;
4665   reader->comp_dir = NULL;
4666 }
4667
4668 /* Subroutine of init_cutu_and_read_dies to simplify it.
4669    Read in the rest of a CU/TU top level DIE from DWO_UNIT.
4670    There's just a lot of work to do, and init_cutu_and_read_dies is big enough
4671    already.
4672
4673    STUB_COMP_UNIT_DIE is for the stub DIE, we copy over certain attributes
4674    from it to the DIE in the DWO.  If NULL we are skipping the stub.
4675    STUB_COMP_DIR is similar to STUB_COMP_UNIT_DIE: When reading a TU directly
4676    from the DWO file, bypassing the stub, it contains the DW_AT_comp_dir
4677    attribute of the referencing CU.  Exactly one of STUB_COMP_UNIT_DIE and
4678    COMP_DIR must be non-NULL.
4679    *RESULT_READER,*RESULT_INFO_PTR,*RESULT_COMP_UNIT_DIE,*RESULT_HAS_CHILDREN
4680    are filled in with the info of the DIE from the DWO file.
4681    ABBREV_TABLE_PROVIDED is non-zero if the caller of init_cutu_and_read_dies
4682    provided an abbrev table to use.
4683    The result is non-zero if a valid (non-dummy) DIE was found.  */
4684
4685 static int
4686 read_cutu_die_from_dwo (struct dwarf2_per_cu_data *this_cu,
4687                         struct dwo_unit *dwo_unit,
4688                         int abbrev_table_provided,
4689                         struct die_info *stub_comp_unit_die,
4690                         const char *stub_comp_dir,
4691                         struct die_reader_specs *result_reader,
4692                         const gdb_byte **result_info_ptr,
4693                         struct die_info **result_comp_unit_die,
4694                         int *result_has_children)
4695 {
4696   struct objfile *objfile = dwarf2_per_objfile->objfile;
4697   struct dwarf2_cu *cu = this_cu->cu;
4698   struct dwarf2_section_info *section;
4699   bfd *abfd;
4700   const gdb_byte *begin_info_ptr, *info_ptr;
4701   const char *comp_dir_string;
4702   ULONGEST signature; /* Or dwo_id.  */
4703   struct attribute *comp_dir, *stmt_list, *low_pc, *high_pc, *ranges;
4704   int i,num_extra_attrs;
4705   struct dwarf2_section_info *dwo_abbrev_section;
4706   struct attribute *attr;
4707   struct attribute comp_dir_attr;
4708   struct die_info *comp_unit_die;
4709
4710   /* Both can't be provided.  */
4711   gdb_assert (! (stub_comp_unit_die && stub_comp_dir));
4712
4713   /* These attributes aren't processed until later:
4714      DW_AT_stmt_list, DW_AT_low_pc, DW_AT_high_pc, DW_AT_ranges.
4715      However, the attribute is found in the stub which we won't have later.
4716      In order to not impose this complication on the rest of the code,
4717      we read them here and copy them to the DWO CU/TU die.  */
4718
4719   stmt_list = NULL;
4720   low_pc = NULL;
4721   high_pc = NULL;
4722   ranges = NULL;
4723   comp_dir = NULL;
4724
4725   if (stub_comp_unit_die != NULL)
4726     {
4727       /* For TUs in DWO files, the DW_AT_stmt_list attribute lives in the
4728          DWO file.  */
4729       if (! this_cu->is_debug_types)
4730         stmt_list = dwarf2_attr (stub_comp_unit_die, DW_AT_stmt_list, cu);
4731       low_pc = dwarf2_attr (stub_comp_unit_die, DW_AT_low_pc, cu);
4732       high_pc = dwarf2_attr (stub_comp_unit_die, DW_AT_high_pc, cu);
4733       ranges = dwarf2_attr (stub_comp_unit_die, DW_AT_ranges, cu);
4734       comp_dir = dwarf2_attr (stub_comp_unit_die, DW_AT_comp_dir, cu);
4735
4736       /* There should be a DW_AT_addr_base attribute here (if needed).
4737          We need the value before we can process DW_FORM_GNU_addr_index.  */
4738       cu->addr_base = 0;
4739       attr = dwarf2_attr (stub_comp_unit_die, DW_AT_GNU_addr_base, cu);
4740       if (attr)
4741         cu->addr_base = DW_UNSND (attr);
4742
4743       /* There should be a DW_AT_ranges_base attribute here (if needed).
4744          We need the value before we can process DW_AT_ranges.  */
4745       cu->ranges_base = 0;
4746       attr = dwarf2_attr (stub_comp_unit_die, DW_AT_GNU_ranges_base, cu);
4747       if (attr)
4748         cu->ranges_base = DW_UNSND (attr);
4749     }
4750   else if (stub_comp_dir != NULL)
4751     {
4752       /* Reconstruct the comp_dir attribute to simplify the code below.  */
4753       comp_dir = (struct attribute *)
4754         obstack_alloc (&cu->comp_unit_obstack, sizeof (*comp_dir));
4755       comp_dir->name = DW_AT_comp_dir;
4756       comp_dir->form = DW_FORM_string;
4757       DW_STRING_IS_CANONICAL (comp_dir) = 0;
4758       DW_STRING (comp_dir) = stub_comp_dir;
4759     }
4760
4761   /* Set up for reading the DWO CU/TU.  */
4762   cu->dwo_unit = dwo_unit;
4763   section = dwo_unit->section;
4764   dwarf2_read_section (objfile, section);
4765   abfd = section->asection->owner;
4766   begin_info_ptr = info_ptr = section->buffer + dwo_unit->offset.sect_off;
4767   dwo_abbrev_section = &dwo_unit->dwo_file->sections.abbrev;
4768   init_cu_die_reader (result_reader, cu, section, dwo_unit->dwo_file);
4769
4770   if (this_cu->is_debug_types)
4771     {
4772       ULONGEST header_signature;
4773       cu_offset type_offset_in_tu;
4774       struct signatured_type *sig_type = (struct signatured_type *) this_cu;
4775
4776       info_ptr = read_and_check_type_unit_head (&cu->header, section,
4777                                                 dwo_abbrev_section,
4778                                                 info_ptr,
4779                                                 &header_signature,
4780                                                 &type_offset_in_tu);
4781       /* This is not an assert because it can be caused by bad debug info.  */
4782       if (sig_type->signature != header_signature)
4783         {
4784           error (_("Dwarf Error: signature mismatch %s vs %s while reading"
4785                    " TU at offset 0x%x [in module %s]"),
4786                  hex_string (sig_type->signature),
4787                  hex_string (header_signature),
4788                  dwo_unit->offset.sect_off,
4789                  bfd_get_filename (abfd));
4790         }
4791       gdb_assert (dwo_unit->offset.sect_off == cu->header.offset.sect_off);
4792       /* For DWOs coming from DWP files, we don't know the CU length
4793          nor the type's offset in the TU until now.  */
4794       dwo_unit->length = get_cu_length (&cu->header);
4795       dwo_unit->type_offset_in_tu = type_offset_in_tu;
4796
4797       /* Establish the type offset that can be used to lookup the type.
4798          For DWO files, we don't know it until now.  */
4799       sig_type->type_offset_in_section.sect_off =
4800         dwo_unit->offset.sect_off + dwo_unit->type_offset_in_tu.cu_off;
4801     }
4802   else
4803     {
4804       info_ptr = read_and_check_comp_unit_head (&cu->header, section,
4805                                                 dwo_abbrev_section,
4806                                                 info_ptr, 0);
4807       gdb_assert (dwo_unit->offset.sect_off == cu->header.offset.sect_off);
4808       /* For DWOs coming from DWP files, we don't know the CU length
4809          until now.  */
4810       dwo_unit->length = get_cu_length (&cu->header);
4811     }
4812
4813   /* Replace the CU's original abbrev table with the DWO's.
4814      Reminder: We can't read the abbrev table until we've read the header.  */
4815   if (abbrev_table_provided)
4816     {
4817       /* Don't free the provided abbrev table, the caller of
4818          init_cutu_and_read_dies owns it.  */
4819       dwarf2_read_abbrevs (cu, dwo_abbrev_section);
4820       /* Ensure the DWO abbrev table gets freed.  */
4821       make_cleanup (dwarf2_free_abbrev_table, cu);
4822     }
4823   else
4824     {
4825       dwarf2_free_abbrev_table (cu);
4826       dwarf2_read_abbrevs (cu, dwo_abbrev_section);
4827       /* Leave any existing abbrev table cleanup as is.  */
4828     }
4829
4830   /* Read in the die, but leave space to copy over the attributes
4831      from the stub.  This has the benefit of simplifying the rest of
4832      the code - all the work to maintain the illusion of a single
4833      DW_TAG_{compile,type}_unit DIE is done here.  */
4834   num_extra_attrs = ((stmt_list != NULL)
4835                      + (low_pc != NULL)
4836                      + (high_pc != NULL)
4837                      + (ranges != NULL)
4838                      + (comp_dir != NULL));
4839   info_ptr = read_full_die_1 (result_reader, result_comp_unit_die, info_ptr,
4840                               result_has_children, num_extra_attrs);
4841
4842   /* Copy over the attributes from the stub to the DIE we just read in.  */
4843   comp_unit_die = *result_comp_unit_die;
4844   i = comp_unit_die->num_attrs;
4845   if (stmt_list != NULL)
4846     comp_unit_die->attrs[i++] = *stmt_list;
4847   if (low_pc != NULL)
4848     comp_unit_die->attrs[i++] = *low_pc;
4849   if (high_pc != NULL)
4850     comp_unit_die->attrs[i++] = *high_pc;
4851   if (ranges != NULL)
4852     comp_unit_die->attrs[i++] = *ranges;
4853   if (comp_dir != NULL)
4854     comp_unit_die->attrs[i++] = *comp_dir;
4855   comp_unit_die->num_attrs += num_extra_attrs;
4856
4857   if (dwarf2_die_debug)
4858     {
4859       fprintf_unfiltered (gdb_stdlog,
4860                           "Read die from %s@0x%x of %s:\n",
4861                           bfd_section_name (abfd, section->asection),
4862                           (unsigned) (begin_info_ptr - section->buffer),
4863                           bfd_get_filename (abfd));
4864       dump_die (comp_unit_die, dwarf2_die_debug);
4865     }
4866
4867   /* Save the comp_dir attribute.  If there is no DWP file then we'll read
4868      TUs by skipping the stub and going directly to the entry in the DWO file.
4869      However, skipping the stub means we won't get DW_AT_comp_dir, so we have
4870      to get it via circuitous means.  Blech.  */
4871   if (comp_dir != NULL)
4872     result_reader->comp_dir = DW_STRING (comp_dir);
4873
4874   /* Skip dummy compilation units.  */
4875   if (info_ptr >= begin_info_ptr + dwo_unit->length
4876       || peek_abbrev_code (abfd, info_ptr) == 0)
4877     return 0;
4878
4879   *result_info_ptr = info_ptr;
4880   return 1;
4881 }
4882
4883 /* Subroutine of init_cutu_and_read_dies to simplify it.
4884    Look up the DWO unit specified by COMP_UNIT_DIE of THIS_CU.
4885    Returns NULL if the specified DWO unit cannot be found.  */
4886
4887 static struct dwo_unit *
4888 lookup_dwo_unit (struct dwarf2_per_cu_data *this_cu,
4889                  struct die_info *comp_unit_die)
4890 {
4891   struct dwarf2_cu *cu = this_cu->cu;
4892   struct attribute *attr;
4893   ULONGEST signature;
4894   struct dwo_unit *dwo_unit;
4895   const char *comp_dir, *dwo_name;
4896
4897   gdb_assert (cu != NULL);
4898
4899   /* Yeah, we look dwo_name up again, but it simplifies the code.  */
4900   attr = dwarf2_attr (comp_unit_die, DW_AT_GNU_dwo_name, cu);
4901   gdb_assert (attr != NULL);
4902   dwo_name = DW_STRING (attr);
4903   comp_dir = NULL;
4904   attr = dwarf2_attr (comp_unit_die, DW_AT_comp_dir, cu);
4905   if (attr)
4906     comp_dir = DW_STRING (attr);
4907
4908   if (this_cu->is_debug_types)
4909     {
4910       struct signatured_type *sig_type;
4911
4912       /* Since this_cu is the first member of struct signatured_type,
4913          we can go from a pointer to one to a pointer to the other.  */
4914       sig_type = (struct signatured_type *) this_cu;
4915       signature = sig_type->signature;
4916       dwo_unit = lookup_dwo_type_unit (sig_type, dwo_name, comp_dir);
4917     }
4918   else
4919     {
4920       struct attribute *attr;
4921
4922       attr = dwarf2_attr (comp_unit_die, DW_AT_GNU_dwo_id, cu);
4923       if (! attr)
4924         error (_("Dwarf Error: missing dwo_id for dwo_name %s"
4925                  " [in module %s]"),
4926                dwo_name, this_cu->objfile->name);
4927       signature = DW_UNSND (attr);
4928       dwo_unit = lookup_dwo_comp_unit (this_cu, dwo_name, comp_dir,
4929                                        signature);
4930     }
4931
4932   return dwo_unit;
4933 }
4934
4935 /* Subroutine of init_cutu_and_read_dies to simplify it.
4936    Read a TU directly from a DWO file, bypassing the stub.  */
4937
4938 static void
4939 init_tu_and_read_dwo_dies (struct dwarf2_per_cu_data *this_cu, int keep,
4940                            die_reader_func_ftype *die_reader_func,
4941                            void *data)
4942 {
4943   struct dwarf2_cu *cu;
4944   struct signatured_type *sig_type;
4945   struct cleanup *cleanups, *free_cu_cleanup;
4946   struct die_reader_specs reader;
4947   const gdb_byte *info_ptr;
4948   struct die_info *comp_unit_die;
4949   int has_children;
4950
4951   /* Verify we can do the following downcast, and that we have the
4952      data we need.  */
4953   gdb_assert (this_cu->is_debug_types && this_cu->reading_dwo_directly);
4954   sig_type = (struct signatured_type *) this_cu;
4955   gdb_assert (sig_type->dwo_unit != NULL);
4956
4957   cleanups = make_cleanup (null_cleanup, NULL);
4958
4959   gdb_assert (this_cu->cu == NULL);
4960   cu = xmalloc (sizeof (*cu));
4961   init_one_comp_unit (cu, this_cu);
4962   /* If an error occurs while loading, release our storage.  */
4963   free_cu_cleanup = make_cleanup (free_heap_comp_unit, cu);
4964
4965   if (read_cutu_die_from_dwo (this_cu, sig_type->dwo_unit,
4966                               0 /* abbrev_table_provided */,
4967                               NULL /* stub_comp_unit_die */,
4968                               sig_type->dwo_unit->dwo_file->comp_dir,
4969                               &reader, &info_ptr,
4970                               &comp_unit_die, &has_children) == 0)
4971     {
4972       /* Dummy die.  */
4973       do_cleanups (cleanups);
4974       return;
4975     }
4976
4977   /* All the "real" work is done here.  */
4978   die_reader_func (&reader, info_ptr, comp_unit_die, has_children, data);
4979
4980   /* This duplicates some code in init_cutu_and_read_dies,
4981      but the alternative is making the latter more complex.
4982      This function is only for the special case of using DWO files directly:
4983      no point in overly complicating the general case just to handle this.  */
4984   if (keep)
4985     {
4986       /* We've successfully allocated this compilation unit.  Let our
4987          caller clean it up when finished with it.  */
4988       discard_cleanups (free_cu_cleanup);
4989
4990       /* We can only discard free_cu_cleanup and all subsequent cleanups.
4991          So we have to manually free the abbrev table.  */
4992       dwarf2_free_abbrev_table (cu);
4993
4994       /* Link this CU into read_in_chain.  */
4995       this_cu->cu->read_in_chain = dwarf2_per_objfile->read_in_chain;
4996       dwarf2_per_objfile->read_in_chain = this_cu;
4997     }
4998   else
4999     do_cleanups (free_cu_cleanup);
5000
5001   do_cleanups (cleanups);
5002 }
5003
5004 /* Initialize a CU (or TU) and read its DIEs.
5005    If the CU defers to a DWO file, read the DWO file as well.
5006
5007    ABBREV_TABLE, if non-NULL, is the abbreviation table to use.
5008    Otherwise the table specified in the comp unit header is read in and used.
5009    This is an optimization for when we already have the abbrev table.
5010
5011    If USE_EXISTING_CU is non-zero, and THIS_CU->cu is non-NULL, then use it.
5012    Otherwise, a new CU is allocated with xmalloc.
5013
5014    If KEEP is non-zero, then if we allocated a dwarf2_cu we add it to
5015    read_in_chain.  Otherwise the dwarf2_cu data is freed at the end.
5016
5017    WARNING: If THIS_CU is a "dummy CU" (used as filler by the incremental
5018    linker) then DIE_READER_FUNC will not get called.  */
5019
5020 static void
5021 init_cutu_and_read_dies (struct dwarf2_per_cu_data *this_cu,
5022                          struct abbrev_table *abbrev_table,
5023                          int use_existing_cu, int keep,
5024                          die_reader_func_ftype *die_reader_func,
5025                          void *data)
5026 {
5027   struct objfile *objfile = dwarf2_per_objfile->objfile;
5028   struct dwarf2_section_info *section = this_cu->section;
5029   bfd *abfd = section->asection->owner;
5030   struct dwarf2_cu *cu;
5031   const gdb_byte *begin_info_ptr, *info_ptr;
5032   struct die_reader_specs reader;
5033   struct die_info *comp_unit_die;
5034   int has_children;
5035   struct attribute *attr;
5036   struct cleanup *cleanups, *free_cu_cleanup = NULL;
5037   struct signatured_type *sig_type = NULL;
5038   struct dwarf2_section_info *abbrev_section;
5039   /* Non-zero if CU currently points to a DWO file and we need to
5040      reread it.  When this happens we need to reread the skeleton die
5041      before we can reread the DWO file (this only applies to CUs, not TUs).  */
5042   int rereading_dwo_cu = 0;
5043
5044   if (dwarf2_die_debug)
5045     fprintf_unfiltered (gdb_stdlog, "Reading %s unit at offset 0x%x\n",
5046                         this_cu->is_debug_types ? "type" : "comp",
5047                         this_cu->offset.sect_off);
5048
5049   if (use_existing_cu)
5050     gdb_assert (keep);
5051
5052   /* If we're reading a TU directly from a DWO file, including a virtual DWO
5053      file (instead of going through the stub), short-circuit all of this.  */
5054   if (this_cu->reading_dwo_directly)
5055     {
5056       /* Narrow down the scope of possibilities to have to understand.  */
5057       gdb_assert (this_cu->is_debug_types);
5058       gdb_assert (abbrev_table == NULL);
5059       gdb_assert (!use_existing_cu);
5060       init_tu_and_read_dwo_dies (this_cu, keep, die_reader_func, data);
5061       return;
5062     }
5063
5064   cleanups = make_cleanup (null_cleanup, NULL);
5065
5066   /* This is cheap if the section is already read in.  */
5067   dwarf2_read_section (objfile, section);
5068
5069   begin_info_ptr = info_ptr = section->buffer + this_cu->offset.sect_off;
5070
5071   abbrev_section = get_abbrev_section_for_cu (this_cu);
5072
5073   if (use_existing_cu && this_cu->cu != NULL)
5074     {
5075       cu = this_cu->cu;
5076
5077       /* If this CU is from a DWO file we need to start over, we need to
5078          refetch the attributes from the skeleton CU.
5079          This could be optimized by retrieving those attributes from when we
5080          were here the first time: the previous comp_unit_die was stored in
5081          comp_unit_obstack.  But there's no data yet that we need this
5082          optimization.  */
5083       if (cu->dwo_unit != NULL)
5084         rereading_dwo_cu = 1;
5085     }
5086   else
5087     {
5088       /* If !use_existing_cu, this_cu->cu must be NULL.  */
5089       gdb_assert (this_cu->cu == NULL);
5090
5091       cu = xmalloc (sizeof (*cu));
5092       init_one_comp_unit (cu, this_cu);
5093
5094       /* If an error occurs while loading, release our storage.  */
5095       free_cu_cleanup = make_cleanup (free_heap_comp_unit, cu);
5096     }
5097
5098   /* Get the header.  */
5099   if (cu->header.first_die_offset.cu_off != 0 && ! rereading_dwo_cu)
5100     {
5101       /* We already have the header, there's no need to read it in again.  */
5102       info_ptr += cu->header.first_die_offset.cu_off;
5103     }
5104   else
5105     {
5106       if (this_cu->is_debug_types)
5107         {
5108           ULONGEST signature;
5109           cu_offset type_offset_in_tu;
5110
5111           info_ptr = read_and_check_type_unit_head (&cu->header, section,
5112                                                     abbrev_section, info_ptr,
5113                                                     &signature,
5114                                                     &type_offset_in_tu);
5115
5116           /* Since per_cu is the first member of struct signatured_type,
5117              we can go from a pointer to one to a pointer to the other.  */
5118           sig_type = (struct signatured_type *) this_cu;
5119           gdb_assert (sig_type->signature == signature);
5120           gdb_assert (sig_type->type_offset_in_tu.cu_off
5121                       == type_offset_in_tu.cu_off);
5122           gdb_assert (this_cu->offset.sect_off == cu->header.offset.sect_off);
5123
5124           /* LENGTH has not been set yet for type units if we're
5125              using .gdb_index.  */
5126           this_cu->length = get_cu_length (&cu->header);
5127
5128           /* Establish the type offset that can be used to lookup the type.  */
5129           sig_type->type_offset_in_section.sect_off =
5130             this_cu->offset.sect_off + sig_type->type_offset_in_tu.cu_off;
5131         }
5132       else
5133         {
5134           info_ptr = read_and_check_comp_unit_head (&cu->header, section,
5135                                                     abbrev_section,
5136                                                     info_ptr, 0);
5137
5138           gdb_assert (this_cu->offset.sect_off == cu->header.offset.sect_off);
5139           gdb_assert (this_cu->length == get_cu_length (&cu->header));
5140         }
5141     }
5142
5143   /* Skip dummy compilation units.  */
5144   if (info_ptr >= begin_info_ptr + this_cu->length
5145       || peek_abbrev_code (abfd, info_ptr) == 0)
5146     {
5147       do_cleanups (cleanups);
5148       return;
5149     }
5150
5151   /* If we don't have them yet, read the abbrevs for this compilation unit.
5152      And if we need to read them now, make sure they're freed when we're
5153      done.  Note that it's important that if the CU had an abbrev table
5154      on entry we don't free it when we're done: Somewhere up the call stack
5155      it may be in use.  */
5156   if (abbrev_table != NULL)
5157     {
5158       gdb_assert (cu->abbrev_table == NULL);
5159       gdb_assert (cu->header.abbrev_offset.sect_off
5160                   == abbrev_table->offset.sect_off);
5161       cu->abbrev_table = abbrev_table;
5162     }
5163   else if (cu->abbrev_table == NULL)
5164     {
5165       dwarf2_read_abbrevs (cu, abbrev_section);
5166       make_cleanup (dwarf2_free_abbrev_table, cu);
5167     }
5168   else if (rereading_dwo_cu)
5169     {
5170       dwarf2_free_abbrev_table (cu);
5171       dwarf2_read_abbrevs (cu, abbrev_section);
5172     }
5173
5174   /* Read the top level CU/TU die.  */
5175   init_cu_die_reader (&reader, cu, section, NULL);
5176   info_ptr = read_full_die (&reader, &comp_unit_die, info_ptr, &has_children);
5177
5178   /* If we are in a DWO stub, process it and then read in the "real" CU/TU
5179      from the DWO file.
5180      Note that if USE_EXISTING_OK != 0, and THIS_CU->cu already contains a
5181      DWO CU, that this test will fail (the attribute will not be present).  */
5182   attr = dwarf2_attr (comp_unit_die, DW_AT_GNU_dwo_name, cu);
5183   if (attr)
5184     {
5185       struct dwo_unit *dwo_unit;
5186       struct die_info *dwo_comp_unit_die;
5187
5188       if (has_children)
5189         {
5190           complaint (&symfile_complaints,
5191                      _("compilation unit with DW_AT_GNU_dwo_name"
5192                        " has children (offset 0x%x) [in module %s]"),
5193                      this_cu->offset.sect_off, bfd_get_filename (abfd));
5194         }
5195       dwo_unit = lookup_dwo_unit (this_cu, comp_unit_die);
5196       if (dwo_unit != NULL)
5197         {
5198           if (read_cutu_die_from_dwo (this_cu, dwo_unit,
5199                                       abbrev_table != NULL,
5200                                       comp_unit_die, NULL,
5201                                       &reader, &info_ptr,
5202                                       &dwo_comp_unit_die, &has_children) == 0)
5203             {
5204               /* Dummy die.  */
5205               do_cleanups (cleanups);
5206               return;
5207             }
5208           comp_unit_die = dwo_comp_unit_die;
5209         }
5210       else
5211         {
5212           /* Yikes, we couldn't find the rest of the DIE, we only have
5213              the stub.  A complaint has already been logged.  There's
5214              not much more we can do except pass on the stub DIE to
5215              die_reader_func.  We don't want to throw an error on bad
5216              debug info.  */
5217         }
5218     }
5219
5220   /* All of the above is setup for this call.  Yikes.  */
5221   die_reader_func (&reader, info_ptr, comp_unit_die, has_children, data);
5222
5223   /* Done, clean up.  */
5224   if (free_cu_cleanup != NULL)
5225     {
5226       if (keep)
5227         {
5228           /* We've successfully allocated this compilation unit.  Let our
5229              caller clean it up when finished with it.  */
5230           discard_cleanups (free_cu_cleanup);
5231
5232           /* We can only discard free_cu_cleanup and all subsequent cleanups.
5233              So we have to manually free the abbrev table.  */
5234           dwarf2_free_abbrev_table (cu);
5235
5236           /* Link this CU into read_in_chain.  */
5237           this_cu->cu->read_in_chain = dwarf2_per_objfile->read_in_chain;
5238           dwarf2_per_objfile->read_in_chain = this_cu;
5239         }
5240       else
5241         do_cleanups (free_cu_cleanup);
5242     }
5243
5244   do_cleanups (cleanups);
5245 }
5246
5247 /* Read CU/TU THIS_CU in section SECTION,
5248    but do not follow DW_AT_GNU_dwo_name if present.
5249    DWOP_FILE, if non-NULL, is the DWO/DWP file to read (the caller is assumed
5250    to have already done the lookup to find the DWO/DWP file).
5251
5252    The caller is required to fill in THIS_CU->section, THIS_CU->offset, and
5253    THIS_CU->is_debug_types, but nothing else.
5254
5255    We fill in THIS_CU->length.
5256
5257    WARNING: If THIS_CU is a "dummy CU" (used as filler by the incremental
5258    linker) then DIE_READER_FUNC will not get called.
5259
5260    THIS_CU->cu is always freed when done.
5261    This is done in order to not leave THIS_CU->cu in a state where we have
5262    to care whether it refers to the "main" CU or the DWO CU.  */
5263
5264 static void
5265 init_cutu_and_read_dies_no_follow (struct dwarf2_per_cu_data *this_cu,
5266                                    struct dwarf2_section_info *abbrev_section,
5267                                    struct dwo_file *dwo_file,
5268                                    die_reader_func_ftype *die_reader_func,
5269                                    void *data)
5270 {
5271   struct objfile *objfile = dwarf2_per_objfile->objfile;
5272   struct dwarf2_section_info *section = this_cu->section;
5273   bfd *abfd = section->asection->owner;
5274   struct dwarf2_cu cu;
5275   const gdb_byte *begin_info_ptr, *info_ptr;
5276   struct die_reader_specs reader;
5277   struct cleanup *cleanups;
5278   struct die_info *comp_unit_die;
5279   int has_children;
5280
5281   if (dwarf2_die_debug)
5282     fprintf_unfiltered (gdb_stdlog, "Reading %s unit at offset 0x%x\n",
5283                         this_cu->is_debug_types ? "type" : "comp",
5284                         this_cu->offset.sect_off);
5285
5286   gdb_assert (this_cu->cu == NULL);
5287
5288   /* This is cheap if the section is already read in.  */
5289   dwarf2_read_section (objfile, section);
5290
5291   init_one_comp_unit (&cu, this_cu);
5292
5293   cleanups = make_cleanup (free_stack_comp_unit, &cu);
5294
5295   begin_info_ptr = info_ptr = section->buffer + this_cu->offset.sect_off;
5296   info_ptr = read_and_check_comp_unit_head (&cu.header, section,
5297                                             abbrev_section, info_ptr,
5298                                             this_cu->is_debug_types);
5299
5300   this_cu->length = get_cu_length (&cu.header);
5301
5302   /* Skip dummy compilation units.  */
5303   if (info_ptr >= begin_info_ptr + this_cu->length
5304       || peek_abbrev_code (abfd, info_ptr) == 0)
5305     {
5306       do_cleanups (cleanups);
5307       return;
5308     }
5309
5310   dwarf2_read_abbrevs (&cu, abbrev_section);
5311   make_cleanup (dwarf2_free_abbrev_table, &cu);
5312
5313   init_cu_die_reader (&reader, &cu, section, dwo_file);
5314   info_ptr = read_full_die (&reader, &comp_unit_die, info_ptr, &has_children);
5315
5316   die_reader_func (&reader, info_ptr, comp_unit_die, has_children, data);
5317
5318   do_cleanups (cleanups);
5319 }
5320
5321 /* Read a CU/TU, except that this does not look for DW_AT_GNU_dwo_name and
5322    does not lookup the specified DWO file.
5323    This cannot be used to read DWO files.
5324
5325    THIS_CU->cu is always freed when done.
5326    This is done in order to not leave THIS_CU->cu in a state where we have
5327    to care whether it refers to the "main" CU or the DWO CU.
5328    We can revisit this if the data shows there's a performance issue.  */
5329
5330 static void
5331 init_cutu_and_read_dies_simple (struct dwarf2_per_cu_data *this_cu,
5332                                 die_reader_func_ftype *die_reader_func,
5333                                 void *data)
5334 {
5335   init_cutu_and_read_dies_no_follow (this_cu,
5336                                      get_abbrev_section_for_cu (this_cu),
5337                                      NULL,
5338                                      die_reader_func, data);
5339 }
5340 \f
5341 /* Type Unit Groups.
5342
5343    Type Unit Groups are a way to collapse the set of all TUs (type units) into
5344    a more manageable set.  The grouping is done by DW_AT_stmt_list entry
5345    so that all types coming from the same compilation (.o file) are grouped
5346    together.  A future step could be to put the types in the same symtab as
5347    the CU the types ultimately came from.  */
5348
5349 static hashval_t
5350 hash_type_unit_group (const void *item)
5351 {
5352   const struct type_unit_group *tu_group = item;
5353
5354   return hash_stmt_list_entry (&tu_group->hash);
5355 }
5356
5357 static int
5358 eq_type_unit_group (const void *item_lhs, const void *item_rhs)
5359 {
5360   const struct type_unit_group *lhs = item_lhs;
5361   const struct type_unit_group *rhs = item_rhs;
5362
5363   return eq_stmt_list_entry (&lhs->hash, &rhs->hash);
5364 }
5365
5366 /* Allocate a hash table for type unit groups.  */
5367
5368 static htab_t
5369 allocate_type_unit_groups_table (void)
5370 {
5371   return htab_create_alloc_ex (3,
5372                                hash_type_unit_group,
5373                                eq_type_unit_group,
5374                                NULL,
5375                                &dwarf2_per_objfile->objfile->objfile_obstack,
5376                                hashtab_obstack_allocate,
5377                                dummy_obstack_deallocate);
5378 }
5379
5380 /* Type units that don't have DW_AT_stmt_list are grouped into their own
5381    partial symtabs.  We combine several TUs per psymtab to not let the size
5382    of any one psymtab grow too big.  */
5383 #define NO_STMT_LIST_TYPE_UNIT_PSYMTAB (1 << 31)
5384 #define NO_STMT_LIST_TYPE_UNIT_PSYMTAB_SIZE 10
5385
5386 /* Helper routine for get_type_unit_group.
5387    Create the type_unit_group object used to hold one or more TUs.  */
5388
5389 static struct type_unit_group *
5390 create_type_unit_group (struct dwarf2_cu *cu, sect_offset line_offset_struct)
5391 {
5392   struct objfile *objfile = dwarf2_per_objfile->objfile;
5393   struct dwarf2_per_cu_data *per_cu;
5394   struct type_unit_group *tu_group;
5395
5396   tu_group = OBSTACK_ZALLOC (&objfile->objfile_obstack,
5397                              struct type_unit_group);
5398   per_cu = &tu_group->per_cu;
5399   per_cu->objfile = objfile;
5400
5401   if (dwarf2_per_objfile->using_index)
5402     {
5403       per_cu->v.quick = OBSTACK_ZALLOC (&objfile->objfile_obstack,
5404                                         struct dwarf2_per_cu_quick_data);
5405     }
5406   else
5407     {
5408       unsigned int line_offset = line_offset_struct.sect_off;
5409       struct partial_symtab *pst;
5410       char *name;
5411
5412       /* Give the symtab a useful name for debug purposes.  */
5413       if ((line_offset & NO_STMT_LIST_TYPE_UNIT_PSYMTAB) != 0)
5414         name = xstrprintf ("<type_units_%d>",
5415                            (line_offset & ~NO_STMT_LIST_TYPE_UNIT_PSYMTAB));
5416       else
5417         name = xstrprintf ("<type_units_at_0x%x>", line_offset);
5418
5419       pst = create_partial_symtab (per_cu, name);
5420       pst->anonymous = 1;
5421
5422       xfree (name);
5423     }
5424
5425   tu_group->hash.dwo_unit = cu->dwo_unit;
5426   tu_group->hash.line_offset = line_offset_struct;
5427
5428   return tu_group;
5429 }
5430
5431 /* Look up the type_unit_group for type unit CU, and create it if necessary.
5432    STMT_LIST is a DW_AT_stmt_list attribute.  */
5433
5434 static struct type_unit_group *
5435 get_type_unit_group (struct dwarf2_cu *cu, const struct attribute *stmt_list)
5436 {
5437   struct tu_stats *tu_stats = &dwarf2_per_objfile->tu_stats;
5438   struct type_unit_group *tu_group;
5439   void **slot;
5440   unsigned int line_offset;
5441   struct type_unit_group type_unit_group_for_lookup;
5442
5443   if (dwarf2_per_objfile->type_unit_groups == NULL)
5444     {
5445       dwarf2_per_objfile->type_unit_groups =
5446         allocate_type_unit_groups_table ();
5447     }
5448
5449   /* Do we need to create a new group, or can we use an existing one?  */
5450
5451   if (stmt_list)
5452     {
5453       line_offset = DW_UNSND (stmt_list);
5454       ++tu_stats->nr_symtab_sharers;
5455     }
5456   else
5457     {
5458       /* Ugh, no stmt_list.  Rare, but we have to handle it.
5459          We can do various things here like create one group per TU or
5460          spread them over multiple groups to split up the expansion work.
5461          To avoid worst case scenarios (too many groups or too large groups)
5462          we, umm, group them in bunches.  */
5463       line_offset = (NO_STMT_LIST_TYPE_UNIT_PSYMTAB
5464                      | (tu_stats->nr_stmt_less_type_units
5465                         / NO_STMT_LIST_TYPE_UNIT_PSYMTAB_SIZE));
5466       ++tu_stats->nr_stmt_less_type_units;
5467     }
5468
5469   type_unit_group_for_lookup.hash.dwo_unit = cu->dwo_unit;
5470   type_unit_group_for_lookup.hash.line_offset.sect_off = line_offset;
5471   slot = htab_find_slot (dwarf2_per_objfile->type_unit_groups,
5472                          &type_unit_group_for_lookup, INSERT);
5473   if (*slot != NULL)
5474     {
5475       tu_group = *slot;
5476       gdb_assert (tu_group != NULL);
5477     }
5478   else
5479     {
5480       sect_offset line_offset_struct;
5481
5482       line_offset_struct.sect_off = line_offset;
5483       tu_group = create_type_unit_group (cu, line_offset_struct);
5484       *slot = tu_group;
5485       ++tu_stats->nr_symtabs;
5486     }
5487
5488   return tu_group;
5489 }
5490
5491 /* Struct used to sort TUs by their abbreviation table offset.  */
5492
5493 struct tu_abbrev_offset
5494 {
5495   struct signatured_type *sig_type;
5496   sect_offset abbrev_offset;
5497 };
5498
5499 /* Helper routine for build_type_unit_groups, passed to qsort.  */
5500
5501 static int
5502 sort_tu_by_abbrev_offset (const void *ap, const void *bp)
5503 {
5504   const struct tu_abbrev_offset * const *a = ap;
5505   const struct tu_abbrev_offset * const *b = bp;
5506   unsigned int aoff = (*a)->abbrev_offset.sect_off;
5507   unsigned int boff = (*b)->abbrev_offset.sect_off;
5508
5509   return (aoff > boff) - (aoff < boff);
5510 }
5511
5512 /* A helper function to add a type_unit_group to a table.  */
5513
5514 static int
5515 add_type_unit_group_to_table (void **slot, void *datum)
5516 {
5517   struct type_unit_group *tu_group = *slot;
5518   struct type_unit_group ***datap = datum;
5519
5520   **datap = tu_group;
5521   ++*datap;
5522
5523   return 1;
5524 }
5525
5526 /* Efficiently read all the type units, calling init_cutu_and_read_dies on
5527    each one passing FUNC,DATA.
5528
5529    The efficiency is because we sort TUs by the abbrev table they use and
5530    only read each abbrev table once.  In one program there are 200K TUs
5531    sharing 8K abbrev tables.
5532
5533    The main purpose of this function is to support building the
5534    dwarf2_per_objfile->type_unit_groups table.
5535    TUs typically share the DW_AT_stmt_list of the CU they came from, so we
5536    can collapse the search space by grouping them by stmt_list.
5537    The savings can be significant, in the same program from above the 200K TUs
5538    share 8K stmt_list tables.
5539
5540    FUNC is expected to call get_type_unit_group, which will create the
5541    struct type_unit_group if necessary and add it to
5542    dwarf2_per_objfile->type_unit_groups.  */
5543
5544 static void
5545 build_type_unit_groups (die_reader_func_ftype *func, void *data)
5546 {
5547   struct objfile *objfile = dwarf2_per_objfile->objfile;
5548   struct tu_stats *tu_stats = &dwarf2_per_objfile->tu_stats;
5549   struct cleanup *cleanups;
5550   struct abbrev_table *abbrev_table;
5551   sect_offset abbrev_offset;
5552   struct tu_abbrev_offset *sorted_by_abbrev;
5553   struct type_unit_group **iter;
5554   int i;
5555
5556   /* It's up to the caller to not call us multiple times.  */
5557   gdb_assert (dwarf2_per_objfile->type_unit_groups == NULL);
5558
5559   if (dwarf2_per_objfile->n_type_units == 0)
5560     return;
5561
5562   /* TUs typically share abbrev tables, and there can be way more TUs than
5563      abbrev tables.  Sort by abbrev table to reduce the number of times we
5564      read each abbrev table in.
5565      Alternatives are to punt or to maintain a cache of abbrev tables.
5566      This is simpler and efficient enough for now.
5567
5568      Later we group TUs by their DW_AT_stmt_list value (as this defines the
5569      symtab to use).  Typically TUs with the same abbrev offset have the same
5570      stmt_list value too so in practice this should work well.
5571
5572      The basic algorithm here is:
5573
5574       sort TUs by abbrev table
5575       for each TU with same abbrev table:
5576         read abbrev table if first user
5577         read TU top level DIE
5578           [IWBN if DWO skeletons had DW_AT_stmt_list]
5579         call FUNC  */
5580
5581   if (dwarf2_read_debug)
5582     fprintf_unfiltered (gdb_stdlog, "Building type unit groups ...\n");
5583
5584   /* Sort in a separate table to maintain the order of all_type_units
5585      for .gdb_index: TU indices directly index all_type_units.  */
5586   sorted_by_abbrev = XNEWVEC (struct tu_abbrev_offset,
5587                               dwarf2_per_objfile->n_type_units);
5588   for (i = 0; i < dwarf2_per_objfile->n_type_units; ++i)
5589     {
5590       struct signatured_type *sig_type = dwarf2_per_objfile->all_type_units[i];
5591
5592       sorted_by_abbrev[i].sig_type = sig_type;
5593       sorted_by_abbrev[i].abbrev_offset =
5594         read_abbrev_offset (sig_type->per_cu.section,
5595                             sig_type->per_cu.offset);
5596     }
5597   cleanups = make_cleanup (xfree, sorted_by_abbrev);
5598   qsort (sorted_by_abbrev, dwarf2_per_objfile->n_type_units,
5599          sizeof (struct tu_abbrev_offset), sort_tu_by_abbrev_offset);
5600
5601   /* Note: In the .gdb_index case, get_type_unit_group may have already been
5602      called any number of times, so we don't reset tu_stats here.  */
5603
5604   abbrev_offset.sect_off = ~(unsigned) 0;
5605   abbrev_table = NULL;
5606   make_cleanup (abbrev_table_free_cleanup, &abbrev_table);
5607
5608   for (i = 0; i < dwarf2_per_objfile->n_type_units; ++i)
5609     {
5610       const struct tu_abbrev_offset *tu = &sorted_by_abbrev[i];
5611
5612       /* Switch to the next abbrev table if necessary.  */
5613       if (abbrev_table == NULL
5614           || tu->abbrev_offset.sect_off != abbrev_offset.sect_off)
5615         {
5616           if (abbrev_table != NULL)
5617             {
5618               abbrev_table_free (abbrev_table);
5619               /* Reset to NULL in case abbrev_table_read_table throws
5620                  an error: abbrev_table_free_cleanup will get called.  */
5621               abbrev_table = NULL;
5622             }
5623           abbrev_offset = tu->abbrev_offset;
5624           abbrev_table =
5625             abbrev_table_read_table (&dwarf2_per_objfile->abbrev,
5626                                      abbrev_offset);
5627           ++tu_stats->nr_uniq_abbrev_tables;
5628         }
5629
5630       init_cutu_and_read_dies (&tu->sig_type->per_cu, abbrev_table, 0, 0,
5631                                func, data);
5632     }
5633
5634   /* type_unit_groups can be NULL if there is an error in the debug info.
5635      Just create an empty table so the rest of gdb doesn't have to watch
5636      for this error case.  */
5637   if (dwarf2_per_objfile->type_unit_groups == NULL)
5638     {
5639       dwarf2_per_objfile->type_unit_groups =
5640         allocate_type_unit_groups_table ();
5641       dwarf2_per_objfile->n_type_unit_groups = 0;
5642     }
5643
5644   /* Create a vector of pointers to primary type units to make it easy to
5645      iterate over them and CUs.  See dw2_get_primary_cu.  */
5646   dwarf2_per_objfile->n_type_unit_groups =
5647     htab_elements (dwarf2_per_objfile->type_unit_groups);
5648   dwarf2_per_objfile->all_type_unit_groups =
5649     obstack_alloc (&objfile->objfile_obstack,
5650                    dwarf2_per_objfile->n_type_unit_groups
5651                    * sizeof (struct type_unit_group *));
5652   iter = &dwarf2_per_objfile->all_type_unit_groups[0];
5653   htab_traverse_noresize (dwarf2_per_objfile->type_unit_groups,
5654                           add_type_unit_group_to_table, &iter);
5655   gdb_assert (iter - &dwarf2_per_objfile->all_type_unit_groups[0]
5656               == dwarf2_per_objfile->n_type_unit_groups);
5657
5658   do_cleanups (cleanups);
5659
5660   if (dwarf2_read_debug)
5661     {
5662       fprintf_unfiltered (gdb_stdlog, "Done building type unit groups:\n");
5663       fprintf_unfiltered (gdb_stdlog, "  %d TUs\n",
5664                           dwarf2_per_objfile->n_type_units);
5665       fprintf_unfiltered (gdb_stdlog, "  %d uniq abbrev tables\n",
5666                           tu_stats->nr_uniq_abbrev_tables);
5667       fprintf_unfiltered (gdb_stdlog, "  %d symtabs from stmt_list entries\n",
5668                           tu_stats->nr_symtabs);
5669       fprintf_unfiltered (gdb_stdlog, "  %d symtab sharers\n",
5670                           tu_stats->nr_symtab_sharers);
5671       fprintf_unfiltered (gdb_stdlog, "  %d type units without a stmt_list\n",
5672                           tu_stats->nr_stmt_less_type_units);
5673     }
5674 }
5675 \f
5676 /* Partial symbol tables.  */
5677
5678 /* Create a psymtab named NAME and assign it to PER_CU.
5679
5680    The caller must fill in the following details:
5681    dirname, textlow, texthigh.  */
5682
5683 static struct partial_symtab *
5684 create_partial_symtab (struct dwarf2_per_cu_data *per_cu, const char *name)
5685 {
5686   struct objfile *objfile = per_cu->objfile;
5687   struct partial_symtab *pst;
5688
5689   pst = start_psymtab_common (objfile, objfile->section_offsets,
5690                               name, 0,
5691                               objfile->global_psymbols.next,
5692                               objfile->static_psymbols.next);
5693
5694   pst->psymtabs_addrmap_supported = 1;
5695
5696   /* This is the glue that links PST into GDB's symbol API.  */
5697   pst->read_symtab_private = per_cu;
5698   pst->read_symtab = dwarf2_read_symtab;
5699   per_cu->v.psymtab = pst;
5700
5701   return pst;
5702 }
5703
5704 /* die_reader_func for process_psymtab_comp_unit.  */
5705
5706 static void
5707 process_psymtab_comp_unit_reader (const struct die_reader_specs *reader,
5708                                   const gdb_byte *info_ptr,
5709                                   struct die_info *comp_unit_die,
5710                                   int has_children,
5711                                   void *data)
5712 {
5713   struct dwarf2_cu *cu = reader->cu;
5714   struct objfile *objfile = cu->objfile;
5715   struct dwarf2_per_cu_data *per_cu = cu->per_cu;
5716   struct attribute *attr;
5717   CORE_ADDR baseaddr;
5718   CORE_ADDR best_lowpc = 0, best_highpc = 0;
5719   struct partial_symtab *pst;
5720   int has_pc_info;
5721   const char *filename;
5722   int *want_partial_unit_ptr = data;
5723
5724   if (comp_unit_die->tag == DW_TAG_partial_unit
5725       && (want_partial_unit_ptr == NULL
5726           || !*want_partial_unit_ptr))
5727     return;
5728
5729   gdb_assert (! per_cu->is_debug_types);
5730
5731   prepare_one_comp_unit (cu, comp_unit_die, language_minimal);
5732
5733   cu->list_in_scope = &file_symbols;
5734
5735   /* Allocate a new partial symbol table structure.  */
5736   attr = dwarf2_attr (comp_unit_die, DW_AT_name, cu);
5737   if (attr == NULL || !DW_STRING (attr))
5738     filename = "";
5739   else
5740     filename = DW_STRING (attr);
5741
5742   pst = create_partial_symtab (per_cu, filename);
5743
5744   /* This must be done before calling dwarf2_build_include_psymtabs.  */
5745   attr = dwarf2_attr (comp_unit_die, DW_AT_comp_dir, cu);
5746   if (attr != NULL)
5747     pst->dirname = DW_STRING (attr);
5748
5749   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
5750
5751   dwarf2_find_base_address (comp_unit_die, cu);
5752
5753   /* Possibly set the default values of LOWPC and HIGHPC from
5754      `DW_AT_ranges'.  */
5755   has_pc_info = dwarf2_get_pc_bounds (comp_unit_die, &best_lowpc,
5756                                       &best_highpc, cu, pst);
5757   if (has_pc_info == 1 && best_lowpc < best_highpc)
5758     /* Store the contiguous range if it is not empty; it can be empty for
5759        CUs with no code.  */
5760     addrmap_set_empty (objfile->psymtabs_addrmap,
5761                        best_lowpc + baseaddr,
5762                        best_highpc + baseaddr - 1, pst);
5763
5764   /* Check if comp unit has_children.
5765      If so, read the rest of the partial symbols from this comp unit.
5766      If not, there's no more debug_info for this comp unit.  */
5767   if (has_children)
5768     {
5769       struct partial_die_info *first_die;
5770       CORE_ADDR lowpc, highpc;
5771
5772       lowpc = ((CORE_ADDR) -1);
5773       highpc = ((CORE_ADDR) 0);
5774
5775       first_die = load_partial_dies (reader, info_ptr, 1);
5776
5777       scan_partial_symbols (first_die, &lowpc, &highpc,
5778                             ! has_pc_info, cu);
5779
5780       /* If we didn't find a lowpc, set it to highpc to avoid
5781          complaints from `maint check'.  */
5782       if (lowpc == ((CORE_ADDR) -1))
5783         lowpc = highpc;
5784
5785       /* If the compilation unit didn't have an explicit address range,
5786          then use the information extracted from its child dies.  */
5787       if (! has_pc_info)
5788         {
5789           best_lowpc = lowpc;
5790           best_highpc = highpc;
5791         }
5792     }
5793   pst->textlow = best_lowpc + baseaddr;
5794   pst->texthigh = best_highpc + baseaddr;
5795
5796   pst->n_global_syms = objfile->global_psymbols.next -
5797     (objfile->global_psymbols.list + pst->globals_offset);
5798   pst->n_static_syms = objfile->static_psymbols.next -
5799     (objfile->static_psymbols.list + pst->statics_offset);
5800   sort_pst_symbols (objfile, pst);
5801
5802   if (!VEC_empty (dwarf2_per_cu_ptr, cu->per_cu->imported_symtabs))
5803     {
5804       int i;
5805       int len = VEC_length (dwarf2_per_cu_ptr, cu->per_cu->imported_symtabs);
5806       struct dwarf2_per_cu_data *iter;
5807
5808       /* Fill in 'dependencies' here; we fill in 'users' in a
5809          post-pass.  */
5810       pst->number_of_dependencies = len;
5811       pst->dependencies = obstack_alloc (&objfile->objfile_obstack,
5812                                          len * sizeof (struct symtab *));
5813       for (i = 0;
5814            VEC_iterate (dwarf2_per_cu_ptr, cu->per_cu->imported_symtabs,
5815                         i, iter);
5816            ++i)
5817         pst->dependencies[i] = iter->v.psymtab;
5818
5819       VEC_free (dwarf2_per_cu_ptr, cu->per_cu->imported_symtabs);
5820     }
5821
5822   /* Get the list of files included in the current compilation unit,
5823      and build a psymtab for each of them.  */
5824   dwarf2_build_include_psymtabs (cu, comp_unit_die, pst);
5825
5826   if (dwarf2_read_debug)
5827     {
5828       struct gdbarch *gdbarch = get_objfile_arch (objfile);
5829
5830       fprintf_unfiltered (gdb_stdlog,
5831                           "Psymtab for %s unit @0x%x: %s - %s"
5832                           ", %d global, %d static syms\n",
5833                           per_cu->is_debug_types ? "type" : "comp",
5834                           per_cu->offset.sect_off,
5835                           paddress (gdbarch, pst->textlow),
5836                           paddress (gdbarch, pst->texthigh),
5837                           pst->n_global_syms, pst->n_static_syms);
5838     }
5839 }
5840
5841 /* Subroutine of dwarf2_build_psymtabs_hard to simplify it.
5842    Process compilation unit THIS_CU for a psymtab.  */
5843
5844 static void
5845 process_psymtab_comp_unit (struct dwarf2_per_cu_data *this_cu,
5846                            int want_partial_unit)
5847 {
5848   /* If this compilation unit was already read in, free the
5849      cached copy in order to read it in again.  This is
5850      necessary because we skipped some symbols when we first
5851      read in the compilation unit (see load_partial_dies).
5852      This problem could be avoided, but the benefit is unclear.  */
5853   if (this_cu->cu != NULL)
5854     free_one_cached_comp_unit (this_cu);
5855
5856   gdb_assert (! this_cu->is_debug_types);
5857   init_cutu_and_read_dies (this_cu, NULL, 0, 0,
5858                            process_psymtab_comp_unit_reader,
5859                            &want_partial_unit);
5860
5861   /* Age out any secondary CUs.  */
5862   age_cached_comp_units ();
5863 }
5864
5865 /* Reader function for build_type_psymtabs.  */
5866
5867 static void
5868 build_type_psymtabs_reader (const struct die_reader_specs *reader,
5869                             const gdb_byte *info_ptr,
5870                             struct die_info *type_unit_die,
5871                             int has_children,
5872                             void *data)
5873 {
5874   struct objfile *objfile = dwarf2_per_objfile->objfile;
5875   struct dwarf2_cu *cu = reader->cu;
5876   struct dwarf2_per_cu_data *per_cu = cu->per_cu;
5877   struct signatured_type *sig_type;
5878   struct type_unit_group *tu_group;
5879   struct attribute *attr;
5880   struct partial_die_info *first_die;
5881   CORE_ADDR lowpc, highpc;
5882   struct partial_symtab *pst;
5883
5884   gdb_assert (data == NULL);
5885   gdb_assert (per_cu->is_debug_types);
5886   sig_type = (struct signatured_type *) per_cu;
5887
5888   if (! has_children)
5889     return;
5890
5891   attr = dwarf2_attr_no_follow (type_unit_die, DW_AT_stmt_list);
5892   tu_group = get_type_unit_group (cu, attr);
5893
5894   VEC_safe_push (sig_type_ptr, tu_group->tus, sig_type);
5895
5896   prepare_one_comp_unit (cu, type_unit_die, language_minimal);
5897   cu->list_in_scope = &file_symbols;
5898   pst = create_partial_symtab (per_cu, "");
5899   pst->anonymous = 1;
5900
5901   first_die = load_partial_dies (reader, info_ptr, 1);
5902
5903   lowpc = (CORE_ADDR) -1;
5904   highpc = (CORE_ADDR) 0;
5905   scan_partial_symbols (first_die, &lowpc, &highpc, 0, cu);
5906
5907   pst->n_global_syms = objfile->global_psymbols.next -
5908     (objfile->global_psymbols.list + pst->globals_offset);
5909   pst->n_static_syms = objfile->static_psymbols.next -
5910     (objfile->static_psymbols.list + pst->statics_offset);
5911   sort_pst_symbols (objfile, pst);
5912 }
5913
5914 /* Traversal function for build_type_psymtabs.  */
5915
5916 static int
5917 build_type_psymtab_dependencies (void **slot, void *info)
5918 {
5919   struct objfile *objfile = dwarf2_per_objfile->objfile;
5920   struct type_unit_group *tu_group = (struct type_unit_group *) *slot;
5921   struct dwarf2_per_cu_data *per_cu = &tu_group->per_cu;
5922   struct partial_symtab *pst = per_cu->v.psymtab;
5923   int len = VEC_length (sig_type_ptr, tu_group->tus);
5924   struct signatured_type *iter;
5925   int i;
5926
5927   gdb_assert (len > 0);
5928   gdb_assert (IS_TYPE_UNIT_GROUP (per_cu));
5929
5930   pst->number_of_dependencies = len;
5931   pst->dependencies = obstack_alloc (&objfile->objfile_obstack,
5932                                      len * sizeof (struct psymtab *));
5933   for (i = 0;
5934        VEC_iterate (sig_type_ptr, tu_group->tus, i, iter);
5935        ++i)
5936     {
5937       gdb_assert (iter->per_cu.is_debug_types);
5938       pst->dependencies[i] = iter->per_cu.v.psymtab;
5939       iter->type_unit_group = tu_group;
5940     }
5941
5942   VEC_free (sig_type_ptr, tu_group->tus);
5943
5944   return 1;
5945 }
5946
5947 /* Subroutine of dwarf2_build_psymtabs_hard to simplify it.
5948    Build partial symbol tables for the .debug_types comp-units.  */
5949
5950 static void
5951 build_type_psymtabs (struct objfile *objfile)
5952 {
5953   if (! create_all_type_units (objfile))
5954     return;
5955
5956   build_type_unit_groups (build_type_psymtabs_reader, NULL);
5957
5958   /* Now that all TUs have been processed we can fill in the dependencies.  */
5959   htab_traverse_noresize (dwarf2_per_objfile->type_unit_groups,
5960                           build_type_psymtab_dependencies, NULL);
5961 }
5962
5963 /* A cleanup function that clears objfile's psymtabs_addrmap field.  */
5964
5965 static void
5966 psymtabs_addrmap_cleanup (void *o)
5967 {
5968   struct objfile *objfile = o;
5969
5970   objfile->psymtabs_addrmap = NULL;
5971 }
5972
5973 /* Compute the 'user' field for each psymtab in OBJFILE.  */
5974
5975 static void
5976 set_partial_user (struct objfile *objfile)
5977 {
5978   int i;
5979
5980   for (i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
5981     {
5982       struct dwarf2_per_cu_data *per_cu = dw2_get_cu (i);
5983       struct partial_symtab *pst = per_cu->v.psymtab;
5984       int j;
5985
5986       if (pst == NULL)
5987         continue;
5988
5989       for (j = 0; j < pst->number_of_dependencies; ++j)
5990         {
5991           /* Set the 'user' field only if it is not already set.  */
5992           if (pst->dependencies[j]->user == NULL)
5993             pst->dependencies[j]->user = pst;
5994         }
5995     }
5996 }
5997
5998 /* Build the partial symbol table by doing a quick pass through the
5999    .debug_info and .debug_abbrev sections.  */
6000
6001 static void
6002 dwarf2_build_psymtabs_hard (struct objfile *objfile)
6003 {
6004   struct cleanup *back_to, *addrmap_cleanup;
6005   struct obstack temp_obstack;
6006   int i;
6007
6008   if (dwarf2_read_debug)
6009     {
6010       fprintf_unfiltered (gdb_stdlog, "Building psymtabs of objfile %s ...\n",
6011                           objfile->name);
6012     }
6013
6014   dwarf2_per_objfile->reading_partial_symbols = 1;
6015
6016   dwarf2_read_section (objfile, &dwarf2_per_objfile->info);
6017
6018   /* Any cached compilation units will be linked by the per-objfile
6019      read_in_chain.  Make sure to free them when we're done.  */
6020   back_to = make_cleanup (free_cached_comp_units, NULL);
6021
6022   build_type_psymtabs (objfile);
6023
6024   create_all_comp_units (objfile);
6025
6026   /* Create a temporary address map on a temporary obstack.  We later
6027      copy this to the final obstack.  */
6028   obstack_init (&temp_obstack);
6029   make_cleanup_obstack_free (&temp_obstack);
6030   objfile->psymtabs_addrmap = addrmap_create_mutable (&temp_obstack);
6031   addrmap_cleanup = make_cleanup (psymtabs_addrmap_cleanup, objfile);
6032
6033   for (i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
6034     {
6035       struct dwarf2_per_cu_data *per_cu = dw2_get_cu (i);
6036
6037       process_psymtab_comp_unit (per_cu, 0);
6038     }
6039
6040   set_partial_user (objfile);
6041
6042   objfile->psymtabs_addrmap = addrmap_create_fixed (objfile->psymtabs_addrmap,
6043                                                     &objfile->objfile_obstack);
6044   discard_cleanups (addrmap_cleanup);
6045
6046   do_cleanups (back_to);
6047
6048   if (dwarf2_read_debug)
6049     fprintf_unfiltered (gdb_stdlog, "Done building psymtabs of %s\n",
6050                         objfile->name);
6051 }
6052
6053 /* die_reader_func for load_partial_comp_unit.  */
6054
6055 static void
6056 load_partial_comp_unit_reader (const struct die_reader_specs *reader,
6057                                const gdb_byte *info_ptr,
6058                                struct die_info *comp_unit_die,
6059                                int has_children,
6060                                void *data)
6061 {
6062   struct dwarf2_cu *cu = reader->cu;
6063
6064   prepare_one_comp_unit (cu, comp_unit_die, language_minimal);
6065
6066   /* Check if comp unit has_children.
6067      If so, read the rest of the partial symbols from this comp unit.
6068      If not, there's no more debug_info for this comp unit.  */
6069   if (has_children)
6070     load_partial_dies (reader, info_ptr, 0);
6071 }
6072
6073 /* Load the partial DIEs for a secondary CU into memory.
6074    This is also used when rereading a primary CU with load_all_dies.  */
6075
6076 static void
6077 load_partial_comp_unit (struct dwarf2_per_cu_data *this_cu)
6078 {
6079   init_cutu_and_read_dies (this_cu, NULL, 1, 1,
6080                            load_partial_comp_unit_reader, NULL);
6081 }
6082
6083 static void
6084 read_comp_units_from_section (struct objfile *objfile,
6085                               struct dwarf2_section_info *section,
6086                               unsigned int is_dwz,
6087                               int *n_allocated,
6088                               int *n_comp_units,
6089                               struct dwarf2_per_cu_data ***all_comp_units)
6090 {
6091   const gdb_byte *info_ptr;
6092   bfd *abfd = section->asection->owner;
6093
6094   if (dwarf2_read_debug)
6095     fprintf_unfiltered (gdb_stdlog, "Reading %s for %s\n",
6096                         section->asection->name, bfd_get_filename (abfd));
6097
6098   dwarf2_read_section (objfile, section);
6099
6100   info_ptr = section->buffer;
6101
6102   while (info_ptr < section->buffer + section->size)
6103     {
6104       unsigned int length, initial_length_size;
6105       struct dwarf2_per_cu_data *this_cu;
6106       sect_offset offset;
6107
6108       offset.sect_off = info_ptr - section->buffer;
6109
6110       /* Read just enough information to find out where the next
6111          compilation unit is.  */
6112       length = read_initial_length (abfd, info_ptr, &initial_length_size);
6113
6114       /* Save the compilation unit for later lookup.  */
6115       this_cu = obstack_alloc (&objfile->objfile_obstack,
6116                                sizeof (struct dwarf2_per_cu_data));
6117       memset (this_cu, 0, sizeof (*this_cu));
6118       this_cu->offset = offset;
6119       this_cu->length = length + initial_length_size;
6120       this_cu->is_dwz = is_dwz;
6121       this_cu->objfile = objfile;
6122       this_cu->section = section;
6123
6124       if (*n_comp_units == *n_allocated)
6125         {
6126           *n_allocated *= 2;
6127           *all_comp_units = xrealloc (*all_comp_units,
6128                                       *n_allocated
6129                                       * sizeof (struct dwarf2_per_cu_data *));
6130         }
6131       (*all_comp_units)[*n_comp_units] = this_cu;
6132       ++*n_comp_units;
6133
6134       info_ptr = info_ptr + this_cu->length;
6135     }
6136 }
6137
6138 /* Create a list of all compilation units in OBJFILE.
6139    This is only done for -readnow and building partial symtabs.  */
6140
6141 static void
6142 create_all_comp_units (struct objfile *objfile)
6143 {
6144   int n_allocated;
6145   int n_comp_units;
6146   struct dwarf2_per_cu_data **all_comp_units;
6147   struct dwz_file *dwz;
6148
6149   n_comp_units = 0;
6150   n_allocated = 10;
6151   all_comp_units = xmalloc (n_allocated
6152                             * sizeof (struct dwarf2_per_cu_data *));
6153
6154   read_comp_units_from_section (objfile, &dwarf2_per_objfile->info, 0,
6155                                 &n_allocated, &n_comp_units, &all_comp_units);
6156
6157   dwz = dwarf2_get_dwz_file ();
6158   if (dwz != NULL)
6159     read_comp_units_from_section (objfile, &dwz->info, 1,
6160                                   &n_allocated, &n_comp_units,
6161                                   &all_comp_units);
6162
6163   dwarf2_per_objfile->all_comp_units
6164     = obstack_alloc (&objfile->objfile_obstack,
6165                      n_comp_units * sizeof (struct dwarf2_per_cu_data *));
6166   memcpy (dwarf2_per_objfile->all_comp_units, all_comp_units,
6167           n_comp_units * sizeof (struct dwarf2_per_cu_data *));
6168   xfree (all_comp_units);
6169   dwarf2_per_objfile->n_comp_units = n_comp_units;
6170 }
6171
6172 /* Process all loaded DIEs for compilation unit CU, starting at
6173    FIRST_DIE.  The caller should pass NEED_PC == 1 if the compilation
6174    unit DIE did not have PC info (DW_AT_low_pc and DW_AT_high_pc, or
6175    DW_AT_ranges).  If NEED_PC is set, then this function will set
6176    *LOWPC and *HIGHPC to the lowest and highest PC values found in CU
6177    and record the covered ranges in the addrmap.  */
6178
6179 static void
6180 scan_partial_symbols (struct partial_die_info *first_die, CORE_ADDR *lowpc,
6181                       CORE_ADDR *highpc, int need_pc, struct dwarf2_cu *cu)
6182 {
6183   struct partial_die_info *pdi;
6184
6185   /* Now, march along the PDI's, descending into ones which have
6186      interesting children but skipping the children of the other ones,
6187      until we reach the end of the compilation unit.  */
6188
6189   pdi = first_die;
6190
6191   while (pdi != NULL)
6192     {
6193       fixup_partial_die (pdi, cu);
6194
6195       /* Anonymous namespaces or modules have no name but have interesting
6196          children, so we need to look at them.  Ditto for anonymous
6197          enums.  */
6198
6199       if (pdi->name != NULL || pdi->tag == DW_TAG_namespace
6200           || pdi->tag == DW_TAG_module || pdi->tag == DW_TAG_enumeration_type
6201           || pdi->tag == DW_TAG_imported_unit)
6202         {
6203           switch (pdi->tag)
6204             {
6205             case DW_TAG_subprogram:
6206               add_partial_subprogram (pdi, lowpc, highpc, need_pc, cu);
6207               break;
6208             case DW_TAG_constant:
6209             case DW_TAG_variable:
6210             case DW_TAG_typedef:
6211             case DW_TAG_union_type:
6212               if (!pdi->is_declaration)
6213                 {
6214                   add_partial_symbol (pdi, cu);
6215                 }
6216               break;
6217             case DW_TAG_class_type:
6218             case DW_TAG_interface_type:
6219             case DW_TAG_structure_type:
6220               if (!pdi->is_declaration)
6221                 {
6222                   add_partial_symbol (pdi, cu);
6223                 }
6224               break;
6225             case DW_TAG_enumeration_type:
6226               if (!pdi->is_declaration)
6227                 add_partial_enumeration (pdi, cu);
6228               break;
6229             case DW_TAG_base_type:
6230             case DW_TAG_subrange_type:
6231               /* File scope base type definitions are added to the partial
6232                  symbol table.  */
6233               add_partial_symbol (pdi, cu);
6234               break;
6235             case DW_TAG_namespace:
6236               add_partial_namespace (pdi, lowpc, highpc, need_pc, cu);
6237               break;
6238             case DW_TAG_module:
6239               add_partial_module (pdi, lowpc, highpc, need_pc, cu);
6240               break;
6241             case DW_TAG_imported_unit:
6242               {
6243                 struct dwarf2_per_cu_data *per_cu;
6244
6245                 /* For now we don't handle imported units in type units.  */
6246                 if (cu->per_cu->is_debug_types)
6247                   {
6248                     error (_("Dwarf Error: DW_TAG_imported_unit is not"
6249                              " supported in type units [in module %s]"),
6250                            cu->objfile->name);
6251                   }
6252
6253                 per_cu = dwarf2_find_containing_comp_unit (pdi->d.offset,
6254                                                            pdi->is_dwz,
6255                                                            cu->objfile);
6256
6257                 /* Go read the partial unit, if needed.  */
6258                 if (per_cu->v.psymtab == NULL)
6259                   process_psymtab_comp_unit (per_cu, 1);
6260
6261                 VEC_safe_push (dwarf2_per_cu_ptr,
6262                                cu->per_cu->imported_symtabs, per_cu);
6263               }
6264               break;
6265             default:
6266               break;
6267             }
6268         }
6269
6270       /* If the die has a sibling, skip to the sibling.  */
6271
6272       pdi = pdi->die_sibling;
6273     }
6274 }
6275
6276 /* Functions used to compute the fully scoped name of a partial DIE.
6277
6278    Normally, this is simple.  For C++, the parent DIE's fully scoped
6279    name is concatenated with "::" and the partial DIE's name.  For
6280    Java, the same thing occurs except that "." is used instead of "::".
6281    Enumerators are an exception; they use the scope of their parent
6282    enumeration type, i.e. the name of the enumeration type is not
6283    prepended to the enumerator.
6284
6285    There are two complexities.  One is DW_AT_specification; in this
6286    case "parent" means the parent of the target of the specification,
6287    instead of the direct parent of the DIE.  The other is compilers
6288    which do not emit DW_TAG_namespace; in this case we try to guess
6289    the fully qualified name of structure types from their members'
6290    linkage names.  This must be done using the DIE's children rather
6291    than the children of any DW_AT_specification target.  We only need
6292    to do this for structures at the top level, i.e. if the target of
6293    any DW_AT_specification (if any; otherwise the DIE itself) does not
6294    have a parent.  */
6295
6296 /* Compute the scope prefix associated with PDI's parent, in
6297    compilation unit CU.  The result will be allocated on CU's
6298    comp_unit_obstack, or a copy of the already allocated PDI->NAME
6299    field.  NULL is returned if no prefix is necessary.  */
6300 static const char *
6301 partial_die_parent_scope (struct partial_die_info *pdi,
6302                           struct dwarf2_cu *cu)
6303 {
6304   const char *grandparent_scope;
6305   struct partial_die_info *parent, *real_pdi;
6306
6307   /* We need to look at our parent DIE; if we have a DW_AT_specification,
6308      then this means the parent of the specification DIE.  */
6309
6310   real_pdi = pdi;
6311   while (real_pdi->has_specification)
6312     real_pdi = find_partial_die (real_pdi->spec_offset,
6313                                  real_pdi->spec_is_dwz, cu);
6314
6315   parent = real_pdi->die_parent;
6316   if (parent == NULL)
6317     return NULL;
6318
6319   if (parent->scope_set)
6320     return parent->scope;
6321
6322   fixup_partial_die (parent, cu);
6323
6324   grandparent_scope = partial_die_parent_scope (parent, cu);
6325
6326   /* GCC 4.0 and 4.1 had a bug (PR c++/28460) where they generated bogus
6327      DW_TAG_namespace DIEs with a name of "::" for the global namespace.
6328      Work around this problem here.  */
6329   if (cu->language == language_cplus
6330       && parent->tag == DW_TAG_namespace
6331       && strcmp (parent->name, "::") == 0
6332       && grandparent_scope == NULL)
6333     {
6334       parent->scope = NULL;
6335       parent->scope_set = 1;
6336       return NULL;
6337     }
6338
6339   if (pdi->tag == DW_TAG_enumerator)
6340     /* Enumerators should not get the name of the enumeration as a prefix.  */
6341     parent->scope = grandparent_scope;
6342   else if (parent->tag == DW_TAG_namespace
6343       || parent->tag == DW_TAG_module
6344       || parent->tag == DW_TAG_structure_type
6345       || parent->tag == DW_TAG_class_type
6346       || parent->tag == DW_TAG_interface_type
6347       || parent->tag == DW_TAG_union_type
6348       || parent->tag == DW_TAG_enumeration_type)
6349     {
6350       if (grandparent_scope == NULL)
6351         parent->scope = parent->name;
6352       else
6353         parent->scope = typename_concat (&cu->comp_unit_obstack,
6354                                          grandparent_scope,
6355                                          parent->name, 0, cu);
6356     }
6357   else
6358     {
6359       /* FIXME drow/2004-04-01: What should we be doing with
6360          function-local names?  For partial symbols, we should probably be
6361          ignoring them.  */
6362       complaint (&symfile_complaints,
6363                  _("unhandled containing DIE tag %d for DIE at %d"),
6364                  parent->tag, pdi->offset.sect_off);
6365       parent->scope = grandparent_scope;
6366     }
6367
6368   parent->scope_set = 1;
6369   return parent->scope;
6370 }
6371
6372 /* Return the fully scoped name associated with PDI, from compilation unit
6373    CU.  The result will be allocated with malloc.  */
6374
6375 static char *
6376 partial_die_full_name (struct partial_die_info *pdi,
6377                        struct dwarf2_cu *cu)
6378 {
6379   const char *parent_scope;
6380
6381   /* If this is a template instantiation, we can not work out the
6382      template arguments from partial DIEs.  So, unfortunately, we have
6383      to go through the full DIEs.  At least any work we do building
6384      types here will be reused if full symbols are loaded later.  */
6385   if (pdi->has_template_arguments)
6386     {
6387       fixup_partial_die (pdi, cu);
6388
6389       if (pdi->name != NULL && strchr (pdi->name, '<') == NULL)
6390         {
6391           struct die_info *die;
6392           struct attribute attr;
6393           struct dwarf2_cu *ref_cu = cu;
6394
6395           /* DW_FORM_ref_addr is using section offset.  */
6396           attr.name = 0;
6397           attr.form = DW_FORM_ref_addr;
6398           attr.u.unsnd = pdi->offset.sect_off;
6399           die = follow_die_ref (NULL, &attr, &ref_cu);
6400
6401           return xstrdup (dwarf2_full_name (NULL, die, ref_cu));
6402         }
6403     }
6404
6405   parent_scope = partial_die_parent_scope (pdi, cu);
6406   if (parent_scope == NULL)
6407     return NULL;
6408   else
6409     return typename_concat (NULL, parent_scope, pdi->name, 0, cu);
6410 }
6411
6412 static void
6413 add_partial_symbol (struct partial_die_info *pdi, struct dwarf2_cu *cu)
6414 {
6415   struct objfile *objfile = cu->objfile;
6416   CORE_ADDR addr = 0;
6417   const char *actual_name = NULL;
6418   CORE_ADDR baseaddr;
6419   char *built_actual_name;
6420
6421   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
6422
6423   built_actual_name = partial_die_full_name (pdi, cu);
6424   if (built_actual_name != NULL)
6425     actual_name = built_actual_name;
6426
6427   if (actual_name == NULL)
6428     actual_name = pdi->name;
6429
6430   switch (pdi->tag)
6431     {
6432     case DW_TAG_subprogram:
6433       if (pdi->is_external || cu->language == language_ada)
6434         {
6435           /* brobecker/2007-12-26: Normally, only "external" DIEs are part
6436              of the global scope.  But in Ada, we want to be able to access
6437              nested procedures globally.  So all Ada subprograms are stored
6438              in the global scope.  */
6439           /* prim_record_minimal_symbol (actual_name, pdi->lowpc + baseaddr,
6440              mst_text, objfile); */
6441           add_psymbol_to_list (actual_name, strlen (actual_name),
6442                                built_actual_name != NULL,
6443                                VAR_DOMAIN, LOC_BLOCK,
6444                                &objfile->global_psymbols,
6445                                0, pdi->lowpc + baseaddr,
6446                                cu->language, objfile);
6447         }
6448       else
6449         {
6450           /* prim_record_minimal_symbol (actual_name, pdi->lowpc + baseaddr,
6451              mst_file_text, objfile); */
6452           add_psymbol_to_list (actual_name, strlen (actual_name),
6453                                built_actual_name != NULL,
6454                                VAR_DOMAIN, LOC_BLOCK,
6455                                &objfile->static_psymbols,
6456                                0, pdi->lowpc + baseaddr,
6457                                cu->language, objfile);
6458         }
6459       break;
6460     case DW_TAG_constant:
6461       {
6462         struct psymbol_allocation_list *list;
6463
6464         if (pdi->is_external)
6465           list = &objfile->global_psymbols;
6466         else
6467           list = &objfile->static_psymbols;
6468         add_psymbol_to_list (actual_name, strlen (actual_name),
6469                              built_actual_name != NULL, VAR_DOMAIN, LOC_STATIC,
6470                              list, 0, 0, cu->language, objfile);
6471       }
6472       break;
6473     case DW_TAG_variable:
6474       if (pdi->d.locdesc)
6475         addr = decode_locdesc (pdi->d.locdesc, cu);
6476
6477       if (pdi->d.locdesc
6478           && addr == 0
6479           && !dwarf2_per_objfile->has_section_at_zero)
6480         {
6481           /* A global or static variable may also have been stripped
6482              out by the linker if unused, in which case its address
6483              will be nullified; do not add such variables into partial
6484              symbol table then.  */
6485         }
6486       else if (pdi->is_external)
6487         {
6488           /* Global Variable.
6489              Don't enter into the minimal symbol tables as there is
6490              a minimal symbol table entry from the ELF symbols already.
6491              Enter into partial symbol table if it has a location
6492              descriptor or a type.
6493              If the location descriptor is missing, new_symbol will create
6494              a LOC_UNRESOLVED symbol, the address of the variable will then
6495              be determined from the minimal symbol table whenever the variable
6496              is referenced.
6497              The address for the partial symbol table entry is not
6498              used by GDB, but it comes in handy for debugging partial symbol
6499              table building.  */
6500
6501           if (pdi->d.locdesc || pdi->has_type)
6502             add_psymbol_to_list (actual_name, strlen (actual_name),
6503                                  built_actual_name != NULL,
6504                                  VAR_DOMAIN, LOC_STATIC,
6505                                  &objfile->global_psymbols,
6506                                  0, addr + baseaddr,
6507                                  cu->language, objfile);
6508         }
6509       else
6510         {
6511           /* Static Variable.  Skip symbols without location descriptors.  */
6512           if (pdi->d.locdesc == NULL)
6513             {
6514               xfree (built_actual_name);
6515               return;
6516             }
6517           /* prim_record_minimal_symbol (actual_name, addr + baseaddr,
6518              mst_file_data, objfile); */
6519           add_psymbol_to_list (actual_name, strlen (actual_name),
6520                                built_actual_name != NULL,
6521                                VAR_DOMAIN, LOC_STATIC,
6522                                &objfile->static_psymbols,
6523                                0, addr + baseaddr,
6524                                cu->language, objfile);
6525         }
6526       break;
6527     case DW_TAG_typedef:
6528     case DW_TAG_base_type:
6529     case DW_TAG_subrange_type:
6530       add_psymbol_to_list (actual_name, strlen (actual_name),
6531                            built_actual_name != NULL,
6532                            VAR_DOMAIN, LOC_TYPEDEF,
6533                            &objfile->static_psymbols,
6534                            0, (CORE_ADDR) 0, cu->language, objfile);
6535       break;
6536     case DW_TAG_namespace:
6537       add_psymbol_to_list (actual_name, strlen (actual_name),
6538                            built_actual_name != NULL,
6539                            VAR_DOMAIN, LOC_TYPEDEF,
6540                            &objfile->global_psymbols,
6541                            0, (CORE_ADDR) 0, cu->language, objfile);
6542       break;
6543     case DW_TAG_class_type:
6544     case DW_TAG_interface_type:
6545     case DW_TAG_structure_type:
6546     case DW_TAG_union_type:
6547     case DW_TAG_enumeration_type:
6548       /* Skip external references.  The DWARF standard says in the section
6549          about "Structure, Union, and Class Type Entries": "An incomplete
6550          structure, union or class type is represented by a structure,
6551          union or class entry that does not have a byte size attribute
6552          and that has a DW_AT_declaration attribute."  */
6553       if (!pdi->has_byte_size && pdi->is_declaration)
6554         {
6555           xfree (built_actual_name);
6556           return;
6557         }
6558
6559       /* NOTE: carlton/2003-10-07: See comment in new_symbol about
6560          static vs. global.  */
6561       add_psymbol_to_list (actual_name, strlen (actual_name),
6562                            built_actual_name != NULL,
6563                            STRUCT_DOMAIN, LOC_TYPEDEF,
6564                            (cu->language == language_cplus
6565                             || cu->language == language_java)
6566                            ? &objfile->global_psymbols
6567                            : &objfile->static_psymbols,
6568                            0, (CORE_ADDR) 0, cu->language, objfile);
6569
6570       break;
6571     case DW_TAG_enumerator:
6572       add_psymbol_to_list (actual_name, strlen (actual_name),
6573                            built_actual_name != NULL,
6574                            VAR_DOMAIN, LOC_CONST,
6575                            (cu->language == language_cplus
6576                             || cu->language == language_java)
6577                            ? &objfile->global_psymbols
6578                            : &objfile->static_psymbols,
6579                            0, (CORE_ADDR) 0, cu->language, objfile);
6580       break;
6581     default:
6582       break;
6583     }
6584
6585   xfree (built_actual_name);
6586 }
6587
6588 /* Read a partial die corresponding to a namespace; also, add a symbol
6589    corresponding to that namespace to the symbol table.  NAMESPACE is
6590    the name of the enclosing namespace.  */
6591
6592 static void
6593 add_partial_namespace (struct partial_die_info *pdi,
6594                        CORE_ADDR *lowpc, CORE_ADDR *highpc,
6595                        int need_pc, struct dwarf2_cu *cu)
6596 {
6597   /* Add a symbol for the namespace.  */
6598
6599   add_partial_symbol (pdi, cu);
6600
6601   /* Now scan partial symbols in that namespace.  */
6602
6603   if (pdi->has_children)
6604     scan_partial_symbols (pdi->die_child, lowpc, highpc, need_pc, cu);
6605 }
6606
6607 /* Read a partial die corresponding to a Fortran module.  */
6608
6609 static void
6610 add_partial_module (struct partial_die_info *pdi, CORE_ADDR *lowpc,
6611                     CORE_ADDR *highpc, int need_pc, struct dwarf2_cu *cu)
6612 {
6613   /* Now scan partial symbols in that module.  */
6614
6615   if (pdi->has_children)
6616     scan_partial_symbols (pdi->die_child, lowpc, highpc, need_pc, cu);
6617 }
6618
6619 /* Read a partial die corresponding to a subprogram and create a partial
6620    symbol for that subprogram.  When the CU language allows it, this
6621    routine also defines a partial symbol for each nested subprogram
6622    that this subprogram contains.
6623
6624    DIE my also be a lexical block, in which case we simply search
6625    recursively for suprograms defined inside that lexical block.
6626    Again, this is only performed when the CU language allows this
6627    type of definitions.  */
6628
6629 static void
6630 add_partial_subprogram (struct partial_die_info *pdi,
6631                         CORE_ADDR *lowpc, CORE_ADDR *highpc,
6632                         int need_pc, struct dwarf2_cu *cu)
6633 {
6634   if (pdi->tag == DW_TAG_subprogram)
6635     {
6636       if (pdi->has_pc_info)
6637         {
6638           if (pdi->lowpc < *lowpc)
6639             *lowpc = pdi->lowpc;
6640           if (pdi->highpc > *highpc)
6641             *highpc = pdi->highpc;
6642           if (need_pc)
6643             {
6644               CORE_ADDR baseaddr;
6645               struct objfile *objfile = cu->objfile;
6646
6647               baseaddr = ANOFFSET (objfile->section_offsets,
6648                                    SECT_OFF_TEXT (objfile));
6649               addrmap_set_empty (objfile->psymtabs_addrmap,
6650                                  pdi->lowpc + baseaddr,
6651                                  pdi->highpc - 1 + baseaddr,
6652                                  cu->per_cu->v.psymtab);
6653             }
6654         }
6655
6656       if (pdi->has_pc_info || (!pdi->is_external && pdi->may_be_inlined))
6657         {
6658           if (!pdi->is_declaration)
6659             /* Ignore subprogram DIEs that do not have a name, they are
6660                illegal.  Do not emit a complaint at this point, we will
6661                do so when we convert this psymtab into a symtab.  */
6662             if (pdi->name)
6663               add_partial_symbol (pdi, cu);
6664         }
6665     }
6666
6667   if (! pdi->has_children)
6668     return;
6669
6670   if (cu->language == language_ada)
6671     {
6672       pdi = pdi->die_child;
6673       while (pdi != NULL)
6674         {
6675           fixup_partial_die (pdi, cu);
6676           if (pdi->tag == DW_TAG_subprogram
6677               || pdi->tag == DW_TAG_lexical_block)
6678             add_partial_subprogram (pdi, lowpc, highpc, need_pc, cu);
6679           pdi = pdi->die_sibling;
6680         }
6681     }
6682 }
6683
6684 /* Read a partial die corresponding to an enumeration type.  */
6685
6686 static void
6687 add_partial_enumeration (struct partial_die_info *enum_pdi,
6688                          struct dwarf2_cu *cu)
6689 {
6690   struct partial_die_info *pdi;
6691
6692   if (enum_pdi->name != NULL)
6693     add_partial_symbol (enum_pdi, cu);
6694
6695   pdi = enum_pdi->die_child;
6696   while (pdi)
6697     {
6698       if (pdi->tag != DW_TAG_enumerator || pdi->name == NULL)
6699         complaint (&symfile_complaints, _("malformed enumerator DIE ignored"));
6700       else
6701         add_partial_symbol (pdi, cu);
6702       pdi = pdi->die_sibling;
6703     }
6704 }
6705
6706 /* Return the initial uleb128 in the die at INFO_PTR.  */
6707
6708 static unsigned int
6709 peek_abbrev_code (bfd *abfd, const gdb_byte *info_ptr)
6710 {
6711   unsigned int bytes_read;
6712
6713   return read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
6714 }
6715
6716 /* Read the initial uleb128 in the die at INFO_PTR in compilation unit CU.
6717    Return the corresponding abbrev, or NULL if the number is zero (indicating
6718    an empty DIE).  In either case *BYTES_READ will be set to the length of
6719    the initial number.  */
6720
6721 static struct abbrev_info *
6722 peek_die_abbrev (const gdb_byte *info_ptr, unsigned int *bytes_read,
6723                  struct dwarf2_cu *cu)
6724 {
6725   bfd *abfd = cu->objfile->obfd;
6726   unsigned int abbrev_number;
6727   struct abbrev_info *abbrev;
6728
6729   abbrev_number = read_unsigned_leb128 (abfd, info_ptr, bytes_read);
6730
6731   if (abbrev_number == 0)
6732     return NULL;
6733
6734   abbrev = abbrev_table_lookup_abbrev (cu->abbrev_table, abbrev_number);
6735   if (!abbrev)
6736     {
6737       error (_("Dwarf Error: Could not find abbrev number %d [in module %s]"),
6738              abbrev_number, bfd_get_filename (abfd));
6739     }
6740
6741   return abbrev;
6742 }
6743
6744 /* Scan the debug information for CU starting at INFO_PTR in buffer BUFFER.
6745    Returns a pointer to the end of a series of DIEs, terminated by an empty
6746    DIE.  Any children of the skipped DIEs will also be skipped.  */
6747
6748 static const gdb_byte *
6749 skip_children (const struct die_reader_specs *reader, const gdb_byte *info_ptr)
6750 {
6751   struct dwarf2_cu *cu = reader->cu;
6752   struct abbrev_info *abbrev;
6753   unsigned int bytes_read;
6754
6755   while (1)
6756     {
6757       abbrev = peek_die_abbrev (info_ptr, &bytes_read, cu);
6758       if (abbrev == NULL)
6759         return info_ptr + bytes_read;
6760       else
6761         info_ptr = skip_one_die (reader, info_ptr + bytes_read, abbrev);
6762     }
6763 }
6764
6765 /* Scan the debug information for CU starting at INFO_PTR in buffer BUFFER.
6766    INFO_PTR should point just after the initial uleb128 of a DIE, and the
6767    abbrev corresponding to that skipped uleb128 should be passed in
6768    ABBREV.  Returns a pointer to this DIE's sibling, skipping any
6769    children.  */
6770
6771 static const gdb_byte *
6772 skip_one_die (const struct die_reader_specs *reader, const gdb_byte *info_ptr,
6773               struct abbrev_info *abbrev)
6774 {
6775   unsigned int bytes_read;
6776   struct attribute attr;
6777   bfd *abfd = reader->abfd;
6778   struct dwarf2_cu *cu = reader->cu;
6779   const gdb_byte *buffer = reader->buffer;
6780   const gdb_byte *buffer_end = reader->buffer_end;
6781   const gdb_byte *start_info_ptr = info_ptr;
6782   unsigned int form, i;
6783
6784   for (i = 0; i < abbrev->num_attrs; i++)
6785     {
6786       /* The only abbrev we care about is DW_AT_sibling.  */
6787       if (abbrev->attrs[i].name == DW_AT_sibling)
6788         {
6789           read_attribute (reader, &attr, &abbrev->attrs[i], info_ptr);
6790           if (attr.form == DW_FORM_ref_addr)
6791             complaint (&symfile_complaints,
6792                        _("ignoring absolute DW_AT_sibling"));
6793           else
6794             return buffer + dwarf2_get_ref_die_offset (&attr).sect_off;
6795         }
6796
6797       /* If it isn't DW_AT_sibling, skip this attribute.  */
6798       form = abbrev->attrs[i].form;
6799     skip_attribute:
6800       switch (form)
6801         {
6802         case DW_FORM_ref_addr:
6803           /* In DWARF 2, DW_FORM_ref_addr is address sized; in DWARF 3
6804              and later it is offset sized.  */
6805           if (cu->header.version == 2)
6806             info_ptr += cu->header.addr_size;
6807           else
6808             info_ptr += cu->header.offset_size;
6809           break;
6810         case DW_FORM_GNU_ref_alt:
6811           info_ptr += cu->header.offset_size;
6812           break;
6813         case DW_FORM_addr:
6814           info_ptr += cu->header.addr_size;
6815           break;
6816         case DW_FORM_data1:
6817         case DW_FORM_ref1:
6818         case DW_FORM_flag:
6819           info_ptr += 1;
6820           break;
6821         case DW_FORM_flag_present:
6822           break;
6823         case DW_FORM_data2:
6824         case DW_FORM_ref2:
6825           info_ptr += 2;
6826           break;
6827         case DW_FORM_data4:
6828         case DW_FORM_ref4:
6829           info_ptr += 4;
6830           break;
6831         case DW_FORM_data8:
6832         case DW_FORM_ref8:
6833         case DW_FORM_ref_sig8:
6834           info_ptr += 8;
6835           break;
6836         case DW_FORM_string:
6837           read_direct_string (abfd, info_ptr, &bytes_read);
6838           info_ptr += bytes_read;
6839           break;
6840         case DW_FORM_sec_offset:
6841         case DW_FORM_strp:
6842         case DW_FORM_GNU_strp_alt:
6843           info_ptr += cu->header.offset_size;
6844           break;
6845         case DW_FORM_exprloc:
6846         case DW_FORM_block:
6847           info_ptr += read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
6848           info_ptr += bytes_read;
6849           break;
6850         case DW_FORM_block1:
6851           info_ptr += 1 + read_1_byte (abfd, info_ptr);
6852           break;
6853         case DW_FORM_block2:
6854           info_ptr += 2 + read_2_bytes (abfd, info_ptr);
6855           break;
6856         case DW_FORM_block4:
6857           info_ptr += 4 + read_4_bytes (abfd, info_ptr);
6858           break;
6859         case DW_FORM_sdata:
6860         case DW_FORM_udata:
6861         case DW_FORM_ref_udata:
6862         case DW_FORM_GNU_addr_index:
6863         case DW_FORM_GNU_str_index:
6864           info_ptr = safe_skip_leb128 (info_ptr, buffer_end);
6865           break;
6866         case DW_FORM_indirect:
6867           form = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
6868           info_ptr += bytes_read;
6869           /* We need to continue parsing from here, so just go back to
6870              the top.  */
6871           goto skip_attribute;
6872
6873         default:
6874           error (_("Dwarf Error: Cannot handle %s "
6875                    "in DWARF reader [in module %s]"),
6876                  dwarf_form_name (form),
6877                  bfd_get_filename (abfd));
6878         }
6879     }
6880
6881   if (abbrev->has_children)
6882     return skip_children (reader, info_ptr);
6883   else
6884     return info_ptr;
6885 }
6886
6887 /* Locate ORIG_PDI's sibling.
6888    INFO_PTR should point to the start of the next DIE after ORIG_PDI.  */
6889
6890 static const gdb_byte *
6891 locate_pdi_sibling (const struct die_reader_specs *reader,
6892                     struct partial_die_info *orig_pdi,
6893                     const gdb_byte *info_ptr)
6894 {
6895   /* Do we know the sibling already?  */
6896
6897   if (orig_pdi->sibling)
6898     return orig_pdi->sibling;
6899
6900   /* Are there any children to deal with?  */
6901
6902   if (!orig_pdi->has_children)
6903     return info_ptr;
6904
6905   /* Skip the children the long way.  */
6906
6907   return skip_children (reader, info_ptr);
6908 }
6909
6910 /* Expand this partial symbol table into a full symbol table.  SELF is
6911    not NULL.  */
6912
6913 static void
6914 dwarf2_read_symtab (struct partial_symtab *self,
6915                     struct objfile *objfile)
6916 {
6917   if (self->readin)
6918     {
6919       warning (_("bug: psymtab for %s is already read in."),
6920                self->filename);
6921     }
6922   else
6923     {
6924       if (info_verbose)
6925         {
6926           printf_filtered (_("Reading in symbols for %s..."),
6927                            self->filename);
6928           gdb_flush (gdb_stdout);
6929         }
6930
6931       /* Restore our global data.  */
6932       dwarf2_per_objfile = objfile_data (objfile, dwarf2_objfile_data_key);
6933
6934       /* If this psymtab is constructed from a debug-only objfile, the
6935          has_section_at_zero flag will not necessarily be correct.  We
6936          can get the correct value for this flag by looking at the data
6937          associated with the (presumably stripped) associated objfile.  */
6938       if (objfile->separate_debug_objfile_backlink)
6939         {
6940           struct dwarf2_per_objfile *dpo_backlink
6941             = objfile_data (objfile->separate_debug_objfile_backlink,
6942                             dwarf2_objfile_data_key);
6943
6944           dwarf2_per_objfile->has_section_at_zero
6945             = dpo_backlink->has_section_at_zero;
6946         }
6947
6948       dwarf2_per_objfile->reading_partial_symbols = 0;
6949
6950       psymtab_to_symtab_1 (self);
6951
6952       /* Finish up the debug error message.  */
6953       if (info_verbose)
6954         printf_filtered (_("done.\n"));
6955     }
6956
6957   process_cu_includes ();
6958 }
6959 \f
6960 /* Reading in full CUs.  */
6961
6962 /* Add PER_CU to the queue.  */
6963
6964 static void
6965 queue_comp_unit (struct dwarf2_per_cu_data *per_cu,
6966                  enum language pretend_language)
6967 {
6968   struct dwarf2_queue_item *item;
6969
6970   per_cu->queued = 1;
6971   item = xmalloc (sizeof (*item));
6972   item->per_cu = per_cu;
6973   item->pretend_language = pretend_language;
6974   item->next = NULL;
6975
6976   if (dwarf2_queue == NULL)
6977     dwarf2_queue = item;
6978   else
6979     dwarf2_queue_tail->next = item;
6980
6981   dwarf2_queue_tail = item;
6982 }
6983
6984 /* THIS_CU has a reference to PER_CU.  If necessary, load the new compilation
6985    unit and add it to our queue.
6986    The result is non-zero if PER_CU was queued, otherwise the result is zero
6987    meaning either PER_CU is already queued or it is already loaded.  */
6988
6989 static int
6990 maybe_queue_comp_unit (struct dwarf2_cu *this_cu,
6991                        struct dwarf2_per_cu_data *per_cu,
6992                        enum language pretend_language)
6993 {
6994   /* We may arrive here during partial symbol reading, if we need full
6995      DIEs to process an unusual case (e.g. template arguments).  Do
6996      not queue PER_CU, just tell our caller to load its DIEs.  */
6997   if (dwarf2_per_objfile->reading_partial_symbols)
6998     {
6999       if (per_cu->cu == NULL || per_cu->cu->dies == NULL)
7000         return 1;
7001       return 0;
7002     }
7003
7004   /* Mark the dependence relation so that we don't flush PER_CU
7005      too early.  */
7006   dwarf2_add_dependence (this_cu, per_cu);
7007
7008   /* If it's already on the queue, we have nothing to do.  */
7009   if (per_cu->queued)
7010     return 0;
7011
7012   /* If the compilation unit is already loaded, just mark it as
7013      used.  */
7014   if (per_cu->cu != NULL)
7015     {
7016       per_cu->cu->last_used = 0;
7017       return 0;
7018     }
7019
7020   /* Add it to the queue.  */
7021   queue_comp_unit (per_cu, pretend_language);
7022
7023   return 1;
7024 }
7025
7026 /* Process the queue.  */
7027
7028 static void
7029 process_queue (void)
7030 {
7031   struct dwarf2_queue_item *item, *next_item;
7032
7033   if (dwarf2_read_debug)
7034     {
7035       fprintf_unfiltered (gdb_stdlog,
7036                           "Expanding one or more symtabs of objfile %s ...\n",
7037                           dwarf2_per_objfile->objfile->name);
7038     }
7039
7040   /* The queue starts out with one item, but following a DIE reference
7041      may load a new CU, adding it to the end of the queue.  */
7042   for (item = dwarf2_queue; item != NULL; dwarf2_queue = item = next_item)
7043     {
7044       if (dwarf2_per_objfile->using_index
7045           ? !item->per_cu->v.quick->symtab
7046           : (item->per_cu->v.psymtab && !item->per_cu->v.psymtab->readin))
7047         {
7048           struct dwarf2_per_cu_data *per_cu = item->per_cu;
7049           char buf[100];
7050
7051           if (per_cu->is_debug_types)
7052             {
7053               struct signatured_type *sig_type =
7054                 (struct signatured_type *) per_cu;
7055
7056               sprintf (buf, "TU %s at offset 0x%x",
7057                        hex_string (sig_type->signature), per_cu->offset.sect_off);
7058             }
7059           else
7060             sprintf (buf, "CU at offset 0x%x", per_cu->offset.sect_off);
7061
7062           if (dwarf2_read_debug)
7063             fprintf_unfiltered (gdb_stdlog, "Expanding symtab of %s\n", buf);
7064
7065           if (per_cu->is_debug_types)
7066             process_full_type_unit (per_cu, item->pretend_language);
7067           else
7068             process_full_comp_unit (per_cu, item->pretend_language);
7069
7070           if (dwarf2_read_debug)
7071             fprintf_unfiltered (gdb_stdlog, "Done expanding %s\n", buf);
7072         }
7073
7074       item->per_cu->queued = 0;
7075       next_item = item->next;
7076       xfree (item);
7077     }
7078
7079   dwarf2_queue_tail = NULL;
7080
7081   if (dwarf2_read_debug)
7082     {
7083       fprintf_unfiltered (gdb_stdlog, "Done expanding symtabs of %s.\n",
7084                           dwarf2_per_objfile->objfile->name);
7085     }
7086 }
7087
7088 /* Free all allocated queue entries.  This function only releases anything if
7089    an error was thrown; if the queue was processed then it would have been
7090    freed as we went along.  */
7091
7092 static void
7093 dwarf2_release_queue (void *dummy)
7094 {
7095   struct dwarf2_queue_item *item, *last;
7096
7097   item = dwarf2_queue;
7098   while (item)
7099     {
7100       /* Anything still marked queued is likely to be in an
7101          inconsistent state, so discard it.  */
7102       if (item->per_cu->queued)
7103         {
7104           if (item->per_cu->cu != NULL)
7105             free_one_cached_comp_unit (item->per_cu);
7106           item->per_cu->queued = 0;
7107         }
7108
7109       last = item;
7110       item = item->next;
7111       xfree (last);
7112     }
7113
7114   dwarf2_queue = dwarf2_queue_tail = NULL;
7115 }
7116
7117 /* Read in full symbols for PST, and anything it depends on.  */
7118
7119 static void
7120 psymtab_to_symtab_1 (struct partial_symtab *pst)
7121 {
7122   struct dwarf2_per_cu_data *per_cu;
7123   int i;
7124
7125   if (pst->readin)
7126     return;
7127
7128   for (i = 0; i < pst->number_of_dependencies; i++)
7129     if (!pst->dependencies[i]->readin
7130         && pst->dependencies[i]->user == NULL)
7131       {
7132         /* Inform about additional files that need to be read in.  */
7133         if (info_verbose)
7134           {
7135             /* FIXME: i18n: Need to make this a single string.  */
7136             fputs_filtered (" ", gdb_stdout);
7137             wrap_here ("");
7138             fputs_filtered ("and ", gdb_stdout);
7139             wrap_here ("");
7140             printf_filtered ("%s...", pst->dependencies[i]->filename);
7141             wrap_here ("");     /* Flush output.  */
7142             gdb_flush (gdb_stdout);
7143           }
7144         psymtab_to_symtab_1 (pst->dependencies[i]);
7145       }
7146
7147   per_cu = pst->read_symtab_private;
7148
7149   if (per_cu == NULL)
7150     {
7151       /* It's an include file, no symbols to read for it.
7152          Everything is in the parent symtab.  */
7153       pst->readin = 1;
7154       return;
7155     }
7156
7157   dw2_do_instantiate_symtab (per_cu);
7158 }
7159
7160 /* Trivial hash function for die_info: the hash value of a DIE
7161    is its offset in .debug_info for this objfile.  */
7162
7163 static hashval_t
7164 die_hash (const void *item)
7165 {
7166   const struct die_info *die = item;
7167
7168   return die->offset.sect_off;
7169 }
7170
7171 /* Trivial comparison function for die_info structures: two DIEs
7172    are equal if they have the same offset.  */
7173
7174 static int
7175 die_eq (const void *item_lhs, const void *item_rhs)
7176 {
7177   const struct die_info *die_lhs = item_lhs;
7178   const struct die_info *die_rhs = item_rhs;
7179
7180   return die_lhs->offset.sect_off == die_rhs->offset.sect_off;
7181 }
7182
7183 /* die_reader_func for load_full_comp_unit.
7184    This is identical to read_signatured_type_reader,
7185    but is kept separate for now.  */
7186
7187 static void
7188 load_full_comp_unit_reader (const struct die_reader_specs *reader,
7189                             const gdb_byte *info_ptr,
7190                             struct die_info *comp_unit_die,
7191                             int has_children,
7192                             void *data)
7193 {
7194   struct dwarf2_cu *cu = reader->cu;
7195   enum language *language_ptr = data;
7196
7197   gdb_assert (cu->die_hash == NULL);
7198   cu->die_hash =
7199     htab_create_alloc_ex (cu->header.length / 12,
7200                           die_hash,
7201                           die_eq,
7202                           NULL,
7203                           &cu->comp_unit_obstack,
7204                           hashtab_obstack_allocate,
7205                           dummy_obstack_deallocate);
7206
7207   if (has_children)
7208     comp_unit_die->child = read_die_and_siblings (reader, info_ptr,
7209                                                   &info_ptr, comp_unit_die);
7210   cu->dies = comp_unit_die;
7211   /* comp_unit_die is not stored in die_hash, no need.  */
7212
7213   /* We try not to read any attributes in this function, because not
7214      all CUs needed for references have been loaded yet, and symbol
7215      table processing isn't initialized.  But we have to set the CU language,
7216      or we won't be able to build types correctly.
7217      Similarly, if we do not read the producer, we can not apply
7218      producer-specific interpretation.  */
7219   prepare_one_comp_unit (cu, cu->dies, *language_ptr);
7220 }
7221
7222 /* Load the DIEs associated with PER_CU into memory.  */
7223
7224 static void
7225 load_full_comp_unit (struct dwarf2_per_cu_data *this_cu,
7226                      enum language pretend_language)
7227 {
7228   gdb_assert (! this_cu->is_debug_types);
7229
7230   init_cutu_and_read_dies (this_cu, NULL, 1, 1,
7231                            load_full_comp_unit_reader, &pretend_language);
7232 }
7233
7234 /* Add a DIE to the delayed physname list.  */
7235
7236 static void
7237 add_to_method_list (struct type *type, int fnfield_index, int index,
7238                     const char *name, struct die_info *die,
7239                     struct dwarf2_cu *cu)
7240 {
7241   struct delayed_method_info mi;
7242   mi.type = type;
7243   mi.fnfield_index = fnfield_index;
7244   mi.index = index;
7245   mi.name = name;
7246   mi.die = die;
7247   VEC_safe_push (delayed_method_info, cu->method_list, &mi);
7248 }
7249
7250 /* A cleanup for freeing the delayed method list.  */
7251
7252 static void
7253 free_delayed_list (void *ptr)
7254 {
7255   struct dwarf2_cu *cu = (struct dwarf2_cu *) ptr;
7256   if (cu->method_list != NULL)
7257     {
7258       VEC_free (delayed_method_info, cu->method_list);
7259       cu->method_list = NULL;
7260     }
7261 }
7262
7263 /* Compute the physnames of any methods on the CU's method list.
7264
7265    The computation of method physnames is delayed in order to avoid the
7266    (bad) condition that one of the method's formal parameters is of an as yet
7267    incomplete type.  */
7268
7269 static void
7270 compute_delayed_physnames (struct dwarf2_cu *cu)
7271 {
7272   int i;
7273   struct delayed_method_info *mi;
7274   for (i = 0; VEC_iterate (delayed_method_info, cu->method_list, i, mi) ; ++i)
7275     {
7276       const char *physname;
7277       struct fn_fieldlist *fn_flp
7278         = &TYPE_FN_FIELDLIST (mi->type, mi->fnfield_index);
7279       physname = dwarf2_physname (mi->name, mi->die, cu);
7280       fn_flp->fn_fields[mi->index].physname = physname ? physname : "";
7281     }
7282 }
7283
7284 /* Go objects should be embedded in a DW_TAG_module DIE,
7285    and it's not clear if/how imported objects will appear.
7286    To keep Go support simple until that's worked out,
7287    go back through what we've read and create something usable.
7288    We could do this while processing each DIE, and feels kinda cleaner,
7289    but that way is more invasive.
7290    This is to, for example, allow the user to type "p var" or "b main"
7291    without having to specify the package name, and allow lookups
7292    of module.object to work in contexts that use the expression
7293    parser.  */
7294
7295 static void
7296 fixup_go_packaging (struct dwarf2_cu *cu)
7297 {
7298   char *package_name = NULL;
7299   struct pending *list;
7300   int i;
7301
7302   for (list = global_symbols; list != NULL; list = list->next)
7303     {
7304       for (i = 0; i < list->nsyms; ++i)
7305         {
7306           struct symbol *sym = list->symbol[i];
7307
7308           if (SYMBOL_LANGUAGE (sym) == language_go
7309               && SYMBOL_CLASS (sym) == LOC_BLOCK)
7310             {
7311               char *this_package_name = go_symbol_package_name (sym);
7312
7313               if (this_package_name == NULL)
7314                 continue;
7315               if (package_name == NULL)
7316                 package_name = this_package_name;
7317               else
7318                 {
7319                   if (strcmp (package_name, this_package_name) != 0)
7320                     complaint (&symfile_complaints,
7321                                _("Symtab %s has objects from two different Go packages: %s and %s"),
7322                                (SYMBOL_SYMTAB (sym)
7323                           ? symtab_to_filename_for_display (SYMBOL_SYMTAB (sym))
7324                                 : cu->objfile->name),
7325                                this_package_name, package_name);
7326                   xfree (this_package_name);
7327                 }
7328             }
7329         }
7330     }
7331
7332   if (package_name != NULL)
7333     {
7334       struct objfile *objfile = cu->objfile;
7335       const char *saved_package_name = obstack_copy0 (&objfile->objfile_obstack,
7336                                                       package_name,
7337                                                       strlen (package_name));
7338       struct type *type = init_type (TYPE_CODE_MODULE, 0, 0,
7339                                      saved_package_name, objfile);
7340       struct symbol *sym;
7341
7342       TYPE_TAG_NAME (type) = TYPE_NAME (type);
7343
7344       sym = allocate_symbol (objfile);
7345       SYMBOL_SET_LANGUAGE (sym, language_go, &objfile->objfile_obstack);
7346       SYMBOL_SET_NAMES (sym, saved_package_name,
7347                         strlen (saved_package_name), 0, objfile);
7348       /* This is not VAR_DOMAIN because we want a way to ensure a lookup of,
7349          e.g., "main" finds the "main" module and not C's main().  */
7350       SYMBOL_DOMAIN (sym) = STRUCT_DOMAIN;
7351       SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
7352       SYMBOL_TYPE (sym) = type;
7353
7354       add_symbol_to_list (sym, &global_symbols);
7355
7356       xfree (package_name);
7357     }
7358 }
7359
7360 /* Return the symtab for PER_CU.  This works properly regardless of
7361    whether we're using the index or psymtabs.  */
7362
7363 static struct symtab *
7364 get_symtab (struct dwarf2_per_cu_data *per_cu)
7365 {
7366   return (dwarf2_per_objfile->using_index
7367           ? per_cu->v.quick->symtab
7368           : per_cu->v.psymtab->symtab);
7369 }
7370
7371 /* A helper function for computing the list of all symbol tables
7372    included by PER_CU.  */
7373
7374 static void
7375 recursively_compute_inclusions (VEC (symtab_ptr) **result,
7376                                 htab_t all_children, htab_t all_type_symtabs,
7377                                 struct dwarf2_per_cu_data *per_cu)
7378 {
7379   void **slot;
7380   int ix;
7381   struct symtab *symtab;
7382   struct dwarf2_per_cu_data *iter;
7383
7384   slot = htab_find_slot (all_children, per_cu, INSERT);
7385   if (*slot != NULL)
7386     {
7387       /* This inclusion and its children have been processed.  */
7388       return;
7389     }
7390
7391   *slot = per_cu;
7392   /* Only add a CU if it has a symbol table.  */
7393   symtab = get_symtab (per_cu);
7394   if (symtab != NULL)
7395     {
7396       /* If this is a type unit only add its symbol table if we haven't
7397          seen it yet (type unit per_cu's can share symtabs).  */
7398       if (per_cu->is_debug_types)
7399         {
7400           slot = htab_find_slot (all_type_symtabs, symtab, INSERT);
7401           if (*slot == NULL)
7402             {
7403               *slot = symtab;
7404               VEC_safe_push (symtab_ptr, *result, symtab);
7405             }
7406         }
7407       else
7408         VEC_safe_push (symtab_ptr, *result, symtab);
7409     }
7410
7411   for (ix = 0;
7412        VEC_iterate (dwarf2_per_cu_ptr, per_cu->imported_symtabs, ix, iter);
7413        ++ix)
7414     {
7415       recursively_compute_inclusions (result, all_children,
7416                                       all_type_symtabs, iter);
7417     }
7418 }
7419
7420 /* Compute the symtab 'includes' fields for the symtab related to
7421    PER_CU.  */
7422
7423 static void
7424 compute_symtab_includes (struct dwarf2_per_cu_data *per_cu)
7425 {
7426   gdb_assert (! per_cu->is_debug_types);
7427
7428   if (!VEC_empty (dwarf2_per_cu_ptr, per_cu->imported_symtabs))
7429     {
7430       int ix, len;
7431       struct dwarf2_per_cu_data *per_cu_iter;
7432       struct symtab *symtab_iter;
7433       VEC (symtab_ptr) *result_symtabs = NULL;
7434       htab_t all_children, all_type_symtabs;
7435       struct symtab *symtab = get_symtab (per_cu);
7436
7437       /* If we don't have a symtab, we can just skip this case.  */
7438       if (symtab == NULL)
7439         return;
7440
7441       all_children = htab_create_alloc (1, htab_hash_pointer, htab_eq_pointer,
7442                                         NULL, xcalloc, xfree);
7443       all_type_symtabs = htab_create_alloc (1, htab_hash_pointer, htab_eq_pointer,
7444                                             NULL, xcalloc, xfree);
7445
7446       for (ix = 0;
7447            VEC_iterate (dwarf2_per_cu_ptr, per_cu->imported_symtabs,
7448                         ix, per_cu_iter);
7449            ++ix)
7450         {
7451           recursively_compute_inclusions (&result_symtabs, all_children,
7452                                           all_type_symtabs, per_cu_iter);
7453         }
7454
7455       /* Now we have a transitive closure of all the included symtabs.  */
7456       len = VEC_length (symtab_ptr, result_symtabs);
7457       symtab->includes
7458         = obstack_alloc (&dwarf2_per_objfile->objfile->objfile_obstack,
7459                          (len + 1) * sizeof (struct symtab *));
7460       for (ix = 0;
7461            VEC_iterate (symtab_ptr, result_symtabs, ix, symtab_iter);
7462            ++ix)
7463         symtab->includes[ix] = symtab_iter;
7464       symtab->includes[len] = NULL;
7465
7466       VEC_free (symtab_ptr, result_symtabs);
7467       htab_delete (all_children);
7468       htab_delete (all_type_symtabs);
7469     }
7470 }
7471
7472 /* Compute the 'includes' field for the symtabs of all the CUs we just
7473    read.  */
7474
7475 static void
7476 process_cu_includes (void)
7477 {
7478   int ix;
7479   struct dwarf2_per_cu_data *iter;
7480
7481   for (ix = 0;
7482        VEC_iterate (dwarf2_per_cu_ptr, dwarf2_per_objfile->just_read_cus,
7483                     ix, iter);
7484        ++ix)
7485     {
7486       if (! iter->is_debug_types)
7487         compute_symtab_includes (iter);
7488     }
7489
7490   VEC_free (dwarf2_per_cu_ptr, dwarf2_per_objfile->just_read_cus);
7491 }
7492
7493 /* Generate full symbol information for PER_CU, whose DIEs have
7494    already been loaded into memory.  */
7495
7496 static void
7497 process_full_comp_unit (struct dwarf2_per_cu_data *per_cu,
7498                         enum language pretend_language)
7499 {
7500   struct dwarf2_cu *cu = per_cu->cu;
7501   struct objfile *objfile = per_cu->objfile;
7502   CORE_ADDR lowpc, highpc;
7503   struct symtab *symtab;
7504   struct cleanup *back_to, *delayed_list_cleanup;
7505   CORE_ADDR baseaddr;
7506   struct block *static_block;
7507
7508   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
7509
7510   buildsym_init ();
7511   back_to = make_cleanup (really_free_pendings, NULL);
7512   delayed_list_cleanup = make_cleanup (free_delayed_list, cu);
7513
7514   cu->list_in_scope = &file_symbols;
7515
7516   cu->language = pretend_language;
7517   cu->language_defn = language_def (cu->language);
7518
7519   /* Do line number decoding in read_file_scope () */
7520   process_die (cu->dies, cu);
7521
7522   /* For now fudge the Go package.  */
7523   if (cu->language == language_go)
7524     fixup_go_packaging (cu);
7525
7526   /* Now that we have processed all the DIEs in the CU, all the types 
7527      should be complete, and it should now be safe to compute all of the
7528      physnames.  */
7529   compute_delayed_physnames (cu);
7530   do_cleanups (delayed_list_cleanup);
7531
7532   /* Some compilers don't define a DW_AT_high_pc attribute for the
7533      compilation unit.  If the DW_AT_high_pc is missing, synthesize
7534      it, by scanning the DIE's below the compilation unit.  */
7535   get_scope_pc_bounds (cu->dies, &lowpc, &highpc, cu);
7536
7537   static_block
7538     = end_symtab_get_static_block (highpc + baseaddr, objfile, 0, 1);
7539
7540   /* If the comp unit has DW_AT_ranges, it may have discontiguous ranges.
7541      Also, DW_AT_ranges may record ranges not belonging to any child DIEs
7542      (such as virtual method tables).  Record the ranges in STATIC_BLOCK's
7543      addrmap to help ensure it has an accurate map of pc values belonging to
7544      this comp unit.  */
7545   dwarf2_record_block_ranges (cu->dies, static_block, baseaddr, cu);
7546
7547   symtab = end_symtab_from_static_block (static_block, objfile,
7548                                          SECT_OFF_TEXT (objfile), 0);
7549
7550   if (symtab != NULL)
7551     {
7552       int gcc_4_minor = producer_is_gcc_ge_4 (cu->producer);
7553
7554       /* Set symtab language to language from DW_AT_language.  If the
7555          compilation is from a C file generated by language preprocessors, do
7556          not set the language if it was already deduced by start_subfile.  */
7557       if (!(cu->language == language_c && symtab->language != language_c))
7558         symtab->language = cu->language;
7559
7560       /* GCC-4.0 has started to support -fvar-tracking.  GCC-3.x still can
7561          produce DW_AT_location with location lists but it can be possibly
7562          invalid without -fvar-tracking.  Still up to GCC-4.4.x incl. 4.4.0
7563          there were bugs in prologue debug info, fixed later in GCC-4.5
7564          by "unwind info for epilogues" patch (which is not directly related).
7565
7566          For -gdwarf-4 type units LOCATIONS_VALID indication is fortunately not
7567          needed, it would be wrong due to missing DW_AT_producer there.
7568
7569          Still one can confuse GDB by using non-standard GCC compilation
7570          options - this waits on GCC PR other/32998 (-frecord-gcc-switches).
7571          */ 
7572       if (cu->has_loclist && gcc_4_minor >= 5)
7573         symtab->locations_valid = 1;
7574
7575       if (gcc_4_minor >= 5)
7576         symtab->epilogue_unwind_valid = 1;
7577
7578       symtab->call_site_htab = cu->call_site_htab;
7579     }
7580
7581   if (dwarf2_per_objfile->using_index)
7582     per_cu->v.quick->symtab = symtab;
7583   else
7584     {
7585       struct partial_symtab *pst = per_cu->v.psymtab;
7586       pst->symtab = symtab;
7587       pst->readin = 1;
7588     }
7589
7590   /* Push it for inclusion processing later.  */
7591   VEC_safe_push (dwarf2_per_cu_ptr, dwarf2_per_objfile->just_read_cus, per_cu);
7592
7593   do_cleanups (back_to);
7594 }
7595
7596 /* Generate full symbol information for type unit PER_CU, whose DIEs have
7597    already been loaded into memory.  */
7598
7599 static void
7600 process_full_type_unit (struct dwarf2_per_cu_data *per_cu,
7601                         enum language pretend_language)
7602 {
7603   struct dwarf2_cu *cu = per_cu->cu;
7604   struct objfile *objfile = per_cu->objfile;
7605   struct symtab *symtab;
7606   struct cleanup *back_to, *delayed_list_cleanup;
7607   struct signatured_type *sig_type;
7608
7609   gdb_assert (per_cu->is_debug_types);
7610   sig_type = (struct signatured_type *) per_cu;
7611
7612   buildsym_init ();
7613   back_to = make_cleanup (really_free_pendings, NULL);
7614   delayed_list_cleanup = make_cleanup (free_delayed_list, cu);
7615
7616   cu->list_in_scope = &file_symbols;
7617
7618   cu->language = pretend_language;
7619   cu->language_defn = language_def (cu->language);
7620
7621   /* The symbol tables are set up in read_type_unit_scope.  */
7622   process_die (cu->dies, cu);
7623
7624   /* For now fudge the Go package.  */
7625   if (cu->language == language_go)
7626     fixup_go_packaging (cu);
7627
7628   /* Now that we have processed all the DIEs in the CU, all the types 
7629      should be complete, and it should now be safe to compute all of the
7630      physnames.  */
7631   compute_delayed_physnames (cu);
7632   do_cleanups (delayed_list_cleanup);
7633
7634   /* TUs share symbol tables.
7635      If this is the first TU to use this symtab, complete the construction
7636      of it with end_expandable_symtab.  Otherwise, complete the addition of
7637      this TU's symbols to the existing symtab.  */
7638   if (sig_type->type_unit_group->primary_symtab == NULL)
7639     {
7640       symtab = end_expandable_symtab (0, objfile, SECT_OFF_TEXT (objfile));
7641       sig_type->type_unit_group->primary_symtab = symtab;
7642
7643       if (symtab != NULL)
7644         {
7645           /* Set symtab language to language from DW_AT_language.  If the
7646              compilation is from a C file generated by language preprocessors,
7647              do not set the language if it was already deduced by
7648              start_subfile.  */
7649           if (!(cu->language == language_c && symtab->language != language_c))
7650             symtab->language = cu->language;
7651         }
7652     }
7653   else
7654     {
7655       augment_type_symtab (objfile,
7656                            sig_type->type_unit_group->primary_symtab);
7657       symtab = sig_type->type_unit_group->primary_symtab;
7658     }
7659
7660   if (dwarf2_per_objfile->using_index)
7661     per_cu->v.quick->symtab = symtab;
7662   else
7663     {
7664       struct partial_symtab *pst = per_cu->v.psymtab;
7665       pst->symtab = symtab;
7666       pst->readin = 1;
7667     }
7668
7669   do_cleanups (back_to);
7670 }
7671
7672 /* Process an imported unit DIE.  */
7673
7674 static void
7675 process_imported_unit_die (struct die_info *die, struct dwarf2_cu *cu)
7676 {
7677   struct attribute *attr;
7678
7679   /* For now we don't handle imported units in type units.  */
7680   if (cu->per_cu->is_debug_types)
7681     {
7682       error (_("Dwarf Error: DW_TAG_imported_unit is not"
7683                " supported in type units [in module %s]"),
7684              cu->objfile->name);
7685     }
7686
7687   attr = dwarf2_attr (die, DW_AT_import, cu);
7688   if (attr != NULL)
7689     {
7690       struct dwarf2_per_cu_data *per_cu;
7691       struct symtab *imported_symtab;
7692       sect_offset offset;
7693       int is_dwz;
7694
7695       offset = dwarf2_get_ref_die_offset (attr);
7696       is_dwz = (attr->form == DW_FORM_GNU_ref_alt || cu->per_cu->is_dwz);
7697       per_cu = dwarf2_find_containing_comp_unit (offset, is_dwz, cu->objfile);
7698
7699       /* Queue the unit, if needed.  */
7700       if (maybe_queue_comp_unit (cu, per_cu, cu->language))
7701         load_full_comp_unit (per_cu, cu->language);
7702
7703       VEC_safe_push (dwarf2_per_cu_ptr, cu->per_cu->imported_symtabs,
7704                      per_cu);
7705     }
7706 }
7707
7708 /* Process a die and its children.  */
7709
7710 static void
7711 process_die (struct die_info *die, struct dwarf2_cu *cu)
7712 {
7713   switch (die->tag)
7714     {
7715     case DW_TAG_padding:
7716       break;
7717     case DW_TAG_compile_unit:
7718     case DW_TAG_partial_unit:
7719       read_file_scope (die, cu);
7720       break;
7721     case DW_TAG_type_unit:
7722       read_type_unit_scope (die, cu);
7723       break;
7724     case DW_TAG_subprogram:
7725     case DW_TAG_inlined_subroutine:
7726       read_func_scope (die, cu);
7727       break;
7728     case DW_TAG_lexical_block:
7729     case DW_TAG_try_block:
7730     case DW_TAG_catch_block:
7731       read_lexical_block_scope (die, cu);
7732       break;
7733     case DW_TAG_GNU_call_site:
7734       read_call_site_scope (die, cu);
7735       break;
7736     case DW_TAG_class_type:
7737     case DW_TAG_interface_type:
7738     case DW_TAG_structure_type:
7739     case DW_TAG_union_type:
7740       process_structure_scope (die, cu);
7741       break;
7742     case DW_TAG_enumeration_type:
7743       process_enumeration_scope (die, cu);
7744       break;
7745
7746     /* These dies have a type, but processing them does not create
7747        a symbol or recurse to process the children.  Therefore we can
7748        read them on-demand through read_type_die.  */
7749     case DW_TAG_subroutine_type:
7750     case DW_TAG_set_type:
7751     case DW_TAG_array_type:
7752     case DW_TAG_pointer_type:
7753     case DW_TAG_ptr_to_member_type:
7754     case DW_TAG_reference_type:
7755     case DW_TAG_string_type:
7756       break;
7757
7758     case DW_TAG_base_type:
7759     case DW_TAG_subrange_type:
7760     case DW_TAG_typedef:
7761       /* Add a typedef symbol for the type definition, if it has a
7762          DW_AT_name.  */
7763       new_symbol (die, read_type_die (die, cu), cu);
7764       break;
7765     case DW_TAG_common_block:
7766       read_common_block (die, cu);
7767       break;
7768     case DW_TAG_common_inclusion:
7769       break;
7770     case DW_TAG_namespace:
7771       cu->processing_has_namespace_info = 1;
7772       read_namespace (die, cu);
7773       break;
7774     case DW_TAG_module:
7775       cu->processing_has_namespace_info = 1;
7776       read_module (die, cu);
7777       break;
7778     case DW_TAG_imported_declaration:
7779     case DW_TAG_imported_module:
7780       cu->processing_has_namespace_info = 1;
7781       if (die->child != NULL && (die->tag == DW_TAG_imported_declaration
7782                                  || cu->language != language_fortran))
7783         complaint (&symfile_complaints, _("Tag '%s' has unexpected children"),
7784                    dwarf_tag_name (die->tag));
7785       read_import_statement (die, cu);
7786       break;
7787
7788     case DW_TAG_imported_unit:
7789       process_imported_unit_die (die, cu);
7790       break;
7791
7792     default:
7793       new_symbol (die, NULL, cu);
7794       break;
7795     }
7796 }
7797 \f
7798 /* DWARF name computation.  */
7799
7800 /* A helper function for dwarf2_compute_name which determines whether DIE
7801    needs to have the name of the scope prepended to the name listed in the
7802    die.  */
7803
7804 static int
7805 die_needs_namespace (struct die_info *die, struct dwarf2_cu *cu)
7806 {
7807   struct attribute *attr;
7808
7809   switch (die->tag)
7810     {
7811     case DW_TAG_namespace:
7812     case DW_TAG_typedef:
7813     case DW_TAG_class_type:
7814     case DW_TAG_interface_type:
7815     case DW_TAG_structure_type:
7816     case DW_TAG_union_type:
7817     case DW_TAG_enumeration_type:
7818     case DW_TAG_enumerator:
7819     case DW_TAG_subprogram:
7820     case DW_TAG_member:
7821       return 1;
7822
7823     case DW_TAG_variable:
7824     case DW_TAG_constant:
7825       /* We only need to prefix "globally" visible variables.  These include
7826          any variable marked with DW_AT_external or any variable that
7827          lives in a namespace.  [Variables in anonymous namespaces
7828          require prefixing, but they are not DW_AT_external.]  */
7829
7830       if (dwarf2_attr (die, DW_AT_specification, cu))
7831         {
7832           struct dwarf2_cu *spec_cu = cu;
7833
7834           return die_needs_namespace (die_specification (die, &spec_cu),
7835                                       spec_cu);
7836         }
7837
7838       attr = dwarf2_attr (die, DW_AT_external, cu);
7839       if (attr == NULL && die->parent->tag != DW_TAG_namespace
7840           && die->parent->tag != DW_TAG_module)
7841         return 0;
7842       /* A variable in a lexical block of some kind does not need a
7843          namespace, even though in C++ such variables may be external
7844          and have a mangled name.  */
7845       if (die->parent->tag ==  DW_TAG_lexical_block
7846           || die->parent->tag ==  DW_TAG_try_block
7847           || die->parent->tag ==  DW_TAG_catch_block
7848           || die->parent->tag == DW_TAG_subprogram)
7849         return 0;
7850       return 1;
7851
7852     default:
7853       return 0;
7854     }
7855 }
7856
7857 /* Retrieve the last character from a mem_file.  */
7858
7859 static void
7860 do_ui_file_peek_last (void *object, const char *buffer, long length)
7861 {
7862   char *last_char_p = (char *) object;
7863
7864   if (length > 0)
7865     *last_char_p = buffer[length - 1];
7866 }
7867
7868 /* Compute the fully qualified name of DIE in CU.  If PHYSNAME is nonzero,
7869    compute the physname for the object, which include a method's:
7870    - formal parameters (C++/Java),
7871    - receiver type (Go),
7872    - return type (Java).
7873
7874    The term "physname" is a bit confusing.
7875    For C++, for example, it is the demangled name.
7876    For Go, for example, it's the mangled name.
7877
7878    For Ada, return the DIE's linkage name rather than the fully qualified
7879    name.  PHYSNAME is ignored..
7880
7881    The result is allocated on the objfile_obstack and canonicalized.  */
7882
7883 static const char *
7884 dwarf2_compute_name (const char *name,
7885                      struct die_info *die, struct dwarf2_cu *cu,
7886                      int physname)
7887 {
7888   struct objfile *objfile = cu->objfile;
7889
7890   if (name == NULL)
7891     name = dwarf2_name (die, cu);
7892
7893   /* For Fortran GDB prefers DW_AT_*linkage_name if present but otherwise
7894      compute it by typename_concat inside GDB.  */
7895   if (cu->language == language_ada
7896       || (cu->language == language_fortran && physname))
7897     {
7898       /* For Ada unit, we prefer the linkage name over the name, as
7899          the former contains the exported name, which the user expects
7900          to be able to reference.  Ideally, we want the user to be able
7901          to reference this entity using either natural or linkage name,
7902          but we haven't started looking at this enhancement yet.  */
7903       struct attribute *attr;
7904
7905       attr = dwarf2_attr (die, DW_AT_linkage_name, cu);
7906       if (attr == NULL)
7907         attr = dwarf2_attr (die, DW_AT_MIPS_linkage_name, cu);
7908       if (attr && DW_STRING (attr))
7909         return DW_STRING (attr);
7910     }
7911
7912   /* These are the only languages we know how to qualify names in.  */
7913   if (name != NULL
7914       && (cu->language == language_cplus || cu->language == language_java
7915           || cu->language == language_fortran))
7916     {
7917       if (die_needs_namespace (die, cu))
7918         {
7919           long length;
7920           const char *prefix;
7921           struct ui_file *buf;
7922
7923           prefix = determine_prefix (die, cu);
7924           buf = mem_fileopen ();
7925           if (*prefix != '\0')
7926             {
7927               char *prefixed_name = typename_concat (NULL, prefix, name,
7928                                                      physname, cu);
7929
7930               fputs_unfiltered (prefixed_name, buf);
7931               xfree (prefixed_name);
7932             }
7933           else
7934             fputs_unfiltered (name, buf);
7935
7936           /* Template parameters may be specified in the DIE's DW_AT_name, or
7937              as children with DW_TAG_template_type_param or
7938              DW_TAG_value_type_param.  If the latter, add them to the name
7939              here.  If the name already has template parameters, then
7940              skip this step; some versions of GCC emit both, and
7941              it is more efficient to use the pre-computed name.
7942
7943              Something to keep in mind about this process: it is very
7944              unlikely, or in some cases downright impossible, to produce
7945              something that will match the mangled name of a function.
7946              If the definition of the function has the same debug info,
7947              we should be able to match up with it anyway.  But fallbacks
7948              using the minimal symbol, for instance to find a method
7949              implemented in a stripped copy of libstdc++, will not work.
7950              If we do not have debug info for the definition, we will have to
7951              match them up some other way.
7952
7953              When we do name matching there is a related problem with function
7954              templates; two instantiated function templates are allowed to
7955              differ only by their return types, which we do not add here.  */
7956
7957           if (cu->language == language_cplus && strchr (name, '<') == NULL)
7958             {
7959               struct attribute *attr;
7960               struct die_info *child;
7961               int first = 1;
7962
7963               die->building_fullname = 1;
7964
7965               for (child = die->child; child != NULL; child = child->sibling)
7966                 {
7967                   struct type *type;
7968                   LONGEST value;
7969                   const gdb_byte *bytes;
7970                   struct dwarf2_locexpr_baton *baton;
7971                   struct value *v;
7972
7973                   if (child->tag != DW_TAG_template_type_param
7974                       && child->tag != DW_TAG_template_value_param)
7975                     continue;
7976
7977                   if (first)
7978                     {
7979                       fputs_unfiltered ("<", buf);
7980                       first = 0;
7981                     }
7982                   else
7983                     fputs_unfiltered (", ", buf);
7984
7985                   attr = dwarf2_attr (child, DW_AT_type, cu);
7986                   if (attr == NULL)
7987                     {
7988                       complaint (&symfile_complaints,
7989                                  _("template parameter missing DW_AT_type"));
7990                       fputs_unfiltered ("UNKNOWN_TYPE", buf);
7991                       continue;
7992                     }
7993                   type = die_type (child, cu);
7994
7995                   if (child->tag == DW_TAG_template_type_param)
7996                     {
7997                       c_print_type (type, "", buf, -1, 0, &type_print_raw_options);
7998                       continue;
7999                     }
8000
8001                   attr = dwarf2_attr (child, DW_AT_const_value, cu);
8002                   if (attr == NULL)
8003                     {
8004                       complaint (&symfile_complaints,
8005                                  _("template parameter missing "
8006                                    "DW_AT_const_value"));
8007                       fputs_unfiltered ("UNKNOWN_VALUE", buf);
8008                       continue;
8009                     }
8010
8011                   dwarf2_const_value_attr (attr, type, name,
8012                                            &cu->comp_unit_obstack, cu,
8013                                            &value, &bytes, &baton);
8014
8015                   if (TYPE_NOSIGN (type))
8016                     /* GDB prints characters as NUMBER 'CHAR'.  If that's
8017                        changed, this can use value_print instead.  */
8018                     c_printchar (value, type, buf);
8019                   else
8020                     {
8021                       struct value_print_options opts;
8022
8023                       if (baton != NULL)
8024                         v = dwarf2_evaluate_loc_desc (type, NULL,
8025                                                       baton->data,
8026                                                       baton->size,
8027                                                       baton->per_cu);
8028                       else if (bytes != NULL)
8029                         {
8030                           v = allocate_value (type);
8031                           memcpy (value_contents_writeable (v), bytes,
8032                                   TYPE_LENGTH (type));
8033                         }
8034                       else
8035                         v = value_from_longest (type, value);
8036
8037                       /* Specify decimal so that we do not depend on
8038                          the radix.  */
8039                       get_formatted_print_options (&opts, 'd');
8040                       opts.raw = 1;
8041                       value_print (v, buf, &opts);
8042                       release_value (v);
8043                       value_free (v);
8044                     }
8045                 }
8046
8047               die->building_fullname = 0;
8048
8049               if (!first)
8050                 {
8051                   /* Close the argument list, with a space if necessary
8052                      (nested templates).  */
8053                   char last_char = '\0';
8054                   ui_file_put (buf, do_ui_file_peek_last, &last_char);
8055                   if (last_char == '>')
8056                     fputs_unfiltered (" >", buf);
8057                   else
8058                     fputs_unfiltered (">", buf);
8059                 }
8060             }
8061
8062           /* For Java and C++ methods, append formal parameter type
8063              information, if PHYSNAME.  */
8064
8065           if (physname && die->tag == DW_TAG_subprogram
8066               && (cu->language == language_cplus
8067                   || cu->language == language_java))
8068             {
8069               struct type *type = read_type_die (die, cu);
8070
8071               c_type_print_args (type, buf, 1, cu->language,
8072                                  &type_print_raw_options);
8073
8074               if (cu->language == language_java)
8075                 {
8076                   /* For java, we must append the return type to method
8077                      names.  */
8078                   if (die->tag == DW_TAG_subprogram)
8079                     java_print_type (TYPE_TARGET_TYPE (type), "", buf,
8080                                      0, 0, &type_print_raw_options);
8081                 }
8082               else if (cu->language == language_cplus)
8083                 {
8084                   /* Assume that an artificial first parameter is
8085                      "this", but do not crash if it is not.  RealView
8086                      marks unnamed (and thus unused) parameters as
8087                      artificial; there is no way to differentiate
8088                      the two cases.  */
8089                   if (TYPE_NFIELDS (type) > 0
8090                       && TYPE_FIELD_ARTIFICIAL (type, 0)
8091                       && TYPE_CODE (TYPE_FIELD_TYPE (type, 0)) == TYPE_CODE_PTR
8092                       && TYPE_CONST (TYPE_TARGET_TYPE (TYPE_FIELD_TYPE (type,
8093                                                                         0))))
8094                     fputs_unfiltered (" const", buf);
8095                 }
8096             }
8097
8098           name = ui_file_obsavestring (buf, &objfile->objfile_obstack,
8099                                        &length);
8100           ui_file_delete (buf);
8101
8102           if (cu->language == language_cplus)
8103             {
8104               const char *cname
8105                 = dwarf2_canonicalize_name (name, cu,
8106                                             &objfile->objfile_obstack);
8107
8108               if (cname != NULL)
8109                 name = cname;
8110             }
8111         }
8112     }
8113
8114   return name;
8115 }
8116
8117 /* Return the fully qualified name of DIE, based on its DW_AT_name.
8118    If scope qualifiers are appropriate they will be added.  The result
8119    will be allocated on the objfile_obstack, or NULL if the DIE does
8120    not have a name.  NAME may either be from a previous call to
8121    dwarf2_name or NULL.
8122
8123    The output string will be canonicalized (if C++/Java).  */
8124
8125 static const char *
8126 dwarf2_full_name (const char *name, struct die_info *die, struct dwarf2_cu *cu)
8127 {
8128   return dwarf2_compute_name (name, die, cu, 0);
8129 }
8130
8131 /* Construct a physname for the given DIE in CU.  NAME may either be
8132    from a previous call to dwarf2_name or NULL.  The result will be
8133    allocated on the objfile_objstack or NULL if the DIE does not have a
8134    name.
8135
8136    The output string will be canonicalized (if C++/Java).  */
8137
8138 static const char *
8139 dwarf2_physname (const char *name, struct die_info *die, struct dwarf2_cu *cu)
8140 {
8141   struct objfile *objfile = cu->objfile;
8142   struct attribute *attr;
8143   const char *retval, *mangled = NULL, *canon = NULL;
8144   struct cleanup *back_to;
8145   int need_copy = 1;
8146
8147   /* In this case dwarf2_compute_name is just a shortcut not building anything
8148      on its own.  */
8149   if (!die_needs_namespace (die, cu))
8150     return dwarf2_compute_name (name, die, cu, 1);
8151
8152   back_to = make_cleanup (null_cleanup, NULL);
8153
8154   attr = dwarf2_attr (die, DW_AT_linkage_name, cu);
8155   if (!attr)
8156     attr = dwarf2_attr (die, DW_AT_MIPS_linkage_name, cu);
8157
8158   /* DW_AT_linkage_name is missing in some cases - depend on what GDB
8159      has computed.  */
8160   if (attr && DW_STRING (attr))
8161     {
8162       char *demangled;
8163
8164       mangled = DW_STRING (attr);
8165
8166       /* Use DMGL_RET_DROP for C++ template functions to suppress their return
8167          type.  It is easier for GDB users to search for such functions as
8168          `name(params)' than `long name(params)'.  In such case the minimal
8169          symbol names do not match the full symbol names but for template
8170          functions there is never a need to look up their definition from their
8171          declaration so the only disadvantage remains the minimal symbol
8172          variant `long name(params)' does not have the proper inferior type.
8173          */
8174
8175       if (cu->language == language_go)
8176         {
8177           /* This is a lie, but we already lie to the caller new_symbol_full.
8178              new_symbol_full assumes we return the mangled name.
8179              This just undoes that lie until things are cleaned up.  */
8180           demangled = NULL;
8181         }
8182       else
8183         {
8184           demangled = gdb_demangle (mangled,
8185                                     (DMGL_PARAMS | DMGL_ANSI
8186                                      | (cu->language == language_java
8187                                         ? DMGL_JAVA | DMGL_RET_POSTFIX
8188                                         : DMGL_RET_DROP)));
8189         }
8190       if (demangled)
8191         {
8192           make_cleanup (xfree, demangled);
8193           canon = demangled;
8194         }
8195       else
8196         {
8197           canon = mangled;
8198           need_copy = 0;
8199         }
8200     }
8201
8202   if (canon == NULL || check_physname)
8203     {
8204       const char *physname = dwarf2_compute_name (name, die, cu, 1);
8205
8206       if (canon != NULL && strcmp (physname, canon) != 0)
8207         {
8208           /* It may not mean a bug in GDB.  The compiler could also
8209              compute DW_AT_linkage_name incorrectly.  But in such case
8210              GDB would need to be bug-to-bug compatible.  */
8211
8212           complaint (&symfile_complaints,
8213                      _("Computed physname <%s> does not match demangled <%s> "
8214                        "(from linkage <%s>) - DIE at 0x%x [in module %s]"),
8215                      physname, canon, mangled, die->offset.sect_off, objfile->name);
8216
8217           /* Prefer DW_AT_linkage_name (in the CANON form) - when it
8218              is available here - over computed PHYSNAME.  It is safer
8219              against both buggy GDB and buggy compilers.  */
8220
8221           retval = canon;
8222         }
8223       else
8224         {
8225           retval = physname;
8226           need_copy = 0;
8227         }
8228     }
8229   else
8230     retval = canon;
8231
8232   if (need_copy)
8233     retval = obstack_copy0 (&objfile->objfile_obstack, retval, strlen (retval));
8234
8235   do_cleanups (back_to);
8236   return retval;
8237 }
8238
8239 /* Read the import statement specified by the given die and record it.  */
8240
8241 static void
8242 read_import_statement (struct die_info *die, struct dwarf2_cu *cu)
8243 {
8244   struct objfile *objfile = cu->objfile;
8245   struct attribute *import_attr;
8246   struct die_info *imported_die, *child_die;
8247   struct dwarf2_cu *imported_cu;
8248   const char *imported_name;
8249   const char *imported_name_prefix;
8250   const char *canonical_name;
8251   const char *import_alias;
8252   const char *imported_declaration = NULL;
8253   const char *import_prefix;
8254   VEC (const_char_ptr) *excludes = NULL;
8255   struct cleanup *cleanups;
8256
8257   import_attr = dwarf2_attr (die, DW_AT_import, cu);
8258   if (import_attr == NULL)
8259     {
8260       complaint (&symfile_complaints, _("Tag '%s' has no DW_AT_import"),
8261                  dwarf_tag_name (die->tag));
8262       return;
8263     }
8264
8265   imported_cu = cu;
8266   imported_die = follow_die_ref_or_sig (die, import_attr, &imported_cu);
8267   imported_name = dwarf2_name (imported_die, imported_cu);
8268   if (imported_name == NULL)
8269     {
8270       /* GCC bug: https://bugzilla.redhat.com/show_bug.cgi?id=506524
8271
8272         The import in the following code:
8273         namespace A
8274           {
8275             typedef int B;
8276           }
8277
8278         int main ()
8279           {
8280             using A::B;
8281             B b;
8282             return b;
8283           }
8284
8285         ...
8286          <2><51>: Abbrev Number: 3 (DW_TAG_imported_declaration)
8287             <52>   DW_AT_decl_file   : 1
8288             <53>   DW_AT_decl_line   : 6
8289             <54>   DW_AT_import      : <0x75>
8290          <2><58>: Abbrev Number: 4 (DW_TAG_typedef)
8291             <59>   DW_AT_name        : B
8292             <5b>   DW_AT_decl_file   : 1
8293             <5c>   DW_AT_decl_line   : 2
8294             <5d>   DW_AT_type        : <0x6e>
8295         ...
8296          <1><75>: Abbrev Number: 7 (DW_TAG_base_type)
8297             <76>   DW_AT_byte_size   : 4
8298             <77>   DW_AT_encoding    : 5        (signed)
8299
8300         imports the wrong die ( 0x75 instead of 0x58 ).
8301         This case will be ignored until the gcc bug is fixed.  */
8302       return;
8303     }
8304
8305   /* Figure out the local name after import.  */
8306   import_alias = dwarf2_name (die, cu);
8307
8308   /* Figure out where the statement is being imported to.  */
8309   import_prefix = determine_prefix (die, cu);
8310
8311   /* Figure out what the scope of the imported die is and prepend it
8312      to the name of the imported die.  */
8313   imported_name_prefix = determine_prefix (imported_die, imported_cu);
8314
8315   if (imported_die->tag != DW_TAG_namespace
8316       && imported_die->tag != DW_TAG_module)
8317     {
8318       imported_declaration = imported_name;
8319       canonical_name = imported_name_prefix;
8320     }
8321   else if (strlen (imported_name_prefix) > 0)
8322     canonical_name = obconcat (&objfile->objfile_obstack,
8323                                imported_name_prefix, "::", imported_name,
8324                                (char *) NULL);
8325   else
8326     canonical_name = imported_name;
8327
8328   cleanups = make_cleanup (VEC_cleanup (const_char_ptr), &excludes);
8329
8330   if (die->tag == DW_TAG_imported_module && cu->language == language_fortran)
8331     for (child_die = die->child; child_die && child_die->tag;
8332          child_die = sibling_die (child_die))
8333       {
8334         /* DWARF-4: A Fortran use statement with a “rename list” may be
8335            represented by an imported module entry with an import attribute
8336            referring to the module and owned entries corresponding to those
8337            entities that are renamed as part of being imported.  */
8338
8339         if (child_die->tag != DW_TAG_imported_declaration)
8340           {
8341             complaint (&symfile_complaints,
8342                        _("child DW_TAG_imported_declaration expected "
8343                          "- DIE at 0x%x [in module %s]"),
8344                        child_die->offset.sect_off, objfile->name);
8345             continue;
8346           }
8347
8348         import_attr = dwarf2_attr (child_die, DW_AT_import, cu);
8349         if (import_attr == NULL)
8350           {
8351             complaint (&symfile_complaints, _("Tag '%s' has no DW_AT_import"),
8352                        dwarf_tag_name (child_die->tag));
8353             continue;
8354           }
8355
8356         imported_cu = cu;
8357         imported_die = follow_die_ref_or_sig (child_die, import_attr,
8358                                               &imported_cu);
8359         imported_name = dwarf2_name (imported_die, imported_cu);
8360         if (imported_name == NULL)
8361           {
8362             complaint (&symfile_complaints,
8363                        _("child DW_TAG_imported_declaration has unknown "
8364                          "imported name - DIE at 0x%x [in module %s]"),
8365                        child_die->offset.sect_off, objfile->name);
8366             continue;
8367           }
8368
8369         VEC_safe_push (const_char_ptr, excludes, imported_name);
8370
8371         process_die (child_die, cu);
8372       }
8373
8374   cp_add_using_directive (import_prefix,
8375                           canonical_name,
8376                           import_alias,
8377                           imported_declaration,
8378                           excludes,
8379                           0,
8380                           &objfile->objfile_obstack);
8381
8382   do_cleanups (cleanups);
8383 }
8384
8385 /* Cleanup function for handle_DW_AT_stmt_list.  */
8386
8387 static void
8388 free_cu_line_header (void *arg)
8389 {
8390   struct dwarf2_cu *cu = arg;
8391
8392   free_line_header (cu->line_header);
8393   cu->line_header = NULL;
8394 }
8395
8396 /* Check for possibly missing DW_AT_comp_dir with relative .debug_line
8397    directory paths.  GCC SVN r127613 (new option -fdebug-prefix-map) fixed
8398    this, it was first present in GCC release 4.3.0.  */
8399
8400 static int
8401 producer_is_gcc_lt_4_3 (struct dwarf2_cu *cu)
8402 {
8403   if (!cu->checked_producer)
8404     check_producer (cu);
8405
8406   return cu->producer_is_gcc_lt_4_3;
8407 }
8408
8409 static void
8410 find_file_and_directory (struct die_info *die, struct dwarf2_cu *cu,
8411                          const char **name, const char **comp_dir)
8412 {
8413   struct attribute *attr;
8414
8415   *name = NULL;
8416   *comp_dir = NULL;
8417
8418   /* Find the filename.  Do not use dwarf2_name here, since the filename
8419      is not a source language identifier.  */
8420   attr = dwarf2_attr (die, DW_AT_name, cu);
8421   if (attr)
8422     {
8423       *name = DW_STRING (attr);
8424     }
8425
8426   attr = dwarf2_attr (die, DW_AT_comp_dir, cu);
8427   if (attr)
8428     *comp_dir = DW_STRING (attr);
8429   else if (producer_is_gcc_lt_4_3 (cu) && *name != NULL
8430            && IS_ABSOLUTE_PATH (*name))
8431     {
8432       char *d = ldirname (*name);
8433
8434       *comp_dir = d;
8435       if (d != NULL)
8436         make_cleanup (xfree, d);
8437     }
8438   if (*comp_dir != NULL)
8439     {
8440       /* Irix 6.2 native cc prepends <machine>.: to the compilation
8441          directory, get rid of it.  */
8442       char *cp = strchr (*comp_dir, ':');
8443
8444       if (cp && cp != *comp_dir && cp[-1] == '.' && cp[1] == '/')
8445         *comp_dir = cp + 1;
8446     }
8447
8448   if (*name == NULL)
8449     *name = "<unknown>";
8450 }
8451
8452 /* Handle DW_AT_stmt_list for a compilation unit.
8453    DIE is the DW_TAG_compile_unit die for CU.
8454    COMP_DIR is the compilation directory.
8455    WANT_LINE_INFO is non-zero if the pc/line-number mapping is needed.  */
8456
8457 static void
8458 handle_DW_AT_stmt_list (struct die_info *die, struct dwarf2_cu *cu,
8459                         const char *comp_dir) /* ARI: editCase function */
8460 {
8461   struct attribute *attr;
8462
8463   gdb_assert (! cu->per_cu->is_debug_types);
8464
8465   attr = dwarf2_attr (die, DW_AT_stmt_list, cu);
8466   if (attr)
8467     {
8468       unsigned int line_offset = DW_UNSND (attr);
8469       struct line_header *line_header
8470         = dwarf_decode_line_header (line_offset, cu);
8471
8472       if (line_header)
8473         {
8474           cu->line_header = line_header;
8475           make_cleanup (free_cu_line_header, cu);
8476           dwarf_decode_lines (line_header, comp_dir, cu, NULL, 1);
8477         }
8478     }
8479 }
8480
8481 /* Process DW_TAG_compile_unit or DW_TAG_partial_unit.  */
8482
8483 static void
8484 read_file_scope (struct die_info *die, struct dwarf2_cu *cu)
8485 {
8486   struct objfile *objfile = dwarf2_per_objfile->objfile;
8487   struct cleanup *back_to = make_cleanup (null_cleanup, 0);
8488   CORE_ADDR lowpc = ((CORE_ADDR) -1);
8489   CORE_ADDR highpc = ((CORE_ADDR) 0);
8490   struct attribute *attr;
8491   const char *name = NULL;
8492   const char *comp_dir = NULL;
8493   struct die_info *child_die;
8494   bfd *abfd = objfile->obfd;
8495   CORE_ADDR baseaddr;
8496
8497   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
8498
8499   get_scope_pc_bounds (die, &lowpc, &highpc, cu);
8500
8501   /* If we didn't find a lowpc, set it to highpc to avoid complaints
8502      from finish_block.  */
8503   if (lowpc == ((CORE_ADDR) -1))
8504     lowpc = highpc;
8505   lowpc += baseaddr;
8506   highpc += baseaddr;
8507
8508   find_file_and_directory (die, cu, &name, &comp_dir);
8509
8510   prepare_one_comp_unit (cu, die, cu->language);
8511
8512   /* The XLCL doesn't generate DW_LANG_OpenCL because this attribute is not
8513      standardised yet.  As a workaround for the language detection we fall
8514      back to the DW_AT_producer string.  */
8515   if (cu->producer && strstr (cu->producer, "IBM XL C for OpenCL") != NULL)
8516     cu->language = language_opencl;
8517
8518   /* Similar hack for Go.  */
8519   if (cu->producer && strstr (cu->producer, "GNU Go ") != NULL)
8520     set_cu_language (DW_LANG_Go, cu);
8521
8522   dwarf2_start_symtab (cu, name, comp_dir, lowpc);
8523
8524   /* Decode line number information if present.  We do this before
8525      processing child DIEs, so that the line header table is available
8526      for DW_AT_decl_file.  */
8527   handle_DW_AT_stmt_list (die, cu, comp_dir);
8528
8529   /* Process all dies in compilation unit.  */
8530   if (die->child != NULL)
8531     {
8532       child_die = die->child;
8533       while (child_die && child_die->tag)
8534         {
8535           process_die (child_die, cu);
8536           child_die = sibling_die (child_die);
8537         }
8538     }
8539
8540   /* Decode macro information, if present.  Dwarf 2 macro information
8541      refers to information in the line number info statement program
8542      header, so we can only read it if we've read the header
8543      successfully.  */
8544   attr = dwarf2_attr (die, DW_AT_GNU_macros, cu);
8545   if (attr && cu->line_header)
8546     {
8547       if (dwarf2_attr (die, DW_AT_macro_info, cu))
8548         complaint (&symfile_complaints,
8549                    _("CU refers to both DW_AT_GNU_macros and DW_AT_macro_info"));
8550
8551       dwarf_decode_macros (cu, DW_UNSND (attr), comp_dir, 1);
8552     }
8553   else
8554     {
8555       attr = dwarf2_attr (die, DW_AT_macro_info, cu);
8556       if (attr && cu->line_header)
8557         {
8558           unsigned int macro_offset = DW_UNSND (attr);
8559
8560           dwarf_decode_macros (cu, macro_offset, comp_dir, 0);
8561         }
8562     }
8563
8564   do_cleanups (back_to);
8565 }
8566
8567 /* TU version of handle_DW_AT_stmt_list for read_type_unit_scope.
8568    Create the set of symtabs used by this TU, or if this TU is sharing
8569    symtabs with another TU and the symtabs have already been created
8570    then restore those symtabs in the line header.
8571    We don't need the pc/line-number mapping for type units.  */
8572
8573 static void
8574 setup_type_unit_groups (struct die_info *die, struct dwarf2_cu *cu)
8575 {
8576   struct objfile *objfile = dwarf2_per_objfile->objfile;
8577   struct dwarf2_per_cu_data *per_cu = cu->per_cu;
8578   struct type_unit_group *tu_group;
8579   int first_time;
8580   struct line_header *lh;
8581   struct attribute *attr;
8582   unsigned int i, line_offset;
8583   struct signatured_type *sig_type;
8584
8585   gdb_assert (per_cu->is_debug_types);
8586   sig_type = (struct signatured_type *) per_cu;
8587
8588   attr = dwarf2_attr (die, DW_AT_stmt_list, cu);
8589
8590   /* If we're using .gdb_index (includes -readnow) then
8591      per_cu->type_unit_group may not have been set up yet.  */
8592   if (sig_type->type_unit_group == NULL)
8593     sig_type->type_unit_group = get_type_unit_group (cu, attr);
8594   tu_group = sig_type->type_unit_group;
8595
8596   /* If we've already processed this stmt_list there's no real need to
8597      do it again, we could fake it and just recreate the part we need
8598      (file name,index -> symtab mapping).  If data shows this optimization
8599      is useful we can do it then.  */
8600   first_time = tu_group->primary_symtab == NULL;
8601
8602   /* We have to handle the case of both a missing DW_AT_stmt_list or bad
8603      debug info.  */
8604   lh = NULL;
8605   if (attr != NULL)
8606     {
8607       line_offset = DW_UNSND (attr);
8608       lh = dwarf_decode_line_header (line_offset, cu);
8609     }
8610   if (lh == NULL)
8611     {
8612       if (first_time)
8613         dwarf2_start_symtab (cu, "", NULL, 0);
8614       else
8615         {
8616           gdb_assert (tu_group->symtabs == NULL);
8617           restart_symtab (0);
8618         }
8619       /* Note: The primary symtab will get allocated at the end.  */
8620       return;
8621     }
8622
8623   cu->line_header = lh;
8624   make_cleanup (free_cu_line_header, cu);
8625
8626   if (first_time)
8627     {
8628       dwarf2_start_symtab (cu, "", NULL, 0);
8629
8630       tu_group->num_symtabs = lh->num_file_names;
8631       tu_group->symtabs = XNEWVEC (struct symtab *, lh->num_file_names);
8632
8633       for (i = 0; i < lh->num_file_names; ++i)
8634         {
8635           const char *dir = NULL;
8636           struct file_entry *fe = &lh->file_names[i];
8637
8638           if (fe->dir_index)
8639             dir = lh->include_dirs[fe->dir_index - 1];
8640           dwarf2_start_subfile (fe->name, dir, NULL);
8641
8642           /* Note: We don't have to watch for the main subfile here, type units
8643              don't have DW_AT_name.  */
8644
8645           if (current_subfile->symtab == NULL)
8646             {
8647               /* NOTE: start_subfile will recognize when it's been passed
8648                  a file it has already seen.  So we can't assume there's a
8649                  simple mapping from lh->file_names to subfiles,
8650                  lh->file_names may contain dups.  */
8651               current_subfile->symtab = allocate_symtab (current_subfile->name,
8652                                                          objfile);
8653             }
8654
8655           fe->symtab = current_subfile->symtab;
8656           tu_group->symtabs[i] = fe->symtab;
8657         }
8658     }
8659   else
8660     {
8661       restart_symtab (0);
8662
8663       for (i = 0; i < lh->num_file_names; ++i)
8664         {
8665           struct file_entry *fe = &lh->file_names[i];
8666
8667           fe->symtab = tu_group->symtabs[i];
8668         }
8669     }
8670
8671   /* The main symtab is allocated last.  Type units don't have DW_AT_name
8672      so they don't have a "real" (so to speak) symtab anyway.
8673      There is later code that will assign the main symtab to all symbols
8674      that don't have one.  We need to handle the case of a symbol with a
8675      missing symtab (DW_AT_decl_file) anyway.  */
8676 }
8677
8678 /* Process DW_TAG_type_unit.
8679    For TUs we want to skip the first top level sibling if it's not the
8680    actual type being defined by this TU.  In this case the first top
8681    level sibling is there to provide context only.  */
8682
8683 static void
8684 read_type_unit_scope (struct die_info *die, struct dwarf2_cu *cu)
8685 {
8686   struct die_info *child_die;
8687
8688   prepare_one_comp_unit (cu, die, language_minimal);
8689
8690   /* Initialize (or reinitialize) the machinery for building symtabs.
8691      We do this before processing child DIEs, so that the line header table
8692      is available for DW_AT_decl_file.  */
8693   setup_type_unit_groups (die, cu);
8694
8695   if (die->child != NULL)
8696     {
8697       child_die = die->child;
8698       while (child_die && child_die->tag)
8699         {
8700           process_die (child_die, cu);
8701           child_die = sibling_die (child_die);
8702         }
8703     }
8704 }
8705 \f
8706 /* DWO/DWP files.
8707
8708    http://gcc.gnu.org/wiki/DebugFission
8709    http://gcc.gnu.org/wiki/DebugFissionDWP
8710
8711    To simplify handling of both DWO files ("object" files with the DWARF info)
8712    and DWP files (a file with the DWOs packaged up into one file), we treat
8713    DWP files as having a collection of virtual DWO files.  */
8714
8715 static hashval_t
8716 hash_dwo_file (const void *item)
8717 {
8718   const struct dwo_file *dwo_file = item;
8719   hashval_t hash;
8720
8721   hash = htab_hash_string (dwo_file->dwo_name);
8722   if (dwo_file->comp_dir != NULL)
8723     hash += htab_hash_string (dwo_file->comp_dir);
8724   return hash;
8725 }
8726
8727 static int
8728 eq_dwo_file (const void *item_lhs, const void *item_rhs)
8729 {
8730   const struct dwo_file *lhs = item_lhs;
8731   const struct dwo_file *rhs = item_rhs;
8732
8733   if (strcmp (lhs->dwo_name, rhs->dwo_name) != 0)
8734     return 0;
8735   if (lhs->comp_dir == NULL || rhs->comp_dir == NULL)
8736     return lhs->comp_dir == rhs->comp_dir;
8737   return strcmp (lhs->comp_dir, rhs->comp_dir) == 0;
8738 }
8739
8740 /* Allocate a hash table for DWO files.  */
8741
8742 static htab_t
8743 allocate_dwo_file_hash_table (void)
8744 {
8745   struct objfile *objfile = dwarf2_per_objfile->objfile;
8746
8747   return htab_create_alloc_ex (41,
8748                                hash_dwo_file,
8749                                eq_dwo_file,
8750                                NULL,
8751                                &objfile->objfile_obstack,
8752                                hashtab_obstack_allocate,
8753                                dummy_obstack_deallocate);
8754 }
8755
8756 /* Lookup DWO file DWO_NAME.  */
8757
8758 static void **
8759 lookup_dwo_file_slot (const char *dwo_name, const char *comp_dir)
8760 {
8761   struct dwo_file find_entry;
8762   void **slot;
8763
8764   if (dwarf2_per_objfile->dwo_files == NULL)
8765     dwarf2_per_objfile->dwo_files = allocate_dwo_file_hash_table ();
8766
8767   memset (&find_entry, 0, sizeof (find_entry));
8768   find_entry.dwo_name = dwo_name;
8769   find_entry.comp_dir = comp_dir;
8770   slot = htab_find_slot (dwarf2_per_objfile->dwo_files, &find_entry, INSERT);
8771
8772   return slot;
8773 }
8774
8775 static hashval_t
8776 hash_dwo_unit (const void *item)
8777 {
8778   const struct dwo_unit *dwo_unit = item;
8779
8780   /* This drops the top 32 bits of the id, but is ok for a hash.  */
8781   return dwo_unit->signature;
8782 }
8783
8784 static int
8785 eq_dwo_unit (const void *item_lhs, const void *item_rhs)
8786 {
8787   const struct dwo_unit *lhs = item_lhs;
8788   const struct dwo_unit *rhs = item_rhs;
8789
8790   /* The signature is assumed to be unique within the DWO file.
8791      So while object file CU dwo_id's always have the value zero,
8792      that's OK, assuming each object file DWO file has only one CU,
8793      and that's the rule for now.  */
8794   return lhs->signature == rhs->signature;
8795 }
8796
8797 /* Allocate a hash table for DWO CUs,TUs.
8798    There is one of these tables for each of CUs,TUs for each DWO file.  */
8799
8800 static htab_t
8801 allocate_dwo_unit_table (struct objfile *objfile)
8802 {
8803   /* Start out with a pretty small number.
8804      Generally DWO files contain only one CU and maybe some TUs.  */
8805   return htab_create_alloc_ex (3,
8806                                hash_dwo_unit,
8807                                eq_dwo_unit,
8808                                NULL,
8809                                &objfile->objfile_obstack,
8810                                hashtab_obstack_allocate,
8811                                dummy_obstack_deallocate);
8812 }
8813
8814 /* Structure used to pass data to create_dwo_debug_info_hash_table_reader.  */
8815
8816 struct create_dwo_cu_data
8817 {
8818   struct dwo_file *dwo_file;
8819   struct dwo_unit dwo_unit;
8820 };
8821
8822 /* die_reader_func for create_dwo_cu.  */
8823
8824 static void
8825 create_dwo_cu_reader (const struct die_reader_specs *reader,
8826                       const gdb_byte *info_ptr,
8827                       struct die_info *comp_unit_die,
8828                       int has_children,
8829                       void *datap)
8830 {
8831   struct dwarf2_cu *cu = reader->cu;
8832   struct objfile *objfile = dwarf2_per_objfile->objfile;
8833   sect_offset offset = cu->per_cu->offset;
8834   struct dwarf2_section_info *section = cu->per_cu->section;
8835   struct create_dwo_cu_data *data = datap;
8836   struct dwo_file *dwo_file = data->dwo_file;
8837   struct dwo_unit *dwo_unit = &data->dwo_unit;
8838   struct attribute *attr;
8839
8840   attr = dwarf2_attr (comp_unit_die, DW_AT_GNU_dwo_id, cu);
8841   if (attr == NULL)
8842     {
8843       complaint (&symfile_complaints,
8844                  _("Dwarf Error: debug entry at offset 0x%x is missing"
8845                    " its dwo_id [in module %s]"),
8846                  offset.sect_off, dwo_file->dwo_name);
8847       return;
8848     }
8849
8850   dwo_unit->dwo_file = dwo_file;
8851   dwo_unit->signature = DW_UNSND (attr);
8852   dwo_unit->section = section;
8853   dwo_unit->offset = offset;
8854   dwo_unit->length = cu->per_cu->length;
8855
8856   if (dwarf2_read_debug)
8857     fprintf_unfiltered (gdb_stdlog, "  offset 0x%x, dwo_id %s\n",
8858                         offset.sect_off, hex_string (dwo_unit->signature));
8859 }
8860
8861 /* Create the dwo_unit for the lone CU in DWO_FILE.
8862    Note: This function processes DWO files only, not DWP files.  */
8863
8864 static struct dwo_unit *
8865 create_dwo_cu (struct dwo_file *dwo_file)
8866 {
8867   struct objfile *objfile = dwarf2_per_objfile->objfile;
8868   struct dwarf2_section_info *section = &dwo_file->sections.info;
8869   bfd *abfd;
8870   htab_t cu_htab;
8871   const gdb_byte *info_ptr, *end_ptr;
8872   struct create_dwo_cu_data create_dwo_cu_data;
8873   struct dwo_unit *dwo_unit;
8874
8875   dwarf2_read_section (objfile, section);
8876   info_ptr = section->buffer;
8877
8878   if (info_ptr == NULL)
8879     return NULL;
8880
8881   /* We can't set abfd until now because the section may be empty or
8882      not present, in which case section->asection will be NULL.  */
8883   abfd = section->asection->owner;
8884
8885   if (dwarf2_read_debug)
8886     {
8887       fprintf_unfiltered (gdb_stdlog, "Reading %s for %s:\n",
8888                           bfd_section_name (abfd, section->asection),
8889                           bfd_get_filename (abfd));
8890     }
8891
8892   create_dwo_cu_data.dwo_file = dwo_file;
8893   dwo_unit = NULL;
8894
8895   end_ptr = info_ptr + section->size;
8896   while (info_ptr < end_ptr)
8897     {
8898       struct dwarf2_per_cu_data per_cu;
8899
8900       memset (&create_dwo_cu_data.dwo_unit, 0,
8901               sizeof (create_dwo_cu_data.dwo_unit));
8902       memset (&per_cu, 0, sizeof (per_cu));
8903       per_cu.objfile = objfile;
8904       per_cu.is_debug_types = 0;
8905       per_cu.offset.sect_off = info_ptr - section->buffer;
8906       per_cu.section = section;
8907
8908       init_cutu_and_read_dies_no_follow (&per_cu,
8909                                          &dwo_file->sections.abbrev,
8910                                          dwo_file,
8911                                          create_dwo_cu_reader,
8912                                          &create_dwo_cu_data);
8913
8914       if (create_dwo_cu_data.dwo_unit.dwo_file != NULL)
8915         {
8916           /* If we've already found one, complain.  We only support one
8917              because having more than one requires hacking the dwo_name of
8918              each to match, which is highly unlikely to happen.  */
8919           if (dwo_unit != NULL)
8920             {
8921               complaint (&symfile_complaints,
8922                          _("Multiple CUs in DWO file %s [in module %s]"),
8923                          dwo_file->dwo_name, objfile->name);
8924               break;
8925             }
8926
8927           dwo_unit = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_unit);
8928           *dwo_unit = create_dwo_cu_data.dwo_unit;
8929         }
8930
8931       info_ptr += per_cu.length;
8932     }
8933
8934   return dwo_unit;
8935 }
8936
8937 /* DWP file .debug_{cu,tu}_index section format:
8938    [ref: http://gcc.gnu.org/wiki/DebugFissionDWP]
8939
8940    DWP Version 1:
8941
8942    Both index sections have the same format, and serve to map a 64-bit
8943    signature to a set of section numbers.  Each section begins with a header,
8944    followed by a hash table of 64-bit signatures, a parallel table of 32-bit
8945    indexes, and a pool of 32-bit section numbers.  The index sections will be
8946    aligned at 8-byte boundaries in the file.
8947
8948    The index section header consists of:
8949
8950     V, 32 bit version number
8951     -, 32 bits unused
8952     N, 32 bit number of compilation units or type units in the index
8953     M, 32 bit number of slots in the hash table
8954
8955    Numbers are recorded using the byte order of the application binary.
8956
8957    We assume that N and M will not exceed 2^32 - 1.
8958
8959    The size of the hash table, M, must be 2^k such that 2^k > 3*N/2.
8960
8961    The hash table begins at offset 16 in the section, and consists of an array
8962    of M 64-bit slots.  Each slot contains a 64-bit signature (using the byte
8963    order of the application binary).  Unused slots in the hash table are 0.
8964    (We rely on the extreme unlikeliness of a signature being exactly 0.)
8965
8966    The parallel table begins immediately after the hash table
8967    (at offset 16 + 8 * M from the beginning of the section), and consists of an
8968    array of 32-bit indexes (using the byte order of the application binary),
8969    corresponding 1-1 with slots in the hash table.  Each entry in the parallel
8970    table contains a 32-bit index into the pool of section numbers.  For unused
8971    hash table slots, the corresponding entry in the parallel table will be 0.
8972
8973    Given a 64-bit compilation unit signature or a type signature S, an entry
8974    in the hash table is located as follows:
8975
8976    1) Calculate a primary hash H = S & MASK(k), where MASK(k) is a mask with
8977       the low-order k bits all set to 1.
8978
8979    2) Calculate a secondary hash H' = (((S >> 32) & MASK(k)) | 1).
8980
8981    3) If the hash table entry at index H matches the signature, use that
8982       entry.  If the hash table entry at index H is unused (all zeroes),
8983       terminate the search: the signature is not present in the table.
8984
8985    4) Let H = (H + H') modulo M. Repeat at Step 3.
8986
8987    Because M > N and H' and M are relatively prime, the search is guaranteed
8988    to stop at an unused slot or find the match.
8989
8990    The pool of section numbers begins immediately following the hash table
8991    (at offset 16 + 12 * M from the beginning of the section).  The pool of
8992    section numbers consists of an array of 32-bit words (using the byte order
8993    of the application binary).  Each item in the array is indexed starting
8994    from 0.  The hash table entry provides the index of the first section
8995    number in the set.  Additional section numbers in the set follow, and the
8996    set is terminated by a 0 entry (section number 0 is not used in ELF).
8997
8998    In each set of section numbers, the .debug_info.dwo or .debug_types.dwo
8999    section must be the first entry in the set, and the .debug_abbrev.dwo must
9000    be the second entry. Other members of the set may follow in any order.  */
9001
9002 /* Create a hash table to map DWO IDs to their CU/TU entry in
9003    .debug_{info,types}.dwo in DWP_FILE.
9004    Returns NULL if there isn't one.
9005    Note: This function processes DWP files only, not DWO files.  */
9006
9007 static struct dwp_hash_table *
9008 create_dwp_hash_table (struct dwp_file *dwp_file, int is_debug_types)
9009 {
9010   struct objfile *objfile = dwarf2_per_objfile->objfile;
9011   bfd *dbfd = dwp_file->dbfd;
9012   const gdb_byte *index_ptr, *index_end;
9013   struct dwarf2_section_info *index;
9014   uint32_t version, nr_units, nr_slots;
9015   struct dwp_hash_table *htab;
9016
9017   if (is_debug_types)
9018     index = &dwp_file->sections.tu_index;
9019   else
9020     index = &dwp_file->sections.cu_index;
9021
9022   if (dwarf2_section_empty_p (index))
9023     return NULL;
9024   dwarf2_read_section (objfile, index);
9025
9026   index_ptr = index->buffer;
9027   index_end = index_ptr + index->size;
9028
9029   version = read_4_bytes (dbfd, index_ptr);
9030   index_ptr += 8; /* Skip the unused word.  */
9031   nr_units = read_4_bytes (dbfd, index_ptr);
9032   index_ptr += 4;
9033   nr_slots = read_4_bytes (dbfd, index_ptr);
9034   index_ptr += 4;
9035
9036   if (version != 1)
9037     {
9038       error (_("Dwarf Error: unsupported DWP file version (%s)"
9039                " [in module %s]"),
9040              pulongest (version), dwp_file->name);
9041     }
9042   if (nr_slots != (nr_slots & -nr_slots))
9043     {
9044       error (_("Dwarf Error: number of slots in DWP hash table (%s)"
9045                " is not power of 2 [in module %s]"),
9046              pulongest (nr_slots), dwp_file->name);
9047     }
9048
9049   htab = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwp_hash_table);
9050   htab->nr_units = nr_units;
9051   htab->nr_slots = nr_slots;
9052   htab->hash_table = index_ptr;
9053   htab->unit_table = htab->hash_table + sizeof (uint64_t) * nr_slots;
9054   htab->section_pool = htab->unit_table + sizeof (uint32_t) * nr_slots;
9055
9056   return htab;
9057 }
9058
9059 /* Update SECTIONS with the data from SECTP.
9060
9061    This function is like the other "locate" section routines that are
9062    passed to bfd_map_over_sections, but in this context the sections to
9063    read comes from the DWP hash table, not the full ELF section table.
9064
9065    The result is non-zero for success, or zero if an error was found.  */
9066
9067 static int
9068 locate_virtual_dwo_sections (asection *sectp,
9069                              struct virtual_dwo_sections *sections)
9070 {
9071   const struct dwop_section_names *names = &dwop_section_names;
9072
9073   if (section_is_p (sectp->name, &names->abbrev_dwo))
9074     {
9075       /* There can be only one.  */
9076       if (sections->abbrev.asection != NULL)
9077         return 0;
9078       sections->abbrev.asection = sectp;
9079       sections->abbrev.size = bfd_get_section_size (sectp);
9080     }
9081   else if (section_is_p (sectp->name, &names->info_dwo)
9082            || section_is_p (sectp->name, &names->types_dwo))
9083     {
9084       /* There can be only one.  */
9085       if (sections->info_or_types.asection != NULL)
9086         return 0;
9087       sections->info_or_types.asection = sectp;
9088       sections->info_or_types.size = bfd_get_section_size (sectp);
9089     }
9090   else if (section_is_p (sectp->name, &names->line_dwo))
9091     {
9092       /* There can be only one.  */
9093       if (sections->line.asection != NULL)
9094         return 0;
9095       sections->line.asection = sectp;
9096       sections->line.size = bfd_get_section_size (sectp);
9097     }
9098   else if (section_is_p (sectp->name, &names->loc_dwo))
9099     {
9100       /* There can be only one.  */
9101       if (sections->loc.asection != NULL)
9102         return 0;
9103       sections->loc.asection = sectp;
9104       sections->loc.size = bfd_get_section_size (sectp);
9105     }
9106   else if (section_is_p (sectp->name, &names->macinfo_dwo))
9107     {
9108       /* There can be only one.  */
9109       if (sections->macinfo.asection != NULL)
9110         return 0;
9111       sections->macinfo.asection = sectp;
9112       sections->macinfo.size = bfd_get_section_size (sectp);
9113     }
9114   else if (section_is_p (sectp->name, &names->macro_dwo))
9115     {
9116       /* There can be only one.  */
9117       if (sections->macro.asection != NULL)
9118         return 0;
9119       sections->macro.asection = sectp;
9120       sections->macro.size = bfd_get_section_size (sectp);
9121     }
9122   else if (section_is_p (sectp->name, &names->str_offsets_dwo))
9123     {
9124       /* There can be only one.  */
9125       if (sections->str_offsets.asection != NULL)
9126         return 0;
9127       sections->str_offsets.asection = sectp;
9128       sections->str_offsets.size = bfd_get_section_size (sectp);
9129     }
9130   else
9131     {
9132       /* No other kind of section is valid.  */
9133       return 0;
9134     }
9135
9136   return 1;
9137 }
9138
9139 /* Create a dwo_unit object for the DWO with signature SIGNATURE.
9140    HTAB is the hash table from the DWP file.
9141    SECTION_INDEX is the index of the DWO in HTAB.
9142    COMP_DIR is the DW_AT_comp_dir attribute of the referencing CU.  */
9143
9144 static struct dwo_unit *
9145 create_dwo_in_dwp (struct dwp_file *dwp_file,
9146                    const struct dwp_hash_table *htab,
9147                    uint32_t section_index,
9148                    const char *comp_dir,
9149                    ULONGEST signature, int is_debug_types)
9150 {
9151   struct objfile *objfile = dwarf2_per_objfile->objfile;
9152   bfd *dbfd = dwp_file->dbfd;
9153   const char *kind = is_debug_types ? "TU" : "CU";
9154   struct dwo_file *dwo_file;
9155   struct dwo_unit *dwo_unit;
9156   struct virtual_dwo_sections sections;
9157   void **dwo_file_slot;
9158   char *virtual_dwo_name;
9159   struct dwarf2_section_info *cutu;
9160   struct cleanup *cleanups;
9161   int i;
9162
9163   if (dwarf2_read_debug)
9164     {
9165       fprintf_unfiltered (gdb_stdlog, "Reading %s %s/%s in DWP file: %s\n",
9166                           kind,
9167                           pulongest (section_index), hex_string (signature),
9168                           dwp_file->name);
9169     }
9170
9171   /* Fetch the sections of this DWO.
9172      Put a limit on the number of sections we look for so that bad data
9173      doesn't cause us to loop forever.  */
9174
9175 #define MAX_NR_DWO_SECTIONS \
9176   (1 /* .debug_info or .debug_types */ \
9177    + 1 /* .debug_abbrev */ \
9178    + 1 /* .debug_line */ \
9179    + 1 /* .debug_loc */ \
9180    + 1 /* .debug_str_offsets */ \
9181    + 1 /* .debug_macro */ \
9182    + 1 /* .debug_macinfo */ \
9183    + 1 /* trailing zero */)
9184
9185   memset (&sections, 0, sizeof (sections));
9186   cleanups = make_cleanup (null_cleanup, 0);
9187
9188   for (i = 0; i < MAX_NR_DWO_SECTIONS; ++i)
9189     {
9190       asection *sectp;
9191       uint32_t section_nr =
9192         read_4_bytes (dbfd,
9193                       htab->section_pool
9194                       + (section_index + i) * sizeof (uint32_t));
9195
9196       if (section_nr == 0)
9197         break;
9198       if (section_nr >= dwp_file->num_sections)
9199         {
9200           error (_("Dwarf Error: bad DWP hash table, section number too large"
9201                    " [in module %s]"),
9202                  dwp_file->name);
9203         }
9204
9205       sectp = dwp_file->elf_sections[section_nr];
9206       if (! locate_virtual_dwo_sections (sectp, &sections))
9207         {
9208           error (_("Dwarf Error: bad DWP hash table, invalid section found"
9209                    " [in module %s]"),
9210                  dwp_file->name);
9211         }
9212     }
9213
9214   if (i < 2
9215       || sections.info_or_types.asection == NULL
9216       || sections.abbrev.asection == NULL)
9217     {
9218       error (_("Dwarf Error: bad DWP hash table, missing DWO sections"
9219                " [in module %s]"),
9220              dwp_file->name);
9221     }
9222   if (i == MAX_NR_DWO_SECTIONS)
9223     {
9224       error (_("Dwarf Error: bad DWP hash table, too many DWO sections"
9225                " [in module %s]"),
9226              dwp_file->name);
9227     }
9228
9229   /* It's easier for the rest of the code if we fake a struct dwo_file and
9230      have dwo_unit "live" in that.  At least for now.
9231
9232      The DWP file can be made up of a random collection of CUs and TUs.
9233      However, for each CU + set of TUs that came from the same original DWO
9234      file, we want to combine them back into a virtual DWO file to save space
9235      (fewer struct dwo_file objects to allocated).  Remember that for really
9236      large apps there can be on the order of 8K CUs and 200K TUs, or more.  */
9237
9238   virtual_dwo_name =
9239     xstrprintf ("virtual-dwo/%d-%d-%d-%d",
9240                 sections.abbrev.asection ? sections.abbrev.asection->id : 0,
9241                 sections.line.asection ? sections.line.asection->id : 0,
9242                 sections.loc.asection ? sections.loc.asection->id : 0,
9243                 (sections.str_offsets.asection
9244                 ? sections.str_offsets.asection->id
9245                 : 0));
9246   make_cleanup (xfree, virtual_dwo_name);
9247   /* Can we use an existing virtual DWO file?  */
9248   dwo_file_slot = lookup_dwo_file_slot (virtual_dwo_name, comp_dir);
9249   /* Create one if necessary.  */
9250   if (*dwo_file_slot == NULL)
9251     {
9252       if (dwarf2_read_debug)
9253         {
9254           fprintf_unfiltered (gdb_stdlog, "Creating virtual DWO: %s\n",
9255                               virtual_dwo_name);
9256         }
9257       dwo_file = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_file);
9258       dwo_file->dwo_name = obstack_copy0 (&objfile->objfile_obstack,
9259                                           virtual_dwo_name,
9260                                           strlen (virtual_dwo_name));
9261       dwo_file->comp_dir = comp_dir;
9262       dwo_file->sections.abbrev = sections.abbrev;
9263       dwo_file->sections.line = sections.line;
9264       dwo_file->sections.loc = sections.loc;
9265       dwo_file->sections.macinfo = sections.macinfo;
9266       dwo_file->sections.macro = sections.macro;
9267       dwo_file->sections.str_offsets = sections.str_offsets;
9268       /* The "str" section is global to the entire DWP file.  */
9269       dwo_file->sections.str = dwp_file->sections.str;
9270       /* The info or types section is assigned later to dwo_unit,
9271          there's no need to record it in dwo_file.
9272          Also, we can't simply record type sections in dwo_file because
9273          we record a pointer into the vector in dwo_unit.  As we collect more
9274          types we'll grow the vector and eventually have to reallocate space
9275          for it, invalidating all the pointers into the current copy.  */
9276       *dwo_file_slot = dwo_file;
9277     }
9278   else
9279     {
9280       if (dwarf2_read_debug)
9281         {
9282           fprintf_unfiltered (gdb_stdlog, "Using existing virtual DWO: %s\n",
9283                               virtual_dwo_name);
9284         }
9285       dwo_file = *dwo_file_slot;
9286     }
9287   do_cleanups (cleanups);
9288
9289   dwo_unit = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_unit);
9290   dwo_unit->dwo_file = dwo_file;
9291   dwo_unit->signature = signature;
9292   dwo_unit->section = obstack_alloc (&objfile->objfile_obstack,
9293                                      sizeof (struct dwarf2_section_info));
9294   *dwo_unit->section = sections.info_or_types;
9295   /* offset, length, type_offset_in_tu are set later.  */
9296
9297   return dwo_unit;
9298 }
9299
9300 /* Lookup the DWO with SIGNATURE in DWP_FILE.  */
9301
9302 static struct dwo_unit *
9303 lookup_dwo_in_dwp (struct dwp_file *dwp_file,
9304                    const struct dwp_hash_table *htab,
9305                    const char *comp_dir,
9306                    ULONGEST signature, int is_debug_types)
9307 {
9308   bfd *dbfd = dwp_file->dbfd;
9309   uint32_t mask = htab->nr_slots - 1;
9310   uint32_t hash = signature & mask;
9311   uint32_t hash2 = ((signature >> 32) & mask) | 1;
9312   unsigned int i;
9313   void **slot;
9314   struct dwo_unit find_dwo_cu, *dwo_cu;
9315
9316   memset (&find_dwo_cu, 0, sizeof (find_dwo_cu));
9317   find_dwo_cu.signature = signature;
9318   slot = htab_find_slot (dwp_file->loaded_cutus, &find_dwo_cu, INSERT);
9319
9320   if (*slot != NULL)
9321     return *slot;
9322
9323   /* Use a for loop so that we don't loop forever on bad debug info.  */
9324   for (i = 0; i < htab->nr_slots; ++i)
9325     {
9326       ULONGEST signature_in_table;
9327
9328       signature_in_table =
9329         read_8_bytes (dbfd, htab->hash_table + hash * sizeof (uint64_t));
9330       if (signature_in_table == signature)
9331         {
9332           uint32_t section_index =
9333             read_4_bytes (dbfd, htab->unit_table + hash * sizeof (uint32_t));
9334
9335           *slot = create_dwo_in_dwp (dwp_file, htab, section_index,
9336                                      comp_dir, signature, is_debug_types);
9337           return *slot;
9338         }
9339       if (signature_in_table == 0)
9340         return NULL;
9341       hash = (hash + hash2) & mask;
9342     }
9343
9344   error (_("Dwarf Error: bad DWP hash table, lookup didn't terminate"
9345            " [in module %s]"),
9346          dwp_file->name);
9347 }
9348
9349 /* Subroutine of open_dwo_file,open_dwp_file to simplify them.
9350    Open the file specified by FILE_NAME and hand it off to BFD for
9351    preliminary analysis.  Return a newly initialized bfd *, which
9352    includes a canonicalized copy of FILE_NAME.
9353    If IS_DWP is TRUE, we're opening a DWP file, otherwise a DWO file.
9354    SEARCH_CWD is true if the current directory is to be searched.
9355    It will be searched before debug-file-directory.
9356    If unable to find/open the file, return NULL.
9357    NOTE: This function is derived from symfile_bfd_open.  */
9358
9359 static bfd *
9360 try_open_dwop_file (const char *file_name, int is_dwp, int search_cwd)
9361 {
9362   bfd *sym_bfd;
9363   int desc, flags;
9364   char *absolute_name;
9365   /* Blech.  OPF_TRY_CWD_FIRST also disables searching the path list if
9366      FILE_NAME contains a '/'.  So we can't use it.  Instead prepend "."
9367      to debug_file_directory.  */
9368   char *search_path;
9369   static const char dirname_separator_string[] = { DIRNAME_SEPARATOR, '\0' };
9370
9371   if (search_cwd)
9372     {
9373       if (*debug_file_directory != '\0')
9374         search_path = concat (".", dirname_separator_string,
9375                               debug_file_directory, NULL);
9376       else
9377         search_path = xstrdup (".");
9378     }
9379   else
9380     search_path = xstrdup (debug_file_directory);
9381
9382   flags = 0;
9383   if (is_dwp)
9384     flags |= OPF_SEARCH_IN_PATH;
9385   desc = openp (search_path, flags, file_name,
9386                 O_RDONLY | O_BINARY, &absolute_name);
9387   xfree (search_path);
9388   if (desc < 0)
9389     return NULL;
9390
9391   sym_bfd = gdb_bfd_open (absolute_name, gnutarget, desc);
9392   xfree (absolute_name);
9393   if (sym_bfd == NULL)
9394     return NULL;
9395   bfd_set_cacheable (sym_bfd, 1);
9396
9397   if (!bfd_check_format (sym_bfd, bfd_object))
9398     {
9399       gdb_bfd_unref (sym_bfd); /* This also closes desc.  */
9400       return NULL;
9401     }
9402
9403   return sym_bfd;
9404 }
9405
9406 /* Try to open DWO file FILE_NAME.
9407    COMP_DIR is the DW_AT_comp_dir attribute.
9408    The result is the bfd handle of the file.
9409    If there is a problem finding or opening the file, return NULL.
9410    Upon success, the canonicalized path of the file is stored in the bfd,
9411    same as symfile_bfd_open.  */
9412
9413 static bfd *
9414 open_dwo_file (const char *file_name, const char *comp_dir)
9415 {
9416   bfd *abfd;
9417
9418   if (IS_ABSOLUTE_PATH (file_name))
9419     return try_open_dwop_file (file_name, 0 /*is_dwp*/, 0 /*search_cwd*/);
9420
9421   /* Before trying the search path, try DWO_NAME in COMP_DIR.  */
9422
9423   if (comp_dir != NULL)
9424     {
9425       char *path_to_try = concat (comp_dir, SLASH_STRING, file_name, NULL);
9426
9427       /* NOTE: If comp_dir is a relative path, this will also try the
9428          search path, which seems useful.  */
9429       abfd = try_open_dwop_file (path_to_try, 0 /*is_dwp*/, 1 /*search_cwd*/);
9430       xfree (path_to_try);
9431       if (abfd != NULL)
9432         return abfd;
9433     }
9434
9435   /* That didn't work, try debug-file-directory, which, despite its name,
9436      is a list of paths.  */
9437
9438   if (*debug_file_directory == '\0')
9439     return NULL;
9440
9441   return try_open_dwop_file (file_name, 0 /*is_dwp*/, 1 /*search_cwd*/);
9442 }
9443
9444 /* This function is mapped across the sections and remembers the offset and
9445    size of each of the DWO debugging sections we are interested in.  */
9446
9447 static void
9448 dwarf2_locate_dwo_sections (bfd *abfd, asection *sectp, void *dwo_sections_ptr)
9449 {
9450   struct dwo_sections *dwo_sections = dwo_sections_ptr;
9451   const struct dwop_section_names *names = &dwop_section_names;
9452
9453   if (section_is_p (sectp->name, &names->abbrev_dwo))
9454     {
9455       dwo_sections->abbrev.asection = sectp;
9456       dwo_sections->abbrev.size = bfd_get_section_size (sectp);
9457     }
9458   else if (section_is_p (sectp->name, &names->info_dwo))
9459     {
9460       dwo_sections->info.asection = sectp;
9461       dwo_sections->info.size = bfd_get_section_size (sectp);
9462     }
9463   else if (section_is_p (sectp->name, &names->line_dwo))
9464     {
9465       dwo_sections->line.asection = sectp;
9466       dwo_sections->line.size = bfd_get_section_size (sectp);
9467     }
9468   else if (section_is_p (sectp->name, &names->loc_dwo))
9469     {
9470       dwo_sections->loc.asection = sectp;
9471       dwo_sections->loc.size = bfd_get_section_size (sectp);
9472     }
9473   else if (section_is_p (sectp->name, &names->macinfo_dwo))
9474     {
9475       dwo_sections->macinfo.asection = sectp;
9476       dwo_sections->macinfo.size = bfd_get_section_size (sectp);
9477     }
9478   else if (section_is_p (sectp->name, &names->macro_dwo))
9479     {
9480       dwo_sections->macro.asection = sectp;
9481       dwo_sections->macro.size = bfd_get_section_size (sectp);
9482     }
9483   else if (section_is_p (sectp->name, &names->str_dwo))
9484     {
9485       dwo_sections->str.asection = sectp;
9486       dwo_sections->str.size = bfd_get_section_size (sectp);
9487     }
9488   else if (section_is_p (sectp->name, &names->str_offsets_dwo))
9489     {
9490       dwo_sections->str_offsets.asection = sectp;
9491       dwo_sections->str_offsets.size = bfd_get_section_size (sectp);
9492     }
9493   else if (section_is_p (sectp->name, &names->types_dwo))
9494     {
9495       struct dwarf2_section_info type_section;
9496
9497       memset (&type_section, 0, sizeof (type_section));
9498       type_section.asection = sectp;
9499       type_section.size = bfd_get_section_size (sectp);
9500       VEC_safe_push (dwarf2_section_info_def, dwo_sections->types,
9501                      &type_section);
9502     }
9503 }
9504
9505 /* Initialize the use of the DWO file specified by DWO_NAME and referenced
9506    by PER_CU.  This is for the non-DWP case.
9507    The result is NULL if DWO_NAME can't be found.  */
9508
9509 static struct dwo_file *
9510 open_and_init_dwo_file (struct dwarf2_per_cu_data *per_cu,
9511                         const char *dwo_name, const char *comp_dir)
9512 {
9513   struct objfile *objfile = dwarf2_per_objfile->objfile;
9514   struct dwo_file *dwo_file;
9515   bfd *dbfd;
9516   struct cleanup *cleanups;
9517
9518   dbfd = open_dwo_file (dwo_name, comp_dir);
9519   if (dbfd == NULL)
9520     {
9521       if (dwarf2_read_debug)
9522         fprintf_unfiltered (gdb_stdlog, "DWO file not found: %s\n", dwo_name);
9523       return NULL;
9524     }
9525   dwo_file = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_file);
9526   dwo_file->dwo_name = dwo_name;
9527   dwo_file->comp_dir = comp_dir;
9528   dwo_file->dbfd = dbfd;
9529
9530   cleanups = make_cleanup (free_dwo_file_cleanup, dwo_file);
9531
9532   bfd_map_over_sections (dbfd, dwarf2_locate_dwo_sections, &dwo_file->sections);
9533
9534   dwo_file->cu = create_dwo_cu (dwo_file);
9535
9536   dwo_file->tus = create_debug_types_hash_table (dwo_file,
9537                                                  dwo_file->sections.types);
9538
9539   discard_cleanups (cleanups);
9540
9541   if (dwarf2_read_debug)
9542     fprintf_unfiltered (gdb_stdlog, "DWO file found: %s\n", dwo_name);
9543
9544   return dwo_file;
9545 }
9546
9547 /* This function is mapped across the sections and remembers the offset and
9548    size of each of the DWP debugging sections we are interested in.  */
9549
9550 static void
9551 dwarf2_locate_dwp_sections (bfd *abfd, asection *sectp, void *dwp_file_ptr)
9552 {
9553   struct dwp_file *dwp_file = dwp_file_ptr;
9554   const struct dwop_section_names *names = &dwop_section_names;
9555   unsigned int elf_section_nr = elf_section_data (sectp)->this_idx;
9556
9557   /* Record the ELF section number for later lookup: this is what the
9558      .debug_cu_index,.debug_tu_index tables use.  */
9559   gdb_assert (elf_section_nr < dwp_file->num_sections);
9560   dwp_file->elf_sections[elf_section_nr] = sectp;
9561
9562   /* Look for specific sections that we need.  */
9563   if (section_is_p (sectp->name, &names->str_dwo))
9564     {
9565       dwp_file->sections.str.asection = sectp;
9566       dwp_file->sections.str.size = bfd_get_section_size (sectp);
9567     }
9568   else if (section_is_p (sectp->name, &names->cu_index))
9569     {
9570       dwp_file->sections.cu_index.asection = sectp;
9571       dwp_file->sections.cu_index.size = bfd_get_section_size (sectp);
9572     }
9573   else if (section_is_p (sectp->name, &names->tu_index))
9574     {
9575       dwp_file->sections.tu_index.asection = sectp;
9576       dwp_file->sections.tu_index.size = bfd_get_section_size (sectp);
9577     }
9578 }
9579
9580 /* Hash function for dwp_file loaded CUs/TUs.  */
9581
9582 static hashval_t
9583 hash_dwp_loaded_cutus (const void *item)
9584 {
9585   const struct dwo_unit *dwo_unit = item;
9586
9587   /* This drops the top 32 bits of the signature, but is ok for a hash.  */
9588   return dwo_unit->signature;
9589 }
9590
9591 /* Equality function for dwp_file loaded CUs/TUs.  */
9592
9593 static int
9594 eq_dwp_loaded_cutus (const void *a, const void *b)
9595 {
9596   const struct dwo_unit *dua = a;
9597   const struct dwo_unit *dub = b;
9598
9599   return dua->signature == dub->signature;
9600 }
9601
9602 /* Allocate a hash table for dwp_file loaded CUs/TUs.  */
9603
9604 static htab_t
9605 allocate_dwp_loaded_cutus_table (struct objfile *objfile)
9606 {
9607   return htab_create_alloc_ex (3,
9608                                hash_dwp_loaded_cutus,
9609                                eq_dwp_loaded_cutus,
9610                                NULL,
9611                                &objfile->objfile_obstack,
9612                                hashtab_obstack_allocate,
9613                                dummy_obstack_deallocate);
9614 }
9615
9616 /* Try to open DWP file FILE_NAME.
9617    The result is the bfd handle of the file.
9618    If there is a problem finding or opening the file, return NULL.
9619    Upon success, the canonicalized path of the file is stored in the bfd,
9620    same as symfile_bfd_open.  */
9621
9622 static bfd *
9623 open_dwp_file (const char *file_name)
9624 {
9625   bfd *abfd;
9626
9627   abfd = try_open_dwop_file (file_name, 1 /*is_dwp*/, 1 /*search_cwd*/);
9628   if (abfd != NULL)
9629     return abfd;
9630
9631   /* Work around upstream bug 15652.
9632      http://sourceware.org/bugzilla/show_bug.cgi?id=15652
9633      [Whether that's a "bug" is debatable, but it is getting in our way.]
9634      We have no real idea where the dwp file is, because gdb's realpath-ing
9635      of the executable's path may have discarded the needed info.
9636      [IWBN if the dwp file name was recorded in the executable, akin to
9637      .gnu_debuglink, but that doesn't exist yet.]
9638      Strip the directory from FILE_NAME and search again.  */
9639   if (*debug_file_directory != '\0')
9640     {
9641       /* Don't implicitly search the current directory here.
9642          If the user wants to search "." to handle this case,
9643          it must be added to debug-file-directory.  */
9644       return try_open_dwop_file (lbasename (file_name), 1 /*is_dwp*/,
9645                                  0 /*search_cwd*/);
9646     }
9647
9648   return NULL;
9649 }
9650
9651 /* Initialize the use of the DWP file for the current objfile.
9652    By convention the name of the DWP file is ${objfile}.dwp.
9653    The result is NULL if it can't be found.  */
9654
9655 static struct dwp_file *
9656 open_and_init_dwp_file (void)
9657 {
9658   struct objfile *objfile = dwarf2_per_objfile->objfile;
9659   struct dwp_file *dwp_file;
9660   char *dwp_name;
9661   bfd *dbfd;
9662   struct cleanup *cleanups;
9663
9664   dwp_name = xstrprintf ("%s.dwp", dwarf2_per_objfile->objfile->name);
9665   cleanups = make_cleanup (xfree, dwp_name);
9666
9667   dbfd = open_dwp_file (dwp_name);
9668   if (dbfd == NULL)
9669     {
9670       if (dwarf2_read_debug)
9671         fprintf_unfiltered (gdb_stdlog, "DWP file not found: %s\n", dwp_name);
9672       do_cleanups (cleanups);
9673       return NULL;
9674     }
9675   dwp_file = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwp_file);
9676   dwp_file->name = bfd_get_filename (dbfd);
9677   dwp_file->dbfd = dbfd;
9678   do_cleanups (cleanups);
9679
9680   /* +1: section 0 is unused */
9681   dwp_file->num_sections = bfd_count_sections (dbfd) + 1;
9682   dwp_file->elf_sections =
9683     OBSTACK_CALLOC (&objfile->objfile_obstack,
9684                     dwp_file->num_sections, asection *);
9685
9686   bfd_map_over_sections (dbfd, dwarf2_locate_dwp_sections, dwp_file);
9687
9688   dwp_file->cus = create_dwp_hash_table (dwp_file, 0);
9689
9690   dwp_file->tus = create_dwp_hash_table (dwp_file, 1);
9691
9692   dwp_file->loaded_cutus = allocate_dwp_loaded_cutus_table (objfile);
9693
9694   if (dwarf2_read_debug)
9695     {
9696       fprintf_unfiltered (gdb_stdlog, "DWP file found: %s\n", dwp_file->name);
9697       fprintf_unfiltered (gdb_stdlog,
9698                           "    %s CUs, %s TUs\n",
9699                           pulongest (dwp_file->cus ? dwp_file->cus->nr_units : 0),
9700                           pulongest (dwp_file->tus ? dwp_file->tus->nr_units : 0));
9701     }
9702
9703   return dwp_file;
9704 }
9705
9706 /* Wrapper around open_and_init_dwp_file, only open it once.  */
9707
9708 static struct dwp_file *
9709 get_dwp_file (void)
9710 {
9711   if (! dwarf2_per_objfile->dwp_checked)
9712     {
9713       dwarf2_per_objfile->dwp_file = open_and_init_dwp_file ();
9714       dwarf2_per_objfile->dwp_checked = 1;
9715     }
9716   return dwarf2_per_objfile->dwp_file;
9717 }
9718
9719 /* Subroutine of lookup_dwo_comp_unit, lookup_dwo_type_unit.
9720    Look up the CU/TU with signature SIGNATURE, either in DWO file DWO_NAME
9721    or in the DWP file for the objfile, referenced by THIS_UNIT.
9722    If non-NULL, comp_dir is the DW_AT_comp_dir attribute.
9723    IS_DEBUG_TYPES is non-zero if reading a TU, otherwise read a CU.
9724
9725    This is called, for example, when wanting to read a variable with a
9726    complex location.  Therefore we don't want to do file i/o for every call.
9727    Therefore we don't want to look for a DWO file on every call.
9728    Therefore we first see if we've already seen SIGNATURE in a DWP file,
9729    then we check if we've already seen DWO_NAME, and only THEN do we check
9730    for a DWO file.
9731
9732    The result is a pointer to the dwo_unit object or NULL if we didn't find it
9733    (dwo_id mismatch or couldn't find the DWO/DWP file).  */
9734
9735 static struct dwo_unit *
9736 lookup_dwo_cutu (struct dwarf2_per_cu_data *this_unit,
9737                  const char *dwo_name, const char *comp_dir,
9738                  ULONGEST signature, int is_debug_types)
9739 {
9740   struct objfile *objfile = dwarf2_per_objfile->objfile;
9741   const char *kind = is_debug_types ? "TU" : "CU";
9742   void **dwo_file_slot;
9743   struct dwo_file *dwo_file;
9744   struct dwp_file *dwp_file;
9745
9746   /* First see if there's a DWP file.
9747      If we have a DWP file but didn't find the DWO inside it, don't
9748      look for the original DWO file.  It makes gdb behave differently
9749      depending on whether one is debugging in the build tree.  */
9750
9751   dwp_file = get_dwp_file ();
9752   if (dwp_file != NULL)
9753     {
9754       const struct dwp_hash_table *dwp_htab =
9755         is_debug_types ? dwp_file->tus : dwp_file->cus;
9756
9757       if (dwp_htab != NULL)
9758         {
9759           struct dwo_unit *dwo_cutu =
9760             lookup_dwo_in_dwp (dwp_file, dwp_htab, comp_dir,
9761                                signature, is_debug_types);
9762
9763           if (dwo_cutu != NULL)
9764             {
9765               if (dwarf2_read_debug)
9766                 {
9767                   fprintf_unfiltered (gdb_stdlog,
9768                                       "Virtual DWO %s %s found: @%s\n",
9769                                       kind, hex_string (signature),
9770                                       host_address_to_string (dwo_cutu));
9771                 }
9772               return dwo_cutu;
9773             }
9774         }
9775     }
9776   else
9777     {
9778       /* No DWP file, look for the DWO file.  */
9779
9780       dwo_file_slot = lookup_dwo_file_slot (dwo_name, comp_dir);
9781       if (*dwo_file_slot == NULL)
9782         {
9783           /* Read in the file and build a table of the CUs/TUs it contains.  */
9784           *dwo_file_slot = open_and_init_dwo_file (this_unit, dwo_name, comp_dir);
9785         }
9786       /* NOTE: This will be NULL if unable to open the file.  */
9787       dwo_file = *dwo_file_slot;
9788
9789       if (dwo_file != NULL)
9790         {
9791           struct dwo_unit *dwo_cutu = NULL;
9792
9793           if (is_debug_types && dwo_file->tus)
9794             {
9795               struct dwo_unit find_dwo_cutu;
9796
9797               memset (&find_dwo_cutu, 0, sizeof (find_dwo_cutu));
9798               find_dwo_cutu.signature = signature;
9799               dwo_cutu = htab_find (dwo_file->tus, &find_dwo_cutu);
9800             }
9801           else if (!is_debug_types && dwo_file->cu)
9802             {
9803               if (signature == dwo_file->cu->signature)
9804                 dwo_cutu = dwo_file->cu;
9805             }
9806
9807           if (dwo_cutu != NULL)
9808             {
9809               if (dwarf2_read_debug)
9810                 {
9811                   fprintf_unfiltered (gdb_stdlog, "DWO %s %s(%s) found: @%s\n",
9812                                       kind, dwo_name, hex_string (signature),
9813                                       host_address_to_string (dwo_cutu));
9814                 }
9815               return dwo_cutu;
9816             }
9817         }
9818     }
9819
9820   /* We didn't find it.  This could mean a dwo_id mismatch, or
9821      someone deleted the DWO/DWP file, or the search path isn't set up
9822      correctly to find the file.  */
9823
9824   if (dwarf2_read_debug)
9825     {
9826       fprintf_unfiltered (gdb_stdlog, "DWO %s %s(%s) not found\n",
9827                           kind, dwo_name, hex_string (signature));
9828     }
9829
9830   /* This is a warning and not a complaint because it can be caused by
9831      pilot error (e.g., user accidentally deleting the DWO).  */
9832   warning (_("Could not find DWO %s %s(%s) referenced by %s at offset 0x%x"
9833              " [in module %s]"),
9834            kind, dwo_name, hex_string (signature),
9835            this_unit->is_debug_types ? "TU" : "CU",
9836            this_unit->offset.sect_off, objfile->name);
9837   return NULL;
9838 }
9839
9840 /* Lookup the DWO CU DWO_NAME/SIGNATURE referenced from THIS_CU.
9841    See lookup_dwo_cutu_unit for details.  */
9842
9843 static struct dwo_unit *
9844 lookup_dwo_comp_unit (struct dwarf2_per_cu_data *this_cu,
9845                       const char *dwo_name, const char *comp_dir,
9846                       ULONGEST signature)
9847 {
9848   return lookup_dwo_cutu (this_cu, dwo_name, comp_dir, signature, 0);
9849 }
9850
9851 /* Lookup the DWO TU DWO_NAME/SIGNATURE referenced from THIS_TU.
9852    See lookup_dwo_cutu_unit for details.  */
9853
9854 static struct dwo_unit *
9855 lookup_dwo_type_unit (struct signatured_type *this_tu,
9856                       const char *dwo_name, const char *comp_dir)
9857 {
9858   return lookup_dwo_cutu (&this_tu->per_cu, dwo_name, comp_dir, this_tu->signature, 1);
9859 }
9860
9861 /* Free all resources associated with DWO_FILE.
9862    Close the DWO file and munmap the sections.
9863    All memory should be on the objfile obstack.  */
9864
9865 static void
9866 free_dwo_file (struct dwo_file *dwo_file, struct objfile *objfile)
9867 {
9868   int ix;
9869   struct dwarf2_section_info *section;
9870
9871   /* Note: dbfd is NULL for virtual DWO files.  */
9872   gdb_bfd_unref (dwo_file->dbfd);
9873
9874   VEC_free (dwarf2_section_info_def, dwo_file->sections.types);
9875 }
9876
9877 /* Wrapper for free_dwo_file for use in cleanups.  */
9878
9879 static void
9880 free_dwo_file_cleanup (void *arg)
9881 {
9882   struct dwo_file *dwo_file = (struct dwo_file *) arg;
9883   struct objfile *objfile = dwarf2_per_objfile->objfile;
9884
9885   free_dwo_file (dwo_file, objfile);
9886 }
9887
9888 /* Traversal function for free_dwo_files.  */
9889
9890 static int
9891 free_dwo_file_from_slot (void **slot, void *info)
9892 {
9893   struct dwo_file *dwo_file = (struct dwo_file *) *slot;
9894   struct objfile *objfile = (struct objfile *) info;
9895
9896   free_dwo_file (dwo_file, objfile);
9897
9898   return 1;
9899 }
9900
9901 /* Free all resources associated with DWO_FILES.  */
9902
9903 static void
9904 free_dwo_files (htab_t dwo_files, struct objfile *objfile)
9905 {
9906   htab_traverse_noresize (dwo_files, free_dwo_file_from_slot, objfile);
9907 }
9908 \f
9909 /* Read in various DIEs.  */
9910
9911 /* qsort helper for inherit_abstract_dies.  */
9912
9913 static int
9914 unsigned_int_compar (const void *ap, const void *bp)
9915 {
9916   unsigned int a = *(unsigned int *) ap;
9917   unsigned int b = *(unsigned int *) bp;
9918
9919   return (a > b) - (b > a);
9920 }
9921
9922 /* DW_AT_abstract_origin inherits whole DIEs (not just their attributes).
9923    Inherit only the children of the DW_AT_abstract_origin DIE not being
9924    already referenced by DW_AT_abstract_origin from the children of the
9925    current DIE.  */
9926
9927 static void
9928 inherit_abstract_dies (struct die_info *die, struct dwarf2_cu *cu)
9929 {
9930   struct die_info *child_die;
9931   unsigned die_children_count;
9932   /* CU offsets which were referenced by children of the current DIE.  */
9933   sect_offset *offsets;
9934   sect_offset *offsets_end, *offsetp;
9935   /* Parent of DIE - referenced by DW_AT_abstract_origin.  */
9936   struct die_info *origin_die;
9937   /* Iterator of the ORIGIN_DIE children.  */
9938   struct die_info *origin_child_die;
9939   struct cleanup *cleanups;
9940   struct attribute *attr;
9941   struct dwarf2_cu *origin_cu;
9942   struct pending **origin_previous_list_in_scope;
9943
9944   attr = dwarf2_attr (die, DW_AT_abstract_origin, cu);
9945   if (!attr)
9946     return;
9947
9948   /* Note that following die references may follow to a die in a
9949      different cu.  */
9950
9951   origin_cu = cu;
9952   origin_die = follow_die_ref (die, attr, &origin_cu);
9953
9954   /* We're inheriting ORIGIN's children into the scope we'd put DIE's
9955      symbols in.  */
9956   origin_previous_list_in_scope = origin_cu->list_in_scope;
9957   origin_cu->list_in_scope = cu->list_in_scope;
9958
9959   if (die->tag != origin_die->tag
9960       && !(die->tag == DW_TAG_inlined_subroutine
9961            && origin_die->tag == DW_TAG_subprogram))
9962     complaint (&symfile_complaints,
9963                _("DIE 0x%x and its abstract origin 0x%x have different tags"),
9964                die->offset.sect_off, origin_die->offset.sect_off);
9965
9966   child_die = die->child;
9967   die_children_count = 0;
9968   while (child_die && child_die->tag)
9969     {
9970       child_die = sibling_die (child_die);
9971       die_children_count++;
9972     }
9973   offsets = xmalloc (sizeof (*offsets) * die_children_count);
9974   cleanups = make_cleanup (xfree, offsets);
9975
9976   offsets_end = offsets;
9977   child_die = die->child;
9978   while (child_die && child_die->tag)
9979     {
9980       /* For each CHILD_DIE, find the corresponding child of
9981          ORIGIN_DIE.  If there is more than one layer of
9982          DW_AT_abstract_origin, follow them all; there shouldn't be,
9983          but GCC versions at least through 4.4 generate this (GCC PR
9984          40573).  */
9985       struct die_info *child_origin_die = child_die;
9986       struct dwarf2_cu *child_origin_cu = cu;
9987
9988       while (1)
9989         {
9990           attr = dwarf2_attr (child_origin_die, DW_AT_abstract_origin,
9991                               child_origin_cu);
9992           if (attr == NULL)
9993             break;
9994           child_origin_die = follow_die_ref (child_origin_die, attr,
9995                                              &child_origin_cu);
9996         }
9997
9998       /* According to DWARF3 3.3.8.2 #3 new entries without their abstract
9999          counterpart may exist.  */
10000       if (child_origin_die != child_die)
10001         {
10002           if (child_die->tag != child_origin_die->tag
10003               && !(child_die->tag == DW_TAG_inlined_subroutine
10004                    && child_origin_die->tag == DW_TAG_subprogram))
10005             complaint (&symfile_complaints,
10006                        _("Child DIE 0x%x and its abstract origin 0x%x have "
10007                          "different tags"), child_die->offset.sect_off,
10008                        child_origin_die->offset.sect_off);
10009           if (child_origin_die->parent != origin_die)
10010             complaint (&symfile_complaints,
10011                        _("Child DIE 0x%x and its abstract origin 0x%x have "
10012                          "different parents"), child_die->offset.sect_off,
10013                        child_origin_die->offset.sect_off);
10014           else
10015             *offsets_end++ = child_origin_die->offset;
10016         }
10017       child_die = sibling_die (child_die);
10018     }
10019   qsort (offsets, offsets_end - offsets, sizeof (*offsets),
10020          unsigned_int_compar);
10021   for (offsetp = offsets + 1; offsetp < offsets_end; offsetp++)
10022     if (offsetp[-1].sect_off == offsetp->sect_off)
10023       complaint (&symfile_complaints,
10024                  _("Multiple children of DIE 0x%x refer "
10025                    "to DIE 0x%x as their abstract origin"),
10026                  die->offset.sect_off, offsetp->sect_off);
10027
10028   offsetp = offsets;
10029   origin_child_die = origin_die->child;
10030   while (origin_child_die && origin_child_die->tag)
10031     {
10032       /* Is ORIGIN_CHILD_DIE referenced by any of the DIE children?  */
10033       while (offsetp < offsets_end
10034              && offsetp->sect_off < origin_child_die->offset.sect_off)
10035         offsetp++;
10036       if (offsetp >= offsets_end
10037           || offsetp->sect_off > origin_child_die->offset.sect_off)
10038         {
10039           /* Found that ORIGIN_CHILD_DIE is really not referenced.  */
10040           process_die (origin_child_die, origin_cu);
10041         }
10042       origin_child_die = sibling_die (origin_child_die);
10043     }
10044   origin_cu->list_in_scope = origin_previous_list_in_scope;
10045
10046   do_cleanups (cleanups);
10047 }
10048
10049 static void
10050 read_func_scope (struct die_info *die, struct dwarf2_cu *cu)
10051 {
10052   struct objfile *objfile = cu->objfile;
10053   struct context_stack *new;
10054   CORE_ADDR lowpc;
10055   CORE_ADDR highpc;
10056   struct die_info *child_die;
10057   struct attribute *attr, *call_line, *call_file;
10058   const char *name;
10059   CORE_ADDR baseaddr;
10060   struct block *block;
10061   int inlined_func = (die->tag == DW_TAG_inlined_subroutine);
10062   VEC (symbolp) *template_args = NULL;
10063   struct template_symbol *templ_func = NULL;
10064
10065   if (inlined_func)
10066     {
10067       /* If we do not have call site information, we can't show the
10068          caller of this inlined function.  That's too confusing, so
10069          only use the scope for local variables.  */
10070       call_line = dwarf2_attr (die, DW_AT_call_line, cu);
10071       call_file = dwarf2_attr (die, DW_AT_call_file, cu);
10072       if (call_line == NULL || call_file == NULL)
10073         {
10074           read_lexical_block_scope (die, cu);
10075           return;
10076         }
10077     }
10078
10079   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
10080
10081   name = dwarf2_name (die, cu);
10082
10083   /* Ignore functions with missing or empty names.  These are actually
10084      illegal according to the DWARF standard.  */
10085   if (name == NULL)
10086     {
10087       complaint (&symfile_complaints,
10088                  _("missing name for subprogram DIE at %d"),
10089                  die->offset.sect_off);
10090       return;
10091     }
10092
10093   /* Ignore functions with missing or invalid low and high pc attributes.  */
10094   if (!dwarf2_get_pc_bounds (die, &lowpc, &highpc, cu, NULL))
10095     {
10096       attr = dwarf2_attr (die, DW_AT_external, cu);
10097       if (!attr || !DW_UNSND (attr))
10098         complaint (&symfile_complaints,
10099                    _("cannot get low and high bounds "
10100                      "for subprogram DIE at %d"),
10101                    die->offset.sect_off);
10102       return;
10103     }
10104
10105   lowpc += baseaddr;
10106   highpc += baseaddr;
10107
10108   /* If we have any template arguments, then we must allocate a
10109      different sort of symbol.  */
10110   for (child_die = die->child; child_die; child_die = sibling_die (child_die))
10111     {
10112       if (child_die->tag == DW_TAG_template_type_param
10113           || child_die->tag == DW_TAG_template_value_param)
10114         {
10115           templ_func = allocate_template_symbol (objfile);
10116           templ_func->base.is_cplus_template_function = 1;
10117           break;
10118         }
10119     }
10120
10121   new = push_context (0, lowpc);
10122   new->name = new_symbol_full (die, read_type_die (die, cu), cu,
10123                                (struct symbol *) templ_func);
10124
10125   /* If there is a location expression for DW_AT_frame_base, record
10126      it.  */
10127   attr = dwarf2_attr (die, DW_AT_frame_base, cu);
10128   if (attr)
10129     dwarf2_symbol_mark_computed (attr, new->name, cu, 1);
10130
10131   cu->list_in_scope = &local_symbols;
10132
10133   if (die->child != NULL)
10134     {
10135       child_die = die->child;
10136       while (child_die && child_die->tag)
10137         {
10138           if (child_die->tag == DW_TAG_template_type_param
10139               || child_die->tag == DW_TAG_template_value_param)
10140             {
10141               struct symbol *arg = new_symbol (child_die, NULL, cu);
10142
10143               if (arg != NULL)
10144                 VEC_safe_push (symbolp, template_args, arg);
10145             }
10146           else
10147             process_die (child_die, cu);
10148           child_die = sibling_die (child_die);
10149         }
10150     }
10151
10152   inherit_abstract_dies (die, cu);
10153
10154   /* If we have a DW_AT_specification, we might need to import using
10155      directives from the context of the specification DIE.  See the
10156      comment in determine_prefix.  */
10157   if (cu->language == language_cplus
10158       && dwarf2_attr (die, DW_AT_specification, cu))
10159     {
10160       struct dwarf2_cu *spec_cu = cu;
10161       struct die_info *spec_die = die_specification (die, &spec_cu);
10162
10163       while (spec_die)
10164         {
10165           child_die = spec_die->child;
10166           while (child_die && child_die->tag)
10167             {
10168               if (child_die->tag == DW_TAG_imported_module)
10169                 process_die (child_die, spec_cu);
10170               child_die = sibling_die (child_die);
10171             }
10172
10173           /* In some cases, GCC generates specification DIEs that
10174              themselves contain DW_AT_specification attributes.  */
10175           spec_die = die_specification (spec_die, &spec_cu);
10176         }
10177     }
10178
10179   new = pop_context ();
10180   /* Make a block for the local symbols within.  */
10181   block = finish_block (new->name, &local_symbols, new->old_blocks,
10182                         lowpc, highpc, objfile);
10183
10184   /* For C++, set the block's scope.  */
10185   if ((cu->language == language_cplus || cu->language == language_fortran)
10186       && cu->processing_has_namespace_info)
10187     block_set_scope (block, determine_prefix (die, cu),
10188                      &objfile->objfile_obstack);
10189
10190   /* If we have address ranges, record them.  */
10191   dwarf2_record_block_ranges (die, block, baseaddr, cu);
10192
10193   /* Attach template arguments to function.  */
10194   if (! VEC_empty (symbolp, template_args))
10195     {
10196       gdb_assert (templ_func != NULL);
10197
10198       templ_func->n_template_arguments = VEC_length (symbolp, template_args);
10199       templ_func->template_arguments
10200         = obstack_alloc (&objfile->objfile_obstack,
10201                          (templ_func->n_template_arguments
10202                           * sizeof (struct symbol *)));
10203       memcpy (templ_func->template_arguments,
10204               VEC_address (symbolp, template_args),
10205               (templ_func->n_template_arguments * sizeof (struct symbol *)));
10206       VEC_free (symbolp, template_args);
10207     }
10208
10209   /* In C++, we can have functions nested inside functions (e.g., when
10210      a function declares a class that has methods).  This means that
10211      when we finish processing a function scope, we may need to go
10212      back to building a containing block's symbol lists.  */
10213   local_symbols = new->locals;
10214   using_directives = new->using_directives;
10215
10216   /* If we've finished processing a top-level function, subsequent
10217      symbols go in the file symbol list.  */
10218   if (outermost_context_p ())
10219     cu->list_in_scope = &file_symbols;
10220 }
10221
10222 /* Process all the DIES contained within a lexical block scope.  Start
10223    a new scope, process the dies, and then close the scope.  */
10224
10225 static void
10226 read_lexical_block_scope (struct die_info *die, struct dwarf2_cu *cu)
10227 {
10228   struct objfile *objfile = cu->objfile;
10229   struct context_stack *new;
10230   CORE_ADDR lowpc, highpc;
10231   struct die_info *child_die;
10232   CORE_ADDR baseaddr;
10233
10234   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
10235
10236   /* Ignore blocks with missing or invalid low and high pc attributes.  */
10237   /* ??? Perhaps consider discontiguous blocks defined by DW_AT_ranges
10238      as multiple lexical blocks?  Handling children in a sane way would
10239      be nasty.  Might be easier to properly extend generic blocks to
10240      describe ranges.  */
10241   if (!dwarf2_get_pc_bounds (die, &lowpc, &highpc, cu, NULL))
10242     return;
10243   lowpc += baseaddr;
10244   highpc += baseaddr;
10245
10246   push_context (0, lowpc);
10247   if (die->child != NULL)
10248     {
10249       child_die = die->child;
10250       while (child_die && child_die->tag)
10251         {
10252           process_die (child_die, cu);
10253           child_die = sibling_die (child_die);
10254         }
10255     }
10256   new = pop_context ();
10257
10258   if (local_symbols != NULL || using_directives != NULL)
10259     {
10260       struct block *block
10261         = finish_block (0, &local_symbols, new->old_blocks, new->start_addr,
10262                         highpc, objfile);
10263
10264       /* Note that recording ranges after traversing children, as we
10265          do here, means that recording a parent's ranges entails
10266          walking across all its children's ranges as they appear in
10267          the address map, which is quadratic behavior.
10268
10269          It would be nicer to record the parent's ranges before
10270          traversing its children, simply overriding whatever you find
10271          there.  But since we don't even decide whether to create a
10272          block until after we've traversed its children, that's hard
10273          to do.  */
10274       dwarf2_record_block_ranges (die, block, baseaddr, cu);
10275     }
10276   local_symbols = new->locals;
10277   using_directives = new->using_directives;
10278 }
10279
10280 /* Read in DW_TAG_GNU_call_site and insert it to CU->call_site_htab.  */
10281
10282 static void
10283 read_call_site_scope (struct die_info *die, struct dwarf2_cu *cu)
10284 {
10285   struct objfile *objfile = cu->objfile;
10286   struct gdbarch *gdbarch = get_objfile_arch (objfile);
10287   CORE_ADDR pc, baseaddr;
10288   struct attribute *attr;
10289   struct call_site *call_site, call_site_local;
10290   void **slot;
10291   int nparams;
10292   struct die_info *child_die;
10293
10294   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
10295
10296   attr = dwarf2_attr (die, DW_AT_low_pc, cu);
10297   if (!attr)
10298     {
10299       complaint (&symfile_complaints,
10300                  _("missing DW_AT_low_pc for DW_TAG_GNU_call_site "
10301                    "DIE 0x%x [in module %s]"),
10302                  die->offset.sect_off, objfile->name);
10303       return;
10304     }
10305   pc = DW_ADDR (attr) + baseaddr;
10306
10307   if (cu->call_site_htab == NULL)
10308     cu->call_site_htab = htab_create_alloc_ex (16, core_addr_hash, core_addr_eq,
10309                                                NULL, &objfile->objfile_obstack,
10310                                                hashtab_obstack_allocate, NULL);
10311   call_site_local.pc = pc;
10312   slot = htab_find_slot (cu->call_site_htab, &call_site_local, INSERT);
10313   if (*slot != NULL)
10314     {
10315       complaint (&symfile_complaints,
10316                  _("Duplicate PC %s for DW_TAG_GNU_call_site "
10317                    "DIE 0x%x [in module %s]"),
10318                  paddress (gdbarch, pc), die->offset.sect_off, objfile->name);
10319       return;
10320     }
10321
10322   /* Count parameters at the caller.  */
10323
10324   nparams = 0;
10325   for (child_die = die->child; child_die && child_die->tag;
10326        child_die = sibling_die (child_die))
10327     {
10328       if (child_die->tag != DW_TAG_GNU_call_site_parameter)
10329         {
10330           complaint (&symfile_complaints,
10331                      _("Tag %d is not DW_TAG_GNU_call_site_parameter in "
10332                        "DW_TAG_GNU_call_site child DIE 0x%x [in module %s]"),
10333                      child_die->tag, child_die->offset.sect_off, objfile->name);
10334           continue;
10335         }
10336
10337       nparams++;
10338     }
10339
10340   call_site = obstack_alloc (&objfile->objfile_obstack,
10341                              (sizeof (*call_site)
10342                               + (sizeof (*call_site->parameter)
10343                                  * (nparams - 1))));
10344   *slot = call_site;
10345   memset (call_site, 0, sizeof (*call_site) - sizeof (*call_site->parameter));
10346   call_site->pc = pc;
10347
10348   if (dwarf2_flag_true_p (die, DW_AT_GNU_tail_call, cu))
10349     {
10350       struct die_info *func_die;
10351
10352       /* Skip also over DW_TAG_inlined_subroutine.  */
10353       for (func_die = die->parent;
10354            func_die && func_die->tag != DW_TAG_subprogram
10355            && func_die->tag != DW_TAG_subroutine_type;
10356            func_die = func_die->parent);
10357
10358       /* DW_AT_GNU_all_call_sites is a superset
10359          of DW_AT_GNU_all_tail_call_sites.  */
10360       if (func_die
10361           && !dwarf2_flag_true_p (func_die, DW_AT_GNU_all_call_sites, cu)
10362           && !dwarf2_flag_true_p (func_die, DW_AT_GNU_all_tail_call_sites, cu))
10363         {
10364           /* TYPE_TAIL_CALL_LIST is not interesting in functions where it is
10365              not complete.  But keep CALL_SITE for look ups via call_site_htab,
10366              both the initial caller containing the real return address PC and
10367              the final callee containing the current PC of a chain of tail
10368              calls do not need to have the tail call list complete.  But any
10369              function candidate for a virtual tail call frame searched via
10370              TYPE_TAIL_CALL_LIST must have the tail call list complete to be
10371              determined unambiguously.  */
10372         }
10373       else
10374         {
10375           struct type *func_type = NULL;
10376
10377           if (func_die)
10378             func_type = get_die_type (func_die, cu);
10379           if (func_type != NULL)
10380             {
10381               gdb_assert (TYPE_CODE (func_type) == TYPE_CODE_FUNC);
10382
10383               /* Enlist this call site to the function.  */
10384               call_site->tail_call_next = TYPE_TAIL_CALL_LIST (func_type);
10385               TYPE_TAIL_CALL_LIST (func_type) = call_site;
10386             }
10387           else
10388             complaint (&symfile_complaints,
10389                        _("Cannot find function owning DW_TAG_GNU_call_site "
10390                          "DIE 0x%x [in module %s]"),
10391                        die->offset.sect_off, objfile->name);
10392         }
10393     }
10394
10395   attr = dwarf2_attr (die, DW_AT_GNU_call_site_target, cu);
10396   if (attr == NULL)
10397     attr = dwarf2_attr (die, DW_AT_abstract_origin, cu);
10398   SET_FIELD_DWARF_BLOCK (call_site->target, NULL);
10399   if (!attr || (attr_form_is_block (attr) && DW_BLOCK (attr)->size == 0))
10400     /* Keep NULL DWARF_BLOCK.  */;
10401   else if (attr_form_is_block (attr))
10402     {
10403       struct dwarf2_locexpr_baton *dlbaton;
10404
10405       dlbaton = obstack_alloc (&objfile->objfile_obstack, sizeof (*dlbaton));
10406       dlbaton->data = DW_BLOCK (attr)->data;
10407       dlbaton->size = DW_BLOCK (attr)->size;
10408       dlbaton->per_cu = cu->per_cu;
10409
10410       SET_FIELD_DWARF_BLOCK (call_site->target, dlbaton);
10411     }
10412   else if (attr_form_is_ref (attr))
10413     {
10414       struct dwarf2_cu *target_cu = cu;
10415       struct die_info *target_die;
10416
10417       target_die = follow_die_ref (die, attr, &target_cu);
10418       gdb_assert (target_cu->objfile == objfile);
10419       if (die_is_declaration (target_die, target_cu))
10420         {
10421           const char *target_physname = NULL;
10422           struct attribute *target_attr;
10423
10424           /* Prefer the mangled name; otherwise compute the demangled one.  */
10425           target_attr = dwarf2_attr (target_die, DW_AT_linkage_name, target_cu);
10426           if (target_attr == NULL)
10427             target_attr = dwarf2_attr (target_die, DW_AT_MIPS_linkage_name,
10428                                        target_cu);
10429           if (target_attr != NULL && DW_STRING (target_attr) != NULL)
10430             target_physname = DW_STRING (target_attr);
10431           else
10432             target_physname = dwarf2_physname (NULL, target_die, target_cu);
10433           if (target_physname == NULL)
10434             complaint (&symfile_complaints,
10435                        _("DW_AT_GNU_call_site_target target DIE has invalid "
10436                          "physname, for referencing DIE 0x%x [in module %s]"),
10437                        die->offset.sect_off, objfile->name);
10438           else
10439             SET_FIELD_PHYSNAME (call_site->target, target_physname);
10440         }
10441       else
10442         {
10443           CORE_ADDR lowpc;
10444
10445           /* DW_AT_entry_pc should be preferred.  */
10446           if (!dwarf2_get_pc_bounds (target_die, &lowpc, NULL, target_cu, NULL))
10447             complaint (&symfile_complaints,
10448                        _("DW_AT_GNU_call_site_target target DIE has invalid "
10449                          "low pc, for referencing DIE 0x%x [in module %s]"),
10450                        die->offset.sect_off, objfile->name);
10451           else
10452             SET_FIELD_PHYSADDR (call_site->target, lowpc + baseaddr);
10453         }
10454     }
10455   else
10456     complaint (&symfile_complaints,
10457                _("DW_TAG_GNU_call_site DW_AT_GNU_call_site_target is neither "
10458                  "block nor reference, for DIE 0x%x [in module %s]"),
10459                die->offset.sect_off, objfile->name);
10460
10461   call_site->per_cu = cu->per_cu;
10462
10463   for (child_die = die->child;
10464        child_die && child_die->tag;
10465        child_die = sibling_die (child_die))
10466     {
10467       struct call_site_parameter *parameter;
10468       struct attribute *loc, *origin;
10469
10470       if (child_die->tag != DW_TAG_GNU_call_site_parameter)
10471         {
10472           /* Already printed the complaint above.  */
10473           continue;
10474         }
10475
10476       gdb_assert (call_site->parameter_count < nparams);
10477       parameter = &call_site->parameter[call_site->parameter_count];
10478
10479       /* DW_AT_location specifies the register number or DW_AT_abstract_origin
10480          specifies DW_TAG_formal_parameter.  Value of the data assumed for the
10481          register is contained in DW_AT_GNU_call_site_value.  */
10482
10483       loc = dwarf2_attr (child_die, DW_AT_location, cu);
10484       origin = dwarf2_attr (child_die, DW_AT_abstract_origin, cu);
10485       if (loc == NULL && origin != NULL && attr_form_is_ref (origin))
10486         {
10487           sect_offset offset;
10488
10489           parameter->kind = CALL_SITE_PARAMETER_PARAM_OFFSET;
10490           offset = dwarf2_get_ref_die_offset (origin);
10491           if (!offset_in_cu_p (&cu->header, offset))
10492             {
10493               /* As DW_OP_GNU_parameter_ref uses CU-relative offset this
10494                  binding can be done only inside one CU.  Such referenced DIE
10495                  therefore cannot be even moved to DW_TAG_partial_unit.  */
10496               complaint (&symfile_complaints,
10497                          _("DW_AT_abstract_origin offset is not in CU for "
10498                            "DW_TAG_GNU_call_site child DIE 0x%x "
10499                            "[in module %s]"),
10500                          child_die->offset.sect_off, objfile->name);
10501               continue;
10502             }
10503           parameter->u.param_offset.cu_off = (offset.sect_off
10504                                               - cu->header.offset.sect_off);
10505         }
10506       else if (loc == NULL || origin != NULL || !attr_form_is_block (loc))
10507         {
10508           complaint (&symfile_complaints,
10509                      _("No DW_FORM_block* DW_AT_location for "
10510                        "DW_TAG_GNU_call_site child DIE 0x%x [in module %s]"),
10511                      child_die->offset.sect_off, objfile->name);
10512           continue;
10513         }
10514       else
10515         {
10516           parameter->u.dwarf_reg = dwarf_block_to_dwarf_reg
10517             (DW_BLOCK (loc)->data, &DW_BLOCK (loc)->data[DW_BLOCK (loc)->size]);
10518           if (parameter->u.dwarf_reg != -1)
10519             parameter->kind = CALL_SITE_PARAMETER_DWARF_REG;
10520           else if (dwarf_block_to_sp_offset (gdbarch, DW_BLOCK (loc)->data,
10521                                     &DW_BLOCK (loc)->data[DW_BLOCK (loc)->size],
10522                                              &parameter->u.fb_offset))
10523             parameter->kind = CALL_SITE_PARAMETER_FB_OFFSET;
10524           else
10525             {
10526               complaint (&symfile_complaints,
10527                          _("Only single DW_OP_reg or DW_OP_fbreg is supported "
10528                            "for DW_FORM_block* DW_AT_location is supported for "
10529                            "DW_TAG_GNU_call_site child DIE 0x%x "
10530                            "[in module %s]"),
10531                          child_die->offset.sect_off, objfile->name);
10532               continue;
10533             }
10534         }
10535
10536       attr = dwarf2_attr (child_die, DW_AT_GNU_call_site_value, cu);
10537       if (!attr_form_is_block (attr))
10538         {
10539           complaint (&symfile_complaints,
10540                      _("No DW_FORM_block* DW_AT_GNU_call_site_value for "
10541                        "DW_TAG_GNU_call_site child DIE 0x%x [in module %s]"),
10542                      child_die->offset.sect_off, objfile->name);
10543           continue;
10544         }
10545       parameter->value = DW_BLOCK (attr)->data;
10546       parameter->value_size = DW_BLOCK (attr)->size;
10547
10548       /* Parameters are not pre-cleared by memset above.  */
10549       parameter->data_value = NULL;
10550       parameter->data_value_size = 0;
10551       call_site->parameter_count++;
10552
10553       attr = dwarf2_attr (child_die, DW_AT_GNU_call_site_data_value, cu);
10554       if (attr)
10555         {
10556           if (!attr_form_is_block (attr))
10557             complaint (&symfile_complaints,
10558                        _("No DW_FORM_block* DW_AT_GNU_call_site_data_value for "
10559                          "DW_TAG_GNU_call_site child DIE 0x%x [in module %s]"),
10560                        child_die->offset.sect_off, objfile->name);
10561           else
10562             {
10563               parameter->data_value = DW_BLOCK (attr)->data;
10564               parameter->data_value_size = DW_BLOCK (attr)->size;
10565             }
10566         }
10567     }
10568 }
10569
10570 /* Get low and high pc attributes from DW_AT_ranges attribute value OFFSET.
10571    Return 1 if the attributes are present and valid, otherwise, return 0.
10572    If RANGES_PST is not NULL we should setup `objfile->psymtabs_addrmap'.  */
10573
10574 static int
10575 dwarf2_ranges_read (unsigned offset, CORE_ADDR *low_return,
10576                     CORE_ADDR *high_return, struct dwarf2_cu *cu,
10577                     struct partial_symtab *ranges_pst)
10578 {
10579   struct objfile *objfile = cu->objfile;
10580   struct comp_unit_head *cu_header = &cu->header;
10581   bfd *obfd = objfile->obfd;
10582   unsigned int addr_size = cu_header->addr_size;
10583   CORE_ADDR mask = ~(~(CORE_ADDR)1 << (addr_size * 8 - 1));
10584   /* Base address selection entry.  */
10585   CORE_ADDR base;
10586   int found_base;
10587   unsigned int dummy;
10588   const gdb_byte *buffer;
10589   CORE_ADDR marker;
10590   int low_set;
10591   CORE_ADDR low = 0;
10592   CORE_ADDR high = 0;
10593   CORE_ADDR baseaddr;
10594
10595   found_base = cu->base_known;
10596   base = cu->base_address;
10597
10598   dwarf2_read_section (objfile, &dwarf2_per_objfile->ranges);
10599   if (offset >= dwarf2_per_objfile->ranges.size)
10600     {
10601       complaint (&symfile_complaints,
10602                  _("Offset %d out of bounds for DW_AT_ranges attribute"),
10603                  offset);
10604       return 0;
10605     }
10606   buffer = dwarf2_per_objfile->ranges.buffer + offset;
10607
10608   /* Read in the largest possible address.  */
10609   marker = read_address (obfd, buffer, cu, &dummy);
10610   if ((marker & mask) == mask)
10611     {
10612       /* If we found the largest possible address, then
10613          read the base address.  */
10614       base = read_address (obfd, buffer + addr_size, cu, &dummy);
10615       buffer += 2 * addr_size;
10616       offset += 2 * addr_size;
10617       found_base = 1;
10618     }
10619
10620   low_set = 0;
10621
10622   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
10623
10624   while (1)
10625     {
10626       CORE_ADDR range_beginning, range_end;
10627
10628       range_beginning = read_address (obfd, buffer, cu, &dummy);
10629       buffer += addr_size;
10630       range_end = read_address (obfd, buffer, cu, &dummy);
10631       buffer += addr_size;
10632       offset += 2 * addr_size;
10633
10634       /* An end of list marker is a pair of zero addresses.  */
10635       if (range_beginning == 0 && range_end == 0)
10636         /* Found the end of list entry.  */
10637         break;
10638
10639       /* Each base address selection entry is a pair of 2 values.
10640          The first is the largest possible address, the second is
10641          the base address.  Check for a base address here.  */
10642       if ((range_beginning & mask) == mask)
10643         {
10644           /* If we found the largest possible address, then
10645              read the base address.  */
10646           base = read_address (obfd, buffer + addr_size, cu, &dummy);
10647           found_base = 1;
10648           continue;
10649         }
10650
10651       if (!found_base)
10652         {
10653           /* We have no valid base address for the ranges
10654              data.  */
10655           complaint (&symfile_complaints,
10656                      _("Invalid .debug_ranges data (no base address)"));
10657           return 0;
10658         }
10659
10660       if (range_beginning > range_end)
10661         {
10662           /* Inverted range entries are invalid.  */
10663           complaint (&symfile_complaints,
10664                      _("Invalid .debug_ranges data (inverted range)"));
10665           return 0;
10666         }
10667
10668       /* Empty range entries have no effect.  */
10669       if (range_beginning == range_end)
10670         continue;
10671
10672       range_beginning += base;
10673       range_end += base;
10674
10675       /* A not-uncommon case of bad debug info.
10676          Don't pollute the addrmap with bad data.  */
10677       if (range_beginning + baseaddr == 0
10678           && !dwarf2_per_objfile->has_section_at_zero)
10679         {
10680           complaint (&symfile_complaints,
10681                      _(".debug_ranges entry has start address of zero"
10682                        " [in module %s]"), objfile->name);
10683           continue;
10684         }
10685
10686       if (ranges_pst != NULL)
10687         addrmap_set_empty (objfile->psymtabs_addrmap,
10688                            range_beginning + baseaddr,
10689                            range_end - 1 + baseaddr,
10690                            ranges_pst);
10691
10692       /* FIXME: This is recording everything as a low-high
10693          segment of consecutive addresses.  We should have a
10694          data structure for discontiguous block ranges
10695          instead.  */
10696       if (! low_set)
10697         {
10698           low = range_beginning;
10699           high = range_end;
10700           low_set = 1;
10701         }
10702       else
10703         {
10704           if (range_beginning < low)
10705             low = range_beginning;
10706           if (range_end > high)
10707             high = range_end;
10708         }
10709     }
10710
10711   if (! low_set)
10712     /* If the first entry is an end-of-list marker, the range
10713        describes an empty scope, i.e. no instructions.  */
10714     return 0;
10715
10716   if (low_return)
10717     *low_return = low;
10718   if (high_return)
10719     *high_return = high;
10720   return 1;
10721 }
10722
10723 /* Get low and high pc attributes from a die.  Return 1 if the attributes
10724    are present and valid, otherwise, return 0.  Return -1 if the range is
10725    discontinuous, i.e. derived from DW_AT_ranges information.  */
10726
10727 static int
10728 dwarf2_get_pc_bounds (struct die_info *die, CORE_ADDR *lowpc,
10729                       CORE_ADDR *highpc, struct dwarf2_cu *cu,
10730                       struct partial_symtab *pst)
10731 {
10732   struct attribute *attr;
10733   struct attribute *attr_high;
10734   CORE_ADDR low = 0;
10735   CORE_ADDR high = 0;
10736   int ret = 0;
10737
10738   attr_high = dwarf2_attr (die, DW_AT_high_pc, cu);
10739   if (attr_high)
10740     {
10741       attr = dwarf2_attr (die, DW_AT_low_pc, cu);
10742       if (attr)
10743         {
10744           low = DW_ADDR (attr);
10745           if (attr_high->form == DW_FORM_addr
10746               || attr_high->form == DW_FORM_GNU_addr_index)
10747             high = DW_ADDR (attr_high);
10748           else
10749             high = low + DW_UNSND (attr_high);
10750         }
10751       else
10752         /* Found high w/o low attribute.  */
10753         return 0;
10754
10755       /* Found consecutive range of addresses.  */
10756       ret = 1;
10757     }
10758   else
10759     {
10760       attr = dwarf2_attr (die, DW_AT_ranges, cu);
10761       if (attr != NULL)
10762         {
10763           /* DW_AT_ranges_base does not apply to DIEs from the DWO skeleton.
10764              We take advantage of the fact that DW_AT_ranges does not appear
10765              in DW_TAG_compile_unit of DWO files.  */
10766           int need_ranges_base = die->tag != DW_TAG_compile_unit;
10767           unsigned int ranges_offset = (DW_UNSND (attr)
10768                                         + (need_ranges_base
10769                                            ? cu->ranges_base
10770                                            : 0));
10771
10772           /* Value of the DW_AT_ranges attribute is the offset in the
10773              .debug_ranges section.  */
10774           if (!dwarf2_ranges_read (ranges_offset, &low, &high, cu, pst))
10775             return 0;
10776           /* Found discontinuous range of addresses.  */
10777           ret = -1;
10778         }
10779     }
10780
10781   /* read_partial_die has also the strict LOW < HIGH requirement.  */
10782   if (high <= low)
10783     return 0;
10784
10785   /* When using the GNU linker, .gnu.linkonce. sections are used to
10786      eliminate duplicate copies of functions and vtables and such.
10787      The linker will arbitrarily choose one and discard the others.
10788      The AT_*_pc values for such functions refer to local labels in
10789      these sections.  If the section from that file was discarded, the
10790      labels are not in the output, so the relocs get a value of 0.
10791      If this is a discarded function, mark the pc bounds as invalid,
10792      so that GDB will ignore it.  */
10793   if (low == 0 && !dwarf2_per_objfile->has_section_at_zero)
10794     return 0;
10795
10796   *lowpc = low;
10797   if (highpc)
10798     *highpc = high;
10799   return ret;
10800 }
10801
10802 /* Assuming that DIE represents a subprogram DIE or a lexical block, get
10803    its low and high PC addresses.  Do nothing if these addresses could not
10804    be determined.  Otherwise, set LOWPC to the low address if it is smaller,
10805    and HIGHPC to the high address if greater than HIGHPC.  */
10806
10807 static void
10808 dwarf2_get_subprogram_pc_bounds (struct die_info *die,
10809                                  CORE_ADDR *lowpc, CORE_ADDR *highpc,
10810                                  struct dwarf2_cu *cu)
10811 {
10812   CORE_ADDR low, high;
10813   struct die_info *child = die->child;
10814
10815   if (dwarf2_get_pc_bounds (die, &low, &high, cu, NULL))
10816     {
10817       *lowpc = min (*lowpc, low);
10818       *highpc = max (*highpc, high);
10819     }
10820
10821   /* If the language does not allow nested subprograms (either inside
10822      subprograms or lexical blocks), we're done.  */
10823   if (cu->language != language_ada)
10824     return;
10825
10826   /* Check all the children of the given DIE.  If it contains nested
10827      subprograms, then check their pc bounds.  Likewise, we need to
10828      check lexical blocks as well, as they may also contain subprogram
10829      definitions.  */
10830   while (child && child->tag)
10831     {
10832       if (child->tag == DW_TAG_subprogram
10833           || child->tag == DW_TAG_lexical_block)
10834         dwarf2_get_subprogram_pc_bounds (child, lowpc, highpc, cu);
10835       child = sibling_die (child);
10836     }
10837 }
10838
10839 /* Get the low and high pc's represented by the scope DIE, and store
10840    them in *LOWPC and *HIGHPC.  If the correct values can't be
10841    determined, set *LOWPC to -1 and *HIGHPC to 0.  */
10842
10843 static void
10844 get_scope_pc_bounds (struct die_info *die,
10845                      CORE_ADDR *lowpc, CORE_ADDR *highpc,
10846                      struct dwarf2_cu *cu)
10847 {
10848   CORE_ADDR best_low = (CORE_ADDR) -1;
10849   CORE_ADDR best_high = (CORE_ADDR) 0;
10850   CORE_ADDR current_low, current_high;
10851
10852   if (dwarf2_get_pc_bounds (die, &current_low, &current_high, cu, NULL))
10853     {
10854       best_low = current_low;
10855       best_high = current_high;
10856     }
10857   else
10858     {
10859       struct die_info *child = die->child;
10860
10861       while (child && child->tag)
10862         {
10863           switch (child->tag) {
10864           case DW_TAG_subprogram:
10865             dwarf2_get_subprogram_pc_bounds (child, &best_low, &best_high, cu);
10866             break;
10867           case DW_TAG_namespace:
10868           case DW_TAG_module:
10869             /* FIXME: carlton/2004-01-16: Should we do this for
10870                DW_TAG_class_type/DW_TAG_structure_type, too?  I think
10871                that current GCC's always emit the DIEs corresponding
10872                to definitions of methods of classes as children of a
10873                DW_TAG_compile_unit or DW_TAG_namespace (as opposed to
10874                the DIEs giving the declarations, which could be
10875                anywhere).  But I don't see any reason why the
10876                standards says that they have to be there.  */
10877             get_scope_pc_bounds (child, &current_low, &current_high, cu);
10878
10879             if (current_low != ((CORE_ADDR) -1))
10880               {
10881                 best_low = min (best_low, current_low);
10882                 best_high = max (best_high, current_high);
10883               }
10884             break;
10885           default:
10886             /* Ignore.  */
10887             break;
10888           }
10889
10890           child = sibling_die (child);
10891         }
10892     }
10893
10894   *lowpc = best_low;
10895   *highpc = best_high;
10896 }
10897
10898 /* Record the address ranges for BLOCK, offset by BASEADDR, as given
10899    in DIE.  */
10900
10901 static void
10902 dwarf2_record_block_ranges (struct die_info *die, struct block *block,
10903                             CORE_ADDR baseaddr, struct dwarf2_cu *cu)
10904 {
10905   struct objfile *objfile = cu->objfile;
10906   struct attribute *attr;
10907   struct attribute *attr_high;
10908
10909   attr_high = dwarf2_attr (die, DW_AT_high_pc, cu);
10910   if (attr_high)
10911     {
10912       attr = dwarf2_attr (die, DW_AT_low_pc, cu);
10913       if (attr)
10914         {
10915           CORE_ADDR low = DW_ADDR (attr);
10916           CORE_ADDR high;
10917           if (attr_high->form == DW_FORM_addr
10918               || attr_high->form == DW_FORM_GNU_addr_index)
10919             high = DW_ADDR (attr_high);
10920           else
10921             high = low + DW_UNSND (attr_high);
10922
10923           record_block_range (block, baseaddr + low, baseaddr + high - 1);
10924         }
10925     }
10926
10927   attr = dwarf2_attr (die, DW_AT_ranges, cu);
10928   if (attr)
10929     {
10930       bfd *obfd = objfile->obfd;
10931       /* DW_AT_ranges_base does not apply to DIEs from the DWO skeleton.
10932          We take advantage of the fact that DW_AT_ranges does not appear
10933          in DW_TAG_compile_unit of DWO files.  */
10934       int need_ranges_base = die->tag != DW_TAG_compile_unit;
10935
10936       /* The value of the DW_AT_ranges attribute is the offset of the
10937          address range list in the .debug_ranges section.  */
10938       unsigned long offset = (DW_UNSND (attr)
10939                               + (need_ranges_base ? cu->ranges_base : 0));
10940       const gdb_byte *buffer;
10941
10942       /* For some target architectures, but not others, the
10943          read_address function sign-extends the addresses it returns.
10944          To recognize base address selection entries, we need a
10945          mask.  */
10946       unsigned int addr_size = cu->header.addr_size;
10947       CORE_ADDR base_select_mask = ~(~(CORE_ADDR)1 << (addr_size * 8 - 1));
10948
10949       /* The base address, to which the next pair is relative.  Note
10950          that this 'base' is a DWARF concept: most entries in a range
10951          list are relative, to reduce the number of relocs against the
10952          debugging information.  This is separate from this function's
10953          'baseaddr' argument, which GDB uses to relocate debugging
10954          information from a shared library based on the address at
10955          which the library was loaded.  */
10956       CORE_ADDR base = cu->base_address;
10957       int base_known = cu->base_known;
10958
10959       dwarf2_read_section (objfile, &dwarf2_per_objfile->ranges);
10960       if (offset >= dwarf2_per_objfile->ranges.size)
10961         {
10962           complaint (&symfile_complaints,
10963                      _("Offset %lu out of bounds for DW_AT_ranges attribute"),
10964                      offset);
10965           return;
10966         }
10967       buffer = dwarf2_per_objfile->ranges.buffer + offset;
10968
10969       for (;;)
10970         {
10971           unsigned int bytes_read;
10972           CORE_ADDR start, end;
10973
10974           start = read_address (obfd, buffer, cu, &bytes_read);
10975           buffer += bytes_read;
10976           end = read_address (obfd, buffer, cu, &bytes_read);
10977           buffer += bytes_read;
10978
10979           /* Did we find the end of the range list?  */
10980           if (start == 0 && end == 0)
10981             break;
10982
10983           /* Did we find a base address selection entry?  */
10984           else if ((start & base_select_mask) == base_select_mask)
10985             {
10986               base = end;
10987               base_known = 1;
10988             }
10989
10990           /* We found an ordinary address range.  */
10991           else
10992             {
10993               if (!base_known)
10994                 {
10995                   complaint (&symfile_complaints,
10996                              _("Invalid .debug_ranges data "
10997                                "(no base address)"));
10998                   return;
10999                 }
11000
11001               if (start > end)
11002                 {
11003                   /* Inverted range entries are invalid.  */
11004                   complaint (&symfile_complaints,
11005                              _("Invalid .debug_ranges data "
11006                                "(inverted range)"));
11007                   return;
11008                 }
11009
11010               /* Empty range entries have no effect.  */
11011               if (start == end)
11012                 continue;
11013
11014               start += base + baseaddr;
11015               end += base + baseaddr;
11016
11017               /* A not-uncommon case of bad debug info.
11018                  Don't pollute the addrmap with bad data.  */
11019               if (start == 0 && !dwarf2_per_objfile->has_section_at_zero)
11020                 {
11021                   complaint (&symfile_complaints,
11022                              _(".debug_ranges entry has start address of zero"
11023                                " [in module %s]"), objfile->name);
11024                   continue;
11025                 }
11026
11027               record_block_range (block, start, end - 1);
11028             }
11029         }
11030     }
11031 }
11032
11033 /* Check whether the producer field indicates either of GCC < 4.6, or the
11034    Intel C/C++ compiler, and cache the result in CU.  */
11035
11036 static void
11037 check_producer (struct dwarf2_cu *cu)
11038 {
11039   const char *cs;
11040   int major, minor, release;
11041
11042   if (cu->producer == NULL)
11043     {
11044       /* For unknown compilers expect their behavior is DWARF version
11045          compliant.
11046
11047          GCC started to support .debug_types sections by -gdwarf-4 since
11048          gcc-4.5.x.  As the .debug_types sections are missing DW_AT_producer
11049          for their space efficiency GDB cannot workaround gcc-4.5.x -gdwarf-4
11050          combination.  gcc-4.5.x -gdwarf-4 binaries have DW_AT_accessibility
11051          interpreted incorrectly by GDB now - GCC PR debug/48229.  */
11052     }
11053   else if (strncmp (cu->producer, "GNU ", strlen ("GNU ")) == 0)
11054     {
11055       /* Skip any identifier after "GNU " - such as "C++" or "Java".  */
11056
11057       cs = &cu->producer[strlen ("GNU ")];
11058       while (*cs && !isdigit (*cs))
11059         cs++;
11060       if (sscanf (cs, "%d.%d.%d", &major, &minor, &release) != 3)
11061         {
11062           /* Not recognized as GCC.  */
11063         }
11064       else
11065         {
11066           cu->producer_is_gxx_lt_4_6 = major < 4 || (major == 4 && minor < 6);
11067           cu->producer_is_gcc_lt_4_3 = major < 4 || (major == 4 && minor < 3);
11068         }
11069     }
11070   else if (strncmp (cu->producer, "Intel(R) C", strlen ("Intel(R) C")) == 0)
11071     cu->producer_is_icc = 1;
11072   else
11073     {
11074       /* For other non-GCC compilers, expect their behavior is DWARF version
11075          compliant.  */
11076     }
11077
11078   cu->checked_producer = 1;
11079 }
11080
11081 /* Check for GCC PR debug/45124 fix which is not present in any G++ version up
11082    to 4.5.any while it is present already in G++ 4.6.0 - the PR has been fixed
11083    during 4.6.0 experimental.  */
11084
11085 static int
11086 producer_is_gxx_lt_4_6 (struct dwarf2_cu *cu)
11087 {
11088   if (!cu->checked_producer)
11089     check_producer (cu);
11090
11091   return cu->producer_is_gxx_lt_4_6;
11092 }
11093
11094 /* Return the default accessibility type if it is not overriden by
11095    DW_AT_accessibility.  */
11096
11097 static enum dwarf_access_attribute
11098 dwarf2_default_access_attribute (struct die_info *die, struct dwarf2_cu *cu)
11099 {
11100   if (cu->header.version < 3 || producer_is_gxx_lt_4_6 (cu))
11101     {
11102       /* The default DWARF 2 accessibility for members is public, the default
11103          accessibility for inheritance is private.  */
11104
11105       if (die->tag != DW_TAG_inheritance)
11106         return DW_ACCESS_public;
11107       else
11108         return DW_ACCESS_private;
11109     }
11110   else
11111     {
11112       /* DWARF 3+ defines the default accessibility a different way.  The same
11113          rules apply now for DW_TAG_inheritance as for the members and it only
11114          depends on the container kind.  */
11115
11116       if (die->parent->tag == DW_TAG_class_type)
11117         return DW_ACCESS_private;
11118       else
11119         return DW_ACCESS_public;
11120     }
11121 }
11122
11123 /* Look for DW_AT_data_member_location.  Set *OFFSET to the byte
11124    offset.  If the attribute was not found return 0, otherwise return
11125    1.  If it was found but could not properly be handled, set *OFFSET
11126    to 0.  */
11127
11128 static int
11129 handle_data_member_location (struct die_info *die, struct dwarf2_cu *cu,
11130                              LONGEST *offset)
11131 {
11132   struct attribute *attr;
11133
11134   attr = dwarf2_attr (die, DW_AT_data_member_location, cu);
11135   if (attr != NULL)
11136     {
11137       *offset = 0;
11138
11139       /* Note that we do not check for a section offset first here.
11140          This is because DW_AT_data_member_location is new in DWARF 4,
11141          so if we see it, we can assume that a constant form is really
11142          a constant and not a section offset.  */
11143       if (attr_form_is_constant (attr))
11144         *offset = dwarf2_get_attr_constant_value (attr, 0);
11145       else if (attr_form_is_section_offset (attr))
11146         dwarf2_complex_location_expr_complaint ();
11147       else if (attr_form_is_block (attr))
11148         *offset = decode_locdesc (DW_BLOCK (attr), cu);
11149       else
11150         dwarf2_complex_location_expr_complaint ();
11151
11152       return 1;
11153     }
11154
11155   return 0;
11156 }
11157
11158 /* Add an aggregate field to the field list.  */
11159
11160 static void
11161 dwarf2_add_field (struct field_info *fip, struct die_info *die,
11162                   struct dwarf2_cu *cu)
11163 {
11164   struct objfile *objfile = cu->objfile;
11165   struct gdbarch *gdbarch = get_objfile_arch (objfile);
11166   struct nextfield *new_field;
11167   struct attribute *attr;
11168   struct field *fp;
11169   const char *fieldname = "";
11170
11171   /* Allocate a new field list entry and link it in.  */
11172   new_field = (struct nextfield *) xmalloc (sizeof (struct nextfield));
11173   make_cleanup (xfree, new_field);
11174   memset (new_field, 0, sizeof (struct nextfield));
11175
11176   if (die->tag == DW_TAG_inheritance)
11177     {
11178       new_field->next = fip->baseclasses;
11179       fip->baseclasses = new_field;
11180     }
11181   else
11182     {
11183       new_field->next = fip->fields;
11184       fip->fields = new_field;
11185     }
11186   fip->nfields++;
11187
11188   attr = dwarf2_attr (die, DW_AT_accessibility, cu);
11189   if (attr)
11190     new_field->accessibility = DW_UNSND (attr);
11191   else
11192     new_field->accessibility = dwarf2_default_access_attribute (die, cu);
11193   if (new_field->accessibility != DW_ACCESS_public)
11194     fip->non_public_fields = 1;
11195
11196   attr = dwarf2_attr (die, DW_AT_virtuality, cu);
11197   if (attr)
11198     new_field->virtuality = DW_UNSND (attr);
11199   else
11200     new_field->virtuality = DW_VIRTUALITY_none;
11201
11202   fp = &new_field->field;
11203
11204   if (die->tag == DW_TAG_member && ! die_is_declaration (die, cu))
11205     {
11206       LONGEST offset;
11207
11208       /* Data member other than a C++ static data member.  */
11209
11210       /* Get type of field.  */
11211       fp->type = die_type (die, cu);
11212
11213       SET_FIELD_BITPOS (*fp, 0);
11214
11215       /* Get bit size of field (zero if none).  */
11216       attr = dwarf2_attr (die, DW_AT_bit_size, cu);
11217       if (attr)
11218         {
11219           FIELD_BITSIZE (*fp) = DW_UNSND (attr);
11220         }
11221       else
11222         {
11223           FIELD_BITSIZE (*fp) = 0;
11224         }
11225
11226       /* Get bit offset of field.  */
11227       if (handle_data_member_location (die, cu, &offset))
11228         SET_FIELD_BITPOS (*fp, offset * bits_per_byte);
11229       attr = dwarf2_attr (die, DW_AT_bit_offset, cu);
11230       if (attr)
11231         {
11232           if (gdbarch_bits_big_endian (gdbarch))
11233             {
11234               /* For big endian bits, the DW_AT_bit_offset gives the
11235                  additional bit offset from the MSB of the containing
11236                  anonymous object to the MSB of the field.  We don't
11237                  have to do anything special since we don't need to
11238                  know the size of the anonymous object.  */
11239               SET_FIELD_BITPOS (*fp, FIELD_BITPOS (*fp) + DW_UNSND (attr));
11240             }
11241           else
11242             {
11243               /* For little endian bits, compute the bit offset to the
11244                  MSB of the anonymous object, subtract off the number of
11245                  bits from the MSB of the field to the MSB of the
11246                  object, and then subtract off the number of bits of
11247                  the field itself.  The result is the bit offset of
11248                  the LSB of the field.  */
11249               int anonymous_size;
11250               int bit_offset = DW_UNSND (attr);
11251
11252               attr = dwarf2_attr (die, DW_AT_byte_size, cu);
11253               if (attr)
11254                 {
11255                   /* The size of the anonymous object containing
11256                      the bit field is explicit, so use the
11257                      indicated size (in bytes).  */
11258                   anonymous_size = DW_UNSND (attr);
11259                 }
11260               else
11261                 {
11262                   /* The size of the anonymous object containing
11263                      the bit field must be inferred from the type
11264                      attribute of the data member containing the
11265                      bit field.  */
11266                   anonymous_size = TYPE_LENGTH (fp->type);
11267                 }
11268               SET_FIELD_BITPOS (*fp,
11269                                 (FIELD_BITPOS (*fp)
11270                                  + anonymous_size * bits_per_byte
11271                                  - bit_offset - FIELD_BITSIZE (*fp)));
11272             }
11273         }
11274
11275       /* Get name of field.  */
11276       fieldname = dwarf2_name (die, cu);
11277       if (fieldname == NULL)
11278         fieldname = "";
11279
11280       /* The name is already allocated along with this objfile, so we don't
11281          need to duplicate it for the type.  */
11282       fp->name = fieldname;
11283
11284       /* Change accessibility for artificial fields (e.g. virtual table
11285          pointer or virtual base class pointer) to private.  */
11286       if (dwarf2_attr (die, DW_AT_artificial, cu))
11287         {
11288           FIELD_ARTIFICIAL (*fp) = 1;
11289           new_field->accessibility = DW_ACCESS_private;
11290           fip->non_public_fields = 1;
11291         }
11292     }
11293   else if (die->tag == DW_TAG_member || die->tag == DW_TAG_variable)
11294     {
11295       /* C++ static member.  */
11296
11297       /* NOTE: carlton/2002-11-05: It should be a DW_TAG_member that
11298          is a declaration, but all versions of G++ as of this writing
11299          (so through at least 3.2.1) incorrectly generate
11300          DW_TAG_variable tags.  */
11301
11302       const char *physname;
11303
11304       /* Get name of field.  */
11305       fieldname = dwarf2_name (die, cu);
11306       if (fieldname == NULL)
11307         return;
11308
11309       attr = dwarf2_attr (die, DW_AT_const_value, cu);
11310       if (attr
11311           /* Only create a symbol if this is an external value.
11312              new_symbol checks this and puts the value in the global symbol
11313              table, which we want.  If it is not external, new_symbol
11314              will try to put the value in cu->list_in_scope which is wrong.  */
11315           && dwarf2_flag_true_p (die, DW_AT_external, cu))
11316         {
11317           /* A static const member, not much different than an enum as far as
11318              we're concerned, except that we can support more types.  */
11319           new_symbol (die, NULL, cu);
11320         }
11321
11322       /* Get physical name.  */
11323       physname = dwarf2_physname (fieldname, die, cu);
11324
11325       /* The name is already allocated along with this objfile, so we don't
11326          need to duplicate it for the type.  */
11327       SET_FIELD_PHYSNAME (*fp, physname ? physname : "");
11328       FIELD_TYPE (*fp) = die_type (die, cu);
11329       FIELD_NAME (*fp) = fieldname;
11330     }
11331   else if (die->tag == DW_TAG_inheritance)
11332     {
11333       LONGEST offset;
11334
11335       /* C++ base class field.  */
11336       if (handle_data_member_location (die, cu, &offset))
11337         SET_FIELD_BITPOS (*fp, offset * bits_per_byte);
11338       FIELD_BITSIZE (*fp) = 0;
11339       FIELD_TYPE (*fp) = die_type (die, cu);
11340       FIELD_NAME (*fp) = type_name_no_tag (fp->type);
11341       fip->nbaseclasses++;
11342     }
11343 }
11344
11345 /* Add a typedef defined in the scope of the FIP's class.  */
11346
11347 static void
11348 dwarf2_add_typedef (struct field_info *fip, struct die_info *die,
11349                     struct dwarf2_cu *cu)
11350 {
11351   struct objfile *objfile = cu->objfile;
11352   struct typedef_field_list *new_field;
11353   struct attribute *attr;
11354   struct typedef_field *fp;
11355   char *fieldname = "";
11356
11357   /* Allocate a new field list entry and link it in.  */
11358   new_field = xzalloc (sizeof (*new_field));
11359   make_cleanup (xfree, new_field);
11360
11361   gdb_assert (die->tag == DW_TAG_typedef);
11362
11363   fp = &new_field->field;
11364
11365   /* Get name of field.  */
11366   fp->name = dwarf2_name (die, cu);
11367   if (fp->name == NULL)
11368     return;
11369
11370   fp->type = read_type_die (die, cu);
11371
11372   new_field->next = fip->typedef_field_list;
11373   fip->typedef_field_list = new_field;
11374   fip->typedef_field_list_count++;
11375 }
11376
11377 /* Create the vector of fields, and attach it to the type.  */
11378
11379 static void
11380 dwarf2_attach_fields_to_type (struct field_info *fip, struct type *type,
11381                               struct dwarf2_cu *cu)
11382 {
11383   int nfields = fip->nfields;
11384
11385   /* Record the field count, allocate space for the array of fields,
11386      and create blank accessibility bitfields if necessary.  */
11387   TYPE_NFIELDS (type) = nfields;
11388   TYPE_FIELDS (type) = (struct field *)
11389     TYPE_ALLOC (type, sizeof (struct field) * nfields);
11390   memset (TYPE_FIELDS (type), 0, sizeof (struct field) * nfields);
11391
11392   if (fip->non_public_fields && cu->language != language_ada)
11393     {
11394       ALLOCATE_CPLUS_STRUCT_TYPE (type);
11395
11396       TYPE_FIELD_PRIVATE_BITS (type) =
11397         (B_TYPE *) TYPE_ALLOC (type, B_BYTES (nfields));
11398       B_CLRALL (TYPE_FIELD_PRIVATE_BITS (type), nfields);
11399
11400       TYPE_FIELD_PROTECTED_BITS (type) =
11401         (B_TYPE *) TYPE_ALLOC (type, B_BYTES (nfields));
11402       B_CLRALL (TYPE_FIELD_PROTECTED_BITS (type), nfields);
11403
11404       TYPE_FIELD_IGNORE_BITS (type) =
11405         (B_TYPE *) TYPE_ALLOC (type, B_BYTES (nfields));
11406       B_CLRALL (TYPE_FIELD_IGNORE_BITS (type), nfields);
11407     }
11408
11409   /* If the type has baseclasses, allocate and clear a bit vector for
11410      TYPE_FIELD_VIRTUAL_BITS.  */
11411   if (fip->nbaseclasses && cu->language != language_ada)
11412     {
11413       int num_bytes = B_BYTES (fip->nbaseclasses);
11414       unsigned char *pointer;
11415
11416       ALLOCATE_CPLUS_STRUCT_TYPE (type);
11417       pointer = TYPE_ALLOC (type, num_bytes);
11418       TYPE_FIELD_VIRTUAL_BITS (type) = pointer;
11419       B_CLRALL (TYPE_FIELD_VIRTUAL_BITS (type), fip->nbaseclasses);
11420       TYPE_N_BASECLASSES (type) = fip->nbaseclasses;
11421     }
11422
11423   /* Copy the saved-up fields into the field vector.  Start from the head of
11424      the list, adding to the tail of the field array, so that they end up in
11425      the same order in the array in which they were added to the list.  */
11426   while (nfields-- > 0)
11427     {
11428       struct nextfield *fieldp;
11429
11430       if (fip->fields)
11431         {
11432           fieldp = fip->fields;
11433           fip->fields = fieldp->next;
11434         }
11435       else
11436         {
11437           fieldp = fip->baseclasses;
11438           fip->baseclasses = fieldp->next;
11439         }
11440
11441       TYPE_FIELD (type, nfields) = fieldp->field;
11442       switch (fieldp->accessibility)
11443         {
11444         case DW_ACCESS_private:
11445           if (cu->language != language_ada)
11446             SET_TYPE_FIELD_PRIVATE (type, nfields);
11447           break;
11448
11449         case DW_ACCESS_protected:
11450           if (cu->language != language_ada)
11451             SET_TYPE_FIELD_PROTECTED (type, nfields);
11452           break;
11453
11454         case DW_ACCESS_public:
11455           break;
11456
11457         default:
11458           /* Unknown accessibility.  Complain and treat it as public.  */
11459           {
11460             complaint (&symfile_complaints, _("unsupported accessibility %d"),
11461                        fieldp->accessibility);
11462           }
11463           break;
11464         }
11465       if (nfields < fip->nbaseclasses)
11466         {
11467           switch (fieldp->virtuality)
11468             {
11469             case DW_VIRTUALITY_virtual:
11470             case DW_VIRTUALITY_pure_virtual:
11471               if (cu->language == language_ada)
11472                 error (_("unexpected virtuality in component of Ada type"));
11473               SET_TYPE_FIELD_VIRTUAL (type, nfields);
11474               break;
11475             }
11476         }
11477     }
11478 }
11479
11480 /* Return true if this member function is a constructor, false
11481    otherwise.  */
11482
11483 static int
11484 dwarf2_is_constructor (struct die_info *die, struct dwarf2_cu *cu)
11485 {
11486   const char *fieldname;
11487   const char *typename;
11488   int len;
11489
11490   if (die->parent == NULL)
11491     return 0;
11492
11493   if (die->parent->tag != DW_TAG_structure_type
11494       && die->parent->tag != DW_TAG_union_type
11495       && die->parent->tag != DW_TAG_class_type)
11496     return 0;
11497
11498   fieldname = dwarf2_name (die, cu);
11499   typename = dwarf2_name (die->parent, cu);
11500   if (fieldname == NULL || typename == NULL)
11501     return 0;
11502
11503   len = strlen (fieldname);
11504   return (strncmp (fieldname, typename, len) == 0
11505           && (typename[len] == '\0' || typename[len] == '<'));
11506 }
11507
11508 /* Add a member function to the proper fieldlist.  */
11509
11510 static void
11511 dwarf2_add_member_fn (struct field_info *fip, struct die_info *die,
11512                       struct type *type, struct dwarf2_cu *cu)
11513 {
11514   struct objfile *objfile = cu->objfile;
11515   struct attribute *attr;
11516   struct fnfieldlist *flp;
11517   int i;
11518   struct fn_field *fnp;
11519   const char *fieldname;
11520   struct nextfnfield *new_fnfield;
11521   struct type *this_type;
11522   enum dwarf_access_attribute accessibility;
11523
11524   if (cu->language == language_ada)
11525     error (_("unexpected member function in Ada type"));
11526
11527   /* Get name of member function.  */
11528   fieldname = dwarf2_name (die, cu);
11529   if (fieldname == NULL)
11530     return;
11531
11532   /* Look up member function name in fieldlist.  */
11533   for (i = 0; i < fip->nfnfields; i++)
11534     {
11535       if (strcmp (fip->fnfieldlists[i].name, fieldname) == 0)
11536         break;
11537     }
11538
11539   /* Create new list element if necessary.  */
11540   if (i < fip->nfnfields)
11541     flp = &fip->fnfieldlists[i];
11542   else
11543     {
11544       if ((fip->nfnfields % DW_FIELD_ALLOC_CHUNK) == 0)
11545         {
11546           fip->fnfieldlists = (struct fnfieldlist *)
11547             xrealloc (fip->fnfieldlists,
11548                       (fip->nfnfields + DW_FIELD_ALLOC_CHUNK)
11549                       * sizeof (struct fnfieldlist));
11550           if (fip->nfnfields == 0)
11551             make_cleanup (free_current_contents, &fip->fnfieldlists);
11552         }
11553       flp = &fip->fnfieldlists[fip->nfnfields];
11554       flp->name = fieldname;
11555       flp->length = 0;
11556       flp->head = NULL;
11557       i = fip->nfnfields++;
11558     }
11559
11560   /* Create a new member function field and chain it to the field list
11561      entry.  */
11562   new_fnfield = (struct nextfnfield *) xmalloc (sizeof (struct nextfnfield));
11563   make_cleanup (xfree, new_fnfield);
11564   memset (new_fnfield, 0, sizeof (struct nextfnfield));
11565   new_fnfield->next = flp->head;
11566   flp->head = new_fnfield;
11567   flp->length++;
11568
11569   /* Fill in the member function field info.  */
11570   fnp = &new_fnfield->fnfield;
11571
11572   /* Delay processing of the physname until later.  */
11573   if (cu->language == language_cplus || cu->language == language_java)
11574     {
11575       add_to_method_list (type, i, flp->length - 1, fieldname,
11576                           die, cu);
11577     }
11578   else
11579     {
11580       const char *physname = dwarf2_physname (fieldname, die, cu);
11581       fnp->physname = physname ? physname : "";
11582     }
11583
11584   fnp->type = alloc_type (objfile);
11585   this_type = read_type_die (die, cu);
11586   if (this_type && TYPE_CODE (this_type) == TYPE_CODE_FUNC)
11587     {
11588       int nparams = TYPE_NFIELDS (this_type);
11589
11590       /* TYPE is the domain of this method, and THIS_TYPE is the type
11591            of the method itself (TYPE_CODE_METHOD).  */
11592       smash_to_method_type (fnp->type, type,
11593                             TYPE_TARGET_TYPE (this_type),
11594                             TYPE_FIELDS (this_type),
11595                             TYPE_NFIELDS (this_type),
11596                             TYPE_VARARGS (this_type));
11597
11598       /* Handle static member functions.
11599          Dwarf2 has no clean way to discern C++ static and non-static
11600          member functions.  G++ helps GDB by marking the first
11601          parameter for non-static member functions (which is the this
11602          pointer) as artificial.  We obtain this information from
11603          read_subroutine_type via TYPE_FIELD_ARTIFICIAL.  */
11604       if (nparams == 0 || TYPE_FIELD_ARTIFICIAL (this_type, 0) == 0)
11605         fnp->voffset = VOFFSET_STATIC;
11606     }
11607   else
11608     complaint (&symfile_complaints, _("member function type missing for '%s'"),
11609                dwarf2_full_name (fieldname, die, cu));
11610
11611   /* Get fcontext from DW_AT_containing_type if present.  */
11612   if (dwarf2_attr (die, DW_AT_containing_type, cu) != NULL)
11613     fnp->fcontext = die_containing_type (die, cu);
11614
11615   /* dwarf2 doesn't have stubbed physical names, so the setting of is_const and
11616      is_volatile is irrelevant, as it is needed by gdb_mangle_name only.  */
11617
11618   /* Get accessibility.  */
11619   attr = dwarf2_attr (die, DW_AT_accessibility, cu);
11620   if (attr)
11621     accessibility = DW_UNSND (attr);
11622   else
11623     accessibility = dwarf2_default_access_attribute (die, cu);
11624   switch (accessibility)
11625     {
11626     case DW_ACCESS_private:
11627       fnp->is_private = 1;
11628       break;
11629     case DW_ACCESS_protected:
11630       fnp->is_protected = 1;
11631       break;
11632     }
11633
11634   /* Check for artificial methods.  */
11635   attr = dwarf2_attr (die, DW_AT_artificial, cu);
11636   if (attr && DW_UNSND (attr) != 0)
11637     fnp->is_artificial = 1;
11638
11639   fnp->is_constructor = dwarf2_is_constructor (die, cu);
11640
11641   /* Get index in virtual function table if it is a virtual member
11642      function.  For older versions of GCC, this is an offset in the
11643      appropriate virtual table, as specified by DW_AT_containing_type.
11644      For everyone else, it is an expression to be evaluated relative
11645      to the object address.  */
11646
11647   attr = dwarf2_attr (die, DW_AT_vtable_elem_location, cu);
11648   if (attr)
11649     {
11650       if (attr_form_is_block (attr) && DW_BLOCK (attr)->size > 0)
11651         {
11652           if (DW_BLOCK (attr)->data[0] == DW_OP_constu)
11653             {
11654               /* Old-style GCC.  */
11655               fnp->voffset = decode_locdesc (DW_BLOCK (attr), cu) + 2;
11656             }
11657           else if (DW_BLOCK (attr)->data[0] == DW_OP_deref
11658                    || (DW_BLOCK (attr)->size > 1
11659                        && DW_BLOCK (attr)->data[0] == DW_OP_deref_size
11660                        && DW_BLOCK (attr)->data[1] == cu->header.addr_size))
11661             {
11662               struct dwarf_block blk;
11663               int offset;
11664
11665               offset = (DW_BLOCK (attr)->data[0] == DW_OP_deref
11666                         ? 1 : 2);
11667               blk.size = DW_BLOCK (attr)->size - offset;
11668               blk.data = DW_BLOCK (attr)->data + offset;
11669               fnp->voffset = decode_locdesc (DW_BLOCK (attr), cu);
11670               if ((fnp->voffset % cu->header.addr_size) != 0)
11671                 dwarf2_complex_location_expr_complaint ();
11672               else
11673                 fnp->voffset /= cu->header.addr_size;
11674               fnp->voffset += 2;
11675             }
11676           else
11677             dwarf2_complex_location_expr_complaint ();
11678
11679           if (!fnp->fcontext)
11680             fnp->fcontext = TYPE_TARGET_TYPE (TYPE_FIELD_TYPE (this_type, 0));
11681         }
11682       else if (attr_form_is_section_offset (attr))
11683         {
11684           dwarf2_complex_location_expr_complaint ();
11685         }
11686       else
11687         {
11688           dwarf2_invalid_attrib_class_complaint ("DW_AT_vtable_elem_location",
11689                                                  fieldname);
11690         }
11691     }
11692   else
11693     {
11694       attr = dwarf2_attr (die, DW_AT_virtuality, cu);
11695       if (attr && DW_UNSND (attr))
11696         {
11697           /* GCC does this, as of 2008-08-25; PR debug/37237.  */
11698           complaint (&symfile_complaints,
11699                      _("Member function \"%s\" (offset %d) is virtual "
11700                        "but the vtable offset is not specified"),
11701                      fieldname, die->offset.sect_off);
11702           ALLOCATE_CPLUS_STRUCT_TYPE (type);
11703           TYPE_CPLUS_DYNAMIC (type) = 1;
11704         }
11705     }
11706 }
11707
11708 /* Create the vector of member function fields, and attach it to the type.  */
11709
11710 static void
11711 dwarf2_attach_fn_fields_to_type (struct field_info *fip, struct type *type,
11712                                  struct dwarf2_cu *cu)
11713 {
11714   struct fnfieldlist *flp;
11715   int i;
11716
11717   if (cu->language == language_ada)
11718     error (_("unexpected member functions in Ada type"));
11719
11720   ALLOCATE_CPLUS_STRUCT_TYPE (type);
11721   TYPE_FN_FIELDLISTS (type) = (struct fn_fieldlist *)
11722     TYPE_ALLOC (type, sizeof (struct fn_fieldlist) * fip->nfnfields);
11723
11724   for (i = 0, flp = fip->fnfieldlists; i < fip->nfnfields; i++, flp++)
11725     {
11726       struct nextfnfield *nfp = flp->head;
11727       struct fn_fieldlist *fn_flp = &TYPE_FN_FIELDLIST (type, i);
11728       int k;
11729
11730       TYPE_FN_FIELDLIST_NAME (type, i) = flp->name;
11731       TYPE_FN_FIELDLIST_LENGTH (type, i) = flp->length;
11732       fn_flp->fn_fields = (struct fn_field *)
11733         TYPE_ALLOC (type, sizeof (struct fn_field) * flp->length);
11734       for (k = flp->length; (k--, nfp); nfp = nfp->next)
11735         fn_flp->fn_fields[k] = nfp->fnfield;
11736     }
11737
11738   TYPE_NFN_FIELDS (type) = fip->nfnfields;
11739 }
11740
11741 /* Returns non-zero if NAME is the name of a vtable member in CU's
11742    language, zero otherwise.  */
11743 static int
11744 is_vtable_name (const char *name, struct dwarf2_cu *cu)
11745 {
11746   static const char vptr[] = "_vptr";
11747   static const char vtable[] = "vtable";
11748
11749   /* Look for the C++ and Java forms of the vtable.  */
11750   if ((cu->language == language_java
11751        && strncmp (name, vtable, sizeof (vtable) - 1) == 0)
11752        || (strncmp (name, vptr, sizeof (vptr) - 1) == 0
11753        && is_cplus_marker (name[sizeof (vptr) - 1])))
11754     return 1;
11755
11756   return 0;
11757 }
11758
11759 /* GCC outputs unnamed structures that are really pointers to member
11760    functions, with the ABI-specified layout.  If TYPE describes
11761    such a structure, smash it into a member function type.
11762
11763    GCC shouldn't do this; it should just output pointer to member DIEs.
11764    This is GCC PR debug/28767.  */
11765
11766 static void
11767 quirk_gcc_member_function_pointer (struct type *type, struct objfile *objfile)
11768 {
11769   struct type *pfn_type, *domain_type, *new_type;
11770
11771   /* Check for a structure with no name and two children.  */
11772   if (TYPE_CODE (type) != TYPE_CODE_STRUCT || TYPE_NFIELDS (type) != 2)
11773     return;
11774
11775   /* Check for __pfn and __delta members.  */
11776   if (TYPE_FIELD_NAME (type, 0) == NULL
11777       || strcmp (TYPE_FIELD_NAME (type, 0), "__pfn") != 0
11778       || TYPE_FIELD_NAME (type, 1) == NULL
11779       || strcmp (TYPE_FIELD_NAME (type, 1), "__delta") != 0)
11780     return;
11781
11782   /* Find the type of the method.  */
11783   pfn_type = TYPE_FIELD_TYPE (type, 0);
11784   if (pfn_type == NULL
11785       || TYPE_CODE (pfn_type) != TYPE_CODE_PTR
11786       || TYPE_CODE (TYPE_TARGET_TYPE (pfn_type)) != TYPE_CODE_FUNC)
11787     return;
11788
11789   /* Look for the "this" argument.  */
11790   pfn_type = TYPE_TARGET_TYPE (pfn_type);
11791   if (TYPE_NFIELDS (pfn_type) == 0
11792       /* || TYPE_FIELD_TYPE (pfn_type, 0) == NULL */
11793       || TYPE_CODE (TYPE_FIELD_TYPE (pfn_type, 0)) != TYPE_CODE_PTR)
11794     return;
11795
11796   domain_type = TYPE_TARGET_TYPE (TYPE_FIELD_TYPE (pfn_type, 0));
11797   new_type = alloc_type (objfile);
11798   smash_to_method_type (new_type, domain_type, TYPE_TARGET_TYPE (pfn_type),
11799                         TYPE_FIELDS (pfn_type), TYPE_NFIELDS (pfn_type),
11800                         TYPE_VARARGS (pfn_type));
11801   smash_to_methodptr_type (type, new_type);
11802 }
11803
11804 /* Return non-zero if the CU's PRODUCER string matches the Intel C/C++ compiler
11805    (icc).  */
11806
11807 static int
11808 producer_is_icc (struct dwarf2_cu *cu)
11809 {
11810   if (!cu->checked_producer)
11811     check_producer (cu);
11812
11813   return cu->producer_is_icc;
11814 }
11815
11816 /* Called when we find the DIE that starts a structure or union scope
11817    (definition) to create a type for the structure or union.  Fill in
11818    the type's name and general properties; the members will not be
11819    processed until process_structure_scope.
11820
11821    NOTE: we need to call these functions regardless of whether or not the
11822    DIE has a DW_AT_name attribute, since it might be an anonymous
11823    structure or union.  This gets the type entered into our set of
11824    user defined types.
11825
11826    However, if the structure is incomplete (an opaque struct/union)
11827    then suppress creating a symbol table entry for it since gdb only
11828    wants to find the one with the complete definition.  Note that if
11829    it is complete, we just call new_symbol, which does it's own
11830    checking about whether the struct/union is anonymous or not (and
11831    suppresses creating a symbol table entry itself).  */
11832
11833 static struct type *
11834 read_structure_type (struct die_info *die, struct dwarf2_cu *cu)
11835 {
11836   struct objfile *objfile = cu->objfile;
11837   struct type *type;
11838   struct attribute *attr;
11839   const char *name;
11840
11841   /* If the definition of this type lives in .debug_types, read that type.
11842      Don't follow DW_AT_specification though, that will take us back up
11843      the chain and we want to go down.  */
11844   attr = dwarf2_attr_no_follow (die, DW_AT_signature);
11845   if (attr)
11846     {
11847       type = get_DW_AT_signature_type (die, attr, cu);
11848
11849       /* The type's CU may not be the same as CU.
11850          Ensure TYPE is recorded with CU in die_type_hash.  */
11851       return set_die_type (die, type, cu);
11852     }
11853
11854   type = alloc_type (objfile);
11855   INIT_CPLUS_SPECIFIC (type);
11856
11857   name = dwarf2_name (die, cu);
11858   if (name != NULL)
11859     {
11860       if (cu->language == language_cplus
11861           || cu->language == language_java)
11862         {
11863           const char *full_name = dwarf2_full_name (name, die, cu);
11864
11865           /* dwarf2_full_name might have already finished building the DIE's
11866              type.  If so, there is no need to continue.  */
11867           if (get_die_type (die, cu) != NULL)
11868             return get_die_type (die, cu);
11869
11870           TYPE_TAG_NAME (type) = full_name;
11871           if (die->tag == DW_TAG_structure_type
11872               || die->tag == DW_TAG_class_type)
11873             TYPE_NAME (type) = TYPE_TAG_NAME (type);
11874         }
11875       else
11876         {
11877           /* The name is already allocated along with this objfile, so
11878              we don't need to duplicate it for the type.  */
11879           TYPE_TAG_NAME (type) = name;
11880           if (die->tag == DW_TAG_class_type)
11881             TYPE_NAME (type) = TYPE_TAG_NAME (type);
11882         }
11883     }
11884
11885   if (die->tag == DW_TAG_structure_type)
11886     {
11887       TYPE_CODE (type) = TYPE_CODE_STRUCT;
11888     }
11889   else if (die->tag == DW_TAG_union_type)
11890     {
11891       TYPE_CODE (type) = TYPE_CODE_UNION;
11892     }
11893   else
11894     {
11895       TYPE_CODE (type) = TYPE_CODE_CLASS;
11896     }
11897
11898   if (cu->language == language_cplus && die->tag == DW_TAG_class_type)
11899     TYPE_DECLARED_CLASS (type) = 1;
11900
11901   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
11902   if (attr)
11903     {
11904       TYPE_LENGTH (type) = DW_UNSND (attr);
11905     }
11906   else
11907     {
11908       TYPE_LENGTH (type) = 0;
11909     }
11910
11911   if (producer_is_icc (cu))
11912     {
11913       /* ICC does not output the required DW_AT_declaration
11914          on incomplete types, but gives them a size of zero.  */
11915     }
11916   else
11917     TYPE_STUB_SUPPORTED (type) = 1;
11918
11919   if (die_is_declaration (die, cu))
11920     TYPE_STUB (type) = 1;
11921   else if (attr == NULL && die->child == NULL
11922            && producer_is_realview (cu->producer))
11923     /* RealView does not output the required DW_AT_declaration
11924        on incomplete types.  */
11925     TYPE_STUB (type) = 1;
11926
11927   /* We need to add the type field to the die immediately so we don't
11928      infinitely recurse when dealing with pointers to the structure
11929      type within the structure itself.  */
11930   set_die_type (die, type, cu);
11931
11932   /* set_die_type should be already done.  */
11933   set_descriptive_type (type, die, cu);
11934
11935   return type;
11936 }
11937
11938 /* Finish creating a structure or union type, including filling in
11939    its members and creating a symbol for it.  */
11940
11941 static void
11942 process_structure_scope (struct die_info *die, struct dwarf2_cu *cu)
11943 {
11944   struct objfile *objfile = cu->objfile;
11945   struct die_info *child_die = die->child;
11946   struct type *type;
11947
11948   type = get_die_type (die, cu);
11949   if (type == NULL)
11950     type = read_structure_type (die, cu);
11951
11952   if (die->child != NULL && ! die_is_declaration (die, cu))
11953     {
11954       struct field_info fi;
11955       struct die_info *child_die;
11956       VEC (symbolp) *template_args = NULL;
11957       struct cleanup *back_to = make_cleanup (null_cleanup, 0);
11958
11959       memset (&fi, 0, sizeof (struct field_info));
11960
11961       child_die = die->child;
11962
11963       while (child_die && child_die->tag)
11964         {
11965           if (child_die->tag == DW_TAG_member
11966               || child_die->tag == DW_TAG_variable)
11967             {
11968               /* NOTE: carlton/2002-11-05: A C++ static data member
11969                  should be a DW_TAG_member that is a declaration, but
11970                  all versions of G++ as of this writing (so through at
11971                  least 3.2.1) incorrectly generate DW_TAG_variable
11972                  tags for them instead.  */
11973               dwarf2_add_field (&fi, child_die, cu);
11974             }
11975           else if (child_die->tag == DW_TAG_subprogram)
11976             {
11977               /* C++ member function.  */
11978               dwarf2_add_member_fn (&fi, child_die, type, cu);
11979             }
11980           else if (child_die->tag == DW_TAG_inheritance)
11981             {
11982               /* C++ base class field.  */
11983               dwarf2_add_field (&fi, child_die, cu);
11984             }
11985           else if (child_die->tag == DW_TAG_typedef)
11986             dwarf2_add_typedef (&fi, child_die, cu);
11987           else if (child_die->tag == DW_TAG_template_type_param
11988                    || child_die->tag == DW_TAG_template_value_param)
11989             {
11990               struct symbol *arg = new_symbol (child_die, NULL, cu);
11991
11992               if (arg != NULL)
11993                 VEC_safe_push (symbolp, template_args, arg);
11994             }
11995
11996           child_die = sibling_die (child_die);
11997         }
11998
11999       /* Attach template arguments to type.  */
12000       if (! VEC_empty (symbolp, template_args))
12001         {
12002           ALLOCATE_CPLUS_STRUCT_TYPE (type);
12003           TYPE_N_TEMPLATE_ARGUMENTS (type)
12004             = VEC_length (symbolp, template_args);
12005           TYPE_TEMPLATE_ARGUMENTS (type)
12006             = obstack_alloc (&objfile->objfile_obstack,
12007                              (TYPE_N_TEMPLATE_ARGUMENTS (type)
12008                               * sizeof (struct symbol *)));
12009           memcpy (TYPE_TEMPLATE_ARGUMENTS (type),
12010                   VEC_address (symbolp, template_args),
12011                   (TYPE_N_TEMPLATE_ARGUMENTS (type)
12012                    * sizeof (struct symbol *)));
12013           VEC_free (symbolp, template_args);
12014         }
12015
12016       /* Attach fields and member functions to the type.  */
12017       if (fi.nfields)
12018         dwarf2_attach_fields_to_type (&fi, type, cu);
12019       if (fi.nfnfields)
12020         {
12021           dwarf2_attach_fn_fields_to_type (&fi, type, cu);
12022
12023           /* Get the type which refers to the base class (possibly this
12024              class itself) which contains the vtable pointer for the current
12025              class from the DW_AT_containing_type attribute.  This use of
12026              DW_AT_containing_type is a GNU extension.  */
12027
12028           if (dwarf2_attr (die, DW_AT_containing_type, cu) != NULL)
12029             {
12030               struct type *t = die_containing_type (die, cu);
12031
12032               TYPE_VPTR_BASETYPE (type) = t;
12033               if (type == t)
12034                 {
12035                   int i;
12036
12037                   /* Our own class provides vtbl ptr.  */
12038                   for (i = TYPE_NFIELDS (t) - 1;
12039                        i >= TYPE_N_BASECLASSES (t);
12040                        --i)
12041                     {
12042                       const char *fieldname = TYPE_FIELD_NAME (t, i);
12043
12044                       if (is_vtable_name (fieldname, cu))
12045                         {
12046                           TYPE_VPTR_FIELDNO (type) = i;
12047                           break;
12048                         }
12049                     }
12050
12051                   /* Complain if virtual function table field not found.  */
12052                   if (i < TYPE_N_BASECLASSES (t))
12053                     complaint (&symfile_complaints,
12054                                _("virtual function table pointer "
12055                                  "not found when defining class '%s'"),
12056                                TYPE_TAG_NAME (type) ? TYPE_TAG_NAME (type) :
12057                                "");
12058                 }
12059               else
12060                 {
12061                   TYPE_VPTR_FIELDNO (type) = TYPE_VPTR_FIELDNO (t);
12062                 }
12063             }
12064           else if (cu->producer
12065                    && strncmp (cu->producer,
12066                                "IBM(R) XL C/C++ Advanced Edition", 32) == 0)
12067             {
12068               /* The IBM XLC compiler does not provide direct indication
12069                  of the containing type, but the vtable pointer is
12070                  always named __vfp.  */
12071
12072               int i;
12073
12074               for (i = TYPE_NFIELDS (type) - 1;
12075                    i >= TYPE_N_BASECLASSES (type);
12076                    --i)
12077                 {
12078                   if (strcmp (TYPE_FIELD_NAME (type, i), "__vfp") == 0)
12079                     {
12080                       TYPE_VPTR_FIELDNO (type) = i;
12081                       TYPE_VPTR_BASETYPE (type) = type;
12082                       break;
12083                     }
12084                 }
12085             }
12086         }
12087
12088       /* Copy fi.typedef_field_list linked list elements content into the
12089          allocated array TYPE_TYPEDEF_FIELD_ARRAY (type).  */
12090       if (fi.typedef_field_list)
12091         {
12092           int i = fi.typedef_field_list_count;
12093
12094           ALLOCATE_CPLUS_STRUCT_TYPE (type);
12095           TYPE_TYPEDEF_FIELD_ARRAY (type)
12096             = TYPE_ALLOC (type, sizeof (TYPE_TYPEDEF_FIELD (type, 0)) * i);
12097           TYPE_TYPEDEF_FIELD_COUNT (type) = i;
12098
12099           /* Reverse the list order to keep the debug info elements order.  */
12100           while (--i >= 0)
12101             {
12102               struct typedef_field *dest, *src;
12103
12104               dest = &TYPE_TYPEDEF_FIELD (type, i);
12105               src = &fi.typedef_field_list->field;
12106               fi.typedef_field_list = fi.typedef_field_list->next;
12107               *dest = *src;
12108             }
12109         }
12110
12111       do_cleanups (back_to);
12112
12113       if (HAVE_CPLUS_STRUCT (type))
12114         TYPE_CPLUS_REALLY_JAVA (type) = cu->language == language_java;
12115     }
12116
12117   quirk_gcc_member_function_pointer (type, objfile);
12118
12119   /* NOTE: carlton/2004-03-16: GCC 3.4 (or at least one of its
12120      snapshots) has been known to create a die giving a declaration
12121      for a class that has, as a child, a die giving a definition for a
12122      nested class.  So we have to process our children even if the
12123      current die is a declaration.  Normally, of course, a declaration
12124      won't have any children at all.  */
12125
12126   while (child_die != NULL && child_die->tag)
12127     {
12128       if (child_die->tag == DW_TAG_member
12129           || child_die->tag == DW_TAG_variable
12130           || child_die->tag == DW_TAG_inheritance
12131           || child_die->tag == DW_TAG_template_value_param
12132           || child_die->tag == DW_TAG_template_type_param)
12133         {
12134           /* Do nothing.  */
12135         }
12136       else
12137         process_die (child_die, cu);
12138
12139       child_die = sibling_die (child_die);
12140     }
12141
12142   /* Do not consider external references.  According to the DWARF standard,
12143      these DIEs are identified by the fact that they have no byte_size
12144      attribute, and a declaration attribute.  */
12145   if (dwarf2_attr (die, DW_AT_byte_size, cu) != NULL
12146       || !die_is_declaration (die, cu))
12147     new_symbol (die, type, cu);
12148 }
12149
12150 /* Given a DW_AT_enumeration_type die, set its type.  We do not
12151    complete the type's fields yet, or create any symbols.  */
12152
12153 static struct type *
12154 read_enumeration_type (struct die_info *die, struct dwarf2_cu *cu)
12155 {
12156   struct objfile *objfile = cu->objfile;
12157   struct type *type;
12158   struct attribute *attr;
12159   const char *name;
12160
12161   /* If the definition of this type lives in .debug_types, read that type.
12162      Don't follow DW_AT_specification though, that will take us back up
12163      the chain and we want to go down.  */
12164   attr = dwarf2_attr_no_follow (die, DW_AT_signature);
12165   if (attr)
12166     {
12167       type = get_DW_AT_signature_type (die, attr, cu);
12168
12169       /* The type's CU may not be the same as CU.
12170          Ensure TYPE is recorded with CU in die_type_hash.  */
12171       return set_die_type (die, type, cu);
12172     }
12173
12174   type = alloc_type (objfile);
12175
12176   TYPE_CODE (type) = TYPE_CODE_ENUM;
12177   name = dwarf2_full_name (NULL, die, cu);
12178   if (name != NULL)
12179     TYPE_TAG_NAME (type) = name;
12180
12181   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
12182   if (attr)
12183     {
12184       TYPE_LENGTH (type) = DW_UNSND (attr);
12185     }
12186   else
12187     {
12188       TYPE_LENGTH (type) = 0;
12189     }
12190
12191   /* The enumeration DIE can be incomplete.  In Ada, any type can be
12192      declared as private in the package spec, and then defined only
12193      inside the package body.  Such types are known as Taft Amendment
12194      Types.  When another package uses such a type, an incomplete DIE
12195      may be generated by the compiler.  */
12196   if (die_is_declaration (die, cu))
12197     TYPE_STUB (type) = 1;
12198
12199   return set_die_type (die, type, cu);
12200 }
12201
12202 /* Given a pointer to a die which begins an enumeration, process all
12203    the dies that define the members of the enumeration, and create the
12204    symbol for the enumeration type.
12205
12206    NOTE: We reverse the order of the element list.  */
12207
12208 static void
12209 process_enumeration_scope (struct die_info *die, struct dwarf2_cu *cu)
12210 {
12211   struct type *this_type;
12212
12213   this_type = get_die_type (die, cu);
12214   if (this_type == NULL)
12215     this_type = read_enumeration_type (die, cu);
12216
12217   if (die->child != NULL)
12218     {
12219       struct die_info *child_die;
12220       struct symbol *sym;
12221       struct field *fields = NULL;
12222       int num_fields = 0;
12223       int unsigned_enum = 1;
12224       const char *name;
12225       int flag_enum = 1;
12226       ULONGEST mask = 0;
12227
12228       child_die = die->child;
12229       while (child_die && child_die->tag)
12230         {
12231           if (child_die->tag != DW_TAG_enumerator)
12232             {
12233               process_die (child_die, cu);
12234             }
12235           else
12236             {
12237               name = dwarf2_name (child_die, cu);
12238               if (name)
12239                 {
12240                   sym = new_symbol (child_die, this_type, cu);
12241                   if (SYMBOL_VALUE (sym) < 0)
12242                     {
12243                       unsigned_enum = 0;
12244                       flag_enum = 0;
12245                     }
12246                   else if ((mask & SYMBOL_VALUE (sym)) != 0)
12247                     flag_enum = 0;
12248                   else
12249                     mask |= SYMBOL_VALUE (sym);
12250
12251                   if ((num_fields % DW_FIELD_ALLOC_CHUNK) == 0)
12252                     {
12253                       fields = (struct field *)
12254                         xrealloc (fields,
12255                                   (num_fields + DW_FIELD_ALLOC_CHUNK)
12256                                   * sizeof (struct field));
12257                     }
12258
12259                   FIELD_NAME (fields[num_fields]) = SYMBOL_LINKAGE_NAME (sym);
12260                   FIELD_TYPE (fields[num_fields]) = NULL;
12261                   SET_FIELD_ENUMVAL (fields[num_fields], SYMBOL_VALUE (sym));
12262                   FIELD_BITSIZE (fields[num_fields]) = 0;
12263
12264                   num_fields++;
12265                 }
12266             }
12267
12268           child_die = sibling_die (child_die);
12269         }
12270
12271       if (num_fields)
12272         {
12273           TYPE_NFIELDS (this_type) = num_fields;
12274           TYPE_FIELDS (this_type) = (struct field *)
12275             TYPE_ALLOC (this_type, sizeof (struct field) * num_fields);
12276           memcpy (TYPE_FIELDS (this_type), fields,
12277                   sizeof (struct field) * num_fields);
12278           xfree (fields);
12279         }
12280       if (unsigned_enum)
12281         TYPE_UNSIGNED (this_type) = 1;
12282       if (flag_enum)
12283         TYPE_FLAG_ENUM (this_type) = 1;
12284     }
12285
12286   /* If we are reading an enum from a .debug_types unit, and the enum
12287      is a declaration, and the enum is not the signatured type in the
12288      unit, then we do not want to add a symbol for it.  Adding a
12289      symbol would in some cases obscure the true definition of the
12290      enum, giving users an incomplete type when the definition is
12291      actually available.  Note that we do not want to do this for all
12292      enums which are just declarations, because C++0x allows forward
12293      enum declarations.  */
12294   if (cu->per_cu->is_debug_types
12295       && die_is_declaration (die, cu))
12296     {
12297       struct signatured_type *sig_type;
12298
12299       sig_type = (struct signatured_type *) cu->per_cu;
12300       gdb_assert (sig_type->type_offset_in_section.sect_off != 0);
12301       if (sig_type->type_offset_in_section.sect_off != die->offset.sect_off)
12302         return;
12303     }
12304
12305   new_symbol (die, this_type, cu);
12306 }
12307
12308 /* Extract all information from a DW_TAG_array_type DIE and put it in
12309    the DIE's type field.  For now, this only handles one dimensional
12310    arrays.  */
12311
12312 static struct type *
12313 read_array_type (struct die_info *die, struct dwarf2_cu *cu)
12314 {
12315   struct objfile *objfile = cu->objfile;
12316   struct die_info *child_die;
12317   struct type *type;
12318   struct type *element_type, *range_type, *index_type;
12319   struct type **range_types = NULL;
12320   struct attribute *attr;
12321   int ndim = 0;
12322   struct cleanup *back_to;
12323   const char *name;
12324
12325   element_type = die_type (die, cu);
12326
12327   /* The die_type call above may have already set the type for this DIE.  */
12328   type = get_die_type (die, cu);
12329   if (type)
12330     return type;
12331
12332   /* Irix 6.2 native cc creates array types without children for
12333      arrays with unspecified length.  */
12334   if (die->child == NULL)
12335     {
12336       index_type = objfile_type (objfile)->builtin_int;
12337       range_type = create_range_type (NULL, index_type, 0, -1);
12338       type = create_array_type (NULL, element_type, range_type);
12339       return set_die_type (die, type, cu);
12340     }
12341
12342   back_to = make_cleanup (null_cleanup, NULL);
12343   child_die = die->child;
12344   while (child_die && child_die->tag)
12345     {
12346       if (child_die->tag == DW_TAG_subrange_type)
12347         {
12348           struct type *child_type = read_type_die (child_die, cu);
12349
12350           if (child_type != NULL)
12351             {
12352               /* The range type was succesfully read.  Save it for the
12353                  array type creation.  */
12354               if ((ndim % DW_FIELD_ALLOC_CHUNK) == 0)
12355                 {
12356                   range_types = (struct type **)
12357                     xrealloc (range_types, (ndim + DW_FIELD_ALLOC_CHUNK)
12358                               * sizeof (struct type *));
12359                   if (ndim == 0)
12360                     make_cleanup (free_current_contents, &range_types);
12361                 }
12362               range_types[ndim++] = child_type;
12363             }
12364         }
12365       child_die = sibling_die (child_die);
12366     }
12367
12368   /* Dwarf2 dimensions are output from left to right, create the
12369      necessary array types in backwards order.  */
12370
12371   type = element_type;
12372
12373   if (read_array_order (die, cu) == DW_ORD_col_major)
12374     {
12375       int i = 0;
12376
12377       while (i < ndim)
12378         type = create_array_type (NULL, type, range_types[i++]);
12379     }
12380   else
12381     {
12382       while (ndim-- > 0)
12383         type = create_array_type (NULL, type, range_types[ndim]);
12384     }
12385
12386   /* Understand Dwarf2 support for vector types (like they occur on
12387      the PowerPC w/ AltiVec).  Gcc just adds another attribute to the
12388      array type.  This is not part of the Dwarf2/3 standard yet, but a
12389      custom vendor extension.  The main difference between a regular
12390      array and the vector variant is that vectors are passed by value
12391      to functions.  */
12392   attr = dwarf2_attr (die, DW_AT_GNU_vector, cu);
12393   if (attr)
12394     make_vector_type (type);
12395
12396   /* The DIE may have DW_AT_byte_size set.  For example an OpenCL
12397      implementation may choose to implement triple vectors using this
12398      attribute.  */
12399   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
12400   if (attr)
12401     {
12402       if (DW_UNSND (attr) >= TYPE_LENGTH (type))
12403         TYPE_LENGTH (type) = DW_UNSND (attr);
12404       else
12405         complaint (&symfile_complaints,
12406                    _("DW_AT_byte_size for array type smaller "
12407                      "than the total size of elements"));
12408     }
12409
12410   name = dwarf2_name (die, cu);
12411   if (name)
12412     TYPE_NAME (type) = name;
12413
12414   /* Install the type in the die.  */
12415   set_die_type (die, type, cu);
12416
12417   /* set_die_type should be already done.  */
12418   set_descriptive_type (type, die, cu);
12419
12420   do_cleanups (back_to);
12421
12422   return type;
12423 }
12424
12425 static enum dwarf_array_dim_ordering
12426 read_array_order (struct die_info *die, struct dwarf2_cu *cu)
12427 {
12428   struct attribute *attr;
12429
12430   attr = dwarf2_attr (die, DW_AT_ordering, cu);
12431
12432   if (attr) return DW_SND (attr);
12433
12434   /* GNU F77 is a special case, as at 08/2004 array type info is the
12435      opposite order to the dwarf2 specification, but data is still
12436      laid out as per normal fortran.
12437
12438      FIXME: dsl/2004-8-20: If G77 is ever fixed, this will also need
12439      version checking.  */
12440
12441   if (cu->language == language_fortran
12442       && cu->producer && strstr (cu->producer, "GNU F77"))
12443     {
12444       return DW_ORD_row_major;
12445     }
12446
12447   switch (cu->language_defn->la_array_ordering)
12448     {
12449     case array_column_major:
12450       return DW_ORD_col_major;
12451     case array_row_major:
12452     default:
12453       return DW_ORD_row_major;
12454     };
12455 }
12456
12457 /* Extract all information from a DW_TAG_set_type DIE and put it in
12458    the DIE's type field.  */
12459
12460 static struct type *
12461 read_set_type (struct die_info *die, struct dwarf2_cu *cu)
12462 {
12463   struct type *domain_type, *set_type;
12464   struct attribute *attr;
12465
12466   domain_type = die_type (die, cu);
12467
12468   /* The die_type call above may have already set the type for this DIE.  */
12469   set_type = get_die_type (die, cu);
12470   if (set_type)
12471     return set_type;
12472
12473   set_type = create_set_type (NULL, domain_type);
12474
12475   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
12476   if (attr)
12477     TYPE_LENGTH (set_type) = DW_UNSND (attr);
12478
12479   return set_die_type (die, set_type, cu);
12480 }
12481
12482 /* A helper for read_common_block that creates a locexpr baton.
12483    SYM is the symbol which we are marking as computed.
12484    COMMON_DIE is the DIE for the common block.
12485    COMMON_LOC is the location expression attribute for the common
12486    block itself.
12487    MEMBER_LOC is the location expression attribute for the particular
12488    member of the common block that we are processing.
12489    CU is the CU from which the above come.  */
12490
12491 static void
12492 mark_common_block_symbol_computed (struct symbol *sym,
12493                                    struct die_info *common_die,
12494                                    struct attribute *common_loc,
12495                                    struct attribute *member_loc,
12496                                    struct dwarf2_cu *cu)
12497 {
12498   struct objfile *objfile = dwarf2_per_objfile->objfile;
12499   struct dwarf2_locexpr_baton *baton;
12500   gdb_byte *ptr;
12501   unsigned int cu_off;
12502   enum bfd_endian byte_order = gdbarch_byte_order (get_objfile_arch (objfile));
12503   LONGEST offset = 0;
12504
12505   gdb_assert (common_loc && member_loc);
12506   gdb_assert (attr_form_is_block (common_loc));
12507   gdb_assert (attr_form_is_block (member_loc)
12508               || attr_form_is_constant (member_loc));
12509
12510   baton = obstack_alloc (&objfile->objfile_obstack,
12511                          sizeof (struct dwarf2_locexpr_baton));
12512   baton->per_cu = cu->per_cu;
12513   gdb_assert (baton->per_cu);
12514
12515   baton->size = 5 /* DW_OP_call4 */ + 1 /* DW_OP_plus */;
12516
12517   if (attr_form_is_constant (member_loc))
12518     {
12519       offset = dwarf2_get_attr_constant_value (member_loc, 0);
12520       baton->size += 1 /* DW_OP_addr */ + cu->header.addr_size;
12521     }
12522   else
12523     baton->size += DW_BLOCK (member_loc)->size;
12524
12525   ptr = obstack_alloc (&objfile->objfile_obstack, baton->size);
12526   baton->data = ptr;
12527
12528   *ptr++ = DW_OP_call4;
12529   cu_off = common_die->offset.sect_off - cu->per_cu->offset.sect_off;
12530   store_unsigned_integer (ptr, 4, byte_order, cu_off);
12531   ptr += 4;
12532
12533   if (attr_form_is_constant (member_loc))
12534     {
12535       *ptr++ = DW_OP_addr;
12536       store_unsigned_integer (ptr, cu->header.addr_size, byte_order, offset);
12537       ptr += cu->header.addr_size;
12538     }
12539   else
12540     {
12541       /* We have to copy the data here, because DW_OP_call4 will only
12542          use a DW_AT_location attribute.  */
12543       memcpy (ptr, DW_BLOCK (member_loc)->data, DW_BLOCK (member_loc)->size);
12544       ptr += DW_BLOCK (member_loc)->size;
12545     }
12546
12547   *ptr++ = DW_OP_plus;
12548   gdb_assert (ptr - baton->data == baton->size);
12549
12550   SYMBOL_LOCATION_BATON (sym) = baton;
12551   SYMBOL_ACLASS_INDEX (sym) = dwarf2_locexpr_index;
12552 }
12553
12554 /* Create appropriate locally-scoped variables for all the
12555    DW_TAG_common_block entries.  Also create a struct common_block
12556    listing all such variables for `info common'.  COMMON_BLOCK_DOMAIN
12557    is used to sepate the common blocks name namespace from regular
12558    variable names.  */
12559
12560 static void
12561 read_common_block (struct die_info *die, struct dwarf2_cu *cu)
12562 {
12563   struct attribute *attr;
12564
12565   attr = dwarf2_attr (die, DW_AT_location, cu);
12566   if (attr)
12567     {
12568       /* Support the .debug_loc offsets.  */
12569       if (attr_form_is_block (attr))
12570         {
12571           /* Ok.  */
12572         }
12573       else if (attr_form_is_section_offset (attr))
12574         {
12575           dwarf2_complex_location_expr_complaint ();
12576           attr = NULL;
12577         }
12578       else
12579         {
12580           dwarf2_invalid_attrib_class_complaint ("DW_AT_location",
12581                                                  "common block member");
12582           attr = NULL;
12583         }
12584     }
12585
12586   if (die->child != NULL)
12587     {
12588       struct objfile *objfile = cu->objfile;
12589       struct die_info *child_die;
12590       size_t n_entries = 0, size;
12591       struct common_block *common_block;
12592       struct symbol *sym;
12593
12594       for (child_die = die->child;
12595            child_die && child_die->tag;
12596            child_die = sibling_die (child_die))
12597         ++n_entries;
12598
12599       size = (sizeof (struct common_block)
12600               + (n_entries - 1) * sizeof (struct symbol *));
12601       common_block = obstack_alloc (&objfile->objfile_obstack, size);
12602       memset (common_block->contents, 0, n_entries * sizeof (struct symbol *));
12603       common_block->n_entries = 0;
12604
12605       for (child_die = die->child;
12606            child_die && child_die->tag;
12607            child_die = sibling_die (child_die))
12608         {
12609           /* Create the symbol in the DW_TAG_common_block block in the current
12610              symbol scope.  */
12611           sym = new_symbol (child_die, NULL, cu);
12612           if (sym != NULL)
12613             {
12614               struct attribute *member_loc;
12615
12616               common_block->contents[common_block->n_entries++] = sym;
12617
12618               member_loc = dwarf2_attr (child_die, DW_AT_data_member_location,
12619                                         cu);
12620               if (member_loc)
12621                 {
12622                   /* GDB has handled this for a long time, but it is
12623                      not specified by DWARF.  It seems to have been
12624                      emitted by gfortran at least as recently as:
12625                      http://gcc.gnu.org/bugzilla/show_bug.cgi?id=23057.  */
12626                   complaint (&symfile_complaints,
12627                              _("Variable in common block has "
12628                                "DW_AT_data_member_location "
12629                                "- DIE at 0x%x [in module %s]"),
12630                              child_die->offset.sect_off, cu->objfile->name);
12631
12632                   if (attr_form_is_section_offset (member_loc))
12633                     dwarf2_complex_location_expr_complaint ();
12634                   else if (attr_form_is_constant (member_loc)
12635                            || attr_form_is_block (member_loc))
12636                     {
12637                       if (attr)
12638                         mark_common_block_symbol_computed (sym, die, attr,
12639                                                            member_loc, cu);
12640                     }
12641                   else
12642                     dwarf2_complex_location_expr_complaint ();
12643                 }
12644             }
12645         }
12646
12647       sym = new_symbol (die, objfile_type (objfile)->builtin_void, cu);
12648       SYMBOL_VALUE_COMMON_BLOCK (sym) = common_block;
12649     }
12650 }
12651
12652 /* Create a type for a C++ namespace.  */
12653
12654 static struct type *
12655 read_namespace_type (struct die_info *die, struct dwarf2_cu *cu)
12656 {
12657   struct objfile *objfile = cu->objfile;
12658   const char *previous_prefix, *name;
12659   int is_anonymous;
12660   struct type *type;
12661
12662   /* For extensions, reuse the type of the original namespace.  */
12663   if (dwarf2_attr (die, DW_AT_extension, cu) != NULL)
12664     {
12665       struct die_info *ext_die;
12666       struct dwarf2_cu *ext_cu = cu;
12667
12668       ext_die = dwarf2_extension (die, &ext_cu);
12669       type = read_type_die (ext_die, ext_cu);
12670
12671       /* EXT_CU may not be the same as CU.
12672          Ensure TYPE is recorded with CU in die_type_hash.  */
12673       return set_die_type (die, type, cu);
12674     }
12675
12676   name = namespace_name (die, &is_anonymous, cu);
12677
12678   /* Now build the name of the current namespace.  */
12679
12680   previous_prefix = determine_prefix (die, cu);
12681   if (previous_prefix[0] != '\0')
12682     name = typename_concat (&objfile->objfile_obstack,
12683                             previous_prefix, name, 0, cu);
12684
12685   /* Create the type.  */
12686   type = init_type (TYPE_CODE_NAMESPACE, 0, 0, NULL,
12687                     objfile);
12688   TYPE_NAME (type) = name;
12689   TYPE_TAG_NAME (type) = TYPE_NAME (type);
12690
12691   return set_die_type (die, type, cu);
12692 }
12693
12694 /* Read a C++ namespace.  */
12695
12696 static void
12697 read_namespace (struct die_info *die, struct dwarf2_cu *cu)
12698 {
12699   struct objfile *objfile = cu->objfile;
12700   int is_anonymous;
12701
12702   /* Add a symbol associated to this if we haven't seen the namespace
12703      before.  Also, add a using directive if it's an anonymous
12704      namespace.  */
12705
12706   if (dwarf2_attr (die, DW_AT_extension, cu) == NULL)
12707     {
12708       struct type *type;
12709
12710       type = read_type_die (die, cu);
12711       new_symbol (die, type, cu);
12712
12713       namespace_name (die, &is_anonymous, cu);
12714       if (is_anonymous)
12715         {
12716           const char *previous_prefix = determine_prefix (die, cu);
12717
12718           cp_add_using_directive (previous_prefix, TYPE_NAME (type), NULL,
12719                                   NULL, NULL, 0, &objfile->objfile_obstack);
12720         }
12721     }
12722
12723   if (die->child != NULL)
12724     {
12725       struct die_info *child_die = die->child;
12726
12727       while (child_die && child_die->tag)
12728         {
12729           process_die (child_die, cu);
12730           child_die = sibling_die (child_die);
12731         }
12732     }
12733 }
12734
12735 /* Read a Fortran module as type.  This DIE can be only a declaration used for
12736    imported module.  Still we need that type as local Fortran "use ... only"
12737    declaration imports depend on the created type in determine_prefix.  */
12738
12739 static struct type *
12740 read_module_type (struct die_info *die, struct dwarf2_cu *cu)
12741 {
12742   struct objfile *objfile = cu->objfile;
12743   const char *module_name;
12744   struct type *type;
12745
12746   module_name = dwarf2_name (die, cu);
12747   if (!module_name)
12748     complaint (&symfile_complaints,
12749                _("DW_TAG_module has no name, offset 0x%x"),
12750                die->offset.sect_off);
12751   type = init_type (TYPE_CODE_MODULE, 0, 0, module_name, objfile);
12752
12753   /* determine_prefix uses TYPE_TAG_NAME.  */
12754   TYPE_TAG_NAME (type) = TYPE_NAME (type);
12755
12756   return set_die_type (die, type, cu);
12757 }
12758
12759 /* Read a Fortran module.  */
12760
12761 static void
12762 read_module (struct die_info *die, struct dwarf2_cu *cu)
12763 {
12764   struct die_info *child_die = die->child;
12765
12766   while (child_die && child_die->tag)
12767     {
12768       process_die (child_die, cu);
12769       child_die = sibling_die (child_die);
12770     }
12771 }
12772
12773 /* Return the name of the namespace represented by DIE.  Set
12774    *IS_ANONYMOUS to tell whether or not the namespace is an anonymous
12775    namespace.  */
12776
12777 static const char *
12778 namespace_name (struct die_info *die, int *is_anonymous, struct dwarf2_cu *cu)
12779 {
12780   struct die_info *current_die;
12781   const char *name = NULL;
12782
12783   /* Loop through the extensions until we find a name.  */
12784
12785   for (current_die = die;
12786        current_die != NULL;
12787        current_die = dwarf2_extension (die, &cu))
12788     {
12789       name = dwarf2_name (current_die, cu);
12790       if (name != NULL)
12791         break;
12792     }
12793
12794   /* Is it an anonymous namespace?  */
12795
12796   *is_anonymous = (name == NULL);
12797   if (*is_anonymous)
12798     name = CP_ANONYMOUS_NAMESPACE_STR;
12799
12800   return name;
12801 }
12802
12803 /* Extract all information from a DW_TAG_pointer_type DIE and add to
12804    the user defined type vector.  */
12805
12806 static struct type *
12807 read_tag_pointer_type (struct die_info *die, struct dwarf2_cu *cu)
12808 {
12809   struct gdbarch *gdbarch = get_objfile_arch (cu->objfile);
12810   struct comp_unit_head *cu_header = &cu->header;
12811   struct type *type;
12812   struct attribute *attr_byte_size;
12813   struct attribute *attr_address_class;
12814   int byte_size, addr_class;
12815   struct type *target_type;
12816
12817   target_type = die_type (die, cu);
12818
12819   /* The die_type call above may have already set the type for this DIE.  */
12820   type = get_die_type (die, cu);
12821   if (type)
12822     return type;
12823
12824   type = lookup_pointer_type (target_type);
12825
12826   attr_byte_size = dwarf2_attr (die, DW_AT_byte_size, cu);
12827   if (attr_byte_size)
12828     byte_size = DW_UNSND (attr_byte_size);
12829   else
12830     byte_size = cu_header->addr_size;
12831
12832   attr_address_class = dwarf2_attr (die, DW_AT_address_class, cu);
12833   if (attr_address_class)
12834     addr_class = DW_UNSND (attr_address_class);
12835   else
12836     addr_class = DW_ADDR_none;
12837
12838   /* If the pointer size or address class is different than the
12839      default, create a type variant marked as such and set the
12840      length accordingly.  */
12841   if (TYPE_LENGTH (type) != byte_size || addr_class != DW_ADDR_none)
12842     {
12843       if (gdbarch_address_class_type_flags_p (gdbarch))
12844         {
12845           int type_flags;
12846
12847           type_flags = gdbarch_address_class_type_flags
12848                          (gdbarch, byte_size, addr_class);
12849           gdb_assert ((type_flags & ~TYPE_INSTANCE_FLAG_ADDRESS_CLASS_ALL)
12850                       == 0);
12851           type = make_type_with_address_space (type, type_flags);
12852         }
12853       else if (TYPE_LENGTH (type) != byte_size)
12854         {
12855           complaint (&symfile_complaints,
12856                      _("invalid pointer size %d"), byte_size);
12857         }
12858       else
12859         {
12860           /* Should we also complain about unhandled address classes?  */
12861         }
12862     }
12863
12864   TYPE_LENGTH (type) = byte_size;
12865   return set_die_type (die, type, cu);
12866 }
12867
12868 /* Extract all information from a DW_TAG_ptr_to_member_type DIE and add to
12869    the user defined type vector.  */
12870
12871 static struct type *
12872 read_tag_ptr_to_member_type (struct die_info *die, struct dwarf2_cu *cu)
12873 {
12874   struct type *type;
12875   struct type *to_type;
12876   struct type *domain;
12877
12878   to_type = die_type (die, cu);
12879   domain = die_containing_type (die, cu);
12880
12881   /* The calls above may have already set the type for this DIE.  */
12882   type = get_die_type (die, cu);
12883   if (type)
12884     return type;
12885
12886   if (TYPE_CODE (check_typedef (to_type)) == TYPE_CODE_METHOD)
12887     type = lookup_methodptr_type (to_type);
12888   else if (TYPE_CODE (check_typedef (to_type)) == TYPE_CODE_FUNC)
12889     {
12890       struct type *new_type = alloc_type (cu->objfile);
12891
12892       smash_to_method_type (new_type, domain, TYPE_TARGET_TYPE (to_type),
12893                             TYPE_FIELDS (to_type), TYPE_NFIELDS (to_type),
12894                             TYPE_VARARGS (to_type));
12895       type = lookup_methodptr_type (new_type);
12896     }
12897   else
12898     type = lookup_memberptr_type (to_type, domain);
12899
12900   return set_die_type (die, type, cu);
12901 }
12902
12903 /* Extract all information from a DW_TAG_reference_type DIE and add to
12904    the user defined type vector.  */
12905
12906 static struct type *
12907 read_tag_reference_type (struct die_info *die, struct dwarf2_cu *cu)
12908 {
12909   struct comp_unit_head *cu_header = &cu->header;
12910   struct type *type, *target_type;
12911   struct attribute *attr;
12912
12913   target_type = die_type (die, cu);
12914
12915   /* The die_type call above may have already set the type for this DIE.  */
12916   type = get_die_type (die, cu);
12917   if (type)
12918     return type;
12919
12920   type = lookup_reference_type (target_type);
12921   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
12922   if (attr)
12923     {
12924       TYPE_LENGTH (type) = DW_UNSND (attr);
12925     }
12926   else
12927     {
12928       TYPE_LENGTH (type) = cu_header->addr_size;
12929     }
12930   return set_die_type (die, type, cu);
12931 }
12932
12933 static struct type *
12934 read_tag_const_type (struct die_info *die, struct dwarf2_cu *cu)
12935 {
12936   struct type *base_type, *cv_type;
12937
12938   base_type = die_type (die, cu);
12939
12940   /* The die_type call above may have already set the type for this DIE.  */
12941   cv_type = get_die_type (die, cu);
12942   if (cv_type)
12943     return cv_type;
12944
12945   /* In case the const qualifier is applied to an array type, the element type
12946      is so qualified, not the array type (section 6.7.3 of C99).  */
12947   if (TYPE_CODE (base_type) == TYPE_CODE_ARRAY)
12948     {
12949       struct type *el_type, *inner_array;
12950
12951       base_type = copy_type (base_type);
12952       inner_array = base_type;
12953
12954       while (TYPE_CODE (TYPE_TARGET_TYPE (inner_array)) == TYPE_CODE_ARRAY)
12955         {
12956           TYPE_TARGET_TYPE (inner_array) =
12957             copy_type (TYPE_TARGET_TYPE (inner_array));
12958           inner_array = TYPE_TARGET_TYPE (inner_array);
12959         }
12960
12961       el_type = TYPE_TARGET_TYPE (inner_array);
12962       TYPE_TARGET_TYPE (inner_array) =
12963         make_cv_type (1, TYPE_VOLATILE (el_type), el_type, NULL);
12964
12965       return set_die_type (die, base_type, cu);
12966     }
12967
12968   cv_type = make_cv_type (1, TYPE_VOLATILE (base_type), base_type, 0);
12969   return set_die_type (die, cv_type, cu);
12970 }
12971
12972 static struct type *
12973 read_tag_volatile_type (struct die_info *die, struct dwarf2_cu *cu)
12974 {
12975   struct type *base_type, *cv_type;
12976
12977   base_type = die_type (die, cu);
12978
12979   /* The die_type call above may have already set the type for this DIE.  */
12980   cv_type = get_die_type (die, cu);
12981   if (cv_type)
12982     return cv_type;
12983
12984   cv_type = make_cv_type (TYPE_CONST (base_type), 1, base_type, 0);
12985   return set_die_type (die, cv_type, cu);
12986 }
12987
12988 /* Handle DW_TAG_restrict_type.  */
12989
12990 static struct type *
12991 read_tag_restrict_type (struct die_info *die, struct dwarf2_cu *cu)
12992 {
12993   struct type *base_type, *cv_type;
12994
12995   base_type = die_type (die, cu);
12996
12997   /* The die_type call above may have already set the type for this DIE.  */
12998   cv_type = get_die_type (die, cu);
12999   if (cv_type)
13000     return cv_type;
13001
13002   cv_type = make_restrict_type (base_type);
13003   return set_die_type (die, cv_type, cu);
13004 }
13005
13006 /* Extract all information from a DW_TAG_string_type DIE and add to
13007    the user defined type vector.  It isn't really a user defined type,
13008    but it behaves like one, with other DIE's using an AT_user_def_type
13009    attribute to reference it.  */
13010
13011 static struct type *
13012 read_tag_string_type (struct die_info *die, struct dwarf2_cu *cu)
13013 {
13014   struct objfile *objfile = cu->objfile;
13015   struct gdbarch *gdbarch = get_objfile_arch (objfile);
13016   struct type *type, *range_type, *index_type, *char_type;
13017   struct attribute *attr;
13018   unsigned int length;
13019
13020   attr = dwarf2_attr (die, DW_AT_string_length, cu);
13021   if (attr)
13022     {
13023       length = DW_UNSND (attr);
13024     }
13025   else
13026     {
13027       /* Check for the DW_AT_byte_size attribute.  */
13028       attr = dwarf2_attr (die, DW_AT_byte_size, cu);
13029       if (attr)
13030         {
13031           length = DW_UNSND (attr);
13032         }
13033       else
13034         {
13035           length = 1;
13036         }
13037     }
13038
13039   index_type = objfile_type (objfile)->builtin_int;
13040   range_type = create_range_type (NULL, index_type, 1, length);
13041   char_type = language_string_char_type (cu->language_defn, gdbarch);
13042   type = create_string_type (NULL, char_type, range_type);
13043
13044   return set_die_type (die, type, cu);
13045 }
13046
13047 /* Assuming that DIE corresponds to a function, returns nonzero
13048    if the function is prototyped.  */
13049
13050 static int
13051 prototyped_function_p (struct die_info *die, struct dwarf2_cu *cu)
13052 {
13053   struct attribute *attr;
13054
13055   attr = dwarf2_attr (die, DW_AT_prototyped, cu);
13056   if (attr && (DW_UNSND (attr) != 0))
13057     return 1;
13058
13059   /* The DWARF standard implies that the DW_AT_prototyped attribute
13060      is only meaninful for C, but the concept also extends to other
13061      languages that allow unprototyped functions (Eg: Objective C).
13062      For all other languages, assume that functions are always
13063      prototyped.  */
13064   if (cu->language != language_c
13065       && cu->language != language_objc
13066       && cu->language != language_opencl)
13067     return 1;
13068
13069   /* RealView does not emit DW_AT_prototyped.  We can not distinguish
13070      prototyped and unprototyped functions; default to prototyped,
13071      since that is more common in modern code (and RealView warns
13072      about unprototyped functions).  */
13073   if (producer_is_realview (cu->producer))
13074     return 1;
13075
13076   return 0;
13077 }
13078
13079 /* Handle DIES due to C code like:
13080
13081    struct foo
13082    {
13083    int (*funcp)(int a, long l);
13084    int b;
13085    };
13086
13087    ('funcp' generates a DW_TAG_subroutine_type DIE).  */
13088
13089 static struct type *
13090 read_subroutine_type (struct die_info *die, struct dwarf2_cu *cu)
13091 {
13092   struct objfile *objfile = cu->objfile;
13093   struct type *type;            /* Type that this function returns.  */
13094   struct type *ftype;           /* Function that returns above type.  */
13095   struct attribute *attr;
13096
13097   type = die_type (die, cu);
13098
13099   /* The die_type call above may have already set the type for this DIE.  */
13100   ftype = get_die_type (die, cu);
13101   if (ftype)
13102     return ftype;
13103
13104   ftype = lookup_function_type (type);
13105
13106   if (prototyped_function_p (die, cu))
13107     TYPE_PROTOTYPED (ftype) = 1;
13108
13109   /* Store the calling convention in the type if it's available in
13110      the subroutine die.  Otherwise set the calling convention to
13111      the default value DW_CC_normal.  */
13112   attr = dwarf2_attr (die, DW_AT_calling_convention, cu);
13113   if (attr)
13114     TYPE_CALLING_CONVENTION (ftype) = DW_UNSND (attr);
13115   else if (cu->producer && strstr (cu->producer, "IBM XL C for OpenCL"))
13116     TYPE_CALLING_CONVENTION (ftype) = DW_CC_GDB_IBM_OpenCL;
13117   else
13118     TYPE_CALLING_CONVENTION (ftype) = DW_CC_normal;
13119
13120   /* We need to add the subroutine type to the die immediately so
13121      we don't infinitely recurse when dealing with parameters
13122      declared as the same subroutine type.  */
13123   set_die_type (die, ftype, cu);
13124
13125   if (die->child != NULL)
13126     {
13127       struct type *void_type = objfile_type (objfile)->builtin_void;
13128       struct die_info *child_die;
13129       int nparams, iparams;
13130
13131       /* Count the number of parameters.
13132          FIXME: GDB currently ignores vararg functions, but knows about
13133          vararg member functions.  */
13134       nparams = 0;
13135       child_die = die->child;
13136       while (child_die && child_die->tag)
13137         {
13138           if (child_die->tag == DW_TAG_formal_parameter)
13139             nparams++;
13140           else if (child_die->tag == DW_TAG_unspecified_parameters)
13141             TYPE_VARARGS (ftype) = 1;
13142           child_die = sibling_die (child_die);
13143         }
13144
13145       /* Allocate storage for parameters and fill them in.  */
13146       TYPE_NFIELDS (ftype) = nparams;
13147       TYPE_FIELDS (ftype) = (struct field *)
13148         TYPE_ZALLOC (ftype, nparams * sizeof (struct field));
13149
13150       /* TYPE_FIELD_TYPE must never be NULL.  Pre-fill the array to ensure it
13151          even if we error out during the parameters reading below.  */
13152       for (iparams = 0; iparams < nparams; iparams++)
13153         TYPE_FIELD_TYPE (ftype, iparams) = void_type;
13154
13155       iparams = 0;
13156       child_die = die->child;
13157       while (child_die && child_die->tag)
13158         {
13159           if (child_die->tag == DW_TAG_formal_parameter)
13160             {
13161               struct type *arg_type;
13162
13163               /* DWARF version 2 has no clean way to discern C++
13164                  static and non-static member functions.  G++ helps
13165                  GDB by marking the first parameter for non-static
13166                  member functions (which is the this pointer) as
13167                  artificial.  We pass this information to
13168                  dwarf2_add_member_fn via TYPE_FIELD_ARTIFICIAL.
13169
13170                  DWARF version 3 added DW_AT_object_pointer, which GCC
13171                  4.5 does not yet generate.  */
13172               attr = dwarf2_attr (child_die, DW_AT_artificial, cu);
13173               if (attr)
13174                 TYPE_FIELD_ARTIFICIAL (ftype, iparams) = DW_UNSND (attr);
13175               else
13176                 {
13177                   TYPE_FIELD_ARTIFICIAL (ftype, iparams) = 0;
13178
13179                   /* GCC/43521: In java, the formal parameter
13180                      "this" is sometimes not marked with DW_AT_artificial.  */
13181                   if (cu->language == language_java)
13182                     {
13183                       const char *name = dwarf2_name (child_die, cu);
13184
13185                       if (name && !strcmp (name, "this"))
13186                         TYPE_FIELD_ARTIFICIAL (ftype, iparams) = 1;
13187                     }
13188                 }
13189               arg_type = die_type (child_die, cu);
13190
13191               /* RealView does not mark THIS as const, which the testsuite
13192                  expects.  GCC marks THIS as const in method definitions,
13193                  but not in the class specifications (GCC PR 43053).  */
13194               if (cu->language == language_cplus && !TYPE_CONST (arg_type)
13195                   && TYPE_FIELD_ARTIFICIAL (ftype, iparams))
13196                 {
13197                   int is_this = 0;
13198                   struct dwarf2_cu *arg_cu = cu;
13199                   const char *name = dwarf2_name (child_die, cu);
13200
13201                   attr = dwarf2_attr (die, DW_AT_object_pointer, cu);
13202                   if (attr)
13203                     {
13204                       /* If the compiler emits this, use it.  */
13205                       if (follow_die_ref (die, attr, &arg_cu) == child_die)
13206                         is_this = 1;
13207                     }
13208                   else if (name && strcmp (name, "this") == 0)
13209                     /* Function definitions will have the argument names.  */
13210                     is_this = 1;
13211                   else if (name == NULL && iparams == 0)
13212                     /* Declarations may not have the names, so like
13213                        elsewhere in GDB, assume an artificial first
13214                        argument is "this".  */
13215                     is_this = 1;
13216
13217                   if (is_this)
13218                     arg_type = make_cv_type (1, TYPE_VOLATILE (arg_type),
13219                                              arg_type, 0);
13220                 }
13221
13222               TYPE_FIELD_TYPE (ftype, iparams) = arg_type;
13223               iparams++;
13224             }
13225           child_die = sibling_die (child_die);
13226         }
13227     }
13228
13229   return ftype;
13230 }
13231
13232 static struct type *
13233 read_typedef (struct die_info *die, struct dwarf2_cu *cu)
13234 {
13235   struct objfile *objfile = cu->objfile;
13236   const char *name = NULL;
13237   struct type *this_type, *target_type;
13238
13239   name = dwarf2_full_name (NULL, die, cu);
13240   this_type = init_type (TYPE_CODE_TYPEDEF, 0,
13241                          TYPE_FLAG_TARGET_STUB, NULL, objfile);
13242   TYPE_NAME (this_type) = name;
13243   set_die_type (die, this_type, cu);
13244   target_type = die_type (die, cu);
13245   if (target_type != this_type)
13246     TYPE_TARGET_TYPE (this_type) = target_type;
13247   else
13248     {
13249       /* Self-referential typedefs are, it seems, not allowed by the DWARF
13250          spec and cause infinite loops in GDB.  */
13251       complaint (&symfile_complaints,
13252                  _("Self-referential DW_TAG_typedef "
13253                    "- DIE at 0x%x [in module %s]"),
13254                  die->offset.sect_off, objfile->name);
13255       TYPE_TARGET_TYPE (this_type) = NULL;
13256     }
13257   return this_type;
13258 }
13259
13260 /* Find a representation of a given base type and install
13261    it in the TYPE field of the die.  */
13262
13263 static struct type *
13264 read_base_type (struct die_info *die, struct dwarf2_cu *cu)
13265 {
13266   struct objfile *objfile = cu->objfile;
13267   struct type *type;
13268   struct attribute *attr;
13269   int encoding = 0, size = 0;
13270   const char *name;
13271   enum type_code code = TYPE_CODE_INT;
13272   int type_flags = 0;
13273   struct type *target_type = NULL;
13274
13275   attr = dwarf2_attr (die, DW_AT_encoding, cu);
13276   if (attr)
13277     {
13278       encoding = DW_UNSND (attr);
13279     }
13280   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
13281   if (attr)
13282     {
13283       size = DW_UNSND (attr);
13284     }
13285   name = dwarf2_name (die, cu);
13286   if (!name)
13287     {
13288       complaint (&symfile_complaints,
13289                  _("DW_AT_name missing from DW_TAG_base_type"));
13290     }
13291
13292   switch (encoding)
13293     {
13294       case DW_ATE_address:
13295         /* Turn DW_ATE_address into a void * pointer.  */
13296         code = TYPE_CODE_PTR;
13297         type_flags |= TYPE_FLAG_UNSIGNED;
13298         target_type = init_type (TYPE_CODE_VOID, 1, 0, NULL, objfile);
13299         break;
13300       case DW_ATE_boolean:
13301         code = TYPE_CODE_BOOL;
13302         type_flags |= TYPE_FLAG_UNSIGNED;
13303         break;
13304       case DW_ATE_complex_float:
13305         code = TYPE_CODE_COMPLEX;
13306         target_type = init_type (TYPE_CODE_FLT, size / 2, 0, NULL, objfile);
13307         break;
13308       case DW_ATE_decimal_float:
13309         code = TYPE_CODE_DECFLOAT;
13310         break;
13311       case DW_ATE_float:
13312         code = TYPE_CODE_FLT;
13313         break;
13314       case DW_ATE_signed:
13315         break;
13316       case DW_ATE_unsigned:
13317         type_flags |= TYPE_FLAG_UNSIGNED;
13318         if (cu->language == language_fortran
13319             && name
13320             && strncmp (name, "character(", sizeof ("character(") - 1) == 0)
13321           code = TYPE_CODE_CHAR;
13322         break;
13323       case DW_ATE_signed_char:
13324         if (cu->language == language_ada || cu->language == language_m2
13325             || cu->language == language_pascal
13326             || cu->language == language_fortran)
13327           code = TYPE_CODE_CHAR;
13328         break;
13329       case DW_ATE_unsigned_char:
13330         if (cu->language == language_ada || cu->language == language_m2
13331             || cu->language == language_pascal
13332             || cu->language == language_fortran)
13333           code = TYPE_CODE_CHAR;
13334         type_flags |= TYPE_FLAG_UNSIGNED;
13335         break;
13336       case DW_ATE_UTF:
13337         /* We just treat this as an integer and then recognize the
13338            type by name elsewhere.  */
13339         break;
13340
13341       default:
13342         complaint (&symfile_complaints, _("unsupported DW_AT_encoding: '%s'"),
13343                    dwarf_type_encoding_name (encoding));
13344         break;
13345     }
13346
13347   type = init_type (code, size, type_flags, NULL, objfile);
13348   TYPE_NAME (type) = name;
13349   TYPE_TARGET_TYPE (type) = target_type;
13350
13351   if (name && strcmp (name, "char") == 0)
13352     TYPE_NOSIGN (type) = 1;
13353
13354   return set_die_type (die, type, cu);
13355 }
13356
13357 /* Read the given DW_AT_subrange DIE.  */
13358
13359 static struct type *
13360 read_subrange_type (struct die_info *die, struct dwarf2_cu *cu)
13361 {
13362   struct type *base_type, *orig_base_type;
13363   struct type *range_type;
13364   struct attribute *attr;
13365   LONGEST low, high;
13366   int low_default_is_valid;
13367   const char *name;
13368   LONGEST negative_mask;
13369
13370   orig_base_type = die_type (die, cu);
13371   /* If ORIG_BASE_TYPE is a typedef, it will not be TYPE_UNSIGNED,
13372      whereas the real type might be.  So, we use ORIG_BASE_TYPE when
13373      creating the range type, but we use the result of check_typedef
13374      when examining properties of the type.  */
13375   base_type = check_typedef (orig_base_type);
13376
13377   /* The die_type call above may have already set the type for this DIE.  */
13378   range_type = get_die_type (die, cu);
13379   if (range_type)
13380     return range_type;
13381
13382   /* Set LOW_DEFAULT_IS_VALID if current language and DWARF version allow
13383      omitting DW_AT_lower_bound.  */
13384   switch (cu->language)
13385     {
13386     case language_c:
13387     case language_cplus:
13388       low = 0;
13389       low_default_is_valid = 1;
13390       break;
13391     case language_fortran:
13392       low = 1;
13393       low_default_is_valid = 1;
13394       break;
13395     case language_d:
13396     case language_java:
13397     case language_objc:
13398       low = 0;
13399       low_default_is_valid = (cu->header.version >= 4);
13400       break;
13401     case language_ada:
13402     case language_m2:
13403     case language_pascal:
13404       low = 1;
13405       low_default_is_valid = (cu->header.version >= 4);
13406       break;
13407     default:
13408       low = 0;
13409       low_default_is_valid = 0;
13410       break;
13411     }
13412
13413   /* FIXME: For variable sized arrays either of these could be
13414      a variable rather than a constant value.  We'll allow it,
13415      but we don't know how to handle it.  */
13416   attr = dwarf2_attr (die, DW_AT_lower_bound, cu);
13417   if (attr)
13418     low = dwarf2_get_attr_constant_value (attr, low);
13419   else if (!low_default_is_valid)
13420     complaint (&symfile_complaints, _("Missing DW_AT_lower_bound "
13421                                       "- DIE at 0x%x [in module %s]"),
13422                die->offset.sect_off, cu->objfile->name);
13423
13424   attr = dwarf2_attr (die, DW_AT_upper_bound, cu);
13425   if (attr)
13426     {
13427       if (attr_form_is_block (attr) || attr_form_is_ref (attr))
13428         {
13429           /* GCC encodes arrays with unspecified or dynamic length
13430              with a DW_FORM_block1 attribute or a reference attribute.
13431              FIXME: GDB does not yet know how to handle dynamic
13432              arrays properly, treat them as arrays with unspecified
13433              length for now.
13434
13435              FIXME: jimb/2003-09-22: GDB does not really know
13436              how to handle arrays of unspecified length
13437              either; we just represent them as zero-length
13438              arrays.  Choose an appropriate upper bound given
13439              the lower bound we've computed above.  */
13440           high = low - 1;
13441         }
13442       else
13443         high = dwarf2_get_attr_constant_value (attr, 1);
13444     }
13445   else
13446     {
13447       attr = dwarf2_attr (die, DW_AT_count, cu);
13448       if (attr)
13449         {
13450           int count = dwarf2_get_attr_constant_value (attr, 1);
13451           high = low + count - 1;
13452         }
13453       else
13454         {
13455           /* Unspecified array length.  */
13456           high = low - 1;
13457         }
13458     }
13459
13460   /* Dwarf-2 specifications explicitly allows to create subrange types
13461      without specifying a base type.
13462      In that case, the base type must be set to the type of
13463      the lower bound, upper bound or count, in that order, if any of these
13464      three attributes references an object that has a type.
13465      If no base type is found, the Dwarf-2 specifications say that
13466      a signed integer type of size equal to the size of an address should
13467      be used.
13468      For the following C code: `extern char gdb_int [];'
13469      GCC produces an empty range DIE.
13470      FIXME: muller/2010-05-28: Possible references to object for low bound,
13471      high bound or count are not yet handled by this code.  */
13472   if (TYPE_CODE (base_type) == TYPE_CODE_VOID)
13473     {
13474       struct objfile *objfile = cu->objfile;
13475       struct gdbarch *gdbarch = get_objfile_arch (objfile);
13476       int addr_size = gdbarch_addr_bit (gdbarch) /8;
13477       struct type *int_type = objfile_type (objfile)->builtin_int;
13478
13479       /* Test "int", "long int", and "long long int" objfile types,
13480          and select the first one having a size above or equal to the
13481          architecture address size.  */
13482       if (int_type && TYPE_LENGTH (int_type) >= addr_size)
13483         base_type = int_type;
13484       else
13485         {
13486           int_type = objfile_type (objfile)->builtin_long;
13487           if (int_type && TYPE_LENGTH (int_type) >= addr_size)
13488             base_type = int_type;
13489           else
13490             {
13491               int_type = objfile_type (objfile)->builtin_long_long;
13492               if (int_type && TYPE_LENGTH (int_type) >= addr_size)
13493                 base_type = int_type;
13494             }
13495         }
13496     }
13497
13498   negative_mask =
13499     (LONGEST) -1 << (TYPE_LENGTH (base_type) * TARGET_CHAR_BIT - 1);
13500   if (!TYPE_UNSIGNED (base_type) && (low & negative_mask))
13501     low |= negative_mask;
13502   if (!TYPE_UNSIGNED (base_type) && (high & negative_mask))
13503     high |= negative_mask;
13504
13505   range_type = create_range_type (NULL, orig_base_type, low, high);
13506
13507   /* Mark arrays with dynamic length at least as an array of unspecified
13508      length.  GDB could check the boundary but before it gets implemented at
13509      least allow accessing the array elements.  */
13510   if (attr && attr_form_is_block (attr))
13511     TYPE_HIGH_BOUND_UNDEFINED (range_type) = 1;
13512
13513   /* Ada expects an empty array on no boundary attributes.  */
13514   if (attr == NULL && cu->language != language_ada)
13515     TYPE_HIGH_BOUND_UNDEFINED (range_type) = 1;
13516
13517   name = dwarf2_name (die, cu);
13518   if (name)
13519     TYPE_NAME (range_type) = name;
13520
13521   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
13522   if (attr)
13523     TYPE_LENGTH (range_type) = DW_UNSND (attr);
13524
13525   set_die_type (die, range_type, cu);
13526
13527   /* set_die_type should be already done.  */
13528   set_descriptive_type (range_type, die, cu);
13529
13530   return range_type;
13531 }
13532
13533 static struct type *
13534 read_unspecified_type (struct die_info *die, struct dwarf2_cu *cu)
13535 {
13536   struct type *type;
13537
13538   /* For now, we only support the C meaning of an unspecified type: void.  */
13539
13540   type = init_type (TYPE_CODE_VOID, 0, 0, NULL, cu->objfile);
13541   TYPE_NAME (type) = dwarf2_name (die, cu);
13542
13543   return set_die_type (die, type, cu);
13544 }
13545
13546 /* Read a single die and all its descendents.  Set the die's sibling
13547    field to NULL; set other fields in the die correctly, and set all
13548    of the descendents' fields correctly.  Set *NEW_INFO_PTR to the
13549    location of the info_ptr after reading all of those dies.  PARENT
13550    is the parent of the die in question.  */
13551
13552 static struct die_info *
13553 read_die_and_children (const struct die_reader_specs *reader,
13554                        const gdb_byte *info_ptr,
13555                        const gdb_byte **new_info_ptr,
13556                        struct die_info *parent)
13557 {
13558   struct die_info *die;
13559   const gdb_byte *cur_ptr;
13560   int has_children;
13561
13562   cur_ptr = read_full_die_1 (reader, &die, info_ptr, &has_children, 0);
13563   if (die == NULL)
13564     {
13565       *new_info_ptr = cur_ptr;
13566       return NULL;
13567     }
13568   store_in_ref_table (die, reader->cu);
13569
13570   if (has_children)
13571     die->child = read_die_and_siblings_1 (reader, cur_ptr, new_info_ptr, die);
13572   else
13573     {
13574       die->child = NULL;
13575       *new_info_ptr = cur_ptr;
13576     }
13577
13578   die->sibling = NULL;
13579   die->parent = parent;
13580   return die;
13581 }
13582
13583 /* Read a die, all of its descendents, and all of its siblings; set
13584    all of the fields of all of the dies correctly.  Arguments are as
13585    in read_die_and_children.  */
13586
13587 static struct die_info *
13588 read_die_and_siblings_1 (const struct die_reader_specs *reader,
13589                          const gdb_byte *info_ptr,
13590                          const gdb_byte **new_info_ptr,
13591                          struct die_info *parent)
13592 {
13593   struct die_info *first_die, *last_sibling;
13594   const gdb_byte *cur_ptr;
13595
13596   cur_ptr = info_ptr;
13597   first_die = last_sibling = NULL;
13598
13599   while (1)
13600     {
13601       struct die_info *die
13602         = read_die_and_children (reader, cur_ptr, &cur_ptr, parent);
13603
13604       if (die == NULL)
13605         {
13606           *new_info_ptr = cur_ptr;
13607           return first_die;
13608         }
13609
13610       if (!first_die)
13611         first_die = die;
13612       else
13613         last_sibling->sibling = die;
13614
13615       last_sibling = die;
13616     }
13617 }
13618
13619 /* Read a die, all of its descendents, and all of its siblings; set
13620    all of the fields of all of the dies correctly.  Arguments are as
13621    in read_die_and_children.
13622    This the main entry point for reading a DIE and all its children.  */
13623
13624 static struct die_info *
13625 read_die_and_siblings (const struct die_reader_specs *reader,
13626                        const gdb_byte *info_ptr,
13627                        const gdb_byte **new_info_ptr,
13628                        struct die_info *parent)
13629 {
13630   struct die_info *die = read_die_and_siblings_1 (reader, info_ptr,
13631                                                   new_info_ptr, parent);
13632
13633   if (dwarf2_die_debug)
13634     {
13635       fprintf_unfiltered (gdb_stdlog,
13636                           "Read die from %s@0x%x of %s:\n",
13637                           bfd_section_name (reader->abfd,
13638                                             reader->die_section->asection),
13639                           (unsigned) (info_ptr - reader->die_section->buffer),
13640                           bfd_get_filename (reader->abfd));
13641       dump_die (die, dwarf2_die_debug);
13642     }
13643
13644   return die;
13645 }
13646
13647 /* Read a die and all its attributes, leave space for NUM_EXTRA_ATTRS
13648    attributes.
13649    The caller is responsible for filling in the extra attributes
13650    and updating (*DIEP)->num_attrs.
13651    Set DIEP to point to a newly allocated die with its information,
13652    except for its child, sibling, and parent fields.
13653    Set HAS_CHILDREN to tell whether the die has children or not.  */
13654
13655 static const gdb_byte *
13656 read_full_die_1 (const struct die_reader_specs *reader,
13657                  struct die_info **diep, const gdb_byte *info_ptr,
13658                  int *has_children, int num_extra_attrs)
13659 {
13660   unsigned int abbrev_number, bytes_read, i;
13661   sect_offset offset;
13662   struct abbrev_info *abbrev;
13663   struct die_info *die;
13664   struct dwarf2_cu *cu = reader->cu;
13665   bfd *abfd = reader->abfd;
13666
13667   offset.sect_off = info_ptr - reader->buffer;
13668   abbrev_number = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
13669   info_ptr += bytes_read;
13670   if (!abbrev_number)
13671     {
13672       *diep = NULL;
13673       *has_children = 0;
13674       return info_ptr;
13675     }
13676
13677   abbrev = abbrev_table_lookup_abbrev (cu->abbrev_table, abbrev_number);
13678   if (!abbrev)
13679     error (_("Dwarf Error: could not find abbrev number %d [in module %s]"),
13680            abbrev_number,
13681            bfd_get_filename (abfd));
13682
13683   die = dwarf_alloc_die (cu, abbrev->num_attrs + num_extra_attrs);
13684   die->offset = offset;
13685   die->tag = abbrev->tag;
13686   die->abbrev = abbrev_number;
13687
13688   /* Make the result usable.
13689      The caller needs to update num_attrs after adding the extra
13690      attributes.  */
13691   die->num_attrs = abbrev->num_attrs;
13692
13693   for (i = 0; i < abbrev->num_attrs; ++i)
13694     info_ptr = read_attribute (reader, &die->attrs[i], &abbrev->attrs[i],
13695                                info_ptr);
13696
13697   *diep = die;
13698   *has_children = abbrev->has_children;
13699   return info_ptr;
13700 }
13701
13702 /* Read a die and all its attributes.
13703    Set DIEP to point to a newly allocated die with its information,
13704    except for its child, sibling, and parent fields.
13705    Set HAS_CHILDREN to tell whether the die has children or not.  */
13706
13707 static const gdb_byte *
13708 read_full_die (const struct die_reader_specs *reader,
13709                struct die_info **diep, const gdb_byte *info_ptr,
13710                int *has_children)
13711 {
13712   const gdb_byte *result;
13713
13714   result = read_full_die_1 (reader, diep, info_ptr, has_children, 0);
13715
13716   if (dwarf2_die_debug)
13717     {
13718       fprintf_unfiltered (gdb_stdlog,
13719                           "Read die from %s@0x%x of %s:\n",
13720                           bfd_section_name (reader->abfd,
13721                                             reader->die_section->asection),
13722                           (unsigned) (info_ptr - reader->die_section->buffer),
13723                           bfd_get_filename (reader->abfd));
13724       dump_die (*diep, dwarf2_die_debug);
13725     }
13726
13727   return result;
13728 }
13729 \f
13730 /* Abbreviation tables.
13731
13732    In DWARF version 2, the description of the debugging information is
13733    stored in a separate .debug_abbrev section.  Before we read any
13734    dies from a section we read in all abbreviations and install them
13735    in a hash table.  */
13736
13737 /* Allocate space for a struct abbrev_info object in ABBREV_TABLE.  */
13738
13739 static struct abbrev_info *
13740 abbrev_table_alloc_abbrev (struct abbrev_table *abbrev_table)
13741 {
13742   struct abbrev_info *abbrev;
13743
13744   abbrev = (struct abbrev_info *)
13745     obstack_alloc (&abbrev_table->abbrev_obstack, sizeof (struct abbrev_info));
13746   memset (abbrev, 0, sizeof (struct abbrev_info));
13747   return abbrev;
13748 }
13749
13750 /* Add an abbreviation to the table.  */
13751
13752 static void
13753 abbrev_table_add_abbrev (struct abbrev_table *abbrev_table,
13754                          unsigned int abbrev_number,
13755                          struct abbrev_info *abbrev)
13756 {
13757   unsigned int hash_number;
13758
13759   hash_number = abbrev_number % ABBREV_HASH_SIZE;
13760   abbrev->next = abbrev_table->abbrevs[hash_number];
13761   abbrev_table->abbrevs[hash_number] = abbrev;
13762 }
13763
13764 /* Look up an abbrev in the table.
13765    Returns NULL if the abbrev is not found.  */
13766
13767 static struct abbrev_info *
13768 abbrev_table_lookup_abbrev (const struct abbrev_table *abbrev_table,
13769                             unsigned int abbrev_number)
13770 {
13771   unsigned int hash_number;
13772   struct abbrev_info *abbrev;
13773
13774   hash_number = abbrev_number % ABBREV_HASH_SIZE;
13775   abbrev = abbrev_table->abbrevs[hash_number];
13776
13777   while (abbrev)
13778     {
13779       if (abbrev->number == abbrev_number)
13780         return abbrev;
13781       abbrev = abbrev->next;
13782     }
13783   return NULL;
13784 }
13785
13786 /* Read in an abbrev table.  */
13787
13788 static struct abbrev_table *
13789 abbrev_table_read_table (struct dwarf2_section_info *section,
13790                          sect_offset offset)
13791 {
13792   struct objfile *objfile = dwarf2_per_objfile->objfile;
13793   bfd *abfd = section->asection->owner;
13794   struct abbrev_table *abbrev_table;
13795   const gdb_byte *abbrev_ptr;
13796   struct abbrev_info *cur_abbrev;
13797   unsigned int abbrev_number, bytes_read, abbrev_name;
13798   unsigned int abbrev_form;
13799   struct attr_abbrev *cur_attrs;
13800   unsigned int allocated_attrs;
13801
13802   abbrev_table = XMALLOC (struct abbrev_table);
13803   abbrev_table->offset = offset;
13804   obstack_init (&abbrev_table->abbrev_obstack);
13805   abbrev_table->abbrevs = obstack_alloc (&abbrev_table->abbrev_obstack,
13806                                          (ABBREV_HASH_SIZE
13807                                           * sizeof (struct abbrev_info *)));
13808   memset (abbrev_table->abbrevs, 0,
13809           ABBREV_HASH_SIZE * sizeof (struct abbrev_info *));
13810
13811   dwarf2_read_section (objfile, section);
13812   abbrev_ptr = section->buffer + offset.sect_off;
13813   abbrev_number = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
13814   abbrev_ptr += bytes_read;
13815
13816   allocated_attrs = ATTR_ALLOC_CHUNK;
13817   cur_attrs = xmalloc (allocated_attrs * sizeof (struct attr_abbrev));
13818
13819   /* Loop until we reach an abbrev number of 0.  */
13820   while (abbrev_number)
13821     {
13822       cur_abbrev = abbrev_table_alloc_abbrev (abbrev_table);
13823
13824       /* read in abbrev header */
13825       cur_abbrev->number = abbrev_number;
13826       cur_abbrev->tag = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
13827       abbrev_ptr += bytes_read;
13828       cur_abbrev->has_children = read_1_byte (abfd, abbrev_ptr);
13829       abbrev_ptr += 1;
13830
13831       /* now read in declarations */
13832       abbrev_name = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
13833       abbrev_ptr += bytes_read;
13834       abbrev_form = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
13835       abbrev_ptr += bytes_read;
13836       while (abbrev_name)
13837         {
13838           if (cur_abbrev->num_attrs == allocated_attrs)
13839             {
13840               allocated_attrs += ATTR_ALLOC_CHUNK;
13841               cur_attrs
13842                 = xrealloc (cur_attrs, (allocated_attrs
13843                                         * sizeof (struct attr_abbrev)));
13844             }
13845
13846           cur_attrs[cur_abbrev->num_attrs].name = abbrev_name;
13847           cur_attrs[cur_abbrev->num_attrs++].form = abbrev_form;
13848           abbrev_name = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
13849           abbrev_ptr += bytes_read;
13850           abbrev_form = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
13851           abbrev_ptr += bytes_read;
13852         }
13853
13854       cur_abbrev->attrs = obstack_alloc (&abbrev_table->abbrev_obstack,
13855                                          (cur_abbrev->num_attrs
13856                                           * sizeof (struct attr_abbrev)));
13857       memcpy (cur_abbrev->attrs, cur_attrs,
13858               cur_abbrev->num_attrs * sizeof (struct attr_abbrev));
13859
13860       abbrev_table_add_abbrev (abbrev_table, abbrev_number, cur_abbrev);
13861
13862       /* Get next abbreviation.
13863          Under Irix6 the abbreviations for a compilation unit are not
13864          always properly terminated with an abbrev number of 0.
13865          Exit loop if we encounter an abbreviation which we have
13866          already read (which means we are about to read the abbreviations
13867          for the next compile unit) or if the end of the abbreviation
13868          table is reached.  */
13869       if ((unsigned int) (abbrev_ptr - section->buffer) >= section->size)
13870         break;
13871       abbrev_number = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
13872       abbrev_ptr += bytes_read;
13873       if (abbrev_table_lookup_abbrev (abbrev_table, abbrev_number) != NULL)
13874         break;
13875     }
13876
13877   xfree (cur_attrs);
13878   return abbrev_table;
13879 }
13880
13881 /* Free the resources held by ABBREV_TABLE.  */
13882
13883 static void
13884 abbrev_table_free (struct abbrev_table *abbrev_table)
13885 {
13886   obstack_free (&abbrev_table->abbrev_obstack, NULL);
13887   xfree (abbrev_table);
13888 }
13889
13890 /* Same as abbrev_table_free but as a cleanup.
13891    We pass in a pointer to the pointer to the table so that we can
13892    set the pointer to NULL when we're done.  It also simplifies
13893    build_type_unit_groups.  */
13894
13895 static void
13896 abbrev_table_free_cleanup (void *table_ptr)
13897 {
13898   struct abbrev_table **abbrev_table_ptr = table_ptr;
13899
13900   if (*abbrev_table_ptr != NULL)
13901     abbrev_table_free (*abbrev_table_ptr);
13902   *abbrev_table_ptr = NULL;
13903 }
13904
13905 /* Read the abbrev table for CU from ABBREV_SECTION.  */
13906
13907 static void
13908 dwarf2_read_abbrevs (struct dwarf2_cu *cu,
13909                      struct dwarf2_section_info *abbrev_section)
13910 {
13911   cu->abbrev_table =
13912     abbrev_table_read_table (abbrev_section, cu->header.abbrev_offset);
13913 }
13914
13915 /* Release the memory used by the abbrev table for a compilation unit.  */
13916
13917 static void
13918 dwarf2_free_abbrev_table (void *ptr_to_cu)
13919 {
13920   struct dwarf2_cu *cu = ptr_to_cu;
13921
13922   if (cu->abbrev_table != NULL)
13923     abbrev_table_free (cu->abbrev_table);
13924   /* Set this to NULL so that we SEGV if we try to read it later,
13925      and also because free_comp_unit verifies this is NULL.  */
13926   cu->abbrev_table = NULL;
13927 }
13928 \f
13929 /* Returns nonzero if TAG represents a type that we might generate a partial
13930    symbol for.  */
13931
13932 static int
13933 is_type_tag_for_partial (int tag)
13934 {
13935   switch (tag)
13936     {
13937 #if 0
13938     /* Some types that would be reasonable to generate partial symbols for,
13939        that we don't at present.  */
13940     case DW_TAG_array_type:
13941     case DW_TAG_file_type:
13942     case DW_TAG_ptr_to_member_type:
13943     case DW_TAG_set_type:
13944     case DW_TAG_string_type:
13945     case DW_TAG_subroutine_type:
13946 #endif
13947     case DW_TAG_base_type:
13948     case DW_TAG_class_type:
13949     case DW_TAG_interface_type:
13950     case DW_TAG_enumeration_type:
13951     case DW_TAG_structure_type:
13952     case DW_TAG_subrange_type:
13953     case DW_TAG_typedef:
13954     case DW_TAG_union_type:
13955       return 1;
13956     default:
13957       return 0;
13958     }
13959 }
13960
13961 /* Load all DIEs that are interesting for partial symbols into memory.  */
13962
13963 static struct partial_die_info *
13964 load_partial_dies (const struct die_reader_specs *reader,
13965                    const gdb_byte *info_ptr, int building_psymtab)
13966 {
13967   struct dwarf2_cu *cu = reader->cu;
13968   struct objfile *objfile = cu->objfile;
13969   struct partial_die_info *part_die;
13970   struct partial_die_info *parent_die, *last_die, *first_die = NULL;
13971   struct abbrev_info *abbrev;
13972   unsigned int bytes_read;
13973   unsigned int load_all = 0;
13974   int nesting_level = 1;
13975
13976   parent_die = NULL;
13977   last_die = NULL;
13978
13979   gdb_assert (cu->per_cu != NULL);
13980   if (cu->per_cu->load_all_dies)
13981     load_all = 1;
13982
13983   cu->partial_dies
13984     = htab_create_alloc_ex (cu->header.length / 12,
13985                             partial_die_hash,
13986                             partial_die_eq,
13987                             NULL,
13988                             &cu->comp_unit_obstack,
13989                             hashtab_obstack_allocate,
13990                             dummy_obstack_deallocate);
13991
13992   part_die = obstack_alloc (&cu->comp_unit_obstack,
13993                             sizeof (struct partial_die_info));
13994
13995   while (1)
13996     {
13997       abbrev = peek_die_abbrev (info_ptr, &bytes_read, cu);
13998
13999       /* A NULL abbrev means the end of a series of children.  */
14000       if (abbrev == NULL)
14001         {
14002           if (--nesting_level == 0)
14003             {
14004               /* PART_DIE was probably the last thing allocated on the
14005                  comp_unit_obstack, so we could call obstack_free
14006                  here.  We don't do that because the waste is small,
14007                  and will be cleaned up when we're done with this
14008                  compilation unit.  This way, we're also more robust
14009                  against other users of the comp_unit_obstack.  */
14010               return first_die;
14011             }
14012           info_ptr += bytes_read;
14013           last_die = parent_die;
14014           parent_die = parent_die->die_parent;
14015           continue;
14016         }
14017
14018       /* Check for template arguments.  We never save these; if
14019          they're seen, we just mark the parent, and go on our way.  */
14020       if (parent_die != NULL
14021           && cu->language == language_cplus
14022           && (abbrev->tag == DW_TAG_template_type_param
14023               || abbrev->tag == DW_TAG_template_value_param))
14024         {
14025           parent_die->has_template_arguments = 1;
14026
14027           if (!load_all)
14028             {
14029               /* We don't need a partial DIE for the template argument.  */
14030               info_ptr = skip_one_die (reader, info_ptr + bytes_read, abbrev);
14031               continue;
14032             }
14033         }
14034
14035       /* We only recurse into c++ subprograms looking for template arguments.
14036          Skip their other children.  */
14037       if (!load_all
14038           && cu->language == language_cplus
14039           && parent_die != NULL
14040           && parent_die->tag == DW_TAG_subprogram)
14041         {
14042           info_ptr = skip_one_die (reader, info_ptr + bytes_read, abbrev);
14043           continue;
14044         }
14045
14046       /* Check whether this DIE is interesting enough to save.  Normally
14047          we would not be interested in members here, but there may be
14048          later variables referencing them via DW_AT_specification (for
14049          static members).  */
14050       if (!load_all
14051           && !is_type_tag_for_partial (abbrev->tag)
14052           && abbrev->tag != DW_TAG_constant
14053           && abbrev->tag != DW_TAG_enumerator
14054           && abbrev->tag != DW_TAG_subprogram
14055           && abbrev->tag != DW_TAG_lexical_block
14056           && abbrev->tag != DW_TAG_variable
14057           && abbrev->tag != DW_TAG_namespace
14058           && abbrev->tag != DW_TAG_module
14059           && abbrev->tag != DW_TAG_member
14060           && abbrev->tag != DW_TAG_imported_unit)
14061         {
14062           /* Otherwise we skip to the next sibling, if any.  */
14063           info_ptr = skip_one_die (reader, info_ptr + bytes_read, abbrev);
14064           continue;
14065         }
14066
14067       info_ptr = read_partial_die (reader, part_die, abbrev, bytes_read,
14068                                    info_ptr);
14069
14070       /* This two-pass algorithm for processing partial symbols has a
14071          high cost in cache pressure.  Thus, handle some simple cases
14072          here which cover the majority of C partial symbols.  DIEs
14073          which neither have specification tags in them, nor could have
14074          specification tags elsewhere pointing at them, can simply be
14075          processed and discarded.
14076
14077          This segment is also optional; scan_partial_symbols and
14078          add_partial_symbol will handle these DIEs if we chain
14079          them in normally.  When compilers which do not emit large
14080          quantities of duplicate debug information are more common,
14081          this code can probably be removed.  */
14082
14083       /* Any complete simple types at the top level (pretty much all
14084          of them, for a language without namespaces), can be processed
14085          directly.  */
14086       if (parent_die == NULL
14087           && part_die->has_specification == 0
14088           && part_die->is_declaration == 0
14089           && ((part_die->tag == DW_TAG_typedef && !part_die->has_children)
14090               || part_die->tag == DW_TAG_base_type
14091               || part_die->tag == DW_TAG_subrange_type))
14092         {
14093           if (building_psymtab && part_die->name != NULL)
14094             add_psymbol_to_list (part_die->name, strlen (part_die->name), 0,
14095                                  VAR_DOMAIN, LOC_TYPEDEF,
14096                                  &objfile->static_psymbols,
14097                                  0, (CORE_ADDR) 0, cu->language, objfile);
14098           info_ptr = locate_pdi_sibling (reader, part_die, info_ptr);
14099           continue;
14100         }
14101
14102       /* The exception for DW_TAG_typedef with has_children above is
14103          a workaround of GCC PR debug/47510.  In the case of this complaint
14104          type_name_no_tag_or_error will error on such types later.
14105
14106          GDB skipped children of DW_TAG_typedef by the shortcut above and then
14107          it could not find the child DIEs referenced later, this is checked
14108          above.  In correct DWARF DW_TAG_typedef should have no children.  */
14109
14110       if (part_die->tag == DW_TAG_typedef && part_die->has_children)
14111         complaint (&symfile_complaints,
14112                    _("DW_TAG_typedef has childen - GCC PR debug/47510 bug "
14113                      "- DIE at 0x%x [in module %s]"),
14114                    part_die->offset.sect_off, objfile->name);
14115
14116       /* If we're at the second level, and we're an enumerator, and
14117          our parent has no specification (meaning possibly lives in a
14118          namespace elsewhere), then we can add the partial symbol now
14119          instead of queueing it.  */
14120       if (part_die->tag == DW_TAG_enumerator
14121           && parent_die != NULL
14122           && parent_die->die_parent == NULL
14123           && parent_die->tag == DW_TAG_enumeration_type
14124           && parent_die->has_specification == 0)
14125         {
14126           if (part_die->name == NULL)
14127             complaint (&symfile_complaints,
14128                        _("malformed enumerator DIE ignored"));
14129           else if (building_psymtab)
14130             add_psymbol_to_list (part_die->name, strlen (part_die->name), 0,
14131                                  VAR_DOMAIN, LOC_CONST,
14132                                  (cu->language == language_cplus
14133                                   || cu->language == language_java)
14134                                  ? &objfile->global_psymbols
14135                                  : &objfile->static_psymbols,
14136                                  0, (CORE_ADDR) 0, cu->language, objfile);
14137
14138           info_ptr = locate_pdi_sibling (reader, part_die, info_ptr);
14139           continue;
14140         }
14141
14142       /* We'll save this DIE so link it in.  */
14143       part_die->die_parent = parent_die;
14144       part_die->die_sibling = NULL;
14145       part_die->die_child = NULL;
14146
14147       if (last_die && last_die == parent_die)
14148         last_die->die_child = part_die;
14149       else if (last_die)
14150         last_die->die_sibling = part_die;
14151
14152       last_die = part_die;
14153
14154       if (first_die == NULL)
14155         first_die = part_die;
14156
14157       /* Maybe add the DIE to the hash table.  Not all DIEs that we
14158          find interesting need to be in the hash table, because we
14159          also have the parent/sibling/child chains; only those that we
14160          might refer to by offset later during partial symbol reading.
14161
14162          For now this means things that might have be the target of a
14163          DW_AT_specification, DW_AT_abstract_origin, or
14164          DW_AT_extension.  DW_AT_extension will refer only to
14165          namespaces; DW_AT_abstract_origin refers to functions (and
14166          many things under the function DIE, but we do not recurse
14167          into function DIEs during partial symbol reading) and
14168          possibly variables as well; DW_AT_specification refers to
14169          declarations.  Declarations ought to have the DW_AT_declaration
14170          flag.  It happens that GCC forgets to put it in sometimes, but
14171          only for functions, not for types.
14172
14173          Adding more things than necessary to the hash table is harmless
14174          except for the performance cost.  Adding too few will result in
14175          wasted time in find_partial_die, when we reread the compilation
14176          unit with load_all_dies set.  */
14177
14178       if (load_all
14179           || abbrev->tag == DW_TAG_constant
14180           || abbrev->tag == DW_TAG_subprogram
14181           || abbrev->tag == DW_TAG_variable
14182           || abbrev->tag == DW_TAG_namespace
14183           || part_die->is_declaration)
14184         {
14185           void **slot;
14186
14187           slot = htab_find_slot_with_hash (cu->partial_dies, part_die,
14188                                            part_die->offset.sect_off, INSERT);
14189           *slot = part_die;
14190         }
14191
14192       part_die = obstack_alloc (&cu->comp_unit_obstack,
14193                                 sizeof (struct partial_die_info));
14194
14195       /* For some DIEs we want to follow their children (if any).  For C
14196          we have no reason to follow the children of structures; for other
14197          languages we have to, so that we can get at method physnames
14198          to infer fully qualified class names, for DW_AT_specification,
14199          and for C++ template arguments.  For C++, we also look one level
14200          inside functions to find template arguments (if the name of the
14201          function does not already contain the template arguments).
14202
14203          For Ada, we need to scan the children of subprograms and lexical
14204          blocks as well because Ada allows the definition of nested
14205          entities that could be interesting for the debugger, such as
14206          nested subprograms for instance.  */
14207       if (last_die->has_children
14208           && (load_all
14209               || last_die->tag == DW_TAG_namespace
14210               || last_die->tag == DW_TAG_module
14211               || last_die->tag == DW_TAG_enumeration_type
14212               || (cu->language == language_cplus
14213                   && last_die->tag == DW_TAG_subprogram
14214                   && (last_die->name == NULL
14215                       || strchr (last_die->name, '<') == NULL))
14216               || (cu->language != language_c
14217                   && (last_die->tag == DW_TAG_class_type
14218                       || last_die->tag == DW_TAG_interface_type
14219                       || last_die->tag == DW_TAG_structure_type
14220                       || last_die->tag == DW_TAG_union_type))
14221               || (cu->language == language_ada
14222                   && (last_die->tag == DW_TAG_subprogram
14223                       || last_die->tag == DW_TAG_lexical_block))))
14224         {
14225           nesting_level++;
14226           parent_die = last_die;
14227           continue;
14228         }
14229
14230       /* Otherwise we skip to the next sibling, if any.  */
14231       info_ptr = locate_pdi_sibling (reader, last_die, info_ptr);
14232
14233       /* Back to the top, do it again.  */
14234     }
14235 }
14236
14237 /* Read a minimal amount of information into the minimal die structure.  */
14238
14239 static const gdb_byte *
14240 read_partial_die (const struct die_reader_specs *reader,
14241                   struct partial_die_info *part_die,
14242                   struct abbrev_info *abbrev, unsigned int abbrev_len,
14243                   const gdb_byte *info_ptr)
14244 {
14245   struct dwarf2_cu *cu = reader->cu;
14246   struct objfile *objfile = cu->objfile;
14247   const gdb_byte *buffer = reader->buffer;
14248   unsigned int i;
14249   struct attribute attr;
14250   int has_low_pc_attr = 0;
14251   int has_high_pc_attr = 0;
14252   int high_pc_relative = 0;
14253
14254   memset (part_die, 0, sizeof (struct partial_die_info));
14255
14256   part_die->offset.sect_off = info_ptr - buffer;
14257
14258   info_ptr += abbrev_len;
14259
14260   if (abbrev == NULL)
14261     return info_ptr;
14262
14263   part_die->tag = abbrev->tag;
14264   part_die->has_children = abbrev->has_children;
14265
14266   for (i = 0; i < abbrev->num_attrs; ++i)
14267     {
14268       info_ptr = read_attribute (reader, &attr, &abbrev->attrs[i], info_ptr);
14269
14270       /* Store the data if it is of an attribute we want to keep in a
14271          partial symbol table.  */
14272       switch (attr.name)
14273         {
14274         case DW_AT_name:
14275           switch (part_die->tag)
14276             {
14277             case DW_TAG_compile_unit:
14278             case DW_TAG_partial_unit:
14279             case DW_TAG_type_unit:
14280               /* Compilation units have a DW_AT_name that is a filename, not
14281                  a source language identifier.  */
14282             case DW_TAG_enumeration_type:
14283             case DW_TAG_enumerator:
14284               /* These tags always have simple identifiers already; no need
14285                  to canonicalize them.  */
14286               part_die->name = DW_STRING (&attr);
14287               break;
14288             default:
14289               part_die->name
14290                 = dwarf2_canonicalize_name (DW_STRING (&attr), cu,
14291                                             &objfile->objfile_obstack);
14292               break;
14293             }
14294           break;
14295         case DW_AT_linkage_name:
14296         case DW_AT_MIPS_linkage_name:
14297           /* Note that both forms of linkage name might appear.  We
14298              assume they will be the same, and we only store the last
14299              one we see.  */
14300           if (cu->language == language_ada)
14301             part_die->name = DW_STRING (&attr);
14302           part_die->linkage_name = DW_STRING (&attr);
14303           break;
14304         case DW_AT_low_pc:
14305           has_low_pc_attr = 1;
14306           part_die->lowpc = DW_ADDR (&attr);
14307           break;
14308         case DW_AT_high_pc:
14309           has_high_pc_attr = 1;
14310           if (attr.form == DW_FORM_addr
14311               || attr.form == DW_FORM_GNU_addr_index)
14312             part_die->highpc = DW_ADDR (&attr);
14313           else
14314             {
14315               high_pc_relative = 1;
14316               part_die->highpc = DW_UNSND (&attr);
14317             }
14318           break;
14319         case DW_AT_location:
14320           /* Support the .debug_loc offsets.  */
14321           if (attr_form_is_block (&attr))
14322             {
14323                part_die->d.locdesc = DW_BLOCK (&attr);
14324             }
14325           else if (attr_form_is_section_offset (&attr))
14326             {
14327               dwarf2_complex_location_expr_complaint ();
14328             }
14329           else
14330             {
14331               dwarf2_invalid_attrib_class_complaint ("DW_AT_location",
14332                                                      "partial symbol information");
14333             }
14334           break;
14335         case DW_AT_external:
14336           part_die->is_external = DW_UNSND (&attr);
14337           break;
14338         case DW_AT_declaration:
14339           part_die->is_declaration = DW_UNSND (&attr);
14340           break;
14341         case DW_AT_type:
14342           part_die->has_type = 1;
14343           break;
14344         case DW_AT_abstract_origin:
14345         case DW_AT_specification:
14346         case DW_AT_extension:
14347           part_die->has_specification = 1;
14348           part_die->spec_offset = dwarf2_get_ref_die_offset (&attr);
14349           part_die->spec_is_dwz = (attr.form == DW_FORM_GNU_ref_alt
14350                                    || cu->per_cu->is_dwz);
14351           break;
14352         case DW_AT_sibling:
14353           /* Ignore absolute siblings, they might point outside of
14354              the current compile unit.  */
14355           if (attr.form == DW_FORM_ref_addr)
14356             complaint (&symfile_complaints,
14357                        _("ignoring absolute DW_AT_sibling"));
14358           else
14359             part_die->sibling = buffer + dwarf2_get_ref_die_offset (&attr).sect_off;
14360           break;
14361         case DW_AT_byte_size:
14362           part_die->has_byte_size = 1;
14363           break;
14364         case DW_AT_calling_convention:
14365           /* DWARF doesn't provide a way to identify a program's source-level
14366              entry point.  DW_AT_calling_convention attributes are only meant
14367              to describe functions' calling conventions.
14368
14369              However, because it's a necessary piece of information in
14370              Fortran, and because DW_CC_program is the only piece of debugging
14371              information whose definition refers to a 'main program' at all,
14372              several compilers have begun marking Fortran main programs with
14373              DW_CC_program --- even when those functions use the standard
14374              calling conventions.
14375
14376              So until DWARF specifies a way to provide this information and
14377              compilers pick up the new representation, we'll support this
14378              practice.  */
14379           if (DW_UNSND (&attr) == DW_CC_program
14380               && cu->language == language_fortran)
14381             {
14382               set_main_name (part_die->name);
14383
14384               /* As this DIE has a static linkage the name would be difficult
14385                  to look up later.  */
14386               language_of_main = language_fortran;
14387             }
14388           break;
14389         case DW_AT_inline:
14390           if (DW_UNSND (&attr) == DW_INL_inlined
14391               || DW_UNSND (&attr) == DW_INL_declared_inlined)
14392             part_die->may_be_inlined = 1;
14393           break;
14394
14395         case DW_AT_import:
14396           if (part_die->tag == DW_TAG_imported_unit)
14397             {
14398               part_die->d.offset = dwarf2_get_ref_die_offset (&attr);
14399               part_die->is_dwz = (attr.form == DW_FORM_GNU_ref_alt
14400                                   || cu->per_cu->is_dwz);
14401             }
14402           break;
14403
14404         default:
14405           break;
14406         }
14407     }
14408
14409   if (high_pc_relative)
14410     part_die->highpc += part_die->lowpc;
14411
14412   if (has_low_pc_attr && has_high_pc_attr)
14413     {
14414       /* When using the GNU linker, .gnu.linkonce. sections are used to
14415          eliminate duplicate copies of functions and vtables and such.
14416          The linker will arbitrarily choose one and discard the others.
14417          The AT_*_pc values for such functions refer to local labels in
14418          these sections.  If the section from that file was discarded, the
14419          labels are not in the output, so the relocs get a value of 0.
14420          If this is a discarded function, mark the pc bounds as invalid,
14421          so that GDB will ignore it.  */
14422       if (part_die->lowpc == 0 && !dwarf2_per_objfile->has_section_at_zero)
14423         {
14424           struct gdbarch *gdbarch = get_objfile_arch (objfile);
14425
14426           complaint (&symfile_complaints,
14427                      _("DW_AT_low_pc %s is zero "
14428                        "for DIE at 0x%x [in module %s]"),
14429                      paddress (gdbarch, part_die->lowpc),
14430                      part_die->offset.sect_off, objfile->name);
14431         }
14432       /* dwarf2_get_pc_bounds has also the strict low < high requirement.  */
14433       else if (part_die->lowpc >= part_die->highpc)
14434         {
14435           struct gdbarch *gdbarch = get_objfile_arch (objfile);
14436
14437           complaint (&symfile_complaints,
14438                      _("DW_AT_low_pc %s is not < DW_AT_high_pc %s "
14439                        "for DIE at 0x%x [in module %s]"),
14440                      paddress (gdbarch, part_die->lowpc),
14441                      paddress (gdbarch, part_die->highpc),
14442                      part_die->offset.sect_off, objfile->name);
14443         }
14444       else
14445         part_die->has_pc_info = 1;
14446     }
14447
14448   return info_ptr;
14449 }
14450
14451 /* Find a cached partial DIE at OFFSET in CU.  */
14452
14453 static struct partial_die_info *
14454 find_partial_die_in_comp_unit (sect_offset offset, struct dwarf2_cu *cu)
14455 {
14456   struct partial_die_info *lookup_die = NULL;
14457   struct partial_die_info part_die;
14458
14459   part_die.offset = offset;
14460   lookup_die = htab_find_with_hash (cu->partial_dies, &part_die,
14461                                     offset.sect_off);
14462
14463   return lookup_die;
14464 }
14465
14466 /* Find a partial DIE at OFFSET, which may or may not be in CU,
14467    except in the case of .debug_types DIEs which do not reference
14468    outside their CU (they do however referencing other types via
14469    DW_FORM_ref_sig8).  */
14470
14471 static struct partial_die_info *
14472 find_partial_die (sect_offset offset, int offset_in_dwz, struct dwarf2_cu *cu)
14473 {
14474   struct objfile *objfile = cu->objfile;
14475   struct dwarf2_per_cu_data *per_cu = NULL;
14476   struct partial_die_info *pd = NULL;
14477
14478   if (offset_in_dwz == cu->per_cu->is_dwz
14479       && offset_in_cu_p (&cu->header, offset))
14480     {
14481       pd = find_partial_die_in_comp_unit (offset, cu);
14482       if (pd != NULL)
14483         return pd;
14484       /* We missed recording what we needed.
14485          Load all dies and try again.  */
14486       per_cu = cu->per_cu;
14487     }
14488   else
14489     {
14490       /* TUs don't reference other CUs/TUs (except via type signatures).  */
14491       if (cu->per_cu->is_debug_types)
14492         {
14493           error (_("Dwarf Error: Type Unit at offset 0x%lx contains"
14494                    " external reference to offset 0x%lx [in module %s].\n"),
14495                  (long) cu->header.offset.sect_off, (long) offset.sect_off,
14496                  bfd_get_filename (objfile->obfd));
14497         }
14498       per_cu = dwarf2_find_containing_comp_unit (offset, offset_in_dwz,
14499                                                  objfile);
14500
14501       if (per_cu->cu == NULL || per_cu->cu->partial_dies == NULL)
14502         load_partial_comp_unit (per_cu);
14503
14504       per_cu->cu->last_used = 0;
14505       pd = find_partial_die_in_comp_unit (offset, per_cu->cu);
14506     }
14507
14508   /* If we didn't find it, and not all dies have been loaded,
14509      load them all and try again.  */
14510
14511   if (pd == NULL && per_cu->load_all_dies == 0)
14512     {
14513       per_cu->load_all_dies = 1;
14514
14515       /* This is nasty.  When we reread the DIEs, somewhere up the call chain
14516          THIS_CU->cu may already be in use.  So we can't just free it and
14517          replace its DIEs with the ones we read in.  Instead, we leave those
14518          DIEs alone (which can still be in use, e.g. in scan_partial_symbols),
14519          and clobber THIS_CU->cu->partial_dies with the hash table for the new
14520          set.  */
14521       load_partial_comp_unit (per_cu);
14522
14523       pd = find_partial_die_in_comp_unit (offset, per_cu->cu);
14524     }
14525
14526   if (pd == NULL)
14527     internal_error (__FILE__, __LINE__,
14528                     _("could not find partial DIE 0x%x "
14529                       "in cache [from module %s]\n"),
14530                     offset.sect_off, bfd_get_filename (objfile->obfd));
14531   return pd;
14532 }
14533
14534 /* See if we can figure out if the class lives in a namespace.  We do
14535    this by looking for a member function; its demangled name will
14536    contain namespace info, if there is any.  */
14537
14538 static void
14539 guess_partial_die_structure_name (struct partial_die_info *struct_pdi,
14540                                   struct dwarf2_cu *cu)
14541 {
14542   /* NOTE: carlton/2003-10-07: Getting the info this way changes
14543      what template types look like, because the demangler
14544      frequently doesn't give the same name as the debug info.  We
14545      could fix this by only using the demangled name to get the
14546      prefix (but see comment in read_structure_type).  */
14547
14548   struct partial_die_info *real_pdi;
14549   struct partial_die_info *child_pdi;
14550
14551   /* If this DIE (this DIE's specification, if any) has a parent, then
14552      we should not do this.  We'll prepend the parent's fully qualified
14553      name when we create the partial symbol.  */
14554
14555   real_pdi = struct_pdi;
14556   while (real_pdi->has_specification)
14557     real_pdi = find_partial_die (real_pdi->spec_offset,
14558                                  real_pdi->spec_is_dwz, cu);
14559
14560   if (real_pdi->die_parent != NULL)
14561     return;
14562
14563   for (child_pdi = struct_pdi->die_child;
14564        child_pdi != NULL;
14565        child_pdi = child_pdi->die_sibling)
14566     {
14567       if (child_pdi->tag == DW_TAG_subprogram
14568           && child_pdi->linkage_name != NULL)
14569         {
14570           char *actual_class_name
14571             = language_class_name_from_physname (cu->language_defn,
14572                                                  child_pdi->linkage_name);
14573           if (actual_class_name != NULL)
14574             {
14575               struct_pdi->name
14576                 = obstack_copy0 (&cu->objfile->objfile_obstack,
14577                                  actual_class_name,
14578                                  strlen (actual_class_name));
14579               xfree (actual_class_name);
14580             }
14581           break;
14582         }
14583     }
14584 }
14585
14586 /* Adjust PART_DIE before generating a symbol for it.  This function
14587    may set the is_external flag or change the DIE's name.  */
14588
14589 static void
14590 fixup_partial_die (struct partial_die_info *part_die,
14591                    struct dwarf2_cu *cu)
14592 {
14593   /* Once we've fixed up a die, there's no point in doing so again.
14594      This also avoids a memory leak if we were to call
14595      guess_partial_die_structure_name multiple times.  */
14596   if (part_die->fixup_called)
14597     return;
14598
14599   /* If we found a reference attribute and the DIE has no name, try
14600      to find a name in the referred to DIE.  */
14601
14602   if (part_die->name == NULL && part_die->has_specification)
14603     {
14604       struct partial_die_info *spec_die;
14605
14606       spec_die = find_partial_die (part_die->spec_offset,
14607                                    part_die->spec_is_dwz, cu);
14608
14609       fixup_partial_die (spec_die, cu);
14610
14611       if (spec_die->name)
14612         {
14613           part_die->name = spec_die->name;
14614
14615           /* Copy DW_AT_external attribute if it is set.  */
14616           if (spec_die->is_external)
14617             part_die->is_external = spec_die->is_external;
14618         }
14619     }
14620
14621   /* Set default names for some unnamed DIEs.  */
14622
14623   if (part_die->name == NULL && part_die->tag == DW_TAG_namespace)
14624     part_die->name = CP_ANONYMOUS_NAMESPACE_STR;
14625
14626   /* If there is no parent die to provide a namespace, and there are
14627      children, see if we can determine the namespace from their linkage
14628      name.  */
14629   if (cu->language == language_cplus
14630       && !VEC_empty (dwarf2_section_info_def, dwarf2_per_objfile->types)
14631       && part_die->die_parent == NULL
14632       && part_die->has_children
14633       && (part_die->tag == DW_TAG_class_type
14634           || part_die->tag == DW_TAG_structure_type
14635           || part_die->tag == DW_TAG_union_type))
14636     guess_partial_die_structure_name (part_die, cu);
14637
14638   /* GCC might emit a nameless struct or union that has a linkage
14639      name.  See http://gcc.gnu.org/bugzilla/show_bug.cgi?id=47510.  */
14640   if (part_die->name == NULL
14641       && (part_die->tag == DW_TAG_class_type
14642           || part_die->tag == DW_TAG_interface_type
14643           || part_die->tag == DW_TAG_structure_type
14644           || part_die->tag == DW_TAG_union_type)
14645       && part_die->linkage_name != NULL)
14646     {
14647       char *demangled;
14648
14649       demangled = gdb_demangle (part_die->linkage_name, DMGL_TYPES);
14650       if (demangled)
14651         {
14652           const char *base;
14653
14654           /* Strip any leading namespaces/classes, keep only the base name.
14655              DW_AT_name for named DIEs does not contain the prefixes.  */
14656           base = strrchr (demangled, ':');
14657           if (base && base > demangled && base[-1] == ':')
14658             base++;
14659           else
14660             base = demangled;
14661
14662           part_die->name = obstack_copy0 (&cu->objfile->objfile_obstack,
14663                                           base, strlen (base));
14664           xfree (demangled);
14665         }
14666     }
14667
14668   part_die->fixup_called = 1;
14669 }
14670
14671 /* Read an attribute value described by an attribute form.  */
14672
14673 static const gdb_byte *
14674 read_attribute_value (const struct die_reader_specs *reader,
14675                       struct attribute *attr, unsigned form,
14676                       const gdb_byte *info_ptr)
14677 {
14678   struct dwarf2_cu *cu = reader->cu;
14679   bfd *abfd = reader->abfd;
14680   struct comp_unit_head *cu_header = &cu->header;
14681   unsigned int bytes_read;
14682   struct dwarf_block *blk;
14683
14684   attr->form = form;
14685   switch (form)
14686     {
14687     case DW_FORM_ref_addr:
14688       if (cu->header.version == 2)
14689         DW_UNSND (attr) = read_address (abfd, info_ptr, cu, &bytes_read);
14690       else
14691         DW_UNSND (attr) = read_offset (abfd, info_ptr,
14692                                        &cu->header, &bytes_read);
14693       info_ptr += bytes_read;
14694       break;
14695     case DW_FORM_GNU_ref_alt:
14696       DW_UNSND (attr) = read_offset (abfd, info_ptr, &cu->header, &bytes_read);
14697       info_ptr += bytes_read;
14698       break;
14699     case DW_FORM_addr:
14700       DW_ADDR (attr) = read_address (abfd, info_ptr, cu, &bytes_read);
14701       info_ptr += bytes_read;
14702       break;
14703     case DW_FORM_block2:
14704       blk = dwarf_alloc_block (cu);
14705       blk->size = read_2_bytes (abfd, info_ptr);
14706       info_ptr += 2;
14707       blk->data = read_n_bytes (abfd, info_ptr, blk->size);
14708       info_ptr += blk->size;
14709       DW_BLOCK (attr) = blk;
14710       break;
14711     case DW_FORM_block4:
14712       blk = dwarf_alloc_block (cu);
14713       blk->size = read_4_bytes (abfd, info_ptr);
14714       info_ptr += 4;
14715       blk->data = read_n_bytes (abfd, info_ptr, blk->size);
14716       info_ptr += blk->size;
14717       DW_BLOCK (attr) = blk;
14718       break;
14719     case DW_FORM_data2:
14720       DW_UNSND (attr) = read_2_bytes (abfd, info_ptr);
14721       info_ptr += 2;
14722       break;
14723     case DW_FORM_data4:
14724       DW_UNSND (attr) = read_4_bytes (abfd, info_ptr);
14725       info_ptr += 4;
14726       break;
14727     case DW_FORM_data8:
14728       DW_UNSND (attr) = read_8_bytes (abfd, info_ptr);
14729       info_ptr += 8;
14730       break;
14731     case DW_FORM_sec_offset:
14732       DW_UNSND (attr) = read_offset (abfd, info_ptr, &cu->header, &bytes_read);
14733       info_ptr += bytes_read;
14734       break;
14735     case DW_FORM_string:
14736       DW_STRING (attr) = read_direct_string (abfd, info_ptr, &bytes_read);
14737       DW_STRING_IS_CANONICAL (attr) = 0;
14738       info_ptr += bytes_read;
14739       break;
14740     case DW_FORM_strp:
14741       if (!cu->per_cu->is_dwz)
14742         {
14743           DW_STRING (attr) = read_indirect_string (abfd, info_ptr, cu_header,
14744                                                    &bytes_read);
14745           DW_STRING_IS_CANONICAL (attr) = 0;
14746           info_ptr += bytes_read;
14747           break;
14748         }
14749       /* FALLTHROUGH */
14750     case DW_FORM_GNU_strp_alt:
14751       {
14752         struct dwz_file *dwz = dwarf2_get_dwz_file ();
14753         LONGEST str_offset = read_offset (abfd, info_ptr, cu_header,
14754                                           &bytes_read);
14755
14756         DW_STRING (attr) = read_indirect_string_from_dwz (dwz, str_offset);
14757         DW_STRING_IS_CANONICAL (attr) = 0;
14758         info_ptr += bytes_read;
14759       }
14760       break;
14761     case DW_FORM_exprloc:
14762     case DW_FORM_block:
14763       blk = dwarf_alloc_block (cu);
14764       blk->size = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
14765       info_ptr += bytes_read;
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_block1:
14771       blk = dwarf_alloc_block (cu);
14772       blk->size = read_1_byte (abfd, info_ptr);
14773       info_ptr += 1;
14774       blk->data = read_n_bytes (abfd, info_ptr, blk->size);
14775       info_ptr += blk->size;
14776       DW_BLOCK (attr) = blk;
14777       break;
14778     case DW_FORM_data1:
14779       DW_UNSND (attr) = read_1_byte (abfd, info_ptr);
14780       info_ptr += 1;
14781       break;
14782     case DW_FORM_flag:
14783       DW_UNSND (attr) = read_1_byte (abfd, info_ptr);
14784       info_ptr += 1;
14785       break;
14786     case DW_FORM_flag_present:
14787       DW_UNSND (attr) = 1;
14788       break;
14789     case DW_FORM_sdata:
14790       DW_SND (attr) = read_signed_leb128 (abfd, info_ptr, &bytes_read);
14791       info_ptr += bytes_read;
14792       break;
14793     case DW_FORM_udata:
14794       DW_UNSND (attr) = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
14795       info_ptr += bytes_read;
14796       break;
14797     case DW_FORM_ref1:
14798       DW_UNSND (attr) = (cu->header.offset.sect_off
14799                          + read_1_byte (abfd, info_ptr));
14800       info_ptr += 1;
14801       break;
14802     case DW_FORM_ref2:
14803       DW_UNSND (attr) = (cu->header.offset.sect_off
14804                          + read_2_bytes (abfd, info_ptr));
14805       info_ptr += 2;
14806       break;
14807     case DW_FORM_ref4:
14808       DW_UNSND (attr) = (cu->header.offset.sect_off
14809                          + read_4_bytes (abfd, info_ptr));
14810       info_ptr += 4;
14811       break;
14812     case DW_FORM_ref8:
14813       DW_UNSND (attr) = (cu->header.offset.sect_off
14814                          + read_8_bytes (abfd, info_ptr));
14815       info_ptr += 8;
14816       break;
14817     case DW_FORM_ref_sig8:
14818       DW_SIGNATURE (attr) = read_8_bytes (abfd, info_ptr);
14819       info_ptr += 8;
14820       break;
14821     case DW_FORM_ref_udata:
14822       DW_UNSND (attr) = (cu->header.offset.sect_off
14823                          + read_unsigned_leb128 (abfd, info_ptr, &bytes_read));
14824       info_ptr += bytes_read;
14825       break;
14826     case DW_FORM_indirect:
14827       form = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
14828       info_ptr += bytes_read;
14829       info_ptr = read_attribute_value (reader, attr, form, info_ptr);
14830       break;
14831     case DW_FORM_GNU_addr_index:
14832       if (reader->dwo_file == NULL)
14833         {
14834           /* For now flag a hard error.
14835              Later we can turn this into a complaint.  */
14836           error (_("Dwarf Error: %s found in non-DWO CU [in module %s]"),
14837                  dwarf_form_name (form),
14838                  bfd_get_filename (abfd));
14839         }
14840       DW_ADDR (attr) = read_addr_index_from_leb128 (cu, info_ptr, &bytes_read);
14841       info_ptr += bytes_read;
14842       break;
14843     case DW_FORM_GNU_str_index:
14844       if (reader->dwo_file == NULL)
14845         {
14846           /* For now flag a hard error.
14847              Later we can turn this into a complaint if warranted.  */
14848           error (_("Dwarf Error: %s found in non-DWO CU [in module %s]"),
14849                  dwarf_form_name (form),
14850                  bfd_get_filename (abfd));
14851         }
14852       {
14853         ULONGEST str_index =
14854           read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
14855
14856         DW_STRING (attr) = read_str_index (reader, cu, str_index);
14857         DW_STRING_IS_CANONICAL (attr) = 0;
14858         info_ptr += bytes_read;
14859       }
14860       break;
14861     default:
14862       error (_("Dwarf Error: Cannot handle %s in DWARF reader [in module %s]"),
14863              dwarf_form_name (form),
14864              bfd_get_filename (abfd));
14865     }
14866
14867   /* Super hack.  */
14868   if (cu->per_cu->is_dwz && attr_form_is_ref (attr))
14869     attr->form = DW_FORM_GNU_ref_alt;
14870
14871   /* We have seen instances where the compiler tried to emit a byte
14872      size attribute of -1 which ended up being encoded as an unsigned
14873      0xffffffff.  Although 0xffffffff is technically a valid size value,
14874      an object of this size seems pretty unlikely so we can relatively
14875      safely treat these cases as if the size attribute was invalid and
14876      treat them as zero by default.  */
14877   if (attr->name == DW_AT_byte_size
14878       && form == DW_FORM_data4
14879       && DW_UNSND (attr) >= 0xffffffff)
14880     {
14881       complaint
14882         (&symfile_complaints,
14883          _("Suspicious DW_AT_byte_size value treated as zero instead of %s"),
14884          hex_string (DW_UNSND (attr)));
14885       DW_UNSND (attr) = 0;
14886     }
14887
14888   return info_ptr;
14889 }
14890
14891 /* Read an attribute described by an abbreviated attribute.  */
14892
14893 static const gdb_byte *
14894 read_attribute (const struct die_reader_specs *reader,
14895                 struct attribute *attr, struct attr_abbrev *abbrev,
14896                 const gdb_byte *info_ptr)
14897 {
14898   attr->name = abbrev->name;
14899   return read_attribute_value (reader, attr, abbrev->form, info_ptr);
14900 }
14901
14902 /* Read dwarf information from a buffer.  */
14903
14904 static unsigned int
14905 read_1_byte (bfd *abfd, const gdb_byte *buf)
14906 {
14907   return bfd_get_8 (abfd, buf);
14908 }
14909
14910 static int
14911 read_1_signed_byte (bfd *abfd, const gdb_byte *buf)
14912 {
14913   return bfd_get_signed_8 (abfd, buf);
14914 }
14915
14916 static unsigned int
14917 read_2_bytes (bfd *abfd, const gdb_byte *buf)
14918 {
14919   return bfd_get_16 (abfd, buf);
14920 }
14921
14922 static int
14923 read_2_signed_bytes (bfd *abfd, const gdb_byte *buf)
14924 {
14925   return bfd_get_signed_16 (abfd, buf);
14926 }
14927
14928 static unsigned int
14929 read_4_bytes (bfd *abfd, const gdb_byte *buf)
14930 {
14931   return bfd_get_32 (abfd, buf);
14932 }
14933
14934 static int
14935 read_4_signed_bytes (bfd *abfd, const gdb_byte *buf)
14936 {
14937   return bfd_get_signed_32 (abfd, buf);
14938 }
14939
14940 static ULONGEST
14941 read_8_bytes (bfd *abfd, const gdb_byte *buf)
14942 {
14943   return bfd_get_64 (abfd, buf);
14944 }
14945
14946 static CORE_ADDR
14947 read_address (bfd *abfd, const gdb_byte *buf, struct dwarf2_cu *cu,
14948               unsigned int *bytes_read)
14949 {
14950   struct comp_unit_head *cu_header = &cu->header;
14951   CORE_ADDR retval = 0;
14952
14953   if (cu_header->signed_addr_p)
14954     {
14955       switch (cu_header->addr_size)
14956         {
14957         case 2:
14958           retval = bfd_get_signed_16 (abfd, buf);
14959           break;
14960         case 4:
14961           retval = bfd_get_signed_32 (abfd, buf);
14962           break;
14963         case 8:
14964           retval = bfd_get_signed_64 (abfd, buf);
14965           break;
14966         default:
14967           internal_error (__FILE__, __LINE__,
14968                           _("read_address: bad switch, signed [in module %s]"),
14969                           bfd_get_filename (abfd));
14970         }
14971     }
14972   else
14973     {
14974       switch (cu_header->addr_size)
14975         {
14976         case 2:
14977           retval = bfd_get_16 (abfd, buf);
14978           break;
14979         case 4:
14980           retval = bfd_get_32 (abfd, buf);
14981           break;
14982         case 8:
14983           retval = bfd_get_64 (abfd, buf);
14984           break;
14985         default:
14986           internal_error (__FILE__, __LINE__,
14987                           _("read_address: bad switch, "
14988                             "unsigned [in module %s]"),
14989                           bfd_get_filename (abfd));
14990         }
14991     }
14992
14993   *bytes_read = cu_header->addr_size;
14994   return retval;
14995 }
14996
14997 /* Read the initial length from a section.  The (draft) DWARF 3
14998    specification allows the initial length to take up either 4 bytes
14999    or 12 bytes.  If the first 4 bytes are 0xffffffff, then the next 8
15000    bytes describe the length and all offsets will be 8 bytes in length
15001    instead of 4.
15002
15003    An older, non-standard 64-bit format is also handled by this
15004    function.  The older format in question stores the initial length
15005    as an 8-byte quantity without an escape value.  Lengths greater
15006    than 2^32 aren't very common which means that the initial 4 bytes
15007    is almost always zero.  Since a length value of zero doesn't make
15008    sense for the 32-bit format, this initial zero can be considered to
15009    be an escape value which indicates the presence of the older 64-bit
15010    format.  As written, the code can't detect (old format) lengths
15011    greater than 4GB.  If it becomes necessary to handle lengths
15012    somewhat larger than 4GB, we could allow other small values (such
15013    as the non-sensical values of 1, 2, and 3) to also be used as
15014    escape values indicating the presence of the old format.
15015
15016    The value returned via bytes_read should be used to increment the
15017    relevant pointer after calling read_initial_length().
15018
15019    [ Note:  read_initial_length() and read_offset() are based on the
15020      document entitled "DWARF Debugging Information Format", revision
15021      3, draft 8, dated November 19, 2001.  This document was obtained
15022      from:
15023
15024         http://reality.sgiweb.org/davea/dwarf3-draft8-011125.pdf
15025
15026      This document is only a draft and is subject to change.  (So beware.)
15027
15028      Details regarding the older, non-standard 64-bit format were
15029      determined empirically by examining 64-bit ELF files produced by
15030      the SGI toolchain on an IRIX 6.5 machine.
15031
15032      - Kevin, July 16, 2002
15033    ] */
15034
15035 static LONGEST
15036 read_initial_length (bfd *abfd, const gdb_byte *buf, unsigned int *bytes_read)
15037 {
15038   LONGEST length = bfd_get_32 (abfd, buf);
15039
15040   if (length == 0xffffffff)
15041     {
15042       length = bfd_get_64 (abfd, buf + 4);
15043       *bytes_read = 12;
15044     }
15045   else if (length == 0)
15046     {
15047       /* Handle the (non-standard) 64-bit DWARF2 format used by IRIX.  */
15048       length = bfd_get_64 (abfd, buf);
15049       *bytes_read = 8;
15050     }
15051   else
15052     {
15053       *bytes_read = 4;
15054     }
15055
15056   return length;
15057 }
15058
15059 /* Cover function for read_initial_length.
15060    Returns the length of the object at BUF, and stores the size of the
15061    initial length in *BYTES_READ and stores the size that offsets will be in
15062    *OFFSET_SIZE.
15063    If the initial length size is not equivalent to that specified in
15064    CU_HEADER then issue a complaint.
15065    This is useful when reading non-comp-unit headers.  */
15066
15067 static LONGEST
15068 read_checked_initial_length_and_offset (bfd *abfd, const gdb_byte *buf,
15069                                         const struct comp_unit_head *cu_header,
15070                                         unsigned int *bytes_read,
15071                                         unsigned int *offset_size)
15072 {
15073   LONGEST length = read_initial_length (abfd, buf, bytes_read);
15074
15075   gdb_assert (cu_header->initial_length_size == 4
15076               || cu_header->initial_length_size == 8
15077               || cu_header->initial_length_size == 12);
15078
15079   if (cu_header->initial_length_size != *bytes_read)
15080     complaint (&symfile_complaints,
15081                _("intermixed 32-bit and 64-bit DWARF sections"));
15082
15083   *offset_size = (*bytes_read == 4) ? 4 : 8;
15084   return length;
15085 }
15086
15087 /* Read an offset from the data stream.  The size of the offset is
15088    given by cu_header->offset_size.  */
15089
15090 static LONGEST
15091 read_offset (bfd *abfd, const gdb_byte *buf,
15092              const struct comp_unit_head *cu_header,
15093              unsigned int *bytes_read)
15094 {
15095   LONGEST offset = read_offset_1 (abfd, buf, cu_header->offset_size);
15096
15097   *bytes_read = cu_header->offset_size;
15098   return offset;
15099 }
15100
15101 /* Read an offset from the data stream.  */
15102
15103 static LONGEST
15104 read_offset_1 (bfd *abfd, const gdb_byte *buf, unsigned int offset_size)
15105 {
15106   LONGEST retval = 0;
15107
15108   switch (offset_size)
15109     {
15110     case 4:
15111       retval = bfd_get_32 (abfd, buf);
15112       break;
15113     case 8:
15114       retval = bfd_get_64 (abfd, buf);
15115       break;
15116     default:
15117       internal_error (__FILE__, __LINE__,
15118                       _("read_offset_1: bad switch [in module %s]"),
15119                       bfd_get_filename (abfd));
15120     }
15121
15122   return retval;
15123 }
15124
15125 static const gdb_byte *
15126 read_n_bytes (bfd *abfd, const gdb_byte *buf, unsigned int size)
15127 {
15128   /* If the size of a host char is 8 bits, we can return a pointer
15129      to the buffer, otherwise we have to copy the data to a buffer
15130      allocated on the temporary obstack.  */
15131   gdb_assert (HOST_CHAR_BIT == 8);
15132   return buf;
15133 }
15134
15135 static const char *
15136 read_direct_string (bfd *abfd, const gdb_byte *buf,
15137                     unsigned int *bytes_read_ptr)
15138 {
15139   /* If the size of a host char is 8 bits, we can return a pointer
15140      to the string, otherwise we have to copy the string to a buffer
15141      allocated on the temporary obstack.  */
15142   gdb_assert (HOST_CHAR_BIT == 8);
15143   if (*buf == '\0')
15144     {
15145       *bytes_read_ptr = 1;
15146       return NULL;
15147     }
15148   *bytes_read_ptr = strlen ((const char *) buf) + 1;
15149   return (const char *) buf;
15150 }
15151
15152 static const char *
15153 read_indirect_string_at_offset (bfd *abfd, LONGEST str_offset)
15154 {
15155   dwarf2_read_section (dwarf2_per_objfile->objfile, &dwarf2_per_objfile->str);
15156   if (dwarf2_per_objfile->str.buffer == NULL)
15157     error (_("DW_FORM_strp used without .debug_str section [in module %s]"),
15158            bfd_get_filename (abfd));
15159   if (str_offset >= dwarf2_per_objfile->str.size)
15160     error (_("DW_FORM_strp pointing outside of "
15161              ".debug_str section [in module %s]"),
15162            bfd_get_filename (abfd));
15163   gdb_assert (HOST_CHAR_BIT == 8);
15164   if (dwarf2_per_objfile->str.buffer[str_offset] == '\0')
15165     return NULL;
15166   return (const char *) (dwarf2_per_objfile->str.buffer + str_offset);
15167 }
15168
15169 /* Read a string at offset STR_OFFSET in the .debug_str section from
15170    the .dwz file DWZ.  Throw an error if the offset is too large.  If
15171    the string consists of a single NUL byte, return NULL; otherwise
15172    return a pointer to the string.  */
15173
15174 static const char *
15175 read_indirect_string_from_dwz (struct dwz_file *dwz, LONGEST str_offset)
15176 {
15177   dwarf2_read_section (dwarf2_per_objfile->objfile, &dwz->str);
15178
15179   if (dwz->str.buffer == NULL)
15180     error (_("DW_FORM_GNU_strp_alt used without .debug_str "
15181              "section [in module %s]"),
15182            bfd_get_filename (dwz->dwz_bfd));
15183   if (str_offset >= dwz->str.size)
15184     error (_("DW_FORM_GNU_strp_alt pointing outside of "
15185              ".debug_str section [in module %s]"),
15186            bfd_get_filename (dwz->dwz_bfd));
15187   gdb_assert (HOST_CHAR_BIT == 8);
15188   if (dwz->str.buffer[str_offset] == '\0')
15189     return NULL;
15190   return (const char *) (dwz->str.buffer + str_offset);
15191 }
15192
15193 static const char *
15194 read_indirect_string (bfd *abfd, const gdb_byte *buf,
15195                       const struct comp_unit_head *cu_header,
15196                       unsigned int *bytes_read_ptr)
15197 {
15198   LONGEST str_offset = read_offset (abfd, buf, cu_header, bytes_read_ptr);
15199
15200   return read_indirect_string_at_offset (abfd, str_offset);
15201 }
15202
15203 static ULONGEST
15204 read_unsigned_leb128 (bfd *abfd, const gdb_byte *buf,
15205                       unsigned int *bytes_read_ptr)
15206 {
15207   ULONGEST result;
15208   unsigned int num_read;
15209   int i, shift;
15210   unsigned char byte;
15211
15212   result = 0;
15213   shift = 0;
15214   num_read = 0;
15215   i = 0;
15216   while (1)
15217     {
15218       byte = bfd_get_8 (abfd, buf);
15219       buf++;
15220       num_read++;
15221       result |= ((ULONGEST) (byte & 127) << shift);
15222       if ((byte & 128) == 0)
15223         {
15224           break;
15225         }
15226       shift += 7;
15227     }
15228   *bytes_read_ptr = num_read;
15229   return result;
15230 }
15231
15232 static LONGEST
15233 read_signed_leb128 (bfd *abfd, const gdb_byte *buf,
15234                     unsigned int *bytes_read_ptr)
15235 {
15236   LONGEST result;
15237   int i, shift, num_read;
15238   unsigned char byte;
15239
15240   result = 0;
15241   shift = 0;
15242   num_read = 0;
15243   i = 0;
15244   while (1)
15245     {
15246       byte = bfd_get_8 (abfd, buf);
15247       buf++;
15248       num_read++;
15249       result |= ((LONGEST) (byte & 127) << shift);
15250       shift += 7;
15251       if ((byte & 128) == 0)
15252         {
15253           break;
15254         }
15255     }
15256   if ((shift < 8 * sizeof (result)) && (byte & 0x40))
15257     result |= -(((LONGEST) 1) << shift);
15258   *bytes_read_ptr = num_read;
15259   return result;
15260 }
15261
15262 /* Given index ADDR_INDEX in .debug_addr, fetch the value.
15263    ADDR_BASE is the DW_AT_GNU_addr_base attribute or zero.
15264    ADDR_SIZE is the size of addresses from the CU header.  */
15265
15266 static CORE_ADDR
15267 read_addr_index_1 (unsigned int addr_index, ULONGEST addr_base, int addr_size)
15268 {
15269   struct objfile *objfile = dwarf2_per_objfile->objfile;
15270   bfd *abfd = objfile->obfd;
15271   const gdb_byte *info_ptr;
15272
15273   dwarf2_read_section (objfile, &dwarf2_per_objfile->addr);
15274   if (dwarf2_per_objfile->addr.buffer == NULL)
15275     error (_("DW_FORM_addr_index used without .debug_addr section [in module %s]"),
15276            objfile->name);
15277   if (addr_base + addr_index * addr_size >= dwarf2_per_objfile->addr.size)
15278     error (_("DW_FORM_addr_index pointing outside of "
15279              ".debug_addr section [in module %s]"),
15280            objfile->name);
15281   info_ptr = (dwarf2_per_objfile->addr.buffer
15282               + addr_base + addr_index * addr_size);
15283   if (addr_size == 4)
15284     return bfd_get_32 (abfd, info_ptr);
15285   else
15286     return bfd_get_64 (abfd, info_ptr);
15287 }
15288
15289 /* Given index ADDR_INDEX in .debug_addr, fetch the value.  */
15290
15291 static CORE_ADDR
15292 read_addr_index (struct dwarf2_cu *cu, unsigned int addr_index)
15293 {
15294   return read_addr_index_1 (addr_index, cu->addr_base, cu->header.addr_size);
15295 }
15296
15297 /* Given a pointer to an leb128 value, fetch the value from .debug_addr.  */
15298
15299 static CORE_ADDR
15300 read_addr_index_from_leb128 (struct dwarf2_cu *cu, const gdb_byte *info_ptr,
15301                              unsigned int *bytes_read)
15302 {
15303   bfd *abfd = cu->objfile->obfd;
15304   unsigned int addr_index = read_unsigned_leb128 (abfd, info_ptr, bytes_read);
15305
15306   return read_addr_index (cu, addr_index);
15307 }
15308
15309 /* Data structure to pass results from dwarf2_read_addr_index_reader
15310    back to dwarf2_read_addr_index.  */
15311
15312 struct dwarf2_read_addr_index_data
15313 {
15314   ULONGEST addr_base;
15315   int addr_size;
15316 };
15317
15318 /* die_reader_func for dwarf2_read_addr_index.  */
15319
15320 static void
15321 dwarf2_read_addr_index_reader (const struct die_reader_specs *reader,
15322                                const gdb_byte *info_ptr,
15323                                struct die_info *comp_unit_die,
15324                                int has_children,
15325                                void *data)
15326 {
15327   struct dwarf2_cu *cu = reader->cu;
15328   struct dwarf2_read_addr_index_data *aidata =
15329     (struct dwarf2_read_addr_index_data *) data;
15330
15331   aidata->addr_base = cu->addr_base;
15332   aidata->addr_size = cu->header.addr_size;
15333 }
15334
15335 /* Given an index in .debug_addr, fetch the value.
15336    NOTE: This can be called during dwarf expression evaluation,
15337    long after the debug information has been read, and thus per_cu->cu
15338    may no longer exist.  */
15339
15340 CORE_ADDR
15341 dwarf2_read_addr_index (struct dwarf2_per_cu_data *per_cu,
15342                         unsigned int addr_index)
15343 {
15344   struct objfile *objfile = per_cu->objfile;
15345   struct dwarf2_cu *cu = per_cu->cu;
15346   ULONGEST addr_base;
15347   int addr_size;
15348
15349   /* This is intended to be called from outside this file.  */
15350   dw2_setup (objfile);
15351
15352   /* We need addr_base and addr_size.
15353      If we don't have PER_CU->cu, we have to get it.
15354      Nasty, but the alternative is storing the needed info in PER_CU,
15355      which at this point doesn't seem justified: it's not clear how frequently
15356      it would get used and it would increase the size of every PER_CU.
15357      Entry points like dwarf2_per_cu_addr_size do a similar thing
15358      so we're not in uncharted territory here.
15359      Alas we need to be a bit more complicated as addr_base is contained
15360      in the DIE.
15361
15362      We don't need to read the entire CU(/TU).
15363      We just need the header and top level die.
15364
15365      IWBN to use the aging mechanism to let us lazily later discard the CU.
15366      For now we skip this optimization.  */
15367
15368   if (cu != NULL)
15369     {
15370       addr_base = cu->addr_base;
15371       addr_size = cu->header.addr_size;
15372     }
15373   else
15374     {
15375       struct dwarf2_read_addr_index_data aidata;
15376
15377       /* Note: We can't use init_cutu_and_read_dies_simple here,
15378          we need addr_base.  */
15379       init_cutu_and_read_dies (per_cu, NULL, 0, 0,
15380                                dwarf2_read_addr_index_reader, &aidata);
15381       addr_base = aidata.addr_base;
15382       addr_size = aidata.addr_size;
15383     }
15384
15385   return read_addr_index_1 (addr_index, addr_base, addr_size);
15386 }
15387
15388 /* Given a DW_AT_str_index, fetch the string.  */
15389
15390 static const char *
15391 read_str_index (const struct die_reader_specs *reader,
15392                 struct dwarf2_cu *cu, ULONGEST str_index)
15393 {
15394   struct objfile *objfile = dwarf2_per_objfile->objfile;
15395   const char *dwo_name = objfile->name;
15396   bfd *abfd = objfile->obfd;
15397   struct dwo_sections *sections = &reader->dwo_file->sections;
15398   const gdb_byte *info_ptr;
15399   ULONGEST str_offset;
15400
15401   dwarf2_read_section (objfile, &sections->str);
15402   dwarf2_read_section (objfile, &sections->str_offsets);
15403   if (sections->str.buffer == NULL)
15404     error (_("DW_FORM_str_index used without .debug_str.dwo section"
15405              " in CU at offset 0x%lx [in module %s]"),
15406            (long) cu->header.offset.sect_off, dwo_name);
15407   if (sections->str_offsets.buffer == NULL)
15408     error (_("DW_FORM_str_index used without .debug_str_offsets.dwo section"
15409              " in CU at offset 0x%lx [in module %s]"),
15410            (long) cu->header.offset.sect_off, dwo_name);
15411   if (str_index * cu->header.offset_size >= sections->str_offsets.size)
15412     error (_("DW_FORM_str_index pointing outside of .debug_str_offsets.dwo"
15413              " section in CU at offset 0x%lx [in module %s]"),
15414            (long) cu->header.offset.sect_off, dwo_name);
15415   info_ptr = (sections->str_offsets.buffer
15416               + str_index * cu->header.offset_size);
15417   if (cu->header.offset_size == 4)
15418     str_offset = bfd_get_32 (abfd, info_ptr);
15419   else
15420     str_offset = bfd_get_64 (abfd, info_ptr);
15421   if (str_offset >= sections->str.size)
15422     error (_("Offset from DW_FORM_str_index pointing outside of"
15423              " .debug_str.dwo section in CU at offset 0x%lx [in module %s]"),
15424            (long) cu->header.offset.sect_off, dwo_name);
15425   return (const char *) (sections->str.buffer + str_offset);
15426 }
15427
15428 /* Return the length of an LEB128 number in BUF.  */
15429
15430 static int
15431 leb128_size (const gdb_byte *buf)
15432 {
15433   const gdb_byte *begin = buf;
15434   gdb_byte byte;
15435
15436   while (1)
15437     {
15438       byte = *buf++;
15439       if ((byte & 128) == 0)
15440         return buf - begin;
15441     }
15442 }
15443
15444 static void
15445 set_cu_language (unsigned int lang, struct dwarf2_cu *cu)
15446 {
15447   switch (lang)
15448     {
15449     case DW_LANG_C89:
15450     case DW_LANG_C99:
15451     case DW_LANG_C:
15452     case DW_LANG_UPC:
15453       cu->language = language_c;
15454       break;
15455     case DW_LANG_C_plus_plus:
15456       cu->language = language_cplus;
15457       break;
15458     case DW_LANG_D:
15459       cu->language = language_d;
15460       break;
15461     case DW_LANG_Fortran77:
15462     case DW_LANG_Fortran90:
15463     case DW_LANG_Fortran95:
15464       cu->language = language_fortran;
15465       break;
15466     case DW_LANG_Go:
15467       cu->language = language_go;
15468       break;
15469     case DW_LANG_Mips_Assembler:
15470       cu->language = language_asm;
15471       break;
15472     case DW_LANG_Java:
15473       cu->language = language_java;
15474       break;
15475     case DW_LANG_Ada83:
15476     case DW_LANG_Ada95:
15477       cu->language = language_ada;
15478       break;
15479     case DW_LANG_Modula2:
15480       cu->language = language_m2;
15481       break;
15482     case DW_LANG_Pascal83:
15483       cu->language = language_pascal;
15484       break;
15485     case DW_LANG_ObjC:
15486       cu->language = language_objc;
15487       break;
15488     case DW_LANG_Cobol74:
15489     case DW_LANG_Cobol85:
15490     default:
15491       cu->language = language_minimal;
15492       break;
15493     }
15494   cu->language_defn = language_def (cu->language);
15495 }
15496
15497 /* Return the named attribute or NULL if not there.  */
15498
15499 static struct attribute *
15500 dwarf2_attr (struct die_info *die, unsigned int name, struct dwarf2_cu *cu)
15501 {
15502   for (;;)
15503     {
15504       unsigned int i;
15505       struct attribute *spec = NULL;
15506
15507       for (i = 0; i < die->num_attrs; ++i)
15508         {
15509           if (die->attrs[i].name == name)
15510             return &die->attrs[i];
15511           if (die->attrs[i].name == DW_AT_specification
15512               || die->attrs[i].name == DW_AT_abstract_origin)
15513             spec = &die->attrs[i];
15514         }
15515
15516       if (!spec)
15517         break;
15518
15519       die = follow_die_ref (die, spec, &cu);
15520     }
15521
15522   return NULL;
15523 }
15524
15525 /* Return the named attribute or NULL if not there,
15526    but do not follow DW_AT_specification, etc.
15527    This is for use in contexts where we're reading .debug_types dies.
15528    Following DW_AT_specification, DW_AT_abstract_origin will take us
15529    back up the chain, and we want to go down.  */
15530
15531 static struct attribute *
15532 dwarf2_attr_no_follow (struct die_info *die, unsigned int name)
15533 {
15534   unsigned int i;
15535
15536   for (i = 0; i < die->num_attrs; ++i)
15537     if (die->attrs[i].name == name)
15538       return &die->attrs[i];
15539
15540   return NULL;
15541 }
15542
15543 /* Return non-zero iff the attribute NAME is defined for the given DIE,
15544    and holds a non-zero value.  This function should only be used for
15545    DW_FORM_flag or DW_FORM_flag_present attributes.  */
15546
15547 static int
15548 dwarf2_flag_true_p (struct die_info *die, unsigned name, struct dwarf2_cu *cu)
15549 {
15550   struct attribute *attr = dwarf2_attr (die, name, cu);
15551
15552   return (attr && DW_UNSND (attr));
15553 }
15554
15555 static int
15556 die_is_declaration (struct die_info *die, struct dwarf2_cu *cu)
15557 {
15558   /* A DIE is a declaration if it has a DW_AT_declaration attribute
15559      which value is non-zero.  However, we have to be careful with
15560      DIEs having a DW_AT_specification attribute, because dwarf2_attr()
15561      (via dwarf2_flag_true_p) follows this attribute.  So we may
15562      end up accidently finding a declaration attribute that belongs
15563      to a different DIE referenced by the specification attribute,
15564      even though the given DIE does not have a declaration attribute.  */
15565   return (dwarf2_flag_true_p (die, DW_AT_declaration, cu)
15566           && dwarf2_attr (die, DW_AT_specification, cu) == NULL);
15567 }
15568
15569 /* Return the die giving the specification for DIE, if there is
15570    one.  *SPEC_CU is the CU containing DIE on input, and the CU
15571    containing the return value on output.  If there is no
15572    specification, but there is an abstract origin, that is
15573    returned.  */
15574
15575 static struct die_info *
15576 die_specification (struct die_info *die, struct dwarf2_cu **spec_cu)
15577 {
15578   struct attribute *spec_attr = dwarf2_attr (die, DW_AT_specification,
15579                                              *spec_cu);
15580
15581   if (spec_attr == NULL)
15582     spec_attr = dwarf2_attr (die, DW_AT_abstract_origin, *spec_cu);
15583
15584   if (spec_attr == NULL)
15585     return NULL;
15586   else
15587     return follow_die_ref (die, spec_attr, spec_cu);
15588 }
15589
15590 /* Free the line_header structure *LH, and any arrays and strings it
15591    refers to.
15592    NOTE: This is also used as a "cleanup" function.  */
15593
15594 static void
15595 free_line_header (struct line_header *lh)
15596 {
15597   if (lh->standard_opcode_lengths)
15598     xfree (lh->standard_opcode_lengths);
15599
15600   /* Remember that all the lh->file_names[i].name pointers are
15601      pointers into debug_line_buffer, and don't need to be freed.  */
15602   if (lh->file_names)
15603     xfree (lh->file_names);
15604
15605   /* Similarly for the include directory names.  */
15606   if (lh->include_dirs)
15607     xfree (lh->include_dirs);
15608
15609   xfree (lh);
15610 }
15611
15612 /* Add an entry to LH's include directory table.  */
15613
15614 static void
15615 add_include_dir (struct line_header *lh, const char *include_dir)
15616 {
15617   /* Grow the array if necessary.  */
15618   if (lh->include_dirs_size == 0)
15619     {
15620       lh->include_dirs_size = 1; /* for testing */
15621       lh->include_dirs = xmalloc (lh->include_dirs_size
15622                                   * sizeof (*lh->include_dirs));
15623     }
15624   else if (lh->num_include_dirs >= lh->include_dirs_size)
15625     {
15626       lh->include_dirs_size *= 2;
15627       lh->include_dirs = xrealloc (lh->include_dirs,
15628                                    (lh->include_dirs_size
15629                                     * sizeof (*lh->include_dirs)));
15630     }
15631
15632   lh->include_dirs[lh->num_include_dirs++] = include_dir;
15633 }
15634
15635 /* Add an entry to LH's file name table.  */
15636
15637 static void
15638 add_file_name (struct line_header *lh,
15639                const char *name,
15640                unsigned int dir_index,
15641                unsigned int mod_time,
15642                unsigned int length)
15643 {
15644   struct file_entry *fe;
15645
15646   /* Grow the array if necessary.  */
15647   if (lh->file_names_size == 0)
15648     {
15649       lh->file_names_size = 1; /* for testing */
15650       lh->file_names = xmalloc (lh->file_names_size
15651                                 * sizeof (*lh->file_names));
15652     }
15653   else if (lh->num_file_names >= lh->file_names_size)
15654     {
15655       lh->file_names_size *= 2;
15656       lh->file_names = xrealloc (lh->file_names,
15657                                  (lh->file_names_size
15658                                   * sizeof (*lh->file_names)));
15659     }
15660
15661   fe = &lh->file_names[lh->num_file_names++];
15662   fe->name = name;
15663   fe->dir_index = dir_index;
15664   fe->mod_time = mod_time;
15665   fe->length = length;
15666   fe->included_p = 0;
15667   fe->symtab = NULL;
15668 }
15669
15670 /* A convenience function to find the proper .debug_line section for a
15671    CU.  */
15672
15673 static struct dwarf2_section_info *
15674 get_debug_line_section (struct dwarf2_cu *cu)
15675 {
15676   struct dwarf2_section_info *section;
15677
15678   /* For TUs in DWO files, the DW_AT_stmt_list attribute lives in the
15679      DWO file.  */
15680   if (cu->dwo_unit && cu->per_cu->is_debug_types)
15681     section = &cu->dwo_unit->dwo_file->sections.line;
15682   else if (cu->per_cu->is_dwz)
15683     {
15684       struct dwz_file *dwz = dwarf2_get_dwz_file ();
15685
15686       section = &dwz->line;
15687     }
15688   else
15689     section = &dwarf2_per_objfile->line;
15690
15691   return section;
15692 }
15693
15694 /* Read the statement program header starting at OFFSET in
15695    .debug_line, or .debug_line.dwo.  Return a pointer
15696    to a struct line_header, allocated using xmalloc.
15697
15698    NOTE: the strings in the include directory and file name tables of
15699    the returned object point into the dwarf line section buffer,
15700    and must not be freed.  */
15701
15702 static struct line_header *
15703 dwarf_decode_line_header (unsigned int offset, struct dwarf2_cu *cu)
15704 {
15705   struct cleanup *back_to;
15706   struct line_header *lh;
15707   const gdb_byte *line_ptr;
15708   unsigned int bytes_read, offset_size;
15709   int i;
15710   const char *cur_dir, *cur_file;
15711   struct dwarf2_section_info *section;
15712   bfd *abfd;
15713
15714   section = get_debug_line_section (cu);
15715   dwarf2_read_section (dwarf2_per_objfile->objfile, section);
15716   if (section->buffer == NULL)
15717     {
15718       if (cu->dwo_unit && cu->per_cu->is_debug_types)
15719         complaint (&symfile_complaints, _("missing .debug_line.dwo section"));
15720       else
15721         complaint (&symfile_complaints, _("missing .debug_line section"));
15722       return 0;
15723     }
15724
15725   /* We can't do this until we know the section is non-empty.
15726      Only then do we know we have such a section.  */
15727   abfd = section->asection->owner;
15728
15729   /* Make sure that at least there's room for the total_length field.
15730      That could be 12 bytes long, but we're just going to fudge that.  */
15731   if (offset + 4 >= section->size)
15732     {
15733       dwarf2_statement_list_fits_in_line_number_section_complaint ();
15734       return 0;
15735     }
15736
15737   lh = xmalloc (sizeof (*lh));
15738   memset (lh, 0, sizeof (*lh));
15739   back_to = make_cleanup ((make_cleanup_ftype *) free_line_header,
15740                           (void *) lh);
15741
15742   line_ptr = section->buffer + offset;
15743
15744   /* Read in the header.  */
15745   lh->total_length =
15746     read_checked_initial_length_and_offset (abfd, line_ptr, &cu->header,
15747                                             &bytes_read, &offset_size);
15748   line_ptr += bytes_read;
15749   if (line_ptr + lh->total_length > (section->buffer + section->size))
15750     {
15751       dwarf2_statement_list_fits_in_line_number_section_complaint ();
15752       do_cleanups (back_to);
15753       return 0;
15754     }
15755   lh->statement_program_end = line_ptr + lh->total_length;
15756   lh->version = read_2_bytes (abfd, line_ptr);
15757   line_ptr += 2;
15758   lh->header_length = read_offset_1 (abfd, line_ptr, offset_size);
15759   line_ptr += offset_size;
15760   lh->minimum_instruction_length = read_1_byte (abfd, line_ptr);
15761   line_ptr += 1;
15762   if (lh->version >= 4)
15763     {
15764       lh->maximum_ops_per_instruction = read_1_byte (abfd, line_ptr);
15765       line_ptr += 1;
15766     }
15767   else
15768     lh->maximum_ops_per_instruction = 1;
15769
15770   if (lh->maximum_ops_per_instruction == 0)
15771     {
15772       lh->maximum_ops_per_instruction = 1;
15773       complaint (&symfile_complaints,
15774                  _("invalid maximum_ops_per_instruction "
15775                    "in `.debug_line' section"));
15776     }
15777
15778   lh->default_is_stmt = read_1_byte (abfd, line_ptr);
15779   line_ptr += 1;
15780   lh->line_base = read_1_signed_byte (abfd, line_ptr);
15781   line_ptr += 1;
15782   lh->line_range = read_1_byte (abfd, line_ptr);
15783   line_ptr += 1;
15784   lh->opcode_base = read_1_byte (abfd, line_ptr);
15785   line_ptr += 1;
15786   lh->standard_opcode_lengths
15787     = xmalloc (lh->opcode_base * sizeof (lh->standard_opcode_lengths[0]));
15788
15789   lh->standard_opcode_lengths[0] = 1;  /* This should never be used anyway.  */
15790   for (i = 1; i < lh->opcode_base; ++i)
15791     {
15792       lh->standard_opcode_lengths[i] = read_1_byte (abfd, line_ptr);
15793       line_ptr += 1;
15794     }
15795
15796   /* Read directory table.  */
15797   while ((cur_dir = read_direct_string (abfd, line_ptr, &bytes_read)) != NULL)
15798     {
15799       line_ptr += bytes_read;
15800       add_include_dir (lh, cur_dir);
15801     }
15802   line_ptr += bytes_read;
15803
15804   /* Read file name table.  */
15805   while ((cur_file = read_direct_string (abfd, line_ptr, &bytes_read)) != NULL)
15806     {
15807       unsigned int dir_index, mod_time, length;
15808
15809       line_ptr += bytes_read;
15810       dir_index = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
15811       line_ptr += bytes_read;
15812       mod_time = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
15813       line_ptr += bytes_read;
15814       length = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
15815       line_ptr += bytes_read;
15816
15817       add_file_name (lh, cur_file, dir_index, mod_time, length);
15818     }
15819   line_ptr += bytes_read;
15820   lh->statement_program_start = line_ptr;
15821
15822   if (line_ptr > (section->buffer + section->size))
15823     complaint (&symfile_complaints,
15824                _("line number info header doesn't "
15825                  "fit in `.debug_line' section"));
15826
15827   discard_cleanups (back_to);
15828   return lh;
15829 }
15830
15831 /* Subroutine of dwarf_decode_lines to simplify it.
15832    Return the file name of the psymtab for included file FILE_INDEX
15833    in line header LH of PST.
15834    COMP_DIR is the compilation directory (DW_AT_comp_dir) or NULL if unknown.
15835    If space for the result is malloc'd, it will be freed by a cleanup.
15836    Returns NULL if FILE_INDEX should be ignored, i.e., it is pst->filename.
15837
15838    The function creates dangling cleanup registration.  */
15839
15840 static const char *
15841 psymtab_include_file_name (const struct line_header *lh, int file_index,
15842                            const struct partial_symtab *pst,
15843                            const char *comp_dir)
15844 {
15845   const struct file_entry fe = lh->file_names [file_index];
15846   const char *include_name = fe.name;
15847   const char *include_name_to_compare = include_name;
15848   const char *dir_name = NULL;
15849   const char *pst_filename;
15850   char *copied_name = NULL;
15851   int file_is_pst;
15852
15853   if (fe.dir_index)
15854     dir_name = lh->include_dirs[fe.dir_index - 1];
15855
15856   if (!IS_ABSOLUTE_PATH (include_name)
15857       && (dir_name != NULL || comp_dir != NULL))
15858     {
15859       /* Avoid creating a duplicate psymtab for PST.
15860          We do this by comparing INCLUDE_NAME and PST_FILENAME.
15861          Before we do the comparison, however, we need to account
15862          for DIR_NAME and COMP_DIR.
15863          First prepend dir_name (if non-NULL).  If we still don't
15864          have an absolute path prepend comp_dir (if non-NULL).
15865          However, the directory we record in the include-file's
15866          psymtab does not contain COMP_DIR (to match the
15867          corresponding symtab(s)).
15868
15869          Example:
15870
15871          bash$ cd /tmp
15872          bash$ gcc -g ./hello.c
15873          include_name = "hello.c"
15874          dir_name = "."
15875          DW_AT_comp_dir = comp_dir = "/tmp"
15876          DW_AT_name = "./hello.c"  */
15877
15878       if (dir_name != NULL)
15879         {
15880           char *tem = concat (dir_name, SLASH_STRING,
15881                               include_name, (char *)NULL);
15882
15883           make_cleanup (xfree, tem);
15884           include_name = tem;
15885           include_name_to_compare = include_name;
15886         }
15887       if (!IS_ABSOLUTE_PATH (include_name) && comp_dir != NULL)
15888         {
15889           char *tem = concat (comp_dir, SLASH_STRING,
15890                               include_name, (char *)NULL);
15891
15892           make_cleanup (xfree, tem);
15893           include_name_to_compare = tem;
15894         }
15895     }
15896
15897   pst_filename = pst->filename;
15898   if (!IS_ABSOLUTE_PATH (pst_filename) && pst->dirname != NULL)
15899     {
15900       copied_name = concat (pst->dirname, SLASH_STRING,
15901                             pst_filename, (char *)NULL);
15902       pst_filename = copied_name;
15903     }
15904
15905   file_is_pst = FILENAME_CMP (include_name_to_compare, pst_filename) == 0;
15906
15907   if (copied_name != NULL)
15908     xfree (copied_name);
15909
15910   if (file_is_pst)
15911     return NULL;
15912   return include_name;
15913 }
15914
15915 /* Ignore this record_line request.  */
15916
15917 static void
15918 noop_record_line (struct subfile *subfile, int line, CORE_ADDR pc)
15919 {
15920   return;
15921 }
15922
15923 /* Subroutine of dwarf_decode_lines to simplify it.
15924    Process the line number information in LH.  */
15925
15926 static void
15927 dwarf_decode_lines_1 (struct line_header *lh, const char *comp_dir,
15928                       struct dwarf2_cu *cu, struct partial_symtab *pst)
15929 {
15930   const gdb_byte *line_ptr, *extended_end;
15931   const gdb_byte *line_end;
15932   unsigned int bytes_read, extended_len;
15933   unsigned char op_code, extended_op, adj_opcode;
15934   CORE_ADDR baseaddr;
15935   struct objfile *objfile = cu->objfile;
15936   bfd *abfd = objfile->obfd;
15937   struct gdbarch *gdbarch = get_objfile_arch (objfile);
15938   const int decode_for_pst_p = (pst != NULL);
15939   struct subfile *last_subfile = NULL;
15940   void (*p_record_line) (struct subfile *subfile, int line, CORE_ADDR pc)
15941     = record_line;
15942
15943   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
15944
15945   line_ptr = lh->statement_program_start;
15946   line_end = lh->statement_program_end;
15947
15948   /* Read the statement sequences until there's nothing left.  */
15949   while (line_ptr < line_end)
15950     {
15951       /* state machine registers  */
15952       CORE_ADDR address = 0;
15953       unsigned int file = 1;
15954       unsigned int line = 1;
15955       unsigned int column = 0;
15956       int is_stmt = lh->default_is_stmt;
15957       int basic_block = 0;
15958       int end_sequence = 0;
15959       CORE_ADDR addr;
15960       unsigned char op_index = 0;
15961
15962       if (!decode_for_pst_p && lh->num_file_names >= file)
15963         {
15964           /* Start a subfile for the current file of the state machine.  */
15965           /* lh->include_dirs and lh->file_names are 0-based, but the
15966              directory and file name numbers in the statement program
15967              are 1-based.  */
15968           struct file_entry *fe = &lh->file_names[file - 1];
15969           const char *dir = NULL;
15970
15971           if (fe->dir_index)
15972             dir = lh->include_dirs[fe->dir_index - 1];
15973
15974           dwarf2_start_subfile (fe->name, dir, comp_dir);
15975         }
15976
15977       /* Decode the table.  */
15978       while (!end_sequence)
15979         {
15980           op_code = read_1_byte (abfd, line_ptr);
15981           line_ptr += 1;
15982           if (line_ptr > line_end)
15983             {
15984               dwarf2_debug_line_missing_end_sequence_complaint ();
15985               break;
15986             }
15987
15988           if (op_code >= lh->opcode_base)
15989             {
15990               /* Special operand.  */
15991               adj_opcode = op_code - lh->opcode_base;
15992               address += (((op_index + (adj_opcode / lh->line_range))
15993                            / lh->maximum_ops_per_instruction)
15994                           * lh->minimum_instruction_length);
15995               op_index = ((op_index + (adj_opcode / lh->line_range))
15996                           % lh->maximum_ops_per_instruction);
15997               line += lh->line_base + (adj_opcode % lh->line_range);
15998               if (lh->num_file_names < file || file == 0)
15999                 dwarf2_debug_line_missing_file_complaint ();
16000               /* For now we ignore lines not starting on an
16001                  instruction boundary.  */
16002               else if (op_index == 0)
16003                 {
16004                   lh->file_names[file - 1].included_p = 1;
16005                   if (!decode_for_pst_p && is_stmt)
16006                     {
16007                       if (last_subfile != current_subfile)
16008                         {
16009                           addr = gdbarch_addr_bits_remove (gdbarch, address);
16010                           if (last_subfile)
16011                             (*p_record_line) (last_subfile, 0, addr);
16012                           last_subfile = current_subfile;
16013                         }
16014                       /* Append row to matrix using current values.  */
16015                       addr = gdbarch_addr_bits_remove (gdbarch, address);
16016                       (*p_record_line) (current_subfile, line, addr);
16017                     }
16018                 }
16019               basic_block = 0;
16020             }
16021           else switch (op_code)
16022             {
16023             case DW_LNS_extended_op:
16024               extended_len = read_unsigned_leb128 (abfd, line_ptr,
16025                                                    &bytes_read);
16026               line_ptr += bytes_read;
16027               extended_end = line_ptr + extended_len;
16028               extended_op = read_1_byte (abfd, line_ptr);
16029               line_ptr += 1;
16030               switch (extended_op)
16031                 {
16032                 case DW_LNE_end_sequence:
16033                   p_record_line = record_line;
16034                   end_sequence = 1;
16035                   break;
16036                 case DW_LNE_set_address:
16037                   address = read_address (abfd, line_ptr, cu, &bytes_read);
16038
16039                   if (address == 0 && !dwarf2_per_objfile->has_section_at_zero)
16040                     {
16041                       /* This line table is for a function which has been
16042                          GCd by the linker.  Ignore it.  PR gdb/12528 */
16043
16044                       long line_offset
16045                         = line_ptr - get_debug_line_section (cu)->buffer;
16046
16047                       complaint (&symfile_complaints,
16048                                  _(".debug_line address at offset 0x%lx is 0 "
16049                                    "[in module %s]"),
16050                                  line_offset, objfile->name);
16051                       p_record_line = noop_record_line;
16052                     }
16053
16054                   op_index = 0;
16055                   line_ptr += bytes_read;
16056                   address += baseaddr;
16057                   break;
16058                 case DW_LNE_define_file:
16059                   {
16060                     const char *cur_file;
16061                     unsigned int dir_index, mod_time, length;
16062
16063                     cur_file = read_direct_string (abfd, line_ptr,
16064                                                    &bytes_read);
16065                     line_ptr += bytes_read;
16066                     dir_index =
16067                       read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
16068                     line_ptr += bytes_read;
16069                     mod_time =
16070                       read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
16071                     line_ptr += bytes_read;
16072                     length =
16073                       read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
16074                     line_ptr += bytes_read;
16075                     add_file_name (lh, cur_file, dir_index, mod_time, length);
16076                   }
16077                   break;
16078                 case DW_LNE_set_discriminator:
16079                   /* The discriminator is not interesting to the debugger;
16080                      just ignore it.  */
16081                   line_ptr = extended_end;
16082                   break;
16083                 default:
16084                   complaint (&symfile_complaints,
16085                              _("mangled .debug_line section"));
16086                   return;
16087                 }
16088               /* Make sure that we parsed the extended op correctly.  If e.g.
16089                  we expected a different address size than the producer used,
16090                  we may have read the wrong number of bytes.  */
16091               if (line_ptr != extended_end)
16092                 {
16093                   complaint (&symfile_complaints,
16094                              _("mangled .debug_line section"));
16095                   return;
16096                 }
16097               break;
16098             case DW_LNS_copy:
16099               if (lh->num_file_names < file || file == 0)
16100                 dwarf2_debug_line_missing_file_complaint ();
16101               else
16102                 {
16103                   lh->file_names[file - 1].included_p = 1;
16104                   if (!decode_for_pst_p && is_stmt)
16105                     {
16106                       if (last_subfile != current_subfile)
16107                         {
16108                           addr = gdbarch_addr_bits_remove (gdbarch, address);
16109                           if (last_subfile)
16110                             (*p_record_line) (last_subfile, 0, addr);
16111                           last_subfile = current_subfile;
16112                         }
16113                       addr = gdbarch_addr_bits_remove (gdbarch, address);
16114                       (*p_record_line) (current_subfile, line, addr);
16115                     }
16116                 }
16117               basic_block = 0;
16118               break;
16119             case DW_LNS_advance_pc:
16120               {
16121                 CORE_ADDR adjust
16122                   = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
16123
16124                 address += (((op_index + adjust)
16125                              / lh->maximum_ops_per_instruction)
16126                             * lh->minimum_instruction_length);
16127                 op_index = ((op_index + adjust)
16128                             % lh->maximum_ops_per_instruction);
16129                 line_ptr += bytes_read;
16130               }
16131               break;
16132             case DW_LNS_advance_line:
16133               line += read_signed_leb128 (abfd, line_ptr, &bytes_read);
16134               line_ptr += bytes_read;
16135               break;
16136             case DW_LNS_set_file:
16137               {
16138                 /* The arrays lh->include_dirs and lh->file_names are
16139                    0-based, but the directory and file name numbers in
16140                    the statement program are 1-based.  */
16141                 struct file_entry *fe;
16142                 const char *dir = NULL;
16143
16144                 file = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
16145                 line_ptr += bytes_read;
16146                 if (lh->num_file_names < file || file == 0)
16147                   dwarf2_debug_line_missing_file_complaint ();
16148                 else
16149                   {
16150                     fe = &lh->file_names[file - 1];
16151                     if (fe->dir_index)
16152                       dir = lh->include_dirs[fe->dir_index - 1];
16153                     if (!decode_for_pst_p)
16154                       {
16155                         last_subfile = current_subfile;
16156                         dwarf2_start_subfile (fe->name, dir, comp_dir);
16157                       }
16158                   }
16159               }
16160               break;
16161             case DW_LNS_set_column:
16162               column = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
16163               line_ptr += bytes_read;
16164               break;
16165             case DW_LNS_negate_stmt:
16166               is_stmt = (!is_stmt);
16167               break;
16168             case DW_LNS_set_basic_block:
16169               basic_block = 1;
16170               break;
16171             /* Add to the address register of the state machine the
16172                address increment value corresponding to special opcode
16173                255.  I.e., this value is scaled by the minimum
16174                instruction length since special opcode 255 would have
16175                scaled the increment.  */
16176             case DW_LNS_const_add_pc:
16177               {
16178                 CORE_ADDR adjust = (255 - lh->opcode_base) / lh->line_range;
16179
16180                 address += (((op_index + adjust)
16181                              / lh->maximum_ops_per_instruction)
16182                             * lh->minimum_instruction_length);
16183                 op_index = ((op_index + adjust)
16184                             % lh->maximum_ops_per_instruction);
16185               }
16186               break;
16187             case DW_LNS_fixed_advance_pc:
16188               address += read_2_bytes (abfd, line_ptr);
16189               op_index = 0;
16190               line_ptr += 2;
16191               break;
16192             default:
16193               {
16194                 /* Unknown standard opcode, ignore it.  */
16195                 int i;
16196
16197                 for (i = 0; i < lh->standard_opcode_lengths[op_code]; i++)
16198                   {
16199                     (void) read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
16200                     line_ptr += bytes_read;
16201                   }
16202               }
16203             }
16204         }
16205       if (lh->num_file_names < file || file == 0)
16206         dwarf2_debug_line_missing_file_complaint ();
16207       else
16208         {
16209           lh->file_names[file - 1].included_p = 1;
16210           if (!decode_for_pst_p)
16211             {
16212               addr = gdbarch_addr_bits_remove (gdbarch, address);
16213               (*p_record_line) (current_subfile, 0, addr);
16214             }
16215         }
16216     }
16217 }
16218
16219 /* Decode the Line Number Program (LNP) for the given line_header
16220    structure and CU.  The actual information extracted and the type
16221    of structures created from the LNP depends on the value of PST.
16222
16223    1. If PST is NULL, then this procedure uses the data from the program
16224       to create all necessary symbol tables, and their linetables.
16225
16226    2. If PST is not NULL, this procedure reads the program to determine
16227       the list of files included by the unit represented by PST, and
16228       builds all the associated partial symbol tables.
16229
16230    COMP_DIR is the compilation directory (DW_AT_comp_dir) or NULL if unknown.
16231    It is used for relative paths in the line table.
16232    NOTE: When processing partial symtabs (pst != NULL),
16233    comp_dir == pst->dirname.
16234
16235    NOTE: It is important that psymtabs have the same file name (via strcmp)
16236    as the corresponding symtab.  Since COMP_DIR is not used in the name of the
16237    symtab we don't use it in the name of the psymtabs we create.
16238    E.g. expand_line_sal requires this when finding psymtabs to expand.
16239    A good testcase for this is mb-inline.exp.  */
16240
16241 static void
16242 dwarf_decode_lines (struct line_header *lh, const char *comp_dir,
16243                     struct dwarf2_cu *cu, struct partial_symtab *pst,
16244                     int want_line_info)
16245 {
16246   struct objfile *objfile = cu->objfile;
16247   const int decode_for_pst_p = (pst != NULL);
16248   struct subfile *first_subfile = current_subfile;
16249
16250   if (want_line_info)
16251     dwarf_decode_lines_1 (lh, comp_dir, cu, pst);
16252
16253   if (decode_for_pst_p)
16254     {
16255       int file_index;
16256
16257       /* Now that we're done scanning the Line Header Program, we can
16258          create the psymtab of each included file.  */
16259       for (file_index = 0; file_index < lh->num_file_names; file_index++)
16260         if (lh->file_names[file_index].included_p == 1)
16261           {
16262             const char *include_name =
16263               psymtab_include_file_name (lh, file_index, pst, comp_dir);
16264             if (include_name != NULL)
16265               dwarf2_create_include_psymtab (include_name, pst, objfile);
16266           }
16267     }
16268   else
16269     {
16270       /* Make sure a symtab is created for every file, even files
16271          which contain only variables (i.e. no code with associated
16272          line numbers).  */
16273       int i;
16274
16275       for (i = 0; i < lh->num_file_names; i++)
16276         {
16277           const char *dir = NULL;
16278           struct file_entry *fe;
16279
16280           fe = &lh->file_names[i];
16281           if (fe->dir_index)
16282             dir = lh->include_dirs[fe->dir_index - 1];
16283           dwarf2_start_subfile (fe->name, dir, comp_dir);
16284
16285           /* Skip the main file; we don't need it, and it must be
16286              allocated last, so that it will show up before the
16287              non-primary symtabs in the objfile's symtab list.  */
16288           if (current_subfile == first_subfile)
16289             continue;
16290
16291           if (current_subfile->symtab == NULL)
16292             current_subfile->symtab = allocate_symtab (current_subfile->name,
16293                                                        objfile);
16294           fe->symtab = current_subfile->symtab;
16295         }
16296     }
16297 }
16298
16299 /* Start a subfile for DWARF.  FILENAME is the name of the file and
16300    DIRNAME the name of the source directory which contains FILENAME
16301    or NULL if not known.  COMP_DIR is the compilation directory for the
16302    linetable's compilation unit or NULL if not known.
16303    This routine tries to keep line numbers from identical absolute and
16304    relative file names in a common subfile.
16305
16306    Using the `list' example from the GDB testsuite, which resides in
16307    /srcdir and compiling it with Irix6.2 cc in /compdir using a filename
16308    of /srcdir/list0.c yields the following debugging information for list0.c:
16309
16310    DW_AT_name:          /srcdir/list0.c
16311    DW_AT_comp_dir:              /compdir
16312    files.files[0].name: list0.h
16313    files.files[0].dir:  /srcdir
16314    files.files[1].name: list0.c
16315    files.files[1].dir:  /srcdir
16316
16317    The line number information for list0.c has to end up in a single
16318    subfile, so that `break /srcdir/list0.c:1' works as expected.
16319    start_subfile will ensure that this happens provided that we pass the
16320    concatenation of files.files[1].dir and files.files[1].name as the
16321    subfile's name.  */
16322
16323 static void
16324 dwarf2_start_subfile (const char *filename, const char *dirname,
16325                       const char *comp_dir)
16326 {
16327   char *copy = NULL;
16328
16329   /* While reading the DIEs, we call start_symtab(DW_AT_name, DW_AT_comp_dir).
16330      `start_symtab' will always pass the contents of DW_AT_comp_dir as
16331      second argument to start_subfile.  To be consistent, we do the
16332      same here.  In order not to lose the line information directory,
16333      we concatenate it to the filename when it makes sense.
16334      Note that the Dwarf3 standard says (speaking of filenames in line
16335      information): ``The directory index is ignored for file names
16336      that represent full path names''.  Thus ignoring dirname in the
16337      `else' branch below isn't an issue.  */
16338
16339   if (!IS_ABSOLUTE_PATH (filename) && dirname != NULL)
16340     {
16341       copy = concat (dirname, SLASH_STRING, filename, (char *)NULL);
16342       filename = copy;
16343     }
16344
16345   start_subfile (filename, comp_dir);
16346
16347   if (copy != NULL)
16348     xfree (copy);
16349 }
16350
16351 /* Start a symtab for DWARF.
16352    NAME, COMP_DIR, LOW_PC are passed to start_symtab.  */
16353
16354 static void
16355 dwarf2_start_symtab (struct dwarf2_cu *cu,
16356                      const char *name, const char *comp_dir, CORE_ADDR low_pc)
16357 {
16358   start_symtab (name, comp_dir, low_pc);
16359   record_debugformat ("DWARF 2");
16360   record_producer (cu->producer);
16361
16362   /* We assume that we're processing GCC output.  */
16363   processing_gcc_compilation = 2;
16364
16365   cu->processing_has_namespace_info = 0;
16366 }
16367
16368 static void
16369 var_decode_location (struct attribute *attr, struct symbol *sym,
16370                      struct dwarf2_cu *cu)
16371 {
16372   struct objfile *objfile = cu->objfile;
16373   struct comp_unit_head *cu_header = &cu->header;
16374
16375   /* NOTE drow/2003-01-30: There used to be a comment and some special
16376      code here to turn a symbol with DW_AT_external and a
16377      SYMBOL_VALUE_ADDRESS of 0 into a LOC_UNRESOLVED symbol.  This was
16378      necessary for platforms (maybe Alpha, certainly PowerPC GNU/Linux
16379      with some versions of binutils) where shared libraries could have
16380      relocations against symbols in their debug information - the
16381      minimal symbol would have the right address, but the debug info
16382      would not.  It's no longer necessary, because we will explicitly
16383      apply relocations when we read in the debug information now.  */
16384
16385   /* A DW_AT_location attribute with no contents indicates that a
16386      variable has been optimized away.  */
16387   if (attr_form_is_block (attr) && DW_BLOCK (attr)->size == 0)
16388     {
16389       SYMBOL_ACLASS_INDEX (sym) = LOC_OPTIMIZED_OUT;
16390       return;
16391     }
16392
16393   /* Handle one degenerate form of location expression specially, to
16394      preserve GDB's previous behavior when section offsets are
16395      specified.  If this is just a DW_OP_addr or DW_OP_GNU_addr_index
16396      then mark this symbol as LOC_STATIC.  */
16397
16398   if (attr_form_is_block (attr)
16399       && ((DW_BLOCK (attr)->data[0] == DW_OP_addr
16400            && DW_BLOCK (attr)->size == 1 + cu_header->addr_size)
16401           || (DW_BLOCK (attr)->data[0] == DW_OP_GNU_addr_index
16402               && (DW_BLOCK (attr)->size
16403                   == 1 + leb128_size (&DW_BLOCK (attr)->data[1])))))
16404     {
16405       unsigned int dummy;
16406
16407       if (DW_BLOCK (attr)->data[0] == DW_OP_addr)
16408         SYMBOL_VALUE_ADDRESS (sym) =
16409           read_address (objfile->obfd, DW_BLOCK (attr)->data + 1, cu, &dummy);
16410       else
16411         SYMBOL_VALUE_ADDRESS (sym) =
16412           read_addr_index_from_leb128 (cu, DW_BLOCK (attr)->data + 1, &dummy);
16413       SYMBOL_ACLASS_INDEX (sym) = LOC_STATIC;
16414       fixup_symbol_section (sym, objfile);
16415       SYMBOL_VALUE_ADDRESS (sym) += ANOFFSET (objfile->section_offsets,
16416                                               SYMBOL_SECTION (sym));
16417       return;
16418     }
16419
16420   /* NOTE drow/2002-01-30: It might be worthwhile to have a static
16421      expression evaluator, and use LOC_COMPUTED only when necessary
16422      (i.e. when the value of a register or memory location is
16423      referenced, or a thread-local block, etc.).  Then again, it might
16424      not be worthwhile.  I'm assuming that it isn't unless performance
16425      or memory numbers show me otherwise.  */
16426
16427   dwarf2_symbol_mark_computed (attr, sym, cu, 0);
16428
16429   if (SYMBOL_COMPUTED_OPS (sym)->location_has_loclist)
16430     cu->has_loclist = 1;
16431 }
16432
16433 /* Given a pointer to a DWARF information entry, figure out if we need
16434    to make a symbol table entry for it, and if so, create a new entry
16435    and return a pointer to it.
16436    If TYPE is NULL, determine symbol type from the die, otherwise
16437    used the passed type.
16438    If SPACE is not NULL, use it to hold the new symbol.  If it is
16439    NULL, allocate a new symbol on the objfile's obstack.  */
16440
16441 static struct symbol *
16442 new_symbol_full (struct die_info *die, struct type *type, struct dwarf2_cu *cu,
16443                  struct symbol *space)
16444 {
16445   struct objfile *objfile = cu->objfile;
16446   struct symbol *sym = NULL;
16447   const char *name;
16448   struct attribute *attr = NULL;
16449   struct attribute *attr2 = NULL;
16450   CORE_ADDR baseaddr;
16451   struct pending **list_to_add = NULL;
16452
16453   int inlined_func = (die->tag == DW_TAG_inlined_subroutine);
16454
16455   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
16456
16457   name = dwarf2_name (die, cu);
16458   if (name)
16459     {
16460       const char *linkagename;
16461       int suppress_add = 0;
16462
16463       if (space)
16464         sym = space;
16465       else
16466         sym = allocate_symbol (objfile);
16467       OBJSTAT (objfile, n_syms++);
16468
16469       /* Cache this symbol's name and the name's demangled form (if any).  */
16470       SYMBOL_SET_LANGUAGE (sym, cu->language, &objfile->objfile_obstack);
16471       linkagename = dwarf2_physname (name, die, cu);
16472       SYMBOL_SET_NAMES (sym, linkagename, strlen (linkagename), 0, objfile);
16473
16474       /* Fortran does not have mangling standard and the mangling does differ
16475          between gfortran, iFort etc.  */
16476       if (cu->language == language_fortran
16477           && symbol_get_demangled_name (&(sym->ginfo)) == NULL)
16478         symbol_set_demangled_name (&(sym->ginfo),
16479                                    dwarf2_full_name (name, die, cu),
16480                                    NULL);
16481
16482       /* Default assumptions.
16483          Use the passed type or decode it from the die.  */
16484       SYMBOL_DOMAIN (sym) = VAR_DOMAIN;
16485       SYMBOL_ACLASS_INDEX (sym) = LOC_OPTIMIZED_OUT;
16486       if (type != NULL)
16487         SYMBOL_TYPE (sym) = type;
16488       else
16489         SYMBOL_TYPE (sym) = die_type (die, cu);
16490       attr = dwarf2_attr (die,
16491                           inlined_func ? DW_AT_call_line : DW_AT_decl_line,
16492                           cu);
16493       if (attr)
16494         {
16495           SYMBOL_LINE (sym) = DW_UNSND (attr);
16496         }
16497
16498       attr = dwarf2_attr (die,
16499                           inlined_func ? DW_AT_call_file : DW_AT_decl_file,
16500                           cu);
16501       if (attr)
16502         {
16503           int file_index = DW_UNSND (attr);
16504
16505           if (cu->line_header == NULL
16506               || file_index > cu->line_header->num_file_names)
16507             complaint (&symfile_complaints,
16508                        _("file index out of range"));
16509           else if (file_index > 0)
16510             {
16511               struct file_entry *fe;
16512
16513               fe = &cu->line_header->file_names[file_index - 1];
16514               SYMBOL_SYMTAB (sym) = fe->symtab;
16515             }
16516         }
16517
16518       switch (die->tag)
16519         {
16520         case DW_TAG_label:
16521           attr = dwarf2_attr (die, DW_AT_low_pc, cu);
16522           if (attr)
16523             {
16524               SYMBOL_VALUE_ADDRESS (sym) = DW_ADDR (attr) + baseaddr;
16525             }
16526           SYMBOL_TYPE (sym) = objfile_type (objfile)->builtin_core_addr;
16527           SYMBOL_DOMAIN (sym) = LABEL_DOMAIN;
16528           SYMBOL_ACLASS_INDEX (sym) = LOC_LABEL;
16529           add_symbol_to_list (sym, cu->list_in_scope);
16530           break;
16531         case DW_TAG_subprogram:
16532           /* SYMBOL_BLOCK_VALUE (sym) will be filled in later by
16533              finish_block.  */
16534           SYMBOL_ACLASS_INDEX (sym) = LOC_BLOCK;
16535           attr2 = dwarf2_attr (die, DW_AT_external, cu);
16536           if ((attr2 && (DW_UNSND (attr2) != 0))
16537               || cu->language == language_ada)
16538             {
16539               /* Subprograms marked external are stored as a global symbol.
16540                  Ada subprograms, whether marked external or not, are always
16541                  stored as a global symbol, because we want to be able to
16542                  access them globally.  For instance, we want to be able
16543                  to break on a nested subprogram without having to
16544                  specify the context.  */
16545               list_to_add = &global_symbols;
16546             }
16547           else
16548             {
16549               list_to_add = cu->list_in_scope;
16550             }
16551           break;
16552         case DW_TAG_inlined_subroutine:
16553           /* SYMBOL_BLOCK_VALUE (sym) will be filled in later by
16554              finish_block.  */
16555           SYMBOL_ACLASS_INDEX (sym) = LOC_BLOCK;
16556           SYMBOL_INLINED (sym) = 1;
16557           list_to_add = cu->list_in_scope;
16558           break;
16559         case DW_TAG_template_value_param:
16560           suppress_add = 1;
16561           /* Fall through.  */
16562         case DW_TAG_constant:
16563         case DW_TAG_variable:
16564         case DW_TAG_member:
16565           /* Compilation with minimal debug info may result in
16566              variables with missing type entries.  Change the
16567              misleading `void' type to something sensible.  */
16568           if (TYPE_CODE (SYMBOL_TYPE (sym)) == TYPE_CODE_VOID)
16569             SYMBOL_TYPE (sym)
16570               = objfile_type (objfile)->nodebug_data_symbol;
16571
16572           attr = dwarf2_attr (die, DW_AT_const_value, cu);
16573           /* In the case of DW_TAG_member, we should only be called for
16574              static const members.  */
16575           if (die->tag == DW_TAG_member)
16576             {
16577               /* dwarf2_add_field uses die_is_declaration,
16578                  so we do the same.  */
16579               gdb_assert (die_is_declaration (die, cu));
16580               gdb_assert (attr);
16581             }
16582           if (attr)
16583             {
16584               dwarf2_const_value (attr, sym, cu);
16585               attr2 = dwarf2_attr (die, DW_AT_external, cu);
16586               if (!suppress_add)
16587                 {
16588                   if (attr2 && (DW_UNSND (attr2) != 0))
16589                     list_to_add = &global_symbols;
16590                   else
16591                     list_to_add = cu->list_in_scope;
16592                 }
16593               break;
16594             }
16595           attr = dwarf2_attr (die, DW_AT_location, cu);
16596           if (attr)
16597             {
16598               var_decode_location (attr, sym, cu);
16599               attr2 = dwarf2_attr (die, DW_AT_external, cu);
16600
16601               /* Fortran explicitly imports any global symbols to the local
16602                  scope by DW_TAG_common_block.  */
16603               if (cu->language == language_fortran && die->parent
16604                   && die->parent->tag == DW_TAG_common_block)
16605                 attr2 = NULL;
16606
16607               if (SYMBOL_CLASS (sym) == LOC_STATIC
16608                   && SYMBOL_VALUE_ADDRESS (sym) == 0
16609                   && !dwarf2_per_objfile->has_section_at_zero)
16610                 {
16611                   /* When a static variable is eliminated by the linker,
16612                      the corresponding debug information is not stripped
16613                      out, but the variable address is set to null;
16614                      do not add such variables into symbol table.  */
16615                 }
16616               else if (attr2 && (DW_UNSND (attr2) != 0))
16617                 {
16618                   /* Workaround gfortran PR debug/40040 - it uses
16619                      DW_AT_location for variables in -fPIC libraries which may
16620                      get overriden by other libraries/executable and get
16621                      a different address.  Resolve it by the minimal symbol
16622                      which may come from inferior's executable using copy
16623                      relocation.  Make this workaround only for gfortran as for
16624                      other compilers GDB cannot guess the minimal symbol
16625                      Fortran mangling kind.  */
16626                   if (cu->language == language_fortran && die->parent
16627                       && die->parent->tag == DW_TAG_module
16628                       && cu->producer
16629                       && strncmp (cu->producer, "GNU Fortran ", 12) == 0)
16630                     SYMBOL_ACLASS_INDEX (sym) = LOC_UNRESOLVED;
16631
16632                   /* A variable with DW_AT_external is never static,
16633                      but it may be block-scoped.  */
16634                   list_to_add = (cu->list_in_scope == &file_symbols
16635                                  ? &global_symbols : cu->list_in_scope);
16636                 }
16637               else
16638                 list_to_add = cu->list_in_scope;
16639             }
16640           else
16641             {
16642               /* We do not know the address of this symbol.
16643                  If it is an external symbol and we have type information
16644                  for it, enter the symbol as a LOC_UNRESOLVED symbol.
16645                  The address of the variable will then be determined from
16646                  the minimal symbol table whenever the variable is
16647                  referenced.  */
16648               attr2 = dwarf2_attr (die, DW_AT_external, cu);
16649
16650               /* Fortran explicitly imports any global symbols to the local
16651                  scope by DW_TAG_common_block.  */
16652               if (cu->language == language_fortran && die->parent
16653                   && die->parent->tag == DW_TAG_common_block)
16654                 {
16655                   /* SYMBOL_CLASS doesn't matter here because
16656                      read_common_block is going to reset it.  */
16657                   if (!suppress_add)
16658                     list_to_add = cu->list_in_scope;
16659                 }
16660               else if (attr2 && (DW_UNSND (attr2) != 0)
16661                        && dwarf2_attr (die, DW_AT_type, cu) != NULL)
16662                 {
16663                   /* A variable with DW_AT_external is never static, but it
16664                      may be block-scoped.  */
16665                   list_to_add = (cu->list_in_scope == &file_symbols
16666                                  ? &global_symbols : cu->list_in_scope);
16667
16668                   SYMBOL_ACLASS_INDEX (sym) = LOC_UNRESOLVED;
16669                 }
16670               else if (!die_is_declaration (die, cu))
16671                 {
16672                   /* Use the default LOC_OPTIMIZED_OUT class.  */
16673                   gdb_assert (SYMBOL_CLASS (sym) == LOC_OPTIMIZED_OUT);
16674                   if (!suppress_add)
16675                     list_to_add = cu->list_in_scope;
16676                 }
16677             }
16678           break;
16679         case DW_TAG_formal_parameter:
16680           /* If we are inside a function, mark this as an argument.  If
16681              not, we might be looking at an argument to an inlined function
16682              when we do not have enough information to show inlined frames;
16683              pretend it's a local variable in that case so that the user can
16684              still see it.  */
16685           if (context_stack_depth > 0
16686               && context_stack[context_stack_depth - 1].name != NULL)
16687             SYMBOL_IS_ARGUMENT (sym) = 1;
16688           attr = dwarf2_attr (die, DW_AT_location, cu);
16689           if (attr)
16690             {
16691               var_decode_location (attr, sym, cu);
16692             }
16693           attr = dwarf2_attr (die, DW_AT_const_value, cu);
16694           if (attr)
16695             {
16696               dwarf2_const_value (attr, sym, cu);
16697             }
16698
16699           list_to_add = cu->list_in_scope;
16700           break;
16701         case DW_TAG_unspecified_parameters:
16702           /* From varargs functions; gdb doesn't seem to have any
16703              interest in this information, so just ignore it for now.
16704              (FIXME?) */
16705           break;
16706         case DW_TAG_template_type_param:
16707           suppress_add = 1;
16708           /* Fall through.  */
16709         case DW_TAG_class_type:
16710         case DW_TAG_interface_type:
16711         case DW_TAG_structure_type:
16712         case DW_TAG_union_type:
16713         case DW_TAG_set_type:
16714         case DW_TAG_enumeration_type:
16715           SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
16716           SYMBOL_DOMAIN (sym) = STRUCT_DOMAIN;
16717
16718           {
16719             /* NOTE: carlton/2003-11-10: C++ and Java class symbols shouldn't
16720                really ever be static objects: otherwise, if you try
16721                to, say, break of a class's method and you're in a file
16722                which doesn't mention that class, it won't work unless
16723                the check for all static symbols in lookup_symbol_aux
16724                saves you.  See the OtherFileClass tests in
16725                gdb.c++/namespace.exp.  */
16726
16727             if (!suppress_add)
16728               {
16729                 list_to_add = (cu->list_in_scope == &file_symbols
16730                                && (cu->language == language_cplus
16731                                    || cu->language == language_java)
16732                                ? &global_symbols : cu->list_in_scope);
16733
16734                 /* The semantics of C++ state that "struct foo {
16735                    ... }" also defines a typedef for "foo".  A Java
16736                    class declaration also defines a typedef for the
16737                    class.  */
16738                 if (cu->language == language_cplus
16739                     || cu->language == language_java
16740                     || cu->language == language_ada)
16741                   {
16742                     /* The symbol's name is already allocated along
16743                        with this objfile, so we don't need to
16744                        duplicate it for the type.  */
16745                     if (TYPE_NAME (SYMBOL_TYPE (sym)) == 0)
16746                       TYPE_NAME (SYMBOL_TYPE (sym)) = SYMBOL_SEARCH_NAME (sym);
16747                   }
16748               }
16749           }
16750           break;
16751         case DW_TAG_typedef:
16752           SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
16753           SYMBOL_DOMAIN (sym) = VAR_DOMAIN;
16754           list_to_add = cu->list_in_scope;
16755           break;
16756         case DW_TAG_base_type:
16757         case DW_TAG_subrange_type:
16758           SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
16759           SYMBOL_DOMAIN (sym) = VAR_DOMAIN;
16760           list_to_add = cu->list_in_scope;
16761           break;
16762         case DW_TAG_enumerator:
16763           attr = dwarf2_attr (die, DW_AT_const_value, cu);
16764           if (attr)
16765             {
16766               dwarf2_const_value (attr, sym, cu);
16767             }
16768           {
16769             /* NOTE: carlton/2003-11-10: See comment above in the
16770                DW_TAG_class_type, etc. block.  */
16771
16772             list_to_add = (cu->list_in_scope == &file_symbols
16773                            && (cu->language == language_cplus
16774                                || cu->language == language_java)
16775                            ? &global_symbols : cu->list_in_scope);
16776           }
16777           break;
16778         case DW_TAG_namespace:
16779           SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
16780           list_to_add = &global_symbols;
16781           break;
16782         case DW_TAG_common_block:
16783           SYMBOL_ACLASS_INDEX (sym) = LOC_COMMON_BLOCK;
16784           SYMBOL_DOMAIN (sym) = COMMON_BLOCK_DOMAIN;
16785           add_symbol_to_list (sym, cu->list_in_scope);
16786           break;
16787         default:
16788           /* Not a tag we recognize.  Hopefully we aren't processing
16789              trash data, but since we must specifically ignore things
16790              we don't recognize, there is nothing else we should do at
16791              this point.  */
16792           complaint (&symfile_complaints, _("unsupported tag: '%s'"),
16793                      dwarf_tag_name (die->tag));
16794           break;
16795         }
16796
16797       if (suppress_add)
16798         {
16799           sym->hash_next = objfile->template_symbols;
16800           objfile->template_symbols = sym;
16801           list_to_add = NULL;
16802         }
16803
16804       if (list_to_add != NULL)
16805         add_symbol_to_list (sym, list_to_add);
16806
16807       /* For the benefit of old versions of GCC, check for anonymous
16808          namespaces based on the demangled name.  */
16809       if (!cu->processing_has_namespace_info
16810           && cu->language == language_cplus)
16811         cp_scan_for_anonymous_namespaces (sym, objfile);
16812     }
16813   return (sym);
16814 }
16815
16816 /* A wrapper for new_symbol_full that always allocates a new symbol.  */
16817
16818 static struct symbol *
16819 new_symbol (struct die_info *die, struct type *type, struct dwarf2_cu *cu)
16820 {
16821   return new_symbol_full (die, type, cu, NULL);
16822 }
16823
16824 /* Given an attr with a DW_FORM_dataN value in host byte order,
16825    zero-extend it as appropriate for the symbol's type.  The DWARF
16826    standard (v4) is not entirely clear about the meaning of using
16827    DW_FORM_dataN for a constant with a signed type, where the type is
16828    wider than the data.  The conclusion of a discussion on the DWARF
16829    list was that this is unspecified.  We choose to always zero-extend
16830    because that is the interpretation long in use by GCC.  */
16831
16832 static gdb_byte *
16833 dwarf2_const_value_data (const struct attribute *attr, struct obstack *obstack,
16834                          struct dwarf2_cu *cu, LONGEST *value, int bits)
16835 {
16836   struct objfile *objfile = cu->objfile;
16837   enum bfd_endian byte_order = bfd_big_endian (objfile->obfd) ?
16838                                 BFD_ENDIAN_BIG : BFD_ENDIAN_LITTLE;
16839   LONGEST l = DW_UNSND (attr);
16840
16841   if (bits < sizeof (*value) * 8)
16842     {
16843       l &= ((LONGEST) 1 << bits) - 1;
16844       *value = l;
16845     }
16846   else if (bits == sizeof (*value) * 8)
16847     *value = l;
16848   else
16849     {
16850       gdb_byte *bytes = obstack_alloc (obstack, bits / 8);
16851       store_unsigned_integer (bytes, bits / 8, byte_order, l);
16852       return bytes;
16853     }
16854
16855   return NULL;
16856 }
16857
16858 /* Read a constant value from an attribute.  Either set *VALUE, or if
16859    the value does not fit in *VALUE, set *BYTES - either already
16860    allocated on the objfile obstack, or newly allocated on OBSTACK,
16861    or, set *BATON, if we translated the constant to a location
16862    expression.  */
16863
16864 static void
16865 dwarf2_const_value_attr (const struct attribute *attr, struct type *type,
16866                          const char *name, struct obstack *obstack,
16867                          struct dwarf2_cu *cu,
16868                          LONGEST *value, const gdb_byte **bytes,
16869                          struct dwarf2_locexpr_baton **baton)
16870 {
16871   struct objfile *objfile = cu->objfile;
16872   struct comp_unit_head *cu_header = &cu->header;
16873   struct dwarf_block *blk;
16874   enum bfd_endian byte_order = (bfd_big_endian (objfile->obfd) ?
16875                                 BFD_ENDIAN_BIG : BFD_ENDIAN_LITTLE);
16876
16877   *value = 0;
16878   *bytes = NULL;
16879   *baton = NULL;
16880
16881   switch (attr->form)
16882     {
16883     case DW_FORM_addr:
16884     case DW_FORM_GNU_addr_index:
16885       {
16886         gdb_byte *data;
16887
16888         if (TYPE_LENGTH (type) != cu_header->addr_size)
16889           dwarf2_const_value_length_mismatch_complaint (name,
16890                                                         cu_header->addr_size,
16891                                                         TYPE_LENGTH (type));
16892         /* Symbols of this form are reasonably rare, so we just
16893            piggyback on the existing location code rather than writing
16894            a new implementation of symbol_computed_ops.  */
16895         *baton = obstack_alloc (obstack, sizeof (struct dwarf2_locexpr_baton));
16896         (*baton)->per_cu = cu->per_cu;
16897         gdb_assert ((*baton)->per_cu);
16898
16899         (*baton)->size = 2 + cu_header->addr_size;
16900         data = obstack_alloc (obstack, (*baton)->size);
16901         (*baton)->data = data;
16902
16903         data[0] = DW_OP_addr;
16904         store_unsigned_integer (&data[1], cu_header->addr_size,
16905                                 byte_order, DW_ADDR (attr));
16906         data[cu_header->addr_size + 1] = DW_OP_stack_value;
16907       }
16908       break;
16909     case DW_FORM_string:
16910     case DW_FORM_strp:
16911     case DW_FORM_GNU_str_index:
16912     case DW_FORM_GNU_strp_alt:
16913       /* DW_STRING is already allocated on the objfile obstack, point
16914          directly to it.  */
16915       *bytes = (const gdb_byte *) DW_STRING (attr);
16916       break;
16917     case DW_FORM_block1:
16918     case DW_FORM_block2:
16919     case DW_FORM_block4:
16920     case DW_FORM_block:
16921     case DW_FORM_exprloc:
16922       blk = DW_BLOCK (attr);
16923       if (TYPE_LENGTH (type) != blk->size)
16924         dwarf2_const_value_length_mismatch_complaint (name, blk->size,
16925                                                       TYPE_LENGTH (type));
16926       *bytes = blk->data;
16927       break;
16928
16929       /* The DW_AT_const_value attributes are supposed to carry the
16930          symbol's value "represented as it would be on the target
16931          architecture."  By the time we get here, it's already been
16932          converted to host endianness, so we just need to sign- or
16933          zero-extend it as appropriate.  */
16934     case DW_FORM_data1:
16935       *bytes = dwarf2_const_value_data (attr, obstack, cu, value, 8);
16936       break;
16937     case DW_FORM_data2:
16938       *bytes = dwarf2_const_value_data (attr, obstack, cu, value, 16);
16939       break;
16940     case DW_FORM_data4:
16941       *bytes = dwarf2_const_value_data (attr, obstack, cu, value, 32);
16942       break;
16943     case DW_FORM_data8:
16944       *bytes = dwarf2_const_value_data (attr, obstack, cu, value, 64);
16945       break;
16946
16947     case DW_FORM_sdata:
16948       *value = DW_SND (attr);
16949       break;
16950
16951     case DW_FORM_udata:
16952       *value = DW_UNSND (attr);
16953       break;
16954
16955     default:
16956       complaint (&symfile_complaints,
16957                  _("unsupported const value attribute form: '%s'"),
16958                  dwarf_form_name (attr->form));
16959       *value = 0;
16960       break;
16961     }
16962 }
16963
16964
16965 /* Copy constant value from an attribute to a symbol.  */
16966
16967 static void
16968 dwarf2_const_value (const struct attribute *attr, struct symbol *sym,
16969                     struct dwarf2_cu *cu)
16970 {
16971   struct objfile *objfile = cu->objfile;
16972   struct comp_unit_head *cu_header = &cu->header;
16973   LONGEST value;
16974   const gdb_byte *bytes;
16975   struct dwarf2_locexpr_baton *baton;
16976
16977   dwarf2_const_value_attr (attr, SYMBOL_TYPE (sym),
16978                            SYMBOL_PRINT_NAME (sym),
16979                            &objfile->objfile_obstack, cu,
16980                            &value, &bytes, &baton);
16981
16982   if (baton != NULL)
16983     {
16984       SYMBOL_LOCATION_BATON (sym) = baton;
16985       SYMBOL_ACLASS_INDEX (sym) = dwarf2_locexpr_index;
16986     }
16987   else if (bytes != NULL)
16988      {
16989       SYMBOL_VALUE_BYTES (sym) = bytes;
16990       SYMBOL_ACLASS_INDEX (sym) = LOC_CONST_BYTES;
16991     }
16992   else
16993     {
16994       SYMBOL_VALUE (sym) = value;
16995       SYMBOL_ACLASS_INDEX (sym) = LOC_CONST;
16996     }
16997 }
16998
16999 /* Return the type of the die in question using its DW_AT_type attribute.  */
17000
17001 static struct type *
17002 die_type (struct die_info *die, struct dwarf2_cu *cu)
17003 {
17004   struct attribute *type_attr;
17005
17006   type_attr = dwarf2_attr (die, DW_AT_type, cu);
17007   if (!type_attr)
17008     {
17009       /* A missing DW_AT_type represents a void type.  */
17010       return objfile_type (cu->objfile)->builtin_void;
17011     }
17012
17013   return lookup_die_type (die, type_attr, cu);
17014 }
17015
17016 /* True iff CU's producer generates GNAT Ada auxiliary information
17017    that allows to find parallel types through that information instead
17018    of having to do expensive parallel lookups by type name.  */
17019
17020 static int
17021 need_gnat_info (struct dwarf2_cu *cu)
17022 {
17023   /* FIXME: brobecker/2010-10-12: As of now, only the AdaCore version
17024      of GNAT produces this auxiliary information, without any indication
17025      that it is produced.  Part of enhancing the FSF version of GNAT
17026      to produce that information will be to put in place an indicator
17027      that we can use in order to determine whether the descriptive type
17028      info is available or not.  One suggestion that has been made is
17029      to use a new attribute, attached to the CU die.  For now, assume
17030      that the descriptive type info is not available.  */
17031   return 0;
17032 }
17033
17034 /* Return the auxiliary type of the die in question using its
17035    DW_AT_GNAT_descriptive_type attribute.  Returns NULL if the
17036    attribute is not present.  */
17037
17038 static struct type *
17039 die_descriptive_type (struct die_info *die, struct dwarf2_cu *cu)
17040 {
17041   struct attribute *type_attr;
17042
17043   type_attr = dwarf2_attr (die, DW_AT_GNAT_descriptive_type, cu);
17044   if (!type_attr)
17045     return NULL;
17046
17047   return lookup_die_type (die, type_attr, cu);
17048 }
17049
17050 /* If DIE has a descriptive_type attribute, then set the TYPE's
17051    descriptive type accordingly.  */
17052
17053 static void
17054 set_descriptive_type (struct type *type, struct die_info *die,
17055                       struct dwarf2_cu *cu)
17056 {
17057   struct type *descriptive_type = die_descriptive_type (die, cu);
17058
17059   if (descriptive_type)
17060     {
17061       ALLOCATE_GNAT_AUX_TYPE (type);
17062       TYPE_DESCRIPTIVE_TYPE (type) = descriptive_type;
17063     }
17064 }
17065
17066 /* Return the containing type of the die in question using its
17067    DW_AT_containing_type attribute.  */
17068
17069 static struct type *
17070 die_containing_type (struct die_info *die, struct dwarf2_cu *cu)
17071 {
17072   struct attribute *type_attr;
17073
17074   type_attr = dwarf2_attr (die, DW_AT_containing_type, cu);
17075   if (!type_attr)
17076     error (_("Dwarf Error: Problem turning containing type into gdb type "
17077              "[in module %s]"), cu->objfile->name);
17078
17079   return lookup_die_type (die, type_attr, cu);
17080 }
17081
17082 /* Return an error marker type to use for the ill formed type in DIE/CU.  */
17083
17084 static struct type *
17085 build_error_marker_type (struct dwarf2_cu *cu, struct die_info *die)
17086 {
17087   struct objfile *objfile = dwarf2_per_objfile->objfile;
17088   char *message, *saved;
17089
17090   message = xstrprintf (_("<unknown type in %s, CU 0x%x, DIE 0x%x>"),
17091                         objfile->name,
17092                         cu->header.offset.sect_off,
17093                         die->offset.sect_off);
17094   saved = obstack_copy0 (&objfile->objfile_obstack,
17095                          message, strlen (message));
17096   xfree (message);
17097
17098   return init_type (TYPE_CODE_ERROR, 0, 0, saved, objfile);
17099 }
17100
17101 /* Look up the type of DIE in CU using its type attribute ATTR.
17102    ATTR must be one of: DW_AT_type, DW_AT_GNAT_descriptive_type,
17103    DW_AT_containing_type.
17104    If there is no type substitute an error marker.  */
17105
17106 static struct type *
17107 lookup_die_type (struct die_info *die, const struct attribute *attr,
17108                  struct dwarf2_cu *cu)
17109 {
17110   struct objfile *objfile = cu->objfile;
17111   struct type *this_type;
17112
17113   gdb_assert (attr->name == DW_AT_type
17114               || attr->name == DW_AT_GNAT_descriptive_type
17115               || attr->name == DW_AT_containing_type);
17116
17117   /* First see if we have it cached.  */
17118
17119   if (attr->form == DW_FORM_GNU_ref_alt)
17120     {
17121       struct dwarf2_per_cu_data *per_cu;
17122       sect_offset offset = dwarf2_get_ref_die_offset (attr);
17123
17124       per_cu = dwarf2_find_containing_comp_unit (offset, 1, cu->objfile);
17125       this_type = get_die_type_at_offset (offset, per_cu);
17126     }
17127   else if (attr_form_is_ref (attr))
17128     {
17129       sect_offset offset = dwarf2_get_ref_die_offset (attr);
17130
17131       this_type = get_die_type_at_offset (offset, cu->per_cu);
17132     }
17133   else if (attr->form == DW_FORM_ref_sig8)
17134     {
17135       ULONGEST signature = DW_SIGNATURE (attr);
17136
17137       return get_signatured_type (die, signature, cu);
17138     }
17139   else
17140     {
17141       complaint (&symfile_complaints,
17142                  _("Dwarf Error: Bad type attribute %s in DIE"
17143                    " at 0x%x [in module %s]"),
17144                  dwarf_attr_name (attr->name), die->offset.sect_off,
17145                  objfile->name);
17146       return build_error_marker_type (cu, die);
17147     }
17148
17149   /* If not cached we need to read it in.  */
17150
17151   if (this_type == NULL)
17152     {
17153       struct die_info *type_die = NULL;
17154       struct dwarf2_cu *type_cu = cu;
17155
17156       if (attr_form_is_ref (attr))
17157         type_die = follow_die_ref (die, attr, &type_cu);
17158       if (type_die == NULL)
17159         return build_error_marker_type (cu, die);
17160       /* If we find the type now, it's probably because the type came
17161          from an inter-CU reference and the type's CU got expanded before
17162          ours.  */
17163       this_type = read_type_die (type_die, type_cu);
17164     }
17165
17166   /* If we still don't have a type use an error marker.  */
17167
17168   if (this_type == NULL)
17169     return build_error_marker_type (cu, die);
17170
17171   return this_type;
17172 }
17173
17174 /* Return the type in DIE, CU.
17175    Returns NULL for invalid types.
17176
17177    This first does a lookup in die_type_hash,
17178    and only reads the die in if necessary.
17179
17180    NOTE: This can be called when reading in partial or full symbols.  */
17181
17182 static struct type *
17183 read_type_die (struct die_info *die, struct dwarf2_cu *cu)
17184 {
17185   struct type *this_type;
17186
17187   this_type = get_die_type (die, cu);
17188   if (this_type)
17189     return this_type;
17190
17191   return read_type_die_1 (die, cu);
17192 }
17193
17194 /* Read the type in DIE, CU.
17195    Returns NULL for invalid types.  */
17196
17197 static struct type *
17198 read_type_die_1 (struct die_info *die, struct dwarf2_cu *cu)
17199 {
17200   struct type *this_type = NULL;
17201
17202   switch (die->tag)
17203     {
17204     case DW_TAG_class_type:
17205     case DW_TAG_interface_type:
17206     case DW_TAG_structure_type:
17207     case DW_TAG_union_type:
17208       this_type = read_structure_type (die, cu);
17209       break;
17210     case DW_TAG_enumeration_type:
17211       this_type = read_enumeration_type (die, cu);
17212       break;
17213     case DW_TAG_subprogram:
17214     case DW_TAG_subroutine_type:
17215     case DW_TAG_inlined_subroutine:
17216       this_type = read_subroutine_type (die, cu);
17217       break;
17218     case DW_TAG_array_type:
17219       this_type = read_array_type (die, cu);
17220       break;
17221     case DW_TAG_set_type:
17222       this_type = read_set_type (die, cu);
17223       break;
17224     case DW_TAG_pointer_type:
17225       this_type = read_tag_pointer_type (die, cu);
17226       break;
17227     case DW_TAG_ptr_to_member_type:
17228       this_type = read_tag_ptr_to_member_type (die, cu);
17229       break;
17230     case DW_TAG_reference_type:
17231       this_type = read_tag_reference_type (die, cu);
17232       break;
17233     case DW_TAG_const_type:
17234       this_type = read_tag_const_type (die, cu);
17235       break;
17236     case DW_TAG_volatile_type:
17237       this_type = read_tag_volatile_type (die, cu);
17238       break;
17239     case DW_TAG_restrict_type:
17240       this_type = read_tag_restrict_type (die, cu);
17241       break;
17242     case DW_TAG_string_type:
17243       this_type = read_tag_string_type (die, cu);
17244       break;
17245     case DW_TAG_typedef:
17246       this_type = read_typedef (die, cu);
17247       break;
17248     case DW_TAG_subrange_type:
17249       this_type = read_subrange_type (die, cu);
17250       break;
17251     case DW_TAG_base_type:
17252       this_type = read_base_type (die, cu);
17253       break;
17254     case DW_TAG_unspecified_type:
17255       this_type = read_unspecified_type (die, cu);
17256       break;
17257     case DW_TAG_namespace:
17258       this_type = read_namespace_type (die, cu);
17259       break;
17260     case DW_TAG_module:
17261       this_type = read_module_type (die, cu);
17262       break;
17263     default:
17264       complaint (&symfile_complaints,
17265                  _("unexpected tag in read_type_die: '%s'"),
17266                  dwarf_tag_name (die->tag));
17267       break;
17268     }
17269
17270   return this_type;
17271 }
17272
17273 /* See if we can figure out if the class lives in a namespace.  We do
17274    this by looking for a member function; its demangled name will
17275    contain namespace info, if there is any.
17276    Return the computed name or NULL.
17277    Space for the result is allocated on the objfile's obstack.
17278    This is the full-die version of guess_partial_die_structure_name.
17279    In this case we know DIE has no useful parent.  */
17280
17281 static char *
17282 guess_full_die_structure_name (struct die_info *die, struct dwarf2_cu *cu)
17283 {
17284   struct die_info *spec_die;
17285   struct dwarf2_cu *spec_cu;
17286   struct die_info *child;
17287
17288   spec_cu = cu;
17289   spec_die = die_specification (die, &spec_cu);
17290   if (spec_die != NULL)
17291     {
17292       die = spec_die;
17293       cu = spec_cu;
17294     }
17295
17296   for (child = die->child;
17297        child != NULL;
17298        child = child->sibling)
17299     {
17300       if (child->tag == DW_TAG_subprogram)
17301         {
17302           struct attribute *attr;
17303
17304           attr = dwarf2_attr (child, DW_AT_linkage_name, cu);
17305           if (attr == NULL)
17306             attr = dwarf2_attr (child, DW_AT_MIPS_linkage_name, cu);
17307           if (attr != NULL)
17308             {
17309               char *actual_name
17310                 = language_class_name_from_physname (cu->language_defn,
17311                                                      DW_STRING (attr));
17312               char *name = NULL;
17313
17314               if (actual_name != NULL)
17315                 {
17316                   const char *die_name = dwarf2_name (die, cu);
17317
17318                   if (die_name != NULL
17319                       && strcmp (die_name, actual_name) != 0)
17320                     {
17321                       /* Strip off the class name from the full name.
17322                          We want the prefix.  */
17323                       int die_name_len = strlen (die_name);
17324                       int actual_name_len = strlen (actual_name);
17325
17326                       /* Test for '::' as a sanity check.  */
17327                       if (actual_name_len > die_name_len + 2
17328                           && actual_name[actual_name_len
17329                                          - die_name_len - 1] == ':')
17330                         name =
17331                           obstack_copy0 (&cu->objfile->objfile_obstack,
17332                                          actual_name,
17333                                          actual_name_len - die_name_len - 2);
17334                     }
17335                 }
17336               xfree (actual_name);
17337               return name;
17338             }
17339         }
17340     }
17341
17342   return NULL;
17343 }
17344
17345 /* GCC might emit a nameless typedef that has a linkage name.  Determine the
17346    prefix part in such case.  See
17347    http://gcc.gnu.org/bugzilla/show_bug.cgi?id=47510.  */
17348
17349 static char *
17350 anonymous_struct_prefix (struct die_info *die, struct dwarf2_cu *cu)
17351 {
17352   struct attribute *attr;
17353   char *base;
17354
17355   if (die->tag != DW_TAG_class_type && die->tag != DW_TAG_interface_type
17356       && die->tag != DW_TAG_structure_type && die->tag != DW_TAG_union_type)
17357     return NULL;
17358
17359   attr = dwarf2_attr (die, DW_AT_name, cu);
17360   if (attr != NULL && DW_STRING (attr) != NULL)
17361     return NULL;
17362
17363   attr = dwarf2_attr (die, DW_AT_linkage_name, cu);
17364   if (attr == NULL)
17365     attr = dwarf2_attr (die, DW_AT_MIPS_linkage_name, cu);
17366   if (attr == NULL || DW_STRING (attr) == NULL)
17367     return NULL;
17368
17369   /* dwarf2_name had to be already called.  */
17370   gdb_assert (DW_STRING_IS_CANONICAL (attr));
17371
17372   /* Strip the base name, keep any leading namespaces/classes.  */
17373   base = strrchr (DW_STRING (attr), ':');
17374   if (base == NULL || base == DW_STRING (attr) || base[-1] != ':')
17375     return "";
17376
17377   return obstack_copy0 (&cu->objfile->objfile_obstack,
17378                         DW_STRING (attr), &base[-1] - DW_STRING (attr));
17379 }
17380
17381 /* Return the name of the namespace/class that DIE is defined within,
17382    or "" if we can't tell.  The caller should not xfree the result.
17383
17384    For example, if we're within the method foo() in the following
17385    code:
17386
17387    namespace N {
17388      class C {
17389        void foo () {
17390        }
17391      };
17392    }
17393
17394    then determine_prefix on foo's die will return "N::C".  */
17395
17396 static const char *
17397 determine_prefix (struct die_info *die, struct dwarf2_cu *cu)
17398 {
17399   struct die_info *parent, *spec_die;
17400   struct dwarf2_cu *spec_cu;
17401   struct type *parent_type;
17402   char *retval;
17403
17404   if (cu->language != language_cplus && cu->language != language_java
17405       && cu->language != language_fortran)
17406     return "";
17407
17408   retval = anonymous_struct_prefix (die, cu);
17409   if (retval)
17410     return retval;
17411
17412   /* We have to be careful in the presence of DW_AT_specification.
17413      For example, with GCC 3.4, given the code
17414
17415      namespace N {
17416        void foo() {
17417          // Definition of N::foo.
17418        }
17419      }
17420
17421      then we'll have a tree of DIEs like this:
17422
17423      1: DW_TAG_compile_unit
17424        2: DW_TAG_namespace        // N
17425          3: DW_TAG_subprogram     // declaration of N::foo
17426        4: DW_TAG_subprogram       // definition of N::foo
17427             DW_AT_specification   // refers to die #3
17428
17429      Thus, when processing die #4, we have to pretend that we're in
17430      the context of its DW_AT_specification, namely the contex of die
17431      #3.  */
17432   spec_cu = cu;
17433   spec_die = die_specification (die, &spec_cu);
17434   if (spec_die == NULL)
17435     parent = die->parent;
17436   else
17437     {
17438       parent = spec_die->parent;
17439       cu = spec_cu;
17440     }
17441
17442   if (parent == NULL)
17443     return "";
17444   else if (parent->building_fullname)
17445     {
17446       const char *name;
17447       const char *parent_name;
17448
17449       /* It has been seen on RealView 2.2 built binaries,
17450          DW_TAG_template_type_param types actually _defined_ as
17451          children of the parent class:
17452
17453          enum E {};
17454          template class <class Enum> Class{};
17455          Class<enum E> class_e;
17456
17457          1: DW_TAG_class_type (Class)
17458            2: DW_TAG_enumeration_type (E)
17459              3: DW_TAG_enumerator (enum1:0)
17460              3: DW_TAG_enumerator (enum2:1)
17461              ...
17462            2: DW_TAG_template_type_param
17463               DW_AT_type  DW_FORM_ref_udata (E)
17464
17465          Besides being broken debug info, it can put GDB into an
17466          infinite loop.  Consider:
17467
17468          When we're building the full name for Class<E>, we'll start
17469          at Class, and go look over its template type parameters,
17470          finding E.  We'll then try to build the full name of E, and
17471          reach here.  We're now trying to build the full name of E,
17472          and look over the parent DIE for containing scope.  In the
17473          broken case, if we followed the parent DIE of E, we'd again
17474          find Class, and once again go look at its template type
17475          arguments, etc., etc.  Simply don't consider such parent die
17476          as source-level parent of this die (it can't be, the language
17477          doesn't allow it), and break the loop here.  */
17478       name = dwarf2_name (die, cu);
17479       parent_name = dwarf2_name (parent, cu);
17480       complaint (&symfile_complaints,
17481                  _("template param type '%s' defined within parent '%s'"),
17482                  name ? name : "<unknown>",
17483                  parent_name ? parent_name : "<unknown>");
17484       return "";
17485     }
17486   else
17487     switch (parent->tag)
17488       {
17489       case DW_TAG_namespace:
17490         parent_type = read_type_die (parent, cu);
17491         /* GCC 4.0 and 4.1 had a bug (PR c++/28460) where they generated bogus
17492            DW_TAG_namespace DIEs with a name of "::" for the global namespace.
17493            Work around this problem here.  */
17494         if (cu->language == language_cplus
17495             && strcmp (TYPE_TAG_NAME (parent_type), "::") == 0)
17496           return "";
17497         /* We give a name to even anonymous namespaces.  */
17498         return TYPE_TAG_NAME (parent_type);
17499       case DW_TAG_class_type:
17500       case DW_TAG_interface_type:
17501       case DW_TAG_structure_type:
17502       case DW_TAG_union_type:
17503       case DW_TAG_module:
17504         parent_type = read_type_die (parent, cu);
17505         if (TYPE_TAG_NAME (parent_type) != NULL)
17506           return TYPE_TAG_NAME (parent_type);
17507         else
17508           /* An anonymous structure is only allowed non-static data
17509              members; no typedefs, no member functions, et cetera.
17510              So it does not need a prefix.  */
17511           return "";
17512       case DW_TAG_compile_unit:
17513       case DW_TAG_partial_unit:
17514         /* gcc-4.5 -gdwarf-4 can drop the enclosing namespace.  Cope.  */
17515         if (cu->language == language_cplus
17516             && !VEC_empty (dwarf2_section_info_def, dwarf2_per_objfile->types)
17517             && die->child != NULL
17518             && (die->tag == DW_TAG_class_type
17519                 || die->tag == DW_TAG_structure_type
17520                 || die->tag == DW_TAG_union_type))
17521           {
17522             char *name = guess_full_die_structure_name (die, cu);
17523             if (name != NULL)
17524               return name;
17525           }
17526         return "";
17527       default:
17528         return determine_prefix (parent, cu);
17529       }
17530 }
17531
17532 /* Return a newly-allocated string formed by concatenating PREFIX and SUFFIX
17533    with appropriate separator.  If PREFIX or SUFFIX is NULL or empty, then
17534    simply copy the SUFFIX or PREFIX, respectively.  If OBS is non-null, perform
17535    an obconcat, otherwise allocate storage for the result.  The CU argument is
17536    used to determine the language and hence, the appropriate separator.  */
17537
17538 #define MAX_SEP_LEN 7  /* strlen ("__") + strlen ("_MOD_")  */
17539
17540 static char *
17541 typename_concat (struct obstack *obs, const char *prefix, const char *suffix,
17542                  int physname, struct dwarf2_cu *cu)
17543 {
17544   const char *lead = "";
17545   const char *sep;
17546
17547   if (suffix == NULL || suffix[0] == '\0'
17548       || prefix == NULL || prefix[0] == '\0')
17549     sep = "";
17550   else if (cu->language == language_java)
17551     sep = ".";
17552   else if (cu->language == language_fortran && physname)
17553     {
17554       /* This is gfortran specific mangling.  Normally DW_AT_linkage_name or
17555          DW_AT_MIPS_linkage_name is preferred and used instead.  */
17556
17557       lead = "__";
17558       sep = "_MOD_";
17559     }
17560   else
17561     sep = "::";
17562
17563   if (prefix == NULL)
17564     prefix = "";
17565   if (suffix == NULL)
17566     suffix = "";
17567
17568   if (obs == NULL)
17569     {
17570       char *retval
17571         = xmalloc (strlen (prefix) + MAX_SEP_LEN + strlen (suffix) + 1);
17572
17573       strcpy (retval, lead);
17574       strcat (retval, prefix);
17575       strcat (retval, sep);
17576       strcat (retval, suffix);
17577       return retval;
17578     }
17579   else
17580     {
17581       /* We have an obstack.  */
17582       return obconcat (obs, lead, prefix, sep, suffix, (char *) NULL);
17583     }
17584 }
17585
17586 /* Return sibling of die, NULL if no sibling.  */
17587
17588 static struct die_info *
17589 sibling_die (struct die_info *die)
17590 {
17591   return die->sibling;
17592 }
17593
17594 /* Get name of a die, return NULL if not found.  */
17595
17596 static const char *
17597 dwarf2_canonicalize_name (const char *name, struct dwarf2_cu *cu,
17598                           struct obstack *obstack)
17599 {
17600   if (name && cu->language == language_cplus)
17601     {
17602       char *canon_name = cp_canonicalize_string (name);
17603
17604       if (canon_name != NULL)
17605         {
17606           if (strcmp (canon_name, name) != 0)
17607             name = obstack_copy0 (obstack, canon_name, strlen (canon_name));
17608           xfree (canon_name);
17609         }
17610     }
17611
17612   return name;
17613 }
17614
17615 /* Get name of a die, return NULL if not found.  */
17616
17617 static const char *
17618 dwarf2_name (struct die_info *die, struct dwarf2_cu *cu)
17619 {
17620   struct attribute *attr;
17621
17622   attr = dwarf2_attr (die, DW_AT_name, cu);
17623   if ((!attr || !DW_STRING (attr))
17624       && die->tag != DW_TAG_class_type
17625       && die->tag != DW_TAG_interface_type
17626       && die->tag != DW_TAG_structure_type
17627       && die->tag != DW_TAG_union_type)
17628     return NULL;
17629
17630   switch (die->tag)
17631     {
17632     case DW_TAG_compile_unit:
17633     case DW_TAG_partial_unit:
17634       /* Compilation units have a DW_AT_name that is a filename, not
17635          a source language identifier.  */
17636     case DW_TAG_enumeration_type:
17637     case DW_TAG_enumerator:
17638       /* These tags always have simple identifiers already; no need
17639          to canonicalize them.  */
17640       return DW_STRING (attr);
17641
17642     case DW_TAG_subprogram:
17643       /* Java constructors will all be named "<init>", so return
17644          the class name when we see this special case.  */
17645       if (cu->language == language_java
17646           && DW_STRING (attr) != NULL
17647           && strcmp (DW_STRING (attr), "<init>") == 0)
17648         {
17649           struct dwarf2_cu *spec_cu = cu;
17650           struct die_info *spec_die;
17651
17652           /* GCJ will output '<init>' for Java constructor names.
17653              For this special case, return the name of the parent class.  */
17654
17655           /* GCJ may output suprogram DIEs with AT_specification set.
17656              If so, use the name of the specified DIE.  */
17657           spec_die = die_specification (die, &spec_cu);
17658           if (spec_die != NULL)
17659             return dwarf2_name (spec_die, spec_cu);
17660
17661           do
17662             {
17663               die = die->parent;
17664               if (die->tag == DW_TAG_class_type)
17665                 return dwarf2_name (die, cu);
17666             }
17667           while (die->tag != DW_TAG_compile_unit
17668                  && die->tag != DW_TAG_partial_unit);
17669         }
17670       break;
17671
17672     case DW_TAG_class_type:
17673     case DW_TAG_interface_type:
17674     case DW_TAG_structure_type:
17675     case DW_TAG_union_type:
17676       /* Some GCC versions emit spurious DW_AT_name attributes for unnamed
17677          structures or unions.  These were of the form "._%d" in GCC 4.1,
17678          or simply "<anonymous struct>" or "<anonymous union>" in GCC 4.3
17679          and GCC 4.4.  We work around this problem by ignoring these.  */
17680       if (attr && DW_STRING (attr)
17681           && (strncmp (DW_STRING (attr), "._", 2) == 0
17682               || strncmp (DW_STRING (attr), "<anonymous", 10) == 0))
17683         return NULL;
17684
17685       /* GCC might emit a nameless typedef that has a linkage name.  See
17686          http://gcc.gnu.org/bugzilla/show_bug.cgi?id=47510.  */
17687       if (!attr || DW_STRING (attr) == NULL)
17688         {
17689           char *demangled = NULL;
17690
17691           attr = dwarf2_attr (die, DW_AT_linkage_name, cu);
17692           if (attr == NULL)
17693             attr = dwarf2_attr (die, DW_AT_MIPS_linkage_name, cu);
17694
17695           if (attr == NULL || DW_STRING (attr) == NULL)
17696             return NULL;
17697
17698           /* Avoid demangling DW_STRING (attr) the second time on a second
17699              call for the same DIE.  */
17700           if (!DW_STRING_IS_CANONICAL (attr))
17701             demangled = gdb_demangle (DW_STRING (attr), DMGL_TYPES);
17702
17703           if (demangled)
17704             {
17705               char *base;
17706
17707               /* FIXME: we already did this for the partial symbol... */
17708               DW_STRING (attr) = obstack_copy0 (&cu->objfile->objfile_obstack,
17709                                                 demangled, strlen (demangled));
17710               DW_STRING_IS_CANONICAL (attr) = 1;
17711               xfree (demangled);
17712
17713               /* Strip any leading namespaces/classes, keep only the base name.
17714                  DW_AT_name for named DIEs does not contain the prefixes.  */
17715               base = strrchr (DW_STRING (attr), ':');
17716               if (base && base > DW_STRING (attr) && base[-1] == ':')
17717                 return &base[1];
17718               else
17719                 return DW_STRING (attr);
17720             }
17721         }
17722       break;
17723
17724     default:
17725       break;
17726     }
17727
17728   if (!DW_STRING_IS_CANONICAL (attr))
17729     {
17730       DW_STRING (attr)
17731         = dwarf2_canonicalize_name (DW_STRING (attr), cu,
17732                                     &cu->objfile->objfile_obstack);
17733       DW_STRING_IS_CANONICAL (attr) = 1;
17734     }
17735   return DW_STRING (attr);
17736 }
17737
17738 /* Return the die that this die in an extension of, or NULL if there
17739    is none.  *EXT_CU is the CU containing DIE on input, and the CU
17740    containing the return value on output.  */
17741
17742 static struct die_info *
17743 dwarf2_extension (struct die_info *die, struct dwarf2_cu **ext_cu)
17744 {
17745   struct attribute *attr;
17746
17747   attr = dwarf2_attr (die, DW_AT_extension, *ext_cu);
17748   if (attr == NULL)
17749     return NULL;
17750
17751   return follow_die_ref (die, attr, ext_cu);
17752 }
17753
17754 /* Convert a DIE tag into its string name.  */
17755
17756 static const char *
17757 dwarf_tag_name (unsigned tag)
17758 {
17759   const char *name = get_DW_TAG_name (tag);
17760
17761   if (name == NULL)
17762     return "DW_TAG_<unknown>";
17763
17764   return name;
17765 }
17766
17767 /* Convert a DWARF attribute code into its string name.  */
17768
17769 static const char *
17770 dwarf_attr_name (unsigned attr)
17771 {
17772   const char *name;
17773
17774 #ifdef MIPS /* collides with DW_AT_HP_block_index */
17775   if (attr == DW_AT_MIPS_fde)
17776     return "DW_AT_MIPS_fde";
17777 #else
17778   if (attr == DW_AT_HP_block_index)
17779     return "DW_AT_HP_block_index";
17780 #endif
17781
17782   name = get_DW_AT_name (attr);
17783
17784   if (name == NULL)
17785     return "DW_AT_<unknown>";
17786
17787   return name;
17788 }
17789
17790 /* Convert a DWARF value form code into its string name.  */
17791
17792 static const char *
17793 dwarf_form_name (unsigned form)
17794 {
17795   const char *name = get_DW_FORM_name (form);
17796
17797   if (name == NULL)
17798     return "DW_FORM_<unknown>";
17799
17800   return name;
17801 }
17802
17803 static char *
17804 dwarf_bool_name (unsigned mybool)
17805 {
17806   if (mybool)
17807     return "TRUE";
17808   else
17809     return "FALSE";
17810 }
17811
17812 /* Convert a DWARF type code into its string name.  */
17813
17814 static const char *
17815 dwarf_type_encoding_name (unsigned enc)
17816 {
17817   const char *name = get_DW_ATE_name (enc);
17818
17819   if (name == NULL)
17820     return "DW_ATE_<unknown>";
17821
17822   return name;
17823 }
17824
17825 static void
17826 dump_die_shallow (struct ui_file *f, int indent, struct die_info *die)
17827 {
17828   unsigned int i;
17829
17830   print_spaces (indent, f);
17831   fprintf_unfiltered (f, "Die: %s (abbrev %d, offset 0x%x)\n",
17832            dwarf_tag_name (die->tag), die->abbrev, die->offset.sect_off);
17833
17834   if (die->parent != NULL)
17835     {
17836       print_spaces (indent, f);
17837       fprintf_unfiltered (f, "  parent at offset: 0x%x\n",
17838                           die->parent->offset.sect_off);
17839     }
17840
17841   print_spaces (indent, f);
17842   fprintf_unfiltered (f, "  has children: %s\n",
17843            dwarf_bool_name (die->child != NULL));
17844
17845   print_spaces (indent, f);
17846   fprintf_unfiltered (f, "  attributes:\n");
17847
17848   for (i = 0; i < die->num_attrs; ++i)
17849     {
17850       print_spaces (indent, f);
17851       fprintf_unfiltered (f, "    %s (%s) ",
17852                dwarf_attr_name (die->attrs[i].name),
17853                dwarf_form_name (die->attrs[i].form));
17854
17855       switch (die->attrs[i].form)
17856         {
17857         case DW_FORM_addr:
17858         case DW_FORM_GNU_addr_index:
17859           fprintf_unfiltered (f, "address: ");
17860           fputs_filtered (hex_string (DW_ADDR (&die->attrs[i])), f);
17861           break;
17862         case DW_FORM_block2:
17863         case DW_FORM_block4:
17864         case DW_FORM_block:
17865         case DW_FORM_block1:
17866           fprintf_unfiltered (f, "block: size %s",
17867                               pulongest (DW_BLOCK (&die->attrs[i])->size));
17868           break;
17869         case DW_FORM_exprloc:
17870           fprintf_unfiltered (f, "expression: size %s",
17871                               pulongest (DW_BLOCK (&die->attrs[i])->size));
17872           break;
17873         case DW_FORM_ref_addr:
17874           fprintf_unfiltered (f, "ref address: ");
17875           fputs_filtered (hex_string (DW_UNSND (&die->attrs[i])), f);
17876           break;
17877         case DW_FORM_GNU_ref_alt:
17878           fprintf_unfiltered (f, "alt ref address: ");
17879           fputs_filtered (hex_string (DW_UNSND (&die->attrs[i])), f);
17880           break;
17881         case DW_FORM_ref1:
17882         case DW_FORM_ref2:
17883         case DW_FORM_ref4:
17884         case DW_FORM_ref8:
17885         case DW_FORM_ref_udata:
17886           fprintf_unfiltered (f, "constant ref: 0x%lx (adjusted)",
17887                               (long) (DW_UNSND (&die->attrs[i])));
17888           break;
17889         case DW_FORM_data1:
17890         case DW_FORM_data2:
17891         case DW_FORM_data4:
17892         case DW_FORM_data8:
17893         case DW_FORM_udata:
17894         case DW_FORM_sdata:
17895           fprintf_unfiltered (f, "constant: %s",
17896                               pulongest (DW_UNSND (&die->attrs[i])));
17897           break;
17898         case DW_FORM_sec_offset:
17899           fprintf_unfiltered (f, "section offset: %s",
17900                               pulongest (DW_UNSND (&die->attrs[i])));
17901           break;
17902         case DW_FORM_ref_sig8:
17903           fprintf_unfiltered (f, "signature: %s",
17904                               hex_string (DW_SIGNATURE (&die->attrs[i])));
17905           break;
17906         case DW_FORM_string:
17907         case DW_FORM_strp:
17908         case DW_FORM_GNU_str_index:
17909         case DW_FORM_GNU_strp_alt:
17910           fprintf_unfiltered (f, "string: \"%s\" (%s canonicalized)",
17911                    DW_STRING (&die->attrs[i])
17912                    ? DW_STRING (&die->attrs[i]) : "",
17913                    DW_STRING_IS_CANONICAL (&die->attrs[i]) ? "is" : "not");
17914           break;
17915         case DW_FORM_flag:
17916           if (DW_UNSND (&die->attrs[i]))
17917             fprintf_unfiltered (f, "flag: TRUE");
17918           else
17919             fprintf_unfiltered (f, "flag: FALSE");
17920           break;
17921         case DW_FORM_flag_present:
17922           fprintf_unfiltered (f, "flag: TRUE");
17923           break;
17924         case DW_FORM_indirect:
17925           /* The reader will have reduced the indirect form to
17926              the "base form" so this form should not occur.  */
17927           fprintf_unfiltered (f, 
17928                               "unexpected attribute form: DW_FORM_indirect");
17929           break;
17930         default:
17931           fprintf_unfiltered (f, "unsupported attribute form: %d.",
17932                    die->attrs[i].form);
17933           break;
17934         }
17935       fprintf_unfiltered (f, "\n");
17936     }
17937 }
17938
17939 static void
17940 dump_die_for_error (struct die_info *die)
17941 {
17942   dump_die_shallow (gdb_stderr, 0, die);
17943 }
17944
17945 static void
17946 dump_die_1 (struct ui_file *f, int level, int max_level, struct die_info *die)
17947 {
17948   int indent = level * 4;
17949
17950   gdb_assert (die != NULL);
17951
17952   if (level >= max_level)
17953     return;
17954
17955   dump_die_shallow (f, indent, die);
17956
17957   if (die->child != NULL)
17958     {
17959       print_spaces (indent, f);
17960       fprintf_unfiltered (f, "  Children:");
17961       if (level + 1 < max_level)
17962         {
17963           fprintf_unfiltered (f, "\n");
17964           dump_die_1 (f, level + 1, max_level, die->child);
17965         }
17966       else
17967         {
17968           fprintf_unfiltered (f,
17969                               " [not printed, max nesting level reached]\n");
17970         }
17971     }
17972
17973   if (die->sibling != NULL && level > 0)
17974     {
17975       dump_die_1 (f, level, max_level, die->sibling);
17976     }
17977 }
17978
17979 /* This is called from the pdie macro in gdbinit.in.
17980    It's not static so gcc will keep a copy callable from gdb.  */
17981
17982 void
17983 dump_die (struct die_info *die, int max_level)
17984 {
17985   dump_die_1 (gdb_stdlog, 0, max_level, die);
17986 }
17987
17988 static void
17989 store_in_ref_table (struct die_info *die, struct dwarf2_cu *cu)
17990 {
17991   void **slot;
17992
17993   slot = htab_find_slot_with_hash (cu->die_hash, die, die->offset.sect_off,
17994                                    INSERT);
17995
17996   *slot = die;
17997 }
17998
17999 /* Return DIE offset of ATTR.  Return 0 with complaint if ATTR is not of the
18000    required kind.  */
18001
18002 static sect_offset
18003 dwarf2_get_ref_die_offset (const struct attribute *attr)
18004 {
18005   sect_offset retval = { DW_UNSND (attr) };
18006
18007   if (attr_form_is_ref (attr))
18008     return retval;
18009
18010   retval.sect_off = 0;
18011   complaint (&symfile_complaints,
18012              _("unsupported die ref attribute form: '%s'"),
18013              dwarf_form_name (attr->form));
18014   return retval;
18015 }
18016
18017 /* Return the constant value held by ATTR.  Return DEFAULT_VALUE if
18018  * the value held by the attribute is not constant.  */
18019
18020 static LONGEST
18021 dwarf2_get_attr_constant_value (const struct attribute *attr, int default_value)
18022 {
18023   if (attr->form == DW_FORM_sdata)
18024     return DW_SND (attr);
18025   else if (attr->form == DW_FORM_udata
18026            || attr->form == DW_FORM_data1
18027            || attr->form == DW_FORM_data2
18028            || attr->form == DW_FORM_data4
18029            || attr->form == DW_FORM_data8)
18030     return DW_UNSND (attr);
18031   else
18032     {
18033       complaint (&symfile_complaints,
18034                  _("Attribute value is not a constant (%s)"),
18035                  dwarf_form_name (attr->form));
18036       return default_value;
18037     }
18038 }
18039
18040 /* Follow reference or signature attribute ATTR of SRC_DIE.
18041    On entry *REF_CU is the CU of SRC_DIE.
18042    On exit *REF_CU is the CU of the result.  */
18043
18044 static struct die_info *
18045 follow_die_ref_or_sig (struct die_info *src_die, const struct attribute *attr,
18046                        struct dwarf2_cu **ref_cu)
18047 {
18048   struct die_info *die;
18049
18050   if (attr_form_is_ref (attr))
18051     die = follow_die_ref (src_die, attr, ref_cu);
18052   else if (attr->form == DW_FORM_ref_sig8)
18053     die = follow_die_sig (src_die, attr, ref_cu);
18054   else
18055     {
18056       dump_die_for_error (src_die);
18057       error (_("Dwarf Error: Expected reference attribute [in module %s]"),
18058              (*ref_cu)->objfile->name);
18059     }
18060
18061   return die;
18062 }
18063
18064 /* Follow reference OFFSET.
18065    On entry *REF_CU is the CU of the source die referencing OFFSET.
18066    On exit *REF_CU is the CU of the result.
18067    Returns NULL if OFFSET is invalid.  */
18068
18069 static struct die_info *
18070 follow_die_offset (sect_offset offset, int offset_in_dwz,
18071                    struct dwarf2_cu **ref_cu)
18072 {
18073   struct die_info temp_die;
18074   struct dwarf2_cu *target_cu, *cu = *ref_cu;
18075
18076   gdb_assert (cu->per_cu != NULL);
18077
18078   target_cu = cu;
18079
18080   if (cu->per_cu->is_debug_types)
18081     {
18082       /* .debug_types CUs cannot reference anything outside their CU.
18083          If they need to, they have to reference a signatured type via
18084          DW_FORM_ref_sig8.  */
18085       if (! offset_in_cu_p (&cu->header, offset))
18086         return NULL;
18087     }
18088   else if (offset_in_dwz != cu->per_cu->is_dwz
18089            || ! offset_in_cu_p (&cu->header, offset))
18090     {
18091       struct dwarf2_per_cu_data *per_cu;
18092
18093       per_cu = dwarf2_find_containing_comp_unit (offset, offset_in_dwz,
18094                                                  cu->objfile);
18095
18096       /* If necessary, add it to the queue and load its DIEs.  */
18097       if (maybe_queue_comp_unit (cu, per_cu, cu->language))
18098         load_full_comp_unit (per_cu, cu->language);
18099
18100       target_cu = per_cu->cu;
18101     }
18102   else if (cu->dies == NULL)
18103     {
18104       /* We're loading full DIEs during partial symbol reading.  */
18105       gdb_assert (dwarf2_per_objfile->reading_partial_symbols);
18106       load_full_comp_unit (cu->per_cu, language_minimal);
18107     }
18108
18109   *ref_cu = target_cu;
18110   temp_die.offset = offset;
18111   return htab_find_with_hash (target_cu->die_hash, &temp_die, offset.sect_off);
18112 }
18113
18114 /* Follow reference attribute ATTR of SRC_DIE.
18115    On entry *REF_CU is the CU of SRC_DIE.
18116    On exit *REF_CU is the CU of the result.  */
18117
18118 static struct die_info *
18119 follow_die_ref (struct die_info *src_die, const struct attribute *attr,
18120                 struct dwarf2_cu **ref_cu)
18121 {
18122   sect_offset offset = dwarf2_get_ref_die_offset (attr);
18123   struct dwarf2_cu *cu = *ref_cu;
18124   struct die_info *die;
18125
18126   die = follow_die_offset (offset,
18127                            (attr->form == DW_FORM_GNU_ref_alt
18128                             || cu->per_cu->is_dwz),
18129                            ref_cu);
18130   if (!die)
18131     error (_("Dwarf Error: Cannot find DIE at 0x%x referenced from DIE "
18132            "at 0x%x [in module %s]"),
18133            offset.sect_off, src_die->offset.sect_off, cu->objfile->name);
18134
18135   return die;
18136 }
18137
18138 /* Return DWARF block referenced by DW_AT_location of DIE at OFFSET at PER_CU.
18139    Returned value is intended for DW_OP_call*.  Returned
18140    dwarf2_locexpr_baton->data has lifetime of PER_CU->OBJFILE.  */
18141
18142 struct dwarf2_locexpr_baton
18143 dwarf2_fetch_die_loc_sect_off (sect_offset offset,
18144                                struct dwarf2_per_cu_data *per_cu,
18145                                CORE_ADDR (*get_frame_pc) (void *baton),
18146                                void *baton)
18147 {
18148   struct dwarf2_cu *cu;
18149   struct die_info *die;
18150   struct attribute *attr;
18151   struct dwarf2_locexpr_baton retval;
18152
18153   dw2_setup (per_cu->objfile);
18154
18155   if (per_cu->cu == NULL)
18156     load_cu (per_cu);
18157   cu = per_cu->cu;
18158
18159   die = follow_die_offset (offset, per_cu->is_dwz, &cu);
18160   if (!die)
18161     error (_("Dwarf Error: Cannot find DIE at 0x%x referenced in module %s"),
18162            offset.sect_off, per_cu->objfile->name);
18163
18164   attr = dwarf2_attr (die, DW_AT_location, cu);
18165   if (!attr)
18166     {
18167       /* DWARF: "If there is no such attribute, then there is no effect.".
18168          DATA is ignored if SIZE is 0.  */
18169
18170       retval.data = NULL;
18171       retval.size = 0;
18172     }
18173   else if (attr_form_is_section_offset (attr))
18174     {
18175       struct dwarf2_loclist_baton loclist_baton;
18176       CORE_ADDR pc = (*get_frame_pc) (baton);
18177       size_t size;
18178
18179       fill_in_loclist_baton (cu, &loclist_baton, attr);
18180
18181       retval.data = dwarf2_find_location_expression (&loclist_baton,
18182                                                      &size, pc);
18183       retval.size = size;
18184     }
18185   else
18186     {
18187       if (!attr_form_is_block (attr))
18188         error (_("Dwarf Error: DIE at 0x%x referenced in module %s "
18189                  "is neither DW_FORM_block* nor DW_FORM_exprloc"),
18190                offset.sect_off, per_cu->objfile->name);
18191
18192       retval.data = DW_BLOCK (attr)->data;
18193       retval.size = DW_BLOCK (attr)->size;
18194     }
18195   retval.per_cu = cu->per_cu;
18196
18197   age_cached_comp_units ();
18198
18199   return retval;
18200 }
18201
18202 /* Like dwarf2_fetch_die_loc_sect_off, but take a CU
18203    offset.  */
18204
18205 struct dwarf2_locexpr_baton
18206 dwarf2_fetch_die_loc_cu_off (cu_offset offset_in_cu,
18207                              struct dwarf2_per_cu_data *per_cu,
18208                              CORE_ADDR (*get_frame_pc) (void *baton),
18209                              void *baton)
18210 {
18211   sect_offset offset = { per_cu->offset.sect_off + offset_in_cu.cu_off };
18212
18213   return dwarf2_fetch_die_loc_sect_off (offset, per_cu, get_frame_pc, baton);
18214 }
18215
18216 /* Write a constant of a given type as target-ordered bytes into
18217    OBSTACK.  */
18218
18219 static const gdb_byte *
18220 write_constant_as_bytes (struct obstack *obstack,
18221                          enum bfd_endian byte_order,
18222                          struct type *type,
18223                          ULONGEST value,
18224                          LONGEST *len)
18225 {
18226   gdb_byte *result;
18227
18228   *len = TYPE_LENGTH (type);
18229   result = obstack_alloc (obstack, *len);
18230   store_unsigned_integer (result, *len, byte_order, value);
18231
18232   return result;
18233 }
18234
18235 /* If the DIE at OFFSET in PER_CU has a DW_AT_const_value, return a
18236    pointer to the constant bytes and set LEN to the length of the
18237    data.  If memory is needed, allocate it on OBSTACK.  If the DIE
18238    does not have a DW_AT_const_value, return NULL.  */
18239
18240 const gdb_byte *
18241 dwarf2_fetch_constant_bytes (sect_offset offset,
18242                              struct dwarf2_per_cu_data *per_cu,
18243                              struct obstack *obstack,
18244                              LONGEST *len)
18245 {
18246   struct dwarf2_cu *cu;
18247   struct die_info *die;
18248   struct attribute *attr;
18249   const gdb_byte *result = NULL;
18250   struct type *type;
18251   LONGEST value;
18252   enum bfd_endian byte_order;
18253
18254   dw2_setup (per_cu->objfile);
18255
18256   if (per_cu->cu == NULL)
18257     load_cu (per_cu);
18258   cu = per_cu->cu;
18259
18260   die = follow_die_offset (offset, per_cu->is_dwz, &cu);
18261   if (!die)
18262     error (_("Dwarf Error: Cannot find DIE at 0x%x referenced in module %s"),
18263            offset.sect_off, per_cu->objfile->name);
18264
18265
18266   attr = dwarf2_attr (die, DW_AT_const_value, cu);
18267   if (attr == NULL)
18268     return NULL;
18269
18270   byte_order = (bfd_big_endian (per_cu->objfile->obfd)
18271                 ? BFD_ENDIAN_BIG : BFD_ENDIAN_LITTLE);
18272
18273   switch (attr->form)
18274     {
18275     case DW_FORM_addr:
18276     case DW_FORM_GNU_addr_index:
18277       {
18278         gdb_byte *tem;
18279
18280         *len = cu->header.addr_size;
18281         tem = obstack_alloc (obstack, *len);
18282         store_unsigned_integer (tem, *len, byte_order, DW_ADDR (attr));
18283         result = tem;
18284       }
18285       break;
18286     case DW_FORM_string:
18287     case DW_FORM_strp:
18288     case DW_FORM_GNU_str_index:
18289     case DW_FORM_GNU_strp_alt:
18290       /* DW_STRING is already allocated on the objfile obstack, point
18291          directly to it.  */
18292       result = (const gdb_byte *) DW_STRING (attr);
18293       *len = strlen (DW_STRING (attr));
18294       break;
18295     case DW_FORM_block1:
18296     case DW_FORM_block2:
18297     case DW_FORM_block4:
18298     case DW_FORM_block:
18299     case DW_FORM_exprloc:
18300       result = DW_BLOCK (attr)->data;
18301       *len = DW_BLOCK (attr)->size;
18302       break;
18303
18304       /* The DW_AT_const_value attributes are supposed to carry the
18305          symbol's value "represented as it would be on the target
18306          architecture."  By the time we get here, it's already been
18307          converted to host endianness, so we just need to sign- or
18308          zero-extend it as appropriate.  */
18309     case DW_FORM_data1:
18310       type = die_type (die, cu);
18311       result = dwarf2_const_value_data (attr, obstack, cu, &value, 8);
18312       if (result == NULL)
18313         result = write_constant_as_bytes (obstack, byte_order,
18314                                           type, value, len);
18315       break;
18316     case DW_FORM_data2:
18317       type = die_type (die, cu);
18318       result = dwarf2_const_value_data (attr, obstack, cu, &value, 16);
18319       if (result == NULL)
18320         result = write_constant_as_bytes (obstack, byte_order,
18321                                           type, value, len);
18322       break;
18323     case DW_FORM_data4:
18324       type = die_type (die, cu);
18325       result = dwarf2_const_value_data (attr, obstack, cu, &value, 32);
18326       if (result == NULL)
18327         result = write_constant_as_bytes (obstack, byte_order,
18328                                           type, value, len);
18329       break;
18330     case DW_FORM_data8:
18331       type = die_type (die, cu);
18332       result = dwarf2_const_value_data (attr, obstack, cu, &value, 64);
18333       if (result == NULL)
18334         result = write_constant_as_bytes (obstack, byte_order,
18335                                           type, value, len);
18336       break;
18337
18338     case DW_FORM_sdata:
18339       type = die_type (die, cu);
18340       result = write_constant_as_bytes (obstack, byte_order,
18341                                         type, DW_SND (attr), len);
18342       break;
18343
18344     case DW_FORM_udata:
18345       type = die_type (die, cu);
18346       result = write_constant_as_bytes (obstack, byte_order,
18347                                         type, DW_UNSND (attr), len);
18348       break;
18349
18350     default:
18351       complaint (&symfile_complaints,
18352                  _("unsupported const value attribute form: '%s'"),
18353                  dwarf_form_name (attr->form));
18354       break;
18355     }
18356
18357   return result;
18358 }
18359
18360 /* Return the type of the DIE at DIE_OFFSET in the CU named by
18361    PER_CU.  */
18362
18363 struct type *
18364 dwarf2_get_die_type (cu_offset die_offset,
18365                      struct dwarf2_per_cu_data *per_cu)
18366 {
18367   sect_offset die_offset_sect;
18368
18369   dw2_setup (per_cu->objfile);
18370
18371   die_offset_sect.sect_off = per_cu->offset.sect_off + die_offset.cu_off;
18372   return get_die_type_at_offset (die_offset_sect, per_cu);
18373 }
18374
18375 /* Follow type unit SIG_TYPE referenced by SRC_DIE.
18376    On entry *REF_CU is the CU of SRC_DIE.
18377    On exit *REF_CU is the CU of the result.
18378    Returns NULL if the referenced DIE isn't found.  */
18379
18380 static struct die_info *
18381 follow_die_sig_1 (struct die_info *src_die, struct signatured_type *sig_type,
18382                   struct dwarf2_cu **ref_cu)
18383 {
18384   struct objfile *objfile = (*ref_cu)->objfile;
18385   struct die_info temp_die;
18386   struct dwarf2_cu *sig_cu;
18387   struct die_info *die;
18388
18389   /* While it might be nice to assert sig_type->type == NULL here,
18390      we can get here for DW_AT_imported_declaration where we need
18391      the DIE not the type.  */
18392
18393   /* If necessary, add it to the queue and load its DIEs.  */
18394
18395   if (maybe_queue_comp_unit (*ref_cu, &sig_type->per_cu, language_minimal))
18396     read_signatured_type (sig_type);
18397
18398   gdb_assert (sig_type->per_cu.cu != NULL);
18399
18400   sig_cu = sig_type->per_cu.cu;
18401   gdb_assert (sig_type->type_offset_in_section.sect_off != 0);
18402   temp_die.offset = sig_type->type_offset_in_section;
18403   die = htab_find_with_hash (sig_cu->die_hash, &temp_die,
18404                              temp_die.offset.sect_off);
18405   if (die)
18406     {
18407       /* For .gdb_index version 7 keep track of included TUs.
18408          http://sourceware.org/bugzilla/show_bug.cgi?id=15021.  */
18409       if (dwarf2_per_objfile->index_table != NULL
18410           && dwarf2_per_objfile->index_table->version <= 7)
18411         {
18412           VEC_safe_push (dwarf2_per_cu_ptr,
18413                          (*ref_cu)->per_cu->imported_symtabs,
18414                          sig_cu->per_cu);
18415         }
18416
18417       *ref_cu = sig_cu;
18418       return die;
18419     }
18420
18421   return NULL;
18422 }
18423
18424 /* Follow signatured type referenced by ATTR in SRC_DIE.
18425    On entry *REF_CU is the CU of SRC_DIE.
18426    On exit *REF_CU is the CU of the result.
18427    The result is the DIE of the type.
18428    If the referenced type cannot be found an error is thrown.  */
18429
18430 static struct die_info *
18431 follow_die_sig (struct die_info *src_die, const struct attribute *attr,
18432                 struct dwarf2_cu **ref_cu)
18433 {
18434   ULONGEST signature = DW_SIGNATURE (attr);
18435   struct signatured_type *sig_type;
18436   struct die_info *die;
18437
18438   gdb_assert (attr->form == DW_FORM_ref_sig8);
18439
18440   sig_type = lookup_signatured_type (*ref_cu, signature);
18441   /* sig_type will be NULL if the signatured type is missing from
18442      the debug info.  */
18443   if (sig_type == NULL)
18444     {
18445       error (_("Dwarf Error: Cannot find signatured DIE %s referenced"
18446                " from DIE at 0x%x [in module %s]"),
18447              hex_string (signature), src_die->offset.sect_off,
18448              (*ref_cu)->objfile->name);
18449     }
18450
18451   die = follow_die_sig_1 (src_die, sig_type, ref_cu);
18452   if (die == NULL)
18453     {
18454       dump_die_for_error (src_die);
18455       error (_("Dwarf Error: Problem reading signatured DIE %s referenced"
18456                " from DIE at 0x%x [in module %s]"),
18457              hex_string (signature), src_die->offset.sect_off,
18458              (*ref_cu)->objfile->name);
18459     }
18460
18461   return die;
18462 }
18463
18464 /* Get the type specified by SIGNATURE referenced in DIE/CU,
18465    reading in and processing the type unit if necessary.  */
18466
18467 static struct type *
18468 get_signatured_type (struct die_info *die, ULONGEST signature,
18469                      struct dwarf2_cu *cu)
18470 {
18471   struct signatured_type *sig_type;
18472   struct dwarf2_cu *type_cu;
18473   struct die_info *type_die;
18474   struct type *type;
18475
18476   sig_type = lookup_signatured_type (cu, signature);
18477   /* sig_type will be NULL if the signatured type is missing from
18478      the debug info.  */
18479   if (sig_type == NULL)
18480     {
18481       complaint (&symfile_complaints,
18482                  _("Dwarf Error: Cannot find signatured DIE %s referenced"
18483                    " from DIE at 0x%x [in module %s]"),
18484                  hex_string (signature), die->offset.sect_off,
18485                  dwarf2_per_objfile->objfile->name);
18486       return build_error_marker_type (cu, die);
18487     }
18488
18489   /* If we already know the type we're done.  */
18490   if (sig_type->type != NULL)
18491     return sig_type->type;
18492
18493   type_cu = cu;
18494   type_die = follow_die_sig_1 (die, sig_type, &type_cu);
18495   if (type_die != NULL)
18496     {
18497       /* N.B. We need to call get_die_type to ensure only one type for this DIE
18498          is created.  This is important, for example, because for c++ classes
18499          we need TYPE_NAME set which is only done by new_symbol.  Blech.  */
18500       type = read_type_die (type_die, type_cu);
18501       if (type == NULL)
18502         {
18503           complaint (&symfile_complaints,
18504                      _("Dwarf Error: Cannot build signatured type %s"
18505                        " referenced from DIE at 0x%x [in module %s]"),
18506                      hex_string (signature), die->offset.sect_off,
18507                      dwarf2_per_objfile->objfile->name);
18508           type = build_error_marker_type (cu, die);
18509         }
18510     }
18511   else
18512     {
18513       complaint (&symfile_complaints,
18514                  _("Dwarf Error: Problem reading signatured DIE %s referenced"
18515                    " from DIE at 0x%x [in module %s]"),
18516                  hex_string (signature), die->offset.sect_off,
18517                  dwarf2_per_objfile->objfile->name);
18518       type = build_error_marker_type (cu, die);
18519     }
18520   sig_type->type = type;
18521
18522   return type;
18523 }
18524
18525 /* Get the type specified by the DW_AT_signature ATTR in DIE/CU,
18526    reading in and processing the type unit if necessary.  */
18527
18528 static struct type *
18529 get_DW_AT_signature_type (struct die_info *die, const struct attribute *attr,
18530                           struct dwarf2_cu *cu) /* ARI: editCase function */
18531 {
18532   /* Yes, DW_AT_signature can use a non-ref_sig8 reference.  */
18533   if (attr_form_is_ref (attr))
18534     {
18535       struct dwarf2_cu *type_cu = cu;
18536       struct die_info *type_die = follow_die_ref (die, attr, &type_cu);
18537
18538       return read_type_die (type_die, type_cu);
18539     }
18540   else if (attr->form == DW_FORM_ref_sig8)
18541     {
18542       return get_signatured_type (die, DW_SIGNATURE (attr), cu);
18543     }
18544   else
18545     {
18546       complaint (&symfile_complaints,
18547                  _("Dwarf Error: DW_AT_signature has bad form %s in DIE"
18548                    " at 0x%x [in module %s]"),
18549                  dwarf_form_name (attr->form), die->offset.sect_off,
18550                  dwarf2_per_objfile->objfile->name);
18551       return build_error_marker_type (cu, die);
18552     }
18553 }
18554
18555 /* Load the DIEs associated with type unit PER_CU into memory.  */
18556
18557 static void
18558 load_full_type_unit (struct dwarf2_per_cu_data *per_cu)
18559 {
18560   struct signatured_type *sig_type;
18561
18562   /* Caller is responsible for ensuring type_unit_groups don't get here.  */
18563   gdb_assert (! IS_TYPE_UNIT_GROUP (per_cu));
18564
18565   /* We have the per_cu, but we need the signatured_type.
18566      Fortunately this is an easy translation.  */
18567   gdb_assert (per_cu->is_debug_types);
18568   sig_type = (struct signatured_type *) per_cu;
18569
18570   gdb_assert (per_cu->cu == NULL);
18571
18572   read_signatured_type (sig_type);
18573
18574   gdb_assert (per_cu->cu != NULL);
18575 }
18576
18577 /* die_reader_func for read_signatured_type.
18578    This is identical to load_full_comp_unit_reader,
18579    but is kept separate for now.  */
18580
18581 static void
18582 read_signatured_type_reader (const struct die_reader_specs *reader,
18583                              const gdb_byte *info_ptr,
18584                              struct die_info *comp_unit_die,
18585                              int has_children,
18586                              void *data)
18587 {
18588   struct dwarf2_cu *cu = reader->cu;
18589
18590   gdb_assert (cu->die_hash == NULL);
18591   cu->die_hash =
18592     htab_create_alloc_ex (cu->header.length / 12,
18593                           die_hash,
18594                           die_eq,
18595                           NULL,
18596                           &cu->comp_unit_obstack,
18597                           hashtab_obstack_allocate,
18598                           dummy_obstack_deallocate);
18599
18600   if (has_children)
18601     comp_unit_die->child = read_die_and_siblings (reader, info_ptr,
18602                                                   &info_ptr, comp_unit_die);
18603   cu->dies = comp_unit_die;
18604   /* comp_unit_die is not stored in die_hash, no need.  */
18605
18606   /* We try not to read any attributes in this function, because not
18607      all CUs needed for references have been loaded yet, and symbol
18608      table processing isn't initialized.  But we have to set the CU language,
18609      or we won't be able to build types correctly.
18610      Similarly, if we do not read the producer, we can not apply
18611      producer-specific interpretation.  */
18612   prepare_one_comp_unit (cu, cu->dies, language_minimal);
18613 }
18614
18615 /* Read in a signatured type and build its CU and DIEs.
18616    If the type is a stub for the real type in a DWO file,
18617    read in the real type from the DWO file as well.  */
18618
18619 static void
18620 read_signatured_type (struct signatured_type *sig_type)
18621 {
18622   struct dwarf2_per_cu_data *per_cu = &sig_type->per_cu;
18623
18624   gdb_assert (per_cu->is_debug_types);
18625   gdb_assert (per_cu->cu == NULL);
18626
18627   init_cutu_and_read_dies (per_cu, NULL, 0, 1,
18628                            read_signatured_type_reader, NULL);
18629   sig_type->per_cu.tu_read = 1;
18630 }
18631
18632 /* Decode simple location descriptions.
18633    Given a pointer to a dwarf block that defines a location, compute
18634    the location and return the value.
18635
18636    NOTE drow/2003-11-18: This function is called in two situations
18637    now: for the address of static or global variables (partial symbols
18638    only) and for offsets into structures which are expected to be
18639    (more or less) constant.  The partial symbol case should go away,
18640    and only the constant case should remain.  That will let this
18641    function complain more accurately.  A few special modes are allowed
18642    without complaint for global variables (for instance, global
18643    register values and thread-local values).
18644
18645    A location description containing no operations indicates that the
18646    object is optimized out.  The return value is 0 for that case.
18647    FIXME drow/2003-11-16: No callers check for this case any more; soon all
18648    callers will only want a very basic result and this can become a
18649    complaint.
18650
18651    Note that stack[0] is unused except as a default error return.  */
18652
18653 static CORE_ADDR
18654 decode_locdesc (struct dwarf_block *blk, struct dwarf2_cu *cu)
18655 {
18656   struct objfile *objfile = cu->objfile;
18657   size_t i;
18658   size_t size = blk->size;
18659   const gdb_byte *data = blk->data;
18660   CORE_ADDR stack[64];
18661   int stacki;
18662   unsigned int bytes_read, unsnd;
18663   gdb_byte op;
18664
18665   i = 0;
18666   stacki = 0;
18667   stack[stacki] = 0;
18668   stack[++stacki] = 0;
18669
18670   while (i < size)
18671     {
18672       op = data[i++];
18673       switch (op)
18674         {
18675         case DW_OP_lit0:
18676         case DW_OP_lit1:
18677         case DW_OP_lit2:
18678         case DW_OP_lit3:
18679         case DW_OP_lit4:
18680         case DW_OP_lit5:
18681         case DW_OP_lit6:
18682         case DW_OP_lit7:
18683         case DW_OP_lit8:
18684         case DW_OP_lit9:
18685         case DW_OP_lit10:
18686         case DW_OP_lit11:
18687         case DW_OP_lit12:
18688         case DW_OP_lit13:
18689         case DW_OP_lit14:
18690         case DW_OP_lit15:
18691         case DW_OP_lit16:
18692         case DW_OP_lit17:
18693         case DW_OP_lit18:
18694         case DW_OP_lit19:
18695         case DW_OP_lit20:
18696         case DW_OP_lit21:
18697         case DW_OP_lit22:
18698         case DW_OP_lit23:
18699         case DW_OP_lit24:
18700         case DW_OP_lit25:
18701         case DW_OP_lit26:
18702         case DW_OP_lit27:
18703         case DW_OP_lit28:
18704         case DW_OP_lit29:
18705         case DW_OP_lit30:
18706         case DW_OP_lit31:
18707           stack[++stacki] = op - DW_OP_lit0;
18708           break;
18709
18710         case DW_OP_reg0:
18711         case DW_OP_reg1:
18712         case DW_OP_reg2:
18713         case DW_OP_reg3:
18714         case DW_OP_reg4:
18715         case DW_OP_reg5:
18716         case DW_OP_reg6:
18717         case DW_OP_reg7:
18718         case DW_OP_reg8:
18719         case DW_OP_reg9:
18720         case DW_OP_reg10:
18721         case DW_OP_reg11:
18722         case DW_OP_reg12:
18723         case DW_OP_reg13:
18724         case DW_OP_reg14:
18725         case DW_OP_reg15:
18726         case DW_OP_reg16:
18727         case DW_OP_reg17:
18728         case DW_OP_reg18:
18729         case DW_OP_reg19:
18730         case DW_OP_reg20:
18731         case DW_OP_reg21:
18732         case DW_OP_reg22:
18733         case DW_OP_reg23:
18734         case DW_OP_reg24:
18735         case DW_OP_reg25:
18736         case DW_OP_reg26:
18737         case DW_OP_reg27:
18738         case DW_OP_reg28:
18739         case DW_OP_reg29:
18740         case DW_OP_reg30:
18741         case DW_OP_reg31:
18742           stack[++stacki] = op - DW_OP_reg0;
18743           if (i < size)
18744             dwarf2_complex_location_expr_complaint ();
18745           break;
18746
18747         case DW_OP_regx:
18748           unsnd = read_unsigned_leb128 (NULL, (data + i), &bytes_read);
18749           i += bytes_read;
18750           stack[++stacki] = unsnd;
18751           if (i < size)
18752             dwarf2_complex_location_expr_complaint ();
18753           break;
18754
18755         case DW_OP_addr:
18756           stack[++stacki] = read_address (objfile->obfd, &data[i],
18757                                           cu, &bytes_read);
18758           i += bytes_read;
18759           break;
18760
18761         case DW_OP_const1u:
18762           stack[++stacki] = read_1_byte (objfile->obfd, &data[i]);
18763           i += 1;
18764           break;
18765
18766         case DW_OP_const1s:
18767           stack[++stacki] = read_1_signed_byte (objfile->obfd, &data[i]);
18768           i += 1;
18769           break;
18770
18771         case DW_OP_const2u:
18772           stack[++stacki] = read_2_bytes (objfile->obfd, &data[i]);
18773           i += 2;
18774           break;
18775
18776         case DW_OP_const2s:
18777           stack[++stacki] = read_2_signed_bytes (objfile->obfd, &data[i]);
18778           i += 2;
18779           break;
18780
18781         case DW_OP_const4u:
18782           stack[++stacki] = read_4_bytes (objfile->obfd, &data[i]);
18783           i += 4;
18784           break;
18785
18786         case DW_OP_const4s:
18787           stack[++stacki] = read_4_signed_bytes (objfile->obfd, &data[i]);
18788           i += 4;
18789           break;
18790
18791         case DW_OP_const8u:
18792           stack[++stacki] = read_8_bytes (objfile->obfd, &data[i]);
18793           i += 8;
18794           break;
18795
18796         case DW_OP_constu:
18797           stack[++stacki] = read_unsigned_leb128 (NULL, (data + i),
18798                                                   &bytes_read);
18799           i += bytes_read;
18800           break;
18801
18802         case DW_OP_consts:
18803           stack[++stacki] = read_signed_leb128 (NULL, (data + i), &bytes_read);
18804           i += bytes_read;
18805           break;
18806
18807         case DW_OP_dup:
18808           stack[stacki + 1] = stack[stacki];
18809           stacki++;
18810           break;
18811
18812         case DW_OP_plus:
18813           stack[stacki - 1] += stack[stacki];
18814           stacki--;
18815           break;
18816
18817         case DW_OP_plus_uconst:
18818           stack[stacki] += read_unsigned_leb128 (NULL, (data + i),
18819                                                  &bytes_read);
18820           i += bytes_read;
18821           break;
18822
18823         case DW_OP_minus:
18824           stack[stacki - 1] -= stack[stacki];
18825           stacki--;
18826           break;
18827
18828         case DW_OP_deref:
18829           /* If we're not the last op, then we definitely can't encode
18830              this using GDB's address_class enum.  This is valid for partial
18831              global symbols, although the variable's address will be bogus
18832              in the psymtab.  */
18833           if (i < size)
18834             dwarf2_complex_location_expr_complaint ();
18835           break;
18836
18837         case DW_OP_GNU_push_tls_address:
18838           /* The top of the stack has the offset from the beginning
18839              of the thread control block at which the variable is located.  */
18840           /* Nothing should follow this operator, so the top of stack would
18841              be returned.  */
18842           /* This is valid for partial global symbols, but the variable's
18843              address will be bogus in the psymtab.  Make it always at least
18844              non-zero to not look as a variable garbage collected by linker
18845              which have DW_OP_addr 0.  */
18846           if (i < size)
18847             dwarf2_complex_location_expr_complaint ();
18848           stack[stacki]++;
18849           break;
18850
18851         case DW_OP_GNU_uninit:
18852           break;
18853
18854         case DW_OP_GNU_addr_index:
18855         case DW_OP_GNU_const_index:
18856           stack[++stacki] = read_addr_index_from_leb128 (cu, &data[i],
18857                                                          &bytes_read);
18858           i += bytes_read;
18859           break;
18860
18861         default:
18862           {
18863             const char *name = get_DW_OP_name (op);
18864
18865             if (name)
18866               complaint (&symfile_complaints, _("unsupported stack op: '%s'"),
18867                          name);
18868             else
18869               complaint (&symfile_complaints, _("unsupported stack op: '%02x'"),
18870                          op);
18871           }
18872
18873           return (stack[stacki]);
18874         }
18875
18876       /* Enforce maximum stack depth of SIZE-1 to avoid writing
18877          outside of the allocated space.  Also enforce minimum>0.  */
18878       if (stacki >= ARRAY_SIZE (stack) - 1)
18879         {
18880           complaint (&symfile_complaints,
18881                      _("location description stack overflow"));
18882           return 0;
18883         }
18884
18885       if (stacki <= 0)
18886         {
18887           complaint (&symfile_complaints,
18888                      _("location description stack underflow"));
18889           return 0;
18890         }
18891     }
18892   return (stack[stacki]);
18893 }
18894
18895 /* memory allocation interface */
18896
18897 static struct dwarf_block *
18898 dwarf_alloc_block (struct dwarf2_cu *cu)
18899 {
18900   struct dwarf_block *blk;
18901
18902   blk = (struct dwarf_block *)
18903     obstack_alloc (&cu->comp_unit_obstack, sizeof (struct dwarf_block));
18904   return (blk);
18905 }
18906
18907 static struct die_info *
18908 dwarf_alloc_die (struct dwarf2_cu *cu, int num_attrs)
18909 {
18910   struct die_info *die;
18911   size_t size = sizeof (struct die_info);
18912
18913   if (num_attrs > 1)
18914     size += (num_attrs - 1) * sizeof (struct attribute);
18915
18916   die = (struct die_info *) obstack_alloc (&cu->comp_unit_obstack, size);
18917   memset (die, 0, sizeof (struct die_info));
18918   return (die);
18919 }
18920
18921 \f
18922 /* Macro support.  */
18923
18924 /* Return file name relative to the compilation directory of file number I in
18925    *LH's file name table.  The result is allocated using xmalloc; the caller is
18926    responsible for freeing it.  */
18927
18928 static char *
18929 file_file_name (int file, struct line_header *lh)
18930 {
18931   /* Is the file number a valid index into the line header's file name
18932      table?  Remember that file numbers start with one, not zero.  */
18933   if (1 <= file && file <= lh->num_file_names)
18934     {
18935       struct file_entry *fe = &lh->file_names[file - 1];
18936
18937       if (IS_ABSOLUTE_PATH (fe->name) || fe->dir_index == 0)
18938         return xstrdup (fe->name);
18939       return concat (lh->include_dirs[fe->dir_index - 1], SLASH_STRING,
18940                      fe->name, NULL);
18941     }
18942   else
18943     {
18944       /* The compiler produced a bogus file number.  We can at least
18945          record the macro definitions made in the file, even if we
18946          won't be able to find the file by name.  */
18947       char fake_name[80];
18948
18949       xsnprintf (fake_name, sizeof (fake_name),
18950                  "<bad macro file number %d>", file);
18951
18952       complaint (&symfile_complaints,
18953                  _("bad file number in macro information (%d)"),
18954                  file);
18955
18956       return xstrdup (fake_name);
18957     }
18958 }
18959
18960 /* Return the full name of file number I in *LH's file name table.
18961    Use COMP_DIR as the name of the current directory of the
18962    compilation.  The result is allocated using xmalloc; the caller is
18963    responsible for freeing it.  */
18964 static char *
18965 file_full_name (int file, struct line_header *lh, const char *comp_dir)
18966 {
18967   /* Is the file number a valid index into the line header's file name
18968      table?  Remember that file numbers start with one, not zero.  */
18969   if (1 <= file && file <= lh->num_file_names)
18970     {
18971       char *relative = file_file_name (file, lh);
18972
18973       if (IS_ABSOLUTE_PATH (relative) || comp_dir == NULL)
18974         return relative;
18975       return reconcat (relative, comp_dir, SLASH_STRING, relative, NULL);
18976     }
18977   else
18978     return file_file_name (file, lh);
18979 }
18980
18981
18982 static struct macro_source_file *
18983 macro_start_file (int file, int line,
18984                   struct macro_source_file *current_file,
18985                   const char *comp_dir,
18986                   struct line_header *lh, struct objfile *objfile)
18987 {
18988   /* File name relative to the compilation directory of this source file.  */
18989   char *file_name = file_file_name (file, lh);
18990
18991   /* We don't create a macro table for this compilation unit
18992      at all until we actually get a filename.  */
18993   if (! pending_macros)
18994     pending_macros = new_macro_table (&objfile->per_bfd->storage_obstack,
18995                                       objfile->per_bfd->macro_cache,
18996                                       comp_dir);
18997
18998   if (! current_file)
18999     {
19000       /* If we have no current file, then this must be the start_file
19001          directive for the compilation unit's main source file.  */
19002       current_file = macro_set_main (pending_macros, file_name);
19003       macro_define_special (pending_macros);
19004     }
19005   else
19006     current_file = macro_include (current_file, line, file_name);
19007
19008   xfree (file_name);
19009
19010   return current_file;
19011 }
19012
19013
19014 /* Copy the LEN characters at BUF to a xmalloc'ed block of memory,
19015    followed by a null byte.  */
19016 static char *
19017 copy_string (const char *buf, int len)
19018 {
19019   char *s = xmalloc (len + 1);
19020
19021   memcpy (s, buf, len);
19022   s[len] = '\0';
19023   return s;
19024 }
19025
19026
19027 static const char *
19028 consume_improper_spaces (const char *p, const char *body)
19029 {
19030   if (*p == ' ')
19031     {
19032       complaint (&symfile_complaints,
19033                  _("macro definition contains spaces "
19034                    "in formal argument list:\n`%s'"),
19035                  body);
19036
19037       while (*p == ' ')
19038         p++;
19039     }
19040
19041   return p;
19042 }
19043
19044
19045 static void
19046 parse_macro_definition (struct macro_source_file *file, int line,
19047                         const char *body)
19048 {
19049   const char *p;
19050
19051   /* The body string takes one of two forms.  For object-like macro
19052      definitions, it should be:
19053
19054         <macro name> " " <definition>
19055
19056      For function-like macro definitions, it should be:
19057
19058         <macro name> "() " <definition>
19059      or
19060         <macro name> "(" <arg name> ( "," <arg name> ) * ") " <definition>
19061
19062      Spaces may appear only where explicitly indicated, and in the
19063      <definition>.
19064
19065      The Dwarf 2 spec says that an object-like macro's name is always
19066      followed by a space, but versions of GCC around March 2002 omit
19067      the space when the macro's definition is the empty string.
19068
19069      The Dwarf 2 spec says that there should be no spaces between the
19070      formal arguments in a function-like macro's formal argument list,
19071      but versions of GCC around March 2002 include spaces after the
19072      commas.  */
19073
19074
19075   /* Find the extent of the macro name.  The macro name is terminated
19076      by either a space or null character (for an object-like macro) or
19077      an opening paren (for a function-like macro).  */
19078   for (p = body; *p; p++)
19079     if (*p == ' ' || *p == '(')
19080       break;
19081
19082   if (*p == ' ' || *p == '\0')
19083     {
19084       /* It's an object-like macro.  */
19085       int name_len = p - body;
19086       char *name = copy_string (body, name_len);
19087       const char *replacement;
19088
19089       if (*p == ' ')
19090         replacement = body + name_len + 1;
19091       else
19092         {
19093           dwarf2_macro_malformed_definition_complaint (body);
19094           replacement = body + name_len;
19095         }
19096
19097       macro_define_object (file, line, name, replacement);
19098
19099       xfree (name);
19100     }
19101   else if (*p == '(')
19102     {
19103       /* It's a function-like macro.  */
19104       char *name = copy_string (body, p - body);
19105       int argc = 0;
19106       int argv_size = 1;
19107       char **argv = xmalloc (argv_size * sizeof (*argv));
19108
19109       p++;
19110
19111       p = consume_improper_spaces (p, body);
19112
19113       /* Parse the formal argument list.  */
19114       while (*p && *p != ')')
19115         {
19116           /* Find the extent of the current argument name.  */
19117           const char *arg_start = p;
19118
19119           while (*p && *p != ',' && *p != ')' && *p != ' ')
19120             p++;
19121
19122           if (! *p || p == arg_start)
19123             dwarf2_macro_malformed_definition_complaint (body);
19124           else
19125             {
19126               /* Make sure argv has room for the new argument.  */
19127               if (argc >= argv_size)
19128                 {
19129                   argv_size *= 2;
19130                   argv = xrealloc (argv, argv_size * sizeof (*argv));
19131                 }
19132
19133               argv[argc++] = copy_string (arg_start, p - arg_start);
19134             }
19135
19136           p = consume_improper_spaces (p, body);
19137
19138           /* Consume the comma, if present.  */
19139           if (*p == ',')
19140             {
19141               p++;
19142
19143               p = consume_improper_spaces (p, body);
19144             }
19145         }
19146
19147       if (*p == ')')
19148         {
19149           p++;
19150
19151           if (*p == ' ')
19152             /* Perfectly formed definition, no complaints.  */
19153             macro_define_function (file, line, name,
19154                                    argc, (const char **) argv,
19155                                    p + 1);
19156           else if (*p == '\0')
19157             {
19158               /* Complain, but do define it.  */
19159               dwarf2_macro_malformed_definition_complaint (body);
19160               macro_define_function (file, line, name,
19161                                      argc, (const char **) argv,
19162                                      p);
19163             }
19164           else
19165             /* Just complain.  */
19166             dwarf2_macro_malformed_definition_complaint (body);
19167         }
19168       else
19169         /* Just complain.  */
19170         dwarf2_macro_malformed_definition_complaint (body);
19171
19172       xfree (name);
19173       {
19174         int i;
19175
19176         for (i = 0; i < argc; i++)
19177           xfree (argv[i]);
19178       }
19179       xfree (argv);
19180     }
19181   else
19182     dwarf2_macro_malformed_definition_complaint (body);
19183 }
19184
19185 /* Skip some bytes from BYTES according to the form given in FORM.
19186    Returns the new pointer.  */
19187
19188 static const gdb_byte *
19189 skip_form_bytes (bfd *abfd, const gdb_byte *bytes, const gdb_byte *buffer_end,
19190                  enum dwarf_form form,
19191                  unsigned int offset_size,
19192                  struct dwarf2_section_info *section)
19193 {
19194   unsigned int bytes_read;
19195
19196   switch (form)
19197     {
19198     case DW_FORM_data1:
19199     case DW_FORM_flag:
19200       ++bytes;
19201       break;
19202
19203     case DW_FORM_data2:
19204       bytes += 2;
19205       break;
19206
19207     case DW_FORM_data4:
19208       bytes += 4;
19209       break;
19210
19211     case DW_FORM_data8:
19212       bytes += 8;
19213       break;
19214
19215     case DW_FORM_string:
19216       read_direct_string (abfd, bytes, &bytes_read);
19217       bytes += bytes_read;
19218       break;
19219
19220     case DW_FORM_sec_offset:
19221     case DW_FORM_strp:
19222     case DW_FORM_GNU_strp_alt:
19223       bytes += offset_size;
19224       break;
19225
19226     case DW_FORM_block:
19227       bytes += read_unsigned_leb128 (abfd, bytes, &bytes_read);
19228       bytes += bytes_read;
19229       break;
19230
19231     case DW_FORM_block1:
19232       bytes += 1 + read_1_byte (abfd, bytes);
19233       break;
19234     case DW_FORM_block2:
19235       bytes += 2 + read_2_bytes (abfd, bytes);
19236       break;
19237     case DW_FORM_block4:
19238       bytes += 4 + read_4_bytes (abfd, bytes);
19239       break;
19240
19241     case DW_FORM_sdata:
19242     case DW_FORM_udata:
19243     case DW_FORM_GNU_addr_index:
19244     case DW_FORM_GNU_str_index:
19245       bytes = gdb_skip_leb128 (bytes, buffer_end);
19246       if (bytes == NULL)
19247         {
19248           dwarf2_section_buffer_overflow_complaint (section);
19249           return NULL;
19250         }
19251       break;
19252
19253     default:
19254       {
19255       complain:
19256         complaint (&symfile_complaints,
19257                    _("invalid form 0x%x in `%s'"),
19258                    form,
19259                    section->asection->name);
19260         return NULL;
19261       }
19262     }
19263
19264   return bytes;
19265 }
19266
19267 /* A helper for dwarf_decode_macros that handles skipping an unknown
19268    opcode.  Returns an updated pointer to the macro data buffer; or,
19269    on error, issues a complaint and returns NULL.  */
19270
19271 static const gdb_byte *
19272 skip_unknown_opcode (unsigned int opcode,
19273                      const gdb_byte **opcode_definitions,
19274                      const gdb_byte *mac_ptr, const gdb_byte *mac_end,
19275                      bfd *abfd,
19276                      unsigned int offset_size,
19277                      struct dwarf2_section_info *section)
19278 {
19279   unsigned int bytes_read, i;
19280   unsigned long arg;
19281   const gdb_byte *defn;
19282
19283   if (opcode_definitions[opcode] == NULL)
19284     {
19285       complaint (&symfile_complaints,
19286                  _("unrecognized DW_MACFINO opcode 0x%x"),
19287                  opcode);
19288       return NULL;
19289     }
19290
19291   defn = opcode_definitions[opcode];
19292   arg = read_unsigned_leb128 (abfd, defn, &bytes_read);
19293   defn += bytes_read;
19294
19295   for (i = 0; i < arg; ++i)
19296     {
19297       mac_ptr = skip_form_bytes (abfd, mac_ptr, mac_end, defn[i], offset_size,
19298                                  section);
19299       if (mac_ptr == NULL)
19300         {
19301           /* skip_form_bytes already issued the complaint.  */
19302           return NULL;
19303         }
19304     }
19305
19306   return mac_ptr;
19307 }
19308
19309 /* A helper function which parses the header of a macro section.
19310    If the macro section is the extended (for now called "GNU") type,
19311    then this updates *OFFSET_SIZE.  Returns a pointer to just after
19312    the header, or issues a complaint and returns NULL on error.  */
19313
19314 static const gdb_byte *
19315 dwarf_parse_macro_header (const gdb_byte **opcode_definitions,
19316                           bfd *abfd,
19317                           const gdb_byte *mac_ptr,
19318                           unsigned int *offset_size,
19319                           int section_is_gnu)
19320 {
19321   memset (opcode_definitions, 0, 256 * sizeof (gdb_byte *));
19322
19323   if (section_is_gnu)
19324     {
19325       unsigned int version, flags;
19326
19327       version = read_2_bytes (abfd, mac_ptr);
19328       if (version != 4)
19329         {
19330           complaint (&symfile_complaints,
19331                      _("unrecognized version `%d' in .debug_macro section"),
19332                      version);
19333           return NULL;
19334         }
19335       mac_ptr += 2;
19336
19337       flags = read_1_byte (abfd, mac_ptr);
19338       ++mac_ptr;
19339       *offset_size = (flags & 1) ? 8 : 4;
19340
19341       if ((flags & 2) != 0)
19342         /* We don't need the line table offset.  */
19343         mac_ptr += *offset_size;
19344
19345       /* Vendor opcode descriptions.  */
19346       if ((flags & 4) != 0)
19347         {
19348           unsigned int i, count;
19349
19350           count = read_1_byte (abfd, mac_ptr);
19351           ++mac_ptr;
19352           for (i = 0; i < count; ++i)
19353             {
19354               unsigned int opcode, bytes_read;
19355               unsigned long arg;
19356
19357               opcode = read_1_byte (abfd, mac_ptr);
19358               ++mac_ptr;
19359               opcode_definitions[opcode] = mac_ptr;
19360               arg = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
19361               mac_ptr += bytes_read;
19362               mac_ptr += arg;
19363             }
19364         }
19365     }
19366
19367   return mac_ptr;
19368 }
19369
19370 /* A helper for dwarf_decode_macros that handles the GNU extensions,
19371    including DW_MACRO_GNU_transparent_include.  */
19372
19373 static void
19374 dwarf_decode_macro_bytes (bfd *abfd,
19375                           const gdb_byte *mac_ptr, const gdb_byte *mac_end,
19376                           struct macro_source_file *current_file,
19377                           struct line_header *lh, const char *comp_dir,
19378                           struct dwarf2_section_info *section,
19379                           int section_is_gnu, int section_is_dwz,
19380                           unsigned int offset_size,
19381                           struct objfile *objfile,
19382                           htab_t include_hash)
19383 {
19384   enum dwarf_macro_record_type macinfo_type;
19385   int at_commandline;
19386   const gdb_byte *opcode_definitions[256];
19387
19388   mac_ptr = dwarf_parse_macro_header (opcode_definitions, abfd, mac_ptr,
19389                                       &offset_size, section_is_gnu);
19390   if (mac_ptr == NULL)
19391     {
19392       /* We already issued a complaint.  */
19393       return;
19394     }
19395
19396   /* Determines if GDB is still before first DW_MACINFO_start_file.  If true
19397      GDB is still reading the definitions from command line.  First
19398      DW_MACINFO_start_file will need to be ignored as it was already executed
19399      to create CURRENT_FILE for the main source holding also the command line
19400      definitions.  On first met DW_MACINFO_start_file this flag is reset to
19401      normally execute all the remaining DW_MACINFO_start_file macinfos.  */
19402
19403   at_commandline = 1;
19404
19405   do
19406     {
19407       /* Do we at least have room for a macinfo type byte?  */
19408       if (mac_ptr >= mac_end)
19409         {
19410           dwarf2_section_buffer_overflow_complaint (section);
19411           break;
19412         }
19413
19414       macinfo_type = read_1_byte (abfd, mac_ptr);
19415       mac_ptr++;
19416
19417       /* Note that we rely on the fact that the corresponding GNU and
19418          DWARF constants are the same.  */
19419       switch (macinfo_type)
19420         {
19421           /* A zero macinfo type indicates the end of the macro
19422              information.  */
19423         case 0:
19424           break;
19425
19426         case DW_MACRO_GNU_define:
19427         case DW_MACRO_GNU_undef:
19428         case DW_MACRO_GNU_define_indirect:
19429         case DW_MACRO_GNU_undef_indirect:
19430         case DW_MACRO_GNU_define_indirect_alt:
19431         case DW_MACRO_GNU_undef_indirect_alt:
19432           {
19433             unsigned int bytes_read;
19434             int line;
19435             const char *body;
19436             int is_define;
19437
19438             line = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
19439             mac_ptr += bytes_read;
19440
19441             if (macinfo_type == DW_MACRO_GNU_define
19442                 || macinfo_type == DW_MACRO_GNU_undef)
19443               {
19444                 body = read_direct_string (abfd, mac_ptr, &bytes_read);
19445                 mac_ptr += bytes_read;
19446               }
19447             else
19448               {
19449                 LONGEST str_offset;
19450
19451                 str_offset = read_offset_1 (abfd, mac_ptr, offset_size);
19452                 mac_ptr += offset_size;
19453
19454                 if (macinfo_type == DW_MACRO_GNU_define_indirect_alt
19455                     || macinfo_type == DW_MACRO_GNU_undef_indirect_alt
19456                     || section_is_dwz)
19457                   {
19458                     struct dwz_file *dwz = dwarf2_get_dwz_file ();
19459
19460                     body = read_indirect_string_from_dwz (dwz, str_offset);
19461                   }
19462                 else
19463                   body = read_indirect_string_at_offset (abfd, str_offset);
19464               }
19465
19466             is_define = (macinfo_type == DW_MACRO_GNU_define
19467                          || macinfo_type == DW_MACRO_GNU_define_indirect
19468                          || macinfo_type == DW_MACRO_GNU_define_indirect_alt);
19469             if (! current_file)
19470               {
19471                 /* DWARF violation as no main source is present.  */
19472                 complaint (&symfile_complaints,
19473                            _("debug info with no main source gives macro %s "
19474                              "on line %d: %s"),
19475                            is_define ? _("definition") : _("undefinition"),
19476                            line, body);
19477                 break;
19478               }
19479             if ((line == 0 && !at_commandline)
19480                 || (line != 0 && at_commandline))
19481               complaint (&symfile_complaints,
19482                          _("debug info gives %s macro %s with %s line %d: %s"),
19483                          at_commandline ? _("command-line") : _("in-file"),
19484                          is_define ? _("definition") : _("undefinition"),
19485                          line == 0 ? _("zero") : _("non-zero"), line, body);
19486
19487             if (is_define)
19488               parse_macro_definition (current_file, line, body);
19489             else
19490               {
19491                 gdb_assert (macinfo_type == DW_MACRO_GNU_undef
19492                             || macinfo_type == DW_MACRO_GNU_undef_indirect
19493                             || macinfo_type == DW_MACRO_GNU_undef_indirect_alt);
19494                 macro_undef (current_file, line, body);
19495               }
19496           }
19497           break;
19498
19499         case DW_MACRO_GNU_start_file:
19500           {
19501             unsigned int bytes_read;
19502             int line, file;
19503
19504             line = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
19505             mac_ptr += bytes_read;
19506             file = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
19507             mac_ptr += bytes_read;
19508
19509             if ((line == 0 && !at_commandline)
19510                 || (line != 0 && at_commandline))
19511               complaint (&symfile_complaints,
19512                          _("debug info gives source %d included "
19513                            "from %s at %s line %d"),
19514                          file, at_commandline ? _("command-line") : _("file"),
19515                          line == 0 ? _("zero") : _("non-zero"), line);
19516
19517             if (at_commandline)
19518               {
19519                 /* This DW_MACRO_GNU_start_file was executed in the
19520                    pass one.  */
19521                 at_commandline = 0;
19522               }
19523             else
19524               current_file = macro_start_file (file, line,
19525                                                current_file, comp_dir,
19526                                                lh, objfile);
19527           }
19528           break;
19529
19530         case DW_MACRO_GNU_end_file:
19531           if (! current_file)
19532             complaint (&symfile_complaints,
19533                        _("macro debug info has an unmatched "
19534                          "`close_file' directive"));
19535           else
19536             {
19537               current_file = current_file->included_by;
19538               if (! current_file)
19539                 {
19540                   enum dwarf_macro_record_type next_type;
19541
19542                   /* GCC circa March 2002 doesn't produce the zero
19543                      type byte marking the end of the compilation
19544                      unit.  Complain if it's not there, but exit no
19545                      matter what.  */
19546
19547                   /* Do we at least have room for a macinfo type byte?  */
19548                   if (mac_ptr >= mac_end)
19549                     {
19550                       dwarf2_section_buffer_overflow_complaint (section);
19551                       return;
19552                     }
19553
19554                   /* We don't increment mac_ptr here, so this is just
19555                      a look-ahead.  */
19556                   next_type = read_1_byte (abfd, mac_ptr);
19557                   if (next_type != 0)
19558                     complaint (&symfile_complaints,
19559                                _("no terminating 0-type entry for "
19560                                  "macros in `.debug_macinfo' section"));
19561
19562                   return;
19563                 }
19564             }
19565           break;
19566
19567         case DW_MACRO_GNU_transparent_include:
19568         case DW_MACRO_GNU_transparent_include_alt:
19569           {
19570             LONGEST offset;
19571             void **slot;
19572             bfd *include_bfd = abfd;
19573             struct dwarf2_section_info *include_section = section;
19574             struct dwarf2_section_info alt_section;
19575             const gdb_byte *include_mac_end = mac_end;
19576             int is_dwz = section_is_dwz;
19577             const gdb_byte *new_mac_ptr;
19578
19579             offset = read_offset_1 (abfd, mac_ptr, offset_size);
19580             mac_ptr += offset_size;
19581
19582             if (macinfo_type == DW_MACRO_GNU_transparent_include_alt)
19583               {
19584                 struct dwz_file *dwz = dwarf2_get_dwz_file ();
19585
19586                 dwarf2_read_section (dwarf2_per_objfile->objfile,
19587                                      &dwz->macro);
19588
19589                 include_bfd = dwz->macro.asection->owner;
19590                 include_section = &dwz->macro;
19591                 include_mac_end = dwz->macro.buffer + dwz->macro.size;
19592                 is_dwz = 1;
19593               }
19594
19595             new_mac_ptr = include_section->buffer + offset;
19596             slot = htab_find_slot (include_hash, new_mac_ptr, INSERT);
19597
19598             if (*slot != NULL)
19599               {
19600                 /* This has actually happened; see
19601                    http://sourceware.org/bugzilla/show_bug.cgi?id=13568.  */
19602                 complaint (&symfile_complaints,
19603                            _("recursive DW_MACRO_GNU_transparent_include in "
19604                              ".debug_macro section"));
19605               }
19606             else
19607               {
19608                 *slot = (void *) new_mac_ptr;
19609
19610                 dwarf_decode_macro_bytes (include_bfd, new_mac_ptr,
19611                                           include_mac_end, current_file,
19612                                           lh, comp_dir,
19613                                           section, section_is_gnu, is_dwz,
19614                                           offset_size, objfile, include_hash);
19615
19616                 htab_remove_elt (include_hash, (void *) new_mac_ptr);
19617               }
19618           }
19619           break;
19620
19621         case DW_MACINFO_vendor_ext:
19622           if (!section_is_gnu)
19623             {
19624               unsigned int bytes_read;
19625               int constant;
19626
19627               constant = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
19628               mac_ptr += bytes_read;
19629               read_direct_string (abfd, mac_ptr, &bytes_read);
19630               mac_ptr += bytes_read;
19631
19632               /* We don't recognize any vendor extensions.  */
19633               break;
19634             }
19635           /* FALLTHROUGH */
19636
19637         default:
19638           mac_ptr = skip_unknown_opcode (macinfo_type, opcode_definitions,
19639                                          mac_ptr, mac_end, abfd, offset_size,
19640                                          section);
19641           if (mac_ptr == NULL)
19642             return;
19643           break;
19644         }
19645     } while (macinfo_type != 0);
19646 }
19647
19648 static void
19649 dwarf_decode_macros (struct dwarf2_cu *cu, unsigned int offset,
19650                      const char *comp_dir, int section_is_gnu)
19651 {
19652   struct objfile *objfile = dwarf2_per_objfile->objfile;
19653   struct line_header *lh = cu->line_header;
19654   bfd *abfd;
19655   const gdb_byte *mac_ptr, *mac_end;
19656   struct macro_source_file *current_file = 0;
19657   enum dwarf_macro_record_type macinfo_type;
19658   unsigned int offset_size = cu->header.offset_size;
19659   const gdb_byte *opcode_definitions[256];
19660   struct cleanup *cleanup;
19661   htab_t include_hash;
19662   void **slot;
19663   struct dwarf2_section_info *section;
19664   const char *section_name;
19665
19666   if (cu->dwo_unit != NULL)
19667     {
19668       if (section_is_gnu)
19669         {
19670           section = &cu->dwo_unit->dwo_file->sections.macro;
19671           section_name = ".debug_macro.dwo";
19672         }
19673       else
19674         {
19675           section = &cu->dwo_unit->dwo_file->sections.macinfo;
19676           section_name = ".debug_macinfo.dwo";
19677         }
19678     }
19679   else
19680     {
19681       if (section_is_gnu)
19682         {
19683           section = &dwarf2_per_objfile->macro;
19684           section_name = ".debug_macro";
19685         }
19686       else
19687         {
19688           section = &dwarf2_per_objfile->macinfo;
19689           section_name = ".debug_macinfo";
19690         }
19691     }
19692
19693   dwarf2_read_section (objfile, section);
19694   if (section->buffer == NULL)
19695     {
19696       complaint (&symfile_complaints, _("missing %s section"), section_name);
19697       return;
19698     }
19699   abfd = section->asection->owner;
19700
19701   /* First pass: Find the name of the base filename.
19702      This filename is needed in order to process all macros whose definition
19703      (or undefinition) comes from the command line.  These macros are defined
19704      before the first DW_MACINFO_start_file entry, and yet still need to be
19705      associated to the base file.
19706
19707      To determine the base file name, we scan the macro definitions until we
19708      reach the first DW_MACINFO_start_file entry.  We then initialize
19709      CURRENT_FILE accordingly so that any macro definition found before the
19710      first DW_MACINFO_start_file can still be associated to the base file.  */
19711
19712   mac_ptr = section->buffer + offset;
19713   mac_end = section->buffer + section->size;
19714
19715   mac_ptr = dwarf_parse_macro_header (opcode_definitions, abfd, mac_ptr,
19716                                       &offset_size, section_is_gnu);
19717   if (mac_ptr == NULL)
19718     {
19719       /* We already issued a complaint.  */
19720       return;
19721     }
19722
19723   do
19724     {
19725       /* Do we at least have room for a macinfo type byte?  */
19726       if (mac_ptr >= mac_end)
19727         {
19728           /* Complaint is printed during the second pass as GDB will probably
19729              stop the first pass earlier upon finding
19730              DW_MACINFO_start_file.  */
19731           break;
19732         }
19733
19734       macinfo_type = read_1_byte (abfd, mac_ptr);
19735       mac_ptr++;
19736
19737       /* Note that we rely on the fact that the corresponding GNU and
19738          DWARF constants are the same.  */
19739       switch (macinfo_type)
19740         {
19741           /* A zero macinfo type indicates the end of the macro
19742              information.  */
19743         case 0:
19744           break;
19745
19746         case DW_MACRO_GNU_define:
19747         case DW_MACRO_GNU_undef:
19748           /* Only skip the data by MAC_PTR.  */
19749           {
19750             unsigned int bytes_read;
19751
19752             read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
19753             mac_ptr += bytes_read;
19754             read_direct_string (abfd, mac_ptr, &bytes_read);
19755             mac_ptr += bytes_read;
19756           }
19757           break;
19758
19759         case DW_MACRO_GNU_start_file:
19760           {
19761             unsigned int bytes_read;
19762             int line, file;
19763
19764             line = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
19765             mac_ptr += bytes_read;
19766             file = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
19767             mac_ptr += bytes_read;
19768
19769             current_file = macro_start_file (file, line, current_file,
19770                                              comp_dir, lh, objfile);
19771           }
19772           break;
19773
19774         case DW_MACRO_GNU_end_file:
19775           /* No data to skip by MAC_PTR.  */
19776           break;
19777
19778         case DW_MACRO_GNU_define_indirect:
19779         case DW_MACRO_GNU_undef_indirect:
19780         case DW_MACRO_GNU_define_indirect_alt:
19781         case DW_MACRO_GNU_undef_indirect_alt:
19782           {
19783             unsigned int bytes_read;
19784
19785             read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
19786             mac_ptr += bytes_read;
19787             mac_ptr += offset_size;
19788           }
19789           break;
19790
19791         case DW_MACRO_GNU_transparent_include:
19792         case DW_MACRO_GNU_transparent_include_alt:
19793           /* Note that, according to the spec, a transparent include
19794              chain cannot call DW_MACRO_GNU_start_file.  So, we can just
19795              skip this opcode.  */
19796           mac_ptr += offset_size;
19797           break;
19798
19799         case DW_MACINFO_vendor_ext:
19800           /* Only skip the data by MAC_PTR.  */
19801           if (!section_is_gnu)
19802             {
19803               unsigned int bytes_read;
19804
19805               read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
19806               mac_ptr += bytes_read;
19807               read_direct_string (abfd, mac_ptr, &bytes_read);
19808               mac_ptr += bytes_read;
19809             }
19810           /* FALLTHROUGH */
19811
19812         default:
19813           mac_ptr = skip_unknown_opcode (macinfo_type, opcode_definitions,
19814                                          mac_ptr, mac_end, abfd, offset_size,
19815                                          section);
19816           if (mac_ptr == NULL)
19817             return;
19818           break;
19819         }
19820     } while (macinfo_type != 0 && current_file == NULL);
19821
19822   /* Second pass: Process all entries.
19823
19824      Use the AT_COMMAND_LINE flag to determine whether we are still processing
19825      command-line macro definitions/undefinitions.  This flag is unset when we
19826      reach the first DW_MACINFO_start_file entry.  */
19827
19828   include_hash = htab_create_alloc (1, htab_hash_pointer, htab_eq_pointer,
19829                                     NULL, xcalloc, xfree);
19830   cleanup = make_cleanup_htab_delete (include_hash);
19831   mac_ptr = section->buffer + offset;
19832   slot = htab_find_slot (include_hash, mac_ptr, INSERT);
19833   *slot = (void *) mac_ptr;
19834   dwarf_decode_macro_bytes (abfd, mac_ptr, mac_end,
19835                             current_file, lh, comp_dir, section,
19836                             section_is_gnu, 0,
19837                             offset_size, objfile, include_hash);
19838   do_cleanups (cleanup);
19839 }
19840
19841 /* Check if the attribute's form is a DW_FORM_block*
19842    if so return true else false.  */
19843
19844 static int
19845 attr_form_is_block (const struct attribute *attr)
19846 {
19847   return (attr == NULL ? 0 :
19848       attr->form == DW_FORM_block1
19849       || attr->form == DW_FORM_block2
19850       || attr->form == DW_FORM_block4
19851       || attr->form == DW_FORM_block
19852       || attr->form == DW_FORM_exprloc);
19853 }
19854
19855 /* Return non-zero if ATTR's value is a section offset --- classes
19856    lineptr, loclistptr, macptr or rangelistptr --- or zero, otherwise.
19857    You may use DW_UNSND (attr) to retrieve such offsets.
19858
19859    Section 7.5.4, "Attribute Encodings", explains that no attribute
19860    may have a value that belongs to more than one of these classes; it
19861    would be ambiguous if we did, because we use the same forms for all
19862    of them.  */
19863
19864 static int
19865 attr_form_is_section_offset (const struct attribute *attr)
19866 {
19867   return (attr->form == DW_FORM_data4
19868           || attr->form == DW_FORM_data8
19869           || attr->form == DW_FORM_sec_offset);
19870 }
19871
19872 /* Return non-zero if ATTR's value falls in the 'constant' class, or
19873    zero otherwise.  When this function returns true, you can apply
19874    dwarf2_get_attr_constant_value to it.
19875
19876    However, note that for some attributes you must check
19877    attr_form_is_section_offset before using this test.  DW_FORM_data4
19878    and DW_FORM_data8 are members of both the constant class, and of
19879    the classes that contain offsets into other debug sections
19880    (lineptr, loclistptr, macptr or rangelistptr).  The DWARF spec says
19881    that, if an attribute's can be either a constant or one of the
19882    section offset classes, DW_FORM_data4 and DW_FORM_data8 should be
19883    taken as section offsets, not constants.  */
19884
19885 static int
19886 attr_form_is_constant (const struct attribute *attr)
19887 {
19888   switch (attr->form)
19889     {
19890     case DW_FORM_sdata:
19891     case DW_FORM_udata:
19892     case DW_FORM_data1:
19893     case DW_FORM_data2:
19894     case DW_FORM_data4:
19895     case DW_FORM_data8:
19896       return 1;
19897     default:
19898       return 0;
19899     }
19900 }
19901
19902
19903 /* DW_ADDR is always stored already as sect_offset; despite for the forms
19904    besides DW_FORM_ref_addr it is stored as cu_offset in the DWARF file.  */
19905
19906 static int
19907 attr_form_is_ref (const struct attribute *attr)
19908 {
19909   switch (attr->form)
19910     {
19911     case DW_FORM_ref_addr:
19912     case DW_FORM_ref1:
19913     case DW_FORM_ref2:
19914     case DW_FORM_ref4:
19915     case DW_FORM_ref8:
19916     case DW_FORM_ref_udata:
19917     case DW_FORM_GNU_ref_alt:
19918       return 1;
19919     default:
19920       return 0;
19921     }
19922 }
19923
19924 /* Return the .debug_loc section to use for CU.
19925    For DWO files use .debug_loc.dwo.  */
19926
19927 static struct dwarf2_section_info *
19928 cu_debug_loc_section (struct dwarf2_cu *cu)
19929 {
19930   if (cu->dwo_unit)
19931     return &cu->dwo_unit->dwo_file->sections.loc;
19932   return &dwarf2_per_objfile->loc;
19933 }
19934
19935 /* A helper function that fills in a dwarf2_loclist_baton.  */
19936
19937 static void
19938 fill_in_loclist_baton (struct dwarf2_cu *cu,
19939                        struct dwarf2_loclist_baton *baton,
19940                        const struct attribute *attr)
19941 {
19942   struct dwarf2_section_info *section = cu_debug_loc_section (cu);
19943
19944   dwarf2_read_section (dwarf2_per_objfile->objfile, section);
19945
19946   baton->per_cu = cu->per_cu;
19947   gdb_assert (baton->per_cu);
19948   /* We don't know how long the location list is, but make sure we
19949      don't run off the edge of the section.  */
19950   baton->size = section->size - DW_UNSND (attr);
19951   baton->data = section->buffer + DW_UNSND (attr);
19952   baton->base_address = cu->base_address;
19953   baton->from_dwo = cu->dwo_unit != NULL;
19954 }
19955
19956 static void
19957 dwarf2_symbol_mark_computed (const struct attribute *attr, struct symbol *sym,
19958                              struct dwarf2_cu *cu, int is_block)
19959 {
19960   struct objfile *objfile = dwarf2_per_objfile->objfile;
19961   struct dwarf2_section_info *section = cu_debug_loc_section (cu);
19962
19963   if (attr_form_is_section_offset (attr)
19964       /* .debug_loc{,.dwo} may not exist at all, or the offset may be outside
19965          the section.  If so, fall through to the complaint in the
19966          other branch.  */
19967       && DW_UNSND (attr) < dwarf2_section_size (objfile, section))
19968     {
19969       struct dwarf2_loclist_baton *baton;
19970
19971       baton = obstack_alloc (&objfile->objfile_obstack,
19972                              sizeof (struct dwarf2_loclist_baton));
19973
19974       fill_in_loclist_baton (cu, baton, attr);
19975
19976       if (cu->base_known == 0)
19977         complaint (&symfile_complaints,
19978                    _("Location list used without "
19979                      "specifying the CU base address."));
19980
19981       SYMBOL_ACLASS_INDEX (sym) = (is_block
19982                                    ? dwarf2_loclist_block_index
19983                                    : dwarf2_loclist_index);
19984       SYMBOL_LOCATION_BATON (sym) = baton;
19985     }
19986   else
19987     {
19988       struct dwarf2_locexpr_baton *baton;
19989
19990       baton = obstack_alloc (&objfile->objfile_obstack,
19991                              sizeof (struct dwarf2_locexpr_baton));
19992       baton->per_cu = cu->per_cu;
19993       gdb_assert (baton->per_cu);
19994
19995       if (attr_form_is_block (attr))
19996         {
19997           /* Note that we're just copying the block's data pointer
19998              here, not the actual data.  We're still pointing into the
19999              info_buffer for SYM's objfile; right now we never release
20000              that buffer, but when we do clean up properly this may
20001              need to change.  */
20002           baton->size = DW_BLOCK (attr)->size;
20003           baton->data = DW_BLOCK (attr)->data;
20004         }
20005       else
20006         {
20007           dwarf2_invalid_attrib_class_complaint ("location description",
20008                                                  SYMBOL_NATURAL_NAME (sym));
20009           baton->size = 0;
20010         }
20011
20012       SYMBOL_ACLASS_INDEX (sym) = (is_block
20013                                    ? dwarf2_locexpr_block_index
20014                                    : dwarf2_locexpr_index);
20015       SYMBOL_LOCATION_BATON (sym) = baton;
20016     }
20017 }
20018
20019 /* Return the OBJFILE associated with the compilation unit CU.  If CU
20020    came from a separate debuginfo file, then the master objfile is
20021    returned.  */
20022
20023 struct objfile *
20024 dwarf2_per_cu_objfile (struct dwarf2_per_cu_data *per_cu)
20025 {
20026   struct objfile *objfile = per_cu->objfile;
20027
20028   /* Return the master objfile, so that we can report and look up the
20029      correct file containing this variable.  */
20030   if (objfile->separate_debug_objfile_backlink)
20031     objfile = objfile->separate_debug_objfile_backlink;
20032
20033   return objfile;
20034 }
20035
20036 /* Return comp_unit_head for PER_CU, either already available in PER_CU->CU
20037    (CU_HEADERP is unused in such case) or prepare a temporary copy at
20038    CU_HEADERP first.  */
20039
20040 static const struct comp_unit_head *
20041 per_cu_header_read_in (struct comp_unit_head *cu_headerp,
20042                        struct dwarf2_per_cu_data *per_cu)
20043 {
20044   const gdb_byte *info_ptr;
20045
20046   if (per_cu->cu)
20047     return &per_cu->cu->header;
20048
20049   info_ptr = per_cu->section->buffer + per_cu->offset.sect_off;
20050
20051   memset (cu_headerp, 0, sizeof (*cu_headerp));
20052   read_comp_unit_head (cu_headerp, info_ptr, per_cu->objfile->obfd);
20053
20054   return cu_headerp;
20055 }
20056
20057 /* Return the address size given in the compilation unit header for CU.  */
20058
20059 int
20060 dwarf2_per_cu_addr_size (struct dwarf2_per_cu_data *per_cu)
20061 {
20062   struct comp_unit_head cu_header_local;
20063   const struct comp_unit_head *cu_headerp;
20064
20065   cu_headerp = per_cu_header_read_in (&cu_header_local, per_cu);
20066
20067   return cu_headerp->addr_size;
20068 }
20069
20070 /* Return the offset size given in the compilation unit header for CU.  */
20071
20072 int
20073 dwarf2_per_cu_offset_size (struct dwarf2_per_cu_data *per_cu)
20074 {
20075   struct comp_unit_head cu_header_local;
20076   const struct comp_unit_head *cu_headerp;
20077
20078   cu_headerp = per_cu_header_read_in (&cu_header_local, per_cu);
20079
20080   return cu_headerp->offset_size;
20081 }
20082
20083 /* See its dwarf2loc.h declaration.  */
20084
20085 int
20086 dwarf2_per_cu_ref_addr_size (struct dwarf2_per_cu_data *per_cu)
20087 {
20088   struct comp_unit_head cu_header_local;
20089   const struct comp_unit_head *cu_headerp;
20090
20091   cu_headerp = per_cu_header_read_in (&cu_header_local, per_cu);
20092
20093   if (cu_headerp->version == 2)
20094     return cu_headerp->addr_size;
20095   else
20096     return cu_headerp->offset_size;
20097 }
20098
20099 /* Return the text offset of the CU.  The returned offset comes from
20100    this CU's objfile.  If this objfile came from a separate debuginfo
20101    file, then the offset may be different from the corresponding
20102    offset in the parent objfile.  */
20103
20104 CORE_ADDR
20105 dwarf2_per_cu_text_offset (struct dwarf2_per_cu_data *per_cu)
20106 {
20107   struct objfile *objfile = per_cu->objfile;
20108
20109   return ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
20110 }
20111
20112 /* Locate the .debug_info compilation unit from CU's objfile which contains
20113    the DIE at OFFSET.  Raises an error on failure.  */
20114
20115 static struct dwarf2_per_cu_data *
20116 dwarf2_find_containing_comp_unit (sect_offset offset,
20117                                   unsigned int offset_in_dwz,
20118                                   struct objfile *objfile)
20119 {
20120   struct dwarf2_per_cu_data *this_cu;
20121   int low, high;
20122   const sect_offset *cu_off;
20123
20124   low = 0;
20125   high = dwarf2_per_objfile->n_comp_units - 1;
20126   while (high > low)
20127     {
20128       struct dwarf2_per_cu_data *mid_cu;
20129       int mid = low + (high - low) / 2;
20130
20131       mid_cu = dwarf2_per_objfile->all_comp_units[mid];
20132       cu_off = &mid_cu->offset;
20133       if (mid_cu->is_dwz > offset_in_dwz
20134           || (mid_cu->is_dwz == offset_in_dwz
20135               && cu_off->sect_off >= offset.sect_off))
20136         high = mid;
20137       else
20138         low = mid + 1;
20139     }
20140   gdb_assert (low == high);
20141   this_cu = dwarf2_per_objfile->all_comp_units[low];
20142   cu_off = &this_cu->offset;
20143   if (this_cu->is_dwz != offset_in_dwz || cu_off->sect_off > offset.sect_off)
20144     {
20145       if (low == 0 || this_cu->is_dwz != offset_in_dwz)
20146         error (_("Dwarf Error: could not find partial DIE containing "
20147                "offset 0x%lx [in module %s]"),
20148                (long) offset.sect_off, bfd_get_filename (objfile->obfd));
20149
20150       gdb_assert (dwarf2_per_objfile->all_comp_units[low-1]->offset.sect_off
20151                   <= offset.sect_off);
20152       return dwarf2_per_objfile->all_comp_units[low-1];
20153     }
20154   else
20155     {
20156       this_cu = dwarf2_per_objfile->all_comp_units[low];
20157       if (low == dwarf2_per_objfile->n_comp_units - 1
20158           && offset.sect_off >= this_cu->offset.sect_off + this_cu->length)
20159         error (_("invalid dwarf2 offset %u"), offset.sect_off);
20160       gdb_assert (offset.sect_off < this_cu->offset.sect_off + this_cu->length);
20161       return this_cu;
20162     }
20163 }
20164
20165 /* Initialize dwarf2_cu CU, owned by PER_CU.  */
20166
20167 static void
20168 init_one_comp_unit (struct dwarf2_cu *cu, struct dwarf2_per_cu_data *per_cu)
20169 {
20170   memset (cu, 0, sizeof (*cu));
20171   per_cu->cu = cu;
20172   cu->per_cu = per_cu;
20173   cu->objfile = per_cu->objfile;
20174   obstack_init (&cu->comp_unit_obstack);
20175 }
20176
20177 /* Initialize basic fields of dwarf_cu CU according to DIE COMP_UNIT_DIE.  */
20178
20179 static void
20180 prepare_one_comp_unit (struct dwarf2_cu *cu, struct die_info *comp_unit_die,
20181                        enum language pretend_language)
20182 {
20183   struct attribute *attr;
20184
20185   /* Set the language we're debugging.  */
20186   attr = dwarf2_attr (comp_unit_die, DW_AT_language, cu);
20187   if (attr)
20188     set_cu_language (DW_UNSND (attr), cu);
20189   else
20190     {
20191       cu->language = pretend_language;
20192       cu->language_defn = language_def (cu->language);
20193     }
20194
20195   attr = dwarf2_attr (comp_unit_die, DW_AT_producer, cu);
20196   if (attr)
20197     cu->producer = DW_STRING (attr);
20198 }
20199
20200 /* Release one cached compilation unit, CU.  We unlink it from the tree
20201    of compilation units, but we don't remove it from the read_in_chain;
20202    the caller is responsible for that.
20203    NOTE: DATA is a void * because this function is also used as a
20204    cleanup routine.  */
20205
20206 static void
20207 free_heap_comp_unit (void *data)
20208 {
20209   struct dwarf2_cu *cu = data;
20210
20211   gdb_assert (cu->per_cu != NULL);
20212   cu->per_cu->cu = NULL;
20213   cu->per_cu = NULL;
20214
20215   obstack_free (&cu->comp_unit_obstack, NULL);
20216
20217   xfree (cu);
20218 }
20219
20220 /* This cleanup function is passed the address of a dwarf2_cu on the stack
20221    when we're finished with it.  We can't free the pointer itself, but be
20222    sure to unlink it from the cache.  Also release any associated storage.  */
20223
20224 static void
20225 free_stack_comp_unit (void *data)
20226 {
20227   struct dwarf2_cu *cu = data;
20228
20229   gdb_assert (cu->per_cu != NULL);
20230   cu->per_cu->cu = NULL;
20231   cu->per_cu = NULL;
20232
20233   obstack_free (&cu->comp_unit_obstack, NULL);
20234   cu->partial_dies = NULL;
20235 }
20236
20237 /* Free all cached compilation units.  */
20238
20239 static void
20240 free_cached_comp_units (void *data)
20241 {
20242   struct dwarf2_per_cu_data *per_cu, **last_chain;
20243
20244   per_cu = dwarf2_per_objfile->read_in_chain;
20245   last_chain = &dwarf2_per_objfile->read_in_chain;
20246   while (per_cu != NULL)
20247     {
20248       struct dwarf2_per_cu_data *next_cu;
20249
20250       next_cu = per_cu->cu->read_in_chain;
20251
20252       free_heap_comp_unit (per_cu->cu);
20253       *last_chain = next_cu;
20254
20255       per_cu = next_cu;
20256     }
20257 }
20258
20259 /* Increase the age counter on each cached compilation unit, and free
20260    any that are too old.  */
20261
20262 static void
20263 age_cached_comp_units (void)
20264 {
20265   struct dwarf2_per_cu_data *per_cu, **last_chain;
20266
20267   dwarf2_clear_marks (dwarf2_per_objfile->read_in_chain);
20268   per_cu = dwarf2_per_objfile->read_in_chain;
20269   while (per_cu != NULL)
20270     {
20271       per_cu->cu->last_used ++;
20272       if (per_cu->cu->last_used <= dwarf2_max_cache_age)
20273         dwarf2_mark (per_cu->cu);
20274       per_cu = per_cu->cu->read_in_chain;
20275     }
20276
20277   per_cu = dwarf2_per_objfile->read_in_chain;
20278   last_chain = &dwarf2_per_objfile->read_in_chain;
20279   while (per_cu != NULL)
20280     {
20281       struct dwarf2_per_cu_data *next_cu;
20282
20283       next_cu = per_cu->cu->read_in_chain;
20284
20285       if (!per_cu->cu->mark)
20286         {
20287           free_heap_comp_unit (per_cu->cu);
20288           *last_chain = next_cu;
20289         }
20290       else
20291         last_chain = &per_cu->cu->read_in_chain;
20292
20293       per_cu = next_cu;
20294     }
20295 }
20296
20297 /* Remove a single compilation unit from the cache.  */
20298
20299 static void
20300 free_one_cached_comp_unit (struct dwarf2_per_cu_data *target_per_cu)
20301 {
20302   struct dwarf2_per_cu_data *per_cu, **last_chain;
20303
20304   per_cu = dwarf2_per_objfile->read_in_chain;
20305   last_chain = &dwarf2_per_objfile->read_in_chain;
20306   while (per_cu != NULL)
20307     {
20308       struct dwarf2_per_cu_data *next_cu;
20309
20310       next_cu = per_cu->cu->read_in_chain;
20311
20312       if (per_cu == target_per_cu)
20313         {
20314           free_heap_comp_unit (per_cu->cu);
20315           per_cu->cu = NULL;
20316           *last_chain = next_cu;
20317           break;
20318         }
20319       else
20320         last_chain = &per_cu->cu->read_in_chain;
20321
20322       per_cu = next_cu;
20323     }
20324 }
20325
20326 /* Release all extra memory associated with OBJFILE.  */
20327
20328 void
20329 dwarf2_free_objfile (struct objfile *objfile)
20330 {
20331   dwarf2_per_objfile = objfile_data (objfile, dwarf2_objfile_data_key);
20332
20333   if (dwarf2_per_objfile == NULL)
20334     return;
20335
20336   /* Cached DIE trees use xmalloc and the comp_unit_obstack.  */
20337   free_cached_comp_units (NULL);
20338
20339   if (dwarf2_per_objfile->quick_file_names_table)
20340     htab_delete (dwarf2_per_objfile->quick_file_names_table);
20341
20342   /* Everything else should be on the objfile obstack.  */
20343 }
20344
20345 /* A set of CU "per_cu" pointer, DIE offset, and GDB type pointer.
20346    We store these in a hash table separate from the DIEs, and preserve them
20347    when the DIEs are flushed out of cache.
20348
20349    The CU "per_cu" pointer is needed because offset alone is not enough to
20350    uniquely identify the type.  A file may have multiple .debug_types sections,
20351    or the type may come from a DWO file.  Furthermore, while it's more logical
20352    to use per_cu->section+offset, with Fission the section with the data is in
20353    the DWO file but we don't know that section at the point we need it.
20354    We have to use something in dwarf2_per_cu_data (or the pointer to it)
20355    because we can enter the lookup routine, get_die_type_at_offset, from
20356    outside this file, and thus won't necessarily have PER_CU->cu.
20357    Fortunately, PER_CU is stable for the life of the objfile.  */
20358
20359 struct dwarf2_per_cu_offset_and_type
20360 {
20361   const struct dwarf2_per_cu_data *per_cu;
20362   sect_offset offset;
20363   struct type *type;
20364 };
20365
20366 /* Hash function for a dwarf2_per_cu_offset_and_type.  */
20367
20368 static hashval_t
20369 per_cu_offset_and_type_hash (const void *item)
20370 {
20371   const struct dwarf2_per_cu_offset_and_type *ofs = item;
20372
20373   return (uintptr_t) ofs->per_cu + ofs->offset.sect_off;
20374 }
20375
20376 /* Equality function for a dwarf2_per_cu_offset_and_type.  */
20377
20378 static int
20379 per_cu_offset_and_type_eq (const void *item_lhs, const void *item_rhs)
20380 {
20381   const struct dwarf2_per_cu_offset_and_type *ofs_lhs = item_lhs;
20382   const struct dwarf2_per_cu_offset_and_type *ofs_rhs = item_rhs;
20383
20384   return (ofs_lhs->per_cu == ofs_rhs->per_cu
20385           && ofs_lhs->offset.sect_off == ofs_rhs->offset.sect_off);
20386 }
20387
20388 /* Set the type associated with DIE to TYPE.  Save it in CU's hash
20389    table if necessary.  For convenience, return TYPE.
20390
20391    The DIEs reading must have careful ordering to:
20392     * Not cause infite loops trying to read in DIEs as a prerequisite for
20393       reading current DIE.
20394     * Not trying to dereference contents of still incompletely read in types
20395       while reading in other DIEs.
20396     * Enable referencing still incompletely read in types just by a pointer to
20397       the type without accessing its fields.
20398
20399    Therefore caller should follow these rules:
20400      * Try to fetch any prerequisite types we may need to build this DIE type
20401        before building the type and calling set_die_type.
20402      * After building type call set_die_type for current DIE as soon as
20403        possible before fetching more types to complete the current type.
20404      * Make the type as complete as possible before fetching more types.  */
20405
20406 static struct type *
20407 set_die_type (struct die_info *die, struct type *type, struct dwarf2_cu *cu)
20408 {
20409   struct dwarf2_per_cu_offset_and_type **slot, ofs;
20410   struct objfile *objfile = cu->objfile;
20411
20412   /* For Ada types, make sure that the gnat-specific data is always
20413      initialized (if not already set).  There are a few types where
20414      we should not be doing so, because the type-specific area is
20415      already used to hold some other piece of info (eg: TYPE_CODE_FLT
20416      where the type-specific area is used to store the floatformat).
20417      But this is not a problem, because the gnat-specific information
20418      is actually not needed for these types.  */
20419   if (need_gnat_info (cu)
20420       && TYPE_CODE (type) != TYPE_CODE_FUNC
20421       && TYPE_CODE (type) != TYPE_CODE_FLT
20422       && !HAVE_GNAT_AUX_INFO (type))
20423     INIT_GNAT_SPECIFIC (type);
20424
20425   if (dwarf2_per_objfile->die_type_hash == NULL)
20426     {
20427       dwarf2_per_objfile->die_type_hash =
20428         htab_create_alloc_ex (127,
20429                               per_cu_offset_and_type_hash,
20430                               per_cu_offset_and_type_eq,
20431                               NULL,
20432                               &objfile->objfile_obstack,
20433                               hashtab_obstack_allocate,
20434                               dummy_obstack_deallocate);
20435     }
20436
20437   ofs.per_cu = cu->per_cu;
20438   ofs.offset = die->offset;
20439   ofs.type = type;
20440   slot = (struct dwarf2_per_cu_offset_and_type **)
20441     htab_find_slot (dwarf2_per_objfile->die_type_hash, &ofs, INSERT);
20442   if (*slot)
20443     complaint (&symfile_complaints,
20444                _("A problem internal to GDB: DIE 0x%x has type already set"),
20445                die->offset.sect_off);
20446   *slot = obstack_alloc (&objfile->objfile_obstack, sizeof (**slot));
20447   **slot = ofs;
20448   return type;
20449 }
20450
20451 /* Look up the type for the die at OFFSET in PER_CU in die_type_hash,
20452    or return NULL if the die does not have a saved type.  */
20453
20454 static struct type *
20455 get_die_type_at_offset (sect_offset offset,
20456                         struct dwarf2_per_cu_data *per_cu)
20457 {
20458   struct dwarf2_per_cu_offset_and_type *slot, ofs;
20459
20460   if (dwarf2_per_objfile->die_type_hash == NULL)
20461     return NULL;
20462
20463   ofs.per_cu = per_cu;
20464   ofs.offset = offset;
20465   slot = htab_find (dwarf2_per_objfile->die_type_hash, &ofs);
20466   if (slot)
20467     return slot->type;
20468   else
20469     return NULL;
20470 }
20471
20472 /* Look up the type for DIE in CU in die_type_hash,
20473    or return NULL if DIE does not have a saved type.  */
20474
20475 static struct type *
20476 get_die_type (struct die_info *die, struct dwarf2_cu *cu)
20477 {
20478   return get_die_type_at_offset (die->offset, cu->per_cu);
20479 }
20480
20481 /* Add a dependence relationship from CU to REF_PER_CU.  */
20482
20483 static void
20484 dwarf2_add_dependence (struct dwarf2_cu *cu,
20485                        struct dwarf2_per_cu_data *ref_per_cu)
20486 {
20487   void **slot;
20488
20489   if (cu->dependencies == NULL)
20490     cu->dependencies
20491       = htab_create_alloc_ex (5, htab_hash_pointer, htab_eq_pointer,
20492                               NULL, &cu->comp_unit_obstack,
20493                               hashtab_obstack_allocate,
20494                               dummy_obstack_deallocate);
20495
20496   slot = htab_find_slot (cu->dependencies, ref_per_cu, INSERT);
20497   if (*slot == NULL)
20498     *slot = ref_per_cu;
20499 }
20500
20501 /* Subroutine of dwarf2_mark to pass to htab_traverse.
20502    Set the mark field in every compilation unit in the
20503    cache that we must keep because we are keeping CU.  */
20504
20505 static int
20506 dwarf2_mark_helper (void **slot, void *data)
20507 {
20508   struct dwarf2_per_cu_data *per_cu;
20509
20510   per_cu = (struct dwarf2_per_cu_data *) *slot;
20511
20512   /* cu->dependencies references may not yet have been ever read if QUIT aborts
20513      reading of the chain.  As such dependencies remain valid it is not much
20514      useful to track and undo them during QUIT cleanups.  */
20515   if (per_cu->cu == NULL)
20516     return 1;
20517
20518   if (per_cu->cu->mark)
20519     return 1;
20520   per_cu->cu->mark = 1;
20521
20522   if (per_cu->cu->dependencies != NULL)
20523     htab_traverse (per_cu->cu->dependencies, dwarf2_mark_helper, NULL);
20524
20525   return 1;
20526 }
20527
20528 /* Set the mark field in CU and in every other compilation unit in the
20529    cache that we must keep because we are keeping CU.  */
20530
20531 static void
20532 dwarf2_mark (struct dwarf2_cu *cu)
20533 {
20534   if (cu->mark)
20535     return;
20536   cu->mark = 1;
20537   if (cu->dependencies != NULL)
20538     htab_traverse (cu->dependencies, dwarf2_mark_helper, NULL);
20539 }
20540
20541 static void
20542 dwarf2_clear_marks (struct dwarf2_per_cu_data *per_cu)
20543 {
20544   while (per_cu)
20545     {
20546       per_cu->cu->mark = 0;
20547       per_cu = per_cu->cu->read_in_chain;
20548     }
20549 }
20550
20551 /* Trivial hash function for partial_die_info: the hash value of a DIE
20552    is its offset in .debug_info for this objfile.  */
20553
20554 static hashval_t
20555 partial_die_hash (const void *item)
20556 {
20557   const struct partial_die_info *part_die = item;
20558
20559   return part_die->offset.sect_off;
20560 }
20561
20562 /* Trivial comparison function for partial_die_info structures: two DIEs
20563    are equal if they have the same offset.  */
20564
20565 static int
20566 partial_die_eq (const void *item_lhs, const void *item_rhs)
20567 {
20568   const struct partial_die_info *part_die_lhs = item_lhs;
20569   const struct partial_die_info *part_die_rhs = item_rhs;
20570
20571   return part_die_lhs->offset.sect_off == part_die_rhs->offset.sect_off;
20572 }
20573
20574 static struct cmd_list_element *set_dwarf2_cmdlist;
20575 static struct cmd_list_element *show_dwarf2_cmdlist;
20576
20577 static void
20578 set_dwarf2_cmd (char *args, int from_tty)
20579 {
20580   help_list (set_dwarf2_cmdlist, "maintenance set dwarf2 ", -1, gdb_stdout);
20581 }
20582
20583 static void
20584 show_dwarf2_cmd (char *args, int from_tty)
20585 {
20586   cmd_show_list (show_dwarf2_cmdlist, from_tty, "");
20587 }
20588
20589 /* Free data associated with OBJFILE, if necessary.  */
20590
20591 static void
20592 dwarf2_per_objfile_free (struct objfile *objfile, void *d)
20593 {
20594   struct dwarf2_per_objfile *data = d;
20595   int ix;
20596
20597   /* Make sure we don't accidentally use dwarf2_per_objfile while
20598      cleaning up.  */
20599   dwarf2_per_objfile = NULL;
20600
20601   for (ix = 0; ix < data->n_comp_units; ++ix)
20602    VEC_free (dwarf2_per_cu_ptr, data->all_comp_units[ix]->imported_symtabs);
20603
20604   for (ix = 0; ix < data->n_type_units; ++ix)
20605     VEC_free (dwarf2_per_cu_ptr,
20606               data->all_type_units[ix]->per_cu.imported_symtabs);
20607   xfree (data->all_type_units);
20608
20609   VEC_free (dwarf2_section_info_def, data->types);
20610
20611   if (data->dwo_files)
20612     free_dwo_files (data->dwo_files, objfile);
20613   if (data->dwp_file)
20614     gdb_bfd_unref (data->dwp_file->dbfd);
20615
20616   if (data->dwz_file && data->dwz_file->dwz_bfd)
20617     gdb_bfd_unref (data->dwz_file->dwz_bfd);
20618 }
20619
20620 \f
20621 /* The "save gdb-index" command.  */
20622
20623 /* The contents of the hash table we create when building the string
20624    table.  */
20625 struct strtab_entry
20626 {
20627   offset_type offset;
20628   const char *str;
20629 };
20630
20631 /* Hash function for a strtab_entry.
20632
20633    Function is used only during write_hash_table so no index format backward
20634    compatibility is needed.  */
20635
20636 static hashval_t
20637 hash_strtab_entry (const void *e)
20638 {
20639   const struct strtab_entry *entry = e;
20640   return mapped_index_string_hash (INT_MAX, entry->str);
20641 }
20642
20643 /* Equality function for a strtab_entry.  */
20644
20645 static int
20646 eq_strtab_entry (const void *a, const void *b)
20647 {
20648   const struct strtab_entry *ea = a;
20649   const struct strtab_entry *eb = b;
20650   return !strcmp (ea->str, eb->str);
20651 }
20652
20653 /* Create a strtab_entry hash table.  */
20654
20655 static htab_t
20656 create_strtab (void)
20657 {
20658   return htab_create_alloc (100, hash_strtab_entry, eq_strtab_entry,
20659                             xfree, xcalloc, xfree);
20660 }
20661
20662 /* Add a string to the constant pool.  Return the string's offset in
20663    host order.  */
20664
20665 static offset_type
20666 add_string (htab_t table, struct obstack *cpool, const char *str)
20667 {
20668   void **slot;
20669   struct strtab_entry entry;
20670   struct strtab_entry *result;
20671
20672   entry.str = str;
20673   slot = htab_find_slot (table, &entry, INSERT);
20674   if (*slot)
20675     result = *slot;
20676   else
20677     {
20678       result = XNEW (struct strtab_entry);
20679       result->offset = obstack_object_size (cpool);
20680       result->str = str;
20681       obstack_grow_str0 (cpool, str);
20682       *slot = result;
20683     }
20684   return result->offset;
20685 }
20686
20687 /* An entry in the symbol table.  */
20688 struct symtab_index_entry
20689 {
20690   /* The name of the symbol.  */
20691   const char *name;
20692   /* The offset of the name in the constant pool.  */
20693   offset_type index_offset;
20694   /* A sorted vector of the indices of all the CUs that hold an object
20695      of this name.  */
20696   VEC (offset_type) *cu_indices;
20697 };
20698
20699 /* The symbol table.  This is a power-of-2-sized hash table.  */
20700 struct mapped_symtab
20701 {
20702   offset_type n_elements;
20703   offset_type size;
20704   struct symtab_index_entry **data;
20705 };
20706
20707 /* Hash function for a symtab_index_entry.  */
20708
20709 static hashval_t
20710 hash_symtab_entry (const void *e)
20711 {
20712   const struct symtab_index_entry *entry = e;
20713   return iterative_hash (VEC_address (offset_type, entry->cu_indices),
20714                          sizeof (offset_type) * VEC_length (offset_type,
20715                                                             entry->cu_indices),
20716                          0);
20717 }
20718
20719 /* Equality function for a symtab_index_entry.  */
20720
20721 static int
20722 eq_symtab_entry (const void *a, const void *b)
20723 {
20724   const struct symtab_index_entry *ea = a;
20725   const struct symtab_index_entry *eb = b;
20726   int len = VEC_length (offset_type, ea->cu_indices);
20727   if (len != VEC_length (offset_type, eb->cu_indices))
20728     return 0;
20729   return !memcmp (VEC_address (offset_type, ea->cu_indices),
20730                   VEC_address (offset_type, eb->cu_indices),
20731                   sizeof (offset_type) * len);
20732 }
20733
20734 /* Destroy a symtab_index_entry.  */
20735
20736 static void
20737 delete_symtab_entry (void *p)
20738 {
20739   struct symtab_index_entry *entry = p;
20740   VEC_free (offset_type, entry->cu_indices);
20741   xfree (entry);
20742 }
20743
20744 /* Create a hash table holding symtab_index_entry objects.  */
20745
20746 static htab_t
20747 create_symbol_hash_table (void)
20748 {
20749   return htab_create_alloc (100, hash_symtab_entry, eq_symtab_entry,
20750                             delete_symtab_entry, xcalloc, xfree);
20751 }
20752
20753 /* Create a new mapped symtab object.  */
20754
20755 static struct mapped_symtab *
20756 create_mapped_symtab (void)
20757 {
20758   struct mapped_symtab *symtab = XNEW (struct mapped_symtab);
20759   symtab->n_elements = 0;
20760   symtab->size = 1024;
20761   symtab->data = XCNEWVEC (struct symtab_index_entry *, symtab->size);
20762   return symtab;
20763 }
20764
20765 /* Destroy a mapped_symtab.  */
20766
20767 static void
20768 cleanup_mapped_symtab (void *p)
20769 {
20770   struct mapped_symtab *symtab = p;
20771   /* The contents of the array are freed when the other hash table is
20772      destroyed.  */
20773   xfree (symtab->data);
20774   xfree (symtab);
20775 }
20776
20777 /* Find a slot in SYMTAB for the symbol NAME.  Returns a pointer to
20778    the slot.
20779    
20780    Function is used only during write_hash_table so no index format backward
20781    compatibility is needed.  */
20782
20783 static struct symtab_index_entry **
20784 find_slot (struct mapped_symtab *symtab, const char *name)
20785 {
20786   offset_type index, step, hash = mapped_index_string_hash (INT_MAX, name);
20787
20788   index = hash & (symtab->size - 1);
20789   step = ((hash * 17) & (symtab->size - 1)) | 1;
20790
20791   for (;;)
20792     {
20793       if (!symtab->data[index] || !strcmp (name, symtab->data[index]->name))
20794         return &symtab->data[index];
20795       index = (index + step) & (symtab->size - 1);
20796     }
20797 }
20798
20799 /* Expand SYMTAB's hash table.  */
20800
20801 static void
20802 hash_expand (struct mapped_symtab *symtab)
20803 {
20804   offset_type old_size = symtab->size;
20805   offset_type i;
20806   struct symtab_index_entry **old_entries = symtab->data;
20807
20808   symtab->size *= 2;
20809   symtab->data = XCNEWVEC (struct symtab_index_entry *, symtab->size);
20810
20811   for (i = 0; i < old_size; ++i)
20812     {
20813       if (old_entries[i])
20814         {
20815           struct symtab_index_entry **slot = find_slot (symtab,
20816                                                         old_entries[i]->name);
20817           *slot = old_entries[i];
20818         }
20819     }
20820
20821   xfree (old_entries);
20822 }
20823
20824 /* Add an entry to SYMTAB.  NAME is the name of the symbol.
20825    CU_INDEX is the index of the CU in which the symbol appears.
20826    IS_STATIC is one if the symbol is static, otherwise zero (global).  */
20827
20828 static void
20829 add_index_entry (struct mapped_symtab *symtab, const char *name,
20830                  int is_static, gdb_index_symbol_kind kind,
20831                  offset_type cu_index)
20832 {
20833   struct symtab_index_entry **slot;
20834   offset_type cu_index_and_attrs;
20835
20836   ++symtab->n_elements;
20837   if (4 * symtab->n_elements / 3 >= symtab->size)
20838     hash_expand (symtab);
20839
20840   slot = find_slot (symtab, name);
20841   if (!*slot)
20842     {
20843       *slot = XNEW (struct symtab_index_entry);
20844       (*slot)->name = name;
20845       /* index_offset is set later.  */
20846       (*slot)->cu_indices = NULL;
20847     }
20848
20849   cu_index_and_attrs = 0;
20850   DW2_GDB_INDEX_CU_SET_VALUE (cu_index_and_attrs, cu_index);
20851   DW2_GDB_INDEX_SYMBOL_STATIC_SET_VALUE (cu_index_and_attrs, is_static);
20852   DW2_GDB_INDEX_SYMBOL_KIND_SET_VALUE (cu_index_and_attrs, kind);
20853
20854   /* We don't want to record an index value twice as we want to avoid the
20855      duplication.
20856      We process all global symbols and then all static symbols
20857      (which would allow us to avoid the duplication by only having to check
20858      the last entry pushed), but a symbol could have multiple kinds in one CU.
20859      To keep things simple we don't worry about the duplication here and
20860      sort and uniqufy the list after we've processed all symbols.  */
20861   VEC_safe_push (offset_type, (*slot)->cu_indices, cu_index_and_attrs);
20862 }
20863
20864 /* qsort helper routine for uniquify_cu_indices.  */
20865
20866 static int
20867 offset_type_compare (const void *ap, const void *bp)
20868 {
20869   offset_type a = *(offset_type *) ap;
20870   offset_type b = *(offset_type *) bp;
20871
20872   return (a > b) - (b > a);
20873 }
20874
20875 /* Sort and remove duplicates of all symbols' cu_indices lists.  */
20876
20877 static void
20878 uniquify_cu_indices (struct mapped_symtab *symtab)
20879 {
20880   int i;
20881
20882   for (i = 0; i < symtab->size; ++i)
20883     {
20884       struct symtab_index_entry *entry = symtab->data[i];
20885
20886       if (entry
20887           && entry->cu_indices != NULL)
20888         {
20889           unsigned int next_to_insert, next_to_check;
20890           offset_type last_value;
20891
20892           qsort (VEC_address (offset_type, entry->cu_indices),
20893                  VEC_length (offset_type, entry->cu_indices),
20894                  sizeof (offset_type), offset_type_compare);
20895
20896           last_value = VEC_index (offset_type, entry->cu_indices, 0);
20897           next_to_insert = 1;
20898           for (next_to_check = 1;
20899                next_to_check < VEC_length (offset_type, entry->cu_indices);
20900                ++next_to_check)
20901             {
20902               if (VEC_index (offset_type, entry->cu_indices, next_to_check)
20903                   != last_value)
20904                 {
20905                   last_value = VEC_index (offset_type, entry->cu_indices,
20906                                           next_to_check);
20907                   VEC_replace (offset_type, entry->cu_indices, next_to_insert,
20908                                last_value);
20909                   ++next_to_insert;
20910                 }
20911             }
20912           VEC_truncate (offset_type, entry->cu_indices, next_to_insert);
20913         }
20914     }
20915 }
20916
20917 /* Add a vector of indices to the constant pool.  */
20918
20919 static offset_type
20920 add_indices_to_cpool (htab_t symbol_hash_table, struct obstack *cpool,
20921                       struct symtab_index_entry *entry)
20922 {
20923   void **slot;
20924
20925   slot = htab_find_slot (symbol_hash_table, entry, INSERT);
20926   if (!*slot)
20927     {
20928       offset_type len = VEC_length (offset_type, entry->cu_indices);
20929       offset_type val = MAYBE_SWAP (len);
20930       offset_type iter;
20931       int i;
20932
20933       *slot = entry;
20934       entry->index_offset = obstack_object_size (cpool);
20935
20936       obstack_grow (cpool, &val, sizeof (val));
20937       for (i = 0;
20938            VEC_iterate (offset_type, entry->cu_indices, i, iter);
20939            ++i)
20940         {
20941           val = MAYBE_SWAP (iter);
20942           obstack_grow (cpool, &val, sizeof (val));
20943         }
20944     }
20945   else
20946     {
20947       struct symtab_index_entry *old_entry = *slot;
20948       entry->index_offset = old_entry->index_offset;
20949       entry = old_entry;
20950     }
20951   return entry->index_offset;
20952 }
20953
20954 /* Write the mapped hash table SYMTAB to the obstack OUTPUT, with
20955    constant pool entries going into the obstack CPOOL.  */
20956
20957 static void
20958 write_hash_table (struct mapped_symtab *symtab,
20959                   struct obstack *output, struct obstack *cpool)
20960 {
20961   offset_type i;
20962   htab_t symbol_hash_table;
20963   htab_t str_table;
20964
20965   symbol_hash_table = create_symbol_hash_table ();
20966   str_table = create_strtab ();
20967
20968   /* We add all the index vectors to the constant pool first, to
20969      ensure alignment is ok.  */
20970   for (i = 0; i < symtab->size; ++i)
20971     {
20972       if (symtab->data[i])
20973         add_indices_to_cpool (symbol_hash_table, cpool, symtab->data[i]);
20974     }
20975
20976   /* Now write out the hash table.  */
20977   for (i = 0; i < symtab->size; ++i)
20978     {
20979       offset_type str_off, vec_off;
20980
20981       if (symtab->data[i])
20982         {
20983           str_off = add_string (str_table, cpool, symtab->data[i]->name);
20984           vec_off = symtab->data[i]->index_offset;
20985         }
20986       else
20987         {
20988           /* While 0 is a valid constant pool index, it is not valid
20989              to have 0 for both offsets.  */
20990           str_off = 0;
20991           vec_off = 0;
20992         }
20993
20994       str_off = MAYBE_SWAP (str_off);
20995       vec_off = MAYBE_SWAP (vec_off);
20996
20997       obstack_grow (output, &str_off, sizeof (str_off));
20998       obstack_grow (output, &vec_off, sizeof (vec_off));
20999     }
21000
21001   htab_delete (str_table);
21002   htab_delete (symbol_hash_table);
21003 }
21004
21005 /* Struct to map psymtab to CU index in the index file.  */
21006 struct psymtab_cu_index_map
21007 {
21008   struct partial_symtab *psymtab;
21009   unsigned int cu_index;
21010 };
21011
21012 static hashval_t
21013 hash_psymtab_cu_index (const void *item)
21014 {
21015   const struct psymtab_cu_index_map *map = item;
21016
21017   return htab_hash_pointer (map->psymtab);
21018 }
21019
21020 static int
21021 eq_psymtab_cu_index (const void *item_lhs, const void *item_rhs)
21022 {
21023   const struct psymtab_cu_index_map *lhs = item_lhs;
21024   const struct psymtab_cu_index_map *rhs = item_rhs;
21025
21026   return lhs->psymtab == rhs->psymtab;
21027 }
21028
21029 /* Helper struct for building the address table.  */
21030 struct addrmap_index_data
21031 {
21032   struct objfile *objfile;
21033   struct obstack *addr_obstack;
21034   htab_t cu_index_htab;
21035
21036   /* Non-zero if the previous_* fields are valid.
21037      We can't write an entry until we see the next entry (since it is only then
21038      that we know the end of the entry).  */
21039   int previous_valid;
21040   /* Index of the CU in the table of all CUs in the index file.  */
21041   unsigned int previous_cu_index;
21042   /* Start address of the CU.  */
21043   CORE_ADDR previous_cu_start;
21044 };
21045
21046 /* Write an address entry to OBSTACK.  */
21047
21048 static void
21049 add_address_entry (struct objfile *objfile, struct obstack *obstack,
21050                    CORE_ADDR start, CORE_ADDR end, unsigned int cu_index)
21051 {
21052   offset_type cu_index_to_write;
21053   gdb_byte addr[8];
21054   CORE_ADDR baseaddr;
21055
21056   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
21057
21058   store_unsigned_integer (addr, 8, BFD_ENDIAN_LITTLE, start - baseaddr);
21059   obstack_grow (obstack, addr, 8);
21060   store_unsigned_integer (addr, 8, BFD_ENDIAN_LITTLE, end - baseaddr);
21061   obstack_grow (obstack, addr, 8);
21062   cu_index_to_write = MAYBE_SWAP (cu_index);
21063   obstack_grow (obstack, &cu_index_to_write, sizeof (offset_type));
21064 }
21065
21066 /* Worker function for traversing an addrmap to build the address table.  */
21067
21068 static int
21069 add_address_entry_worker (void *datap, CORE_ADDR start_addr, void *obj)
21070 {
21071   struct addrmap_index_data *data = datap;
21072   struct partial_symtab *pst = obj;
21073
21074   if (data->previous_valid)
21075     add_address_entry (data->objfile, data->addr_obstack,
21076                        data->previous_cu_start, start_addr,
21077                        data->previous_cu_index);
21078
21079   data->previous_cu_start = start_addr;
21080   if (pst != NULL)
21081     {
21082       struct psymtab_cu_index_map find_map, *map;
21083       find_map.psymtab = pst;
21084       map = htab_find (data->cu_index_htab, &find_map);
21085       gdb_assert (map != NULL);
21086       data->previous_cu_index = map->cu_index;
21087       data->previous_valid = 1;
21088     }
21089   else
21090       data->previous_valid = 0;
21091
21092   return 0;
21093 }
21094
21095 /* Write OBJFILE's address map to OBSTACK.
21096    CU_INDEX_HTAB is used to map addrmap entries to their CU indices
21097    in the index file.  */
21098
21099 static void
21100 write_address_map (struct objfile *objfile, struct obstack *obstack,
21101                    htab_t cu_index_htab)
21102 {
21103   struct addrmap_index_data addrmap_index_data;
21104
21105   /* When writing the address table, we have to cope with the fact that
21106      the addrmap iterator only provides the start of a region; we have to
21107      wait until the next invocation to get the start of the next region.  */
21108
21109   addrmap_index_data.objfile = objfile;
21110   addrmap_index_data.addr_obstack = obstack;
21111   addrmap_index_data.cu_index_htab = cu_index_htab;
21112   addrmap_index_data.previous_valid = 0;
21113
21114   addrmap_foreach (objfile->psymtabs_addrmap, add_address_entry_worker,
21115                    &addrmap_index_data);
21116
21117   /* It's highly unlikely the last entry (end address = 0xff...ff)
21118      is valid, but we should still handle it.
21119      The end address is recorded as the start of the next region, but that
21120      doesn't work here.  To cope we pass 0xff...ff, this is a rare situation
21121      anyway.  */
21122   if (addrmap_index_data.previous_valid)
21123     add_address_entry (objfile, obstack,
21124                        addrmap_index_data.previous_cu_start, (CORE_ADDR) -1,
21125                        addrmap_index_data.previous_cu_index);
21126 }
21127
21128 /* Return the symbol kind of PSYM.  */
21129
21130 static gdb_index_symbol_kind
21131 symbol_kind (struct partial_symbol *psym)
21132 {
21133   domain_enum domain = PSYMBOL_DOMAIN (psym);
21134   enum address_class aclass = PSYMBOL_CLASS (psym);
21135
21136   switch (domain)
21137     {
21138     case VAR_DOMAIN:
21139       switch (aclass)
21140         {
21141         case LOC_BLOCK:
21142           return GDB_INDEX_SYMBOL_KIND_FUNCTION;
21143         case LOC_TYPEDEF:
21144           return GDB_INDEX_SYMBOL_KIND_TYPE;
21145         case LOC_COMPUTED:
21146         case LOC_CONST_BYTES:
21147         case LOC_OPTIMIZED_OUT:
21148         case LOC_STATIC:
21149           return GDB_INDEX_SYMBOL_KIND_VARIABLE;
21150         case LOC_CONST:
21151           /* Note: It's currently impossible to recognize psyms as enum values
21152              short of reading the type info.  For now punt.  */
21153           return GDB_INDEX_SYMBOL_KIND_VARIABLE;
21154         default:
21155           /* There are other LOC_FOO values that one might want to classify
21156              as variables, but dwarf2read.c doesn't currently use them.  */
21157           return GDB_INDEX_SYMBOL_KIND_OTHER;
21158         }
21159     case STRUCT_DOMAIN:
21160       return GDB_INDEX_SYMBOL_KIND_TYPE;
21161     default:
21162       return GDB_INDEX_SYMBOL_KIND_OTHER;
21163     }
21164 }
21165
21166 /* Add a list of partial symbols to SYMTAB.  */
21167
21168 static void
21169 write_psymbols (struct mapped_symtab *symtab,
21170                 htab_t psyms_seen,
21171                 struct partial_symbol **psymp,
21172                 int count,
21173                 offset_type cu_index,
21174                 int is_static)
21175 {
21176   for (; count-- > 0; ++psymp)
21177     {
21178       struct partial_symbol *psym = *psymp;
21179       void **slot;
21180
21181       if (SYMBOL_LANGUAGE (psym) == language_ada)
21182         error (_("Ada is not currently supported by the index"));
21183
21184       /* Only add a given psymbol once.  */
21185       slot = htab_find_slot (psyms_seen, psym, INSERT);
21186       if (!*slot)
21187         {
21188           gdb_index_symbol_kind kind = symbol_kind (psym);
21189
21190           *slot = psym;
21191           add_index_entry (symtab, SYMBOL_SEARCH_NAME (psym),
21192                            is_static, kind, cu_index);
21193         }
21194     }
21195 }
21196
21197 /* Write the contents of an ("unfinished") obstack to FILE.  Throw an
21198    exception if there is an error.  */
21199
21200 static void
21201 write_obstack (FILE *file, struct obstack *obstack)
21202 {
21203   if (fwrite (obstack_base (obstack), 1, obstack_object_size (obstack),
21204               file)
21205       != obstack_object_size (obstack))
21206     error (_("couldn't data write to file"));
21207 }
21208
21209 /* Unlink a file if the argument is not NULL.  */
21210
21211 static void
21212 unlink_if_set (void *p)
21213 {
21214   char **filename = p;
21215   if (*filename)
21216     unlink (*filename);
21217 }
21218
21219 /* A helper struct used when iterating over debug_types.  */
21220 struct signatured_type_index_data
21221 {
21222   struct objfile *objfile;
21223   struct mapped_symtab *symtab;
21224   struct obstack *types_list;
21225   htab_t psyms_seen;
21226   int cu_index;
21227 };
21228
21229 /* A helper function that writes a single signatured_type to an
21230    obstack.  */
21231
21232 static int
21233 write_one_signatured_type (void **slot, void *d)
21234 {
21235   struct signatured_type_index_data *info = d;
21236   struct signatured_type *entry = (struct signatured_type *) *slot;
21237   struct partial_symtab *psymtab = entry->per_cu.v.psymtab;
21238   gdb_byte val[8];
21239
21240   write_psymbols (info->symtab,
21241                   info->psyms_seen,
21242                   info->objfile->global_psymbols.list
21243                   + psymtab->globals_offset,
21244                   psymtab->n_global_syms, info->cu_index,
21245                   0);
21246   write_psymbols (info->symtab,
21247                   info->psyms_seen,
21248                   info->objfile->static_psymbols.list
21249                   + psymtab->statics_offset,
21250                   psymtab->n_static_syms, info->cu_index,
21251                   1);
21252
21253   store_unsigned_integer (val, 8, BFD_ENDIAN_LITTLE,
21254                           entry->per_cu.offset.sect_off);
21255   obstack_grow (info->types_list, val, 8);
21256   store_unsigned_integer (val, 8, BFD_ENDIAN_LITTLE,
21257                           entry->type_offset_in_tu.cu_off);
21258   obstack_grow (info->types_list, val, 8);
21259   store_unsigned_integer (val, 8, BFD_ENDIAN_LITTLE, entry->signature);
21260   obstack_grow (info->types_list, val, 8);
21261
21262   ++info->cu_index;
21263
21264   return 1;
21265 }
21266
21267 /* Recurse into all "included" dependencies and write their symbols as
21268    if they appeared in this psymtab.  */
21269
21270 static void
21271 recursively_write_psymbols (struct objfile *objfile,
21272                             struct partial_symtab *psymtab,
21273                             struct mapped_symtab *symtab,
21274                             htab_t psyms_seen,
21275                             offset_type cu_index)
21276 {
21277   int i;
21278
21279   for (i = 0; i < psymtab->number_of_dependencies; ++i)
21280     if (psymtab->dependencies[i]->user != NULL)
21281       recursively_write_psymbols (objfile, psymtab->dependencies[i],
21282                                   symtab, psyms_seen, cu_index);
21283
21284   write_psymbols (symtab,
21285                   psyms_seen,
21286                   objfile->global_psymbols.list + psymtab->globals_offset,
21287                   psymtab->n_global_syms, cu_index,
21288                   0);
21289   write_psymbols (symtab,
21290                   psyms_seen,
21291                   objfile->static_psymbols.list + psymtab->statics_offset,
21292                   psymtab->n_static_syms, cu_index,
21293                   1);
21294 }
21295
21296 /* Create an index file for OBJFILE in the directory DIR.  */
21297
21298 static void
21299 write_psymtabs_to_index (struct objfile *objfile, const char *dir)
21300 {
21301   struct cleanup *cleanup;
21302   char *filename, *cleanup_filename;
21303   struct obstack contents, addr_obstack, constant_pool, symtab_obstack;
21304   struct obstack cu_list, types_cu_list;
21305   int i;
21306   FILE *out_file;
21307   struct mapped_symtab *symtab;
21308   offset_type val, size_of_contents, total_len;
21309   struct stat st;
21310   htab_t psyms_seen;
21311   htab_t cu_index_htab;
21312   struct psymtab_cu_index_map *psymtab_cu_index_map;
21313
21314   if (!objfile->psymtabs || !objfile->psymtabs_addrmap)
21315     return;
21316
21317   if (dwarf2_per_objfile->using_index)
21318     error (_("Cannot use an index to create the index"));
21319
21320   if (VEC_length (dwarf2_section_info_def, dwarf2_per_objfile->types) > 1)
21321     error (_("Cannot make an index when the file has multiple .debug_types sections"));
21322
21323   if (stat (objfile->name, &st) < 0)
21324     perror_with_name (objfile->name);
21325
21326   filename = concat (dir, SLASH_STRING, lbasename (objfile->name),
21327                      INDEX_SUFFIX, (char *) NULL);
21328   cleanup = make_cleanup (xfree, filename);
21329
21330   out_file = gdb_fopen_cloexec (filename, "wb");
21331   if (!out_file)
21332     error (_("Can't open `%s' for writing"), filename);
21333
21334   cleanup_filename = filename;
21335   make_cleanup (unlink_if_set, &cleanup_filename);
21336
21337   symtab = create_mapped_symtab ();
21338   make_cleanup (cleanup_mapped_symtab, symtab);
21339
21340   obstack_init (&addr_obstack);
21341   make_cleanup_obstack_free (&addr_obstack);
21342
21343   obstack_init (&cu_list);
21344   make_cleanup_obstack_free (&cu_list);
21345
21346   obstack_init (&types_cu_list);
21347   make_cleanup_obstack_free (&types_cu_list);
21348
21349   psyms_seen = htab_create_alloc (100, htab_hash_pointer, htab_eq_pointer,
21350                                   NULL, xcalloc, xfree);
21351   make_cleanup_htab_delete (psyms_seen);
21352
21353   /* While we're scanning CU's create a table that maps a psymtab pointer
21354      (which is what addrmap records) to its index (which is what is recorded
21355      in the index file).  This will later be needed to write the address
21356      table.  */
21357   cu_index_htab = htab_create_alloc (100,
21358                                      hash_psymtab_cu_index,
21359                                      eq_psymtab_cu_index,
21360                                      NULL, xcalloc, xfree);
21361   make_cleanup_htab_delete (cu_index_htab);
21362   psymtab_cu_index_map = (struct psymtab_cu_index_map *)
21363     xmalloc (sizeof (struct psymtab_cu_index_map)
21364              * dwarf2_per_objfile->n_comp_units);
21365   make_cleanup (xfree, psymtab_cu_index_map);
21366
21367   /* The CU list is already sorted, so we don't need to do additional
21368      work here.  Also, the debug_types entries do not appear in
21369      all_comp_units, but only in their own hash table.  */
21370   for (i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
21371     {
21372       struct dwarf2_per_cu_data *per_cu
21373         = dwarf2_per_objfile->all_comp_units[i];
21374       struct partial_symtab *psymtab = per_cu->v.psymtab;
21375       gdb_byte val[8];
21376       struct psymtab_cu_index_map *map;
21377       void **slot;
21378
21379       /* CU of a shared file from 'dwz -m' may be unused by this main file.
21380          It may be referenced from a local scope but in such case it does not
21381          need to be present in .gdb_index.  */
21382       if (psymtab == NULL)
21383         continue;
21384
21385       if (psymtab->user == NULL)
21386         recursively_write_psymbols (objfile, psymtab, symtab, psyms_seen, i);
21387
21388       map = &psymtab_cu_index_map[i];
21389       map->psymtab = psymtab;
21390       map->cu_index = i;
21391       slot = htab_find_slot (cu_index_htab, map, INSERT);
21392       gdb_assert (slot != NULL);
21393       gdb_assert (*slot == NULL);
21394       *slot = map;
21395
21396       store_unsigned_integer (val, 8, BFD_ENDIAN_LITTLE,
21397                               per_cu->offset.sect_off);
21398       obstack_grow (&cu_list, val, 8);
21399       store_unsigned_integer (val, 8, BFD_ENDIAN_LITTLE, per_cu->length);
21400       obstack_grow (&cu_list, val, 8);
21401     }
21402
21403   /* Dump the address map.  */
21404   write_address_map (objfile, &addr_obstack, cu_index_htab);
21405
21406   /* Write out the .debug_type entries, if any.  */
21407   if (dwarf2_per_objfile->signatured_types)
21408     {
21409       struct signatured_type_index_data sig_data;
21410
21411       sig_data.objfile = objfile;
21412       sig_data.symtab = symtab;
21413       sig_data.types_list = &types_cu_list;
21414       sig_data.psyms_seen = psyms_seen;
21415       sig_data.cu_index = dwarf2_per_objfile->n_comp_units;
21416       htab_traverse_noresize (dwarf2_per_objfile->signatured_types,
21417                               write_one_signatured_type, &sig_data);
21418     }
21419
21420   /* Now that we've processed all symbols we can shrink their cu_indices
21421      lists.  */
21422   uniquify_cu_indices (symtab);
21423
21424   obstack_init (&constant_pool);
21425   make_cleanup_obstack_free (&constant_pool);
21426   obstack_init (&symtab_obstack);
21427   make_cleanup_obstack_free (&symtab_obstack);
21428   write_hash_table (symtab, &symtab_obstack, &constant_pool);
21429
21430   obstack_init (&contents);
21431   make_cleanup_obstack_free (&contents);
21432   size_of_contents = 6 * sizeof (offset_type);
21433   total_len = size_of_contents;
21434
21435   /* The version number.  */
21436   val = MAYBE_SWAP (8);
21437   obstack_grow (&contents, &val, sizeof (val));
21438
21439   /* The offset of the CU list from the start of the file.  */
21440   val = MAYBE_SWAP (total_len);
21441   obstack_grow (&contents, &val, sizeof (val));
21442   total_len += obstack_object_size (&cu_list);
21443
21444   /* The offset of the types CU list from the start of the file.  */
21445   val = MAYBE_SWAP (total_len);
21446   obstack_grow (&contents, &val, sizeof (val));
21447   total_len += obstack_object_size (&types_cu_list);
21448
21449   /* The offset of the address table from the start of the file.  */
21450   val = MAYBE_SWAP (total_len);
21451   obstack_grow (&contents, &val, sizeof (val));
21452   total_len += obstack_object_size (&addr_obstack);
21453
21454   /* The offset of the symbol table from the start of the file.  */
21455   val = MAYBE_SWAP (total_len);
21456   obstack_grow (&contents, &val, sizeof (val));
21457   total_len += obstack_object_size (&symtab_obstack);
21458
21459   /* The offset of the constant pool from the start of the file.  */
21460   val = MAYBE_SWAP (total_len);
21461   obstack_grow (&contents, &val, sizeof (val));
21462   total_len += obstack_object_size (&constant_pool);
21463
21464   gdb_assert (obstack_object_size (&contents) == size_of_contents);
21465
21466   write_obstack (out_file, &contents);
21467   write_obstack (out_file, &cu_list);
21468   write_obstack (out_file, &types_cu_list);
21469   write_obstack (out_file, &addr_obstack);
21470   write_obstack (out_file, &symtab_obstack);
21471   write_obstack (out_file, &constant_pool);
21472
21473   fclose (out_file);
21474
21475   /* We want to keep the file, so we set cleanup_filename to NULL
21476      here.  See unlink_if_set.  */
21477   cleanup_filename = NULL;
21478
21479   do_cleanups (cleanup);
21480 }
21481
21482 /* Implementation of the `save gdb-index' command.
21483    
21484    Note that the file format used by this command is documented in the
21485    GDB manual.  Any changes here must be documented there.  */
21486
21487 static void
21488 save_gdb_index_command (char *arg, int from_tty)
21489 {
21490   struct objfile *objfile;
21491
21492   if (!arg || !*arg)
21493     error (_("usage: save gdb-index DIRECTORY"));
21494
21495   ALL_OBJFILES (objfile)
21496   {
21497     struct stat st;
21498
21499     /* If the objfile does not correspond to an actual file, skip it.  */
21500     if (stat (objfile->name, &st) < 0)
21501       continue;
21502
21503     dwarf2_per_objfile = objfile_data (objfile, dwarf2_objfile_data_key);
21504     if (dwarf2_per_objfile)
21505       {
21506         volatile struct gdb_exception except;
21507
21508         TRY_CATCH (except, RETURN_MASK_ERROR)
21509           {
21510             write_psymtabs_to_index (objfile, arg);
21511           }
21512         if (except.reason < 0)
21513           exception_fprintf (gdb_stderr, except,
21514                              _("Error while writing index for `%s': "),
21515                              objfile->name);
21516       }
21517   }
21518 }
21519
21520 \f
21521
21522 int dwarf2_always_disassemble;
21523
21524 static void
21525 show_dwarf2_always_disassemble (struct ui_file *file, int from_tty,
21526                                 struct cmd_list_element *c, const char *value)
21527 {
21528   fprintf_filtered (file,
21529                     _("Whether to always disassemble "
21530                       "DWARF expressions is %s.\n"),
21531                     value);
21532 }
21533
21534 static void
21535 show_check_physname (struct ui_file *file, int from_tty,
21536                      struct cmd_list_element *c, const char *value)
21537 {
21538   fprintf_filtered (file,
21539                     _("Whether to check \"physname\" is %s.\n"),
21540                     value);
21541 }
21542
21543 void _initialize_dwarf2_read (void);
21544
21545 void
21546 _initialize_dwarf2_read (void)
21547 {
21548   struct cmd_list_element *c;
21549
21550   dwarf2_objfile_data_key
21551     = register_objfile_data_with_cleanup (NULL, dwarf2_per_objfile_free);
21552
21553   add_prefix_cmd ("dwarf2", class_maintenance, set_dwarf2_cmd, _("\
21554 Set DWARF 2 specific variables.\n\
21555 Configure DWARF 2 variables such as the cache size"),
21556                   &set_dwarf2_cmdlist, "maintenance set dwarf2 ",
21557                   0/*allow-unknown*/, &maintenance_set_cmdlist);
21558
21559   add_prefix_cmd ("dwarf2", class_maintenance, show_dwarf2_cmd, _("\
21560 Show DWARF 2 specific variables\n\
21561 Show DWARF 2 variables such as the cache size"),
21562                   &show_dwarf2_cmdlist, "maintenance show dwarf2 ",
21563                   0/*allow-unknown*/, &maintenance_show_cmdlist);
21564
21565   add_setshow_zinteger_cmd ("max-cache-age", class_obscure,
21566                             &dwarf2_max_cache_age, _("\
21567 Set the upper bound on the age of cached dwarf2 compilation units."), _("\
21568 Show the upper bound on the age of cached dwarf2 compilation units."), _("\
21569 A higher limit means that cached compilation units will be stored\n\
21570 in memory longer, and more total memory will be used.  Zero disables\n\
21571 caching, which can slow down startup."),
21572                             NULL,
21573                             show_dwarf2_max_cache_age,
21574                             &set_dwarf2_cmdlist,
21575                             &show_dwarf2_cmdlist);
21576
21577   add_setshow_boolean_cmd ("always-disassemble", class_obscure,
21578                            &dwarf2_always_disassemble, _("\
21579 Set whether `info address' always disassembles DWARF expressions."), _("\
21580 Show whether `info address' always disassembles DWARF expressions."), _("\
21581 When enabled, DWARF expressions are always printed in an assembly-like\n\
21582 syntax.  When disabled, expressions will be printed in a more\n\
21583 conversational style, when possible."),
21584                            NULL,
21585                            show_dwarf2_always_disassemble,
21586                            &set_dwarf2_cmdlist,
21587                            &show_dwarf2_cmdlist);
21588
21589   add_setshow_boolean_cmd ("dwarf2-read", no_class, &dwarf2_read_debug, _("\
21590 Set debugging of the dwarf2 reader."), _("\
21591 Show debugging of the dwarf2 reader."), _("\
21592 When enabled, debugging messages are printed during dwarf2 reading\n\
21593 and symtab expansion."),
21594                             NULL,
21595                             NULL,
21596                             &setdebuglist, &showdebuglist);
21597
21598   add_setshow_zuinteger_cmd ("dwarf2-die", no_class, &dwarf2_die_debug, _("\
21599 Set debugging of the dwarf2 DIE reader."), _("\
21600 Show debugging of the dwarf2 DIE reader."), _("\
21601 When enabled (non-zero), DIEs are dumped after they are read in.\n\
21602 The value is the maximum depth to print."),
21603                              NULL,
21604                              NULL,
21605                              &setdebuglist, &showdebuglist);
21606
21607   add_setshow_boolean_cmd ("check-physname", no_class, &check_physname, _("\
21608 Set cross-checking of \"physname\" code against demangler."), _("\
21609 Show cross-checking of \"physname\" code against demangler."), _("\
21610 When enabled, GDB's internal \"physname\" code is checked against\n\
21611 the demangler."),
21612                            NULL, show_check_physname,
21613                            &setdebuglist, &showdebuglist);
21614
21615   add_setshow_boolean_cmd ("use-deprecated-index-sections",
21616                            no_class, &use_deprecated_index_sections, _("\
21617 Set whether to use deprecated gdb_index sections."), _("\
21618 Show whether to use deprecated gdb_index sections."), _("\
21619 When enabled, deprecated .gdb_index sections are used anyway.\n\
21620 Normally they are ignored either because of a missing feature or\n\
21621 performance issue.\n\
21622 Warning: This option must be enabled before gdb reads the file."),
21623                            NULL,
21624                            NULL,
21625                            &setlist, &showlist);
21626
21627   c = add_cmd ("gdb-index", class_files, save_gdb_index_command,
21628                _("\
21629 Save a gdb-index file.\n\
21630 Usage: save gdb-index DIRECTORY"),
21631                &save_cmdlist);
21632   set_cmd_completer (c, filename_completer);
21633
21634   dwarf2_locexpr_index = register_symbol_computed_impl (LOC_COMPUTED,
21635                                                         &dwarf2_locexpr_funcs);
21636   dwarf2_loclist_index = register_symbol_computed_impl (LOC_COMPUTED,
21637                                                         &dwarf2_loclist_funcs);
21638
21639   dwarf2_locexpr_block_index = register_symbol_block_impl (LOC_BLOCK,
21640                                         &dwarf2_block_frame_base_locexpr_funcs);
21641   dwarf2_loclist_block_index = register_symbol_block_impl (LOC_BLOCK,
21642                                         &dwarf2_block_frame_base_loclist_funcs);
21643 }