fix init_cutu_and_read_dies
[external/binutils.git] / gdb / dwarf2read.c
1 /* DWARF 2 debugging format support for GDB.
2
3    Copyright (C) 1994-2013 Free Software Foundation, Inc.
4
5    Adapted by Gary Funck (gary@intrepid.com), Intrepid Technology,
6    Inc.  with support from Florida State University (under contract
7    with the Ada Joint Program Office), and Silicon Graphics, Inc.
8    Initial contribution by Brent Benson, Harris Computer Systems, Inc.,
9    based on Fred Fish's (Cygnus Support) implementation of DWARF 1
10    support.
11
12    This file is part of GDB.
13
14    This program is free software; you can redistribute it and/or modify
15    it under the terms of the GNU General Public License as published by
16    the Free Software Foundation; either version 3 of the License, or
17    (at your option) any later version.
18
19    This program is distributed in the hope that it will be useful,
20    but WITHOUT ANY WARRANTY; without even the implied warranty of
21    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
22    GNU General Public License for more details.
23
24    You should have received a copy of the GNU General Public License
25    along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
26
27 /* FIXME: Various die-reading functions need to be more careful with
28    reading off the end of the section.
29    E.g., load_partial_dies, read_partial_die.  */
30
31 #include "defs.h"
32 #include "bfd.h"
33 #include "elf-bfd.h"
34 #include "symtab.h"
35 #include "gdbtypes.h"
36 #include "objfiles.h"
37 #include "dwarf2.h"
38 #include "buildsym.h"
39 #include "demangle.h"
40 #include "gdb-demangle.h"
41 #include "expression.h"
42 #include "filenames.h"  /* for DOSish file names */
43 #include "macrotab.h"
44 #include "language.h"
45 #include "complaints.h"
46 #include "bcache.h"
47 #include "dwarf2expr.h"
48 #include "dwarf2loc.h"
49 #include "cp-support.h"
50 #include "hashtab.h"
51 #include "command.h"
52 #include "gdbcmd.h"
53 #include "block.h"
54 #include "addrmap.h"
55 #include "typeprint.h"
56 #include "jv-lang.h"
57 #include "psympriv.h"
58 #include "exceptions.h"
59 #include "gdb_stat.h"
60 #include "completer.h"
61 #include "vec.h"
62 #include "c-lang.h"
63 #include "go-lang.h"
64 #include "valprint.h"
65 #include "gdbcore.h" /* for gnutarget */
66 #include "gdb/gdb-index.h"
67 #include <ctype.h>
68 #include "gdb_bfd.h"
69 #include "f-lang.h"
70 #include "source.h"
71 #include "filestuff.h"
72
73 #include <fcntl.h>
74 #include "gdb_string.h"
75 #include "gdb_assert.h"
76 #include <sys/types.h>
77
78 typedef struct symbol *symbolp;
79 DEF_VEC_P (symbolp);
80
81 /* When non-zero, print basic high level tracing messages.
82    This is in contrast to the low level DIE reading of dwarf2_die_debug.  */
83 static int dwarf2_read_debug = 0;
84
85 /* When non-zero, dump DIEs after they are read in.  */
86 static unsigned int dwarf2_die_debug = 0;
87
88 /* When non-zero, cross-check physname against demangler.  */
89 static int check_physname = 0;
90
91 /* When non-zero, do not reject deprecated .gdb_index sections.  */
92 static int use_deprecated_index_sections = 0;
93
94 static const struct objfile_data *dwarf2_objfile_data_key;
95
96 /* The "aclass" indices for various kinds of computed DWARF symbols.  */
97
98 static int dwarf2_locexpr_index;
99 static int dwarf2_loclist_index;
100 static int dwarf2_locexpr_block_index;
101 static int dwarf2_loclist_block_index;
102
103 struct dwarf2_section_info
104 {
105   asection *asection;
106   const gdb_byte *buffer;
107   bfd_size_type size;
108   /* True if we have tried to read this section.  */
109   int readin;
110 };
111
112 typedef struct dwarf2_section_info dwarf2_section_info_def;
113 DEF_VEC_O (dwarf2_section_info_def);
114
115 /* All offsets in the index are of this type.  It must be
116    architecture-independent.  */
117 typedef uint32_t offset_type;
118
119 DEF_VEC_I (offset_type);
120
121 /* Ensure only legit values are used.  */
122 #define DW2_GDB_INDEX_SYMBOL_STATIC_SET_VALUE(cu_index, value) \
123   do { \
124     gdb_assert ((unsigned int) (value) <= 1); \
125     GDB_INDEX_SYMBOL_STATIC_SET_VALUE((cu_index), (value)); \
126   } while (0)
127
128 /* Ensure only legit values are used.  */
129 #define DW2_GDB_INDEX_SYMBOL_KIND_SET_VALUE(cu_index, value) \
130   do { \
131     gdb_assert ((value) >= GDB_INDEX_SYMBOL_KIND_TYPE \
132                 && (value) <= GDB_INDEX_SYMBOL_KIND_OTHER); \
133     GDB_INDEX_SYMBOL_KIND_SET_VALUE((cu_index), (value)); \
134   } while (0)
135
136 /* Ensure we don't use more than the alloted nuber of bits for the CU.  */
137 #define DW2_GDB_INDEX_CU_SET_VALUE(cu_index, value) \
138   do { \
139     gdb_assert (((value) & ~GDB_INDEX_CU_MASK) == 0); \
140     GDB_INDEX_CU_SET_VALUE((cu_index), (value)); \
141   } while (0)
142
143 /* A description of the mapped index.  The file format is described in
144    a comment by the code that writes the index.  */
145 struct mapped_index
146 {
147   /* Index data format version.  */
148   int version;
149
150   /* The total length of the buffer.  */
151   off_t total_size;
152
153   /* A pointer to the address table data.  */
154   const gdb_byte *address_table;
155
156   /* Size of the address table data in bytes.  */
157   offset_type address_table_size;
158
159   /* The symbol table, implemented as a hash table.  */
160   const offset_type *symbol_table;
161
162   /* Size in slots, each slot is 2 offset_types.  */
163   offset_type symbol_table_slots;
164
165   /* A pointer to the constant pool.  */
166   const char *constant_pool;
167 };
168
169 typedef struct dwarf2_per_cu_data *dwarf2_per_cu_ptr;
170 DEF_VEC_P (dwarf2_per_cu_ptr);
171
172 /* Collection of data recorded per objfile.
173    This hangs off of dwarf2_objfile_data_key.  */
174
175 struct dwarf2_per_objfile
176 {
177   struct dwarf2_section_info info;
178   struct dwarf2_section_info abbrev;
179   struct dwarf2_section_info line;
180   struct dwarf2_section_info loc;
181   struct dwarf2_section_info macinfo;
182   struct dwarf2_section_info macro;
183   struct dwarf2_section_info str;
184   struct dwarf2_section_info ranges;
185   struct dwarf2_section_info addr;
186   struct dwarf2_section_info frame;
187   struct dwarf2_section_info eh_frame;
188   struct dwarf2_section_info gdb_index;
189
190   VEC (dwarf2_section_info_def) *types;
191
192   /* Back link.  */
193   struct objfile *objfile;
194
195   /* Table of all the compilation units.  This is used to locate
196      the target compilation unit of a particular reference.  */
197   struct dwarf2_per_cu_data **all_comp_units;
198
199   /* The number of compilation units in ALL_COMP_UNITS.  */
200   int n_comp_units;
201
202   /* The number of .debug_types-related CUs.  */
203   int n_type_units;
204
205   /* The .debug_types-related CUs (TUs).
206      This is stored in malloc space because we may realloc it.  */
207   struct signatured_type **all_type_units;
208
209   /* The number of entries in all_type_unit_groups.  */
210   int n_type_unit_groups;
211
212   /* Table of type unit groups.
213      This exists to make it easy to iterate over all CUs and TU groups.  */
214   struct type_unit_group **all_type_unit_groups;
215
216   /* Table of struct type_unit_group objects.
217      The hash key is the DW_AT_stmt_list value.  */
218   htab_t type_unit_groups;
219
220   /* A table mapping .debug_types signatures to its signatured_type entry.
221      This is NULL if the .debug_types section hasn't been read in yet.  */
222   htab_t signatured_types;
223
224   /* Type unit statistics, to see how well the scaling improvements
225      are doing.  */
226   struct tu_stats
227   {
228     int nr_uniq_abbrev_tables;
229     int nr_symtabs;
230     int nr_symtab_sharers;
231     int nr_stmt_less_type_units;
232   } tu_stats;
233
234   /* A chain of compilation units that are currently read in, so that
235      they can be freed later.  */
236   struct dwarf2_per_cu_data *read_in_chain;
237
238   /* A table mapping DW_AT_dwo_name values to struct dwo_file objects.
239      This is NULL if the table hasn't been allocated yet.  */
240   htab_t dwo_files;
241
242   /* Non-zero if we've check for whether there is a DWP file.  */
243   int dwp_checked;
244
245   /* The DWP file if there is one, or NULL.  */
246   struct dwp_file *dwp_file;
247
248   /* The shared '.dwz' file, if one exists.  This is used when the
249      original data was compressed using 'dwz -m'.  */
250   struct dwz_file *dwz_file;
251
252   /* A flag indicating wether this objfile has a section loaded at a
253      VMA of 0.  */
254   int has_section_at_zero;
255
256   /* True if we are using the mapped index,
257      or we are faking it for OBJF_READNOW's sake.  */
258   unsigned char using_index;
259
260   /* The mapped index, or NULL if .gdb_index is missing or not being used.  */
261   struct mapped_index *index_table;
262
263   /* When using index_table, this keeps track of all quick_file_names entries.
264      TUs typically share line table entries with a CU, so we maintain a
265      separate table of all line table entries to support the sharing.
266      Note that while there can be way more TUs than CUs, we've already
267      sorted all the TUs into "type unit groups", grouped by their
268      DW_AT_stmt_list value.  Therefore the only sharing done here is with a
269      CU and its associated TU group if there is one.  */
270   htab_t quick_file_names_table;
271
272   /* Set during partial symbol reading, to prevent queueing of full
273      symbols.  */
274   int reading_partial_symbols;
275
276   /* Table mapping type DIEs to their struct type *.
277      This is NULL if not allocated yet.
278      The mapping is done via (CU/TU + DIE offset) -> type.  */
279   htab_t die_type_hash;
280
281   /* The CUs we recently read.  */
282   VEC (dwarf2_per_cu_ptr) *just_read_cus;
283 };
284
285 static struct dwarf2_per_objfile *dwarf2_per_objfile;
286
287 /* Default names of the debugging sections.  */
288
289 /* Note that if the debugging section has been compressed, it might
290    have a name like .zdebug_info.  */
291
292 static const struct dwarf2_debug_sections dwarf2_elf_names =
293 {
294   { ".debug_info", ".zdebug_info" },
295   { ".debug_abbrev", ".zdebug_abbrev" },
296   { ".debug_line", ".zdebug_line" },
297   { ".debug_loc", ".zdebug_loc" },
298   { ".debug_macinfo", ".zdebug_macinfo" },
299   { ".debug_macro", ".zdebug_macro" },
300   { ".debug_str", ".zdebug_str" },
301   { ".debug_ranges", ".zdebug_ranges" },
302   { ".debug_types", ".zdebug_types" },
303   { ".debug_addr", ".zdebug_addr" },
304   { ".debug_frame", ".zdebug_frame" },
305   { ".eh_frame", NULL },
306   { ".gdb_index", ".zgdb_index" },
307   23
308 };
309
310 /* List of DWO/DWP sections.  */
311
312 static const struct dwop_section_names
313 {
314   struct dwarf2_section_names abbrev_dwo;
315   struct dwarf2_section_names info_dwo;
316   struct dwarf2_section_names line_dwo;
317   struct dwarf2_section_names loc_dwo;
318   struct dwarf2_section_names macinfo_dwo;
319   struct dwarf2_section_names macro_dwo;
320   struct dwarf2_section_names str_dwo;
321   struct dwarf2_section_names str_offsets_dwo;
322   struct dwarf2_section_names types_dwo;
323   struct dwarf2_section_names cu_index;
324   struct dwarf2_section_names tu_index;
325 }
326 dwop_section_names =
327 {
328   { ".debug_abbrev.dwo", ".zdebug_abbrev.dwo" },
329   { ".debug_info.dwo", ".zdebug_info.dwo" },
330   { ".debug_line.dwo", ".zdebug_line.dwo" },
331   { ".debug_loc.dwo", ".zdebug_loc.dwo" },
332   { ".debug_macinfo.dwo", ".zdebug_macinfo.dwo" },
333   { ".debug_macro.dwo", ".zdebug_macro.dwo" },
334   { ".debug_str.dwo", ".zdebug_str.dwo" },
335   { ".debug_str_offsets.dwo", ".zdebug_str_offsets.dwo" },
336   { ".debug_types.dwo", ".zdebug_types.dwo" },
337   { ".debug_cu_index", ".zdebug_cu_index" },
338   { ".debug_tu_index", ".zdebug_tu_index" },
339 };
340
341 /* local data types */
342
343 /* The data in a compilation unit header, after target2host
344    translation, looks like this.  */
345 struct comp_unit_head
346 {
347   unsigned int length;
348   short version;
349   unsigned char addr_size;
350   unsigned char signed_addr_p;
351   sect_offset abbrev_offset;
352
353   /* Size of file offsets; either 4 or 8.  */
354   unsigned int offset_size;
355
356   /* Size of the length field; either 4 or 12.  */
357   unsigned int initial_length_size;
358
359   /* Offset to the first byte of this compilation unit header in the
360      .debug_info section, for resolving relative reference dies.  */
361   sect_offset offset;
362
363   /* Offset to first die in this cu from the start of the cu.
364      This will be the first byte following the compilation unit header.  */
365   cu_offset first_die_offset;
366 };
367
368 /* Type used for delaying computation of method physnames.
369    See comments for compute_delayed_physnames.  */
370 struct delayed_method_info
371 {
372   /* The type to which the method is attached, i.e., its parent class.  */
373   struct type *type;
374
375   /* The index of the method in the type's function fieldlists.  */
376   int fnfield_index;
377
378   /* The index of the method in the fieldlist.  */
379   int index;
380
381   /* The name of the DIE.  */
382   const char *name;
383
384   /*  The DIE associated with this method.  */
385   struct die_info *die;
386 };
387
388 typedef struct delayed_method_info delayed_method_info;
389 DEF_VEC_O (delayed_method_info);
390
391 /* Internal state when decoding a particular compilation unit.  */
392 struct dwarf2_cu
393 {
394   /* The objfile containing this compilation unit.  */
395   struct objfile *objfile;
396
397   /* The header of the compilation unit.  */
398   struct comp_unit_head header;
399
400   /* Base address of this compilation unit.  */
401   CORE_ADDR base_address;
402
403   /* Non-zero if base_address has been set.  */
404   int base_known;
405
406   /* The language we are debugging.  */
407   enum language language;
408   const struct language_defn *language_defn;
409
410   const char *producer;
411
412   /* The generic symbol table building routines have separate lists for
413      file scope symbols and all all other scopes (local scopes).  So
414      we need to select the right one to pass to add_symbol_to_list().
415      We do it by keeping a pointer to the correct list in list_in_scope.
416
417      FIXME: The original dwarf code just treated the file scope as the
418      first local scope, and all other local scopes as nested local
419      scopes, and worked fine.  Check to see if we really need to
420      distinguish these in buildsym.c.  */
421   struct pending **list_in_scope;
422
423   /* The abbrev table for this CU.
424      Normally this points to the abbrev table in the objfile.
425      But if DWO_UNIT is non-NULL this is the abbrev table in the DWO file.  */
426   struct abbrev_table *abbrev_table;
427
428   /* Hash table holding all the loaded partial DIEs
429      with partial_die->offset.SECT_OFF as hash.  */
430   htab_t partial_dies;
431
432   /* Storage for things with the same lifetime as this read-in compilation
433      unit, including partial DIEs.  */
434   struct obstack comp_unit_obstack;
435
436   /* When multiple dwarf2_cu structures are living in memory, this field
437      chains them all together, so that they can be released efficiently.
438      We will probably also want a generation counter so that most-recently-used
439      compilation units are cached...  */
440   struct dwarf2_per_cu_data *read_in_chain;
441
442   /* 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   /* The section this CU/TU lives in.
562      If the DIE refers to a DWO file, this is always the original die,
563      not the DWO file.  */
564   struct dwarf2_section_info *section;
565
566   /* Set to non-NULL iff this CU is currently loaded.  When it gets freed out
567      of the CU cache it gets reset to NULL again.  */
568   struct dwarf2_cu *cu;
569
570   /* The corresponding objfile.
571      Normally we can get the objfile from dwarf2_per_objfile.
572      However we can enter this file with just a "per_cu" handle.  */
573   struct objfile *objfile;
574
575   /* When using partial symbol tables, the 'psymtab' field is active.
576      Otherwise the 'quick' field is active.  */
577   union
578   {
579     /* The partial symbol table associated with this compilation unit,
580        or NULL for unread partial units.  */
581     struct partial_symtab *psymtab;
582
583     /* Data needed by the "quick" functions.  */
584     struct dwarf2_per_cu_quick_data *quick;
585   } v;
586
587   /* The CUs we import using DW_TAG_imported_unit.  This is filled in
588      while reading psymtabs, used to compute the psymtab dependencies,
589      and then cleared.  Then it is filled in again while reading full
590      symbols, and only deleted when the objfile is destroyed.
591
592      This is also used to work around a difference between the way gold
593      generates .gdb_index version <=7 and the way gdb does.  Arguably this
594      is a gold bug.  For symbols coming from TUs, gold records in the index
595      the CU that includes the TU instead of the TU itself.  This breaks
596      dw2_lookup_symbol: It assumes that if the index says symbol X lives
597      in CU/TU Y, then one need only expand Y and a subsequent lookup in Y
598      will find X.  Alas TUs live in their own symtab, so after expanding CU Y
599      we need to look in TU Z to find X.  Fortunately, this is akin to
600      DW_TAG_imported_unit, so we just use the same mechanism: For
601      .gdb_index version <=7 this also records the TUs that the CU referred
602      to.  Concurrently with this change gdb was modified to emit version 8
603      indices so we only pay a price for gold generated indices.  */
604   VEC (dwarf2_per_cu_ptr) *imported_symtabs;
605 };
606
607 /* Entry in the signatured_types hash table.  */
608
609 struct signatured_type
610 {
611   /* The "per_cu" object of this type.
612      This struct is used iff per_cu.is_debug_types.
613      N.B.: This is the first member so that it's easy to convert pointers
614      between them.  */
615   struct dwarf2_per_cu_data per_cu;
616
617   /* The type's signature.  */
618   ULONGEST signature;
619
620   /* Offset in the TU of the type's DIE, as read from the TU header.
621      If this TU is a DWO stub and the definition lives in a DWO file
622      (specified by DW_AT_GNU_dwo_name), this value is unusable.  */
623   cu_offset type_offset_in_tu;
624
625   /* Offset in the section of the type's DIE.
626      If the definition lives in a DWO file, this is the offset in the
627      .debug_types.dwo section.
628      The value is zero until the actual value is known.
629      Zero is otherwise not a valid section offset.  */
630   sect_offset type_offset_in_section;
631
632   /* Type units are grouped by their DW_AT_stmt_list entry so that they
633      can share them.  This points to the containing symtab.  */
634   struct type_unit_group *type_unit_group;
635
636   /* The type.
637      The first time we encounter this type we fully read it in and install it
638      in the symbol tables.  Subsequent times we only need the type.  */
639   struct type *type;
640
641   /* Containing DWO unit.
642      This field is valid iff per_cu.reading_dwo_directly.  */
643   struct dwo_unit *dwo_unit;
644 };
645
646 typedef struct signatured_type *sig_type_ptr;
647 DEF_VEC_P (sig_type_ptr);
648
649 /* A struct that can be used as a hash key for tables based on DW_AT_stmt_list.
650    This includes type_unit_group and quick_file_names.  */
651
652 struct stmt_list_hash
653 {
654   /* The DWO unit this table is from or NULL if there is none.  */
655   struct dwo_unit *dwo_unit;
656
657   /* Offset in .debug_line or .debug_line.dwo.  */
658   sect_offset line_offset;
659 };
660
661 /* Each element of dwarf2_per_objfile->type_unit_groups is a pointer to
662    an object of this type.  */
663
664 struct type_unit_group
665 {
666   /* dwarf2read.c's main "handle" on a TU symtab.
667      To simplify things we create an artificial CU that "includes" all the
668      type units using this stmt_list so that the rest of the code still has
669      a "per_cu" handle on the symtab.
670      This PER_CU is recognized by having no section.  */
671 #define IS_TYPE_UNIT_GROUP(per_cu) ((per_cu)->section == NULL)
672   struct dwarf2_per_cu_data per_cu;
673
674   /* The TUs that share this DW_AT_stmt_list entry.
675      This is added to while parsing type units to build partial symtabs,
676      and is deleted afterwards and not used again.  */
677   VEC (sig_type_ptr) *tus;
678
679   /* The primary symtab.
680      Type units in a group needn't all be defined in the same source file,
681      so we create an essentially anonymous symtab as the primary symtab.  */
682   struct symtab *primary_symtab;
683
684   /* The data used to construct the hash key.  */
685   struct stmt_list_hash hash;
686
687   /* The number of symtabs from the line header.
688      The value here must match line_header.num_file_names.  */
689   unsigned int num_symtabs;
690
691   /* The symbol tables for this TU (obtained from the files listed in
692      DW_AT_stmt_list).
693      WARNING: The order of entries here must match the order of entries
694      in the line header.  After the first TU using this type_unit_group, the
695      line header for the subsequent TUs is recreated from this.  This is done
696      because we need to use the same symtabs for each TU using the same
697      DW_AT_stmt_list value.  Also note that symtabs may be repeated here,
698      there's no guarantee the line header doesn't have duplicate entries.  */
699   struct symtab **symtabs;
700 };
701
702 /* These sections are what may appear in a DWO file.  */
703
704 struct dwo_sections
705 {
706   struct dwarf2_section_info abbrev;
707   struct dwarf2_section_info line;
708   struct dwarf2_section_info loc;
709   struct dwarf2_section_info macinfo;
710   struct dwarf2_section_info macro;
711   struct dwarf2_section_info str;
712   struct dwarf2_section_info str_offsets;
713   /* In the case of a virtual DWO file, these two are unused.  */
714   struct dwarf2_section_info info;
715   VEC (dwarf2_section_info_def) *types;
716 };
717
718 /* CUs/TUs in DWP/DWO files.  */
719
720 struct dwo_unit
721 {
722   /* Backlink to the containing struct dwo_file.  */
723   struct dwo_file *dwo_file;
724
725   /* The "id" that distinguishes this CU/TU.
726      .debug_info calls this "dwo_id", .debug_types calls this "signature".
727      Since signatures came first, we stick with it for consistency.  */
728   ULONGEST signature;
729
730   /* The section this CU/TU lives in, in the DWO file.  */
731   struct dwarf2_section_info *section;
732
733   /* Same as dwarf2_per_cu_data:{offset,length} but for the DWO section.  */
734   sect_offset offset;
735   unsigned int length;
736
737   /* For types, offset in the type's DIE of the type defined by this TU.  */
738   cu_offset type_offset_in_tu;
739 };
740
741 /* Data for one DWO file.
742    This includes virtual DWO files that have been packaged into a
743    DWP file.  */
744
745 struct dwo_file
746 {
747   /* The DW_AT_GNU_dwo_name attribute.
748      For virtual DWO files the name is constructed from the section offsets
749      of abbrev,line,loc,str_offsets so that we combine virtual DWO files
750      from related CU+TUs.  */
751   const char *dwo_name;
752
753   /* The DW_AT_comp_dir attribute.  */
754   const char *comp_dir;
755
756   /* The bfd, when the file is open.  Otherwise this is NULL.
757      This is unused(NULL) for virtual DWO files where we use dwp_file.dbfd.  */
758   bfd *dbfd;
759
760   /* Section info for this file.  */
761   struct dwo_sections sections;
762
763   /* The CU in the file.
764      We only support one because having more than one requires hacking the
765      dwo_name of each to match, which is highly unlikely to happen.
766      Doing this means all TUs can share comp_dir: We also assume that
767      DW_AT_comp_dir across all TUs in a DWO file will be identical.  */
768   struct dwo_unit *cu;
769
770   /* Table of TUs in the file.
771      Each element is a struct dwo_unit.  */
772   htab_t tus;
773 };
774
775 /* These sections are what may appear in a DWP file.  */
776
777 struct dwp_sections
778 {
779   struct dwarf2_section_info str;
780   struct dwarf2_section_info cu_index;
781   struct dwarf2_section_info tu_index;
782   /* The .debug_info.dwo, .debug_types.dwo, and other sections are referenced
783      by section number.  We don't need to record them here.  */
784 };
785
786 /* These sections are what may appear in a virtual DWO file.  */
787
788 struct virtual_dwo_sections
789 {
790   struct dwarf2_section_info abbrev;
791   struct dwarf2_section_info line;
792   struct dwarf2_section_info loc;
793   struct dwarf2_section_info macinfo;
794   struct dwarf2_section_info macro;
795   struct dwarf2_section_info str_offsets;
796   /* Each DWP hash table entry records one CU or one TU.
797      That is recorded here, and copied to dwo_unit.section.  */
798   struct dwarf2_section_info info_or_types;
799 };
800
801 /* Contents of DWP hash tables.  */
802
803 struct dwp_hash_table
804 {
805   uint32_t nr_units, nr_slots;
806   const gdb_byte *hash_table, *unit_table, *section_pool;
807 };
808
809 /* Data for one DWP file.  */
810
811 struct dwp_file
812 {
813   /* Name of the file.  */
814   const char *name;
815
816   /* The bfd.  */
817   bfd *dbfd;
818
819   /* Section info for this file.  */
820   struct dwp_sections sections;
821
822   /* Table of CUs in the file. */
823   const struct dwp_hash_table *cus;
824
825   /* Table of TUs in the file.  */
826   const struct dwp_hash_table *tus;
827
828   /* Table of loaded CUs/TUs.  Each entry is a struct dwo_unit *.  */
829   htab_t loaded_cutus;
830
831   /* Table to map ELF section numbers to their sections.  */
832   unsigned int num_sections;
833   asection **elf_sections;
834 };
835
836 /* This represents a '.dwz' file.  */
837
838 struct dwz_file
839 {
840   /* A dwz file can only contain a few sections.  */
841   struct dwarf2_section_info abbrev;
842   struct dwarf2_section_info info;
843   struct dwarf2_section_info str;
844   struct dwarf2_section_info line;
845   struct dwarf2_section_info macro;
846   struct dwarf2_section_info gdb_index;
847
848   /* The dwz's BFD.  */
849   bfd *dwz_bfd;
850 };
851
852 /* Struct used to pass misc. parameters to read_die_and_children, et
853    al.  which are used for both .debug_info and .debug_types dies.
854    All parameters here are unchanging for the life of the call.  This
855    struct exists to abstract away the constant parameters of die reading.  */
856
857 struct die_reader_specs
858 {
859   /* die_section->asection->owner.  */
860   bfd* abfd;
861
862   /* The CU of the DIE we are parsing.  */
863   struct dwarf2_cu *cu;
864
865   /* Non-NULL if reading a DWO file (including one packaged into a DWP).  */
866   struct dwo_file *dwo_file;
867
868   /* The section the die comes from.
869      This is either .debug_info or .debug_types, or the .dwo variants.  */
870   struct dwarf2_section_info *die_section;
871
872   /* die_section->buffer.  */
873   const gdb_byte *buffer;
874
875   /* The end of the buffer.  */
876   const gdb_byte *buffer_end;
877
878   /* The value of the DW_AT_comp_dir attribute.  */
879   const char *comp_dir;
880 };
881
882 /* Type of function passed to init_cutu_and_read_dies, et.al.  */
883 typedef void (die_reader_func_ftype) (const struct die_reader_specs *reader,
884                                       const gdb_byte *info_ptr,
885                                       struct die_info *comp_unit_die,
886                                       int has_children,
887                                       void *data);
888
889 /* The line number information for a compilation unit (found in the
890    .debug_line section) begins with a "statement program header",
891    which contains the following information.  */
892 struct line_header
893 {
894   unsigned int total_length;
895   unsigned short version;
896   unsigned int header_length;
897   unsigned char minimum_instruction_length;
898   unsigned char maximum_ops_per_instruction;
899   unsigned char default_is_stmt;
900   int line_base;
901   unsigned char line_range;
902   unsigned char opcode_base;
903
904   /* standard_opcode_lengths[i] is the number of operands for the
905      standard opcode whose value is i.  This means that
906      standard_opcode_lengths[0] is unused, and the last meaningful
907      element is standard_opcode_lengths[opcode_base - 1].  */
908   unsigned char *standard_opcode_lengths;
909
910   /* The include_directories table.  NOTE!  These strings are not
911      allocated with xmalloc; instead, they are pointers into
912      debug_line_buffer.  If you try to free them, `free' will get
913      indigestion.  */
914   unsigned int num_include_dirs, include_dirs_size;
915   const char **include_dirs;
916
917   /* The file_names table.  NOTE!  These strings are not allocated
918      with xmalloc; instead, they are pointers into debug_line_buffer.
919      Don't try to free them directly.  */
920   unsigned int num_file_names, file_names_size;
921   struct file_entry
922   {
923     const char *name;
924     unsigned int dir_index;
925     unsigned int mod_time;
926     unsigned int length;
927     int included_p; /* Non-zero if referenced by the Line Number Program.  */
928     struct symtab *symtab; /* The associated symbol table, if any.  */
929   } *file_names;
930
931   /* The start and end of the statement program following this
932      header.  These point into dwarf2_per_objfile->line_buffer.  */
933   const gdb_byte *statement_program_start, *statement_program_end;
934 };
935
936 /* When we construct a partial symbol table entry we only
937    need this much information.  */
938 struct partial_die_info
939   {
940     /* Offset of this DIE.  */
941     sect_offset offset;
942
943     /* DWARF-2 tag for this DIE.  */
944     ENUM_BITFIELD(dwarf_tag) tag : 16;
945
946     /* Assorted flags describing the data found in this DIE.  */
947     unsigned int has_children : 1;
948     unsigned int is_external : 1;
949     unsigned int is_declaration : 1;
950     unsigned int has_type : 1;
951     unsigned int has_specification : 1;
952     unsigned int has_pc_info : 1;
953     unsigned int may_be_inlined : 1;
954
955     /* Flag set if the SCOPE field of this structure has been
956        computed.  */
957     unsigned int scope_set : 1;
958
959     /* Flag set if the DIE has a byte_size attribute.  */
960     unsigned int has_byte_size : 1;
961
962     /* Flag set if any of the DIE's children are template arguments.  */
963     unsigned int has_template_arguments : 1;
964
965     /* Flag set if fixup_partial_die has been called on this die.  */
966     unsigned int fixup_called : 1;
967
968     /* Flag set if DW_TAG_imported_unit uses DW_FORM_GNU_ref_alt.  */
969     unsigned int is_dwz : 1;
970
971     /* Flag set if spec_offset uses DW_FORM_GNU_ref_alt.  */
972     unsigned int spec_is_dwz : 1;
973
974     /* The name of this DIE.  Normally the value of DW_AT_name, but
975        sometimes a default name for unnamed DIEs.  */
976     const char *name;
977
978     /* The linkage name, if present.  */
979     const char *linkage_name;
980
981     /* The scope to prepend to our children.  This is generally
982        allocated on the comp_unit_obstack, so will disappear
983        when this compilation unit leaves the cache.  */
984     const char *scope;
985
986     /* Some data associated with the partial DIE.  The tag determines
987        which field is live.  */
988     union
989     {
990       /* The location description associated with this DIE, if any.  */
991       struct dwarf_block *locdesc;
992       /* The offset of an import, for DW_TAG_imported_unit.  */
993       sect_offset offset;
994     } d;
995
996     /* If HAS_PC_INFO, the PC range associated with this DIE.  */
997     CORE_ADDR lowpc;
998     CORE_ADDR highpc;
999
1000     /* Pointer into the info_buffer (or types_buffer) pointing at the target of
1001        DW_AT_sibling, if any.  */
1002     /* NOTE: This member isn't strictly necessary, read_partial_die could
1003        return DW_AT_sibling values to its caller load_partial_dies.  */
1004     const gdb_byte *sibling;
1005
1006     /* If HAS_SPECIFICATION, the offset of the DIE referred to by
1007        DW_AT_specification (or DW_AT_abstract_origin or
1008        DW_AT_extension).  */
1009     sect_offset spec_offset;
1010
1011     /* Pointers to this DIE's parent, first child, and next sibling,
1012        if any.  */
1013     struct partial_die_info *die_parent, *die_child, *die_sibling;
1014   };
1015
1016 /* This data structure holds the information of an abbrev.  */
1017 struct abbrev_info
1018   {
1019     unsigned int number;        /* number identifying abbrev */
1020     enum dwarf_tag tag;         /* dwarf tag */
1021     unsigned short has_children;                /* boolean */
1022     unsigned short num_attrs;   /* number of attributes */
1023     struct attr_abbrev *attrs;  /* an array of attribute descriptions */
1024     struct abbrev_info *next;   /* next in chain */
1025   };
1026
1027 struct attr_abbrev
1028   {
1029     ENUM_BITFIELD(dwarf_attribute) name : 16;
1030     ENUM_BITFIELD(dwarf_form) form : 16;
1031   };
1032
1033 /* Size of abbrev_table.abbrev_hash_table.  */
1034 #define ABBREV_HASH_SIZE 121
1035
1036 /* Top level data structure to contain an abbreviation table.  */
1037
1038 struct abbrev_table
1039 {
1040   /* Where the abbrev table came from.
1041      This is used as a sanity check when the table is used.  */
1042   sect_offset offset;
1043
1044   /* Storage for the abbrev table.  */
1045   struct obstack abbrev_obstack;
1046
1047   /* Hash table of abbrevs.
1048      This is an array of size ABBREV_HASH_SIZE allocated in abbrev_obstack.
1049      It could be statically allocated, but the previous code didn't so we
1050      don't either.  */
1051   struct abbrev_info **abbrevs;
1052 };
1053
1054 /* Attributes have a name and a value.  */
1055 struct attribute
1056   {
1057     ENUM_BITFIELD(dwarf_attribute) name : 16;
1058     ENUM_BITFIELD(dwarf_form) form : 15;
1059
1060     /* Has DW_STRING already been updated by dwarf2_canonicalize_name?  This
1061        field should be in u.str (existing only for DW_STRING) but it is kept
1062        here for better struct attribute alignment.  */
1063     unsigned int string_is_canonical : 1;
1064
1065     union
1066       {
1067         const char *str;
1068         struct dwarf_block *blk;
1069         ULONGEST unsnd;
1070         LONGEST snd;
1071         CORE_ADDR addr;
1072         ULONGEST signature;
1073       }
1074     u;
1075   };
1076
1077 /* This data structure holds a complete die structure.  */
1078 struct die_info
1079   {
1080     /* DWARF-2 tag for this DIE.  */
1081     ENUM_BITFIELD(dwarf_tag) tag : 16;
1082
1083     /* Number of attributes */
1084     unsigned char num_attrs;
1085
1086     /* True if we're presently building the full type name for the
1087        type derived from this DIE.  */
1088     unsigned char building_fullname : 1;
1089
1090     /* Abbrev number */
1091     unsigned int abbrev;
1092
1093     /* Offset in .debug_info or .debug_types section.  */
1094     sect_offset offset;
1095
1096     /* The dies in a compilation unit form an n-ary tree.  PARENT
1097        points to this die's parent; CHILD points to the first child of
1098        this node; and all the children of a given node are chained
1099        together via their SIBLING fields.  */
1100     struct die_info *child;     /* Its first child, if any.  */
1101     struct die_info *sibling;   /* Its next sibling, if any.  */
1102     struct die_info *parent;    /* Its parent, if any.  */
1103
1104     /* An array of attributes, with NUM_ATTRS elements.  There may be
1105        zero, but it's not common and zero-sized arrays are not
1106        sufficiently portable C.  */
1107     struct attribute attrs[1];
1108   };
1109
1110 /* Get at parts of an attribute structure.  */
1111
1112 #define DW_STRING(attr)    ((attr)->u.str)
1113 #define DW_STRING_IS_CANONICAL(attr) ((attr)->string_is_canonical)
1114 #define DW_UNSND(attr)     ((attr)->u.unsnd)
1115 #define DW_BLOCK(attr)     ((attr)->u.blk)
1116 #define DW_SND(attr)       ((attr)->u.snd)
1117 #define DW_ADDR(attr)      ((attr)->u.addr)
1118 #define DW_SIGNATURE(attr) ((attr)->u.signature)
1119
1120 /* Blocks are a bunch of untyped bytes.  */
1121 struct dwarf_block
1122   {
1123     size_t size;
1124
1125     /* Valid only if SIZE is not zero.  */
1126     const gdb_byte *data;
1127   };
1128
1129 #ifndef ATTR_ALLOC_CHUNK
1130 #define ATTR_ALLOC_CHUNK 4
1131 #endif
1132
1133 /* Allocate fields for structs, unions and enums in this size.  */
1134 #ifndef DW_FIELD_ALLOC_CHUNK
1135 #define DW_FIELD_ALLOC_CHUNK 4
1136 #endif
1137
1138 /* FIXME: We might want to set this from BFD via bfd_arch_bits_per_byte,
1139    but this would require a corresponding change in unpack_field_as_long
1140    and friends.  */
1141 static int bits_per_byte = 8;
1142
1143 /* The routines that read and process dies for a C struct or C++ class
1144    pass lists of data member fields and lists of member function fields
1145    in an instance of a field_info structure, as defined below.  */
1146 struct field_info
1147   {
1148     /* List of data member and baseclasses fields.  */
1149     struct nextfield
1150       {
1151         struct nextfield *next;
1152         int accessibility;
1153         int virtuality;
1154         struct field field;
1155       }
1156      *fields, *baseclasses;
1157
1158     /* Number of fields (including baseclasses).  */
1159     int nfields;
1160
1161     /* Number of baseclasses.  */
1162     int nbaseclasses;
1163
1164     /* Set if the accesibility of one of the fields is not public.  */
1165     int non_public_fields;
1166
1167     /* Member function fields array, entries are allocated in the order they
1168        are encountered in the object file.  */
1169     struct nextfnfield
1170       {
1171         struct nextfnfield *next;
1172         struct fn_field fnfield;
1173       }
1174      *fnfields;
1175
1176     /* Member function fieldlist array, contains name of possibly overloaded
1177        member function, number of overloaded member functions and a pointer
1178        to the head of the member function field chain.  */
1179     struct fnfieldlist
1180       {
1181         const char *name;
1182         int length;
1183         struct nextfnfield *head;
1184       }
1185      *fnfieldlists;
1186
1187     /* Number of entries in the fnfieldlists array.  */
1188     int nfnfields;
1189
1190     /* typedefs defined inside this class.  TYPEDEF_FIELD_LIST contains head of
1191        a NULL terminated list of TYPEDEF_FIELD_LIST_COUNT elements.  */
1192     struct typedef_field_list
1193       {
1194         struct typedef_field field;
1195         struct typedef_field_list *next;
1196       }
1197     *typedef_field_list;
1198     unsigned typedef_field_list_count;
1199   };
1200
1201 /* One item on the queue of compilation units to read in full symbols
1202    for.  */
1203 struct dwarf2_queue_item
1204 {
1205   struct dwarf2_per_cu_data *per_cu;
1206   enum language pretend_language;
1207   struct dwarf2_queue_item *next;
1208 };
1209
1210 /* The current queue.  */
1211 static struct dwarf2_queue_item *dwarf2_queue, *dwarf2_queue_tail;
1212
1213 /* Loaded secondary compilation units are kept in memory until they
1214    have not been referenced for the processing of this many
1215    compilation units.  Set this to zero to disable caching.  Cache
1216    sizes of up to at least twenty will improve startup time for
1217    typical inter-CU-reference binaries, at an obvious memory cost.  */
1218 static int dwarf2_max_cache_age = 5;
1219 static void
1220 show_dwarf2_max_cache_age (struct ui_file *file, int from_tty,
1221                            struct cmd_list_element *c, const char *value)
1222 {
1223   fprintf_filtered (file, _("The upper bound on the age of cached "
1224                             "dwarf2 compilation units is %s.\n"),
1225                     value);
1226 }
1227
1228
1229 /* Various complaints about symbol reading that don't abort the process.  */
1230
1231 static void
1232 dwarf2_statement_list_fits_in_line_number_section_complaint (void)
1233 {
1234   complaint (&symfile_complaints,
1235              _("statement list doesn't fit in .debug_line section"));
1236 }
1237
1238 static void
1239 dwarf2_debug_line_missing_file_complaint (void)
1240 {
1241   complaint (&symfile_complaints,
1242              _(".debug_line section has line data without a file"));
1243 }
1244
1245 static void
1246 dwarf2_debug_line_missing_end_sequence_complaint (void)
1247 {
1248   complaint (&symfile_complaints,
1249              _(".debug_line section has line "
1250                "program sequence without an end"));
1251 }
1252
1253 static void
1254 dwarf2_complex_location_expr_complaint (void)
1255 {
1256   complaint (&symfile_complaints, _("location expression too complex"));
1257 }
1258
1259 static void
1260 dwarf2_const_value_length_mismatch_complaint (const char *arg1, int arg2,
1261                                               int arg3)
1262 {
1263   complaint (&symfile_complaints,
1264              _("const value length mismatch for '%s', got %d, expected %d"),
1265              arg1, arg2, arg3);
1266 }
1267
1268 static void
1269 dwarf2_section_buffer_overflow_complaint (struct dwarf2_section_info *section)
1270 {
1271   complaint (&symfile_complaints,
1272              _("debug info runs off end of %s section"
1273                " [in module %s]"),
1274              section->asection->name,
1275              bfd_get_filename (section->asection->owner));
1276 }
1277
1278 static void
1279 dwarf2_macro_malformed_definition_complaint (const char *arg1)
1280 {
1281   complaint (&symfile_complaints,
1282              _("macro debug info contains a "
1283                "malformed macro definition:\n`%s'"),
1284              arg1);
1285 }
1286
1287 static void
1288 dwarf2_invalid_attrib_class_complaint (const char *arg1, const char *arg2)
1289 {
1290   complaint (&symfile_complaints,
1291              _("invalid attribute class or form for '%s' in '%s'"),
1292              arg1, arg2);
1293 }
1294
1295 /* local function prototypes */
1296
1297 static void dwarf2_locate_sections (bfd *, asection *, void *);
1298
1299 static void dwarf2_find_base_address (struct die_info *die,
1300                                       struct dwarf2_cu *cu);
1301
1302 static struct partial_symtab *create_partial_symtab
1303   (struct dwarf2_per_cu_data *per_cu, const char *name);
1304
1305 static void dwarf2_build_psymtabs_hard (struct objfile *);
1306
1307 static void scan_partial_symbols (struct partial_die_info *,
1308                                   CORE_ADDR *, CORE_ADDR *,
1309                                   int, struct dwarf2_cu *);
1310
1311 static void add_partial_symbol (struct partial_die_info *,
1312                                 struct dwarf2_cu *);
1313
1314 static void add_partial_namespace (struct partial_die_info *pdi,
1315                                    CORE_ADDR *lowpc, CORE_ADDR *highpc,
1316                                    int need_pc, struct dwarf2_cu *cu);
1317
1318 static void add_partial_module (struct partial_die_info *pdi, CORE_ADDR *lowpc,
1319                                 CORE_ADDR *highpc, int need_pc,
1320                                 struct dwarf2_cu *cu);
1321
1322 static void add_partial_enumeration (struct partial_die_info *enum_pdi,
1323                                      struct dwarf2_cu *cu);
1324
1325 static void add_partial_subprogram (struct partial_die_info *pdi,
1326                                     CORE_ADDR *lowpc, CORE_ADDR *highpc,
1327                                     int need_pc, struct dwarf2_cu *cu);
1328
1329 static void dwarf2_read_symtab (struct partial_symtab *,
1330                                 struct objfile *);
1331
1332 static void psymtab_to_symtab_1 (struct partial_symtab *);
1333
1334 static struct abbrev_info *abbrev_table_lookup_abbrev
1335   (const struct abbrev_table *, unsigned int);
1336
1337 static struct abbrev_table *abbrev_table_read_table
1338   (struct dwarf2_section_info *, sect_offset);
1339
1340 static void abbrev_table_free (struct abbrev_table *);
1341
1342 static void abbrev_table_free_cleanup (void *);
1343
1344 static void dwarf2_read_abbrevs (struct dwarf2_cu *,
1345                                  struct dwarf2_section_info *);
1346
1347 static void dwarf2_free_abbrev_table (void *);
1348
1349 static unsigned int peek_abbrev_code (bfd *, const gdb_byte *);
1350
1351 static struct partial_die_info *load_partial_dies
1352   (const struct die_reader_specs *, const gdb_byte *, int);
1353
1354 static const gdb_byte *read_partial_die (const struct die_reader_specs *,
1355                                          struct partial_die_info *,
1356                                          struct abbrev_info *,
1357                                          unsigned int,
1358                                          const gdb_byte *);
1359
1360 static struct partial_die_info *find_partial_die (sect_offset, int,
1361                                                   struct dwarf2_cu *);
1362
1363 static void fixup_partial_die (struct partial_die_info *,
1364                                struct dwarf2_cu *);
1365
1366 static const gdb_byte *read_attribute (const struct die_reader_specs *,
1367                                        struct attribute *, struct attr_abbrev *,
1368                                        const gdb_byte *);
1369
1370 static unsigned int read_1_byte (bfd *, const gdb_byte *);
1371
1372 static int read_1_signed_byte (bfd *, const gdb_byte *);
1373
1374 static unsigned int read_2_bytes (bfd *, const gdb_byte *);
1375
1376 static unsigned int read_4_bytes (bfd *, const gdb_byte *);
1377
1378 static ULONGEST read_8_bytes (bfd *, const gdb_byte *);
1379
1380 static CORE_ADDR read_address (bfd *, const gdb_byte *ptr, struct dwarf2_cu *,
1381                                unsigned int *);
1382
1383 static LONGEST read_initial_length (bfd *, const gdb_byte *, unsigned int *);
1384
1385 static LONGEST read_checked_initial_length_and_offset
1386   (bfd *, const gdb_byte *, const struct comp_unit_head *,
1387    unsigned int *, unsigned int *);
1388
1389 static LONGEST read_offset (bfd *, const gdb_byte *,
1390                             const struct comp_unit_head *,
1391                             unsigned int *);
1392
1393 static LONGEST read_offset_1 (bfd *, const gdb_byte *, unsigned int);
1394
1395 static sect_offset read_abbrev_offset (struct dwarf2_section_info *,
1396                                        sect_offset);
1397
1398 static const gdb_byte *read_n_bytes (bfd *, const gdb_byte *, unsigned int);
1399
1400 static const char *read_direct_string (bfd *, const gdb_byte *, unsigned int *);
1401
1402 static const char *read_indirect_string (bfd *, const gdb_byte *,
1403                                          const struct comp_unit_head *,
1404                                          unsigned int *);
1405
1406 static const char *read_indirect_string_from_dwz (struct dwz_file *, LONGEST);
1407
1408 static ULONGEST read_unsigned_leb128 (bfd *, const gdb_byte *, unsigned int *);
1409
1410 static LONGEST read_signed_leb128 (bfd *, const gdb_byte *, unsigned int *);
1411
1412 static CORE_ADDR read_addr_index_from_leb128 (struct dwarf2_cu *,
1413                                               const gdb_byte *,
1414                                               unsigned int *);
1415
1416 static const char *read_str_index (const struct die_reader_specs *reader,
1417                                    struct dwarf2_cu *cu, ULONGEST str_index);
1418
1419 static void set_cu_language (unsigned int, struct dwarf2_cu *);
1420
1421 static struct attribute *dwarf2_attr (struct die_info *, unsigned int,
1422                                       struct dwarf2_cu *);
1423
1424 static struct attribute *dwarf2_attr_no_follow (struct die_info *,
1425                                                 unsigned int);
1426
1427 static int dwarf2_flag_true_p (struct die_info *die, unsigned name,
1428                                struct dwarf2_cu *cu);
1429
1430 static int die_is_declaration (struct die_info *, struct dwarf2_cu *cu);
1431
1432 static struct die_info *die_specification (struct die_info *die,
1433                                            struct dwarf2_cu **);
1434
1435 static void free_line_header (struct line_header *lh);
1436
1437 static struct line_header *dwarf_decode_line_header (unsigned int offset,
1438                                                      struct dwarf2_cu *cu);
1439
1440 static void dwarf_decode_lines (struct line_header *, const char *,
1441                                 struct dwarf2_cu *, struct partial_symtab *,
1442                                 int);
1443
1444 static void dwarf2_start_subfile (const char *, const char *, const char *);
1445
1446 static void dwarf2_start_symtab (struct dwarf2_cu *,
1447                                  const char *, const char *, CORE_ADDR);
1448
1449 static struct symbol *new_symbol (struct die_info *, struct type *,
1450                                   struct dwarf2_cu *);
1451
1452 static struct symbol *new_symbol_full (struct die_info *, struct type *,
1453                                        struct dwarf2_cu *, struct symbol *);
1454
1455 static void dwarf2_const_value (struct attribute *, struct symbol *,
1456                                 struct dwarf2_cu *);
1457
1458 static void dwarf2_const_value_attr (struct attribute *attr,
1459                                      struct type *type,
1460                                      const char *name,
1461                                      struct obstack *obstack,
1462                                      struct dwarf2_cu *cu, LONGEST *value,
1463                                      const gdb_byte **bytes,
1464                                      struct dwarf2_locexpr_baton **baton);
1465
1466 static struct type *die_type (struct die_info *, struct dwarf2_cu *);
1467
1468 static int need_gnat_info (struct dwarf2_cu *);
1469
1470 static struct type *die_descriptive_type (struct die_info *,
1471                                           struct dwarf2_cu *);
1472
1473 static void set_descriptive_type (struct type *, struct die_info *,
1474                                   struct dwarf2_cu *);
1475
1476 static struct type *die_containing_type (struct die_info *,
1477                                          struct dwarf2_cu *);
1478
1479 static struct type *lookup_die_type (struct die_info *, struct attribute *,
1480                                      struct dwarf2_cu *);
1481
1482 static struct type *read_type_die (struct die_info *, struct dwarf2_cu *);
1483
1484 static struct type *read_type_die_1 (struct die_info *, struct dwarf2_cu *);
1485
1486 static const char *determine_prefix (struct die_info *die, struct dwarf2_cu *);
1487
1488 static char *typename_concat (struct obstack *obs, const char *prefix,
1489                               const char *suffix, int physname,
1490                               struct dwarf2_cu *cu);
1491
1492 static void read_file_scope (struct die_info *, struct dwarf2_cu *);
1493
1494 static void read_type_unit_scope (struct die_info *, struct dwarf2_cu *);
1495
1496 static void read_func_scope (struct die_info *, struct dwarf2_cu *);
1497
1498 static void read_lexical_block_scope (struct die_info *, struct dwarf2_cu *);
1499
1500 static void read_call_site_scope (struct die_info *die, struct dwarf2_cu *cu);
1501
1502 static int dwarf2_ranges_read (unsigned, CORE_ADDR *, CORE_ADDR *,
1503                                struct dwarf2_cu *, struct partial_symtab *);
1504
1505 static int dwarf2_get_pc_bounds (struct die_info *,
1506                                  CORE_ADDR *, CORE_ADDR *, struct dwarf2_cu *,
1507                                  struct partial_symtab *);
1508
1509 static void get_scope_pc_bounds (struct die_info *,
1510                                  CORE_ADDR *, CORE_ADDR *,
1511                                  struct dwarf2_cu *);
1512
1513 static void dwarf2_record_block_ranges (struct die_info *, struct block *,
1514                                         CORE_ADDR, struct dwarf2_cu *);
1515
1516 static void dwarf2_add_field (struct field_info *, struct die_info *,
1517                               struct dwarf2_cu *);
1518
1519 static void dwarf2_attach_fields_to_type (struct field_info *,
1520                                           struct type *, struct dwarf2_cu *);
1521
1522 static void dwarf2_add_member_fn (struct field_info *,
1523                                   struct die_info *, struct type *,
1524                                   struct dwarf2_cu *);
1525
1526 static void dwarf2_attach_fn_fields_to_type (struct field_info *,
1527                                              struct type *,
1528                                              struct dwarf2_cu *);
1529
1530 static void process_structure_scope (struct die_info *, struct dwarf2_cu *);
1531
1532 static void read_common_block (struct die_info *, struct dwarf2_cu *);
1533
1534 static void read_namespace (struct die_info *die, struct dwarf2_cu *);
1535
1536 static void read_module (struct die_info *die, struct dwarf2_cu *cu);
1537
1538 static void read_import_statement (struct die_info *die, struct dwarf2_cu *);
1539
1540 static struct type *read_module_type (struct die_info *die,
1541                                       struct dwarf2_cu *cu);
1542
1543 static const char *namespace_name (struct die_info *die,
1544                                    int *is_anonymous, struct dwarf2_cu *);
1545
1546 static void process_enumeration_scope (struct die_info *, struct dwarf2_cu *);
1547
1548 static CORE_ADDR decode_locdesc (struct dwarf_block *, struct dwarf2_cu *);
1549
1550 static enum dwarf_array_dim_ordering read_array_order (struct die_info *,
1551                                                        struct dwarf2_cu *);
1552
1553 static struct die_info *read_die_and_siblings_1
1554   (const struct die_reader_specs *, const gdb_byte *, const gdb_byte **,
1555    struct die_info *);
1556
1557 static struct die_info *read_die_and_siblings (const struct die_reader_specs *,
1558                                                const gdb_byte *info_ptr,
1559                                                const gdb_byte **new_info_ptr,
1560                                                struct die_info *parent);
1561
1562 static const gdb_byte *read_full_die_1 (const struct die_reader_specs *,
1563                                         struct die_info **, const gdb_byte *,
1564                                         int *, int);
1565
1566 static const gdb_byte *read_full_die (const struct die_reader_specs *,
1567                                       struct die_info **, const gdb_byte *,
1568                                       int *);
1569
1570 static void process_die (struct die_info *, struct dwarf2_cu *);
1571
1572 static const char *dwarf2_canonicalize_name (const char *, struct dwarf2_cu *,
1573                                              struct obstack *);
1574
1575 static const char *dwarf2_name (struct die_info *die, struct dwarf2_cu *);
1576
1577 static const char *dwarf2_full_name (const char *name,
1578                                      struct die_info *die,
1579                                      struct dwarf2_cu *cu);
1580
1581 static const char *dwarf2_physname (const char *name, struct die_info *die,
1582                                     struct dwarf2_cu *cu);
1583
1584 static struct die_info *dwarf2_extension (struct die_info *die,
1585                                           struct dwarf2_cu **);
1586
1587 static const char *dwarf_tag_name (unsigned int);
1588
1589 static const char *dwarf_attr_name (unsigned int);
1590
1591 static const char *dwarf_form_name (unsigned int);
1592
1593 static char *dwarf_bool_name (unsigned int);
1594
1595 static const char *dwarf_type_encoding_name (unsigned int);
1596
1597 static struct die_info *sibling_die (struct die_info *);
1598
1599 static void dump_die_shallow (struct ui_file *, int indent, struct die_info *);
1600
1601 static void dump_die_for_error (struct die_info *);
1602
1603 static void dump_die_1 (struct ui_file *, int level, int max_level,
1604                         struct die_info *);
1605
1606 /*static*/ void dump_die (struct die_info *, int max_level);
1607
1608 static void store_in_ref_table (struct die_info *,
1609                                 struct dwarf2_cu *);
1610
1611 static int is_ref_attr (struct attribute *);
1612
1613 static sect_offset dwarf2_get_ref_die_offset (struct attribute *);
1614
1615 static LONGEST dwarf2_get_attr_constant_value (struct attribute *, int);
1616
1617 static struct die_info *follow_die_ref_or_sig (struct die_info *,
1618                                                struct attribute *,
1619                                                struct dwarf2_cu **);
1620
1621 static struct die_info *follow_die_ref (struct die_info *,
1622                                         struct attribute *,
1623                                         struct dwarf2_cu **);
1624
1625 static struct die_info *follow_die_sig (struct die_info *,
1626                                         struct attribute *,
1627                                         struct dwarf2_cu **);
1628
1629 static struct type *get_signatured_type (struct die_info *, ULONGEST,
1630                                          struct dwarf2_cu *);
1631
1632 static struct type *get_DW_AT_signature_type (struct die_info *,
1633                                               struct attribute *,
1634                                               struct dwarf2_cu *);
1635
1636 static void load_full_type_unit (struct dwarf2_per_cu_data *per_cu);
1637
1638 static void read_signatured_type (struct signatured_type *);
1639
1640 static struct type_unit_group *get_type_unit_group
1641     (struct dwarf2_cu *, struct attribute *);
1642
1643 static void build_type_unit_groups (die_reader_func_ftype *, void *);
1644
1645 /* memory allocation interface */
1646
1647 static struct dwarf_block *dwarf_alloc_block (struct dwarf2_cu *);
1648
1649 static struct die_info *dwarf_alloc_die (struct dwarf2_cu *, int);
1650
1651 static void dwarf_decode_macros (struct dwarf2_cu *, unsigned int,
1652                                  const char *, int);
1653
1654 static int attr_form_is_block (struct attribute *);
1655
1656 static int attr_form_is_section_offset (struct attribute *);
1657
1658 static int attr_form_is_constant (struct attribute *);
1659
1660 static void fill_in_loclist_baton (struct dwarf2_cu *cu,
1661                                    struct dwarf2_loclist_baton *baton,
1662                                    struct attribute *attr);
1663
1664 static void dwarf2_symbol_mark_computed (struct attribute *attr,
1665                                          struct symbol *sym,
1666                                          struct dwarf2_cu *cu,
1667                                          int is_block);
1668
1669 static const gdb_byte *skip_one_die (const struct die_reader_specs *reader,
1670                                      const gdb_byte *info_ptr,
1671                                      struct abbrev_info *abbrev);
1672
1673 static void free_stack_comp_unit (void *);
1674
1675 static hashval_t partial_die_hash (const void *item);
1676
1677 static int partial_die_eq (const void *item_lhs, const void *item_rhs);
1678
1679 static struct dwarf2_per_cu_data *dwarf2_find_containing_comp_unit
1680   (sect_offset offset, unsigned int offset_in_dwz, struct objfile *objfile);
1681
1682 static void init_one_comp_unit (struct dwarf2_cu *cu,
1683                                 struct dwarf2_per_cu_data *per_cu);
1684
1685 static void prepare_one_comp_unit (struct dwarf2_cu *cu,
1686                                    struct die_info *comp_unit_die,
1687                                    enum language pretend_language);
1688
1689 static void free_heap_comp_unit (void *);
1690
1691 static void free_cached_comp_units (void *);
1692
1693 static void age_cached_comp_units (void);
1694
1695 static void free_one_cached_comp_unit (struct dwarf2_per_cu_data *);
1696
1697 static struct type *set_die_type (struct die_info *, struct type *,
1698                                   struct dwarf2_cu *);
1699
1700 static void create_all_comp_units (struct objfile *);
1701
1702 static int create_all_type_units (struct objfile *);
1703
1704 static void load_full_comp_unit (struct dwarf2_per_cu_data *,
1705                                  enum language);
1706
1707 static void process_full_comp_unit (struct dwarf2_per_cu_data *,
1708                                     enum language);
1709
1710 static void process_full_type_unit (struct dwarf2_per_cu_data *,
1711                                     enum language);
1712
1713 static void dwarf2_add_dependence (struct dwarf2_cu *,
1714                                    struct dwarf2_per_cu_data *);
1715
1716 static void dwarf2_mark (struct dwarf2_cu *);
1717
1718 static void dwarf2_clear_marks (struct dwarf2_per_cu_data *);
1719
1720 static struct type *get_die_type_at_offset (sect_offset,
1721                                             struct dwarf2_per_cu_data *);
1722
1723 static struct type *get_die_type (struct die_info *die, struct dwarf2_cu *cu);
1724
1725 static void dwarf2_release_queue (void *dummy);
1726
1727 static void queue_comp_unit (struct dwarf2_per_cu_data *per_cu,
1728                              enum language pretend_language);
1729
1730 static int maybe_queue_comp_unit (struct dwarf2_cu *this_cu,
1731                                   struct dwarf2_per_cu_data *per_cu,
1732                                   enum language pretend_language);
1733
1734 static void process_queue (void);
1735
1736 static void find_file_and_directory (struct die_info *die,
1737                                      struct dwarf2_cu *cu,
1738                                      const char **name, const char **comp_dir);
1739
1740 static char *file_full_name (int file, struct line_header *lh,
1741                              const char *comp_dir);
1742
1743 static const gdb_byte *read_and_check_comp_unit_head
1744   (struct comp_unit_head *header,
1745    struct dwarf2_section_info *section,
1746    struct dwarf2_section_info *abbrev_section, const gdb_byte *info_ptr,
1747    int is_debug_types_section);
1748
1749 static void init_cutu_and_read_dies
1750   (struct dwarf2_per_cu_data *this_cu, struct abbrev_table *abbrev_table,
1751    int use_existing_cu, int keep,
1752    die_reader_func_ftype *die_reader_func, void *data);
1753
1754 static void init_cutu_and_read_dies_simple
1755   (struct dwarf2_per_cu_data *this_cu,
1756    die_reader_func_ftype *die_reader_func, void *data);
1757
1758 static htab_t allocate_signatured_type_table (struct objfile *objfile);
1759
1760 static htab_t allocate_dwo_unit_table (struct objfile *objfile);
1761
1762 static struct dwo_unit *lookup_dwo_in_dwp
1763   (struct dwp_file *dwp_file, const struct dwp_hash_table *htab,
1764    const char *comp_dir, ULONGEST signature, int is_debug_types);
1765
1766 static struct dwp_file *get_dwp_file (void);
1767
1768 static struct dwo_unit *lookup_dwo_comp_unit
1769   (struct dwarf2_per_cu_data *, const char *, const char *, ULONGEST);
1770
1771 static struct dwo_unit *lookup_dwo_type_unit
1772   (struct signatured_type *, const char *, const char *);
1773
1774 static void free_dwo_file_cleanup (void *);
1775
1776 static void process_cu_includes (void);
1777
1778 static void check_producer (struct dwarf2_cu *cu);
1779
1780 #if WORDS_BIGENDIAN
1781
1782 /* Convert VALUE between big- and little-endian.  */
1783 static offset_type
1784 byte_swap (offset_type value)
1785 {
1786   offset_type result;
1787
1788   result = (value & 0xff) << 24;
1789   result |= (value & 0xff00) << 8;
1790   result |= (value & 0xff0000) >> 8;
1791   result |= (value & 0xff000000) >> 24;
1792   return result;
1793 }
1794
1795 #define MAYBE_SWAP(V)  byte_swap (V)
1796
1797 #else
1798 #define MAYBE_SWAP(V) (V)
1799 #endif /* WORDS_BIGENDIAN */
1800
1801 /* The suffix for an index file.  */
1802 #define INDEX_SUFFIX ".gdb-index"
1803
1804 /* Try to locate the sections we need for DWARF 2 debugging
1805    information and return true if we have enough to do something.
1806    NAMES points to the dwarf2 section names, or is NULL if the standard
1807    ELF names are used.  */
1808
1809 int
1810 dwarf2_has_info (struct objfile *objfile,
1811                  const struct dwarf2_debug_sections *names)
1812 {
1813   dwarf2_per_objfile = objfile_data (objfile, dwarf2_objfile_data_key);
1814   if (!dwarf2_per_objfile)
1815     {
1816       /* Initialize per-objfile state.  */
1817       struct dwarf2_per_objfile *data
1818         = obstack_alloc (&objfile->objfile_obstack, sizeof (*data));
1819
1820       memset (data, 0, sizeof (*data));
1821       set_objfile_data (objfile, dwarf2_objfile_data_key, data);
1822       dwarf2_per_objfile = data;
1823
1824       bfd_map_over_sections (objfile->obfd, dwarf2_locate_sections,
1825                              (void *) names);
1826       dwarf2_per_objfile->objfile = objfile;
1827     }
1828   return (dwarf2_per_objfile->info.asection != NULL
1829           && dwarf2_per_objfile->abbrev.asection != NULL);
1830 }
1831
1832 /* When loading sections, we look either for uncompressed section or for
1833    compressed section names.  */
1834
1835 static int
1836 section_is_p (const char *section_name,
1837               const struct dwarf2_section_names *names)
1838 {
1839   if (names->normal != NULL
1840       && strcmp (section_name, names->normal) == 0)
1841     return 1;
1842   if (names->compressed != NULL
1843       && strcmp (section_name, names->compressed) == 0)
1844     return 1;
1845   return 0;
1846 }
1847
1848 /* This function is mapped across the sections and remembers the
1849    offset and size of each of the debugging sections we are interested
1850    in.  */
1851
1852 static void
1853 dwarf2_locate_sections (bfd *abfd, asection *sectp, void *vnames)
1854 {
1855   const struct dwarf2_debug_sections *names;
1856   flagword aflag = bfd_get_section_flags (abfd, sectp);
1857
1858   if (vnames == NULL)
1859     names = &dwarf2_elf_names;
1860   else
1861     names = (const struct dwarf2_debug_sections *) vnames;
1862
1863   if ((aflag & SEC_HAS_CONTENTS) == 0)
1864     {
1865     }
1866   else if (section_is_p (sectp->name, &names->info))
1867     {
1868       dwarf2_per_objfile->info.asection = sectp;
1869       dwarf2_per_objfile->info.size = bfd_get_section_size (sectp);
1870     }
1871   else if (section_is_p (sectp->name, &names->abbrev))
1872     {
1873       dwarf2_per_objfile->abbrev.asection = sectp;
1874       dwarf2_per_objfile->abbrev.size = bfd_get_section_size (sectp);
1875     }
1876   else if (section_is_p (sectp->name, &names->line))
1877     {
1878       dwarf2_per_objfile->line.asection = sectp;
1879       dwarf2_per_objfile->line.size = bfd_get_section_size (sectp);
1880     }
1881   else if (section_is_p (sectp->name, &names->loc))
1882     {
1883       dwarf2_per_objfile->loc.asection = sectp;
1884       dwarf2_per_objfile->loc.size = bfd_get_section_size (sectp);
1885     }
1886   else if (section_is_p (sectp->name, &names->macinfo))
1887     {
1888       dwarf2_per_objfile->macinfo.asection = sectp;
1889       dwarf2_per_objfile->macinfo.size = bfd_get_section_size (sectp);
1890     }
1891   else if (section_is_p (sectp->name, &names->macro))
1892     {
1893       dwarf2_per_objfile->macro.asection = sectp;
1894       dwarf2_per_objfile->macro.size = bfd_get_section_size (sectp);
1895     }
1896   else if (section_is_p (sectp->name, &names->str))
1897     {
1898       dwarf2_per_objfile->str.asection = sectp;
1899       dwarf2_per_objfile->str.size = bfd_get_section_size (sectp);
1900     }
1901   else if (section_is_p (sectp->name, &names->addr))
1902     {
1903       dwarf2_per_objfile->addr.asection = sectp;
1904       dwarf2_per_objfile->addr.size = bfd_get_section_size (sectp);
1905     }
1906   else if (section_is_p (sectp->name, &names->frame))
1907     {
1908       dwarf2_per_objfile->frame.asection = sectp;
1909       dwarf2_per_objfile->frame.size = bfd_get_section_size (sectp);
1910     }
1911   else if (section_is_p (sectp->name, &names->eh_frame))
1912     {
1913       dwarf2_per_objfile->eh_frame.asection = sectp;
1914       dwarf2_per_objfile->eh_frame.size = bfd_get_section_size (sectp);
1915     }
1916   else if (section_is_p (sectp->name, &names->ranges))
1917     {
1918       dwarf2_per_objfile->ranges.asection = sectp;
1919       dwarf2_per_objfile->ranges.size = bfd_get_section_size (sectp);
1920     }
1921   else if (section_is_p (sectp->name, &names->types))
1922     {
1923       struct dwarf2_section_info type_section;
1924
1925       memset (&type_section, 0, sizeof (type_section));
1926       type_section.asection = sectp;
1927       type_section.size = bfd_get_section_size (sectp);
1928
1929       VEC_safe_push (dwarf2_section_info_def, dwarf2_per_objfile->types,
1930                      &type_section);
1931     }
1932   else if (section_is_p (sectp->name, &names->gdb_index))
1933     {
1934       dwarf2_per_objfile->gdb_index.asection = sectp;
1935       dwarf2_per_objfile->gdb_index.size = bfd_get_section_size (sectp);
1936     }
1937
1938   if ((bfd_get_section_flags (abfd, sectp) & SEC_LOAD)
1939       && bfd_section_vma (abfd, sectp) == 0)
1940     dwarf2_per_objfile->has_section_at_zero = 1;
1941 }
1942
1943 /* A helper function that decides whether a section is empty,
1944    or not present.  */
1945
1946 static int
1947 dwarf2_section_empty_p (struct dwarf2_section_info *info)
1948 {
1949   return info->asection == NULL || info->size == 0;
1950 }
1951
1952 /* Read the contents of the section INFO.
1953    OBJFILE is the main object file, but not necessarily the file where
1954    the section comes from.  E.g., for DWO files INFO->asection->owner
1955    is the bfd of the DWO file.
1956    If the section is compressed, uncompress it before returning.  */
1957
1958 static void
1959 dwarf2_read_section (struct objfile *objfile, struct dwarf2_section_info *info)
1960 {
1961   asection *sectp = info->asection;
1962   bfd *abfd;
1963   gdb_byte *buf, *retbuf;
1964   unsigned char header[4];
1965
1966   if (info->readin)
1967     return;
1968   info->buffer = NULL;
1969   info->readin = 1;
1970
1971   if (dwarf2_section_empty_p (info))
1972     return;
1973
1974   abfd = sectp->owner;
1975
1976   /* If the section has relocations, we must read it ourselves.
1977      Otherwise we attach it to the BFD.  */
1978   if ((sectp->flags & SEC_RELOC) == 0)
1979     {
1980       info->buffer = gdb_bfd_map_section (sectp, &info->size);
1981       return;
1982     }
1983
1984   buf = obstack_alloc (&objfile->objfile_obstack, info->size);
1985   info->buffer = buf;
1986
1987   /* When debugging .o files, we may need to apply relocations; see
1988      http://sourceware.org/ml/gdb-patches/2002-04/msg00136.html .
1989      We never compress sections in .o files, so we only need to
1990      try this when the section is not compressed.  */
1991   retbuf = symfile_relocate_debug_section (objfile, sectp, buf);
1992   if (retbuf != NULL)
1993     {
1994       info->buffer = retbuf;
1995       return;
1996     }
1997
1998   if (bfd_seek (abfd, sectp->filepos, SEEK_SET) != 0
1999       || bfd_bread (buf, info->size, abfd) != info->size)
2000     error (_("Dwarf Error: Can't read DWARF data from '%s'"),
2001            bfd_get_filename (abfd));
2002 }
2003
2004 /* A helper function that returns the size of a section in a safe way.
2005    If you are positive that the section has been read before using the
2006    size, then it is safe to refer to the dwarf2_section_info object's
2007    "size" field directly.  In other cases, you must call this
2008    function, because for compressed sections the size field is not set
2009    correctly until the section has been read.  */
2010
2011 static bfd_size_type
2012 dwarf2_section_size (struct objfile *objfile,
2013                      struct dwarf2_section_info *info)
2014 {
2015   if (!info->readin)
2016     dwarf2_read_section (objfile, info);
2017   return info->size;
2018 }
2019
2020 /* Fill in SECTP, BUFP and SIZEP with section info, given OBJFILE and
2021    SECTION_NAME.  */
2022
2023 void
2024 dwarf2_get_section_info (struct objfile *objfile,
2025                          enum dwarf2_section_enum sect,
2026                          asection **sectp, const gdb_byte **bufp,
2027                          bfd_size_type *sizep)
2028 {
2029   struct dwarf2_per_objfile *data
2030     = objfile_data (objfile, dwarf2_objfile_data_key);
2031   struct dwarf2_section_info *info;
2032
2033   /* We may see an objfile without any DWARF, in which case we just
2034      return nothing.  */
2035   if (data == NULL)
2036     {
2037       *sectp = NULL;
2038       *bufp = NULL;
2039       *sizep = 0;
2040       return;
2041     }
2042   switch (sect)
2043     {
2044     case DWARF2_DEBUG_FRAME:
2045       info = &data->frame;
2046       break;
2047     case DWARF2_EH_FRAME:
2048       info = &data->eh_frame;
2049       break;
2050     default:
2051       gdb_assert_not_reached ("unexpected section");
2052     }
2053
2054   dwarf2_read_section (objfile, info);
2055
2056   *sectp = info->asection;
2057   *bufp = info->buffer;
2058   *sizep = info->size;
2059 }
2060
2061 /* A helper function to find the sections for a .dwz file.  */
2062
2063 static void
2064 locate_dwz_sections (bfd *abfd, asection *sectp, void *arg)
2065 {
2066   struct dwz_file *dwz_file = arg;
2067
2068   /* Note that we only support the standard ELF names, because .dwz
2069      is ELF-only (at the time of writing).  */
2070   if (section_is_p (sectp->name, &dwarf2_elf_names.abbrev))
2071     {
2072       dwz_file->abbrev.asection = sectp;
2073       dwz_file->abbrev.size = bfd_get_section_size (sectp);
2074     }
2075   else if (section_is_p (sectp->name, &dwarf2_elf_names.info))
2076     {
2077       dwz_file->info.asection = sectp;
2078       dwz_file->info.size = bfd_get_section_size (sectp);
2079     }
2080   else if (section_is_p (sectp->name, &dwarf2_elf_names.str))
2081     {
2082       dwz_file->str.asection = sectp;
2083       dwz_file->str.size = bfd_get_section_size (sectp);
2084     }
2085   else if (section_is_p (sectp->name, &dwarf2_elf_names.line))
2086     {
2087       dwz_file->line.asection = sectp;
2088       dwz_file->line.size = bfd_get_section_size (sectp);
2089     }
2090   else if (section_is_p (sectp->name, &dwarf2_elf_names.macro))
2091     {
2092       dwz_file->macro.asection = sectp;
2093       dwz_file->macro.size = bfd_get_section_size (sectp);
2094     }
2095   else if (section_is_p (sectp->name, &dwarf2_elf_names.gdb_index))
2096     {
2097       dwz_file->gdb_index.asection = sectp;
2098       dwz_file->gdb_index.size = bfd_get_section_size (sectp);
2099     }
2100 }
2101
2102 /* Open the separate '.dwz' debug file, if needed.  Return NULL if
2103    there is no .gnu_debugaltlink section in the file.  Error if there
2104    is such a section but the file cannot be found.  */
2105
2106 static struct dwz_file *
2107 dwarf2_get_dwz_file (void)
2108 {
2109   bfd *dwz_bfd;
2110   char *data;
2111   struct cleanup *cleanup;
2112   const char *filename;
2113   struct dwz_file *result;
2114   unsigned long buildid;
2115
2116   if (dwarf2_per_objfile->dwz_file != NULL)
2117     return dwarf2_per_objfile->dwz_file;
2118
2119   bfd_set_error (bfd_error_no_error);
2120   data = bfd_get_alt_debug_link_info (dwarf2_per_objfile->objfile->obfd,
2121                                       &buildid);
2122   if (data == NULL)
2123     {
2124       if (bfd_get_error () == bfd_error_no_error)
2125         return NULL;
2126       error (_("could not read '.gnu_debugaltlink' section: %s"),
2127              bfd_errmsg (bfd_get_error ()));
2128     }
2129   cleanup = make_cleanup (xfree, data);
2130
2131   filename = (const char *) data;
2132   if (!IS_ABSOLUTE_PATH (filename))
2133     {
2134       char *abs = gdb_realpath (dwarf2_per_objfile->objfile->name);
2135       char *rel;
2136
2137       make_cleanup (xfree, abs);
2138       abs = ldirname (abs);
2139       make_cleanup (xfree, abs);
2140
2141       rel = concat (abs, SLASH_STRING, filename, (char *) NULL);
2142       make_cleanup (xfree, rel);
2143       filename = rel;
2144     }
2145
2146   /* The format is just a NUL-terminated file name, followed by the
2147      build-id.  For now, though, we ignore the build-id.  */
2148   dwz_bfd = gdb_bfd_open (filename, gnutarget, -1);
2149   if (dwz_bfd == NULL)
2150     error (_("could not read '%s': %s"), filename,
2151            bfd_errmsg (bfd_get_error ()));
2152
2153   if (!bfd_check_format (dwz_bfd, bfd_object))
2154     {
2155       gdb_bfd_unref (dwz_bfd);
2156       error (_("file '%s' was not usable: %s"), filename,
2157              bfd_errmsg (bfd_get_error ()));
2158     }
2159
2160   result = OBSTACK_ZALLOC (&dwarf2_per_objfile->objfile->objfile_obstack,
2161                            struct dwz_file);
2162   result->dwz_bfd = dwz_bfd;
2163
2164   bfd_map_over_sections (dwz_bfd, locate_dwz_sections, result);
2165
2166   do_cleanups (cleanup);
2167
2168   dwarf2_per_objfile->dwz_file = result;
2169   return result;
2170 }
2171 \f
2172 /* DWARF quick_symbols_functions support.  */
2173
2174 /* TUs can share .debug_line entries, and there can be a lot more TUs than
2175    unique line tables, so we maintain a separate table of all .debug_line
2176    derived entries to support the sharing.
2177    All the quick functions need is the list of file names.  We discard the
2178    line_header when we're done and don't need to record it here.  */
2179 struct quick_file_names
2180 {
2181   /* The data used to construct the hash key.  */
2182   struct stmt_list_hash hash;
2183
2184   /* The number of entries in file_names, real_names.  */
2185   unsigned int num_file_names;
2186
2187   /* The file names from the line table, after being run through
2188      file_full_name.  */
2189   const char **file_names;
2190
2191   /* The file names from the line table after being run through
2192      gdb_realpath.  These are computed lazily.  */
2193   const char **real_names;
2194 };
2195
2196 /* When using the index (and thus not using psymtabs), each CU has an
2197    object of this type.  This is used to hold information needed by
2198    the various "quick" methods.  */
2199 struct dwarf2_per_cu_quick_data
2200 {
2201   /* The file table.  This can be NULL if there was no file table
2202      or it's currently not read in.
2203      NOTE: This points into dwarf2_per_objfile->quick_file_names_table.  */
2204   struct quick_file_names *file_names;
2205
2206   /* The corresponding symbol table.  This is NULL if symbols for this
2207      CU have not yet been read.  */
2208   struct symtab *symtab;
2209
2210   /* A temporary mark bit used when iterating over all CUs in
2211      expand_symtabs_matching.  */
2212   unsigned int mark : 1;
2213
2214   /* True if we've tried to read the file table and found there isn't one.
2215      There will be no point in trying to read it again next time.  */
2216   unsigned int no_file_data : 1;
2217 };
2218
2219 /* Utility hash function for a stmt_list_hash.  */
2220
2221 static hashval_t
2222 hash_stmt_list_entry (const struct stmt_list_hash *stmt_list_hash)
2223 {
2224   hashval_t v = 0;
2225
2226   if (stmt_list_hash->dwo_unit != NULL)
2227     v += (uintptr_t) stmt_list_hash->dwo_unit->dwo_file;
2228   v += stmt_list_hash->line_offset.sect_off;
2229   return v;
2230 }
2231
2232 /* Utility equality function for a stmt_list_hash.  */
2233
2234 static int
2235 eq_stmt_list_entry (const struct stmt_list_hash *lhs,
2236                     const struct stmt_list_hash *rhs)
2237 {
2238   if ((lhs->dwo_unit != NULL) != (rhs->dwo_unit != NULL))
2239     return 0;
2240   if (lhs->dwo_unit != NULL
2241       && lhs->dwo_unit->dwo_file != rhs->dwo_unit->dwo_file)
2242     return 0;
2243
2244   return lhs->line_offset.sect_off == rhs->line_offset.sect_off;
2245 }
2246
2247 /* Hash function for a quick_file_names.  */
2248
2249 static hashval_t
2250 hash_file_name_entry (const void *e)
2251 {
2252   const struct quick_file_names *file_data = e;
2253
2254   return hash_stmt_list_entry (&file_data->hash);
2255 }
2256
2257 /* Equality function for a quick_file_names.  */
2258
2259 static int
2260 eq_file_name_entry (const void *a, const void *b)
2261 {
2262   const struct quick_file_names *ea = a;
2263   const struct quick_file_names *eb = b;
2264
2265   return eq_stmt_list_entry (&ea->hash, &eb->hash);
2266 }
2267
2268 /* Delete function for a quick_file_names.  */
2269
2270 static void
2271 delete_file_name_entry (void *e)
2272 {
2273   struct quick_file_names *file_data = e;
2274   int i;
2275
2276   for (i = 0; i < file_data->num_file_names; ++i)
2277     {
2278       xfree ((void*) file_data->file_names[i]);
2279       if (file_data->real_names)
2280         xfree ((void*) file_data->real_names[i]);
2281     }
2282
2283   /* The space for the struct itself lives on objfile_obstack,
2284      so we don't free it here.  */
2285 }
2286
2287 /* Create a quick_file_names hash table.  */
2288
2289 static htab_t
2290 create_quick_file_names_table (unsigned int nr_initial_entries)
2291 {
2292   return htab_create_alloc (nr_initial_entries,
2293                             hash_file_name_entry, eq_file_name_entry,
2294                             delete_file_name_entry, xcalloc, xfree);
2295 }
2296
2297 /* Read in PER_CU->CU.  This function is unrelated to symtabs, symtab would
2298    have to be created afterwards.  You should call age_cached_comp_units after
2299    processing PER_CU->CU.  dw2_setup must have been already called.  */
2300
2301 static void
2302 load_cu (struct dwarf2_per_cu_data *per_cu)
2303 {
2304   if (per_cu->is_debug_types)
2305     load_full_type_unit (per_cu);
2306   else
2307     load_full_comp_unit (per_cu, language_minimal);
2308
2309   gdb_assert (per_cu->cu != NULL);
2310
2311   dwarf2_find_base_address (per_cu->cu->dies, per_cu->cu);
2312 }
2313
2314 /* Read in the symbols for PER_CU.  */
2315
2316 static void
2317 dw2_do_instantiate_symtab (struct dwarf2_per_cu_data *per_cu)
2318 {
2319   struct cleanup *back_to;
2320
2321   /* Skip type_unit_groups, reading the type units they contain
2322      is handled elsewhere.  */
2323   if (IS_TYPE_UNIT_GROUP (per_cu))
2324     return;
2325
2326   back_to = make_cleanup (dwarf2_release_queue, NULL);
2327
2328   if (dwarf2_per_objfile->using_index
2329       ? per_cu->v.quick->symtab == NULL
2330       : (per_cu->v.psymtab == NULL || !per_cu->v.psymtab->readin))
2331     {
2332       queue_comp_unit (per_cu, language_minimal);
2333       load_cu (per_cu);
2334     }
2335
2336   process_queue ();
2337
2338   /* Age the cache, releasing compilation units that have not
2339      been used recently.  */
2340   age_cached_comp_units ();
2341
2342   do_cleanups (back_to);
2343 }
2344
2345 /* Ensure that the symbols for PER_CU have been read in.  OBJFILE is
2346    the objfile from which this CU came.  Returns the resulting symbol
2347    table.  */
2348
2349 static struct symtab *
2350 dw2_instantiate_symtab (struct dwarf2_per_cu_data *per_cu)
2351 {
2352   gdb_assert (dwarf2_per_objfile->using_index);
2353   if (!per_cu->v.quick->symtab)
2354     {
2355       struct cleanup *back_to = make_cleanup (free_cached_comp_units, NULL);
2356       increment_reading_symtab ();
2357       dw2_do_instantiate_symtab (per_cu);
2358       process_cu_includes ();
2359       do_cleanups (back_to);
2360     }
2361   return per_cu->v.quick->symtab;
2362 }
2363
2364 /* Return the CU given its index.
2365
2366    This is intended for loops like:
2367
2368    for (i = 0; i < (dwarf2_per_objfile->n_comp_units
2369                     + dwarf2_per_objfile->n_type_units); ++i)
2370      {
2371        struct dwarf2_per_cu_data *per_cu = dw2_get_cu (i);
2372
2373        ...;
2374      }
2375 */
2376
2377 static struct dwarf2_per_cu_data *
2378 dw2_get_cu (int index)
2379 {
2380   if (index >= dwarf2_per_objfile->n_comp_units)
2381     {
2382       index -= dwarf2_per_objfile->n_comp_units;
2383       gdb_assert (index < dwarf2_per_objfile->n_type_units);
2384       return &dwarf2_per_objfile->all_type_units[index]->per_cu;
2385     }
2386
2387   return dwarf2_per_objfile->all_comp_units[index];
2388 }
2389
2390 /* Return the primary CU given its index.
2391    The difference between this function and dw2_get_cu is in the handling
2392    of type units (TUs).  Here we return the type_unit_group object.
2393
2394    This is intended for loops like:
2395
2396    for (i = 0; i < (dwarf2_per_objfile->n_comp_units
2397                     + dwarf2_per_objfile->n_type_unit_groups); ++i)
2398      {
2399        struct dwarf2_per_cu_data *per_cu = dw2_get_primary_cu (i);
2400
2401        ...;
2402      }
2403 */
2404
2405 static struct dwarf2_per_cu_data *
2406 dw2_get_primary_cu (int index)
2407 {
2408   if (index >= dwarf2_per_objfile->n_comp_units)
2409     {
2410       index -= dwarf2_per_objfile->n_comp_units;
2411       gdb_assert (index < dwarf2_per_objfile->n_type_unit_groups);
2412       return &dwarf2_per_objfile->all_type_unit_groups[index]->per_cu;
2413     }
2414
2415   return dwarf2_per_objfile->all_comp_units[index];
2416 }
2417
2418 /* A helper for create_cus_from_index that handles a given list of
2419    CUs.  */
2420
2421 static void
2422 create_cus_from_index_list (struct objfile *objfile,
2423                             const gdb_byte *cu_list, offset_type n_elements,
2424                             struct dwarf2_section_info *section,
2425                             int is_dwz,
2426                             int base_offset)
2427 {
2428   offset_type i;
2429
2430   for (i = 0; i < n_elements; i += 2)
2431     {
2432       struct dwarf2_per_cu_data *the_cu;
2433       ULONGEST offset, length;
2434
2435       gdb_static_assert (sizeof (ULONGEST) >= 8);
2436       offset = extract_unsigned_integer (cu_list, 8, BFD_ENDIAN_LITTLE);
2437       length = extract_unsigned_integer (cu_list + 8, 8, BFD_ENDIAN_LITTLE);
2438       cu_list += 2 * 8;
2439
2440       the_cu = OBSTACK_ZALLOC (&objfile->objfile_obstack,
2441                                struct dwarf2_per_cu_data);
2442       the_cu->offset.sect_off = offset;
2443       the_cu->length = length;
2444       the_cu->objfile = objfile;
2445       the_cu->section = section;
2446       the_cu->v.quick = OBSTACK_ZALLOC (&objfile->objfile_obstack,
2447                                         struct dwarf2_per_cu_quick_data);
2448       the_cu->is_dwz = is_dwz;
2449       dwarf2_per_objfile->all_comp_units[base_offset + i / 2] = the_cu;
2450     }
2451 }
2452
2453 /* Read the CU list from the mapped index, and use it to create all
2454    the CU objects for this objfile.  */
2455
2456 static void
2457 create_cus_from_index (struct objfile *objfile,
2458                        const gdb_byte *cu_list, offset_type cu_list_elements,
2459                        const gdb_byte *dwz_list, offset_type dwz_elements)
2460 {
2461   struct dwz_file *dwz;
2462
2463   dwarf2_per_objfile->n_comp_units = (cu_list_elements + dwz_elements) / 2;
2464   dwarf2_per_objfile->all_comp_units
2465     = obstack_alloc (&objfile->objfile_obstack,
2466                      dwarf2_per_objfile->n_comp_units
2467                      * sizeof (struct dwarf2_per_cu_data *));
2468
2469   create_cus_from_index_list (objfile, cu_list, cu_list_elements,
2470                               &dwarf2_per_objfile->info, 0, 0);
2471
2472   if (dwz_elements == 0)
2473     return;
2474
2475   dwz = dwarf2_get_dwz_file ();
2476   create_cus_from_index_list (objfile, dwz_list, dwz_elements, &dwz->info, 1,
2477                               cu_list_elements / 2);
2478 }
2479
2480 /* Create the signatured type hash table from the index.  */
2481
2482 static void
2483 create_signatured_type_table_from_index (struct objfile *objfile,
2484                                          struct dwarf2_section_info *section,
2485                                          const gdb_byte *bytes,
2486                                          offset_type elements)
2487 {
2488   offset_type i;
2489   htab_t sig_types_hash;
2490
2491   dwarf2_per_objfile->n_type_units = elements / 3;
2492   dwarf2_per_objfile->all_type_units
2493     = xmalloc (dwarf2_per_objfile->n_type_units
2494                * sizeof (struct signatured_type *));
2495
2496   sig_types_hash = allocate_signatured_type_table (objfile);
2497
2498   for (i = 0; i < elements; i += 3)
2499     {
2500       struct signatured_type *sig_type;
2501       ULONGEST offset, type_offset_in_tu, signature;
2502       void **slot;
2503
2504       gdb_static_assert (sizeof (ULONGEST) >= 8);
2505       offset = extract_unsigned_integer (bytes, 8, BFD_ENDIAN_LITTLE);
2506       type_offset_in_tu = extract_unsigned_integer (bytes + 8, 8,
2507                                                     BFD_ENDIAN_LITTLE);
2508       signature = extract_unsigned_integer (bytes + 16, 8, BFD_ENDIAN_LITTLE);
2509       bytes += 3 * 8;
2510
2511       sig_type = OBSTACK_ZALLOC (&objfile->objfile_obstack,
2512                                  struct signatured_type);
2513       sig_type->signature = signature;
2514       sig_type->type_offset_in_tu.cu_off = type_offset_in_tu;
2515       sig_type->per_cu.is_debug_types = 1;
2516       sig_type->per_cu.section = section;
2517       sig_type->per_cu.offset.sect_off = offset;
2518       sig_type->per_cu.objfile = objfile;
2519       sig_type->per_cu.v.quick
2520         = OBSTACK_ZALLOC (&objfile->objfile_obstack,
2521                           struct dwarf2_per_cu_quick_data);
2522
2523       slot = htab_find_slot (sig_types_hash, sig_type, INSERT);
2524       *slot = sig_type;
2525
2526       dwarf2_per_objfile->all_type_units[i / 3] = sig_type;
2527     }
2528
2529   dwarf2_per_objfile->signatured_types = sig_types_hash;
2530 }
2531
2532 /* Read the address map data from the mapped index, and use it to
2533    populate the objfile's psymtabs_addrmap.  */
2534
2535 static void
2536 create_addrmap_from_index (struct objfile *objfile, struct mapped_index *index)
2537 {
2538   const gdb_byte *iter, *end;
2539   struct obstack temp_obstack;
2540   struct addrmap *mutable_map;
2541   struct cleanup *cleanup;
2542   CORE_ADDR baseaddr;
2543
2544   obstack_init (&temp_obstack);
2545   cleanup = make_cleanup_obstack_free (&temp_obstack);
2546   mutable_map = addrmap_create_mutable (&temp_obstack);
2547
2548   iter = index->address_table;
2549   end = iter + index->address_table_size;
2550
2551   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
2552
2553   while (iter < end)
2554     {
2555       ULONGEST hi, lo, cu_index;
2556       lo = extract_unsigned_integer (iter, 8, BFD_ENDIAN_LITTLE);
2557       iter += 8;
2558       hi = extract_unsigned_integer (iter, 8, BFD_ENDIAN_LITTLE);
2559       iter += 8;
2560       cu_index = extract_unsigned_integer (iter, 4, BFD_ENDIAN_LITTLE);
2561       iter += 4;
2562
2563       if (cu_index < dwarf2_per_objfile->n_comp_units)
2564         {
2565           addrmap_set_empty (mutable_map, lo + baseaddr, hi + baseaddr - 1,
2566                              dw2_get_cu (cu_index));
2567         }
2568       else
2569         {
2570           complaint (&symfile_complaints,
2571                      _(".gdb_index address table has invalid CU number %u"),
2572                      (unsigned) cu_index);
2573         }
2574     }
2575
2576   objfile->psymtabs_addrmap = addrmap_create_fixed (mutable_map,
2577                                                     &objfile->objfile_obstack);
2578   do_cleanups (cleanup);
2579 }
2580
2581 /* The hash function for strings in the mapped index.  This is the same as
2582    SYMBOL_HASH_NEXT, but we keep a separate copy to maintain control over the
2583    implementation.  This is necessary because the hash function is tied to the
2584    format of the mapped index file.  The hash values do not have to match with
2585    SYMBOL_HASH_NEXT.
2586    
2587    Use INT_MAX for INDEX_VERSION if you generate the current index format.  */
2588
2589 static hashval_t
2590 mapped_index_string_hash (int index_version, const void *p)
2591 {
2592   const unsigned char *str = (const unsigned char *) p;
2593   hashval_t r = 0;
2594   unsigned char c;
2595
2596   while ((c = *str++) != 0)
2597     {
2598       if (index_version >= 5)
2599         c = tolower (c);
2600       r = r * 67 + c - 113;
2601     }
2602
2603   return r;
2604 }
2605
2606 /* Find a slot in the mapped index INDEX for the object named NAME.
2607    If NAME is found, set *VEC_OUT to point to the CU vector in the
2608    constant pool and return 1.  If NAME cannot be found, return 0.  */
2609
2610 static int
2611 find_slot_in_mapped_hash (struct mapped_index *index, const char *name,
2612                           offset_type **vec_out)
2613 {
2614   struct cleanup *back_to = make_cleanup (null_cleanup, 0);
2615   offset_type hash;
2616   offset_type slot, step;
2617   int (*cmp) (const char *, const char *);
2618
2619   if (current_language->la_language == language_cplus
2620       || current_language->la_language == language_java
2621       || current_language->la_language == language_fortran)
2622     {
2623       /* NAME is already canonical.  Drop any qualifiers as .gdb_index does
2624          not contain any.  */
2625       const char *paren = strchr (name, '(');
2626
2627       if (paren)
2628         {
2629           char *dup;
2630
2631           dup = xmalloc (paren - name + 1);
2632           memcpy (dup, name, paren - name);
2633           dup[paren - name] = 0;
2634
2635           make_cleanup (xfree, dup);
2636           name = dup;
2637         }
2638     }
2639
2640   /* Index version 4 did not support case insensitive searches.  But the
2641      indices for case insensitive languages are built in lowercase, therefore
2642      simulate our NAME being searched is also lowercased.  */
2643   hash = mapped_index_string_hash ((index->version == 4
2644                                     && case_sensitivity == case_sensitive_off
2645                                     ? 5 : index->version),
2646                                    name);
2647
2648   slot = hash & (index->symbol_table_slots - 1);
2649   step = ((hash * 17) & (index->symbol_table_slots - 1)) | 1;
2650   cmp = (case_sensitivity == case_sensitive_on ? strcmp : strcasecmp);
2651
2652   for (;;)
2653     {
2654       /* Convert a slot number to an offset into the table.  */
2655       offset_type i = 2 * slot;
2656       const char *str;
2657       if (index->symbol_table[i] == 0 && index->symbol_table[i + 1] == 0)
2658         {
2659           do_cleanups (back_to);
2660           return 0;
2661         }
2662
2663       str = index->constant_pool + MAYBE_SWAP (index->symbol_table[i]);
2664       if (!cmp (name, str))
2665         {
2666           *vec_out = (offset_type *) (index->constant_pool
2667                                       + MAYBE_SWAP (index->symbol_table[i + 1]));
2668           do_cleanups (back_to);
2669           return 1;
2670         }
2671
2672       slot = (slot + step) & (index->symbol_table_slots - 1);
2673     }
2674 }
2675
2676 /* A helper function that reads the .gdb_index from SECTION and fills
2677    in MAP.  FILENAME is the name of the file containing the section;
2678    it is used for error reporting.  DEPRECATED_OK is nonzero if it is
2679    ok to use deprecated sections.
2680
2681    CU_LIST, CU_LIST_ELEMENTS, TYPES_LIST, and TYPES_LIST_ELEMENTS are
2682    out parameters that are filled in with information about the CU and
2683    TU lists in the section.
2684
2685    Returns 1 if all went well, 0 otherwise.  */
2686
2687 static int
2688 read_index_from_section (struct objfile *objfile,
2689                          const char *filename,
2690                          int deprecated_ok,
2691                          struct dwarf2_section_info *section,
2692                          struct mapped_index *map,
2693                          const gdb_byte **cu_list,
2694                          offset_type *cu_list_elements,
2695                          const gdb_byte **types_list,
2696                          offset_type *types_list_elements)
2697 {
2698   const gdb_byte *addr;
2699   offset_type version;
2700   offset_type *metadata;
2701   int i;
2702
2703   if (dwarf2_section_empty_p (section))
2704     return 0;
2705
2706   /* Older elfutils strip versions could keep the section in the main
2707      executable while splitting it for the separate debug info file.  */
2708   if ((bfd_get_file_flags (section->asection) & SEC_HAS_CONTENTS) == 0)
2709     return 0;
2710
2711   dwarf2_read_section (objfile, section);
2712
2713   addr = section->buffer;
2714   /* Version check.  */
2715   version = MAYBE_SWAP (*(offset_type *) addr);
2716   /* Versions earlier than 3 emitted every copy of a psymbol.  This
2717      causes the index to behave very poorly for certain requests.  Version 3
2718      contained incomplete addrmap.  So, it seems better to just ignore such
2719      indices.  */
2720   if (version < 4)
2721     {
2722       static int warning_printed = 0;
2723       if (!warning_printed)
2724         {
2725           warning (_("Skipping obsolete .gdb_index section in %s."),
2726                    filename);
2727           warning_printed = 1;
2728         }
2729       return 0;
2730     }
2731   /* Index version 4 uses a different hash function than index version
2732      5 and later.
2733
2734      Versions earlier than 6 did not emit psymbols for inlined
2735      functions.  Using these files will cause GDB not to be able to
2736      set breakpoints on inlined functions by name, so we ignore these
2737      indices unless the user has done
2738      "set use-deprecated-index-sections on".  */
2739   if (version < 6 && !deprecated_ok)
2740     {
2741       static int warning_printed = 0;
2742       if (!warning_printed)
2743         {
2744           warning (_("\
2745 Skipping deprecated .gdb_index section in %s.\n\
2746 Do \"set use-deprecated-index-sections on\" before the file is read\n\
2747 to use the section anyway."),
2748                    filename);
2749           warning_printed = 1;
2750         }
2751       return 0;
2752     }
2753   /* Version 7 indices generated by gold refer to the CU for a symbol instead
2754      of the TU (for symbols coming from TUs).  It's just a performance bug, and
2755      we can't distinguish gdb-generated indices from gold-generated ones, so
2756      nothing to do here.  */
2757
2758   /* Indexes with higher version than the one supported by GDB may be no
2759      longer backward compatible.  */
2760   if (version > 8)
2761     return 0;
2762
2763   map->version = version;
2764   map->total_size = section->size;
2765
2766   metadata = (offset_type *) (addr + sizeof (offset_type));
2767
2768   i = 0;
2769   *cu_list = addr + MAYBE_SWAP (metadata[i]);
2770   *cu_list_elements = ((MAYBE_SWAP (metadata[i + 1]) - MAYBE_SWAP (metadata[i]))
2771                        / 8);
2772   ++i;
2773
2774   *types_list = addr + MAYBE_SWAP (metadata[i]);
2775   *types_list_elements = ((MAYBE_SWAP (metadata[i + 1])
2776                            - MAYBE_SWAP (metadata[i]))
2777                           / 8);
2778   ++i;
2779
2780   map->address_table = addr + MAYBE_SWAP (metadata[i]);
2781   map->address_table_size = (MAYBE_SWAP (metadata[i + 1])
2782                              - MAYBE_SWAP (metadata[i]));
2783   ++i;
2784
2785   map->symbol_table = (offset_type *) (addr + MAYBE_SWAP (metadata[i]));
2786   map->symbol_table_slots = ((MAYBE_SWAP (metadata[i + 1])
2787                               - MAYBE_SWAP (metadata[i]))
2788                              / (2 * sizeof (offset_type)));
2789   ++i;
2790
2791   map->constant_pool = (char *) (addr + MAYBE_SWAP (metadata[i]));
2792
2793   return 1;
2794 }
2795
2796
2797 /* Read the index file.  If everything went ok, initialize the "quick"
2798    elements of all the CUs and return 1.  Otherwise, return 0.  */
2799
2800 static int
2801 dwarf2_read_index (struct objfile *objfile)
2802 {
2803   struct mapped_index local_map, *map;
2804   const gdb_byte *cu_list, *types_list, *dwz_list = NULL;
2805   offset_type cu_list_elements, types_list_elements, dwz_list_elements = 0;
2806   struct dwz_file *dwz;
2807
2808   if (!read_index_from_section (objfile, objfile->name,
2809                                 use_deprecated_index_sections,
2810                                 &dwarf2_per_objfile->gdb_index, &local_map,
2811                                 &cu_list, &cu_list_elements,
2812                                 &types_list, &types_list_elements))
2813     return 0;
2814
2815   /* Don't use the index if it's empty.  */
2816   if (local_map.symbol_table_slots == 0)
2817     return 0;
2818
2819   /* If there is a .dwz file, read it so we can get its CU list as
2820      well.  */
2821   dwz = dwarf2_get_dwz_file ();
2822   if (dwz != NULL)
2823     {
2824       struct mapped_index dwz_map;
2825       const gdb_byte *dwz_types_ignore;
2826       offset_type dwz_types_elements_ignore;
2827
2828       if (!read_index_from_section (objfile, bfd_get_filename (dwz->dwz_bfd),
2829                                     1,
2830                                     &dwz->gdb_index, &dwz_map,
2831                                     &dwz_list, &dwz_list_elements,
2832                                     &dwz_types_ignore,
2833                                     &dwz_types_elements_ignore))
2834         {
2835           warning (_("could not read '.gdb_index' section from %s; skipping"),
2836                    bfd_get_filename (dwz->dwz_bfd));
2837           return 0;
2838         }
2839     }
2840
2841   create_cus_from_index (objfile, cu_list, cu_list_elements, dwz_list,
2842                          dwz_list_elements);
2843
2844   if (types_list_elements)
2845     {
2846       struct dwarf2_section_info *section;
2847
2848       /* We can only handle a single .debug_types when we have an
2849          index.  */
2850       if (VEC_length (dwarf2_section_info_def, dwarf2_per_objfile->types) != 1)
2851         return 0;
2852
2853       section = VEC_index (dwarf2_section_info_def,
2854                            dwarf2_per_objfile->types, 0);
2855
2856       create_signatured_type_table_from_index (objfile, section, types_list,
2857                                                types_list_elements);
2858     }
2859
2860   create_addrmap_from_index (objfile, &local_map);
2861
2862   map = obstack_alloc (&objfile->objfile_obstack, sizeof (struct mapped_index));
2863   *map = local_map;
2864
2865   dwarf2_per_objfile->index_table = map;
2866   dwarf2_per_objfile->using_index = 1;
2867   dwarf2_per_objfile->quick_file_names_table =
2868     create_quick_file_names_table (dwarf2_per_objfile->n_comp_units);
2869
2870   return 1;
2871 }
2872
2873 /* A helper for the "quick" functions which sets the global
2874    dwarf2_per_objfile according to OBJFILE.  */
2875
2876 static void
2877 dw2_setup (struct objfile *objfile)
2878 {
2879   dwarf2_per_objfile = objfile_data (objfile, dwarf2_objfile_data_key);
2880   gdb_assert (dwarf2_per_objfile);
2881 }
2882
2883 /* die_reader_func for dw2_get_file_names.  */
2884
2885 static void
2886 dw2_get_file_names_reader (const struct die_reader_specs *reader,
2887                            const gdb_byte *info_ptr,
2888                            struct die_info *comp_unit_die,
2889                            int has_children,
2890                            void *data)
2891 {
2892   struct dwarf2_cu *cu = reader->cu;
2893   struct dwarf2_per_cu_data *this_cu = cu->per_cu;  
2894   struct objfile *objfile = dwarf2_per_objfile->objfile;
2895   struct dwarf2_per_cu_data *lh_cu;
2896   struct line_header *lh;
2897   struct attribute *attr;
2898   int i;
2899   const char *name, *comp_dir;
2900   void **slot;
2901   struct quick_file_names *qfn;
2902   unsigned int line_offset;
2903
2904   gdb_assert (! this_cu->is_debug_types);
2905
2906   /* Our callers never want to match partial units -- instead they
2907      will match the enclosing full CU.  */
2908   if (comp_unit_die->tag == DW_TAG_partial_unit)
2909     {
2910       this_cu->v.quick->no_file_data = 1;
2911       return;
2912     }
2913
2914   lh_cu = this_cu;
2915   lh = NULL;
2916   slot = NULL;
2917   line_offset = 0;
2918
2919   attr = dwarf2_attr (comp_unit_die, DW_AT_stmt_list, cu);
2920   if (attr)
2921     {
2922       struct quick_file_names find_entry;
2923
2924       line_offset = DW_UNSND (attr);
2925
2926       /* We may have already read in this line header (TU line header sharing).
2927          If we have we're done.  */
2928       find_entry.hash.dwo_unit = cu->dwo_unit;
2929       find_entry.hash.line_offset.sect_off = line_offset;
2930       slot = htab_find_slot (dwarf2_per_objfile->quick_file_names_table,
2931                              &find_entry, INSERT);
2932       if (*slot != NULL)
2933         {
2934           lh_cu->v.quick->file_names = *slot;
2935           return;
2936         }
2937
2938       lh = dwarf_decode_line_header (line_offset, cu);
2939     }
2940   if (lh == NULL)
2941     {
2942       lh_cu->v.quick->no_file_data = 1;
2943       return;
2944     }
2945
2946   qfn = obstack_alloc (&objfile->objfile_obstack, sizeof (*qfn));
2947   qfn->hash.dwo_unit = cu->dwo_unit;
2948   qfn->hash.line_offset.sect_off = line_offset;
2949   gdb_assert (slot != NULL);
2950   *slot = qfn;
2951
2952   find_file_and_directory (comp_unit_die, cu, &name, &comp_dir);
2953
2954   qfn->num_file_names = lh->num_file_names;
2955   qfn->file_names = obstack_alloc (&objfile->objfile_obstack,
2956                                    lh->num_file_names * sizeof (char *));
2957   for (i = 0; i < lh->num_file_names; ++i)
2958     qfn->file_names[i] = file_full_name (i + 1, lh, comp_dir);
2959   qfn->real_names = NULL;
2960
2961   free_line_header (lh);
2962
2963   lh_cu->v.quick->file_names = qfn;
2964 }
2965
2966 /* A helper for the "quick" functions which attempts to read the line
2967    table for THIS_CU.  */
2968
2969 static struct quick_file_names *
2970 dw2_get_file_names (struct dwarf2_per_cu_data *this_cu)
2971 {
2972   /* This should never be called for TUs.  */
2973   gdb_assert (! this_cu->is_debug_types);
2974   /* Nor type unit groups.  */
2975   gdb_assert (! IS_TYPE_UNIT_GROUP (this_cu));
2976
2977   if (this_cu->v.quick->file_names != NULL)
2978     return this_cu->v.quick->file_names;
2979   /* If we know there is no line data, no point in looking again.  */
2980   if (this_cu->v.quick->no_file_data)
2981     return NULL;
2982
2983   init_cutu_and_read_dies_simple (this_cu, dw2_get_file_names_reader, NULL);
2984
2985   if (this_cu->v.quick->no_file_data)
2986     return NULL;
2987   return this_cu->v.quick->file_names;
2988 }
2989
2990 /* A helper for the "quick" functions which computes and caches the
2991    real path for a given file name from the line table.  */
2992
2993 static const char *
2994 dw2_get_real_path (struct objfile *objfile,
2995                    struct quick_file_names *qfn, int index)
2996 {
2997   if (qfn->real_names == NULL)
2998     qfn->real_names = OBSTACK_CALLOC (&objfile->objfile_obstack,
2999                                       qfn->num_file_names, sizeof (char *));
3000
3001   if (qfn->real_names[index] == NULL)
3002     qfn->real_names[index] = gdb_realpath (qfn->file_names[index]);
3003
3004   return qfn->real_names[index];
3005 }
3006
3007 static struct symtab *
3008 dw2_find_last_source_symtab (struct objfile *objfile)
3009 {
3010   int index;
3011
3012   dw2_setup (objfile);
3013   index = dwarf2_per_objfile->n_comp_units - 1;
3014   return dw2_instantiate_symtab (dw2_get_cu (index));
3015 }
3016
3017 /* Traversal function for dw2_forget_cached_source_info.  */
3018
3019 static int
3020 dw2_free_cached_file_names (void **slot, void *info)
3021 {
3022   struct quick_file_names *file_data = (struct quick_file_names *) *slot;
3023
3024   if (file_data->real_names)
3025     {
3026       int i;
3027
3028       for (i = 0; i < file_data->num_file_names; ++i)
3029         {
3030           xfree ((void*) file_data->real_names[i]);
3031           file_data->real_names[i] = NULL;
3032         }
3033     }
3034
3035   return 1;
3036 }
3037
3038 static void
3039 dw2_forget_cached_source_info (struct objfile *objfile)
3040 {
3041   dw2_setup (objfile);
3042
3043   htab_traverse_noresize (dwarf2_per_objfile->quick_file_names_table,
3044                           dw2_free_cached_file_names, NULL);
3045 }
3046
3047 /* Helper function for dw2_map_symtabs_matching_filename that expands
3048    the symtabs and calls the iterator.  */
3049
3050 static int
3051 dw2_map_expand_apply (struct objfile *objfile,
3052                       struct dwarf2_per_cu_data *per_cu,
3053                       const char *name, const char *real_path,
3054                       int (*callback) (struct symtab *, void *),
3055                       void *data)
3056 {
3057   struct symtab *last_made = objfile->symtabs;
3058
3059   /* Don't visit already-expanded CUs.  */
3060   if (per_cu->v.quick->symtab)
3061     return 0;
3062
3063   /* This may expand more than one symtab, and we want to iterate over
3064      all of them.  */
3065   dw2_instantiate_symtab (per_cu);
3066
3067   return iterate_over_some_symtabs (name, real_path, callback, data,
3068                                     objfile->symtabs, last_made);
3069 }
3070
3071 /* Implementation of the map_symtabs_matching_filename method.  */
3072
3073 static int
3074 dw2_map_symtabs_matching_filename (struct objfile *objfile, const char *name,
3075                                    const char *real_path,
3076                                    int (*callback) (struct symtab *, void *),
3077                                    void *data)
3078 {
3079   int i;
3080   const char *name_basename = lbasename (name);
3081
3082   dw2_setup (objfile);
3083
3084   /* The rule is CUs specify all the files, including those used by
3085      any TU, so there's no need to scan TUs here.  */
3086
3087   for (i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
3088     {
3089       int j;
3090       struct dwarf2_per_cu_data *per_cu = dw2_get_primary_cu (i);
3091       struct quick_file_names *file_data;
3092
3093       /* We only need to look at symtabs not already expanded.  */
3094       if (per_cu->v.quick->symtab)
3095         continue;
3096
3097       file_data = dw2_get_file_names (per_cu);
3098       if (file_data == NULL)
3099         continue;
3100
3101       for (j = 0; j < file_data->num_file_names; ++j)
3102         {
3103           const char *this_name = file_data->file_names[j];
3104           const char *this_real_name;
3105
3106           if (compare_filenames_for_search (this_name, name))
3107             {
3108               if (dw2_map_expand_apply (objfile, per_cu, name, real_path,
3109                                         callback, data))
3110                 return 1;
3111               continue;
3112             }
3113
3114           /* Before we invoke realpath, which can get expensive when many
3115              files are involved, do a quick comparison of the basenames.  */
3116           if (! basenames_may_differ
3117               && FILENAME_CMP (lbasename (this_name), name_basename) != 0)
3118             continue;
3119
3120           this_real_name = dw2_get_real_path (objfile, file_data, j);
3121           if (compare_filenames_for_search (this_real_name, name))
3122             {
3123               if (dw2_map_expand_apply (objfile, per_cu, name, real_path,
3124                                         callback, data))
3125                 return 1;
3126               continue;
3127             }
3128
3129           if (real_path != NULL)
3130             {
3131               gdb_assert (IS_ABSOLUTE_PATH (real_path));
3132               gdb_assert (IS_ABSOLUTE_PATH (name));
3133               if (this_real_name != NULL
3134                   && FILENAME_CMP (real_path, this_real_name) == 0)
3135                 {
3136                   if (dw2_map_expand_apply (objfile, per_cu, name, real_path,
3137                                             callback, data))
3138                     return 1;
3139                   continue;
3140                 }
3141             }
3142         }
3143     }
3144
3145   return 0;
3146 }
3147
3148 /* Struct used to manage iterating over all CUs looking for a symbol.  */
3149
3150 struct dw2_symtab_iterator
3151 {
3152   /* The internalized form of .gdb_index.  */
3153   struct mapped_index *index;
3154   /* If non-zero, only look for symbols that match BLOCK_INDEX.  */
3155   int want_specific_block;
3156   /* One of GLOBAL_BLOCK or STATIC_BLOCK.
3157      Unused if !WANT_SPECIFIC_BLOCK.  */
3158   int block_index;
3159   /* The kind of symbol we're looking for.  */
3160   domain_enum domain;
3161   /* The list of CUs from the index entry of the symbol,
3162      or NULL if not found.  */
3163   offset_type *vec;
3164   /* The next element in VEC to look at.  */
3165   int next;
3166   /* The number of elements in VEC, or zero if there is no match.  */
3167   int length;
3168 };
3169
3170 /* Initialize the index symtab iterator ITER.
3171    If WANT_SPECIFIC_BLOCK is non-zero, only look for symbols
3172    in block BLOCK_INDEX.  Otherwise BLOCK_INDEX is ignored.  */
3173
3174 static void
3175 dw2_symtab_iter_init (struct dw2_symtab_iterator *iter,
3176                       struct mapped_index *index,
3177                       int want_specific_block,
3178                       int block_index,
3179                       domain_enum domain,
3180                       const char *name)
3181 {
3182   iter->index = index;
3183   iter->want_specific_block = want_specific_block;
3184   iter->block_index = block_index;
3185   iter->domain = domain;
3186   iter->next = 0;
3187
3188   if (find_slot_in_mapped_hash (index, name, &iter->vec))
3189     iter->length = MAYBE_SWAP (*iter->vec);
3190   else
3191     {
3192       iter->vec = NULL;
3193       iter->length = 0;
3194     }
3195 }
3196
3197 /* Return the next matching CU or NULL if there are no more.  */
3198
3199 static struct dwarf2_per_cu_data *
3200 dw2_symtab_iter_next (struct dw2_symtab_iterator *iter)
3201 {
3202   for ( ; iter->next < iter->length; ++iter->next)
3203     {
3204       offset_type cu_index_and_attrs =
3205         MAYBE_SWAP (iter->vec[iter->next + 1]);
3206       offset_type cu_index = GDB_INDEX_CU_VALUE (cu_index_and_attrs);
3207       struct dwarf2_per_cu_data *per_cu;
3208       int want_static = iter->block_index != GLOBAL_BLOCK;
3209       /* This value is only valid for index versions >= 7.  */
3210       int is_static = GDB_INDEX_SYMBOL_STATIC_VALUE (cu_index_and_attrs);
3211       gdb_index_symbol_kind symbol_kind =
3212         GDB_INDEX_SYMBOL_KIND_VALUE (cu_index_and_attrs);
3213       /* Only check the symbol attributes if they're present.
3214          Indices prior to version 7 don't record them,
3215          and indices >= 7 may elide them for certain symbols
3216          (gold does this).  */
3217       int attrs_valid =
3218         (iter->index->version >= 7
3219          && symbol_kind != GDB_INDEX_SYMBOL_KIND_NONE);
3220
3221       /* Don't crash on bad data.  */
3222       if (cu_index >= (dwarf2_per_objfile->n_comp_units
3223                        + dwarf2_per_objfile->n_type_units))
3224         {
3225           complaint (&symfile_complaints,
3226                      _(".gdb_index entry has bad CU index"
3227                        " [in module %s]"), dwarf2_per_objfile->objfile->name);
3228           continue;
3229         }
3230
3231       per_cu = dw2_get_cu (cu_index);
3232
3233       /* Skip if already read in.  */
3234       if (per_cu->v.quick->symtab)
3235         continue;
3236
3237       if (attrs_valid
3238           && iter->want_specific_block
3239           && want_static != is_static)
3240         continue;
3241
3242       /* Only check the symbol's kind if it has one.  */
3243       if (attrs_valid)
3244         {
3245           switch (iter->domain)
3246             {
3247             case VAR_DOMAIN:
3248               if (symbol_kind != GDB_INDEX_SYMBOL_KIND_VARIABLE
3249                   && symbol_kind != GDB_INDEX_SYMBOL_KIND_FUNCTION
3250                   /* Some types are also in VAR_DOMAIN.  */
3251                   && symbol_kind != GDB_INDEX_SYMBOL_KIND_TYPE)
3252                 continue;
3253               break;
3254             case STRUCT_DOMAIN:
3255               if (symbol_kind != GDB_INDEX_SYMBOL_KIND_TYPE)
3256                 continue;
3257               break;
3258             case LABEL_DOMAIN:
3259               if (symbol_kind != GDB_INDEX_SYMBOL_KIND_OTHER)
3260                 continue;
3261               break;
3262             default:
3263               break;
3264             }
3265         }
3266
3267       ++iter->next;
3268       return per_cu;
3269     }
3270
3271   return NULL;
3272 }
3273
3274 static struct symtab *
3275 dw2_lookup_symbol (struct objfile *objfile, int block_index,
3276                    const char *name, domain_enum domain)
3277 {
3278   struct symtab *stab_best = NULL;
3279   struct mapped_index *index;
3280
3281   dw2_setup (objfile);
3282
3283   index = dwarf2_per_objfile->index_table;
3284
3285   /* index is NULL if OBJF_READNOW.  */
3286   if (index)
3287     {
3288       struct dw2_symtab_iterator iter;
3289       struct dwarf2_per_cu_data *per_cu;
3290
3291       dw2_symtab_iter_init (&iter, index, 1, block_index, domain, name);
3292
3293       while ((per_cu = dw2_symtab_iter_next (&iter)) != NULL)
3294         {
3295           struct symbol *sym = NULL;
3296           struct symtab *stab = dw2_instantiate_symtab (per_cu);
3297
3298           /* Some caution must be observed with overloaded functions
3299              and methods, since the index will not contain any overload
3300              information (but NAME might contain it).  */
3301           if (stab->primary)
3302             {
3303               struct blockvector *bv = BLOCKVECTOR (stab);
3304               struct block *block = BLOCKVECTOR_BLOCK (bv, block_index);
3305
3306               sym = lookup_block_symbol (block, name, domain);
3307             }
3308
3309           if (sym && strcmp_iw (SYMBOL_SEARCH_NAME (sym), name) == 0)
3310             {
3311               if (!TYPE_IS_OPAQUE (SYMBOL_TYPE (sym)))
3312                 return stab;
3313
3314               stab_best = stab;
3315             }
3316
3317           /* Keep looking through other CUs.  */
3318         }
3319     }
3320
3321   return stab_best;
3322 }
3323
3324 static void
3325 dw2_print_stats (struct objfile *objfile)
3326 {
3327   int i, total, count;
3328
3329   dw2_setup (objfile);
3330   total = dwarf2_per_objfile->n_comp_units + dwarf2_per_objfile->n_type_units;
3331   count = 0;
3332   for (i = 0; i < total; ++i)
3333     {
3334       struct dwarf2_per_cu_data *per_cu = dw2_get_cu (i);
3335
3336       if (!per_cu->v.quick->symtab)
3337         ++count;
3338     }
3339   printf_filtered (_("  Number of read CUs: %d\n"), total - count);
3340   printf_filtered (_("  Number of unread CUs: %d\n"), count);
3341 }
3342
3343 static void
3344 dw2_dump (struct objfile *objfile)
3345 {
3346   /* Nothing worth printing.  */
3347 }
3348
3349 static void
3350 dw2_relocate (struct objfile *objfile,
3351               const struct section_offsets *new_offsets,
3352               const struct section_offsets *delta)
3353 {
3354   /* There's nothing to relocate here.  */
3355 }
3356
3357 static void
3358 dw2_expand_symtabs_for_function (struct objfile *objfile,
3359                                  const char *func_name)
3360 {
3361   struct mapped_index *index;
3362
3363   dw2_setup (objfile);
3364
3365   index = dwarf2_per_objfile->index_table;
3366
3367   /* index is NULL if OBJF_READNOW.  */
3368   if (index)
3369     {
3370       struct dw2_symtab_iterator iter;
3371       struct dwarf2_per_cu_data *per_cu;
3372
3373       /* Note: It doesn't matter what we pass for block_index here.  */
3374       dw2_symtab_iter_init (&iter, index, 0, GLOBAL_BLOCK, VAR_DOMAIN,
3375                             func_name);
3376
3377       while ((per_cu = dw2_symtab_iter_next (&iter)) != NULL)
3378         dw2_instantiate_symtab (per_cu);
3379     }
3380 }
3381
3382 static void
3383 dw2_expand_all_symtabs (struct objfile *objfile)
3384 {
3385   int i;
3386
3387   dw2_setup (objfile);
3388
3389   for (i = 0; i < (dwarf2_per_objfile->n_comp_units
3390                    + dwarf2_per_objfile->n_type_units); ++i)
3391     {
3392       struct dwarf2_per_cu_data *per_cu = dw2_get_cu (i);
3393
3394       dw2_instantiate_symtab (per_cu);
3395     }
3396 }
3397
3398 static void
3399 dw2_expand_symtabs_with_fullname (struct objfile *objfile,
3400                                   const char *fullname)
3401 {
3402   int i;
3403
3404   dw2_setup (objfile);
3405
3406   /* We don't need to consider type units here.
3407      This is only called for examining code, e.g. expand_line_sal.
3408      There can be an order of magnitude (or more) more type units
3409      than comp units, and we avoid them if we can.  */
3410
3411   for (i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
3412     {
3413       int j;
3414       struct dwarf2_per_cu_data *per_cu = dw2_get_cu (i);
3415       struct quick_file_names *file_data;
3416
3417       /* We only need to look at symtabs not already expanded.  */
3418       if (per_cu->v.quick->symtab)
3419         continue;
3420
3421       file_data = dw2_get_file_names (per_cu);
3422       if (file_data == NULL)
3423         continue;
3424
3425       for (j = 0; j < file_data->num_file_names; ++j)
3426         {
3427           const char *this_fullname = file_data->file_names[j];
3428
3429           if (filename_cmp (this_fullname, fullname) == 0)
3430             {
3431               dw2_instantiate_symtab (per_cu);
3432               break;
3433             }
3434         }
3435     }
3436 }
3437
3438 /* A helper function for dw2_find_symbol_file that finds the primary
3439    file name for a given CU.  This is a die_reader_func.  */
3440
3441 static void
3442 dw2_get_primary_filename_reader (const struct die_reader_specs *reader,
3443                                  const gdb_byte *info_ptr,
3444                                  struct die_info *comp_unit_die,
3445                                  int has_children,
3446                                  void *data)
3447 {
3448   const char **result_ptr = data;
3449   struct dwarf2_cu *cu = reader->cu;
3450   struct attribute *attr;
3451
3452   attr = dwarf2_attr (comp_unit_die, DW_AT_name, cu);
3453   if (attr == NULL)
3454     *result_ptr = NULL;
3455   else
3456     *result_ptr = DW_STRING (attr);
3457 }
3458
3459 static const char *
3460 dw2_find_symbol_file (struct objfile *objfile, const char *name)
3461 {
3462   struct dwarf2_per_cu_data *per_cu;
3463   offset_type *vec;
3464   const char *filename;
3465
3466   dw2_setup (objfile);
3467
3468   /* index_table is NULL if OBJF_READNOW.  */
3469   if (!dwarf2_per_objfile->index_table)
3470     {
3471       struct symtab *s;
3472
3473       ALL_OBJFILE_PRIMARY_SYMTABS (objfile, s)
3474         {
3475           struct blockvector *bv = BLOCKVECTOR (s);
3476           const struct block *block = BLOCKVECTOR_BLOCK (bv, GLOBAL_BLOCK);
3477           struct symbol *sym = lookup_block_symbol (block, name, VAR_DOMAIN);
3478
3479           if (sym)
3480             {
3481               /* Only file extension of returned filename is recognized.  */
3482               return SYMBOL_SYMTAB (sym)->filename;
3483             }
3484         }
3485       return NULL;
3486     }
3487
3488   if (!find_slot_in_mapped_hash (dwarf2_per_objfile->index_table,
3489                                  name, &vec))
3490     return NULL;
3491
3492   /* Note that this just looks at the very first one named NAME -- but
3493      actually we are looking for a function.  find_main_filename
3494      should be rewritten so that it doesn't require a custom hook.  It
3495      could just use the ordinary symbol tables.  */
3496   /* vec[0] is the length, which must always be >0.  */
3497   per_cu = dw2_get_cu (GDB_INDEX_CU_VALUE (MAYBE_SWAP (vec[1])));
3498
3499   if (per_cu->v.quick->symtab != NULL)
3500     {
3501       /* Only file extension of returned filename is recognized.  */
3502       return per_cu->v.quick->symtab->filename;
3503     }
3504
3505   /* Initialize filename in case there's a problem reading the DWARF,
3506      dw2_get_primary_filename_reader may not get called.  */
3507   filename = NULL;
3508   init_cutu_and_read_dies (per_cu, NULL, 0, 0,
3509                            dw2_get_primary_filename_reader, &filename);
3510
3511   /* Only file extension of returned filename is recognized.  */
3512   return filename;
3513 }
3514
3515 static void
3516 dw2_map_matching_symbols (const char * name, domain_enum namespace,
3517                           struct objfile *objfile, int global,
3518                           int (*callback) (struct block *,
3519                                            struct symbol *, void *),
3520                           void *data, symbol_compare_ftype *match,
3521                           symbol_compare_ftype *ordered_compare)
3522 {
3523   /* Currently unimplemented; used for Ada.  The function can be called if the
3524      current language is Ada for a non-Ada objfile using GNU index.  As Ada
3525      does not look for non-Ada symbols this function should just return.  */
3526 }
3527
3528 static void
3529 dw2_expand_symtabs_matching
3530   (struct objfile *objfile,
3531    int (*file_matcher) (const char *, void *, int basenames),
3532    int (*name_matcher) (const char *, void *),
3533    enum search_domain kind,
3534    void *data)
3535 {
3536   int i;
3537   offset_type iter;
3538   struct mapped_index *index;
3539
3540   dw2_setup (objfile);
3541
3542   /* index_table is NULL if OBJF_READNOW.  */
3543   if (!dwarf2_per_objfile->index_table)
3544     return;
3545   index = dwarf2_per_objfile->index_table;
3546
3547   if (file_matcher != NULL)
3548     {
3549       struct cleanup *cleanup;
3550       htab_t visited_found, visited_not_found;
3551
3552       visited_found = htab_create_alloc (10,
3553                                          htab_hash_pointer, htab_eq_pointer,
3554                                          NULL, xcalloc, xfree);
3555       cleanup = make_cleanup_htab_delete (visited_found);
3556       visited_not_found = htab_create_alloc (10,
3557                                              htab_hash_pointer, htab_eq_pointer,
3558                                              NULL, xcalloc, xfree);
3559       make_cleanup_htab_delete (visited_not_found);
3560
3561       /* The rule is CUs specify all the files, including those used by
3562          any TU, so there's no need to scan TUs here.  */
3563
3564       for (i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
3565         {
3566           int j;
3567           struct dwarf2_per_cu_data *per_cu = dw2_get_primary_cu (i);
3568           struct quick_file_names *file_data;
3569           void **slot;
3570
3571           per_cu->v.quick->mark = 0;
3572
3573           /* We only need to look at symtabs not already expanded.  */
3574           if (per_cu->v.quick->symtab)
3575             continue;
3576
3577           file_data = dw2_get_file_names (per_cu);
3578           if (file_data == NULL)
3579             continue;
3580
3581           if (htab_find (visited_not_found, file_data) != NULL)
3582             continue;
3583           else if (htab_find (visited_found, file_data) != NULL)
3584             {
3585               per_cu->v.quick->mark = 1;
3586               continue;
3587             }
3588
3589           for (j = 0; j < file_data->num_file_names; ++j)
3590             {
3591               const char *this_real_name;
3592
3593               if (file_matcher (file_data->file_names[j], data, 0))
3594                 {
3595                   per_cu->v.quick->mark = 1;
3596                   break;
3597                 }
3598
3599               /* Before we invoke realpath, which can get expensive when many
3600                  files are involved, do a quick comparison of the basenames.  */
3601               if (!basenames_may_differ
3602                   && !file_matcher (lbasename (file_data->file_names[j]),
3603                                     data, 1))
3604                 continue;
3605
3606               this_real_name = dw2_get_real_path (objfile, file_data, j);
3607               if (file_matcher (this_real_name, data, 0))
3608                 {
3609                   per_cu->v.quick->mark = 1;
3610                   break;
3611                 }
3612             }
3613
3614           slot = htab_find_slot (per_cu->v.quick->mark
3615                                  ? visited_found
3616                                  : visited_not_found,
3617                                  file_data, INSERT);
3618           *slot = file_data;
3619         }
3620
3621       do_cleanups (cleanup);
3622     }
3623
3624   for (iter = 0; iter < index->symbol_table_slots; ++iter)
3625     {
3626       offset_type idx = 2 * iter;
3627       const char *name;
3628       offset_type *vec, vec_len, vec_idx;
3629
3630       if (index->symbol_table[idx] == 0 && index->symbol_table[idx + 1] == 0)
3631         continue;
3632
3633       name = index->constant_pool + MAYBE_SWAP (index->symbol_table[idx]);
3634
3635       if (! (*name_matcher) (name, data))
3636         continue;
3637
3638       /* The name was matched, now expand corresponding CUs that were
3639          marked.  */
3640       vec = (offset_type *) (index->constant_pool
3641                              + MAYBE_SWAP (index->symbol_table[idx + 1]));
3642       vec_len = MAYBE_SWAP (vec[0]);
3643       for (vec_idx = 0; vec_idx < vec_len; ++vec_idx)
3644         {
3645           struct dwarf2_per_cu_data *per_cu;
3646           offset_type cu_index_and_attrs = MAYBE_SWAP (vec[vec_idx + 1]);
3647           gdb_index_symbol_kind symbol_kind =
3648             GDB_INDEX_SYMBOL_KIND_VALUE (cu_index_and_attrs);
3649           int cu_index = GDB_INDEX_CU_VALUE (cu_index_and_attrs);
3650           /* Only check the symbol attributes if they're present.
3651              Indices prior to version 7 don't record them,
3652              and indices >= 7 may elide them for certain symbols
3653              (gold does this).  */
3654           int attrs_valid =
3655             (index->version >= 7
3656              && symbol_kind != GDB_INDEX_SYMBOL_KIND_NONE);
3657
3658           /* Only check the symbol's kind if it has one.  */
3659           if (attrs_valid)
3660             {
3661               switch (kind)
3662                 {
3663                 case VARIABLES_DOMAIN:
3664                   if (symbol_kind != GDB_INDEX_SYMBOL_KIND_VARIABLE)
3665                     continue;
3666                   break;
3667                 case FUNCTIONS_DOMAIN:
3668                   if (symbol_kind != GDB_INDEX_SYMBOL_KIND_FUNCTION)
3669                     continue;
3670                   break;
3671                 case TYPES_DOMAIN:
3672                   if (symbol_kind != GDB_INDEX_SYMBOL_KIND_TYPE)
3673                     continue;
3674                   break;
3675                 default:
3676                   break;
3677                 }
3678             }
3679
3680           /* Don't crash on bad data.  */
3681           if (cu_index >= (dwarf2_per_objfile->n_comp_units
3682                            + dwarf2_per_objfile->n_type_units))
3683             {
3684               complaint (&symfile_complaints,
3685                          _(".gdb_index entry has bad CU index"
3686                            " [in module %s]"), objfile->name);
3687               continue;
3688             }
3689
3690           per_cu = dw2_get_cu (cu_index);
3691           if (file_matcher == NULL || per_cu->v.quick->mark)
3692             dw2_instantiate_symtab (per_cu);
3693         }
3694     }
3695 }
3696
3697 /* A helper for dw2_find_pc_sect_symtab which finds the most specific
3698    symtab.  */
3699
3700 static struct symtab *
3701 recursively_find_pc_sect_symtab (struct symtab *symtab, CORE_ADDR pc)
3702 {
3703   int i;
3704
3705   if (BLOCKVECTOR (symtab) != NULL
3706       && blockvector_contains_pc (BLOCKVECTOR (symtab), pc))
3707     return symtab;
3708
3709   if (symtab->includes == NULL)
3710     return NULL;
3711
3712   for (i = 0; symtab->includes[i]; ++i)
3713     {
3714       struct symtab *s = symtab->includes[i];
3715
3716       s = recursively_find_pc_sect_symtab (s, pc);
3717       if (s != NULL)
3718         return s;
3719     }
3720
3721   return NULL;
3722 }
3723
3724 static struct symtab *
3725 dw2_find_pc_sect_symtab (struct objfile *objfile,
3726                          struct minimal_symbol *msymbol,
3727                          CORE_ADDR pc,
3728                          struct obj_section *section,
3729                          int warn_if_readin)
3730 {
3731   struct dwarf2_per_cu_data *data;
3732   struct symtab *result;
3733
3734   dw2_setup (objfile);
3735
3736   if (!objfile->psymtabs_addrmap)
3737     return NULL;
3738
3739   data = addrmap_find (objfile->psymtabs_addrmap, pc);
3740   if (!data)
3741     return NULL;
3742
3743   if (warn_if_readin && data->v.quick->symtab)
3744     warning (_("(Internal error: pc %s in read in CU, but not in symtab.)"),
3745              paddress (get_objfile_arch (objfile), pc));
3746
3747   result = recursively_find_pc_sect_symtab (dw2_instantiate_symtab (data), pc);
3748   gdb_assert (result != NULL);
3749   return result;
3750 }
3751
3752 static void
3753 dw2_map_symbol_filenames (struct objfile *objfile, symbol_filename_ftype *fun,
3754                           void *data, int need_fullname)
3755 {
3756   int i;
3757   struct cleanup *cleanup;
3758   htab_t visited = htab_create_alloc (10, htab_hash_pointer, htab_eq_pointer,
3759                                       NULL, xcalloc, xfree);
3760
3761   cleanup = make_cleanup_htab_delete (visited);
3762   dw2_setup (objfile);
3763
3764   /* The rule is CUs specify all the files, including those used by
3765      any TU, so there's no need to scan TUs here.
3766      We can ignore file names coming from already-expanded CUs.  */
3767
3768   for (i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
3769     {
3770       struct dwarf2_per_cu_data *per_cu = dw2_get_cu (i);
3771
3772       if (per_cu->v.quick->symtab)
3773         {
3774           void **slot = htab_find_slot (visited, per_cu->v.quick->file_names,
3775                                         INSERT);
3776
3777           *slot = per_cu->v.quick->file_names;
3778         }
3779     }
3780
3781   for (i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
3782     {
3783       int j;
3784       struct dwarf2_per_cu_data *per_cu = dw2_get_primary_cu (i);
3785       struct quick_file_names *file_data;
3786       void **slot;
3787
3788       /* We only need to look at symtabs not already expanded.  */
3789       if (per_cu->v.quick->symtab)
3790         continue;
3791
3792       file_data = dw2_get_file_names (per_cu);
3793       if (file_data == NULL)
3794         continue;
3795
3796       slot = htab_find_slot (visited, file_data, INSERT);
3797       if (*slot)
3798         {
3799           /* Already visited.  */
3800           continue;
3801         }
3802       *slot = file_data;
3803
3804       for (j = 0; j < file_data->num_file_names; ++j)
3805         {
3806           const char *this_real_name;
3807
3808           if (need_fullname)
3809             this_real_name = dw2_get_real_path (objfile, file_data, j);
3810           else
3811             this_real_name = NULL;
3812           (*fun) (file_data->file_names[j], this_real_name, data);
3813         }
3814     }
3815
3816   do_cleanups (cleanup);
3817 }
3818
3819 static int
3820 dw2_has_symbols (struct objfile *objfile)
3821 {
3822   return 1;
3823 }
3824
3825 const struct quick_symbol_functions dwarf2_gdb_index_functions =
3826 {
3827   dw2_has_symbols,
3828   dw2_find_last_source_symtab,
3829   dw2_forget_cached_source_info,
3830   dw2_map_symtabs_matching_filename,
3831   dw2_lookup_symbol,
3832   dw2_print_stats,
3833   dw2_dump,
3834   dw2_relocate,
3835   dw2_expand_symtabs_for_function,
3836   dw2_expand_all_symtabs,
3837   dw2_expand_symtabs_with_fullname,
3838   dw2_find_symbol_file,
3839   dw2_map_matching_symbols,
3840   dw2_expand_symtabs_matching,
3841   dw2_find_pc_sect_symtab,
3842   dw2_map_symbol_filenames
3843 };
3844
3845 /* Initialize for reading DWARF for this objfile.  Return 0 if this
3846    file will use psymtabs, or 1 if using the GNU index.  */
3847
3848 int
3849 dwarf2_initialize_objfile (struct objfile *objfile)
3850 {
3851   /* If we're about to read full symbols, don't bother with the
3852      indices.  In this case we also don't care if some other debug
3853      format is making psymtabs, because they are all about to be
3854      expanded anyway.  */
3855   if ((objfile->flags & OBJF_READNOW))
3856     {
3857       int i;
3858
3859       dwarf2_per_objfile->using_index = 1;
3860       create_all_comp_units (objfile);
3861       create_all_type_units (objfile);
3862       dwarf2_per_objfile->quick_file_names_table =
3863         create_quick_file_names_table (dwarf2_per_objfile->n_comp_units);
3864
3865       for (i = 0; i < (dwarf2_per_objfile->n_comp_units
3866                        + dwarf2_per_objfile->n_type_units); ++i)
3867         {
3868           struct dwarf2_per_cu_data *per_cu = dw2_get_cu (i);
3869
3870           per_cu->v.quick = OBSTACK_ZALLOC (&objfile->objfile_obstack,
3871                                             struct dwarf2_per_cu_quick_data);
3872         }
3873
3874       /* Return 1 so that gdb sees the "quick" functions.  However,
3875          these functions will be no-ops because we will have expanded
3876          all symtabs.  */
3877       return 1;
3878     }
3879
3880   if (dwarf2_read_index (objfile))
3881     return 1;
3882
3883   return 0;
3884 }
3885
3886 \f
3887
3888 /* Build a partial symbol table.  */
3889
3890 void
3891 dwarf2_build_psymtabs (struct objfile *objfile)
3892 {
3893   volatile struct gdb_exception except;
3894
3895   if (objfile->global_psymbols.size == 0 && objfile->static_psymbols.size == 0)
3896     {
3897       init_psymbol_list (objfile, 1024);
3898     }
3899
3900   TRY_CATCH (except, RETURN_MASK_ERROR)
3901     {
3902       /* This isn't really ideal: all the data we allocate on the
3903          objfile's obstack is still uselessly kept around.  However,
3904          freeing it seems unsafe.  */
3905       struct cleanup *cleanups = make_cleanup_discard_psymtabs (objfile);
3906
3907       dwarf2_build_psymtabs_hard (objfile);
3908       discard_cleanups (cleanups);
3909     }
3910   if (except.reason < 0)
3911     exception_print (gdb_stderr, except);
3912 }
3913
3914 /* Return the total length of the CU described by HEADER.  */
3915
3916 static unsigned int
3917 get_cu_length (const struct comp_unit_head *header)
3918 {
3919   return header->initial_length_size + header->length;
3920 }
3921
3922 /* Return TRUE if OFFSET is within CU_HEADER.  */
3923
3924 static inline int
3925 offset_in_cu_p (const struct comp_unit_head *cu_header, sect_offset offset)
3926 {
3927   sect_offset bottom = { cu_header->offset.sect_off };
3928   sect_offset top = { cu_header->offset.sect_off + get_cu_length (cu_header) };
3929
3930   return (offset.sect_off >= bottom.sect_off && offset.sect_off < top.sect_off);
3931 }
3932
3933 /* Find the base address of the compilation unit for range lists and
3934    location lists.  It will normally be specified by DW_AT_low_pc.
3935    In DWARF-3 draft 4, the base address could be overridden by
3936    DW_AT_entry_pc.  It's been removed, but GCC still uses this for
3937    compilation units with discontinuous ranges.  */
3938
3939 static void
3940 dwarf2_find_base_address (struct die_info *die, struct dwarf2_cu *cu)
3941 {
3942   struct attribute *attr;
3943
3944   cu->base_known = 0;
3945   cu->base_address = 0;
3946
3947   attr = dwarf2_attr (die, DW_AT_entry_pc, cu);
3948   if (attr)
3949     {
3950       cu->base_address = DW_ADDR (attr);
3951       cu->base_known = 1;
3952     }
3953   else
3954     {
3955       attr = dwarf2_attr (die, DW_AT_low_pc, cu);
3956       if (attr)
3957         {
3958           cu->base_address = DW_ADDR (attr);
3959           cu->base_known = 1;
3960         }
3961     }
3962 }
3963
3964 /* Read in the comp unit header information from the debug_info at info_ptr.
3965    NOTE: This leaves members offset, first_die_offset to be filled in
3966    by the caller.  */
3967
3968 static const gdb_byte *
3969 read_comp_unit_head (struct comp_unit_head *cu_header,
3970                      const gdb_byte *info_ptr, bfd *abfd)
3971 {
3972   int signed_addr;
3973   unsigned int bytes_read;
3974
3975   cu_header->length = read_initial_length (abfd, info_ptr, &bytes_read);
3976   cu_header->initial_length_size = bytes_read;
3977   cu_header->offset_size = (bytes_read == 4) ? 4 : 8;
3978   info_ptr += bytes_read;
3979   cu_header->version = read_2_bytes (abfd, info_ptr);
3980   info_ptr += 2;
3981   cu_header->abbrev_offset.sect_off = read_offset (abfd, info_ptr, cu_header,
3982                                              &bytes_read);
3983   info_ptr += bytes_read;
3984   cu_header->addr_size = read_1_byte (abfd, info_ptr);
3985   info_ptr += 1;
3986   signed_addr = bfd_get_sign_extend_vma (abfd);
3987   if (signed_addr < 0)
3988     internal_error (__FILE__, __LINE__,
3989                     _("read_comp_unit_head: dwarf from non elf file"));
3990   cu_header->signed_addr_p = signed_addr;
3991
3992   return info_ptr;
3993 }
3994
3995 /* Helper function that returns the proper abbrev section for
3996    THIS_CU.  */
3997
3998 static struct dwarf2_section_info *
3999 get_abbrev_section_for_cu (struct dwarf2_per_cu_data *this_cu)
4000 {
4001   struct dwarf2_section_info *abbrev;
4002
4003   if (this_cu->is_dwz)
4004     abbrev = &dwarf2_get_dwz_file ()->abbrev;
4005   else
4006     abbrev = &dwarf2_per_objfile->abbrev;
4007
4008   return abbrev;
4009 }
4010
4011 /* Subroutine of read_and_check_comp_unit_head and
4012    read_and_check_type_unit_head to simplify them.
4013    Perform various error checking on the header.  */
4014
4015 static void
4016 error_check_comp_unit_head (struct comp_unit_head *header,
4017                             struct dwarf2_section_info *section,
4018                             struct dwarf2_section_info *abbrev_section)
4019 {
4020   bfd *abfd = section->asection->owner;
4021   const char *filename = bfd_get_filename (abfd);
4022
4023   if (header->version != 2 && header->version != 3 && header->version != 4)
4024     error (_("Dwarf Error: wrong version in compilation unit header "
4025            "(is %d, should be 2, 3, or 4) [in module %s]"), header->version,
4026            filename);
4027
4028   if (header->abbrev_offset.sect_off
4029       >= dwarf2_section_size (dwarf2_per_objfile->objfile, abbrev_section))
4030     error (_("Dwarf Error: bad offset (0x%lx) in compilation unit header "
4031            "(offset 0x%lx + 6) [in module %s]"),
4032            (long) header->abbrev_offset.sect_off, (long) header->offset.sect_off,
4033            filename);
4034
4035   /* Cast to unsigned long to use 64-bit arithmetic when possible to
4036      avoid potential 32-bit overflow.  */
4037   if (((unsigned long) header->offset.sect_off + get_cu_length (header))
4038       > section->size)
4039     error (_("Dwarf Error: bad length (0x%lx) in compilation unit header "
4040            "(offset 0x%lx + 0) [in module %s]"),
4041            (long) header->length, (long) header->offset.sect_off,
4042            filename);
4043 }
4044
4045 /* Read in a CU/TU header and perform some basic error checking.
4046    The contents of the header are stored in HEADER.
4047    The result is a pointer to the start of the first DIE.  */
4048
4049 static const gdb_byte *
4050 read_and_check_comp_unit_head (struct comp_unit_head *header,
4051                                struct dwarf2_section_info *section,
4052                                struct dwarf2_section_info *abbrev_section,
4053                                const gdb_byte *info_ptr,
4054                                int is_debug_types_section)
4055 {
4056   const gdb_byte *beg_of_comp_unit = info_ptr;
4057   bfd *abfd = section->asection->owner;
4058
4059   header->offset.sect_off = beg_of_comp_unit - section->buffer;
4060
4061   info_ptr = read_comp_unit_head (header, info_ptr, abfd);
4062
4063   /* If we're reading a type unit, skip over the signature and
4064      type_offset fields.  */
4065   if (is_debug_types_section)
4066     info_ptr += 8 /*signature*/ + header->offset_size;
4067
4068   header->first_die_offset.cu_off = info_ptr - beg_of_comp_unit;
4069
4070   error_check_comp_unit_head (header, section, abbrev_section);
4071
4072   return info_ptr;
4073 }
4074
4075 /* Read in the types comp unit header information from .debug_types entry at
4076    types_ptr.  The result is a pointer to one past the end of the header.  */
4077
4078 static const gdb_byte *
4079 read_and_check_type_unit_head (struct comp_unit_head *header,
4080                                struct dwarf2_section_info *section,
4081                                struct dwarf2_section_info *abbrev_section,
4082                                const gdb_byte *info_ptr,
4083                                ULONGEST *signature,
4084                                cu_offset *type_offset_in_tu)
4085 {
4086   const gdb_byte *beg_of_comp_unit = info_ptr;
4087   bfd *abfd = section->asection->owner;
4088
4089   header->offset.sect_off = beg_of_comp_unit - section->buffer;
4090
4091   info_ptr = read_comp_unit_head (header, info_ptr, abfd);
4092
4093   /* If we're reading a type unit, skip over the signature and
4094      type_offset fields.  */
4095   if (signature != NULL)
4096     *signature = read_8_bytes (abfd, info_ptr);
4097   info_ptr += 8;
4098   if (type_offset_in_tu != NULL)
4099     type_offset_in_tu->cu_off = read_offset_1 (abfd, info_ptr,
4100                                                header->offset_size);
4101   info_ptr += header->offset_size;
4102
4103   header->first_die_offset.cu_off = info_ptr - beg_of_comp_unit;
4104
4105   error_check_comp_unit_head (header, section, abbrev_section);
4106
4107   return info_ptr;
4108 }
4109
4110 /* Fetch the abbreviation table offset from a comp or type unit header.  */
4111
4112 static sect_offset
4113 read_abbrev_offset (struct dwarf2_section_info *section,
4114                     sect_offset offset)
4115 {
4116   bfd *abfd = section->asection->owner;
4117   const gdb_byte *info_ptr;
4118   unsigned int length, initial_length_size, offset_size;
4119   sect_offset abbrev_offset;
4120
4121   dwarf2_read_section (dwarf2_per_objfile->objfile, section);
4122   info_ptr = section->buffer + offset.sect_off;
4123   length = read_initial_length (abfd, info_ptr, &initial_length_size);
4124   offset_size = initial_length_size == 4 ? 4 : 8;
4125   info_ptr += initial_length_size + 2 /*version*/;
4126   abbrev_offset.sect_off = read_offset_1 (abfd, info_ptr, offset_size);
4127   return abbrev_offset;
4128 }
4129
4130 /* Allocate a new partial symtab for file named NAME and mark this new
4131    partial symtab as being an include of PST.  */
4132
4133 static void
4134 dwarf2_create_include_psymtab (const char *name, struct partial_symtab *pst,
4135                                struct objfile *objfile)
4136 {
4137   struct partial_symtab *subpst = allocate_psymtab (name, objfile);
4138
4139   if (!IS_ABSOLUTE_PATH (subpst->filename))
4140     {
4141       /* It shares objfile->objfile_obstack.  */
4142       subpst->dirname = pst->dirname;
4143     }
4144
4145   subpst->section_offsets = pst->section_offsets;
4146   subpst->textlow = 0;
4147   subpst->texthigh = 0;
4148
4149   subpst->dependencies = (struct partial_symtab **)
4150     obstack_alloc (&objfile->objfile_obstack,
4151                    sizeof (struct partial_symtab *));
4152   subpst->dependencies[0] = pst;
4153   subpst->number_of_dependencies = 1;
4154
4155   subpst->globals_offset = 0;
4156   subpst->n_global_syms = 0;
4157   subpst->statics_offset = 0;
4158   subpst->n_static_syms = 0;
4159   subpst->symtab = NULL;
4160   subpst->read_symtab = pst->read_symtab;
4161   subpst->readin = 0;
4162
4163   /* No private part is necessary for include psymtabs.  This property
4164      can be used to differentiate between such include psymtabs and
4165      the regular ones.  */
4166   subpst->read_symtab_private = NULL;
4167 }
4168
4169 /* Read the Line Number Program data and extract the list of files
4170    included by the source file represented by PST.  Build an include
4171    partial symtab for each of these included files.  */
4172
4173 static void
4174 dwarf2_build_include_psymtabs (struct dwarf2_cu *cu,
4175                                struct die_info *die,
4176                                struct partial_symtab *pst)
4177 {
4178   struct line_header *lh = NULL;
4179   struct attribute *attr;
4180
4181   attr = dwarf2_attr (die, DW_AT_stmt_list, cu);
4182   if (attr)
4183     lh = dwarf_decode_line_header (DW_UNSND (attr), cu);
4184   if (lh == NULL)
4185     return;  /* No linetable, so no includes.  */
4186
4187   /* NOTE: pst->dirname is DW_AT_comp_dir (if present).  */
4188   dwarf_decode_lines (lh, pst->dirname, cu, pst, 1);
4189
4190   free_line_header (lh);
4191 }
4192
4193 static hashval_t
4194 hash_signatured_type (const void *item)
4195 {
4196   const struct signatured_type *sig_type = item;
4197
4198   /* This drops the top 32 bits of the signature, but is ok for a hash.  */
4199   return sig_type->signature;
4200 }
4201
4202 static int
4203 eq_signatured_type (const void *item_lhs, const void *item_rhs)
4204 {
4205   const struct signatured_type *lhs = item_lhs;
4206   const struct signatured_type *rhs = item_rhs;
4207
4208   return lhs->signature == rhs->signature;
4209 }
4210
4211 /* Allocate a hash table for signatured types.  */
4212
4213 static htab_t
4214 allocate_signatured_type_table (struct objfile *objfile)
4215 {
4216   return htab_create_alloc_ex (41,
4217                                hash_signatured_type,
4218                                eq_signatured_type,
4219                                NULL,
4220                                &objfile->objfile_obstack,
4221                                hashtab_obstack_allocate,
4222                                dummy_obstack_deallocate);
4223 }
4224
4225 /* A helper function to add a signatured type CU to a table.  */
4226
4227 static int
4228 add_signatured_type_cu_to_table (void **slot, void *datum)
4229 {
4230   struct signatured_type *sigt = *slot;
4231   struct signatured_type ***datap = datum;
4232
4233   **datap = sigt;
4234   ++*datap;
4235
4236   return 1;
4237 }
4238
4239 /* Create the hash table of all entries in the .debug_types
4240    (or .debug_types.dwo) section(s).
4241    If reading a DWO file, then DWO_FILE is a pointer to the DWO file object,
4242    otherwise it is NULL.
4243
4244    The result is a pointer to the hash table or NULL if there are no types.
4245
4246    Note: This function processes DWO files only, not DWP files.  */
4247
4248 static htab_t
4249 create_debug_types_hash_table (struct dwo_file *dwo_file,
4250                                VEC (dwarf2_section_info_def) *types)
4251 {
4252   struct objfile *objfile = dwarf2_per_objfile->objfile;
4253   htab_t types_htab = NULL;
4254   int ix;
4255   struct dwarf2_section_info *section;
4256   struct dwarf2_section_info *abbrev_section;
4257
4258   if (VEC_empty (dwarf2_section_info_def, types))
4259     return NULL;
4260
4261   abbrev_section = (dwo_file != NULL
4262                     ? &dwo_file->sections.abbrev
4263                     : &dwarf2_per_objfile->abbrev);
4264
4265   if (dwarf2_read_debug)
4266     fprintf_unfiltered (gdb_stdlog, "Reading .debug_types%s for %s:\n",
4267                         dwo_file ? ".dwo" : "",
4268                         bfd_get_filename (abbrev_section->asection->owner));
4269
4270   for (ix = 0;
4271        VEC_iterate (dwarf2_section_info_def, types, ix, section);
4272        ++ix)
4273     {
4274       bfd *abfd;
4275       const gdb_byte *info_ptr, *end_ptr;
4276       struct dwarf2_section_info *abbrev_section;
4277
4278       dwarf2_read_section (objfile, section);
4279       info_ptr = section->buffer;
4280
4281       if (info_ptr == NULL)
4282         continue;
4283
4284       /* We can't set abfd until now because the section may be empty or
4285          not present, in which case section->asection will be NULL.  */
4286       abfd = section->asection->owner;
4287
4288       if (dwo_file)
4289         abbrev_section = &dwo_file->sections.abbrev;
4290       else
4291         abbrev_section = &dwarf2_per_objfile->abbrev;
4292
4293       /* We don't use init_cutu_and_read_dies_simple, or some such, here
4294          because we don't need to read any dies: the signature is in the
4295          header.  */
4296
4297       end_ptr = info_ptr + section->size;
4298       while (info_ptr < end_ptr)
4299         {
4300           sect_offset offset;
4301           cu_offset type_offset_in_tu;
4302           ULONGEST signature;
4303           struct signatured_type *sig_type;
4304           struct dwo_unit *dwo_tu;
4305           void **slot;
4306           const gdb_byte *ptr = info_ptr;
4307           struct comp_unit_head header;
4308           unsigned int length;
4309
4310           offset.sect_off = ptr - section->buffer;
4311
4312           /* We need to read the type's signature in order to build the hash
4313              table, but we don't need anything else just yet.  */
4314
4315           ptr = read_and_check_type_unit_head (&header, section,
4316                                                abbrev_section, ptr,
4317                                                &signature, &type_offset_in_tu);
4318
4319           length = get_cu_length (&header);
4320
4321           /* Skip dummy type units.  */
4322           if (ptr >= info_ptr + length
4323               || peek_abbrev_code (abfd, ptr) == 0)
4324             {
4325               info_ptr += length;
4326               continue;
4327             }
4328
4329           if (types_htab == NULL)
4330             {
4331               if (dwo_file)
4332                 types_htab = allocate_dwo_unit_table (objfile);
4333               else
4334                 types_htab = allocate_signatured_type_table (objfile);
4335             }
4336
4337           if (dwo_file)
4338             {
4339               sig_type = NULL;
4340               dwo_tu = OBSTACK_ZALLOC (&objfile->objfile_obstack,
4341                                        struct dwo_unit);
4342               dwo_tu->dwo_file = dwo_file;
4343               dwo_tu->signature = signature;
4344               dwo_tu->type_offset_in_tu = type_offset_in_tu;
4345               dwo_tu->section = section;
4346               dwo_tu->offset = offset;
4347               dwo_tu->length = length;
4348             }
4349           else
4350             {
4351               /* N.B.: type_offset is not usable if this type uses a DWO file.
4352                  The real type_offset is in the DWO file.  */
4353               dwo_tu = NULL;
4354               sig_type = OBSTACK_ZALLOC (&objfile->objfile_obstack,
4355                                          struct signatured_type);
4356               sig_type->signature = signature;
4357               sig_type->type_offset_in_tu = type_offset_in_tu;
4358               sig_type->per_cu.objfile = objfile;
4359               sig_type->per_cu.is_debug_types = 1;
4360               sig_type->per_cu.section = section;
4361               sig_type->per_cu.offset = offset;
4362               sig_type->per_cu.length = length;
4363             }
4364
4365           slot = htab_find_slot (types_htab,
4366                                  dwo_file ? (void*) dwo_tu : (void *) sig_type,
4367                                  INSERT);
4368           gdb_assert (slot != NULL);
4369           if (*slot != NULL)
4370             {
4371               sect_offset dup_offset;
4372
4373               if (dwo_file)
4374                 {
4375                   const struct dwo_unit *dup_tu = *slot;
4376
4377                   dup_offset = dup_tu->offset;
4378                 }
4379               else
4380                 {
4381                   const struct signatured_type *dup_tu = *slot;
4382
4383                   dup_offset = dup_tu->per_cu.offset;
4384                 }
4385
4386               complaint (&symfile_complaints,
4387                          _("debug type entry at offset 0x%x is duplicate to"
4388                            " the entry at offset 0x%x, signature %s"),
4389                          offset.sect_off, dup_offset.sect_off,
4390                          hex_string (signature));
4391             }
4392           *slot = dwo_file ? (void *) dwo_tu : (void *) sig_type;
4393
4394           if (dwarf2_read_debug)
4395             fprintf_unfiltered (gdb_stdlog, "  offset 0x%x, signature %s\n",
4396                                 offset.sect_off,
4397                                 hex_string (signature));
4398
4399           info_ptr += length;
4400         }
4401     }
4402
4403   return types_htab;
4404 }
4405
4406 /* Create the hash table of all entries in the .debug_types section,
4407    and initialize all_type_units.
4408    The result is zero if there is an error (e.g. missing .debug_types section),
4409    otherwise non-zero.  */
4410
4411 static int
4412 create_all_type_units (struct objfile *objfile)
4413 {
4414   htab_t types_htab;
4415   struct signatured_type **iter;
4416
4417   types_htab = create_debug_types_hash_table (NULL, dwarf2_per_objfile->types);
4418   if (types_htab == NULL)
4419     {
4420       dwarf2_per_objfile->signatured_types = NULL;
4421       return 0;
4422     }
4423
4424   dwarf2_per_objfile->signatured_types = types_htab;
4425
4426   dwarf2_per_objfile->n_type_units = htab_elements (types_htab);
4427   dwarf2_per_objfile->all_type_units
4428     = xmalloc (dwarf2_per_objfile->n_type_units
4429                * sizeof (struct signatured_type *));
4430   iter = &dwarf2_per_objfile->all_type_units[0];
4431   htab_traverse_noresize (types_htab, add_signatured_type_cu_to_table, &iter);
4432   gdb_assert (iter - &dwarf2_per_objfile->all_type_units[0]
4433               == dwarf2_per_objfile->n_type_units);
4434
4435   return 1;
4436 }
4437
4438 /* Subroutine of lookup_dwo_signatured_type and lookup_dwp_signatured_type.
4439    Fill in SIG_ENTRY with DWO_ENTRY.  */
4440
4441 static void
4442 fill_in_sig_entry_from_dwo_entry (struct objfile *objfile,
4443                                   struct signatured_type *sig_entry,
4444                                   struct dwo_unit *dwo_entry)
4445 {
4446   sig_entry->per_cu.section = dwo_entry->section;
4447   sig_entry->per_cu.offset = dwo_entry->offset;
4448   sig_entry->per_cu.length = dwo_entry->length;
4449   sig_entry->per_cu.reading_dwo_directly = 1;
4450   sig_entry->per_cu.objfile = objfile;
4451   gdb_assert (! sig_entry->per_cu.queued);
4452   gdb_assert (sig_entry->per_cu.cu == NULL);
4453   gdb_assert (sig_entry->per_cu.v.quick != NULL);
4454   gdb_assert (sig_entry->per_cu.v.quick->symtab == NULL);
4455   gdb_assert (sig_entry->signature == dwo_entry->signature);
4456   gdb_assert (sig_entry->type_offset_in_section.sect_off == 0);
4457   gdb_assert (sig_entry->type_unit_group == NULL);
4458   sig_entry->type_offset_in_tu = dwo_entry->type_offset_in_tu;
4459   sig_entry->dwo_unit = dwo_entry;
4460 }
4461
4462 /* Subroutine of lookup_signatured_type.
4463    Create the signatured_type data structure for a TU to be read in
4464    directly from a DWO file, bypassing the stub.
4465    We do this for the case where there is no DWP file and we're using
4466    .gdb_index: When reading a CU we want to stay in the DWO file containing
4467    that CU.  Otherwise we could end up reading several other DWO files (due
4468    to comdat folding) to process the transitive closure of all the mentioned
4469    TUs, and that can be slow.  The current DWO file will have every type
4470    signature that it needs.
4471    We only do this for .gdb_index because in the psymtab case we already have
4472    to read all the DWOs to build the type unit groups.  */
4473
4474 static struct signatured_type *
4475 lookup_dwo_signatured_type (struct dwarf2_cu *cu, ULONGEST sig)
4476 {
4477   struct objfile *objfile = dwarf2_per_objfile->objfile;
4478   struct dwo_file *dwo_file;
4479   struct dwo_unit find_dwo_entry, *dwo_entry;
4480   struct signatured_type find_sig_entry, *sig_entry;
4481
4482   gdb_assert (cu->dwo_unit && dwarf2_per_objfile->using_index);
4483
4484   /* Note: cu->dwo_unit is the dwo_unit that references this TU, not the
4485      dwo_unit of the TU itself.  */
4486   dwo_file = cu->dwo_unit->dwo_file;
4487
4488   /* We only ever need to read in one copy of a signatured type.
4489      Just use the global signatured_types array.  If this is the first time
4490      we're reading this type, replace the recorded data from .gdb_index with
4491      this TU.  */
4492
4493   if (dwarf2_per_objfile->signatured_types == NULL)
4494     return NULL;
4495   find_sig_entry.signature = sig;
4496   sig_entry = htab_find (dwarf2_per_objfile->signatured_types, &find_sig_entry);
4497   if (sig_entry == NULL)
4498     return NULL;
4499   /* Have we already tried to read this TU?  */
4500   if (sig_entry->dwo_unit != NULL)
4501     return sig_entry;
4502
4503   /* Ok, this is the first time we're reading this TU.  */
4504   if (dwo_file->tus == NULL)
4505     return NULL;
4506   find_dwo_entry.signature = sig;
4507   dwo_entry = htab_find (dwo_file->tus, &find_dwo_entry);
4508   if (dwo_entry == NULL)
4509     return NULL;
4510
4511   fill_in_sig_entry_from_dwo_entry (objfile, sig_entry, dwo_entry);
4512   return sig_entry;
4513 }
4514
4515 /* Subroutine of lookup_dwp_signatured_type.
4516    Add an entry for signature SIG to dwarf2_per_objfile->signatured_types.  */
4517
4518 static struct signatured_type *
4519 add_type_unit (ULONGEST sig)
4520 {
4521   struct objfile *objfile = dwarf2_per_objfile->objfile;
4522   int n_type_units = dwarf2_per_objfile->n_type_units;
4523   struct signatured_type *sig_type;
4524   void **slot;
4525
4526   ++n_type_units;
4527   dwarf2_per_objfile->all_type_units =
4528     xrealloc (dwarf2_per_objfile->all_type_units,
4529               n_type_units * sizeof (struct signatured_type *));
4530   dwarf2_per_objfile->n_type_units = n_type_units;
4531   sig_type = OBSTACK_ZALLOC (&objfile->objfile_obstack,
4532                              struct signatured_type);
4533   dwarf2_per_objfile->all_type_units[n_type_units - 1] = sig_type;
4534   sig_type->signature = sig;
4535   sig_type->per_cu.is_debug_types = 1;
4536   sig_type->per_cu.v.quick =
4537     OBSTACK_ZALLOC (&objfile->objfile_obstack,
4538                     struct dwarf2_per_cu_quick_data);
4539   slot = htab_find_slot (dwarf2_per_objfile->signatured_types,
4540                          sig_type, INSERT);
4541   gdb_assert (*slot == NULL);
4542   *slot = sig_type;
4543   /* The rest of sig_type must be filled in by the caller.  */
4544   return sig_type;
4545 }
4546
4547 /* Subroutine of lookup_signatured_type.
4548    Look up the type for signature SIG, and if we can't find SIG in .gdb_index
4549    then try the DWP file.
4550    Normally this "can't happen", but if there's a bug in signature
4551    generation and/or the DWP file is built incorrectly, it can happen.
4552    Using the type directly from the DWP file means we don't have the stub
4553    which has some useful attributes (e.g., DW_AT_comp_dir), but they're
4554    not critical.  [Eventually the stub may go away for type units anyway.]  */
4555
4556 static struct signatured_type *
4557 lookup_dwp_signatured_type (struct dwarf2_cu *cu, ULONGEST sig)
4558 {
4559   struct objfile *objfile = dwarf2_per_objfile->objfile;
4560   struct dwp_file *dwp_file = get_dwp_file ();
4561   struct dwo_unit *dwo_entry;
4562   struct signatured_type find_sig_entry, *sig_entry;
4563
4564   gdb_assert (cu->dwo_unit && dwarf2_per_objfile->using_index);
4565   gdb_assert (dwp_file != NULL);
4566
4567   if (dwarf2_per_objfile->signatured_types != NULL)
4568     {
4569       find_sig_entry.signature = sig;
4570       sig_entry = htab_find (dwarf2_per_objfile->signatured_types,
4571                              &find_sig_entry);
4572       if (sig_entry != NULL)
4573         return sig_entry;
4574     }
4575
4576   /* This is the "shouldn't happen" case.
4577      Try the DWP file and hope for the best.  */
4578   if (dwp_file->tus == NULL)
4579     return NULL;
4580   dwo_entry = lookup_dwo_in_dwp (dwp_file, dwp_file->tus, NULL,
4581                                  sig, 1 /* is_debug_types */);
4582   if (dwo_entry == NULL)
4583     return NULL;
4584
4585   sig_entry = add_type_unit (sig);
4586   fill_in_sig_entry_from_dwo_entry (objfile, sig_entry, dwo_entry);
4587
4588   /* The caller will signal a complaint if we return NULL.
4589      Here we don't return NULL but we still want to complain.  */
4590   complaint (&symfile_complaints,
4591              _("Bad type signature %s referenced by %s at 0x%x,"
4592                " coping by using copy in DWP [in module %s]"),
4593              hex_string (sig),
4594              cu->per_cu->is_debug_types ? "TU" : "CU",
4595              cu->per_cu->offset.sect_off,
4596              objfile->name);
4597
4598   return sig_entry;
4599 }
4600
4601 /* Lookup a signature based type for DW_FORM_ref_sig8.
4602    Returns NULL if signature SIG is not present in the table.
4603    It is up to the caller to complain about this.  */
4604
4605 static struct signatured_type *
4606 lookup_signatured_type (struct dwarf2_cu *cu, ULONGEST sig)
4607 {
4608   if (cu->dwo_unit
4609       && dwarf2_per_objfile->using_index)
4610     {
4611       /* We're in a DWO/DWP file, and we're using .gdb_index.
4612          These cases require special processing.  */
4613       if (get_dwp_file () == NULL)
4614         return lookup_dwo_signatured_type (cu, sig);
4615       else
4616         return lookup_dwp_signatured_type (cu, sig);
4617     }
4618   else
4619     {
4620       struct signatured_type find_entry, *entry;
4621
4622       if (dwarf2_per_objfile->signatured_types == NULL)
4623         return NULL;
4624       find_entry.signature = sig;
4625       entry = htab_find (dwarf2_per_objfile->signatured_types, &find_entry);
4626       return entry;
4627     }
4628 }
4629 \f
4630 /* Low level DIE reading support.  */
4631
4632 /* Initialize a die_reader_specs struct from a dwarf2_cu struct.  */
4633
4634 static void
4635 init_cu_die_reader (struct die_reader_specs *reader,
4636                     struct dwarf2_cu *cu,
4637                     struct dwarf2_section_info *section,
4638                     struct dwo_file *dwo_file)
4639 {
4640   gdb_assert (section->readin && section->buffer != NULL);
4641   reader->abfd = section->asection->owner;
4642   reader->cu = cu;
4643   reader->dwo_file = dwo_file;
4644   reader->die_section = section;
4645   reader->buffer = section->buffer;
4646   reader->buffer_end = section->buffer + section->size;
4647   reader->comp_dir = NULL;
4648 }
4649
4650 /* Subroutine of init_cutu_and_read_dies to simplify it.
4651    Read in the rest of a CU/TU top level DIE from DWO_UNIT.
4652    There's just a lot of work to do, and init_cutu_and_read_dies is big enough
4653    already.
4654
4655    STUB_COMP_UNIT_DIE is for the stub DIE, we copy over certain attributes
4656    from it to the DIE in the DWO.  If NULL we are skipping the stub.
4657    STUB_COMP_DIR is similar to STUB_COMP_UNIT_DIE: When reading a TU directly
4658    from the DWO file, bypassing the stub, it contains the DW_AT_comp_dir
4659    attribute of the referencing CU.  Exactly one of STUB_COMP_UNIT_DIE and
4660    COMP_DIR must be non-NULL.
4661    *RESULT_READER,*RESULT_INFO_PTR,*RESULT_COMP_UNIT_DIE,*RESULT_HAS_CHILDREN
4662    are filled in with the info of the DIE from the DWO file.
4663    ABBREV_TABLE_PROVIDED is non-zero if the caller of init_cutu_and_read_dies
4664    provided an abbrev table to use.
4665    The result is non-zero if a valid (non-dummy) DIE was found.  */
4666
4667 static int
4668 read_cutu_die_from_dwo (struct dwarf2_per_cu_data *this_cu,
4669                         struct dwo_unit *dwo_unit,
4670                         int abbrev_table_provided,
4671                         struct die_info *stub_comp_unit_die,
4672                         const char *stub_comp_dir,
4673                         struct die_reader_specs *result_reader,
4674                         const gdb_byte **result_info_ptr,
4675                         struct die_info **result_comp_unit_die,
4676                         int *result_has_children)
4677 {
4678   struct objfile *objfile = dwarf2_per_objfile->objfile;
4679   struct dwarf2_cu *cu = this_cu->cu;
4680   struct dwarf2_section_info *section;
4681   bfd *abfd;
4682   const gdb_byte *begin_info_ptr, *info_ptr;
4683   const char *comp_dir_string;
4684   ULONGEST signature; /* Or dwo_id.  */
4685   struct attribute *comp_dir, *stmt_list, *low_pc, *high_pc, *ranges;
4686   int i,num_extra_attrs;
4687   struct dwarf2_section_info *dwo_abbrev_section;
4688   struct attribute *attr;
4689   struct attribute comp_dir_attr;
4690   struct die_info *comp_unit_die;
4691
4692   /* Both can't be provided.  */
4693   gdb_assert (! (stub_comp_unit_die && stub_comp_dir));
4694
4695   /* These attributes aren't processed until later:
4696      DW_AT_stmt_list, DW_AT_low_pc, DW_AT_high_pc, DW_AT_ranges.
4697      However, the attribute is found in the stub which we won't have later.
4698      In order to not impose this complication on the rest of the code,
4699      we read them here and copy them to the DWO CU/TU die.  */
4700
4701   stmt_list = NULL;
4702   low_pc = NULL;
4703   high_pc = NULL;
4704   ranges = NULL;
4705   comp_dir = NULL;
4706
4707   if (stub_comp_unit_die != NULL)
4708     {
4709       /* For TUs in DWO files, the DW_AT_stmt_list attribute lives in the
4710          DWO file.  */
4711       if (! this_cu->is_debug_types)
4712         stmt_list = dwarf2_attr (stub_comp_unit_die, DW_AT_stmt_list, cu);
4713       low_pc = dwarf2_attr (stub_comp_unit_die, DW_AT_low_pc, cu);
4714       high_pc = dwarf2_attr (stub_comp_unit_die, DW_AT_high_pc, cu);
4715       ranges = dwarf2_attr (stub_comp_unit_die, DW_AT_ranges, cu);
4716       comp_dir = dwarf2_attr (stub_comp_unit_die, DW_AT_comp_dir, cu);
4717
4718       /* There should be a DW_AT_addr_base attribute here (if needed).
4719          We need the value before we can process DW_FORM_GNU_addr_index.  */
4720       cu->addr_base = 0;
4721       attr = dwarf2_attr (stub_comp_unit_die, DW_AT_GNU_addr_base, cu);
4722       if (attr)
4723         cu->addr_base = DW_UNSND (attr);
4724
4725       /* There should be a DW_AT_ranges_base attribute here (if needed).
4726          We need the value before we can process DW_AT_ranges.  */
4727       cu->ranges_base = 0;
4728       attr = dwarf2_attr (stub_comp_unit_die, DW_AT_GNU_ranges_base, cu);
4729       if (attr)
4730         cu->ranges_base = DW_UNSND (attr);
4731     }
4732   else if (stub_comp_dir != NULL)
4733     {
4734       /* Reconstruct the comp_dir attribute to simplify the code below.  */
4735       comp_dir = (struct attribute *)
4736         obstack_alloc (&cu->comp_unit_obstack, sizeof (*comp_dir));
4737       comp_dir->name = DW_AT_comp_dir;
4738       comp_dir->form = DW_FORM_string;
4739       DW_STRING_IS_CANONICAL (comp_dir) = 0;
4740       DW_STRING (comp_dir) = stub_comp_dir;
4741     }
4742
4743   /* Set up for reading the DWO CU/TU.  */
4744   cu->dwo_unit = dwo_unit;
4745   section = dwo_unit->section;
4746   dwarf2_read_section (objfile, section);
4747   abfd = section->asection->owner;
4748   begin_info_ptr = info_ptr = section->buffer + dwo_unit->offset.sect_off;
4749   dwo_abbrev_section = &dwo_unit->dwo_file->sections.abbrev;
4750   init_cu_die_reader (result_reader, cu, section, dwo_unit->dwo_file);
4751
4752   if (this_cu->is_debug_types)
4753     {
4754       ULONGEST header_signature;
4755       cu_offset type_offset_in_tu;
4756       struct signatured_type *sig_type = (struct signatured_type *) this_cu;
4757
4758       info_ptr = read_and_check_type_unit_head (&cu->header, section,
4759                                                 dwo_abbrev_section,
4760                                                 info_ptr,
4761                                                 &header_signature,
4762                                                 &type_offset_in_tu);
4763       /* This is not an assert because it can be caused by bad debug info.  */
4764       if (sig_type->signature != header_signature)
4765         {
4766           error (_("Dwarf Error: signature mismatch %s vs %s while reading"
4767                    " TU at offset 0x%x [in module %s]"),
4768                  hex_string (sig_type->signature),
4769                  hex_string (header_signature),
4770                  dwo_unit->offset.sect_off,
4771                  bfd_get_filename (abfd));
4772         }
4773       gdb_assert (dwo_unit->offset.sect_off == cu->header.offset.sect_off);
4774       /* For DWOs coming from DWP files, we don't know the CU length
4775          nor the type's offset in the TU until now.  */
4776       dwo_unit->length = get_cu_length (&cu->header);
4777       dwo_unit->type_offset_in_tu = type_offset_in_tu;
4778
4779       /* Establish the type offset that can be used to lookup the type.
4780          For DWO files, we don't know it until now.  */
4781       sig_type->type_offset_in_section.sect_off =
4782         dwo_unit->offset.sect_off + dwo_unit->type_offset_in_tu.cu_off;
4783     }
4784   else
4785     {
4786       info_ptr = read_and_check_comp_unit_head (&cu->header, section,
4787                                                 dwo_abbrev_section,
4788                                                 info_ptr, 0);
4789       gdb_assert (dwo_unit->offset.sect_off == cu->header.offset.sect_off);
4790       /* For DWOs coming from DWP files, we don't know the CU length
4791          until now.  */
4792       dwo_unit->length = get_cu_length (&cu->header);
4793     }
4794
4795   /* Replace the CU's original abbrev table with the DWO's.
4796      Reminder: We can't read the abbrev table until we've read the header.  */
4797   if (abbrev_table_provided)
4798     {
4799       /* Don't free the provided abbrev table, the caller of
4800          init_cutu_and_read_dies owns it.  */
4801       dwarf2_read_abbrevs (cu, dwo_abbrev_section);
4802       /* Ensure the DWO abbrev table gets freed.  */
4803       make_cleanup (dwarf2_free_abbrev_table, cu);
4804     }
4805   else
4806     {
4807       dwarf2_free_abbrev_table (cu);
4808       dwarf2_read_abbrevs (cu, dwo_abbrev_section);
4809       /* Leave any existing abbrev table cleanup as is.  */
4810     }
4811
4812   /* Read in the die, but leave space to copy over the attributes
4813      from the stub.  This has the benefit of simplifying the rest of
4814      the code - all the work to maintain the illusion of a single
4815      DW_TAG_{compile,type}_unit DIE is done here.  */
4816   num_extra_attrs = ((stmt_list != NULL)
4817                      + (low_pc != NULL)
4818                      + (high_pc != NULL)
4819                      + (ranges != NULL)
4820                      + (comp_dir != NULL));
4821   info_ptr = read_full_die_1 (result_reader, result_comp_unit_die, info_ptr,
4822                               result_has_children, num_extra_attrs);
4823
4824   /* Copy over the attributes from the stub to the DIE we just read in.  */
4825   comp_unit_die = *result_comp_unit_die;
4826   i = comp_unit_die->num_attrs;
4827   if (stmt_list != NULL)
4828     comp_unit_die->attrs[i++] = *stmt_list;
4829   if (low_pc != NULL)
4830     comp_unit_die->attrs[i++] = *low_pc;
4831   if (high_pc != NULL)
4832     comp_unit_die->attrs[i++] = *high_pc;
4833   if (ranges != NULL)
4834     comp_unit_die->attrs[i++] = *ranges;
4835   if (comp_dir != NULL)
4836     comp_unit_die->attrs[i++] = *comp_dir;
4837   comp_unit_die->num_attrs += num_extra_attrs;
4838
4839   if (dwarf2_die_debug)
4840     {
4841       fprintf_unfiltered (gdb_stdlog,
4842                           "Read die from %s@0x%x of %s:\n",
4843                           bfd_section_name (abfd, section->asection),
4844                           (unsigned) (begin_info_ptr - section->buffer),
4845                           bfd_get_filename (abfd));
4846       dump_die (comp_unit_die, dwarf2_die_debug);
4847     }
4848
4849   /* Save the comp_dir attribute.  If there is no DWP file then we'll read
4850      TUs by skipping the stub and going directly to the entry in the DWO file.
4851      However, skipping the stub means we won't get DW_AT_comp_dir, so we have
4852      to get it via circuitous means.  Blech.  */
4853   if (comp_dir != NULL)
4854     result_reader->comp_dir = DW_STRING (comp_dir);
4855
4856   /* Skip dummy compilation units.  */
4857   if (info_ptr >= begin_info_ptr + dwo_unit->length
4858       || peek_abbrev_code (abfd, info_ptr) == 0)
4859     return 0;
4860
4861   *result_info_ptr = info_ptr;
4862   return 1;
4863 }
4864
4865 /* Subroutine of init_cutu_and_read_dies to simplify it.
4866    Look up the DWO unit specified by COMP_UNIT_DIE of THIS_CU.
4867    Returns NULL if the specified DWO unit cannot be found.  */
4868
4869 static struct dwo_unit *
4870 lookup_dwo_unit (struct dwarf2_per_cu_data *this_cu,
4871                  struct die_info *comp_unit_die)
4872 {
4873   struct dwarf2_cu *cu = this_cu->cu;
4874   struct attribute *attr;
4875   ULONGEST signature;
4876   struct dwo_unit *dwo_unit;
4877   const char *comp_dir, *dwo_name;
4878
4879   gdb_assert (cu != NULL);
4880
4881   /* Yeah, we look dwo_name up again, but it simplifies the code.  */
4882   attr = dwarf2_attr (comp_unit_die, DW_AT_GNU_dwo_name, cu);
4883   gdb_assert (attr != NULL);
4884   dwo_name = DW_STRING (attr);
4885   comp_dir = NULL;
4886   attr = dwarf2_attr (comp_unit_die, DW_AT_comp_dir, cu);
4887   if (attr)
4888     comp_dir = DW_STRING (attr);
4889
4890   if (this_cu->is_debug_types)
4891     {
4892       struct signatured_type *sig_type;
4893
4894       /* Since this_cu is the first member of struct signatured_type,
4895          we can go from a pointer to one to a pointer to the other.  */
4896       sig_type = (struct signatured_type *) this_cu;
4897       signature = sig_type->signature;
4898       dwo_unit = lookup_dwo_type_unit (sig_type, dwo_name, comp_dir);
4899     }
4900   else
4901     {
4902       struct attribute *attr;
4903
4904       attr = dwarf2_attr (comp_unit_die, DW_AT_GNU_dwo_id, cu);
4905       if (! attr)
4906         error (_("Dwarf Error: missing dwo_id for dwo_name %s"
4907                  " [in module %s]"),
4908                dwo_name, this_cu->objfile->name);
4909       signature = DW_UNSND (attr);
4910       dwo_unit = lookup_dwo_comp_unit (this_cu, dwo_name, comp_dir,
4911                                        signature);
4912     }
4913
4914   return dwo_unit;
4915 }
4916
4917 /* Subroutine of init_cutu_and_read_dies to simplify it.
4918    Read a TU directly from a DWO file, bypassing the stub.  */
4919
4920 static void
4921 init_tu_and_read_dwo_dies (struct dwarf2_per_cu_data *this_cu, int keep,
4922                            die_reader_func_ftype *die_reader_func,
4923                            void *data)
4924 {
4925   struct dwarf2_cu *cu;
4926   struct signatured_type *sig_type;
4927   struct cleanup *cleanups, *free_cu_cleanup;
4928   struct die_reader_specs reader;
4929   const gdb_byte *info_ptr;
4930   struct die_info *comp_unit_die;
4931   int has_children;
4932
4933   /* Verify we can do the following downcast, and that we have the
4934      data we need.  */
4935   gdb_assert (this_cu->is_debug_types && this_cu->reading_dwo_directly);
4936   sig_type = (struct signatured_type *) this_cu;
4937   gdb_assert (sig_type->dwo_unit != NULL);
4938
4939   cleanups = make_cleanup (null_cleanup, NULL);
4940
4941   gdb_assert (this_cu->cu == NULL);
4942   cu = xmalloc (sizeof (*cu));
4943   init_one_comp_unit (cu, this_cu);
4944   /* If an error occurs while loading, release our storage.  */
4945   free_cu_cleanup = make_cleanup (free_heap_comp_unit, cu);
4946
4947   if (read_cutu_die_from_dwo (this_cu, sig_type->dwo_unit,
4948                               0 /* abbrev_table_provided */,
4949                               NULL /* stub_comp_unit_die */,
4950                               sig_type->dwo_unit->dwo_file->comp_dir,
4951                               &reader, &info_ptr,
4952                               &comp_unit_die, &has_children) == 0)
4953     {
4954       /* Dummy die.  */
4955       do_cleanups (cleanups);
4956       return;
4957     }
4958
4959   /* All the "real" work is done here.  */
4960   die_reader_func (&reader, info_ptr, comp_unit_die, has_children, data);
4961
4962   /* This duplicates some code in init_cutu_and_read_dies,
4963      but the alternative is making the latter more complex.
4964      This function is only for the special case of using DWO files directly:
4965      no point in overly complicating the general case just to handle this.  */
4966   if (keep)
4967     {
4968       /* We've successfully allocated this compilation unit.  Let our
4969          caller clean it up when finished with it.  */
4970       discard_cleanups (free_cu_cleanup);
4971
4972       /* We can only discard free_cu_cleanup and all subsequent cleanups.
4973          So we have to manually free the abbrev table.  */
4974       dwarf2_free_abbrev_table (cu);
4975
4976       /* Link this CU into read_in_chain.  */
4977       this_cu->cu->read_in_chain = dwarf2_per_objfile->read_in_chain;
4978       dwarf2_per_objfile->read_in_chain = this_cu;
4979     }
4980   else
4981     do_cleanups (free_cu_cleanup);
4982
4983   do_cleanups (cleanups);
4984 }
4985
4986 /* Initialize a CU (or TU) and read its DIEs.
4987    If the CU defers to a DWO file, read the DWO file as well.
4988
4989    ABBREV_TABLE, if non-NULL, is the abbreviation table to use.
4990    Otherwise the table specified in the comp unit header is read in and used.
4991    This is an optimization for when we already have the abbrev table.
4992
4993    If USE_EXISTING_CU is non-zero, and THIS_CU->cu is non-NULL, then use it.
4994    Otherwise, a new CU is allocated with xmalloc.
4995
4996    If KEEP is non-zero, then if we allocated a dwarf2_cu we add it to
4997    read_in_chain.  Otherwise the dwarf2_cu data is freed at the end.
4998
4999    WARNING: If THIS_CU is a "dummy CU" (used as filler by the incremental
5000    linker) then DIE_READER_FUNC will not get called.  */
5001
5002 static void
5003 init_cutu_and_read_dies (struct dwarf2_per_cu_data *this_cu,
5004                          struct abbrev_table *abbrev_table,
5005                          int use_existing_cu, int keep,
5006                          die_reader_func_ftype *die_reader_func,
5007                          void *data)
5008 {
5009   struct objfile *objfile = dwarf2_per_objfile->objfile;
5010   struct dwarf2_section_info *section = this_cu->section;
5011   bfd *abfd = section->asection->owner;
5012   struct dwarf2_cu *cu;
5013   const gdb_byte *begin_info_ptr, *info_ptr;
5014   struct die_reader_specs reader;
5015   struct die_info *comp_unit_die;
5016   int has_children;
5017   struct attribute *attr;
5018   struct cleanup *cleanups;
5019   struct signatured_type *sig_type = NULL;
5020   struct dwarf2_section_info *abbrev_section;
5021   /* Non-zero if CU currently points to a DWO file and we need to
5022      reread it.  When this happens we need to reread the skeleton die
5023      before we can reread the DWO file (this only applies to CUs, not TUs).  */
5024   int rereading_dwo_cu = 0;
5025
5026   if (dwarf2_die_debug)
5027     fprintf_unfiltered (gdb_stdlog, "Reading %s unit at offset 0x%x\n",
5028                         this_cu->is_debug_types ? "type" : "comp",
5029                         this_cu->offset.sect_off);
5030
5031   if (use_existing_cu)
5032     gdb_assert (keep);
5033
5034   /* If we're reading a TU directly from a DWO file, including a virtual DWO
5035      file (instead of going through the stub), short-circuit all of this.  */
5036   if (this_cu->reading_dwo_directly)
5037     {
5038       /* Narrow down the scope of possibilities to have to understand.  */
5039       gdb_assert (this_cu->is_debug_types);
5040       gdb_assert (abbrev_table == NULL);
5041       gdb_assert (!use_existing_cu);
5042       init_tu_and_read_dwo_dies (this_cu, keep, die_reader_func, data);
5043       return;
5044     }
5045
5046   cleanups = make_cleanup (null_cleanup, NULL);
5047
5048   /* This is cheap if the section is already read in.  */
5049   dwarf2_read_section (objfile, section);
5050
5051   begin_info_ptr = info_ptr = section->buffer + this_cu->offset.sect_off;
5052
5053   abbrev_section = get_abbrev_section_for_cu (this_cu);
5054
5055   if (use_existing_cu && this_cu->cu != NULL)
5056     {
5057       cu = this_cu->cu;
5058
5059       /* If this CU is from a DWO file we need to start over, we need to
5060          refetch the attributes from the skeleton CU.
5061          This could be optimized by retrieving those attributes from when we
5062          were here the first time: the previous comp_unit_die was stored in
5063          comp_unit_obstack.  But there's no data yet that we need this
5064          optimization.  */
5065       if (cu->dwo_unit != NULL)
5066         rereading_dwo_cu = 1;
5067     }
5068   else
5069     {
5070       /* If !use_existing_cu, this_cu->cu must be NULL.  */
5071       gdb_assert (this_cu->cu == NULL);
5072
5073       cu = xmalloc (sizeof (*cu));
5074       init_one_comp_unit (cu, this_cu);
5075
5076       /* If an error occurs while loading, release our storage.  */
5077       make_cleanup (free_heap_comp_unit, cu);
5078     }
5079
5080   /* Get the header.  */
5081   if (cu->header.first_die_offset.cu_off != 0 && ! rereading_dwo_cu)
5082     {
5083       /* We already have the header, there's no need to read it in again.  */
5084       info_ptr += cu->header.first_die_offset.cu_off;
5085     }
5086   else
5087     {
5088       if (this_cu->is_debug_types)
5089         {
5090           ULONGEST signature;
5091           cu_offset type_offset_in_tu;
5092
5093           info_ptr = read_and_check_type_unit_head (&cu->header, section,
5094                                                     abbrev_section, info_ptr,
5095                                                     &signature,
5096                                                     &type_offset_in_tu);
5097
5098           /* Since per_cu is the first member of struct signatured_type,
5099              we can go from a pointer to one to a pointer to the other.  */
5100           sig_type = (struct signatured_type *) this_cu;
5101           gdb_assert (sig_type->signature == signature);
5102           gdb_assert (sig_type->type_offset_in_tu.cu_off
5103                       == type_offset_in_tu.cu_off);
5104           gdb_assert (this_cu->offset.sect_off == cu->header.offset.sect_off);
5105
5106           /* LENGTH has not been set yet for type units if we're
5107              using .gdb_index.  */
5108           this_cu->length = get_cu_length (&cu->header);
5109
5110           /* Establish the type offset that can be used to lookup the type.  */
5111           sig_type->type_offset_in_section.sect_off =
5112             this_cu->offset.sect_off + sig_type->type_offset_in_tu.cu_off;
5113         }
5114       else
5115         {
5116           info_ptr = read_and_check_comp_unit_head (&cu->header, section,
5117                                                     abbrev_section,
5118                                                     info_ptr, 0);
5119
5120           gdb_assert (this_cu->offset.sect_off == cu->header.offset.sect_off);
5121           gdb_assert (this_cu->length == get_cu_length (&cu->header));
5122         }
5123     }
5124
5125   /* Skip dummy compilation units.  */
5126   if (info_ptr >= begin_info_ptr + this_cu->length
5127       || peek_abbrev_code (abfd, info_ptr) == 0)
5128     {
5129       do_cleanups (cleanups);
5130       return;
5131     }
5132
5133   /* If we don't have them yet, read the abbrevs for this compilation unit.
5134      And if we need to read them now, make sure they're freed when we're
5135      done.  Note that it's important that if the CU had an abbrev table
5136      on entry we don't free it when we're done: Somewhere up the call stack
5137      it may be in use.  */
5138   if (abbrev_table != NULL)
5139     {
5140       gdb_assert (cu->abbrev_table == NULL);
5141       gdb_assert (cu->header.abbrev_offset.sect_off
5142                   == abbrev_table->offset.sect_off);
5143       cu->abbrev_table = abbrev_table;
5144     }
5145   else if (cu->abbrev_table == NULL)
5146     {
5147       dwarf2_read_abbrevs (cu, abbrev_section);
5148       make_cleanup (dwarf2_free_abbrev_table, cu);
5149     }
5150   else if (rereading_dwo_cu)
5151     {
5152       dwarf2_free_abbrev_table (cu);
5153       dwarf2_read_abbrevs (cu, abbrev_section);
5154     }
5155
5156   /* Read the top level CU/TU die.  */
5157   init_cu_die_reader (&reader, cu, section, NULL);
5158   info_ptr = read_full_die (&reader, &comp_unit_die, info_ptr, &has_children);
5159
5160   /* If we are in a DWO stub, process it and then read in the "real" CU/TU
5161      from the DWO file.
5162      Note that if USE_EXISTING_OK != 0, and THIS_CU->cu already contains a
5163      DWO CU, that this test will fail (the attribute will not be present).  */
5164   attr = dwarf2_attr (comp_unit_die, DW_AT_GNU_dwo_name, cu);
5165   if (attr)
5166     {
5167       struct dwo_unit *dwo_unit;
5168       struct die_info *dwo_comp_unit_die;
5169
5170       if (has_children)
5171         {
5172           complaint (&symfile_complaints,
5173                      _("compilation unit with DW_AT_GNU_dwo_name"
5174                        " has children (offset 0x%x) [in module %s]"),
5175                      this_cu->offset.sect_off, bfd_get_filename (abfd));
5176         }
5177       dwo_unit = lookup_dwo_unit (this_cu, comp_unit_die);
5178       if (dwo_unit != NULL)
5179         {
5180           if (read_cutu_die_from_dwo (this_cu, dwo_unit,
5181                                       abbrev_table != NULL,
5182                                       comp_unit_die, NULL,
5183                                       &reader, &info_ptr,
5184                                       &dwo_comp_unit_die, &has_children) == 0)
5185             {
5186               /* Dummy die.  */
5187               do_cleanups (cleanups);
5188               return;
5189             }
5190           comp_unit_die = dwo_comp_unit_die;
5191         }
5192       else
5193         {
5194           /* Yikes, we couldn't find the rest of the DIE, we only have
5195              the stub.  A complaint has already been logged.  There's
5196              not much more we can do except pass on the stub DIE to
5197              die_reader_func.  We don't want to throw an error on bad
5198              debug info.  */
5199         }
5200     }
5201
5202   /* All of the above is setup for this call.  Yikes.  */
5203   die_reader_func (&reader, info_ptr, comp_unit_die, has_children, data);
5204
5205   /* Done, clean up.  */
5206   if (keep)
5207     {
5208       /* We've successfully allocated this compilation unit.  Let our
5209          caller clean it up when finished with it.  */
5210       discard_cleanups (cleanups);
5211
5212       /* We can only discard free_cu_cleanup and all subsequent cleanups.
5213          So we have to manually free the abbrev table.  */
5214       dwarf2_free_abbrev_table (cu);
5215
5216       /* Link this CU into read_in_chain.  */
5217       this_cu->cu->read_in_chain = dwarf2_per_objfile->read_in_chain;
5218       dwarf2_per_objfile->read_in_chain = this_cu;
5219     }
5220   else
5221     do_cleanups (cleanups);
5222 }
5223
5224 /* Read CU/TU THIS_CU in section SECTION,
5225    but do not follow DW_AT_GNU_dwo_name if present.
5226    DWOP_FILE, if non-NULL, is the DWO/DWP file to read (the caller is assumed
5227    to have already done the lookup to find the DWO/DWP file).
5228
5229    The caller is required to fill in THIS_CU->section, THIS_CU->offset, and
5230    THIS_CU->is_debug_types, but nothing else.
5231
5232    We fill in THIS_CU->length.
5233
5234    WARNING: If THIS_CU is a "dummy CU" (used as filler by the incremental
5235    linker) then DIE_READER_FUNC will not get called.
5236
5237    THIS_CU->cu is always freed when done.
5238    This is done in order to not leave THIS_CU->cu in a state where we have
5239    to care whether it refers to the "main" CU or the DWO CU.  */
5240
5241 static void
5242 init_cutu_and_read_dies_no_follow (struct dwarf2_per_cu_data *this_cu,
5243                                    struct dwarf2_section_info *abbrev_section,
5244                                    struct dwo_file *dwo_file,
5245                                    die_reader_func_ftype *die_reader_func,
5246                                    void *data)
5247 {
5248   struct objfile *objfile = dwarf2_per_objfile->objfile;
5249   struct dwarf2_section_info *section = this_cu->section;
5250   bfd *abfd = section->asection->owner;
5251   struct dwarf2_cu cu;
5252   const gdb_byte *begin_info_ptr, *info_ptr;
5253   struct die_reader_specs reader;
5254   struct cleanup *cleanups;
5255   struct die_info *comp_unit_die;
5256   int has_children;
5257
5258   if (dwarf2_die_debug)
5259     fprintf_unfiltered (gdb_stdlog, "Reading %s unit at offset 0x%x\n",
5260                         this_cu->is_debug_types ? "type" : "comp",
5261                         this_cu->offset.sect_off);
5262
5263   gdb_assert (this_cu->cu == NULL);
5264
5265   /* This is cheap if the section is already read in.  */
5266   dwarf2_read_section (objfile, section);
5267
5268   init_one_comp_unit (&cu, this_cu);
5269
5270   cleanups = make_cleanup (free_stack_comp_unit, &cu);
5271
5272   begin_info_ptr = info_ptr = section->buffer + this_cu->offset.sect_off;
5273   info_ptr = read_and_check_comp_unit_head (&cu.header, section,
5274                                             abbrev_section, info_ptr,
5275                                             this_cu->is_debug_types);
5276
5277   this_cu->length = get_cu_length (&cu.header);
5278
5279   /* Skip dummy compilation units.  */
5280   if (info_ptr >= begin_info_ptr + this_cu->length
5281       || peek_abbrev_code (abfd, info_ptr) == 0)
5282     {
5283       do_cleanups (cleanups);
5284       return;
5285     }
5286
5287   dwarf2_read_abbrevs (&cu, abbrev_section);
5288   make_cleanup (dwarf2_free_abbrev_table, &cu);
5289
5290   init_cu_die_reader (&reader, &cu, section, dwo_file);
5291   info_ptr = read_full_die (&reader, &comp_unit_die, info_ptr, &has_children);
5292
5293   die_reader_func (&reader, info_ptr, comp_unit_die, has_children, data);
5294
5295   do_cleanups (cleanups);
5296 }
5297
5298 /* Read a CU/TU, except that this does not look for DW_AT_GNU_dwo_name and
5299    does not lookup the specified DWO file.
5300    This cannot be used to read DWO files.
5301
5302    THIS_CU->cu is always freed when done.
5303    This is done in order to not leave THIS_CU->cu in a state where we have
5304    to care whether it refers to the "main" CU or the DWO CU.
5305    We can revisit this if the data shows there's a performance issue.  */
5306
5307 static void
5308 init_cutu_and_read_dies_simple (struct dwarf2_per_cu_data *this_cu,
5309                                 die_reader_func_ftype *die_reader_func,
5310                                 void *data)
5311 {
5312   init_cutu_and_read_dies_no_follow (this_cu,
5313                                      get_abbrev_section_for_cu (this_cu),
5314                                      NULL,
5315                                      die_reader_func, data);
5316 }
5317 \f
5318 /* Type Unit Groups.
5319
5320    Type Unit Groups are a way to collapse the set of all TUs (type units) into
5321    a more manageable set.  The grouping is done by DW_AT_stmt_list entry
5322    so that all types coming from the same compilation (.o file) are grouped
5323    together.  A future step could be to put the types in the same symtab as
5324    the CU the types ultimately came from.  */
5325
5326 static hashval_t
5327 hash_type_unit_group (const void *item)
5328 {
5329   const struct type_unit_group *tu_group = item;
5330
5331   return hash_stmt_list_entry (&tu_group->hash);
5332 }
5333
5334 static int
5335 eq_type_unit_group (const void *item_lhs, const void *item_rhs)
5336 {
5337   const struct type_unit_group *lhs = item_lhs;
5338   const struct type_unit_group *rhs = item_rhs;
5339
5340   return eq_stmt_list_entry (&lhs->hash, &rhs->hash);
5341 }
5342
5343 /* Allocate a hash table for type unit groups.  */
5344
5345 static htab_t
5346 allocate_type_unit_groups_table (void)
5347 {
5348   return htab_create_alloc_ex (3,
5349                                hash_type_unit_group,
5350                                eq_type_unit_group,
5351                                NULL,
5352                                &dwarf2_per_objfile->objfile->objfile_obstack,
5353                                hashtab_obstack_allocate,
5354                                dummy_obstack_deallocate);
5355 }
5356
5357 /* Type units that don't have DW_AT_stmt_list are grouped into their own
5358    partial symtabs.  We combine several TUs per psymtab to not let the size
5359    of any one psymtab grow too big.  */
5360 #define NO_STMT_LIST_TYPE_UNIT_PSYMTAB (1 << 31)
5361 #define NO_STMT_LIST_TYPE_UNIT_PSYMTAB_SIZE 10
5362
5363 /* Helper routine for get_type_unit_group.
5364    Create the type_unit_group object used to hold one or more TUs.  */
5365
5366 static struct type_unit_group *
5367 create_type_unit_group (struct dwarf2_cu *cu, sect_offset line_offset_struct)
5368 {
5369   struct objfile *objfile = dwarf2_per_objfile->objfile;
5370   struct dwarf2_per_cu_data *per_cu;
5371   struct type_unit_group *tu_group;
5372
5373   tu_group = OBSTACK_ZALLOC (&objfile->objfile_obstack,
5374                              struct type_unit_group);
5375   per_cu = &tu_group->per_cu;
5376   per_cu->objfile = objfile;
5377
5378   if (dwarf2_per_objfile->using_index)
5379     {
5380       per_cu->v.quick = OBSTACK_ZALLOC (&objfile->objfile_obstack,
5381                                         struct dwarf2_per_cu_quick_data);
5382     }
5383   else
5384     {
5385       unsigned int line_offset = line_offset_struct.sect_off;
5386       struct partial_symtab *pst;
5387       char *name;
5388
5389       /* Give the symtab a useful name for debug purposes.  */
5390       if ((line_offset & NO_STMT_LIST_TYPE_UNIT_PSYMTAB) != 0)
5391         name = xstrprintf ("<type_units_%d>",
5392                            (line_offset & ~NO_STMT_LIST_TYPE_UNIT_PSYMTAB));
5393       else
5394         name = xstrprintf ("<type_units_at_0x%x>", line_offset);
5395
5396       pst = create_partial_symtab (per_cu, name);
5397       pst->anonymous = 1;
5398
5399       xfree (name);
5400     }
5401
5402   tu_group->hash.dwo_unit = cu->dwo_unit;
5403   tu_group->hash.line_offset = line_offset_struct;
5404
5405   return tu_group;
5406 }
5407
5408 /* Look up the type_unit_group for type unit CU, and create it if necessary.
5409    STMT_LIST is a DW_AT_stmt_list attribute.  */
5410
5411 static struct type_unit_group *
5412 get_type_unit_group (struct dwarf2_cu *cu, struct attribute *stmt_list)
5413 {
5414   struct tu_stats *tu_stats = &dwarf2_per_objfile->tu_stats;
5415   struct type_unit_group *tu_group;
5416   void **slot;
5417   unsigned int line_offset;
5418   struct type_unit_group type_unit_group_for_lookup;
5419
5420   if (dwarf2_per_objfile->type_unit_groups == NULL)
5421     {
5422       dwarf2_per_objfile->type_unit_groups =
5423         allocate_type_unit_groups_table ();
5424     }
5425
5426   /* Do we need to create a new group, or can we use an existing one?  */
5427
5428   if (stmt_list)
5429     {
5430       line_offset = DW_UNSND (stmt_list);
5431       ++tu_stats->nr_symtab_sharers;
5432     }
5433   else
5434     {
5435       /* Ugh, no stmt_list.  Rare, but we have to handle it.
5436          We can do various things here like create one group per TU or
5437          spread them over multiple groups to split up the expansion work.
5438          To avoid worst case scenarios (too many groups or too large groups)
5439          we, umm, group them in bunches.  */
5440       line_offset = (NO_STMT_LIST_TYPE_UNIT_PSYMTAB
5441                      | (tu_stats->nr_stmt_less_type_units
5442                         / NO_STMT_LIST_TYPE_UNIT_PSYMTAB_SIZE));
5443       ++tu_stats->nr_stmt_less_type_units;
5444     }
5445
5446   type_unit_group_for_lookup.hash.dwo_unit = cu->dwo_unit;
5447   type_unit_group_for_lookup.hash.line_offset.sect_off = line_offset;
5448   slot = htab_find_slot (dwarf2_per_objfile->type_unit_groups,
5449                          &type_unit_group_for_lookup, INSERT);
5450   if (*slot != NULL)
5451     {
5452       tu_group = *slot;
5453       gdb_assert (tu_group != NULL);
5454     }
5455   else
5456     {
5457       sect_offset line_offset_struct;
5458
5459       line_offset_struct.sect_off = line_offset;
5460       tu_group = create_type_unit_group (cu, line_offset_struct);
5461       *slot = tu_group;
5462       ++tu_stats->nr_symtabs;
5463     }
5464
5465   return tu_group;
5466 }
5467
5468 /* Struct used to sort TUs by their abbreviation table offset.  */
5469
5470 struct tu_abbrev_offset
5471 {
5472   struct signatured_type *sig_type;
5473   sect_offset abbrev_offset;
5474 };
5475
5476 /* Helper routine for build_type_unit_groups, passed to qsort.  */
5477
5478 static int
5479 sort_tu_by_abbrev_offset (const void *ap, const void *bp)
5480 {
5481   const struct tu_abbrev_offset * const *a = ap;
5482   const struct tu_abbrev_offset * const *b = bp;
5483   unsigned int aoff = (*a)->abbrev_offset.sect_off;
5484   unsigned int boff = (*b)->abbrev_offset.sect_off;
5485
5486   return (aoff > boff) - (aoff < boff);
5487 }
5488
5489 /* A helper function to add a type_unit_group to a table.  */
5490
5491 static int
5492 add_type_unit_group_to_table (void **slot, void *datum)
5493 {
5494   struct type_unit_group *tu_group = *slot;
5495   struct type_unit_group ***datap = datum;
5496
5497   **datap = tu_group;
5498   ++*datap;
5499
5500   return 1;
5501 }
5502
5503 /* Efficiently read all the type units, calling init_cutu_and_read_dies on
5504    each one passing FUNC,DATA.
5505
5506    The efficiency is because we sort TUs by the abbrev table they use and
5507    only read each abbrev table once.  In one program there are 200K TUs
5508    sharing 8K abbrev tables.
5509
5510    The main purpose of this function is to support building the
5511    dwarf2_per_objfile->type_unit_groups table.
5512    TUs typically share the DW_AT_stmt_list of the CU they came from, so we
5513    can collapse the search space by grouping them by stmt_list.
5514    The savings can be significant, in the same program from above the 200K TUs
5515    share 8K stmt_list tables.
5516
5517    FUNC is expected to call get_type_unit_group, which will create the
5518    struct type_unit_group if necessary and add it to
5519    dwarf2_per_objfile->type_unit_groups.  */
5520
5521 static void
5522 build_type_unit_groups (die_reader_func_ftype *func, void *data)
5523 {
5524   struct objfile *objfile = dwarf2_per_objfile->objfile;
5525   struct tu_stats *tu_stats = &dwarf2_per_objfile->tu_stats;
5526   struct cleanup *cleanups;
5527   struct abbrev_table *abbrev_table;
5528   sect_offset abbrev_offset;
5529   struct tu_abbrev_offset *sorted_by_abbrev;
5530   struct type_unit_group **iter;
5531   int i;
5532
5533   /* It's up to the caller to not call us multiple times.  */
5534   gdb_assert (dwarf2_per_objfile->type_unit_groups == NULL);
5535
5536   if (dwarf2_per_objfile->n_type_units == 0)
5537     return;
5538
5539   /* TUs typically share abbrev tables, and there can be way more TUs than
5540      abbrev tables.  Sort by abbrev table to reduce the number of times we
5541      read each abbrev table in.
5542      Alternatives are to punt or to maintain a cache of abbrev tables.
5543      This is simpler and efficient enough for now.
5544
5545      Later we group TUs by their DW_AT_stmt_list value (as this defines the
5546      symtab to use).  Typically TUs with the same abbrev offset have the same
5547      stmt_list value too so in practice this should work well.
5548
5549      The basic algorithm here is:
5550
5551       sort TUs by abbrev table
5552       for each TU with same abbrev table:
5553         read abbrev table if first user
5554         read TU top level DIE
5555           [IWBN if DWO skeletons had DW_AT_stmt_list]
5556         call FUNC  */
5557
5558   if (dwarf2_read_debug)
5559     fprintf_unfiltered (gdb_stdlog, "Building type unit groups ...\n");
5560
5561   /* Sort in a separate table to maintain the order of all_type_units
5562      for .gdb_index: TU indices directly index all_type_units.  */
5563   sorted_by_abbrev = XNEWVEC (struct tu_abbrev_offset,
5564                               dwarf2_per_objfile->n_type_units);
5565   for (i = 0; i < dwarf2_per_objfile->n_type_units; ++i)
5566     {
5567       struct signatured_type *sig_type = dwarf2_per_objfile->all_type_units[i];
5568
5569       sorted_by_abbrev[i].sig_type = sig_type;
5570       sorted_by_abbrev[i].abbrev_offset =
5571         read_abbrev_offset (sig_type->per_cu.section,
5572                             sig_type->per_cu.offset);
5573     }
5574   cleanups = make_cleanup (xfree, sorted_by_abbrev);
5575   qsort (sorted_by_abbrev, dwarf2_per_objfile->n_type_units,
5576          sizeof (struct tu_abbrev_offset), sort_tu_by_abbrev_offset);
5577
5578   /* Note: In the .gdb_index case, get_type_unit_group may have already been
5579      called any number of times, so we don't reset tu_stats here.  */
5580
5581   abbrev_offset.sect_off = ~(unsigned) 0;
5582   abbrev_table = NULL;
5583   make_cleanup (abbrev_table_free_cleanup, &abbrev_table);
5584
5585   for (i = 0; i < dwarf2_per_objfile->n_type_units; ++i)
5586     {
5587       const struct tu_abbrev_offset *tu = &sorted_by_abbrev[i];
5588
5589       /* Switch to the next abbrev table if necessary.  */
5590       if (abbrev_table == NULL
5591           || tu->abbrev_offset.sect_off != abbrev_offset.sect_off)
5592         {
5593           if (abbrev_table != NULL)
5594             {
5595               abbrev_table_free (abbrev_table);
5596               /* Reset to NULL in case abbrev_table_read_table throws
5597                  an error: abbrev_table_free_cleanup will get called.  */
5598               abbrev_table = NULL;
5599             }
5600           abbrev_offset = tu->abbrev_offset;
5601           abbrev_table =
5602             abbrev_table_read_table (&dwarf2_per_objfile->abbrev,
5603                                      abbrev_offset);
5604           ++tu_stats->nr_uniq_abbrev_tables;
5605         }
5606
5607       init_cutu_and_read_dies (&tu->sig_type->per_cu, abbrev_table, 0, 0,
5608                                func, data);
5609     }
5610
5611   /* type_unit_groups can be NULL if there is an error in the debug info.
5612      Just create an empty table so the rest of gdb doesn't have to watch
5613      for this error case.  */
5614   if (dwarf2_per_objfile->type_unit_groups == NULL)
5615     {
5616       dwarf2_per_objfile->type_unit_groups =
5617         allocate_type_unit_groups_table ();
5618       dwarf2_per_objfile->n_type_unit_groups = 0;
5619     }
5620
5621   /* Create a vector of pointers to primary type units to make it easy to
5622      iterate over them and CUs.  See dw2_get_primary_cu.  */
5623   dwarf2_per_objfile->n_type_unit_groups =
5624     htab_elements (dwarf2_per_objfile->type_unit_groups);
5625   dwarf2_per_objfile->all_type_unit_groups =
5626     obstack_alloc (&objfile->objfile_obstack,
5627                    dwarf2_per_objfile->n_type_unit_groups
5628                    * sizeof (struct type_unit_group *));
5629   iter = &dwarf2_per_objfile->all_type_unit_groups[0];
5630   htab_traverse_noresize (dwarf2_per_objfile->type_unit_groups,
5631                           add_type_unit_group_to_table, &iter);
5632   gdb_assert (iter - &dwarf2_per_objfile->all_type_unit_groups[0]
5633               == dwarf2_per_objfile->n_type_unit_groups);
5634
5635   do_cleanups (cleanups);
5636
5637   if (dwarf2_read_debug)
5638     {
5639       fprintf_unfiltered (gdb_stdlog, "Done building type unit groups:\n");
5640       fprintf_unfiltered (gdb_stdlog, "  %d TUs\n",
5641                           dwarf2_per_objfile->n_type_units);
5642       fprintf_unfiltered (gdb_stdlog, "  %d uniq abbrev tables\n",
5643                           tu_stats->nr_uniq_abbrev_tables);
5644       fprintf_unfiltered (gdb_stdlog, "  %d symtabs from stmt_list entries\n",
5645                           tu_stats->nr_symtabs);
5646       fprintf_unfiltered (gdb_stdlog, "  %d symtab sharers\n",
5647                           tu_stats->nr_symtab_sharers);
5648       fprintf_unfiltered (gdb_stdlog, "  %d type units without a stmt_list\n",
5649                           tu_stats->nr_stmt_less_type_units);
5650     }
5651 }
5652 \f
5653 /* Partial symbol tables.  */
5654
5655 /* Create a psymtab named NAME and assign it to PER_CU.
5656
5657    The caller must fill in the following details:
5658    dirname, textlow, texthigh.  */
5659
5660 static struct partial_symtab *
5661 create_partial_symtab (struct dwarf2_per_cu_data *per_cu, const char *name)
5662 {
5663   struct objfile *objfile = per_cu->objfile;
5664   struct partial_symtab *pst;
5665
5666   pst = start_psymtab_common (objfile, objfile->section_offsets,
5667                               name, 0,
5668                               objfile->global_psymbols.next,
5669                               objfile->static_psymbols.next);
5670
5671   pst->psymtabs_addrmap_supported = 1;
5672
5673   /* This is the glue that links PST into GDB's symbol API.  */
5674   pst->read_symtab_private = per_cu;
5675   pst->read_symtab = dwarf2_read_symtab;
5676   per_cu->v.psymtab = pst;
5677
5678   return pst;
5679 }
5680
5681 /* die_reader_func for process_psymtab_comp_unit.  */
5682
5683 static void
5684 process_psymtab_comp_unit_reader (const struct die_reader_specs *reader,
5685                                   const gdb_byte *info_ptr,
5686                                   struct die_info *comp_unit_die,
5687                                   int has_children,
5688                                   void *data)
5689 {
5690   struct dwarf2_cu *cu = reader->cu;
5691   struct objfile *objfile = cu->objfile;
5692   struct dwarf2_per_cu_data *per_cu = cu->per_cu;
5693   struct attribute *attr;
5694   CORE_ADDR baseaddr;
5695   CORE_ADDR best_lowpc = 0, best_highpc = 0;
5696   struct partial_symtab *pst;
5697   int has_pc_info;
5698   const char *filename;
5699   int *want_partial_unit_ptr = data;
5700
5701   if (comp_unit_die->tag == DW_TAG_partial_unit
5702       && (want_partial_unit_ptr == NULL
5703           || !*want_partial_unit_ptr))
5704     return;
5705
5706   gdb_assert (! per_cu->is_debug_types);
5707
5708   prepare_one_comp_unit (cu, comp_unit_die, language_minimal);
5709
5710   cu->list_in_scope = &file_symbols;
5711
5712   /* Allocate a new partial symbol table structure.  */
5713   attr = dwarf2_attr (comp_unit_die, DW_AT_name, cu);
5714   if (attr == NULL || !DW_STRING (attr))
5715     filename = "";
5716   else
5717     filename = DW_STRING (attr);
5718
5719   pst = create_partial_symtab (per_cu, filename);
5720
5721   /* This must be done before calling dwarf2_build_include_psymtabs.  */
5722   attr = dwarf2_attr (comp_unit_die, DW_AT_comp_dir, cu);
5723   if (attr != NULL)
5724     pst->dirname = DW_STRING (attr);
5725
5726   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
5727
5728   dwarf2_find_base_address (comp_unit_die, cu);
5729
5730   /* Possibly set the default values of LOWPC and HIGHPC from
5731      `DW_AT_ranges'.  */
5732   has_pc_info = dwarf2_get_pc_bounds (comp_unit_die, &best_lowpc,
5733                                       &best_highpc, cu, pst);
5734   if (has_pc_info == 1 && best_lowpc < best_highpc)
5735     /* Store the contiguous range if it is not empty; it can be empty for
5736        CUs with no code.  */
5737     addrmap_set_empty (objfile->psymtabs_addrmap,
5738                        best_lowpc + baseaddr,
5739                        best_highpc + baseaddr - 1, pst);
5740
5741   /* Check if comp unit has_children.
5742      If so, read the rest of the partial symbols from this comp unit.
5743      If not, there's no more debug_info for this comp unit.  */
5744   if (has_children)
5745     {
5746       struct partial_die_info *first_die;
5747       CORE_ADDR lowpc, highpc;
5748
5749       lowpc = ((CORE_ADDR) -1);
5750       highpc = ((CORE_ADDR) 0);
5751
5752       first_die = load_partial_dies (reader, info_ptr, 1);
5753
5754       scan_partial_symbols (first_die, &lowpc, &highpc,
5755                             ! has_pc_info, cu);
5756
5757       /* If we didn't find a lowpc, set it to highpc to avoid
5758          complaints from `maint check'.  */
5759       if (lowpc == ((CORE_ADDR) -1))
5760         lowpc = highpc;
5761
5762       /* If the compilation unit didn't have an explicit address range,
5763          then use the information extracted from its child dies.  */
5764       if (! has_pc_info)
5765         {
5766           best_lowpc = lowpc;
5767           best_highpc = highpc;
5768         }
5769     }
5770   pst->textlow = best_lowpc + baseaddr;
5771   pst->texthigh = best_highpc + baseaddr;
5772
5773   pst->n_global_syms = objfile->global_psymbols.next -
5774     (objfile->global_psymbols.list + pst->globals_offset);
5775   pst->n_static_syms = objfile->static_psymbols.next -
5776     (objfile->static_psymbols.list + pst->statics_offset);
5777   sort_pst_symbols (objfile, pst);
5778
5779   if (!VEC_empty (dwarf2_per_cu_ptr, cu->per_cu->imported_symtabs))
5780     {
5781       int i;
5782       int len = VEC_length (dwarf2_per_cu_ptr, cu->per_cu->imported_symtabs);
5783       struct dwarf2_per_cu_data *iter;
5784
5785       /* Fill in 'dependencies' here; we fill in 'users' in a
5786          post-pass.  */
5787       pst->number_of_dependencies = len;
5788       pst->dependencies = obstack_alloc (&objfile->objfile_obstack,
5789                                          len * sizeof (struct symtab *));
5790       for (i = 0;
5791            VEC_iterate (dwarf2_per_cu_ptr, cu->per_cu->imported_symtabs,
5792                         i, iter);
5793            ++i)
5794         pst->dependencies[i] = iter->v.psymtab;
5795
5796       VEC_free (dwarf2_per_cu_ptr, cu->per_cu->imported_symtabs);
5797     }
5798
5799   /* Get the list of files included in the current compilation unit,
5800      and build a psymtab for each of them.  */
5801   dwarf2_build_include_psymtabs (cu, comp_unit_die, pst);
5802
5803   if (dwarf2_read_debug)
5804     {
5805       struct gdbarch *gdbarch = get_objfile_arch (objfile);
5806
5807       fprintf_unfiltered (gdb_stdlog,
5808                           "Psymtab for %s unit @0x%x: %s - %s"
5809                           ", %d global, %d static syms\n",
5810                           per_cu->is_debug_types ? "type" : "comp",
5811                           per_cu->offset.sect_off,
5812                           paddress (gdbarch, pst->textlow),
5813                           paddress (gdbarch, pst->texthigh),
5814                           pst->n_global_syms, pst->n_static_syms);
5815     }
5816 }
5817
5818 /* Subroutine of dwarf2_build_psymtabs_hard to simplify it.
5819    Process compilation unit THIS_CU for a psymtab.  */
5820
5821 static void
5822 process_psymtab_comp_unit (struct dwarf2_per_cu_data *this_cu,
5823                            int want_partial_unit)
5824 {
5825   /* If this compilation unit was already read in, free the
5826      cached copy in order to read it in again.  This is
5827      necessary because we skipped some symbols when we first
5828      read in the compilation unit (see load_partial_dies).
5829      This problem could be avoided, but the benefit is unclear.  */
5830   if (this_cu->cu != NULL)
5831     free_one_cached_comp_unit (this_cu);
5832
5833   gdb_assert (! this_cu->is_debug_types);
5834   init_cutu_and_read_dies (this_cu, NULL, 0, 0,
5835                            process_psymtab_comp_unit_reader,
5836                            &want_partial_unit);
5837
5838   /* Age out any secondary CUs.  */
5839   age_cached_comp_units ();
5840 }
5841
5842 /* Reader function for build_type_psymtabs.  */
5843
5844 static void
5845 build_type_psymtabs_reader (const struct die_reader_specs *reader,
5846                             const gdb_byte *info_ptr,
5847                             struct die_info *type_unit_die,
5848                             int has_children,
5849                             void *data)
5850 {
5851   struct objfile *objfile = dwarf2_per_objfile->objfile;
5852   struct dwarf2_cu *cu = reader->cu;
5853   struct dwarf2_per_cu_data *per_cu = cu->per_cu;
5854   struct signatured_type *sig_type;
5855   struct type_unit_group *tu_group;
5856   struct attribute *attr;
5857   struct partial_die_info *first_die;
5858   CORE_ADDR lowpc, highpc;
5859   struct partial_symtab *pst;
5860
5861   gdb_assert (data == NULL);
5862   gdb_assert (per_cu->is_debug_types);
5863   sig_type = (struct signatured_type *) per_cu;
5864
5865   if (! has_children)
5866     return;
5867
5868   attr = dwarf2_attr_no_follow (type_unit_die, DW_AT_stmt_list);
5869   tu_group = get_type_unit_group (cu, attr);
5870
5871   VEC_safe_push (sig_type_ptr, tu_group->tus, sig_type);
5872
5873   prepare_one_comp_unit (cu, type_unit_die, language_minimal);
5874   cu->list_in_scope = &file_symbols;
5875   pst = create_partial_symtab (per_cu, "");
5876   pst->anonymous = 1;
5877
5878   first_die = load_partial_dies (reader, info_ptr, 1);
5879
5880   lowpc = (CORE_ADDR) -1;
5881   highpc = (CORE_ADDR) 0;
5882   scan_partial_symbols (first_die, &lowpc, &highpc, 0, cu);
5883
5884   pst->n_global_syms = objfile->global_psymbols.next -
5885     (objfile->global_psymbols.list + pst->globals_offset);
5886   pst->n_static_syms = objfile->static_psymbols.next -
5887     (objfile->static_psymbols.list + pst->statics_offset);
5888   sort_pst_symbols (objfile, pst);
5889 }
5890
5891 /* Traversal function for build_type_psymtabs.  */
5892
5893 static int
5894 build_type_psymtab_dependencies (void **slot, void *info)
5895 {
5896   struct objfile *objfile = dwarf2_per_objfile->objfile;
5897   struct type_unit_group *tu_group = (struct type_unit_group *) *slot;
5898   struct dwarf2_per_cu_data *per_cu = &tu_group->per_cu;
5899   struct partial_symtab *pst = per_cu->v.psymtab;
5900   int len = VEC_length (sig_type_ptr, tu_group->tus);
5901   struct signatured_type *iter;
5902   int i;
5903
5904   gdb_assert (len > 0);
5905   gdb_assert (IS_TYPE_UNIT_GROUP (per_cu));
5906
5907   pst->number_of_dependencies = len;
5908   pst->dependencies = obstack_alloc (&objfile->objfile_obstack,
5909                                      len * sizeof (struct psymtab *));
5910   for (i = 0;
5911        VEC_iterate (sig_type_ptr, tu_group->tus, i, iter);
5912        ++i)
5913     {
5914       gdb_assert (iter->per_cu.is_debug_types);
5915       pst->dependencies[i] = iter->per_cu.v.psymtab;
5916       iter->type_unit_group = tu_group;
5917     }
5918
5919   VEC_free (sig_type_ptr, tu_group->tus);
5920
5921   return 1;
5922 }
5923
5924 /* Subroutine of dwarf2_build_psymtabs_hard to simplify it.
5925    Build partial symbol tables for the .debug_types comp-units.  */
5926
5927 static void
5928 build_type_psymtabs (struct objfile *objfile)
5929 {
5930   if (! create_all_type_units (objfile))
5931     return;
5932
5933   build_type_unit_groups (build_type_psymtabs_reader, NULL);
5934
5935   /* Now that all TUs have been processed we can fill in the dependencies.  */
5936   htab_traverse_noresize (dwarf2_per_objfile->type_unit_groups,
5937                           build_type_psymtab_dependencies, NULL);
5938 }
5939
5940 /* A cleanup function that clears objfile's psymtabs_addrmap field.  */
5941
5942 static void
5943 psymtabs_addrmap_cleanup (void *o)
5944 {
5945   struct objfile *objfile = o;
5946
5947   objfile->psymtabs_addrmap = NULL;
5948 }
5949
5950 /* Compute the 'user' field for each psymtab in OBJFILE.  */
5951
5952 static void
5953 set_partial_user (struct objfile *objfile)
5954 {
5955   int i;
5956
5957   for (i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
5958     {
5959       struct dwarf2_per_cu_data *per_cu = dw2_get_cu (i);
5960       struct partial_symtab *pst = per_cu->v.psymtab;
5961       int j;
5962
5963       if (pst == NULL)
5964         continue;
5965
5966       for (j = 0; j < pst->number_of_dependencies; ++j)
5967         {
5968           /* Set the 'user' field only if it is not already set.  */
5969           if (pst->dependencies[j]->user == NULL)
5970             pst->dependencies[j]->user = pst;
5971         }
5972     }
5973 }
5974
5975 /* Build the partial symbol table by doing a quick pass through the
5976    .debug_info and .debug_abbrev sections.  */
5977
5978 static void
5979 dwarf2_build_psymtabs_hard (struct objfile *objfile)
5980 {
5981   struct cleanup *back_to, *addrmap_cleanup;
5982   struct obstack temp_obstack;
5983   int i;
5984
5985   if (dwarf2_read_debug)
5986     {
5987       fprintf_unfiltered (gdb_stdlog, "Building psymtabs of objfile %s ...\n",
5988                           objfile->name);
5989     }
5990
5991   dwarf2_per_objfile->reading_partial_symbols = 1;
5992
5993   dwarf2_read_section (objfile, &dwarf2_per_objfile->info);
5994
5995   /* Any cached compilation units will be linked by the per-objfile
5996      read_in_chain.  Make sure to free them when we're done.  */
5997   back_to = make_cleanup (free_cached_comp_units, NULL);
5998
5999   build_type_psymtabs (objfile);
6000
6001   create_all_comp_units (objfile);
6002
6003   /* Create a temporary address map on a temporary obstack.  We later
6004      copy this to the final obstack.  */
6005   obstack_init (&temp_obstack);
6006   make_cleanup_obstack_free (&temp_obstack);
6007   objfile->psymtabs_addrmap = addrmap_create_mutable (&temp_obstack);
6008   addrmap_cleanup = make_cleanup (psymtabs_addrmap_cleanup, objfile);
6009
6010   for (i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
6011     {
6012       struct dwarf2_per_cu_data *per_cu = dw2_get_cu (i);
6013
6014       process_psymtab_comp_unit (per_cu, 0);
6015     }
6016
6017   set_partial_user (objfile);
6018
6019   objfile->psymtabs_addrmap = addrmap_create_fixed (objfile->psymtabs_addrmap,
6020                                                     &objfile->objfile_obstack);
6021   discard_cleanups (addrmap_cleanup);
6022
6023   do_cleanups (back_to);
6024
6025   if (dwarf2_read_debug)
6026     fprintf_unfiltered (gdb_stdlog, "Done building psymtabs of %s\n",
6027                         objfile->name);
6028 }
6029
6030 /* die_reader_func for load_partial_comp_unit.  */
6031
6032 static void
6033 load_partial_comp_unit_reader (const struct die_reader_specs *reader,
6034                                const gdb_byte *info_ptr,
6035                                struct die_info *comp_unit_die,
6036                                int has_children,
6037                                void *data)
6038 {
6039   struct dwarf2_cu *cu = reader->cu;
6040
6041   prepare_one_comp_unit (cu, comp_unit_die, language_minimal);
6042
6043   /* Check if comp unit has_children.
6044      If so, read the rest of the partial symbols from this comp unit.
6045      If not, there's no more debug_info for this comp unit.  */
6046   if (has_children)
6047     load_partial_dies (reader, info_ptr, 0);
6048 }
6049
6050 /* Load the partial DIEs for a secondary CU into memory.
6051    This is also used when rereading a primary CU with load_all_dies.  */
6052
6053 static void
6054 load_partial_comp_unit (struct dwarf2_per_cu_data *this_cu)
6055 {
6056   init_cutu_and_read_dies (this_cu, NULL, 1, 1,
6057                            load_partial_comp_unit_reader, NULL);
6058 }
6059
6060 static void
6061 read_comp_units_from_section (struct objfile *objfile,
6062                               struct dwarf2_section_info *section,
6063                               unsigned int is_dwz,
6064                               int *n_allocated,
6065                               int *n_comp_units,
6066                               struct dwarf2_per_cu_data ***all_comp_units)
6067 {
6068   const gdb_byte *info_ptr;
6069   bfd *abfd = section->asection->owner;
6070
6071   if (dwarf2_read_debug)
6072     fprintf_unfiltered (gdb_stdlog, "Reading %s for %s\n",
6073                         section->asection->name, bfd_get_filename (abfd));
6074
6075   dwarf2_read_section (objfile, section);
6076
6077   info_ptr = section->buffer;
6078
6079   while (info_ptr < section->buffer + section->size)
6080     {
6081       unsigned int length, initial_length_size;
6082       struct dwarf2_per_cu_data *this_cu;
6083       sect_offset offset;
6084
6085       offset.sect_off = info_ptr - section->buffer;
6086
6087       /* Read just enough information to find out where the next
6088          compilation unit is.  */
6089       length = read_initial_length (abfd, info_ptr, &initial_length_size);
6090
6091       /* Save the compilation unit for later lookup.  */
6092       this_cu = obstack_alloc (&objfile->objfile_obstack,
6093                                sizeof (struct dwarf2_per_cu_data));
6094       memset (this_cu, 0, sizeof (*this_cu));
6095       this_cu->offset = offset;
6096       this_cu->length = length + initial_length_size;
6097       this_cu->is_dwz = is_dwz;
6098       this_cu->objfile = objfile;
6099       this_cu->section = section;
6100
6101       if (*n_comp_units == *n_allocated)
6102         {
6103           *n_allocated *= 2;
6104           *all_comp_units = xrealloc (*all_comp_units,
6105                                       *n_allocated
6106                                       * sizeof (struct dwarf2_per_cu_data *));
6107         }
6108       (*all_comp_units)[*n_comp_units] = this_cu;
6109       ++*n_comp_units;
6110
6111       info_ptr = info_ptr + this_cu->length;
6112     }
6113 }
6114
6115 /* Create a list of all compilation units in OBJFILE.
6116    This is only done for -readnow and building partial symtabs.  */
6117
6118 static void
6119 create_all_comp_units (struct objfile *objfile)
6120 {
6121   int n_allocated;
6122   int n_comp_units;
6123   struct dwarf2_per_cu_data **all_comp_units;
6124   struct dwz_file *dwz;
6125
6126   n_comp_units = 0;
6127   n_allocated = 10;
6128   all_comp_units = xmalloc (n_allocated
6129                             * sizeof (struct dwarf2_per_cu_data *));
6130
6131   read_comp_units_from_section (objfile, &dwarf2_per_objfile->info, 0,
6132                                 &n_allocated, &n_comp_units, &all_comp_units);
6133
6134   dwz = dwarf2_get_dwz_file ();
6135   if (dwz != NULL)
6136     read_comp_units_from_section (objfile, &dwz->info, 1,
6137                                   &n_allocated, &n_comp_units,
6138                                   &all_comp_units);
6139
6140   dwarf2_per_objfile->all_comp_units
6141     = obstack_alloc (&objfile->objfile_obstack,
6142                      n_comp_units * sizeof (struct dwarf2_per_cu_data *));
6143   memcpy (dwarf2_per_objfile->all_comp_units, all_comp_units,
6144           n_comp_units * sizeof (struct dwarf2_per_cu_data *));
6145   xfree (all_comp_units);
6146   dwarf2_per_objfile->n_comp_units = n_comp_units;
6147 }
6148
6149 /* Process all loaded DIEs for compilation unit CU, starting at
6150    FIRST_DIE.  The caller should pass NEED_PC == 1 if the compilation
6151    unit DIE did not have PC info (DW_AT_low_pc and DW_AT_high_pc, or
6152    DW_AT_ranges).  If NEED_PC is set, then this function will set
6153    *LOWPC and *HIGHPC to the lowest and highest PC values found in CU
6154    and record the covered ranges in the addrmap.  */
6155
6156 static void
6157 scan_partial_symbols (struct partial_die_info *first_die, CORE_ADDR *lowpc,
6158                       CORE_ADDR *highpc, int need_pc, struct dwarf2_cu *cu)
6159 {
6160   struct partial_die_info *pdi;
6161
6162   /* Now, march along the PDI's, descending into ones which have
6163      interesting children but skipping the children of the other ones,
6164      until we reach the end of the compilation unit.  */
6165
6166   pdi = first_die;
6167
6168   while (pdi != NULL)
6169     {
6170       fixup_partial_die (pdi, cu);
6171
6172       /* Anonymous namespaces or modules have no name but have interesting
6173          children, so we need to look at them.  Ditto for anonymous
6174          enums.  */
6175
6176       if (pdi->name != NULL || pdi->tag == DW_TAG_namespace
6177           || pdi->tag == DW_TAG_module || pdi->tag == DW_TAG_enumeration_type
6178           || pdi->tag == DW_TAG_imported_unit)
6179         {
6180           switch (pdi->tag)
6181             {
6182             case DW_TAG_subprogram:
6183               add_partial_subprogram (pdi, lowpc, highpc, need_pc, cu);
6184               break;
6185             case DW_TAG_constant:
6186             case DW_TAG_variable:
6187             case DW_TAG_typedef:
6188             case DW_TAG_union_type:
6189               if (!pdi->is_declaration)
6190                 {
6191                   add_partial_symbol (pdi, cu);
6192                 }
6193               break;
6194             case DW_TAG_class_type:
6195             case DW_TAG_interface_type:
6196             case DW_TAG_structure_type:
6197               if (!pdi->is_declaration)
6198                 {
6199                   add_partial_symbol (pdi, cu);
6200                 }
6201               break;
6202             case DW_TAG_enumeration_type:
6203               if (!pdi->is_declaration)
6204                 add_partial_enumeration (pdi, cu);
6205               break;
6206             case DW_TAG_base_type:
6207             case DW_TAG_subrange_type:
6208               /* File scope base type definitions are added to the partial
6209                  symbol table.  */
6210               add_partial_symbol (pdi, cu);
6211               break;
6212             case DW_TAG_namespace:
6213               add_partial_namespace (pdi, lowpc, highpc, need_pc, cu);
6214               break;
6215             case DW_TAG_module:
6216               add_partial_module (pdi, lowpc, highpc, need_pc, cu);
6217               break;
6218             case DW_TAG_imported_unit:
6219               {
6220                 struct dwarf2_per_cu_data *per_cu;
6221
6222                 /* For now we don't handle imported units in type units.  */
6223                 if (cu->per_cu->is_debug_types)
6224                   {
6225                     error (_("Dwarf Error: DW_TAG_imported_unit is not"
6226                              " supported in type units [in module %s]"),
6227                            cu->objfile->name);
6228                   }
6229
6230                 per_cu = dwarf2_find_containing_comp_unit (pdi->d.offset,
6231                                                            pdi->is_dwz,
6232                                                            cu->objfile);
6233
6234                 /* Go read the partial unit, if needed.  */
6235                 if (per_cu->v.psymtab == NULL)
6236                   process_psymtab_comp_unit (per_cu, 1);
6237
6238                 VEC_safe_push (dwarf2_per_cu_ptr,
6239                                cu->per_cu->imported_symtabs, per_cu);
6240               }
6241               break;
6242             default:
6243               break;
6244             }
6245         }
6246
6247       /* If the die has a sibling, skip to the sibling.  */
6248
6249       pdi = pdi->die_sibling;
6250     }
6251 }
6252
6253 /* Functions used to compute the fully scoped name of a partial DIE.
6254
6255    Normally, this is simple.  For C++, the parent DIE's fully scoped
6256    name is concatenated with "::" and the partial DIE's name.  For
6257    Java, the same thing occurs except that "." is used instead of "::".
6258    Enumerators are an exception; they use the scope of their parent
6259    enumeration type, i.e. the name of the enumeration type is not
6260    prepended to the enumerator.
6261
6262    There are two complexities.  One is DW_AT_specification; in this
6263    case "parent" means the parent of the target of the specification,
6264    instead of the direct parent of the DIE.  The other is compilers
6265    which do not emit DW_TAG_namespace; in this case we try to guess
6266    the fully qualified name of structure types from their members'
6267    linkage names.  This must be done using the DIE's children rather
6268    than the children of any DW_AT_specification target.  We only need
6269    to do this for structures at the top level, i.e. if the target of
6270    any DW_AT_specification (if any; otherwise the DIE itself) does not
6271    have a parent.  */
6272
6273 /* Compute the scope prefix associated with PDI's parent, in
6274    compilation unit CU.  The result will be allocated on CU's
6275    comp_unit_obstack, or a copy of the already allocated PDI->NAME
6276    field.  NULL is returned if no prefix is necessary.  */
6277 static const char *
6278 partial_die_parent_scope (struct partial_die_info *pdi,
6279                           struct dwarf2_cu *cu)
6280 {
6281   const char *grandparent_scope;
6282   struct partial_die_info *parent, *real_pdi;
6283
6284   /* We need to look at our parent DIE; if we have a DW_AT_specification,
6285      then this means the parent of the specification DIE.  */
6286
6287   real_pdi = pdi;
6288   while (real_pdi->has_specification)
6289     real_pdi = find_partial_die (real_pdi->spec_offset,
6290                                  real_pdi->spec_is_dwz, cu);
6291
6292   parent = real_pdi->die_parent;
6293   if (parent == NULL)
6294     return NULL;
6295
6296   if (parent->scope_set)
6297     return parent->scope;
6298
6299   fixup_partial_die (parent, cu);
6300
6301   grandparent_scope = partial_die_parent_scope (parent, cu);
6302
6303   /* GCC 4.0 and 4.1 had a bug (PR c++/28460) where they generated bogus
6304      DW_TAG_namespace DIEs with a name of "::" for the global namespace.
6305      Work around this problem here.  */
6306   if (cu->language == language_cplus
6307       && parent->tag == DW_TAG_namespace
6308       && strcmp (parent->name, "::") == 0
6309       && grandparent_scope == NULL)
6310     {
6311       parent->scope = NULL;
6312       parent->scope_set = 1;
6313       return NULL;
6314     }
6315
6316   if (pdi->tag == DW_TAG_enumerator)
6317     /* Enumerators should not get the name of the enumeration as a prefix.  */
6318     parent->scope = grandparent_scope;
6319   else if (parent->tag == DW_TAG_namespace
6320       || parent->tag == DW_TAG_module
6321       || parent->tag == DW_TAG_structure_type
6322       || parent->tag == DW_TAG_class_type
6323       || parent->tag == DW_TAG_interface_type
6324       || parent->tag == DW_TAG_union_type
6325       || parent->tag == DW_TAG_enumeration_type)
6326     {
6327       if (grandparent_scope == NULL)
6328         parent->scope = parent->name;
6329       else
6330         parent->scope = typename_concat (&cu->comp_unit_obstack,
6331                                          grandparent_scope,
6332                                          parent->name, 0, cu);
6333     }
6334   else
6335     {
6336       /* FIXME drow/2004-04-01: What should we be doing with
6337          function-local names?  For partial symbols, we should probably be
6338          ignoring them.  */
6339       complaint (&symfile_complaints,
6340                  _("unhandled containing DIE tag %d for DIE at %d"),
6341                  parent->tag, pdi->offset.sect_off);
6342       parent->scope = grandparent_scope;
6343     }
6344
6345   parent->scope_set = 1;
6346   return parent->scope;
6347 }
6348
6349 /* Return the fully scoped name associated with PDI, from compilation unit
6350    CU.  The result will be allocated with malloc.  */
6351
6352 static char *
6353 partial_die_full_name (struct partial_die_info *pdi,
6354                        struct dwarf2_cu *cu)
6355 {
6356   const char *parent_scope;
6357
6358   /* If this is a template instantiation, we can not work out the
6359      template arguments from partial DIEs.  So, unfortunately, we have
6360      to go through the full DIEs.  At least any work we do building
6361      types here will be reused if full symbols are loaded later.  */
6362   if (pdi->has_template_arguments)
6363     {
6364       fixup_partial_die (pdi, cu);
6365
6366       if (pdi->name != NULL && strchr (pdi->name, '<') == NULL)
6367         {
6368           struct die_info *die;
6369           struct attribute attr;
6370           struct dwarf2_cu *ref_cu = cu;
6371
6372           /* DW_FORM_ref_addr is using section offset.  */
6373           attr.name = 0;
6374           attr.form = DW_FORM_ref_addr;
6375           attr.u.unsnd = pdi->offset.sect_off;
6376           die = follow_die_ref (NULL, &attr, &ref_cu);
6377
6378           return xstrdup (dwarf2_full_name (NULL, die, ref_cu));
6379         }
6380     }
6381
6382   parent_scope = partial_die_parent_scope (pdi, cu);
6383   if (parent_scope == NULL)
6384     return NULL;
6385   else
6386     return typename_concat (NULL, parent_scope, pdi->name, 0, cu);
6387 }
6388
6389 static void
6390 add_partial_symbol (struct partial_die_info *pdi, struct dwarf2_cu *cu)
6391 {
6392   struct objfile *objfile = cu->objfile;
6393   CORE_ADDR addr = 0;
6394   const char *actual_name = NULL;
6395   CORE_ADDR baseaddr;
6396   char *built_actual_name;
6397
6398   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
6399
6400   built_actual_name = partial_die_full_name (pdi, cu);
6401   if (built_actual_name != NULL)
6402     actual_name = built_actual_name;
6403
6404   if (actual_name == NULL)
6405     actual_name = pdi->name;
6406
6407   switch (pdi->tag)
6408     {
6409     case DW_TAG_subprogram:
6410       if (pdi->is_external || cu->language == language_ada)
6411         {
6412           /* brobecker/2007-12-26: Normally, only "external" DIEs are part
6413              of the global scope.  But in Ada, we want to be able to access
6414              nested procedures globally.  So all Ada subprograms are stored
6415              in the global scope.  */
6416           /* prim_record_minimal_symbol (actual_name, pdi->lowpc + baseaddr,
6417              mst_text, objfile); */
6418           add_psymbol_to_list (actual_name, strlen (actual_name),
6419                                built_actual_name != NULL,
6420                                VAR_DOMAIN, LOC_BLOCK,
6421                                &objfile->global_psymbols,
6422                                0, pdi->lowpc + baseaddr,
6423                                cu->language, objfile);
6424         }
6425       else
6426         {
6427           /* prim_record_minimal_symbol (actual_name, pdi->lowpc + baseaddr,
6428              mst_file_text, objfile); */
6429           add_psymbol_to_list (actual_name, strlen (actual_name),
6430                                built_actual_name != NULL,
6431                                VAR_DOMAIN, LOC_BLOCK,
6432                                &objfile->static_psymbols,
6433                                0, pdi->lowpc + baseaddr,
6434                                cu->language, objfile);
6435         }
6436       break;
6437     case DW_TAG_constant:
6438       {
6439         struct psymbol_allocation_list *list;
6440
6441         if (pdi->is_external)
6442           list = &objfile->global_psymbols;
6443         else
6444           list = &objfile->static_psymbols;
6445         add_psymbol_to_list (actual_name, strlen (actual_name),
6446                              built_actual_name != NULL, VAR_DOMAIN, LOC_STATIC,
6447                              list, 0, 0, cu->language, objfile);
6448       }
6449       break;
6450     case DW_TAG_variable:
6451       if (pdi->d.locdesc)
6452         addr = decode_locdesc (pdi->d.locdesc, cu);
6453
6454       if (pdi->d.locdesc
6455           && addr == 0
6456           && !dwarf2_per_objfile->has_section_at_zero)
6457         {
6458           /* A global or static variable may also have been stripped
6459              out by the linker if unused, in which case its address
6460              will be nullified; do not add such variables into partial
6461              symbol table then.  */
6462         }
6463       else if (pdi->is_external)
6464         {
6465           /* Global Variable.
6466              Don't enter into the minimal symbol tables as there is
6467              a minimal symbol table entry from the ELF symbols already.
6468              Enter into partial symbol table if it has a location
6469              descriptor or a type.
6470              If the location descriptor is missing, new_symbol will create
6471              a LOC_UNRESOLVED symbol, the address of the variable will then
6472              be determined from the minimal symbol table whenever the variable
6473              is referenced.
6474              The address for the partial symbol table entry is not
6475              used by GDB, but it comes in handy for debugging partial symbol
6476              table building.  */
6477
6478           if (pdi->d.locdesc || pdi->has_type)
6479             add_psymbol_to_list (actual_name, strlen (actual_name),
6480                                  built_actual_name != NULL,
6481                                  VAR_DOMAIN, LOC_STATIC,
6482                                  &objfile->global_psymbols,
6483                                  0, addr + baseaddr,
6484                                  cu->language, objfile);
6485         }
6486       else
6487         {
6488           /* Static Variable.  Skip symbols without location descriptors.  */
6489           if (pdi->d.locdesc == NULL)
6490             {
6491               xfree (built_actual_name);
6492               return;
6493             }
6494           /* prim_record_minimal_symbol (actual_name, addr + baseaddr,
6495              mst_file_data, objfile); */
6496           add_psymbol_to_list (actual_name, strlen (actual_name),
6497                                built_actual_name != NULL,
6498                                VAR_DOMAIN, LOC_STATIC,
6499                                &objfile->static_psymbols,
6500                                0, addr + baseaddr,
6501                                cu->language, objfile);
6502         }
6503       break;
6504     case DW_TAG_typedef:
6505     case DW_TAG_base_type:
6506     case DW_TAG_subrange_type:
6507       add_psymbol_to_list (actual_name, strlen (actual_name),
6508                            built_actual_name != NULL,
6509                            VAR_DOMAIN, LOC_TYPEDEF,
6510                            &objfile->static_psymbols,
6511                            0, (CORE_ADDR) 0, cu->language, objfile);
6512       break;
6513     case DW_TAG_namespace:
6514       add_psymbol_to_list (actual_name, strlen (actual_name),
6515                            built_actual_name != NULL,
6516                            VAR_DOMAIN, LOC_TYPEDEF,
6517                            &objfile->global_psymbols,
6518                            0, (CORE_ADDR) 0, cu->language, objfile);
6519       break;
6520     case DW_TAG_class_type:
6521     case DW_TAG_interface_type:
6522     case DW_TAG_structure_type:
6523     case DW_TAG_union_type:
6524     case DW_TAG_enumeration_type:
6525       /* Skip external references.  The DWARF standard says in the section
6526          about "Structure, Union, and Class Type Entries": "An incomplete
6527          structure, union or class type is represented by a structure,
6528          union or class entry that does not have a byte size attribute
6529          and that has a DW_AT_declaration attribute."  */
6530       if (!pdi->has_byte_size && pdi->is_declaration)
6531         {
6532           xfree (built_actual_name);
6533           return;
6534         }
6535
6536       /* NOTE: carlton/2003-10-07: See comment in new_symbol about
6537          static vs. global.  */
6538       add_psymbol_to_list (actual_name, strlen (actual_name),
6539                            built_actual_name != NULL,
6540                            STRUCT_DOMAIN, LOC_TYPEDEF,
6541                            (cu->language == language_cplus
6542                             || cu->language == language_java)
6543                            ? &objfile->global_psymbols
6544                            : &objfile->static_psymbols,
6545                            0, (CORE_ADDR) 0, cu->language, objfile);
6546
6547       break;
6548     case DW_TAG_enumerator:
6549       add_psymbol_to_list (actual_name, strlen (actual_name),
6550                            built_actual_name != NULL,
6551                            VAR_DOMAIN, LOC_CONST,
6552                            (cu->language == language_cplus
6553                             || cu->language == language_java)
6554                            ? &objfile->global_psymbols
6555                            : &objfile->static_psymbols,
6556                            0, (CORE_ADDR) 0, cu->language, objfile);
6557       break;
6558     default:
6559       break;
6560     }
6561
6562   xfree (built_actual_name);
6563 }
6564
6565 /* Read a partial die corresponding to a namespace; also, add a symbol
6566    corresponding to that namespace to the symbol table.  NAMESPACE is
6567    the name of the enclosing namespace.  */
6568
6569 static void
6570 add_partial_namespace (struct partial_die_info *pdi,
6571                        CORE_ADDR *lowpc, CORE_ADDR *highpc,
6572                        int need_pc, struct dwarf2_cu *cu)
6573 {
6574   /* Add a symbol for the namespace.  */
6575
6576   add_partial_symbol (pdi, cu);
6577
6578   /* Now scan partial symbols in that namespace.  */
6579
6580   if (pdi->has_children)
6581     scan_partial_symbols (pdi->die_child, lowpc, highpc, need_pc, cu);
6582 }
6583
6584 /* Read a partial die corresponding to a Fortran module.  */
6585
6586 static void
6587 add_partial_module (struct partial_die_info *pdi, CORE_ADDR *lowpc,
6588                     CORE_ADDR *highpc, int need_pc, struct dwarf2_cu *cu)
6589 {
6590   /* Now scan partial symbols in that module.  */
6591
6592   if (pdi->has_children)
6593     scan_partial_symbols (pdi->die_child, lowpc, highpc, need_pc, cu);
6594 }
6595
6596 /* Read a partial die corresponding to a subprogram and create a partial
6597    symbol for that subprogram.  When the CU language allows it, this
6598    routine also defines a partial symbol for each nested subprogram
6599    that this subprogram contains.
6600
6601    DIE my also be a lexical block, in which case we simply search
6602    recursively for suprograms defined inside that lexical block.
6603    Again, this is only performed when the CU language allows this
6604    type of definitions.  */
6605
6606 static void
6607 add_partial_subprogram (struct partial_die_info *pdi,
6608                         CORE_ADDR *lowpc, CORE_ADDR *highpc,
6609                         int need_pc, struct dwarf2_cu *cu)
6610 {
6611   if (pdi->tag == DW_TAG_subprogram)
6612     {
6613       if (pdi->has_pc_info)
6614         {
6615           if (pdi->lowpc < *lowpc)
6616             *lowpc = pdi->lowpc;
6617           if (pdi->highpc > *highpc)
6618             *highpc = pdi->highpc;
6619           if (need_pc)
6620             {
6621               CORE_ADDR baseaddr;
6622               struct objfile *objfile = cu->objfile;
6623
6624               baseaddr = ANOFFSET (objfile->section_offsets,
6625                                    SECT_OFF_TEXT (objfile));
6626               addrmap_set_empty (objfile->psymtabs_addrmap,
6627                                  pdi->lowpc + baseaddr,
6628                                  pdi->highpc - 1 + baseaddr,
6629                                  cu->per_cu->v.psymtab);
6630             }
6631         }
6632
6633       if (pdi->has_pc_info || (!pdi->is_external && pdi->may_be_inlined))
6634         {
6635           if (!pdi->is_declaration)
6636             /* Ignore subprogram DIEs that do not have a name, they are
6637                illegal.  Do not emit a complaint at this point, we will
6638                do so when we convert this psymtab into a symtab.  */
6639             if (pdi->name)
6640               add_partial_symbol (pdi, cu);
6641         }
6642     }
6643
6644   if (! pdi->has_children)
6645     return;
6646
6647   if (cu->language == language_ada)
6648     {
6649       pdi = pdi->die_child;
6650       while (pdi != NULL)
6651         {
6652           fixup_partial_die (pdi, cu);
6653           if (pdi->tag == DW_TAG_subprogram
6654               || pdi->tag == DW_TAG_lexical_block)
6655             add_partial_subprogram (pdi, lowpc, highpc, need_pc, cu);
6656           pdi = pdi->die_sibling;
6657         }
6658     }
6659 }
6660
6661 /* Read a partial die corresponding to an enumeration type.  */
6662
6663 static void
6664 add_partial_enumeration (struct partial_die_info *enum_pdi,
6665                          struct dwarf2_cu *cu)
6666 {
6667   struct partial_die_info *pdi;
6668
6669   if (enum_pdi->name != NULL)
6670     add_partial_symbol (enum_pdi, cu);
6671
6672   pdi = enum_pdi->die_child;
6673   while (pdi)
6674     {
6675       if (pdi->tag != DW_TAG_enumerator || pdi->name == NULL)
6676         complaint (&symfile_complaints, _("malformed enumerator DIE ignored"));
6677       else
6678         add_partial_symbol (pdi, cu);
6679       pdi = pdi->die_sibling;
6680     }
6681 }
6682
6683 /* Return the initial uleb128 in the die at INFO_PTR.  */
6684
6685 static unsigned int
6686 peek_abbrev_code (bfd *abfd, const gdb_byte *info_ptr)
6687 {
6688   unsigned int bytes_read;
6689
6690   return read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
6691 }
6692
6693 /* Read the initial uleb128 in the die at INFO_PTR in compilation unit CU.
6694    Return the corresponding abbrev, or NULL if the number is zero (indicating
6695    an empty DIE).  In either case *BYTES_READ will be set to the length of
6696    the initial number.  */
6697
6698 static struct abbrev_info *
6699 peek_die_abbrev (const gdb_byte *info_ptr, unsigned int *bytes_read,
6700                  struct dwarf2_cu *cu)
6701 {
6702   bfd *abfd = cu->objfile->obfd;
6703   unsigned int abbrev_number;
6704   struct abbrev_info *abbrev;
6705
6706   abbrev_number = read_unsigned_leb128 (abfd, info_ptr, bytes_read);
6707
6708   if (abbrev_number == 0)
6709     return NULL;
6710
6711   abbrev = abbrev_table_lookup_abbrev (cu->abbrev_table, abbrev_number);
6712   if (!abbrev)
6713     {
6714       error (_("Dwarf Error: Could not find abbrev number %d [in module %s]"),
6715              abbrev_number, bfd_get_filename (abfd));
6716     }
6717
6718   return abbrev;
6719 }
6720
6721 /* Scan the debug information for CU starting at INFO_PTR in buffer BUFFER.
6722    Returns a pointer to the end of a series of DIEs, terminated by an empty
6723    DIE.  Any children of the skipped DIEs will also be skipped.  */
6724
6725 static const gdb_byte *
6726 skip_children (const struct die_reader_specs *reader, const gdb_byte *info_ptr)
6727 {
6728   struct dwarf2_cu *cu = reader->cu;
6729   struct abbrev_info *abbrev;
6730   unsigned int bytes_read;
6731
6732   while (1)
6733     {
6734       abbrev = peek_die_abbrev (info_ptr, &bytes_read, cu);
6735       if (abbrev == NULL)
6736         return info_ptr + bytes_read;
6737       else
6738         info_ptr = skip_one_die (reader, info_ptr + bytes_read, abbrev);
6739     }
6740 }
6741
6742 /* Scan the debug information for CU starting at INFO_PTR in buffer BUFFER.
6743    INFO_PTR should point just after the initial uleb128 of a DIE, and the
6744    abbrev corresponding to that skipped uleb128 should be passed in
6745    ABBREV.  Returns a pointer to this DIE's sibling, skipping any
6746    children.  */
6747
6748 static const gdb_byte *
6749 skip_one_die (const struct die_reader_specs *reader, const gdb_byte *info_ptr,
6750               struct abbrev_info *abbrev)
6751 {
6752   unsigned int bytes_read;
6753   struct attribute attr;
6754   bfd *abfd = reader->abfd;
6755   struct dwarf2_cu *cu = reader->cu;
6756   const gdb_byte *buffer = reader->buffer;
6757   const gdb_byte *buffer_end = reader->buffer_end;
6758   const gdb_byte *start_info_ptr = info_ptr;
6759   unsigned int form, i;
6760
6761   for (i = 0; i < abbrev->num_attrs; i++)
6762     {
6763       /* The only abbrev we care about is DW_AT_sibling.  */
6764       if (abbrev->attrs[i].name == DW_AT_sibling)
6765         {
6766           read_attribute (reader, &attr, &abbrev->attrs[i], info_ptr);
6767           if (attr.form == DW_FORM_ref_addr)
6768             complaint (&symfile_complaints,
6769                        _("ignoring absolute DW_AT_sibling"));
6770           else
6771             return buffer + dwarf2_get_ref_die_offset (&attr).sect_off;
6772         }
6773
6774       /* If it isn't DW_AT_sibling, skip this attribute.  */
6775       form = abbrev->attrs[i].form;
6776     skip_attribute:
6777       switch (form)
6778         {
6779         case DW_FORM_ref_addr:
6780           /* In DWARF 2, DW_FORM_ref_addr is address sized; in DWARF 3
6781              and later it is offset sized.  */
6782           if (cu->header.version == 2)
6783             info_ptr += cu->header.addr_size;
6784           else
6785             info_ptr += cu->header.offset_size;
6786           break;
6787         case DW_FORM_GNU_ref_alt:
6788           info_ptr += cu->header.offset_size;
6789           break;
6790         case DW_FORM_addr:
6791           info_ptr += cu->header.addr_size;
6792           break;
6793         case DW_FORM_data1:
6794         case DW_FORM_ref1:
6795         case DW_FORM_flag:
6796           info_ptr += 1;
6797           break;
6798         case DW_FORM_flag_present:
6799           break;
6800         case DW_FORM_data2:
6801         case DW_FORM_ref2:
6802           info_ptr += 2;
6803           break;
6804         case DW_FORM_data4:
6805         case DW_FORM_ref4:
6806           info_ptr += 4;
6807           break;
6808         case DW_FORM_data8:
6809         case DW_FORM_ref8:
6810         case DW_FORM_ref_sig8:
6811           info_ptr += 8;
6812           break;
6813         case DW_FORM_string:
6814           read_direct_string (abfd, info_ptr, &bytes_read);
6815           info_ptr += bytes_read;
6816           break;
6817         case DW_FORM_sec_offset:
6818         case DW_FORM_strp:
6819         case DW_FORM_GNU_strp_alt:
6820           info_ptr += cu->header.offset_size;
6821           break;
6822         case DW_FORM_exprloc:
6823         case DW_FORM_block:
6824           info_ptr += read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
6825           info_ptr += bytes_read;
6826           break;
6827         case DW_FORM_block1:
6828           info_ptr += 1 + read_1_byte (abfd, info_ptr);
6829           break;
6830         case DW_FORM_block2:
6831           info_ptr += 2 + read_2_bytes (abfd, info_ptr);
6832           break;
6833         case DW_FORM_block4:
6834           info_ptr += 4 + read_4_bytes (abfd, info_ptr);
6835           break;
6836         case DW_FORM_sdata:
6837         case DW_FORM_udata:
6838         case DW_FORM_ref_udata:
6839         case DW_FORM_GNU_addr_index:
6840         case DW_FORM_GNU_str_index:
6841           info_ptr = safe_skip_leb128 (info_ptr, buffer_end);
6842           break;
6843         case DW_FORM_indirect:
6844           form = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
6845           info_ptr += bytes_read;
6846           /* We need to continue parsing from here, so just go back to
6847              the top.  */
6848           goto skip_attribute;
6849
6850         default:
6851           error (_("Dwarf Error: Cannot handle %s "
6852                    "in DWARF reader [in module %s]"),
6853                  dwarf_form_name (form),
6854                  bfd_get_filename (abfd));
6855         }
6856     }
6857
6858   if (abbrev->has_children)
6859     return skip_children (reader, info_ptr);
6860   else
6861     return info_ptr;
6862 }
6863
6864 /* Locate ORIG_PDI's sibling.
6865    INFO_PTR should point to the start of the next DIE after ORIG_PDI.  */
6866
6867 static const gdb_byte *
6868 locate_pdi_sibling (const struct die_reader_specs *reader,
6869                     struct partial_die_info *orig_pdi,
6870                     const gdb_byte *info_ptr)
6871 {
6872   /* Do we know the sibling already?  */
6873
6874   if (orig_pdi->sibling)
6875     return orig_pdi->sibling;
6876
6877   /* Are there any children to deal with?  */
6878
6879   if (!orig_pdi->has_children)
6880     return info_ptr;
6881
6882   /* Skip the children the long way.  */
6883
6884   return skip_children (reader, info_ptr);
6885 }
6886
6887 /* Expand this partial symbol table into a full symbol table.  SELF is
6888    not NULL.  */
6889
6890 static void
6891 dwarf2_read_symtab (struct partial_symtab *self,
6892                     struct objfile *objfile)
6893 {
6894   if (self->readin)
6895     {
6896       warning (_("bug: psymtab for %s is already read in."),
6897                self->filename);
6898     }
6899   else
6900     {
6901       if (info_verbose)
6902         {
6903           printf_filtered (_("Reading in symbols for %s..."),
6904                            self->filename);
6905           gdb_flush (gdb_stdout);
6906         }
6907
6908       /* Restore our global data.  */
6909       dwarf2_per_objfile = objfile_data (objfile, dwarf2_objfile_data_key);
6910
6911       /* If this psymtab is constructed from a debug-only objfile, the
6912          has_section_at_zero flag will not necessarily be correct.  We
6913          can get the correct value for this flag by looking at the data
6914          associated with the (presumably stripped) associated objfile.  */
6915       if (objfile->separate_debug_objfile_backlink)
6916         {
6917           struct dwarf2_per_objfile *dpo_backlink
6918             = objfile_data (objfile->separate_debug_objfile_backlink,
6919                             dwarf2_objfile_data_key);
6920
6921           dwarf2_per_objfile->has_section_at_zero
6922             = dpo_backlink->has_section_at_zero;
6923         }
6924
6925       dwarf2_per_objfile->reading_partial_symbols = 0;
6926
6927       psymtab_to_symtab_1 (self);
6928
6929       /* Finish up the debug error message.  */
6930       if (info_verbose)
6931         printf_filtered (_("done.\n"));
6932     }
6933
6934   process_cu_includes ();
6935 }
6936 \f
6937 /* Reading in full CUs.  */
6938
6939 /* Add PER_CU to the queue.  */
6940
6941 static void
6942 queue_comp_unit (struct dwarf2_per_cu_data *per_cu,
6943                  enum language pretend_language)
6944 {
6945   struct dwarf2_queue_item *item;
6946
6947   per_cu->queued = 1;
6948   item = xmalloc (sizeof (*item));
6949   item->per_cu = per_cu;
6950   item->pretend_language = pretend_language;
6951   item->next = NULL;
6952
6953   if (dwarf2_queue == NULL)
6954     dwarf2_queue = item;
6955   else
6956     dwarf2_queue_tail->next = item;
6957
6958   dwarf2_queue_tail = item;
6959 }
6960
6961 /* THIS_CU has a reference to PER_CU.  If necessary, load the new compilation
6962    unit and add it to our queue.
6963    The result is non-zero if PER_CU was queued, otherwise the result is zero
6964    meaning either PER_CU is already queued or it is already loaded.  */
6965
6966 static int
6967 maybe_queue_comp_unit (struct dwarf2_cu *this_cu,
6968                        struct dwarf2_per_cu_data *per_cu,
6969                        enum language pretend_language)
6970 {
6971   /* We may arrive here during partial symbol reading, if we need full
6972      DIEs to process an unusual case (e.g. template arguments).  Do
6973      not queue PER_CU, just tell our caller to load its DIEs.  */
6974   if (dwarf2_per_objfile->reading_partial_symbols)
6975     {
6976       if (per_cu->cu == NULL || per_cu->cu->dies == NULL)
6977         return 1;
6978       return 0;
6979     }
6980
6981   /* Mark the dependence relation so that we don't flush PER_CU
6982      too early.  */
6983   dwarf2_add_dependence (this_cu, per_cu);
6984
6985   /* If it's already on the queue, we have nothing to do.  */
6986   if (per_cu->queued)
6987     return 0;
6988
6989   /* If the compilation unit is already loaded, just mark it as
6990      used.  */
6991   if (per_cu->cu != NULL)
6992     {
6993       per_cu->cu->last_used = 0;
6994       return 0;
6995     }
6996
6997   /* Add it to the queue.  */
6998   queue_comp_unit (per_cu, pretend_language);
6999
7000   return 1;
7001 }
7002
7003 /* Process the queue.  */
7004
7005 static void
7006 process_queue (void)
7007 {
7008   struct dwarf2_queue_item *item, *next_item;
7009
7010   if (dwarf2_read_debug)
7011     {
7012       fprintf_unfiltered (gdb_stdlog,
7013                           "Expanding one or more symtabs of objfile %s ...\n",
7014                           dwarf2_per_objfile->objfile->name);
7015     }
7016
7017   /* The queue starts out with one item, but following a DIE reference
7018      may load a new CU, adding it to the end of the queue.  */
7019   for (item = dwarf2_queue; item != NULL; dwarf2_queue = item = next_item)
7020     {
7021       if (dwarf2_per_objfile->using_index
7022           ? !item->per_cu->v.quick->symtab
7023           : (item->per_cu->v.psymtab && !item->per_cu->v.psymtab->readin))
7024         {
7025           struct dwarf2_per_cu_data *per_cu = item->per_cu;
7026
7027           if (dwarf2_read_debug)
7028             {
7029               fprintf_unfiltered (gdb_stdlog,
7030                                   "Expanding symtab of %s at offset 0x%x\n",
7031                                   per_cu->is_debug_types ? "TU" : "CU",
7032                                   per_cu->offset.sect_off);
7033             }
7034
7035           if (per_cu->is_debug_types)
7036             process_full_type_unit (per_cu, item->pretend_language);
7037           else
7038             process_full_comp_unit (per_cu, item->pretend_language);
7039
7040           if (dwarf2_read_debug)
7041             {
7042               fprintf_unfiltered (gdb_stdlog,
7043                                   "Done expanding %s at offset 0x%x\n",
7044                                   per_cu->is_debug_types ? "TU" : "CU",
7045                                   per_cu->offset.sect_off);
7046             }
7047         }
7048
7049       item->per_cu->queued = 0;
7050       next_item = item->next;
7051       xfree (item);
7052     }
7053
7054   dwarf2_queue_tail = NULL;
7055
7056   if (dwarf2_read_debug)
7057     {
7058       fprintf_unfiltered (gdb_stdlog, "Done expanding symtabs of %s.\n",
7059                           dwarf2_per_objfile->objfile->name);
7060     }
7061 }
7062
7063 /* Free all allocated queue entries.  This function only releases anything if
7064    an error was thrown; if the queue was processed then it would have been
7065    freed as we went along.  */
7066
7067 static void
7068 dwarf2_release_queue (void *dummy)
7069 {
7070   struct dwarf2_queue_item *item, *last;
7071
7072   item = dwarf2_queue;
7073   while (item)
7074     {
7075       /* Anything still marked queued is likely to be in an
7076          inconsistent state, so discard it.  */
7077       if (item->per_cu->queued)
7078         {
7079           if (item->per_cu->cu != NULL)
7080             free_one_cached_comp_unit (item->per_cu);
7081           item->per_cu->queued = 0;
7082         }
7083
7084       last = item;
7085       item = item->next;
7086       xfree (last);
7087     }
7088
7089   dwarf2_queue = dwarf2_queue_tail = NULL;
7090 }
7091
7092 /* Read in full symbols for PST, and anything it depends on.  */
7093
7094 static void
7095 psymtab_to_symtab_1 (struct partial_symtab *pst)
7096 {
7097   struct dwarf2_per_cu_data *per_cu;
7098   int i;
7099
7100   if (pst->readin)
7101     return;
7102
7103   for (i = 0; i < pst->number_of_dependencies; i++)
7104     if (!pst->dependencies[i]->readin
7105         && pst->dependencies[i]->user == NULL)
7106       {
7107         /* Inform about additional files that need to be read in.  */
7108         if (info_verbose)
7109           {
7110             /* FIXME: i18n: Need to make this a single string.  */
7111             fputs_filtered (" ", gdb_stdout);
7112             wrap_here ("");
7113             fputs_filtered ("and ", gdb_stdout);
7114             wrap_here ("");
7115             printf_filtered ("%s...", pst->dependencies[i]->filename);
7116             wrap_here ("");     /* Flush output.  */
7117             gdb_flush (gdb_stdout);
7118           }
7119         psymtab_to_symtab_1 (pst->dependencies[i]);
7120       }
7121
7122   per_cu = pst->read_symtab_private;
7123
7124   if (per_cu == NULL)
7125     {
7126       /* It's an include file, no symbols to read for it.
7127          Everything is in the parent symtab.  */
7128       pst->readin = 1;
7129       return;
7130     }
7131
7132   dw2_do_instantiate_symtab (per_cu);
7133 }
7134
7135 /* Trivial hash function for die_info: the hash value of a DIE
7136    is its offset in .debug_info for this objfile.  */
7137
7138 static hashval_t
7139 die_hash (const void *item)
7140 {
7141   const struct die_info *die = item;
7142
7143   return die->offset.sect_off;
7144 }
7145
7146 /* Trivial comparison function for die_info structures: two DIEs
7147    are equal if they have the same offset.  */
7148
7149 static int
7150 die_eq (const void *item_lhs, const void *item_rhs)
7151 {
7152   const struct die_info *die_lhs = item_lhs;
7153   const struct die_info *die_rhs = item_rhs;
7154
7155   return die_lhs->offset.sect_off == die_rhs->offset.sect_off;
7156 }
7157
7158 /* die_reader_func for load_full_comp_unit.
7159    This is identical to read_signatured_type_reader,
7160    but is kept separate for now.  */
7161
7162 static void
7163 load_full_comp_unit_reader (const struct die_reader_specs *reader,
7164                             const gdb_byte *info_ptr,
7165                             struct die_info *comp_unit_die,
7166                             int has_children,
7167                             void *data)
7168 {
7169   struct dwarf2_cu *cu = reader->cu;
7170   enum language *language_ptr = data;
7171
7172   gdb_assert (cu->die_hash == NULL);
7173   cu->die_hash =
7174     htab_create_alloc_ex (cu->header.length / 12,
7175                           die_hash,
7176                           die_eq,
7177                           NULL,
7178                           &cu->comp_unit_obstack,
7179                           hashtab_obstack_allocate,
7180                           dummy_obstack_deallocate);
7181
7182   if (has_children)
7183     comp_unit_die->child = read_die_and_siblings (reader, info_ptr,
7184                                                   &info_ptr, comp_unit_die);
7185   cu->dies = comp_unit_die;
7186   /* comp_unit_die is not stored in die_hash, no need.  */
7187
7188   /* We try not to read any attributes in this function, because not
7189      all CUs needed for references have been loaded yet, and symbol
7190      table processing isn't initialized.  But we have to set the CU language,
7191      or we won't be able to build types correctly.
7192      Similarly, if we do not read the producer, we can not apply
7193      producer-specific interpretation.  */
7194   prepare_one_comp_unit (cu, cu->dies, *language_ptr);
7195 }
7196
7197 /* Load the DIEs associated with PER_CU into memory.  */
7198
7199 static void
7200 load_full_comp_unit (struct dwarf2_per_cu_data *this_cu,
7201                      enum language pretend_language)
7202 {
7203   gdb_assert (! this_cu->is_debug_types);
7204
7205   init_cutu_and_read_dies (this_cu, NULL, 1, 1,
7206                            load_full_comp_unit_reader, &pretend_language);
7207 }
7208
7209 /* Add a DIE to the delayed physname list.  */
7210
7211 static void
7212 add_to_method_list (struct type *type, int fnfield_index, int index,
7213                     const char *name, struct die_info *die,
7214                     struct dwarf2_cu *cu)
7215 {
7216   struct delayed_method_info mi;
7217   mi.type = type;
7218   mi.fnfield_index = fnfield_index;
7219   mi.index = index;
7220   mi.name = name;
7221   mi.die = die;
7222   VEC_safe_push (delayed_method_info, cu->method_list, &mi);
7223 }
7224
7225 /* A cleanup for freeing the delayed method list.  */
7226
7227 static void
7228 free_delayed_list (void *ptr)
7229 {
7230   struct dwarf2_cu *cu = (struct dwarf2_cu *) ptr;
7231   if (cu->method_list != NULL)
7232     {
7233       VEC_free (delayed_method_info, cu->method_list);
7234       cu->method_list = NULL;
7235     }
7236 }
7237
7238 /* Compute the physnames of any methods on the CU's method list.
7239
7240    The computation of method physnames is delayed in order to avoid the
7241    (bad) condition that one of the method's formal parameters is of an as yet
7242    incomplete type.  */
7243
7244 static void
7245 compute_delayed_physnames (struct dwarf2_cu *cu)
7246 {
7247   int i;
7248   struct delayed_method_info *mi;
7249   for (i = 0; VEC_iterate (delayed_method_info, cu->method_list, i, mi) ; ++i)
7250     {
7251       const char *physname;
7252       struct fn_fieldlist *fn_flp
7253         = &TYPE_FN_FIELDLIST (mi->type, mi->fnfield_index);
7254       physname = dwarf2_physname (mi->name, mi->die, cu);
7255       fn_flp->fn_fields[mi->index].physname = physname ? physname : "";
7256     }
7257 }
7258
7259 /* Go objects should be embedded in a DW_TAG_module DIE,
7260    and it's not clear if/how imported objects will appear.
7261    To keep Go support simple until that's worked out,
7262    go back through what we've read and create something usable.
7263    We could do this while processing each DIE, and feels kinda cleaner,
7264    but that way is more invasive.
7265    This is to, for example, allow the user to type "p var" or "b main"
7266    without having to specify the package name, and allow lookups
7267    of module.object to work in contexts that use the expression
7268    parser.  */
7269
7270 static void
7271 fixup_go_packaging (struct dwarf2_cu *cu)
7272 {
7273   char *package_name = NULL;
7274   struct pending *list;
7275   int i;
7276
7277   for (list = global_symbols; list != NULL; list = list->next)
7278     {
7279       for (i = 0; i < list->nsyms; ++i)
7280         {
7281           struct symbol *sym = list->symbol[i];
7282
7283           if (SYMBOL_LANGUAGE (sym) == language_go
7284               && SYMBOL_CLASS (sym) == LOC_BLOCK)
7285             {
7286               char *this_package_name = go_symbol_package_name (sym);
7287
7288               if (this_package_name == NULL)
7289                 continue;
7290               if (package_name == NULL)
7291                 package_name = this_package_name;
7292               else
7293                 {
7294                   if (strcmp (package_name, this_package_name) != 0)
7295                     complaint (&symfile_complaints,
7296                                _("Symtab %s has objects from two different Go packages: %s and %s"),
7297                                (SYMBOL_SYMTAB (sym)
7298                           ? symtab_to_filename_for_display (SYMBOL_SYMTAB (sym))
7299                                 : cu->objfile->name),
7300                                this_package_name, package_name);
7301                   xfree (this_package_name);
7302                 }
7303             }
7304         }
7305     }
7306
7307   if (package_name != NULL)
7308     {
7309       struct objfile *objfile = cu->objfile;
7310       const char *saved_package_name = obstack_copy0 (&objfile->objfile_obstack,
7311                                                       package_name,
7312                                                       strlen (package_name));
7313       struct type *type = init_type (TYPE_CODE_MODULE, 0, 0,
7314                                      saved_package_name, objfile);
7315       struct symbol *sym;
7316
7317       TYPE_TAG_NAME (type) = TYPE_NAME (type);
7318
7319       sym = allocate_symbol (objfile);
7320       SYMBOL_SET_LANGUAGE (sym, language_go, &objfile->objfile_obstack);
7321       SYMBOL_SET_NAMES (sym, saved_package_name,
7322                         strlen (saved_package_name), 0, objfile);
7323       /* This is not VAR_DOMAIN because we want a way to ensure a lookup of,
7324          e.g., "main" finds the "main" module and not C's main().  */
7325       SYMBOL_DOMAIN (sym) = STRUCT_DOMAIN;
7326       SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
7327       SYMBOL_TYPE (sym) = type;
7328
7329       add_symbol_to_list (sym, &global_symbols);
7330
7331       xfree (package_name);
7332     }
7333 }
7334
7335 /* Return the symtab for PER_CU.  This works properly regardless of
7336    whether we're using the index or psymtabs.  */
7337
7338 static struct symtab *
7339 get_symtab (struct dwarf2_per_cu_data *per_cu)
7340 {
7341   return (dwarf2_per_objfile->using_index
7342           ? per_cu->v.quick->symtab
7343           : per_cu->v.psymtab->symtab);
7344 }
7345
7346 /* A helper function for computing the list of all symbol tables
7347    included by PER_CU.  */
7348
7349 static void
7350 recursively_compute_inclusions (VEC (dwarf2_per_cu_ptr) **result,
7351                                 htab_t all_children,
7352                                 struct dwarf2_per_cu_data *per_cu)
7353 {
7354   void **slot;
7355   int ix;
7356   struct dwarf2_per_cu_data *iter;
7357
7358   slot = htab_find_slot (all_children, per_cu, INSERT);
7359   if (*slot != NULL)
7360     {
7361       /* This inclusion and its children have been processed.  */
7362       return;
7363     }
7364
7365   *slot = per_cu;
7366   /* Only add a CU if it has a symbol table.  */
7367   if (get_symtab (per_cu) != NULL)
7368     VEC_safe_push (dwarf2_per_cu_ptr, *result, per_cu);
7369
7370   for (ix = 0;
7371        VEC_iterate (dwarf2_per_cu_ptr, per_cu->imported_symtabs, ix, iter);
7372        ++ix)
7373     recursively_compute_inclusions (result, all_children, iter);
7374 }
7375
7376 /* Compute the symtab 'includes' fields for the symtab related to
7377    PER_CU.  */
7378
7379 static void
7380 compute_symtab_includes (struct dwarf2_per_cu_data *per_cu)
7381 {
7382   gdb_assert (! per_cu->is_debug_types);
7383
7384   if (!VEC_empty (dwarf2_per_cu_ptr, per_cu->imported_symtabs))
7385     {
7386       int ix, len;
7387       struct dwarf2_per_cu_data *iter;
7388       VEC (dwarf2_per_cu_ptr) *result_children = NULL;
7389       htab_t all_children;
7390       struct symtab *symtab = get_symtab (per_cu);
7391
7392       /* If we don't have a symtab, we can just skip this case.  */
7393       if (symtab == NULL)
7394         return;
7395
7396       all_children = htab_create_alloc (1, htab_hash_pointer, htab_eq_pointer,
7397                                         NULL, xcalloc, xfree);
7398
7399       for (ix = 0;
7400            VEC_iterate (dwarf2_per_cu_ptr, per_cu->imported_symtabs,
7401                         ix, iter);
7402            ++ix)
7403         recursively_compute_inclusions (&result_children, all_children, iter);
7404
7405       /* Now we have a transitive closure of all the included CUs, and
7406          for .gdb_index version 7 the included TUs, so we can convert it
7407          to a list of symtabs.  */
7408       len = VEC_length (dwarf2_per_cu_ptr, result_children);
7409       symtab->includes
7410         = obstack_alloc (&dwarf2_per_objfile->objfile->objfile_obstack,
7411                          (len + 1) * sizeof (struct symtab *));
7412       for (ix = 0;
7413            VEC_iterate (dwarf2_per_cu_ptr, result_children, ix, iter);
7414            ++ix)
7415         symtab->includes[ix] = get_symtab (iter);
7416       symtab->includes[len] = NULL;
7417
7418       VEC_free (dwarf2_per_cu_ptr, result_children);
7419       htab_delete (all_children);
7420     }
7421 }
7422
7423 /* Compute the 'includes' field for the symtabs of all the CUs we just
7424    read.  */
7425
7426 static void
7427 process_cu_includes (void)
7428 {
7429   int ix;
7430   struct dwarf2_per_cu_data *iter;
7431
7432   for (ix = 0;
7433        VEC_iterate (dwarf2_per_cu_ptr, dwarf2_per_objfile->just_read_cus,
7434                     ix, iter);
7435        ++ix)
7436     {
7437       if (! iter->is_debug_types)
7438         compute_symtab_includes (iter);
7439     }
7440
7441   VEC_free (dwarf2_per_cu_ptr, dwarf2_per_objfile->just_read_cus);
7442 }
7443
7444 /* Generate full symbol information for PER_CU, whose DIEs have
7445    already been loaded into memory.  */
7446
7447 static void
7448 process_full_comp_unit (struct dwarf2_per_cu_data *per_cu,
7449                         enum language pretend_language)
7450 {
7451   struct dwarf2_cu *cu = per_cu->cu;
7452   struct objfile *objfile = per_cu->objfile;
7453   CORE_ADDR lowpc, highpc;
7454   struct symtab *symtab;
7455   struct cleanup *back_to, *delayed_list_cleanup;
7456   CORE_ADDR baseaddr;
7457   struct block *static_block;
7458
7459   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
7460
7461   buildsym_init ();
7462   back_to = make_cleanup (really_free_pendings, NULL);
7463   delayed_list_cleanup = make_cleanup (free_delayed_list, cu);
7464
7465   cu->list_in_scope = &file_symbols;
7466
7467   cu->language = pretend_language;
7468   cu->language_defn = language_def (cu->language);
7469
7470   /* Do line number decoding in read_file_scope () */
7471   process_die (cu->dies, cu);
7472
7473   /* For now fudge the Go package.  */
7474   if (cu->language == language_go)
7475     fixup_go_packaging (cu);
7476
7477   /* Now that we have processed all the DIEs in the CU, all the types 
7478      should be complete, and it should now be safe to compute all of the
7479      physnames.  */
7480   compute_delayed_physnames (cu);
7481   do_cleanups (delayed_list_cleanup);
7482
7483   /* Some compilers don't define a DW_AT_high_pc attribute for the
7484      compilation unit.  If the DW_AT_high_pc is missing, synthesize
7485      it, by scanning the DIE's below the compilation unit.  */
7486   get_scope_pc_bounds (cu->dies, &lowpc, &highpc, cu);
7487
7488   static_block
7489     = end_symtab_get_static_block (highpc + baseaddr, objfile, 0, 1);
7490
7491   /* If the comp unit has DW_AT_ranges, it may have discontiguous ranges.
7492      Also, DW_AT_ranges may record ranges not belonging to any child DIEs
7493      (such as virtual method tables).  Record the ranges in STATIC_BLOCK's
7494      addrmap to help ensure it has an accurate map of pc values belonging to
7495      this comp unit.  */
7496   dwarf2_record_block_ranges (cu->dies, static_block, baseaddr, cu);
7497
7498   symtab = end_symtab_from_static_block (static_block, objfile,
7499                                          SECT_OFF_TEXT (objfile), 0);
7500
7501   if (symtab != NULL)
7502     {
7503       int gcc_4_minor = producer_is_gcc_ge_4 (cu->producer);
7504
7505       /* Set symtab language to language from DW_AT_language.  If the
7506          compilation is from a C file generated by language preprocessors, do
7507          not set the language if it was already deduced by start_subfile.  */
7508       if (!(cu->language == language_c && symtab->language != language_c))
7509         symtab->language = cu->language;
7510
7511       /* GCC-4.0 has started to support -fvar-tracking.  GCC-3.x still can
7512          produce DW_AT_location with location lists but it can be possibly
7513          invalid without -fvar-tracking.  Still up to GCC-4.4.x incl. 4.4.0
7514          there were bugs in prologue debug info, fixed later in GCC-4.5
7515          by "unwind info for epilogues" patch (which is not directly related).
7516
7517          For -gdwarf-4 type units LOCATIONS_VALID indication is fortunately not
7518          needed, it would be wrong due to missing DW_AT_producer there.
7519
7520          Still one can confuse GDB by using non-standard GCC compilation
7521          options - this waits on GCC PR other/32998 (-frecord-gcc-switches).
7522          */ 
7523       if (cu->has_loclist && gcc_4_minor >= 5)
7524         symtab->locations_valid = 1;
7525
7526       if (gcc_4_minor >= 5)
7527         symtab->epilogue_unwind_valid = 1;
7528
7529       symtab->call_site_htab = cu->call_site_htab;
7530     }
7531
7532   if (dwarf2_per_objfile->using_index)
7533     per_cu->v.quick->symtab = symtab;
7534   else
7535     {
7536       struct partial_symtab *pst = per_cu->v.psymtab;
7537       pst->symtab = symtab;
7538       pst->readin = 1;
7539     }
7540
7541   /* Push it for inclusion processing later.  */
7542   VEC_safe_push (dwarf2_per_cu_ptr, dwarf2_per_objfile->just_read_cus, per_cu);
7543
7544   do_cleanups (back_to);
7545 }
7546
7547 /* Generate full symbol information for type unit PER_CU, whose DIEs have
7548    already been loaded into memory.  */
7549
7550 static void
7551 process_full_type_unit (struct dwarf2_per_cu_data *per_cu,
7552                         enum language pretend_language)
7553 {
7554   struct dwarf2_cu *cu = per_cu->cu;
7555   struct objfile *objfile = per_cu->objfile;
7556   struct symtab *symtab;
7557   struct cleanup *back_to, *delayed_list_cleanup;
7558   struct signatured_type *sig_type;
7559
7560   gdb_assert (per_cu->is_debug_types);
7561   sig_type = (struct signatured_type *) per_cu;
7562
7563   buildsym_init ();
7564   back_to = make_cleanup (really_free_pendings, NULL);
7565   delayed_list_cleanup = make_cleanup (free_delayed_list, cu);
7566
7567   cu->list_in_scope = &file_symbols;
7568
7569   cu->language = pretend_language;
7570   cu->language_defn = language_def (cu->language);
7571
7572   /* The symbol tables are set up in read_type_unit_scope.  */
7573   process_die (cu->dies, cu);
7574
7575   /* For now fudge the Go package.  */
7576   if (cu->language == language_go)
7577     fixup_go_packaging (cu);
7578
7579   /* Now that we have processed all the DIEs in the CU, all the types 
7580      should be complete, and it should now be safe to compute all of the
7581      physnames.  */
7582   compute_delayed_physnames (cu);
7583   do_cleanups (delayed_list_cleanup);
7584
7585   /* TUs share symbol tables.
7586      If this is the first TU to use this symtab, complete the construction
7587      of it with end_expandable_symtab.  Otherwise, complete the addition of
7588      this TU's symbols to the existing symtab.  */
7589   if (sig_type->type_unit_group->primary_symtab == NULL)
7590     {
7591       symtab = end_expandable_symtab (0, objfile, SECT_OFF_TEXT (objfile));
7592       sig_type->type_unit_group->primary_symtab = symtab;
7593
7594       if (symtab != NULL)
7595         {
7596           /* Set symtab language to language from DW_AT_language.  If the
7597              compilation is from a C file generated by language preprocessors,
7598              do not set the language if it was already deduced by
7599              start_subfile.  */
7600           if (!(cu->language == language_c && symtab->language != language_c))
7601             symtab->language = cu->language;
7602         }
7603     }
7604   else
7605     {
7606       augment_type_symtab (objfile,
7607                            sig_type->type_unit_group->primary_symtab);
7608       symtab = sig_type->type_unit_group->primary_symtab;
7609     }
7610
7611   if (dwarf2_per_objfile->using_index)
7612     per_cu->v.quick->symtab = symtab;
7613   else
7614     {
7615       struct partial_symtab *pst = per_cu->v.psymtab;
7616       pst->symtab = symtab;
7617       pst->readin = 1;
7618     }
7619
7620   do_cleanups (back_to);
7621 }
7622
7623 /* Process an imported unit DIE.  */
7624
7625 static void
7626 process_imported_unit_die (struct die_info *die, struct dwarf2_cu *cu)
7627 {
7628   struct attribute *attr;
7629
7630   /* For now we don't handle imported units in type units.  */
7631   if (cu->per_cu->is_debug_types)
7632     {
7633       error (_("Dwarf Error: DW_TAG_imported_unit is not"
7634                " supported in type units [in module %s]"),
7635              cu->objfile->name);
7636     }
7637
7638   attr = dwarf2_attr (die, DW_AT_import, cu);
7639   if (attr != NULL)
7640     {
7641       struct dwarf2_per_cu_data *per_cu;
7642       struct symtab *imported_symtab;
7643       sect_offset offset;
7644       int is_dwz;
7645
7646       offset = dwarf2_get_ref_die_offset (attr);
7647       is_dwz = (attr->form == DW_FORM_GNU_ref_alt || cu->per_cu->is_dwz);
7648       per_cu = dwarf2_find_containing_comp_unit (offset, is_dwz, cu->objfile);
7649
7650       /* Queue the unit, if needed.  */
7651       if (maybe_queue_comp_unit (cu, per_cu, cu->language))
7652         load_full_comp_unit (per_cu, cu->language);
7653
7654       VEC_safe_push (dwarf2_per_cu_ptr, cu->per_cu->imported_symtabs,
7655                      per_cu);
7656     }
7657 }
7658
7659 /* Process a die and its children.  */
7660
7661 static void
7662 process_die (struct die_info *die, struct dwarf2_cu *cu)
7663 {
7664   switch (die->tag)
7665     {
7666     case DW_TAG_padding:
7667       break;
7668     case DW_TAG_compile_unit:
7669     case DW_TAG_partial_unit:
7670       read_file_scope (die, cu);
7671       break;
7672     case DW_TAG_type_unit:
7673       read_type_unit_scope (die, cu);
7674       break;
7675     case DW_TAG_subprogram:
7676     case DW_TAG_inlined_subroutine:
7677       read_func_scope (die, cu);
7678       break;
7679     case DW_TAG_lexical_block:
7680     case DW_TAG_try_block:
7681     case DW_TAG_catch_block:
7682       read_lexical_block_scope (die, cu);
7683       break;
7684     case DW_TAG_GNU_call_site:
7685       read_call_site_scope (die, cu);
7686       break;
7687     case DW_TAG_class_type:
7688     case DW_TAG_interface_type:
7689     case DW_TAG_structure_type:
7690     case DW_TAG_union_type:
7691       process_structure_scope (die, cu);
7692       break;
7693     case DW_TAG_enumeration_type:
7694       process_enumeration_scope (die, cu);
7695       break;
7696
7697     /* These dies have a type, but processing them does not create
7698        a symbol or recurse to process the children.  Therefore we can
7699        read them on-demand through read_type_die.  */
7700     case DW_TAG_subroutine_type:
7701     case DW_TAG_set_type:
7702     case DW_TAG_array_type:
7703     case DW_TAG_pointer_type:
7704     case DW_TAG_ptr_to_member_type:
7705     case DW_TAG_reference_type:
7706     case DW_TAG_string_type:
7707       break;
7708
7709     case DW_TAG_base_type:
7710     case DW_TAG_subrange_type:
7711     case DW_TAG_typedef:
7712       /* Add a typedef symbol for the type definition, if it has a
7713          DW_AT_name.  */
7714       new_symbol (die, read_type_die (die, cu), cu);
7715       break;
7716     case DW_TAG_common_block:
7717       read_common_block (die, cu);
7718       break;
7719     case DW_TAG_common_inclusion:
7720       break;
7721     case DW_TAG_namespace:
7722       cu->processing_has_namespace_info = 1;
7723       read_namespace (die, cu);
7724       break;
7725     case DW_TAG_module:
7726       cu->processing_has_namespace_info = 1;
7727       read_module (die, cu);
7728       break;
7729     case DW_TAG_imported_declaration:
7730     case DW_TAG_imported_module:
7731       cu->processing_has_namespace_info = 1;
7732       if (die->child != NULL && (die->tag == DW_TAG_imported_declaration
7733                                  || cu->language != language_fortran))
7734         complaint (&symfile_complaints, _("Tag '%s' has unexpected children"),
7735                    dwarf_tag_name (die->tag));
7736       read_import_statement (die, cu);
7737       break;
7738
7739     case DW_TAG_imported_unit:
7740       process_imported_unit_die (die, cu);
7741       break;
7742
7743     default:
7744       new_symbol (die, NULL, cu);
7745       break;
7746     }
7747 }
7748 \f
7749 /* DWARF name computation.  */
7750
7751 /* A helper function for dwarf2_compute_name which determines whether DIE
7752    needs to have the name of the scope prepended to the name listed in the
7753    die.  */
7754
7755 static int
7756 die_needs_namespace (struct die_info *die, struct dwarf2_cu *cu)
7757 {
7758   struct attribute *attr;
7759
7760   switch (die->tag)
7761     {
7762     case DW_TAG_namespace:
7763     case DW_TAG_typedef:
7764     case DW_TAG_class_type:
7765     case DW_TAG_interface_type:
7766     case DW_TAG_structure_type:
7767     case DW_TAG_union_type:
7768     case DW_TAG_enumeration_type:
7769     case DW_TAG_enumerator:
7770     case DW_TAG_subprogram:
7771     case DW_TAG_member:
7772       return 1;
7773
7774     case DW_TAG_variable:
7775     case DW_TAG_constant:
7776       /* We only need to prefix "globally" visible variables.  These include
7777          any variable marked with DW_AT_external or any variable that
7778          lives in a namespace.  [Variables in anonymous namespaces
7779          require prefixing, but they are not DW_AT_external.]  */
7780
7781       if (dwarf2_attr (die, DW_AT_specification, cu))
7782         {
7783           struct dwarf2_cu *spec_cu = cu;
7784
7785           return die_needs_namespace (die_specification (die, &spec_cu),
7786                                       spec_cu);
7787         }
7788
7789       attr = dwarf2_attr (die, DW_AT_external, cu);
7790       if (attr == NULL && die->parent->tag != DW_TAG_namespace
7791           && die->parent->tag != DW_TAG_module)
7792         return 0;
7793       /* A variable in a lexical block of some kind does not need a
7794          namespace, even though in C++ such variables may be external
7795          and have a mangled name.  */
7796       if (die->parent->tag ==  DW_TAG_lexical_block
7797           || die->parent->tag ==  DW_TAG_try_block
7798           || die->parent->tag ==  DW_TAG_catch_block
7799           || die->parent->tag == DW_TAG_subprogram)
7800         return 0;
7801       return 1;
7802
7803     default:
7804       return 0;
7805     }
7806 }
7807
7808 /* Retrieve the last character from a mem_file.  */
7809
7810 static void
7811 do_ui_file_peek_last (void *object, const char *buffer, long length)
7812 {
7813   char *last_char_p = (char *) object;
7814
7815   if (length > 0)
7816     *last_char_p = buffer[length - 1];
7817 }
7818
7819 /* Compute the fully qualified name of DIE in CU.  If PHYSNAME is nonzero,
7820    compute the physname for the object, which include a method's:
7821    - formal parameters (C++/Java),
7822    - receiver type (Go),
7823    - return type (Java).
7824
7825    The term "physname" is a bit confusing.
7826    For C++, for example, it is the demangled name.
7827    For Go, for example, it's the mangled name.
7828
7829    For Ada, return the DIE's linkage name rather than the fully qualified
7830    name.  PHYSNAME is ignored..
7831
7832    The result is allocated on the objfile_obstack and canonicalized.  */
7833
7834 static const char *
7835 dwarf2_compute_name (const char *name,
7836                      struct die_info *die, struct dwarf2_cu *cu,
7837                      int physname)
7838 {
7839   struct objfile *objfile = cu->objfile;
7840
7841   if (name == NULL)
7842     name = dwarf2_name (die, cu);
7843
7844   /* For Fortran GDB prefers DW_AT_*linkage_name if present but otherwise
7845      compute it by typename_concat inside GDB.  */
7846   if (cu->language == language_ada
7847       || (cu->language == language_fortran && physname))
7848     {
7849       /* For Ada unit, we prefer the linkage name over the name, as
7850          the former contains the exported name, which the user expects
7851          to be able to reference.  Ideally, we want the user to be able
7852          to reference this entity using either natural or linkage name,
7853          but we haven't started looking at this enhancement yet.  */
7854       struct attribute *attr;
7855
7856       attr = dwarf2_attr (die, DW_AT_linkage_name, cu);
7857       if (attr == NULL)
7858         attr = dwarf2_attr (die, DW_AT_MIPS_linkage_name, cu);
7859       if (attr && DW_STRING (attr))
7860         return DW_STRING (attr);
7861     }
7862
7863   /* These are the only languages we know how to qualify names in.  */
7864   if (name != NULL
7865       && (cu->language == language_cplus || cu->language == language_java
7866           || cu->language == language_fortran))
7867     {
7868       if (die_needs_namespace (die, cu))
7869         {
7870           long length;
7871           const char *prefix;
7872           struct ui_file *buf;
7873
7874           prefix = determine_prefix (die, cu);
7875           buf = mem_fileopen ();
7876           if (*prefix != '\0')
7877             {
7878               char *prefixed_name = typename_concat (NULL, prefix, name,
7879                                                      physname, cu);
7880
7881               fputs_unfiltered (prefixed_name, buf);
7882               xfree (prefixed_name);
7883             }
7884           else
7885             fputs_unfiltered (name, buf);
7886
7887           /* Template parameters may be specified in the DIE's DW_AT_name, or
7888              as children with DW_TAG_template_type_param or
7889              DW_TAG_value_type_param.  If the latter, add them to the name
7890              here.  If the name already has template parameters, then
7891              skip this step; some versions of GCC emit both, and
7892              it is more efficient to use the pre-computed name.
7893
7894              Something to keep in mind about this process: it is very
7895              unlikely, or in some cases downright impossible, to produce
7896              something that will match the mangled name of a function.
7897              If the definition of the function has the same debug info,
7898              we should be able to match up with it anyway.  But fallbacks
7899              using the minimal symbol, for instance to find a method
7900              implemented in a stripped copy of libstdc++, will not work.
7901              If we do not have debug info for the definition, we will have to
7902              match them up some other way.
7903
7904              When we do name matching there is a related problem with function
7905              templates; two instantiated function templates are allowed to
7906              differ only by their return types, which we do not add here.  */
7907
7908           if (cu->language == language_cplus && strchr (name, '<') == NULL)
7909             {
7910               struct attribute *attr;
7911               struct die_info *child;
7912               int first = 1;
7913
7914               die->building_fullname = 1;
7915
7916               for (child = die->child; child != NULL; child = child->sibling)
7917                 {
7918                   struct type *type;
7919                   LONGEST value;
7920                   const gdb_byte *bytes;
7921                   struct dwarf2_locexpr_baton *baton;
7922                   struct value *v;
7923
7924                   if (child->tag != DW_TAG_template_type_param
7925                       && child->tag != DW_TAG_template_value_param)
7926                     continue;
7927
7928                   if (first)
7929                     {
7930                       fputs_unfiltered ("<", buf);
7931                       first = 0;
7932                     }
7933                   else
7934                     fputs_unfiltered (", ", buf);
7935
7936                   attr = dwarf2_attr (child, DW_AT_type, cu);
7937                   if (attr == NULL)
7938                     {
7939                       complaint (&symfile_complaints,
7940                                  _("template parameter missing DW_AT_type"));
7941                       fputs_unfiltered ("UNKNOWN_TYPE", buf);
7942                       continue;
7943                     }
7944                   type = die_type (child, cu);
7945
7946                   if (child->tag == DW_TAG_template_type_param)
7947                     {
7948                       c_print_type (type, "", buf, -1, 0, &type_print_raw_options);
7949                       continue;
7950                     }
7951
7952                   attr = dwarf2_attr (child, DW_AT_const_value, cu);
7953                   if (attr == NULL)
7954                     {
7955                       complaint (&symfile_complaints,
7956                                  _("template parameter missing "
7957                                    "DW_AT_const_value"));
7958                       fputs_unfiltered ("UNKNOWN_VALUE", buf);
7959                       continue;
7960                     }
7961
7962                   dwarf2_const_value_attr (attr, type, name,
7963                                            &cu->comp_unit_obstack, cu,
7964                                            &value, &bytes, &baton);
7965
7966                   if (TYPE_NOSIGN (type))
7967                     /* GDB prints characters as NUMBER 'CHAR'.  If that's
7968                        changed, this can use value_print instead.  */
7969                     c_printchar (value, type, buf);
7970                   else
7971                     {
7972                       struct value_print_options opts;
7973
7974                       if (baton != NULL)
7975                         v = dwarf2_evaluate_loc_desc (type, NULL,
7976                                                       baton->data,
7977                                                       baton->size,
7978                                                       baton->per_cu);
7979                       else if (bytes != NULL)
7980                         {
7981                           v = allocate_value (type);
7982                           memcpy (value_contents_writeable (v), bytes,
7983                                   TYPE_LENGTH (type));
7984                         }
7985                       else
7986                         v = value_from_longest (type, value);
7987
7988                       /* Specify decimal so that we do not depend on
7989                          the radix.  */
7990                       get_formatted_print_options (&opts, 'd');
7991                       opts.raw = 1;
7992                       value_print (v, buf, &opts);
7993                       release_value (v);
7994                       value_free (v);
7995                     }
7996                 }
7997
7998               die->building_fullname = 0;
7999
8000               if (!first)
8001                 {
8002                   /* Close the argument list, with a space if necessary
8003                      (nested templates).  */
8004                   char last_char = '\0';
8005                   ui_file_put (buf, do_ui_file_peek_last, &last_char);
8006                   if (last_char == '>')
8007                     fputs_unfiltered (" >", buf);
8008                   else
8009                     fputs_unfiltered (">", buf);
8010                 }
8011             }
8012
8013           /* For Java and C++ methods, append formal parameter type
8014              information, if PHYSNAME.  */
8015
8016           if (physname && die->tag == DW_TAG_subprogram
8017               && (cu->language == language_cplus
8018                   || cu->language == language_java))
8019             {
8020               struct type *type = read_type_die (die, cu);
8021
8022               c_type_print_args (type, buf, 1, cu->language,
8023                                  &type_print_raw_options);
8024
8025               if (cu->language == language_java)
8026                 {
8027                   /* For java, we must append the return type to method
8028                      names.  */
8029                   if (die->tag == DW_TAG_subprogram)
8030                     java_print_type (TYPE_TARGET_TYPE (type), "", buf,
8031                                      0, 0, &type_print_raw_options);
8032                 }
8033               else if (cu->language == language_cplus)
8034                 {
8035                   /* Assume that an artificial first parameter is
8036                      "this", but do not crash if it is not.  RealView
8037                      marks unnamed (and thus unused) parameters as
8038                      artificial; there is no way to differentiate
8039                      the two cases.  */
8040                   if (TYPE_NFIELDS (type) > 0
8041                       && TYPE_FIELD_ARTIFICIAL (type, 0)
8042                       && TYPE_CODE (TYPE_FIELD_TYPE (type, 0)) == TYPE_CODE_PTR
8043                       && TYPE_CONST (TYPE_TARGET_TYPE (TYPE_FIELD_TYPE (type,
8044                                                                         0))))
8045                     fputs_unfiltered (" const", buf);
8046                 }
8047             }
8048
8049           name = ui_file_obsavestring (buf, &objfile->objfile_obstack,
8050                                        &length);
8051           ui_file_delete (buf);
8052
8053           if (cu->language == language_cplus)
8054             {
8055               const char *cname
8056                 = dwarf2_canonicalize_name (name, cu,
8057                                             &objfile->objfile_obstack);
8058
8059               if (cname != NULL)
8060                 name = cname;
8061             }
8062         }
8063     }
8064
8065   return name;
8066 }
8067
8068 /* Return the fully qualified name of DIE, based on its DW_AT_name.
8069    If scope qualifiers are appropriate they will be added.  The result
8070    will be allocated on the objfile_obstack, or NULL if the DIE does
8071    not have a name.  NAME may either be from a previous call to
8072    dwarf2_name or NULL.
8073
8074    The output string will be canonicalized (if C++/Java).  */
8075
8076 static const char *
8077 dwarf2_full_name (const char *name, struct die_info *die, struct dwarf2_cu *cu)
8078 {
8079   return dwarf2_compute_name (name, die, cu, 0);
8080 }
8081
8082 /* Construct a physname for the given DIE in CU.  NAME may either be
8083    from a previous call to dwarf2_name or NULL.  The result will be
8084    allocated on the objfile_objstack or NULL if the DIE does not have a
8085    name.
8086
8087    The output string will be canonicalized (if C++/Java).  */
8088
8089 static const char *
8090 dwarf2_physname (const char *name, struct die_info *die, struct dwarf2_cu *cu)
8091 {
8092   struct objfile *objfile = cu->objfile;
8093   struct attribute *attr;
8094   const char *retval, *mangled = NULL, *canon = NULL;
8095   struct cleanup *back_to;
8096   int need_copy = 1;
8097
8098   /* In this case dwarf2_compute_name is just a shortcut not building anything
8099      on its own.  */
8100   if (!die_needs_namespace (die, cu))
8101     return dwarf2_compute_name (name, die, cu, 1);
8102
8103   back_to = make_cleanup (null_cleanup, NULL);
8104
8105   attr = dwarf2_attr (die, DW_AT_linkage_name, cu);
8106   if (!attr)
8107     attr = dwarf2_attr (die, DW_AT_MIPS_linkage_name, cu);
8108
8109   /* DW_AT_linkage_name is missing in some cases - depend on what GDB
8110      has computed.  */
8111   if (attr && DW_STRING (attr))
8112     {
8113       char *demangled;
8114
8115       mangled = DW_STRING (attr);
8116
8117       /* Use DMGL_RET_DROP for C++ template functions to suppress their return
8118          type.  It is easier for GDB users to search for such functions as
8119          `name(params)' than `long name(params)'.  In such case the minimal
8120          symbol names do not match the full symbol names but for template
8121          functions there is never a need to look up their definition from their
8122          declaration so the only disadvantage remains the minimal symbol
8123          variant `long name(params)' does not have the proper inferior type.
8124          */
8125
8126       if (cu->language == language_go)
8127         {
8128           /* This is a lie, but we already lie to the caller new_symbol_full.
8129              new_symbol_full assumes we return the mangled name.
8130              This just undoes that lie until things are cleaned up.  */
8131           demangled = NULL;
8132         }
8133       else
8134         {
8135           demangled = gdb_demangle (mangled,
8136                                     (DMGL_PARAMS | DMGL_ANSI
8137                                      | (cu->language == language_java
8138                                         ? DMGL_JAVA | DMGL_RET_POSTFIX
8139                                         : DMGL_RET_DROP)));
8140         }
8141       if (demangled)
8142         {
8143           make_cleanup (xfree, demangled);
8144           canon = demangled;
8145         }
8146       else
8147         {
8148           canon = mangled;
8149           need_copy = 0;
8150         }
8151     }
8152
8153   if (canon == NULL || check_physname)
8154     {
8155       const char *physname = dwarf2_compute_name (name, die, cu, 1);
8156
8157       if (canon != NULL && strcmp (physname, canon) != 0)
8158         {
8159           /* It may not mean a bug in GDB.  The compiler could also
8160              compute DW_AT_linkage_name incorrectly.  But in such case
8161              GDB would need to be bug-to-bug compatible.  */
8162
8163           complaint (&symfile_complaints,
8164                      _("Computed physname <%s> does not match demangled <%s> "
8165                        "(from linkage <%s>) - DIE at 0x%x [in module %s]"),
8166                      physname, canon, mangled, die->offset.sect_off, objfile->name);
8167
8168           /* Prefer DW_AT_linkage_name (in the CANON form) - when it
8169              is available here - over computed PHYSNAME.  It is safer
8170              against both buggy GDB and buggy compilers.  */
8171
8172           retval = canon;
8173         }
8174       else
8175         {
8176           retval = physname;
8177           need_copy = 0;
8178         }
8179     }
8180   else
8181     retval = canon;
8182
8183   if (need_copy)
8184     retval = obstack_copy0 (&objfile->objfile_obstack, retval, strlen (retval));
8185
8186   do_cleanups (back_to);
8187   return retval;
8188 }
8189
8190 /* Read the import statement specified by the given die and record it.  */
8191
8192 static void
8193 read_import_statement (struct die_info *die, struct dwarf2_cu *cu)
8194 {
8195   struct objfile *objfile = cu->objfile;
8196   struct attribute *import_attr;
8197   struct die_info *imported_die, *child_die;
8198   struct dwarf2_cu *imported_cu;
8199   const char *imported_name;
8200   const char *imported_name_prefix;
8201   const char *canonical_name;
8202   const char *import_alias;
8203   const char *imported_declaration = NULL;
8204   const char *import_prefix;
8205   VEC (const_char_ptr) *excludes = NULL;
8206   struct cleanup *cleanups;
8207
8208   import_attr = dwarf2_attr (die, DW_AT_import, cu);
8209   if (import_attr == NULL)
8210     {
8211       complaint (&symfile_complaints, _("Tag '%s' has no DW_AT_import"),
8212                  dwarf_tag_name (die->tag));
8213       return;
8214     }
8215
8216   imported_cu = cu;
8217   imported_die = follow_die_ref_or_sig (die, import_attr, &imported_cu);
8218   imported_name = dwarf2_name (imported_die, imported_cu);
8219   if (imported_name == NULL)
8220     {
8221       /* GCC bug: https://bugzilla.redhat.com/show_bug.cgi?id=506524
8222
8223         The import in the following code:
8224         namespace A
8225           {
8226             typedef int B;
8227           }
8228
8229         int main ()
8230           {
8231             using A::B;
8232             B b;
8233             return b;
8234           }
8235
8236         ...
8237          <2><51>: Abbrev Number: 3 (DW_TAG_imported_declaration)
8238             <52>   DW_AT_decl_file   : 1
8239             <53>   DW_AT_decl_line   : 6
8240             <54>   DW_AT_import      : <0x75>
8241          <2><58>: Abbrev Number: 4 (DW_TAG_typedef)
8242             <59>   DW_AT_name        : B
8243             <5b>   DW_AT_decl_file   : 1
8244             <5c>   DW_AT_decl_line   : 2
8245             <5d>   DW_AT_type        : <0x6e>
8246         ...
8247          <1><75>: Abbrev Number: 7 (DW_TAG_base_type)
8248             <76>   DW_AT_byte_size   : 4
8249             <77>   DW_AT_encoding    : 5        (signed)
8250
8251         imports the wrong die ( 0x75 instead of 0x58 ).
8252         This case will be ignored until the gcc bug is fixed.  */
8253       return;
8254     }
8255
8256   /* Figure out the local name after import.  */
8257   import_alias = dwarf2_name (die, cu);
8258
8259   /* Figure out where the statement is being imported to.  */
8260   import_prefix = determine_prefix (die, cu);
8261
8262   /* Figure out what the scope of the imported die is and prepend it
8263      to the name of the imported die.  */
8264   imported_name_prefix = determine_prefix (imported_die, imported_cu);
8265
8266   if (imported_die->tag != DW_TAG_namespace
8267       && imported_die->tag != DW_TAG_module)
8268     {
8269       imported_declaration = imported_name;
8270       canonical_name = imported_name_prefix;
8271     }
8272   else if (strlen (imported_name_prefix) > 0)
8273     canonical_name = obconcat (&objfile->objfile_obstack,
8274                                imported_name_prefix, "::", imported_name,
8275                                (char *) NULL);
8276   else
8277     canonical_name = imported_name;
8278
8279   cleanups = make_cleanup (VEC_cleanup (const_char_ptr), &excludes);
8280
8281   if (die->tag == DW_TAG_imported_module && cu->language == language_fortran)
8282     for (child_die = die->child; child_die && child_die->tag;
8283          child_die = sibling_die (child_die))
8284       {
8285         /* DWARF-4: A Fortran use statement with a “rename list” may be
8286            represented by an imported module entry with an import attribute
8287            referring to the module and owned entries corresponding to those
8288            entities that are renamed as part of being imported.  */
8289
8290         if (child_die->tag != DW_TAG_imported_declaration)
8291           {
8292             complaint (&symfile_complaints,
8293                        _("child DW_TAG_imported_declaration expected "
8294                          "- DIE at 0x%x [in module %s]"),
8295                        child_die->offset.sect_off, objfile->name);
8296             continue;
8297           }
8298
8299         import_attr = dwarf2_attr (child_die, DW_AT_import, cu);
8300         if (import_attr == NULL)
8301           {
8302             complaint (&symfile_complaints, _("Tag '%s' has no DW_AT_import"),
8303                        dwarf_tag_name (child_die->tag));
8304             continue;
8305           }
8306
8307         imported_cu = cu;
8308         imported_die = follow_die_ref_or_sig (child_die, import_attr,
8309                                               &imported_cu);
8310         imported_name = dwarf2_name (imported_die, imported_cu);
8311         if (imported_name == NULL)
8312           {
8313             complaint (&symfile_complaints,
8314                        _("child DW_TAG_imported_declaration has unknown "
8315                          "imported name - DIE at 0x%x [in module %s]"),
8316                        child_die->offset.sect_off, objfile->name);
8317             continue;
8318           }
8319
8320         VEC_safe_push (const_char_ptr, excludes, imported_name);
8321
8322         process_die (child_die, cu);
8323       }
8324
8325   cp_add_using_directive (import_prefix,
8326                           canonical_name,
8327                           import_alias,
8328                           imported_declaration,
8329                           excludes,
8330                           0,
8331                           &objfile->objfile_obstack);
8332
8333   do_cleanups (cleanups);
8334 }
8335
8336 /* Cleanup function for handle_DW_AT_stmt_list.  */
8337
8338 static void
8339 free_cu_line_header (void *arg)
8340 {
8341   struct dwarf2_cu *cu = arg;
8342
8343   free_line_header (cu->line_header);
8344   cu->line_header = NULL;
8345 }
8346
8347 /* Check for possibly missing DW_AT_comp_dir with relative .debug_line
8348    directory paths.  GCC SVN r127613 (new option -fdebug-prefix-map) fixed
8349    this, it was first present in GCC release 4.3.0.  */
8350
8351 static int
8352 producer_is_gcc_lt_4_3 (struct dwarf2_cu *cu)
8353 {
8354   if (!cu->checked_producer)
8355     check_producer (cu);
8356
8357   return cu->producer_is_gcc_lt_4_3;
8358 }
8359
8360 static void
8361 find_file_and_directory (struct die_info *die, struct dwarf2_cu *cu,
8362                          const char **name, const char **comp_dir)
8363 {
8364   struct attribute *attr;
8365
8366   *name = NULL;
8367   *comp_dir = NULL;
8368
8369   /* Find the filename.  Do not use dwarf2_name here, since the filename
8370      is not a source language identifier.  */
8371   attr = dwarf2_attr (die, DW_AT_name, cu);
8372   if (attr)
8373     {
8374       *name = DW_STRING (attr);
8375     }
8376
8377   attr = dwarf2_attr (die, DW_AT_comp_dir, cu);
8378   if (attr)
8379     *comp_dir = DW_STRING (attr);
8380   else if (producer_is_gcc_lt_4_3 (cu) && *name != NULL
8381            && IS_ABSOLUTE_PATH (*name))
8382     {
8383       char *d = ldirname (*name);
8384
8385       *comp_dir = d;
8386       if (d != NULL)
8387         make_cleanup (xfree, d);
8388     }
8389   if (*comp_dir != NULL)
8390     {
8391       /* Irix 6.2 native cc prepends <machine>.: to the compilation
8392          directory, get rid of it.  */
8393       char *cp = strchr (*comp_dir, ':');
8394
8395       if (cp && cp != *comp_dir && cp[-1] == '.' && cp[1] == '/')
8396         *comp_dir = cp + 1;
8397     }
8398
8399   if (*name == NULL)
8400     *name = "<unknown>";
8401 }
8402
8403 /* Handle DW_AT_stmt_list for a compilation unit.
8404    DIE is the DW_TAG_compile_unit die for CU.
8405    COMP_DIR is the compilation directory.
8406    WANT_LINE_INFO is non-zero if the pc/line-number mapping is needed.  */
8407
8408 static void
8409 handle_DW_AT_stmt_list (struct die_info *die, struct dwarf2_cu *cu,
8410                         const char *comp_dir) /* ARI: editCase function */
8411 {
8412   struct attribute *attr;
8413
8414   gdb_assert (! cu->per_cu->is_debug_types);
8415
8416   attr = dwarf2_attr (die, DW_AT_stmt_list, cu);
8417   if (attr)
8418     {
8419       unsigned int line_offset = DW_UNSND (attr);
8420       struct line_header *line_header
8421         = dwarf_decode_line_header (line_offset, cu);
8422
8423       if (line_header)
8424         {
8425           cu->line_header = line_header;
8426           make_cleanup (free_cu_line_header, cu);
8427           dwarf_decode_lines (line_header, comp_dir, cu, NULL, 1);
8428         }
8429     }
8430 }
8431
8432 /* Process DW_TAG_compile_unit or DW_TAG_partial_unit.  */
8433
8434 static void
8435 read_file_scope (struct die_info *die, struct dwarf2_cu *cu)
8436 {
8437   struct objfile *objfile = dwarf2_per_objfile->objfile;
8438   struct cleanup *back_to = make_cleanup (null_cleanup, 0);
8439   CORE_ADDR lowpc = ((CORE_ADDR) -1);
8440   CORE_ADDR highpc = ((CORE_ADDR) 0);
8441   struct attribute *attr;
8442   const char *name = NULL;
8443   const char *comp_dir = NULL;
8444   struct die_info *child_die;
8445   bfd *abfd = objfile->obfd;
8446   CORE_ADDR baseaddr;
8447
8448   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
8449
8450   get_scope_pc_bounds (die, &lowpc, &highpc, cu);
8451
8452   /* If we didn't find a lowpc, set it to highpc to avoid complaints
8453      from finish_block.  */
8454   if (lowpc == ((CORE_ADDR) -1))
8455     lowpc = highpc;
8456   lowpc += baseaddr;
8457   highpc += baseaddr;
8458
8459   find_file_and_directory (die, cu, &name, &comp_dir);
8460
8461   prepare_one_comp_unit (cu, die, cu->language);
8462
8463   /* The XLCL doesn't generate DW_LANG_OpenCL because this attribute is not
8464      standardised yet.  As a workaround for the language detection we fall
8465      back to the DW_AT_producer string.  */
8466   if (cu->producer && strstr (cu->producer, "IBM XL C for OpenCL") != NULL)
8467     cu->language = language_opencl;
8468
8469   /* Similar hack for Go.  */
8470   if (cu->producer && strstr (cu->producer, "GNU Go ") != NULL)
8471     set_cu_language (DW_LANG_Go, cu);
8472
8473   dwarf2_start_symtab (cu, name, comp_dir, lowpc);
8474
8475   /* Decode line number information if present.  We do this before
8476      processing child DIEs, so that the line header table is available
8477      for DW_AT_decl_file.  */
8478   handle_DW_AT_stmt_list (die, cu, comp_dir);
8479
8480   /* Process all dies in compilation unit.  */
8481   if (die->child != NULL)
8482     {
8483       child_die = die->child;
8484       while (child_die && child_die->tag)
8485         {
8486           process_die (child_die, cu);
8487           child_die = sibling_die (child_die);
8488         }
8489     }
8490
8491   /* Decode macro information, if present.  Dwarf 2 macro information
8492      refers to information in the line number info statement program
8493      header, so we can only read it if we've read the header
8494      successfully.  */
8495   attr = dwarf2_attr (die, DW_AT_GNU_macros, cu);
8496   if (attr && cu->line_header)
8497     {
8498       if (dwarf2_attr (die, DW_AT_macro_info, cu))
8499         complaint (&symfile_complaints,
8500                    _("CU refers to both DW_AT_GNU_macros and DW_AT_macro_info"));
8501
8502       dwarf_decode_macros (cu, DW_UNSND (attr), comp_dir, 1);
8503     }
8504   else
8505     {
8506       attr = dwarf2_attr (die, DW_AT_macro_info, cu);
8507       if (attr && cu->line_header)
8508         {
8509           unsigned int macro_offset = DW_UNSND (attr);
8510
8511           dwarf_decode_macros (cu, macro_offset, comp_dir, 0);
8512         }
8513     }
8514
8515   do_cleanups (back_to);
8516 }
8517
8518 /* TU version of handle_DW_AT_stmt_list for read_type_unit_scope.
8519    Create the set of symtabs used by this TU, or if this TU is sharing
8520    symtabs with another TU and the symtabs have already been created
8521    then restore those symtabs in the line header.
8522    We don't need the pc/line-number mapping for type units.  */
8523
8524 static void
8525 setup_type_unit_groups (struct die_info *die, struct dwarf2_cu *cu)
8526 {
8527   struct objfile *objfile = dwarf2_per_objfile->objfile;
8528   struct dwarf2_per_cu_data *per_cu = cu->per_cu;
8529   struct type_unit_group *tu_group;
8530   int first_time;
8531   struct line_header *lh;
8532   struct attribute *attr;
8533   unsigned int i, line_offset;
8534   struct signatured_type *sig_type;
8535
8536   gdb_assert (per_cu->is_debug_types);
8537   sig_type = (struct signatured_type *) per_cu;
8538
8539   attr = dwarf2_attr (die, DW_AT_stmt_list, cu);
8540
8541   /* If we're using .gdb_index (includes -readnow) then
8542      per_cu->type_unit_group may not have been set up yet.  */
8543   if (sig_type->type_unit_group == NULL)
8544     sig_type->type_unit_group = get_type_unit_group (cu, attr);
8545   tu_group = sig_type->type_unit_group;
8546
8547   /* If we've already processed this stmt_list there's no real need to
8548      do it again, we could fake it and just recreate the part we need
8549      (file name,index -> symtab mapping).  If data shows this optimization
8550      is useful we can do it then.  */
8551   first_time = tu_group->primary_symtab == NULL;
8552
8553   /* We have to handle the case of both a missing DW_AT_stmt_list or bad
8554      debug info.  */
8555   lh = NULL;
8556   if (attr != NULL)
8557     {
8558       line_offset = DW_UNSND (attr);
8559       lh = dwarf_decode_line_header (line_offset, cu);
8560     }
8561   if (lh == NULL)
8562     {
8563       if (first_time)
8564         dwarf2_start_symtab (cu, "", NULL, 0);
8565       else
8566         {
8567           gdb_assert (tu_group->symtabs == NULL);
8568           restart_symtab (0);
8569         }
8570       /* Note: The primary symtab will get allocated at the end.  */
8571       return;
8572     }
8573
8574   cu->line_header = lh;
8575   make_cleanup (free_cu_line_header, cu);
8576
8577   if (first_time)
8578     {
8579       dwarf2_start_symtab (cu, "", NULL, 0);
8580
8581       tu_group->num_symtabs = lh->num_file_names;
8582       tu_group->symtabs = XNEWVEC (struct symtab *, lh->num_file_names);
8583
8584       for (i = 0; i < lh->num_file_names; ++i)
8585         {
8586           const char *dir = NULL;
8587           struct file_entry *fe = &lh->file_names[i];
8588
8589           if (fe->dir_index)
8590             dir = lh->include_dirs[fe->dir_index - 1];
8591           dwarf2_start_subfile (fe->name, dir, NULL);
8592
8593           /* Note: We don't have to watch for the main subfile here, type units
8594              don't have DW_AT_name.  */
8595
8596           if (current_subfile->symtab == NULL)
8597             {
8598               /* NOTE: start_subfile will recognize when it's been passed
8599                  a file it has already seen.  So we can't assume there's a
8600                  simple mapping from lh->file_names to subfiles,
8601                  lh->file_names may contain dups.  */
8602               current_subfile->symtab = allocate_symtab (current_subfile->name,
8603                                                          objfile);
8604             }
8605
8606           fe->symtab = current_subfile->symtab;
8607           tu_group->symtabs[i] = fe->symtab;
8608         }
8609     }
8610   else
8611     {
8612       restart_symtab (0);
8613
8614       for (i = 0; i < lh->num_file_names; ++i)
8615         {
8616           struct file_entry *fe = &lh->file_names[i];
8617
8618           fe->symtab = tu_group->symtabs[i];
8619         }
8620     }
8621
8622   /* The main symtab is allocated last.  Type units don't have DW_AT_name
8623      so they don't have a "real" (so to speak) symtab anyway.
8624      There is later code that will assign the main symtab to all symbols
8625      that don't have one.  We need to handle the case of a symbol with a
8626      missing symtab (DW_AT_decl_file) anyway.  */
8627 }
8628
8629 /* Process DW_TAG_type_unit.
8630    For TUs we want to skip the first top level sibling if it's not the
8631    actual type being defined by this TU.  In this case the first top
8632    level sibling is there to provide context only.  */
8633
8634 static void
8635 read_type_unit_scope (struct die_info *die, struct dwarf2_cu *cu)
8636 {
8637   struct die_info *child_die;
8638
8639   prepare_one_comp_unit (cu, die, language_minimal);
8640
8641   /* Initialize (or reinitialize) the machinery for building symtabs.
8642      We do this before processing child DIEs, so that the line header table
8643      is available for DW_AT_decl_file.  */
8644   setup_type_unit_groups (die, cu);
8645
8646   if (die->child != NULL)
8647     {
8648       child_die = die->child;
8649       while (child_die && child_die->tag)
8650         {
8651           process_die (child_die, cu);
8652           child_die = sibling_die (child_die);
8653         }
8654     }
8655 }
8656 \f
8657 /* DWO/DWP files.
8658
8659    http://gcc.gnu.org/wiki/DebugFission
8660    http://gcc.gnu.org/wiki/DebugFissionDWP
8661
8662    To simplify handling of both DWO files ("object" files with the DWARF info)
8663    and DWP files (a file with the DWOs packaged up into one file), we treat
8664    DWP files as having a collection of virtual DWO files.  */
8665
8666 static hashval_t
8667 hash_dwo_file (const void *item)
8668 {
8669   const struct dwo_file *dwo_file = item;
8670   hashval_t hash;
8671
8672   hash = htab_hash_string (dwo_file->dwo_name);
8673   if (dwo_file->comp_dir != NULL)
8674     hash += htab_hash_string (dwo_file->comp_dir);
8675   return hash;
8676 }
8677
8678 static int
8679 eq_dwo_file (const void *item_lhs, const void *item_rhs)
8680 {
8681   const struct dwo_file *lhs = item_lhs;
8682   const struct dwo_file *rhs = item_rhs;
8683
8684   if (strcmp (lhs->dwo_name, rhs->dwo_name) != 0)
8685     return 0;
8686   if (lhs->comp_dir == NULL || rhs->comp_dir == NULL)
8687     return lhs->comp_dir == rhs->comp_dir;
8688   return strcmp (lhs->comp_dir, rhs->comp_dir) == 0;
8689 }
8690
8691 /* Allocate a hash table for DWO files.  */
8692
8693 static htab_t
8694 allocate_dwo_file_hash_table (void)
8695 {
8696   struct objfile *objfile = dwarf2_per_objfile->objfile;
8697
8698   return htab_create_alloc_ex (41,
8699                                hash_dwo_file,
8700                                eq_dwo_file,
8701                                NULL,
8702                                &objfile->objfile_obstack,
8703                                hashtab_obstack_allocate,
8704                                dummy_obstack_deallocate);
8705 }
8706
8707 /* Lookup DWO file DWO_NAME.  */
8708
8709 static void **
8710 lookup_dwo_file_slot (const char *dwo_name, const char *comp_dir)
8711 {
8712   struct dwo_file find_entry;
8713   void **slot;
8714
8715   if (dwarf2_per_objfile->dwo_files == NULL)
8716     dwarf2_per_objfile->dwo_files = allocate_dwo_file_hash_table ();
8717
8718   memset (&find_entry, 0, sizeof (find_entry));
8719   find_entry.dwo_name = dwo_name;
8720   find_entry.comp_dir = comp_dir;
8721   slot = htab_find_slot (dwarf2_per_objfile->dwo_files, &find_entry, INSERT);
8722
8723   return slot;
8724 }
8725
8726 static hashval_t
8727 hash_dwo_unit (const void *item)
8728 {
8729   const struct dwo_unit *dwo_unit = item;
8730
8731   /* This drops the top 32 bits of the id, but is ok for a hash.  */
8732   return dwo_unit->signature;
8733 }
8734
8735 static int
8736 eq_dwo_unit (const void *item_lhs, const void *item_rhs)
8737 {
8738   const struct dwo_unit *lhs = item_lhs;
8739   const struct dwo_unit *rhs = item_rhs;
8740
8741   /* The signature is assumed to be unique within the DWO file.
8742      So while object file CU dwo_id's always have the value zero,
8743      that's OK, assuming each object file DWO file has only one CU,
8744      and that's the rule for now.  */
8745   return lhs->signature == rhs->signature;
8746 }
8747
8748 /* Allocate a hash table for DWO CUs,TUs.
8749    There is one of these tables for each of CUs,TUs for each DWO file.  */
8750
8751 static htab_t
8752 allocate_dwo_unit_table (struct objfile *objfile)
8753 {
8754   /* Start out with a pretty small number.
8755      Generally DWO files contain only one CU and maybe some TUs.  */
8756   return htab_create_alloc_ex (3,
8757                                hash_dwo_unit,
8758                                eq_dwo_unit,
8759                                NULL,
8760                                &objfile->objfile_obstack,
8761                                hashtab_obstack_allocate,
8762                                dummy_obstack_deallocate);
8763 }
8764
8765 /* Structure used to pass data to create_dwo_debug_info_hash_table_reader.  */
8766
8767 struct create_dwo_cu_data
8768 {
8769   struct dwo_file *dwo_file;
8770   struct dwo_unit dwo_unit;
8771 };
8772
8773 /* die_reader_func for create_dwo_cu.  */
8774
8775 static void
8776 create_dwo_cu_reader (const struct die_reader_specs *reader,
8777                       const gdb_byte *info_ptr,
8778                       struct die_info *comp_unit_die,
8779                       int has_children,
8780                       void *datap)
8781 {
8782   struct dwarf2_cu *cu = reader->cu;
8783   struct objfile *objfile = dwarf2_per_objfile->objfile;
8784   sect_offset offset = cu->per_cu->offset;
8785   struct dwarf2_section_info *section = cu->per_cu->section;
8786   struct create_dwo_cu_data *data = datap;
8787   struct dwo_file *dwo_file = data->dwo_file;
8788   struct dwo_unit *dwo_unit = &data->dwo_unit;
8789   struct attribute *attr;
8790
8791   attr = dwarf2_attr (comp_unit_die, DW_AT_GNU_dwo_id, cu);
8792   if (attr == NULL)
8793     {
8794       complaint (&symfile_complaints,
8795                  _("Dwarf Error: debug entry at offset 0x%x is missing"
8796                    " its dwo_id [in module %s]"),
8797                  offset.sect_off, dwo_file->dwo_name);
8798       return;
8799     }
8800
8801   dwo_unit->dwo_file = dwo_file;
8802   dwo_unit->signature = DW_UNSND (attr);
8803   dwo_unit->section = section;
8804   dwo_unit->offset = offset;
8805   dwo_unit->length = cu->per_cu->length;
8806
8807   if (dwarf2_read_debug)
8808     fprintf_unfiltered (gdb_stdlog, "  offset 0x%x, dwo_id %s\n",
8809                         offset.sect_off, hex_string (dwo_unit->signature));
8810 }
8811
8812 /* Create the dwo_unit for the lone CU in DWO_FILE.
8813    Note: This function processes DWO files only, not DWP files.  */
8814
8815 static struct dwo_unit *
8816 create_dwo_cu (struct dwo_file *dwo_file)
8817 {
8818   struct objfile *objfile = dwarf2_per_objfile->objfile;
8819   struct dwarf2_section_info *section = &dwo_file->sections.info;
8820   bfd *abfd;
8821   htab_t cu_htab;
8822   const gdb_byte *info_ptr, *end_ptr;
8823   struct create_dwo_cu_data create_dwo_cu_data;
8824   struct dwo_unit *dwo_unit;
8825
8826   dwarf2_read_section (objfile, section);
8827   info_ptr = section->buffer;
8828
8829   if (info_ptr == NULL)
8830     return NULL;
8831
8832   /* We can't set abfd until now because the section may be empty or
8833      not present, in which case section->asection will be NULL.  */
8834   abfd = section->asection->owner;
8835
8836   if (dwarf2_read_debug)
8837     {
8838       fprintf_unfiltered (gdb_stdlog, "Reading %s for %s:\n",
8839                           bfd_section_name (abfd, section->asection),
8840                           bfd_get_filename (abfd));
8841     }
8842
8843   create_dwo_cu_data.dwo_file = dwo_file;
8844   dwo_unit = NULL;
8845
8846   end_ptr = info_ptr + section->size;
8847   while (info_ptr < end_ptr)
8848     {
8849       struct dwarf2_per_cu_data per_cu;
8850
8851       memset (&create_dwo_cu_data.dwo_unit, 0,
8852               sizeof (create_dwo_cu_data.dwo_unit));
8853       memset (&per_cu, 0, sizeof (per_cu));
8854       per_cu.objfile = objfile;
8855       per_cu.is_debug_types = 0;
8856       per_cu.offset.sect_off = info_ptr - section->buffer;
8857       per_cu.section = section;
8858
8859       init_cutu_and_read_dies_no_follow (&per_cu,
8860                                          &dwo_file->sections.abbrev,
8861                                          dwo_file,
8862                                          create_dwo_cu_reader,
8863                                          &create_dwo_cu_data);
8864
8865       if (create_dwo_cu_data.dwo_unit.dwo_file != NULL)
8866         {
8867           /* If we've already found one, complain.  We only support one
8868              because having more than one requires hacking the dwo_name of
8869              each to match, which is highly unlikely to happen.  */
8870           if (dwo_unit != NULL)
8871             {
8872               complaint (&symfile_complaints,
8873                          _("Multiple CUs in DWO file %s [in module %s]"),
8874                          dwo_file->dwo_name, objfile->name);
8875               break;
8876             }
8877
8878           dwo_unit = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_unit);
8879           *dwo_unit = create_dwo_cu_data.dwo_unit;
8880         }
8881
8882       info_ptr += per_cu.length;
8883     }
8884
8885   return dwo_unit;
8886 }
8887
8888 /* DWP file .debug_{cu,tu}_index section format:
8889    [ref: http://gcc.gnu.org/wiki/DebugFissionDWP]
8890
8891    DWP Version 1:
8892
8893    Both index sections have the same format, and serve to map a 64-bit
8894    signature to a set of section numbers.  Each section begins with a header,
8895    followed by a hash table of 64-bit signatures, a parallel table of 32-bit
8896    indexes, and a pool of 32-bit section numbers.  The index sections will be
8897    aligned at 8-byte boundaries in the file.
8898
8899    The index section header consists of:
8900
8901     V, 32 bit version number
8902     -, 32 bits unused
8903     N, 32 bit number of compilation units or type units in the index
8904     M, 32 bit number of slots in the hash table
8905
8906    Numbers are recorded using the byte order of the application binary.
8907
8908    We assume that N and M will not exceed 2^32 - 1.
8909
8910    The size of the hash table, M, must be 2^k such that 2^k > 3*N/2.
8911
8912    The hash table begins at offset 16 in the section, and consists of an array
8913    of M 64-bit slots.  Each slot contains a 64-bit signature (using the byte
8914    order of the application binary).  Unused slots in the hash table are 0.
8915    (We rely on the extreme unlikeliness of a signature being exactly 0.)
8916
8917    The parallel table begins immediately after the hash table
8918    (at offset 16 + 8 * M from the beginning of the section), and consists of an
8919    array of 32-bit indexes (using the byte order of the application binary),
8920    corresponding 1-1 with slots in the hash table.  Each entry in the parallel
8921    table contains a 32-bit index into the pool of section numbers.  For unused
8922    hash table slots, the corresponding entry in the parallel table will be 0.
8923
8924    Given a 64-bit compilation unit signature or a type signature S, an entry
8925    in the hash table is located as follows:
8926
8927    1) Calculate a primary hash H = S & MASK(k), where MASK(k) is a mask with
8928       the low-order k bits all set to 1.
8929
8930    2) Calculate a secondary hash H' = (((S >> 32) & MASK(k)) | 1).
8931
8932    3) If the hash table entry at index H matches the signature, use that
8933       entry.  If the hash table entry at index H is unused (all zeroes),
8934       terminate the search: the signature is not present in the table.
8935
8936    4) Let H = (H + H') modulo M. Repeat at Step 3.
8937
8938    Because M > N and H' and M are relatively prime, the search is guaranteed
8939    to stop at an unused slot or find the match.
8940
8941    The pool of section numbers begins immediately following the hash table
8942    (at offset 16 + 12 * M from the beginning of the section).  The pool of
8943    section numbers consists of an array of 32-bit words (using the byte order
8944    of the application binary).  Each item in the array is indexed starting
8945    from 0.  The hash table entry provides the index of the first section
8946    number in the set.  Additional section numbers in the set follow, and the
8947    set is terminated by a 0 entry (section number 0 is not used in ELF).
8948
8949    In each set of section numbers, the .debug_info.dwo or .debug_types.dwo
8950    section must be the first entry in the set, and the .debug_abbrev.dwo must
8951    be the second entry. Other members of the set may follow in any order.  */
8952
8953 /* Create a hash table to map DWO IDs to their CU/TU entry in
8954    .debug_{info,types}.dwo in DWP_FILE.
8955    Returns NULL if there isn't one.
8956    Note: This function processes DWP files only, not DWO files.  */
8957
8958 static struct dwp_hash_table *
8959 create_dwp_hash_table (struct dwp_file *dwp_file, int is_debug_types)
8960 {
8961   struct objfile *objfile = dwarf2_per_objfile->objfile;
8962   bfd *dbfd = dwp_file->dbfd;
8963   const gdb_byte *index_ptr, *index_end;
8964   struct dwarf2_section_info *index;
8965   uint32_t version, nr_units, nr_slots;
8966   struct dwp_hash_table *htab;
8967
8968   if (is_debug_types)
8969     index = &dwp_file->sections.tu_index;
8970   else
8971     index = &dwp_file->sections.cu_index;
8972
8973   if (dwarf2_section_empty_p (index))
8974     return NULL;
8975   dwarf2_read_section (objfile, index);
8976
8977   index_ptr = index->buffer;
8978   index_end = index_ptr + index->size;
8979
8980   version = read_4_bytes (dbfd, index_ptr);
8981   index_ptr += 8; /* Skip the unused word.  */
8982   nr_units = read_4_bytes (dbfd, index_ptr);
8983   index_ptr += 4;
8984   nr_slots = read_4_bytes (dbfd, index_ptr);
8985   index_ptr += 4;
8986
8987   if (version != 1)
8988     {
8989       error (_("Dwarf Error: unsupported DWP file version (%s)"
8990                " [in module %s]"),
8991              pulongest (version), dwp_file->name);
8992     }
8993   if (nr_slots != (nr_slots & -nr_slots))
8994     {
8995       error (_("Dwarf Error: number of slots in DWP hash table (%s)"
8996                " is not power of 2 [in module %s]"),
8997              pulongest (nr_slots), dwp_file->name);
8998     }
8999
9000   htab = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwp_hash_table);
9001   htab->nr_units = nr_units;
9002   htab->nr_slots = nr_slots;
9003   htab->hash_table = index_ptr;
9004   htab->unit_table = htab->hash_table + sizeof (uint64_t) * nr_slots;
9005   htab->section_pool = htab->unit_table + sizeof (uint32_t) * nr_slots;
9006
9007   return htab;
9008 }
9009
9010 /* Update SECTIONS with the data from SECTP.
9011
9012    This function is like the other "locate" section routines that are
9013    passed to bfd_map_over_sections, but in this context the sections to
9014    read comes from the DWP hash table, not the full ELF section table.
9015
9016    The result is non-zero for success, or zero if an error was found.  */
9017
9018 static int
9019 locate_virtual_dwo_sections (asection *sectp,
9020                              struct virtual_dwo_sections *sections)
9021 {
9022   const struct dwop_section_names *names = &dwop_section_names;
9023
9024   if (section_is_p (sectp->name, &names->abbrev_dwo))
9025     {
9026       /* There can be only one.  */
9027       if (sections->abbrev.asection != NULL)
9028         return 0;
9029       sections->abbrev.asection = sectp;
9030       sections->abbrev.size = bfd_get_section_size (sectp);
9031     }
9032   else if (section_is_p (sectp->name, &names->info_dwo)
9033            || section_is_p (sectp->name, &names->types_dwo))
9034     {
9035       /* There can be only one.  */
9036       if (sections->info_or_types.asection != NULL)
9037         return 0;
9038       sections->info_or_types.asection = sectp;
9039       sections->info_or_types.size = bfd_get_section_size (sectp);
9040     }
9041   else if (section_is_p (sectp->name, &names->line_dwo))
9042     {
9043       /* There can be only one.  */
9044       if (sections->line.asection != NULL)
9045         return 0;
9046       sections->line.asection = sectp;
9047       sections->line.size = bfd_get_section_size (sectp);
9048     }
9049   else if (section_is_p (sectp->name, &names->loc_dwo))
9050     {
9051       /* There can be only one.  */
9052       if (sections->loc.asection != NULL)
9053         return 0;
9054       sections->loc.asection = sectp;
9055       sections->loc.size = bfd_get_section_size (sectp);
9056     }
9057   else if (section_is_p (sectp->name, &names->macinfo_dwo))
9058     {
9059       /* There can be only one.  */
9060       if (sections->macinfo.asection != NULL)
9061         return 0;
9062       sections->macinfo.asection = sectp;
9063       sections->macinfo.size = bfd_get_section_size (sectp);
9064     }
9065   else if (section_is_p (sectp->name, &names->macro_dwo))
9066     {
9067       /* There can be only one.  */
9068       if (sections->macro.asection != NULL)
9069         return 0;
9070       sections->macro.asection = sectp;
9071       sections->macro.size = bfd_get_section_size (sectp);
9072     }
9073   else if (section_is_p (sectp->name, &names->str_offsets_dwo))
9074     {
9075       /* There can be only one.  */
9076       if (sections->str_offsets.asection != NULL)
9077         return 0;
9078       sections->str_offsets.asection = sectp;
9079       sections->str_offsets.size = bfd_get_section_size (sectp);
9080     }
9081   else
9082     {
9083       /* No other kind of section is valid.  */
9084       return 0;
9085     }
9086
9087   return 1;
9088 }
9089
9090 /* Create a dwo_unit object for the DWO with signature SIGNATURE.
9091    HTAB is the hash table from the DWP file.
9092    SECTION_INDEX is the index of the DWO in HTAB.
9093    COMP_DIR is the DW_AT_comp_dir attribute of the referencing CU.  */
9094
9095 static struct dwo_unit *
9096 create_dwo_in_dwp (struct dwp_file *dwp_file,
9097                    const struct dwp_hash_table *htab,
9098                    uint32_t section_index,
9099                    const char *comp_dir,
9100                    ULONGEST signature, int is_debug_types)
9101 {
9102   struct objfile *objfile = dwarf2_per_objfile->objfile;
9103   bfd *dbfd = dwp_file->dbfd;
9104   const char *kind = is_debug_types ? "TU" : "CU";
9105   struct dwo_file *dwo_file;
9106   struct dwo_unit *dwo_unit;
9107   struct virtual_dwo_sections sections;
9108   void **dwo_file_slot;
9109   char *virtual_dwo_name;
9110   struct dwarf2_section_info *cutu;
9111   struct cleanup *cleanups;
9112   int i;
9113
9114   if (dwarf2_read_debug)
9115     {
9116       fprintf_unfiltered (gdb_stdlog, "Reading %s %s/%s in DWP file: %s\n",
9117                           kind,
9118                           pulongest (section_index), hex_string (signature),
9119                           dwp_file->name);
9120     }
9121
9122   /* Fetch the sections of this DWO.
9123      Put a limit on the number of sections we look for so that bad data
9124      doesn't cause us to loop forever.  */
9125
9126 #define MAX_NR_DWO_SECTIONS \
9127   (1 /* .debug_info or .debug_types */ \
9128    + 1 /* .debug_abbrev */ \
9129    + 1 /* .debug_line */ \
9130    + 1 /* .debug_loc */ \
9131    + 1 /* .debug_str_offsets */ \
9132    + 1 /* .debug_macro */ \
9133    + 1 /* .debug_macinfo */ \
9134    + 1 /* trailing zero */)
9135
9136   memset (&sections, 0, sizeof (sections));
9137   cleanups = make_cleanup (null_cleanup, 0);
9138
9139   for (i = 0; i < MAX_NR_DWO_SECTIONS; ++i)
9140     {
9141       asection *sectp;
9142       uint32_t section_nr =
9143         read_4_bytes (dbfd,
9144                       htab->section_pool
9145                       + (section_index + i) * sizeof (uint32_t));
9146
9147       if (section_nr == 0)
9148         break;
9149       if (section_nr >= dwp_file->num_sections)
9150         {
9151           error (_("Dwarf Error: bad DWP hash table, section number too large"
9152                    " [in module %s]"),
9153                  dwp_file->name);
9154         }
9155
9156       sectp = dwp_file->elf_sections[section_nr];
9157       if (! locate_virtual_dwo_sections (sectp, &sections))
9158         {
9159           error (_("Dwarf Error: bad DWP hash table, invalid section found"
9160                    " [in module %s]"),
9161                  dwp_file->name);
9162         }
9163     }
9164
9165   if (i < 2
9166       || sections.info_or_types.asection == NULL
9167       || sections.abbrev.asection == NULL)
9168     {
9169       error (_("Dwarf Error: bad DWP hash table, missing DWO sections"
9170                " [in module %s]"),
9171              dwp_file->name);
9172     }
9173   if (i == MAX_NR_DWO_SECTIONS)
9174     {
9175       error (_("Dwarf Error: bad DWP hash table, too many DWO sections"
9176                " [in module %s]"),
9177              dwp_file->name);
9178     }
9179
9180   /* It's easier for the rest of the code if we fake a struct dwo_file and
9181      have dwo_unit "live" in that.  At least for now.
9182
9183      The DWP file can be made up of a random collection of CUs and TUs.
9184      However, for each CU + set of TUs that came from the same original DWO
9185      file, we want to combine them back into a virtual DWO file to save space
9186      (fewer struct dwo_file objects to allocated).  Remember that for really
9187      large apps there can be on the order of 8K CUs and 200K TUs, or more.  */
9188
9189   virtual_dwo_name =
9190     xstrprintf ("virtual-dwo/%d-%d-%d-%d",
9191                 sections.abbrev.asection ? sections.abbrev.asection->id : 0,
9192                 sections.line.asection ? sections.line.asection->id : 0,
9193                 sections.loc.asection ? sections.loc.asection->id : 0,
9194                 (sections.str_offsets.asection
9195                 ? sections.str_offsets.asection->id
9196                 : 0));
9197   make_cleanup (xfree, virtual_dwo_name);
9198   /* Can we use an existing virtual DWO file?  */
9199   dwo_file_slot = lookup_dwo_file_slot (virtual_dwo_name, comp_dir);
9200   /* Create one if necessary.  */
9201   if (*dwo_file_slot == NULL)
9202     {
9203       if (dwarf2_read_debug)
9204         {
9205           fprintf_unfiltered (gdb_stdlog, "Creating virtual DWO: %s\n",
9206                               virtual_dwo_name);
9207         }
9208       dwo_file = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_file);
9209       dwo_file->dwo_name = obstack_copy0 (&objfile->objfile_obstack,
9210                                           virtual_dwo_name,
9211                                           strlen (virtual_dwo_name));
9212       dwo_file->comp_dir = comp_dir;
9213       dwo_file->sections.abbrev = sections.abbrev;
9214       dwo_file->sections.line = sections.line;
9215       dwo_file->sections.loc = sections.loc;
9216       dwo_file->sections.macinfo = sections.macinfo;
9217       dwo_file->sections.macro = sections.macro;
9218       dwo_file->sections.str_offsets = sections.str_offsets;
9219       /* The "str" section is global to the entire DWP file.  */
9220       dwo_file->sections.str = dwp_file->sections.str;
9221       /* The info or types section is assigned later to dwo_unit,
9222          there's no need to record it in dwo_file.
9223          Also, we can't simply record type sections in dwo_file because
9224          we record a pointer into the vector in dwo_unit.  As we collect more
9225          types we'll grow the vector and eventually have to reallocate space
9226          for it, invalidating all the pointers into the current copy.  */
9227       *dwo_file_slot = dwo_file;
9228     }
9229   else
9230     {
9231       if (dwarf2_read_debug)
9232         {
9233           fprintf_unfiltered (gdb_stdlog, "Using existing virtual DWO: %s\n",
9234                               virtual_dwo_name);
9235         }
9236       dwo_file = *dwo_file_slot;
9237     }
9238   do_cleanups (cleanups);
9239
9240   dwo_unit = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_unit);
9241   dwo_unit->dwo_file = dwo_file;
9242   dwo_unit->signature = signature;
9243   dwo_unit->section = obstack_alloc (&objfile->objfile_obstack,
9244                                      sizeof (struct dwarf2_section_info));
9245   *dwo_unit->section = sections.info_or_types;
9246   /* offset, length, type_offset_in_tu are set later.  */
9247
9248   return dwo_unit;
9249 }
9250
9251 /* Lookup the DWO with SIGNATURE in DWP_FILE.  */
9252
9253 static struct dwo_unit *
9254 lookup_dwo_in_dwp (struct dwp_file *dwp_file,
9255                    const struct dwp_hash_table *htab,
9256                    const char *comp_dir,
9257                    ULONGEST signature, int is_debug_types)
9258 {
9259   bfd *dbfd = dwp_file->dbfd;
9260   uint32_t mask = htab->nr_slots - 1;
9261   uint32_t hash = signature & mask;
9262   uint32_t hash2 = ((signature >> 32) & mask) | 1;
9263   unsigned int i;
9264   void **slot;
9265   struct dwo_unit find_dwo_cu, *dwo_cu;
9266
9267   memset (&find_dwo_cu, 0, sizeof (find_dwo_cu));
9268   find_dwo_cu.signature = signature;
9269   slot = htab_find_slot (dwp_file->loaded_cutus, &find_dwo_cu, INSERT);
9270
9271   if (*slot != NULL)
9272     return *slot;
9273
9274   /* Use a for loop so that we don't loop forever on bad debug info.  */
9275   for (i = 0; i < htab->nr_slots; ++i)
9276     {
9277       ULONGEST signature_in_table;
9278
9279       signature_in_table =
9280         read_8_bytes (dbfd, htab->hash_table + hash * sizeof (uint64_t));
9281       if (signature_in_table == signature)
9282         {
9283           uint32_t section_index =
9284             read_4_bytes (dbfd, htab->unit_table + hash * sizeof (uint32_t));
9285
9286           *slot = create_dwo_in_dwp (dwp_file, htab, section_index,
9287                                      comp_dir, signature, is_debug_types);
9288           return *slot;
9289         }
9290       if (signature_in_table == 0)
9291         return NULL;
9292       hash = (hash + hash2) & mask;
9293     }
9294
9295   error (_("Dwarf Error: bad DWP hash table, lookup didn't terminate"
9296            " [in module %s]"),
9297          dwp_file->name);
9298 }
9299
9300 /* Subroutine of open_dwo_file,open_dwp_file to simplify them.
9301    Open the file specified by FILE_NAME and hand it off to BFD for
9302    preliminary analysis.  Return a newly initialized bfd *, which
9303    includes a canonicalized copy of FILE_NAME.
9304    If IS_DWP is TRUE, we're opening a DWP file, otherwise a DWO file.
9305    SEARCH_CWD is true if the current directory is to be searched.
9306    It will be searched before debug-file-directory.
9307    If unable to find/open the file, return NULL.
9308    NOTE: This function is derived from symfile_bfd_open.  */
9309
9310 static bfd *
9311 try_open_dwop_file (const char *file_name, int is_dwp, int search_cwd)
9312 {
9313   bfd *sym_bfd;
9314   int desc, flags;
9315   char *absolute_name;
9316   /* Blech.  OPF_TRY_CWD_FIRST also disables searching the path list if
9317      FILE_NAME contains a '/'.  So we can't use it.  Instead prepend "."
9318      to debug_file_directory.  */
9319   char *search_path;
9320   static const char dirname_separator_string[] = { DIRNAME_SEPARATOR, '\0' };
9321
9322   if (search_cwd)
9323     {
9324       if (*debug_file_directory != '\0')
9325         search_path = concat (".", dirname_separator_string,
9326                               debug_file_directory, NULL);
9327       else
9328         search_path = xstrdup (".");
9329     }
9330   else
9331     search_path = xstrdup (debug_file_directory);
9332
9333   flags = 0;
9334   if (is_dwp)
9335     flags |= OPF_SEARCH_IN_PATH;
9336   desc = openp (search_path, flags, file_name,
9337                 O_RDONLY | O_BINARY, &absolute_name);
9338   xfree (search_path);
9339   if (desc < 0)
9340     return NULL;
9341
9342   sym_bfd = gdb_bfd_open (absolute_name, gnutarget, desc);
9343   xfree (absolute_name);
9344   if (sym_bfd == NULL)
9345     return NULL;
9346   bfd_set_cacheable (sym_bfd, 1);
9347
9348   if (!bfd_check_format (sym_bfd, bfd_object))
9349     {
9350       gdb_bfd_unref (sym_bfd); /* This also closes desc.  */
9351       return NULL;
9352     }
9353
9354   return sym_bfd;
9355 }
9356
9357 /* Try to open DWO file FILE_NAME.
9358    COMP_DIR is the DW_AT_comp_dir attribute.
9359    The result is the bfd handle of the file.
9360    If there is a problem finding or opening the file, return NULL.
9361    Upon success, the canonicalized path of the file is stored in the bfd,
9362    same as symfile_bfd_open.  */
9363
9364 static bfd *
9365 open_dwo_file (const char *file_name, const char *comp_dir)
9366 {
9367   bfd *abfd;
9368
9369   if (IS_ABSOLUTE_PATH (file_name))
9370     return try_open_dwop_file (file_name, 0 /*is_dwp*/, 0 /*search_cwd*/);
9371
9372   /* Before trying the search path, try DWO_NAME in COMP_DIR.  */
9373
9374   if (comp_dir != NULL)
9375     {
9376       char *path_to_try = concat (comp_dir, SLASH_STRING, file_name, NULL);
9377
9378       /* NOTE: If comp_dir is a relative path, this will also try the
9379          search path, which seems useful.  */
9380       abfd = try_open_dwop_file (path_to_try, 0 /*is_dwp*/, 1 /*search_cwd*/);
9381       xfree (path_to_try);
9382       if (abfd != NULL)
9383         return abfd;
9384     }
9385
9386   /* That didn't work, try debug-file-directory, which, despite its name,
9387      is a list of paths.  */
9388
9389   if (*debug_file_directory == '\0')
9390     return NULL;
9391
9392   return try_open_dwop_file (file_name, 0 /*is_dwp*/, 1 /*search_cwd*/);
9393 }
9394
9395 /* This function is mapped across the sections and remembers the offset and
9396    size of each of the DWO debugging sections we are interested in.  */
9397
9398 static void
9399 dwarf2_locate_dwo_sections (bfd *abfd, asection *sectp, void *dwo_sections_ptr)
9400 {
9401   struct dwo_sections *dwo_sections = dwo_sections_ptr;
9402   const struct dwop_section_names *names = &dwop_section_names;
9403
9404   if (section_is_p (sectp->name, &names->abbrev_dwo))
9405     {
9406       dwo_sections->abbrev.asection = sectp;
9407       dwo_sections->abbrev.size = bfd_get_section_size (sectp);
9408     }
9409   else if (section_is_p (sectp->name, &names->info_dwo))
9410     {
9411       dwo_sections->info.asection = sectp;
9412       dwo_sections->info.size = bfd_get_section_size (sectp);
9413     }
9414   else if (section_is_p (sectp->name, &names->line_dwo))
9415     {
9416       dwo_sections->line.asection = sectp;
9417       dwo_sections->line.size = bfd_get_section_size (sectp);
9418     }
9419   else if (section_is_p (sectp->name, &names->loc_dwo))
9420     {
9421       dwo_sections->loc.asection = sectp;
9422       dwo_sections->loc.size = bfd_get_section_size (sectp);
9423     }
9424   else if (section_is_p (sectp->name, &names->macinfo_dwo))
9425     {
9426       dwo_sections->macinfo.asection = sectp;
9427       dwo_sections->macinfo.size = bfd_get_section_size (sectp);
9428     }
9429   else if (section_is_p (sectp->name, &names->macro_dwo))
9430     {
9431       dwo_sections->macro.asection = sectp;
9432       dwo_sections->macro.size = bfd_get_section_size (sectp);
9433     }
9434   else if (section_is_p (sectp->name, &names->str_dwo))
9435     {
9436       dwo_sections->str.asection = sectp;
9437       dwo_sections->str.size = bfd_get_section_size (sectp);
9438     }
9439   else if (section_is_p (sectp->name, &names->str_offsets_dwo))
9440     {
9441       dwo_sections->str_offsets.asection = sectp;
9442       dwo_sections->str_offsets.size = bfd_get_section_size (sectp);
9443     }
9444   else if (section_is_p (sectp->name, &names->types_dwo))
9445     {
9446       struct dwarf2_section_info type_section;
9447
9448       memset (&type_section, 0, sizeof (type_section));
9449       type_section.asection = sectp;
9450       type_section.size = bfd_get_section_size (sectp);
9451       VEC_safe_push (dwarf2_section_info_def, dwo_sections->types,
9452                      &type_section);
9453     }
9454 }
9455
9456 /* Initialize the use of the DWO file specified by DWO_NAME and referenced
9457    by PER_CU.  This is for the non-DWP case.
9458    The result is NULL if DWO_NAME can't be found.  */
9459
9460 static struct dwo_file *
9461 open_and_init_dwo_file (struct dwarf2_per_cu_data *per_cu,
9462                         const char *dwo_name, const char *comp_dir)
9463 {
9464   struct objfile *objfile = dwarf2_per_objfile->objfile;
9465   struct dwo_file *dwo_file;
9466   bfd *dbfd;
9467   struct cleanup *cleanups;
9468
9469   dbfd = open_dwo_file (dwo_name, comp_dir);
9470   if (dbfd == NULL)
9471     {
9472       if (dwarf2_read_debug)
9473         fprintf_unfiltered (gdb_stdlog, "DWO file not found: %s\n", dwo_name);
9474       return NULL;
9475     }
9476   dwo_file = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_file);
9477   dwo_file->dwo_name = dwo_name;
9478   dwo_file->comp_dir = comp_dir;
9479   dwo_file->dbfd = dbfd;
9480
9481   cleanups = make_cleanup (free_dwo_file_cleanup, dwo_file);
9482
9483   bfd_map_over_sections (dbfd, dwarf2_locate_dwo_sections, &dwo_file->sections);
9484
9485   dwo_file->cu = create_dwo_cu (dwo_file);
9486
9487   dwo_file->tus = create_debug_types_hash_table (dwo_file,
9488                                                  dwo_file->sections.types);
9489
9490   discard_cleanups (cleanups);
9491
9492   if (dwarf2_read_debug)
9493     fprintf_unfiltered (gdb_stdlog, "DWO file found: %s\n", dwo_name);
9494
9495   return dwo_file;
9496 }
9497
9498 /* This function is mapped across the sections and remembers the offset and
9499    size of each of the DWP debugging sections we are interested in.  */
9500
9501 static void
9502 dwarf2_locate_dwp_sections (bfd *abfd, asection *sectp, void *dwp_file_ptr)
9503 {
9504   struct dwp_file *dwp_file = dwp_file_ptr;
9505   const struct dwop_section_names *names = &dwop_section_names;
9506   unsigned int elf_section_nr = elf_section_data (sectp)->this_idx;
9507
9508   /* Record the ELF section number for later lookup: this is what the
9509      .debug_cu_index,.debug_tu_index tables use.  */
9510   gdb_assert (elf_section_nr < dwp_file->num_sections);
9511   dwp_file->elf_sections[elf_section_nr] = sectp;
9512
9513   /* Look for specific sections that we need.  */
9514   if (section_is_p (sectp->name, &names->str_dwo))
9515     {
9516       dwp_file->sections.str.asection = sectp;
9517       dwp_file->sections.str.size = bfd_get_section_size (sectp);
9518     }
9519   else if (section_is_p (sectp->name, &names->cu_index))
9520     {
9521       dwp_file->sections.cu_index.asection = sectp;
9522       dwp_file->sections.cu_index.size = bfd_get_section_size (sectp);
9523     }
9524   else if (section_is_p (sectp->name, &names->tu_index))
9525     {
9526       dwp_file->sections.tu_index.asection = sectp;
9527       dwp_file->sections.tu_index.size = bfd_get_section_size (sectp);
9528     }
9529 }
9530
9531 /* Hash function for dwp_file loaded CUs/TUs.  */
9532
9533 static hashval_t
9534 hash_dwp_loaded_cutus (const void *item)
9535 {
9536   const struct dwo_unit *dwo_unit = item;
9537
9538   /* This drops the top 32 bits of the signature, but is ok for a hash.  */
9539   return dwo_unit->signature;
9540 }
9541
9542 /* Equality function for dwp_file loaded CUs/TUs.  */
9543
9544 static int
9545 eq_dwp_loaded_cutus (const void *a, const void *b)
9546 {
9547   const struct dwo_unit *dua = a;
9548   const struct dwo_unit *dub = b;
9549
9550   return dua->signature == dub->signature;
9551 }
9552
9553 /* Allocate a hash table for dwp_file loaded CUs/TUs.  */
9554
9555 static htab_t
9556 allocate_dwp_loaded_cutus_table (struct objfile *objfile)
9557 {
9558   return htab_create_alloc_ex (3,
9559                                hash_dwp_loaded_cutus,
9560                                eq_dwp_loaded_cutus,
9561                                NULL,
9562                                &objfile->objfile_obstack,
9563                                hashtab_obstack_allocate,
9564                                dummy_obstack_deallocate);
9565 }
9566
9567 /* Try to open DWP file FILE_NAME.
9568    The result is the bfd handle of the file.
9569    If there is a problem finding or opening the file, return NULL.
9570    Upon success, the canonicalized path of the file is stored in the bfd,
9571    same as symfile_bfd_open.  */
9572
9573 static bfd *
9574 open_dwp_file (const char *file_name)
9575 {
9576   bfd *abfd;
9577
9578   abfd = try_open_dwop_file (file_name, 1 /*is_dwp*/, 1 /*search_cwd*/);
9579   if (abfd != NULL)
9580     return abfd;
9581
9582   /* Work around upstream bug 15652.
9583      http://sourceware.org/bugzilla/show_bug.cgi?id=15652
9584      [Whether that's a "bug" is debatable, but it is getting in our way.]
9585      We have no real idea where the dwp file is, because gdb's realpath-ing
9586      of the executable's path may have discarded the needed info.
9587      [IWBN if the dwp file name was recorded in the executable, akin to
9588      .gnu_debuglink, but that doesn't exist yet.]
9589      Strip the directory from FILE_NAME and search again.  */
9590   if (*debug_file_directory != '\0')
9591     {
9592       /* Don't implicitly search the current directory here.
9593          If the user wants to search "." to handle this case,
9594          it must be added to debug-file-directory.  */
9595       return try_open_dwop_file (lbasename (file_name), 1 /*is_dwp*/,
9596                                  0 /*search_cwd*/);
9597     }
9598
9599   return NULL;
9600 }
9601
9602 /* Initialize the use of the DWP file for the current objfile.
9603    By convention the name of the DWP file is ${objfile}.dwp.
9604    The result is NULL if it can't be found.  */
9605
9606 static struct dwp_file *
9607 open_and_init_dwp_file (void)
9608 {
9609   struct objfile *objfile = dwarf2_per_objfile->objfile;
9610   struct dwp_file *dwp_file;
9611   char *dwp_name;
9612   bfd *dbfd;
9613   struct cleanup *cleanups;
9614
9615   dwp_name = xstrprintf ("%s.dwp", dwarf2_per_objfile->objfile->name);
9616   cleanups = make_cleanup (xfree, dwp_name);
9617
9618   dbfd = open_dwp_file (dwp_name);
9619   if (dbfd == NULL)
9620     {
9621       if (dwarf2_read_debug)
9622         fprintf_unfiltered (gdb_stdlog, "DWP file not found: %s\n", dwp_name);
9623       do_cleanups (cleanups);
9624       return NULL;
9625     }
9626   dwp_file = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwp_file);
9627   dwp_file->name = bfd_get_filename (dbfd);
9628   dwp_file->dbfd = dbfd;
9629   do_cleanups (cleanups);
9630
9631   /* +1: section 0 is unused */
9632   dwp_file->num_sections = bfd_count_sections (dbfd) + 1;
9633   dwp_file->elf_sections =
9634     OBSTACK_CALLOC (&objfile->objfile_obstack,
9635                     dwp_file->num_sections, asection *);
9636
9637   bfd_map_over_sections (dbfd, dwarf2_locate_dwp_sections, dwp_file);
9638
9639   dwp_file->cus = create_dwp_hash_table (dwp_file, 0);
9640
9641   dwp_file->tus = create_dwp_hash_table (dwp_file, 1);
9642
9643   dwp_file->loaded_cutus = allocate_dwp_loaded_cutus_table (objfile);
9644
9645   if (dwarf2_read_debug)
9646     {
9647       fprintf_unfiltered (gdb_stdlog, "DWP file found: %s\n", dwp_file->name);
9648       fprintf_unfiltered (gdb_stdlog,
9649                           "    %s CUs, %s TUs\n",
9650                           pulongest (dwp_file->cus ? dwp_file->cus->nr_units : 0),
9651                           pulongest (dwp_file->tus ? dwp_file->tus->nr_units : 0));
9652     }
9653
9654   return dwp_file;
9655 }
9656
9657 /* Wrapper around open_and_init_dwp_file, only open it once.  */
9658
9659 static struct dwp_file *
9660 get_dwp_file (void)
9661 {
9662   if (! dwarf2_per_objfile->dwp_checked)
9663     {
9664       dwarf2_per_objfile->dwp_file = open_and_init_dwp_file ();
9665       dwarf2_per_objfile->dwp_checked = 1;
9666     }
9667   return dwarf2_per_objfile->dwp_file;
9668 }
9669
9670 /* Subroutine of lookup_dwo_comp_unit, lookup_dwo_type_unit.
9671    Look up the CU/TU with signature SIGNATURE, either in DWO file DWO_NAME
9672    or in the DWP file for the objfile, referenced by THIS_UNIT.
9673    If non-NULL, comp_dir is the DW_AT_comp_dir attribute.
9674    IS_DEBUG_TYPES is non-zero if reading a TU, otherwise read a CU.
9675
9676    This is called, for example, when wanting to read a variable with a
9677    complex location.  Therefore we don't want to do file i/o for every call.
9678    Therefore we don't want to look for a DWO file on every call.
9679    Therefore we first see if we've already seen SIGNATURE in a DWP file,
9680    then we check if we've already seen DWO_NAME, and only THEN do we check
9681    for a DWO file.
9682
9683    The result is a pointer to the dwo_unit object or NULL if we didn't find it
9684    (dwo_id mismatch or couldn't find the DWO/DWP file).  */
9685
9686 static struct dwo_unit *
9687 lookup_dwo_cutu (struct dwarf2_per_cu_data *this_unit,
9688                  const char *dwo_name, const char *comp_dir,
9689                  ULONGEST signature, int is_debug_types)
9690 {
9691   struct objfile *objfile = dwarf2_per_objfile->objfile;
9692   const char *kind = is_debug_types ? "TU" : "CU";
9693   void **dwo_file_slot;
9694   struct dwo_file *dwo_file;
9695   struct dwp_file *dwp_file;
9696
9697   /* First see if there's a DWP file.
9698      If we have a DWP file but didn't find the DWO inside it, don't
9699      look for the original DWO file.  It makes gdb behave differently
9700      depending on whether one is debugging in the build tree.  */
9701
9702   dwp_file = get_dwp_file ();
9703   if (dwp_file != NULL)
9704     {
9705       const struct dwp_hash_table *dwp_htab =
9706         is_debug_types ? dwp_file->tus : dwp_file->cus;
9707
9708       if (dwp_htab != NULL)
9709         {
9710           struct dwo_unit *dwo_cutu =
9711             lookup_dwo_in_dwp (dwp_file, dwp_htab, comp_dir,
9712                                signature, is_debug_types);
9713
9714           if (dwo_cutu != NULL)
9715             {
9716               if (dwarf2_read_debug)
9717                 {
9718                   fprintf_unfiltered (gdb_stdlog,
9719                                       "Virtual DWO %s %s found: @%s\n",
9720                                       kind, hex_string (signature),
9721                                       host_address_to_string (dwo_cutu));
9722                 }
9723               return dwo_cutu;
9724             }
9725         }
9726     }
9727   else
9728     {
9729       /* No DWP file, look for the DWO file.  */
9730
9731       dwo_file_slot = lookup_dwo_file_slot (dwo_name, comp_dir);
9732       if (*dwo_file_slot == NULL)
9733         {
9734           /* Read in the file and build a table of the CUs/TUs it contains.  */
9735           *dwo_file_slot = open_and_init_dwo_file (this_unit, dwo_name, comp_dir);
9736         }
9737       /* NOTE: This will be NULL if unable to open the file.  */
9738       dwo_file = *dwo_file_slot;
9739
9740       if (dwo_file != NULL)
9741         {
9742           struct dwo_unit *dwo_cutu = NULL;
9743
9744           if (is_debug_types && dwo_file->tus)
9745             {
9746               struct dwo_unit find_dwo_cutu;
9747
9748               memset (&find_dwo_cutu, 0, sizeof (find_dwo_cutu));
9749               find_dwo_cutu.signature = signature;
9750               dwo_cutu = htab_find (dwo_file->tus, &find_dwo_cutu);
9751             }
9752           else if (!is_debug_types && dwo_file->cu)
9753             {
9754               if (signature == dwo_file->cu->signature)
9755                 dwo_cutu = dwo_file->cu;
9756             }
9757
9758           if (dwo_cutu != NULL)
9759             {
9760               if (dwarf2_read_debug)
9761                 {
9762                   fprintf_unfiltered (gdb_stdlog, "DWO %s %s(%s) found: @%s\n",
9763                                       kind, dwo_name, hex_string (signature),
9764                                       host_address_to_string (dwo_cutu));
9765                 }
9766               return dwo_cutu;
9767             }
9768         }
9769     }
9770
9771   /* We didn't find it.  This could mean a dwo_id mismatch, or
9772      someone deleted the DWO/DWP file, or the search path isn't set up
9773      correctly to find the file.  */
9774
9775   if (dwarf2_read_debug)
9776     {
9777       fprintf_unfiltered (gdb_stdlog, "DWO %s %s(%s) not found\n",
9778                           kind, dwo_name, hex_string (signature));
9779     }
9780
9781   complaint (&symfile_complaints,
9782              _("Could not find DWO %s %s(%s) referenced by %s at offset 0x%x"
9783                " [in module %s]"),
9784              kind, dwo_name, hex_string (signature),
9785              this_unit->is_debug_types ? "TU" : "CU",
9786              this_unit->offset.sect_off, objfile->name);
9787   return NULL;
9788 }
9789
9790 /* Lookup the DWO CU DWO_NAME/SIGNATURE referenced from THIS_CU.
9791    See lookup_dwo_cutu_unit for details.  */
9792
9793 static struct dwo_unit *
9794 lookup_dwo_comp_unit (struct dwarf2_per_cu_data *this_cu,
9795                       const char *dwo_name, const char *comp_dir,
9796                       ULONGEST signature)
9797 {
9798   return lookup_dwo_cutu (this_cu, dwo_name, comp_dir, signature, 0);
9799 }
9800
9801 /* Lookup the DWO TU DWO_NAME/SIGNATURE referenced from THIS_TU.
9802    See lookup_dwo_cutu_unit for details.  */
9803
9804 static struct dwo_unit *
9805 lookup_dwo_type_unit (struct signatured_type *this_tu,
9806                       const char *dwo_name, const char *comp_dir)
9807 {
9808   return lookup_dwo_cutu (&this_tu->per_cu, dwo_name, comp_dir, this_tu->signature, 1);
9809 }
9810
9811 /* Free all resources associated with DWO_FILE.
9812    Close the DWO file and munmap the sections.
9813    All memory should be on the objfile obstack.  */
9814
9815 static void
9816 free_dwo_file (struct dwo_file *dwo_file, struct objfile *objfile)
9817 {
9818   int ix;
9819   struct dwarf2_section_info *section;
9820
9821   /* Note: dbfd is NULL for virtual DWO files.  */
9822   gdb_bfd_unref (dwo_file->dbfd);
9823
9824   VEC_free (dwarf2_section_info_def, dwo_file->sections.types);
9825 }
9826
9827 /* Wrapper for free_dwo_file for use in cleanups.  */
9828
9829 static void
9830 free_dwo_file_cleanup (void *arg)
9831 {
9832   struct dwo_file *dwo_file = (struct dwo_file *) arg;
9833   struct objfile *objfile = dwarf2_per_objfile->objfile;
9834
9835   free_dwo_file (dwo_file, objfile);
9836 }
9837
9838 /* Traversal function for free_dwo_files.  */
9839
9840 static int
9841 free_dwo_file_from_slot (void **slot, void *info)
9842 {
9843   struct dwo_file *dwo_file = (struct dwo_file *) *slot;
9844   struct objfile *objfile = (struct objfile *) info;
9845
9846   free_dwo_file (dwo_file, objfile);
9847
9848   return 1;
9849 }
9850
9851 /* Free all resources associated with DWO_FILES.  */
9852
9853 static void
9854 free_dwo_files (htab_t dwo_files, struct objfile *objfile)
9855 {
9856   htab_traverse_noresize (dwo_files, free_dwo_file_from_slot, objfile);
9857 }
9858 \f
9859 /* Read in various DIEs.  */
9860
9861 /* qsort helper for inherit_abstract_dies.  */
9862
9863 static int
9864 unsigned_int_compar (const void *ap, const void *bp)
9865 {
9866   unsigned int a = *(unsigned int *) ap;
9867   unsigned int b = *(unsigned int *) bp;
9868
9869   return (a > b) - (b > a);
9870 }
9871
9872 /* DW_AT_abstract_origin inherits whole DIEs (not just their attributes).
9873    Inherit only the children of the DW_AT_abstract_origin DIE not being
9874    already referenced by DW_AT_abstract_origin from the children of the
9875    current DIE.  */
9876
9877 static void
9878 inherit_abstract_dies (struct die_info *die, struct dwarf2_cu *cu)
9879 {
9880   struct die_info *child_die;
9881   unsigned die_children_count;
9882   /* CU offsets which were referenced by children of the current DIE.  */
9883   sect_offset *offsets;
9884   sect_offset *offsets_end, *offsetp;
9885   /* Parent of DIE - referenced by DW_AT_abstract_origin.  */
9886   struct die_info *origin_die;
9887   /* Iterator of the ORIGIN_DIE children.  */
9888   struct die_info *origin_child_die;
9889   struct cleanup *cleanups;
9890   struct attribute *attr;
9891   struct dwarf2_cu *origin_cu;
9892   struct pending **origin_previous_list_in_scope;
9893
9894   attr = dwarf2_attr (die, DW_AT_abstract_origin, cu);
9895   if (!attr)
9896     return;
9897
9898   /* Note that following die references may follow to a die in a
9899      different cu.  */
9900
9901   origin_cu = cu;
9902   origin_die = follow_die_ref (die, attr, &origin_cu);
9903
9904   /* We're inheriting ORIGIN's children into the scope we'd put DIE's
9905      symbols in.  */
9906   origin_previous_list_in_scope = origin_cu->list_in_scope;
9907   origin_cu->list_in_scope = cu->list_in_scope;
9908
9909   if (die->tag != origin_die->tag
9910       && !(die->tag == DW_TAG_inlined_subroutine
9911            && origin_die->tag == DW_TAG_subprogram))
9912     complaint (&symfile_complaints,
9913                _("DIE 0x%x and its abstract origin 0x%x have different tags"),
9914                die->offset.sect_off, origin_die->offset.sect_off);
9915
9916   child_die = die->child;
9917   die_children_count = 0;
9918   while (child_die && child_die->tag)
9919     {
9920       child_die = sibling_die (child_die);
9921       die_children_count++;
9922     }
9923   offsets = xmalloc (sizeof (*offsets) * die_children_count);
9924   cleanups = make_cleanup (xfree, offsets);
9925
9926   offsets_end = offsets;
9927   child_die = die->child;
9928   while (child_die && child_die->tag)
9929     {
9930       /* For each CHILD_DIE, find the corresponding child of
9931          ORIGIN_DIE.  If there is more than one layer of
9932          DW_AT_abstract_origin, follow them all; there shouldn't be,
9933          but GCC versions at least through 4.4 generate this (GCC PR
9934          40573).  */
9935       struct die_info *child_origin_die = child_die;
9936       struct dwarf2_cu *child_origin_cu = cu;
9937
9938       while (1)
9939         {
9940           attr = dwarf2_attr (child_origin_die, DW_AT_abstract_origin,
9941                               child_origin_cu);
9942           if (attr == NULL)
9943             break;
9944           child_origin_die = follow_die_ref (child_origin_die, attr,
9945                                              &child_origin_cu);
9946         }
9947
9948       /* According to DWARF3 3.3.8.2 #3 new entries without their abstract
9949          counterpart may exist.  */
9950       if (child_origin_die != child_die)
9951         {
9952           if (child_die->tag != child_origin_die->tag
9953               && !(child_die->tag == DW_TAG_inlined_subroutine
9954                    && child_origin_die->tag == DW_TAG_subprogram))
9955             complaint (&symfile_complaints,
9956                        _("Child DIE 0x%x and its abstract origin 0x%x have "
9957                          "different tags"), child_die->offset.sect_off,
9958                        child_origin_die->offset.sect_off);
9959           if (child_origin_die->parent != origin_die)
9960             complaint (&symfile_complaints,
9961                        _("Child DIE 0x%x and its abstract origin 0x%x have "
9962                          "different parents"), child_die->offset.sect_off,
9963                        child_origin_die->offset.sect_off);
9964           else
9965             *offsets_end++ = child_origin_die->offset;
9966         }
9967       child_die = sibling_die (child_die);
9968     }
9969   qsort (offsets, offsets_end - offsets, sizeof (*offsets),
9970          unsigned_int_compar);
9971   for (offsetp = offsets + 1; offsetp < offsets_end; offsetp++)
9972     if (offsetp[-1].sect_off == offsetp->sect_off)
9973       complaint (&symfile_complaints,
9974                  _("Multiple children of DIE 0x%x refer "
9975                    "to DIE 0x%x as their abstract origin"),
9976                  die->offset.sect_off, offsetp->sect_off);
9977
9978   offsetp = offsets;
9979   origin_child_die = origin_die->child;
9980   while (origin_child_die && origin_child_die->tag)
9981     {
9982       /* Is ORIGIN_CHILD_DIE referenced by any of the DIE children?  */
9983       while (offsetp < offsets_end
9984              && offsetp->sect_off < origin_child_die->offset.sect_off)
9985         offsetp++;
9986       if (offsetp >= offsets_end
9987           || offsetp->sect_off > origin_child_die->offset.sect_off)
9988         {
9989           /* Found that ORIGIN_CHILD_DIE is really not referenced.  */
9990           process_die (origin_child_die, origin_cu);
9991         }
9992       origin_child_die = sibling_die (origin_child_die);
9993     }
9994   origin_cu->list_in_scope = origin_previous_list_in_scope;
9995
9996   do_cleanups (cleanups);
9997 }
9998
9999 static void
10000 read_func_scope (struct die_info *die, struct dwarf2_cu *cu)
10001 {
10002   struct objfile *objfile = cu->objfile;
10003   struct context_stack *new;
10004   CORE_ADDR lowpc;
10005   CORE_ADDR highpc;
10006   struct die_info *child_die;
10007   struct attribute *attr, *call_line, *call_file;
10008   const char *name;
10009   CORE_ADDR baseaddr;
10010   struct block *block;
10011   int inlined_func = (die->tag == DW_TAG_inlined_subroutine);
10012   VEC (symbolp) *template_args = NULL;
10013   struct template_symbol *templ_func = NULL;
10014
10015   if (inlined_func)
10016     {
10017       /* If we do not have call site information, we can't show the
10018          caller of this inlined function.  That's too confusing, so
10019          only use the scope for local variables.  */
10020       call_line = dwarf2_attr (die, DW_AT_call_line, cu);
10021       call_file = dwarf2_attr (die, DW_AT_call_file, cu);
10022       if (call_line == NULL || call_file == NULL)
10023         {
10024           read_lexical_block_scope (die, cu);
10025           return;
10026         }
10027     }
10028
10029   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
10030
10031   name = dwarf2_name (die, cu);
10032
10033   /* Ignore functions with missing or empty names.  These are actually
10034      illegal according to the DWARF standard.  */
10035   if (name == NULL)
10036     {
10037       complaint (&symfile_complaints,
10038                  _("missing name for subprogram DIE at %d"),
10039                  die->offset.sect_off);
10040       return;
10041     }
10042
10043   /* Ignore functions with missing or invalid low and high pc attributes.  */
10044   if (!dwarf2_get_pc_bounds (die, &lowpc, &highpc, cu, NULL))
10045     {
10046       attr = dwarf2_attr (die, DW_AT_external, cu);
10047       if (!attr || !DW_UNSND (attr))
10048         complaint (&symfile_complaints,
10049                    _("cannot get low and high bounds "
10050                      "for subprogram DIE at %d"),
10051                    die->offset.sect_off);
10052       return;
10053     }
10054
10055   lowpc += baseaddr;
10056   highpc += baseaddr;
10057
10058   /* If we have any template arguments, then we must allocate a
10059      different sort of symbol.  */
10060   for (child_die = die->child; child_die; child_die = sibling_die (child_die))
10061     {
10062       if (child_die->tag == DW_TAG_template_type_param
10063           || child_die->tag == DW_TAG_template_value_param)
10064         {
10065           templ_func = allocate_template_symbol (objfile);
10066           templ_func->base.is_cplus_template_function = 1;
10067           break;
10068         }
10069     }
10070
10071   new = push_context (0, lowpc);
10072   new->name = new_symbol_full (die, read_type_die (die, cu), cu,
10073                                (struct symbol *) templ_func);
10074
10075   /* If there is a location expression for DW_AT_frame_base, record
10076      it.  */
10077   attr = dwarf2_attr (die, DW_AT_frame_base, cu);
10078   if (attr)
10079     dwarf2_symbol_mark_computed (attr, new->name, cu, 1);
10080
10081   cu->list_in_scope = &local_symbols;
10082
10083   if (die->child != NULL)
10084     {
10085       child_die = die->child;
10086       while (child_die && child_die->tag)
10087         {
10088           if (child_die->tag == DW_TAG_template_type_param
10089               || child_die->tag == DW_TAG_template_value_param)
10090             {
10091               struct symbol *arg = new_symbol (child_die, NULL, cu);
10092
10093               if (arg != NULL)
10094                 VEC_safe_push (symbolp, template_args, arg);
10095             }
10096           else
10097             process_die (child_die, cu);
10098           child_die = sibling_die (child_die);
10099         }
10100     }
10101
10102   inherit_abstract_dies (die, cu);
10103
10104   /* If we have a DW_AT_specification, we might need to import using
10105      directives from the context of the specification DIE.  See the
10106      comment in determine_prefix.  */
10107   if (cu->language == language_cplus
10108       && dwarf2_attr (die, DW_AT_specification, cu))
10109     {
10110       struct dwarf2_cu *spec_cu = cu;
10111       struct die_info *spec_die = die_specification (die, &spec_cu);
10112
10113       while (spec_die)
10114         {
10115           child_die = spec_die->child;
10116           while (child_die && child_die->tag)
10117             {
10118               if (child_die->tag == DW_TAG_imported_module)
10119                 process_die (child_die, spec_cu);
10120               child_die = sibling_die (child_die);
10121             }
10122
10123           /* In some cases, GCC generates specification DIEs that
10124              themselves contain DW_AT_specification attributes.  */
10125           spec_die = die_specification (spec_die, &spec_cu);
10126         }
10127     }
10128
10129   new = pop_context ();
10130   /* Make a block for the local symbols within.  */
10131   block = finish_block (new->name, &local_symbols, new->old_blocks,
10132                         lowpc, highpc, objfile);
10133
10134   /* For C++, set the block's scope.  */
10135   if ((cu->language == language_cplus || cu->language == language_fortran)
10136       && cu->processing_has_namespace_info)
10137     block_set_scope (block, determine_prefix (die, cu),
10138                      &objfile->objfile_obstack);
10139
10140   /* If we have address ranges, record them.  */
10141   dwarf2_record_block_ranges (die, block, baseaddr, cu);
10142
10143   /* Attach template arguments to function.  */
10144   if (! VEC_empty (symbolp, template_args))
10145     {
10146       gdb_assert (templ_func != NULL);
10147
10148       templ_func->n_template_arguments = VEC_length (symbolp, template_args);
10149       templ_func->template_arguments
10150         = obstack_alloc (&objfile->objfile_obstack,
10151                          (templ_func->n_template_arguments
10152                           * sizeof (struct symbol *)));
10153       memcpy (templ_func->template_arguments,
10154               VEC_address (symbolp, template_args),
10155               (templ_func->n_template_arguments * sizeof (struct symbol *)));
10156       VEC_free (symbolp, template_args);
10157     }
10158
10159   /* In C++, we can have functions nested inside functions (e.g., when
10160      a function declares a class that has methods).  This means that
10161      when we finish processing a function scope, we may need to go
10162      back to building a containing block's symbol lists.  */
10163   local_symbols = new->locals;
10164   using_directives = new->using_directives;
10165
10166   /* If we've finished processing a top-level function, subsequent
10167      symbols go in the file symbol list.  */
10168   if (outermost_context_p ())
10169     cu->list_in_scope = &file_symbols;
10170 }
10171
10172 /* Process all the DIES contained within a lexical block scope.  Start
10173    a new scope, process the dies, and then close the scope.  */
10174
10175 static void
10176 read_lexical_block_scope (struct die_info *die, struct dwarf2_cu *cu)
10177 {
10178   struct objfile *objfile = cu->objfile;
10179   struct context_stack *new;
10180   CORE_ADDR lowpc, highpc;
10181   struct die_info *child_die;
10182   CORE_ADDR baseaddr;
10183
10184   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
10185
10186   /* Ignore blocks with missing or invalid low and high pc attributes.  */
10187   /* ??? Perhaps consider discontiguous blocks defined by DW_AT_ranges
10188      as multiple lexical blocks?  Handling children in a sane way would
10189      be nasty.  Might be easier to properly extend generic blocks to
10190      describe ranges.  */
10191   if (!dwarf2_get_pc_bounds (die, &lowpc, &highpc, cu, NULL))
10192     return;
10193   lowpc += baseaddr;
10194   highpc += baseaddr;
10195
10196   push_context (0, lowpc);
10197   if (die->child != NULL)
10198     {
10199       child_die = die->child;
10200       while (child_die && child_die->tag)
10201         {
10202           process_die (child_die, cu);
10203           child_die = sibling_die (child_die);
10204         }
10205     }
10206   new = pop_context ();
10207
10208   if (local_symbols != NULL || using_directives != NULL)
10209     {
10210       struct block *block
10211         = finish_block (0, &local_symbols, new->old_blocks, new->start_addr,
10212                         highpc, objfile);
10213
10214       /* Note that recording ranges after traversing children, as we
10215          do here, means that recording a parent's ranges entails
10216          walking across all its children's ranges as they appear in
10217          the address map, which is quadratic behavior.
10218
10219          It would be nicer to record the parent's ranges before
10220          traversing its children, simply overriding whatever you find
10221          there.  But since we don't even decide whether to create a
10222          block until after we've traversed its children, that's hard
10223          to do.  */
10224       dwarf2_record_block_ranges (die, block, baseaddr, cu);
10225     }
10226   local_symbols = new->locals;
10227   using_directives = new->using_directives;
10228 }
10229
10230 /* Read in DW_TAG_GNU_call_site and insert it to CU->call_site_htab.  */
10231
10232 static void
10233 read_call_site_scope (struct die_info *die, struct dwarf2_cu *cu)
10234 {
10235   struct objfile *objfile = cu->objfile;
10236   struct gdbarch *gdbarch = get_objfile_arch (objfile);
10237   CORE_ADDR pc, baseaddr;
10238   struct attribute *attr;
10239   struct call_site *call_site, call_site_local;
10240   void **slot;
10241   int nparams;
10242   struct die_info *child_die;
10243
10244   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
10245
10246   attr = dwarf2_attr (die, DW_AT_low_pc, cu);
10247   if (!attr)
10248     {
10249       complaint (&symfile_complaints,
10250                  _("missing DW_AT_low_pc for DW_TAG_GNU_call_site "
10251                    "DIE 0x%x [in module %s]"),
10252                  die->offset.sect_off, objfile->name);
10253       return;
10254     }
10255   pc = DW_ADDR (attr) + baseaddr;
10256
10257   if (cu->call_site_htab == NULL)
10258     cu->call_site_htab = htab_create_alloc_ex (16, core_addr_hash, core_addr_eq,
10259                                                NULL, &objfile->objfile_obstack,
10260                                                hashtab_obstack_allocate, NULL);
10261   call_site_local.pc = pc;
10262   slot = htab_find_slot (cu->call_site_htab, &call_site_local, INSERT);
10263   if (*slot != NULL)
10264     {
10265       complaint (&symfile_complaints,
10266                  _("Duplicate PC %s for DW_TAG_GNU_call_site "
10267                    "DIE 0x%x [in module %s]"),
10268                  paddress (gdbarch, pc), die->offset.sect_off, objfile->name);
10269       return;
10270     }
10271
10272   /* Count parameters at the caller.  */
10273
10274   nparams = 0;
10275   for (child_die = die->child; child_die && child_die->tag;
10276        child_die = sibling_die (child_die))
10277     {
10278       if (child_die->tag != DW_TAG_GNU_call_site_parameter)
10279         {
10280           complaint (&symfile_complaints,
10281                      _("Tag %d is not DW_TAG_GNU_call_site_parameter in "
10282                        "DW_TAG_GNU_call_site child DIE 0x%x [in module %s]"),
10283                      child_die->tag, child_die->offset.sect_off, objfile->name);
10284           continue;
10285         }
10286
10287       nparams++;
10288     }
10289
10290   call_site = obstack_alloc (&objfile->objfile_obstack,
10291                              (sizeof (*call_site)
10292                               + (sizeof (*call_site->parameter)
10293                                  * (nparams - 1))));
10294   *slot = call_site;
10295   memset (call_site, 0, sizeof (*call_site) - sizeof (*call_site->parameter));
10296   call_site->pc = pc;
10297
10298   if (dwarf2_flag_true_p (die, DW_AT_GNU_tail_call, cu))
10299     {
10300       struct die_info *func_die;
10301
10302       /* Skip also over DW_TAG_inlined_subroutine.  */
10303       for (func_die = die->parent;
10304            func_die && func_die->tag != DW_TAG_subprogram
10305            && func_die->tag != DW_TAG_subroutine_type;
10306            func_die = func_die->parent);
10307
10308       /* DW_AT_GNU_all_call_sites is a superset
10309          of DW_AT_GNU_all_tail_call_sites.  */
10310       if (func_die
10311           && !dwarf2_flag_true_p (func_die, DW_AT_GNU_all_call_sites, cu)
10312           && !dwarf2_flag_true_p (func_die, DW_AT_GNU_all_tail_call_sites, cu))
10313         {
10314           /* TYPE_TAIL_CALL_LIST is not interesting in functions where it is
10315              not complete.  But keep CALL_SITE for look ups via call_site_htab,
10316              both the initial caller containing the real return address PC and
10317              the final callee containing the current PC of a chain of tail
10318              calls do not need to have the tail call list complete.  But any
10319              function candidate for a virtual tail call frame searched via
10320              TYPE_TAIL_CALL_LIST must have the tail call list complete to be
10321              determined unambiguously.  */
10322         }
10323       else
10324         {
10325           struct type *func_type = NULL;
10326
10327           if (func_die)
10328             func_type = get_die_type (func_die, cu);
10329           if (func_type != NULL)
10330             {
10331               gdb_assert (TYPE_CODE (func_type) == TYPE_CODE_FUNC);
10332
10333               /* Enlist this call site to the function.  */
10334               call_site->tail_call_next = TYPE_TAIL_CALL_LIST (func_type);
10335               TYPE_TAIL_CALL_LIST (func_type) = call_site;
10336             }
10337           else
10338             complaint (&symfile_complaints,
10339                        _("Cannot find function owning DW_TAG_GNU_call_site "
10340                          "DIE 0x%x [in module %s]"),
10341                        die->offset.sect_off, objfile->name);
10342         }
10343     }
10344
10345   attr = dwarf2_attr (die, DW_AT_GNU_call_site_target, cu);
10346   if (attr == NULL)
10347     attr = dwarf2_attr (die, DW_AT_abstract_origin, cu);
10348   SET_FIELD_DWARF_BLOCK (call_site->target, NULL);
10349   if (!attr || (attr_form_is_block (attr) && DW_BLOCK (attr)->size == 0))
10350     /* Keep NULL DWARF_BLOCK.  */;
10351   else if (attr_form_is_block (attr))
10352     {
10353       struct dwarf2_locexpr_baton *dlbaton;
10354
10355       dlbaton = obstack_alloc (&objfile->objfile_obstack, sizeof (*dlbaton));
10356       dlbaton->data = DW_BLOCK (attr)->data;
10357       dlbaton->size = DW_BLOCK (attr)->size;
10358       dlbaton->per_cu = cu->per_cu;
10359
10360       SET_FIELD_DWARF_BLOCK (call_site->target, dlbaton);
10361     }
10362   else if (is_ref_attr (attr))
10363     {
10364       struct dwarf2_cu *target_cu = cu;
10365       struct die_info *target_die;
10366
10367       target_die = follow_die_ref (die, attr, &target_cu);
10368       gdb_assert (target_cu->objfile == objfile);
10369       if (die_is_declaration (target_die, target_cu))
10370         {
10371           const char *target_physname = NULL;
10372           struct attribute *target_attr;
10373
10374           /* Prefer the mangled name; otherwise compute the demangled one.  */
10375           target_attr = dwarf2_attr (target_die, DW_AT_linkage_name, target_cu);
10376           if (target_attr == NULL)
10377             target_attr = dwarf2_attr (target_die, DW_AT_MIPS_linkage_name,
10378                                        target_cu);
10379           if (target_attr != NULL && DW_STRING (target_attr) != NULL)
10380             target_physname = DW_STRING (target_attr);
10381           else
10382             target_physname = dwarf2_physname (NULL, target_die, target_cu);
10383           if (target_physname == NULL)
10384             complaint (&symfile_complaints,
10385                        _("DW_AT_GNU_call_site_target target DIE has invalid "
10386                          "physname, for referencing DIE 0x%x [in module %s]"),
10387                        die->offset.sect_off, objfile->name);
10388           else
10389             SET_FIELD_PHYSNAME (call_site->target, target_physname);
10390         }
10391       else
10392         {
10393           CORE_ADDR lowpc;
10394
10395           /* DW_AT_entry_pc should be preferred.  */
10396           if (!dwarf2_get_pc_bounds (target_die, &lowpc, NULL, target_cu, NULL))
10397             complaint (&symfile_complaints,
10398                        _("DW_AT_GNU_call_site_target target DIE has invalid "
10399                          "low pc, for referencing DIE 0x%x [in module %s]"),
10400                        die->offset.sect_off, objfile->name);
10401           else
10402             SET_FIELD_PHYSADDR (call_site->target, lowpc + baseaddr);
10403         }
10404     }
10405   else
10406     complaint (&symfile_complaints,
10407                _("DW_TAG_GNU_call_site DW_AT_GNU_call_site_target is neither "
10408                  "block nor reference, for DIE 0x%x [in module %s]"),
10409                die->offset.sect_off, objfile->name);
10410
10411   call_site->per_cu = cu->per_cu;
10412
10413   for (child_die = die->child;
10414        child_die && child_die->tag;
10415        child_die = sibling_die (child_die))
10416     {
10417       struct call_site_parameter *parameter;
10418       struct attribute *loc, *origin;
10419
10420       if (child_die->tag != DW_TAG_GNU_call_site_parameter)
10421         {
10422           /* Already printed the complaint above.  */
10423           continue;
10424         }
10425
10426       gdb_assert (call_site->parameter_count < nparams);
10427       parameter = &call_site->parameter[call_site->parameter_count];
10428
10429       /* DW_AT_location specifies the register number or DW_AT_abstract_origin
10430          specifies DW_TAG_formal_parameter.  Value of the data assumed for the
10431          register is contained in DW_AT_GNU_call_site_value.  */
10432
10433       loc = dwarf2_attr (child_die, DW_AT_location, cu);
10434       origin = dwarf2_attr (child_die, DW_AT_abstract_origin, cu);
10435       if (loc == NULL && origin != NULL && is_ref_attr (origin))
10436         {
10437           sect_offset offset;
10438
10439           parameter->kind = CALL_SITE_PARAMETER_PARAM_OFFSET;
10440           offset = dwarf2_get_ref_die_offset (origin);
10441           if (!offset_in_cu_p (&cu->header, offset))
10442             {
10443               /* As DW_OP_GNU_parameter_ref uses CU-relative offset this
10444                  binding can be done only inside one CU.  Such referenced DIE
10445                  therefore cannot be even moved to DW_TAG_partial_unit.  */
10446               complaint (&symfile_complaints,
10447                          _("DW_AT_abstract_origin offset is not in CU for "
10448                            "DW_TAG_GNU_call_site child DIE 0x%x "
10449                            "[in module %s]"),
10450                          child_die->offset.sect_off, objfile->name);
10451               continue;
10452             }
10453           parameter->u.param_offset.cu_off = (offset.sect_off
10454                                               - cu->header.offset.sect_off);
10455         }
10456       else if (loc == NULL || origin != NULL || !attr_form_is_block (loc))
10457         {
10458           complaint (&symfile_complaints,
10459                      _("No DW_FORM_block* DW_AT_location for "
10460                        "DW_TAG_GNU_call_site child DIE 0x%x [in module %s]"),
10461                      child_die->offset.sect_off, objfile->name);
10462           continue;
10463         }
10464       else
10465         {
10466           parameter->u.dwarf_reg = dwarf_block_to_dwarf_reg
10467             (DW_BLOCK (loc)->data, &DW_BLOCK (loc)->data[DW_BLOCK (loc)->size]);
10468           if (parameter->u.dwarf_reg != -1)
10469             parameter->kind = CALL_SITE_PARAMETER_DWARF_REG;
10470           else if (dwarf_block_to_sp_offset (gdbarch, DW_BLOCK (loc)->data,
10471                                     &DW_BLOCK (loc)->data[DW_BLOCK (loc)->size],
10472                                              &parameter->u.fb_offset))
10473             parameter->kind = CALL_SITE_PARAMETER_FB_OFFSET;
10474           else
10475             {
10476               complaint (&symfile_complaints,
10477                          _("Only single DW_OP_reg or DW_OP_fbreg is supported "
10478                            "for DW_FORM_block* DW_AT_location is supported for "
10479                            "DW_TAG_GNU_call_site child DIE 0x%x "
10480                            "[in module %s]"),
10481                          child_die->offset.sect_off, objfile->name);
10482               continue;
10483             }
10484         }
10485
10486       attr = dwarf2_attr (child_die, DW_AT_GNU_call_site_value, cu);
10487       if (!attr_form_is_block (attr))
10488         {
10489           complaint (&symfile_complaints,
10490                      _("No DW_FORM_block* DW_AT_GNU_call_site_value for "
10491                        "DW_TAG_GNU_call_site child DIE 0x%x [in module %s]"),
10492                      child_die->offset.sect_off, objfile->name);
10493           continue;
10494         }
10495       parameter->value = DW_BLOCK (attr)->data;
10496       parameter->value_size = DW_BLOCK (attr)->size;
10497
10498       /* Parameters are not pre-cleared by memset above.  */
10499       parameter->data_value = NULL;
10500       parameter->data_value_size = 0;
10501       call_site->parameter_count++;
10502
10503       attr = dwarf2_attr (child_die, DW_AT_GNU_call_site_data_value, cu);
10504       if (attr)
10505         {
10506           if (!attr_form_is_block (attr))
10507             complaint (&symfile_complaints,
10508                        _("No DW_FORM_block* DW_AT_GNU_call_site_data_value for "
10509                          "DW_TAG_GNU_call_site child DIE 0x%x [in module %s]"),
10510                        child_die->offset.sect_off, objfile->name);
10511           else
10512             {
10513               parameter->data_value = DW_BLOCK (attr)->data;
10514               parameter->data_value_size = DW_BLOCK (attr)->size;
10515             }
10516         }
10517     }
10518 }
10519
10520 /* Get low and high pc attributes from DW_AT_ranges attribute value OFFSET.
10521    Return 1 if the attributes are present and valid, otherwise, return 0.
10522    If RANGES_PST is not NULL we should setup `objfile->psymtabs_addrmap'.  */
10523
10524 static int
10525 dwarf2_ranges_read (unsigned offset, CORE_ADDR *low_return,
10526                     CORE_ADDR *high_return, struct dwarf2_cu *cu,
10527                     struct partial_symtab *ranges_pst)
10528 {
10529   struct objfile *objfile = cu->objfile;
10530   struct comp_unit_head *cu_header = &cu->header;
10531   bfd *obfd = objfile->obfd;
10532   unsigned int addr_size = cu_header->addr_size;
10533   CORE_ADDR mask = ~(~(CORE_ADDR)1 << (addr_size * 8 - 1));
10534   /* Base address selection entry.  */
10535   CORE_ADDR base;
10536   int found_base;
10537   unsigned int dummy;
10538   const gdb_byte *buffer;
10539   CORE_ADDR marker;
10540   int low_set;
10541   CORE_ADDR low = 0;
10542   CORE_ADDR high = 0;
10543   CORE_ADDR baseaddr;
10544
10545   found_base = cu->base_known;
10546   base = cu->base_address;
10547
10548   dwarf2_read_section (objfile, &dwarf2_per_objfile->ranges);
10549   if (offset >= dwarf2_per_objfile->ranges.size)
10550     {
10551       complaint (&symfile_complaints,
10552                  _("Offset %d out of bounds for DW_AT_ranges attribute"),
10553                  offset);
10554       return 0;
10555     }
10556   buffer = dwarf2_per_objfile->ranges.buffer + offset;
10557
10558   /* Read in the largest possible address.  */
10559   marker = read_address (obfd, buffer, cu, &dummy);
10560   if ((marker & mask) == mask)
10561     {
10562       /* If we found the largest possible address, then
10563          read the base address.  */
10564       base = read_address (obfd, buffer + addr_size, cu, &dummy);
10565       buffer += 2 * addr_size;
10566       offset += 2 * addr_size;
10567       found_base = 1;
10568     }
10569
10570   low_set = 0;
10571
10572   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
10573
10574   while (1)
10575     {
10576       CORE_ADDR range_beginning, range_end;
10577
10578       range_beginning = read_address (obfd, buffer, cu, &dummy);
10579       buffer += addr_size;
10580       range_end = read_address (obfd, buffer, cu, &dummy);
10581       buffer += addr_size;
10582       offset += 2 * addr_size;
10583
10584       /* An end of list marker is a pair of zero addresses.  */
10585       if (range_beginning == 0 && range_end == 0)
10586         /* Found the end of list entry.  */
10587         break;
10588
10589       /* Each base address selection entry is a pair of 2 values.
10590          The first is the largest possible address, the second is
10591          the base address.  Check for a base address here.  */
10592       if ((range_beginning & mask) == mask)
10593         {
10594           /* If we found the largest possible address, then
10595              read the base address.  */
10596           base = read_address (obfd, buffer + addr_size, cu, &dummy);
10597           found_base = 1;
10598           continue;
10599         }
10600
10601       if (!found_base)
10602         {
10603           /* We have no valid base address for the ranges
10604              data.  */
10605           complaint (&symfile_complaints,
10606                      _("Invalid .debug_ranges data (no base address)"));
10607           return 0;
10608         }
10609
10610       if (range_beginning > range_end)
10611         {
10612           /* Inverted range entries are invalid.  */
10613           complaint (&symfile_complaints,
10614                      _("Invalid .debug_ranges data (inverted range)"));
10615           return 0;
10616         }
10617
10618       /* Empty range entries have no effect.  */
10619       if (range_beginning == range_end)
10620         continue;
10621
10622       range_beginning += base;
10623       range_end += base;
10624
10625       /* A not-uncommon case of bad debug info.
10626          Don't pollute the addrmap with bad data.  */
10627       if (range_beginning + baseaddr == 0
10628           && !dwarf2_per_objfile->has_section_at_zero)
10629         {
10630           complaint (&symfile_complaints,
10631                      _(".debug_ranges entry has start address of zero"
10632                        " [in module %s]"), objfile->name);
10633           continue;
10634         }
10635
10636       if (ranges_pst != NULL)
10637         addrmap_set_empty (objfile->psymtabs_addrmap,
10638                            range_beginning + baseaddr,
10639                            range_end - 1 + baseaddr,
10640                            ranges_pst);
10641
10642       /* FIXME: This is recording everything as a low-high
10643          segment of consecutive addresses.  We should have a
10644          data structure for discontiguous block ranges
10645          instead.  */
10646       if (! low_set)
10647         {
10648           low = range_beginning;
10649           high = range_end;
10650           low_set = 1;
10651         }
10652       else
10653         {
10654           if (range_beginning < low)
10655             low = range_beginning;
10656           if (range_end > high)
10657             high = range_end;
10658         }
10659     }
10660
10661   if (! low_set)
10662     /* If the first entry is an end-of-list marker, the range
10663        describes an empty scope, i.e. no instructions.  */
10664     return 0;
10665
10666   if (low_return)
10667     *low_return = low;
10668   if (high_return)
10669     *high_return = high;
10670   return 1;
10671 }
10672
10673 /* Get low and high pc attributes from a die.  Return 1 if the attributes
10674    are present and valid, otherwise, return 0.  Return -1 if the range is
10675    discontinuous, i.e. derived from DW_AT_ranges information.  */
10676
10677 static int
10678 dwarf2_get_pc_bounds (struct die_info *die, CORE_ADDR *lowpc,
10679                       CORE_ADDR *highpc, struct dwarf2_cu *cu,
10680                       struct partial_symtab *pst)
10681 {
10682   struct attribute *attr;
10683   struct attribute *attr_high;
10684   CORE_ADDR low = 0;
10685   CORE_ADDR high = 0;
10686   int ret = 0;
10687
10688   attr_high = dwarf2_attr (die, DW_AT_high_pc, cu);
10689   if (attr_high)
10690     {
10691       attr = dwarf2_attr (die, DW_AT_low_pc, cu);
10692       if (attr)
10693         {
10694           low = DW_ADDR (attr);
10695           if (attr_high->form == DW_FORM_addr
10696               || attr_high->form == DW_FORM_GNU_addr_index)
10697             high = DW_ADDR (attr_high);
10698           else
10699             high = low + DW_UNSND (attr_high);
10700         }
10701       else
10702         /* Found high w/o low attribute.  */
10703         return 0;
10704
10705       /* Found consecutive range of addresses.  */
10706       ret = 1;
10707     }
10708   else
10709     {
10710       attr = dwarf2_attr (die, DW_AT_ranges, cu);
10711       if (attr != NULL)
10712         {
10713           /* DW_AT_ranges_base does not apply to DIEs from the DWO skeleton.
10714              We take advantage of the fact that DW_AT_ranges does not appear
10715              in DW_TAG_compile_unit of DWO files.  */
10716           int need_ranges_base = die->tag != DW_TAG_compile_unit;
10717           unsigned int ranges_offset = (DW_UNSND (attr)
10718                                         + (need_ranges_base
10719                                            ? cu->ranges_base
10720                                            : 0));
10721
10722           /* Value of the DW_AT_ranges attribute is the offset in the
10723              .debug_ranges section.  */
10724           if (!dwarf2_ranges_read (ranges_offset, &low, &high, cu, pst))
10725             return 0;
10726           /* Found discontinuous range of addresses.  */
10727           ret = -1;
10728         }
10729     }
10730
10731   /* read_partial_die has also the strict LOW < HIGH requirement.  */
10732   if (high <= low)
10733     return 0;
10734
10735   /* When using the GNU linker, .gnu.linkonce. sections are used to
10736      eliminate duplicate copies of functions and vtables and such.
10737      The linker will arbitrarily choose one and discard the others.
10738      The AT_*_pc values for such functions refer to local labels in
10739      these sections.  If the section from that file was discarded, the
10740      labels are not in the output, so the relocs get a value of 0.
10741      If this is a discarded function, mark the pc bounds as invalid,
10742      so that GDB will ignore it.  */
10743   if (low == 0 && !dwarf2_per_objfile->has_section_at_zero)
10744     return 0;
10745
10746   *lowpc = low;
10747   if (highpc)
10748     *highpc = high;
10749   return ret;
10750 }
10751
10752 /* Assuming that DIE represents a subprogram DIE or a lexical block, get
10753    its low and high PC addresses.  Do nothing if these addresses could not
10754    be determined.  Otherwise, set LOWPC to the low address if it is smaller,
10755    and HIGHPC to the high address if greater than HIGHPC.  */
10756
10757 static void
10758 dwarf2_get_subprogram_pc_bounds (struct die_info *die,
10759                                  CORE_ADDR *lowpc, CORE_ADDR *highpc,
10760                                  struct dwarf2_cu *cu)
10761 {
10762   CORE_ADDR low, high;
10763   struct die_info *child = die->child;
10764
10765   if (dwarf2_get_pc_bounds (die, &low, &high, cu, NULL))
10766     {
10767       *lowpc = min (*lowpc, low);
10768       *highpc = max (*highpc, high);
10769     }
10770
10771   /* If the language does not allow nested subprograms (either inside
10772      subprograms or lexical blocks), we're done.  */
10773   if (cu->language != language_ada)
10774     return;
10775
10776   /* Check all the children of the given DIE.  If it contains nested
10777      subprograms, then check their pc bounds.  Likewise, we need to
10778      check lexical blocks as well, as they may also contain subprogram
10779      definitions.  */
10780   while (child && child->tag)
10781     {
10782       if (child->tag == DW_TAG_subprogram
10783           || child->tag == DW_TAG_lexical_block)
10784         dwarf2_get_subprogram_pc_bounds (child, lowpc, highpc, cu);
10785       child = sibling_die (child);
10786     }
10787 }
10788
10789 /* Get the low and high pc's represented by the scope DIE, and store
10790    them in *LOWPC and *HIGHPC.  If the correct values can't be
10791    determined, set *LOWPC to -1 and *HIGHPC to 0.  */
10792
10793 static void
10794 get_scope_pc_bounds (struct die_info *die,
10795                      CORE_ADDR *lowpc, CORE_ADDR *highpc,
10796                      struct dwarf2_cu *cu)
10797 {
10798   CORE_ADDR best_low = (CORE_ADDR) -1;
10799   CORE_ADDR best_high = (CORE_ADDR) 0;
10800   CORE_ADDR current_low, current_high;
10801
10802   if (dwarf2_get_pc_bounds (die, &current_low, &current_high, cu, NULL))
10803     {
10804       best_low = current_low;
10805       best_high = current_high;
10806     }
10807   else
10808     {
10809       struct die_info *child = die->child;
10810
10811       while (child && child->tag)
10812         {
10813           switch (child->tag) {
10814           case DW_TAG_subprogram:
10815             dwarf2_get_subprogram_pc_bounds (child, &best_low, &best_high, cu);
10816             break;
10817           case DW_TAG_namespace:
10818           case DW_TAG_module:
10819             /* FIXME: carlton/2004-01-16: Should we do this for
10820                DW_TAG_class_type/DW_TAG_structure_type, too?  I think
10821                that current GCC's always emit the DIEs corresponding
10822                to definitions of methods of classes as children of a
10823                DW_TAG_compile_unit or DW_TAG_namespace (as opposed to
10824                the DIEs giving the declarations, which could be
10825                anywhere).  But I don't see any reason why the
10826                standards says that they have to be there.  */
10827             get_scope_pc_bounds (child, &current_low, &current_high, cu);
10828
10829             if (current_low != ((CORE_ADDR) -1))
10830               {
10831                 best_low = min (best_low, current_low);
10832                 best_high = max (best_high, current_high);
10833               }
10834             break;
10835           default:
10836             /* Ignore.  */
10837             break;
10838           }
10839
10840           child = sibling_die (child);
10841         }
10842     }
10843
10844   *lowpc = best_low;
10845   *highpc = best_high;
10846 }
10847
10848 /* Record the address ranges for BLOCK, offset by BASEADDR, as given
10849    in DIE.  */
10850
10851 static void
10852 dwarf2_record_block_ranges (struct die_info *die, struct block *block,
10853                             CORE_ADDR baseaddr, struct dwarf2_cu *cu)
10854 {
10855   struct objfile *objfile = cu->objfile;
10856   struct attribute *attr;
10857   struct attribute *attr_high;
10858
10859   attr_high = dwarf2_attr (die, DW_AT_high_pc, cu);
10860   if (attr_high)
10861     {
10862       attr = dwarf2_attr (die, DW_AT_low_pc, cu);
10863       if (attr)
10864         {
10865           CORE_ADDR low = DW_ADDR (attr);
10866           CORE_ADDR high;
10867           if (attr_high->form == DW_FORM_addr
10868               || attr_high->form == DW_FORM_GNU_addr_index)
10869             high = DW_ADDR (attr_high);
10870           else
10871             high = low + DW_UNSND (attr_high);
10872
10873           record_block_range (block, baseaddr + low, baseaddr + high - 1);
10874         }
10875     }
10876
10877   attr = dwarf2_attr (die, DW_AT_ranges, cu);
10878   if (attr)
10879     {
10880       bfd *obfd = objfile->obfd;
10881       /* DW_AT_ranges_base does not apply to DIEs from the DWO skeleton.
10882          We take advantage of the fact that DW_AT_ranges does not appear
10883          in DW_TAG_compile_unit of DWO files.  */
10884       int need_ranges_base = die->tag != DW_TAG_compile_unit;
10885
10886       /* The value of the DW_AT_ranges attribute is the offset of the
10887          address range list in the .debug_ranges section.  */
10888       unsigned long offset = (DW_UNSND (attr)
10889                               + (need_ranges_base ? cu->ranges_base : 0));
10890       const gdb_byte *buffer;
10891
10892       /* For some target architectures, but not others, the
10893          read_address function sign-extends the addresses it returns.
10894          To recognize base address selection entries, we need a
10895          mask.  */
10896       unsigned int addr_size = cu->header.addr_size;
10897       CORE_ADDR base_select_mask = ~(~(CORE_ADDR)1 << (addr_size * 8 - 1));
10898
10899       /* The base address, to which the next pair is relative.  Note
10900          that this 'base' is a DWARF concept: most entries in a range
10901          list are relative, to reduce the number of relocs against the
10902          debugging information.  This is separate from this function's
10903          'baseaddr' argument, which GDB uses to relocate debugging
10904          information from a shared library based on the address at
10905          which the library was loaded.  */
10906       CORE_ADDR base = cu->base_address;
10907       int base_known = cu->base_known;
10908
10909       dwarf2_read_section (objfile, &dwarf2_per_objfile->ranges);
10910       if (offset >= dwarf2_per_objfile->ranges.size)
10911         {
10912           complaint (&symfile_complaints,
10913                      _("Offset %lu out of bounds for DW_AT_ranges attribute"),
10914                      offset);
10915           return;
10916         }
10917       buffer = dwarf2_per_objfile->ranges.buffer + offset;
10918
10919       for (;;)
10920         {
10921           unsigned int bytes_read;
10922           CORE_ADDR start, end;
10923
10924           start = read_address (obfd, buffer, cu, &bytes_read);
10925           buffer += bytes_read;
10926           end = read_address (obfd, buffer, cu, &bytes_read);
10927           buffer += bytes_read;
10928
10929           /* Did we find the end of the range list?  */
10930           if (start == 0 && end == 0)
10931             break;
10932
10933           /* Did we find a base address selection entry?  */
10934           else if ((start & base_select_mask) == base_select_mask)
10935             {
10936               base = end;
10937               base_known = 1;
10938             }
10939
10940           /* We found an ordinary address range.  */
10941           else
10942             {
10943               if (!base_known)
10944                 {
10945                   complaint (&symfile_complaints,
10946                              _("Invalid .debug_ranges data "
10947                                "(no base address)"));
10948                   return;
10949                 }
10950
10951               if (start > end)
10952                 {
10953                   /* Inverted range entries are invalid.  */
10954                   complaint (&symfile_complaints,
10955                              _("Invalid .debug_ranges data "
10956                                "(inverted range)"));
10957                   return;
10958                 }
10959
10960               /* Empty range entries have no effect.  */
10961               if (start == end)
10962                 continue;
10963
10964               start += base + baseaddr;
10965               end += base + baseaddr;
10966
10967               /* A not-uncommon case of bad debug info.
10968                  Don't pollute the addrmap with bad data.  */
10969               if (start == 0 && !dwarf2_per_objfile->has_section_at_zero)
10970                 {
10971                   complaint (&symfile_complaints,
10972                              _(".debug_ranges entry has start address of zero"
10973                                " [in module %s]"), objfile->name);
10974                   continue;
10975                 }
10976
10977               record_block_range (block, start, end - 1);
10978             }
10979         }
10980     }
10981 }
10982
10983 /* Check whether the producer field indicates either of GCC < 4.6, or the
10984    Intel C/C++ compiler, and cache the result in CU.  */
10985
10986 static void
10987 check_producer (struct dwarf2_cu *cu)
10988 {
10989   const char *cs;
10990   int major, minor, release;
10991
10992   if (cu->producer == NULL)
10993     {
10994       /* For unknown compilers expect their behavior is DWARF version
10995          compliant.
10996
10997          GCC started to support .debug_types sections by -gdwarf-4 since
10998          gcc-4.5.x.  As the .debug_types sections are missing DW_AT_producer
10999          for their space efficiency GDB cannot workaround gcc-4.5.x -gdwarf-4
11000          combination.  gcc-4.5.x -gdwarf-4 binaries have DW_AT_accessibility
11001          interpreted incorrectly by GDB now - GCC PR debug/48229.  */
11002     }
11003   else if (strncmp (cu->producer, "GNU ", strlen ("GNU ")) == 0)
11004     {
11005       /* Skip any identifier after "GNU " - such as "C++" or "Java".  */
11006
11007       cs = &cu->producer[strlen ("GNU ")];
11008       while (*cs && !isdigit (*cs))
11009         cs++;
11010       if (sscanf (cs, "%d.%d.%d", &major, &minor, &release) != 3)
11011         {
11012           /* Not recognized as GCC.  */
11013         }
11014       else
11015         {
11016           cu->producer_is_gxx_lt_4_6 = major < 4 || (major == 4 && minor < 6);
11017           cu->producer_is_gcc_lt_4_3 = major < 4 || (major == 4 && minor < 3);
11018         }
11019     }
11020   else if (strncmp (cu->producer, "Intel(R) C", strlen ("Intel(R) C")) == 0)
11021     cu->producer_is_icc = 1;
11022   else
11023     {
11024       /* For other non-GCC compilers, expect their behavior is DWARF version
11025          compliant.  */
11026     }
11027
11028   cu->checked_producer = 1;
11029 }
11030
11031 /* Check for GCC PR debug/45124 fix which is not present in any G++ version up
11032    to 4.5.any while it is present already in G++ 4.6.0 - the PR has been fixed
11033    during 4.6.0 experimental.  */
11034
11035 static int
11036 producer_is_gxx_lt_4_6 (struct dwarf2_cu *cu)
11037 {
11038   if (!cu->checked_producer)
11039     check_producer (cu);
11040
11041   return cu->producer_is_gxx_lt_4_6;
11042 }
11043
11044 /* Return the default accessibility type if it is not overriden by
11045    DW_AT_accessibility.  */
11046
11047 static enum dwarf_access_attribute
11048 dwarf2_default_access_attribute (struct die_info *die, struct dwarf2_cu *cu)
11049 {
11050   if (cu->header.version < 3 || producer_is_gxx_lt_4_6 (cu))
11051     {
11052       /* The default DWARF 2 accessibility for members is public, the default
11053          accessibility for inheritance is private.  */
11054
11055       if (die->tag != DW_TAG_inheritance)
11056         return DW_ACCESS_public;
11057       else
11058         return DW_ACCESS_private;
11059     }
11060   else
11061     {
11062       /* DWARF 3+ defines the default accessibility a different way.  The same
11063          rules apply now for DW_TAG_inheritance as for the members and it only
11064          depends on the container kind.  */
11065
11066       if (die->parent->tag == DW_TAG_class_type)
11067         return DW_ACCESS_private;
11068       else
11069         return DW_ACCESS_public;
11070     }
11071 }
11072
11073 /* Look for DW_AT_data_member_location.  Set *OFFSET to the byte
11074    offset.  If the attribute was not found return 0, otherwise return
11075    1.  If it was found but could not properly be handled, set *OFFSET
11076    to 0.  */
11077
11078 static int
11079 handle_data_member_location (struct die_info *die, struct dwarf2_cu *cu,
11080                              LONGEST *offset)
11081 {
11082   struct attribute *attr;
11083
11084   attr = dwarf2_attr (die, DW_AT_data_member_location, cu);
11085   if (attr != NULL)
11086     {
11087       *offset = 0;
11088
11089       /* Note that we do not check for a section offset first here.
11090          This is because DW_AT_data_member_location is new in DWARF 4,
11091          so if we see it, we can assume that a constant form is really
11092          a constant and not a section offset.  */
11093       if (attr_form_is_constant (attr))
11094         *offset = dwarf2_get_attr_constant_value (attr, 0);
11095       else if (attr_form_is_section_offset (attr))
11096         dwarf2_complex_location_expr_complaint ();
11097       else if (attr_form_is_block (attr))
11098         *offset = decode_locdesc (DW_BLOCK (attr), cu);
11099       else
11100         dwarf2_complex_location_expr_complaint ();
11101
11102       return 1;
11103     }
11104
11105   return 0;
11106 }
11107
11108 /* Add an aggregate field to the field list.  */
11109
11110 static void
11111 dwarf2_add_field (struct field_info *fip, struct die_info *die,
11112                   struct dwarf2_cu *cu)
11113 {
11114   struct objfile *objfile = cu->objfile;
11115   struct gdbarch *gdbarch = get_objfile_arch (objfile);
11116   struct nextfield *new_field;
11117   struct attribute *attr;
11118   struct field *fp;
11119   const char *fieldname = "";
11120
11121   /* Allocate a new field list entry and link it in.  */
11122   new_field = (struct nextfield *) xmalloc (sizeof (struct nextfield));
11123   make_cleanup (xfree, new_field);
11124   memset (new_field, 0, sizeof (struct nextfield));
11125
11126   if (die->tag == DW_TAG_inheritance)
11127     {
11128       new_field->next = fip->baseclasses;
11129       fip->baseclasses = new_field;
11130     }
11131   else
11132     {
11133       new_field->next = fip->fields;
11134       fip->fields = new_field;
11135     }
11136   fip->nfields++;
11137
11138   attr = dwarf2_attr (die, DW_AT_accessibility, cu);
11139   if (attr)
11140     new_field->accessibility = DW_UNSND (attr);
11141   else
11142     new_field->accessibility = dwarf2_default_access_attribute (die, cu);
11143   if (new_field->accessibility != DW_ACCESS_public)
11144     fip->non_public_fields = 1;
11145
11146   attr = dwarf2_attr (die, DW_AT_virtuality, cu);
11147   if (attr)
11148     new_field->virtuality = DW_UNSND (attr);
11149   else
11150     new_field->virtuality = DW_VIRTUALITY_none;
11151
11152   fp = &new_field->field;
11153
11154   if (die->tag == DW_TAG_member && ! die_is_declaration (die, cu))
11155     {
11156       LONGEST offset;
11157
11158       /* Data member other than a C++ static data member.  */
11159
11160       /* Get type of field.  */
11161       fp->type = die_type (die, cu);
11162
11163       SET_FIELD_BITPOS (*fp, 0);
11164
11165       /* Get bit size of field (zero if none).  */
11166       attr = dwarf2_attr (die, DW_AT_bit_size, cu);
11167       if (attr)
11168         {
11169           FIELD_BITSIZE (*fp) = DW_UNSND (attr);
11170         }
11171       else
11172         {
11173           FIELD_BITSIZE (*fp) = 0;
11174         }
11175
11176       /* Get bit offset of field.  */
11177       if (handle_data_member_location (die, cu, &offset))
11178         SET_FIELD_BITPOS (*fp, offset * bits_per_byte);
11179       attr = dwarf2_attr (die, DW_AT_bit_offset, cu);
11180       if (attr)
11181         {
11182           if (gdbarch_bits_big_endian (gdbarch))
11183             {
11184               /* For big endian bits, the DW_AT_bit_offset gives the
11185                  additional bit offset from the MSB of the containing
11186                  anonymous object to the MSB of the field.  We don't
11187                  have to do anything special since we don't need to
11188                  know the size of the anonymous object.  */
11189               SET_FIELD_BITPOS (*fp, FIELD_BITPOS (*fp) + DW_UNSND (attr));
11190             }
11191           else
11192             {
11193               /* For little endian bits, compute the bit offset to the
11194                  MSB of the anonymous object, subtract off the number of
11195                  bits from the MSB of the field to the MSB of the
11196                  object, and then subtract off the number of bits of
11197                  the field itself.  The result is the bit offset of
11198                  the LSB of the field.  */
11199               int anonymous_size;
11200               int bit_offset = DW_UNSND (attr);
11201
11202               attr = dwarf2_attr (die, DW_AT_byte_size, cu);
11203               if (attr)
11204                 {
11205                   /* The size of the anonymous object containing
11206                      the bit field is explicit, so use the
11207                      indicated size (in bytes).  */
11208                   anonymous_size = DW_UNSND (attr);
11209                 }
11210               else
11211                 {
11212                   /* The size of the anonymous object containing
11213                      the bit field must be inferred from the type
11214                      attribute of the data member containing the
11215                      bit field.  */
11216                   anonymous_size = TYPE_LENGTH (fp->type);
11217                 }
11218               SET_FIELD_BITPOS (*fp,
11219                                 (FIELD_BITPOS (*fp)
11220                                  + anonymous_size * bits_per_byte
11221                                  - bit_offset - FIELD_BITSIZE (*fp)));
11222             }
11223         }
11224
11225       /* Get name of field.  */
11226       fieldname = dwarf2_name (die, cu);
11227       if (fieldname == NULL)
11228         fieldname = "";
11229
11230       /* The name is already allocated along with this objfile, so we don't
11231          need to duplicate it for the type.  */
11232       fp->name = fieldname;
11233
11234       /* Change accessibility for artificial fields (e.g. virtual table
11235          pointer or virtual base class pointer) to private.  */
11236       if (dwarf2_attr (die, DW_AT_artificial, cu))
11237         {
11238           FIELD_ARTIFICIAL (*fp) = 1;
11239           new_field->accessibility = DW_ACCESS_private;
11240           fip->non_public_fields = 1;
11241         }
11242     }
11243   else if (die->tag == DW_TAG_member || die->tag == DW_TAG_variable)
11244     {
11245       /* C++ static member.  */
11246
11247       /* NOTE: carlton/2002-11-05: It should be a DW_TAG_member that
11248          is a declaration, but all versions of G++ as of this writing
11249          (so through at least 3.2.1) incorrectly generate
11250          DW_TAG_variable tags.  */
11251
11252       const char *physname;
11253
11254       /* Get name of field.  */
11255       fieldname = dwarf2_name (die, cu);
11256       if (fieldname == NULL)
11257         return;
11258
11259       attr = dwarf2_attr (die, DW_AT_const_value, cu);
11260       if (attr
11261           /* Only create a symbol if this is an external value.
11262              new_symbol checks this and puts the value in the global symbol
11263              table, which we want.  If it is not external, new_symbol
11264              will try to put the value in cu->list_in_scope which is wrong.  */
11265           && dwarf2_flag_true_p (die, DW_AT_external, cu))
11266         {
11267           /* A static const member, not much different than an enum as far as
11268              we're concerned, except that we can support more types.  */
11269           new_symbol (die, NULL, cu);
11270         }
11271
11272       /* Get physical name.  */
11273       physname = dwarf2_physname (fieldname, die, cu);
11274
11275       /* The name is already allocated along with this objfile, so we don't
11276          need to duplicate it for the type.  */
11277       SET_FIELD_PHYSNAME (*fp, physname ? physname : "");
11278       FIELD_TYPE (*fp) = die_type (die, cu);
11279       FIELD_NAME (*fp) = fieldname;
11280     }
11281   else if (die->tag == DW_TAG_inheritance)
11282     {
11283       LONGEST offset;
11284
11285       /* C++ base class field.  */
11286       if (handle_data_member_location (die, cu, &offset))
11287         SET_FIELD_BITPOS (*fp, offset * bits_per_byte);
11288       FIELD_BITSIZE (*fp) = 0;
11289       FIELD_TYPE (*fp) = die_type (die, cu);
11290       FIELD_NAME (*fp) = type_name_no_tag (fp->type);
11291       fip->nbaseclasses++;
11292     }
11293 }
11294
11295 /* Add a typedef defined in the scope of the FIP's class.  */
11296
11297 static void
11298 dwarf2_add_typedef (struct field_info *fip, struct die_info *die,
11299                     struct dwarf2_cu *cu)
11300 {
11301   struct objfile *objfile = cu->objfile;
11302   struct typedef_field_list *new_field;
11303   struct attribute *attr;
11304   struct typedef_field *fp;
11305   char *fieldname = "";
11306
11307   /* Allocate a new field list entry and link it in.  */
11308   new_field = xzalloc (sizeof (*new_field));
11309   make_cleanup (xfree, new_field);
11310
11311   gdb_assert (die->tag == DW_TAG_typedef);
11312
11313   fp = &new_field->field;
11314
11315   /* Get name of field.  */
11316   fp->name = dwarf2_name (die, cu);
11317   if (fp->name == NULL)
11318     return;
11319
11320   fp->type = read_type_die (die, cu);
11321
11322   new_field->next = fip->typedef_field_list;
11323   fip->typedef_field_list = new_field;
11324   fip->typedef_field_list_count++;
11325 }
11326
11327 /* Create the vector of fields, and attach it to the type.  */
11328
11329 static void
11330 dwarf2_attach_fields_to_type (struct field_info *fip, struct type *type,
11331                               struct dwarf2_cu *cu)
11332 {
11333   int nfields = fip->nfields;
11334
11335   /* Record the field count, allocate space for the array of fields,
11336      and create blank accessibility bitfields if necessary.  */
11337   TYPE_NFIELDS (type) = nfields;
11338   TYPE_FIELDS (type) = (struct field *)
11339     TYPE_ALLOC (type, sizeof (struct field) * nfields);
11340   memset (TYPE_FIELDS (type), 0, sizeof (struct field) * nfields);
11341
11342   if (fip->non_public_fields && cu->language != language_ada)
11343     {
11344       ALLOCATE_CPLUS_STRUCT_TYPE (type);
11345
11346       TYPE_FIELD_PRIVATE_BITS (type) =
11347         (B_TYPE *) TYPE_ALLOC (type, B_BYTES (nfields));
11348       B_CLRALL (TYPE_FIELD_PRIVATE_BITS (type), nfields);
11349
11350       TYPE_FIELD_PROTECTED_BITS (type) =
11351         (B_TYPE *) TYPE_ALLOC (type, B_BYTES (nfields));
11352       B_CLRALL (TYPE_FIELD_PROTECTED_BITS (type), nfields);
11353
11354       TYPE_FIELD_IGNORE_BITS (type) =
11355         (B_TYPE *) TYPE_ALLOC (type, B_BYTES (nfields));
11356       B_CLRALL (TYPE_FIELD_IGNORE_BITS (type), nfields);
11357     }
11358
11359   /* If the type has baseclasses, allocate and clear a bit vector for
11360      TYPE_FIELD_VIRTUAL_BITS.  */
11361   if (fip->nbaseclasses && cu->language != language_ada)
11362     {
11363       int num_bytes = B_BYTES (fip->nbaseclasses);
11364       unsigned char *pointer;
11365
11366       ALLOCATE_CPLUS_STRUCT_TYPE (type);
11367       pointer = TYPE_ALLOC (type, num_bytes);
11368       TYPE_FIELD_VIRTUAL_BITS (type) = pointer;
11369       B_CLRALL (TYPE_FIELD_VIRTUAL_BITS (type), fip->nbaseclasses);
11370       TYPE_N_BASECLASSES (type) = fip->nbaseclasses;
11371     }
11372
11373   /* Copy the saved-up fields into the field vector.  Start from the head of
11374      the list, adding to the tail of the field array, so that they end up in
11375      the same order in the array in which they were added to the list.  */
11376   while (nfields-- > 0)
11377     {
11378       struct nextfield *fieldp;
11379
11380       if (fip->fields)
11381         {
11382           fieldp = fip->fields;
11383           fip->fields = fieldp->next;
11384         }
11385       else
11386         {
11387           fieldp = fip->baseclasses;
11388           fip->baseclasses = fieldp->next;
11389         }
11390
11391       TYPE_FIELD (type, nfields) = fieldp->field;
11392       switch (fieldp->accessibility)
11393         {
11394         case DW_ACCESS_private:
11395           if (cu->language != language_ada)
11396             SET_TYPE_FIELD_PRIVATE (type, nfields);
11397           break;
11398
11399         case DW_ACCESS_protected:
11400           if (cu->language != language_ada)
11401             SET_TYPE_FIELD_PROTECTED (type, nfields);
11402           break;
11403
11404         case DW_ACCESS_public:
11405           break;
11406
11407         default:
11408           /* Unknown accessibility.  Complain and treat it as public.  */
11409           {
11410             complaint (&symfile_complaints, _("unsupported accessibility %d"),
11411                        fieldp->accessibility);
11412           }
11413           break;
11414         }
11415       if (nfields < fip->nbaseclasses)
11416         {
11417           switch (fieldp->virtuality)
11418             {
11419             case DW_VIRTUALITY_virtual:
11420             case DW_VIRTUALITY_pure_virtual:
11421               if (cu->language == language_ada)
11422                 error (_("unexpected virtuality in component of Ada type"));
11423               SET_TYPE_FIELD_VIRTUAL (type, nfields);
11424               break;
11425             }
11426         }
11427     }
11428 }
11429
11430 /* Return true if this member function is a constructor, false
11431    otherwise.  */
11432
11433 static int
11434 dwarf2_is_constructor (struct die_info *die, struct dwarf2_cu *cu)
11435 {
11436   const char *fieldname;
11437   const char *typename;
11438   int len;
11439
11440   if (die->parent == NULL)
11441     return 0;
11442
11443   if (die->parent->tag != DW_TAG_structure_type
11444       && die->parent->tag != DW_TAG_union_type
11445       && die->parent->tag != DW_TAG_class_type)
11446     return 0;
11447
11448   fieldname = dwarf2_name (die, cu);
11449   typename = dwarf2_name (die->parent, cu);
11450   if (fieldname == NULL || typename == NULL)
11451     return 0;
11452
11453   len = strlen (fieldname);
11454   return (strncmp (fieldname, typename, len) == 0
11455           && (typename[len] == '\0' || typename[len] == '<'));
11456 }
11457
11458 /* Add a member function to the proper fieldlist.  */
11459
11460 static void
11461 dwarf2_add_member_fn (struct field_info *fip, struct die_info *die,
11462                       struct type *type, struct dwarf2_cu *cu)
11463 {
11464   struct objfile *objfile = cu->objfile;
11465   struct attribute *attr;
11466   struct fnfieldlist *flp;
11467   int i;
11468   struct fn_field *fnp;
11469   const char *fieldname;
11470   struct nextfnfield *new_fnfield;
11471   struct type *this_type;
11472   enum dwarf_access_attribute accessibility;
11473
11474   if (cu->language == language_ada)
11475     error (_("unexpected member function in Ada type"));
11476
11477   /* Get name of member function.  */
11478   fieldname = dwarf2_name (die, cu);
11479   if (fieldname == NULL)
11480     return;
11481
11482   /* Look up member function name in fieldlist.  */
11483   for (i = 0; i < fip->nfnfields; i++)
11484     {
11485       if (strcmp (fip->fnfieldlists[i].name, fieldname) == 0)
11486         break;
11487     }
11488
11489   /* Create new list element if necessary.  */
11490   if (i < fip->nfnfields)
11491     flp = &fip->fnfieldlists[i];
11492   else
11493     {
11494       if ((fip->nfnfields % DW_FIELD_ALLOC_CHUNK) == 0)
11495         {
11496           fip->fnfieldlists = (struct fnfieldlist *)
11497             xrealloc (fip->fnfieldlists,
11498                       (fip->nfnfields + DW_FIELD_ALLOC_CHUNK)
11499                       * sizeof (struct fnfieldlist));
11500           if (fip->nfnfields == 0)
11501             make_cleanup (free_current_contents, &fip->fnfieldlists);
11502         }
11503       flp = &fip->fnfieldlists[fip->nfnfields];
11504       flp->name = fieldname;
11505       flp->length = 0;
11506       flp->head = NULL;
11507       i = fip->nfnfields++;
11508     }
11509
11510   /* Create a new member function field and chain it to the field list
11511      entry.  */
11512   new_fnfield = (struct nextfnfield *) xmalloc (sizeof (struct nextfnfield));
11513   make_cleanup (xfree, new_fnfield);
11514   memset (new_fnfield, 0, sizeof (struct nextfnfield));
11515   new_fnfield->next = flp->head;
11516   flp->head = new_fnfield;
11517   flp->length++;
11518
11519   /* Fill in the member function field info.  */
11520   fnp = &new_fnfield->fnfield;
11521
11522   /* Delay processing of the physname until later.  */
11523   if (cu->language == language_cplus || cu->language == language_java)
11524     {
11525       add_to_method_list (type, i, flp->length - 1, fieldname,
11526                           die, cu);
11527     }
11528   else
11529     {
11530       const char *physname = dwarf2_physname (fieldname, die, cu);
11531       fnp->physname = physname ? physname : "";
11532     }
11533
11534   fnp->type = alloc_type (objfile);
11535   this_type = read_type_die (die, cu);
11536   if (this_type && TYPE_CODE (this_type) == TYPE_CODE_FUNC)
11537     {
11538       int nparams = TYPE_NFIELDS (this_type);
11539
11540       /* TYPE is the domain of this method, and THIS_TYPE is the type
11541            of the method itself (TYPE_CODE_METHOD).  */
11542       smash_to_method_type (fnp->type, type,
11543                             TYPE_TARGET_TYPE (this_type),
11544                             TYPE_FIELDS (this_type),
11545                             TYPE_NFIELDS (this_type),
11546                             TYPE_VARARGS (this_type));
11547
11548       /* Handle static member functions.
11549          Dwarf2 has no clean way to discern C++ static and non-static
11550          member functions.  G++ helps GDB by marking the first
11551          parameter for non-static member functions (which is the this
11552          pointer) as artificial.  We obtain this information from
11553          read_subroutine_type via TYPE_FIELD_ARTIFICIAL.  */
11554       if (nparams == 0 || TYPE_FIELD_ARTIFICIAL (this_type, 0) == 0)
11555         fnp->voffset = VOFFSET_STATIC;
11556     }
11557   else
11558     complaint (&symfile_complaints, _("member function type missing for '%s'"),
11559                dwarf2_full_name (fieldname, die, cu));
11560
11561   /* Get fcontext from DW_AT_containing_type if present.  */
11562   if (dwarf2_attr (die, DW_AT_containing_type, cu) != NULL)
11563     fnp->fcontext = die_containing_type (die, cu);
11564
11565   /* dwarf2 doesn't have stubbed physical names, so the setting of is_const and
11566      is_volatile is irrelevant, as it is needed by gdb_mangle_name only.  */
11567
11568   /* Get accessibility.  */
11569   attr = dwarf2_attr (die, DW_AT_accessibility, cu);
11570   if (attr)
11571     accessibility = DW_UNSND (attr);
11572   else
11573     accessibility = dwarf2_default_access_attribute (die, cu);
11574   switch (accessibility)
11575     {
11576     case DW_ACCESS_private:
11577       fnp->is_private = 1;
11578       break;
11579     case DW_ACCESS_protected:
11580       fnp->is_protected = 1;
11581       break;
11582     }
11583
11584   /* Check for artificial methods.  */
11585   attr = dwarf2_attr (die, DW_AT_artificial, cu);
11586   if (attr && DW_UNSND (attr) != 0)
11587     fnp->is_artificial = 1;
11588
11589   fnp->is_constructor = dwarf2_is_constructor (die, cu);
11590
11591   /* Get index in virtual function table if it is a virtual member
11592      function.  For older versions of GCC, this is an offset in the
11593      appropriate virtual table, as specified by DW_AT_containing_type.
11594      For everyone else, it is an expression to be evaluated relative
11595      to the object address.  */
11596
11597   attr = dwarf2_attr (die, DW_AT_vtable_elem_location, cu);
11598   if (attr)
11599     {
11600       if (attr_form_is_block (attr) && DW_BLOCK (attr)->size > 0)
11601         {
11602           if (DW_BLOCK (attr)->data[0] == DW_OP_constu)
11603             {
11604               /* Old-style GCC.  */
11605               fnp->voffset = decode_locdesc (DW_BLOCK (attr), cu) + 2;
11606             }
11607           else if (DW_BLOCK (attr)->data[0] == DW_OP_deref
11608                    || (DW_BLOCK (attr)->size > 1
11609                        && DW_BLOCK (attr)->data[0] == DW_OP_deref_size
11610                        && DW_BLOCK (attr)->data[1] == cu->header.addr_size))
11611             {
11612               struct dwarf_block blk;
11613               int offset;
11614
11615               offset = (DW_BLOCK (attr)->data[0] == DW_OP_deref
11616                         ? 1 : 2);
11617               blk.size = DW_BLOCK (attr)->size - offset;
11618               blk.data = DW_BLOCK (attr)->data + offset;
11619               fnp->voffset = decode_locdesc (DW_BLOCK (attr), cu);
11620               if ((fnp->voffset % cu->header.addr_size) != 0)
11621                 dwarf2_complex_location_expr_complaint ();
11622               else
11623                 fnp->voffset /= cu->header.addr_size;
11624               fnp->voffset += 2;
11625             }
11626           else
11627             dwarf2_complex_location_expr_complaint ();
11628
11629           if (!fnp->fcontext)
11630             fnp->fcontext = TYPE_TARGET_TYPE (TYPE_FIELD_TYPE (this_type, 0));
11631         }
11632       else if (attr_form_is_section_offset (attr))
11633         {
11634           dwarf2_complex_location_expr_complaint ();
11635         }
11636       else
11637         {
11638           dwarf2_invalid_attrib_class_complaint ("DW_AT_vtable_elem_location",
11639                                                  fieldname);
11640         }
11641     }
11642   else
11643     {
11644       attr = dwarf2_attr (die, DW_AT_virtuality, cu);
11645       if (attr && DW_UNSND (attr))
11646         {
11647           /* GCC does this, as of 2008-08-25; PR debug/37237.  */
11648           complaint (&symfile_complaints,
11649                      _("Member function \"%s\" (offset %d) is virtual "
11650                        "but the vtable offset is not specified"),
11651                      fieldname, die->offset.sect_off);
11652           ALLOCATE_CPLUS_STRUCT_TYPE (type);
11653           TYPE_CPLUS_DYNAMIC (type) = 1;
11654         }
11655     }
11656 }
11657
11658 /* Create the vector of member function fields, and attach it to the type.  */
11659
11660 static void
11661 dwarf2_attach_fn_fields_to_type (struct field_info *fip, struct type *type,
11662                                  struct dwarf2_cu *cu)
11663 {
11664   struct fnfieldlist *flp;
11665   int i;
11666
11667   if (cu->language == language_ada)
11668     error (_("unexpected member functions in Ada type"));
11669
11670   ALLOCATE_CPLUS_STRUCT_TYPE (type);
11671   TYPE_FN_FIELDLISTS (type) = (struct fn_fieldlist *)
11672     TYPE_ALLOC (type, sizeof (struct fn_fieldlist) * fip->nfnfields);
11673
11674   for (i = 0, flp = fip->fnfieldlists; i < fip->nfnfields; i++, flp++)
11675     {
11676       struct nextfnfield *nfp = flp->head;
11677       struct fn_fieldlist *fn_flp = &TYPE_FN_FIELDLIST (type, i);
11678       int k;
11679
11680       TYPE_FN_FIELDLIST_NAME (type, i) = flp->name;
11681       TYPE_FN_FIELDLIST_LENGTH (type, i) = flp->length;
11682       fn_flp->fn_fields = (struct fn_field *)
11683         TYPE_ALLOC (type, sizeof (struct fn_field) * flp->length);
11684       for (k = flp->length; (k--, nfp); nfp = nfp->next)
11685         fn_flp->fn_fields[k] = nfp->fnfield;
11686     }
11687
11688   TYPE_NFN_FIELDS (type) = fip->nfnfields;
11689 }
11690
11691 /* Returns non-zero if NAME is the name of a vtable member in CU's
11692    language, zero otherwise.  */
11693 static int
11694 is_vtable_name (const char *name, struct dwarf2_cu *cu)
11695 {
11696   static const char vptr[] = "_vptr";
11697   static const char vtable[] = "vtable";
11698
11699   /* Look for the C++ and Java forms of the vtable.  */
11700   if ((cu->language == language_java
11701        && strncmp (name, vtable, sizeof (vtable) - 1) == 0)
11702        || (strncmp (name, vptr, sizeof (vptr) - 1) == 0
11703        && is_cplus_marker (name[sizeof (vptr) - 1])))
11704     return 1;
11705
11706   return 0;
11707 }
11708
11709 /* GCC outputs unnamed structures that are really pointers to member
11710    functions, with the ABI-specified layout.  If TYPE describes
11711    such a structure, smash it into a member function type.
11712
11713    GCC shouldn't do this; it should just output pointer to member DIEs.
11714    This is GCC PR debug/28767.  */
11715
11716 static void
11717 quirk_gcc_member_function_pointer (struct type *type, struct objfile *objfile)
11718 {
11719   struct type *pfn_type, *domain_type, *new_type;
11720
11721   /* Check for a structure with no name and two children.  */
11722   if (TYPE_CODE (type) != TYPE_CODE_STRUCT || TYPE_NFIELDS (type) != 2)
11723     return;
11724
11725   /* Check for __pfn and __delta members.  */
11726   if (TYPE_FIELD_NAME (type, 0) == NULL
11727       || strcmp (TYPE_FIELD_NAME (type, 0), "__pfn") != 0
11728       || TYPE_FIELD_NAME (type, 1) == NULL
11729       || strcmp (TYPE_FIELD_NAME (type, 1), "__delta") != 0)
11730     return;
11731
11732   /* Find the type of the method.  */
11733   pfn_type = TYPE_FIELD_TYPE (type, 0);
11734   if (pfn_type == NULL
11735       || TYPE_CODE (pfn_type) != TYPE_CODE_PTR
11736       || TYPE_CODE (TYPE_TARGET_TYPE (pfn_type)) != TYPE_CODE_FUNC)
11737     return;
11738
11739   /* Look for the "this" argument.  */
11740   pfn_type = TYPE_TARGET_TYPE (pfn_type);
11741   if (TYPE_NFIELDS (pfn_type) == 0
11742       /* || TYPE_FIELD_TYPE (pfn_type, 0) == NULL */
11743       || TYPE_CODE (TYPE_FIELD_TYPE (pfn_type, 0)) != TYPE_CODE_PTR)
11744     return;
11745
11746   domain_type = TYPE_TARGET_TYPE (TYPE_FIELD_TYPE (pfn_type, 0));
11747   new_type = alloc_type (objfile);
11748   smash_to_method_type (new_type, domain_type, TYPE_TARGET_TYPE (pfn_type),
11749                         TYPE_FIELDS (pfn_type), TYPE_NFIELDS (pfn_type),
11750                         TYPE_VARARGS (pfn_type));
11751   smash_to_methodptr_type (type, new_type);
11752 }
11753
11754 /* Return non-zero if the CU's PRODUCER string matches the Intel C/C++ compiler
11755    (icc).  */
11756
11757 static int
11758 producer_is_icc (struct dwarf2_cu *cu)
11759 {
11760   if (!cu->checked_producer)
11761     check_producer (cu);
11762
11763   return cu->producer_is_icc;
11764 }
11765
11766 /* Called when we find the DIE that starts a structure or union scope
11767    (definition) to create a type for the structure or union.  Fill in
11768    the type's name and general properties; the members will not be
11769    processed until process_structure_scope.
11770
11771    NOTE: we need to call these functions regardless of whether or not the
11772    DIE has a DW_AT_name attribute, since it might be an anonymous
11773    structure or union.  This gets the type entered into our set of
11774    user defined types.
11775
11776    However, if the structure is incomplete (an opaque struct/union)
11777    then suppress creating a symbol table entry for it since gdb only
11778    wants to find the one with the complete definition.  Note that if
11779    it is complete, we just call new_symbol, which does it's own
11780    checking about whether the struct/union is anonymous or not (and
11781    suppresses creating a symbol table entry itself).  */
11782
11783 static struct type *
11784 read_structure_type (struct die_info *die, struct dwarf2_cu *cu)
11785 {
11786   struct objfile *objfile = cu->objfile;
11787   struct type *type;
11788   struct attribute *attr;
11789   const char *name;
11790
11791   /* If the definition of this type lives in .debug_types, read that type.
11792      Don't follow DW_AT_specification though, that will take us back up
11793      the chain and we want to go down.  */
11794   attr = dwarf2_attr_no_follow (die, DW_AT_signature);
11795   if (attr)
11796     {
11797       type = get_DW_AT_signature_type (die, attr, cu);
11798
11799       /* The type's CU may not be the same as CU.
11800          Ensure TYPE is recorded with CU in die_type_hash.  */
11801       return set_die_type (die, type, cu);
11802     }
11803
11804   type = alloc_type (objfile);
11805   INIT_CPLUS_SPECIFIC (type);
11806
11807   name = dwarf2_name (die, cu);
11808   if (name != NULL)
11809     {
11810       if (cu->language == language_cplus
11811           || cu->language == language_java)
11812         {
11813           const char *full_name = dwarf2_full_name (name, die, cu);
11814
11815           /* dwarf2_full_name might have already finished building the DIE's
11816              type.  If so, there is no need to continue.  */
11817           if (get_die_type (die, cu) != NULL)
11818             return get_die_type (die, cu);
11819
11820           TYPE_TAG_NAME (type) = full_name;
11821           if (die->tag == DW_TAG_structure_type
11822               || die->tag == DW_TAG_class_type)
11823             TYPE_NAME (type) = TYPE_TAG_NAME (type);
11824         }
11825       else
11826         {
11827           /* The name is already allocated along with this objfile, so
11828              we don't need to duplicate it for the type.  */
11829           TYPE_TAG_NAME (type) = name;
11830           if (die->tag == DW_TAG_class_type)
11831             TYPE_NAME (type) = TYPE_TAG_NAME (type);
11832         }
11833     }
11834
11835   if (die->tag == DW_TAG_structure_type)
11836     {
11837       TYPE_CODE (type) = TYPE_CODE_STRUCT;
11838     }
11839   else if (die->tag == DW_TAG_union_type)
11840     {
11841       TYPE_CODE (type) = TYPE_CODE_UNION;
11842     }
11843   else
11844     {
11845       TYPE_CODE (type) = TYPE_CODE_CLASS;
11846     }
11847
11848   if (cu->language == language_cplus && die->tag == DW_TAG_class_type)
11849     TYPE_DECLARED_CLASS (type) = 1;
11850
11851   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
11852   if (attr)
11853     {
11854       TYPE_LENGTH (type) = DW_UNSND (attr);
11855     }
11856   else
11857     {
11858       TYPE_LENGTH (type) = 0;
11859     }
11860
11861   if (producer_is_icc (cu))
11862     {
11863       /* ICC does not output the required DW_AT_declaration
11864          on incomplete types, but gives them a size of zero.  */
11865     }
11866   else
11867     TYPE_STUB_SUPPORTED (type) = 1;
11868
11869   if (die_is_declaration (die, cu))
11870     TYPE_STUB (type) = 1;
11871   else if (attr == NULL && die->child == NULL
11872            && producer_is_realview (cu->producer))
11873     /* RealView does not output the required DW_AT_declaration
11874        on incomplete types.  */
11875     TYPE_STUB (type) = 1;
11876
11877   /* We need to add the type field to the die immediately so we don't
11878      infinitely recurse when dealing with pointers to the structure
11879      type within the structure itself.  */
11880   set_die_type (die, type, cu);
11881
11882   /* set_die_type should be already done.  */
11883   set_descriptive_type (type, die, cu);
11884
11885   return type;
11886 }
11887
11888 /* Finish creating a structure or union type, including filling in
11889    its members and creating a symbol for it.  */
11890
11891 static void
11892 process_structure_scope (struct die_info *die, struct dwarf2_cu *cu)
11893 {
11894   struct objfile *objfile = cu->objfile;
11895   struct die_info *child_die = die->child;
11896   struct type *type;
11897
11898   type = get_die_type (die, cu);
11899   if (type == NULL)
11900     type = read_structure_type (die, cu);
11901
11902   if (die->child != NULL && ! die_is_declaration (die, cu))
11903     {
11904       struct field_info fi;
11905       struct die_info *child_die;
11906       VEC (symbolp) *template_args = NULL;
11907       struct cleanup *back_to = make_cleanup (null_cleanup, 0);
11908
11909       memset (&fi, 0, sizeof (struct field_info));
11910
11911       child_die = die->child;
11912
11913       while (child_die && child_die->tag)
11914         {
11915           if (child_die->tag == DW_TAG_member
11916               || child_die->tag == DW_TAG_variable)
11917             {
11918               /* NOTE: carlton/2002-11-05: A C++ static data member
11919                  should be a DW_TAG_member that is a declaration, but
11920                  all versions of G++ as of this writing (so through at
11921                  least 3.2.1) incorrectly generate DW_TAG_variable
11922                  tags for them instead.  */
11923               dwarf2_add_field (&fi, child_die, cu);
11924             }
11925           else if (child_die->tag == DW_TAG_subprogram)
11926             {
11927               /* C++ member function.  */
11928               dwarf2_add_member_fn (&fi, child_die, type, cu);
11929             }
11930           else if (child_die->tag == DW_TAG_inheritance)
11931             {
11932               /* C++ base class field.  */
11933               dwarf2_add_field (&fi, child_die, cu);
11934             }
11935           else if (child_die->tag == DW_TAG_typedef)
11936             dwarf2_add_typedef (&fi, child_die, cu);
11937           else if (child_die->tag == DW_TAG_template_type_param
11938                    || child_die->tag == DW_TAG_template_value_param)
11939             {
11940               struct symbol *arg = new_symbol (child_die, NULL, cu);
11941
11942               if (arg != NULL)
11943                 VEC_safe_push (symbolp, template_args, arg);
11944             }
11945
11946           child_die = sibling_die (child_die);
11947         }
11948
11949       /* Attach template arguments to type.  */
11950       if (! VEC_empty (symbolp, template_args))
11951         {
11952           ALLOCATE_CPLUS_STRUCT_TYPE (type);
11953           TYPE_N_TEMPLATE_ARGUMENTS (type)
11954             = VEC_length (symbolp, template_args);
11955           TYPE_TEMPLATE_ARGUMENTS (type)
11956             = obstack_alloc (&objfile->objfile_obstack,
11957                              (TYPE_N_TEMPLATE_ARGUMENTS (type)
11958                               * sizeof (struct symbol *)));
11959           memcpy (TYPE_TEMPLATE_ARGUMENTS (type),
11960                   VEC_address (symbolp, template_args),
11961                   (TYPE_N_TEMPLATE_ARGUMENTS (type)
11962                    * sizeof (struct symbol *)));
11963           VEC_free (symbolp, template_args);
11964         }
11965
11966       /* Attach fields and member functions to the type.  */
11967       if (fi.nfields)
11968         dwarf2_attach_fields_to_type (&fi, type, cu);
11969       if (fi.nfnfields)
11970         {
11971           dwarf2_attach_fn_fields_to_type (&fi, type, cu);
11972
11973           /* Get the type which refers to the base class (possibly this
11974              class itself) which contains the vtable pointer for the current
11975              class from the DW_AT_containing_type attribute.  This use of
11976              DW_AT_containing_type is a GNU extension.  */
11977
11978           if (dwarf2_attr (die, DW_AT_containing_type, cu) != NULL)
11979             {
11980               struct type *t = die_containing_type (die, cu);
11981
11982               TYPE_VPTR_BASETYPE (type) = t;
11983               if (type == t)
11984                 {
11985                   int i;
11986
11987                   /* Our own class provides vtbl ptr.  */
11988                   for (i = TYPE_NFIELDS (t) - 1;
11989                        i >= TYPE_N_BASECLASSES (t);
11990                        --i)
11991                     {
11992                       const char *fieldname = TYPE_FIELD_NAME (t, i);
11993
11994                       if (is_vtable_name (fieldname, cu))
11995                         {
11996                           TYPE_VPTR_FIELDNO (type) = i;
11997                           break;
11998                         }
11999                     }
12000
12001                   /* Complain if virtual function table field not found.  */
12002                   if (i < TYPE_N_BASECLASSES (t))
12003                     complaint (&symfile_complaints,
12004                                _("virtual function table pointer "
12005                                  "not found when defining class '%s'"),
12006                                TYPE_TAG_NAME (type) ? TYPE_TAG_NAME (type) :
12007                                "");
12008                 }
12009               else
12010                 {
12011                   TYPE_VPTR_FIELDNO (type) = TYPE_VPTR_FIELDNO (t);
12012                 }
12013             }
12014           else if (cu->producer
12015                    && strncmp (cu->producer,
12016                                "IBM(R) XL C/C++ Advanced Edition", 32) == 0)
12017             {
12018               /* The IBM XLC compiler does not provide direct indication
12019                  of the containing type, but the vtable pointer is
12020                  always named __vfp.  */
12021
12022               int i;
12023
12024               for (i = TYPE_NFIELDS (type) - 1;
12025                    i >= TYPE_N_BASECLASSES (type);
12026                    --i)
12027                 {
12028                   if (strcmp (TYPE_FIELD_NAME (type, i), "__vfp") == 0)
12029                     {
12030                       TYPE_VPTR_FIELDNO (type) = i;
12031                       TYPE_VPTR_BASETYPE (type) = type;
12032                       break;
12033                     }
12034                 }
12035             }
12036         }
12037
12038       /* Copy fi.typedef_field_list linked list elements content into the
12039          allocated array TYPE_TYPEDEF_FIELD_ARRAY (type).  */
12040       if (fi.typedef_field_list)
12041         {
12042           int i = fi.typedef_field_list_count;
12043
12044           ALLOCATE_CPLUS_STRUCT_TYPE (type);
12045           TYPE_TYPEDEF_FIELD_ARRAY (type)
12046             = TYPE_ALLOC (type, sizeof (TYPE_TYPEDEF_FIELD (type, 0)) * i);
12047           TYPE_TYPEDEF_FIELD_COUNT (type) = i;
12048
12049           /* Reverse the list order to keep the debug info elements order.  */
12050           while (--i >= 0)
12051             {
12052               struct typedef_field *dest, *src;
12053
12054               dest = &TYPE_TYPEDEF_FIELD (type, i);
12055               src = &fi.typedef_field_list->field;
12056               fi.typedef_field_list = fi.typedef_field_list->next;
12057               *dest = *src;
12058             }
12059         }
12060
12061       do_cleanups (back_to);
12062
12063       if (HAVE_CPLUS_STRUCT (type))
12064         TYPE_CPLUS_REALLY_JAVA (type) = cu->language == language_java;
12065     }
12066
12067   quirk_gcc_member_function_pointer (type, objfile);
12068
12069   /* NOTE: carlton/2004-03-16: GCC 3.4 (or at least one of its
12070      snapshots) has been known to create a die giving a declaration
12071      for a class that has, as a child, a die giving a definition for a
12072      nested class.  So we have to process our children even if the
12073      current die is a declaration.  Normally, of course, a declaration
12074      won't have any children at all.  */
12075
12076   while (child_die != NULL && child_die->tag)
12077     {
12078       if (child_die->tag == DW_TAG_member
12079           || child_die->tag == DW_TAG_variable
12080           || child_die->tag == DW_TAG_inheritance
12081           || child_die->tag == DW_TAG_template_value_param
12082           || child_die->tag == DW_TAG_template_type_param)
12083         {
12084           /* Do nothing.  */
12085         }
12086       else
12087         process_die (child_die, cu);
12088
12089       child_die = sibling_die (child_die);
12090     }
12091
12092   /* Do not consider external references.  According to the DWARF standard,
12093      these DIEs are identified by the fact that they have no byte_size
12094      attribute, and a declaration attribute.  */
12095   if (dwarf2_attr (die, DW_AT_byte_size, cu) != NULL
12096       || !die_is_declaration (die, cu))
12097     new_symbol (die, type, cu);
12098 }
12099
12100 /* Given a DW_AT_enumeration_type die, set its type.  We do not
12101    complete the type's fields yet, or create any symbols.  */
12102
12103 static struct type *
12104 read_enumeration_type (struct die_info *die, struct dwarf2_cu *cu)
12105 {
12106   struct objfile *objfile = cu->objfile;
12107   struct type *type;
12108   struct attribute *attr;
12109   const char *name;
12110
12111   /* If the definition of this type lives in .debug_types, read that type.
12112      Don't follow DW_AT_specification though, that will take us back up
12113      the chain and we want to go down.  */
12114   attr = dwarf2_attr_no_follow (die, DW_AT_signature);
12115   if (attr)
12116     {
12117       type = get_DW_AT_signature_type (die, attr, cu);
12118
12119       /* The type's CU may not be the same as CU.
12120          Ensure TYPE is recorded with CU in die_type_hash.  */
12121       return set_die_type (die, type, cu);
12122     }
12123
12124   type = alloc_type (objfile);
12125
12126   TYPE_CODE (type) = TYPE_CODE_ENUM;
12127   name = dwarf2_full_name (NULL, die, cu);
12128   if (name != NULL)
12129     TYPE_TAG_NAME (type) = name;
12130
12131   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
12132   if (attr)
12133     {
12134       TYPE_LENGTH (type) = DW_UNSND (attr);
12135     }
12136   else
12137     {
12138       TYPE_LENGTH (type) = 0;
12139     }
12140
12141   /* The enumeration DIE can be incomplete.  In Ada, any type can be
12142      declared as private in the package spec, and then defined only
12143      inside the package body.  Such types are known as Taft Amendment
12144      Types.  When another package uses such a type, an incomplete DIE
12145      may be generated by the compiler.  */
12146   if (die_is_declaration (die, cu))
12147     TYPE_STUB (type) = 1;
12148
12149   return set_die_type (die, type, cu);
12150 }
12151
12152 /* Given a pointer to a die which begins an enumeration, process all
12153    the dies that define the members of the enumeration, and create the
12154    symbol for the enumeration type.
12155
12156    NOTE: We reverse the order of the element list.  */
12157
12158 static void
12159 process_enumeration_scope (struct die_info *die, struct dwarf2_cu *cu)
12160 {
12161   struct type *this_type;
12162
12163   this_type = get_die_type (die, cu);
12164   if (this_type == NULL)
12165     this_type = read_enumeration_type (die, cu);
12166
12167   if (die->child != NULL)
12168     {
12169       struct die_info *child_die;
12170       struct symbol *sym;
12171       struct field *fields = NULL;
12172       int num_fields = 0;
12173       int unsigned_enum = 1;
12174       const char *name;
12175       int flag_enum = 1;
12176       ULONGEST mask = 0;
12177
12178       child_die = die->child;
12179       while (child_die && child_die->tag)
12180         {
12181           if (child_die->tag != DW_TAG_enumerator)
12182             {
12183               process_die (child_die, cu);
12184             }
12185           else
12186             {
12187               name = dwarf2_name (child_die, cu);
12188               if (name)
12189                 {
12190                   sym = new_symbol (child_die, this_type, cu);
12191                   if (SYMBOL_VALUE (sym) < 0)
12192                     {
12193                       unsigned_enum = 0;
12194                       flag_enum = 0;
12195                     }
12196                   else if ((mask & SYMBOL_VALUE (sym)) != 0)
12197                     flag_enum = 0;
12198                   else
12199                     mask |= SYMBOL_VALUE (sym);
12200
12201                   if ((num_fields % DW_FIELD_ALLOC_CHUNK) == 0)
12202                     {
12203                       fields = (struct field *)
12204                         xrealloc (fields,
12205                                   (num_fields + DW_FIELD_ALLOC_CHUNK)
12206                                   * sizeof (struct field));
12207                     }
12208
12209                   FIELD_NAME (fields[num_fields]) = SYMBOL_LINKAGE_NAME (sym);
12210                   FIELD_TYPE (fields[num_fields]) = NULL;
12211                   SET_FIELD_ENUMVAL (fields[num_fields], SYMBOL_VALUE (sym));
12212                   FIELD_BITSIZE (fields[num_fields]) = 0;
12213
12214                   num_fields++;
12215                 }
12216             }
12217
12218           child_die = sibling_die (child_die);
12219         }
12220
12221       if (num_fields)
12222         {
12223           TYPE_NFIELDS (this_type) = num_fields;
12224           TYPE_FIELDS (this_type) = (struct field *)
12225             TYPE_ALLOC (this_type, sizeof (struct field) * num_fields);
12226           memcpy (TYPE_FIELDS (this_type), fields,
12227                   sizeof (struct field) * num_fields);
12228           xfree (fields);
12229         }
12230       if (unsigned_enum)
12231         TYPE_UNSIGNED (this_type) = 1;
12232       if (flag_enum)
12233         TYPE_FLAG_ENUM (this_type) = 1;
12234     }
12235
12236   /* If we are reading an enum from a .debug_types unit, and the enum
12237      is a declaration, and the enum is not the signatured type in the
12238      unit, then we do not want to add a symbol for it.  Adding a
12239      symbol would in some cases obscure the true definition of the
12240      enum, giving users an incomplete type when the definition is
12241      actually available.  Note that we do not want to do this for all
12242      enums which are just declarations, because C++0x allows forward
12243      enum declarations.  */
12244   if (cu->per_cu->is_debug_types
12245       && die_is_declaration (die, cu))
12246     {
12247       struct signatured_type *sig_type;
12248
12249       sig_type = (struct signatured_type *) cu->per_cu;
12250       gdb_assert (sig_type->type_offset_in_section.sect_off != 0);
12251       if (sig_type->type_offset_in_section.sect_off != die->offset.sect_off)
12252         return;
12253     }
12254
12255   new_symbol (die, this_type, cu);
12256 }
12257
12258 /* Extract all information from a DW_TAG_array_type DIE and put it in
12259    the DIE's type field.  For now, this only handles one dimensional
12260    arrays.  */
12261
12262 static struct type *
12263 read_array_type (struct die_info *die, struct dwarf2_cu *cu)
12264 {
12265   struct objfile *objfile = cu->objfile;
12266   struct die_info *child_die;
12267   struct type *type;
12268   struct type *element_type, *range_type, *index_type;
12269   struct type **range_types = NULL;
12270   struct attribute *attr;
12271   int ndim = 0;
12272   struct cleanup *back_to;
12273   const char *name;
12274
12275   element_type = die_type (die, cu);
12276
12277   /* The die_type call above may have already set the type for this DIE.  */
12278   type = get_die_type (die, cu);
12279   if (type)
12280     return type;
12281
12282   /* Irix 6.2 native cc creates array types without children for
12283      arrays with unspecified length.  */
12284   if (die->child == NULL)
12285     {
12286       index_type = objfile_type (objfile)->builtin_int;
12287       range_type = create_range_type (NULL, index_type, 0, -1);
12288       type = create_array_type (NULL, element_type, range_type);
12289       return set_die_type (die, type, cu);
12290     }
12291
12292   back_to = make_cleanup (null_cleanup, NULL);
12293   child_die = die->child;
12294   while (child_die && child_die->tag)
12295     {
12296       if (child_die->tag == DW_TAG_subrange_type)
12297         {
12298           struct type *child_type = read_type_die (child_die, cu);
12299
12300           if (child_type != NULL)
12301             {
12302               /* The range type was succesfully read.  Save it for the
12303                  array type creation.  */
12304               if ((ndim % DW_FIELD_ALLOC_CHUNK) == 0)
12305                 {
12306                   range_types = (struct type **)
12307                     xrealloc (range_types, (ndim + DW_FIELD_ALLOC_CHUNK)
12308                               * sizeof (struct type *));
12309                   if (ndim == 0)
12310                     make_cleanup (free_current_contents, &range_types);
12311                 }
12312               range_types[ndim++] = child_type;
12313             }
12314         }
12315       child_die = sibling_die (child_die);
12316     }
12317
12318   /* Dwarf2 dimensions are output from left to right, create the
12319      necessary array types in backwards order.  */
12320
12321   type = element_type;
12322
12323   if (read_array_order (die, cu) == DW_ORD_col_major)
12324     {
12325       int i = 0;
12326
12327       while (i < ndim)
12328         type = create_array_type (NULL, type, range_types[i++]);
12329     }
12330   else
12331     {
12332       while (ndim-- > 0)
12333         type = create_array_type (NULL, type, range_types[ndim]);
12334     }
12335
12336   /* Understand Dwarf2 support for vector types (like they occur on
12337      the PowerPC w/ AltiVec).  Gcc just adds another attribute to the
12338      array type.  This is not part of the Dwarf2/3 standard yet, but a
12339      custom vendor extension.  The main difference between a regular
12340      array and the vector variant is that vectors are passed by value
12341      to functions.  */
12342   attr = dwarf2_attr (die, DW_AT_GNU_vector, cu);
12343   if (attr)
12344     make_vector_type (type);
12345
12346   /* The DIE may have DW_AT_byte_size set.  For example an OpenCL
12347      implementation may choose to implement triple vectors using this
12348      attribute.  */
12349   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
12350   if (attr)
12351     {
12352       if (DW_UNSND (attr) >= TYPE_LENGTH (type))
12353         TYPE_LENGTH (type) = DW_UNSND (attr);
12354       else
12355         complaint (&symfile_complaints,
12356                    _("DW_AT_byte_size for array type smaller "
12357                      "than the total size of elements"));
12358     }
12359
12360   name = dwarf2_name (die, cu);
12361   if (name)
12362     TYPE_NAME (type) = name;
12363
12364   /* Install the type in the die.  */
12365   set_die_type (die, type, cu);
12366
12367   /* set_die_type should be already done.  */
12368   set_descriptive_type (type, die, cu);
12369
12370   do_cleanups (back_to);
12371
12372   return type;
12373 }
12374
12375 static enum dwarf_array_dim_ordering
12376 read_array_order (struct die_info *die, struct dwarf2_cu *cu)
12377 {
12378   struct attribute *attr;
12379
12380   attr = dwarf2_attr (die, DW_AT_ordering, cu);
12381
12382   if (attr) return DW_SND (attr);
12383
12384   /* GNU F77 is a special case, as at 08/2004 array type info is the
12385      opposite order to the dwarf2 specification, but data is still
12386      laid out as per normal fortran.
12387
12388      FIXME: dsl/2004-8-20: If G77 is ever fixed, this will also need
12389      version checking.  */
12390
12391   if (cu->language == language_fortran
12392       && cu->producer && strstr (cu->producer, "GNU F77"))
12393     {
12394       return DW_ORD_row_major;
12395     }
12396
12397   switch (cu->language_defn->la_array_ordering)
12398     {
12399     case array_column_major:
12400       return DW_ORD_col_major;
12401     case array_row_major:
12402     default:
12403       return DW_ORD_row_major;
12404     };
12405 }
12406
12407 /* Extract all information from a DW_TAG_set_type DIE and put it in
12408    the DIE's type field.  */
12409
12410 static struct type *
12411 read_set_type (struct die_info *die, struct dwarf2_cu *cu)
12412 {
12413   struct type *domain_type, *set_type;
12414   struct attribute *attr;
12415
12416   domain_type = die_type (die, cu);
12417
12418   /* The die_type call above may have already set the type for this DIE.  */
12419   set_type = get_die_type (die, cu);
12420   if (set_type)
12421     return set_type;
12422
12423   set_type = create_set_type (NULL, domain_type);
12424
12425   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
12426   if (attr)
12427     TYPE_LENGTH (set_type) = DW_UNSND (attr);
12428
12429   return set_die_type (die, set_type, cu);
12430 }
12431
12432 /* A helper for read_common_block that creates a locexpr baton.
12433    SYM is the symbol which we are marking as computed.
12434    COMMON_DIE is the DIE for the common block.
12435    COMMON_LOC is the location expression attribute for the common
12436    block itself.
12437    MEMBER_LOC is the location expression attribute for the particular
12438    member of the common block that we are processing.
12439    CU is the CU from which the above come.  */
12440
12441 static void
12442 mark_common_block_symbol_computed (struct symbol *sym,
12443                                    struct die_info *common_die,
12444                                    struct attribute *common_loc,
12445                                    struct attribute *member_loc,
12446                                    struct dwarf2_cu *cu)
12447 {
12448   struct objfile *objfile = dwarf2_per_objfile->objfile;
12449   struct dwarf2_locexpr_baton *baton;
12450   gdb_byte *ptr;
12451   unsigned int cu_off;
12452   enum bfd_endian byte_order = gdbarch_byte_order (get_objfile_arch (objfile));
12453   LONGEST offset = 0;
12454
12455   gdb_assert (common_loc && member_loc);
12456   gdb_assert (attr_form_is_block (common_loc));
12457   gdb_assert (attr_form_is_block (member_loc)
12458               || attr_form_is_constant (member_loc));
12459
12460   baton = obstack_alloc (&objfile->objfile_obstack,
12461                          sizeof (struct dwarf2_locexpr_baton));
12462   baton->per_cu = cu->per_cu;
12463   gdb_assert (baton->per_cu);
12464
12465   baton->size = 5 /* DW_OP_call4 */ + 1 /* DW_OP_plus */;
12466
12467   if (attr_form_is_constant (member_loc))
12468     {
12469       offset = dwarf2_get_attr_constant_value (member_loc, 0);
12470       baton->size += 1 /* DW_OP_addr */ + cu->header.addr_size;
12471     }
12472   else
12473     baton->size += DW_BLOCK (member_loc)->size;
12474
12475   ptr = obstack_alloc (&objfile->objfile_obstack, baton->size);
12476   baton->data = ptr;
12477
12478   *ptr++ = DW_OP_call4;
12479   cu_off = common_die->offset.sect_off - cu->per_cu->offset.sect_off;
12480   store_unsigned_integer (ptr, 4, byte_order, cu_off);
12481   ptr += 4;
12482
12483   if (attr_form_is_constant (member_loc))
12484     {
12485       *ptr++ = DW_OP_addr;
12486       store_unsigned_integer (ptr, cu->header.addr_size, byte_order, offset);
12487       ptr += cu->header.addr_size;
12488     }
12489   else
12490     {
12491       /* We have to copy the data here, because DW_OP_call4 will only
12492          use a DW_AT_location attribute.  */
12493       memcpy (ptr, DW_BLOCK (member_loc)->data, DW_BLOCK (member_loc)->size);
12494       ptr += DW_BLOCK (member_loc)->size;
12495     }
12496
12497   *ptr++ = DW_OP_plus;
12498   gdb_assert (ptr - baton->data == baton->size);
12499
12500   SYMBOL_LOCATION_BATON (sym) = baton;
12501   SYMBOL_ACLASS_INDEX (sym) = dwarf2_locexpr_index;
12502 }
12503
12504 /* Create appropriate locally-scoped variables for all the
12505    DW_TAG_common_block entries.  Also create a struct common_block
12506    listing all such variables for `info common'.  COMMON_BLOCK_DOMAIN
12507    is used to sepate the common blocks name namespace from regular
12508    variable names.  */
12509
12510 static void
12511 read_common_block (struct die_info *die, struct dwarf2_cu *cu)
12512 {
12513   struct attribute *attr;
12514
12515   attr = dwarf2_attr (die, DW_AT_location, cu);
12516   if (attr)
12517     {
12518       /* Support the .debug_loc offsets.  */
12519       if (attr_form_is_block (attr))
12520         {
12521           /* Ok.  */
12522         }
12523       else if (attr_form_is_section_offset (attr))
12524         {
12525           dwarf2_complex_location_expr_complaint ();
12526           attr = NULL;
12527         }
12528       else
12529         {
12530           dwarf2_invalid_attrib_class_complaint ("DW_AT_location",
12531                                                  "common block member");
12532           attr = NULL;
12533         }
12534     }
12535
12536   if (die->child != NULL)
12537     {
12538       struct objfile *objfile = cu->objfile;
12539       struct die_info *child_die;
12540       size_t n_entries = 0, size;
12541       struct common_block *common_block;
12542       struct symbol *sym;
12543
12544       for (child_die = die->child;
12545            child_die && child_die->tag;
12546            child_die = sibling_die (child_die))
12547         ++n_entries;
12548
12549       size = (sizeof (struct common_block)
12550               + (n_entries - 1) * sizeof (struct symbol *));
12551       common_block = obstack_alloc (&objfile->objfile_obstack, size);
12552       memset (common_block->contents, 0, n_entries * sizeof (struct symbol *));
12553       common_block->n_entries = 0;
12554
12555       for (child_die = die->child;
12556            child_die && child_die->tag;
12557            child_die = sibling_die (child_die))
12558         {
12559           /* Create the symbol in the DW_TAG_common_block block in the current
12560              symbol scope.  */
12561           sym = new_symbol (child_die, NULL, cu);
12562           if (sym != NULL)
12563             {
12564               struct attribute *member_loc;
12565
12566               common_block->contents[common_block->n_entries++] = sym;
12567
12568               member_loc = dwarf2_attr (child_die, DW_AT_data_member_location,
12569                                         cu);
12570               if (member_loc)
12571                 {
12572                   /* GDB has handled this for a long time, but it is
12573                      not specified by DWARF.  It seems to have been
12574                      emitted by gfortran at least as recently as:
12575                      http://gcc.gnu.org/bugzilla/show_bug.cgi?id=23057.  */
12576                   complaint (&symfile_complaints,
12577                              _("Variable in common block has "
12578                                "DW_AT_data_member_location "
12579                                "- DIE at 0x%x [in module %s]"),
12580                              child_die->offset.sect_off, cu->objfile->name);
12581
12582                   if (attr_form_is_section_offset (member_loc))
12583                     dwarf2_complex_location_expr_complaint ();
12584                   else if (attr_form_is_constant (member_loc)
12585                            || attr_form_is_block (member_loc))
12586                     {
12587                       if (attr)
12588                         mark_common_block_symbol_computed (sym, die, attr,
12589                                                            member_loc, cu);
12590                     }
12591                   else
12592                     dwarf2_complex_location_expr_complaint ();
12593                 }
12594             }
12595         }
12596
12597       sym = new_symbol (die, objfile_type (objfile)->builtin_void, cu);
12598       SYMBOL_VALUE_COMMON_BLOCK (sym) = common_block;
12599     }
12600 }
12601
12602 /* Create a type for a C++ namespace.  */
12603
12604 static struct type *
12605 read_namespace_type (struct die_info *die, struct dwarf2_cu *cu)
12606 {
12607   struct objfile *objfile = cu->objfile;
12608   const char *previous_prefix, *name;
12609   int is_anonymous;
12610   struct type *type;
12611
12612   /* For extensions, reuse the type of the original namespace.  */
12613   if (dwarf2_attr (die, DW_AT_extension, cu) != NULL)
12614     {
12615       struct die_info *ext_die;
12616       struct dwarf2_cu *ext_cu = cu;
12617
12618       ext_die = dwarf2_extension (die, &ext_cu);
12619       type = read_type_die (ext_die, ext_cu);
12620
12621       /* EXT_CU may not be the same as CU.
12622          Ensure TYPE is recorded with CU in die_type_hash.  */
12623       return set_die_type (die, type, cu);
12624     }
12625
12626   name = namespace_name (die, &is_anonymous, cu);
12627
12628   /* Now build the name of the current namespace.  */
12629
12630   previous_prefix = determine_prefix (die, cu);
12631   if (previous_prefix[0] != '\0')
12632     name = typename_concat (&objfile->objfile_obstack,
12633                             previous_prefix, name, 0, cu);
12634
12635   /* Create the type.  */
12636   type = init_type (TYPE_CODE_NAMESPACE, 0, 0, NULL,
12637                     objfile);
12638   TYPE_NAME (type) = name;
12639   TYPE_TAG_NAME (type) = TYPE_NAME (type);
12640
12641   return set_die_type (die, type, cu);
12642 }
12643
12644 /* Read a C++ namespace.  */
12645
12646 static void
12647 read_namespace (struct die_info *die, struct dwarf2_cu *cu)
12648 {
12649   struct objfile *objfile = cu->objfile;
12650   int is_anonymous;
12651
12652   /* Add a symbol associated to this if we haven't seen the namespace
12653      before.  Also, add a using directive if it's an anonymous
12654      namespace.  */
12655
12656   if (dwarf2_attr (die, DW_AT_extension, cu) == NULL)
12657     {
12658       struct type *type;
12659
12660       type = read_type_die (die, cu);
12661       new_symbol (die, type, cu);
12662
12663       namespace_name (die, &is_anonymous, cu);
12664       if (is_anonymous)
12665         {
12666           const char *previous_prefix = determine_prefix (die, cu);
12667
12668           cp_add_using_directive (previous_prefix, TYPE_NAME (type), NULL,
12669                                   NULL, NULL, 0, &objfile->objfile_obstack);
12670         }
12671     }
12672
12673   if (die->child != NULL)
12674     {
12675       struct die_info *child_die = die->child;
12676
12677       while (child_die && child_die->tag)
12678         {
12679           process_die (child_die, cu);
12680           child_die = sibling_die (child_die);
12681         }
12682     }
12683 }
12684
12685 /* Read a Fortran module as type.  This DIE can be only a declaration used for
12686    imported module.  Still we need that type as local Fortran "use ... only"
12687    declaration imports depend on the created type in determine_prefix.  */
12688
12689 static struct type *
12690 read_module_type (struct die_info *die, struct dwarf2_cu *cu)
12691 {
12692   struct objfile *objfile = cu->objfile;
12693   const char *module_name;
12694   struct type *type;
12695
12696   module_name = dwarf2_name (die, cu);
12697   if (!module_name)
12698     complaint (&symfile_complaints,
12699                _("DW_TAG_module has no name, offset 0x%x"),
12700                die->offset.sect_off);
12701   type = init_type (TYPE_CODE_MODULE, 0, 0, module_name, objfile);
12702
12703   /* determine_prefix uses TYPE_TAG_NAME.  */
12704   TYPE_TAG_NAME (type) = TYPE_NAME (type);
12705
12706   return set_die_type (die, type, cu);
12707 }
12708
12709 /* Read a Fortran module.  */
12710
12711 static void
12712 read_module (struct die_info *die, struct dwarf2_cu *cu)
12713 {
12714   struct die_info *child_die = die->child;
12715
12716   while (child_die && child_die->tag)
12717     {
12718       process_die (child_die, cu);
12719       child_die = sibling_die (child_die);
12720     }
12721 }
12722
12723 /* Return the name of the namespace represented by DIE.  Set
12724    *IS_ANONYMOUS to tell whether or not the namespace is an anonymous
12725    namespace.  */
12726
12727 static const char *
12728 namespace_name (struct die_info *die, int *is_anonymous, struct dwarf2_cu *cu)
12729 {
12730   struct die_info *current_die;
12731   const char *name = NULL;
12732
12733   /* Loop through the extensions until we find a name.  */
12734
12735   for (current_die = die;
12736        current_die != NULL;
12737        current_die = dwarf2_extension (die, &cu))
12738     {
12739       name = dwarf2_name (current_die, cu);
12740       if (name != NULL)
12741         break;
12742     }
12743
12744   /* Is it an anonymous namespace?  */
12745
12746   *is_anonymous = (name == NULL);
12747   if (*is_anonymous)
12748     name = CP_ANONYMOUS_NAMESPACE_STR;
12749
12750   return name;
12751 }
12752
12753 /* Extract all information from a DW_TAG_pointer_type DIE and add to
12754    the user defined type vector.  */
12755
12756 static struct type *
12757 read_tag_pointer_type (struct die_info *die, struct dwarf2_cu *cu)
12758 {
12759   struct gdbarch *gdbarch = get_objfile_arch (cu->objfile);
12760   struct comp_unit_head *cu_header = &cu->header;
12761   struct type *type;
12762   struct attribute *attr_byte_size;
12763   struct attribute *attr_address_class;
12764   int byte_size, addr_class;
12765   struct type *target_type;
12766
12767   target_type = die_type (die, cu);
12768
12769   /* The die_type call above may have already set the type for this DIE.  */
12770   type = get_die_type (die, cu);
12771   if (type)
12772     return type;
12773
12774   type = lookup_pointer_type (target_type);
12775
12776   attr_byte_size = dwarf2_attr (die, DW_AT_byte_size, cu);
12777   if (attr_byte_size)
12778     byte_size = DW_UNSND (attr_byte_size);
12779   else
12780     byte_size = cu_header->addr_size;
12781
12782   attr_address_class = dwarf2_attr (die, DW_AT_address_class, cu);
12783   if (attr_address_class)
12784     addr_class = DW_UNSND (attr_address_class);
12785   else
12786     addr_class = DW_ADDR_none;
12787
12788   /* If the pointer size or address class is different than the
12789      default, create a type variant marked as such and set the
12790      length accordingly.  */
12791   if (TYPE_LENGTH (type) != byte_size || addr_class != DW_ADDR_none)
12792     {
12793       if (gdbarch_address_class_type_flags_p (gdbarch))
12794         {
12795           int type_flags;
12796
12797           type_flags = gdbarch_address_class_type_flags
12798                          (gdbarch, byte_size, addr_class);
12799           gdb_assert ((type_flags & ~TYPE_INSTANCE_FLAG_ADDRESS_CLASS_ALL)
12800                       == 0);
12801           type = make_type_with_address_space (type, type_flags);
12802         }
12803       else if (TYPE_LENGTH (type) != byte_size)
12804         {
12805           complaint (&symfile_complaints,
12806                      _("invalid pointer size %d"), byte_size);
12807         }
12808       else
12809         {
12810           /* Should we also complain about unhandled address classes?  */
12811         }
12812     }
12813
12814   TYPE_LENGTH (type) = byte_size;
12815   return set_die_type (die, type, cu);
12816 }
12817
12818 /* Extract all information from a DW_TAG_ptr_to_member_type DIE and add to
12819    the user defined type vector.  */
12820
12821 static struct type *
12822 read_tag_ptr_to_member_type (struct die_info *die, struct dwarf2_cu *cu)
12823 {
12824   struct type *type;
12825   struct type *to_type;
12826   struct type *domain;
12827
12828   to_type = die_type (die, cu);
12829   domain = die_containing_type (die, cu);
12830
12831   /* The calls above may have already set the type for this DIE.  */
12832   type = get_die_type (die, cu);
12833   if (type)
12834     return type;
12835
12836   if (TYPE_CODE (check_typedef (to_type)) == TYPE_CODE_METHOD)
12837     type = lookup_methodptr_type (to_type);
12838   else if (TYPE_CODE (check_typedef (to_type)) == TYPE_CODE_FUNC)
12839     {
12840       struct type *new_type = alloc_type (cu->objfile);
12841
12842       smash_to_method_type (new_type, domain, TYPE_TARGET_TYPE (to_type),
12843                             TYPE_FIELDS (to_type), TYPE_NFIELDS (to_type),
12844                             TYPE_VARARGS (to_type));
12845       type = lookup_methodptr_type (new_type);
12846     }
12847   else
12848     type = lookup_memberptr_type (to_type, domain);
12849
12850   return set_die_type (die, type, cu);
12851 }
12852
12853 /* Extract all information from a DW_TAG_reference_type DIE and add to
12854    the user defined type vector.  */
12855
12856 static struct type *
12857 read_tag_reference_type (struct die_info *die, struct dwarf2_cu *cu)
12858 {
12859   struct comp_unit_head *cu_header = &cu->header;
12860   struct type *type, *target_type;
12861   struct attribute *attr;
12862
12863   target_type = die_type (die, cu);
12864
12865   /* The die_type call above may have already set the type for this DIE.  */
12866   type = get_die_type (die, cu);
12867   if (type)
12868     return type;
12869
12870   type = lookup_reference_type (target_type);
12871   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
12872   if (attr)
12873     {
12874       TYPE_LENGTH (type) = DW_UNSND (attr);
12875     }
12876   else
12877     {
12878       TYPE_LENGTH (type) = cu_header->addr_size;
12879     }
12880   return set_die_type (die, type, cu);
12881 }
12882
12883 static struct type *
12884 read_tag_const_type (struct die_info *die, struct dwarf2_cu *cu)
12885 {
12886   struct type *base_type, *cv_type;
12887
12888   base_type = die_type (die, cu);
12889
12890   /* The die_type call above may have already set the type for this DIE.  */
12891   cv_type = get_die_type (die, cu);
12892   if (cv_type)
12893     return cv_type;
12894
12895   /* In case the const qualifier is applied to an array type, the element type
12896      is so qualified, not the array type (section 6.7.3 of C99).  */
12897   if (TYPE_CODE (base_type) == TYPE_CODE_ARRAY)
12898     {
12899       struct type *el_type, *inner_array;
12900
12901       base_type = copy_type (base_type);
12902       inner_array = base_type;
12903
12904       while (TYPE_CODE (TYPE_TARGET_TYPE (inner_array)) == TYPE_CODE_ARRAY)
12905         {
12906           TYPE_TARGET_TYPE (inner_array) =
12907             copy_type (TYPE_TARGET_TYPE (inner_array));
12908           inner_array = TYPE_TARGET_TYPE (inner_array);
12909         }
12910
12911       el_type = TYPE_TARGET_TYPE (inner_array);
12912       TYPE_TARGET_TYPE (inner_array) =
12913         make_cv_type (1, TYPE_VOLATILE (el_type), el_type, NULL);
12914
12915       return set_die_type (die, base_type, cu);
12916     }
12917
12918   cv_type = make_cv_type (1, TYPE_VOLATILE (base_type), base_type, 0);
12919   return set_die_type (die, cv_type, cu);
12920 }
12921
12922 static struct type *
12923 read_tag_volatile_type (struct die_info *die, struct dwarf2_cu *cu)
12924 {
12925   struct type *base_type, *cv_type;
12926
12927   base_type = die_type (die, cu);
12928
12929   /* The die_type call above may have already set the type for this DIE.  */
12930   cv_type = get_die_type (die, cu);
12931   if (cv_type)
12932     return cv_type;
12933
12934   cv_type = make_cv_type (TYPE_CONST (base_type), 1, base_type, 0);
12935   return set_die_type (die, cv_type, cu);
12936 }
12937
12938 /* Handle DW_TAG_restrict_type.  */
12939
12940 static struct type *
12941 read_tag_restrict_type (struct die_info *die, struct dwarf2_cu *cu)
12942 {
12943   struct type *base_type, *cv_type;
12944
12945   base_type = die_type (die, cu);
12946
12947   /* The die_type call above may have already set the type for this DIE.  */
12948   cv_type = get_die_type (die, cu);
12949   if (cv_type)
12950     return cv_type;
12951
12952   cv_type = make_restrict_type (base_type);
12953   return set_die_type (die, cv_type, cu);
12954 }
12955
12956 /* Extract all information from a DW_TAG_string_type DIE and add to
12957    the user defined type vector.  It isn't really a user defined type,
12958    but it behaves like one, with other DIE's using an AT_user_def_type
12959    attribute to reference it.  */
12960
12961 static struct type *
12962 read_tag_string_type (struct die_info *die, struct dwarf2_cu *cu)
12963 {
12964   struct objfile *objfile = cu->objfile;
12965   struct gdbarch *gdbarch = get_objfile_arch (objfile);
12966   struct type *type, *range_type, *index_type, *char_type;
12967   struct attribute *attr;
12968   unsigned int length;
12969
12970   attr = dwarf2_attr (die, DW_AT_string_length, cu);
12971   if (attr)
12972     {
12973       length = DW_UNSND (attr);
12974     }
12975   else
12976     {
12977       /* Check for the DW_AT_byte_size attribute.  */
12978       attr = dwarf2_attr (die, DW_AT_byte_size, cu);
12979       if (attr)
12980         {
12981           length = DW_UNSND (attr);
12982         }
12983       else
12984         {
12985           length = 1;
12986         }
12987     }
12988
12989   index_type = objfile_type (objfile)->builtin_int;
12990   range_type = create_range_type (NULL, index_type, 1, length);
12991   char_type = language_string_char_type (cu->language_defn, gdbarch);
12992   type = create_string_type (NULL, char_type, range_type);
12993
12994   return set_die_type (die, type, cu);
12995 }
12996
12997 /* Assuming that DIE corresponds to a function, returns nonzero
12998    if the function is prototyped.  */
12999
13000 static int
13001 prototyped_function_p (struct die_info *die, struct dwarf2_cu *cu)
13002 {
13003   struct attribute *attr;
13004
13005   attr = dwarf2_attr (die, DW_AT_prototyped, cu);
13006   if (attr && (DW_UNSND (attr) != 0))
13007     return 1;
13008
13009   /* The DWARF standard implies that the DW_AT_prototyped attribute
13010      is only meaninful for C, but the concept also extends to other
13011      languages that allow unprototyped functions (Eg: Objective C).
13012      For all other languages, assume that functions are always
13013      prototyped.  */
13014   if (cu->language != language_c
13015       && cu->language != language_objc
13016       && cu->language != language_opencl)
13017     return 1;
13018
13019   /* RealView does not emit DW_AT_prototyped.  We can not distinguish
13020      prototyped and unprototyped functions; default to prototyped,
13021      since that is more common in modern code (and RealView warns
13022      about unprototyped functions).  */
13023   if (producer_is_realview (cu->producer))
13024     return 1;
13025
13026   return 0;
13027 }
13028
13029 /* Handle DIES due to C code like:
13030
13031    struct foo
13032    {
13033    int (*funcp)(int a, long l);
13034    int b;
13035    };
13036
13037    ('funcp' generates a DW_TAG_subroutine_type DIE).  */
13038
13039 static struct type *
13040 read_subroutine_type (struct die_info *die, struct dwarf2_cu *cu)
13041 {
13042   struct objfile *objfile = cu->objfile;
13043   struct type *type;            /* Type that this function returns.  */
13044   struct type *ftype;           /* Function that returns above type.  */
13045   struct attribute *attr;
13046
13047   type = die_type (die, cu);
13048
13049   /* The die_type call above may have already set the type for this DIE.  */
13050   ftype = get_die_type (die, cu);
13051   if (ftype)
13052     return ftype;
13053
13054   ftype = lookup_function_type (type);
13055
13056   if (prototyped_function_p (die, cu))
13057     TYPE_PROTOTYPED (ftype) = 1;
13058
13059   /* Store the calling convention in the type if it's available in
13060      the subroutine die.  Otherwise set the calling convention to
13061      the default value DW_CC_normal.  */
13062   attr = dwarf2_attr (die, DW_AT_calling_convention, cu);
13063   if (attr)
13064     TYPE_CALLING_CONVENTION (ftype) = DW_UNSND (attr);
13065   else if (cu->producer && strstr (cu->producer, "IBM XL C for OpenCL"))
13066     TYPE_CALLING_CONVENTION (ftype) = DW_CC_GDB_IBM_OpenCL;
13067   else
13068     TYPE_CALLING_CONVENTION (ftype) = DW_CC_normal;
13069
13070   /* We need to add the subroutine type to the die immediately so
13071      we don't infinitely recurse when dealing with parameters
13072      declared as the same subroutine type.  */
13073   set_die_type (die, ftype, cu);
13074
13075   if (die->child != NULL)
13076     {
13077       struct type *void_type = objfile_type (objfile)->builtin_void;
13078       struct die_info *child_die;
13079       int nparams, iparams;
13080
13081       /* Count the number of parameters.
13082          FIXME: GDB currently ignores vararg functions, but knows about
13083          vararg member functions.  */
13084       nparams = 0;
13085       child_die = die->child;
13086       while (child_die && child_die->tag)
13087         {
13088           if (child_die->tag == DW_TAG_formal_parameter)
13089             nparams++;
13090           else if (child_die->tag == DW_TAG_unspecified_parameters)
13091             TYPE_VARARGS (ftype) = 1;
13092           child_die = sibling_die (child_die);
13093         }
13094
13095       /* Allocate storage for parameters and fill them in.  */
13096       TYPE_NFIELDS (ftype) = nparams;
13097       TYPE_FIELDS (ftype) = (struct field *)
13098         TYPE_ZALLOC (ftype, nparams * sizeof (struct field));
13099
13100       /* TYPE_FIELD_TYPE must never be NULL.  Pre-fill the array to ensure it
13101          even if we error out during the parameters reading below.  */
13102       for (iparams = 0; iparams < nparams; iparams++)
13103         TYPE_FIELD_TYPE (ftype, iparams) = void_type;
13104
13105       iparams = 0;
13106       child_die = die->child;
13107       while (child_die && child_die->tag)
13108         {
13109           if (child_die->tag == DW_TAG_formal_parameter)
13110             {
13111               struct type *arg_type;
13112
13113               /* DWARF version 2 has no clean way to discern C++
13114                  static and non-static member functions.  G++ helps
13115                  GDB by marking the first parameter for non-static
13116                  member functions (which is the this pointer) as
13117                  artificial.  We pass this information to
13118                  dwarf2_add_member_fn via TYPE_FIELD_ARTIFICIAL.
13119
13120                  DWARF version 3 added DW_AT_object_pointer, which GCC
13121                  4.5 does not yet generate.  */
13122               attr = dwarf2_attr (child_die, DW_AT_artificial, cu);
13123               if (attr)
13124                 TYPE_FIELD_ARTIFICIAL (ftype, iparams) = DW_UNSND (attr);
13125               else
13126                 {
13127                   TYPE_FIELD_ARTIFICIAL (ftype, iparams) = 0;
13128
13129                   /* GCC/43521: In java, the formal parameter
13130                      "this" is sometimes not marked with DW_AT_artificial.  */
13131                   if (cu->language == language_java)
13132                     {
13133                       const char *name = dwarf2_name (child_die, cu);
13134
13135                       if (name && !strcmp (name, "this"))
13136                         TYPE_FIELD_ARTIFICIAL (ftype, iparams) = 1;
13137                     }
13138                 }
13139               arg_type = die_type (child_die, cu);
13140
13141               /* RealView does not mark THIS as const, which the testsuite
13142                  expects.  GCC marks THIS as const in method definitions,
13143                  but not in the class specifications (GCC PR 43053).  */
13144               if (cu->language == language_cplus && !TYPE_CONST (arg_type)
13145                   && TYPE_FIELD_ARTIFICIAL (ftype, iparams))
13146                 {
13147                   int is_this = 0;
13148                   struct dwarf2_cu *arg_cu = cu;
13149                   const char *name = dwarf2_name (child_die, cu);
13150
13151                   attr = dwarf2_attr (die, DW_AT_object_pointer, cu);
13152                   if (attr)
13153                     {
13154                       /* If the compiler emits this, use it.  */
13155                       if (follow_die_ref (die, attr, &arg_cu) == child_die)
13156                         is_this = 1;
13157                     }
13158                   else if (name && strcmp (name, "this") == 0)
13159                     /* Function definitions will have the argument names.  */
13160                     is_this = 1;
13161                   else if (name == NULL && iparams == 0)
13162                     /* Declarations may not have the names, so like
13163                        elsewhere in GDB, assume an artificial first
13164                        argument is "this".  */
13165                     is_this = 1;
13166
13167                   if (is_this)
13168                     arg_type = make_cv_type (1, TYPE_VOLATILE (arg_type),
13169                                              arg_type, 0);
13170                 }
13171
13172               TYPE_FIELD_TYPE (ftype, iparams) = arg_type;
13173               iparams++;
13174             }
13175           child_die = sibling_die (child_die);
13176         }
13177     }
13178
13179   return ftype;
13180 }
13181
13182 static struct type *
13183 read_typedef (struct die_info *die, struct dwarf2_cu *cu)
13184 {
13185   struct objfile *objfile = cu->objfile;
13186   const char *name = NULL;
13187   struct type *this_type, *target_type;
13188
13189   name = dwarf2_full_name (NULL, die, cu);
13190   this_type = init_type (TYPE_CODE_TYPEDEF, 0,
13191                          TYPE_FLAG_TARGET_STUB, NULL, objfile);
13192   TYPE_NAME (this_type) = name;
13193   set_die_type (die, this_type, cu);
13194   target_type = die_type (die, cu);
13195   if (target_type != this_type)
13196     TYPE_TARGET_TYPE (this_type) = target_type;
13197   else
13198     {
13199       /* Self-referential typedefs are, it seems, not allowed by the DWARF
13200          spec and cause infinite loops in GDB.  */
13201       complaint (&symfile_complaints,
13202                  _("Self-referential DW_TAG_typedef "
13203                    "- DIE at 0x%x [in module %s]"),
13204                  die->offset.sect_off, objfile->name);
13205       TYPE_TARGET_TYPE (this_type) = NULL;
13206     }
13207   return this_type;
13208 }
13209
13210 /* Find a representation of a given base type and install
13211    it in the TYPE field of the die.  */
13212
13213 static struct type *
13214 read_base_type (struct die_info *die, struct dwarf2_cu *cu)
13215 {
13216   struct objfile *objfile = cu->objfile;
13217   struct type *type;
13218   struct attribute *attr;
13219   int encoding = 0, size = 0;
13220   const char *name;
13221   enum type_code code = TYPE_CODE_INT;
13222   int type_flags = 0;
13223   struct type *target_type = NULL;
13224
13225   attr = dwarf2_attr (die, DW_AT_encoding, cu);
13226   if (attr)
13227     {
13228       encoding = DW_UNSND (attr);
13229     }
13230   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
13231   if (attr)
13232     {
13233       size = DW_UNSND (attr);
13234     }
13235   name = dwarf2_name (die, cu);
13236   if (!name)
13237     {
13238       complaint (&symfile_complaints,
13239                  _("DW_AT_name missing from DW_TAG_base_type"));
13240     }
13241
13242   switch (encoding)
13243     {
13244       case DW_ATE_address:
13245         /* Turn DW_ATE_address into a void * pointer.  */
13246         code = TYPE_CODE_PTR;
13247         type_flags |= TYPE_FLAG_UNSIGNED;
13248         target_type = init_type (TYPE_CODE_VOID, 1, 0, NULL, objfile);
13249         break;
13250       case DW_ATE_boolean:
13251         code = TYPE_CODE_BOOL;
13252         type_flags |= TYPE_FLAG_UNSIGNED;
13253         break;
13254       case DW_ATE_complex_float:
13255         code = TYPE_CODE_COMPLEX;
13256         target_type = init_type (TYPE_CODE_FLT, size / 2, 0, NULL, objfile);
13257         break;
13258       case DW_ATE_decimal_float:
13259         code = TYPE_CODE_DECFLOAT;
13260         break;
13261       case DW_ATE_float:
13262         code = TYPE_CODE_FLT;
13263         break;
13264       case DW_ATE_signed:
13265         break;
13266       case DW_ATE_unsigned:
13267         type_flags |= TYPE_FLAG_UNSIGNED;
13268         if (cu->language == language_fortran
13269             && name
13270             && strncmp (name, "character(", sizeof ("character(") - 1) == 0)
13271           code = TYPE_CODE_CHAR;
13272         break;
13273       case DW_ATE_signed_char:
13274         if (cu->language == language_ada || cu->language == language_m2
13275             || cu->language == language_pascal
13276             || cu->language == language_fortran)
13277           code = TYPE_CODE_CHAR;
13278         break;
13279       case DW_ATE_unsigned_char:
13280         if (cu->language == language_ada || cu->language == language_m2
13281             || cu->language == language_pascal
13282             || cu->language == language_fortran)
13283           code = TYPE_CODE_CHAR;
13284         type_flags |= TYPE_FLAG_UNSIGNED;
13285         break;
13286       case DW_ATE_UTF:
13287         /* We just treat this as an integer and then recognize the
13288            type by name elsewhere.  */
13289         break;
13290
13291       default:
13292         complaint (&symfile_complaints, _("unsupported DW_AT_encoding: '%s'"),
13293                    dwarf_type_encoding_name (encoding));
13294         break;
13295     }
13296
13297   type = init_type (code, size, type_flags, NULL, objfile);
13298   TYPE_NAME (type) = name;
13299   TYPE_TARGET_TYPE (type) = target_type;
13300
13301   if (name && strcmp (name, "char") == 0)
13302     TYPE_NOSIGN (type) = 1;
13303
13304   return set_die_type (die, type, cu);
13305 }
13306
13307 /* Read the given DW_AT_subrange DIE.  */
13308
13309 static struct type *
13310 read_subrange_type (struct die_info *die, struct dwarf2_cu *cu)
13311 {
13312   struct type *base_type, *orig_base_type;
13313   struct type *range_type;
13314   struct attribute *attr;
13315   LONGEST low, high;
13316   int low_default_is_valid;
13317   const char *name;
13318   LONGEST negative_mask;
13319
13320   orig_base_type = die_type (die, cu);
13321   /* If ORIG_BASE_TYPE is a typedef, it will not be TYPE_UNSIGNED,
13322      whereas the real type might be.  So, we use ORIG_BASE_TYPE when
13323      creating the range type, but we use the result of check_typedef
13324      when examining properties of the type.  */
13325   base_type = check_typedef (orig_base_type);
13326
13327   /* The die_type call above may have already set the type for this DIE.  */
13328   range_type = get_die_type (die, cu);
13329   if (range_type)
13330     return range_type;
13331
13332   /* Set LOW_DEFAULT_IS_VALID if current language and DWARF version allow
13333      omitting DW_AT_lower_bound.  */
13334   switch (cu->language)
13335     {
13336     case language_c:
13337     case language_cplus:
13338       low = 0;
13339       low_default_is_valid = 1;
13340       break;
13341     case language_fortran:
13342       low = 1;
13343       low_default_is_valid = 1;
13344       break;
13345     case language_d:
13346     case language_java:
13347     case language_objc:
13348       low = 0;
13349       low_default_is_valid = (cu->header.version >= 4);
13350       break;
13351     case language_ada:
13352     case language_m2:
13353     case language_pascal:
13354       low = 1;
13355       low_default_is_valid = (cu->header.version >= 4);
13356       break;
13357     default:
13358       low = 0;
13359       low_default_is_valid = 0;
13360       break;
13361     }
13362
13363   /* FIXME: For variable sized arrays either of these could be
13364      a variable rather than a constant value.  We'll allow it,
13365      but we don't know how to handle it.  */
13366   attr = dwarf2_attr (die, DW_AT_lower_bound, cu);
13367   if (attr)
13368     low = dwarf2_get_attr_constant_value (attr, low);
13369   else if (!low_default_is_valid)
13370     complaint (&symfile_complaints, _("Missing DW_AT_lower_bound "
13371                                       "- DIE at 0x%x [in module %s]"),
13372                die->offset.sect_off, cu->objfile->name);
13373
13374   attr = dwarf2_attr (die, DW_AT_upper_bound, cu);
13375   if (attr)
13376     {
13377       if (attr_form_is_block (attr) || is_ref_attr (attr))
13378         {
13379           /* GCC encodes arrays with unspecified or dynamic length
13380              with a DW_FORM_block1 attribute or a reference attribute.
13381              FIXME: GDB does not yet know how to handle dynamic
13382              arrays properly, treat them as arrays with unspecified
13383              length for now.
13384
13385              FIXME: jimb/2003-09-22: GDB does not really know
13386              how to handle arrays of unspecified length
13387              either; we just represent them as zero-length
13388              arrays.  Choose an appropriate upper bound given
13389              the lower bound we've computed above.  */
13390           high = low - 1;
13391         }
13392       else
13393         high = dwarf2_get_attr_constant_value (attr, 1);
13394     }
13395   else
13396     {
13397       attr = dwarf2_attr (die, DW_AT_count, cu);
13398       if (attr)
13399         {
13400           int count = dwarf2_get_attr_constant_value (attr, 1);
13401           high = low + count - 1;
13402         }
13403       else
13404         {
13405           /* Unspecified array length.  */
13406           high = low - 1;
13407         }
13408     }
13409
13410   /* Dwarf-2 specifications explicitly allows to create subrange types
13411      without specifying a base type.
13412      In that case, the base type must be set to the type of
13413      the lower bound, upper bound or count, in that order, if any of these
13414      three attributes references an object that has a type.
13415      If no base type is found, the Dwarf-2 specifications say that
13416      a signed integer type of size equal to the size of an address should
13417      be used.
13418      For the following C code: `extern char gdb_int [];'
13419      GCC produces an empty range DIE.
13420      FIXME: muller/2010-05-28: Possible references to object for low bound,
13421      high bound or count are not yet handled by this code.  */
13422   if (TYPE_CODE (base_type) == TYPE_CODE_VOID)
13423     {
13424       struct objfile *objfile = cu->objfile;
13425       struct gdbarch *gdbarch = get_objfile_arch (objfile);
13426       int addr_size = gdbarch_addr_bit (gdbarch) /8;
13427       struct type *int_type = objfile_type (objfile)->builtin_int;
13428
13429       /* Test "int", "long int", and "long long int" objfile types,
13430          and select the first one having a size above or equal to the
13431          architecture address size.  */
13432       if (int_type && TYPE_LENGTH (int_type) >= addr_size)
13433         base_type = int_type;
13434       else
13435         {
13436           int_type = objfile_type (objfile)->builtin_long;
13437           if (int_type && TYPE_LENGTH (int_type) >= addr_size)
13438             base_type = int_type;
13439           else
13440             {
13441               int_type = objfile_type (objfile)->builtin_long_long;
13442               if (int_type && TYPE_LENGTH (int_type) >= addr_size)
13443                 base_type = int_type;
13444             }
13445         }
13446     }
13447
13448   negative_mask =
13449     (LONGEST) -1 << (TYPE_LENGTH (base_type) * TARGET_CHAR_BIT - 1);
13450   if (!TYPE_UNSIGNED (base_type) && (low & negative_mask))
13451     low |= negative_mask;
13452   if (!TYPE_UNSIGNED (base_type) && (high & negative_mask))
13453     high |= negative_mask;
13454
13455   range_type = create_range_type (NULL, orig_base_type, low, high);
13456
13457   /* Mark arrays with dynamic length at least as an array of unspecified
13458      length.  GDB could check the boundary but before it gets implemented at
13459      least allow accessing the array elements.  */
13460   if (attr && attr_form_is_block (attr))
13461     TYPE_HIGH_BOUND_UNDEFINED (range_type) = 1;
13462
13463   /* Ada expects an empty array on no boundary attributes.  */
13464   if (attr == NULL && cu->language != language_ada)
13465     TYPE_HIGH_BOUND_UNDEFINED (range_type) = 1;
13466
13467   name = dwarf2_name (die, cu);
13468   if (name)
13469     TYPE_NAME (range_type) = name;
13470
13471   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
13472   if (attr)
13473     TYPE_LENGTH (range_type) = DW_UNSND (attr);
13474
13475   set_die_type (die, range_type, cu);
13476
13477   /* set_die_type should be already done.  */
13478   set_descriptive_type (range_type, die, cu);
13479
13480   return range_type;
13481 }
13482
13483 static struct type *
13484 read_unspecified_type (struct die_info *die, struct dwarf2_cu *cu)
13485 {
13486   struct type *type;
13487
13488   /* For now, we only support the C meaning of an unspecified type: void.  */
13489
13490   type = init_type (TYPE_CODE_VOID, 0, 0, NULL, cu->objfile);
13491   TYPE_NAME (type) = dwarf2_name (die, cu);
13492
13493   return set_die_type (die, type, cu);
13494 }
13495
13496 /* Read a single die and all its descendents.  Set the die's sibling
13497    field to NULL; set other fields in the die correctly, and set all
13498    of the descendents' fields correctly.  Set *NEW_INFO_PTR to the
13499    location of the info_ptr after reading all of those dies.  PARENT
13500    is the parent of the die in question.  */
13501
13502 static struct die_info *
13503 read_die_and_children (const struct die_reader_specs *reader,
13504                        const gdb_byte *info_ptr,
13505                        const gdb_byte **new_info_ptr,
13506                        struct die_info *parent)
13507 {
13508   struct die_info *die;
13509   const gdb_byte *cur_ptr;
13510   int has_children;
13511
13512   cur_ptr = read_full_die_1 (reader, &die, info_ptr, &has_children, 0);
13513   if (die == NULL)
13514     {
13515       *new_info_ptr = cur_ptr;
13516       return NULL;
13517     }
13518   store_in_ref_table (die, reader->cu);
13519
13520   if (has_children)
13521     die->child = read_die_and_siblings_1 (reader, cur_ptr, new_info_ptr, die);
13522   else
13523     {
13524       die->child = NULL;
13525       *new_info_ptr = cur_ptr;
13526     }
13527
13528   die->sibling = NULL;
13529   die->parent = parent;
13530   return die;
13531 }
13532
13533 /* Read a die, all of its descendents, and all of its siblings; set
13534    all of the fields of all of the dies correctly.  Arguments are as
13535    in read_die_and_children.  */
13536
13537 static struct die_info *
13538 read_die_and_siblings_1 (const struct die_reader_specs *reader,
13539                          const gdb_byte *info_ptr,
13540                          const gdb_byte **new_info_ptr,
13541                          struct die_info *parent)
13542 {
13543   struct die_info *first_die, *last_sibling;
13544   const gdb_byte *cur_ptr;
13545
13546   cur_ptr = info_ptr;
13547   first_die = last_sibling = NULL;
13548
13549   while (1)
13550     {
13551       struct die_info *die
13552         = read_die_and_children (reader, cur_ptr, &cur_ptr, parent);
13553
13554       if (die == NULL)
13555         {
13556           *new_info_ptr = cur_ptr;
13557           return first_die;
13558         }
13559
13560       if (!first_die)
13561         first_die = die;
13562       else
13563         last_sibling->sibling = die;
13564
13565       last_sibling = die;
13566     }
13567 }
13568
13569 /* Read a die, all of its descendents, and all of its siblings; set
13570    all of the fields of all of the dies correctly.  Arguments are as
13571    in read_die_and_children.
13572    This the main entry point for reading a DIE and all its children.  */
13573
13574 static struct die_info *
13575 read_die_and_siblings (const struct die_reader_specs *reader,
13576                        const gdb_byte *info_ptr,
13577                        const gdb_byte **new_info_ptr,
13578                        struct die_info *parent)
13579 {
13580   struct die_info *die = read_die_and_siblings_1 (reader, info_ptr,
13581                                                   new_info_ptr, parent);
13582
13583   if (dwarf2_die_debug)
13584     {
13585       fprintf_unfiltered (gdb_stdlog,
13586                           "Read die from %s@0x%x of %s:\n",
13587                           bfd_section_name (reader->abfd,
13588                                             reader->die_section->asection),
13589                           (unsigned) (info_ptr - reader->die_section->buffer),
13590                           bfd_get_filename (reader->abfd));
13591       dump_die (die, dwarf2_die_debug);
13592     }
13593
13594   return die;
13595 }
13596
13597 /* Read a die and all its attributes, leave space for NUM_EXTRA_ATTRS
13598    attributes.
13599    The caller is responsible for filling in the extra attributes
13600    and updating (*DIEP)->num_attrs.
13601    Set DIEP to point to a newly allocated die with its information,
13602    except for its child, sibling, and parent fields.
13603    Set HAS_CHILDREN to tell whether the die has children or not.  */
13604
13605 static const gdb_byte *
13606 read_full_die_1 (const struct die_reader_specs *reader,
13607                  struct die_info **diep, const gdb_byte *info_ptr,
13608                  int *has_children, int num_extra_attrs)
13609 {
13610   unsigned int abbrev_number, bytes_read, i;
13611   sect_offset offset;
13612   struct abbrev_info *abbrev;
13613   struct die_info *die;
13614   struct dwarf2_cu *cu = reader->cu;
13615   bfd *abfd = reader->abfd;
13616
13617   offset.sect_off = info_ptr - reader->buffer;
13618   abbrev_number = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
13619   info_ptr += bytes_read;
13620   if (!abbrev_number)
13621     {
13622       *diep = NULL;
13623       *has_children = 0;
13624       return info_ptr;
13625     }
13626
13627   abbrev = abbrev_table_lookup_abbrev (cu->abbrev_table, abbrev_number);
13628   if (!abbrev)
13629     error (_("Dwarf Error: could not find abbrev number %d [in module %s]"),
13630            abbrev_number,
13631            bfd_get_filename (abfd));
13632
13633   die = dwarf_alloc_die (cu, abbrev->num_attrs + num_extra_attrs);
13634   die->offset = offset;
13635   die->tag = abbrev->tag;
13636   die->abbrev = abbrev_number;
13637
13638   /* Make the result usable.
13639      The caller needs to update num_attrs after adding the extra
13640      attributes.  */
13641   die->num_attrs = abbrev->num_attrs;
13642
13643   for (i = 0; i < abbrev->num_attrs; ++i)
13644     info_ptr = read_attribute (reader, &die->attrs[i], &abbrev->attrs[i],
13645                                info_ptr);
13646
13647   *diep = die;
13648   *has_children = abbrev->has_children;
13649   return info_ptr;
13650 }
13651
13652 /* Read a die and all its attributes.
13653    Set DIEP to point to a newly allocated die with its information,
13654    except for its child, sibling, and parent fields.
13655    Set HAS_CHILDREN to tell whether the die has children or not.  */
13656
13657 static const gdb_byte *
13658 read_full_die (const struct die_reader_specs *reader,
13659                struct die_info **diep, const gdb_byte *info_ptr,
13660                int *has_children)
13661 {
13662   const gdb_byte *result;
13663
13664   result = read_full_die_1 (reader, diep, info_ptr, has_children, 0);
13665
13666   if (dwarf2_die_debug)
13667     {
13668       fprintf_unfiltered (gdb_stdlog,
13669                           "Read die from %s@0x%x of %s:\n",
13670                           bfd_section_name (reader->abfd,
13671                                             reader->die_section->asection),
13672                           (unsigned) (info_ptr - reader->die_section->buffer),
13673                           bfd_get_filename (reader->abfd));
13674       dump_die (*diep, dwarf2_die_debug);
13675     }
13676
13677   return result;
13678 }
13679 \f
13680 /* Abbreviation tables.
13681
13682    In DWARF version 2, the description of the debugging information is
13683    stored in a separate .debug_abbrev section.  Before we read any
13684    dies from a section we read in all abbreviations and install them
13685    in a hash table.  */
13686
13687 /* Allocate space for a struct abbrev_info object in ABBREV_TABLE.  */
13688
13689 static struct abbrev_info *
13690 abbrev_table_alloc_abbrev (struct abbrev_table *abbrev_table)
13691 {
13692   struct abbrev_info *abbrev;
13693
13694   abbrev = (struct abbrev_info *)
13695     obstack_alloc (&abbrev_table->abbrev_obstack, sizeof (struct abbrev_info));
13696   memset (abbrev, 0, sizeof (struct abbrev_info));
13697   return abbrev;
13698 }
13699
13700 /* Add an abbreviation to the table.  */
13701
13702 static void
13703 abbrev_table_add_abbrev (struct abbrev_table *abbrev_table,
13704                          unsigned int abbrev_number,
13705                          struct abbrev_info *abbrev)
13706 {
13707   unsigned int hash_number;
13708
13709   hash_number = abbrev_number % ABBREV_HASH_SIZE;
13710   abbrev->next = abbrev_table->abbrevs[hash_number];
13711   abbrev_table->abbrevs[hash_number] = abbrev;
13712 }
13713
13714 /* Look up an abbrev in the table.
13715    Returns NULL if the abbrev is not found.  */
13716
13717 static struct abbrev_info *
13718 abbrev_table_lookup_abbrev (const struct abbrev_table *abbrev_table,
13719                             unsigned int abbrev_number)
13720 {
13721   unsigned int hash_number;
13722   struct abbrev_info *abbrev;
13723
13724   hash_number = abbrev_number % ABBREV_HASH_SIZE;
13725   abbrev = abbrev_table->abbrevs[hash_number];
13726
13727   while (abbrev)
13728     {
13729       if (abbrev->number == abbrev_number)
13730         return abbrev;
13731       abbrev = abbrev->next;
13732     }
13733   return NULL;
13734 }
13735
13736 /* Read in an abbrev table.  */
13737
13738 static struct abbrev_table *
13739 abbrev_table_read_table (struct dwarf2_section_info *section,
13740                          sect_offset offset)
13741 {
13742   struct objfile *objfile = dwarf2_per_objfile->objfile;
13743   bfd *abfd = section->asection->owner;
13744   struct abbrev_table *abbrev_table;
13745   const gdb_byte *abbrev_ptr;
13746   struct abbrev_info *cur_abbrev;
13747   unsigned int abbrev_number, bytes_read, abbrev_name;
13748   unsigned int abbrev_form;
13749   struct attr_abbrev *cur_attrs;
13750   unsigned int allocated_attrs;
13751
13752   abbrev_table = XMALLOC (struct abbrev_table);
13753   abbrev_table->offset = offset;
13754   obstack_init (&abbrev_table->abbrev_obstack);
13755   abbrev_table->abbrevs = obstack_alloc (&abbrev_table->abbrev_obstack,
13756                                          (ABBREV_HASH_SIZE
13757                                           * sizeof (struct abbrev_info *)));
13758   memset (abbrev_table->abbrevs, 0,
13759           ABBREV_HASH_SIZE * sizeof (struct abbrev_info *));
13760
13761   dwarf2_read_section (objfile, section);
13762   abbrev_ptr = section->buffer + offset.sect_off;
13763   abbrev_number = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
13764   abbrev_ptr += bytes_read;
13765
13766   allocated_attrs = ATTR_ALLOC_CHUNK;
13767   cur_attrs = xmalloc (allocated_attrs * sizeof (struct attr_abbrev));
13768
13769   /* Loop until we reach an abbrev number of 0.  */
13770   while (abbrev_number)
13771     {
13772       cur_abbrev = abbrev_table_alloc_abbrev (abbrev_table);
13773
13774       /* read in abbrev header */
13775       cur_abbrev->number = abbrev_number;
13776       cur_abbrev->tag = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
13777       abbrev_ptr += bytes_read;
13778       cur_abbrev->has_children = read_1_byte (abfd, abbrev_ptr);
13779       abbrev_ptr += 1;
13780
13781       /* now read in declarations */
13782       abbrev_name = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
13783       abbrev_ptr += bytes_read;
13784       abbrev_form = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
13785       abbrev_ptr += bytes_read;
13786       while (abbrev_name)
13787         {
13788           if (cur_abbrev->num_attrs == allocated_attrs)
13789             {
13790               allocated_attrs += ATTR_ALLOC_CHUNK;
13791               cur_attrs
13792                 = xrealloc (cur_attrs, (allocated_attrs
13793                                         * sizeof (struct attr_abbrev)));
13794             }
13795
13796           cur_attrs[cur_abbrev->num_attrs].name = abbrev_name;
13797           cur_attrs[cur_abbrev->num_attrs++].form = abbrev_form;
13798           abbrev_name = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
13799           abbrev_ptr += bytes_read;
13800           abbrev_form = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
13801           abbrev_ptr += bytes_read;
13802         }
13803
13804       cur_abbrev->attrs = obstack_alloc (&abbrev_table->abbrev_obstack,
13805                                          (cur_abbrev->num_attrs
13806                                           * sizeof (struct attr_abbrev)));
13807       memcpy (cur_abbrev->attrs, cur_attrs,
13808               cur_abbrev->num_attrs * sizeof (struct attr_abbrev));
13809
13810       abbrev_table_add_abbrev (abbrev_table, abbrev_number, cur_abbrev);
13811
13812       /* Get next abbreviation.
13813          Under Irix6 the abbreviations for a compilation unit are not
13814          always properly terminated with an abbrev number of 0.
13815          Exit loop if we encounter an abbreviation which we have
13816          already read (which means we are about to read the abbreviations
13817          for the next compile unit) or if the end of the abbreviation
13818          table is reached.  */
13819       if ((unsigned int) (abbrev_ptr - section->buffer) >= section->size)
13820         break;
13821       abbrev_number = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
13822       abbrev_ptr += bytes_read;
13823       if (abbrev_table_lookup_abbrev (abbrev_table, abbrev_number) != NULL)
13824         break;
13825     }
13826
13827   xfree (cur_attrs);
13828   return abbrev_table;
13829 }
13830
13831 /* Free the resources held by ABBREV_TABLE.  */
13832
13833 static void
13834 abbrev_table_free (struct abbrev_table *abbrev_table)
13835 {
13836   obstack_free (&abbrev_table->abbrev_obstack, NULL);
13837   xfree (abbrev_table);
13838 }
13839
13840 /* Same as abbrev_table_free but as a cleanup.
13841    We pass in a pointer to the pointer to the table so that we can
13842    set the pointer to NULL when we're done.  It also simplifies
13843    build_type_unit_groups.  */
13844
13845 static void
13846 abbrev_table_free_cleanup (void *table_ptr)
13847 {
13848   struct abbrev_table **abbrev_table_ptr = table_ptr;
13849
13850   if (*abbrev_table_ptr != NULL)
13851     abbrev_table_free (*abbrev_table_ptr);
13852   *abbrev_table_ptr = NULL;
13853 }
13854
13855 /* Read the abbrev table for CU from ABBREV_SECTION.  */
13856
13857 static void
13858 dwarf2_read_abbrevs (struct dwarf2_cu *cu,
13859                      struct dwarf2_section_info *abbrev_section)
13860 {
13861   cu->abbrev_table =
13862     abbrev_table_read_table (abbrev_section, cu->header.abbrev_offset);
13863 }
13864
13865 /* Release the memory used by the abbrev table for a compilation unit.  */
13866
13867 static void
13868 dwarf2_free_abbrev_table (void *ptr_to_cu)
13869 {
13870   struct dwarf2_cu *cu = ptr_to_cu;
13871
13872   if (cu->abbrev_table != NULL)
13873     abbrev_table_free (cu->abbrev_table);
13874   /* Set this to NULL so that we SEGV if we try to read it later,
13875      and also because free_comp_unit verifies this is NULL.  */
13876   cu->abbrev_table = NULL;
13877 }
13878 \f
13879 /* Returns nonzero if TAG represents a type that we might generate a partial
13880    symbol for.  */
13881
13882 static int
13883 is_type_tag_for_partial (int tag)
13884 {
13885   switch (tag)
13886     {
13887 #if 0
13888     /* Some types that would be reasonable to generate partial symbols for,
13889        that we don't at present.  */
13890     case DW_TAG_array_type:
13891     case DW_TAG_file_type:
13892     case DW_TAG_ptr_to_member_type:
13893     case DW_TAG_set_type:
13894     case DW_TAG_string_type:
13895     case DW_TAG_subroutine_type:
13896 #endif
13897     case DW_TAG_base_type:
13898     case DW_TAG_class_type:
13899     case DW_TAG_interface_type:
13900     case DW_TAG_enumeration_type:
13901     case DW_TAG_structure_type:
13902     case DW_TAG_subrange_type:
13903     case DW_TAG_typedef:
13904     case DW_TAG_union_type:
13905       return 1;
13906     default:
13907       return 0;
13908     }
13909 }
13910
13911 /* Load all DIEs that are interesting for partial symbols into memory.  */
13912
13913 static struct partial_die_info *
13914 load_partial_dies (const struct die_reader_specs *reader,
13915                    const gdb_byte *info_ptr, int building_psymtab)
13916 {
13917   struct dwarf2_cu *cu = reader->cu;
13918   struct objfile *objfile = cu->objfile;
13919   struct partial_die_info *part_die;
13920   struct partial_die_info *parent_die, *last_die, *first_die = NULL;
13921   struct abbrev_info *abbrev;
13922   unsigned int bytes_read;
13923   unsigned int load_all = 0;
13924   int nesting_level = 1;
13925
13926   parent_die = NULL;
13927   last_die = NULL;
13928
13929   gdb_assert (cu->per_cu != NULL);
13930   if (cu->per_cu->load_all_dies)
13931     load_all = 1;
13932
13933   cu->partial_dies
13934     = htab_create_alloc_ex (cu->header.length / 12,
13935                             partial_die_hash,
13936                             partial_die_eq,
13937                             NULL,
13938                             &cu->comp_unit_obstack,
13939                             hashtab_obstack_allocate,
13940                             dummy_obstack_deallocate);
13941
13942   part_die = obstack_alloc (&cu->comp_unit_obstack,
13943                             sizeof (struct partial_die_info));
13944
13945   while (1)
13946     {
13947       abbrev = peek_die_abbrev (info_ptr, &bytes_read, cu);
13948
13949       /* A NULL abbrev means the end of a series of children.  */
13950       if (abbrev == NULL)
13951         {
13952           if (--nesting_level == 0)
13953             {
13954               /* PART_DIE was probably the last thing allocated on the
13955                  comp_unit_obstack, so we could call obstack_free
13956                  here.  We don't do that because the waste is small,
13957                  and will be cleaned up when we're done with this
13958                  compilation unit.  This way, we're also more robust
13959                  against other users of the comp_unit_obstack.  */
13960               return first_die;
13961             }
13962           info_ptr += bytes_read;
13963           last_die = parent_die;
13964           parent_die = parent_die->die_parent;
13965           continue;
13966         }
13967
13968       /* Check for template arguments.  We never save these; if
13969          they're seen, we just mark the parent, and go on our way.  */
13970       if (parent_die != NULL
13971           && cu->language == language_cplus
13972           && (abbrev->tag == DW_TAG_template_type_param
13973               || abbrev->tag == DW_TAG_template_value_param))
13974         {
13975           parent_die->has_template_arguments = 1;
13976
13977           if (!load_all)
13978             {
13979               /* We don't need a partial DIE for the template argument.  */
13980               info_ptr = skip_one_die (reader, info_ptr + bytes_read, abbrev);
13981               continue;
13982             }
13983         }
13984
13985       /* We only recurse into c++ subprograms looking for template arguments.
13986          Skip their other children.  */
13987       if (!load_all
13988           && cu->language == language_cplus
13989           && parent_die != NULL
13990           && parent_die->tag == DW_TAG_subprogram)
13991         {
13992           info_ptr = skip_one_die (reader, info_ptr + bytes_read, abbrev);
13993           continue;
13994         }
13995
13996       /* Check whether this DIE is interesting enough to save.  Normally
13997          we would not be interested in members here, but there may be
13998          later variables referencing them via DW_AT_specification (for
13999          static members).  */
14000       if (!load_all
14001           && !is_type_tag_for_partial (abbrev->tag)
14002           && abbrev->tag != DW_TAG_constant
14003           && abbrev->tag != DW_TAG_enumerator
14004           && abbrev->tag != DW_TAG_subprogram
14005           && abbrev->tag != DW_TAG_lexical_block
14006           && abbrev->tag != DW_TAG_variable
14007           && abbrev->tag != DW_TAG_namespace
14008           && abbrev->tag != DW_TAG_module
14009           && abbrev->tag != DW_TAG_member
14010           && abbrev->tag != DW_TAG_imported_unit)
14011         {
14012           /* Otherwise we skip to the next sibling, if any.  */
14013           info_ptr = skip_one_die (reader, info_ptr + bytes_read, abbrev);
14014           continue;
14015         }
14016
14017       info_ptr = read_partial_die (reader, part_die, abbrev, bytes_read,
14018                                    info_ptr);
14019
14020       /* This two-pass algorithm for processing partial symbols has a
14021          high cost in cache pressure.  Thus, handle some simple cases
14022          here which cover the majority of C partial symbols.  DIEs
14023          which neither have specification tags in them, nor could have
14024          specification tags elsewhere pointing at them, can simply be
14025          processed and discarded.
14026
14027          This segment is also optional; scan_partial_symbols and
14028          add_partial_symbol will handle these DIEs if we chain
14029          them in normally.  When compilers which do not emit large
14030          quantities of duplicate debug information are more common,
14031          this code can probably be removed.  */
14032
14033       /* Any complete simple types at the top level (pretty much all
14034          of them, for a language without namespaces), can be processed
14035          directly.  */
14036       if (parent_die == NULL
14037           && part_die->has_specification == 0
14038           && part_die->is_declaration == 0
14039           && ((part_die->tag == DW_TAG_typedef && !part_die->has_children)
14040               || part_die->tag == DW_TAG_base_type
14041               || part_die->tag == DW_TAG_subrange_type))
14042         {
14043           if (building_psymtab && part_die->name != NULL)
14044             add_psymbol_to_list (part_die->name, strlen (part_die->name), 0,
14045                                  VAR_DOMAIN, LOC_TYPEDEF,
14046                                  &objfile->static_psymbols,
14047                                  0, (CORE_ADDR) 0, cu->language, objfile);
14048           info_ptr = locate_pdi_sibling (reader, part_die, info_ptr);
14049           continue;
14050         }
14051
14052       /* The exception for DW_TAG_typedef with has_children above is
14053          a workaround of GCC PR debug/47510.  In the case of this complaint
14054          type_name_no_tag_or_error will error on such types later.
14055
14056          GDB skipped children of DW_TAG_typedef by the shortcut above and then
14057          it could not find the child DIEs referenced later, this is checked
14058          above.  In correct DWARF DW_TAG_typedef should have no children.  */
14059
14060       if (part_die->tag == DW_TAG_typedef && part_die->has_children)
14061         complaint (&symfile_complaints,
14062                    _("DW_TAG_typedef has childen - GCC PR debug/47510 bug "
14063                      "- DIE at 0x%x [in module %s]"),
14064                    part_die->offset.sect_off, objfile->name);
14065
14066       /* If we're at the second level, and we're an enumerator, and
14067          our parent has no specification (meaning possibly lives in a
14068          namespace elsewhere), then we can add the partial symbol now
14069          instead of queueing it.  */
14070       if (part_die->tag == DW_TAG_enumerator
14071           && parent_die != NULL
14072           && parent_die->die_parent == NULL
14073           && parent_die->tag == DW_TAG_enumeration_type
14074           && parent_die->has_specification == 0)
14075         {
14076           if (part_die->name == NULL)
14077             complaint (&symfile_complaints,
14078                        _("malformed enumerator DIE ignored"));
14079           else if (building_psymtab)
14080             add_psymbol_to_list (part_die->name, strlen (part_die->name), 0,
14081                                  VAR_DOMAIN, LOC_CONST,
14082                                  (cu->language == language_cplus
14083                                   || cu->language == language_java)
14084                                  ? &objfile->global_psymbols
14085                                  : &objfile->static_psymbols,
14086                                  0, (CORE_ADDR) 0, cu->language, objfile);
14087
14088           info_ptr = locate_pdi_sibling (reader, part_die, info_ptr);
14089           continue;
14090         }
14091
14092       /* We'll save this DIE so link it in.  */
14093       part_die->die_parent = parent_die;
14094       part_die->die_sibling = NULL;
14095       part_die->die_child = NULL;
14096
14097       if (last_die && last_die == parent_die)
14098         last_die->die_child = part_die;
14099       else if (last_die)
14100         last_die->die_sibling = part_die;
14101
14102       last_die = part_die;
14103
14104       if (first_die == NULL)
14105         first_die = part_die;
14106
14107       /* Maybe add the DIE to the hash table.  Not all DIEs that we
14108          find interesting need to be in the hash table, because we
14109          also have the parent/sibling/child chains; only those that we
14110          might refer to by offset later during partial symbol reading.
14111
14112          For now this means things that might have be the target of a
14113          DW_AT_specification, DW_AT_abstract_origin, or
14114          DW_AT_extension.  DW_AT_extension will refer only to
14115          namespaces; DW_AT_abstract_origin refers to functions (and
14116          many things under the function DIE, but we do not recurse
14117          into function DIEs during partial symbol reading) and
14118          possibly variables as well; DW_AT_specification refers to
14119          declarations.  Declarations ought to have the DW_AT_declaration
14120          flag.  It happens that GCC forgets to put it in sometimes, but
14121          only for functions, not for types.
14122
14123          Adding more things than necessary to the hash table is harmless
14124          except for the performance cost.  Adding too few will result in
14125          wasted time in find_partial_die, when we reread the compilation
14126          unit with load_all_dies set.  */
14127
14128       if (load_all
14129           || abbrev->tag == DW_TAG_constant
14130           || abbrev->tag == DW_TAG_subprogram
14131           || abbrev->tag == DW_TAG_variable
14132           || abbrev->tag == DW_TAG_namespace
14133           || part_die->is_declaration)
14134         {
14135           void **slot;
14136
14137           slot = htab_find_slot_with_hash (cu->partial_dies, part_die,
14138                                            part_die->offset.sect_off, INSERT);
14139           *slot = part_die;
14140         }
14141
14142       part_die = obstack_alloc (&cu->comp_unit_obstack,
14143                                 sizeof (struct partial_die_info));
14144
14145       /* For some DIEs we want to follow their children (if any).  For C
14146          we have no reason to follow the children of structures; for other
14147          languages we have to, so that we can get at method physnames
14148          to infer fully qualified class names, for DW_AT_specification,
14149          and for C++ template arguments.  For C++, we also look one level
14150          inside functions to find template arguments (if the name of the
14151          function does not already contain the template arguments).
14152
14153          For Ada, we need to scan the children of subprograms and lexical
14154          blocks as well because Ada allows the definition of nested
14155          entities that could be interesting for the debugger, such as
14156          nested subprograms for instance.  */
14157       if (last_die->has_children
14158           && (load_all
14159               || last_die->tag == DW_TAG_namespace
14160               || last_die->tag == DW_TAG_module
14161               || last_die->tag == DW_TAG_enumeration_type
14162               || (cu->language == language_cplus
14163                   && last_die->tag == DW_TAG_subprogram
14164                   && (last_die->name == NULL
14165                       || strchr (last_die->name, '<') == NULL))
14166               || (cu->language != language_c
14167                   && (last_die->tag == DW_TAG_class_type
14168                       || last_die->tag == DW_TAG_interface_type
14169                       || last_die->tag == DW_TAG_structure_type
14170                       || last_die->tag == DW_TAG_union_type))
14171               || (cu->language == language_ada
14172                   && (last_die->tag == DW_TAG_subprogram
14173                       || last_die->tag == DW_TAG_lexical_block))))
14174         {
14175           nesting_level++;
14176           parent_die = last_die;
14177           continue;
14178         }
14179
14180       /* Otherwise we skip to the next sibling, if any.  */
14181       info_ptr = locate_pdi_sibling (reader, last_die, info_ptr);
14182
14183       /* Back to the top, do it again.  */
14184     }
14185 }
14186
14187 /* Read a minimal amount of information into the minimal die structure.  */
14188
14189 static const gdb_byte *
14190 read_partial_die (const struct die_reader_specs *reader,
14191                   struct partial_die_info *part_die,
14192                   struct abbrev_info *abbrev, unsigned int abbrev_len,
14193                   const gdb_byte *info_ptr)
14194 {
14195   struct dwarf2_cu *cu = reader->cu;
14196   struct objfile *objfile = cu->objfile;
14197   const gdb_byte *buffer = reader->buffer;
14198   unsigned int i;
14199   struct attribute attr;
14200   int has_low_pc_attr = 0;
14201   int has_high_pc_attr = 0;
14202   int high_pc_relative = 0;
14203
14204   memset (part_die, 0, sizeof (struct partial_die_info));
14205
14206   part_die->offset.sect_off = info_ptr - buffer;
14207
14208   info_ptr += abbrev_len;
14209
14210   if (abbrev == NULL)
14211     return info_ptr;
14212
14213   part_die->tag = abbrev->tag;
14214   part_die->has_children = abbrev->has_children;
14215
14216   for (i = 0; i < abbrev->num_attrs; ++i)
14217     {
14218       info_ptr = read_attribute (reader, &attr, &abbrev->attrs[i], info_ptr);
14219
14220       /* Store the data if it is of an attribute we want to keep in a
14221          partial symbol table.  */
14222       switch (attr.name)
14223         {
14224         case DW_AT_name:
14225           switch (part_die->tag)
14226             {
14227             case DW_TAG_compile_unit:
14228             case DW_TAG_partial_unit:
14229             case DW_TAG_type_unit:
14230               /* Compilation units have a DW_AT_name that is a filename, not
14231                  a source language identifier.  */
14232             case DW_TAG_enumeration_type:
14233             case DW_TAG_enumerator:
14234               /* These tags always have simple identifiers already; no need
14235                  to canonicalize them.  */
14236               part_die->name = DW_STRING (&attr);
14237               break;
14238             default:
14239               part_die->name
14240                 = dwarf2_canonicalize_name (DW_STRING (&attr), cu,
14241                                             &objfile->objfile_obstack);
14242               break;
14243             }
14244           break;
14245         case DW_AT_linkage_name:
14246         case DW_AT_MIPS_linkage_name:
14247           /* Note that both forms of linkage name might appear.  We
14248              assume they will be the same, and we only store the last
14249              one we see.  */
14250           if (cu->language == language_ada)
14251             part_die->name = DW_STRING (&attr);
14252           part_die->linkage_name = DW_STRING (&attr);
14253           break;
14254         case DW_AT_low_pc:
14255           has_low_pc_attr = 1;
14256           part_die->lowpc = DW_ADDR (&attr);
14257           break;
14258         case DW_AT_high_pc:
14259           has_high_pc_attr = 1;
14260           if (attr.form == DW_FORM_addr
14261               || attr.form == DW_FORM_GNU_addr_index)
14262             part_die->highpc = DW_ADDR (&attr);
14263           else
14264             {
14265               high_pc_relative = 1;
14266               part_die->highpc = DW_UNSND (&attr);
14267             }
14268           break;
14269         case DW_AT_location:
14270           /* Support the .debug_loc offsets.  */
14271           if (attr_form_is_block (&attr))
14272             {
14273                part_die->d.locdesc = DW_BLOCK (&attr);
14274             }
14275           else if (attr_form_is_section_offset (&attr))
14276             {
14277               dwarf2_complex_location_expr_complaint ();
14278             }
14279           else
14280             {
14281               dwarf2_invalid_attrib_class_complaint ("DW_AT_location",
14282                                                      "partial symbol information");
14283             }
14284           break;
14285         case DW_AT_external:
14286           part_die->is_external = DW_UNSND (&attr);
14287           break;
14288         case DW_AT_declaration:
14289           part_die->is_declaration = DW_UNSND (&attr);
14290           break;
14291         case DW_AT_type:
14292           part_die->has_type = 1;
14293           break;
14294         case DW_AT_abstract_origin:
14295         case DW_AT_specification:
14296         case DW_AT_extension:
14297           part_die->has_specification = 1;
14298           part_die->spec_offset = dwarf2_get_ref_die_offset (&attr);
14299           part_die->spec_is_dwz = (attr.form == DW_FORM_GNU_ref_alt
14300                                    || cu->per_cu->is_dwz);
14301           break;
14302         case DW_AT_sibling:
14303           /* Ignore absolute siblings, they might point outside of
14304              the current compile unit.  */
14305           if (attr.form == DW_FORM_ref_addr)
14306             complaint (&symfile_complaints,
14307                        _("ignoring absolute DW_AT_sibling"));
14308           else
14309             part_die->sibling = buffer + dwarf2_get_ref_die_offset (&attr).sect_off;
14310           break;
14311         case DW_AT_byte_size:
14312           part_die->has_byte_size = 1;
14313           break;
14314         case DW_AT_calling_convention:
14315           /* DWARF doesn't provide a way to identify a program's source-level
14316              entry point.  DW_AT_calling_convention attributes are only meant
14317              to describe functions' calling conventions.
14318
14319              However, because it's a necessary piece of information in
14320              Fortran, and because DW_CC_program is the only piece of debugging
14321              information whose definition refers to a 'main program' at all,
14322              several compilers have begun marking Fortran main programs with
14323              DW_CC_program --- even when those functions use the standard
14324              calling conventions.
14325
14326              So until DWARF specifies a way to provide this information and
14327              compilers pick up the new representation, we'll support this
14328              practice.  */
14329           if (DW_UNSND (&attr) == DW_CC_program
14330               && cu->language == language_fortran)
14331             {
14332               set_main_name (part_die->name);
14333
14334               /* As this DIE has a static linkage the name would be difficult
14335                  to look up later.  */
14336               language_of_main = language_fortran;
14337             }
14338           break;
14339         case DW_AT_inline:
14340           if (DW_UNSND (&attr) == DW_INL_inlined
14341               || DW_UNSND (&attr) == DW_INL_declared_inlined)
14342             part_die->may_be_inlined = 1;
14343           break;
14344
14345         case DW_AT_import:
14346           if (part_die->tag == DW_TAG_imported_unit)
14347             {
14348               part_die->d.offset = dwarf2_get_ref_die_offset (&attr);
14349               part_die->is_dwz = (attr.form == DW_FORM_GNU_ref_alt
14350                                   || cu->per_cu->is_dwz);
14351             }
14352           break;
14353
14354         default:
14355           break;
14356         }
14357     }
14358
14359   if (high_pc_relative)
14360     part_die->highpc += part_die->lowpc;
14361
14362   if (has_low_pc_attr && has_high_pc_attr)
14363     {
14364       /* When using the GNU linker, .gnu.linkonce. sections are used to
14365          eliminate duplicate copies of functions and vtables and such.
14366          The linker will arbitrarily choose one and discard the others.
14367          The AT_*_pc values for such functions refer to local labels in
14368          these sections.  If the section from that file was discarded, the
14369          labels are not in the output, so the relocs get a value of 0.
14370          If this is a discarded function, mark the pc bounds as invalid,
14371          so that GDB will ignore it.  */
14372       if (part_die->lowpc == 0 && !dwarf2_per_objfile->has_section_at_zero)
14373         {
14374           struct gdbarch *gdbarch = get_objfile_arch (objfile);
14375
14376           complaint (&symfile_complaints,
14377                      _("DW_AT_low_pc %s is zero "
14378                        "for DIE at 0x%x [in module %s]"),
14379                      paddress (gdbarch, part_die->lowpc),
14380                      part_die->offset.sect_off, objfile->name);
14381         }
14382       /* dwarf2_get_pc_bounds has also the strict low < high requirement.  */
14383       else if (part_die->lowpc >= part_die->highpc)
14384         {
14385           struct gdbarch *gdbarch = get_objfile_arch (objfile);
14386
14387           complaint (&symfile_complaints,
14388                      _("DW_AT_low_pc %s is not < DW_AT_high_pc %s "
14389                        "for DIE at 0x%x [in module %s]"),
14390                      paddress (gdbarch, part_die->lowpc),
14391                      paddress (gdbarch, part_die->highpc),
14392                      part_die->offset.sect_off, objfile->name);
14393         }
14394       else
14395         part_die->has_pc_info = 1;
14396     }
14397
14398   return info_ptr;
14399 }
14400
14401 /* Find a cached partial DIE at OFFSET in CU.  */
14402
14403 static struct partial_die_info *
14404 find_partial_die_in_comp_unit (sect_offset offset, struct dwarf2_cu *cu)
14405 {
14406   struct partial_die_info *lookup_die = NULL;
14407   struct partial_die_info part_die;
14408
14409   part_die.offset = offset;
14410   lookup_die = htab_find_with_hash (cu->partial_dies, &part_die,
14411                                     offset.sect_off);
14412
14413   return lookup_die;
14414 }
14415
14416 /* Find a partial DIE at OFFSET, which may or may not be in CU,
14417    except in the case of .debug_types DIEs which do not reference
14418    outside their CU (they do however referencing other types via
14419    DW_FORM_ref_sig8).  */
14420
14421 static struct partial_die_info *
14422 find_partial_die (sect_offset offset, int offset_in_dwz, struct dwarf2_cu *cu)
14423 {
14424   struct objfile *objfile = cu->objfile;
14425   struct dwarf2_per_cu_data *per_cu = NULL;
14426   struct partial_die_info *pd = NULL;
14427
14428   if (offset_in_dwz == cu->per_cu->is_dwz
14429       && offset_in_cu_p (&cu->header, offset))
14430     {
14431       pd = find_partial_die_in_comp_unit (offset, cu);
14432       if (pd != NULL)
14433         return pd;
14434       /* We missed recording what we needed.
14435          Load all dies and try again.  */
14436       per_cu = cu->per_cu;
14437     }
14438   else
14439     {
14440       /* TUs don't reference other CUs/TUs (except via type signatures).  */
14441       if (cu->per_cu->is_debug_types)
14442         {
14443           error (_("Dwarf Error: Type Unit at offset 0x%lx contains"
14444                    " external reference to offset 0x%lx [in module %s].\n"),
14445                  (long) cu->header.offset.sect_off, (long) offset.sect_off,
14446                  bfd_get_filename (objfile->obfd));
14447         }
14448       per_cu = dwarf2_find_containing_comp_unit (offset, offset_in_dwz,
14449                                                  objfile);
14450
14451       if (per_cu->cu == NULL || per_cu->cu->partial_dies == NULL)
14452         load_partial_comp_unit (per_cu);
14453
14454       per_cu->cu->last_used = 0;
14455       pd = find_partial_die_in_comp_unit (offset, per_cu->cu);
14456     }
14457
14458   /* If we didn't find it, and not all dies have been loaded,
14459      load them all and try again.  */
14460
14461   if (pd == NULL && per_cu->load_all_dies == 0)
14462     {
14463       per_cu->load_all_dies = 1;
14464
14465       /* This is nasty.  When we reread the DIEs, somewhere up the call chain
14466          THIS_CU->cu may already be in use.  So we can't just free it and
14467          replace its DIEs with the ones we read in.  Instead, we leave those
14468          DIEs alone (which can still be in use, e.g. in scan_partial_symbols),
14469          and clobber THIS_CU->cu->partial_dies with the hash table for the new
14470          set.  */
14471       load_partial_comp_unit (per_cu);
14472
14473       pd = find_partial_die_in_comp_unit (offset, per_cu->cu);
14474     }
14475
14476   if (pd == NULL)
14477     internal_error (__FILE__, __LINE__,
14478                     _("could not find partial DIE 0x%x "
14479                       "in cache [from module %s]\n"),
14480                     offset.sect_off, bfd_get_filename (objfile->obfd));
14481   return pd;
14482 }
14483
14484 /* See if we can figure out if the class lives in a namespace.  We do
14485    this by looking for a member function; its demangled name will
14486    contain namespace info, if there is any.  */
14487
14488 static void
14489 guess_partial_die_structure_name (struct partial_die_info *struct_pdi,
14490                                   struct dwarf2_cu *cu)
14491 {
14492   /* NOTE: carlton/2003-10-07: Getting the info this way changes
14493      what template types look like, because the demangler
14494      frequently doesn't give the same name as the debug info.  We
14495      could fix this by only using the demangled name to get the
14496      prefix (but see comment in read_structure_type).  */
14497
14498   struct partial_die_info *real_pdi;
14499   struct partial_die_info *child_pdi;
14500
14501   /* If this DIE (this DIE's specification, if any) has a parent, then
14502      we should not do this.  We'll prepend the parent's fully qualified
14503      name when we create the partial symbol.  */
14504
14505   real_pdi = struct_pdi;
14506   while (real_pdi->has_specification)
14507     real_pdi = find_partial_die (real_pdi->spec_offset,
14508                                  real_pdi->spec_is_dwz, cu);
14509
14510   if (real_pdi->die_parent != NULL)
14511     return;
14512
14513   for (child_pdi = struct_pdi->die_child;
14514        child_pdi != NULL;
14515        child_pdi = child_pdi->die_sibling)
14516     {
14517       if (child_pdi->tag == DW_TAG_subprogram
14518           && child_pdi->linkage_name != NULL)
14519         {
14520           char *actual_class_name
14521             = language_class_name_from_physname (cu->language_defn,
14522                                                  child_pdi->linkage_name);
14523           if (actual_class_name != NULL)
14524             {
14525               struct_pdi->name
14526                 = obstack_copy0 (&cu->objfile->objfile_obstack,
14527                                  actual_class_name,
14528                                  strlen (actual_class_name));
14529               xfree (actual_class_name);
14530             }
14531           break;
14532         }
14533     }
14534 }
14535
14536 /* Adjust PART_DIE before generating a symbol for it.  This function
14537    may set the is_external flag or change the DIE's name.  */
14538
14539 static void
14540 fixup_partial_die (struct partial_die_info *part_die,
14541                    struct dwarf2_cu *cu)
14542 {
14543   /* Once we've fixed up a die, there's no point in doing so again.
14544      This also avoids a memory leak if we were to call
14545      guess_partial_die_structure_name multiple times.  */
14546   if (part_die->fixup_called)
14547     return;
14548
14549   /* If we found a reference attribute and the DIE has no name, try
14550      to find a name in the referred to DIE.  */
14551
14552   if (part_die->name == NULL && part_die->has_specification)
14553     {
14554       struct partial_die_info *spec_die;
14555
14556       spec_die = find_partial_die (part_die->spec_offset,
14557                                    part_die->spec_is_dwz, cu);
14558
14559       fixup_partial_die (spec_die, cu);
14560
14561       if (spec_die->name)
14562         {
14563           part_die->name = spec_die->name;
14564
14565           /* Copy DW_AT_external attribute if it is set.  */
14566           if (spec_die->is_external)
14567             part_die->is_external = spec_die->is_external;
14568         }
14569     }
14570
14571   /* Set default names for some unnamed DIEs.  */
14572
14573   if (part_die->name == NULL && part_die->tag == DW_TAG_namespace)
14574     part_die->name = CP_ANONYMOUS_NAMESPACE_STR;
14575
14576   /* If there is no parent die to provide a namespace, and there are
14577      children, see if we can determine the namespace from their linkage
14578      name.  */
14579   if (cu->language == language_cplus
14580       && !VEC_empty (dwarf2_section_info_def, dwarf2_per_objfile->types)
14581       && part_die->die_parent == NULL
14582       && part_die->has_children
14583       && (part_die->tag == DW_TAG_class_type
14584           || part_die->tag == DW_TAG_structure_type
14585           || part_die->tag == DW_TAG_union_type))
14586     guess_partial_die_structure_name (part_die, cu);
14587
14588   /* GCC might emit a nameless struct or union that has a linkage
14589      name.  See http://gcc.gnu.org/bugzilla/show_bug.cgi?id=47510.  */
14590   if (part_die->name == NULL
14591       && (part_die->tag == DW_TAG_class_type
14592           || part_die->tag == DW_TAG_interface_type
14593           || part_die->tag == DW_TAG_structure_type
14594           || part_die->tag == DW_TAG_union_type)
14595       && part_die->linkage_name != NULL)
14596     {
14597       char *demangled;
14598
14599       demangled = gdb_demangle (part_die->linkage_name, DMGL_TYPES);
14600       if (demangled)
14601         {
14602           const char *base;
14603
14604           /* Strip any leading namespaces/classes, keep only the base name.
14605              DW_AT_name for named DIEs does not contain the prefixes.  */
14606           base = strrchr (demangled, ':');
14607           if (base && base > demangled && base[-1] == ':')
14608             base++;
14609           else
14610             base = demangled;
14611
14612           part_die->name = obstack_copy0 (&cu->objfile->objfile_obstack,
14613                                           base, strlen (base));
14614           xfree (demangled);
14615         }
14616     }
14617
14618   part_die->fixup_called = 1;
14619 }
14620
14621 /* Read an attribute value described by an attribute form.  */
14622
14623 static const gdb_byte *
14624 read_attribute_value (const struct die_reader_specs *reader,
14625                       struct attribute *attr, unsigned form,
14626                       const gdb_byte *info_ptr)
14627 {
14628   struct dwarf2_cu *cu = reader->cu;
14629   bfd *abfd = reader->abfd;
14630   struct comp_unit_head *cu_header = &cu->header;
14631   unsigned int bytes_read;
14632   struct dwarf_block *blk;
14633
14634   attr->form = form;
14635   switch (form)
14636     {
14637     case DW_FORM_ref_addr:
14638       if (cu->header.version == 2)
14639         DW_UNSND (attr) = read_address (abfd, info_ptr, cu, &bytes_read);
14640       else
14641         DW_UNSND (attr) = read_offset (abfd, info_ptr,
14642                                        &cu->header, &bytes_read);
14643       info_ptr += bytes_read;
14644       break;
14645     case DW_FORM_GNU_ref_alt:
14646       DW_UNSND (attr) = read_offset (abfd, info_ptr, &cu->header, &bytes_read);
14647       info_ptr += bytes_read;
14648       break;
14649     case DW_FORM_addr:
14650       DW_ADDR (attr) = read_address (abfd, info_ptr, cu, &bytes_read);
14651       info_ptr += bytes_read;
14652       break;
14653     case DW_FORM_block2:
14654       blk = dwarf_alloc_block (cu);
14655       blk->size = read_2_bytes (abfd, info_ptr);
14656       info_ptr += 2;
14657       blk->data = read_n_bytes (abfd, info_ptr, blk->size);
14658       info_ptr += blk->size;
14659       DW_BLOCK (attr) = blk;
14660       break;
14661     case DW_FORM_block4:
14662       blk = dwarf_alloc_block (cu);
14663       blk->size = read_4_bytes (abfd, info_ptr);
14664       info_ptr += 4;
14665       blk->data = read_n_bytes (abfd, info_ptr, blk->size);
14666       info_ptr += blk->size;
14667       DW_BLOCK (attr) = blk;
14668       break;
14669     case DW_FORM_data2:
14670       DW_UNSND (attr) = read_2_bytes (abfd, info_ptr);
14671       info_ptr += 2;
14672       break;
14673     case DW_FORM_data4:
14674       DW_UNSND (attr) = read_4_bytes (abfd, info_ptr);
14675       info_ptr += 4;
14676       break;
14677     case DW_FORM_data8:
14678       DW_UNSND (attr) = read_8_bytes (abfd, info_ptr);
14679       info_ptr += 8;
14680       break;
14681     case DW_FORM_sec_offset:
14682       DW_UNSND (attr) = read_offset (abfd, info_ptr, &cu->header, &bytes_read);
14683       info_ptr += bytes_read;
14684       break;
14685     case DW_FORM_string:
14686       DW_STRING (attr) = read_direct_string (abfd, info_ptr, &bytes_read);
14687       DW_STRING_IS_CANONICAL (attr) = 0;
14688       info_ptr += bytes_read;
14689       break;
14690     case DW_FORM_strp:
14691       if (!cu->per_cu->is_dwz)
14692         {
14693           DW_STRING (attr) = read_indirect_string (abfd, info_ptr, cu_header,
14694                                                    &bytes_read);
14695           DW_STRING_IS_CANONICAL (attr) = 0;
14696           info_ptr += bytes_read;
14697           break;
14698         }
14699       /* FALLTHROUGH */
14700     case DW_FORM_GNU_strp_alt:
14701       {
14702         struct dwz_file *dwz = dwarf2_get_dwz_file ();
14703         LONGEST str_offset = read_offset (abfd, info_ptr, cu_header,
14704                                           &bytes_read);
14705
14706         DW_STRING (attr) = read_indirect_string_from_dwz (dwz, str_offset);
14707         DW_STRING_IS_CANONICAL (attr) = 0;
14708         info_ptr += bytes_read;
14709       }
14710       break;
14711     case DW_FORM_exprloc:
14712     case DW_FORM_block:
14713       blk = dwarf_alloc_block (cu);
14714       blk->size = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
14715       info_ptr += bytes_read;
14716       blk->data = read_n_bytes (abfd, info_ptr, blk->size);
14717       info_ptr += blk->size;
14718       DW_BLOCK (attr) = blk;
14719       break;
14720     case DW_FORM_block1:
14721       blk = dwarf_alloc_block (cu);
14722       blk->size = read_1_byte (abfd, info_ptr);
14723       info_ptr += 1;
14724       blk->data = read_n_bytes (abfd, info_ptr, blk->size);
14725       info_ptr += blk->size;
14726       DW_BLOCK (attr) = blk;
14727       break;
14728     case DW_FORM_data1:
14729       DW_UNSND (attr) = read_1_byte (abfd, info_ptr);
14730       info_ptr += 1;
14731       break;
14732     case DW_FORM_flag:
14733       DW_UNSND (attr) = read_1_byte (abfd, info_ptr);
14734       info_ptr += 1;
14735       break;
14736     case DW_FORM_flag_present:
14737       DW_UNSND (attr) = 1;
14738       break;
14739     case DW_FORM_sdata:
14740       DW_SND (attr) = read_signed_leb128 (abfd, info_ptr, &bytes_read);
14741       info_ptr += bytes_read;
14742       break;
14743     case DW_FORM_udata:
14744       DW_UNSND (attr) = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
14745       info_ptr += bytes_read;
14746       break;
14747     case DW_FORM_ref1:
14748       DW_UNSND (attr) = (cu->header.offset.sect_off
14749                          + read_1_byte (abfd, info_ptr));
14750       info_ptr += 1;
14751       break;
14752     case DW_FORM_ref2:
14753       DW_UNSND (attr) = (cu->header.offset.sect_off
14754                          + read_2_bytes (abfd, info_ptr));
14755       info_ptr += 2;
14756       break;
14757     case DW_FORM_ref4:
14758       DW_UNSND (attr) = (cu->header.offset.sect_off
14759                          + read_4_bytes (abfd, info_ptr));
14760       info_ptr += 4;
14761       break;
14762     case DW_FORM_ref8:
14763       DW_UNSND (attr) = (cu->header.offset.sect_off
14764                          + read_8_bytes (abfd, info_ptr));
14765       info_ptr += 8;
14766       break;
14767     case DW_FORM_ref_sig8:
14768       DW_SIGNATURE (attr) = read_8_bytes (abfd, info_ptr);
14769       info_ptr += 8;
14770       break;
14771     case DW_FORM_ref_udata:
14772       DW_UNSND (attr) = (cu->header.offset.sect_off
14773                          + read_unsigned_leb128 (abfd, info_ptr, &bytes_read));
14774       info_ptr += bytes_read;
14775       break;
14776     case DW_FORM_indirect:
14777       form = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
14778       info_ptr += bytes_read;
14779       info_ptr = read_attribute_value (reader, attr, form, info_ptr);
14780       break;
14781     case DW_FORM_GNU_addr_index:
14782       if (reader->dwo_file == NULL)
14783         {
14784           /* For now flag a hard error.
14785              Later we can turn this into a complaint.  */
14786           error (_("Dwarf Error: %s found in non-DWO CU [in module %s]"),
14787                  dwarf_form_name (form),
14788                  bfd_get_filename (abfd));
14789         }
14790       DW_ADDR (attr) = read_addr_index_from_leb128 (cu, info_ptr, &bytes_read);
14791       info_ptr += bytes_read;
14792       break;
14793     case DW_FORM_GNU_str_index:
14794       if (reader->dwo_file == NULL)
14795         {
14796           /* For now flag a hard error.
14797              Later we can turn this into a complaint if warranted.  */
14798           error (_("Dwarf Error: %s found in non-DWO CU [in module %s]"),
14799                  dwarf_form_name (form),
14800                  bfd_get_filename (abfd));
14801         }
14802       {
14803         ULONGEST str_index =
14804           read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
14805
14806         DW_STRING (attr) = read_str_index (reader, cu, str_index);
14807         DW_STRING_IS_CANONICAL (attr) = 0;
14808         info_ptr += bytes_read;
14809       }
14810       break;
14811     default:
14812       error (_("Dwarf Error: Cannot handle %s in DWARF reader [in module %s]"),
14813              dwarf_form_name (form),
14814              bfd_get_filename (abfd));
14815     }
14816
14817   /* Super hack.  */
14818   if (cu->per_cu->is_dwz && is_ref_attr (attr))
14819     attr->form = DW_FORM_GNU_ref_alt;
14820
14821   /* We have seen instances where the compiler tried to emit a byte
14822      size attribute of -1 which ended up being encoded as an unsigned
14823      0xffffffff.  Although 0xffffffff is technically a valid size value,
14824      an object of this size seems pretty unlikely so we can relatively
14825      safely treat these cases as if the size attribute was invalid and
14826      treat them as zero by default.  */
14827   if (attr->name == DW_AT_byte_size
14828       && form == DW_FORM_data4
14829       && DW_UNSND (attr) >= 0xffffffff)
14830     {
14831       complaint
14832         (&symfile_complaints,
14833          _("Suspicious DW_AT_byte_size value treated as zero instead of %s"),
14834          hex_string (DW_UNSND (attr)));
14835       DW_UNSND (attr) = 0;
14836     }
14837
14838   return info_ptr;
14839 }
14840
14841 /* Read an attribute described by an abbreviated attribute.  */
14842
14843 static const gdb_byte *
14844 read_attribute (const struct die_reader_specs *reader,
14845                 struct attribute *attr, struct attr_abbrev *abbrev,
14846                 const gdb_byte *info_ptr)
14847 {
14848   attr->name = abbrev->name;
14849   return read_attribute_value (reader, attr, abbrev->form, info_ptr);
14850 }
14851
14852 /* Read dwarf information from a buffer.  */
14853
14854 static unsigned int
14855 read_1_byte (bfd *abfd, const gdb_byte *buf)
14856 {
14857   return bfd_get_8 (abfd, buf);
14858 }
14859
14860 static int
14861 read_1_signed_byte (bfd *abfd, const gdb_byte *buf)
14862 {
14863   return bfd_get_signed_8 (abfd, buf);
14864 }
14865
14866 static unsigned int
14867 read_2_bytes (bfd *abfd, const gdb_byte *buf)
14868 {
14869   return bfd_get_16 (abfd, buf);
14870 }
14871
14872 static int
14873 read_2_signed_bytes (bfd *abfd, const gdb_byte *buf)
14874 {
14875   return bfd_get_signed_16 (abfd, buf);
14876 }
14877
14878 static unsigned int
14879 read_4_bytes (bfd *abfd, const gdb_byte *buf)
14880 {
14881   return bfd_get_32 (abfd, buf);
14882 }
14883
14884 static int
14885 read_4_signed_bytes (bfd *abfd, const gdb_byte *buf)
14886 {
14887   return bfd_get_signed_32 (abfd, buf);
14888 }
14889
14890 static ULONGEST
14891 read_8_bytes (bfd *abfd, const gdb_byte *buf)
14892 {
14893   return bfd_get_64 (abfd, buf);
14894 }
14895
14896 static CORE_ADDR
14897 read_address (bfd *abfd, const gdb_byte *buf, struct dwarf2_cu *cu,
14898               unsigned int *bytes_read)
14899 {
14900   struct comp_unit_head *cu_header = &cu->header;
14901   CORE_ADDR retval = 0;
14902
14903   if (cu_header->signed_addr_p)
14904     {
14905       switch (cu_header->addr_size)
14906         {
14907         case 2:
14908           retval = bfd_get_signed_16 (abfd, buf);
14909           break;
14910         case 4:
14911           retval = bfd_get_signed_32 (abfd, buf);
14912           break;
14913         case 8:
14914           retval = bfd_get_signed_64 (abfd, buf);
14915           break;
14916         default:
14917           internal_error (__FILE__, __LINE__,
14918                           _("read_address: bad switch, signed [in module %s]"),
14919                           bfd_get_filename (abfd));
14920         }
14921     }
14922   else
14923     {
14924       switch (cu_header->addr_size)
14925         {
14926         case 2:
14927           retval = bfd_get_16 (abfd, buf);
14928           break;
14929         case 4:
14930           retval = bfd_get_32 (abfd, buf);
14931           break;
14932         case 8:
14933           retval = bfd_get_64 (abfd, buf);
14934           break;
14935         default:
14936           internal_error (__FILE__, __LINE__,
14937                           _("read_address: bad switch, "
14938                             "unsigned [in module %s]"),
14939                           bfd_get_filename (abfd));
14940         }
14941     }
14942
14943   *bytes_read = cu_header->addr_size;
14944   return retval;
14945 }
14946
14947 /* Read the initial length from a section.  The (draft) DWARF 3
14948    specification allows the initial length to take up either 4 bytes
14949    or 12 bytes.  If the first 4 bytes are 0xffffffff, then the next 8
14950    bytes describe the length and all offsets will be 8 bytes in length
14951    instead of 4.
14952
14953    An older, non-standard 64-bit format is also handled by this
14954    function.  The older format in question stores the initial length
14955    as an 8-byte quantity without an escape value.  Lengths greater
14956    than 2^32 aren't very common which means that the initial 4 bytes
14957    is almost always zero.  Since a length value of zero doesn't make
14958    sense for the 32-bit format, this initial zero can be considered to
14959    be an escape value which indicates the presence of the older 64-bit
14960    format.  As written, the code can't detect (old format) lengths
14961    greater than 4GB.  If it becomes necessary to handle lengths
14962    somewhat larger than 4GB, we could allow other small values (such
14963    as the non-sensical values of 1, 2, and 3) to also be used as
14964    escape values indicating the presence of the old format.
14965
14966    The value returned via bytes_read should be used to increment the
14967    relevant pointer after calling read_initial_length().
14968
14969    [ Note:  read_initial_length() and read_offset() are based on the
14970      document entitled "DWARF Debugging Information Format", revision
14971      3, draft 8, dated November 19, 2001.  This document was obtained
14972      from:
14973
14974         http://reality.sgiweb.org/davea/dwarf3-draft8-011125.pdf
14975
14976      This document is only a draft and is subject to change.  (So beware.)
14977
14978      Details regarding the older, non-standard 64-bit format were
14979      determined empirically by examining 64-bit ELF files produced by
14980      the SGI toolchain on an IRIX 6.5 machine.
14981
14982      - Kevin, July 16, 2002
14983    ] */
14984
14985 static LONGEST
14986 read_initial_length (bfd *abfd, const gdb_byte *buf, unsigned int *bytes_read)
14987 {
14988   LONGEST length = bfd_get_32 (abfd, buf);
14989
14990   if (length == 0xffffffff)
14991     {
14992       length = bfd_get_64 (abfd, buf + 4);
14993       *bytes_read = 12;
14994     }
14995   else if (length == 0)
14996     {
14997       /* Handle the (non-standard) 64-bit DWARF2 format used by IRIX.  */
14998       length = bfd_get_64 (abfd, buf);
14999       *bytes_read = 8;
15000     }
15001   else
15002     {
15003       *bytes_read = 4;
15004     }
15005
15006   return length;
15007 }
15008
15009 /* Cover function for read_initial_length.
15010    Returns the length of the object at BUF, and stores the size of the
15011    initial length in *BYTES_READ and stores the size that offsets will be in
15012    *OFFSET_SIZE.
15013    If the initial length size is not equivalent to that specified in
15014    CU_HEADER then issue a complaint.
15015    This is useful when reading non-comp-unit headers.  */
15016
15017 static LONGEST
15018 read_checked_initial_length_and_offset (bfd *abfd, const gdb_byte *buf,
15019                                         const struct comp_unit_head *cu_header,
15020                                         unsigned int *bytes_read,
15021                                         unsigned int *offset_size)
15022 {
15023   LONGEST length = read_initial_length (abfd, buf, bytes_read);
15024
15025   gdb_assert (cu_header->initial_length_size == 4
15026               || cu_header->initial_length_size == 8
15027               || cu_header->initial_length_size == 12);
15028
15029   if (cu_header->initial_length_size != *bytes_read)
15030     complaint (&symfile_complaints,
15031                _("intermixed 32-bit and 64-bit DWARF sections"));
15032
15033   *offset_size = (*bytes_read == 4) ? 4 : 8;
15034   return length;
15035 }
15036
15037 /* Read an offset from the data stream.  The size of the offset is
15038    given by cu_header->offset_size.  */
15039
15040 static LONGEST
15041 read_offset (bfd *abfd, const gdb_byte *buf,
15042              const struct comp_unit_head *cu_header,
15043              unsigned int *bytes_read)
15044 {
15045   LONGEST offset = read_offset_1 (abfd, buf, cu_header->offset_size);
15046
15047   *bytes_read = cu_header->offset_size;
15048   return offset;
15049 }
15050
15051 /* Read an offset from the data stream.  */
15052
15053 static LONGEST
15054 read_offset_1 (bfd *abfd, const gdb_byte *buf, unsigned int offset_size)
15055 {
15056   LONGEST retval = 0;
15057
15058   switch (offset_size)
15059     {
15060     case 4:
15061       retval = bfd_get_32 (abfd, buf);
15062       break;
15063     case 8:
15064       retval = bfd_get_64 (abfd, buf);
15065       break;
15066     default:
15067       internal_error (__FILE__, __LINE__,
15068                       _("read_offset_1: bad switch [in module %s]"),
15069                       bfd_get_filename (abfd));
15070     }
15071
15072   return retval;
15073 }
15074
15075 static const gdb_byte *
15076 read_n_bytes (bfd *abfd, const gdb_byte *buf, unsigned int size)
15077 {
15078   /* If the size of a host char is 8 bits, we can return a pointer
15079      to the buffer, otherwise we have to copy the data to a buffer
15080      allocated on the temporary obstack.  */
15081   gdb_assert (HOST_CHAR_BIT == 8);
15082   return buf;
15083 }
15084
15085 static const char *
15086 read_direct_string (bfd *abfd, const gdb_byte *buf,
15087                     unsigned int *bytes_read_ptr)
15088 {
15089   /* If the size of a host char is 8 bits, we can return a pointer
15090      to the string, otherwise we have to copy the string to a buffer
15091      allocated on the temporary obstack.  */
15092   gdb_assert (HOST_CHAR_BIT == 8);
15093   if (*buf == '\0')
15094     {
15095       *bytes_read_ptr = 1;
15096       return NULL;
15097     }
15098   *bytes_read_ptr = strlen ((const char *) buf) + 1;
15099   return (const char *) buf;
15100 }
15101
15102 static const char *
15103 read_indirect_string_at_offset (bfd *abfd, LONGEST str_offset)
15104 {
15105   dwarf2_read_section (dwarf2_per_objfile->objfile, &dwarf2_per_objfile->str);
15106   if (dwarf2_per_objfile->str.buffer == NULL)
15107     error (_("DW_FORM_strp used without .debug_str section [in module %s]"),
15108            bfd_get_filename (abfd));
15109   if (str_offset >= dwarf2_per_objfile->str.size)
15110     error (_("DW_FORM_strp pointing outside of "
15111              ".debug_str section [in module %s]"),
15112            bfd_get_filename (abfd));
15113   gdb_assert (HOST_CHAR_BIT == 8);
15114   if (dwarf2_per_objfile->str.buffer[str_offset] == '\0')
15115     return NULL;
15116   return (const char *) (dwarf2_per_objfile->str.buffer + str_offset);
15117 }
15118
15119 /* Read a string at offset STR_OFFSET in the .debug_str section from
15120    the .dwz file DWZ.  Throw an error if the offset is too large.  If
15121    the string consists of a single NUL byte, return NULL; otherwise
15122    return a pointer to the string.  */
15123
15124 static const char *
15125 read_indirect_string_from_dwz (struct dwz_file *dwz, LONGEST str_offset)
15126 {
15127   dwarf2_read_section (dwarf2_per_objfile->objfile, &dwz->str);
15128
15129   if (dwz->str.buffer == NULL)
15130     error (_("DW_FORM_GNU_strp_alt used without .debug_str "
15131              "section [in module %s]"),
15132            bfd_get_filename (dwz->dwz_bfd));
15133   if (str_offset >= dwz->str.size)
15134     error (_("DW_FORM_GNU_strp_alt pointing outside of "
15135              ".debug_str section [in module %s]"),
15136            bfd_get_filename (dwz->dwz_bfd));
15137   gdb_assert (HOST_CHAR_BIT == 8);
15138   if (dwz->str.buffer[str_offset] == '\0')
15139     return NULL;
15140   return (const char *) (dwz->str.buffer + str_offset);
15141 }
15142
15143 static const char *
15144 read_indirect_string (bfd *abfd, const gdb_byte *buf,
15145                       const struct comp_unit_head *cu_header,
15146                       unsigned int *bytes_read_ptr)
15147 {
15148   LONGEST str_offset = read_offset (abfd, buf, cu_header, bytes_read_ptr);
15149
15150   return read_indirect_string_at_offset (abfd, str_offset);
15151 }
15152
15153 static ULONGEST
15154 read_unsigned_leb128 (bfd *abfd, const gdb_byte *buf,
15155                       unsigned int *bytes_read_ptr)
15156 {
15157   ULONGEST result;
15158   unsigned int num_read;
15159   int i, shift;
15160   unsigned char byte;
15161
15162   result = 0;
15163   shift = 0;
15164   num_read = 0;
15165   i = 0;
15166   while (1)
15167     {
15168       byte = bfd_get_8 (abfd, buf);
15169       buf++;
15170       num_read++;
15171       result |= ((ULONGEST) (byte & 127) << shift);
15172       if ((byte & 128) == 0)
15173         {
15174           break;
15175         }
15176       shift += 7;
15177     }
15178   *bytes_read_ptr = num_read;
15179   return result;
15180 }
15181
15182 static LONGEST
15183 read_signed_leb128 (bfd *abfd, const gdb_byte *buf,
15184                     unsigned int *bytes_read_ptr)
15185 {
15186   LONGEST result;
15187   int i, shift, num_read;
15188   unsigned char byte;
15189
15190   result = 0;
15191   shift = 0;
15192   num_read = 0;
15193   i = 0;
15194   while (1)
15195     {
15196       byte = bfd_get_8 (abfd, buf);
15197       buf++;
15198       num_read++;
15199       result |= ((LONGEST) (byte & 127) << shift);
15200       shift += 7;
15201       if ((byte & 128) == 0)
15202         {
15203           break;
15204         }
15205     }
15206   if ((shift < 8 * sizeof (result)) && (byte & 0x40))
15207     result |= -(((LONGEST) 1) << shift);
15208   *bytes_read_ptr = num_read;
15209   return result;
15210 }
15211
15212 /* Given index ADDR_INDEX in .debug_addr, fetch the value.
15213    ADDR_BASE is the DW_AT_GNU_addr_base attribute or zero.
15214    ADDR_SIZE is the size of addresses from the CU header.  */
15215
15216 static CORE_ADDR
15217 read_addr_index_1 (unsigned int addr_index, ULONGEST addr_base, int addr_size)
15218 {
15219   struct objfile *objfile = dwarf2_per_objfile->objfile;
15220   bfd *abfd = objfile->obfd;
15221   const gdb_byte *info_ptr;
15222
15223   dwarf2_read_section (objfile, &dwarf2_per_objfile->addr);
15224   if (dwarf2_per_objfile->addr.buffer == NULL)
15225     error (_("DW_FORM_addr_index used without .debug_addr section [in module %s]"),
15226            objfile->name);
15227   if (addr_base + addr_index * addr_size >= dwarf2_per_objfile->addr.size)
15228     error (_("DW_FORM_addr_index pointing outside of "
15229              ".debug_addr section [in module %s]"),
15230            objfile->name);
15231   info_ptr = (dwarf2_per_objfile->addr.buffer
15232               + addr_base + addr_index * addr_size);
15233   if (addr_size == 4)
15234     return bfd_get_32 (abfd, info_ptr);
15235   else
15236     return bfd_get_64 (abfd, info_ptr);
15237 }
15238
15239 /* Given index ADDR_INDEX in .debug_addr, fetch the value.  */
15240
15241 static CORE_ADDR
15242 read_addr_index (struct dwarf2_cu *cu, unsigned int addr_index)
15243 {
15244   return read_addr_index_1 (addr_index, cu->addr_base, cu->header.addr_size);
15245 }
15246
15247 /* Given a pointer to an leb128 value, fetch the value from .debug_addr.  */
15248
15249 static CORE_ADDR
15250 read_addr_index_from_leb128 (struct dwarf2_cu *cu, const gdb_byte *info_ptr,
15251                              unsigned int *bytes_read)
15252 {
15253   bfd *abfd = cu->objfile->obfd;
15254   unsigned int addr_index = read_unsigned_leb128 (abfd, info_ptr, bytes_read);
15255
15256   return read_addr_index (cu, addr_index);
15257 }
15258
15259 /* Data structure to pass results from dwarf2_read_addr_index_reader
15260    back to dwarf2_read_addr_index.  */
15261
15262 struct dwarf2_read_addr_index_data
15263 {
15264   ULONGEST addr_base;
15265   int addr_size;
15266 };
15267
15268 /* die_reader_func for dwarf2_read_addr_index.  */
15269
15270 static void
15271 dwarf2_read_addr_index_reader (const struct die_reader_specs *reader,
15272                                const gdb_byte *info_ptr,
15273                                struct die_info *comp_unit_die,
15274                                int has_children,
15275                                void *data)
15276 {
15277   struct dwarf2_cu *cu = reader->cu;
15278   struct dwarf2_read_addr_index_data *aidata =
15279     (struct dwarf2_read_addr_index_data *) data;
15280
15281   aidata->addr_base = cu->addr_base;
15282   aidata->addr_size = cu->header.addr_size;
15283 }
15284
15285 /* Given an index in .debug_addr, fetch the value.
15286    NOTE: This can be called during dwarf expression evaluation,
15287    long after the debug information has been read, and thus per_cu->cu
15288    may no longer exist.  */
15289
15290 CORE_ADDR
15291 dwarf2_read_addr_index (struct dwarf2_per_cu_data *per_cu,
15292                         unsigned int addr_index)
15293 {
15294   struct objfile *objfile = per_cu->objfile;
15295   struct dwarf2_cu *cu = per_cu->cu;
15296   ULONGEST addr_base;
15297   int addr_size;
15298
15299   /* This is intended to be called from outside this file.  */
15300   dw2_setup (objfile);
15301
15302   /* We need addr_base and addr_size.
15303      If we don't have PER_CU->cu, we have to get it.
15304      Nasty, but the alternative is storing the needed info in PER_CU,
15305      which at this point doesn't seem justified: it's not clear how frequently
15306      it would get used and it would increase the size of every PER_CU.
15307      Entry points like dwarf2_per_cu_addr_size do a similar thing
15308      so we're not in uncharted territory here.
15309      Alas we need to be a bit more complicated as addr_base is contained
15310      in the DIE.
15311
15312      We don't need to read the entire CU(/TU).
15313      We just need the header and top level die.
15314
15315      IWBN to use the aging mechanism to let us lazily later discard the CU.
15316      For now we skip this optimization.  */
15317
15318   if (cu != NULL)
15319     {
15320       addr_base = cu->addr_base;
15321       addr_size = cu->header.addr_size;
15322     }
15323   else
15324     {
15325       struct dwarf2_read_addr_index_data aidata;
15326
15327       /* Note: We can't use init_cutu_and_read_dies_simple here,
15328          we need addr_base.  */
15329       init_cutu_and_read_dies (per_cu, NULL, 0, 0,
15330                                dwarf2_read_addr_index_reader, &aidata);
15331       addr_base = aidata.addr_base;
15332       addr_size = aidata.addr_size;
15333     }
15334
15335   return read_addr_index_1 (addr_index, addr_base, addr_size);
15336 }
15337
15338 /* Given a DW_AT_str_index, fetch the string.  */
15339
15340 static const char *
15341 read_str_index (const struct die_reader_specs *reader,
15342                 struct dwarf2_cu *cu, ULONGEST str_index)
15343 {
15344   struct objfile *objfile = dwarf2_per_objfile->objfile;
15345   const char *dwo_name = objfile->name;
15346   bfd *abfd = objfile->obfd;
15347   struct dwo_sections *sections = &reader->dwo_file->sections;
15348   const gdb_byte *info_ptr;
15349   ULONGEST str_offset;
15350
15351   dwarf2_read_section (objfile, &sections->str);
15352   dwarf2_read_section (objfile, &sections->str_offsets);
15353   if (sections->str.buffer == NULL)
15354     error (_("DW_FORM_str_index used without .debug_str.dwo section"
15355              " in CU at offset 0x%lx [in module %s]"),
15356            (long) cu->header.offset.sect_off, dwo_name);
15357   if (sections->str_offsets.buffer == NULL)
15358     error (_("DW_FORM_str_index used without .debug_str_offsets.dwo section"
15359              " in CU at offset 0x%lx [in module %s]"),
15360            (long) cu->header.offset.sect_off, dwo_name);
15361   if (str_index * cu->header.offset_size >= sections->str_offsets.size)
15362     error (_("DW_FORM_str_index pointing outside of .debug_str_offsets.dwo"
15363              " section in CU at offset 0x%lx [in module %s]"),
15364            (long) cu->header.offset.sect_off, dwo_name);
15365   info_ptr = (sections->str_offsets.buffer
15366               + str_index * cu->header.offset_size);
15367   if (cu->header.offset_size == 4)
15368     str_offset = bfd_get_32 (abfd, info_ptr);
15369   else
15370     str_offset = bfd_get_64 (abfd, info_ptr);
15371   if (str_offset >= sections->str.size)
15372     error (_("Offset from DW_FORM_str_index pointing outside of"
15373              " .debug_str.dwo section in CU at offset 0x%lx [in module %s]"),
15374            (long) cu->header.offset.sect_off, dwo_name);
15375   return (const char *) (sections->str.buffer + str_offset);
15376 }
15377
15378 /* Return the length of an LEB128 number in BUF.  */
15379
15380 static int
15381 leb128_size (const gdb_byte *buf)
15382 {
15383   const gdb_byte *begin = buf;
15384   gdb_byte byte;
15385
15386   while (1)
15387     {
15388       byte = *buf++;
15389       if ((byte & 128) == 0)
15390         return buf - begin;
15391     }
15392 }
15393
15394 static void
15395 set_cu_language (unsigned int lang, struct dwarf2_cu *cu)
15396 {
15397   switch (lang)
15398     {
15399     case DW_LANG_C89:
15400     case DW_LANG_C99:
15401     case DW_LANG_C:
15402     case DW_LANG_UPC:
15403       cu->language = language_c;
15404       break;
15405     case DW_LANG_C_plus_plus:
15406       cu->language = language_cplus;
15407       break;
15408     case DW_LANG_D:
15409       cu->language = language_d;
15410       break;
15411     case DW_LANG_Fortran77:
15412     case DW_LANG_Fortran90:
15413     case DW_LANG_Fortran95:
15414       cu->language = language_fortran;
15415       break;
15416     case DW_LANG_Go:
15417       cu->language = language_go;
15418       break;
15419     case DW_LANG_Mips_Assembler:
15420       cu->language = language_asm;
15421       break;
15422     case DW_LANG_Java:
15423       cu->language = language_java;
15424       break;
15425     case DW_LANG_Ada83:
15426     case DW_LANG_Ada95:
15427       cu->language = language_ada;
15428       break;
15429     case DW_LANG_Modula2:
15430       cu->language = language_m2;
15431       break;
15432     case DW_LANG_Pascal83:
15433       cu->language = language_pascal;
15434       break;
15435     case DW_LANG_ObjC:
15436       cu->language = language_objc;
15437       break;
15438     case DW_LANG_Cobol74:
15439     case DW_LANG_Cobol85:
15440     default:
15441       cu->language = language_minimal;
15442       break;
15443     }
15444   cu->language_defn = language_def (cu->language);
15445 }
15446
15447 /* Return the named attribute or NULL if not there.  */
15448
15449 static struct attribute *
15450 dwarf2_attr (struct die_info *die, unsigned int name, struct dwarf2_cu *cu)
15451 {
15452   for (;;)
15453     {
15454       unsigned int i;
15455       struct attribute *spec = NULL;
15456
15457       for (i = 0; i < die->num_attrs; ++i)
15458         {
15459           if (die->attrs[i].name == name)
15460             return &die->attrs[i];
15461           if (die->attrs[i].name == DW_AT_specification
15462               || die->attrs[i].name == DW_AT_abstract_origin)
15463             spec = &die->attrs[i];
15464         }
15465
15466       if (!spec)
15467         break;
15468
15469       die = follow_die_ref (die, spec, &cu);
15470     }
15471
15472   return NULL;
15473 }
15474
15475 /* Return the named attribute or NULL if not there,
15476    but do not follow DW_AT_specification, etc.
15477    This is for use in contexts where we're reading .debug_types dies.
15478    Following DW_AT_specification, DW_AT_abstract_origin will take us
15479    back up the chain, and we want to go down.  */
15480
15481 static struct attribute *
15482 dwarf2_attr_no_follow (struct die_info *die, unsigned int name)
15483 {
15484   unsigned int i;
15485
15486   for (i = 0; i < die->num_attrs; ++i)
15487     if (die->attrs[i].name == name)
15488       return &die->attrs[i];
15489
15490   return NULL;
15491 }
15492
15493 /* Return non-zero iff the attribute NAME is defined for the given DIE,
15494    and holds a non-zero value.  This function should only be used for
15495    DW_FORM_flag or DW_FORM_flag_present attributes.  */
15496
15497 static int
15498 dwarf2_flag_true_p (struct die_info *die, unsigned name, struct dwarf2_cu *cu)
15499 {
15500   struct attribute *attr = dwarf2_attr (die, name, cu);
15501
15502   return (attr && DW_UNSND (attr));
15503 }
15504
15505 static int
15506 die_is_declaration (struct die_info *die, struct dwarf2_cu *cu)
15507 {
15508   /* A DIE is a declaration if it has a DW_AT_declaration attribute
15509      which value is non-zero.  However, we have to be careful with
15510      DIEs having a DW_AT_specification attribute, because dwarf2_attr()
15511      (via dwarf2_flag_true_p) follows this attribute.  So we may
15512      end up accidently finding a declaration attribute that belongs
15513      to a different DIE referenced by the specification attribute,
15514      even though the given DIE does not have a declaration attribute.  */
15515   return (dwarf2_flag_true_p (die, DW_AT_declaration, cu)
15516           && dwarf2_attr (die, DW_AT_specification, cu) == NULL);
15517 }
15518
15519 /* Return the die giving the specification for DIE, if there is
15520    one.  *SPEC_CU is the CU containing DIE on input, and the CU
15521    containing the return value on output.  If there is no
15522    specification, but there is an abstract origin, that is
15523    returned.  */
15524
15525 static struct die_info *
15526 die_specification (struct die_info *die, struct dwarf2_cu **spec_cu)
15527 {
15528   struct attribute *spec_attr = dwarf2_attr (die, DW_AT_specification,
15529                                              *spec_cu);
15530
15531   if (spec_attr == NULL)
15532     spec_attr = dwarf2_attr (die, DW_AT_abstract_origin, *spec_cu);
15533
15534   if (spec_attr == NULL)
15535     return NULL;
15536   else
15537     return follow_die_ref (die, spec_attr, spec_cu);
15538 }
15539
15540 /* Free the line_header structure *LH, and any arrays and strings it
15541    refers to.
15542    NOTE: This is also used as a "cleanup" function.  */
15543
15544 static void
15545 free_line_header (struct line_header *lh)
15546 {
15547   if (lh->standard_opcode_lengths)
15548     xfree (lh->standard_opcode_lengths);
15549
15550   /* Remember that all the lh->file_names[i].name pointers are
15551      pointers into debug_line_buffer, and don't need to be freed.  */
15552   if (lh->file_names)
15553     xfree (lh->file_names);
15554
15555   /* Similarly for the include directory names.  */
15556   if (lh->include_dirs)
15557     xfree (lh->include_dirs);
15558
15559   xfree (lh);
15560 }
15561
15562 /* Add an entry to LH's include directory table.  */
15563
15564 static void
15565 add_include_dir (struct line_header *lh, const char *include_dir)
15566 {
15567   /* Grow the array if necessary.  */
15568   if (lh->include_dirs_size == 0)
15569     {
15570       lh->include_dirs_size = 1; /* for testing */
15571       lh->include_dirs = xmalloc (lh->include_dirs_size
15572                                   * sizeof (*lh->include_dirs));
15573     }
15574   else if (lh->num_include_dirs >= lh->include_dirs_size)
15575     {
15576       lh->include_dirs_size *= 2;
15577       lh->include_dirs = xrealloc (lh->include_dirs,
15578                                    (lh->include_dirs_size
15579                                     * sizeof (*lh->include_dirs)));
15580     }
15581
15582   lh->include_dirs[lh->num_include_dirs++] = include_dir;
15583 }
15584
15585 /* Add an entry to LH's file name table.  */
15586
15587 static void
15588 add_file_name (struct line_header *lh,
15589                const char *name,
15590                unsigned int dir_index,
15591                unsigned int mod_time,
15592                unsigned int length)
15593 {
15594   struct file_entry *fe;
15595
15596   /* Grow the array if necessary.  */
15597   if (lh->file_names_size == 0)
15598     {
15599       lh->file_names_size = 1; /* for testing */
15600       lh->file_names = xmalloc (lh->file_names_size
15601                                 * sizeof (*lh->file_names));
15602     }
15603   else if (lh->num_file_names >= lh->file_names_size)
15604     {
15605       lh->file_names_size *= 2;
15606       lh->file_names = xrealloc (lh->file_names,
15607                                  (lh->file_names_size
15608                                   * sizeof (*lh->file_names)));
15609     }
15610
15611   fe = &lh->file_names[lh->num_file_names++];
15612   fe->name = name;
15613   fe->dir_index = dir_index;
15614   fe->mod_time = mod_time;
15615   fe->length = length;
15616   fe->included_p = 0;
15617   fe->symtab = NULL;
15618 }
15619
15620 /* A convenience function to find the proper .debug_line section for a
15621    CU.  */
15622
15623 static struct dwarf2_section_info *
15624 get_debug_line_section (struct dwarf2_cu *cu)
15625 {
15626   struct dwarf2_section_info *section;
15627
15628   /* For TUs in DWO files, the DW_AT_stmt_list attribute lives in the
15629      DWO file.  */
15630   if (cu->dwo_unit && cu->per_cu->is_debug_types)
15631     section = &cu->dwo_unit->dwo_file->sections.line;
15632   else if (cu->per_cu->is_dwz)
15633     {
15634       struct dwz_file *dwz = dwarf2_get_dwz_file ();
15635
15636       section = &dwz->line;
15637     }
15638   else
15639     section = &dwarf2_per_objfile->line;
15640
15641   return section;
15642 }
15643
15644 /* Read the statement program header starting at OFFSET in
15645    .debug_line, or .debug_line.dwo.  Return a pointer
15646    to a struct line_header, allocated using xmalloc.
15647
15648    NOTE: the strings in the include directory and file name tables of
15649    the returned object point into the dwarf line section buffer,
15650    and must not be freed.  */
15651
15652 static struct line_header *
15653 dwarf_decode_line_header (unsigned int offset, struct dwarf2_cu *cu)
15654 {
15655   struct cleanup *back_to;
15656   struct line_header *lh;
15657   const gdb_byte *line_ptr;
15658   unsigned int bytes_read, offset_size;
15659   int i;
15660   const char *cur_dir, *cur_file;
15661   struct dwarf2_section_info *section;
15662   bfd *abfd;
15663
15664   section = get_debug_line_section (cu);
15665   dwarf2_read_section (dwarf2_per_objfile->objfile, section);
15666   if (section->buffer == NULL)
15667     {
15668       if (cu->dwo_unit && cu->per_cu->is_debug_types)
15669         complaint (&symfile_complaints, _("missing .debug_line.dwo section"));
15670       else
15671         complaint (&symfile_complaints, _("missing .debug_line section"));
15672       return 0;
15673     }
15674
15675   /* We can't do this until we know the section is non-empty.
15676      Only then do we know we have such a section.  */
15677   abfd = section->asection->owner;
15678
15679   /* Make sure that at least there's room for the total_length field.
15680      That could be 12 bytes long, but we're just going to fudge that.  */
15681   if (offset + 4 >= section->size)
15682     {
15683       dwarf2_statement_list_fits_in_line_number_section_complaint ();
15684       return 0;
15685     }
15686
15687   lh = xmalloc (sizeof (*lh));
15688   memset (lh, 0, sizeof (*lh));
15689   back_to = make_cleanup ((make_cleanup_ftype *) free_line_header,
15690                           (void *) lh);
15691
15692   line_ptr = section->buffer + offset;
15693
15694   /* Read in the header.  */
15695   lh->total_length =
15696     read_checked_initial_length_and_offset (abfd, line_ptr, &cu->header,
15697                                             &bytes_read, &offset_size);
15698   line_ptr += bytes_read;
15699   if (line_ptr + lh->total_length > (section->buffer + section->size))
15700     {
15701       dwarf2_statement_list_fits_in_line_number_section_complaint ();
15702       do_cleanups (back_to);
15703       return 0;
15704     }
15705   lh->statement_program_end = line_ptr + lh->total_length;
15706   lh->version = read_2_bytes (abfd, line_ptr);
15707   line_ptr += 2;
15708   lh->header_length = read_offset_1 (abfd, line_ptr, offset_size);
15709   line_ptr += offset_size;
15710   lh->minimum_instruction_length = read_1_byte (abfd, line_ptr);
15711   line_ptr += 1;
15712   if (lh->version >= 4)
15713     {
15714       lh->maximum_ops_per_instruction = read_1_byte (abfd, line_ptr);
15715       line_ptr += 1;
15716     }
15717   else
15718     lh->maximum_ops_per_instruction = 1;
15719
15720   if (lh->maximum_ops_per_instruction == 0)
15721     {
15722       lh->maximum_ops_per_instruction = 1;
15723       complaint (&symfile_complaints,
15724                  _("invalid maximum_ops_per_instruction "
15725                    "in `.debug_line' section"));
15726     }
15727
15728   lh->default_is_stmt = read_1_byte (abfd, line_ptr);
15729   line_ptr += 1;
15730   lh->line_base = read_1_signed_byte (abfd, line_ptr);
15731   line_ptr += 1;
15732   lh->line_range = read_1_byte (abfd, line_ptr);
15733   line_ptr += 1;
15734   lh->opcode_base = read_1_byte (abfd, line_ptr);
15735   line_ptr += 1;
15736   lh->standard_opcode_lengths
15737     = xmalloc (lh->opcode_base * sizeof (lh->standard_opcode_lengths[0]));
15738
15739   lh->standard_opcode_lengths[0] = 1;  /* This should never be used anyway.  */
15740   for (i = 1; i < lh->opcode_base; ++i)
15741     {
15742       lh->standard_opcode_lengths[i] = read_1_byte (abfd, line_ptr);
15743       line_ptr += 1;
15744     }
15745
15746   /* Read directory table.  */
15747   while ((cur_dir = read_direct_string (abfd, line_ptr, &bytes_read)) != NULL)
15748     {
15749       line_ptr += bytes_read;
15750       add_include_dir (lh, cur_dir);
15751     }
15752   line_ptr += bytes_read;
15753
15754   /* Read file name table.  */
15755   while ((cur_file = read_direct_string (abfd, line_ptr, &bytes_read)) != NULL)
15756     {
15757       unsigned int dir_index, mod_time, length;
15758
15759       line_ptr += bytes_read;
15760       dir_index = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
15761       line_ptr += bytes_read;
15762       mod_time = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
15763       line_ptr += bytes_read;
15764       length = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
15765       line_ptr += bytes_read;
15766
15767       add_file_name (lh, cur_file, dir_index, mod_time, length);
15768     }
15769   line_ptr += bytes_read;
15770   lh->statement_program_start = line_ptr;
15771
15772   if (line_ptr > (section->buffer + section->size))
15773     complaint (&symfile_complaints,
15774                _("line number info header doesn't "
15775                  "fit in `.debug_line' section"));
15776
15777   discard_cleanups (back_to);
15778   return lh;
15779 }
15780
15781 /* Subroutine of dwarf_decode_lines to simplify it.
15782    Return the file name of the psymtab for included file FILE_INDEX
15783    in line header LH of PST.
15784    COMP_DIR is the compilation directory (DW_AT_comp_dir) or NULL if unknown.
15785    If space for the result is malloc'd, it will be freed by a cleanup.
15786    Returns NULL if FILE_INDEX should be ignored, i.e., it is pst->filename.
15787
15788    The function creates dangling cleanup registration.  */
15789
15790 static const char *
15791 psymtab_include_file_name (const struct line_header *lh, int file_index,
15792                            const struct partial_symtab *pst,
15793                            const char *comp_dir)
15794 {
15795   const struct file_entry fe = lh->file_names [file_index];
15796   const char *include_name = fe.name;
15797   const char *include_name_to_compare = include_name;
15798   const char *dir_name = NULL;
15799   const char *pst_filename;
15800   char *copied_name = NULL;
15801   int file_is_pst;
15802
15803   if (fe.dir_index)
15804     dir_name = lh->include_dirs[fe.dir_index - 1];
15805
15806   if (!IS_ABSOLUTE_PATH (include_name)
15807       && (dir_name != NULL || comp_dir != NULL))
15808     {
15809       /* Avoid creating a duplicate psymtab for PST.
15810          We do this by comparing INCLUDE_NAME and PST_FILENAME.
15811          Before we do the comparison, however, we need to account
15812          for DIR_NAME and COMP_DIR.
15813          First prepend dir_name (if non-NULL).  If we still don't
15814          have an absolute path prepend comp_dir (if non-NULL).
15815          However, the directory we record in the include-file's
15816          psymtab does not contain COMP_DIR (to match the
15817          corresponding symtab(s)).
15818
15819          Example:
15820
15821          bash$ cd /tmp
15822          bash$ gcc -g ./hello.c
15823          include_name = "hello.c"
15824          dir_name = "."
15825          DW_AT_comp_dir = comp_dir = "/tmp"
15826          DW_AT_name = "./hello.c"  */
15827
15828       if (dir_name != NULL)
15829         {
15830           char *tem = concat (dir_name, SLASH_STRING,
15831                               include_name, (char *)NULL);
15832
15833           make_cleanup (xfree, tem);
15834           include_name = tem;
15835           include_name_to_compare = include_name;
15836         }
15837       if (!IS_ABSOLUTE_PATH (include_name) && comp_dir != NULL)
15838         {
15839           char *tem = concat (comp_dir, SLASH_STRING,
15840                               include_name, (char *)NULL);
15841
15842           make_cleanup (xfree, tem);
15843           include_name_to_compare = tem;
15844         }
15845     }
15846
15847   pst_filename = pst->filename;
15848   if (!IS_ABSOLUTE_PATH (pst_filename) && pst->dirname != NULL)
15849     {
15850       copied_name = concat (pst->dirname, SLASH_STRING,
15851                             pst_filename, (char *)NULL);
15852       pst_filename = copied_name;
15853     }
15854
15855   file_is_pst = FILENAME_CMP (include_name_to_compare, pst_filename) == 0;
15856
15857   if (copied_name != NULL)
15858     xfree (copied_name);
15859
15860   if (file_is_pst)
15861     return NULL;
15862   return include_name;
15863 }
15864
15865 /* Ignore this record_line request.  */
15866
15867 static void
15868 noop_record_line (struct subfile *subfile, int line, CORE_ADDR pc)
15869 {
15870   return;
15871 }
15872
15873 /* Subroutine of dwarf_decode_lines to simplify it.
15874    Process the line number information in LH.  */
15875
15876 static void
15877 dwarf_decode_lines_1 (struct line_header *lh, const char *comp_dir,
15878                       struct dwarf2_cu *cu, struct partial_symtab *pst)
15879 {
15880   const gdb_byte *line_ptr, *extended_end;
15881   const gdb_byte *line_end;
15882   unsigned int bytes_read, extended_len;
15883   unsigned char op_code, extended_op, adj_opcode;
15884   CORE_ADDR baseaddr;
15885   struct objfile *objfile = cu->objfile;
15886   bfd *abfd = objfile->obfd;
15887   struct gdbarch *gdbarch = get_objfile_arch (objfile);
15888   const int decode_for_pst_p = (pst != NULL);
15889   struct subfile *last_subfile = NULL;
15890   void (*p_record_line) (struct subfile *subfile, int line, CORE_ADDR pc)
15891     = record_line;
15892
15893   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
15894
15895   line_ptr = lh->statement_program_start;
15896   line_end = lh->statement_program_end;
15897
15898   /* Read the statement sequences until there's nothing left.  */
15899   while (line_ptr < line_end)
15900     {
15901       /* state machine registers  */
15902       CORE_ADDR address = 0;
15903       unsigned int file = 1;
15904       unsigned int line = 1;
15905       unsigned int column = 0;
15906       int is_stmt = lh->default_is_stmt;
15907       int basic_block = 0;
15908       int end_sequence = 0;
15909       CORE_ADDR addr;
15910       unsigned char op_index = 0;
15911
15912       if (!decode_for_pst_p && lh->num_file_names >= file)
15913         {
15914           /* Start a subfile for the current file of the state machine.  */
15915           /* lh->include_dirs and lh->file_names are 0-based, but the
15916              directory and file name numbers in the statement program
15917              are 1-based.  */
15918           struct file_entry *fe = &lh->file_names[file - 1];
15919           const char *dir = NULL;
15920
15921           if (fe->dir_index)
15922             dir = lh->include_dirs[fe->dir_index - 1];
15923
15924           dwarf2_start_subfile (fe->name, dir, comp_dir);
15925         }
15926
15927       /* Decode the table.  */
15928       while (!end_sequence)
15929         {
15930           op_code = read_1_byte (abfd, line_ptr);
15931           line_ptr += 1;
15932           if (line_ptr > line_end)
15933             {
15934               dwarf2_debug_line_missing_end_sequence_complaint ();
15935               break;
15936             }
15937
15938           if (op_code >= lh->opcode_base)
15939             {
15940               /* Special operand.  */
15941               adj_opcode = op_code - lh->opcode_base;
15942               address += (((op_index + (adj_opcode / lh->line_range))
15943                            / lh->maximum_ops_per_instruction)
15944                           * lh->minimum_instruction_length);
15945               op_index = ((op_index + (adj_opcode / lh->line_range))
15946                           % lh->maximum_ops_per_instruction);
15947               line += lh->line_base + (adj_opcode % lh->line_range);
15948               if (lh->num_file_names < file || file == 0)
15949                 dwarf2_debug_line_missing_file_complaint ();
15950               /* For now we ignore lines not starting on an
15951                  instruction boundary.  */
15952               else if (op_index == 0)
15953                 {
15954                   lh->file_names[file - 1].included_p = 1;
15955                   if (!decode_for_pst_p && is_stmt)
15956                     {
15957                       if (last_subfile != current_subfile)
15958                         {
15959                           addr = gdbarch_addr_bits_remove (gdbarch, address);
15960                           if (last_subfile)
15961                             (*p_record_line) (last_subfile, 0, addr);
15962                           last_subfile = current_subfile;
15963                         }
15964                       /* Append row to matrix using current values.  */
15965                       addr = gdbarch_addr_bits_remove (gdbarch, address);
15966                       (*p_record_line) (current_subfile, line, addr);
15967                     }
15968                 }
15969               basic_block = 0;
15970             }
15971           else switch (op_code)
15972             {
15973             case DW_LNS_extended_op:
15974               extended_len = read_unsigned_leb128 (abfd, line_ptr,
15975                                                    &bytes_read);
15976               line_ptr += bytes_read;
15977               extended_end = line_ptr + extended_len;
15978               extended_op = read_1_byte (abfd, line_ptr);
15979               line_ptr += 1;
15980               switch (extended_op)
15981                 {
15982                 case DW_LNE_end_sequence:
15983                   p_record_line = record_line;
15984                   end_sequence = 1;
15985                   break;
15986                 case DW_LNE_set_address:
15987                   address = read_address (abfd, line_ptr, cu, &bytes_read);
15988
15989                   if (address == 0 && !dwarf2_per_objfile->has_section_at_zero)
15990                     {
15991                       /* This line table is for a function which has been
15992                          GCd by the linker.  Ignore it.  PR gdb/12528 */
15993
15994                       long line_offset
15995                         = line_ptr - get_debug_line_section (cu)->buffer;
15996
15997                       complaint (&symfile_complaints,
15998                                  _(".debug_line address at offset 0x%lx is 0 "
15999                                    "[in module %s]"),
16000                                  line_offset, objfile->name);
16001                       p_record_line = noop_record_line;
16002                     }
16003
16004                   op_index = 0;
16005                   line_ptr += bytes_read;
16006                   address += baseaddr;
16007                   break;
16008                 case DW_LNE_define_file:
16009                   {
16010                     const char *cur_file;
16011                     unsigned int dir_index, mod_time, length;
16012
16013                     cur_file = read_direct_string (abfd, line_ptr,
16014                                                    &bytes_read);
16015                     line_ptr += bytes_read;
16016                     dir_index =
16017                       read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
16018                     line_ptr += bytes_read;
16019                     mod_time =
16020                       read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
16021                     line_ptr += bytes_read;
16022                     length =
16023                       read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
16024                     line_ptr += bytes_read;
16025                     add_file_name (lh, cur_file, dir_index, mod_time, length);
16026                   }
16027                   break;
16028                 case DW_LNE_set_discriminator:
16029                   /* The discriminator is not interesting to the debugger;
16030                      just ignore it.  */
16031                   line_ptr = extended_end;
16032                   break;
16033                 default:
16034                   complaint (&symfile_complaints,
16035                              _("mangled .debug_line section"));
16036                   return;
16037                 }
16038               /* Make sure that we parsed the extended op correctly.  If e.g.
16039                  we expected a different address size than the producer used,
16040                  we may have read the wrong number of bytes.  */
16041               if (line_ptr != extended_end)
16042                 {
16043                   complaint (&symfile_complaints,
16044                              _("mangled .debug_line section"));
16045                   return;
16046                 }
16047               break;
16048             case DW_LNS_copy:
16049               if (lh->num_file_names < file || file == 0)
16050                 dwarf2_debug_line_missing_file_complaint ();
16051               else
16052                 {
16053                   lh->file_names[file - 1].included_p = 1;
16054                   if (!decode_for_pst_p && is_stmt)
16055                     {
16056                       if (last_subfile != current_subfile)
16057                         {
16058                           addr = gdbarch_addr_bits_remove (gdbarch, address);
16059                           if (last_subfile)
16060                             (*p_record_line) (last_subfile, 0, addr);
16061                           last_subfile = current_subfile;
16062                         }
16063                       addr = gdbarch_addr_bits_remove (gdbarch, address);
16064                       (*p_record_line) (current_subfile, line, addr);
16065                     }
16066                 }
16067               basic_block = 0;
16068               break;
16069             case DW_LNS_advance_pc:
16070               {
16071                 CORE_ADDR adjust
16072                   = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
16073
16074                 address += (((op_index + adjust)
16075                              / lh->maximum_ops_per_instruction)
16076                             * lh->minimum_instruction_length);
16077                 op_index = ((op_index + adjust)
16078                             % lh->maximum_ops_per_instruction);
16079                 line_ptr += bytes_read;
16080               }
16081               break;
16082             case DW_LNS_advance_line:
16083               line += read_signed_leb128 (abfd, line_ptr, &bytes_read);
16084               line_ptr += bytes_read;
16085               break;
16086             case DW_LNS_set_file:
16087               {
16088                 /* The arrays lh->include_dirs and lh->file_names are
16089                    0-based, but the directory and file name numbers in
16090                    the statement program are 1-based.  */
16091                 struct file_entry *fe;
16092                 const char *dir = NULL;
16093
16094                 file = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
16095                 line_ptr += bytes_read;
16096                 if (lh->num_file_names < file || file == 0)
16097                   dwarf2_debug_line_missing_file_complaint ();
16098                 else
16099                   {
16100                     fe = &lh->file_names[file - 1];
16101                     if (fe->dir_index)
16102                       dir = lh->include_dirs[fe->dir_index - 1];
16103                     if (!decode_for_pst_p)
16104                       {
16105                         last_subfile = current_subfile;
16106                         dwarf2_start_subfile (fe->name, dir, comp_dir);
16107                       }
16108                   }
16109               }
16110               break;
16111             case DW_LNS_set_column:
16112               column = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
16113               line_ptr += bytes_read;
16114               break;
16115             case DW_LNS_negate_stmt:
16116               is_stmt = (!is_stmt);
16117               break;
16118             case DW_LNS_set_basic_block:
16119               basic_block = 1;
16120               break;
16121             /* Add to the address register of the state machine the
16122                address increment value corresponding to special opcode
16123                255.  I.e., this value is scaled by the minimum
16124                instruction length since special opcode 255 would have
16125                scaled the increment.  */
16126             case DW_LNS_const_add_pc:
16127               {
16128                 CORE_ADDR adjust = (255 - lh->opcode_base) / lh->line_range;
16129
16130                 address += (((op_index + adjust)
16131                              / lh->maximum_ops_per_instruction)
16132                             * lh->minimum_instruction_length);
16133                 op_index = ((op_index + adjust)
16134                             % lh->maximum_ops_per_instruction);
16135               }
16136               break;
16137             case DW_LNS_fixed_advance_pc:
16138               address += read_2_bytes (abfd, line_ptr);
16139               op_index = 0;
16140               line_ptr += 2;
16141               break;
16142             default:
16143               {
16144                 /* Unknown standard opcode, ignore it.  */
16145                 int i;
16146
16147                 for (i = 0; i < lh->standard_opcode_lengths[op_code]; i++)
16148                   {
16149                     (void) read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
16150                     line_ptr += bytes_read;
16151                   }
16152               }
16153             }
16154         }
16155       if (lh->num_file_names < file || file == 0)
16156         dwarf2_debug_line_missing_file_complaint ();
16157       else
16158         {
16159           lh->file_names[file - 1].included_p = 1;
16160           if (!decode_for_pst_p)
16161             {
16162               addr = gdbarch_addr_bits_remove (gdbarch, address);
16163               (*p_record_line) (current_subfile, 0, addr);
16164             }
16165         }
16166     }
16167 }
16168
16169 /* Decode the Line Number Program (LNP) for the given line_header
16170    structure and CU.  The actual information extracted and the type
16171    of structures created from the LNP depends on the value of PST.
16172
16173    1. If PST is NULL, then this procedure uses the data from the program
16174       to create all necessary symbol tables, and their linetables.
16175
16176    2. If PST is not NULL, this procedure reads the program to determine
16177       the list of files included by the unit represented by PST, and
16178       builds all the associated partial symbol tables.
16179
16180    COMP_DIR is the compilation directory (DW_AT_comp_dir) or NULL if unknown.
16181    It is used for relative paths in the line table.
16182    NOTE: When processing partial symtabs (pst != NULL),
16183    comp_dir == pst->dirname.
16184
16185    NOTE: It is important that psymtabs have the same file name (via strcmp)
16186    as the corresponding symtab.  Since COMP_DIR is not used in the name of the
16187    symtab we don't use it in the name of the psymtabs we create.
16188    E.g. expand_line_sal requires this when finding psymtabs to expand.
16189    A good testcase for this is mb-inline.exp.  */
16190
16191 static void
16192 dwarf_decode_lines (struct line_header *lh, const char *comp_dir,
16193                     struct dwarf2_cu *cu, struct partial_symtab *pst,
16194                     int want_line_info)
16195 {
16196   struct objfile *objfile = cu->objfile;
16197   const int decode_for_pst_p = (pst != NULL);
16198   struct subfile *first_subfile = current_subfile;
16199
16200   if (want_line_info)
16201     dwarf_decode_lines_1 (lh, comp_dir, cu, pst);
16202
16203   if (decode_for_pst_p)
16204     {
16205       int file_index;
16206
16207       /* Now that we're done scanning the Line Header Program, we can
16208          create the psymtab of each included file.  */
16209       for (file_index = 0; file_index < lh->num_file_names; file_index++)
16210         if (lh->file_names[file_index].included_p == 1)
16211           {
16212             const char *include_name =
16213               psymtab_include_file_name (lh, file_index, pst, comp_dir);
16214             if (include_name != NULL)
16215               dwarf2_create_include_psymtab (include_name, pst, objfile);
16216           }
16217     }
16218   else
16219     {
16220       /* Make sure a symtab is created for every file, even files
16221          which contain only variables (i.e. no code with associated
16222          line numbers).  */
16223       int i;
16224
16225       for (i = 0; i < lh->num_file_names; i++)
16226         {
16227           const char *dir = NULL;
16228           struct file_entry *fe;
16229
16230           fe = &lh->file_names[i];
16231           if (fe->dir_index)
16232             dir = lh->include_dirs[fe->dir_index - 1];
16233           dwarf2_start_subfile (fe->name, dir, comp_dir);
16234
16235           /* Skip the main file; we don't need it, and it must be
16236              allocated last, so that it will show up before the
16237              non-primary symtabs in the objfile's symtab list.  */
16238           if (current_subfile == first_subfile)
16239             continue;
16240
16241           if (current_subfile->symtab == NULL)
16242             current_subfile->symtab = allocate_symtab (current_subfile->name,
16243                                                        objfile);
16244           fe->symtab = current_subfile->symtab;
16245         }
16246     }
16247 }
16248
16249 /* Start a subfile for DWARF.  FILENAME is the name of the file and
16250    DIRNAME the name of the source directory which contains FILENAME
16251    or NULL if not known.  COMP_DIR is the compilation directory for the
16252    linetable's compilation unit or NULL if not known.
16253    This routine tries to keep line numbers from identical absolute and
16254    relative file names in a common subfile.
16255
16256    Using the `list' example from the GDB testsuite, which resides in
16257    /srcdir and compiling it with Irix6.2 cc in /compdir using a filename
16258    of /srcdir/list0.c yields the following debugging information for list0.c:
16259
16260    DW_AT_name:          /srcdir/list0.c
16261    DW_AT_comp_dir:              /compdir
16262    files.files[0].name: list0.h
16263    files.files[0].dir:  /srcdir
16264    files.files[1].name: list0.c
16265    files.files[1].dir:  /srcdir
16266
16267    The line number information for list0.c has to end up in a single
16268    subfile, so that `break /srcdir/list0.c:1' works as expected.
16269    start_subfile will ensure that this happens provided that we pass the
16270    concatenation of files.files[1].dir and files.files[1].name as the
16271    subfile's name.  */
16272
16273 static void
16274 dwarf2_start_subfile (const char *filename, const char *dirname,
16275                       const char *comp_dir)
16276 {
16277   char *copy = NULL;
16278
16279   /* While reading the DIEs, we call start_symtab(DW_AT_name, DW_AT_comp_dir).
16280      `start_symtab' will always pass the contents of DW_AT_comp_dir as
16281      second argument to start_subfile.  To be consistent, we do the
16282      same here.  In order not to lose the line information directory,
16283      we concatenate it to the filename when it makes sense.
16284      Note that the Dwarf3 standard says (speaking of filenames in line
16285      information): ``The directory index is ignored for file names
16286      that represent full path names''.  Thus ignoring dirname in the
16287      `else' branch below isn't an issue.  */
16288
16289   if (!IS_ABSOLUTE_PATH (filename) && dirname != NULL)
16290     {
16291       copy = concat (dirname, SLASH_STRING, filename, (char *)NULL);
16292       filename = copy;
16293     }
16294
16295   start_subfile (filename, comp_dir);
16296
16297   if (copy != NULL)
16298     xfree (copy);
16299 }
16300
16301 /* Start a symtab for DWARF.
16302    NAME, COMP_DIR, LOW_PC are passed to start_symtab.  */
16303
16304 static void
16305 dwarf2_start_symtab (struct dwarf2_cu *cu,
16306                      const char *name, const char *comp_dir, CORE_ADDR low_pc)
16307 {
16308   start_symtab (name, comp_dir, low_pc);
16309   record_debugformat ("DWARF 2");
16310   record_producer (cu->producer);
16311
16312   /* We assume that we're processing GCC output.  */
16313   processing_gcc_compilation = 2;
16314
16315   cu->processing_has_namespace_info = 0;
16316 }
16317
16318 static void
16319 var_decode_location (struct attribute *attr, struct symbol *sym,
16320                      struct dwarf2_cu *cu)
16321 {
16322   struct objfile *objfile = cu->objfile;
16323   struct comp_unit_head *cu_header = &cu->header;
16324
16325   /* NOTE drow/2003-01-30: There used to be a comment and some special
16326      code here to turn a symbol with DW_AT_external and a
16327      SYMBOL_VALUE_ADDRESS of 0 into a LOC_UNRESOLVED symbol.  This was
16328      necessary for platforms (maybe Alpha, certainly PowerPC GNU/Linux
16329      with some versions of binutils) where shared libraries could have
16330      relocations against symbols in their debug information - the
16331      minimal symbol would have the right address, but the debug info
16332      would not.  It's no longer necessary, because we will explicitly
16333      apply relocations when we read in the debug information now.  */
16334
16335   /* A DW_AT_location attribute with no contents indicates that a
16336      variable has been optimized away.  */
16337   if (attr_form_is_block (attr) && DW_BLOCK (attr)->size == 0)
16338     {
16339       SYMBOL_ACLASS_INDEX (sym) = LOC_OPTIMIZED_OUT;
16340       return;
16341     }
16342
16343   /* Handle one degenerate form of location expression specially, to
16344      preserve GDB's previous behavior when section offsets are
16345      specified.  If this is just a DW_OP_addr or DW_OP_GNU_addr_index
16346      then mark this symbol as LOC_STATIC.  */
16347
16348   if (attr_form_is_block (attr)
16349       && ((DW_BLOCK (attr)->data[0] == DW_OP_addr
16350            && DW_BLOCK (attr)->size == 1 + cu_header->addr_size)
16351           || (DW_BLOCK (attr)->data[0] == DW_OP_GNU_addr_index
16352               && (DW_BLOCK (attr)->size
16353                   == 1 + leb128_size (&DW_BLOCK (attr)->data[1])))))
16354     {
16355       unsigned int dummy;
16356
16357       if (DW_BLOCK (attr)->data[0] == DW_OP_addr)
16358         SYMBOL_VALUE_ADDRESS (sym) =
16359           read_address (objfile->obfd, DW_BLOCK (attr)->data + 1, cu, &dummy);
16360       else
16361         SYMBOL_VALUE_ADDRESS (sym) =
16362           read_addr_index_from_leb128 (cu, DW_BLOCK (attr)->data + 1, &dummy);
16363       SYMBOL_ACLASS_INDEX (sym) = LOC_STATIC;
16364       fixup_symbol_section (sym, objfile);
16365       SYMBOL_VALUE_ADDRESS (sym) += ANOFFSET (objfile->section_offsets,
16366                                               SYMBOL_SECTION (sym));
16367       return;
16368     }
16369
16370   /* NOTE drow/2002-01-30: It might be worthwhile to have a static
16371      expression evaluator, and use LOC_COMPUTED only when necessary
16372      (i.e. when the value of a register or memory location is
16373      referenced, or a thread-local block, etc.).  Then again, it might
16374      not be worthwhile.  I'm assuming that it isn't unless performance
16375      or memory numbers show me otherwise.  */
16376
16377   dwarf2_symbol_mark_computed (attr, sym, cu, 0);
16378
16379   if (SYMBOL_COMPUTED_OPS (sym)->location_has_loclist)
16380     cu->has_loclist = 1;
16381 }
16382
16383 /* Given a pointer to a DWARF information entry, figure out if we need
16384    to make a symbol table entry for it, and if so, create a new entry
16385    and return a pointer to it.
16386    If TYPE is NULL, determine symbol type from the die, otherwise
16387    used the passed type.
16388    If SPACE is not NULL, use it to hold the new symbol.  If it is
16389    NULL, allocate a new symbol on the objfile's obstack.  */
16390
16391 static struct symbol *
16392 new_symbol_full (struct die_info *die, struct type *type, struct dwarf2_cu *cu,
16393                  struct symbol *space)
16394 {
16395   struct objfile *objfile = cu->objfile;
16396   struct symbol *sym = NULL;
16397   const char *name;
16398   struct attribute *attr = NULL;
16399   struct attribute *attr2 = NULL;
16400   CORE_ADDR baseaddr;
16401   struct pending **list_to_add = NULL;
16402
16403   int inlined_func = (die->tag == DW_TAG_inlined_subroutine);
16404
16405   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
16406
16407   name = dwarf2_name (die, cu);
16408   if (name)
16409     {
16410       const char *linkagename;
16411       int suppress_add = 0;
16412
16413       if (space)
16414         sym = space;
16415       else
16416         sym = allocate_symbol (objfile);
16417       OBJSTAT (objfile, n_syms++);
16418
16419       /* Cache this symbol's name and the name's demangled form (if any).  */
16420       SYMBOL_SET_LANGUAGE (sym, cu->language, &objfile->objfile_obstack);
16421       linkagename = dwarf2_physname (name, die, cu);
16422       SYMBOL_SET_NAMES (sym, linkagename, strlen (linkagename), 0, objfile);
16423
16424       /* Fortran does not have mangling standard and the mangling does differ
16425          between gfortran, iFort etc.  */
16426       if (cu->language == language_fortran
16427           && symbol_get_demangled_name (&(sym->ginfo)) == NULL)
16428         symbol_set_demangled_name (&(sym->ginfo),
16429                                    dwarf2_full_name (name, die, cu),
16430                                    NULL);
16431
16432       /* Default assumptions.
16433          Use the passed type or decode it from the die.  */
16434       SYMBOL_DOMAIN (sym) = VAR_DOMAIN;
16435       SYMBOL_ACLASS_INDEX (sym) = LOC_OPTIMIZED_OUT;
16436       if (type != NULL)
16437         SYMBOL_TYPE (sym) = type;
16438       else
16439         SYMBOL_TYPE (sym) = die_type (die, cu);
16440       attr = dwarf2_attr (die,
16441                           inlined_func ? DW_AT_call_line : DW_AT_decl_line,
16442                           cu);
16443       if (attr)
16444         {
16445           SYMBOL_LINE (sym) = DW_UNSND (attr);
16446         }
16447
16448       attr = dwarf2_attr (die,
16449                           inlined_func ? DW_AT_call_file : DW_AT_decl_file,
16450                           cu);
16451       if (attr)
16452         {
16453           int file_index = DW_UNSND (attr);
16454
16455           if (cu->line_header == NULL
16456               || file_index > cu->line_header->num_file_names)
16457             complaint (&symfile_complaints,
16458                        _("file index out of range"));
16459           else if (file_index > 0)
16460             {
16461               struct file_entry *fe;
16462
16463               fe = &cu->line_header->file_names[file_index - 1];
16464               SYMBOL_SYMTAB (sym) = fe->symtab;
16465             }
16466         }
16467
16468       switch (die->tag)
16469         {
16470         case DW_TAG_label:
16471           attr = dwarf2_attr (die, DW_AT_low_pc, cu);
16472           if (attr)
16473             {
16474               SYMBOL_VALUE_ADDRESS (sym) = DW_ADDR (attr) + baseaddr;
16475             }
16476           SYMBOL_TYPE (sym) = objfile_type (objfile)->builtin_core_addr;
16477           SYMBOL_DOMAIN (sym) = LABEL_DOMAIN;
16478           SYMBOL_ACLASS_INDEX (sym) = LOC_LABEL;
16479           add_symbol_to_list (sym, cu->list_in_scope);
16480           break;
16481         case DW_TAG_subprogram:
16482           /* SYMBOL_BLOCK_VALUE (sym) will be filled in later by
16483              finish_block.  */
16484           SYMBOL_ACLASS_INDEX (sym) = LOC_BLOCK;
16485           attr2 = dwarf2_attr (die, DW_AT_external, cu);
16486           if ((attr2 && (DW_UNSND (attr2) != 0))
16487               || cu->language == language_ada)
16488             {
16489               /* Subprograms marked external are stored as a global symbol.
16490                  Ada subprograms, whether marked external or not, are always
16491                  stored as a global symbol, because we want to be able to
16492                  access them globally.  For instance, we want to be able
16493                  to break on a nested subprogram without having to
16494                  specify the context.  */
16495               list_to_add = &global_symbols;
16496             }
16497           else
16498             {
16499               list_to_add = cu->list_in_scope;
16500             }
16501           break;
16502         case DW_TAG_inlined_subroutine:
16503           /* SYMBOL_BLOCK_VALUE (sym) will be filled in later by
16504              finish_block.  */
16505           SYMBOL_ACLASS_INDEX (sym) = LOC_BLOCK;
16506           SYMBOL_INLINED (sym) = 1;
16507           list_to_add = cu->list_in_scope;
16508           break;
16509         case DW_TAG_template_value_param:
16510           suppress_add = 1;
16511           /* Fall through.  */
16512         case DW_TAG_constant:
16513         case DW_TAG_variable:
16514         case DW_TAG_member:
16515           /* Compilation with minimal debug info may result in
16516              variables with missing type entries.  Change the
16517              misleading `void' type to something sensible.  */
16518           if (TYPE_CODE (SYMBOL_TYPE (sym)) == TYPE_CODE_VOID)
16519             SYMBOL_TYPE (sym)
16520               = objfile_type (objfile)->nodebug_data_symbol;
16521
16522           attr = dwarf2_attr (die, DW_AT_const_value, cu);
16523           /* In the case of DW_TAG_member, we should only be called for
16524              static const members.  */
16525           if (die->tag == DW_TAG_member)
16526             {
16527               /* dwarf2_add_field uses die_is_declaration,
16528                  so we do the same.  */
16529               gdb_assert (die_is_declaration (die, cu));
16530               gdb_assert (attr);
16531             }
16532           if (attr)
16533             {
16534               dwarf2_const_value (attr, sym, cu);
16535               attr2 = dwarf2_attr (die, DW_AT_external, cu);
16536               if (!suppress_add)
16537                 {
16538                   if (attr2 && (DW_UNSND (attr2) != 0))
16539                     list_to_add = &global_symbols;
16540                   else
16541                     list_to_add = cu->list_in_scope;
16542                 }
16543               break;
16544             }
16545           attr = dwarf2_attr (die, DW_AT_location, cu);
16546           if (attr)
16547             {
16548               var_decode_location (attr, sym, cu);
16549               attr2 = dwarf2_attr (die, DW_AT_external, cu);
16550
16551               /* Fortran explicitly imports any global symbols to the local
16552                  scope by DW_TAG_common_block.  */
16553               if (cu->language == language_fortran && die->parent
16554                   && die->parent->tag == DW_TAG_common_block)
16555                 attr2 = NULL;
16556
16557               if (SYMBOL_CLASS (sym) == LOC_STATIC
16558                   && SYMBOL_VALUE_ADDRESS (sym) == 0
16559                   && !dwarf2_per_objfile->has_section_at_zero)
16560                 {
16561                   /* When a static variable is eliminated by the linker,
16562                      the corresponding debug information is not stripped
16563                      out, but the variable address is set to null;
16564                      do not add such variables into symbol table.  */
16565                 }
16566               else if (attr2 && (DW_UNSND (attr2) != 0))
16567                 {
16568                   /* Workaround gfortran PR debug/40040 - it uses
16569                      DW_AT_location for variables in -fPIC libraries which may
16570                      get overriden by other libraries/executable and get
16571                      a different address.  Resolve it by the minimal symbol
16572                      which may come from inferior's executable using copy
16573                      relocation.  Make this workaround only for gfortran as for
16574                      other compilers GDB cannot guess the minimal symbol
16575                      Fortran mangling kind.  */
16576                   if (cu->language == language_fortran && die->parent
16577                       && die->parent->tag == DW_TAG_module
16578                       && cu->producer
16579                       && strncmp (cu->producer, "GNU Fortran ", 12) == 0)
16580                     SYMBOL_ACLASS_INDEX (sym) = LOC_UNRESOLVED;
16581
16582                   /* A variable with DW_AT_external is never static,
16583                      but it may be block-scoped.  */
16584                   list_to_add = (cu->list_in_scope == &file_symbols
16585                                  ? &global_symbols : cu->list_in_scope);
16586                 }
16587               else
16588                 list_to_add = cu->list_in_scope;
16589             }
16590           else
16591             {
16592               /* We do not know the address of this symbol.
16593                  If it is an external symbol and we have type information
16594                  for it, enter the symbol as a LOC_UNRESOLVED symbol.
16595                  The address of the variable will then be determined from
16596                  the minimal symbol table whenever the variable is
16597                  referenced.  */
16598               attr2 = dwarf2_attr (die, DW_AT_external, cu);
16599
16600               /* Fortran explicitly imports any global symbols to the local
16601                  scope by DW_TAG_common_block.  */
16602               if (cu->language == language_fortran && die->parent
16603                   && die->parent->tag == DW_TAG_common_block)
16604                 {
16605                   /* SYMBOL_CLASS doesn't matter here because
16606                      read_common_block is going to reset it.  */
16607                   if (!suppress_add)
16608                     list_to_add = cu->list_in_scope;
16609                 }
16610               else if (attr2 && (DW_UNSND (attr2) != 0)
16611                        && dwarf2_attr (die, DW_AT_type, cu) != NULL)
16612                 {
16613                   /* A variable with DW_AT_external is never static, but it
16614                      may be block-scoped.  */
16615                   list_to_add = (cu->list_in_scope == &file_symbols
16616                                  ? &global_symbols : cu->list_in_scope);
16617
16618                   SYMBOL_ACLASS_INDEX (sym) = LOC_UNRESOLVED;
16619                 }
16620               else if (!die_is_declaration (die, cu))
16621                 {
16622                   /* Use the default LOC_OPTIMIZED_OUT class.  */
16623                   gdb_assert (SYMBOL_CLASS (sym) == LOC_OPTIMIZED_OUT);
16624                   if (!suppress_add)
16625                     list_to_add = cu->list_in_scope;
16626                 }
16627             }
16628           break;
16629         case DW_TAG_formal_parameter:
16630           /* If we are inside a function, mark this as an argument.  If
16631              not, we might be looking at an argument to an inlined function
16632              when we do not have enough information to show inlined frames;
16633              pretend it's a local variable in that case so that the user can
16634              still see it.  */
16635           if (context_stack_depth > 0
16636               && context_stack[context_stack_depth - 1].name != NULL)
16637             SYMBOL_IS_ARGUMENT (sym) = 1;
16638           attr = dwarf2_attr (die, DW_AT_location, cu);
16639           if (attr)
16640             {
16641               var_decode_location (attr, sym, cu);
16642             }
16643           attr = dwarf2_attr (die, DW_AT_const_value, cu);
16644           if (attr)
16645             {
16646               dwarf2_const_value (attr, sym, cu);
16647             }
16648
16649           list_to_add = cu->list_in_scope;
16650           break;
16651         case DW_TAG_unspecified_parameters:
16652           /* From varargs functions; gdb doesn't seem to have any
16653              interest in this information, so just ignore it for now.
16654              (FIXME?) */
16655           break;
16656         case DW_TAG_template_type_param:
16657           suppress_add = 1;
16658           /* Fall through.  */
16659         case DW_TAG_class_type:
16660         case DW_TAG_interface_type:
16661         case DW_TAG_structure_type:
16662         case DW_TAG_union_type:
16663         case DW_TAG_set_type:
16664         case DW_TAG_enumeration_type:
16665           SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
16666           SYMBOL_DOMAIN (sym) = STRUCT_DOMAIN;
16667
16668           {
16669             /* NOTE: carlton/2003-11-10: C++ and Java class symbols shouldn't
16670                really ever be static objects: otherwise, if you try
16671                to, say, break of a class's method and you're in a file
16672                which doesn't mention that class, it won't work unless
16673                the check for all static symbols in lookup_symbol_aux
16674                saves you.  See the OtherFileClass tests in
16675                gdb.c++/namespace.exp.  */
16676
16677             if (!suppress_add)
16678               {
16679                 list_to_add = (cu->list_in_scope == &file_symbols
16680                                && (cu->language == language_cplus
16681                                    || cu->language == language_java)
16682                                ? &global_symbols : cu->list_in_scope);
16683
16684                 /* The semantics of C++ state that "struct foo {
16685                    ... }" also defines a typedef for "foo".  A Java
16686                    class declaration also defines a typedef for the
16687                    class.  */
16688                 if (cu->language == language_cplus
16689                     || cu->language == language_java
16690                     || cu->language == language_ada)
16691                   {
16692                     /* The symbol's name is already allocated along
16693                        with this objfile, so we don't need to
16694                        duplicate it for the type.  */
16695                     if (TYPE_NAME (SYMBOL_TYPE (sym)) == 0)
16696                       TYPE_NAME (SYMBOL_TYPE (sym)) = SYMBOL_SEARCH_NAME (sym);
16697                   }
16698               }
16699           }
16700           break;
16701         case DW_TAG_typedef:
16702           SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
16703           SYMBOL_DOMAIN (sym) = VAR_DOMAIN;
16704           list_to_add = cu->list_in_scope;
16705           break;
16706         case DW_TAG_base_type:
16707         case DW_TAG_subrange_type:
16708           SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
16709           SYMBOL_DOMAIN (sym) = VAR_DOMAIN;
16710           list_to_add = cu->list_in_scope;
16711           break;
16712         case DW_TAG_enumerator:
16713           attr = dwarf2_attr (die, DW_AT_const_value, cu);
16714           if (attr)
16715             {
16716               dwarf2_const_value (attr, sym, cu);
16717             }
16718           {
16719             /* NOTE: carlton/2003-11-10: See comment above in the
16720                DW_TAG_class_type, etc. block.  */
16721
16722             list_to_add = (cu->list_in_scope == &file_symbols
16723                            && (cu->language == language_cplus
16724                                || cu->language == language_java)
16725                            ? &global_symbols : cu->list_in_scope);
16726           }
16727           break;
16728         case DW_TAG_namespace:
16729           SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
16730           list_to_add = &global_symbols;
16731           break;
16732         case DW_TAG_common_block:
16733           SYMBOL_ACLASS_INDEX (sym) = LOC_COMMON_BLOCK;
16734           SYMBOL_DOMAIN (sym) = COMMON_BLOCK_DOMAIN;
16735           add_symbol_to_list (sym, cu->list_in_scope);
16736           break;
16737         default:
16738           /* Not a tag we recognize.  Hopefully we aren't processing
16739              trash data, but since we must specifically ignore things
16740              we don't recognize, there is nothing else we should do at
16741              this point.  */
16742           complaint (&symfile_complaints, _("unsupported tag: '%s'"),
16743                      dwarf_tag_name (die->tag));
16744           break;
16745         }
16746
16747       if (suppress_add)
16748         {
16749           sym->hash_next = objfile->template_symbols;
16750           objfile->template_symbols = sym;
16751           list_to_add = NULL;
16752         }
16753
16754       if (list_to_add != NULL)
16755         add_symbol_to_list (sym, list_to_add);
16756
16757       /* For the benefit of old versions of GCC, check for anonymous
16758          namespaces based on the demangled name.  */
16759       if (!cu->processing_has_namespace_info
16760           && cu->language == language_cplus)
16761         cp_scan_for_anonymous_namespaces (sym, objfile);
16762     }
16763   return (sym);
16764 }
16765
16766 /* A wrapper for new_symbol_full that always allocates a new symbol.  */
16767
16768 static struct symbol *
16769 new_symbol (struct die_info *die, struct type *type, struct dwarf2_cu *cu)
16770 {
16771   return new_symbol_full (die, type, cu, NULL);
16772 }
16773
16774 /* Given an attr with a DW_FORM_dataN value in host byte order,
16775    zero-extend it as appropriate for the symbol's type.  The DWARF
16776    standard (v4) is not entirely clear about the meaning of using
16777    DW_FORM_dataN for a constant with a signed type, where the type is
16778    wider than the data.  The conclusion of a discussion on the DWARF
16779    list was that this is unspecified.  We choose to always zero-extend
16780    because that is the interpretation long in use by GCC.  */
16781
16782 static gdb_byte *
16783 dwarf2_const_value_data (struct attribute *attr, struct obstack *obstack,
16784                          struct dwarf2_cu *cu, LONGEST *value, int bits)
16785 {
16786   struct objfile *objfile = cu->objfile;
16787   enum bfd_endian byte_order = bfd_big_endian (objfile->obfd) ?
16788                                 BFD_ENDIAN_BIG : BFD_ENDIAN_LITTLE;
16789   LONGEST l = DW_UNSND (attr);
16790
16791   if (bits < sizeof (*value) * 8)
16792     {
16793       l &= ((LONGEST) 1 << bits) - 1;
16794       *value = l;
16795     }
16796   else if (bits == sizeof (*value) * 8)
16797     *value = l;
16798   else
16799     {
16800       gdb_byte *bytes = obstack_alloc (obstack, bits / 8);
16801       store_unsigned_integer (bytes, bits / 8, byte_order, l);
16802       return bytes;
16803     }
16804
16805   return NULL;
16806 }
16807
16808 /* Read a constant value from an attribute.  Either set *VALUE, or if
16809    the value does not fit in *VALUE, set *BYTES - either already
16810    allocated on the objfile obstack, or newly allocated on OBSTACK,
16811    or, set *BATON, if we translated the constant to a location
16812    expression.  */
16813
16814 static void
16815 dwarf2_const_value_attr (struct attribute *attr, struct type *type,
16816                          const char *name, struct obstack *obstack,
16817                          struct dwarf2_cu *cu,
16818                          LONGEST *value, const gdb_byte **bytes,
16819                          struct dwarf2_locexpr_baton **baton)
16820 {
16821   struct objfile *objfile = cu->objfile;
16822   struct comp_unit_head *cu_header = &cu->header;
16823   struct dwarf_block *blk;
16824   enum bfd_endian byte_order = (bfd_big_endian (objfile->obfd) ?
16825                                 BFD_ENDIAN_BIG : BFD_ENDIAN_LITTLE);
16826
16827   *value = 0;
16828   *bytes = NULL;
16829   *baton = NULL;
16830
16831   switch (attr->form)
16832     {
16833     case DW_FORM_addr:
16834     case DW_FORM_GNU_addr_index:
16835       {
16836         gdb_byte *data;
16837
16838         if (TYPE_LENGTH (type) != cu_header->addr_size)
16839           dwarf2_const_value_length_mismatch_complaint (name,
16840                                                         cu_header->addr_size,
16841                                                         TYPE_LENGTH (type));
16842         /* Symbols of this form are reasonably rare, so we just
16843            piggyback on the existing location code rather than writing
16844            a new implementation of symbol_computed_ops.  */
16845         *baton = obstack_alloc (obstack, sizeof (struct dwarf2_locexpr_baton));
16846         (*baton)->per_cu = cu->per_cu;
16847         gdb_assert ((*baton)->per_cu);
16848
16849         (*baton)->size = 2 + cu_header->addr_size;
16850         data = obstack_alloc (obstack, (*baton)->size);
16851         (*baton)->data = data;
16852
16853         data[0] = DW_OP_addr;
16854         store_unsigned_integer (&data[1], cu_header->addr_size,
16855                                 byte_order, DW_ADDR (attr));
16856         data[cu_header->addr_size + 1] = DW_OP_stack_value;
16857       }
16858       break;
16859     case DW_FORM_string:
16860     case DW_FORM_strp:
16861     case DW_FORM_GNU_str_index:
16862     case DW_FORM_GNU_strp_alt:
16863       /* DW_STRING is already allocated on the objfile obstack, point
16864          directly to it.  */
16865       *bytes = (const gdb_byte *) DW_STRING (attr);
16866       break;
16867     case DW_FORM_block1:
16868     case DW_FORM_block2:
16869     case DW_FORM_block4:
16870     case DW_FORM_block:
16871     case DW_FORM_exprloc:
16872       blk = DW_BLOCK (attr);
16873       if (TYPE_LENGTH (type) != blk->size)
16874         dwarf2_const_value_length_mismatch_complaint (name, blk->size,
16875                                                       TYPE_LENGTH (type));
16876       *bytes = blk->data;
16877       break;
16878
16879       /* The DW_AT_const_value attributes are supposed to carry the
16880          symbol's value "represented as it would be on the target
16881          architecture."  By the time we get here, it's already been
16882          converted to host endianness, so we just need to sign- or
16883          zero-extend it as appropriate.  */
16884     case DW_FORM_data1:
16885       *bytes = dwarf2_const_value_data (attr, obstack, cu, value, 8);
16886       break;
16887     case DW_FORM_data2:
16888       *bytes = dwarf2_const_value_data (attr, obstack, cu, value, 16);
16889       break;
16890     case DW_FORM_data4:
16891       *bytes = dwarf2_const_value_data (attr, obstack, cu, value, 32);
16892       break;
16893     case DW_FORM_data8:
16894       *bytes = dwarf2_const_value_data (attr, obstack, cu, value, 64);
16895       break;
16896
16897     case DW_FORM_sdata:
16898       *value = DW_SND (attr);
16899       break;
16900
16901     case DW_FORM_udata:
16902       *value = DW_UNSND (attr);
16903       break;
16904
16905     default:
16906       complaint (&symfile_complaints,
16907                  _("unsupported const value attribute form: '%s'"),
16908                  dwarf_form_name (attr->form));
16909       *value = 0;
16910       break;
16911     }
16912 }
16913
16914
16915 /* Copy constant value from an attribute to a symbol.  */
16916
16917 static void
16918 dwarf2_const_value (struct attribute *attr, struct symbol *sym,
16919                     struct dwarf2_cu *cu)
16920 {
16921   struct objfile *objfile = cu->objfile;
16922   struct comp_unit_head *cu_header = &cu->header;
16923   LONGEST value;
16924   const gdb_byte *bytes;
16925   struct dwarf2_locexpr_baton *baton;
16926
16927   dwarf2_const_value_attr (attr, SYMBOL_TYPE (sym),
16928                            SYMBOL_PRINT_NAME (sym),
16929                            &objfile->objfile_obstack, cu,
16930                            &value, &bytes, &baton);
16931
16932   if (baton != NULL)
16933     {
16934       SYMBOL_LOCATION_BATON (sym) = baton;
16935       SYMBOL_ACLASS_INDEX (sym) = dwarf2_locexpr_index;
16936     }
16937   else if (bytes != NULL)
16938      {
16939       SYMBOL_VALUE_BYTES (sym) = bytes;
16940       SYMBOL_ACLASS_INDEX (sym) = LOC_CONST_BYTES;
16941     }
16942   else
16943     {
16944       SYMBOL_VALUE (sym) = value;
16945       SYMBOL_ACLASS_INDEX (sym) = LOC_CONST;
16946     }
16947 }
16948
16949 /* Return the type of the die in question using its DW_AT_type attribute.  */
16950
16951 static struct type *
16952 die_type (struct die_info *die, struct dwarf2_cu *cu)
16953 {
16954   struct attribute *type_attr;
16955
16956   type_attr = dwarf2_attr (die, DW_AT_type, cu);
16957   if (!type_attr)
16958     {
16959       /* A missing DW_AT_type represents a void type.  */
16960       return objfile_type (cu->objfile)->builtin_void;
16961     }
16962
16963   return lookup_die_type (die, type_attr, cu);
16964 }
16965
16966 /* True iff CU's producer generates GNAT Ada auxiliary information
16967    that allows to find parallel types through that information instead
16968    of having to do expensive parallel lookups by type name.  */
16969
16970 static int
16971 need_gnat_info (struct dwarf2_cu *cu)
16972 {
16973   /* FIXME: brobecker/2010-10-12: As of now, only the AdaCore version
16974      of GNAT produces this auxiliary information, without any indication
16975      that it is produced.  Part of enhancing the FSF version of GNAT
16976      to produce that information will be to put in place an indicator
16977      that we can use in order to determine whether the descriptive type
16978      info is available or not.  One suggestion that has been made is
16979      to use a new attribute, attached to the CU die.  For now, assume
16980      that the descriptive type info is not available.  */
16981   return 0;
16982 }
16983
16984 /* Return the auxiliary type of the die in question using its
16985    DW_AT_GNAT_descriptive_type attribute.  Returns NULL if the
16986    attribute is not present.  */
16987
16988 static struct type *
16989 die_descriptive_type (struct die_info *die, struct dwarf2_cu *cu)
16990 {
16991   struct attribute *type_attr;
16992
16993   type_attr = dwarf2_attr (die, DW_AT_GNAT_descriptive_type, cu);
16994   if (!type_attr)
16995     return NULL;
16996
16997   return lookup_die_type (die, type_attr, cu);
16998 }
16999
17000 /* If DIE has a descriptive_type attribute, then set the TYPE's
17001    descriptive type accordingly.  */
17002
17003 static void
17004 set_descriptive_type (struct type *type, struct die_info *die,
17005                       struct dwarf2_cu *cu)
17006 {
17007   struct type *descriptive_type = die_descriptive_type (die, cu);
17008
17009   if (descriptive_type)
17010     {
17011       ALLOCATE_GNAT_AUX_TYPE (type);
17012       TYPE_DESCRIPTIVE_TYPE (type) = descriptive_type;
17013     }
17014 }
17015
17016 /* Return the containing type of the die in question using its
17017    DW_AT_containing_type attribute.  */
17018
17019 static struct type *
17020 die_containing_type (struct die_info *die, struct dwarf2_cu *cu)
17021 {
17022   struct attribute *type_attr;
17023
17024   type_attr = dwarf2_attr (die, DW_AT_containing_type, cu);
17025   if (!type_attr)
17026     error (_("Dwarf Error: Problem turning containing type into gdb type "
17027              "[in module %s]"), cu->objfile->name);
17028
17029   return lookup_die_type (die, type_attr, cu);
17030 }
17031
17032 /* Return an error marker type to use for the ill formed type in DIE/CU.  */
17033
17034 static struct type *
17035 build_error_marker_type (struct dwarf2_cu *cu, struct die_info *die)
17036 {
17037   struct objfile *objfile = dwarf2_per_objfile->objfile;
17038   char *message, *saved;
17039
17040   message = xstrprintf (_("<unknown type in %s, CU 0x%x, DIE 0x%x>"),
17041                         objfile->name,
17042                         cu->header.offset.sect_off,
17043                         die->offset.sect_off);
17044   saved = obstack_copy0 (&objfile->objfile_obstack,
17045                          message, strlen (message));
17046   xfree (message);
17047
17048   return init_type (TYPE_CODE_ERROR, 0, 0, saved, objfile);
17049 }
17050
17051 /* Look up the type of DIE in CU using its type attribute ATTR.
17052    ATTR must be one of: DW_AT_type, DW_AT_GNAT_descriptive_type,
17053    DW_AT_containing_type.
17054    If there is no type substitute an error marker.  */
17055
17056 static struct type *
17057 lookup_die_type (struct die_info *die, struct attribute *attr,
17058                  struct dwarf2_cu *cu)
17059 {
17060   struct objfile *objfile = cu->objfile;
17061   struct type *this_type;
17062
17063   gdb_assert (attr->name == DW_AT_type
17064               || attr->name == DW_AT_GNAT_descriptive_type
17065               || attr->name == DW_AT_containing_type);
17066
17067   /* First see if we have it cached.  */
17068
17069   if (attr->form == DW_FORM_GNU_ref_alt)
17070     {
17071       struct dwarf2_per_cu_data *per_cu;
17072       sect_offset offset = dwarf2_get_ref_die_offset (attr);
17073
17074       per_cu = dwarf2_find_containing_comp_unit (offset, 1, cu->objfile);
17075       this_type = get_die_type_at_offset (offset, per_cu);
17076     }
17077   else if (is_ref_attr (attr))
17078     {
17079       sect_offset offset = dwarf2_get_ref_die_offset (attr);
17080
17081       this_type = get_die_type_at_offset (offset, cu->per_cu);
17082     }
17083   else if (attr->form == DW_FORM_ref_sig8)
17084     {
17085       ULONGEST signature = DW_SIGNATURE (attr);
17086
17087       return get_signatured_type (die, signature, cu);
17088     }
17089   else
17090     {
17091       complaint (&symfile_complaints,
17092                  _("Dwarf Error: Bad type attribute %s in DIE"
17093                    " at 0x%x [in module %s]"),
17094                  dwarf_attr_name (attr->name), die->offset.sect_off,
17095                  objfile->name);
17096       return build_error_marker_type (cu, die);
17097     }
17098
17099   /* If not cached we need to read it in.  */
17100
17101   if (this_type == NULL)
17102     {
17103       struct die_info *type_die = NULL;
17104       struct dwarf2_cu *type_cu = cu;
17105
17106       if (is_ref_attr (attr))
17107         type_die = follow_die_ref (die, attr, &type_cu);
17108       if (type_die == NULL)
17109         return build_error_marker_type (cu, die);
17110       /* If we find the type now, it's probably because the type came
17111          from an inter-CU reference and the type's CU got expanded before
17112          ours.  */
17113       this_type = read_type_die (type_die, type_cu);
17114     }
17115
17116   /* If we still don't have a type use an error marker.  */
17117
17118   if (this_type == NULL)
17119     return build_error_marker_type (cu, die);
17120
17121   return this_type;
17122 }
17123
17124 /* Return the type in DIE, CU.
17125    Returns NULL for invalid types.
17126
17127    This first does a lookup in die_type_hash,
17128    and only reads the die in if necessary.
17129
17130    NOTE: This can be called when reading in partial or full symbols.  */
17131
17132 static struct type *
17133 read_type_die (struct die_info *die, struct dwarf2_cu *cu)
17134 {
17135   struct type *this_type;
17136
17137   this_type = get_die_type (die, cu);
17138   if (this_type)
17139     return this_type;
17140
17141   return read_type_die_1 (die, cu);
17142 }
17143
17144 /* Read the type in DIE, CU.
17145    Returns NULL for invalid types.  */
17146
17147 static struct type *
17148 read_type_die_1 (struct die_info *die, struct dwarf2_cu *cu)
17149 {
17150   struct type *this_type = NULL;
17151
17152   switch (die->tag)
17153     {
17154     case DW_TAG_class_type:
17155     case DW_TAG_interface_type:
17156     case DW_TAG_structure_type:
17157     case DW_TAG_union_type:
17158       this_type = read_structure_type (die, cu);
17159       break;
17160     case DW_TAG_enumeration_type:
17161       this_type = read_enumeration_type (die, cu);
17162       break;
17163     case DW_TAG_subprogram:
17164     case DW_TAG_subroutine_type:
17165     case DW_TAG_inlined_subroutine:
17166       this_type = read_subroutine_type (die, cu);
17167       break;
17168     case DW_TAG_array_type:
17169       this_type = read_array_type (die, cu);
17170       break;
17171     case DW_TAG_set_type:
17172       this_type = read_set_type (die, cu);
17173       break;
17174     case DW_TAG_pointer_type:
17175       this_type = read_tag_pointer_type (die, cu);
17176       break;
17177     case DW_TAG_ptr_to_member_type:
17178       this_type = read_tag_ptr_to_member_type (die, cu);
17179       break;
17180     case DW_TAG_reference_type:
17181       this_type = read_tag_reference_type (die, cu);
17182       break;
17183     case DW_TAG_const_type:
17184       this_type = read_tag_const_type (die, cu);
17185       break;
17186     case DW_TAG_volatile_type:
17187       this_type = read_tag_volatile_type (die, cu);
17188       break;
17189     case DW_TAG_restrict_type:
17190       this_type = read_tag_restrict_type (die, cu);
17191       break;
17192     case DW_TAG_string_type:
17193       this_type = read_tag_string_type (die, cu);
17194       break;
17195     case DW_TAG_typedef:
17196       this_type = read_typedef (die, cu);
17197       break;
17198     case DW_TAG_subrange_type:
17199       this_type = read_subrange_type (die, cu);
17200       break;
17201     case DW_TAG_base_type:
17202       this_type = read_base_type (die, cu);
17203       break;
17204     case DW_TAG_unspecified_type:
17205       this_type = read_unspecified_type (die, cu);
17206       break;
17207     case DW_TAG_namespace:
17208       this_type = read_namespace_type (die, cu);
17209       break;
17210     case DW_TAG_module:
17211       this_type = read_module_type (die, cu);
17212       break;
17213     default:
17214       complaint (&symfile_complaints,
17215                  _("unexpected tag in read_type_die: '%s'"),
17216                  dwarf_tag_name (die->tag));
17217       break;
17218     }
17219
17220   return this_type;
17221 }
17222
17223 /* See if we can figure out if the class lives in a namespace.  We do
17224    this by looking for a member function; its demangled name will
17225    contain namespace info, if there is any.
17226    Return the computed name or NULL.
17227    Space for the result is allocated on the objfile's obstack.
17228    This is the full-die version of guess_partial_die_structure_name.
17229    In this case we know DIE has no useful parent.  */
17230
17231 static char *
17232 guess_full_die_structure_name (struct die_info *die, struct dwarf2_cu *cu)
17233 {
17234   struct die_info *spec_die;
17235   struct dwarf2_cu *spec_cu;
17236   struct die_info *child;
17237
17238   spec_cu = cu;
17239   spec_die = die_specification (die, &spec_cu);
17240   if (spec_die != NULL)
17241     {
17242       die = spec_die;
17243       cu = spec_cu;
17244     }
17245
17246   for (child = die->child;
17247        child != NULL;
17248        child = child->sibling)
17249     {
17250       if (child->tag == DW_TAG_subprogram)
17251         {
17252           struct attribute *attr;
17253
17254           attr = dwarf2_attr (child, DW_AT_linkage_name, cu);
17255           if (attr == NULL)
17256             attr = dwarf2_attr (child, DW_AT_MIPS_linkage_name, cu);
17257           if (attr != NULL)
17258             {
17259               char *actual_name
17260                 = language_class_name_from_physname (cu->language_defn,
17261                                                      DW_STRING (attr));
17262               char *name = NULL;
17263
17264               if (actual_name != NULL)
17265                 {
17266                   const char *die_name = dwarf2_name (die, cu);
17267
17268                   if (die_name != NULL
17269                       && strcmp (die_name, actual_name) != 0)
17270                     {
17271                       /* Strip off the class name from the full name.
17272                          We want the prefix.  */
17273                       int die_name_len = strlen (die_name);
17274                       int actual_name_len = strlen (actual_name);
17275
17276                       /* Test for '::' as a sanity check.  */
17277                       if (actual_name_len > die_name_len + 2
17278                           && actual_name[actual_name_len
17279                                          - die_name_len - 1] == ':')
17280                         name =
17281                           obstack_copy0 (&cu->objfile->objfile_obstack,
17282                                          actual_name,
17283                                          actual_name_len - die_name_len - 2);
17284                     }
17285                 }
17286               xfree (actual_name);
17287               return name;
17288             }
17289         }
17290     }
17291
17292   return NULL;
17293 }
17294
17295 /* GCC might emit a nameless typedef that has a linkage name.  Determine the
17296    prefix part in such case.  See
17297    http://gcc.gnu.org/bugzilla/show_bug.cgi?id=47510.  */
17298
17299 static char *
17300 anonymous_struct_prefix (struct die_info *die, struct dwarf2_cu *cu)
17301 {
17302   struct attribute *attr;
17303   char *base;
17304
17305   if (die->tag != DW_TAG_class_type && die->tag != DW_TAG_interface_type
17306       && die->tag != DW_TAG_structure_type && die->tag != DW_TAG_union_type)
17307     return NULL;
17308
17309   attr = dwarf2_attr (die, DW_AT_name, cu);
17310   if (attr != NULL && DW_STRING (attr) != NULL)
17311     return NULL;
17312
17313   attr = dwarf2_attr (die, DW_AT_linkage_name, cu);
17314   if (attr == NULL)
17315     attr = dwarf2_attr (die, DW_AT_MIPS_linkage_name, cu);
17316   if (attr == NULL || DW_STRING (attr) == NULL)
17317     return NULL;
17318
17319   /* dwarf2_name had to be already called.  */
17320   gdb_assert (DW_STRING_IS_CANONICAL (attr));
17321
17322   /* Strip the base name, keep any leading namespaces/classes.  */
17323   base = strrchr (DW_STRING (attr), ':');
17324   if (base == NULL || base == DW_STRING (attr) || base[-1] != ':')
17325     return "";
17326
17327   return obstack_copy0 (&cu->objfile->objfile_obstack,
17328                         DW_STRING (attr), &base[-1] - DW_STRING (attr));
17329 }
17330
17331 /* Return the name of the namespace/class that DIE is defined within,
17332    or "" if we can't tell.  The caller should not xfree the result.
17333
17334    For example, if we're within the method foo() in the following
17335    code:
17336
17337    namespace N {
17338      class C {
17339        void foo () {
17340        }
17341      };
17342    }
17343
17344    then determine_prefix on foo's die will return "N::C".  */
17345
17346 static const char *
17347 determine_prefix (struct die_info *die, struct dwarf2_cu *cu)
17348 {
17349   struct die_info *parent, *spec_die;
17350   struct dwarf2_cu *spec_cu;
17351   struct type *parent_type;
17352   char *retval;
17353
17354   if (cu->language != language_cplus && cu->language != language_java
17355       && cu->language != language_fortran)
17356     return "";
17357
17358   retval = anonymous_struct_prefix (die, cu);
17359   if (retval)
17360     return retval;
17361
17362   /* We have to be careful in the presence of DW_AT_specification.
17363      For example, with GCC 3.4, given the code
17364
17365      namespace N {
17366        void foo() {
17367          // Definition of N::foo.
17368        }
17369      }
17370
17371      then we'll have a tree of DIEs like this:
17372
17373      1: DW_TAG_compile_unit
17374        2: DW_TAG_namespace        // N
17375          3: DW_TAG_subprogram     // declaration of N::foo
17376        4: DW_TAG_subprogram       // definition of N::foo
17377             DW_AT_specification   // refers to die #3
17378
17379      Thus, when processing die #4, we have to pretend that we're in
17380      the context of its DW_AT_specification, namely the contex of die
17381      #3.  */
17382   spec_cu = cu;
17383   spec_die = die_specification (die, &spec_cu);
17384   if (spec_die == NULL)
17385     parent = die->parent;
17386   else
17387     {
17388       parent = spec_die->parent;
17389       cu = spec_cu;
17390     }
17391
17392   if (parent == NULL)
17393     return "";
17394   else if (parent->building_fullname)
17395     {
17396       const char *name;
17397       const char *parent_name;
17398
17399       /* It has been seen on RealView 2.2 built binaries,
17400          DW_TAG_template_type_param types actually _defined_ as
17401          children of the parent class:
17402
17403          enum E {};
17404          template class <class Enum> Class{};
17405          Class<enum E> class_e;
17406
17407          1: DW_TAG_class_type (Class)
17408            2: DW_TAG_enumeration_type (E)
17409              3: DW_TAG_enumerator (enum1:0)
17410              3: DW_TAG_enumerator (enum2:1)
17411              ...
17412            2: DW_TAG_template_type_param
17413               DW_AT_type  DW_FORM_ref_udata (E)
17414
17415          Besides being broken debug info, it can put GDB into an
17416          infinite loop.  Consider:
17417
17418          When we're building the full name for Class<E>, we'll start
17419          at Class, and go look over its template type parameters,
17420          finding E.  We'll then try to build the full name of E, and
17421          reach here.  We're now trying to build the full name of E,
17422          and look over the parent DIE for containing scope.  In the
17423          broken case, if we followed the parent DIE of E, we'd again
17424          find Class, and once again go look at its template type
17425          arguments, etc., etc.  Simply don't consider such parent die
17426          as source-level parent of this die (it can't be, the language
17427          doesn't allow it), and break the loop here.  */
17428       name = dwarf2_name (die, cu);
17429       parent_name = dwarf2_name (parent, cu);
17430       complaint (&symfile_complaints,
17431                  _("template param type '%s' defined within parent '%s'"),
17432                  name ? name : "<unknown>",
17433                  parent_name ? parent_name : "<unknown>");
17434       return "";
17435     }
17436   else
17437     switch (parent->tag)
17438       {
17439       case DW_TAG_namespace:
17440         parent_type = read_type_die (parent, cu);
17441         /* GCC 4.0 and 4.1 had a bug (PR c++/28460) where they generated bogus
17442            DW_TAG_namespace DIEs with a name of "::" for the global namespace.
17443            Work around this problem here.  */
17444         if (cu->language == language_cplus
17445             && strcmp (TYPE_TAG_NAME (parent_type), "::") == 0)
17446           return "";
17447         /* We give a name to even anonymous namespaces.  */
17448         return TYPE_TAG_NAME (parent_type);
17449       case DW_TAG_class_type:
17450       case DW_TAG_interface_type:
17451       case DW_TAG_structure_type:
17452       case DW_TAG_union_type:
17453       case DW_TAG_module:
17454         parent_type = read_type_die (parent, cu);
17455         if (TYPE_TAG_NAME (parent_type) != NULL)
17456           return TYPE_TAG_NAME (parent_type);
17457         else
17458           /* An anonymous structure is only allowed non-static data
17459              members; no typedefs, no member functions, et cetera.
17460              So it does not need a prefix.  */
17461           return "";
17462       case DW_TAG_compile_unit:
17463       case DW_TAG_partial_unit:
17464         /* gcc-4.5 -gdwarf-4 can drop the enclosing namespace.  Cope.  */
17465         if (cu->language == language_cplus
17466             && !VEC_empty (dwarf2_section_info_def, dwarf2_per_objfile->types)
17467             && die->child != NULL
17468             && (die->tag == DW_TAG_class_type
17469                 || die->tag == DW_TAG_structure_type
17470                 || die->tag == DW_TAG_union_type))
17471           {
17472             char *name = guess_full_die_structure_name (die, cu);
17473             if (name != NULL)
17474               return name;
17475           }
17476         return "";
17477       default:
17478         return determine_prefix (parent, cu);
17479       }
17480 }
17481
17482 /* Return a newly-allocated string formed by concatenating PREFIX and SUFFIX
17483    with appropriate separator.  If PREFIX or SUFFIX is NULL or empty, then
17484    simply copy the SUFFIX or PREFIX, respectively.  If OBS is non-null, perform
17485    an obconcat, otherwise allocate storage for the result.  The CU argument is
17486    used to determine the language and hence, the appropriate separator.  */
17487
17488 #define MAX_SEP_LEN 7  /* strlen ("__") + strlen ("_MOD_")  */
17489
17490 static char *
17491 typename_concat (struct obstack *obs, const char *prefix, const char *suffix,
17492                  int physname, struct dwarf2_cu *cu)
17493 {
17494   const char *lead = "";
17495   const char *sep;
17496
17497   if (suffix == NULL || suffix[0] == '\0'
17498       || prefix == NULL || prefix[0] == '\0')
17499     sep = "";
17500   else if (cu->language == language_java)
17501     sep = ".";
17502   else if (cu->language == language_fortran && physname)
17503     {
17504       /* This is gfortran specific mangling.  Normally DW_AT_linkage_name or
17505          DW_AT_MIPS_linkage_name is preferred and used instead.  */
17506
17507       lead = "__";
17508       sep = "_MOD_";
17509     }
17510   else
17511     sep = "::";
17512
17513   if (prefix == NULL)
17514     prefix = "";
17515   if (suffix == NULL)
17516     suffix = "";
17517
17518   if (obs == NULL)
17519     {
17520       char *retval
17521         = xmalloc (strlen (prefix) + MAX_SEP_LEN + strlen (suffix) + 1);
17522
17523       strcpy (retval, lead);
17524       strcat (retval, prefix);
17525       strcat (retval, sep);
17526       strcat (retval, suffix);
17527       return retval;
17528     }
17529   else
17530     {
17531       /* We have an obstack.  */
17532       return obconcat (obs, lead, prefix, sep, suffix, (char *) NULL);
17533     }
17534 }
17535
17536 /* Return sibling of die, NULL if no sibling.  */
17537
17538 static struct die_info *
17539 sibling_die (struct die_info *die)
17540 {
17541   return die->sibling;
17542 }
17543
17544 /* Get name of a die, return NULL if not found.  */
17545
17546 static const char *
17547 dwarf2_canonicalize_name (const char *name, struct dwarf2_cu *cu,
17548                           struct obstack *obstack)
17549 {
17550   if (name && cu->language == language_cplus)
17551     {
17552       char *canon_name = cp_canonicalize_string (name);
17553
17554       if (canon_name != NULL)
17555         {
17556           if (strcmp (canon_name, name) != 0)
17557             name = obstack_copy0 (obstack, canon_name, strlen (canon_name));
17558           xfree (canon_name);
17559         }
17560     }
17561
17562   return name;
17563 }
17564
17565 /* Get name of a die, return NULL if not found.  */
17566
17567 static const char *
17568 dwarf2_name (struct die_info *die, struct dwarf2_cu *cu)
17569 {
17570   struct attribute *attr;
17571
17572   attr = dwarf2_attr (die, DW_AT_name, cu);
17573   if ((!attr || !DW_STRING (attr))
17574       && die->tag != DW_TAG_class_type
17575       && die->tag != DW_TAG_interface_type
17576       && die->tag != DW_TAG_structure_type
17577       && die->tag != DW_TAG_union_type)
17578     return NULL;
17579
17580   switch (die->tag)
17581     {
17582     case DW_TAG_compile_unit:
17583     case DW_TAG_partial_unit:
17584       /* Compilation units have a DW_AT_name that is a filename, not
17585          a source language identifier.  */
17586     case DW_TAG_enumeration_type:
17587     case DW_TAG_enumerator:
17588       /* These tags always have simple identifiers already; no need
17589          to canonicalize them.  */
17590       return DW_STRING (attr);
17591
17592     case DW_TAG_subprogram:
17593       /* Java constructors will all be named "<init>", so return
17594          the class name when we see this special case.  */
17595       if (cu->language == language_java
17596           && DW_STRING (attr) != NULL
17597           && strcmp (DW_STRING (attr), "<init>") == 0)
17598         {
17599           struct dwarf2_cu *spec_cu = cu;
17600           struct die_info *spec_die;
17601
17602           /* GCJ will output '<init>' for Java constructor names.
17603              For this special case, return the name of the parent class.  */
17604
17605           /* GCJ may output suprogram DIEs with AT_specification set.
17606              If so, use the name of the specified DIE.  */
17607           spec_die = die_specification (die, &spec_cu);
17608           if (spec_die != NULL)
17609             return dwarf2_name (spec_die, spec_cu);
17610
17611           do
17612             {
17613               die = die->parent;
17614               if (die->tag == DW_TAG_class_type)
17615                 return dwarf2_name (die, cu);
17616             }
17617           while (die->tag != DW_TAG_compile_unit
17618                  && die->tag != DW_TAG_partial_unit);
17619         }
17620       break;
17621
17622     case DW_TAG_class_type:
17623     case DW_TAG_interface_type:
17624     case DW_TAG_structure_type:
17625     case DW_TAG_union_type:
17626       /* Some GCC versions emit spurious DW_AT_name attributes for unnamed
17627          structures or unions.  These were of the form "._%d" in GCC 4.1,
17628          or simply "<anonymous struct>" or "<anonymous union>" in GCC 4.3
17629          and GCC 4.4.  We work around this problem by ignoring these.  */
17630       if (attr && DW_STRING (attr)
17631           && (strncmp (DW_STRING (attr), "._", 2) == 0
17632               || strncmp (DW_STRING (attr), "<anonymous", 10) == 0))
17633         return NULL;
17634
17635       /* GCC might emit a nameless typedef that has a linkage name.  See
17636          http://gcc.gnu.org/bugzilla/show_bug.cgi?id=47510.  */
17637       if (!attr || DW_STRING (attr) == NULL)
17638         {
17639           char *demangled = NULL;
17640
17641           attr = dwarf2_attr (die, DW_AT_linkage_name, cu);
17642           if (attr == NULL)
17643             attr = dwarf2_attr (die, DW_AT_MIPS_linkage_name, cu);
17644
17645           if (attr == NULL || DW_STRING (attr) == NULL)
17646             return NULL;
17647
17648           /* Avoid demangling DW_STRING (attr) the second time on a second
17649              call for the same DIE.  */
17650           if (!DW_STRING_IS_CANONICAL (attr))
17651             demangled = gdb_demangle (DW_STRING (attr), DMGL_TYPES);
17652
17653           if (demangled)
17654             {
17655               char *base;
17656
17657               /* FIXME: we already did this for the partial symbol... */
17658               DW_STRING (attr) = obstack_copy0 (&cu->objfile->objfile_obstack,
17659                                                 demangled, strlen (demangled));
17660               DW_STRING_IS_CANONICAL (attr) = 1;
17661               xfree (demangled);
17662
17663               /* Strip any leading namespaces/classes, keep only the base name.
17664                  DW_AT_name for named DIEs does not contain the prefixes.  */
17665               base = strrchr (DW_STRING (attr), ':');
17666               if (base && base > DW_STRING (attr) && base[-1] == ':')
17667                 return &base[1];
17668               else
17669                 return DW_STRING (attr);
17670             }
17671         }
17672       break;
17673
17674     default:
17675       break;
17676     }
17677
17678   if (!DW_STRING_IS_CANONICAL (attr))
17679     {
17680       DW_STRING (attr)
17681         = dwarf2_canonicalize_name (DW_STRING (attr), cu,
17682                                     &cu->objfile->objfile_obstack);
17683       DW_STRING_IS_CANONICAL (attr) = 1;
17684     }
17685   return DW_STRING (attr);
17686 }
17687
17688 /* Return the die that this die in an extension of, or NULL if there
17689    is none.  *EXT_CU is the CU containing DIE on input, and the CU
17690    containing the return value on output.  */
17691
17692 static struct die_info *
17693 dwarf2_extension (struct die_info *die, struct dwarf2_cu **ext_cu)
17694 {
17695   struct attribute *attr;
17696
17697   attr = dwarf2_attr (die, DW_AT_extension, *ext_cu);
17698   if (attr == NULL)
17699     return NULL;
17700
17701   return follow_die_ref (die, attr, ext_cu);
17702 }
17703
17704 /* Convert a DIE tag into its string name.  */
17705
17706 static const char *
17707 dwarf_tag_name (unsigned tag)
17708 {
17709   const char *name = get_DW_TAG_name (tag);
17710
17711   if (name == NULL)
17712     return "DW_TAG_<unknown>";
17713
17714   return name;
17715 }
17716
17717 /* Convert a DWARF attribute code into its string name.  */
17718
17719 static const char *
17720 dwarf_attr_name (unsigned attr)
17721 {
17722   const char *name;
17723
17724 #ifdef MIPS /* collides with DW_AT_HP_block_index */
17725   if (attr == DW_AT_MIPS_fde)
17726     return "DW_AT_MIPS_fde";
17727 #else
17728   if (attr == DW_AT_HP_block_index)
17729     return "DW_AT_HP_block_index";
17730 #endif
17731
17732   name = get_DW_AT_name (attr);
17733
17734   if (name == NULL)
17735     return "DW_AT_<unknown>";
17736
17737   return name;
17738 }
17739
17740 /* Convert a DWARF value form code into its string name.  */
17741
17742 static const char *
17743 dwarf_form_name (unsigned form)
17744 {
17745   const char *name = get_DW_FORM_name (form);
17746
17747   if (name == NULL)
17748     return "DW_FORM_<unknown>";
17749
17750   return name;
17751 }
17752
17753 static char *
17754 dwarf_bool_name (unsigned mybool)
17755 {
17756   if (mybool)
17757     return "TRUE";
17758   else
17759     return "FALSE";
17760 }
17761
17762 /* Convert a DWARF type code into its string name.  */
17763
17764 static const char *
17765 dwarf_type_encoding_name (unsigned enc)
17766 {
17767   const char *name = get_DW_ATE_name (enc);
17768
17769   if (name == NULL)
17770     return "DW_ATE_<unknown>";
17771
17772   return name;
17773 }
17774
17775 static void
17776 dump_die_shallow (struct ui_file *f, int indent, struct die_info *die)
17777 {
17778   unsigned int i;
17779
17780   print_spaces (indent, f);
17781   fprintf_unfiltered (f, "Die: %s (abbrev %d, offset 0x%x)\n",
17782            dwarf_tag_name (die->tag), die->abbrev, die->offset.sect_off);
17783
17784   if (die->parent != NULL)
17785     {
17786       print_spaces (indent, f);
17787       fprintf_unfiltered (f, "  parent at offset: 0x%x\n",
17788                           die->parent->offset.sect_off);
17789     }
17790
17791   print_spaces (indent, f);
17792   fprintf_unfiltered (f, "  has children: %s\n",
17793            dwarf_bool_name (die->child != NULL));
17794
17795   print_spaces (indent, f);
17796   fprintf_unfiltered (f, "  attributes:\n");
17797
17798   for (i = 0; i < die->num_attrs; ++i)
17799     {
17800       print_spaces (indent, f);
17801       fprintf_unfiltered (f, "    %s (%s) ",
17802                dwarf_attr_name (die->attrs[i].name),
17803                dwarf_form_name (die->attrs[i].form));
17804
17805       switch (die->attrs[i].form)
17806         {
17807         case DW_FORM_addr:
17808         case DW_FORM_GNU_addr_index:
17809           fprintf_unfiltered (f, "address: ");
17810           fputs_filtered (hex_string (DW_ADDR (&die->attrs[i])), f);
17811           break;
17812         case DW_FORM_block2:
17813         case DW_FORM_block4:
17814         case DW_FORM_block:
17815         case DW_FORM_block1:
17816           fprintf_unfiltered (f, "block: size %s",
17817                               pulongest (DW_BLOCK (&die->attrs[i])->size));
17818           break;
17819         case DW_FORM_exprloc:
17820           fprintf_unfiltered (f, "expression: size %s",
17821                               pulongest (DW_BLOCK (&die->attrs[i])->size));
17822           break;
17823         case DW_FORM_ref_addr:
17824           fprintf_unfiltered (f, "ref address: ");
17825           fputs_filtered (hex_string (DW_UNSND (&die->attrs[i])), f);
17826           break;
17827         case DW_FORM_GNU_ref_alt:
17828           fprintf_unfiltered (f, "alt ref address: ");
17829           fputs_filtered (hex_string (DW_UNSND (&die->attrs[i])), f);
17830           break;
17831         case DW_FORM_ref1:
17832         case DW_FORM_ref2:
17833         case DW_FORM_ref4:
17834         case DW_FORM_ref8:
17835         case DW_FORM_ref_udata:
17836           fprintf_unfiltered (f, "constant ref: 0x%lx (adjusted)",
17837                               (long) (DW_UNSND (&die->attrs[i])));
17838           break;
17839         case DW_FORM_data1:
17840         case DW_FORM_data2:
17841         case DW_FORM_data4:
17842         case DW_FORM_data8:
17843         case DW_FORM_udata:
17844         case DW_FORM_sdata:
17845           fprintf_unfiltered (f, "constant: %s",
17846                               pulongest (DW_UNSND (&die->attrs[i])));
17847           break;
17848         case DW_FORM_sec_offset:
17849           fprintf_unfiltered (f, "section offset: %s",
17850                               pulongest (DW_UNSND (&die->attrs[i])));
17851           break;
17852         case DW_FORM_ref_sig8:
17853           fprintf_unfiltered (f, "signature: %s",
17854                               hex_string (DW_SIGNATURE (&die->attrs[i])));
17855           break;
17856         case DW_FORM_string:
17857         case DW_FORM_strp:
17858         case DW_FORM_GNU_str_index:
17859         case DW_FORM_GNU_strp_alt:
17860           fprintf_unfiltered (f, "string: \"%s\" (%s canonicalized)",
17861                    DW_STRING (&die->attrs[i])
17862                    ? DW_STRING (&die->attrs[i]) : "",
17863                    DW_STRING_IS_CANONICAL (&die->attrs[i]) ? "is" : "not");
17864           break;
17865         case DW_FORM_flag:
17866           if (DW_UNSND (&die->attrs[i]))
17867             fprintf_unfiltered (f, "flag: TRUE");
17868           else
17869             fprintf_unfiltered (f, "flag: FALSE");
17870           break;
17871         case DW_FORM_flag_present:
17872           fprintf_unfiltered (f, "flag: TRUE");
17873           break;
17874         case DW_FORM_indirect:
17875           /* The reader will have reduced the indirect form to
17876              the "base form" so this form should not occur.  */
17877           fprintf_unfiltered (f, 
17878                               "unexpected attribute form: DW_FORM_indirect");
17879           break;
17880         default:
17881           fprintf_unfiltered (f, "unsupported attribute form: %d.",
17882                    die->attrs[i].form);
17883           break;
17884         }
17885       fprintf_unfiltered (f, "\n");
17886     }
17887 }
17888
17889 static void
17890 dump_die_for_error (struct die_info *die)
17891 {
17892   dump_die_shallow (gdb_stderr, 0, die);
17893 }
17894
17895 static void
17896 dump_die_1 (struct ui_file *f, int level, int max_level, struct die_info *die)
17897 {
17898   int indent = level * 4;
17899
17900   gdb_assert (die != NULL);
17901
17902   if (level >= max_level)
17903     return;
17904
17905   dump_die_shallow (f, indent, die);
17906
17907   if (die->child != NULL)
17908     {
17909       print_spaces (indent, f);
17910       fprintf_unfiltered (f, "  Children:");
17911       if (level + 1 < max_level)
17912         {
17913           fprintf_unfiltered (f, "\n");
17914           dump_die_1 (f, level + 1, max_level, die->child);
17915         }
17916       else
17917         {
17918           fprintf_unfiltered (f,
17919                               " [not printed, max nesting level reached]\n");
17920         }
17921     }
17922
17923   if (die->sibling != NULL && level > 0)
17924     {
17925       dump_die_1 (f, level, max_level, die->sibling);
17926     }
17927 }
17928
17929 /* This is called from the pdie macro in gdbinit.in.
17930    It's not static so gcc will keep a copy callable from gdb.  */
17931
17932 void
17933 dump_die (struct die_info *die, int max_level)
17934 {
17935   dump_die_1 (gdb_stdlog, 0, max_level, die);
17936 }
17937
17938 static void
17939 store_in_ref_table (struct die_info *die, struct dwarf2_cu *cu)
17940 {
17941   void **slot;
17942
17943   slot = htab_find_slot_with_hash (cu->die_hash, die, die->offset.sect_off,
17944                                    INSERT);
17945
17946   *slot = die;
17947 }
17948
17949 /* DW_ADDR is always stored already as sect_offset; despite for the forms
17950    besides DW_FORM_ref_addr it is stored as cu_offset in the DWARF file.  */
17951
17952 static int
17953 is_ref_attr (struct attribute *attr)
17954 {
17955   switch (attr->form)
17956     {
17957     case DW_FORM_ref_addr:
17958     case DW_FORM_ref1:
17959     case DW_FORM_ref2:
17960     case DW_FORM_ref4:
17961     case DW_FORM_ref8:
17962     case DW_FORM_ref_udata:
17963     case DW_FORM_GNU_ref_alt:
17964       return 1;
17965     default:
17966       return 0;
17967     }
17968 }
17969
17970 /* Return DIE offset of ATTR.  Return 0 with complaint if ATTR is not of the
17971    required kind.  */
17972
17973 static sect_offset
17974 dwarf2_get_ref_die_offset (struct attribute *attr)
17975 {
17976   sect_offset retval = { DW_UNSND (attr) };
17977
17978   if (is_ref_attr (attr))
17979     return retval;
17980
17981   retval.sect_off = 0;
17982   complaint (&symfile_complaints,
17983              _("unsupported die ref attribute form: '%s'"),
17984              dwarf_form_name (attr->form));
17985   return retval;
17986 }
17987
17988 /* Return the constant value held by ATTR.  Return DEFAULT_VALUE if
17989  * the value held by the attribute is not constant.  */
17990
17991 static LONGEST
17992 dwarf2_get_attr_constant_value (struct attribute *attr, int default_value)
17993 {
17994   if (attr->form == DW_FORM_sdata)
17995     return DW_SND (attr);
17996   else if (attr->form == DW_FORM_udata
17997            || attr->form == DW_FORM_data1
17998            || attr->form == DW_FORM_data2
17999            || attr->form == DW_FORM_data4
18000            || attr->form == DW_FORM_data8)
18001     return DW_UNSND (attr);
18002   else
18003     {
18004       complaint (&symfile_complaints,
18005                  _("Attribute value is not a constant (%s)"),
18006                  dwarf_form_name (attr->form));
18007       return default_value;
18008     }
18009 }
18010
18011 /* Follow reference or signature attribute ATTR of SRC_DIE.
18012    On entry *REF_CU is the CU of SRC_DIE.
18013    On exit *REF_CU is the CU of the result.  */
18014
18015 static struct die_info *
18016 follow_die_ref_or_sig (struct die_info *src_die, struct attribute *attr,
18017                        struct dwarf2_cu **ref_cu)
18018 {
18019   struct die_info *die;
18020
18021   if (is_ref_attr (attr))
18022     die = follow_die_ref (src_die, attr, ref_cu);
18023   else if (attr->form == DW_FORM_ref_sig8)
18024     die = follow_die_sig (src_die, attr, ref_cu);
18025   else
18026     {
18027       dump_die_for_error (src_die);
18028       error (_("Dwarf Error: Expected reference attribute [in module %s]"),
18029              (*ref_cu)->objfile->name);
18030     }
18031
18032   return die;
18033 }
18034
18035 /* Follow reference OFFSET.
18036    On entry *REF_CU is the CU of the source die referencing OFFSET.
18037    On exit *REF_CU is the CU of the result.
18038    Returns NULL if OFFSET is invalid.  */
18039
18040 static struct die_info *
18041 follow_die_offset (sect_offset offset, int offset_in_dwz,
18042                    struct dwarf2_cu **ref_cu)
18043 {
18044   struct die_info temp_die;
18045   struct dwarf2_cu *target_cu, *cu = *ref_cu;
18046
18047   gdb_assert (cu->per_cu != NULL);
18048
18049   target_cu = cu;
18050
18051   if (cu->per_cu->is_debug_types)
18052     {
18053       /* .debug_types CUs cannot reference anything outside their CU.
18054          If they need to, they have to reference a signatured type via
18055          DW_FORM_ref_sig8.  */
18056       if (! offset_in_cu_p (&cu->header, offset))
18057         return NULL;
18058     }
18059   else if (offset_in_dwz != cu->per_cu->is_dwz
18060            || ! offset_in_cu_p (&cu->header, offset))
18061     {
18062       struct dwarf2_per_cu_data *per_cu;
18063
18064       per_cu = dwarf2_find_containing_comp_unit (offset, offset_in_dwz,
18065                                                  cu->objfile);
18066
18067       /* If necessary, add it to the queue and load its DIEs.  */
18068       if (maybe_queue_comp_unit (cu, per_cu, cu->language))
18069         load_full_comp_unit (per_cu, cu->language);
18070
18071       target_cu = per_cu->cu;
18072     }
18073   else if (cu->dies == NULL)
18074     {
18075       /* We're loading full DIEs during partial symbol reading.  */
18076       gdb_assert (dwarf2_per_objfile->reading_partial_symbols);
18077       load_full_comp_unit (cu->per_cu, language_minimal);
18078     }
18079
18080   *ref_cu = target_cu;
18081   temp_die.offset = offset;
18082   return htab_find_with_hash (target_cu->die_hash, &temp_die, offset.sect_off);
18083 }
18084
18085 /* Follow reference attribute ATTR of SRC_DIE.
18086    On entry *REF_CU is the CU of SRC_DIE.
18087    On exit *REF_CU is the CU of the result.  */
18088
18089 static struct die_info *
18090 follow_die_ref (struct die_info *src_die, struct attribute *attr,
18091                 struct dwarf2_cu **ref_cu)
18092 {
18093   sect_offset offset = dwarf2_get_ref_die_offset (attr);
18094   struct dwarf2_cu *cu = *ref_cu;
18095   struct die_info *die;
18096
18097   die = follow_die_offset (offset,
18098                            (attr->form == DW_FORM_GNU_ref_alt
18099                             || cu->per_cu->is_dwz),
18100                            ref_cu);
18101   if (!die)
18102     error (_("Dwarf Error: Cannot find DIE at 0x%x referenced from DIE "
18103            "at 0x%x [in module %s]"),
18104            offset.sect_off, src_die->offset.sect_off, cu->objfile->name);
18105
18106   return die;
18107 }
18108
18109 /* Return DWARF block referenced by DW_AT_location of DIE at OFFSET at PER_CU.
18110    Returned value is intended for DW_OP_call*.  Returned
18111    dwarf2_locexpr_baton->data has lifetime of PER_CU->OBJFILE.  */
18112
18113 struct dwarf2_locexpr_baton
18114 dwarf2_fetch_die_loc_sect_off (sect_offset offset,
18115                                struct dwarf2_per_cu_data *per_cu,
18116                                CORE_ADDR (*get_frame_pc) (void *baton),
18117                                void *baton)
18118 {
18119   struct dwarf2_cu *cu;
18120   struct die_info *die;
18121   struct attribute *attr;
18122   struct dwarf2_locexpr_baton retval;
18123
18124   dw2_setup (per_cu->objfile);
18125
18126   if (per_cu->cu == NULL)
18127     load_cu (per_cu);
18128   cu = per_cu->cu;
18129
18130   die = follow_die_offset (offset, per_cu->is_dwz, &cu);
18131   if (!die)
18132     error (_("Dwarf Error: Cannot find DIE at 0x%x referenced in module %s"),
18133            offset.sect_off, per_cu->objfile->name);
18134
18135   attr = dwarf2_attr (die, DW_AT_location, cu);
18136   if (!attr)
18137     {
18138       /* DWARF: "If there is no such attribute, then there is no effect.".
18139          DATA is ignored if SIZE is 0.  */
18140
18141       retval.data = NULL;
18142       retval.size = 0;
18143     }
18144   else if (attr_form_is_section_offset (attr))
18145     {
18146       struct dwarf2_loclist_baton loclist_baton;
18147       CORE_ADDR pc = (*get_frame_pc) (baton);
18148       size_t size;
18149
18150       fill_in_loclist_baton (cu, &loclist_baton, attr);
18151
18152       retval.data = dwarf2_find_location_expression (&loclist_baton,
18153                                                      &size, pc);
18154       retval.size = size;
18155     }
18156   else
18157     {
18158       if (!attr_form_is_block (attr))
18159         error (_("Dwarf Error: DIE at 0x%x referenced in module %s "
18160                  "is neither DW_FORM_block* nor DW_FORM_exprloc"),
18161                offset.sect_off, per_cu->objfile->name);
18162
18163       retval.data = DW_BLOCK (attr)->data;
18164       retval.size = DW_BLOCK (attr)->size;
18165     }
18166   retval.per_cu = cu->per_cu;
18167
18168   age_cached_comp_units ();
18169
18170   return retval;
18171 }
18172
18173 /* Like dwarf2_fetch_die_loc_sect_off, but take a CU
18174    offset.  */
18175
18176 struct dwarf2_locexpr_baton
18177 dwarf2_fetch_die_loc_cu_off (cu_offset offset_in_cu,
18178                              struct dwarf2_per_cu_data *per_cu,
18179                              CORE_ADDR (*get_frame_pc) (void *baton),
18180                              void *baton)
18181 {
18182   sect_offset offset = { per_cu->offset.sect_off + offset_in_cu.cu_off };
18183
18184   return dwarf2_fetch_die_loc_sect_off (offset, per_cu, get_frame_pc, baton);
18185 }
18186
18187 /* Write a constant of a given type as target-ordered bytes into
18188    OBSTACK.  */
18189
18190 static const gdb_byte *
18191 write_constant_as_bytes (struct obstack *obstack,
18192                          enum bfd_endian byte_order,
18193                          struct type *type,
18194                          ULONGEST value,
18195                          LONGEST *len)
18196 {
18197   gdb_byte *result;
18198
18199   *len = TYPE_LENGTH (type);
18200   result = obstack_alloc (obstack, *len);
18201   store_unsigned_integer (result, *len, byte_order, value);
18202
18203   return result;
18204 }
18205
18206 /* If the DIE at OFFSET in PER_CU has a DW_AT_const_value, return a
18207    pointer to the constant bytes and set LEN to the length of the
18208    data.  If memory is needed, allocate it on OBSTACK.  If the DIE
18209    does not have a DW_AT_const_value, return NULL.  */
18210
18211 const gdb_byte *
18212 dwarf2_fetch_constant_bytes (sect_offset offset,
18213                              struct dwarf2_per_cu_data *per_cu,
18214                              struct obstack *obstack,
18215                              LONGEST *len)
18216 {
18217   struct dwarf2_cu *cu;
18218   struct die_info *die;
18219   struct attribute *attr;
18220   const gdb_byte *result = NULL;
18221   struct type *type;
18222   LONGEST value;
18223   enum bfd_endian byte_order;
18224
18225   dw2_setup (per_cu->objfile);
18226
18227   if (per_cu->cu == NULL)
18228     load_cu (per_cu);
18229   cu = per_cu->cu;
18230
18231   die = follow_die_offset (offset, per_cu->is_dwz, &cu);
18232   if (!die)
18233     error (_("Dwarf Error: Cannot find DIE at 0x%x referenced in module %s"),
18234            offset.sect_off, per_cu->objfile->name);
18235
18236
18237   attr = dwarf2_attr (die, DW_AT_const_value, cu);
18238   if (attr == NULL)
18239     return NULL;
18240
18241   byte_order = (bfd_big_endian (per_cu->objfile->obfd)
18242                 ? BFD_ENDIAN_BIG : BFD_ENDIAN_LITTLE);
18243
18244   switch (attr->form)
18245     {
18246     case DW_FORM_addr:
18247     case DW_FORM_GNU_addr_index:
18248       {
18249         gdb_byte *tem;
18250
18251         *len = cu->header.addr_size;
18252         tem = obstack_alloc (obstack, *len);
18253         store_unsigned_integer (tem, *len, byte_order, DW_ADDR (attr));
18254         result = tem;
18255       }
18256       break;
18257     case DW_FORM_string:
18258     case DW_FORM_strp:
18259     case DW_FORM_GNU_str_index:
18260     case DW_FORM_GNU_strp_alt:
18261       /* DW_STRING is already allocated on the objfile obstack, point
18262          directly to it.  */
18263       result = (const gdb_byte *) DW_STRING (attr);
18264       *len = strlen (DW_STRING (attr));
18265       break;
18266     case DW_FORM_block1:
18267     case DW_FORM_block2:
18268     case DW_FORM_block4:
18269     case DW_FORM_block:
18270     case DW_FORM_exprloc:
18271       result = DW_BLOCK (attr)->data;
18272       *len = DW_BLOCK (attr)->size;
18273       break;
18274
18275       /* The DW_AT_const_value attributes are supposed to carry the
18276          symbol's value "represented as it would be on the target
18277          architecture."  By the time we get here, it's already been
18278          converted to host endianness, so we just need to sign- or
18279          zero-extend it as appropriate.  */
18280     case DW_FORM_data1:
18281       type = die_type (die, cu);
18282       result = dwarf2_const_value_data (attr, obstack, cu, &value, 8);
18283       if (result == NULL)
18284         result = write_constant_as_bytes (obstack, byte_order,
18285                                           type, value, len);
18286       break;
18287     case DW_FORM_data2:
18288       type = die_type (die, cu);
18289       result = dwarf2_const_value_data (attr, obstack, cu, &value, 16);
18290       if (result == NULL)
18291         result = write_constant_as_bytes (obstack, byte_order,
18292                                           type, value, len);
18293       break;
18294     case DW_FORM_data4:
18295       type = die_type (die, cu);
18296       result = dwarf2_const_value_data (attr, obstack, cu, &value, 32);
18297       if (result == NULL)
18298         result = write_constant_as_bytes (obstack, byte_order,
18299                                           type, value, len);
18300       break;
18301     case DW_FORM_data8:
18302       type = die_type (die, cu);
18303       result = dwarf2_const_value_data (attr, obstack, cu, &value, 64);
18304       if (result == NULL)
18305         result = write_constant_as_bytes (obstack, byte_order,
18306                                           type, value, len);
18307       break;
18308
18309     case DW_FORM_sdata:
18310       type = die_type (die, cu);
18311       result = write_constant_as_bytes (obstack, byte_order,
18312                                         type, DW_SND (attr), len);
18313       break;
18314
18315     case DW_FORM_udata:
18316       type = die_type (die, cu);
18317       result = write_constant_as_bytes (obstack, byte_order,
18318                                         type, DW_UNSND (attr), len);
18319       break;
18320
18321     default:
18322       complaint (&symfile_complaints,
18323                  _("unsupported const value attribute form: '%s'"),
18324                  dwarf_form_name (attr->form));
18325       break;
18326     }
18327
18328   return result;
18329 }
18330
18331 /* Return the type of the DIE at DIE_OFFSET in the CU named by
18332    PER_CU.  */
18333
18334 struct type *
18335 dwarf2_get_die_type (cu_offset die_offset,
18336                      struct dwarf2_per_cu_data *per_cu)
18337 {
18338   sect_offset die_offset_sect;
18339
18340   dw2_setup (per_cu->objfile);
18341
18342   die_offset_sect.sect_off = per_cu->offset.sect_off + die_offset.cu_off;
18343   return get_die_type_at_offset (die_offset_sect, per_cu);
18344 }
18345
18346 /* Follow type unit SIG_TYPE referenced by SRC_DIE.
18347    On entry *REF_CU is the CU of SRC_DIE.
18348    On exit *REF_CU is the CU of the result.
18349    Returns NULL if the referenced DIE isn't found.  */
18350
18351 static struct die_info *
18352 follow_die_sig_1 (struct die_info *src_die, struct signatured_type *sig_type,
18353                   struct dwarf2_cu **ref_cu)
18354 {
18355   struct objfile *objfile = (*ref_cu)->objfile;
18356   struct die_info temp_die;
18357   struct dwarf2_cu *sig_cu;
18358   struct die_info *die;
18359
18360   /* While it might be nice to assert sig_type->type == NULL here,
18361      we can get here for DW_AT_imported_declaration where we need
18362      the DIE not the type.  */
18363
18364   /* If necessary, add it to the queue and load its DIEs.  */
18365
18366   if (maybe_queue_comp_unit (*ref_cu, &sig_type->per_cu, language_minimal))
18367     read_signatured_type (sig_type);
18368
18369   gdb_assert (sig_type->per_cu.cu != NULL);
18370
18371   sig_cu = sig_type->per_cu.cu;
18372   gdb_assert (sig_type->type_offset_in_section.sect_off != 0);
18373   temp_die.offset = sig_type->type_offset_in_section;
18374   die = htab_find_with_hash (sig_cu->die_hash, &temp_die,
18375                              temp_die.offset.sect_off);
18376   if (die)
18377     {
18378       /* For .gdb_index version 7 keep track of included TUs.
18379          http://sourceware.org/bugzilla/show_bug.cgi?id=15021.  */
18380       if (dwarf2_per_objfile->index_table != NULL
18381           && dwarf2_per_objfile->index_table->version <= 7)
18382         {
18383           VEC_safe_push (dwarf2_per_cu_ptr,
18384                          (*ref_cu)->per_cu->imported_symtabs,
18385                          sig_cu->per_cu);
18386         }
18387
18388       *ref_cu = sig_cu;
18389       return die;
18390     }
18391
18392   return NULL;
18393 }
18394
18395 /* Follow signatured type referenced by ATTR in SRC_DIE.
18396    On entry *REF_CU is the CU of SRC_DIE.
18397    On exit *REF_CU is the CU of the result.
18398    The result is the DIE of the type.
18399    If the referenced type cannot be found an error is thrown.  */
18400
18401 static struct die_info *
18402 follow_die_sig (struct die_info *src_die, struct attribute *attr,
18403                 struct dwarf2_cu **ref_cu)
18404 {
18405   ULONGEST signature = DW_SIGNATURE (attr);
18406   struct signatured_type *sig_type;
18407   struct die_info *die;
18408
18409   gdb_assert (attr->form == DW_FORM_ref_sig8);
18410
18411   sig_type = lookup_signatured_type (*ref_cu, signature);
18412   /* sig_type will be NULL if the signatured type is missing from
18413      the debug info.  */
18414   if (sig_type == NULL)
18415     {
18416       error (_("Dwarf Error: Cannot find signatured DIE %s referenced"
18417                " from DIE at 0x%x [in module %s]"),
18418              hex_string (signature), src_die->offset.sect_off,
18419              (*ref_cu)->objfile->name);
18420     }
18421
18422   die = follow_die_sig_1 (src_die, sig_type, ref_cu);
18423   if (die == NULL)
18424     {
18425       dump_die_for_error (src_die);
18426       error (_("Dwarf Error: Problem reading signatured DIE %s referenced"
18427                " from DIE at 0x%x [in module %s]"),
18428              hex_string (signature), src_die->offset.sect_off,
18429              (*ref_cu)->objfile->name);
18430     }
18431
18432   return die;
18433 }
18434
18435 /* Get the type specified by SIGNATURE referenced in DIE/CU,
18436    reading in and processing the type unit if necessary.  */
18437
18438 static struct type *
18439 get_signatured_type (struct die_info *die, ULONGEST signature,
18440                      struct dwarf2_cu *cu)
18441 {
18442   struct signatured_type *sig_type;
18443   struct dwarf2_cu *type_cu;
18444   struct die_info *type_die;
18445   struct type *type;
18446
18447   sig_type = lookup_signatured_type (cu, signature);
18448   /* sig_type will be NULL if the signatured type is missing from
18449      the debug info.  */
18450   if (sig_type == NULL)
18451     {
18452       complaint (&symfile_complaints,
18453                  _("Dwarf Error: Cannot find signatured DIE %s referenced"
18454                    " from DIE at 0x%x [in module %s]"),
18455                  hex_string (signature), die->offset.sect_off,
18456                  dwarf2_per_objfile->objfile->name);
18457       return build_error_marker_type (cu, die);
18458     }
18459
18460   /* If we already know the type we're done.  */
18461   if (sig_type->type != NULL)
18462     return sig_type->type;
18463
18464   type_cu = cu;
18465   type_die = follow_die_sig_1 (die, sig_type, &type_cu);
18466   if (type_die != NULL)
18467     {
18468       /* N.B. We need to call get_die_type to ensure only one type for this DIE
18469          is created.  This is important, for example, because for c++ classes
18470          we need TYPE_NAME set which is only done by new_symbol.  Blech.  */
18471       type = read_type_die (type_die, type_cu);
18472       if (type == NULL)
18473         {
18474           complaint (&symfile_complaints,
18475                      _("Dwarf Error: Cannot build signatured type %s"
18476                        " referenced from DIE at 0x%x [in module %s]"),
18477                      hex_string (signature), die->offset.sect_off,
18478                      dwarf2_per_objfile->objfile->name);
18479           type = build_error_marker_type (cu, die);
18480         }
18481     }
18482   else
18483     {
18484       complaint (&symfile_complaints,
18485                  _("Dwarf Error: Problem reading signatured DIE %s referenced"
18486                    " from DIE at 0x%x [in module %s]"),
18487                  hex_string (signature), die->offset.sect_off,
18488                  dwarf2_per_objfile->objfile->name);
18489       type = build_error_marker_type (cu, die);
18490     }
18491   sig_type->type = type;
18492
18493   return type;
18494 }
18495
18496 /* Get the type specified by the DW_AT_signature ATTR in DIE/CU,
18497    reading in and processing the type unit if necessary.  */
18498
18499 static struct type *
18500 get_DW_AT_signature_type (struct die_info *die, struct attribute *attr,
18501                           struct dwarf2_cu *cu) /* ARI: editCase function */
18502 {
18503   /* Yes, DW_AT_signature can use a non-ref_sig8 reference.  */
18504   if (is_ref_attr (attr))
18505     {
18506       struct dwarf2_cu *type_cu = cu;
18507       struct die_info *type_die = follow_die_ref (die, attr, &type_cu);
18508
18509       return read_type_die (type_die, type_cu);
18510     }
18511   else if (attr->form == DW_FORM_ref_sig8)
18512     {
18513       return get_signatured_type (die, DW_SIGNATURE (attr), cu);
18514     }
18515   else
18516     {
18517       complaint (&symfile_complaints,
18518                  _("Dwarf Error: DW_AT_signature has bad form %s in DIE"
18519                    " at 0x%x [in module %s]"),
18520                  dwarf_form_name (attr->form), die->offset.sect_off,
18521                  dwarf2_per_objfile->objfile->name);
18522       return build_error_marker_type (cu, die);
18523     }
18524 }
18525
18526 /* Load the DIEs associated with type unit PER_CU into memory.  */
18527
18528 static void
18529 load_full_type_unit (struct dwarf2_per_cu_data *per_cu)
18530 {
18531   struct signatured_type *sig_type;
18532
18533   /* Caller is responsible for ensuring type_unit_groups don't get here.  */
18534   gdb_assert (! IS_TYPE_UNIT_GROUP (per_cu));
18535
18536   /* We have the per_cu, but we need the signatured_type.
18537      Fortunately this is an easy translation.  */
18538   gdb_assert (per_cu->is_debug_types);
18539   sig_type = (struct signatured_type *) per_cu;
18540
18541   gdb_assert (per_cu->cu == NULL);
18542
18543   read_signatured_type (sig_type);
18544
18545   gdb_assert (per_cu->cu != NULL);
18546 }
18547
18548 /* die_reader_func for read_signatured_type.
18549    This is identical to load_full_comp_unit_reader,
18550    but is kept separate for now.  */
18551
18552 static void
18553 read_signatured_type_reader (const struct die_reader_specs *reader,
18554                              const gdb_byte *info_ptr,
18555                              struct die_info *comp_unit_die,
18556                              int has_children,
18557                              void *data)
18558 {
18559   struct dwarf2_cu *cu = reader->cu;
18560
18561   gdb_assert (cu->die_hash == NULL);
18562   cu->die_hash =
18563     htab_create_alloc_ex (cu->header.length / 12,
18564                           die_hash,
18565                           die_eq,
18566                           NULL,
18567                           &cu->comp_unit_obstack,
18568                           hashtab_obstack_allocate,
18569                           dummy_obstack_deallocate);
18570
18571   if (has_children)
18572     comp_unit_die->child = read_die_and_siblings (reader, info_ptr,
18573                                                   &info_ptr, comp_unit_die);
18574   cu->dies = comp_unit_die;
18575   /* comp_unit_die is not stored in die_hash, no need.  */
18576
18577   /* We try not to read any attributes in this function, because not
18578      all CUs needed for references have been loaded yet, and symbol
18579      table processing isn't initialized.  But we have to set the CU language,
18580      or we won't be able to build types correctly.
18581      Similarly, if we do not read the producer, we can not apply
18582      producer-specific interpretation.  */
18583   prepare_one_comp_unit (cu, cu->dies, language_minimal);
18584 }
18585
18586 /* Read in a signatured type and build its CU and DIEs.
18587    If the type is a stub for the real type in a DWO file,
18588    read in the real type from the DWO file as well.  */
18589
18590 static void
18591 read_signatured_type (struct signatured_type *sig_type)
18592 {
18593   struct dwarf2_per_cu_data *per_cu = &sig_type->per_cu;
18594
18595   gdb_assert (per_cu->is_debug_types);
18596   gdb_assert (per_cu->cu == NULL);
18597
18598   init_cutu_and_read_dies (per_cu, NULL, 0, 1,
18599                            read_signatured_type_reader, NULL);
18600 }
18601
18602 /* Decode simple location descriptions.
18603    Given a pointer to a dwarf block that defines a location, compute
18604    the location and return the value.
18605
18606    NOTE drow/2003-11-18: This function is called in two situations
18607    now: for the address of static or global variables (partial symbols
18608    only) and for offsets into structures which are expected to be
18609    (more or less) constant.  The partial symbol case should go away,
18610    and only the constant case should remain.  That will let this
18611    function complain more accurately.  A few special modes are allowed
18612    without complaint for global variables (for instance, global
18613    register values and thread-local values).
18614
18615    A location description containing no operations indicates that the
18616    object is optimized out.  The return value is 0 for that case.
18617    FIXME drow/2003-11-16: No callers check for this case any more; soon all
18618    callers will only want a very basic result and this can become a
18619    complaint.
18620
18621    Note that stack[0] is unused except as a default error return.  */
18622
18623 static CORE_ADDR
18624 decode_locdesc (struct dwarf_block *blk, struct dwarf2_cu *cu)
18625 {
18626   struct objfile *objfile = cu->objfile;
18627   size_t i;
18628   size_t size = blk->size;
18629   const gdb_byte *data = blk->data;
18630   CORE_ADDR stack[64];
18631   int stacki;
18632   unsigned int bytes_read, unsnd;
18633   gdb_byte op;
18634
18635   i = 0;
18636   stacki = 0;
18637   stack[stacki] = 0;
18638   stack[++stacki] = 0;
18639
18640   while (i < size)
18641     {
18642       op = data[i++];
18643       switch (op)
18644         {
18645         case DW_OP_lit0:
18646         case DW_OP_lit1:
18647         case DW_OP_lit2:
18648         case DW_OP_lit3:
18649         case DW_OP_lit4:
18650         case DW_OP_lit5:
18651         case DW_OP_lit6:
18652         case DW_OP_lit7:
18653         case DW_OP_lit8:
18654         case DW_OP_lit9:
18655         case DW_OP_lit10:
18656         case DW_OP_lit11:
18657         case DW_OP_lit12:
18658         case DW_OP_lit13:
18659         case DW_OP_lit14:
18660         case DW_OP_lit15:
18661         case DW_OP_lit16:
18662         case DW_OP_lit17:
18663         case DW_OP_lit18:
18664         case DW_OP_lit19:
18665         case DW_OP_lit20:
18666         case DW_OP_lit21:
18667         case DW_OP_lit22:
18668         case DW_OP_lit23:
18669         case DW_OP_lit24:
18670         case DW_OP_lit25:
18671         case DW_OP_lit26:
18672         case DW_OP_lit27:
18673         case DW_OP_lit28:
18674         case DW_OP_lit29:
18675         case DW_OP_lit30:
18676         case DW_OP_lit31:
18677           stack[++stacki] = op - DW_OP_lit0;
18678           break;
18679
18680         case DW_OP_reg0:
18681         case DW_OP_reg1:
18682         case DW_OP_reg2:
18683         case DW_OP_reg3:
18684         case DW_OP_reg4:
18685         case DW_OP_reg5:
18686         case DW_OP_reg6:
18687         case DW_OP_reg7:
18688         case DW_OP_reg8:
18689         case DW_OP_reg9:
18690         case DW_OP_reg10:
18691         case DW_OP_reg11:
18692         case DW_OP_reg12:
18693         case DW_OP_reg13:
18694         case DW_OP_reg14:
18695         case DW_OP_reg15:
18696         case DW_OP_reg16:
18697         case DW_OP_reg17:
18698         case DW_OP_reg18:
18699         case DW_OP_reg19:
18700         case DW_OP_reg20:
18701         case DW_OP_reg21:
18702         case DW_OP_reg22:
18703         case DW_OP_reg23:
18704         case DW_OP_reg24:
18705         case DW_OP_reg25:
18706         case DW_OP_reg26:
18707         case DW_OP_reg27:
18708         case DW_OP_reg28:
18709         case DW_OP_reg29:
18710         case DW_OP_reg30:
18711         case DW_OP_reg31:
18712           stack[++stacki] = op - DW_OP_reg0;
18713           if (i < size)
18714             dwarf2_complex_location_expr_complaint ();
18715           break;
18716
18717         case DW_OP_regx:
18718           unsnd = read_unsigned_leb128 (NULL, (data + i), &bytes_read);
18719           i += bytes_read;
18720           stack[++stacki] = unsnd;
18721           if (i < size)
18722             dwarf2_complex_location_expr_complaint ();
18723           break;
18724
18725         case DW_OP_addr:
18726           stack[++stacki] = read_address (objfile->obfd, &data[i],
18727                                           cu, &bytes_read);
18728           i += bytes_read;
18729           break;
18730
18731         case DW_OP_const1u:
18732           stack[++stacki] = read_1_byte (objfile->obfd, &data[i]);
18733           i += 1;
18734           break;
18735
18736         case DW_OP_const1s:
18737           stack[++stacki] = read_1_signed_byte (objfile->obfd, &data[i]);
18738           i += 1;
18739           break;
18740
18741         case DW_OP_const2u:
18742           stack[++stacki] = read_2_bytes (objfile->obfd, &data[i]);
18743           i += 2;
18744           break;
18745
18746         case DW_OP_const2s:
18747           stack[++stacki] = read_2_signed_bytes (objfile->obfd, &data[i]);
18748           i += 2;
18749           break;
18750
18751         case DW_OP_const4u:
18752           stack[++stacki] = read_4_bytes (objfile->obfd, &data[i]);
18753           i += 4;
18754           break;
18755
18756         case DW_OP_const4s:
18757           stack[++stacki] = read_4_signed_bytes (objfile->obfd, &data[i]);
18758           i += 4;
18759           break;
18760
18761         case DW_OP_const8u:
18762           stack[++stacki] = read_8_bytes (objfile->obfd, &data[i]);
18763           i += 8;
18764           break;
18765
18766         case DW_OP_constu:
18767           stack[++stacki] = read_unsigned_leb128 (NULL, (data + i),
18768                                                   &bytes_read);
18769           i += bytes_read;
18770           break;
18771
18772         case DW_OP_consts:
18773           stack[++stacki] = read_signed_leb128 (NULL, (data + i), &bytes_read);
18774           i += bytes_read;
18775           break;
18776
18777         case DW_OP_dup:
18778           stack[stacki + 1] = stack[stacki];
18779           stacki++;
18780           break;
18781
18782         case DW_OP_plus:
18783           stack[stacki - 1] += stack[stacki];
18784           stacki--;
18785           break;
18786
18787         case DW_OP_plus_uconst:
18788           stack[stacki] += read_unsigned_leb128 (NULL, (data + i),
18789                                                  &bytes_read);
18790           i += bytes_read;
18791           break;
18792
18793         case DW_OP_minus:
18794           stack[stacki - 1] -= stack[stacki];
18795           stacki--;
18796           break;
18797
18798         case DW_OP_deref:
18799           /* If we're not the last op, then we definitely can't encode
18800              this using GDB's address_class enum.  This is valid for partial
18801              global symbols, although the variable's address will be bogus
18802              in the psymtab.  */
18803           if (i < size)
18804             dwarf2_complex_location_expr_complaint ();
18805           break;
18806
18807         case DW_OP_GNU_push_tls_address:
18808           /* The top of the stack has the offset from the beginning
18809              of the thread control block at which the variable is located.  */
18810           /* Nothing should follow this operator, so the top of stack would
18811              be returned.  */
18812           /* This is valid for partial global symbols, but the variable's
18813              address will be bogus in the psymtab.  Make it always at least
18814              non-zero to not look as a variable garbage collected by linker
18815              which have DW_OP_addr 0.  */
18816           if (i < size)
18817             dwarf2_complex_location_expr_complaint ();
18818           stack[stacki]++;
18819           break;
18820
18821         case DW_OP_GNU_uninit:
18822           break;
18823
18824         case DW_OP_GNU_addr_index:
18825         case DW_OP_GNU_const_index:
18826           stack[++stacki] = read_addr_index_from_leb128 (cu, &data[i],
18827                                                          &bytes_read);
18828           i += bytes_read;
18829           break;
18830
18831         default:
18832           {
18833             const char *name = get_DW_OP_name (op);
18834
18835             if (name)
18836               complaint (&symfile_complaints, _("unsupported stack op: '%s'"),
18837                          name);
18838             else
18839               complaint (&symfile_complaints, _("unsupported stack op: '%02x'"),
18840                          op);
18841           }
18842
18843           return (stack[stacki]);
18844         }
18845
18846       /* Enforce maximum stack depth of SIZE-1 to avoid writing
18847          outside of the allocated space.  Also enforce minimum>0.  */
18848       if (stacki >= ARRAY_SIZE (stack) - 1)
18849         {
18850           complaint (&symfile_complaints,
18851                      _("location description stack overflow"));
18852           return 0;
18853         }
18854
18855       if (stacki <= 0)
18856         {
18857           complaint (&symfile_complaints,
18858                      _("location description stack underflow"));
18859           return 0;
18860         }
18861     }
18862   return (stack[stacki]);
18863 }
18864
18865 /* memory allocation interface */
18866
18867 static struct dwarf_block *
18868 dwarf_alloc_block (struct dwarf2_cu *cu)
18869 {
18870   struct dwarf_block *blk;
18871
18872   blk = (struct dwarf_block *)
18873     obstack_alloc (&cu->comp_unit_obstack, sizeof (struct dwarf_block));
18874   return (blk);
18875 }
18876
18877 static struct die_info *
18878 dwarf_alloc_die (struct dwarf2_cu *cu, int num_attrs)
18879 {
18880   struct die_info *die;
18881   size_t size = sizeof (struct die_info);
18882
18883   if (num_attrs > 1)
18884     size += (num_attrs - 1) * sizeof (struct attribute);
18885
18886   die = (struct die_info *) obstack_alloc (&cu->comp_unit_obstack, size);
18887   memset (die, 0, sizeof (struct die_info));
18888   return (die);
18889 }
18890
18891 \f
18892 /* Macro support.  */
18893
18894 /* Return file name relative to the compilation directory of file number I in
18895    *LH's file name table.  The result is allocated using xmalloc; the caller is
18896    responsible for freeing it.  */
18897
18898 static char *
18899 file_file_name (int file, struct line_header *lh)
18900 {
18901   /* Is the file number a valid index into the line header's file name
18902      table?  Remember that file numbers start with one, not zero.  */
18903   if (1 <= file && file <= lh->num_file_names)
18904     {
18905       struct file_entry *fe = &lh->file_names[file - 1];
18906
18907       if (IS_ABSOLUTE_PATH (fe->name) || fe->dir_index == 0)
18908         return xstrdup (fe->name);
18909       return concat (lh->include_dirs[fe->dir_index - 1], SLASH_STRING,
18910                      fe->name, NULL);
18911     }
18912   else
18913     {
18914       /* The compiler produced a bogus file number.  We can at least
18915          record the macro definitions made in the file, even if we
18916          won't be able to find the file by name.  */
18917       char fake_name[80];
18918
18919       xsnprintf (fake_name, sizeof (fake_name),
18920                  "<bad macro file number %d>", file);
18921
18922       complaint (&symfile_complaints,
18923                  _("bad file number in macro information (%d)"),
18924                  file);
18925
18926       return xstrdup (fake_name);
18927     }
18928 }
18929
18930 /* Return the full name of file number I in *LH's file name table.
18931    Use COMP_DIR as the name of the current directory of the
18932    compilation.  The result is allocated using xmalloc; the caller is
18933    responsible for freeing it.  */
18934 static char *
18935 file_full_name (int file, struct line_header *lh, const char *comp_dir)
18936 {
18937   /* Is the file number a valid index into the line header's file name
18938      table?  Remember that file numbers start with one, not zero.  */
18939   if (1 <= file && file <= lh->num_file_names)
18940     {
18941       char *relative = file_file_name (file, lh);
18942
18943       if (IS_ABSOLUTE_PATH (relative) || comp_dir == NULL)
18944         return relative;
18945       return reconcat (relative, comp_dir, SLASH_STRING, relative, NULL);
18946     }
18947   else
18948     return file_file_name (file, lh);
18949 }
18950
18951
18952 static struct macro_source_file *
18953 macro_start_file (int file, int line,
18954                   struct macro_source_file *current_file,
18955                   const char *comp_dir,
18956                   struct line_header *lh, struct objfile *objfile)
18957 {
18958   /* File name relative to the compilation directory of this source file.  */
18959   char *file_name = file_file_name (file, lh);
18960
18961   /* We don't create a macro table for this compilation unit
18962      at all until we actually get a filename.  */
18963   if (! pending_macros)
18964     pending_macros = new_macro_table (&objfile->per_bfd->storage_obstack,
18965                                       objfile->per_bfd->macro_cache,
18966                                       comp_dir);
18967
18968   if (! current_file)
18969     {
18970       /* If we have no current file, then this must be the start_file
18971          directive for the compilation unit's main source file.  */
18972       current_file = macro_set_main (pending_macros, file_name);
18973       macro_define_special (pending_macros);
18974     }
18975   else
18976     current_file = macro_include (current_file, line, file_name);
18977
18978   xfree (file_name);
18979
18980   return current_file;
18981 }
18982
18983
18984 /* Copy the LEN characters at BUF to a xmalloc'ed block of memory,
18985    followed by a null byte.  */
18986 static char *
18987 copy_string (const char *buf, int len)
18988 {
18989   char *s = xmalloc (len + 1);
18990
18991   memcpy (s, buf, len);
18992   s[len] = '\0';
18993   return s;
18994 }
18995
18996
18997 static const char *
18998 consume_improper_spaces (const char *p, const char *body)
18999 {
19000   if (*p == ' ')
19001     {
19002       complaint (&symfile_complaints,
19003                  _("macro definition contains spaces "
19004                    "in formal argument list:\n`%s'"),
19005                  body);
19006
19007       while (*p == ' ')
19008         p++;
19009     }
19010
19011   return p;
19012 }
19013
19014
19015 static void
19016 parse_macro_definition (struct macro_source_file *file, int line,
19017                         const char *body)
19018 {
19019   const char *p;
19020
19021   /* The body string takes one of two forms.  For object-like macro
19022      definitions, it should be:
19023
19024         <macro name> " " <definition>
19025
19026      For function-like macro definitions, it should be:
19027
19028         <macro name> "() " <definition>
19029      or
19030         <macro name> "(" <arg name> ( "," <arg name> ) * ") " <definition>
19031
19032      Spaces may appear only where explicitly indicated, and in the
19033      <definition>.
19034
19035      The Dwarf 2 spec says that an object-like macro's name is always
19036      followed by a space, but versions of GCC around March 2002 omit
19037      the space when the macro's definition is the empty string.
19038
19039      The Dwarf 2 spec says that there should be no spaces between the
19040      formal arguments in a function-like macro's formal argument list,
19041      but versions of GCC around March 2002 include spaces after the
19042      commas.  */
19043
19044
19045   /* Find the extent of the macro name.  The macro name is terminated
19046      by either a space or null character (for an object-like macro) or
19047      an opening paren (for a function-like macro).  */
19048   for (p = body; *p; p++)
19049     if (*p == ' ' || *p == '(')
19050       break;
19051
19052   if (*p == ' ' || *p == '\0')
19053     {
19054       /* It's an object-like macro.  */
19055       int name_len = p - body;
19056       char *name = copy_string (body, name_len);
19057       const char *replacement;
19058
19059       if (*p == ' ')
19060         replacement = body + name_len + 1;
19061       else
19062         {
19063           dwarf2_macro_malformed_definition_complaint (body);
19064           replacement = body + name_len;
19065         }
19066
19067       macro_define_object (file, line, name, replacement);
19068
19069       xfree (name);
19070     }
19071   else if (*p == '(')
19072     {
19073       /* It's a function-like macro.  */
19074       char *name = copy_string (body, p - body);
19075       int argc = 0;
19076       int argv_size = 1;
19077       char **argv = xmalloc (argv_size * sizeof (*argv));
19078
19079       p++;
19080
19081       p = consume_improper_spaces (p, body);
19082
19083       /* Parse the formal argument list.  */
19084       while (*p && *p != ')')
19085         {
19086           /* Find the extent of the current argument name.  */
19087           const char *arg_start = p;
19088
19089           while (*p && *p != ',' && *p != ')' && *p != ' ')
19090             p++;
19091
19092           if (! *p || p == arg_start)
19093             dwarf2_macro_malformed_definition_complaint (body);
19094           else
19095             {
19096               /* Make sure argv has room for the new argument.  */
19097               if (argc >= argv_size)
19098                 {
19099                   argv_size *= 2;
19100                   argv = xrealloc (argv, argv_size * sizeof (*argv));
19101                 }
19102
19103               argv[argc++] = copy_string (arg_start, p - arg_start);
19104             }
19105
19106           p = consume_improper_spaces (p, body);
19107
19108           /* Consume the comma, if present.  */
19109           if (*p == ',')
19110             {
19111               p++;
19112
19113               p = consume_improper_spaces (p, body);
19114             }
19115         }
19116
19117       if (*p == ')')
19118         {
19119           p++;
19120
19121           if (*p == ' ')
19122             /* Perfectly formed definition, no complaints.  */
19123             macro_define_function (file, line, name,
19124                                    argc, (const char **) argv,
19125                                    p + 1);
19126           else if (*p == '\0')
19127             {
19128               /* Complain, but do define it.  */
19129               dwarf2_macro_malformed_definition_complaint (body);
19130               macro_define_function (file, line, name,
19131                                      argc, (const char **) argv,
19132                                      p);
19133             }
19134           else
19135             /* Just complain.  */
19136             dwarf2_macro_malformed_definition_complaint (body);
19137         }
19138       else
19139         /* Just complain.  */
19140         dwarf2_macro_malformed_definition_complaint (body);
19141
19142       xfree (name);
19143       {
19144         int i;
19145
19146         for (i = 0; i < argc; i++)
19147           xfree (argv[i]);
19148       }
19149       xfree (argv);
19150     }
19151   else
19152     dwarf2_macro_malformed_definition_complaint (body);
19153 }
19154
19155 /* Skip some bytes from BYTES according to the form given in FORM.
19156    Returns the new pointer.  */
19157
19158 static const gdb_byte *
19159 skip_form_bytes (bfd *abfd, const gdb_byte *bytes, const gdb_byte *buffer_end,
19160                  enum dwarf_form form,
19161                  unsigned int offset_size,
19162                  struct dwarf2_section_info *section)
19163 {
19164   unsigned int bytes_read;
19165
19166   switch (form)
19167     {
19168     case DW_FORM_data1:
19169     case DW_FORM_flag:
19170       ++bytes;
19171       break;
19172
19173     case DW_FORM_data2:
19174       bytes += 2;
19175       break;
19176
19177     case DW_FORM_data4:
19178       bytes += 4;
19179       break;
19180
19181     case DW_FORM_data8:
19182       bytes += 8;
19183       break;
19184
19185     case DW_FORM_string:
19186       read_direct_string (abfd, bytes, &bytes_read);
19187       bytes += bytes_read;
19188       break;
19189
19190     case DW_FORM_sec_offset:
19191     case DW_FORM_strp:
19192     case DW_FORM_GNU_strp_alt:
19193       bytes += offset_size;
19194       break;
19195
19196     case DW_FORM_block:
19197       bytes += read_unsigned_leb128 (abfd, bytes, &bytes_read);
19198       bytes += bytes_read;
19199       break;
19200
19201     case DW_FORM_block1:
19202       bytes += 1 + read_1_byte (abfd, bytes);
19203       break;
19204     case DW_FORM_block2:
19205       bytes += 2 + read_2_bytes (abfd, bytes);
19206       break;
19207     case DW_FORM_block4:
19208       bytes += 4 + read_4_bytes (abfd, bytes);
19209       break;
19210
19211     case DW_FORM_sdata:
19212     case DW_FORM_udata:
19213     case DW_FORM_GNU_addr_index:
19214     case DW_FORM_GNU_str_index:
19215       bytes = gdb_skip_leb128 (bytes, buffer_end);
19216       if (bytes == NULL)
19217         {
19218           dwarf2_section_buffer_overflow_complaint (section);
19219           return NULL;
19220         }
19221       break;
19222
19223     default:
19224       {
19225       complain:
19226         complaint (&symfile_complaints,
19227                    _("invalid form 0x%x in `%s'"),
19228                    form,
19229                    section->asection->name);
19230         return NULL;
19231       }
19232     }
19233
19234   return bytes;
19235 }
19236
19237 /* A helper for dwarf_decode_macros that handles skipping an unknown
19238    opcode.  Returns an updated pointer to the macro data buffer; or,
19239    on error, issues a complaint and returns NULL.  */
19240
19241 static const gdb_byte *
19242 skip_unknown_opcode (unsigned int opcode,
19243                      const gdb_byte **opcode_definitions,
19244                      const gdb_byte *mac_ptr, const gdb_byte *mac_end,
19245                      bfd *abfd,
19246                      unsigned int offset_size,
19247                      struct dwarf2_section_info *section)
19248 {
19249   unsigned int bytes_read, i;
19250   unsigned long arg;
19251   const gdb_byte *defn;
19252
19253   if (opcode_definitions[opcode] == NULL)
19254     {
19255       complaint (&symfile_complaints,
19256                  _("unrecognized DW_MACFINO opcode 0x%x"),
19257                  opcode);
19258       return NULL;
19259     }
19260
19261   defn = opcode_definitions[opcode];
19262   arg = read_unsigned_leb128 (abfd, defn, &bytes_read);
19263   defn += bytes_read;
19264
19265   for (i = 0; i < arg; ++i)
19266     {
19267       mac_ptr = skip_form_bytes (abfd, mac_ptr, mac_end, defn[i], offset_size,
19268                                  section);
19269       if (mac_ptr == NULL)
19270         {
19271           /* skip_form_bytes already issued the complaint.  */
19272           return NULL;
19273         }
19274     }
19275
19276   return mac_ptr;
19277 }
19278
19279 /* A helper function which parses the header of a macro section.
19280    If the macro section is the extended (for now called "GNU") type,
19281    then this updates *OFFSET_SIZE.  Returns a pointer to just after
19282    the header, or issues a complaint and returns NULL on error.  */
19283
19284 static const gdb_byte *
19285 dwarf_parse_macro_header (const gdb_byte **opcode_definitions,
19286                           bfd *abfd,
19287                           const gdb_byte *mac_ptr,
19288                           unsigned int *offset_size,
19289                           int section_is_gnu)
19290 {
19291   memset (opcode_definitions, 0, 256 * sizeof (gdb_byte *));
19292
19293   if (section_is_gnu)
19294     {
19295       unsigned int version, flags;
19296
19297       version = read_2_bytes (abfd, mac_ptr);
19298       if (version != 4)
19299         {
19300           complaint (&symfile_complaints,
19301                      _("unrecognized version `%d' in .debug_macro section"),
19302                      version);
19303           return NULL;
19304         }
19305       mac_ptr += 2;
19306
19307       flags = read_1_byte (abfd, mac_ptr);
19308       ++mac_ptr;
19309       *offset_size = (flags & 1) ? 8 : 4;
19310
19311       if ((flags & 2) != 0)
19312         /* We don't need the line table offset.  */
19313         mac_ptr += *offset_size;
19314
19315       /* Vendor opcode descriptions.  */
19316       if ((flags & 4) != 0)
19317         {
19318           unsigned int i, count;
19319
19320           count = read_1_byte (abfd, mac_ptr);
19321           ++mac_ptr;
19322           for (i = 0; i < count; ++i)
19323             {
19324               unsigned int opcode, bytes_read;
19325               unsigned long arg;
19326
19327               opcode = read_1_byte (abfd, mac_ptr);
19328               ++mac_ptr;
19329               opcode_definitions[opcode] = mac_ptr;
19330               arg = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
19331               mac_ptr += bytes_read;
19332               mac_ptr += arg;
19333             }
19334         }
19335     }
19336
19337   return mac_ptr;
19338 }
19339
19340 /* A helper for dwarf_decode_macros that handles the GNU extensions,
19341    including DW_MACRO_GNU_transparent_include.  */
19342
19343 static void
19344 dwarf_decode_macro_bytes (bfd *abfd,
19345                           const gdb_byte *mac_ptr, const gdb_byte *mac_end,
19346                           struct macro_source_file *current_file,
19347                           struct line_header *lh, const char *comp_dir,
19348                           struct dwarf2_section_info *section,
19349                           int section_is_gnu, int section_is_dwz,
19350                           unsigned int offset_size,
19351                           struct objfile *objfile,
19352                           htab_t include_hash)
19353 {
19354   enum dwarf_macro_record_type macinfo_type;
19355   int at_commandline;
19356   const gdb_byte *opcode_definitions[256];
19357
19358   mac_ptr = dwarf_parse_macro_header (opcode_definitions, abfd, mac_ptr,
19359                                       &offset_size, section_is_gnu);
19360   if (mac_ptr == NULL)
19361     {
19362       /* We already issued a complaint.  */
19363       return;
19364     }
19365
19366   /* Determines if GDB is still before first DW_MACINFO_start_file.  If true
19367      GDB is still reading the definitions from command line.  First
19368      DW_MACINFO_start_file will need to be ignored as it was already executed
19369      to create CURRENT_FILE for the main source holding also the command line
19370      definitions.  On first met DW_MACINFO_start_file this flag is reset to
19371      normally execute all the remaining DW_MACINFO_start_file macinfos.  */
19372
19373   at_commandline = 1;
19374
19375   do
19376     {
19377       /* Do we at least have room for a macinfo type byte?  */
19378       if (mac_ptr >= mac_end)
19379         {
19380           dwarf2_section_buffer_overflow_complaint (section);
19381           break;
19382         }
19383
19384       macinfo_type = read_1_byte (abfd, mac_ptr);
19385       mac_ptr++;
19386
19387       /* Note that we rely on the fact that the corresponding GNU and
19388          DWARF constants are the same.  */
19389       switch (macinfo_type)
19390         {
19391           /* A zero macinfo type indicates the end of the macro
19392              information.  */
19393         case 0:
19394           break;
19395
19396         case DW_MACRO_GNU_define:
19397         case DW_MACRO_GNU_undef:
19398         case DW_MACRO_GNU_define_indirect:
19399         case DW_MACRO_GNU_undef_indirect:
19400         case DW_MACRO_GNU_define_indirect_alt:
19401         case DW_MACRO_GNU_undef_indirect_alt:
19402           {
19403             unsigned int bytes_read;
19404             int line;
19405             const char *body;
19406             int is_define;
19407
19408             line = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
19409             mac_ptr += bytes_read;
19410
19411             if (macinfo_type == DW_MACRO_GNU_define
19412                 || macinfo_type == DW_MACRO_GNU_undef)
19413               {
19414                 body = read_direct_string (abfd, mac_ptr, &bytes_read);
19415                 mac_ptr += bytes_read;
19416               }
19417             else
19418               {
19419                 LONGEST str_offset;
19420
19421                 str_offset = read_offset_1 (abfd, mac_ptr, offset_size);
19422                 mac_ptr += offset_size;
19423
19424                 if (macinfo_type == DW_MACRO_GNU_define_indirect_alt
19425                     || macinfo_type == DW_MACRO_GNU_undef_indirect_alt
19426                     || section_is_dwz)
19427                   {
19428                     struct dwz_file *dwz = dwarf2_get_dwz_file ();
19429
19430                     body = read_indirect_string_from_dwz (dwz, str_offset);
19431                   }
19432                 else
19433                   body = read_indirect_string_at_offset (abfd, str_offset);
19434               }
19435
19436             is_define = (macinfo_type == DW_MACRO_GNU_define
19437                          || macinfo_type == DW_MACRO_GNU_define_indirect
19438                          || macinfo_type == DW_MACRO_GNU_define_indirect_alt);
19439             if (! current_file)
19440               {
19441                 /* DWARF violation as no main source is present.  */
19442                 complaint (&symfile_complaints,
19443                            _("debug info with no main source gives macro %s "
19444                              "on line %d: %s"),
19445                            is_define ? _("definition") : _("undefinition"),
19446                            line, body);
19447                 break;
19448               }
19449             if ((line == 0 && !at_commandline)
19450                 || (line != 0 && at_commandline))
19451               complaint (&symfile_complaints,
19452                          _("debug info gives %s macro %s with %s line %d: %s"),
19453                          at_commandline ? _("command-line") : _("in-file"),
19454                          is_define ? _("definition") : _("undefinition"),
19455                          line == 0 ? _("zero") : _("non-zero"), line, body);
19456
19457             if (is_define)
19458               parse_macro_definition (current_file, line, body);
19459             else
19460               {
19461                 gdb_assert (macinfo_type == DW_MACRO_GNU_undef
19462                             || macinfo_type == DW_MACRO_GNU_undef_indirect
19463                             || macinfo_type == DW_MACRO_GNU_undef_indirect_alt);
19464                 macro_undef (current_file, line, body);
19465               }
19466           }
19467           break;
19468
19469         case DW_MACRO_GNU_start_file:
19470           {
19471             unsigned int bytes_read;
19472             int line, file;
19473
19474             line = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
19475             mac_ptr += bytes_read;
19476             file = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
19477             mac_ptr += bytes_read;
19478
19479             if ((line == 0 && !at_commandline)
19480                 || (line != 0 && at_commandline))
19481               complaint (&symfile_complaints,
19482                          _("debug info gives source %d included "
19483                            "from %s at %s line %d"),
19484                          file, at_commandline ? _("command-line") : _("file"),
19485                          line == 0 ? _("zero") : _("non-zero"), line);
19486
19487             if (at_commandline)
19488               {
19489                 /* This DW_MACRO_GNU_start_file was executed in the
19490                    pass one.  */
19491                 at_commandline = 0;
19492               }
19493             else
19494               current_file = macro_start_file (file, line,
19495                                                current_file, comp_dir,
19496                                                lh, objfile);
19497           }
19498           break;
19499
19500         case DW_MACRO_GNU_end_file:
19501           if (! current_file)
19502             complaint (&symfile_complaints,
19503                        _("macro debug info has an unmatched "
19504                          "`close_file' directive"));
19505           else
19506             {
19507               current_file = current_file->included_by;
19508               if (! current_file)
19509                 {
19510                   enum dwarf_macro_record_type next_type;
19511
19512                   /* GCC circa March 2002 doesn't produce the zero
19513                      type byte marking the end of the compilation
19514                      unit.  Complain if it's not there, but exit no
19515                      matter what.  */
19516
19517                   /* Do we at least have room for a macinfo type byte?  */
19518                   if (mac_ptr >= mac_end)
19519                     {
19520                       dwarf2_section_buffer_overflow_complaint (section);
19521                       return;
19522                     }
19523
19524                   /* We don't increment mac_ptr here, so this is just
19525                      a look-ahead.  */
19526                   next_type = read_1_byte (abfd, mac_ptr);
19527                   if (next_type != 0)
19528                     complaint (&symfile_complaints,
19529                                _("no terminating 0-type entry for "
19530                                  "macros in `.debug_macinfo' section"));
19531
19532                   return;
19533                 }
19534             }
19535           break;
19536
19537         case DW_MACRO_GNU_transparent_include:
19538         case DW_MACRO_GNU_transparent_include_alt:
19539           {
19540             LONGEST offset;
19541             void **slot;
19542             bfd *include_bfd = abfd;
19543             struct dwarf2_section_info *include_section = section;
19544             struct dwarf2_section_info alt_section;
19545             const gdb_byte *include_mac_end = mac_end;
19546             int is_dwz = section_is_dwz;
19547             const gdb_byte *new_mac_ptr;
19548
19549             offset = read_offset_1 (abfd, mac_ptr, offset_size);
19550             mac_ptr += offset_size;
19551
19552             if (macinfo_type == DW_MACRO_GNU_transparent_include_alt)
19553               {
19554                 struct dwz_file *dwz = dwarf2_get_dwz_file ();
19555
19556                 dwarf2_read_section (dwarf2_per_objfile->objfile,
19557                                      &dwz->macro);
19558
19559                 include_bfd = dwz->macro.asection->owner;
19560                 include_section = &dwz->macro;
19561                 include_mac_end = dwz->macro.buffer + dwz->macro.size;
19562                 is_dwz = 1;
19563               }
19564
19565             new_mac_ptr = include_section->buffer + offset;
19566             slot = htab_find_slot (include_hash, new_mac_ptr, INSERT);
19567
19568             if (*slot != NULL)
19569               {
19570                 /* This has actually happened; see
19571                    http://sourceware.org/bugzilla/show_bug.cgi?id=13568.  */
19572                 complaint (&symfile_complaints,
19573                            _("recursive DW_MACRO_GNU_transparent_include in "
19574                              ".debug_macro section"));
19575               }
19576             else
19577               {
19578                 *slot = (void *) new_mac_ptr;
19579
19580                 dwarf_decode_macro_bytes (include_bfd, new_mac_ptr,
19581                                           include_mac_end, current_file,
19582                                           lh, comp_dir,
19583                                           section, section_is_gnu, is_dwz,
19584                                           offset_size, objfile, include_hash);
19585
19586                 htab_remove_elt (include_hash, (void *) new_mac_ptr);
19587               }
19588           }
19589           break;
19590
19591         case DW_MACINFO_vendor_ext:
19592           if (!section_is_gnu)
19593             {
19594               unsigned int bytes_read;
19595               int constant;
19596
19597               constant = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
19598               mac_ptr += bytes_read;
19599               read_direct_string (abfd, mac_ptr, &bytes_read);
19600               mac_ptr += bytes_read;
19601
19602               /* We don't recognize any vendor extensions.  */
19603               break;
19604             }
19605           /* FALLTHROUGH */
19606
19607         default:
19608           mac_ptr = skip_unknown_opcode (macinfo_type, opcode_definitions,
19609                                          mac_ptr, mac_end, abfd, offset_size,
19610                                          section);
19611           if (mac_ptr == NULL)
19612             return;
19613           break;
19614         }
19615     } while (macinfo_type != 0);
19616 }
19617
19618 static void
19619 dwarf_decode_macros (struct dwarf2_cu *cu, unsigned int offset,
19620                      const char *comp_dir, int section_is_gnu)
19621 {
19622   struct objfile *objfile = dwarf2_per_objfile->objfile;
19623   struct line_header *lh = cu->line_header;
19624   bfd *abfd;
19625   const gdb_byte *mac_ptr, *mac_end;
19626   struct macro_source_file *current_file = 0;
19627   enum dwarf_macro_record_type macinfo_type;
19628   unsigned int offset_size = cu->header.offset_size;
19629   const gdb_byte *opcode_definitions[256];
19630   struct cleanup *cleanup;
19631   htab_t include_hash;
19632   void **slot;
19633   struct dwarf2_section_info *section;
19634   const char *section_name;
19635
19636   if (cu->dwo_unit != NULL)
19637     {
19638       if (section_is_gnu)
19639         {
19640           section = &cu->dwo_unit->dwo_file->sections.macro;
19641           section_name = ".debug_macro.dwo";
19642         }
19643       else
19644         {
19645           section = &cu->dwo_unit->dwo_file->sections.macinfo;
19646           section_name = ".debug_macinfo.dwo";
19647         }
19648     }
19649   else
19650     {
19651       if (section_is_gnu)
19652         {
19653           section = &dwarf2_per_objfile->macro;
19654           section_name = ".debug_macro";
19655         }
19656       else
19657         {
19658           section = &dwarf2_per_objfile->macinfo;
19659           section_name = ".debug_macinfo";
19660         }
19661     }
19662
19663   dwarf2_read_section (objfile, section);
19664   if (section->buffer == NULL)
19665     {
19666       complaint (&symfile_complaints, _("missing %s section"), section_name);
19667       return;
19668     }
19669   abfd = section->asection->owner;
19670
19671   /* First pass: Find the name of the base filename.
19672      This filename is needed in order to process all macros whose definition
19673      (or undefinition) comes from the command line.  These macros are defined
19674      before the first DW_MACINFO_start_file entry, and yet still need to be
19675      associated to the base file.
19676
19677      To determine the base file name, we scan the macro definitions until we
19678      reach the first DW_MACINFO_start_file entry.  We then initialize
19679      CURRENT_FILE accordingly so that any macro definition found before the
19680      first DW_MACINFO_start_file can still be associated to the base file.  */
19681
19682   mac_ptr = section->buffer + offset;
19683   mac_end = section->buffer + section->size;
19684
19685   mac_ptr = dwarf_parse_macro_header (opcode_definitions, abfd, mac_ptr,
19686                                       &offset_size, section_is_gnu);
19687   if (mac_ptr == NULL)
19688     {
19689       /* We already issued a complaint.  */
19690       return;
19691     }
19692
19693   do
19694     {
19695       /* Do we at least have room for a macinfo type byte?  */
19696       if (mac_ptr >= mac_end)
19697         {
19698           /* Complaint is printed during the second pass as GDB will probably
19699              stop the first pass earlier upon finding
19700              DW_MACINFO_start_file.  */
19701           break;
19702         }
19703
19704       macinfo_type = read_1_byte (abfd, mac_ptr);
19705       mac_ptr++;
19706
19707       /* Note that we rely on the fact that the corresponding GNU and
19708          DWARF constants are the same.  */
19709       switch (macinfo_type)
19710         {
19711           /* A zero macinfo type indicates the end of the macro
19712              information.  */
19713         case 0:
19714           break;
19715
19716         case DW_MACRO_GNU_define:
19717         case DW_MACRO_GNU_undef:
19718           /* Only skip the data by MAC_PTR.  */
19719           {
19720             unsigned int bytes_read;
19721
19722             read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
19723             mac_ptr += bytes_read;
19724             read_direct_string (abfd, mac_ptr, &bytes_read);
19725             mac_ptr += bytes_read;
19726           }
19727           break;
19728
19729         case DW_MACRO_GNU_start_file:
19730           {
19731             unsigned int bytes_read;
19732             int line, file;
19733
19734             line = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
19735             mac_ptr += bytes_read;
19736             file = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
19737             mac_ptr += bytes_read;
19738
19739             current_file = macro_start_file (file, line, current_file,
19740                                              comp_dir, lh, objfile);
19741           }
19742           break;
19743
19744         case DW_MACRO_GNU_end_file:
19745           /* No data to skip by MAC_PTR.  */
19746           break;
19747
19748         case DW_MACRO_GNU_define_indirect:
19749         case DW_MACRO_GNU_undef_indirect:
19750         case DW_MACRO_GNU_define_indirect_alt:
19751         case DW_MACRO_GNU_undef_indirect_alt:
19752           {
19753             unsigned int bytes_read;
19754
19755             read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
19756             mac_ptr += bytes_read;
19757             mac_ptr += offset_size;
19758           }
19759           break;
19760
19761         case DW_MACRO_GNU_transparent_include:
19762         case DW_MACRO_GNU_transparent_include_alt:
19763           /* Note that, according to the spec, a transparent include
19764              chain cannot call DW_MACRO_GNU_start_file.  So, we can just
19765              skip this opcode.  */
19766           mac_ptr += offset_size;
19767           break;
19768
19769         case DW_MACINFO_vendor_ext:
19770           /* Only skip the data by MAC_PTR.  */
19771           if (!section_is_gnu)
19772             {
19773               unsigned int bytes_read;
19774
19775               read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
19776               mac_ptr += bytes_read;
19777               read_direct_string (abfd, mac_ptr, &bytes_read);
19778               mac_ptr += bytes_read;
19779             }
19780           /* FALLTHROUGH */
19781
19782         default:
19783           mac_ptr = skip_unknown_opcode (macinfo_type, opcode_definitions,
19784                                          mac_ptr, mac_end, abfd, offset_size,
19785                                          section);
19786           if (mac_ptr == NULL)
19787             return;
19788           break;
19789         }
19790     } while (macinfo_type != 0 && current_file == NULL);
19791
19792   /* Second pass: Process all entries.
19793
19794      Use the AT_COMMAND_LINE flag to determine whether we are still processing
19795      command-line macro definitions/undefinitions.  This flag is unset when we
19796      reach the first DW_MACINFO_start_file entry.  */
19797
19798   include_hash = htab_create_alloc (1, htab_hash_pointer, htab_eq_pointer,
19799                                     NULL, xcalloc, xfree);
19800   cleanup = make_cleanup_htab_delete (include_hash);
19801   mac_ptr = section->buffer + offset;
19802   slot = htab_find_slot (include_hash, mac_ptr, INSERT);
19803   *slot = (void *) mac_ptr;
19804   dwarf_decode_macro_bytes (abfd, mac_ptr, mac_end,
19805                             current_file, lh, comp_dir, section,
19806                             section_is_gnu, 0,
19807                             offset_size, objfile, include_hash);
19808   do_cleanups (cleanup);
19809 }
19810
19811 /* Check if the attribute's form is a DW_FORM_block*
19812    if so return true else false.  */
19813
19814 static int
19815 attr_form_is_block (struct attribute *attr)
19816 {
19817   return (attr == NULL ? 0 :
19818       attr->form == DW_FORM_block1
19819       || attr->form == DW_FORM_block2
19820       || attr->form == DW_FORM_block4
19821       || attr->form == DW_FORM_block
19822       || attr->form == DW_FORM_exprloc);
19823 }
19824
19825 /* Return non-zero if ATTR's value is a section offset --- classes
19826    lineptr, loclistptr, macptr or rangelistptr --- or zero, otherwise.
19827    You may use DW_UNSND (attr) to retrieve such offsets.
19828
19829    Section 7.5.4, "Attribute Encodings", explains that no attribute
19830    may have a value that belongs to more than one of these classes; it
19831    would be ambiguous if we did, because we use the same forms for all
19832    of them.  */
19833
19834 static int
19835 attr_form_is_section_offset (struct attribute *attr)
19836 {
19837   return (attr->form == DW_FORM_data4
19838           || attr->form == DW_FORM_data8
19839           || attr->form == DW_FORM_sec_offset);
19840 }
19841
19842 /* Return non-zero if ATTR's value falls in the 'constant' class, or
19843    zero otherwise.  When this function returns true, you can apply
19844    dwarf2_get_attr_constant_value to it.
19845
19846    However, note that for some attributes you must check
19847    attr_form_is_section_offset before using this test.  DW_FORM_data4
19848    and DW_FORM_data8 are members of both the constant class, and of
19849    the classes that contain offsets into other debug sections
19850    (lineptr, loclistptr, macptr or rangelistptr).  The DWARF spec says
19851    that, if an attribute's can be either a constant or one of the
19852    section offset classes, DW_FORM_data4 and DW_FORM_data8 should be
19853    taken as section offsets, not constants.  */
19854
19855 static int
19856 attr_form_is_constant (struct attribute *attr)
19857 {
19858   switch (attr->form)
19859     {
19860     case DW_FORM_sdata:
19861     case DW_FORM_udata:
19862     case DW_FORM_data1:
19863     case DW_FORM_data2:
19864     case DW_FORM_data4:
19865     case DW_FORM_data8:
19866       return 1;
19867     default:
19868       return 0;
19869     }
19870 }
19871
19872 /* Return the .debug_loc section to use for CU.
19873    For DWO files use .debug_loc.dwo.  */
19874
19875 static struct dwarf2_section_info *
19876 cu_debug_loc_section (struct dwarf2_cu *cu)
19877 {
19878   if (cu->dwo_unit)
19879     return &cu->dwo_unit->dwo_file->sections.loc;
19880   return &dwarf2_per_objfile->loc;
19881 }
19882
19883 /* A helper function that fills in a dwarf2_loclist_baton.  */
19884
19885 static void
19886 fill_in_loclist_baton (struct dwarf2_cu *cu,
19887                        struct dwarf2_loclist_baton *baton,
19888                        struct attribute *attr)
19889 {
19890   struct dwarf2_section_info *section = cu_debug_loc_section (cu);
19891
19892   dwarf2_read_section (dwarf2_per_objfile->objfile, section);
19893
19894   baton->per_cu = cu->per_cu;
19895   gdb_assert (baton->per_cu);
19896   /* We don't know how long the location list is, but make sure we
19897      don't run off the edge of the section.  */
19898   baton->size = section->size - DW_UNSND (attr);
19899   baton->data = section->buffer + DW_UNSND (attr);
19900   baton->base_address = cu->base_address;
19901   baton->from_dwo = cu->dwo_unit != NULL;
19902 }
19903
19904 static void
19905 dwarf2_symbol_mark_computed (struct attribute *attr, struct symbol *sym,
19906                              struct dwarf2_cu *cu, int is_block)
19907 {
19908   struct objfile *objfile = dwarf2_per_objfile->objfile;
19909   struct dwarf2_section_info *section = cu_debug_loc_section (cu);
19910
19911   if (attr_form_is_section_offset (attr)
19912       /* .debug_loc{,.dwo} may not exist at all, or the offset may be outside
19913          the section.  If so, fall through to the complaint in the
19914          other branch.  */
19915       && DW_UNSND (attr) < dwarf2_section_size (objfile, section))
19916     {
19917       struct dwarf2_loclist_baton *baton;
19918
19919       baton = obstack_alloc (&objfile->objfile_obstack,
19920                              sizeof (struct dwarf2_loclist_baton));
19921
19922       fill_in_loclist_baton (cu, baton, attr);
19923
19924       if (cu->base_known == 0)
19925         complaint (&symfile_complaints,
19926                    _("Location list used without "
19927                      "specifying the CU base address."));
19928
19929       SYMBOL_ACLASS_INDEX (sym) = (is_block
19930                                    ? dwarf2_loclist_block_index
19931                                    : dwarf2_loclist_index);
19932       SYMBOL_LOCATION_BATON (sym) = baton;
19933     }
19934   else
19935     {
19936       struct dwarf2_locexpr_baton *baton;
19937
19938       baton = obstack_alloc (&objfile->objfile_obstack,
19939                              sizeof (struct dwarf2_locexpr_baton));
19940       baton->per_cu = cu->per_cu;
19941       gdb_assert (baton->per_cu);
19942
19943       if (attr_form_is_block (attr))
19944         {
19945           /* Note that we're just copying the block's data pointer
19946              here, not the actual data.  We're still pointing into the
19947              info_buffer for SYM's objfile; right now we never release
19948              that buffer, but when we do clean up properly this may
19949              need to change.  */
19950           baton->size = DW_BLOCK (attr)->size;
19951           baton->data = DW_BLOCK (attr)->data;
19952         }
19953       else
19954         {
19955           dwarf2_invalid_attrib_class_complaint ("location description",
19956                                                  SYMBOL_NATURAL_NAME (sym));
19957           baton->size = 0;
19958         }
19959
19960       SYMBOL_ACLASS_INDEX (sym) = (is_block
19961                                    ? dwarf2_locexpr_block_index
19962                                    : dwarf2_locexpr_index);
19963       SYMBOL_LOCATION_BATON (sym) = baton;
19964     }
19965 }
19966
19967 /* Return the OBJFILE associated with the compilation unit CU.  If CU
19968    came from a separate debuginfo file, then the master objfile is
19969    returned.  */
19970
19971 struct objfile *
19972 dwarf2_per_cu_objfile (struct dwarf2_per_cu_data *per_cu)
19973 {
19974   struct objfile *objfile = per_cu->objfile;
19975
19976   /* Return the master objfile, so that we can report and look up the
19977      correct file containing this variable.  */
19978   if (objfile->separate_debug_objfile_backlink)
19979     objfile = objfile->separate_debug_objfile_backlink;
19980
19981   return objfile;
19982 }
19983
19984 /* Return comp_unit_head for PER_CU, either already available in PER_CU->CU
19985    (CU_HEADERP is unused in such case) or prepare a temporary copy at
19986    CU_HEADERP first.  */
19987
19988 static const struct comp_unit_head *
19989 per_cu_header_read_in (struct comp_unit_head *cu_headerp,
19990                        struct dwarf2_per_cu_data *per_cu)
19991 {
19992   const gdb_byte *info_ptr;
19993
19994   if (per_cu->cu)
19995     return &per_cu->cu->header;
19996
19997   info_ptr = per_cu->section->buffer + per_cu->offset.sect_off;
19998
19999   memset (cu_headerp, 0, sizeof (*cu_headerp));
20000   read_comp_unit_head (cu_headerp, info_ptr, per_cu->objfile->obfd);
20001
20002   return cu_headerp;
20003 }
20004
20005 /* Return the address size given in the compilation unit header for CU.  */
20006
20007 int
20008 dwarf2_per_cu_addr_size (struct dwarf2_per_cu_data *per_cu)
20009 {
20010   struct comp_unit_head cu_header_local;
20011   const struct comp_unit_head *cu_headerp;
20012
20013   cu_headerp = per_cu_header_read_in (&cu_header_local, per_cu);
20014
20015   return cu_headerp->addr_size;
20016 }
20017
20018 /* Return the offset size given in the compilation unit header for CU.  */
20019
20020 int
20021 dwarf2_per_cu_offset_size (struct dwarf2_per_cu_data *per_cu)
20022 {
20023   struct comp_unit_head cu_header_local;
20024   const struct comp_unit_head *cu_headerp;
20025
20026   cu_headerp = per_cu_header_read_in (&cu_header_local, per_cu);
20027
20028   return cu_headerp->offset_size;
20029 }
20030
20031 /* See its dwarf2loc.h declaration.  */
20032
20033 int
20034 dwarf2_per_cu_ref_addr_size (struct dwarf2_per_cu_data *per_cu)
20035 {
20036   struct comp_unit_head cu_header_local;
20037   const struct comp_unit_head *cu_headerp;
20038
20039   cu_headerp = per_cu_header_read_in (&cu_header_local, per_cu);
20040
20041   if (cu_headerp->version == 2)
20042     return cu_headerp->addr_size;
20043   else
20044     return cu_headerp->offset_size;
20045 }
20046
20047 /* Return the text offset of the CU.  The returned offset comes from
20048    this CU's objfile.  If this objfile came from a separate debuginfo
20049    file, then the offset may be different from the corresponding
20050    offset in the parent objfile.  */
20051
20052 CORE_ADDR
20053 dwarf2_per_cu_text_offset (struct dwarf2_per_cu_data *per_cu)
20054 {
20055   struct objfile *objfile = per_cu->objfile;
20056
20057   return ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
20058 }
20059
20060 /* Locate the .debug_info compilation unit from CU's objfile which contains
20061    the DIE at OFFSET.  Raises an error on failure.  */
20062
20063 static struct dwarf2_per_cu_data *
20064 dwarf2_find_containing_comp_unit (sect_offset offset,
20065                                   unsigned int offset_in_dwz,
20066                                   struct objfile *objfile)
20067 {
20068   struct dwarf2_per_cu_data *this_cu;
20069   int low, high;
20070   const sect_offset *cu_off;
20071
20072   low = 0;
20073   high = dwarf2_per_objfile->n_comp_units - 1;
20074   while (high > low)
20075     {
20076       struct dwarf2_per_cu_data *mid_cu;
20077       int mid = low + (high - low) / 2;
20078
20079       mid_cu = dwarf2_per_objfile->all_comp_units[mid];
20080       cu_off = &mid_cu->offset;
20081       if (mid_cu->is_dwz > offset_in_dwz
20082           || (mid_cu->is_dwz == offset_in_dwz
20083               && cu_off->sect_off >= offset.sect_off))
20084         high = mid;
20085       else
20086         low = mid + 1;
20087     }
20088   gdb_assert (low == high);
20089   this_cu = dwarf2_per_objfile->all_comp_units[low];
20090   cu_off = &this_cu->offset;
20091   if (this_cu->is_dwz != offset_in_dwz || cu_off->sect_off > offset.sect_off)
20092     {
20093       if (low == 0 || this_cu->is_dwz != offset_in_dwz)
20094         error (_("Dwarf Error: could not find partial DIE containing "
20095                "offset 0x%lx [in module %s]"),
20096                (long) offset.sect_off, bfd_get_filename (objfile->obfd));
20097
20098       gdb_assert (dwarf2_per_objfile->all_comp_units[low-1]->offset.sect_off
20099                   <= offset.sect_off);
20100       return dwarf2_per_objfile->all_comp_units[low-1];
20101     }
20102   else
20103     {
20104       this_cu = dwarf2_per_objfile->all_comp_units[low];
20105       if (low == dwarf2_per_objfile->n_comp_units - 1
20106           && offset.sect_off >= this_cu->offset.sect_off + this_cu->length)
20107         error (_("invalid dwarf2 offset %u"), offset.sect_off);
20108       gdb_assert (offset.sect_off < this_cu->offset.sect_off + this_cu->length);
20109       return this_cu;
20110     }
20111 }
20112
20113 /* Initialize dwarf2_cu CU, owned by PER_CU.  */
20114
20115 static void
20116 init_one_comp_unit (struct dwarf2_cu *cu, struct dwarf2_per_cu_data *per_cu)
20117 {
20118   memset (cu, 0, sizeof (*cu));
20119   per_cu->cu = cu;
20120   cu->per_cu = per_cu;
20121   cu->objfile = per_cu->objfile;
20122   obstack_init (&cu->comp_unit_obstack);
20123 }
20124
20125 /* Initialize basic fields of dwarf_cu CU according to DIE COMP_UNIT_DIE.  */
20126
20127 static void
20128 prepare_one_comp_unit (struct dwarf2_cu *cu, struct die_info *comp_unit_die,
20129                        enum language pretend_language)
20130 {
20131   struct attribute *attr;
20132
20133   /* Set the language we're debugging.  */
20134   attr = dwarf2_attr (comp_unit_die, DW_AT_language, cu);
20135   if (attr)
20136     set_cu_language (DW_UNSND (attr), cu);
20137   else
20138     {
20139       cu->language = pretend_language;
20140       cu->language_defn = language_def (cu->language);
20141     }
20142
20143   attr = dwarf2_attr (comp_unit_die, DW_AT_producer, cu);
20144   if (attr)
20145     cu->producer = DW_STRING (attr);
20146 }
20147
20148 /* Release one cached compilation unit, CU.  We unlink it from the tree
20149    of compilation units, but we don't remove it from the read_in_chain;
20150    the caller is responsible for that.
20151    NOTE: DATA is a void * because this function is also used as a
20152    cleanup routine.  */
20153
20154 static void
20155 free_heap_comp_unit (void *data)
20156 {
20157   struct dwarf2_cu *cu = data;
20158
20159   gdb_assert (cu->per_cu != NULL);
20160   cu->per_cu->cu = NULL;
20161   cu->per_cu = NULL;
20162
20163   obstack_free (&cu->comp_unit_obstack, NULL);
20164
20165   xfree (cu);
20166 }
20167
20168 /* This cleanup function is passed the address of a dwarf2_cu on the stack
20169    when we're finished with it.  We can't free the pointer itself, but be
20170    sure to unlink it from the cache.  Also release any associated storage.  */
20171
20172 static void
20173 free_stack_comp_unit (void *data)
20174 {
20175   struct dwarf2_cu *cu = data;
20176
20177   gdb_assert (cu->per_cu != NULL);
20178   cu->per_cu->cu = NULL;
20179   cu->per_cu = NULL;
20180
20181   obstack_free (&cu->comp_unit_obstack, NULL);
20182   cu->partial_dies = NULL;
20183 }
20184
20185 /* Free all cached compilation units.  */
20186
20187 static void
20188 free_cached_comp_units (void *data)
20189 {
20190   struct dwarf2_per_cu_data *per_cu, **last_chain;
20191
20192   per_cu = dwarf2_per_objfile->read_in_chain;
20193   last_chain = &dwarf2_per_objfile->read_in_chain;
20194   while (per_cu != NULL)
20195     {
20196       struct dwarf2_per_cu_data *next_cu;
20197
20198       next_cu = per_cu->cu->read_in_chain;
20199
20200       free_heap_comp_unit (per_cu->cu);
20201       *last_chain = next_cu;
20202
20203       per_cu = next_cu;
20204     }
20205 }
20206
20207 /* Increase the age counter on each cached compilation unit, and free
20208    any that are too old.  */
20209
20210 static void
20211 age_cached_comp_units (void)
20212 {
20213   struct dwarf2_per_cu_data *per_cu, **last_chain;
20214
20215   dwarf2_clear_marks (dwarf2_per_objfile->read_in_chain);
20216   per_cu = dwarf2_per_objfile->read_in_chain;
20217   while (per_cu != NULL)
20218     {
20219       per_cu->cu->last_used ++;
20220       if (per_cu->cu->last_used <= dwarf2_max_cache_age)
20221         dwarf2_mark (per_cu->cu);
20222       per_cu = per_cu->cu->read_in_chain;
20223     }
20224
20225   per_cu = dwarf2_per_objfile->read_in_chain;
20226   last_chain = &dwarf2_per_objfile->read_in_chain;
20227   while (per_cu != NULL)
20228     {
20229       struct dwarf2_per_cu_data *next_cu;
20230
20231       next_cu = per_cu->cu->read_in_chain;
20232
20233       if (!per_cu->cu->mark)
20234         {
20235           free_heap_comp_unit (per_cu->cu);
20236           *last_chain = next_cu;
20237         }
20238       else
20239         last_chain = &per_cu->cu->read_in_chain;
20240
20241       per_cu = next_cu;
20242     }
20243 }
20244
20245 /* Remove a single compilation unit from the cache.  */
20246
20247 static void
20248 free_one_cached_comp_unit (struct dwarf2_per_cu_data *target_per_cu)
20249 {
20250   struct dwarf2_per_cu_data *per_cu, **last_chain;
20251
20252   per_cu = dwarf2_per_objfile->read_in_chain;
20253   last_chain = &dwarf2_per_objfile->read_in_chain;
20254   while (per_cu != NULL)
20255     {
20256       struct dwarf2_per_cu_data *next_cu;
20257
20258       next_cu = per_cu->cu->read_in_chain;
20259
20260       if (per_cu == target_per_cu)
20261         {
20262           free_heap_comp_unit (per_cu->cu);
20263           per_cu->cu = NULL;
20264           *last_chain = next_cu;
20265           break;
20266         }
20267       else
20268         last_chain = &per_cu->cu->read_in_chain;
20269
20270       per_cu = next_cu;
20271     }
20272 }
20273
20274 /* Release all extra memory associated with OBJFILE.  */
20275
20276 void
20277 dwarf2_free_objfile (struct objfile *objfile)
20278 {
20279   dwarf2_per_objfile = objfile_data (objfile, dwarf2_objfile_data_key);
20280
20281   if (dwarf2_per_objfile == NULL)
20282     return;
20283
20284   /* Cached DIE trees use xmalloc and the comp_unit_obstack.  */
20285   free_cached_comp_units (NULL);
20286
20287   if (dwarf2_per_objfile->quick_file_names_table)
20288     htab_delete (dwarf2_per_objfile->quick_file_names_table);
20289
20290   /* Everything else should be on the objfile obstack.  */
20291 }
20292
20293 /* A set of CU "per_cu" pointer, DIE offset, and GDB type pointer.
20294    We store these in a hash table separate from the DIEs, and preserve them
20295    when the DIEs are flushed out of cache.
20296
20297    The CU "per_cu" pointer is needed because offset alone is not enough to
20298    uniquely identify the type.  A file may have multiple .debug_types sections,
20299    or the type may come from a DWO file.  Furthermore, while it's more logical
20300    to use per_cu->section+offset, with Fission the section with the data is in
20301    the DWO file but we don't know that section at the point we need it.
20302    We have to use something in dwarf2_per_cu_data (or the pointer to it)
20303    because we can enter the lookup routine, get_die_type_at_offset, from
20304    outside this file, and thus won't necessarily have PER_CU->cu.
20305    Fortunately, PER_CU is stable for the life of the objfile.  */
20306
20307 struct dwarf2_per_cu_offset_and_type
20308 {
20309   const struct dwarf2_per_cu_data *per_cu;
20310   sect_offset offset;
20311   struct type *type;
20312 };
20313
20314 /* Hash function for a dwarf2_per_cu_offset_and_type.  */
20315
20316 static hashval_t
20317 per_cu_offset_and_type_hash (const void *item)
20318 {
20319   const struct dwarf2_per_cu_offset_and_type *ofs = item;
20320
20321   return (uintptr_t) ofs->per_cu + ofs->offset.sect_off;
20322 }
20323
20324 /* Equality function for a dwarf2_per_cu_offset_and_type.  */
20325
20326 static int
20327 per_cu_offset_and_type_eq (const void *item_lhs, const void *item_rhs)
20328 {
20329   const struct dwarf2_per_cu_offset_and_type *ofs_lhs = item_lhs;
20330   const struct dwarf2_per_cu_offset_and_type *ofs_rhs = item_rhs;
20331
20332   return (ofs_lhs->per_cu == ofs_rhs->per_cu
20333           && ofs_lhs->offset.sect_off == ofs_rhs->offset.sect_off);
20334 }
20335
20336 /* Set the type associated with DIE to TYPE.  Save it in CU's hash
20337    table if necessary.  For convenience, return TYPE.
20338
20339    The DIEs reading must have careful ordering to:
20340     * Not cause infite loops trying to read in DIEs as a prerequisite for
20341       reading current DIE.
20342     * Not trying to dereference contents of still incompletely read in types
20343       while reading in other DIEs.
20344     * Enable referencing still incompletely read in types just by a pointer to
20345       the type without accessing its fields.
20346
20347    Therefore caller should follow these rules:
20348      * Try to fetch any prerequisite types we may need to build this DIE type
20349        before building the type and calling set_die_type.
20350      * After building type call set_die_type for current DIE as soon as
20351        possible before fetching more types to complete the current type.
20352      * Make the type as complete as possible before fetching more types.  */
20353
20354 static struct type *
20355 set_die_type (struct die_info *die, struct type *type, struct dwarf2_cu *cu)
20356 {
20357   struct dwarf2_per_cu_offset_and_type **slot, ofs;
20358   struct objfile *objfile = cu->objfile;
20359
20360   /* For Ada types, make sure that the gnat-specific data is always
20361      initialized (if not already set).  There are a few types where
20362      we should not be doing so, because the type-specific area is
20363      already used to hold some other piece of info (eg: TYPE_CODE_FLT
20364      where the type-specific area is used to store the floatformat).
20365      But this is not a problem, because the gnat-specific information
20366      is actually not needed for these types.  */
20367   if (need_gnat_info (cu)
20368       && TYPE_CODE (type) != TYPE_CODE_FUNC
20369       && TYPE_CODE (type) != TYPE_CODE_FLT
20370       && !HAVE_GNAT_AUX_INFO (type))
20371     INIT_GNAT_SPECIFIC (type);
20372
20373   if (dwarf2_per_objfile->die_type_hash == NULL)
20374     {
20375       dwarf2_per_objfile->die_type_hash =
20376         htab_create_alloc_ex (127,
20377                               per_cu_offset_and_type_hash,
20378                               per_cu_offset_and_type_eq,
20379                               NULL,
20380                               &objfile->objfile_obstack,
20381                               hashtab_obstack_allocate,
20382                               dummy_obstack_deallocate);
20383     }
20384
20385   ofs.per_cu = cu->per_cu;
20386   ofs.offset = die->offset;
20387   ofs.type = type;
20388   slot = (struct dwarf2_per_cu_offset_and_type **)
20389     htab_find_slot (dwarf2_per_objfile->die_type_hash, &ofs, INSERT);
20390   if (*slot)
20391     complaint (&symfile_complaints,
20392                _("A problem internal to GDB: DIE 0x%x has type already set"),
20393                die->offset.sect_off);
20394   *slot = obstack_alloc (&objfile->objfile_obstack, sizeof (**slot));
20395   **slot = ofs;
20396   return type;
20397 }
20398
20399 /* Look up the type for the die at OFFSET in PER_CU in die_type_hash,
20400    or return NULL if the die does not have a saved type.  */
20401
20402 static struct type *
20403 get_die_type_at_offset (sect_offset offset,
20404                         struct dwarf2_per_cu_data *per_cu)
20405 {
20406   struct dwarf2_per_cu_offset_and_type *slot, ofs;
20407
20408   if (dwarf2_per_objfile->die_type_hash == NULL)
20409     return NULL;
20410
20411   ofs.per_cu = per_cu;
20412   ofs.offset = offset;
20413   slot = htab_find (dwarf2_per_objfile->die_type_hash, &ofs);
20414   if (slot)
20415     return slot->type;
20416   else
20417     return NULL;
20418 }
20419
20420 /* Look up the type for DIE in CU in die_type_hash,
20421    or return NULL if DIE does not have a saved type.  */
20422
20423 static struct type *
20424 get_die_type (struct die_info *die, struct dwarf2_cu *cu)
20425 {
20426   return get_die_type_at_offset (die->offset, cu->per_cu);
20427 }
20428
20429 /* Add a dependence relationship from CU to REF_PER_CU.  */
20430
20431 static void
20432 dwarf2_add_dependence (struct dwarf2_cu *cu,
20433                        struct dwarf2_per_cu_data *ref_per_cu)
20434 {
20435   void **slot;
20436
20437   if (cu->dependencies == NULL)
20438     cu->dependencies
20439       = htab_create_alloc_ex (5, htab_hash_pointer, htab_eq_pointer,
20440                               NULL, &cu->comp_unit_obstack,
20441                               hashtab_obstack_allocate,
20442                               dummy_obstack_deallocate);
20443
20444   slot = htab_find_slot (cu->dependencies, ref_per_cu, INSERT);
20445   if (*slot == NULL)
20446     *slot = ref_per_cu;
20447 }
20448
20449 /* Subroutine of dwarf2_mark to pass to htab_traverse.
20450    Set the mark field in every compilation unit in the
20451    cache that we must keep because we are keeping CU.  */
20452
20453 static int
20454 dwarf2_mark_helper (void **slot, void *data)
20455 {
20456   struct dwarf2_per_cu_data *per_cu;
20457
20458   per_cu = (struct dwarf2_per_cu_data *) *slot;
20459
20460   /* cu->dependencies references may not yet have been ever read if QUIT aborts
20461      reading of the chain.  As such dependencies remain valid it is not much
20462      useful to track and undo them during QUIT cleanups.  */
20463   if (per_cu->cu == NULL)
20464     return 1;
20465
20466   if (per_cu->cu->mark)
20467     return 1;
20468   per_cu->cu->mark = 1;
20469
20470   if (per_cu->cu->dependencies != NULL)
20471     htab_traverse (per_cu->cu->dependencies, dwarf2_mark_helper, NULL);
20472
20473   return 1;
20474 }
20475
20476 /* Set the mark field in CU and in every other compilation unit in the
20477    cache that we must keep because we are keeping CU.  */
20478
20479 static void
20480 dwarf2_mark (struct dwarf2_cu *cu)
20481 {
20482   if (cu->mark)
20483     return;
20484   cu->mark = 1;
20485   if (cu->dependencies != NULL)
20486     htab_traverse (cu->dependencies, dwarf2_mark_helper, NULL);
20487 }
20488
20489 static void
20490 dwarf2_clear_marks (struct dwarf2_per_cu_data *per_cu)
20491 {
20492   while (per_cu)
20493     {
20494       per_cu->cu->mark = 0;
20495       per_cu = per_cu->cu->read_in_chain;
20496     }
20497 }
20498
20499 /* Trivial hash function for partial_die_info: the hash value of a DIE
20500    is its offset in .debug_info for this objfile.  */
20501
20502 static hashval_t
20503 partial_die_hash (const void *item)
20504 {
20505   const struct partial_die_info *part_die = item;
20506
20507   return part_die->offset.sect_off;
20508 }
20509
20510 /* Trivial comparison function for partial_die_info structures: two DIEs
20511    are equal if they have the same offset.  */
20512
20513 static int
20514 partial_die_eq (const void *item_lhs, const void *item_rhs)
20515 {
20516   const struct partial_die_info *part_die_lhs = item_lhs;
20517   const struct partial_die_info *part_die_rhs = item_rhs;
20518
20519   return part_die_lhs->offset.sect_off == part_die_rhs->offset.sect_off;
20520 }
20521
20522 static struct cmd_list_element *set_dwarf2_cmdlist;
20523 static struct cmd_list_element *show_dwarf2_cmdlist;
20524
20525 static void
20526 set_dwarf2_cmd (char *args, int from_tty)
20527 {
20528   help_list (set_dwarf2_cmdlist, "maintenance set dwarf2 ", -1, gdb_stdout);
20529 }
20530
20531 static void
20532 show_dwarf2_cmd (char *args, int from_tty)
20533 {
20534   cmd_show_list (show_dwarf2_cmdlist, from_tty, "");
20535 }
20536
20537 /* Free data associated with OBJFILE, if necessary.  */
20538
20539 static void
20540 dwarf2_per_objfile_free (struct objfile *objfile, void *d)
20541 {
20542   struct dwarf2_per_objfile *data = d;
20543   int ix;
20544
20545   /* Make sure we don't accidentally use dwarf2_per_objfile while
20546      cleaning up.  */
20547   dwarf2_per_objfile = NULL;
20548
20549   for (ix = 0; ix < data->n_comp_units; ++ix)
20550    VEC_free (dwarf2_per_cu_ptr, data->all_comp_units[ix]->imported_symtabs);
20551
20552   for (ix = 0; ix < data->n_type_units; ++ix)
20553     VEC_free (dwarf2_per_cu_ptr,
20554               data->all_type_units[ix]->per_cu.imported_symtabs);
20555   xfree (data->all_type_units);
20556
20557   VEC_free (dwarf2_section_info_def, data->types);
20558
20559   if (data->dwo_files)
20560     free_dwo_files (data->dwo_files, objfile);
20561   if (data->dwp_file)
20562     gdb_bfd_unref (data->dwp_file->dbfd);
20563
20564   if (data->dwz_file && data->dwz_file->dwz_bfd)
20565     gdb_bfd_unref (data->dwz_file->dwz_bfd);
20566 }
20567
20568 \f
20569 /* The "save gdb-index" command.  */
20570
20571 /* The contents of the hash table we create when building the string
20572    table.  */
20573 struct strtab_entry
20574 {
20575   offset_type offset;
20576   const char *str;
20577 };
20578
20579 /* Hash function for a strtab_entry.
20580
20581    Function is used only during write_hash_table so no index format backward
20582    compatibility is needed.  */
20583
20584 static hashval_t
20585 hash_strtab_entry (const void *e)
20586 {
20587   const struct strtab_entry *entry = e;
20588   return mapped_index_string_hash (INT_MAX, entry->str);
20589 }
20590
20591 /* Equality function for a strtab_entry.  */
20592
20593 static int
20594 eq_strtab_entry (const void *a, const void *b)
20595 {
20596   const struct strtab_entry *ea = a;
20597   const struct strtab_entry *eb = b;
20598   return !strcmp (ea->str, eb->str);
20599 }
20600
20601 /* Create a strtab_entry hash table.  */
20602
20603 static htab_t
20604 create_strtab (void)
20605 {
20606   return htab_create_alloc (100, hash_strtab_entry, eq_strtab_entry,
20607                             xfree, xcalloc, xfree);
20608 }
20609
20610 /* Add a string to the constant pool.  Return the string's offset in
20611    host order.  */
20612
20613 static offset_type
20614 add_string (htab_t table, struct obstack *cpool, const char *str)
20615 {
20616   void **slot;
20617   struct strtab_entry entry;
20618   struct strtab_entry *result;
20619
20620   entry.str = str;
20621   slot = htab_find_slot (table, &entry, INSERT);
20622   if (*slot)
20623     result = *slot;
20624   else
20625     {
20626       result = XNEW (struct strtab_entry);
20627       result->offset = obstack_object_size (cpool);
20628       result->str = str;
20629       obstack_grow_str0 (cpool, str);
20630       *slot = result;
20631     }
20632   return result->offset;
20633 }
20634
20635 /* An entry in the symbol table.  */
20636 struct symtab_index_entry
20637 {
20638   /* The name of the symbol.  */
20639   const char *name;
20640   /* The offset of the name in the constant pool.  */
20641   offset_type index_offset;
20642   /* A sorted vector of the indices of all the CUs that hold an object
20643      of this name.  */
20644   VEC (offset_type) *cu_indices;
20645 };
20646
20647 /* The symbol table.  This is a power-of-2-sized hash table.  */
20648 struct mapped_symtab
20649 {
20650   offset_type n_elements;
20651   offset_type size;
20652   struct symtab_index_entry **data;
20653 };
20654
20655 /* Hash function for a symtab_index_entry.  */
20656
20657 static hashval_t
20658 hash_symtab_entry (const void *e)
20659 {
20660   const struct symtab_index_entry *entry = e;
20661   return iterative_hash (VEC_address (offset_type, entry->cu_indices),
20662                          sizeof (offset_type) * VEC_length (offset_type,
20663                                                             entry->cu_indices),
20664                          0);
20665 }
20666
20667 /* Equality function for a symtab_index_entry.  */
20668
20669 static int
20670 eq_symtab_entry (const void *a, const void *b)
20671 {
20672   const struct symtab_index_entry *ea = a;
20673   const struct symtab_index_entry *eb = b;
20674   int len = VEC_length (offset_type, ea->cu_indices);
20675   if (len != VEC_length (offset_type, eb->cu_indices))
20676     return 0;
20677   return !memcmp (VEC_address (offset_type, ea->cu_indices),
20678                   VEC_address (offset_type, eb->cu_indices),
20679                   sizeof (offset_type) * len);
20680 }
20681
20682 /* Destroy a symtab_index_entry.  */
20683
20684 static void
20685 delete_symtab_entry (void *p)
20686 {
20687   struct symtab_index_entry *entry = p;
20688   VEC_free (offset_type, entry->cu_indices);
20689   xfree (entry);
20690 }
20691
20692 /* Create a hash table holding symtab_index_entry objects.  */
20693
20694 static htab_t
20695 create_symbol_hash_table (void)
20696 {
20697   return htab_create_alloc (100, hash_symtab_entry, eq_symtab_entry,
20698                             delete_symtab_entry, xcalloc, xfree);
20699 }
20700
20701 /* Create a new mapped symtab object.  */
20702
20703 static struct mapped_symtab *
20704 create_mapped_symtab (void)
20705 {
20706   struct mapped_symtab *symtab = XNEW (struct mapped_symtab);
20707   symtab->n_elements = 0;
20708   symtab->size = 1024;
20709   symtab->data = XCNEWVEC (struct symtab_index_entry *, symtab->size);
20710   return symtab;
20711 }
20712
20713 /* Destroy a mapped_symtab.  */
20714
20715 static void
20716 cleanup_mapped_symtab (void *p)
20717 {
20718   struct mapped_symtab *symtab = p;
20719   /* The contents of the array are freed when the other hash table is
20720      destroyed.  */
20721   xfree (symtab->data);
20722   xfree (symtab);
20723 }
20724
20725 /* Find a slot in SYMTAB for the symbol NAME.  Returns a pointer to
20726    the slot.
20727    
20728    Function is used only during write_hash_table so no index format backward
20729    compatibility is needed.  */
20730
20731 static struct symtab_index_entry **
20732 find_slot (struct mapped_symtab *symtab, const char *name)
20733 {
20734   offset_type index, step, hash = mapped_index_string_hash (INT_MAX, name);
20735
20736   index = hash & (symtab->size - 1);
20737   step = ((hash * 17) & (symtab->size - 1)) | 1;
20738
20739   for (;;)
20740     {
20741       if (!symtab->data[index] || !strcmp (name, symtab->data[index]->name))
20742         return &symtab->data[index];
20743       index = (index + step) & (symtab->size - 1);
20744     }
20745 }
20746
20747 /* Expand SYMTAB's hash table.  */
20748
20749 static void
20750 hash_expand (struct mapped_symtab *symtab)
20751 {
20752   offset_type old_size = symtab->size;
20753   offset_type i;
20754   struct symtab_index_entry **old_entries = symtab->data;
20755
20756   symtab->size *= 2;
20757   symtab->data = XCNEWVEC (struct symtab_index_entry *, symtab->size);
20758
20759   for (i = 0; i < old_size; ++i)
20760     {
20761       if (old_entries[i])
20762         {
20763           struct symtab_index_entry **slot = find_slot (symtab,
20764                                                         old_entries[i]->name);
20765           *slot = old_entries[i];
20766         }
20767     }
20768
20769   xfree (old_entries);
20770 }
20771
20772 /* Add an entry to SYMTAB.  NAME is the name of the symbol.
20773    CU_INDEX is the index of the CU in which the symbol appears.
20774    IS_STATIC is one if the symbol is static, otherwise zero (global).  */
20775
20776 static void
20777 add_index_entry (struct mapped_symtab *symtab, const char *name,
20778                  int is_static, gdb_index_symbol_kind kind,
20779                  offset_type cu_index)
20780 {
20781   struct symtab_index_entry **slot;
20782   offset_type cu_index_and_attrs;
20783
20784   ++symtab->n_elements;
20785   if (4 * symtab->n_elements / 3 >= symtab->size)
20786     hash_expand (symtab);
20787
20788   slot = find_slot (symtab, name);
20789   if (!*slot)
20790     {
20791       *slot = XNEW (struct symtab_index_entry);
20792       (*slot)->name = name;
20793       /* index_offset is set later.  */
20794       (*slot)->cu_indices = NULL;
20795     }
20796
20797   cu_index_and_attrs = 0;
20798   DW2_GDB_INDEX_CU_SET_VALUE (cu_index_and_attrs, cu_index);
20799   DW2_GDB_INDEX_SYMBOL_STATIC_SET_VALUE (cu_index_and_attrs, is_static);
20800   DW2_GDB_INDEX_SYMBOL_KIND_SET_VALUE (cu_index_and_attrs, kind);
20801
20802   /* We don't want to record an index value twice as we want to avoid the
20803      duplication.
20804      We process all global symbols and then all static symbols
20805      (which would allow us to avoid the duplication by only having to check
20806      the last entry pushed), but a symbol could have multiple kinds in one CU.
20807      To keep things simple we don't worry about the duplication here and
20808      sort and uniqufy the list after we've processed all symbols.  */
20809   VEC_safe_push (offset_type, (*slot)->cu_indices, cu_index_and_attrs);
20810 }
20811
20812 /* qsort helper routine for uniquify_cu_indices.  */
20813
20814 static int
20815 offset_type_compare (const void *ap, const void *bp)
20816 {
20817   offset_type a = *(offset_type *) ap;
20818   offset_type b = *(offset_type *) bp;
20819
20820   return (a > b) - (b > a);
20821 }
20822
20823 /* Sort and remove duplicates of all symbols' cu_indices lists.  */
20824
20825 static void
20826 uniquify_cu_indices (struct mapped_symtab *symtab)
20827 {
20828   int i;
20829
20830   for (i = 0; i < symtab->size; ++i)
20831     {
20832       struct symtab_index_entry *entry = symtab->data[i];
20833
20834       if (entry
20835           && entry->cu_indices != NULL)
20836         {
20837           unsigned int next_to_insert, next_to_check;
20838           offset_type last_value;
20839
20840           qsort (VEC_address (offset_type, entry->cu_indices),
20841                  VEC_length (offset_type, entry->cu_indices),
20842                  sizeof (offset_type), offset_type_compare);
20843
20844           last_value = VEC_index (offset_type, entry->cu_indices, 0);
20845           next_to_insert = 1;
20846           for (next_to_check = 1;
20847                next_to_check < VEC_length (offset_type, entry->cu_indices);
20848                ++next_to_check)
20849             {
20850               if (VEC_index (offset_type, entry->cu_indices, next_to_check)
20851                   != last_value)
20852                 {
20853                   last_value = VEC_index (offset_type, entry->cu_indices,
20854                                           next_to_check);
20855                   VEC_replace (offset_type, entry->cu_indices, next_to_insert,
20856                                last_value);
20857                   ++next_to_insert;
20858                 }
20859             }
20860           VEC_truncate (offset_type, entry->cu_indices, next_to_insert);
20861         }
20862     }
20863 }
20864
20865 /* Add a vector of indices to the constant pool.  */
20866
20867 static offset_type
20868 add_indices_to_cpool (htab_t symbol_hash_table, struct obstack *cpool,
20869                       struct symtab_index_entry *entry)
20870 {
20871   void **slot;
20872
20873   slot = htab_find_slot (symbol_hash_table, entry, INSERT);
20874   if (!*slot)
20875     {
20876       offset_type len = VEC_length (offset_type, entry->cu_indices);
20877       offset_type val = MAYBE_SWAP (len);
20878       offset_type iter;
20879       int i;
20880
20881       *slot = entry;
20882       entry->index_offset = obstack_object_size (cpool);
20883
20884       obstack_grow (cpool, &val, sizeof (val));
20885       for (i = 0;
20886            VEC_iterate (offset_type, entry->cu_indices, i, iter);
20887            ++i)
20888         {
20889           val = MAYBE_SWAP (iter);
20890           obstack_grow (cpool, &val, sizeof (val));
20891         }
20892     }
20893   else
20894     {
20895       struct symtab_index_entry *old_entry = *slot;
20896       entry->index_offset = old_entry->index_offset;
20897       entry = old_entry;
20898     }
20899   return entry->index_offset;
20900 }
20901
20902 /* Write the mapped hash table SYMTAB to the obstack OUTPUT, with
20903    constant pool entries going into the obstack CPOOL.  */
20904
20905 static void
20906 write_hash_table (struct mapped_symtab *symtab,
20907                   struct obstack *output, struct obstack *cpool)
20908 {
20909   offset_type i;
20910   htab_t symbol_hash_table;
20911   htab_t str_table;
20912
20913   symbol_hash_table = create_symbol_hash_table ();
20914   str_table = create_strtab ();
20915
20916   /* We add all the index vectors to the constant pool first, to
20917      ensure alignment is ok.  */
20918   for (i = 0; i < symtab->size; ++i)
20919     {
20920       if (symtab->data[i])
20921         add_indices_to_cpool (symbol_hash_table, cpool, symtab->data[i]);
20922     }
20923
20924   /* Now write out the hash table.  */
20925   for (i = 0; i < symtab->size; ++i)
20926     {
20927       offset_type str_off, vec_off;
20928
20929       if (symtab->data[i])
20930         {
20931           str_off = add_string (str_table, cpool, symtab->data[i]->name);
20932           vec_off = symtab->data[i]->index_offset;
20933         }
20934       else
20935         {
20936           /* While 0 is a valid constant pool index, it is not valid
20937              to have 0 for both offsets.  */
20938           str_off = 0;
20939           vec_off = 0;
20940         }
20941
20942       str_off = MAYBE_SWAP (str_off);
20943       vec_off = MAYBE_SWAP (vec_off);
20944
20945       obstack_grow (output, &str_off, sizeof (str_off));
20946       obstack_grow (output, &vec_off, sizeof (vec_off));
20947     }
20948
20949   htab_delete (str_table);
20950   htab_delete (symbol_hash_table);
20951 }
20952
20953 /* Struct to map psymtab to CU index in the index file.  */
20954 struct psymtab_cu_index_map
20955 {
20956   struct partial_symtab *psymtab;
20957   unsigned int cu_index;
20958 };
20959
20960 static hashval_t
20961 hash_psymtab_cu_index (const void *item)
20962 {
20963   const struct psymtab_cu_index_map *map = item;
20964
20965   return htab_hash_pointer (map->psymtab);
20966 }
20967
20968 static int
20969 eq_psymtab_cu_index (const void *item_lhs, const void *item_rhs)
20970 {
20971   const struct psymtab_cu_index_map *lhs = item_lhs;
20972   const struct psymtab_cu_index_map *rhs = item_rhs;
20973
20974   return lhs->psymtab == rhs->psymtab;
20975 }
20976
20977 /* Helper struct for building the address table.  */
20978 struct addrmap_index_data
20979 {
20980   struct objfile *objfile;
20981   struct obstack *addr_obstack;
20982   htab_t cu_index_htab;
20983
20984   /* Non-zero if the previous_* fields are valid.
20985      We can't write an entry until we see the next entry (since it is only then
20986      that we know the end of the entry).  */
20987   int previous_valid;
20988   /* Index of the CU in the table of all CUs in the index file.  */
20989   unsigned int previous_cu_index;
20990   /* Start address of the CU.  */
20991   CORE_ADDR previous_cu_start;
20992 };
20993
20994 /* Write an address entry to OBSTACK.  */
20995
20996 static void
20997 add_address_entry (struct objfile *objfile, struct obstack *obstack,
20998                    CORE_ADDR start, CORE_ADDR end, unsigned int cu_index)
20999 {
21000   offset_type cu_index_to_write;
21001   gdb_byte addr[8];
21002   CORE_ADDR baseaddr;
21003
21004   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
21005
21006   store_unsigned_integer (addr, 8, BFD_ENDIAN_LITTLE, start - baseaddr);
21007   obstack_grow (obstack, addr, 8);
21008   store_unsigned_integer (addr, 8, BFD_ENDIAN_LITTLE, end - baseaddr);
21009   obstack_grow (obstack, addr, 8);
21010   cu_index_to_write = MAYBE_SWAP (cu_index);
21011   obstack_grow (obstack, &cu_index_to_write, sizeof (offset_type));
21012 }
21013
21014 /* Worker function for traversing an addrmap to build the address table.  */
21015
21016 static int
21017 add_address_entry_worker (void *datap, CORE_ADDR start_addr, void *obj)
21018 {
21019   struct addrmap_index_data *data = datap;
21020   struct partial_symtab *pst = obj;
21021
21022   if (data->previous_valid)
21023     add_address_entry (data->objfile, data->addr_obstack,
21024                        data->previous_cu_start, start_addr,
21025                        data->previous_cu_index);
21026
21027   data->previous_cu_start = start_addr;
21028   if (pst != NULL)
21029     {
21030       struct psymtab_cu_index_map find_map, *map;
21031       find_map.psymtab = pst;
21032       map = htab_find (data->cu_index_htab, &find_map);
21033       gdb_assert (map != NULL);
21034       data->previous_cu_index = map->cu_index;
21035       data->previous_valid = 1;
21036     }
21037   else
21038       data->previous_valid = 0;
21039
21040   return 0;
21041 }
21042
21043 /* Write OBJFILE's address map to OBSTACK.
21044    CU_INDEX_HTAB is used to map addrmap entries to their CU indices
21045    in the index file.  */
21046
21047 static void
21048 write_address_map (struct objfile *objfile, struct obstack *obstack,
21049                    htab_t cu_index_htab)
21050 {
21051   struct addrmap_index_data addrmap_index_data;
21052
21053   /* When writing the address table, we have to cope with the fact that
21054      the addrmap iterator only provides the start of a region; we have to
21055      wait until the next invocation to get the start of the next region.  */
21056
21057   addrmap_index_data.objfile = objfile;
21058   addrmap_index_data.addr_obstack = obstack;
21059   addrmap_index_data.cu_index_htab = cu_index_htab;
21060   addrmap_index_data.previous_valid = 0;
21061
21062   addrmap_foreach (objfile->psymtabs_addrmap, add_address_entry_worker,
21063                    &addrmap_index_data);
21064
21065   /* It's highly unlikely the last entry (end address = 0xff...ff)
21066      is valid, but we should still handle it.
21067      The end address is recorded as the start of the next region, but that
21068      doesn't work here.  To cope we pass 0xff...ff, this is a rare situation
21069      anyway.  */
21070   if (addrmap_index_data.previous_valid)
21071     add_address_entry (objfile, obstack,
21072                        addrmap_index_data.previous_cu_start, (CORE_ADDR) -1,
21073                        addrmap_index_data.previous_cu_index);
21074 }
21075
21076 /* Return the symbol kind of PSYM.  */
21077
21078 static gdb_index_symbol_kind
21079 symbol_kind (struct partial_symbol *psym)
21080 {
21081   domain_enum domain = PSYMBOL_DOMAIN (psym);
21082   enum address_class aclass = PSYMBOL_CLASS (psym);
21083
21084   switch (domain)
21085     {
21086     case VAR_DOMAIN:
21087       switch (aclass)
21088         {
21089         case LOC_BLOCK:
21090           return GDB_INDEX_SYMBOL_KIND_FUNCTION;
21091         case LOC_TYPEDEF:
21092           return GDB_INDEX_SYMBOL_KIND_TYPE;
21093         case LOC_COMPUTED:
21094         case LOC_CONST_BYTES:
21095         case LOC_OPTIMIZED_OUT:
21096         case LOC_STATIC:
21097           return GDB_INDEX_SYMBOL_KIND_VARIABLE;
21098         case LOC_CONST:
21099           /* Note: It's currently impossible to recognize psyms as enum values
21100              short of reading the type info.  For now punt.  */
21101           return GDB_INDEX_SYMBOL_KIND_VARIABLE;
21102         default:
21103           /* There are other LOC_FOO values that one might want to classify
21104              as variables, but dwarf2read.c doesn't currently use them.  */
21105           return GDB_INDEX_SYMBOL_KIND_OTHER;
21106         }
21107     case STRUCT_DOMAIN:
21108       return GDB_INDEX_SYMBOL_KIND_TYPE;
21109     default:
21110       return GDB_INDEX_SYMBOL_KIND_OTHER;
21111     }
21112 }
21113
21114 /* Add a list of partial symbols to SYMTAB.  */
21115
21116 static void
21117 write_psymbols (struct mapped_symtab *symtab,
21118                 htab_t psyms_seen,
21119                 struct partial_symbol **psymp,
21120                 int count,
21121                 offset_type cu_index,
21122                 int is_static)
21123 {
21124   for (; count-- > 0; ++psymp)
21125     {
21126       struct partial_symbol *psym = *psymp;
21127       void **slot;
21128
21129       if (SYMBOL_LANGUAGE (psym) == language_ada)
21130         error (_("Ada is not currently supported by the index"));
21131
21132       /* Only add a given psymbol once.  */
21133       slot = htab_find_slot (psyms_seen, psym, INSERT);
21134       if (!*slot)
21135         {
21136           gdb_index_symbol_kind kind = symbol_kind (psym);
21137
21138           *slot = psym;
21139           add_index_entry (symtab, SYMBOL_SEARCH_NAME (psym),
21140                            is_static, kind, cu_index);
21141         }
21142     }
21143 }
21144
21145 /* Write the contents of an ("unfinished") obstack to FILE.  Throw an
21146    exception if there is an error.  */
21147
21148 static void
21149 write_obstack (FILE *file, struct obstack *obstack)
21150 {
21151   if (fwrite (obstack_base (obstack), 1, obstack_object_size (obstack),
21152               file)
21153       != obstack_object_size (obstack))
21154     error (_("couldn't data write to file"));
21155 }
21156
21157 /* Unlink a file if the argument is not NULL.  */
21158
21159 static void
21160 unlink_if_set (void *p)
21161 {
21162   char **filename = p;
21163   if (*filename)
21164     unlink (*filename);
21165 }
21166
21167 /* A helper struct used when iterating over debug_types.  */
21168 struct signatured_type_index_data
21169 {
21170   struct objfile *objfile;
21171   struct mapped_symtab *symtab;
21172   struct obstack *types_list;
21173   htab_t psyms_seen;
21174   int cu_index;
21175 };
21176
21177 /* A helper function that writes a single signatured_type to an
21178    obstack.  */
21179
21180 static int
21181 write_one_signatured_type (void **slot, void *d)
21182 {
21183   struct signatured_type_index_data *info = d;
21184   struct signatured_type *entry = (struct signatured_type *) *slot;
21185   struct partial_symtab *psymtab = entry->per_cu.v.psymtab;
21186   gdb_byte val[8];
21187
21188   write_psymbols (info->symtab,
21189                   info->psyms_seen,
21190                   info->objfile->global_psymbols.list
21191                   + psymtab->globals_offset,
21192                   psymtab->n_global_syms, info->cu_index,
21193                   0);
21194   write_psymbols (info->symtab,
21195                   info->psyms_seen,
21196                   info->objfile->static_psymbols.list
21197                   + psymtab->statics_offset,
21198                   psymtab->n_static_syms, info->cu_index,
21199                   1);
21200
21201   store_unsigned_integer (val, 8, BFD_ENDIAN_LITTLE,
21202                           entry->per_cu.offset.sect_off);
21203   obstack_grow (info->types_list, val, 8);
21204   store_unsigned_integer (val, 8, BFD_ENDIAN_LITTLE,
21205                           entry->type_offset_in_tu.cu_off);
21206   obstack_grow (info->types_list, val, 8);
21207   store_unsigned_integer (val, 8, BFD_ENDIAN_LITTLE, entry->signature);
21208   obstack_grow (info->types_list, val, 8);
21209
21210   ++info->cu_index;
21211
21212   return 1;
21213 }
21214
21215 /* Recurse into all "included" dependencies and write their symbols as
21216    if they appeared in this psymtab.  */
21217
21218 static void
21219 recursively_write_psymbols (struct objfile *objfile,
21220                             struct partial_symtab *psymtab,
21221                             struct mapped_symtab *symtab,
21222                             htab_t psyms_seen,
21223                             offset_type cu_index)
21224 {
21225   int i;
21226
21227   for (i = 0; i < psymtab->number_of_dependencies; ++i)
21228     if (psymtab->dependencies[i]->user != NULL)
21229       recursively_write_psymbols (objfile, psymtab->dependencies[i],
21230                                   symtab, psyms_seen, cu_index);
21231
21232   write_psymbols (symtab,
21233                   psyms_seen,
21234                   objfile->global_psymbols.list + psymtab->globals_offset,
21235                   psymtab->n_global_syms, cu_index,
21236                   0);
21237   write_psymbols (symtab,
21238                   psyms_seen,
21239                   objfile->static_psymbols.list + psymtab->statics_offset,
21240                   psymtab->n_static_syms, cu_index,
21241                   1);
21242 }
21243
21244 /* Create an index file for OBJFILE in the directory DIR.  */
21245
21246 static void
21247 write_psymtabs_to_index (struct objfile *objfile, const char *dir)
21248 {
21249   struct cleanup *cleanup;
21250   char *filename, *cleanup_filename;
21251   struct obstack contents, addr_obstack, constant_pool, symtab_obstack;
21252   struct obstack cu_list, types_cu_list;
21253   int i;
21254   FILE *out_file;
21255   struct mapped_symtab *symtab;
21256   offset_type val, size_of_contents, total_len;
21257   struct stat st;
21258   htab_t psyms_seen;
21259   htab_t cu_index_htab;
21260   struct psymtab_cu_index_map *psymtab_cu_index_map;
21261
21262   if (!objfile->psymtabs || !objfile->psymtabs_addrmap)
21263     return;
21264
21265   if (dwarf2_per_objfile->using_index)
21266     error (_("Cannot use an index to create the index"));
21267
21268   if (VEC_length (dwarf2_section_info_def, dwarf2_per_objfile->types) > 1)
21269     error (_("Cannot make an index when the file has multiple .debug_types sections"));
21270
21271   if (stat (objfile->name, &st) < 0)
21272     perror_with_name (objfile->name);
21273
21274   filename = concat (dir, SLASH_STRING, lbasename (objfile->name),
21275                      INDEX_SUFFIX, (char *) NULL);
21276   cleanup = make_cleanup (xfree, filename);
21277
21278   out_file = gdb_fopen_cloexec (filename, "wb");
21279   if (!out_file)
21280     error (_("Can't open `%s' for writing"), filename);
21281
21282   cleanup_filename = filename;
21283   make_cleanup (unlink_if_set, &cleanup_filename);
21284
21285   symtab = create_mapped_symtab ();
21286   make_cleanup (cleanup_mapped_symtab, symtab);
21287
21288   obstack_init (&addr_obstack);
21289   make_cleanup_obstack_free (&addr_obstack);
21290
21291   obstack_init (&cu_list);
21292   make_cleanup_obstack_free (&cu_list);
21293
21294   obstack_init (&types_cu_list);
21295   make_cleanup_obstack_free (&types_cu_list);
21296
21297   psyms_seen = htab_create_alloc (100, htab_hash_pointer, htab_eq_pointer,
21298                                   NULL, xcalloc, xfree);
21299   make_cleanup_htab_delete (psyms_seen);
21300
21301   /* While we're scanning CU's create a table that maps a psymtab pointer
21302      (which is what addrmap records) to its index (which is what is recorded
21303      in the index file).  This will later be needed to write the address
21304      table.  */
21305   cu_index_htab = htab_create_alloc (100,
21306                                      hash_psymtab_cu_index,
21307                                      eq_psymtab_cu_index,
21308                                      NULL, xcalloc, xfree);
21309   make_cleanup_htab_delete (cu_index_htab);
21310   psymtab_cu_index_map = (struct psymtab_cu_index_map *)
21311     xmalloc (sizeof (struct psymtab_cu_index_map)
21312              * dwarf2_per_objfile->n_comp_units);
21313   make_cleanup (xfree, psymtab_cu_index_map);
21314
21315   /* The CU list is already sorted, so we don't need to do additional
21316      work here.  Also, the debug_types entries do not appear in
21317      all_comp_units, but only in their own hash table.  */
21318   for (i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
21319     {
21320       struct dwarf2_per_cu_data *per_cu
21321         = dwarf2_per_objfile->all_comp_units[i];
21322       struct partial_symtab *psymtab = per_cu->v.psymtab;
21323       gdb_byte val[8];
21324       struct psymtab_cu_index_map *map;
21325       void **slot;
21326
21327       /* CU of a shared file from 'dwz -m' may be unused by this main file.
21328          It may be referenced from a local scope but in such case it does not
21329          need to be present in .gdb_index.  */
21330       if (psymtab == NULL)
21331         continue;
21332
21333       if (psymtab->user == NULL)
21334         recursively_write_psymbols (objfile, psymtab, symtab, psyms_seen, i);
21335
21336       map = &psymtab_cu_index_map[i];
21337       map->psymtab = psymtab;
21338       map->cu_index = i;
21339       slot = htab_find_slot (cu_index_htab, map, INSERT);
21340       gdb_assert (slot != NULL);
21341       gdb_assert (*slot == NULL);
21342       *slot = map;
21343
21344       store_unsigned_integer (val, 8, BFD_ENDIAN_LITTLE,
21345                               per_cu->offset.sect_off);
21346       obstack_grow (&cu_list, val, 8);
21347       store_unsigned_integer (val, 8, BFD_ENDIAN_LITTLE, per_cu->length);
21348       obstack_grow (&cu_list, val, 8);
21349     }
21350
21351   /* Dump the address map.  */
21352   write_address_map (objfile, &addr_obstack, cu_index_htab);
21353
21354   /* Write out the .debug_type entries, if any.  */
21355   if (dwarf2_per_objfile->signatured_types)
21356     {
21357       struct signatured_type_index_data sig_data;
21358
21359       sig_data.objfile = objfile;
21360       sig_data.symtab = symtab;
21361       sig_data.types_list = &types_cu_list;
21362       sig_data.psyms_seen = psyms_seen;
21363       sig_data.cu_index = dwarf2_per_objfile->n_comp_units;
21364       htab_traverse_noresize (dwarf2_per_objfile->signatured_types,
21365                               write_one_signatured_type, &sig_data);
21366     }
21367
21368   /* Now that we've processed all symbols we can shrink their cu_indices
21369      lists.  */
21370   uniquify_cu_indices (symtab);
21371
21372   obstack_init (&constant_pool);
21373   make_cleanup_obstack_free (&constant_pool);
21374   obstack_init (&symtab_obstack);
21375   make_cleanup_obstack_free (&symtab_obstack);
21376   write_hash_table (symtab, &symtab_obstack, &constant_pool);
21377
21378   obstack_init (&contents);
21379   make_cleanup_obstack_free (&contents);
21380   size_of_contents = 6 * sizeof (offset_type);
21381   total_len = size_of_contents;
21382
21383   /* The version number.  */
21384   val = MAYBE_SWAP (8);
21385   obstack_grow (&contents, &val, sizeof (val));
21386
21387   /* The offset of the CU list from the start of the file.  */
21388   val = MAYBE_SWAP (total_len);
21389   obstack_grow (&contents, &val, sizeof (val));
21390   total_len += obstack_object_size (&cu_list);
21391
21392   /* The offset of the types CU list from the start of the file.  */
21393   val = MAYBE_SWAP (total_len);
21394   obstack_grow (&contents, &val, sizeof (val));
21395   total_len += obstack_object_size (&types_cu_list);
21396
21397   /* The offset of the address table from the start of the file.  */
21398   val = MAYBE_SWAP (total_len);
21399   obstack_grow (&contents, &val, sizeof (val));
21400   total_len += obstack_object_size (&addr_obstack);
21401
21402   /* The offset of the symbol table from the start of the file.  */
21403   val = MAYBE_SWAP (total_len);
21404   obstack_grow (&contents, &val, sizeof (val));
21405   total_len += obstack_object_size (&symtab_obstack);
21406
21407   /* The offset of the constant pool from the start of the file.  */
21408   val = MAYBE_SWAP (total_len);
21409   obstack_grow (&contents, &val, sizeof (val));
21410   total_len += obstack_object_size (&constant_pool);
21411
21412   gdb_assert (obstack_object_size (&contents) == size_of_contents);
21413
21414   write_obstack (out_file, &contents);
21415   write_obstack (out_file, &cu_list);
21416   write_obstack (out_file, &types_cu_list);
21417   write_obstack (out_file, &addr_obstack);
21418   write_obstack (out_file, &symtab_obstack);
21419   write_obstack (out_file, &constant_pool);
21420
21421   fclose (out_file);
21422
21423   /* We want to keep the file, so we set cleanup_filename to NULL
21424      here.  See unlink_if_set.  */
21425   cleanup_filename = NULL;
21426
21427   do_cleanups (cleanup);
21428 }
21429
21430 /* Implementation of the `save gdb-index' command.
21431    
21432    Note that the file format used by this command is documented in the
21433    GDB manual.  Any changes here must be documented there.  */
21434
21435 static void
21436 save_gdb_index_command (char *arg, int from_tty)
21437 {
21438   struct objfile *objfile;
21439
21440   if (!arg || !*arg)
21441     error (_("usage: save gdb-index DIRECTORY"));
21442
21443   ALL_OBJFILES (objfile)
21444   {
21445     struct stat st;
21446
21447     /* If the objfile does not correspond to an actual file, skip it.  */
21448     if (stat (objfile->name, &st) < 0)
21449       continue;
21450
21451     dwarf2_per_objfile = objfile_data (objfile, dwarf2_objfile_data_key);
21452     if (dwarf2_per_objfile)
21453       {
21454         volatile struct gdb_exception except;
21455
21456         TRY_CATCH (except, RETURN_MASK_ERROR)
21457           {
21458             write_psymtabs_to_index (objfile, arg);
21459           }
21460         if (except.reason < 0)
21461           exception_fprintf (gdb_stderr, except,
21462                              _("Error while writing index for `%s': "),
21463                              objfile->name);
21464       }
21465   }
21466 }
21467
21468 \f
21469
21470 int dwarf2_always_disassemble;
21471
21472 static void
21473 show_dwarf2_always_disassemble (struct ui_file *file, int from_tty,
21474                                 struct cmd_list_element *c, const char *value)
21475 {
21476   fprintf_filtered (file,
21477                     _("Whether to always disassemble "
21478                       "DWARF expressions is %s.\n"),
21479                     value);
21480 }
21481
21482 static void
21483 show_check_physname (struct ui_file *file, int from_tty,
21484                      struct cmd_list_element *c, const char *value)
21485 {
21486   fprintf_filtered (file,
21487                     _("Whether to check \"physname\" is %s.\n"),
21488                     value);
21489 }
21490
21491 void _initialize_dwarf2_read (void);
21492
21493 void
21494 _initialize_dwarf2_read (void)
21495 {
21496   struct cmd_list_element *c;
21497
21498   dwarf2_objfile_data_key
21499     = register_objfile_data_with_cleanup (NULL, dwarf2_per_objfile_free);
21500
21501   add_prefix_cmd ("dwarf2", class_maintenance, set_dwarf2_cmd, _("\
21502 Set DWARF 2 specific variables.\n\
21503 Configure DWARF 2 variables such as the cache size"),
21504                   &set_dwarf2_cmdlist, "maintenance set dwarf2 ",
21505                   0/*allow-unknown*/, &maintenance_set_cmdlist);
21506
21507   add_prefix_cmd ("dwarf2", class_maintenance, show_dwarf2_cmd, _("\
21508 Show DWARF 2 specific variables\n\
21509 Show DWARF 2 variables such as the cache size"),
21510                   &show_dwarf2_cmdlist, "maintenance show dwarf2 ",
21511                   0/*allow-unknown*/, &maintenance_show_cmdlist);
21512
21513   add_setshow_zinteger_cmd ("max-cache-age", class_obscure,
21514                             &dwarf2_max_cache_age, _("\
21515 Set the upper bound on the age of cached dwarf2 compilation units."), _("\
21516 Show the upper bound on the age of cached dwarf2 compilation units."), _("\
21517 A higher limit means that cached compilation units will be stored\n\
21518 in memory longer, and more total memory will be used.  Zero disables\n\
21519 caching, which can slow down startup."),
21520                             NULL,
21521                             show_dwarf2_max_cache_age,
21522                             &set_dwarf2_cmdlist,
21523                             &show_dwarf2_cmdlist);
21524
21525   add_setshow_boolean_cmd ("always-disassemble", class_obscure,
21526                            &dwarf2_always_disassemble, _("\
21527 Set whether `info address' always disassembles DWARF expressions."), _("\
21528 Show whether `info address' always disassembles DWARF expressions."), _("\
21529 When enabled, DWARF expressions are always printed in an assembly-like\n\
21530 syntax.  When disabled, expressions will be printed in a more\n\
21531 conversational style, when possible."),
21532                            NULL,
21533                            show_dwarf2_always_disassemble,
21534                            &set_dwarf2_cmdlist,
21535                            &show_dwarf2_cmdlist);
21536
21537   add_setshow_boolean_cmd ("dwarf2-read", no_class, &dwarf2_read_debug, _("\
21538 Set debugging of the dwarf2 reader."), _("\
21539 Show debugging of the dwarf2 reader."), _("\
21540 When enabled, debugging messages are printed during dwarf2 reading\n\
21541 and symtab expansion."),
21542                             NULL,
21543                             NULL,
21544                             &setdebuglist, &showdebuglist);
21545
21546   add_setshow_zuinteger_cmd ("dwarf2-die", no_class, &dwarf2_die_debug, _("\
21547 Set debugging of the dwarf2 DIE reader."), _("\
21548 Show debugging of the dwarf2 DIE reader."), _("\
21549 When enabled (non-zero), DIEs are dumped after they are read in.\n\
21550 The value is the maximum depth to print."),
21551                              NULL,
21552                              NULL,
21553                              &setdebuglist, &showdebuglist);
21554
21555   add_setshow_boolean_cmd ("check-physname", no_class, &check_physname, _("\
21556 Set cross-checking of \"physname\" code against demangler."), _("\
21557 Show cross-checking of \"physname\" code against demangler."), _("\
21558 When enabled, GDB's internal \"physname\" code is checked against\n\
21559 the demangler."),
21560                            NULL, show_check_physname,
21561                            &setdebuglist, &showdebuglist);
21562
21563   add_setshow_boolean_cmd ("use-deprecated-index-sections",
21564                            no_class, &use_deprecated_index_sections, _("\
21565 Set whether to use deprecated gdb_index sections."), _("\
21566 Show whether to use deprecated gdb_index sections."), _("\
21567 When enabled, deprecated .gdb_index sections are used anyway.\n\
21568 Normally they are ignored either because of a missing feature or\n\
21569 performance issue.\n\
21570 Warning: This option must be enabled before gdb reads the file."),
21571                            NULL,
21572                            NULL,
21573                            &setlist, &showlist);
21574
21575   c = add_cmd ("gdb-index", class_files, save_gdb_index_command,
21576                _("\
21577 Save a gdb-index file.\n\
21578 Usage: save gdb-index DIRECTORY"),
21579                &save_cmdlist);
21580   set_cmd_completer (c, filename_completer);
21581
21582   dwarf2_locexpr_index = register_symbol_computed_impl (LOC_COMPUTED,
21583                                                         &dwarf2_locexpr_funcs);
21584   dwarf2_loclist_index = register_symbol_computed_impl (LOC_COMPUTED,
21585                                                         &dwarf2_loclist_funcs);
21586
21587   dwarf2_locexpr_block_index = register_symbol_block_impl (LOC_BLOCK,
21588                                         &dwarf2_block_frame_base_locexpr_funcs);
21589   dwarf2_loclist_block_index = register_symbol_block_impl (LOC_BLOCK,
21590                                         &dwarf2_block_frame_base_loclist_funcs);
21591 }